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
1957 if let Some(false) = show_edit_predictions {
1958 self.discard_inline_completion(false, cx);
1959 } else {
1960 self.refresh_inline_completion(false, true, window, cx);
1961 }
1962 }
1963
1964 fn inline_completions_disabled_in_scope(
1965 &self,
1966 buffer: &Entity<Buffer>,
1967 buffer_position: language::Anchor,
1968 cx: &App,
1969 ) -> bool {
1970 let snapshot = buffer.read(cx).snapshot();
1971 let settings = snapshot.settings_at(buffer_position, cx);
1972
1973 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1974 return false;
1975 };
1976
1977 scope.override_name().map_or(false, |scope_name| {
1978 settings
1979 .edit_predictions_disabled_in
1980 .iter()
1981 .any(|s| s == scope_name)
1982 })
1983 }
1984
1985 pub fn set_use_modal_editing(&mut self, to: bool) {
1986 self.use_modal_editing = to;
1987 }
1988
1989 pub fn use_modal_editing(&self) -> bool {
1990 self.use_modal_editing
1991 }
1992
1993 fn selections_did_change(
1994 &mut self,
1995 local: bool,
1996 old_cursor_position: &Anchor,
1997 show_completions: bool,
1998 window: &mut Window,
1999 cx: &mut Context<Self>,
2000 ) {
2001 window.invalidate_character_coordinates();
2002
2003 // Copy selections to primary selection buffer
2004 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2005 if local {
2006 let selections = self.selections.all::<usize>(cx);
2007 let buffer_handle = self.buffer.read(cx).read(cx);
2008
2009 let mut text = String::new();
2010 for (index, selection) in selections.iter().enumerate() {
2011 let text_for_selection = buffer_handle
2012 .text_for_range(selection.start..selection.end)
2013 .collect::<String>();
2014
2015 text.push_str(&text_for_selection);
2016 if index != selections.len() - 1 {
2017 text.push('\n');
2018 }
2019 }
2020
2021 if !text.is_empty() {
2022 cx.write_to_primary(ClipboardItem::new_string(text));
2023 }
2024 }
2025
2026 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2027 self.buffer.update(cx, |buffer, cx| {
2028 buffer.set_active_selections(
2029 &self.selections.disjoint_anchors(),
2030 self.selections.line_mode,
2031 self.cursor_shape,
2032 cx,
2033 )
2034 });
2035 }
2036 let display_map = self
2037 .display_map
2038 .update(cx, |display_map, cx| display_map.snapshot(cx));
2039 let buffer = &display_map.buffer_snapshot;
2040 self.add_selections_state = None;
2041 self.select_next_state = None;
2042 self.select_prev_state = None;
2043 self.select_larger_syntax_node_stack.clear();
2044 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2045 self.snippet_stack
2046 .invalidate(&self.selections.disjoint_anchors(), buffer);
2047 self.take_rename(false, window, cx);
2048
2049 let new_cursor_position = self.selections.newest_anchor().head();
2050
2051 self.push_to_nav_history(
2052 *old_cursor_position,
2053 Some(new_cursor_position.to_point(buffer)),
2054 cx,
2055 );
2056
2057 if local {
2058 let new_cursor_position = self.selections.newest_anchor().head();
2059 let mut context_menu = self.context_menu.borrow_mut();
2060 let completion_menu = match context_menu.as_ref() {
2061 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2062 _ => {
2063 *context_menu = None;
2064 None
2065 }
2066 };
2067 if let Some(buffer_id) = new_cursor_position.buffer_id {
2068 if !self.registered_buffers.contains_key(&buffer_id) {
2069 if let Some(project) = self.project.as_ref() {
2070 project.update(cx, |project, cx| {
2071 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2072 return;
2073 };
2074 self.registered_buffers.insert(
2075 buffer_id,
2076 project.register_buffer_with_language_servers(&buffer, cx),
2077 );
2078 })
2079 }
2080 }
2081 }
2082
2083 if let Some(completion_menu) = completion_menu {
2084 let cursor_position = new_cursor_position.to_offset(buffer);
2085 let (word_range, kind) =
2086 buffer.surrounding_word(completion_menu.initial_position, true);
2087 if kind == Some(CharKind::Word)
2088 && word_range.to_inclusive().contains(&cursor_position)
2089 {
2090 let mut completion_menu = completion_menu.clone();
2091 drop(context_menu);
2092
2093 let query = Self::completion_query(buffer, cursor_position);
2094 cx.spawn(move |this, mut cx| async move {
2095 completion_menu
2096 .filter(query.as_deref(), cx.background_executor().clone())
2097 .await;
2098
2099 this.update(&mut cx, |this, cx| {
2100 let mut context_menu = this.context_menu.borrow_mut();
2101 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2102 else {
2103 return;
2104 };
2105
2106 if menu.id > completion_menu.id {
2107 return;
2108 }
2109
2110 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2111 drop(context_menu);
2112 cx.notify();
2113 })
2114 })
2115 .detach();
2116
2117 if show_completions {
2118 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2119 }
2120 } else {
2121 drop(context_menu);
2122 self.hide_context_menu(window, cx);
2123 }
2124 } else {
2125 drop(context_menu);
2126 }
2127
2128 hide_hover(self, cx);
2129
2130 if old_cursor_position.to_display_point(&display_map).row()
2131 != new_cursor_position.to_display_point(&display_map).row()
2132 {
2133 self.available_code_actions.take();
2134 }
2135 self.refresh_code_actions(window, cx);
2136 self.refresh_document_highlights(cx);
2137 self.refresh_selected_text_highlights(window, cx);
2138 refresh_matching_bracket_highlights(self, window, cx);
2139 self.update_visible_inline_completion(window, cx);
2140 self.edit_prediction_requires_modifier_in_leading_space = true;
2141 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2142 if self.git_blame_inline_enabled {
2143 self.start_inline_blame_timer(window, cx);
2144 }
2145 }
2146
2147 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2148 cx.emit(EditorEvent::SelectionsChanged { local });
2149
2150 let selections = &self.selections.disjoint;
2151 if selections.len() == 1 {
2152 cx.emit(SearchEvent::ActiveMatchChanged)
2153 }
2154 if local
2155 && self.is_singleton(cx)
2156 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2157 {
2158 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2159 let background_executor = cx.background_executor().clone();
2160 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2161 let snapshot = self.buffer().read(cx).snapshot(cx);
2162 let selections = selections.clone();
2163 self.serialize_selections = cx.background_spawn(async move {
2164 background_executor.timer(Duration::from_millis(100)).await;
2165 let selections = selections
2166 .iter()
2167 .map(|selection| {
2168 (
2169 selection.start.to_offset(&snapshot),
2170 selection.end.to_offset(&snapshot),
2171 )
2172 })
2173 .collect();
2174 DB.save_editor_selections(editor_id, workspace_id, selections)
2175 .await
2176 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2177 .log_err();
2178 });
2179 }
2180 }
2181
2182 cx.notify();
2183 }
2184
2185 pub fn change_selections<R>(
2186 &mut self,
2187 autoscroll: Option<Autoscroll>,
2188 window: &mut Window,
2189 cx: &mut Context<Self>,
2190 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2191 ) -> R {
2192 self.change_selections_inner(autoscroll, true, window, cx, change)
2193 }
2194
2195 fn change_selections_inner<R>(
2196 &mut self,
2197 autoscroll: Option<Autoscroll>,
2198 request_completions: bool,
2199 window: &mut Window,
2200 cx: &mut Context<Self>,
2201 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2202 ) -> R {
2203 let old_cursor_position = self.selections.newest_anchor().head();
2204 self.push_to_selection_history();
2205
2206 let (changed, result) = self.selections.change_with(cx, change);
2207
2208 if changed {
2209 if let Some(autoscroll) = autoscroll {
2210 self.request_autoscroll(autoscroll, cx);
2211 }
2212 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2213
2214 if self.should_open_signature_help_automatically(
2215 &old_cursor_position,
2216 self.signature_help_state.backspace_pressed(),
2217 cx,
2218 ) {
2219 self.show_signature_help(&ShowSignatureHelp, window, cx);
2220 }
2221 self.signature_help_state.set_backspace_pressed(false);
2222 }
2223
2224 result
2225 }
2226
2227 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2228 where
2229 I: IntoIterator<Item = (Range<S>, T)>,
2230 S: ToOffset,
2231 T: Into<Arc<str>>,
2232 {
2233 if self.read_only(cx) {
2234 return;
2235 }
2236
2237 self.buffer
2238 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2239 }
2240
2241 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2242 where
2243 I: IntoIterator<Item = (Range<S>, T)>,
2244 S: ToOffset,
2245 T: Into<Arc<str>>,
2246 {
2247 if self.read_only(cx) {
2248 return;
2249 }
2250
2251 self.buffer.update(cx, |buffer, cx| {
2252 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2253 });
2254 }
2255
2256 pub fn edit_with_block_indent<I, S, T>(
2257 &mut self,
2258 edits: I,
2259 original_indent_columns: Vec<u32>,
2260 cx: &mut Context<Self>,
2261 ) where
2262 I: IntoIterator<Item = (Range<S>, T)>,
2263 S: ToOffset,
2264 T: Into<Arc<str>>,
2265 {
2266 if self.read_only(cx) {
2267 return;
2268 }
2269
2270 self.buffer.update(cx, |buffer, cx| {
2271 buffer.edit(
2272 edits,
2273 Some(AutoindentMode::Block {
2274 original_indent_columns,
2275 }),
2276 cx,
2277 )
2278 });
2279 }
2280
2281 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2282 self.hide_context_menu(window, cx);
2283
2284 match phase {
2285 SelectPhase::Begin {
2286 position,
2287 add,
2288 click_count,
2289 } => self.begin_selection(position, add, click_count, window, cx),
2290 SelectPhase::BeginColumnar {
2291 position,
2292 goal_column,
2293 reset,
2294 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2295 SelectPhase::Extend {
2296 position,
2297 click_count,
2298 } => self.extend_selection(position, click_count, window, cx),
2299 SelectPhase::Update {
2300 position,
2301 goal_column,
2302 scroll_delta,
2303 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2304 SelectPhase::End => self.end_selection(window, cx),
2305 }
2306 }
2307
2308 fn extend_selection(
2309 &mut self,
2310 position: DisplayPoint,
2311 click_count: usize,
2312 window: &mut Window,
2313 cx: &mut Context<Self>,
2314 ) {
2315 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2316 let tail = self.selections.newest::<usize>(cx).tail();
2317 self.begin_selection(position, false, click_count, window, cx);
2318
2319 let position = position.to_offset(&display_map, Bias::Left);
2320 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2321
2322 let mut pending_selection = self
2323 .selections
2324 .pending_anchor()
2325 .expect("extend_selection not called with pending selection");
2326 if position >= tail {
2327 pending_selection.start = tail_anchor;
2328 } else {
2329 pending_selection.end = tail_anchor;
2330 pending_selection.reversed = true;
2331 }
2332
2333 let mut pending_mode = self.selections.pending_mode().unwrap();
2334 match &mut pending_mode {
2335 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2336 _ => {}
2337 }
2338
2339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2340 s.set_pending(pending_selection, pending_mode)
2341 });
2342 }
2343
2344 fn begin_selection(
2345 &mut self,
2346 position: DisplayPoint,
2347 add: bool,
2348 click_count: usize,
2349 window: &mut Window,
2350 cx: &mut Context<Self>,
2351 ) {
2352 if !self.focus_handle.is_focused(window) {
2353 self.last_focused_descendant = None;
2354 window.focus(&self.focus_handle);
2355 }
2356
2357 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2358 let buffer = &display_map.buffer_snapshot;
2359 let newest_selection = self.selections.newest_anchor().clone();
2360 let position = display_map.clip_point(position, Bias::Left);
2361
2362 let start;
2363 let end;
2364 let mode;
2365 let mut auto_scroll;
2366 match click_count {
2367 1 => {
2368 start = buffer.anchor_before(position.to_point(&display_map));
2369 end = start;
2370 mode = SelectMode::Character;
2371 auto_scroll = true;
2372 }
2373 2 => {
2374 let range = movement::surrounding_word(&display_map, position);
2375 start = buffer.anchor_before(range.start.to_point(&display_map));
2376 end = buffer.anchor_before(range.end.to_point(&display_map));
2377 mode = SelectMode::Word(start..end);
2378 auto_scroll = true;
2379 }
2380 3 => {
2381 let position = display_map
2382 .clip_point(position, Bias::Left)
2383 .to_point(&display_map);
2384 let line_start = display_map.prev_line_boundary(position).0;
2385 let next_line_start = buffer.clip_point(
2386 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2387 Bias::Left,
2388 );
2389 start = buffer.anchor_before(line_start);
2390 end = buffer.anchor_before(next_line_start);
2391 mode = SelectMode::Line(start..end);
2392 auto_scroll = true;
2393 }
2394 _ => {
2395 start = buffer.anchor_before(0);
2396 end = buffer.anchor_before(buffer.len());
2397 mode = SelectMode::All;
2398 auto_scroll = false;
2399 }
2400 }
2401 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2402
2403 let point_to_delete: Option<usize> = {
2404 let selected_points: Vec<Selection<Point>> =
2405 self.selections.disjoint_in_range(start..end, cx);
2406
2407 if !add || click_count > 1 {
2408 None
2409 } else if !selected_points.is_empty() {
2410 Some(selected_points[0].id)
2411 } else {
2412 let clicked_point_already_selected =
2413 self.selections.disjoint.iter().find(|selection| {
2414 selection.start.to_point(buffer) == start.to_point(buffer)
2415 || selection.end.to_point(buffer) == end.to_point(buffer)
2416 });
2417
2418 clicked_point_already_selected.map(|selection| selection.id)
2419 }
2420 };
2421
2422 let selections_count = self.selections.count();
2423
2424 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2425 if let Some(point_to_delete) = point_to_delete {
2426 s.delete(point_to_delete);
2427
2428 if selections_count == 1 {
2429 s.set_pending_anchor_range(start..end, mode);
2430 }
2431 } else {
2432 if !add {
2433 s.clear_disjoint();
2434 } else if click_count > 1 {
2435 s.delete(newest_selection.id)
2436 }
2437
2438 s.set_pending_anchor_range(start..end, mode);
2439 }
2440 });
2441 }
2442
2443 fn begin_columnar_selection(
2444 &mut self,
2445 position: DisplayPoint,
2446 goal_column: u32,
2447 reset: bool,
2448 window: &mut Window,
2449 cx: &mut Context<Self>,
2450 ) {
2451 if !self.focus_handle.is_focused(window) {
2452 self.last_focused_descendant = None;
2453 window.focus(&self.focus_handle);
2454 }
2455
2456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2457
2458 if reset {
2459 let pointer_position = display_map
2460 .buffer_snapshot
2461 .anchor_before(position.to_point(&display_map));
2462
2463 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2464 s.clear_disjoint();
2465 s.set_pending_anchor_range(
2466 pointer_position..pointer_position,
2467 SelectMode::Character,
2468 );
2469 });
2470 }
2471
2472 let tail = self.selections.newest::<Point>(cx).tail();
2473 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2474
2475 if !reset {
2476 self.select_columns(
2477 tail.to_display_point(&display_map),
2478 position,
2479 goal_column,
2480 &display_map,
2481 window,
2482 cx,
2483 );
2484 }
2485 }
2486
2487 fn update_selection(
2488 &mut self,
2489 position: DisplayPoint,
2490 goal_column: u32,
2491 scroll_delta: gpui::Point<f32>,
2492 window: &mut Window,
2493 cx: &mut Context<Self>,
2494 ) {
2495 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2496
2497 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2498 let tail = tail.to_display_point(&display_map);
2499 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2500 } else if let Some(mut pending) = self.selections.pending_anchor() {
2501 let buffer = self.buffer.read(cx).snapshot(cx);
2502 let head;
2503 let tail;
2504 let mode = self.selections.pending_mode().unwrap();
2505 match &mode {
2506 SelectMode::Character => {
2507 head = position.to_point(&display_map);
2508 tail = pending.tail().to_point(&buffer);
2509 }
2510 SelectMode::Word(original_range) => {
2511 let original_display_range = original_range.start.to_display_point(&display_map)
2512 ..original_range.end.to_display_point(&display_map);
2513 let original_buffer_range = original_display_range.start.to_point(&display_map)
2514 ..original_display_range.end.to_point(&display_map);
2515 if movement::is_inside_word(&display_map, position)
2516 || original_display_range.contains(&position)
2517 {
2518 let word_range = movement::surrounding_word(&display_map, position);
2519 if word_range.start < original_display_range.start {
2520 head = word_range.start.to_point(&display_map);
2521 } else {
2522 head = word_range.end.to_point(&display_map);
2523 }
2524 } else {
2525 head = position.to_point(&display_map);
2526 }
2527
2528 if head <= original_buffer_range.start {
2529 tail = original_buffer_range.end;
2530 } else {
2531 tail = original_buffer_range.start;
2532 }
2533 }
2534 SelectMode::Line(original_range) => {
2535 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2536
2537 let position = display_map
2538 .clip_point(position, Bias::Left)
2539 .to_point(&display_map);
2540 let line_start = display_map.prev_line_boundary(position).0;
2541 let next_line_start = buffer.clip_point(
2542 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2543 Bias::Left,
2544 );
2545
2546 if line_start < original_range.start {
2547 head = line_start
2548 } else {
2549 head = next_line_start
2550 }
2551
2552 if head <= original_range.start {
2553 tail = original_range.end;
2554 } else {
2555 tail = original_range.start;
2556 }
2557 }
2558 SelectMode::All => {
2559 return;
2560 }
2561 };
2562
2563 if head < tail {
2564 pending.start = buffer.anchor_before(head);
2565 pending.end = buffer.anchor_before(tail);
2566 pending.reversed = true;
2567 } else {
2568 pending.start = buffer.anchor_before(tail);
2569 pending.end = buffer.anchor_before(head);
2570 pending.reversed = false;
2571 }
2572
2573 self.change_selections(None, window, cx, |s| {
2574 s.set_pending(pending, mode);
2575 });
2576 } else {
2577 log::error!("update_selection dispatched with no pending selection");
2578 return;
2579 }
2580
2581 self.apply_scroll_delta(scroll_delta, window, cx);
2582 cx.notify();
2583 }
2584
2585 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2586 self.columnar_selection_tail.take();
2587 if self.selections.pending_anchor().is_some() {
2588 let selections = self.selections.all::<usize>(cx);
2589 self.change_selections(None, window, cx, |s| {
2590 s.select(selections);
2591 s.clear_pending();
2592 });
2593 }
2594 }
2595
2596 fn select_columns(
2597 &mut self,
2598 tail: DisplayPoint,
2599 head: DisplayPoint,
2600 goal_column: u32,
2601 display_map: &DisplaySnapshot,
2602 window: &mut Window,
2603 cx: &mut Context<Self>,
2604 ) {
2605 let start_row = cmp::min(tail.row(), head.row());
2606 let end_row = cmp::max(tail.row(), head.row());
2607 let start_column = cmp::min(tail.column(), goal_column);
2608 let end_column = cmp::max(tail.column(), goal_column);
2609 let reversed = start_column < tail.column();
2610
2611 let selection_ranges = (start_row.0..=end_row.0)
2612 .map(DisplayRow)
2613 .filter_map(|row| {
2614 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2615 let start = display_map
2616 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2617 .to_point(display_map);
2618 let end = display_map
2619 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2620 .to_point(display_map);
2621 if reversed {
2622 Some(end..start)
2623 } else {
2624 Some(start..end)
2625 }
2626 } else {
2627 None
2628 }
2629 })
2630 .collect::<Vec<_>>();
2631
2632 self.change_selections(None, window, cx, |s| {
2633 s.select_ranges(selection_ranges);
2634 });
2635 cx.notify();
2636 }
2637
2638 pub fn has_pending_nonempty_selection(&self) -> bool {
2639 let pending_nonempty_selection = match self.selections.pending_anchor() {
2640 Some(Selection { start, end, .. }) => start != end,
2641 None => false,
2642 };
2643
2644 pending_nonempty_selection
2645 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2646 }
2647
2648 pub fn has_pending_selection(&self) -> bool {
2649 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2650 }
2651
2652 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2653 self.selection_mark_mode = false;
2654
2655 if self.clear_expanded_diff_hunks(cx) {
2656 cx.notify();
2657 return;
2658 }
2659 if self.dismiss_menus_and_popups(true, window, cx) {
2660 return;
2661 }
2662
2663 if self.mode == EditorMode::Full
2664 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2665 {
2666 return;
2667 }
2668
2669 cx.propagate();
2670 }
2671
2672 pub fn dismiss_menus_and_popups(
2673 &mut self,
2674 is_user_requested: bool,
2675 window: &mut Window,
2676 cx: &mut Context<Self>,
2677 ) -> bool {
2678 if self.take_rename(false, window, cx).is_some() {
2679 return true;
2680 }
2681
2682 if hide_hover(self, cx) {
2683 return true;
2684 }
2685
2686 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2687 return true;
2688 }
2689
2690 if self.hide_context_menu(window, cx).is_some() {
2691 return true;
2692 }
2693
2694 if self.mouse_context_menu.take().is_some() {
2695 return true;
2696 }
2697
2698 if is_user_requested && self.discard_inline_completion(true, cx) {
2699 return true;
2700 }
2701
2702 if self.snippet_stack.pop().is_some() {
2703 return true;
2704 }
2705
2706 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2707 self.dismiss_diagnostics(cx);
2708 return true;
2709 }
2710
2711 false
2712 }
2713
2714 fn linked_editing_ranges_for(
2715 &self,
2716 selection: Range<text::Anchor>,
2717 cx: &App,
2718 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2719 if self.linked_edit_ranges.is_empty() {
2720 return None;
2721 }
2722 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2723 selection.end.buffer_id.and_then(|end_buffer_id| {
2724 if selection.start.buffer_id != Some(end_buffer_id) {
2725 return None;
2726 }
2727 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2728 let snapshot = buffer.read(cx).snapshot();
2729 self.linked_edit_ranges
2730 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2731 .map(|ranges| (ranges, snapshot, buffer))
2732 })?;
2733 use text::ToOffset as TO;
2734 // find offset from the start of current range to current cursor position
2735 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2736
2737 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2738 let start_difference = start_offset - start_byte_offset;
2739 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2740 let end_difference = end_offset - start_byte_offset;
2741 // Current range has associated linked ranges.
2742 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2743 for range in linked_ranges.iter() {
2744 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2745 let end_offset = start_offset + end_difference;
2746 let start_offset = start_offset + start_difference;
2747 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2748 continue;
2749 }
2750 if self.selections.disjoint_anchor_ranges().any(|s| {
2751 if s.start.buffer_id != selection.start.buffer_id
2752 || s.end.buffer_id != selection.end.buffer_id
2753 {
2754 return false;
2755 }
2756 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2757 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2758 }) {
2759 continue;
2760 }
2761 let start = buffer_snapshot.anchor_after(start_offset);
2762 let end = buffer_snapshot.anchor_after(end_offset);
2763 linked_edits
2764 .entry(buffer.clone())
2765 .or_default()
2766 .push(start..end);
2767 }
2768 Some(linked_edits)
2769 }
2770
2771 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2772 let text: Arc<str> = text.into();
2773
2774 if self.read_only(cx) {
2775 return;
2776 }
2777
2778 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
2779
2780 let selections = self.selections.all_adjusted(cx);
2781 let mut bracket_inserted = false;
2782 let mut edits = Vec::new();
2783 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2784 let mut new_selections = Vec::with_capacity(selections.len());
2785 let mut new_autoclose_regions = Vec::new();
2786 let snapshot = self.buffer.read(cx).read(cx);
2787
2788 for (selection, autoclose_region) in
2789 self.selections_with_autoclose_regions(selections, &snapshot)
2790 {
2791 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2792 // Determine if the inserted text matches the opening or closing
2793 // bracket of any of this language's bracket pairs.
2794 let mut bracket_pair = None;
2795 let mut is_bracket_pair_start = false;
2796 let mut is_bracket_pair_end = false;
2797 if !text.is_empty() {
2798 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2799 // and they are removing the character that triggered IME popup.
2800 for (pair, enabled) in scope.brackets() {
2801 if !pair.close && !pair.surround {
2802 continue;
2803 }
2804
2805 if enabled && pair.start.ends_with(text.as_ref()) {
2806 let prefix_len = pair.start.len() - text.len();
2807 let preceding_text_matches_prefix = prefix_len == 0
2808 || (selection.start.column >= (prefix_len as u32)
2809 && snapshot.contains_str_at(
2810 Point::new(
2811 selection.start.row,
2812 selection.start.column - (prefix_len as u32),
2813 ),
2814 &pair.start[..prefix_len],
2815 ));
2816 if preceding_text_matches_prefix {
2817 bracket_pair = Some(pair.clone());
2818 is_bracket_pair_start = true;
2819 break;
2820 }
2821 }
2822 if pair.end.as_str() == text.as_ref() {
2823 bracket_pair = Some(pair.clone());
2824 is_bracket_pair_end = true;
2825 break;
2826 }
2827 }
2828 }
2829
2830 if let Some(bracket_pair) = bracket_pair {
2831 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2832 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2833 let auto_surround =
2834 self.use_auto_surround && snapshot_settings.use_auto_surround;
2835 if selection.is_empty() {
2836 if is_bracket_pair_start {
2837 // If the inserted text is a suffix of an opening bracket and the
2838 // selection is preceded by the rest of the opening bracket, then
2839 // insert the closing bracket.
2840 let following_text_allows_autoclose = snapshot
2841 .chars_at(selection.start)
2842 .next()
2843 .map_or(true, |c| scope.should_autoclose_before(c));
2844
2845 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2846 && bracket_pair.start.len() == 1
2847 {
2848 let target = bracket_pair.start.chars().next().unwrap();
2849 let current_line_count = snapshot
2850 .reversed_chars_at(selection.start)
2851 .take_while(|&c| c != '\n')
2852 .filter(|&c| c == target)
2853 .count();
2854 current_line_count % 2 == 1
2855 } else {
2856 false
2857 };
2858
2859 if autoclose
2860 && bracket_pair.close
2861 && following_text_allows_autoclose
2862 && !is_closing_quote
2863 {
2864 let anchor = snapshot.anchor_before(selection.end);
2865 new_selections.push((selection.map(|_| anchor), text.len()));
2866 new_autoclose_regions.push((
2867 anchor,
2868 text.len(),
2869 selection.id,
2870 bracket_pair.clone(),
2871 ));
2872 edits.push((
2873 selection.range(),
2874 format!("{}{}", text, bracket_pair.end).into(),
2875 ));
2876 bracket_inserted = true;
2877 continue;
2878 }
2879 }
2880
2881 if let Some(region) = autoclose_region {
2882 // If the selection is followed by an auto-inserted closing bracket,
2883 // then don't insert that closing bracket again; just move the selection
2884 // past the closing bracket.
2885 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2886 && text.as_ref() == region.pair.end.as_str();
2887 if should_skip {
2888 let anchor = snapshot.anchor_after(selection.end);
2889 new_selections
2890 .push((selection.map(|_| anchor), region.pair.end.len()));
2891 continue;
2892 }
2893 }
2894
2895 let always_treat_brackets_as_autoclosed = snapshot
2896 .settings_at(selection.start, cx)
2897 .always_treat_brackets_as_autoclosed;
2898 if always_treat_brackets_as_autoclosed
2899 && is_bracket_pair_end
2900 && snapshot.contains_str_at(selection.end, text.as_ref())
2901 {
2902 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2903 // and the inserted text is a closing bracket and the selection is followed
2904 // by the closing bracket then move the selection past the closing bracket.
2905 let anchor = snapshot.anchor_after(selection.end);
2906 new_selections.push((selection.map(|_| anchor), text.len()));
2907 continue;
2908 }
2909 }
2910 // If an opening bracket is 1 character long and is typed while
2911 // text is selected, then surround that text with the bracket pair.
2912 else if auto_surround
2913 && bracket_pair.surround
2914 && is_bracket_pair_start
2915 && bracket_pair.start.chars().count() == 1
2916 {
2917 edits.push((selection.start..selection.start, text.clone()));
2918 edits.push((
2919 selection.end..selection.end,
2920 bracket_pair.end.as_str().into(),
2921 ));
2922 bracket_inserted = true;
2923 new_selections.push((
2924 Selection {
2925 id: selection.id,
2926 start: snapshot.anchor_after(selection.start),
2927 end: snapshot.anchor_before(selection.end),
2928 reversed: selection.reversed,
2929 goal: selection.goal,
2930 },
2931 0,
2932 ));
2933 continue;
2934 }
2935 }
2936 }
2937
2938 if self.auto_replace_emoji_shortcode
2939 && selection.is_empty()
2940 && text.as_ref().ends_with(':')
2941 {
2942 if let Some(possible_emoji_short_code) =
2943 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2944 {
2945 if !possible_emoji_short_code.is_empty() {
2946 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2947 let emoji_shortcode_start = Point::new(
2948 selection.start.row,
2949 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2950 );
2951
2952 // Remove shortcode from buffer
2953 edits.push((
2954 emoji_shortcode_start..selection.start,
2955 "".to_string().into(),
2956 ));
2957 new_selections.push((
2958 Selection {
2959 id: selection.id,
2960 start: snapshot.anchor_after(emoji_shortcode_start),
2961 end: snapshot.anchor_before(selection.start),
2962 reversed: selection.reversed,
2963 goal: selection.goal,
2964 },
2965 0,
2966 ));
2967
2968 // Insert emoji
2969 let selection_start_anchor = snapshot.anchor_after(selection.start);
2970 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2971 edits.push((selection.start..selection.end, emoji.to_string().into()));
2972
2973 continue;
2974 }
2975 }
2976 }
2977 }
2978
2979 // If not handling any auto-close operation, then just replace the selected
2980 // text with the given input and move the selection to the end of the
2981 // newly inserted text.
2982 let anchor = snapshot.anchor_after(selection.end);
2983 if !self.linked_edit_ranges.is_empty() {
2984 let start_anchor = snapshot.anchor_before(selection.start);
2985
2986 let is_word_char = text.chars().next().map_or(true, |char| {
2987 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2988 classifier.is_word(char)
2989 });
2990
2991 if is_word_char {
2992 if let Some(ranges) = self
2993 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2994 {
2995 for (buffer, edits) in ranges {
2996 linked_edits
2997 .entry(buffer.clone())
2998 .or_default()
2999 .extend(edits.into_iter().map(|range| (range, text.clone())));
3000 }
3001 }
3002 }
3003 }
3004
3005 new_selections.push((selection.map(|_| anchor), 0));
3006 edits.push((selection.start..selection.end, text.clone()));
3007 }
3008
3009 drop(snapshot);
3010
3011 self.transact(window, cx, |this, window, cx| {
3012 this.buffer.update(cx, |buffer, cx| {
3013 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3014 });
3015 for (buffer, edits) in linked_edits {
3016 buffer.update(cx, |buffer, cx| {
3017 let snapshot = buffer.snapshot();
3018 let edits = edits
3019 .into_iter()
3020 .map(|(range, text)| {
3021 use text::ToPoint as TP;
3022 let end_point = TP::to_point(&range.end, &snapshot);
3023 let start_point = TP::to_point(&range.start, &snapshot);
3024 (start_point..end_point, text)
3025 })
3026 .sorted_by_key(|(range, _)| range.start)
3027 .collect::<Vec<_>>();
3028 buffer.edit(edits, None, cx);
3029 })
3030 }
3031 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3032 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3033 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3034 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3035 .zip(new_selection_deltas)
3036 .map(|(selection, delta)| Selection {
3037 id: selection.id,
3038 start: selection.start + delta,
3039 end: selection.end + delta,
3040 reversed: selection.reversed,
3041 goal: SelectionGoal::None,
3042 })
3043 .collect::<Vec<_>>();
3044
3045 let mut i = 0;
3046 for (position, delta, selection_id, pair) in new_autoclose_regions {
3047 let position = position.to_offset(&map.buffer_snapshot) + delta;
3048 let start = map.buffer_snapshot.anchor_before(position);
3049 let end = map.buffer_snapshot.anchor_after(position);
3050 while let Some(existing_state) = this.autoclose_regions.get(i) {
3051 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3052 Ordering::Less => i += 1,
3053 Ordering::Greater => break,
3054 Ordering::Equal => {
3055 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3056 Ordering::Less => i += 1,
3057 Ordering::Equal => break,
3058 Ordering::Greater => break,
3059 }
3060 }
3061 }
3062 }
3063 this.autoclose_regions.insert(
3064 i,
3065 AutocloseRegion {
3066 selection_id,
3067 range: start..end,
3068 pair,
3069 },
3070 );
3071 }
3072
3073 let had_active_inline_completion = this.has_active_inline_completion();
3074 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3075 s.select(new_selections)
3076 });
3077
3078 if !bracket_inserted {
3079 if let Some(on_type_format_task) =
3080 this.trigger_on_type_formatting(text.to_string(), window, cx)
3081 {
3082 on_type_format_task.detach_and_log_err(cx);
3083 }
3084 }
3085
3086 let editor_settings = EditorSettings::get_global(cx);
3087 if bracket_inserted
3088 && (editor_settings.auto_signature_help
3089 || editor_settings.show_signature_help_after_edits)
3090 {
3091 this.show_signature_help(&ShowSignatureHelp, window, cx);
3092 }
3093
3094 let trigger_in_words =
3095 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3096 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3097 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3098 this.refresh_inline_completion(true, false, window, cx);
3099 });
3100 }
3101
3102 fn find_possible_emoji_shortcode_at_position(
3103 snapshot: &MultiBufferSnapshot,
3104 position: Point,
3105 ) -> Option<String> {
3106 let mut chars = Vec::new();
3107 let mut found_colon = false;
3108 for char in snapshot.reversed_chars_at(position).take(100) {
3109 // Found a possible emoji shortcode in the middle of the buffer
3110 if found_colon {
3111 if char.is_whitespace() {
3112 chars.reverse();
3113 return Some(chars.iter().collect());
3114 }
3115 // If the previous character is not a whitespace, we are in the middle of a word
3116 // and we only want to complete the shortcode if the word is made up of other emojis
3117 let mut containing_word = String::new();
3118 for ch in snapshot
3119 .reversed_chars_at(position)
3120 .skip(chars.len() + 1)
3121 .take(100)
3122 {
3123 if ch.is_whitespace() {
3124 break;
3125 }
3126 containing_word.push(ch);
3127 }
3128 let containing_word = containing_word.chars().rev().collect::<String>();
3129 if util::word_consists_of_emojis(containing_word.as_str()) {
3130 chars.reverse();
3131 return Some(chars.iter().collect());
3132 }
3133 }
3134
3135 if char.is_whitespace() || !char.is_ascii() {
3136 return None;
3137 }
3138 if char == ':' {
3139 found_colon = true;
3140 } else {
3141 chars.push(char);
3142 }
3143 }
3144 // Found a possible emoji shortcode at the beginning of the buffer
3145 chars.reverse();
3146 Some(chars.iter().collect())
3147 }
3148
3149 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3150 self.transact(window, cx, |this, window, cx| {
3151 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3152 let selections = this.selections.all::<usize>(cx);
3153 let multi_buffer = this.buffer.read(cx);
3154 let buffer = multi_buffer.snapshot(cx);
3155 selections
3156 .iter()
3157 .map(|selection| {
3158 let start_point = selection.start.to_point(&buffer);
3159 let mut indent =
3160 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3161 indent.len = cmp::min(indent.len, start_point.column);
3162 let start = selection.start;
3163 let end = selection.end;
3164 let selection_is_empty = start == end;
3165 let language_scope = buffer.language_scope_at(start);
3166 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3167 &language_scope
3168 {
3169 let insert_extra_newline =
3170 insert_extra_newline_brackets(&buffer, start..end, language)
3171 || insert_extra_newline_tree_sitter(&buffer, start..end);
3172
3173 // Comment extension on newline is allowed only for cursor selections
3174 let comment_delimiter = maybe!({
3175 if !selection_is_empty {
3176 return None;
3177 }
3178
3179 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3180 return None;
3181 }
3182
3183 let delimiters = language.line_comment_prefixes();
3184 let max_len_of_delimiter =
3185 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3186 let (snapshot, range) =
3187 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3188
3189 let mut index_of_first_non_whitespace = 0;
3190 let comment_candidate = snapshot
3191 .chars_for_range(range)
3192 .skip_while(|c| {
3193 let should_skip = c.is_whitespace();
3194 if should_skip {
3195 index_of_first_non_whitespace += 1;
3196 }
3197 should_skip
3198 })
3199 .take(max_len_of_delimiter)
3200 .collect::<String>();
3201 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3202 comment_candidate.starts_with(comment_prefix.as_ref())
3203 })?;
3204 let cursor_is_placed_after_comment_marker =
3205 index_of_first_non_whitespace + comment_prefix.len()
3206 <= start_point.column as usize;
3207 if cursor_is_placed_after_comment_marker {
3208 Some(comment_prefix.clone())
3209 } else {
3210 None
3211 }
3212 });
3213 (comment_delimiter, insert_extra_newline)
3214 } else {
3215 (None, false)
3216 };
3217
3218 let capacity_for_delimiter = comment_delimiter
3219 .as_deref()
3220 .map(str::len)
3221 .unwrap_or_default();
3222 let mut new_text =
3223 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3224 new_text.push('\n');
3225 new_text.extend(indent.chars());
3226 if let Some(delimiter) = &comment_delimiter {
3227 new_text.push_str(delimiter);
3228 }
3229 if insert_extra_newline {
3230 new_text = new_text.repeat(2);
3231 }
3232
3233 let anchor = buffer.anchor_after(end);
3234 let new_selection = selection.map(|_| anchor);
3235 (
3236 (start..end, new_text),
3237 (insert_extra_newline, new_selection),
3238 )
3239 })
3240 .unzip()
3241 };
3242
3243 this.edit_with_autoindent(edits, cx);
3244 let buffer = this.buffer.read(cx).snapshot(cx);
3245 let new_selections = selection_fixup_info
3246 .into_iter()
3247 .map(|(extra_newline_inserted, new_selection)| {
3248 let mut cursor = new_selection.end.to_point(&buffer);
3249 if extra_newline_inserted {
3250 cursor.row -= 1;
3251 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3252 }
3253 new_selection.map(|_| cursor)
3254 })
3255 .collect();
3256
3257 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3258 s.select(new_selections)
3259 });
3260 this.refresh_inline_completion(true, false, window, cx);
3261 });
3262 }
3263
3264 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3265 let buffer = self.buffer.read(cx);
3266 let snapshot = buffer.snapshot(cx);
3267
3268 let mut edits = Vec::new();
3269 let mut rows = Vec::new();
3270
3271 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3272 let cursor = selection.head();
3273 let row = cursor.row;
3274
3275 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3276
3277 let newline = "\n".to_string();
3278 edits.push((start_of_line..start_of_line, newline));
3279
3280 rows.push(row + rows_inserted as u32);
3281 }
3282
3283 self.transact(window, cx, |editor, window, cx| {
3284 editor.edit(edits, cx);
3285
3286 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3287 let mut index = 0;
3288 s.move_cursors_with(|map, _, _| {
3289 let row = rows[index];
3290 index += 1;
3291
3292 let point = Point::new(row, 0);
3293 let boundary = map.next_line_boundary(point).1;
3294 let clipped = map.clip_point(boundary, Bias::Left);
3295
3296 (clipped, SelectionGoal::None)
3297 });
3298 });
3299
3300 let mut indent_edits = Vec::new();
3301 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3302 for row in rows {
3303 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3304 for (row, indent) in indents {
3305 if indent.len == 0 {
3306 continue;
3307 }
3308
3309 let text = match indent.kind {
3310 IndentKind::Space => " ".repeat(indent.len as usize),
3311 IndentKind::Tab => "\t".repeat(indent.len as usize),
3312 };
3313 let point = Point::new(row.0, 0);
3314 indent_edits.push((point..point, text));
3315 }
3316 }
3317 editor.edit(indent_edits, cx);
3318 });
3319 }
3320
3321 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3322 let buffer = self.buffer.read(cx);
3323 let snapshot = buffer.snapshot(cx);
3324
3325 let mut edits = Vec::new();
3326 let mut rows = Vec::new();
3327 let mut rows_inserted = 0;
3328
3329 for selection in self.selections.all_adjusted(cx) {
3330 let cursor = selection.head();
3331 let row = cursor.row;
3332
3333 let point = Point::new(row + 1, 0);
3334 let start_of_line = snapshot.clip_point(point, Bias::Left);
3335
3336 let newline = "\n".to_string();
3337 edits.push((start_of_line..start_of_line, newline));
3338
3339 rows_inserted += 1;
3340 rows.push(row + rows_inserted);
3341 }
3342
3343 self.transact(window, cx, |editor, window, cx| {
3344 editor.edit(edits, cx);
3345
3346 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3347 let mut index = 0;
3348 s.move_cursors_with(|map, _, _| {
3349 let row = rows[index];
3350 index += 1;
3351
3352 let point = Point::new(row, 0);
3353 let boundary = map.next_line_boundary(point).1;
3354 let clipped = map.clip_point(boundary, Bias::Left);
3355
3356 (clipped, SelectionGoal::None)
3357 });
3358 });
3359
3360 let mut indent_edits = Vec::new();
3361 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3362 for row in rows {
3363 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3364 for (row, indent) in indents {
3365 if indent.len == 0 {
3366 continue;
3367 }
3368
3369 let text = match indent.kind {
3370 IndentKind::Space => " ".repeat(indent.len as usize),
3371 IndentKind::Tab => "\t".repeat(indent.len as usize),
3372 };
3373 let point = Point::new(row.0, 0);
3374 indent_edits.push((point..point, text));
3375 }
3376 }
3377 editor.edit(indent_edits, cx);
3378 });
3379 }
3380
3381 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3382 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3383 original_indent_columns: Vec::new(),
3384 });
3385 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3386 }
3387
3388 fn insert_with_autoindent_mode(
3389 &mut self,
3390 text: &str,
3391 autoindent_mode: Option<AutoindentMode>,
3392 window: &mut Window,
3393 cx: &mut Context<Self>,
3394 ) {
3395 if self.read_only(cx) {
3396 return;
3397 }
3398
3399 let text: Arc<str> = text.into();
3400 self.transact(window, cx, |this, window, cx| {
3401 let old_selections = this.selections.all_adjusted(cx);
3402 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3403 let anchors = {
3404 let snapshot = buffer.read(cx);
3405 old_selections
3406 .iter()
3407 .map(|s| {
3408 let anchor = snapshot.anchor_after(s.head());
3409 s.map(|_| anchor)
3410 })
3411 .collect::<Vec<_>>()
3412 };
3413 buffer.edit(
3414 old_selections
3415 .iter()
3416 .map(|s| (s.start..s.end, text.clone())),
3417 autoindent_mode,
3418 cx,
3419 );
3420 anchors
3421 });
3422
3423 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3424 s.select_anchors(selection_anchors);
3425 });
3426
3427 cx.notify();
3428 });
3429 }
3430
3431 fn trigger_completion_on_input(
3432 &mut self,
3433 text: &str,
3434 trigger_in_words: bool,
3435 window: &mut Window,
3436 cx: &mut Context<Self>,
3437 ) {
3438 if self.is_completion_trigger(text, trigger_in_words, cx) {
3439 self.show_completions(
3440 &ShowCompletions {
3441 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3442 },
3443 window,
3444 cx,
3445 );
3446 } else {
3447 self.hide_context_menu(window, cx);
3448 }
3449 }
3450
3451 fn is_completion_trigger(
3452 &self,
3453 text: &str,
3454 trigger_in_words: bool,
3455 cx: &mut Context<Self>,
3456 ) -> bool {
3457 let position = self.selections.newest_anchor().head();
3458 let multibuffer = self.buffer.read(cx);
3459 let Some(buffer) = position
3460 .buffer_id
3461 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3462 else {
3463 return false;
3464 };
3465
3466 if let Some(completion_provider) = &self.completion_provider {
3467 completion_provider.is_completion_trigger(
3468 &buffer,
3469 position.text_anchor,
3470 text,
3471 trigger_in_words,
3472 cx,
3473 )
3474 } else {
3475 false
3476 }
3477 }
3478
3479 /// If any empty selections is touching the start of its innermost containing autoclose
3480 /// region, expand it to select the brackets.
3481 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3482 let selections = self.selections.all::<usize>(cx);
3483 let buffer = self.buffer.read(cx).read(cx);
3484 let new_selections = self
3485 .selections_with_autoclose_regions(selections, &buffer)
3486 .map(|(mut selection, region)| {
3487 if !selection.is_empty() {
3488 return selection;
3489 }
3490
3491 if let Some(region) = region {
3492 let mut range = region.range.to_offset(&buffer);
3493 if selection.start == range.start && range.start >= region.pair.start.len() {
3494 range.start -= region.pair.start.len();
3495 if buffer.contains_str_at(range.start, ®ion.pair.start)
3496 && buffer.contains_str_at(range.end, ®ion.pair.end)
3497 {
3498 range.end += region.pair.end.len();
3499 selection.start = range.start;
3500 selection.end = range.end;
3501
3502 return selection;
3503 }
3504 }
3505 }
3506
3507 let always_treat_brackets_as_autoclosed = buffer
3508 .settings_at(selection.start, cx)
3509 .always_treat_brackets_as_autoclosed;
3510
3511 if !always_treat_brackets_as_autoclosed {
3512 return selection;
3513 }
3514
3515 if let Some(scope) = buffer.language_scope_at(selection.start) {
3516 for (pair, enabled) in scope.brackets() {
3517 if !enabled || !pair.close {
3518 continue;
3519 }
3520
3521 if buffer.contains_str_at(selection.start, &pair.end) {
3522 let pair_start_len = pair.start.len();
3523 if buffer.contains_str_at(
3524 selection.start.saturating_sub(pair_start_len),
3525 &pair.start,
3526 ) {
3527 selection.start -= pair_start_len;
3528 selection.end += pair.end.len();
3529
3530 return selection;
3531 }
3532 }
3533 }
3534 }
3535
3536 selection
3537 })
3538 .collect();
3539
3540 drop(buffer);
3541 self.change_selections(None, window, cx, |selections| {
3542 selections.select(new_selections)
3543 });
3544 }
3545
3546 /// Iterate the given selections, and for each one, find the smallest surrounding
3547 /// autoclose region. This uses the ordering of the selections and the autoclose
3548 /// regions to avoid repeated comparisons.
3549 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3550 &'a self,
3551 selections: impl IntoIterator<Item = Selection<D>>,
3552 buffer: &'a MultiBufferSnapshot,
3553 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3554 let mut i = 0;
3555 let mut regions = self.autoclose_regions.as_slice();
3556 selections.into_iter().map(move |selection| {
3557 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3558
3559 let mut enclosing = None;
3560 while let Some(pair_state) = regions.get(i) {
3561 if pair_state.range.end.to_offset(buffer) < range.start {
3562 regions = ®ions[i + 1..];
3563 i = 0;
3564 } else if pair_state.range.start.to_offset(buffer) > range.end {
3565 break;
3566 } else {
3567 if pair_state.selection_id == selection.id {
3568 enclosing = Some(pair_state);
3569 }
3570 i += 1;
3571 }
3572 }
3573
3574 (selection, enclosing)
3575 })
3576 }
3577
3578 /// Remove any autoclose regions that no longer contain their selection.
3579 fn invalidate_autoclose_regions(
3580 &mut self,
3581 mut selections: &[Selection<Anchor>],
3582 buffer: &MultiBufferSnapshot,
3583 ) {
3584 self.autoclose_regions.retain(|state| {
3585 let mut i = 0;
3586 while let Some(selection) = selections.get(i) {
3587 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3588 selections = &selections[1..];
3589 continue;
3590 }
3591 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3592 break;
3593 }
3594 if selection.id == state.selection_id {
3595 return true;
3596 } else {
3597 i += 1;
3598 }
3599 }
3600 false
3601 });
3602 }
3603
3604 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3605 let offset = position.to_offset(buffer);
3606 let (word_range, kind) = buffer.surrounding_word(offset, true);
3607 if offset > word_range.start && kind == Some(CharKind::Word) {
3608 Some(
3609 buffer
3610 .text_for_range(word_range.start..offset)
3611 .collect::<String>(),
3612 )
3613 } else {
3614 None
3615 }
3616 }
3617
3618 pub fn toggle_inlay_hints(
3619 &mut self,
3620 _: &ToggleInlayHints,
3621 _: &mut Window,
3622 cx: &mut Context<Self>,
3623 ) {
3624 self.refresh_inlay_hints(
3625 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3626 cx,
3627 );
3628 }
3629
3630 pub fn inlay_hints_enabled(&self) -> bool {
3631 self.inlay_hint_cache.enabled
3632 }
3633
3634 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3635 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3636 return;
3637 }
3638
3639 let reason_description = reason.description();
3640 let ignore_debounce = matches!(
3641 reason,
3642 InlayHintRefreshReason::SettingsChange(_)
3643 | InlayHintRefreshReason::Toggle(_)
3644 | InlayHintRefreshReason::ExcerptsRemoved(_)
3645 );
3646 let (invalidate_cache, required_languages) = match reason {
3647 InlayHintRefreshReason::Toggle(enabled) => {
3648 self.inlay_hint_cache.enabled = enabled;
3649 if enabled {
3650 (InvalidationStrategy::RefreshRequested, None)
3651 } else {
3652 self.inlay_hint_cache.clear();
3653 self.splice_inlays(
3654 &self
3655 .visible_inlay_hints(cx)
3656 .iter()
3657 .map(|inlay| inlay.id)
3658 .collect::<Vec<InlayId>>(),
3659 Vec::new(),
3660 cx,
3661 );
3662 return;
3663 }
3664 }
3665 InlayHintRefreshReason::SettingsChange(new_settings) => {
3666 match self.inlay_hint_cache.update_settings(
3667 &self.buffer,
3668 new_settings,
3669 self.visible_inlay_hints(cx),
3670 cx,
3671 ) {
3672 ControlFlow::Break(Some(InlaySplice {
3673 to_remove,
3674 to_insert,
3675 })) => {
3676 self.splice_inlays(&to_remove, to_insert, cx);
3677 return;
3678 }
3679 ControlFlow::Break(None) => return,
3680 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3681 }
3682 }
3683 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3684 if let Some(InlaySplice {
3685 to_remove,
3686 to_insert,
3687 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3688 {
3689 self.splice_inlays(&to_remove, to_insert, cx);
3690 }
3691 return;
3692 }
3693 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3694 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3695 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3696 }
3697 InlayHintRefreshReason::RefreshRequested => {
3698 (InvalidationStrategy::RefreshRequested, None)
3699 }
3700 };
3701
3702 if let Some(InlaySplice {
3703 to_remove,
3704 to_insert,
3705 }) = self.inlay_hint_cache.spawn_hint_refresh(
3706 reason_description,
3707 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3708 invalidate_cache,
3709 ignore_debounce,
3710 cx,
3711 ) {
3712 self.splice_inlays(&to_remove, to_insert, cx);
3713 }
3714 }
3715
3716 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3717 self.display_map
3718 .read(cx)
3719 .current_inlays()
3720 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3721 .cloned()
3722 .collect()
3723 }
3724
3725 pub fn excerpts_for_inlay_hints_query(
3726 &self,
3727 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3728 cx: &mut Context<Editor>,
3729 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3730 let Some(project) = self.project.as_ref() else {
3731 return HashMap::default();
3732 };
3733 let project = project.read(cx);
3734 let multi_buffer = self.buffer().read(cx);
3735 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3736 let multi_buffer_visible_start = self
3737 .scroll_manager
3738 .anchor()
3739 .anchor
3740 .to_point(&multi_buffer_snapshot);
3741 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3742 multi_buffer_visible_start
3743 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3744 Bias::Left,
3745 );
3746 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3747 multi_buffer_snapshot
3748 .range_to_buffer_ranges(multi_buffer_visible_range)
3749 .into_iter()
3750 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3751 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3752 let buffer_file = project::File::from_dyn(buffer.file())?;
3753 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3754 let worktree_entry = buffer_worktree
3755 .read(cx)
3756 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3757 if worktree_entry.is_ignored {
3758 return None;
3759 }
3760
3761 let language = buffer.language()?;
3762 if let Some(restrict_to_languages) = restrict_to_languages {
3763 if !restrict_to_languages.contains(language) {
3764 return None;
3765 }
3766 }
3767 Some((
3768 excerpt_id,
3769 (
3770 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3771 buffer.version().clone(),
3772 excerpt_visible_range,
3773 ),
3774 ))
3775 })
3776 .collect()
3777 }
3778
3779 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3780 TextLayoutDetails {
3781 text_system: window.text_system().clone(),
3782 editor_style: self.style.clone().unwrap(),
3783 rem_size: window.rem_size(),
3784 scroll_anchor: self.scroll_manager.anchor(),
3785 visible_rows: self.visible_line_count(),
3786 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3787 }
3788 }
3789
3790 pub fn splice_inlays(
3791 &self,
3792 to_remove: &[InlayId],
3793 to_insert: Vec<Inlay>,
3794 cx: &mut Context<Self>,
3795 ) {
3796 self.display_map.update(cx, |display_map, cx| {
3797 display_map.splice_inlays(to_remove, to_insert, cx)
3798 });
3799 cx.notify();
3800 }
3801
3802 fn trigger_on_type_formatting(
3803 &self,
3804 input: String,
3805 window: &mut Window,
3806 cx: &mut Context<Self>,
3807 ) -> Option<Task<Result<()>>> {
3808 if input.len() != 1 {
3809 return None;
3810 }
3811
3812 let project = self.project.as_ref()?;
3813 let position = self.selections.newest_anchor().head();
3814 let (buffer, buffer_position) = self
3815 .buffer
3816 .read(cx)
3817 .text_anchor_for_position(position, cx)?;
3818
3819 let settings = language_settings::language_settings(
3820 buffer
3821 .read(cx)
3822 .language_at(buffer_position)
3823 .map(|l| l.name()),
3824 buffer.read(cx).file(),
3825 cx,
3826 );
3827 if !settings.use_on_type_format {
3828 return None;
3829 }
3830
3831 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3832 // hence we do LSP request & edit on host side only — add formats to host's history.
3833 let push_to_lsp_host_history = true;
3834 // If this is not the host, append its history with new edits.
3835 let push_to_client_history = project.read(cx).is_via_collab();
3836
3837 let on_type_formatting = project.update(cx, |project, cx| {
3838 project.on_type_format(
3839 buffer.clone(),
3840 buffer_position,
3841 input,
3842 push_to_lsp_host_history,
3843 cx,
3844 )
3845 });
3846 Some(cx.spawn_in(window, |editor, mut cx| async move {
3847 if let Some(transaction) = on_type_formatting.await? {
3848 if push_to_client_history {
3849 buffer
3850 .update(&mut cx, |buffer, _| {
3851 buffer.push_transaction(transaction, Instant::now());
3852 })
3853 .ok();
3854 }
3855 editor.update(&mut cx, |editor, cx| {
3856 editor.refresh_document_highlights(cx);
3857 })?;
3858 }
3859 Ok(())
3860 }))
3861 }
3862
3863 pub fn show_completions(
3864 &mut self,
3865 options: &ShowCompletions,
3866 window: &mut Window,
3867 cx: &mut Context<Self>,
3868 ) {
3869 if self.pending_rename.is_some() {
3870 return;
3871 }
3872
3873 let Some(provider) = self.completion_provider.as_ref() else {
3874 return;
3875 };
3876
3877 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3878 return;
3879 }
3880
3881 let position = self.selections.newest_anchor().head();
3882 if position.diff_base_anchor.is_some() {
3883 return;
3884 }
3885 let (buffer, buffer_position) =
3886 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3887 output
3888 } else {
3889 return;
3890 };
3891 let show_completion_documentation = buffer
3892 .read(cx)
3893 .snapshot()
3894 .settings_at(buffer_position, cx)
3895 .show_completion_documentation;
3896
3897 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3898
3899 let trigger_kind = match &options.trigger {
3900 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3901 CompletionTriggerKind::TRIGGER_CHARACTER
3902 }
3903 _ => CompletionTriggerKind::INVOKED,
3904 };
3905 let completion_context = CompletionContext {
3906 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3907 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3908 Some(String::from(trigger))
3909 } else {
3910 None
3911 }
3912 }),
3913 trigger_kind,
3914 };
3915 let completions =
3916 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3917 let sort_completions = provider.sort_completions();
3918
3919 let id = post_inc(&mut self.next_completion_id);
3920 let task = cx.spawn_in(window, |editor, mut cx| {
3921 async move {
3922 editor.update(&mut cx, |this, _| {
3923 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3924 })?;
3925 let completions = completions.await.log_err();
3926 let menu = if let Some(completions) = completions {
3927 let mut menu = CompletionsMenu::new(
3928 id,
3929 sort_completions,
3930 show_completion_documentation,
3931 position,
3932 buffer.clone(),
3933 completions.into(),
3934 );
3935
3936 menu.filter(query.as_deref(), cx.background_executor().clone())
3937 .await;
3938
3939 menu.visible().then_some(menu)
3940 } else {
3941 None
3942 };
3943
3944 editor.update_in(&mut cx, |editor, window, cx| {
3945 match editor.context_menu.borrow().as_ref() {
3946 None => {}
3947 Some(CodeContextMenu::Completions(prev_menu)) => {
3948 if prev_menu.id > id {
3949 return;
3950 }
3951 }
3952 _ => return,
3953 }
3954
3955 if editor.focus_handle.is_focused(window) && menu.is_some() {
3956 let mut menu = menu.unwrap();
3957 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3958
3959 *editor.context_menu.borrow_mut() =
3960 Some(CodeContextMenu::Completions(menu));
3961
3962 if editor.show_edit_predictions_in_menu() {
3963 editor.update_visible_inline_completion(window, cx);
3964 } else {
3965 editor.discard_inline_completion(false, cx);
3966 }
3967
3968 cx.notify();
3969 } else if editor.completion_tasks.len() <= 1 {
3970 // If there are no more completion tasks and the last menu was
3971 // empty, we should hide it.
3972 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3973 // If it was already hidden and we don't show inline
3974 // completions in the menu, we should also show the
3975 // inline-completion when available.
3976 if was_hidden && editor.show_edit_predictions_in_menu() {
3977 editor.update_visible_inline_completion(window, cx);
3978 }
3979 }
3980 })?;
3981
3982 Ok::<_, anyhow::Error>(())
3983 }
3984 .log_err()
3985 });
3986
3987 self.completion_tasks.push((id, task));
3988 }
3989
3990 pub fn confirm_completion(
3991 &mut self,
3992 action: &ConfirmCompletion,
3993 window: &mut Window,
3994 cx: &mut Context<Self>,
3995 ) -> Option<Task<Result<()>>> {
3996 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3997 }
3998
3999 pub fn compose_completion(
4000 &mut self,
4001 action: &ComposeCompletion,
4002 window: &mut Window,
4003 cx: &mut Context<Self>,
4004 ) -> Option<Task<Result<()>>> {
4005 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4006 }
4007
4008 fn do_completion(
4009 &mut self,
4010 item_ix: Option<usize>,
4011 intent: CompletionIntent,
4012 window: &mut Window,
4013 cx: &mut Context<Editor>,
4014 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4015 use language::ToOffset as _;
4016
4017 let completions_menu =
4018 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4019 menu
4020 } else {
4021 return None;
4022 };
4023
4024 let entries = completions_menu.entries.borrow();
4025 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4026 if self.show_edit_predictions_in_menu() {
4027 self.discard_inline_completion(true, cx);
4028 }
4029 let candidate_id = mat.candidate_id;
4030 drop(entries);
4031
4032 let buffer_handle = completions_menu.buffer;
4033 let completion = completions_menu
4034 .completions
4035 .borrow()
4036 .get(candidate_id)?
4037 .clone();
4038 cx.stop_propagation();
4039
4040 let snippet;
4041 let text;
4042
4043 if completion.is_snippet() {
4044 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4045 text = snippet.as_ref().unwrap().text.clone();
4046 } else {
4047 snippet = None;
4048 text = completion.new_text.clone();
4049 };
4050 let selections = self.selections.all::<usize>(cx);
4051 let buffer = buffer_handle.read(cx);
4052 let old_range = completion.old_range.to_offset(buffer);
4053 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4054
4055 let newest_selection = self.selections.newest_anchor();
4056 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4057 return None;
4058 }
4059
4060 let lookbehind = newest_selection
4061 .start
4062 .text_anchor
4063 .to_offset(buffer)
4064 .saturating_sub(old_range.start);
4065 let lookahead = old_range
4066 .end
4067 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4068 let mut common_prefix_len = old_text
4069 .bytes()
4070 .zip(text.bytes())
4071 .take_while(|(a, b)| a == b)
4072 .count();
4073
4074 let snapshot = self.buffer.read(cx).snapshot(cx);
4075 let mut range_to_replace: Option<Range<isize>> = None;
4076 let mut ranges = Vec::new();
4077 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4078 for selection in &selections {
4079 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4080 let start = selection.start.saturating_sub(lookbehind);
4081 let end = selection.end + lookahead;
4082 if selection.id == newest_selection.id {
4083 range_to_replace = Some(
4084 ((start + common_prefix_len) as isize - selection.start as isize)
4085 ..(end as isize - selection.start as isize),
4086 );
4087 }
4088 ranges.push(start + common_prefix_len..end);
4089 } else {
4090 common_prefix_len = 0;
4091 ranges.clear();
4092 ranges.extend(selections.iter().map(|s| {
4093 if s.id == newest_selection.id {
4094 range_to_replace = Some(
4095 old_range.start.to_offset_utf16(&snapshot).0 as isize
4096 - selection.start as isize
4097 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4098 - selection.start as isize,
4099 );
4100 old_range.clone()
4101 } else {
4102 s.start..s.end
4103 }
4104 }));
4105 break;
4106 }
4107 if !self.linked_edit_ranges.is_empty() {
4108 let start_anchor = snapshot.anchor_before(selection.head());
4109 let end_anchor = snapshot.anchor_after(selection.tail());
4110 if let Some(ranges) = self
4111 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4112 {
4113 for (buffer, edits) in ranges {
4114 linked_edits.entry(buffer.clone()).or_default().extend(
4115 edits
4116 .into_iter()
4117 .map(|range| (range, text[common_prefix_len..].to_owned())),
4118 );
4119 }
4120 }
4121 }
4122 }
4123 let text = &text[common_prefix_len..];
4124
4125 cx.emit(EditorEvent::InputHandled {
4126 utf16_range_to_replace: range_to_replace,
4127 text: text.into(),
4128 });
4129
4130 self.transact(window, cx, |this, window, cx| {
4131 if let Some(mut snippet) = snippet {
4132 snippet.text = text.to_string();
4133 for tabstop in snippet
4134 .tabstops
4135 .iter_mut()
4136 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4137 {
4138 tabstop.start -= common_prefix_len as isize;
4139 tabstop.end -= common_prefix_len as isize;
4140 }
4141
4142 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4143 } else {
4144 this.buffer.update(cx, |buffer, cx| {
4145 buffer.edit(
4146 ranges.iter().map(|range| (range.clone(), text)),
4147 this.autoindent_mode.clone(),
4148 cx,
4149 );
4150 });
4151 }
4152 for (buffer, edits) in linked_edits {
4153 buffer.update(cx, |buffer, cx| {
4154 let snapshot = buffer.snapshot();
4155 let edits = edits
4156 .into_iter()
4157 .map(|(range, text)| {
4158 use text::ToPoint as TP;
4159 let end_point = TP::to_point(&range.end, &snapshot);
4160 let start_point = TP::to_point(&range.start, &snapshot);
4161 (start_point..end_point, text)
4162 })
4163 .sorted_by_key(|(range, _)| range.start)
4164 .collect::<Vec<_>>();
4165 buffer.edit(edits, None, cx);
4166 })
4167 }
4168
4169 this.refresh_inline_completion(true, false, window, cx);
4170 });
4171
4172 let show_new_completions_on_confirm = completion
4173 .confirm
4174 .as_ref()
4175 .map_or(false, |confirm| confirm(intent, window, cx));
4176 if show_new_completions_on_confirm {
4177 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4178 }
4179
4180 let provider = self.completion_provider.as_ref()?;
4181 drop(completion);
4182 let apply_edits = provider.apply_additional_edits_for_completion(
4183 buffer_handle,
4184 completions_menu.completions.clone(),
4185 candidate_id,
4186 true,
4187 cx,
4188 );
4189
4190 let editor_settings = EditorSettings::get_global(cx);
4191 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4192 // After the code completion is finished, users often want to know what signatures are needed.
4193 // so we should automatically call signature_help
4194 self.show_signature_help(&ShowSignatureHelp, window, cx);
4195 }
4196
4197 Some(cx.foreground_executor().spawn(async move {
4198 apply_edits.await?;
4199 Ok(())
4200 }))
4201 }
4202
4203 pub fn toggle_code_actions(
4204 &mut self,
4205 action: &ToggleCodeActions,
4206 window: &mut Window,
4207 cx: &mut Context<Self>,
4208 ) {
4209 let mut context_menu = self.context_menu.borrow_mut();
4210 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4211 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4212 // Toggle if we're selecting the same one
4213 *context_menu = None;
4214 cx.notify();
4215 return;
4216 } else {
4217 // Otherwise, clear it and start a new one
4218 *context_menu = None;
4219 cx.notify();
4220 }
4221 }
4222 drop(context_menu);
4223 let snapshot = self.snapshot(window, cx);
4224 let deployed_from_indicator = action.deployed_from_indicator;
4225 let mut task = self.code_actions_task.take();
4226 let action = action.clone();
4227 cx.spawn_in(window, |editor, mut cx| async move {
4228 while let Some(prev_task) = task {
4229 prev_task.await.log_err();
4230 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4231 }
4232
4233 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4234 if editor.focus_handle.is_focused(window) {
4235 let multibuffer_point = action
4236 .deployed_from_indicator
4237 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4238 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4239 let (buffer, buffer_row) = snapshot
4240 .buffer_snapshot
4241 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4242 .and_then(|(buffer_snapshot, range)| {
4243 editor
4244 .buffer
4245 .read(cx)
4246 .buffer(buffer_snapshot.remote_id())
4247 .map(|buffer| (buffer, range.start.row))
4248 })?;
4249 let (_, code_actions) = editor
4250 .available_code_actions
4251 .clone()
4252 .and_then(|(location, code_actions)| {
4253 let snapshot = location.buffer.read(cx).snapshot();
4254 let point_range = location.range.to_point(&snapshot);
4255 let point_range = point_range.start.row..=point_range.end.row;
4256 if point_range.contains(&buffer_row) {
4257 Some((location, code_actions))
4258 } else {
4259 None
4260 }
4261 })
4262 .unzip();
4263 let buffer_id = buffer.read(cx).remote_id();
4264 let tasks = editor
4265 .tasks
4266 .get(&(buffer_id, buffer_row))
4267 .map(|t| Arc::new(t.to_owned()));
4268 if tasks.is_none() && code_actions.is_none() {
4269 return None;
4270 }
4271
4272 editor.completion_tasks.clear();
4273 editor.discard_inline_completion(false, cx);
4274 let task_context =
4275 tasks
4276 .as_ref()
4277 .zip(editor.project.clone())
4278 .map(|(tasks, project)| {
4279 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4280 });
4281
4282 Some(cx.spawn_in(window, |editor, mut cx| async move {
4283 let task_context = match task_context {
4284 Some(task_context) => task_context.await,
4285 None => None,
4286 };
4287 let resolved_tasks =
4288 tasks.zip(task_context).map(|(tasks, task_context)| {
4289 Rc::new(ResolvedTasks {
4290 templates: tasks.resolve(&task_context).collect(),
4291 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4292 multibuffer_point.row,
4293 tasks.column,
4294 )),
4295 })
4296 });
4297 let spawn_straight_away = resolved_tasks
4298 .as_ref()
4299 .map_or(false, |tasks| tasks.templates.len() == 1)
4300 && code_actions
4301 .as_ref()
4302 .map_or(true, |actions| actions.is_empty());
4303 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4304 *editor.context_menu.borrow_mut() =
4305 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4306 buffer,
4307 actions: CodeActionContents {
4308 tasks: resolved_tasks,
4309 actions: code_actions,
4310 },
4311 selected_item: Default::default(),
4312 scroll_handle: UniformListScrollHandle::default(),
4313 deployed_from_indicator,
4314 }));
4315 if spawn_straight_away {
4316 if let Some(task) = editor.confirm_code_action(
4317 &ConfirmCodeAction { item_ix: Some(0) },
4318 window,
4319 cx,
4320 ) {
4321 cx.notify();
4322 return task;
4323 }
4324 }
4325 cx.notify();
4326 Task::ready(Ok(()))
4327 }) {
4328 task.await
4329 } else {
4330 Ok(())
4331 }
4332 }))
4333 } else {
4334 Some(Task::ready(Ok(())))
4335 }
4336 })?;
4337 if let Some(task) = spawned_test_task {
4338 task.await?;
4339 }
4340
4341 Ok::<_, anyhow::Error>(())
4342 })
4343 .detach_and_log_err(cx);
4344 }
4345
4346 pub fn confirm_code_action(
4347 &mut self,
4348 action: &ConfirmCodeAction,
4349 window: &mut Window,
4350 cx: &mut Context<Self>,
4351 ) -> Option<Task<Result<()>>> {
4352 let actions_menu =
4353 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4354 menu
4355 } else {
4356 return None;
4357 };
4358 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4359 let action = actions_menu.actions.get(action_ix)?;
4360 let title = action.label();
4361 let buffer = actions_menu.buffer;
4362 let workspace = self.workspace()?;
4363
4364 match action {
4365 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4366 workspace.update(cx, |workspace, cx| {
4367 workspace::tasks::schedule_resolved_task(
4368 workspace,
4369 task_source_kind,
4370 resolved_task,
4371 false,
4372 cx,
4373 );
4374
4375 Some(Task::ready(Ok(())))
4376 })
4377 }
4378 CodeActionsItem::CodeAction {
4379 excerpt_id,
4380 action,
4381 provider,
4382 } => {
4383 let apply_code_action =
4384 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4385 let workspace = workspace.downgrade();
4386 Some(cx.spawn_in(window, |editor, cx| async move {
4387 let project_transaction = apply_code_action.await?;
4388 Self::open_project_transaction(
4389 &editor,
4390 workspace,
4391 project_transaction,
4392 title,
4393 cx,
4394 )
4395 .await
4396 }))
4397 }
4398 }
4399 }
4400
4401 pub async fn open_project_transaction(
4402 this: &WeakEntity<Editor>,
4403 workspace: WeakEntity<Workspace>,
4404 transaction: ProjectTransaction,
4405 title: String,
4406 mut cx: AsyncWindowContext,
4407 ) -> Result<()> {
4408 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4409 cx.update(|_, cx| {
4410 entries.sort_unstable_by_key(|(buffer, _)| {
4411 buffer.read(cx).file().map(|f| f.path().clone())
4412 });
4413 })?;
4414
4415 // If the project transaction's edits are all contained within this editor, then
4416 // avoid opening a new editor to display them.
4417
4418 if let Some((buffer, transaction)) = entries.first() {
4419 if entries.len() == 1 {
4420 let excerpt = this.update(&mut cx, |editor, cx| {
4421 editor
4422 .buffer()
4423 .read(cx)
4424 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4425 })?;
4426 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4427 if excerpted_buffer == *buffer {
4428 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4429 let excerpt_range = excerpt_range.to_offset(buffer);
4430 buffer
4431 .edited_ranges_for_transaction::<usize>(transaction)
4432 .all(|range| {
4433 excerpt_range.start <= range.start
4434 && excerpt_range.end >= range.end
4435 })
4436 })?;
4437
4438 if all_edits_within_excerpt {
4439 return Ok(());
4440 }
4441 }
4442 }
4443 }
4444 } else {
4445 return Ok(());
4446 }
4447
4448 let mut ranges_to_highlight = Vec::new();
4449 let excerpt_buffer = cx.new(|cx| {
4450 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4451 for (buffer_handle, transaction) in &entries {
4452 let buffer = buffer_handle.read(cx);
4453 ranges_to_highlight.extend(
4454 multibuffer.push_excerpts_with_context_lines(
4455 buffer_handle.clone(),
4456 buffer
4457 .edited_ranges_for_transaction::<usize>(transaction)
4458 .collect(),
4459 DEFAULT_MULTIBUFFER_CONTEXT,
4460 cx,
4461 ),
4462 );
4463 }
4464 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4465 multibuffer
4466 })?;
4467
4468 workspace.update_in(&mut cx, |workspace, window, cx| {
4469 let project = workspace.project().clone();
4470 let editor = cx
4471 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4472 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4473 editor.update(cx, |editor, cx| {
4474 editor.highlight_background::<Self>(
4475 &ranges_to_highlight,
4476 |theme| theme.editor_highlighted_line_background,
4477 cx,
4478 );
4479 });
4480 })?;
4481
4482 Ok(())
4483 }
4484
4485 pub fn clear_code_action_providers(&mut self) {
4486 self.code_action_providers.clear();
4487 self.available_code_actions.take();
4488 }
4489
4490 pub fn add_code_action_provider(
4491 &mut self,
4492 provider: Rc<dyn CodeActionProvider>,
4493 window: &mut Window,
4494 cx: &mut Context<Self>,
4495 ) {
4496 if self
4497 .code_action_providers
4498 .iter()
4499 .any(|existing_provider| existing_provider.id() == provider.id())
4500 {
4501 return;
4502 }
4503
4504 self.code_action_providers.push(provider);
4505 self.refresh_code_actions(window, cx);
4506 }
4507
4508 pub fn remove_code_action_provider(
4509 &mut self,
4510 id: Arc<str>,
4511 window: &mut Window,
4512 cx: &mut Context<Self>,
4513 ) {
4514 self.code_action_providers
4515 .retain(|provider| provider.id() != id);
4516 self.refresh_code_actions(window, cx);
4517 }
4518
4519 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4520 let buffer = self.buffer.read(cx);
4521 let newest_selection = self.selections.newest_anchor().clone();
4522 if newest_selection.head().diff_base_anchor.is_some() {
4523 return None;
4524 }
4525 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4526 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4527 if start_buffer != end_buffer {
4528 return None;
4529 }
4530
4531 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4532 cx.background_executor()
4533 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4534 .await;
4535
4536 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4537 let providers = this.code_action_providers.clone();
4538 let tasks = this
4539 .code_action_providers
4540 .iter()
4541 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4542 .collect::<Vec<_>>();
4543 (providers, tasks)
4544 })?;
4545
4546 let mut actions = Vec::new();
4547 for (provider, provider_actions) in
4548 providers.into_iter().zip(future::join_all(tasks).await)
4549 {
4550 if let Some(provider_actions) = provider_actions.log_err() {
4551 actions.extend(provider_actions.into_iter().map(|action| {
4552 AvailableCodeAction {
4553 excerpt_id: newest_selection.start.excerpt_id,
4554 action,
4555 provider: provider.clone(),
4556 }
4557 }));
4558 }
4559 }
4560
4561 this.update(&mut cx, |this, cx| {
4562 this.available_code_actions = if actions.is_empty() {
4563 None
4564 } else {
4565 Some((
4566 Location {
4567 buffer: start_buffer,
4568 range: start..end,
4569 },
4570 actions.into(),
4571 ))
4572 };
4573 cx.notify();
4574 })
4575 }));
4576 None
4577 }
4578
4579 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4580 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4581 self.show_git_blame_inline = false;
4582
4583 self.show_git_blame_inline_delay_task =
4584 Some(cx.spawn_in(window, |this, mut cx| async move {
4585 cx.background_executor().timer(delay).await;
4586
4587 this.update(&mut cx, |this, cx| {
4588 this.show_git_blame_inline = true;
4589 cx.notify();
4590 })
4591 .log_err();
4592 }));
4593 }
4594 }
4595
4596 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4597 if self.pending_rename.is_some() {
4598 return None;
4599 }
4600
4601 let provider = self.semantics_provider.clone()?;
4602 let buffer = self.buffer.read(cx);
4603 let newest_selection = self.selections.newest_anchor().clone();
4604 let cursor_position = newest_selection.head();
4605 let (cursor_buffer, cursor_buffer_position) =
4606 buffer.text_anchor_for_position(cursor_position, cx)?;
4607 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4608 if cursor_buffer != tail_buffer {
4609 return None;
4610 }
4611 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4612 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4613 cx.background_executor()
4614 .timer(Duration::from_millis(debounce))
4615 .await;
4616
4617 let highlights = if let Some(highlights) = cx
4618 .update(|cx| {
4619 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4620 })
4621 .ok()
4622 .flatten()
4623 {
4624 highlights.await.log_err()
4625 } else {
4626 None
4627 };
4628
4629 if let Some(highlights) = highlights {
4630 this.update(&mut cx, |this, cx| {
4631 if this.pending_rename.is_some() {
4632 return;
4633 }
4634
4635 let buffer_id = cursor_position.buffer_id;
4636 let buffer = this.buffer.read(cx);
4637 if !buffer
4638 .text_anchor_for_position(cursor_position, cx)
4639 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4640 {
4641 return;
4642 }
4643
4644 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4645 let mut write_ranges = Vec::new();
4646 let mut read_ranges = Vec::new();
4647 for highlight in highlights {
4648 for (excerpt_id, excerpt_range) in
4649 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4650 {
4651 let start = highlight
4652 .range
4653 .start
4654 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4655 let end = highlight
4656 .range
4657 .end
4658 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4659 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4660 continue;
4661 }
4662
4663 let range = Anchor {
4664 buffer_id,
4665 excerpt_id,
4666 text_anchor: start,
4667 diff_base_anchor: None,
4668 }..Anchor {
4669 buffer_id,
4670 excerpt_id,
4671 text_anchor: end,
4672 diff_base_anchor: None,
4673 };
4674 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4675 write_ranges.push(range);
4676 } else {
4677 read_ranges.push(range);
4678 }
4679 }
4680 }
4681
4682 this.highlight_background::<DocumentHighlightRead>(
4683 &read_ranges,
4684 |theme| theme.editor_document_highlight_read_background,
4685 cx,
4686 );
4687 this.highlight_background::<DocumentHighlightWrite>(
4688 &write_ranges,
4689 |theme| theme.editor_document_highlight_write_background,
4690 cx,
4691 );
4692 cx.notify();
4693 })
4694 .log_err();
4695 }
4696 }));
4697 None
4698 }
4699
4700 pub fn refresh_selected_text_highlights(
4701 &mut self,
4702 window: &mut Window,
4703 cx: &mut Context<Editor>,
4704 ) {
4705 self.selection_highlight_task.take();
4706 if !EditorSettings::get_global(cx).selection_highlight {
4707 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4708 return;
4709 }
4710 if self.selections.count() != 1 || self.selections.line_mode {
4711 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4712 return;
4713 }
4714 let selection = self.selections.newest::<Point>(cx);
4715 if selection.is_empty() || selection.start.row != selection.end.row {
4716 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4717 return;
4718 }
4719 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4720 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4721 cx.background_executor()
4722 .timer(Duration::from_millis(debounce))
4723 .await;
4724 let Some(Some(matches_task)) = editor
4725 .update_in(&mut cx, |editor, _, cx| {
4726 if editor.selections.count() != 1 || editor.selections.line_mode {
4727 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4728 return None;
4729 }
4730 let selection = editor.selections.newest::<Point>(cx);
4731 if selection.is_empty() || selection.start.row != selection.end.row {
4732 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4733 return None;
4734 }
4735 let buffer = editor.buffer().read(cx).snapshot(cx);
4736 let query = buffer.text_for_range(selection.range()).collect::<String>();
4737 if query.trim().is_empty() {
4738 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4739 return None;
4740 }
4741 Some(cx.background_spawn(async move {
4742 let mut ranges = Vec::new();
4743 let selection_anchors = selection.range().to_anchors(&buffer);
4744 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4745 for (search_buffer, search_range, excerpt_id) in
4746 buffer.range_to_buffer_ranges(range)
4747 {
4748 ranges.extend(
4749 project::search::SearchQuery::text(
4750 query.clone(),
4751 false,
4752 false,
4753 false,
4754 Default::default(),
4755 Default::default(),
4756 None,
4757 )
4758 .unwrap()
4759 .search(search_buffer, Some(search_range.clone()))
4760 .await
4761 .into_iter()
4762 .filter_map(
4763 |match_range| {
4764 let start = search_buffer.anchor_after(
4765 search_range.start + match_range.start,
4766 );
4767 let end = search_buffer.anchor_before(
4768 search_range.start + match_range.end,
4769 );
4770 let range = Anchor::range_in_buffer(
4771 excerpt_id,
4772 search_buffer.remote_id(),
4773 start..end,
4774 );
4775 (range != selection_anchors).then_some(range)
4776 },
4777 ),
4778 );
4779 }
4780 }
4781 ranges
4782 }))
4783 })
4784 .log_err()
4785 else {
4786 return;
4787 };
4788 let matches = matches_task.await;
4789 editor
4790 .update_in(&mut cx, |editor, _, cx| {
4791 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4792 if !matches.is_empty() {
4793 editor.highlight_background::<SelectedTextHighlight>(
4794 &matches,
4795 |theme| theme.editor_document_highlight_bracket_background,
4796 cx,
4797 )
4798 }
4799 })
4800 .log_err();
4801 }));
4802 }
4803
4804 pub fn refresh_inline_completion(
4805 &mut self,
4806 debounce: bool,
4807 user_requested: bool,
4808 window: &mut Window,
4809 cx: &mut Context<Self>,
4810 ) -> Option<()> {
4811 let provider = self.edit_prediction_provider()?;
4812 let cursor = self.selections.newest_anchor().head();
4813 let (buffer, cursor_buffer_position) =
4814 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4815
4816 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4817 self.discard_inline_completion(false, cx);
4818 return None;
4819 }
4820
4821 if !user_requested
4822 && (!self.should_show_edit_predictions()
4823 || !self.is_focused(window)
4824 || buffer.read(cx).is_empty())
4825 {
4826 self.discard_inline_completion(false, cx);
4827 return None;
4828 }
4829
4830 self.update_visible_inline_completion(window, cx);
4831 provider.refresh(
4832 self.project.clone(),
4833 buffer,
4834 cursor_buffer_position,
4835 debounce,
4836 cx,
4837 );
4838 Some(())
4839 }
4840
4841 fn show_edit_predictions_in_menu(&self) -> bool {
4842 match self.edit_prediction_settings {
4843 EditPredictionSettings::Disabled => false,
4844 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4845 }
4846 }
4847
4848 pub fn edit_predictions_enabled(&self) -> bool {
4849 match self.edit_prediction_settings {
4850 EditPredictionSettings::Disabled => false,
4851 EditPredictionSettings::Enabled { .. } => true,
4852 }
4853 }
4854
4855 fn edit_prediction_requires_modifier(&self) -> bool {
4856 match self.edit_prediction_settings {
4857 EditPredictionSettings::Disabled => false,
4858 EditPredictionSettings::Enabled {
4859 preview_requires_modifier,
4860 ..
4861 } => preview_requires_modifier,
4862 }
4863 }
4864
4865 fn edit_prediction_settings_at_position(
4866 &self,
4867 buffer: &Entity<Buffer>,
4868 buffer_position: language::Anchor,
4869 cx: &App,
4870 ) -> EditPredictionSettings {
4871 if self.mode != EditorMode::Full
4872 || !self.show_inline_completions_override.unwrap_or(true)
4873 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4874 {
4875 return EditPredictionSettings::Disabled;
4876 }
4877
4878 let buffer = buffer.read(cx);
4879
4880 let file = buffer.file();
4881
4882 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4883 return EditPredictionSettings::Disabled;
4884 };
4885
4886 let by_provider = matches!(
4887 self.menu_inline_completions_policy,
4888 MenuInlineCompletionsPolicy::ByProvider
4889 );
4890
4891 let show_in_menu = by_provider
4892 && self
4893 .edit_prediction_provider
4894 .as_ref()
4895 .map_or(false, |provider| {
4896 provider.provider.show_completions_in_menu()
4897 });
4898
4899 let preview_requires_modifier =
4900 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4901
4902 EditPredictionSettings::Enabled {
4903 show_in_menu,
4904 preview_requires_modifier,
4905 }
4906 }
4907
4908 fn should_show_edit_predictions(&self) -> bool {
4909 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4910 }
4911
4912 pub fn edit_prediction_preview_is_active(&self) -> bool {
4913 matches!(
4914 self.edit_prediction_preview,
4915 EditPredictionPreview::Active { .. }
4916 )
4917 }
4918
4919 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4920 let cursor = self.selections.newest_anchor().head();
4921 if let Some((buffer, cursor_position)) =
4922 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4923 {
4924 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4925 } else {
4926 false
4927 }
4928 }
4929
4930 fn inline_completions_enabled_in_buffer(
4931 &self,
4932 buffer: &Entity<Buffer>,
4933 buffer_position: language::Anchor,
4934 cx: &App,
4935 ) -> bool {
4936 maybe!({
4937 let provider = self.edit_prediction_provider()?;
4938 if !provider.is_enabled(&buffer, buffer_position, cx) {
4939 return Some(false);
4940 }
4941 let buffer = buffer.read(cx);
4942 let Some(file) = buffer.file() else {
4943 return Some(true);
4944 };
4945 let settings = all_language_settings(Some(file), cx);
4946 Some(settings.inline_completions_enabled_for_path(file.path()))
4947 })
4948 .unwrap_or(false)
4949 }
4950
4951 fn cycle_inline_completion(
4952 &mut self,
4953 direction: Direction,
4954 window: &mut Window,
4955 cx: &mut Context<Self>,
4956 ) -> Option<()> {
4957 let provider = self.edit_prediction_provider()?;
4958 let cursor = self.selections.newest_anchor().head();
4959 let (buffer, cursor_buffer_position) =
4960 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4961 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4962 return None;
4963 }
4964
4965 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4966 self.update_visible_inline_completion(window, cx);
4967
4968 Some(())
4969 }
4970
4971 pub fn show_inline_completion(
4972 &mut self,
4973 _: &ShowEditPrediction,
4974 window: &mut Window,
4975 cx: &mut Context<Self>,
4976 ) {
4977 if !self.has_active_inline_completion() {
4978 self.refresh_inline_completion(false, true, window, cx);
4979 return;
4980 }
4981
4982 self.update_visible_inline_completion(window, cx);
4983 }
4984
4985 pub fn display_cursor_names(
4986 &mut self,
4987 _: &DisplayCursorNames,
4988 window: &mut Window,
4989 cx: &mut Context<Self>,
4990 ) {
4991 self.show_cursor_names(window, cx);
4992 }
4993
4994 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4995 self.show_cursor_names = true;
4996 cx.notify();
4997 cx.spawn_in(window, |this, mut cx| async move {
4998 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4999 this.update(&mut cx, |this, cx| {
5000 this.show_cursor_names = false;
5001 cx.notify()
5002 })
5003 .ok()
5004 })
5005 .detach();
5006 }
5007
5008 pub fn next_edit_prediction(
5009 &mut self,
5010 _: &NextEditPrediction,
5011 window: &mut Window,
5012 cx: &mut Context<Self>,
5013 ) {
5014 if self.has_active_inline_completion() {
5015 self.cycle_inline_completion(Direction::Next, window, cx);
5016 } else {
5017 let is_copilot_disabled = self
5018 .refresh_inline_completion(false, true, window, cx)
5019 .is_none();
5020 if is_copilot_disabled {
5021 cx.propagate();
5022 }
5023 }
5024 }
5025
5026 pub fn previous_edit_prediction(
5027 &mut self,
5028 _: &PreviousEditPrediction,
5029 window: &mut Window,
5030 cx: &mut Context<Self>,
5031 ) {
5032 if self.has_active_inline_completion() {
5033 self.cycle_inline_completion(Direction::Prev, window, cx);
5034 } else {
5035 let is_copilot_disabled = self
5036 .refresh_inline_completion(false, true, window, cx)
5037 .is_none();
5038 if is_copilot_disabled {
5039 cx.propagate();
5040 }
5041 }
5042 }
5043
5044 pub fn accept_edit_prediction(
5045 &mut self,
5046 _: &AcceptEditPrediction,
5047 window: &mut Window,
5048 cx: &mut Context<Self>,
5049 ) {
5050 if self.show_edit_predictions_in_menu() {
5051 self.hide_context_menu(window, cx);
5052 }
5053
5054 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5055 return;
5056 };
5057
5058 self.report_inline_completion_event(
5059 active_inline_completion.completion_id.clone(),
5060 true,
5061 cx,
5062 );
5063
5064 match &active_inline_completion.completion {
5065 InlineCompletion::Move { target, .. } => {
5066 let target = *target;
5067
5068 if let Some(position_map) = &self.last_position_map {
5069 if position_map
5070 .visible_row_range
5071 .contains(&target.to_display_point(&position_map.snapshot).row())
5072 || !self.edit_prediction_requires_modifier()
5073 {
5074 self.unfold_ranges(&[target..target], true, false, cx);
5075 // Note that this is also done in vim's handler of the Tab action.
5076 self.change_selections(
5077 Some(Autoscroll::newest()),
5078 window,
5079 cx,
5080 |selections| {
5081 selections.select_anchor_ranges([target..target]);
5082 },
5083 );
5084 self.clear_row_highlights::<EditPredictionPreview>();
5085
5086 self.edit_prediction_preview = EditPredictionPreview::Active {
5087 previous_scroll_position: None,
5088 };
5089 } else {
5090 self.edit_prediction_preview = EditPredictionPreview::Active {
5091 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5092 };
5093 self.highlight_rows::<EditPredictionPreview>(
5094 target..target,
5095 cx.theme().colors().editor_highlighted_line_background,
5096 true,
5097 cx,
5098 );
5099 self.request_autoscroll(Autoscroll::fit(), cx);
5100 }
5101 }
5102 }
5103 InlineCompletion::Edit { edits, .. } => {
5104 if let Some(provider) = self.edit_prediction_provider() {
5105 provider.accept(cx);
5106 }
5107
5108 let snapshot = self.buffer.read(cx).snapshot(cx);
5109 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5110
5111 self.buffer.update(cx, |buffer, cx| {
5112 buffer.edit(edits.iter().cloned(), None, cx)
5113 });
5114
5115 self.change_selections(None, window, cx, |s| {
5116 s.select_anchor_ranges([last_edit_end..last_edit_end])
5117 });
5118
5119 self.update_visible_inline_completion(window, cx);
5120 if self.active_inline_completion.is_none() {
5121 self.refresh_inline_completion(true, true, window, cx);
5122 }
5123
5124 cx.notify();
5125 }
5126 }
5127
5128 self.edit_prediction_requires_modifier_in_leading_space = false;
5129 }
5130
5131 pub fn accept_partial_inline_completion(
5132 &mut self,
5133 _: &AcceptPartialEditPrediction,
5134 window: &mut Window,
5135 cx: &mut Context<Self>,
5136 ) {
5137 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5138 return;
5139 };
5140 if self.selections.count() != 1 {
5141 return;
5142 }
5143
5144 self.report_inline_completion_event(
5145 active_inline_completion.completion_id.clone(),
5146 true,
5147 cx,
5148 );
5149
5150 match &active_inline_completion.completion {
5151 InlineCompletion::Move { target, .. } => {
5152 let target = *target;
5153 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5154 selections.select_anchor_ranges([target..target]);
5155 });
5156 }
5157 InlineCompletion::Edit { edits, .. } => {
5158 // Find an insertion that starts at the cursor position.
5159 let snapshot = self.buffer.read(cx).snapshot(cx);
5160 let cursor_offset = self.selections.newest::<usize>(cx).head();
5161 let insertion = edits.iter().find_map(|(range, text)| {
5162 let range = range.to_offset(&snapshot);
5163 if range.is_empty() && range.start == cursor_offset {
5164 Some(text)
5165 } else {
5166 None
5167 }
5168 });
5169
5170 if let Some(text) = insertion {
5171 let mut partial_completion = text
5172 .chars()
5173 .by_ref()
5174 .take_while(|c| c.is_alphabetic())
5175 .collect::<String>();
5176 if partial_completion.is_empty() {
5177 partial_completion = text
5178 .chars()
5179 .by_ref()
5180 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5181 .collect::<String>();
5182 }
5183
5184 cx.emit(EditorEvent::InputHandled {
5185 utf16_range_to_replace: None,
5186 text: partial_completion.clone().into(),
5187 });
5188
5189 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5190
5191 self.refresh_inline_completion(true, true, window, cx);
5192 cx.notify();
5193 } else {
5194 self.accept_edit_prediction(&Default::default(), window, cx);
5195 }
5196 }
5197 }
5198 }
5199
5200 fn discard_inline_completion(
5201 &mut self,
5202 should_report_inline_completion_event: bool,
5203 cx: &mut Context<Self>,
5204 ) -> bool {
5205 if should_report_inline_completion_event {
5206 let completion_id = self
5207 .active_inline_completion
5208 .as_ref()
5209 .and_then(|active_completion| active_completion.completion_id.clone());
5210
5211 self.report_inline_completion_event(completion_id, false, cx);
5212 }
5213
5214 if let Some(provider) = self.edit_prediction_provider() {
5215 provider.discard(cx);
5216 }
5217
5218 self.take_active_inline_completion(cx)
5219 }
5220
5221 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5222 let Some(provider) = self.edit_prediction_provider() else {
5223 return;
5224 };
5225
5226 let Some((_, buffer, _)) = self
5227 .buffer
5228 .read(cx)
5229 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5230 else {
5231 return;
5232 };
5233
5234 let extension = buffer
5235 .read(cx)
5236 .file()
5237 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5238
5239 let event_type = match accepted {
5240 true => "Edit Prediction Accepted",
5241 false => "Edit Prediction Discarded",
5242 };
5243 telemetry::event!(
5244 event_type,
5245 provider = provider.name(),
5246 prediction_id = id,
5247 suggestion_accepted = accepted,
5248 file_extension = extension,
5249 );
5250 }
5251
5252 pub fn has_active_inline_completion(&self) -> bool {
5253 self.active_inline_completion.is_some()
5254 }
5255
5256 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5257 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5258 return false;
5259 };
5260
5261 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5262 self.clear_highlights::<InlineCompletionHighlight>(cx);
5263 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5264 true
5265 }
5266
5267 /// Returns true when we're displaying the edit prediction popover below the cursor
5268 /// like we are not previewing and the LSP autocomplete menu is visible
5269 /// or we are in `when_holding_modifier` mode.
5270 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5271 if self.edit_prediction_preview_is_active()
5272 || !self.show_edit_predictions_in_menu()
5273 || !self.edit_predictions_enabled()
5274 {
5275 return false;
5276 }
5277
5278 if self.has_visible_completions_menu() {
5279 return true;
5280 }
5281
5282 has_completion && self.edit_prediction_requires_modifier()
5283 }
5284
5285 fn handle_modifiers_changed(
5286 &mut self,
5287 modifiers: Modifiers,
5288 position_map: &PositionMap,
5289 window: &mut Window,
5290 cx: &mut Context<Self>,
5291 ) {
5292 if self.show_edit_predictions_in_menu() {
5293 self.update_edit_prediction_preview(&modifiers, window, cx);
5294 }
5295
5296 self.update_selection_mode(&modifiers, position_map, window, cx);
5297
5298 let mouse_position = window.mouse_position();
5299 if !position_map.text_hitbox.is_hovered(window) {
5300 return;
5301 }
5302
5303 self.update_hovered_link(
5304 position_map.point_for_position(mouse_position),
5305 &position_map.snapshot,
5306 modifiers,
5307 window,
5308 cx,
5309 )
5310 }
5311
5312 fn update_selection_mode(
5313 &mut self,
5314 modifiers: &Modifiers,
5315 position_map: &PositionMap,
5316 window: &mut Window,
5317 cx: &mut Context<Self>,
5318 ) {
5319 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5320 return;
5321 }
5322
5323 let mouse_position = window.mouse_position();
5324 let point_for_position = position_map.point_for_position(mouse_position);
5325 let position = point_for_position.previous_valid;
5326
5327 self.select(
5328 SelectPhase::BeginColumnar {
5329 position,
5330 reset: false,
5331 goal_column: point_for_position.exact_unclipped.column(),
5332 },
5333 window,
5334 cx,
5335 );
5336 }
5337
5338 fn update_edit_prediction_preview(
5339 &mut self,
5340 modifiers: &Modifiers,
5341 window: &mut Window,
5342 cx: &mut Context<Self>,
5343 ) {
5344 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5345 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5346 return;
5347 };
5348
5349 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5350 if matches!(
5351 self.edit_prediction_preview,
5352 EditPredictionPreview::Inactive
5353 ) {
5354 self.edit_prediction_preview = EditPredictionPreview::Active {
5355 previous_scroll_position: None,
5356 };
5357
5358 self.update_visible_inline_completion(window, cx);
5359 cx.notify();
5360 }
5361 } else if let EditPredictionPreview::Active {
5362 previous_scroll_position,
5363 } = self.edit_prediction_preview
5364 {
5365 if let (Some(previous_scroll_position), Some(position_map)) =
5366 (previous_scroll_position, self.last_position_map.as_ref())
5367 {
5368 self.set_scroll_position(
5369 previous_scroll_position
5370 .scroll_position(&position_map.snapshot.display_snapshot),
5371 window,
5372 cx,
5373 );
5374 }
5375
5376 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5377 self.clear_row_highlights::<EditPredictionPreview>();
5378 self.update_visible_inline_completion(window, cx);
5379 cx.notify();
5380 }
5381 }
5382
5383 fn update_visible_inline_completion(
5384 &mut self,
5385 _window: &mut Window,
5386 cx: &mut Context<Self>,
5387 ) -> Option<()> {
5388 let selection = self.selections.newest_anchor();
5389 let cursor = selection.head();
5390 let multibuffer = self.buffer.read(cx).snapshot(cx);
5391 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5392 let excerpt_id = cursor.excerpt_id;
5393
5394 let show_in_menu = self.show_edit_predictions_in_menu();
5395 let completions_menu_has_precedence = !show_in_menu
5396 && (self.context_menu.borrow().is_some()
5397 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5398
5399 if completions_menu_has_precedence
5400 || !offset_selection.is_empty()
5401 || self
5402 .active_inline_completion
5403 .as_ref()
5404 .map_or(false, |completion| {
5405 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5406 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5407 !invalidation_range.contains(&offset_selection.head())
5408 })
5409 {
5410 self.discard_inline_completion(false, cx);
5411 return None;
5412 }
5413
5414 self.take_active_inline_completion(cx);
5415 let Some(provider) = self.edit_prediction_provider() else {
5416 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5417 return None;
5418 };
5419
5420 let (buffer, cursor_buffer_position) =
5421 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5422
5423 self.edit_prediction_settings =
5424 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5425
5426 self.edit_prediction_cursor_on_leading_whitespace =
5427 multibuffer.is_line_whitespace_upto(cursor);
5428
5429 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5430 let edits = inline_completion
5431 .edits
5432 .into_iter()
5433 .flat_map(|(range, new_text)| {
5434 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5435 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5436 Some((start..end, new_text))
5437 })
5438 .collect::<Vec<_>>();
5439 if edits.is_empty() {
5440 return None;
5441 }
5442
5443 let first_edit_start = edits.first().unwrap().0.start;
5444 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5445 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5446
5447 let last_edit_end = edits.last().unwrap().0.end;
5448 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5449 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5450
5451 let cursor_row = cursor.to_point(&multibuffer).row;
5452
5453 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5454
5455 let mut inlay_ids = Vec::new();
5456 let invalidation_row_range;
5457 let move_invalidation_row_range = if cursor_row < edit_start_row {
5458 Some(cursor_row..edit_end_row)
5459 } else if cursor_row > edit_end_row {
5460 Some(edit_start_row..cursor_row)
5461 } else {
5462 None
5463 };
5464 let is_move =
5465 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5466 let completion = if is_move {
5467 invalidation_row_range =
5468 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5469 let target = first_edit_start;
5470 InlineCompletion::Move { target, snapshot }
5471 } else {
5472 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5473 && !self.inline_completions_hidden_for_vim_mode;
5474
5475 if show_completions_in_buffer {
5476 if edits
5477 .iter()
5478 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5479 {
5480 let mut inlays = Vec::new();
5481 for (range, new_text) in &edits {
5482 let inlay = Inlay::inline_completion(
5483 post_inc(&mut self.next_inlay_id),
5484 range.start,
5485 new_text.as_str(),
5486 );
5487 inlay_ids.push(inlay.id);
5488 inlays.push(inlay);
5489 }
5490
5491 self.splice_inlays(&[], inlays, cx);
5492 } else {
5493 let background_color = cx.theme().status().deleted_background;
5494 self.highlight_text::<InlineCompletionHighlight>(
5495 edits.iter().map(|(range, _)| range.clone()).collect(),
5496 HighlightStyle {
5497 background_color: Some(background_color),
5498 ..Default::default()
5499 },
5500 cx,
5501 );
5502 }
5503 }
5504
5505 invalidation_row_range = edit_start_row..edit_end_row;
5506
5507 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5508 if provider.show_tab_accept_marker() {
5509 EditDisplayMode::TabAccept
5510 } else {
5511 EditDisplayMode::Inline
5512 }
5513 } else {
5514 EditDisplayMode::DiffPopover
5515 };
5516
5517 InlineCompletion::Edit {
5518 edits,
5519 edit_preview: inline_completion.edit_preview,
5520 display_mode,
5521 snapshot,
5522 }
5523 };
5524
5525 let invalidation_range = multibuffer
5526 .anchor_before(Point::new(invalidation_row_range.start, 0))
5527 ..multibuffer.anchor_after(Point::new(
5528 invalidation_row_range.end,
5529 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5530 ));
5531
5532 self.stale_inline_completion_in_menu = None;
5533 self.active_inline_completion = Some(InlineCompletionState {
5534 inlay_ids,
5535 completion,
5536 completion_id: inline_completion.id,
5537 invalidation_range,
5538 });
5539
5540 cx.notify();
5541
5542 Some(())
5543 }
5544
5545 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5546 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5547 }
5548
5549 fn render_code_actions_indicator(
5550 &self,
5551 _style: &EditorStyle,
5552 row: DisplayRow,
5553 is_active: bool,
5554 cx: &mut Context<Self>,
5555 ) -> Option<IconButton> {
5556 if self.available_code_actions.is_some() {
5557 Some(
5558 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5559 .shape(ui::IconButtonShape::Square)
5560 .icon_size(IconSize::XSmall)
5561 .icon_color(Color::Muted)
5562 .toggle_state(is_active)
5563 .tooltip({
5564 let focus_handle = self.focus_handle.clone();
5565 move |window, cx| {
5566 Tooltip::for_action_in(
5567 "Toggle Code Actions",
5568 &ToggleCodeActions {
5569 deployed_from_indicator: None,
5570 },
5571 &focus_handle,
5572 window,
5573 cx,
5574 )
5575 }
5576 })
5577 .on_click(cx.listener(move |editor, _e, window, cx| {
5578 window.focus(&editor.focus_handle(cx));
5579 editor.toggle_code_actions(
5580 &ToggleCodeActions {
5581 deployed_from_indicator: Some(row),
5582 },
5583 window,
5584 cx,
5585 );
5586 })),
5587 )
5588 } else {
5589 None
5590 }
5591 }
5592
5593 fn clear_tasks(&mut self) {
5594 self.tasks.clear()
5595 }
5596
5597 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5598 if self.tasks.insert(key, value).is_some() {
5599 // This case should hopefully be rare, but just in case...
5600 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5601 }
5602 }
5603
5604 fn build_tasks_context(
5605 project: &Entity<Project>,
5606 buffer: &Entity<Buffer>,
5607 buffer_row: u32,
5608 tasks: &Arc<RunnableTasks>,
5609 cx: &mut Context<Self>,
5610 ) -> Task<Option<task::TaskContext>> {
5611 let position = Point::new(buffer_row, tasks.column);
5612 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5613 let location = Location {
5614 buffer: buffer.clone(),
5615 range: range_start..range_start,
5616 };
5617 // Fill in the environmental variables from the tree-sitter captures
5618 let mut captured_task_variables = TaskVariables::default();
5619 for (capture_name, value) in tasks.extra_variables.clone() {
5620 captured_task_variables.insert(
5621 task::VariableName::Custom(capture_name.into()),
5622 value.clone(),
5623 );
5624 }
5625 project.update(cx, |project, cx| {
5626 project.task_store().update(cx, |task_store, cx| {
5627 task_store.task_context_for_location(captured_task_variables, location, cx)
5628 })
5629 })
5630 }
5631
5632 pub fn spawn_nearest_task(
5633 &mut self,
5634 action: &SpawnNearestTask,
5635 window: &mut Window,
5636 cx: &mut Context<Self>,
5637 ) {
5638 let Some((workspace, _)) = self.workspace.clone() else {
5639 return;
5640 };
5641 let Some(project) = self.project.clone() else {
5642 return;
5643 };
5644
5645 // Try to find a closest, enclosing node using tree-sitter that has a
5646 // task
5647 let Some((buffer, buffer_row, tasks)) = self
5648 .find_enclosing_node_task(cx)
5649 // Or find the task that's closest in row-distance.
5650 .or_else(|| self.find_closest_task(cx))
5651 else {
5652 return;
5653 };
5654
5655 let reveal_strategy = action.reveal;
5656 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5657 cx.spawn_in(window, |_, mut cx| async move {
5658 let context = task_context.await?;
5659 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5660
5661 let resolved = resolved_task.resolved.as_mut()?;
5662 resolved.reveal = reveal_strategy;
5663
5664 workspace
5665 .update(&mut cx, |workspace, cx| {
5666 workspace::tasks::schedule_resolved_task(
5667 workspace,
5668 task_source_kind,
5669 resolved_task,
5670 false,
5671 cx,
5672 );
5673 })
5674 .ok()
5675 })
5676 .detach();
5677 }
5678
5679 fn find_closest_task(
5680 &mut self,
5681 cx: &mut Context<Self>,
5682 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5683 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5684
5685 let ((buffer_id, row), tasks) = self
5686 .tasks
5687 .iter()
5688 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5689
5690 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5691 let tasks = Arc::new(tasks.to_owned());
5692 Some((buffer, *row, tasks))
5693 }
5694
5695 fn find_enclosing_node_task(
5696 &mut self,
5697 cx: &mut Context<Self>,
5698 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5699 let snapshot = self.buffer.read(cx).snapshot(cx);
5700 let offset = self.selections.newest::<usize>(cx).head();
5701 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5702 let buffer_id = excerpt.buffer().remote_id();
5703
5704 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5705 let mut cursor = layer.node().walk();
5706
5707 while cursor.goto_first_child_for_byte(offset).is_some() {
5708 if cursor.node().end_byte() == offset {
5709 cursor.goto_next_sibling();
5710 }
5711 }
5712
5713 // Ascend to the smallest ancestor that contains the range and has a task.
5714 loop {
5715 let node = cursor.node();
5716 let node_range = node.byte_range();
5717 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5718
5719 // Check if this node contains our offset
5720 if node_range.start <= offset && node_range.end >= offset {
5721 // If it contains offset, check for task
5722 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5723 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5724 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5725 }
5726 }
5727
5728 if !cursor.goto_parent() {
5729 break;
5730 }
5731 }
5732 None
5733 }
5734
5735 fn render_run_indicator(
5736 &self,
5737 _style: &EditorStyle,
5738 is_active: bool,
5739 row: DisplayRow,
5740 cx: &mut Context<Self>,
5741 ) -> IconButton {
5742 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5743 .shape(ui::IconButtonShape::Square)
5744 .icon_size(IconSize::XSmall)
5745 .icon_color(Color::Muted)
5746 .toggle_state(is_active)
5747 .on_click(cx.listener(move |editor, _e, window, cx| {
5748 window.focus(&editor.focus_handle(cx));
5749 editor.toggle_code_actions(
5750 &ToggleCodeActions {
5751 deployed_from_indicator: Some(row),
5752 },
5753 window,
5754 cx,
5755 );
5756 }))
5757 }
5758
5759 pub fn context_menu_visible(&self) -> bool {
5760 !self.edit_prediction_preview_is_active()
5761 && self
5762 .context_menu
5763 .borrow()
5764 .as_ref()
5765 .map_or(false, |menu| menu.visible())
5766 }
5767
5768 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5769 self.context_menu
5770 .borrow()
5771 .as_ref()
5772 .map(|menu| menu.origin())
5773 }
5774
5775 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5776 px(30.)
5777 }
5778
5779 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5780 if self.read_only(cx) {
5781 cx.theme().players().read_only()
5782 } else {
5783 self.style.as_ref().unwrap().local_player
5784 }
5785 }
5786
5787 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5788 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5789 let accept_keystroke = accept_binding.keystroke()?;
5790
5791 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5792
5793 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5794 Color::Accent
5795 } else {
5796 Color::Muted
5797 };
5798
5799 h_flex()
5800 .px_0p5()
5801 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5802 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5803 .text_size(TextSize::XSmall.rems(cx))
5804 .child(h_flex().children(ui::render_modifiers(
5805 &accept_keystroke.modifiers,
5806 PlatformStyle::platform(),
5807 Some(modifiers_color),
5808 Some(IconSize::XSmall.rems().into()),
5809 true,
5810 )))
5811 .when(is_platform_style_mac, |parent| {
5812 parent.child(accept_keystroke.key.clone())
5813 })
5814 .when(!is_platform_style_mac, |parent| {
5815 parent.child(
5816 Key::new(
5817 util::capitalize(&accept_keystroke.key),
5818 Some(Color::Default),
5819 )
5820 .size(Some(IconSize::XSmall.rems().into())),
5821 )
5822 })
5823 .into()
5824 }
5825
5826 fn render_edit_prediction_line_popover(
5827 &self,
5828 label: impl Into<SharedString>,
5829 icon: Option<IconName>,
5830 window: &mut Window,
5831 cx: &App,
5832 ) -> Option<Div> {
5833 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5834
5835 let result = h_flex()
5836 .py_0p5()
5837 .pl_1()
5838 .pr(padding_right)
5839 .gap_1()
5840 .rounded(px(6.))
5841 .border_1()
5842 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5843 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5844 .shadow_sm()
5845 .children(self.render_edit_prediction_accept_keybind(window, cx))
5846 .child(Label::new(label).size(LabelSize::Small))
5847 .when_some(icon, |element, icon| {
5848 element.child(
5849 div()
5850 .mt(px(1.5))
5851 .child(Icon::new(icon).size(IconSize::Small)),
5852 )
5853 });
5854
5855 Some(result)
5856 }
5857
5858 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5859 let accent_color = cx.theme().colors().text_accent;
5860 let editor_bg_color = cx.theme().colors().editor_background;
5861 editor_bg_color.blend(accent_color.opacity(0.1))
5862 }
5863
5864 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5865 let accent_color = cx.theme().colors().text_accent;
5866 let editor_bg_color = cx.theme().colors().editor_background;
5867 editor_bg_color.blend(accent_color.opacity(0.6))
5868 }
5869
5870 #[allow(clippy::too_many_arguments)]
5871 fn render_edit_prediction_cursor_popover(
5872 &self,
5873 min_width: Pixels,
5874 max_width: Pixels,
5875 cursor_point: Point,
5876 style: &EditorStyle,
5877 accept_keystroke: Option<&gpui::Keystroke>,
5878 _window: &Window,
5879 cx: &mut Context<Editor>,
5880 ) -> Option<AnyElement> {
5881 let provider = self.edit_prediction_provider.as_ref()?;
5882
5883 if provider.provider.needs_terms_acceptance(cx) {
5884 return Some(
5885 h_flex()
5886 .min_w(min_width)
5887 .flex_1()
5888 .px_2()
5889 .py_1()
5890 .gap_3()
5891 .elevation_2(cx)
5892 .hover(|style| style.bg(cx.theme().colors().element_hover))
5893 .id("accept-terms")
5894 .cursor_pointer()
5895 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5896 .on_click(cx.listener(|this, _event, window, cx| {
5897 cx.stop_propagation();
5898 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5899 window.dispatch_action(
5900 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5901 cx,
5902 );
5903 }))
5904 .child(
5905 h_flex()
5906 .flex_1()
5907 .gap_2()
5908 .child(Icon::new(IconName::ZedPredict))
5909 .child(Label::new("Accept Terms of Service"))
5910 .child(div().w_full())
5911 .child(
5912 Icon::new(IconName::ArrowUpRight)
5913 .color(Color::Muted)
5914 .size(IconSize::Small),
5915 )
5916 .into_any_element(),
5917 )
5918 .into_any(),
5919 );
5920 }
5921
5922 let is_refreshing = provider.provider.is_refreshing(cx);
5923
5924 fn pending_completion_container() -> Div {
5925 h_flex()
5926 .h_full()
5927 .flex_1()
5928 .gap_2()
5929 .child(Icon::new(IconName::ZedPredict))
5930 }
5931
5932 let completion = match &self.active_inline_completion {
5933 Some(completion) => match &completion.completion {
5934 InlineCompletion::Move {
5935 target, snapshot, ..
5936 } if !self.has_visible_completions_menu() => {
5937 use text::ToPoint as _;
5938
5939 return Some(
5940 h_flex()
5941 .px_2()
5942 .py_1()
5943 .gap_2()
5944 .elevation_2(cx)
5945 .border_color(cx.theme().colors().border)
5946 .rounded(px(6.))
5947 .rounded_tl(px(0.))
5948 .child(
5949 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5950 Icon::new(IconName::ZedPredictDown)
5951 } else {
5952 Icon::new(IconName::ZedPredictUp)
5953 },
5954 )
5955 .child(Label::new("Hold").size(LabelSize::Small))
5956 .child(h_flex().children(ui::render_modifiers(
5957 &accept_keystroke?.modifiers,
5958 PlatformStyle::platform(),
5959 Some(Color::Default),
5960 Some(IconSize::Small.rems().into()),
5961 false,
5962 )))
5963 .into_any(),
5964 );
5965 }
5966 _ => self.render_edit_prediction_cursor_popover_preview(
5967 completion,
5968 cursor_point,
5969 style,
5970 cx,
5971 )?,
5972 },
5973
5974 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5975 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5976 stale_completion,
5977 cursor_point,
5978 style,
5979 cx,
5980 )?,
5981
5982 None => {
5983 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5984 }
5985 },
5986
5987 None => pending_completion_container().child(Label::new("No Prediction")),
5988 };
5989
5990 let completion = if is_refreshing {
5991 completion
5992 .with_animation(
5993 "loading-completion",
5994 Animation::new(Duration::from_secs(2))
5995 .repeat()
5996 .with_easing(pulsating_between(0.4, 0.8)),
5997 |label, delta| label.opacity(delta),
5998 )
5999 .into_any_element()
6000 } else {
6001 completion.into_any_element()
6002 };
6003
6004 let has_completion = self.active_inline_completion.is_some();
6005
6006 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6007 Some(
6008 h_flex()
6009 .min_w(min_width)
6010 .max_w(max_width)
6011 .flex_1()
6012 .elevation_2(cx)
6013 .border_color(cx.theme().colors().border)
6014 .child(
6015 div()
6016 .flex_1()
6017 .py_1()
6018 .px_2()
6019 .overflow_hidden()
6020 .child(completion),
6021 )
6022 .when_some(accept_keystroke, |el, accept_keystroke| {
6023 if !accept_keystroke.modifiers.modified() {
6024 return el;
6025 }
6026
6027 el.child(
6028 h_flex()
6029 .h_full()
6030 .border_l_1()
6031 .rounded_r_lg()
6032 .border_color(cx.theme().colors().border)
6033 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6034 .gap_1()
6035 .py_1()
6036 .px_2()
6037 .child(
6038 h_flex()
6039 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6040 .when(is_platform_style_mac, |parent| parent.gap_1())
6041 .child(h_flex().children(ui::render_modifiers(
6042 &accept_keystroke.modifiers,
6043 PlatformStyle::platform(),
6044 Some(if !has_completion {
6045 Color::Muted
6046 } else {
6047 Color::Default
6048 }),
6049 None,
6050 false,
6051 ))),
6052 )
6053 .child(Label::new("Preview").into_any_element())
6054 .opacity(if has_completion { 1.0 } else { 0.4 }),
6055 )
6056 })
6057 .into_any(),
6058 )
6059 }
6060
6061 fn render_edit_prediction_cursor_popover_preview(
6062 &self,
6063 completion: &InlineCompletionState,
6064 cursor_point: Point,
6065 style: &EditorStyle,
6066 cx: &mut Context<Editor>,
6067 ) -> Option<Div> {
6068 use text::ToPoint as _;
6069
6070 fn render_relative_row_jump(
6071 prefix: impl Into<String>,
6072 current_row: u32,
6073 target_row: u32,
6074 ) -> Div {
6075 let (row_diff, arrow) = if target_row < current_row {
6076 (current_row - target_row, IconName::ArrowUp)
6077 } else {
6078 (target_row - current_row, IconName::ArrowDown)
6079 };
6080
6081 h_flex()
6082 .child(
6083 Label::new(format!("{}{}", prefix.into(), row_diff))
6084 .color(Color::Muted)
6085 .size(LabelSize::Small),
6086 )
6087 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6088 }
6089
6090 match &completion.completion {
6091 InlineCompletion::Move {
6092 target, snapshot, ..
6093 } => Some(
6094 h_flex()
6095 .px_2()
6096 .gap_2()
6097 .flex_1()
6098 .child(
6099 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6100 Icon::new(IconName::ZedPredictDown)
6101 } else {
6102 Icon::new(IconName::ZedPredictUp)
6103 },
6104 )
6105 .child(Label::new("Jump to Edit")),
6106 ),
6107
6108 InlineCompletion::Edit {
6109 edits,
6110 edit_preview,
6111 snapshot,
6112 display_mode: _,
6113 } => {
6114 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6115
6116 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6117 &snapshot,
6118 &edits,
6119 edit_preview.as_ref()?,
6120 true,
6121 cx,
6122 )
6123 .first_line_preview();
6124
6125 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6126 .with_highlights(&style.text, highlighted_edits.highlights);
6127
6128 let preview = h_flex()
6129 .gap_1()
6130 .min_w_16()
6131 .child(styled_text)
6132 .when(has_more_lines, |parent| parent.child("…"));
6133
6134 let left = if first_edit_row != cursor_point.row {
6135 render_relative_row_jump("", cursor_point.row, first_edit_row)
6136 .into_any_element()
6137 } else {
6138 Icon::new(IconName::ZedPredict).into_any_element()
6139 };
6140
6141 Some(
6142 h_flex()
6143 .h_full()
6144 .flex_1()
6145 .gap_2()
6146 .pr_1()
6147 .overflow_x_hidden()
6148 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6149 .child(left)
6150 .child(preview),
6151 )
6152 }
6153 }
6154 }
6155
6156 fn render_context_menu(
6157 &self,
6158 style: &EditorStyle,
6159 max_height_in_lines: u32,
6160 y_flipped: bool,
6161 window: &mut Window,
6162 cx: &mut Context<Editor>,
6163 ) -> Option<AnyElement> {
6164 let menu = self.context_menu.borrow();
6165 let menu = menu.as_ref()?;
6166 if !menu.visible() {
6167 return None;
6168 };
6169 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6170 }
6171
6172 fn render_context_menu_aside(
6173 &mut self,
6174 max_size: Size<Pixels>,
6175 window: &mut Window,
6176 cx: &mut Context<Editor>,
6177 ) -> Option<AnyElement> {
6178 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6179 if menu.visible() {
6180 menu.render_aside(self, max_size, window, cx)
6181 } else {
6182 None
6183 }
6184 })
6185 }
6186
6187 fn hide_context_menu(
6188 &mut self,
6189 window: &mut Window,
6190 cx: &mut Context<Self>,
6191 ) -> Option<CodeContextMenu> {
6192 cx.notify();
6193 self.completion_tasks.clear();
6194 let context_menu = self.context_menu.borrow_mut().take();
6195 self.stale_inline_completion_in_menu.take();
6196 self.update_visible_inline_completion(window, cx);
6197 context_menu
6198 }
6199
6200 fn show_snippet_choices(
6201 &mut self,
6202 choices: &Vec<String>,
6203 selection: Range<Anchor>,
6204 cx: &mut Context<Self>,
6205 ) {
6206 if selection.start.buffer_id.is_none() {
6207 return;
6208 }
6209 let buffer_id = selection.start.buffer_id.unwrap();
6210 let buffer = self.buffer().read(cx).buffer(buffer_id);
6211 let id = post_inc(&mut self.next_completion_id);
6212
6213 if let Some(buffer) = buffer {
6214 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6215 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6216 ));
6217 }
6218 }
6219
6220 pub fn insert_snippet(
6221 &mut self,
6222 insertion_ranges: &[Range<usize>],
6223 snippet: Snippet,
6224 window: &mut Window,
6225 cx: &mut Context<Self>,
6226 ) -> Result<()> {
6227 struct Tabstop<T> {
6228 is_end_tabstop: bool,
6229 ranges: Vec<Range<T>>,
6230 choices: Option<Vec<String>>,
6231 }
6232
6233 let tabstops = self.buffer.update(cx, |buffer, cx| {
6234 let snippet_text: Arc<str> = snippet.text.clone().into();
6235 buffer.edit(
6236 insertion_ranges
6237 .iter()
6238 .cloned()
6239 .map(|range| (range, snippet_text.clone())),
6240 Some(AutoindentMode::EachLine),
6241 cx,
6242 );
6243
6244 let snapshot = &*buffer.read(cx);
6245 let snippet = &snippet;
6246 snippet
6247 .tabstops
6248 .iter()
6249 .map(|tabstop| {
6250 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6251 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6252 });
6253 let mut tabstop_ranges = tabstop
6254 .ranges
6255 .iter()
6256 .flat_map(|tabstop_range| {
6257 let mut delta = 0_isize;
6258 insertion_ranges.iter().map(move |insertion_range| {
6259 let insertion_start = insertion_range.start as isize + delta;
6260 delta +=
6261 snippet.text.len() as isize - insertion_range.len() as isize;
6262
6263 let start = ((insertion_start + tabstop_range.start) as usize)
6264 .min(snapshot.len());
6265 let end = ((insertion_start + tabstop_range.end) as usize)
6266 .min(snapshot.len());
6267 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6268 })
6269 })
6270 .collect::<Vec<_>>();
6271 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6272
6273 Tabstop {
6274 is_end_tabstop,
6275 ranges: tabstop_ranges,
6276 choices: tabstop.choices.clone(),
6277 }
6278 })
6279 .collect::<Vec<_>>()
6280 });
6281 if let Some(tabstop) = tabstops.first() {
6282 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6283 s.select_ranges(tabstop.ranges.iter().cloned());
6284 });
6285
6286 if let Some(choices) = &tabstop.choices {
6287 if let Some(selection) = tabstop.ranges.first() {
6288 self.show_snippet_choices(choices, selection.clone(), cx)
6289 }
6290 }
6291
6292 // If we're already at the last tabstop and it's at the end of the snippet,
6293 // we're done, we don't need to keep the state around.
6294 if !tabstop.is_end_tabstop {
6295 let choices = tabstops
6296 .iter()
6297 .map(|tabstop| tabstop.choices.clone())
6298 .collect();
6299
6300 let ranges = tabstops
6301 .into_iter()
6302 .map(|tabstop| tabstop.ranges)
6303 .collect::<Vec<_>>();
6304
6305 self.snippet_stack.push(SnippetState {
6306 active_index: 0,
6307 ranges,
6308 choices,
6309 });
6310 }
6311
6312 // Check whether the just-entered snippet ends with an auto-closable bracket.
6313 if self.autoclose_regions.is_empty() {
6314 let snapshot = self.buffer.read(cx).snapshot(cx);
6315 for selection in &mut self.selections.all::<Point>(cx) {
6316 let selection_head = selection.head();
6317 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6318 continue;
6319 };
6320
6321 let mut bracket_pair = None;
6322 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6323 let prev_chars = snapshot
6324 .reversed_chars_at(selection_head)
6325 .collect::<String>();
6326 for (pair, enabled) in scope.brackets() {
6327 if enabled
6328 && pair.close
6329 && prev_chars.starts_with(pair.start.as_str())
6330 && next_chars.starts_with(pair.end.as_str())
6331 {
6332 bracket_pair = Some(pair.clone());
6333 break;
6334 }
6335 }
6336 if let Some(pair) = bracket_pair {
6337 let start = snapshot.anchor_after(selection_head);
6338 let end = snapshot.anchor_after(selection_head);
6339 self.autoclose_regions.push(AutocloseRegion {
6340 selection_id: selection.id,
6341 range: start..end,
6342 pair,
6343 });
6344 }
6345 }
6346 }
6347 }
6348 Ok(())
6349 }
6350
6351 pub fn move_to_next_snippet_tabstop(
6352 &mut self,
6353 window: &mut Window,
6354 cx: &mut Context<Self>,
6355 ) -> bool {
6356 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6357 }
6358
6359 pub fn move_to_prev_snippet_tabstop(
6360 &mut self,
6361 window: &mut Window,
6362 cx: &mut Context<Self>,
6363 ) -> bool {
6364 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6365 }
6366
6367 pub fn move_to_snippet_tabstop(
6368 &mut self,
6369 bias: Bias,
6370 window: &mut Window,
6371 cx: &mut Context<Self>,
6372 ) -> bool {
6373 if let Some(mut snippet) = self.snippet_stack.pop() {
6374 match bias {
6375 Bias::Left => {
6376 if snippet.active_index > 0 {
6377 snippet.active_index -= 1;
6378 } else {
6379 self.snippet_stack.push(snippet);
6380 return false;
6381 }
6382 }
6383 Bias::Right => {
6384 if snippet.active_index + 1 < snippet.ranges.len() {
6385 snippet.active_index += 1;
6386 } else {
6387 self.snippet_stack.push(snippet);
6388 return false;
6389 }
6390 }
6391 }
6392 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6393 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6394 s.select_anchor_ranges(current_ranges.iter().cloned())
6395 });
6396
6397 if let Some(choices) = &snippet.choices[snippet.active_index] {
6398 if let Some(selection) = current_ranges.first() {
6399 self.show_snippet_choices(&choices, selection.clone(), cx);
6400 }
6401 }
6402
6403 // If snippet state is not at the last tabstop, push it back on the stack
6404 if snippet.active_index + 1 < snippet.ranges.len() {
6405 self.snippet_stack.push(snippet);
6406 }
6407 return true;
6408 }
6409 }
6410
6411 false
6412 }
6413
6414 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6415 self.transact(window, cx, |this, window, cx| {
6416 this.select_all(&SelectAll, window, cx);
6417 this.insert("", window, cx);
6418 });
6419 }
6420
6421 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6422 self.transact(window, cx, |this, window, cx| {
6423 this.select_autoclose_pair(window, cx);
6424 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6425 if !this.linked_edit_ranges.is_empty() {
6426 let selections = this.selections.all::<MultiBufferPoint>(cx);
6427 let snapshot = this.buffer.read(cx).snapshot(cx);
6428
6429 for selection in selections.iter() {
6430 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6431 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6432 if selection_start.buffer_id != selection_end.buffer_id {
6433 continue;
6434 }
6435 if let Some(ranges) =
6436 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6437 {
6438 for (buffer, entries) in ranges {
6439 linked_ranges.entry(buffer).or_default().extend(entries);
6440 }
6441 }
6442 }
6443 }
6444
6445 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6446 if !this.selections.line_mode {
6447 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6448 for selection in &mut selections {
6449 if selection.is_empty() {
6450 let old_head = selection.head();
6451 let mut new_head =
6452 movement::left(&display_map, old_head.to_display_point(&display_map))
6453 .to_point(&display_map);
6454 if let Some((buffer, line_buffer_range)) = display_map
6455 .buffer_snapshot
6456 .buffer_line_for_row(MultiBufferRow(old_head.row))
6457 {
6458 let indent_size =
6459 buffer.indent_size_for_line(line_buffer_range.start.row);
6460 let indent_len = match indent_size.kind {
6461 IndentKind::Space => {
6462 buffer.settings_at(line_buffer_range.start, cx).tab_size
6463 }
6464 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6465 };
6466 if old_head.column <= indent_size.len && old_head.column > 0 {
6467 let indent_len = indent_len.get();
6468 new_head = cmp::min(
6469 new_head,
6470 MultiBufferPoint::new(
6471 old_head.row,
6472 ((old_head.column - 1) / indent_len) * indent_len,
6473 ),
6474 );
6475 }
6476 }
6477
6478 selection.set_head(new_head, SelectionGoal::None);
6479 }
6480 }
6481 }
6482
6483 this.signature_help_state.set_backspace_pressed(true);
6484 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6485 s.select(selections)
6486 });
6487 this.insert("", window, cx);
6488 let empty_str: Arc<str> = Arc::from("");
6489 for (buffer, edits) in linked_ranges {
6490 let snapshot = buffer.read(cx).snapshot();
6491 use text::ToPoint as TP;
6492
6493 let edits = edits
6494 .into_iter()
6495 .map(|range| {
6496 let end_point = TP::to_point(&range.end, &snapshot);
6497 let mut start_point = TP::to_point(&range.start, &snapshot);
6498
6499 if end_point == start_point {
6500 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6501 .saturating_sub(1);
6502 start_point =
6503 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6504 };
6505
6506 (start_point..end_point, empty_str.clone())
6507 })
6508 .sorted_by_key(|(range, _)| range.start)
6509 .collect::<Vec<_>>();
6510 buffer.update(cx, |this, cx| {
6511 this.edit(edits, None, cx);
6512 })
6513 }
6514 this.refresh_inline_completion(true, false, window, cx);
6515 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6516 });
6517 }
6518
6519 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6520 self.transact(window, cx, |this, window, cx| {
6521 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6522 let line_mode = s.line_mode;
6523 s.move_with(|map, selection| {
6524 if selection.is_empty() && !line_mode {
6525 let cursor = movement::right(map, selection.head());
6526 selection.end = cursor;
6527 selection.reversed = true;
6528 selection.goal = SelectionGoal::None;
6529 }
6530 })
6531 });
6532 this.insert("", window, cx);
6533 this.refresh_inline_completion(true, false, window, cx);
6534 });
6535 }
6536
6537 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6538 if self.move_to_prev_snippet_tabstop(window, cx) {
6539 return;
6540 }
6541
6542 self.outdent(&Outdent, window, cx);
6543 }
6544
6545 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6546 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6547 return;
6548 }
6549
6550 let mut selections = self.selections.all_adjusted(cx);
6551 let buffer = self.buffer.read(cx);
6552 let snapshot = buffer.snapshot(cx);
6553 let rows_iter = selections.iter().map(|s| s.head().row);
6554 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6555
6556 let mut edits = Vec::new();
6557 let mut prev_edited_row = 0;
6558 let mut row_delta = 0;
6559 for selection in &mut selections {
6560 if selection.start.row != prev_edited_row {
6561 row_delta = 0;
6562 }
6563 prev_edited_row = selection.end.row;
6564
6565 // If the selection is non-empty, then increase the indentation of the selected lines.
6566 if !selection.is_empty() {
6567 row_delta =
6568 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6569 continue;
6570 }
6571
6572 // If the selection is empty and the cursor is in the leading whitespace before the
6573 // suggested indentation, then auto-indent the line.
6574 let cursor = selection.head();
6575 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6576 if let Some(suggested_indent) =
6577 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6578 {
6579 if cursor.column < suggested_indent.len
6580 && cursor.column <= current_indent.len
6581 && current_indent.len <= suggested_indent.len
6582 {
6583 selection.start = Point::new(cursor.row, suggested_indent.len);
6584 selection.end = selection.start;
6585 if row_delta == 0 {
6586 edits.extend(Buffer::edit_for_indent_size_adjustment(
6587 cursor.row,
6588 current_indent,
6589 suggested_indent,
6590 ));
6591 row_delta = suggested_indent.len - current_indent.len;
6592 }
6593 continue;
6594 }
6595 }
6596
6597 // Otherwise, insert a hard or soft tab.
6598 let settings = buffer.settings_at(cursor, cx);
6599 let tab_size = if settings.hard_tabs {
6600 IndentSize::tab()
6601 } else {
6602 let tab_size = settings.tab_size.get();
6603 let char_column = snapshot
6604 .text_for_range(Point::new(cursor.row, 0)..cursor)
6605 .flat_map(str::chars)
6606 .count()
6607 + row_delta as usize;
6608 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6609 IndentSize::spaces(chars_to_next_tab_stop)
6610 };
6611 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6612 selection.end = selection.start;
6613 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6614 row_delta += tab_size.len;
6615 }
6616
6617 self.transact(window, cx, |this, window, cx| {
6618 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6619 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6620 s.select(selections)
6621 });
6622 this.refresh_inline_completion(true, false, window, cx);
6623 });
6624 }
6625
6626 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6627 if self.read_only(cx) {
6628 return;
6629 }
6630 let mut selections = self.selections.all::<Point>(cx);
6631 let mut prev_edited_row = 0;
6632 let mut row_delta = 0;
6633 let mut edits = Vec::new();
6634 let buffer = self.buffer.read(cx);
6635 let snapshot = buffer.snapshot(cx);
6636 for selection in &mut selections {
6637 if selection.start.row != prev_edited_row {
6638 row_delta = 0;
6639 }
6640 prev_edited_row = selection.end.row;
6641
6642 row_delta =
6643 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6644 }
6645
6646 self.transact(window, cx, |this, window, cx| {
6647 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6648 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6649 s.select(selections)
6650 });
6651 });
6652 }
6653
6654 fn indent_selection(
6655 buffer: &MultiBuffer,
6656 snapshot: &MultiBufferSnapshot,
6657 selection: &mut Selection<Point>,
6658 edits: &mut Vec<(Range<Point>, String)>,
6659 delta_for_start_row: u32,
6660 cx: &App,
6661 ) -> u32 {
6662 let settings = buffer.settings_at(selection.start, cx);
6663 let tab_size = settings.tab_size.get();
6664 let indent_kind = if settings.hard_tabs {
6665 IndentKind::Tab
6666 } else {
6667 IndentKind::Space
6668 };
6669 let mut start_row = selection.start.row;
6670 let mut end_row = selection.end.row + 1;
6671
6672 // If a selection ends at the beginning of a line, don't indent
6673 // that last line.
6674 if selection.end.column == 0 && selection.end.row > selection.start.row {
6675 end_row -= 1;
6676 }
6677
6678 // Avoid re-indenting a row that has already been indented by a
6679 // previous selection, but still update this selection's column
6680 // to reflect that indentation.
6681 if delta_for_start_row > 0 {
6682 start_row += 1;
6683 selection.start.column += delta_for_start_row;
6684 if selection.end.row == selection.start.row {
6685 selection.end.column += delta_for_start_row;
6686 }
6687 }
6688
6689 let mut delta_for_end_row = 0;
6690 let has_multiple_rows = start_row + 1 != end_row;
6691 for row in start_row..end_row {
6692 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6693 let indent_delta = match (current_indent.kind, indent_kind) {
6694 (IndentKind::Space, IndentKind::Space) => {
6695 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6696 IndentSize::spaces(columns_to_next_tab_stop)
6697 }
6698 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6699 (_, IndentKind::Tab) => IndentSize::tab(),
6700 };
6701
6702 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6703 0
6704 } else {
6705 selection.start.column
6706 };
6707 let row_start = Point::new(row, start);
6708 edits.push((
6709 row_start..row_start,
6710 indent_delta.chars().collect::<String>(),
6711 ));
6712
6713 // Update this selection's endpoints to reflect the indentation.
6714 if row == selection.start.row {
6715 selection.start.column += indent_delta.len;
6716 }
6717 if row == selection.end.row {
6718 selection.end.column += indent_delta.len;
6719 delta_for_end_row = indent_delta.len;
6720 }
6721 }
6722
6723 if selection.start.row == selection.end.row {
6724 delta_for_start_row + delta_for_end_row
6725 } else {
6726 delta_for_end_row
6727 }
6728 }
6729
6730 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6731 if self.read_only(cx) {
6732 return;
6733 }
6734 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6735 let selections = self.selections.all::<Point>(cx);
6736 let mut deletion_ranges = Vec::new();
6737 let mut last_outdent = None;
6738 {
6739 let buffer = self.buffer.read(cx);
6740 let snapshot = buffer.snapshot(cx);
6741 for selection in &selections {
6742 let settings = buffer.settings_at(selection.start, cx);
6743 let tab_size = settings.tab_size.get();
6744 let mut rows = selection.spanned_rows(false, &display_map);
6745
6746 // Avoid re-outdenting a row that has already been outdented by a
6747 // previous selection.
6748 if let Some(last_row) = last_outdent {
6749 if last_row == rows.start {
6750 rows.start = rows.start.next_row();
6751 }
6752 }
6753 let has_multiple_rows = rows.len() > 1;
6754 for row in rows.iter_rows() {
6755 let indent_size = snapshot.indent_size_for_line(row);
6756 if indent_size.len > 0 {
6757 let deletion_len = match indent_size.kind {
6758 IndentKind::Space => {
6759 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6760 if columns_to_prev_tab_stop == 0 {
6761 tab_size
6762 } else {
6763 columns_to_prev_tab_stop
6764 }
6765 }
6766 IndentKind::Tab => 1,
6767 };
6768 let start = if has_multiple_rows
6769 || deletion_len > selection.start.column
6770 || indent_size.len < selection.start.column
6771 {
6772 0
6773 } else {
6774 selection.start.column - deletion_len
6775 };
6776 deletion_ranges.push(
6777 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6778 );
6779 last_outdent = Some(row);
6780 }
6781 }
6782 }
6783 }
6784
6785 self.transact(window, cx, |this, window, cx| {
6786 this.buffer.update(cx, |buffer, cx| {
6787 let empty_str: Arc<str> = Arc::default();
6788 buffer.edit(
6789 deletion_ranges
6790 .into_iter()
6791 .map(|range| (range, empty_str.clone())),
6792 None,
6793 cx,
6794 );
6795 });
6796 let selections = this.selections.all::<usize>(cx);
6797 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6798 s.select(selections)
6799 });
6800 });
6801 }
6802
6803 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6804 if self.read_only(cx) {
6805 return;
6806 }
6807 let selections = self
6808 .selections
6809 .all::<usize>(cx)
6810 .into_iter()
6811 .map(|s| s.range());
6812
6813 self.transact(window, cx, |this, window, cx| {
6814 this.buffer.update(cx, |buffer, cx| {
6815 buffer.autoindent_ranges(selections, cx);
6816 });
6817 let selections = this.selections.all::<usize>(cx);
6818 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6819 s.select(selections)
6820 });
6821 });
6822 }
6823
6824 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6825 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6826 let selections = self.selections.all::<Point>(cx);
6827
6828 let mut new_cursors = Vec::new();
6829 let mut edit_ranges = Vec::new();
6830 let mut selections = selections.iter().peekable();
6831 while let Some(selection) = selections.next() {
6832 let mut rows = selection.spanned_rows(false, &display_map);
6833 let goal_display_column = selection.head().to_display_point(&display_map).column();
6834
6835 // Accumulate contiguous regions of rows that we want to delete.
6836 while let Some(next_selection) = selections.peek() {
6837 let next_rows = next_selection.spanned_rows(false, &display_map);
6838 if next_rows.start <= rows.end {
6839 rows.end = next_rows.end;
6840 selections.next().unwrap();
6841 } else {
6842 break;
6843 }
6844 }
6845
6846 let buffer = &display_map.buffer_snapshot;
6847 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6848 let edit_end;
6849 let cursor_buffer_row;
6850 if buffer.max_point().row >= rows.end.0 {
6851 // If there's a line after the range, delete the \n from the end of the row range
6852 // and position the cursor on the next line.
6853 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6854 cursor_buffer_row = rows.end;
6855 } else {
6856 // If there isn't a line after the range, delete the \n from the line before the
6857 // start of the row range and position the cursor there.
6858 edit_start = edit_start.saturating_sub(1);
6859 edit_end = buffer.len();
6860 cursor_buffer_row = rows.start.previous_row();
6861 }
6862
6863 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6864 *cursor.column_mut() =
6865 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6866
6867 new_cursors.push((
6868 selection.id,
6869 buffer.anchor_after(cursor.to_point(&display_map)),
6870 ));
6871 edit_ranges.push(edit_start..edit_end);
6872 }
6873
6874 self.transact(window, cx, |this, window, cx| {
6875 let buffer = this.buffer.update(cx, |buffer, cx| {
6876 let empty_str: Arc<str> = Arc::default();
6877 buffer.edit(
6878 edit_ranges
6879 .into_iter()
6880 .map(|range| (range, empty_str.clone())),
6881 None,
6882 cx,
6883 );
6884 buffer.snapshot(cx)
6885 });
6886 let new_selections = new_cursors
6887 .into_iter()
6888 .map(|(id, cursor)| {
6889 let cursor = cursor.to_point(&buffer);
6890 Selection {
6891 id,
6892 start: cursor,
6893 end: cursor,
6894 reversed: false,
6895 goal: SelectionGoal::None,
6896 }
6897 })
6898 .collect();
6899
6900 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6901 s.select(new_selections);
6902 });
6903 });
6904 }
6905
6906 pub fn join_lines_impl(
6907 &mut self,
6908 insert_whitespace: bool,
6909 window: &mut Window,
6910 cx: &mut Context<Self>,
6911 ) {
6912 if self.read_only(cx) {
6913 return;
6914 }
6915 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6916 for selection in self.selections.all::<Point>(cx) {
6917 let start = MultiBufferRow(selection.start.row);
6918 // Treat single line selections as if they include the next line. Otherwise this action
6919 // would do nothing for single line selections individual cursors.
6920 let end = if selection.start.row == selection.end.row {
6921 MultiBufferRow(selection.start.row + 1)
6922 } else {
6923 MultiBufferRow(selection.end.row)
6924 };
6925
6926 if let Some(last_row_range) = row_ranges.last_mut() {
6927 if start <= last_row_range.end {
6928 last_row_range.end = end;
6929 continue;
6930 }
6931 }
6932 row_ranges.push(start..end);
6933 }
6934
6935 let snapshot = self.buffer.read(cx).snapshot(cx);
6936 let mut cursor_positions = Vec::new();
6937 for row_range in &row_ranges {
6938 let anchor = snapshot.anchor_before(Point::new(
6939 row_range.end.previous_row().0,
6940 snapshot.line_len(row_range.end.previous_row()),
6941 ));
6942 cursor_positions.push(anchor..anchor);
6943 }
6944
6945 self.transact(window, cx, |this, window, cx| {
6946 for row_range in row_ranges.into_iter().rev() {
6947 for row in row_range.iter_rows().rev() {
6948 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6949 let next_line_row = row.next_row();
6950 let indent = snapshot.indent_size_for_line(next_line_row);
6951 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6952
6953 let replace =
6954 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6955 " "
6956 } else {
6957 ""
6958 };
6959
6960 this.buffer.update(cx, |buffer, cx| {
6961 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6962 });
6963 }
6964 }
6965
6966 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6967 s.select_anchor_ranges(cursor_positions)
6968 });
6969 });
6970 }
6971
6972 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6973 self.join_lines_impl(true, window, cx);
6974 }
6975
6976 pub fn sort_lines_case_sensitive(
6977 &mut self,
6978 _: &SortLinesCaseSensitive,
6979 window: &mut Window,
6980 cx: &mut Context<Self>,
6981 ) {
6982 self.manipulate_lines(window, cx, |lines| lines.sort())
6983 }
6984
6985 pub fn sort_lines_case_insensitive(
6986 &mut self,
6987 _: &SortLinesCaseInsensitive,
6988 window: &mut Window,
6989 cx: &mut Context<Self>,
6990 ) {
6991 self.manipulate_lines(window, cx, |lines| {
6992 lines.sort_by_key(|line| line.to_lowercase())
6993 })
6994 }
6995
6996 pub fn unique_lines_case_insensitive(
6997 &mut self,
6998 _: &UniqueLinesCaseInsensitive,
6999 window: &mut Window,
7000 cx: &mut Context<Self>,
7001 ) {
7002 self.manipulate_lines(window, cx, |lines| {
7003 let mut seen = HashSet::default();
7004 lines.retain(|line| seen.insert(line.to_lowercase()));
7005 })
7006 }
7007
7008 pub fn unique_lines_case_sensitive(
7009 &mut self,
7010 _: &UniqueLinesCaseSensitive,
7011 window: &mut Window,
7012 cx: &mut Context<Self>,
7013 ) {
7014 self.manipulate_lines(window, cx, |lines| {
7015 let mut seen = HashSet::default();
7016 lines.retain(|line| seen.insert(*line));
7017 })
7018 }
7019
7020 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7021 let Some(project) = self.project.clone() else {
7022 return;
7023 };
7024 self.reload(project, window, cx)
7025 .detach_and_notify_err(window, cx);
7026 }
7027
7028 pub fn restore_file(
7029 &mut self,
7030 _: &::git::RestoreFile,
7031 window: &mut Window,
7032 cx: &mut Context<Self>,
7033 ) {
7034 let mut buffer_ids = HashSet::default();
7035 let snapshot = self.buffer().read(cx).snapshot(cx);
7036 for selection in self.selections.all::<usize>(cx) {
7037 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7038 }
7039
7040 let buffer = self.buffer().read(cx);
7041 let ranges = buffer_ids
7042 .into_iter()
7043 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7044 .collect::<Vec<_>>();
7045
7046 self.restore_hunks_in_ranges(ranges, window, cx);
7047 }
7048
7049 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7050 let selections = self
7051 .selections
7052 .all(cx)
7053 .into_iter()
7054 .map(|s| s.range())
7055 .collect();
7056 self.restore_hunks_in_ranges(selections, window, cx);
7057 }
7058
7059 fn restore_hunks_in_ranges(
7060 &mut self,
7061 ranges: Vec<Range<Point>>,
7062 window: &mut Window,
7063 cx: &mut Context<Editor>,
7064 ) {
7065 let mut revert_changes = HashMap::default();
7066 let snapshot = self.buffer.read(cx).snapshot(cx);
7067 let Some(project) = &self.project else {
7068 return;
7069 };
7070
7071 let chunk_by = self
7072 .snapshot(window, cx)
7073 .hunks_for_ranges(ranges.into_iter())
7074 .into_iter()
7075 .chunk_by(|hunk| hunk.buffer_id);
7076 for (buffer_id, hunks) in &chunk_by {
7077 let hunks = hunks.collect::<Vec<_>>();
7078 for hunk in &hunks {
7079 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7080 }
7081 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7082 }
7083 drop(chunk_by);
7084 if !revert_changes.is_empty() {
7085 self.transact(window, cx, |editor, window, cx| {
7086 editor.revert(revert_changes, window, cx);
7087 });
7088 }
7089 }
7090
7091 pub fn open_active_item_in_terminal(
7092 &mut self,
7093 _: &OpenInTerminal,
7094 window: &mut Window,
7095 cx: &mut Context<Self>,
7096 ) {
7097 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7098 let project_path = buffer.read(cx).project_path(cx)?;
7099 let project = self.project.as_ref()?.read(cx);
7100 let entry = project.entry_for_path(&project_path, cx)?;
7101 let parent = match &entry.canonical_path {
7102 Some(canonical_path) => canonical_path.to_path_buf(),
7103 None => project.absolute_path(&project_path, cx)?,
7104 }
7105 .parent()?
7106 .to_path_buf();
7107 Some(parent)
7108 }) {
7109 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7110 }
7111 }
7112
7113 pub fn prepare_restore_change(
7114 &self,
7115 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7116 hunk: &MultiBufferDiffHunk,
7117 cx: &mut App,
7118 ) -> Option<()> {
7119 let buffer = self.buffer.read(cx);
7120 let diff = buffer.diff_for(hunk.buffer_id)?;
7121 let buffer = buffer.buffer(hunk.buffer_id)?;
7122 let buffer = buffer.read(cx);
7123 let original_text = diff
7124 .read(cx)
7125 .base_text()
7126 .as_ref()?
7127 .as_rope()
7128 .slice(hunk.diff_base_byte_range.clone());
7129 let buffer_snapshot = buffer.snapshot();
7130 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7131 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7132 probe
7133 .0
7134 .start
7135 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7136 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7137 }) {
7138 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7139 Some(())
7140 } else {
7141 None
7142 }
7143 }
7144
7145 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7146 self.manipulate_lines(window, cx, |lines| lines.reverse())
7147 }
7148
7149 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7150 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7151 }
7152
7153 fn manipulate_lines<Fn>(
7154 &mut self,
7155 window: &mut Window,
7156 cx: &mut Context<Self>,
7157 mut callback: Fn,
7158 ) where
7159 Fn: FnMut(&mut Vec<&str>),
7160 {
7161 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7162 let buffer = self.buffer.read(cx).snapshot(cx);
7163
7164 let mut edits = Vec::new();
7165
7166 let selections = self.selections.all::<Point>(cx);
7167 let mut selections = selections.iter().peekable();
7168 let mut contiguous_row_selections = Vec::new();
7169 let mut new_selections = Vec::new();
7170 let mut added_lines = 0;
7171 let mut removed_lines = 0;
7172
7173 while let Some(selection) = selections.next() {
7174 let (start_row, end_row) = consume_contiguous_rows(
7175 &mut contiguous_row_selections,
7176 selection,
7177 &display_map,
7178 &mut selections,
7179 );
7180
7181 let start_point = Point::new(start_row.0, 0);
7182 let end_point = Point::new(
7183 end_row.previous_row().0,
7184 buffer.line_len(end_row.previous_row()),
7185 );
7186 let text = buffer
7187 .text_for_range(start_point..end_point)
7188 .collect::<String>();
7189
7190 let mut lines = text.split('\n').collect_vec();
7191
7192 let lines_before = lines.len();
7193 callback(&mut lines);
7194 let lines_after = lines.len();
7195
7196 edits.push((start_point..end_point, lines.join("\n")));
7197
7198 // Selections must change based on added and removed line count
7199 let start_row =
7200 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7201 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7202 new_selections.push(Selection {
7203 id: selection.id,
7204 start: start_row,
7205 end: end_row,
7206 goal: SelectionGoal::None,
7207 reversed: selection.reversed,
7208 });
7209
7210 if lines_after > lines_before {
7211 added_lines += lines_after - lines_before;
7212 } else if lines_before > lines_after {
7213 removed_lines += lines_before - lines_after;
7214 }
7215 }
7216
7217 self.transact(window, cx, |this, window, cx| {
7218 let buffer = this.buffer.update(cx, |buffer, cx| {
7219 buffer.edit(edits, None, cx);
7220 buffer.snapshot(cx)
7221 });
7222
7223 // Recalculate offsets on newly edited buffer
7224 let new_selections = new_selections
7225 .iter()
7226 .map(|s| {
7227 let start_point = Point::new(s.start.0, 0);
7228 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7229 Selection {
7230 id: s.id,
7231 start: buffer.point_to_offset(start_point),
7232 end: buffer.point_to_offset(end_point),
7233 goal: s.goal,
7234 reversed: s.reversed,
7235 }
7236 })
7237 .collect();
7238
7239 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7240 s.select(new_selections);
7241 });
7242
7243 this.request_autoscroll(Autoscroll::fit(), cx);
7244 });
7245 }
7246
7247 pub fn convert_to_upper_case(
7248 &mut self,
7249 _: &ConvertToUpperCase,
7250 window: &mut Window,
7251 cx: &mut Context<Self>,
7252 ) {
7253 self.manipulate_text(window, cx, |text| text.to_uppercase())
7254 }
7255
7256 pub fn convert_to_lower_case(
7257 &mut self,
7258 _: &ConvertToLowerCase,
7259 window: &mut Window,
7260 cx: &mut Context<Self>,
7261 ) {
7262 self.manipulate_text(window, cx, |text| text.to_lowercase())
7263 }
7264
7265 pub fn convert_to_title_case(
7266 &mut self,
7267 _: &ConvertToTitleCase,
7268 window: &mut Window,
7269 cx: &mut Context<Self>,
7270 ) {
7271 self.manipulate_text(window, cx, |text| {
7272 text.split('\n')
7273 .map(|line| line.to_case(Case::Title))
7274 .join("\n")
7275 })
7276 }
7277
7278 pub fn convert_to_snake_case(
7279 &mut self,
7280 _: &ConvertToSnakeCase,
7281 window: &mut Window,
7282 cx: &mut Context<Self>,
7283 ) {
7284 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7285 }
7286
7287 pub fn convert_to_kebab_case(
7288 &mut self,
7289 _: &ConvertToKebabCase,
7290 window: &mut Window,
7291 cx: &mut Context<Self>,
7292 ) {
7293 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7294 }
7295
7296 pub fn convert_to_upper_camel_case(
7297 &mut self,
7298 _: &ConvertToUpperCamelCase,
7299 window: &mut Window,
7300 cx: &mut Context<Self>,
7301 ) {
7302 self.manipulate_text(window, cx, |text| {
7303 text.split('\n')
7304 .map(|line| line.to_case(Case::UpperCamel))
7305 .join("\n")
7306 })
7307 }
7308
7309 pub fn convert_to_lower_camel_case(
7310 &mut self,
7311 _: &ConvertToLowerCamelCase,
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) {
7315 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7316 }
7317
7318 pub fn convert_to_opposite_case(
7319 &mut self,
7320 _: &ConvertToOppositeCase,
7321 window: &mut Window,
7322 cx: &mut Context<Self>,
7323 ) {
7324 self.manipulate_text(window, cx, |text| {
7325 text.chars()
7326 .fold(String::with_capacity(text.len()), |mut t, c| {
7327 if c.is_uppercase() {
7328 t.extend(c.to_lowercase());
7329 } else {
7330 t.extend(c.to_uppercase());
7331 }
7332 t
7333 })
7334 })
7335 }
7336
7337 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7338 where
7339 Fn: FnMut(&str) -> String,
7340 {
7341 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7342 let buffer = self.buffer.read(cx).snapshot(cx);
7343
7344 let mut new_selections = Vec::new();
7345 let mut edits = Vec::new();
7346 let mut selection_adjustment = 0i32;
7347
7348 for selection in self.selections.all::<usize>(cx) {
7349 let selection_is_empty = selection.is_empty();
7350
7351 let (start, end) = if selection_is_empty {
7352 let word_range = movement::surrounding_word(
7353 &display_map,
7354 selection.start.to_display_point(&display_map),
7355 );
7356 let start = word_range.start.to_offset(&display_map, Bias::Left);
7357 let end = word_range.end.to_offset(&display_map, Bias::Left);
7358 (start, end)
7359 } else {
7360 (selection.start, selection.end)
7361 };
7362
7363 let text = buffer.text_for_range(start..end).collect::<String>();
7364 let old_length = text.len() as i32;
7365 let text = callback(&text);
7366
7367 new_selections.push(Selection {
7368 start: (start as i32 - selection_adjustment) as usize,
7369 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7370 goal: SelectionGoal::None,
7371 ..selection
7372 });
7373
7374 selection_adjustment += old_length - text.len() as i32;
7375
7376 edits.push((start..end, text));
7377 }
7378
7379 self.transact(window, cx, |this, window, cx| {
7380 this.buffer.update(cx, |buffer, cx| {
7381 buffer.edit(edits, None, cx);
7382 });
7383
7384 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7385 s.select(new_selections);
7386 });
7387
7388 this.request_autoscroll(Autoscroll::fit(), cx);
7389 });
7390 }
7391
7392 pub fn duplicate(
7393 &mut self,
7394 upwards: bool,
7395 whole_lines: bool,
7396 window: &mut Window,
7397 cx: &mut Context<Self>,
7398 ) {
7399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7400 let buffer = &display_map.buffer_snapshot;
7401 let selections = self.selections.all::<Point>(cx);
7402
7403 let mut edits = Vec::new();
7404 let mut selections_iter = selections.iter().peekable();
7405 while let Some(selection) = selections_iter.next() {
7406 let mut rows = selection.spanned_rows(false, &display_map);
7407 // duplicate line-wise
7408 if whole_lines || selection.start == selection.end {
7409 // Avoid duplicating the same lines twice.
7410 while let Some(next_selection) = selections_iter.peek() {
7411 let next_rows = next_selection.spanned_rows(false, &display_map);
7412 if next_rows.start < rows.end {
7413 rows.end = next_rows.end;
7414 selections_iter.next().unwrap();
7415 } else {
7416 break;
7417 }
7418 }
7419
7420 // Copy the text from the selected row region and splice it either at the start
7421 // or end of the region.
7422 let start = Point::new(rows.start.0, 0);
7423 let end = Point::new(
7424 rows.end.previous_row().0,
7425 buffer.line_len(rows.end.previous_row()),
7426 );
7427 let text = buffer
7428 .text_for_range(start..end)
7429 .chain(Some("\n"))
7430 .collect::<String>();
7431 let insert_location = if upwards {
7432 Point::new(rows.end.0, 0)
7433 } else {
7434 start
7435 };
7436 edits.push((insert_location..insert_location, text));
7437 } else {
7438 // duplicate character-wise
7439 let start = selection.start;
7440 let end = selection.end;
7441 let text = buffer.text_for_range(start..end).collect::<String>();
7442 edits.push((selection.end..selection.end, text));
7443 }
7444 }
7445
7446 self.transact(window, cx, |this, _, cx| {
7447 this.buffer.update(cx, |buffer, cx| {
7448 buffer.edit(edits, None, cx);
7449 });
7450
7451 this.request_autoscroll(Autoscroll::fit(), cx);
7452 });
7453 }
7454
7455 pub fn duplicate_line_up(
7456 &mut self,
7457 _: &DuplicateLineUp,
7458 window: &mut Window,
7459 cx: &mut Context<Self>,
7460 ) {
7461 self.duplicate(true, true, window, cx);
7462 }
7463
7464 pub fn duplicate_line_down(
7465 &mut self,
7466 _: &DuplicateLineDown,
7467 window: &mut Window,
7468 cx: &mut Context<Self>,
7469 ) {
7470 self.duplicate(false, true, window, cx);
7471 }
7472
7473 pub fn duplicate_selection(
7474 &mut self,
7475 _: &DuplicateSelection,
7476 window: &mut Window,
7477 cx: &mut Context<Self>,
7478 ) {
7479 self.duplicate(false, false, window, cx);
7480 }
7481
7482 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7484 let buffer = self.buffer.read(cx).snapshot(cx);
7485
7486 let mut edits = Vec::new();
7487 let mut unfold_ranges = Vec::new();
7488 let mut refold_creases = Vec::new();
7489
7490 let selections = self.selections.all::<Point>(cx);
7491 let mut selections = selections.iter().peekable();
7492 let mut contiguous_row_selections = Vec::new();
7493 let mut new_selections = Vec::new();
7494
7495 while let Some(selection) = selections.next() {
7496 // Find all the selections that span a contiguous row range
7497 let (start_row, end_row) = consume_contiguous_rows(
7498 &mut contiguous_row_selections,
7499 selection,
7500 &display_map,
7501 &mut selections,
7502 );
7503
7504 // Move the text spanned by the row range to be before the line preceding the row range
7505 if start_row.0 > 0 {
7506 let range_to_move = Point::new(
7507 start_row.previous_row().0,
7508 buffer.line_len(start_row.previous_row()),
7509 )
7510 ..Point::new(
7511 end_row.previous_row().0,
7512 buffer.line_len(end_row.previous_row()),
7513 );
7514 let insertion_point = display_map
7515 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7516 .0;
7517
7518 // Don't move lines across excerpts
7519 if buffer
7520 .excerpt_containing(insertion_point..range_to_move.end)
7521 .is_some()
7522 {
7523 let text = buffer
7524 .text_for_range(range_to_move.clone())
7525 .flat_map(|s| s.chars())
7526 .skip(1)
7527 .chain(['\n'])
7528 .collect::<String>();
7529
7530 edits.push((
7531 buffer.anchor_after(range_to_move.start)
7532 ..buffer.anchor_before(range_to_move.end),
7533 String::new(),
7534 ));
7535 let insertion_anchor = buffer.anchor_after(insertion_point);
7536 edits.push((insertion_anchor..insertion_anchor, text));
7537
7538 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7539
7540 // Move selections up
7541 new_selections.extend(contiguous_row_selections.drain(..).map(
7542 |mut selection| {
7543 selection.start.row -= row_delta;
7544 selection.end.row -= row_delta;
7545 selection
7546 },
7547 ));
7548
7549 // Move folds up
7550 unfold_ranges.push(range_to_move.clone());
7551 for fold in display_map.folds_in_range(
7552 buffer.anchor_before(range_to_move.start)
7553 ..buffer.anchor_after(range_to_move.end),
7554 ) {
7555 let mut start = fold.range.start.to_point(&buffer);
7556 let mut end = fold.range.end.to_point(&buffer);
7557 start.row -= row_delta;
7558 end.row -= row_delta;
7559 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7560 }
7561 }
7562 }
7563
7564 // If we didn't move line(s), preserve the existing selections
7565 new_selections.append(&mut contiguous_row_selections);
7566 }
7567
7568 self.transact(window, cx, |this, window, cx| {
7569 this.unfold_ranges(&unfold_ranges, true, true, cx);
7570 this.buffer.update(cx, |buffer, cx| {
7571 for (range, text) in edits {
7572 buffer.edit([(range, text)], None, cx);
7573 }
7574 });
7575 this.fold_creases(refold_creases, true, window, cx);
7576 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7577 s.select(new_selections);
7578 })
7579 });
7580 }
7581
7582 pub fn move_line_down(
7583 &mut self,
7584 _: &MoveLineDown,
7585 window: &mut Window,
7586 cx: &mut Context<Self>,
7587 ) {
7588 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7589 let buffer = self.buffer.read(cx).snapshot(cx);
7590
7591 let mut edits = Vec::new();
7592 let mut unfold_ranges = Vec::new();
7593 let mut refold_creases = Vec::new();
7594
7595 let selections = self.selections.all::<Point>(cx);
7596 let mut selections = selections.iter().peekable();
7597 let mut contiguous_row_selections = Vec::new();
7598 let mut new_selections = Vec::new();
7599
7600 while let Some(selection) = selections.next() {
7601 // Find all the selections that span a contiguous row range
7602 let (start_row, end_row) = consume_contiguous_rows(
7603 &mut contiguous_row_selections,
7604 selection,
7605 &display_map,
7606 &mut selections,
7607 );
7608
7609 // Move the text spanned by the row range to be after the last line of the row range
7610 if end_row.0 <= buffer.max_point().row {
7611 let range_to_move =
7612 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7613 let insertion_point = display_map
7614 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7615 .0;
7616
7617 // Don't move lines across excerpt boundaries
7618 if buffer
7619 .excerpt_containing(range_to_move.start..insertion_point)
7620 .is_some()
7621 {
7622 let mut text = String::from("\n");
7623 text.extend(buffer.text_for_range(range_to_move.clone()));
7624 text.pop(); // Drop trailing newline
7625 edits.push((
7626 buffer.anchor_after(range_to_move.start)
7627 ..buffer.anchor_before(range_to_move.end),
7628 String::new(),
7629 ));
7630 let insertion_anchor = buffer.anchor_after(insertion_point);
7631 edits.push((insertion_anchor..insertion_anchor, text));
7632
7633 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7634
7635 // Move selections down
7636 new_selections.extend(contiguous_row_selections.drain(..).map(
7637 |mut selection| {
7638 selection.start.row += row_delta;
7639 selection.end.row += row_delta;
7640 selection
7641 },
7642 ));
7643
7644 // Move folds down
7645 unfold_ranges.push(range_to_move.clone());
7646 for fold in display_map.folds_in_range(
7647 buffer.anchor_before(range_to_move.start)
7648 ..buffer.anchor_after(range_to_move.end),
7649 ) {
7650 let mut start = fold.range.start.to_point(&buffer);
7651 let mut end = fold.range.end.to_point(&buffer);
7652 start.row += row_delta;
7653 end.row += row_delta;
7654 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7655 }
7656 }
7657 }
7658
7659 // If we didn't move line(s), preserve the existing selections
7660 new_selections.append(&mut contiguous_row_selections);
7661 }
7662
7663 self.transact(window, cx, |this, window, cx| {
7664 this.unfold_ranges(&unfold_ranges, true, true, cx);
7665 this.buffer.update(cx, |buffer, cx| {
7666 for (range, text) in edits {
7667 buffer.edit([(range, text)], None, cx);
7668 }
7669 });
7670 this.fold_creases(refold_creases, true, window, cx);
7671 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7672 s.select(new_selections)
7673 });
7674 });
7675 }
7676
7677 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7678 let text_layout_details = &self.text_layout_details(window);
7679 self.transact(window, cx, |this, window, cx| {
7680 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7681 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7682 let line_mode = s.line_mode;
7683 s.move_with(|display_map, selection| {
7684 if !selection.is_empty() || line_mode {
7685 return;
7686 }
7687
7688 let mut head = selection.head();
7689 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7690 if head.column() == display_map.line_len(head.row()) {
7691 transpose_offset = display_map
7692 .buffer_snapshot
7693 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7694 }
7695
7696 if transpose_offset == 0 {
7697 return;
7698 }
7699
7700 *head.column_mut() += 1;
7701 head = display_map.clip_point(head, Bias::Right);
7702 let goal = SelectionGoal::HorizontalPosition(
7703 display_map
7704 .x_for_display_point(head, text_layout_details)
7705 .into(),
7706 );
7707 selection.collapse_to(head, goal);
7708
7709 let transpose_start = display_map
7710 .buffer_snapshot
7711 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7712 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7713 let transpose_end = display_map
7714 .buffer_snapshot
7715 .clip_offset(transpose_offset + 1, Bias::Right);
7716 if let Some(ch) =
7717 display_map.buffer_snapshot.chars_at(transpose_start).next()
7718 {
7719 edits.push((transpose_start..transpose_offset, String::new()));
7720 edits.push((transpose_end..transpose_end, ch.to_string()));
7721 }
7722 }
7723 });
7724 edits
7725 });
7726 this.buffer
7727 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7728 let selections = this.selections.all::<usize>(cx);
7729 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7730 s.select(selections);
7731 });
7732 });
7733 }
7734
7735 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7736 self.rewrap_impl(IsVimMode::No, cx)
7737 }
7738
7739 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7740 let buffer = self.buffer.read(cx).snapshot(cx);
7741 let selections = self.selections.all::<Point>(cx);
7742 let mut selections = selections.iter().peekable();
7743
7744 let mut edits = Vec::new();
7745 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7746
7747 while let Some(selection) = selections.next() {
7748 let mut start_row = selection.start.row;
7749 let mut end_row = selection.end.row;
7750
7751 // Skip selections that overlap with a range that has already been rewrapped.
7752 let selection_range = start_row..end_row;
7753 if rewrapped_row_ranges
7754 .iter()
7755 .any(|range| range.overlaps(&selection_range))
7756 {
7757 continue;
7758 }
7759
7760 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7761
7762 // Since not all lines in the selection may be at the same indent
7763 // level, choose the indent size that is the most common between all
7764 // of the lines.
7765 //
7766 // If there is a tie, we use the deepest indent.
7767 let (indent_size, indent_end) = {
7768 let mut indent_size_occurrences = HashMap::default();
7769 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7770
7771 for row in start_row..=end_row {
7772 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7773 rows_by_indent_size.entry(indent).or_default().push(row);
7774 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7775 }
7776
7777 let indent_size = indent_size_occurrences
7778 .into_iter()
7779 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7780 .map(|(indent, _)| indent)
7781 .unwrap_or_default();
7782 let row = rows_by_indent_size[&indent_size][0];
7783 let indent_end = Point::new(row, indent_size.len);
7784
7785 (indent_size, indent_end)
7786 };
7787
7788 let mut line_prefix = indent_size.chars().collect::<String>();
7789
7790 let mut inside_comment = false;
7791 if let Some(comment_prefix) =
7792 buffer
7793 .language_scope_at(selection.head())
7794 .and_then(|language| {
7795 language
7796 .line_comment_prefixes()
7797 .iter()
7798 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7799 .cloned()
7800 })
7801 {
7802 line_prefix.push_str(&comment_prefix);
7803 inside_comment = true;
7804 }
7805
7806 let language_settings = buffer.settings_at(selection.head(), cx);
7807 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
7808 RewrapBehavior::InComments => inside_comment,
7809 RewrapBehavior::InSelections => !selection.is_empty(),
7810 RewrapBehavior::Anywhere => true,
7811 };
7812
7813 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
7814 if !should_rewrap {
7815 continue;
7816 }
7817
7818 if selection.is_empty() {
7819 'expand_upwards: while start_row > 0 {
7820 let prev_row = start_row - 1;
7821 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7822 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7823 {
7824 start_row = prev_row;
7825 } else {
7826 break 'expand_upwards;
7827 }
7828 }
7829
7830 'expand_downwards: while end_row < buffer.max_point().row {
7831 let next_row = end_row + 1;
7832 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7833 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7834 {
7835 end_row = next_row;
7836 } else {
7837 break 'expand_downwards;
7838 }
7839 }
7840 }
7841
7842 let start = Point::new(start_row, 0);
7843 let start_offset = start.to_offset(&buffer);
7844 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7845 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7846 let Some(lines_without_prefixes) = selection_text
7847 .lines()
7848 .map(|line| {
7849 line.strip_prefix(&line_prefix)
7850 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7851 .ok_or_else(|| {
7852 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7853 })
7854 })
7855 .collect::<Result<Vec<_>, _>>()
7856 .log_err()
7857 else {
7858 continue;
7859 };
7860
7861 let wrap_column = buffer
7862 .settings_at(Point::new(start_row, 0), cx)
7863 .preferred_line_length as usize;
7864 let wrapped_text = wrap_with_prefix(
7865 line_prefix,
7866 lines_without_prefixes.join(" "),
7867 wrap_column,
7868 tab_size,
7869 );
7870
7871 // TODO: should always use char-based diff while still supporting cursor behavior that
7872 // matches vim.
7873 let mut diff_options = DiffOptions::default();
7874 if is_vim_mode == IsVimMode::Yes {
7875 diff_options.max_word_diff_len = 0;
7876 diff_options.max_word_diff_line_count = 0;
7877 } else {
7878 diff_options.max_word_diff_len = usize::MAX;
7879 diff_options.max_word_diff_line_count = usize::MAX;
7880 }
7881
7882 for (old_range, new_text) in
7883 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
7884 {
7885 let edit_start = buffer.anchor_after(start_offset + old_range.start);
7886 let edit_end = buffer.anchor_after(start_offset + old_range.end);
7887 edits.push((edit_start..edit_end, new_text));
7888 }
7889
7890 rewrapped_row_ranges.push(start_row..=end_row);
7891 }
7892
7893 self.buffer
7894 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7895 }
7896
7897 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7898 let mut text = String::new();
7899 let buffer = self.buffer.read(cx).snapshot(cx);
7900 let mut selections = self.selections.all::<Point>(cx);
7901 let mut clipboard_selections = Vec::with_capacity(selections.len());
7902 {
7903 let max_point = buffer.max_point();
7904 let mut is_first = true;
7905 for selection in &mut selections {
7906 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7907 if is_entire_line {
7908 selection.start = Point::new(selection.start.row, 0);
7909 if !selection.is_empty() && selection.end.column == 0 {
7910 selection.end = cmp::min(max_point, selection.end);
7911 } else {
7912 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7913 }
7914 selection.goal = SelectionGoal::None;
7915 }
7916 if is_first {
7917 is_first = false;
7918 } else {
7919 text += "\n";
7920 }
7921 let mut len = 0;
7922 for chunk in buffer.text_for_range(selection.start..selection.end) {
7923 text.push_str(chunk);
7924 len += chunk.len();
7925 }
7926 clipboard_selections.push(ClipboardSelection {
7927 len,
7928 is_entire_line,
7929 first_line_indent: buffer
7930 .indent_size_for_line(MultiBufferRow(selection.start.row))
7931 .len,
7932 });
7933 }
7934 }
7935
7936 self.transact(window, cx, |this, window, cx| {
7937 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7938 s.select(selections);
7939 });
7940 this.insert("", window, cx);
7941 });
7942 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7943 }
7944
7945 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7946 let item = self.cut_common(window, cx);
7947 cx.write_to_clipboard(item);
7948 }
7949
7950 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7951 self.change_selections(None, window, cx, |s| {
7952 s.move_with(|snapshot, sel| {
7953 if sel.is_empty() {
7954 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7955 }
7956 });
7957 });
7958 let item = self.cut_common(window, cx);
7959 cx.set_global(KillRing(item))
7960 }
7961
7962 pub fn kill_ring_yank(
7963 &mut self,
7964 _: &KillRingYank,
7965 window: &mut Window,
7966 cx: &mut Context<Self>,
7967 ) {
7968 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7969 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7970 (kill_ring.text().to_string(), kill_ring.metadata_json())
7971 } else {
7972 return;
7973 }
7974 } else {
7975 return;
7976 };
7977 self.do_paste(&text, metadata, false, window, cx);
7978 }
7979
7980 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7981 let selections = self.selections.all::<Point>(cx);
7982 let buffer = self.buffer.read(cx).read(cx);
7983 let mut text = String::new();
7984
7985 let mut clipboard_selections = Vec::with_capacity(selections.len());
7986 {
7987 let max_point = buffer.max_point();
7988 let mut is_first = true;
7989 for selection in selections.iter() {
7990 let mut start = selection.start;
7991 let mut end = selection.end;
7992 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7993 if is_entire_line {
7994 start = Point::new(start.row, 0);
7995 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7996 }
7997 if is_first {
7998 is_first = false;
7999 } else {
8000 text += "\n";
8001 }
8002 let mut len = 0;
8003 for chunk in buffer.text_for_range(start..end) {
8004 text.push_str(chunk);
8005 len += chunk.len();
8006 }
8007 clipboard_selections.push(ClipboardSelection {
8008 len,
8009 is_entire_line,
8010 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8011 });
8012 }
8013 }
8014
8015 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8016 text,
8017 clipboard_selections,
8018 ));
8019 }
8020
8021 pub fn do_paste(
8022 &mut self,
8023 text: &String,
8024 clipboard_selections: Option<Vec<ClipboardSelection>>,
8025 handle_entire_lines: bool,
8026 window: &mut Window,
8027 cx: &mut Context<Self>,
8028 ) {
8029 if self.read_only(cx) {
8030 return;
8031 }
8032
8033 let clipboard_text = Cow::Borrowed(text);
8034
8035 self.transact(window, cx, |this, window, cx| {
8036 if let Some(mut clipboard_selections) = clipboard_selections {
8037 let old_selections = this.selections.all::<usize>(cx);
8038 let all_selections_were_entire_line =
8039 clipboard_selections.iter().all(|s| s.is_entire_line);
8040 let first_selection_indent_column =
8041 clipboard_selections.first().map(|s| s.first_line_indent);
8042 if clipboard_selections.len() != old_selections.len() {
8043 clipboard_selections.drain(..);
8044 }
8045 let cursor_offset = this.selections.last::<usize>(cx).head();
8046 let mut auto_indent_on_paste = true;
8047
8048 this.buffer.update(cx, |buffer, cx| {
8049 let snapshot = buffer.read(cx);
8050 auto_indent_on_paste =
8051 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8052
8053 let mut start_offset = 0;
8054 let mut edits = Vec::new();
8055 let mut original_indent_columns = Vec::new();
8056 for (ix, selection) in old_selections.iter().enumerate() {
8057 let to_insert;
8058 let entire_line;
8059 let original_indent_column;
8060 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8061 let end_offset = start_offset + clipboard_selection.len;
8062 to_insert = &clipboard_text[start_offset..end_offset];
8063 entire_line = clipboard_selection.is_entire_line;
8064 start_offset = end_offset + 1;
8065 original_indent_column = Some(clipboard_selection.first_line_indent);
8066 } else {
8067 to_insert = clipboard_text.as_str();
8068 entire_line = all_selections_were_entire_line;
8069 original_indent_column = first_selection_indent_column
8070 }
8071
8072 // If the corresponding selection was empty when this slice of the
8073 // clipboard text was written, then the entire line containing the
8074 // selection was copied. If this selection is also currently empty,
8075 // then paste the line before the current line of the buffer.
8076 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8077 let column = selection.start.to_point(&snapshot).column as usize;
8078 let line_start = selection.start - column;
8079 line_start..line_start
8080 } else {
8081 selection.range()
8082 };
8083
8084 edits.push((range, to_insert));
8085 original_indent_columns.extend(original_indent_column);
8086 }
8087 drop(snapshot);
8088
8089 buffer.edit(
8090 edits,
8091 if auto_indent_on_paste {
8092 Some(AutoindentMode::Block {
8093 original_indent_columns,
8094 })
8095 } else {
8096 None
8097 },
8098 cx,
8099 );
8100 });
8101
8102 let selections = this.selections.all::<usize>(cx);
8103 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8104 s.select(selections)
8105 });
8106 } else {
8107 this.insert(&clipboard_text, window, cx);
8108 }
8109 });
8110 }
8111
8112 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8113 if let Some(item) = cx.read_from_clipboard() {
8114 let entries = item.entries();
8115
8116 match entries.first() {
8117 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8118 // of all the pasted entries.
8119 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8120 .do_paste(
8121 clipboard_string.text(),
8122 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8123 true,
8124 window,
8125 cx,
8126 ),
8127 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8128 }
8129 }
8130 }
8131
8132 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8133 if self.read_only(cx) {
8134 return;
8135 }
8136
8137 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8138 if let Some((selections, _)) =
8139 self.selection_history.transaction(transaction_id).cloned()
8140 {
8141 self.change_selections(None, window, cx, |s| {
8142 s.select_anchors(selections.to_vec());
8143 });
8144 }
8145 self.request_autoscroll(Autoscroll::fit(), cx);
8146 self.unmark_text(window, cx);
8147 self.refresh_inline_completion(true, false, window, cx);
8148 cx.emit(EditorEvent::Edited { transaction_id });
8149 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8150 }
8151 }
8152
8153 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8154 if self.read_only(cx) {
8155 return;
8156 }
8157
8158 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8159 if let Some((_, Some(selections))) =
8160 self.selection_history.transaction(transaction_id).cloned()
8161 {
8162 self.change_selections(None, window, cx, |s| {
8163 s.select_anchors(selections.to_vec());
8164 });
8165 }
8166 self.request_autoscroll(Autoscroll::fit(), cx);
8167 self.unmark_text(window, cx);
8168 self.refresh_inline_completion(true, false, window, cx);
8169 cx.emit(EditorEvent::Edited { transaction_id });
8170 }
8171 }
8172
8173 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8174 self.buffer
8175 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8176 }
8177
8178 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8179 self.buffer
8180 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8181 }
8182
8183 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8184 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8185 let line_mode = s.line_mode;
8186 s.move_with(|map, selection| {
8187 let cursor = if selection.is_empty() && !line_mode {
8188 movement::left(map, selection.start)
8189 } else {
8190 selection.start
8191 };
8192 selection.collapse_to(cursor, SelectionGoal::None);
8193 });
8194 })
8195 }
8196
8197 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8198 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8199 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8200 })
8201 }
8202
8203 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8204 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8205 let line_mode = s.line_mode;
8206 s.move_with(|map, selection| {
8207 let cursor = if selection.is_empty() && !line_mode {
8208 movement::right(map, selection.end)
8209 } else {
8210 selection.end
8211 };
8212 selection.collapse_to(cursor, SelectionGoal::None)
8213 });
8214 })
8215 }
8216
8217 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8218 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8219 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8220 })
8221 }
8222
8223 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8224 if self.take_rename(true, window, cx).is_some() {
8225 return;
8226 }
8227
8228 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8229 cx.propagate();
8230 return;
8231 }
8232
8233 let text_layout_details = &self.text_layout_details(window);
8234 let selection_count = self.selections.count();
8235 let first_selection = self.selections.first_anchor();
8236
8237 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8238 let line_mode = s.line_mode;
8239 s.move_with(|map, selection| {
8240 if !selection.is_empty() && !line_mode {
8241 selection.goal = SelectionGoal::None;
8242 }
8243 let (cursor, goal) = movement::up(
8244 map,
8245 selection.start,
8246 selection.goal,
8247 false,
8248 text_layout_details,
8249 );
8250 selection.collapse_to(cursor, goal);
8251 });
8252 });
8253
8254 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8255 {
8256 cx.propagate();
8257 }
8258 }
8259
8260 pub fn move_up_by_lines(
8261 &mut self,
8262 action: &MoveUpByLines,
8263 window: &mut Window,
8264 cx: &mut Context<Self>,
8265 ) {
8266 if self.take_rename(true, window, cx).is_some() {
8267 return;
8268 }
8269
8270 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8271 cx.propagate();
8272 return;
8273 }
8274
8275 let text_layout_details = &self.text_layout_details(window);
8276
8277 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8278 let line_mode = s.line_mode;
8279 s.move_with(|map, selection| {
8280 if !selection.is_empty() && !line_mode {
8281 selection.goal = SelectionGoal::None;
8282 }
8283 let (cursor, goal) = movement::up_by_rows(
8284 map,
8285 selection.start,
8286 action.lines,
8287 selection.goal,
8288 false,
8289 text_layout_details,
8290 );
8291 selection.collapse_to(cursor, goal);
8292 });
8293 })
8294 }
8295
8296 pub fn move_down_by_lines(
8297 &mut self,
8298 action: &MoveDownByLines,
8299 window: &mut Window,
8300 cx: &mut Context<Self>,
8301 ) {
8302 if self.take_rename(true, window, cx).is_some() {
8303 return;
8304 }
8305
8306 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8307 cx.propagate();
8308 return;
8309 }
8310
8311 let text_layout_details = &self.text_layout_details(window);
8312
8313 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8314 let line_mode = s.line_mode;
8315 s.move_with(|map, selection| {
8316 if !selection.is_empty() && !line_mode {
8317 selection.goal = SelectionGoal::None;
8318 }
8319 let (cursor, goal) = movement::down_by_rows(
8320 map,
8321 selection.start,
8322 action.lines,
8323 selection.goal,
8324 false,
8325 text_layout_details,
8326 );
8327 selection.collapse_to(cursor, goal);
8328 });
8329 })
8330 }
8331
8332 pub fn select_down_by_lines(
8333 &mut self,
8334 action: &SelectDownByLines,
8335 window: &mut Window,
8336 cx: &mut Context<Self>,
8337 ) {
8338 let text_layout_details = &self.text_layout_details(window);
8339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8340 s.move_heads_with(|map, head, goal| {
8341 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8342 })
8343 })
8344 }
8345
8346 pub fn select_up_by_lines(
8347 &mut self,
8348 action: &SelectUpByLines,
8349 window: &mut Window,
8350 cx: &mut Context<Self>,
8351 ) {
8352 let text_layout_details = &self.text_layout_details(window);
8353 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8354 s.move_heads_with(|map, head, goal| {
8355 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8356 })
8357 })
8358 }
8359
8360 pub fn select_page_up(
8361 &mut self,
8362 _: &SelectPageUp,
8363 window: &mut Window,
8364 cx: &mut Context<Self>,
8365 ) {
8366 let Some(row_count) = self.visible_row_count() else {
8367 return;
8368 };
8369
8370 let text_layout_details = &self.text_layout_details(window);
8371
8372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8373 s.move_heads_with(|map, head, goal| {
8374 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8375 })
8376 })
8377 }
8378
8379 pub fn move_page_up(
8380 &mut self,
8381 action: &MovePageUp,
8382 window: &mut Window,
8383 cx: &mut Context<Self>,
8384 ) {
8385 if self.take_rename(true, window, cx).is_some() {
8386 return;
8387 }
8388
8389 if self
8390 .context_menu
8391 .borrow_mut()
8392 .as_mut()
8393 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8394 .unwrap_or(false)
8395 {
8396 return;
8397 }
8398
8399 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8400 cx.propagate();
8401 return;
8402 }
8403
8404 let Some(row_count) = self.visible_row_count() else {
8405 return;
8406 };
8407
8408 let autoscroll = if action.center_cursor {
8409 Autoscroll::center()
8410 } else {
8411 Autoscroll::fit()
8412 };
8413
8414 let text_layout_details = &self.text_layout_details(window);
8415
8416 self.change_selections(Some(autoscroll), window, cx, |s| {
8417 let line_mode = s.line_mode;
8418 s.move_with(|map, selection| {
8419 if !selection.is_empty() && !line_mode {
8420 selection.goal = SelectionGoal::None;
8421 }
8422 let (cursor, goal) = movement::up_by_rows(
8423 map,
8424 selection.end,
8425 row_count,
8426 selection.goal,
8427 false,
8428 text_layout_details,
8429 );
8430 selection.collapse_to(cursor, goal);
8431 });
8432 });
8433 }
8434
8435 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8436 let text_layout_details = &self.text_layout_details(window);
8437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8438 s.move_heads_with(|map, head, goal| {
8439 movement::up(map, head, goal, false, text_layout_details)
8440 })
8441 })
8442 }
8443
8444 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8445 self.take_rename(true, window, cx);
8446
8447 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8448 cx.propagate();
8449 return;
8450 }
8451
8452 let text_layout_details = &self.text_layout_details(window);
8453 let selection_count = self.selections.count();
8454 let first_selection = self.selections.first_anchor();
8455
8456 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8457 let line_mode = s.line_mode;
8458 s.move_with(|map, selection| {
8459 if !selection.is_empty() && !line_mode {
8460 selection.goal = SelectionGoal::None;
8461 }
8462 let (cursor, goal) = movement::down(
8463 map,
8464 selection.end,
8465 selection.goal,
8466 false,
8467 text_layout_details,
8468 );
8469 selection.collapse_to(cursor, goal);
8470 });
8471 });
8472
8473 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8474 {
8475 cx.propagate();
8476 }
8477 }
8478
8479 pub fn select_page_down(
8480 &mut self,
8481 _: &SelectPageDown,
8482 window: &mut Window,
8483 cx: &mut Context<Self>,
8484 ) {
8485 let Some(row_count) = self.visible_row_count() else {
8486 return;
8487 };
8488
8489 let text_layout_details = &self.text_layout_details(window);
8490
8491 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8492 s.move_heads_with(|map, head, goal| {
8493 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8494 })
8495 })
8496 }
8497
8498 pub fn move_page_down(
8499 &mut self,
8500 action: &MovePageDown,
8501 window: &mut Window,
8502 cx: &mut Context<Self>,
8503 ) {
8504 if self.take_rename(true, window, cx).is_some() {
8505 return;
8506 }
8507
8508 if self
8509 .context_menu
8510 .borrow_mut()
8511 .as_mut()
8512 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8513 .unwrap_or(false)
8514 {
8515 return;
8516 }
8517
8518 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8519 cx.propagate();
8520 return;
8521 }
8522
8523 let Some(row_count) = self.visible_row_count() else {
8524 return;
8525 };
8526
8527 let autoscroll = if action.center_cursor {
8528 Autoscroll::center()
8529 } else {
8530 Autoscroll::fit()
8531 };
8532
8533 let text_layout_details = &self.text_layout_details(window);
8534 self.change_selections(Some(autoscroll), window, cx, |s| {
8535 let line_mode = s.line_mode;
8536 s.move_with(|map, selection| {
8537 if !selection.is_empty() && !line_mode {
8538 selection.goal = SelectionGoal::None;
8539 }
8540 let (cursor, goal) = movement::down_by_rows(
8541 map,
8542 selection.end,
8543 row_count,
8544 selection.goal,
8545 false,
8546 text_layout_details,
8547 );
8548 selection.collapse_to(cursor, goal);
8549 });
8550 });
8551 }
8552
8553 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8554 let text_layout_details = &self.text_layout_details(window);
8555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8556 s.move_heads_with(|map, head, goal| {
8557 movement::down(map, head, goal, false, text_layout_details)
8558 })
8559 });
8560 }
8561
8562 pub fn context_menu_first(
8563 &mut self,
8564 _: &ContextMenuFirst,
8565 _window: &mut Window,
8566 cx: &mut Context<Self>,
8567 ) {
8568 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8569 context_menu.select_first(self.completion_provider.as_deref(), cx);
8570 }
8571 }
8572
8573 pub fn context_menu_prev(
8574 &mut self,
8575 _: &ContextMenuPrev,
8576 _window: &mut Window,
8577 cx: &mut Context<Self>,
8578 ) {
8579 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8580 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8581 }
8582 }
8583
8584 pub fn context_menu_next(
8585 &mut self,
8586 _: &ContextMenuNext,
8587 _window: &mut Window,
8588 cx: &mut Context<Self>,
8589 ) {
8590 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8591 context_menu.select_next(self.completion_provider.as_deref(), cx);
8592 }
8593 }
8594
8595 pub fn context_menu_last(
8596 &mut self,
8597 _: &ContextMenuLast,
8598 _window: &mut Window,
8599 cx: &mut Context<Self>,
8600 ) {
8601 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8602 context_menu.select_last(self.completion_provider.as_deref(), cx);
8603 }
8604 }
8605
8606 pub fn move_to_previous_word_start(
8607 &mut self,
8608 _: &MoveToPreviousWordStart,
8609 window: &mut Window,
8610 cx: &mut Context<Self>,
8611 ) {
8612 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8613 s.move_cursors_with(|map, head, _| {
8614 (
8615 movement::previous_word_start(map, head),
8616 SelectionGoal::None,
8617 )
8618 });
8619 })
8620 }
8621
8622 pub fn move_to_previous_subword_start(
8623 &mut self,
8624 _: &MoveToPreviousSubwordStart,
8625 window: &mut Window,
8626 cx: &mut Context<Self>,
8627 ) {
8628 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8629 s.move_cursors_with(|map, head, _| {
8630 (
8631 movement::previous_subword_start(map, head),
8632 SelectionGoal::None,
8633 )
8634 });
8635 })
8636 }
8637
8638 pub fn select_to_previous_word_start(
8639 &mut self,
8640 _: &SelectToPreviousWordStart,
8641 window: &mut Window,
8642 cx: &mut Context<Self>,
8643 ) {
8644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8645 s.move_heads_with(|map, head, _| {
8646 (
8647 movement::previous_word_start(map, head),
8648 SelectionGoal::None,
8649 )
8650 });
8651 })
8652 }
8653
8654 pub fn select_to_previous_subword_start(
8655 &mut self,
8656 _: &SelectToPreviousSubwordStart,
8657 window: &mut Window,
8658 cx: &mut Context<Self>,
8659 ) {
8660 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8661 s.move_heads_with(|map, head, _| {
8662 (
8663 movement::previous_subword_start(map, head),
8664 SelectionGoal::None,
8665 )
8666 });
8667 })
8668 }
8669
8670 pub fn delete_to_previous_word_start(
8671 &mut self,
8672 action: &DeleteToPreviousWordStart,
8673 window: &mut Window,
8674 cx: &mut Context<Self>,
8675 ) {
8676 self.transact(window, cx, |this, window, cx| {
8677 this.select_autoclose_pair(window, cx);
8678 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8679 let line_mode = s.line_mode;
8680 s.move_with(|map, selection| {
8681 if selection.is_empty() && !line_mode {
8682 let cursor = if action.ignore_newlines {
8683 movement::previous_word_start(map, selection.head())
8684 } else {
8685 movement::previous_word_start_or_newline(map, selection.head())
8686 };
8687 selection.set_head(cursor, SelectionGoal::None);
8688 }
8689 });
8690 });
8691 this.insert("", window, cx);
8692 });
8693 }
8694
8695 pub fn delete_to_previous_subword_start(
8696 &mut self,
8697 _: &DeleteToPreviousSubwordStart,
8698 window: &mut Window,
8699 cx: &mut Context<Self>,
8700 ) {
8701 self.transact(window, cx, |this, window, cx| {
8702 this.select_autoclose_pair(window, cx);
8703 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8704 let line_mode = s.line_mode;
8705 s.move_with(|map, selection| {
8706 if selection.is_empty() && !line_mode {
8707 let cursor = movement::previous_subword_start(map, selection.head());
8708 selection.set_head(cursor, SelectionGoal::None);
8709 }
8710 });
8711 });
8712 this.insert("", window, cx);
8713 });
8714 }
8715
8716 pub fn move_to_next_word_end(
8717 &mut self,
8718 _: &MoveToNextWordEnd,
8719 window: &mut Window,
8720 cx: &mut Context<Self>,
8721 ) {
8722 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8723 s.move_cursors_with(|map, head, _| {
8724 (movement::next_word_end(map, head), SelectionGoal::None)
8725 });
8726 })
8727 }
8728
8729 pub fn move_to_next_subword_end(
8730 &mut self,
8731 _: &MoveToNextSubwordEnd,
8732 window: &mut Window,
8733 cx: &mut Context<Self>,
8734 ) {
8735 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8736 s.move_cursors_with(|map, head, _| {
8737 (movement::next_subword_end(map, head), SelectionGoal::None)
8738 });
8739 })
8740 }
8741
8742 pub fn select_to_next_word_end(
8743 &mut self,
8744 _: &SelectToNextWordEnd,
8745 window: &mut Window,
8746 cx: &mut Context<Self>,
8747 ) {
8748 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8749 s.move_heads_with(|map, head, _| {
8750 (movement::next_word_end(map, head), SelectionGoal::None)
8751 });
8752 })
8753 }
8754
8755 pub fn select_to_next_subword_end(
8756 &mut self,
8757 _: &SelectToNextSubwordEnd,
8758 window: &mut Window,
8759 cx: &mut Context<Self>,
8760 ) {
8761 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8762 s.move_heads_with(|map, head, _| {
8763 (movement::next_subword_end(map, head), SelectionGoal::None)
8764 });
8765 })
8766 }
8767
8768 pub fn delete_to_next_word_end(
8769 &mut self,
8770 action: &DeleteToNextWordEnd,
8771 window: &mut Window,
8772 cx: &mut Context<Self>,
8773 ) {
8774 self.transact(window, cx, |this, window, cx| {
8775 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8776 let line_mode = s.line_mode;
8777 s.move_with(|map, selection| {
8778 if selection.is_empty() && !line_mode {
8779 let cursor = if action.ignore_newlines {
8780 movement::next_word_end(map, selection.head())
8781 } else {
8782 movement::next_word_end_or_newline(map, selection.head())
8783 };
8784 selection.set_head(cursor, SelectionGoal::None);
8785 }
8786 });
8787 });
8788 this.insert("", window, cx);
8789 });
8790 }
8791
8792 pub fn delete_to_next_subword_end(
8793 &mut self,
8794 _: &DeleteToNextSubwordEnd,
8795 window: &mut Window,
8796 cx: &mut Context<Self>,
8797 ) {
8798 self.transact(window, cx, |this, window, cx| {
8799 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8800 s.move_with(|map, selection| {
8801 if selection.is_empty() {
8802 let cursor = movement::next_subword_end(map, selection.head());
8803 selection.set_head(cursor, SelectionGoal::None);
8804 }
8805 });
8806 });
8807 this.insert("", window, cx);
8808 });
8809 }
8810
8811 pub fn move_to_beginning_of_line(
8812 &mut self,
8813 action: &MoveToBeginningOfLine,
8814 window: &mut Window,
8815 cx: &mut Context<Self>,
8816 ) {
8817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8818 s.move_cursors_with(|map, head, _| {
8819 (
8820 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8821 SelectionGoal::None,
8822 )
8823 });
8824 })
8825 }
8826
8827 pub fn select_to_beginning_of_line(
8828 &mut self,
8829 action: &SelectToBeginningOfLine,
8830 window: &mut Window,
8831 cx: &mut Context<Self>,
8832 ) {
8833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8834 s.move_heads_with(|map, head, _| {
8835 (
8836 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8837 SelectionGoal::None,
8838 )
8839 });
8840 });
8841 }
8842
8843 pub fn delete_to_beginning_of_line(
8844 &mut self,
8845 _: &DeleteToBeginningOfLine,
8846 window: &mut Window,
8847 cx: &mut Context<Self>,
8848 ) {
8849 self.transact(window, cx, |this, window, cx| {
8850 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8851 s.move_with(|_, selection| {
8852 selection.reversed = true;
8853 });
8854 });
8855
8856 this.select_to_beginning_of_line(
8857 &SelectToBeginningOfLine {
8858 stop_at_soft_wraps: false,
8859 },
8860 window,
8861 cx,
8862 );
8863 this.backspace(&Backspace, window, cx);
8864 });
8865 }
8866
8867 pub fn move_to_end_of_line(
8868 &mut self,
8869 action: &MoveToEndOfLine,
8870 window: &mut Window,
8871 cx: &mut Context<Self>,
8872 ) {
8873 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8874 s.move_cursors_with(|map, head, _| {
8875 (
8876 movement::line_end(map, head, action.stop_at_soft_wraps),
8877 SelectionGoal::None,
8878 )
8879 });
8880 })
8881 }
8882
8883 pub fn select_to_end_of_line(
8884 &mut self,
8885 action: &SelectToEndOfLine,
8886 window: &mut Window,
8887 cx: &mut Context<Self>,
8888 ) {
8889 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8890 s.move_heads_with(|map, head, _| {
8891 (
8892 movement::line_end(map, head, action.stop_at_soft_wraps),
8893 SelectionGoal::None,
8894 )
8895 });
8896 })
8897 }
8898
8899 pub fn delete_to_end_of_line(
8900 &mut self,
8901 _: &DeleteToEndOfLine,
8902 window: &mut Window,
8903 cx: &mut Context<Self>,
8904 ) {
8905 self.transact(window, cx, |this, window, cx| {
8906 this.select_to_end_of_line(
8907 &SelectToEndOfLine {
8908 stop_at_soft_wraps: false,
8909 },
8910 window,
8911 cx,
8912 );
8913 this.delete(&Delete, window, cx);
8914 });
8915 }
8916
8917 pub fn cut_to_end_of_line(
8918 &mut self,
8919 _: &CutToEndOfLine,
8920 window: &mut Window,
8921 cx: &mut Context<Self>,
8922 ) {
8923 self.transact(window, cx, |this, window, cx| {
8924 this.select_to_end_of_line(
8925 &SelectToEndOfLine {
8926 stop_at_soft_wraps: false,
8927 },
8928 window,
8929 cx,
8930 );
8931 this.cut(&Cut, window, cx);
8932 });
8933 }
8934
8935 pub fn move_to_start_of_paragraph(
8936 &mut self,
8937 _: &MoveToStartOfParagraph,
8938 window: &mut Window,
8939 cx: &mut Context<Self>,
8940 ) {
8941 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8942 cx.propagate();
8943 return;
8944 }
8945
8946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8947 s.move_with(|map, selection| {
8948 selection.collapse_to(
8949 movement::start_of_paragraph(map, selection.head(), 1),
8950 SelectionGoal::None,
8951 )
8952 });
8953 })
8954 }
8955
8956 pub fn move_to_end_of_paragraph(
8957 &mut self,
8958 _: &MoveToEndOfParagraph,
8959 window: &mut Window,
8960 cx: &mut Context<Self>,
8961 ) {
8962 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8963 cx.propagate();
8964 return;
8965 }
8966
8967 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8968 s.move_with(|map, selection| {
8969 selection.collapse_to(
8970 movement::end_of_paragraph(map, selection.head(), 1),
8971 SelectionGoal::None,
8972 )
8973 });
8974 })
8975 }
8976
8977 pub fn select_to_start_of_paragraph(
8978 &mut self,
8979 _: &SelectToStartOfParagraph,
8980 window: &mut Window,
8981 cx: &mut Context<Self>,
8982 ) {
8983 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8984 cx.propagate();
8985 return;
8986 }
8987
8988 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8989 s.move_heads_with(|map, head, _| {
8990 (
8991 movement::start_of_paragraph(map, head, 1),
8992 SelectionGoal::None,
8993 )
8994 });
8995 })
8996 }
8997
8998 pub fn select_to_end_of_paragraph(
8999 &mut self,
9000 _: &SelectToEndOfParagraph,
9001 window: &mut Window,
9002 cx: &mut Context<Self>,
9003 ) {
9004 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9005 cx.propagate();
9006 return;
9007 }
9008
9009 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9010 s.move_heads_with(|map, head, _| {
9011 (
9012 movement::end_of_paragraph(map, head, 1),
9013 SelectionGoal::None,
9014 )
9015 });
9016 })
9017 }
9018
9019 pub fn move_to_beginning(
9020 &mut self,
9021 _: &MoveToBeginning,
9022 window: &mut Window,
9023 cx: &mut Context<Self>,
9024 ) {
9025 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9026 cx.propagate();
9027 return;
9028 }
9029
9030 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9031 s.select_ranges(vec![0..0]);
9032 });
9033 }
9034
9035 pub fn select_to_beginning(
9036 &mut self,
9037 _: &SelectToBeginning,
9038 window: &mut Window,
9039 cx: &mut Context<Self>,
9040 ) {
9041 let mut selection = self.selections.last::<Point>(cx);
9042 selection.set_head(Point::zero(), SelectionGoal::None);
9043
9044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9045 s.select(vec![selection]);
9046 });
9047 }
9048
9049 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9050 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9051 cx.propagate();
9052 return;
9053 }
9054
9055 let cursor = self.buffer.read(cx).read(cx).len();
9056 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9057 s.select_ranges(vec![cursor..cursor])
9058 });
9059 }
9060
9061 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9062 self.nav_history = nav_history;
9063 }
9064
9065 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9066 self.nav_history.as_ref()
9067 }
9068
9069 fn push_to_nav_history(
9070 &mut self,
9071 cursor_anchor: Anchor,
9072 new_position: Option<Point>,
9073 cx: &mut Context<Self>,
9074 ) {
9075 if let Some(nav_history) = self.nav_history.as_mut() {
9076 let buffer = self.buffer.read(cx).read(cx);
9077 let cursor_position = cursor_anchor.to_point(&buffer);
9078 let scroll_state = self.scroll_manager.anchor();
9079 let scroll_top_row = scroll_state.top_row(&buffer);
9080 drop(buffer);
9081
9082 if let Some(new_position) = new_position {
9083 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9084 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9085 return;
9086 }
9087 }
9088
9089 nav_history.push(
9090 Some(NavigationData {
9091 cursor_anchor,
9092 cursor_position,
9093 scroll_anchor: scroll_state,
9094 scroll_top_row,
9095 }),
9096 cx,
9097 );
9098 }
9099 }
9100
9101 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9102 let buffer = self.buffer.read(cx).snapshot(cx);
9103 let mut selection = self.selections.first::<usize>(cx);
9104 selection.set_head(buffer.len(), SelectionGoal::None);
9105 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9106 s.select(vec![selection]);
9107 });
9108 }
9109
9110 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9111 let end = self.buffer.read(cx).read(cx).len();
9112 self.change_selections(None, window, cx, |s| {
9113 s.select_ranges(vec![0..end]);
9114 });
9115 }
9116
9117 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9119 let mut selections = self.selections.all::<Point>(cx);
9120 let max_point = display_map.buffer_snapshot.max_point();
9121 for selection in &mut selections {
9122 let rows = selection.spanned_rows(true, &display_map);
9123 selection.start = Point::new(rows.start.0, 0);
9124 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9125 selection.reversed = false;
9126 }
9127 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9128 s.select(selections);
9129 });
9130 }
9131
9132 pub fn split_selection_into_lines(
9133 &mut self,
9134 _: &SplitSelectionIntoLines,
9135 window: &mut Window,
9136 cx: &mut Context<Self>,
9137 ) {
9138 let selections = self
9139 .selections
9140 .all::<Point>(cx)
9141 .into_iter()
9142 .map(|selection| selection.start..selection.end)
9143 .collect::<Vec<_>>();
9144 self.unfold_ranges(&selections, true, true, cx);
9145
9146 let mut new_selection_ranges = Vec::new();
9147 {
9148 let buffer = self.buffer.read(cx).read(cx);
9149 for selection in selections {
9150 for row in selection.start.row..selection.end.row {
9151 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9152 new_selection_ranges.push(cursor..cursor);
9153 }
9154
9155 let is_multiline_selection = selection.start.row != selection.end.row;
9156 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9157 // so this action feels more ergonomic when paired with other selection operations
9158 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9159 if !should_skip_last {
9160 new_selection_ranges.push(selection.end..selection.end);
9161 }
9162 }
9163 }
9164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9165 s.select_ranges(new_selection_ranges);
9166 });
9167 }
9168
9169 pub fn add_selection_above(
9170 &mut self,
9171 _: &AddSelectionAbove,
9172 window: &mut Window,
9173 cx: &mut Context<Self>,
9174 ) {
9175 self.add_selection(true, window, cx);
9176 }
9177
9178 pub fn add_selection_below(
9179 &mut self,
9180 _: &AddSelectionBelow,
9181 window: &mut Window,
9182 cx: &mut Context<Self>,
9183 ) {
9184 self.add_selection(false, window, cx);
9185 }
9186
9187 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9188 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9189 let mut selections = self.selections.all::<Point>(cx);
9190 let text_layout_details = self.text_layout_details(window);
9191 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9192 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9193 let range = oldest_selection.display_range(&display_map).sorted();
9194
9195 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9196 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9197 let positions = start_x.min(end_x)..start_x.max(end_x);
9198
9199 selections.clear();
9200 let mut stack = Vec::new();
9201 for row in range.start.row().0..=range.end.row().0 {
9202 if let Some(selection) = self.selections.build_columnar_selection(
9203 &display_map,
9204 DisplayRow(row),
9205 &positions,
9206 oldest_selection.reversed,
9207 &text_layout_details,
9208 ) {
9209 stack.push(selection.id);
9210 selections.push(selection);
9211 }
9212 }
9213
9214 if above {
9215 stack.reverse();
9216 }
9217
9218 AddSelectionsState { above, stack }
9219 });
9220
9221 let last_added_selection = *state.stack.last().unwrap();
9222 let mut new_selections = Vec::new();
9223 if above == state.above {
9224 let end_row = if above {
9225 DisplayRow(0)
9226 } else {
9227 display_map.max_point().row()
9228 };
9229
9230 'outer: for selection in selections {
9231 if selection.id == last_added_selection {
9232 let range = selection.display_range(&display_map).sorted();
9233 debug_assert_eq!(range.start.row(), range.end.row());
9234 let mut row = range.start.row();
9235 let positions =
9236 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9237 px(start)..px(end)
9238 } else {
9239 let start_x =
9240 display_map.x_for_display_point(range.start, &text_layout_details);
9241 let end_x =
9242 display_map.x_for_display_point(range.end, &text_layout_details);
9243 start_x.min(end_x)..start_x.max(end_x)
9244 };
9245
9246 while row != end_row {
9247 if above {
9248 row.0 -= 1;
9249 } else {
9250 row.0 += 1;
9251 }
9252
9253 if let Some(new_selection) = self.selections.build_columnar_selection(
9254 &display_map,
9255 row,
9256 &positions,
9257 selection.reversed,
9258 &text_layout_details,
9259 ) {
9260 state.stack.push(new_selection.id);
9261 if above {
9262 new_selections.push(new_selection);
9263 new_selections.push(selection);
9264 } else {
9265 new_selections.push(selection);
9266 new_selections.push(new_selection);
9267 }
9268
9269 continue 'outer;
9270 }
9271 }
9272 }
9273
9274 new_selections.push(selection);
9275 }
9276 } else {
9277 new_selections = selections;
9278 new_selections.retain(|s| s.id != last_added_selection);
9279 state.stack.pop();
9280 }
9281
9282 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9283 s.select(new_selections);
9284 });
9285 if state.stack.len() > 1 {
9286 self.add_selections_state = Some(state);
9287 }
9288 }
9289
9290 pub fn select_next_match_internal(
9291 &mut self,
9292 display_map: &DisplaySnapshot,
9293 replace_newest: bool,
9294 autoscroll: Option<Autoscroll>,
9295 window: &mut Window,
9296 cx: &mut Context<Self>,
9297 ) -> Result<()> {
9298 fn select_next_match_ranges(
9299 this: &mut Editor,
9300 range: Range<usize>,
9301 replace_newest: bool,
9302 auto_scroll: Option<Autoscroll>,
9303 window: &mut Window,
9304 cx: &mut Context<Editor>,
9305 ) {
9306 this.unfold_ranges(&[range.clone()], false, true, cx);
9307 this.change_selections(auto_scroll, window, cx, |s| {
9308 if replace_newest {
9309 s.delete(s.newest_anchor().id);
9310 }
9311 s.insert_range(range.clone());
9312 });
9313 }
9314
9315 let buffer = &display_map.buffer_snapshot;
9316 let mut selections = self.selections.all::<usize>(cx);
9317 if let Some(mut select_next_state) = self.select_next_state.take() {
9318 let query = &select_next_state.query;
9319 if !select_next_state.done {
9320 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9321 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9322 let mut next_selected_range = None;
9323
9324 let bytes_after_last_selection =
9325 buffer.bytes_in_range(last_selection.end..buffer.len());
9326 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9327 let query_matches = query
9328 .stream_find_iter(bytes_after_last_selection)
9329 .map(|result| (last_selection.end, result))
9330 .chain(
9331 query
9332 .stream_find_iter(bytes_before_first_selection)
9333 .map(|result| (0, result)),
9334 );
9335
9336 for (start_offset, query_match) in query_matches {
9337 let query_match = query_match.unwrap(); // can only fail due to I/O
9338 let offset_range =
9339 start_offset + query_match.start()..start_offset + query_match.end();
9340 let display_range = offset_range.start.to_display_point(display_map)
9341 ..offset_range.end.to_display_point(display_map);
9342
9343 if !select_next_state.wordwise
9344 || (!movement::is_inside_word(display_map, display_range.start)
9345 && !movement::is_inside_word(display_map, display_range.end))
9346 {
9347 // TODO: This is n^2, because we might check all the selections
9348 if !selections
9349 .iter()
9350 .any(|selection| selection.range().overlaps(&offset_range))
9351 {
9352 next_selected_range = Some(offset_range);
9353 break;
9354 }
9355 }
9356 }
9357
9358 if let Some(next_selected_range) = next_selected_range {
9359 select_next_match_ranges(
9360 self,
9361 next_selected_range,
9362 replace_newest,
9363 autoscroll,
9364 window,
9365 cx,
9366 );
9367 } else {
9368 select_next_state.done = true;
9369 }
9370 }
9371
9372 self.select_next_state = Some(select_next_state);
9373 } else {
9374 let mut only_carets = true;
9375 let mut same_text_selected = true;
9376 let mut selected_text = None;
9377
9378 let mut selections_iter = selections.iter().peekable();
9379 while let Some(selection) = selections_iter.next() {
9380 if selection.start != selection.end {
9381 only_carets = false;
9382 }
9383
9384 if same_text_selected {
9385 if selected_text.is_none() {
9386 selected_text =
9387 Some(buffer.text_for_range(selection.range()).collect::<String>());
9388 }
9389
9390 if let Some(next_selection) = selections_iter.peek() {
9391 if next_selection.range().len() == selection.range().len() {
9392 let next_selected_text = buffer
9393 .text_for_range(next_selection.range())
9394 .collect::<String>();
9395 if Some(next_selected_text) != selected_text {
9396 same_text_selected = false;
9397 selected_text = None;
9398 }
9399 } else {
9400 same_text_selected = false;
9401 selected_text = None;
9402 }
9403 }
9404 }
9405 }
9406
9407 if only_carets {
9408 for selection in &mut selections {
9409 let word_range = movement::surrounding_word(
9410 display_map,
9411 selection.start.to_display_point(display_map),
9412 );
9413 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9414 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9415 selection.goal = SelectionGoal::None;
9416 selection.reversed = false;
9417 select_next_match_ranges(
9418 self,
9419 selection.start..selection.end,
9420 replace_newest,
9421 autoscroll,
9422 window,
9423 cx,
9424 );
9425 }
9426
9427 if selections.len() == 1 {
9428 let selection = selections
9429 .last()
9430 .expect("ensured that there's only one selection");
9431 let query = buffer
9432 .text_for_range(selection.start..selection.end)
9433 .collect::<String>();
9434 let is_empty = query.is_empty();
9435 let select_state = SelectNextState {
9436 query: AhoCorasick::new(&[query])?,
9437 wordwise: true,
9438 done: is_empty,
9439 };
9440 self.select_next_state = Some(select_state);
9441 } else {
9442 self.select_next_state = None;
9443 }
9444 } else if let Some(selected_text) = selected_text {
9445 self.select_next_state = Some(SelectNextState {
9446 query: AhoCorasick::new(&[selected_text])?,
9447 wordwise: false,
9448 done: false,
9449 });
9450 self.select_next_match_internal(
9451 display_map,
9452 replace_newest,
9453 autoscroll,
9454 window,
9455 cx,
9456 )?;
9457 }
9458 }
9459 Ok(())
9460 }
9461
9462 pub fn select_all_matches(
9463 &mut self,
9464 _action: &SelectAllMatches,
9465 window: &mut Window,
9466 cx: &mut Context<Self>,
9467 ) -> Result<()> {
9468 self.push_to_selection_history();
9469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9470
9471 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9472 let Some(select_next_state) = self.select_next_state.as_mut() else {
9473 return Ok(());
9474 };
9475 if select_next_state.done {
9476 return Ok(());
9477 }
9478
9479 let mut new_selections = self.selections.all::<usize>(cx);
9480
9481 let buffer = &display_map.buffer_snapshot;
9482 let query_matches = select_next_state
9483 .query
9484 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9485
9486 for query_match in query_matches {
9487 let query_match = query_match.unwrap(); // can only fail due to I/O
9488 let offset_range = query_match.start()..query_match.end();
9489 let display_range = offset_range.start.to_display_point(&display_map)
9490 ..offset_range.end.to_display_point(&display_map);
9491
9492 if !select_next_state.wordwise
9493 || (!movement::is_inside_word(&display_map, display_range.start)
9494 && !movement::is_inside_word(&display_map, display_range.end))
9495 {
9496 self.selections.change_with(cx, |selections| {
9497 new_selections.push(Selection {
9498 id: selections.new_selection_id(),
9499 start: offset_range.start,
9500 end: offset_range.end,
9501 reversed: false,
9502 goal: SelectionGoal::None,
9503 });
9504 });
9505 }
9506 }
9507
9508 new_selections.sort_by_key(|selection| selection.start);
9509 let mut ix = 0;
9510 while ix + 1 < new_selections.len() {
9511 let current_selection = &new_selections[ix];
9512 let next_selection = &new_selections[ix + 1];
9513 if current_selection.range().overlaps(&next_selection.range()) {
9514 if current_selection.id < next_selection.id {
9515 new_selections.remove(ix + 1);
9516 } else {
9517 new_selections.remove(ix);
9518 }
9519 } else {
9520 ix += 1;
9521 }
9522 }
9523
9524 let reversed = self.selections.oldest::<usize>(cx).reversed;
9525
9526 for selection in new_selections.iter_mut() {
9527 selection.reversed = reversed;
9528 }
9529
9530 select_next_state.done = true;
9531 self.unfold_ranges(
9532 &new_selections
9533 .iter()
9534 .map(|selection| selection.range())
9535 .collect::<Vec<_>>(),
9536 false,
9537 false,
9538 cx,
9539 );
9540 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9541 selections.select(new_selections)
9542 });
9543
9544 Ok(())
9545 }
9546
9547 pub fn select_next(
9548 &mut self,
9549 action: &SelectNext,
9550 window: &mut Window,
9551 cx: &mut Context<Self>,
9552 ) -> Result<()> {
9553 self.push_to_selection_history();
9554 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9555 self.select_next_match_internal(
9556 &display_map,
9557 action.replace_newest,
9558 Some(Autoscroll::newest()),
9559 window,
9560 cx,
9561 )?;
9562 Ok(())
9563 }
9564
9565 pub fn select_previous(
9566 &mut self,
9567 action: &SelectPrevious,
9568 window: &mut Window,
9569 cx: &mut Context<Self>,
9570 ) -> Result<()> {
9571 self.push_to_selection_history();
9572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9573 let buffer = &display_map.buffer_snapshot;
9574 let mut selections = self.selections.all::<usize>(cx);
9575 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9576 let query = &select_prev_state.query;
9577 if !select_prev_state.done {
9578 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9579 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9580 let mut next_selected_range = None;
9581 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9582 let bytes_before_last_selection =
9583 buffer.reversed_bytes_in_range(0..last_selection.start);
9584 let bytes_after_first_selection =
9585 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9586 let query_matches = query
9587 .stream_find_iter(bytes_before_last_selection)
9588 .map(|result| (last_selection.start, result))
9589 .chain(
9590 query
9591 .stream_find_iter(bytes_after_first_selection)
9592 .map(|result| (buffer.len(), result)),
9593 );
9594 for (end_offset, query_match) in query_matches {
9595 let query_match = query_match.unwrap(); // can only fail due to I/O
9596 let offset_range =
9597 end_offset - query_match.end()..end_offset - query_match.start();
9598 let display_range = offset_range.start.to_display_point(&display_map)
9599 ..offset_range.end.to_display_point(&display_map);
9600
9601 if !select_prev_state.wordwise
9602 || (!movement::is_inside_word(&display_map, display_range.start)
9603 && !movement::is_inside_word(&display_map, display_range.end))
9604 {
9605 next_selected_range = Some(offset_range);
9606 break;
9607 }
9608 }
9609
9610 if let Some(next_selected_range) = next_selected_range {
9611 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9612 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9613 if action.replace_newest {
9614 s.delete(s.newest_anchor().id);
9615 }
9616 s.insert_range(next_selected_range);
9617 });
9618 } else {
9619 select_prev_state.done = true;
9620 }
9621 }
9622
9623 self.select_prev_state = Some(select_prev_state);
9624 } else {
9625 let mut only_carets = true;
9626 let mut same_text_selected = true;
9627 let mut selected_text = None;
9628
9629 let mut selections_iter = selections.iter().peekable();
9630 while let Some(selection) = selections_iter.next() {
9631 if selection.start != selection.end {
9632 only_carets = false;
9633 }
9634
9635 if same_text_selected {
9636 if selected_text.is_none() {
9637 selected_text =
9638 Some(buffer.text_for_range(selection.range()).collect::<String>());
9639 }
9640
9641 if let Some(next_selection) = selections_iter.peek() {
9642 if next_selection.range().len() == selection.range().len() {
9643 let next_selected_text = buffer
9644 .text_for_range(next_selection.range())
9645 .collect::<String>();
9646 if Some(next_selected_text) != selected_text {
9647 same_text_selected = false;
9648 selected_text = None;
9649 }
9650 } else {
9651 same_text_selected = false;
9652 selected_text = None;
9653 }
9654 }
9655 }
9656 }
9657
9658 if only_carets {
9659 for selection in &mut selections {
9660 let word_range = movement::surrounding_word(
9661 &display_map,
9662 selection.start.to_display_point(&display_map),
9663 );
9664 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9665 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9666 selection.goal = SelectionGoal::None;
9667 selection.reversed = false;
9668 }
9669 if selections.len() == 1 {
9670 let selection = selections
9671 .last()
9672 .expect("ensured that there's only one selection");
9673 let query = buffer
9674 .text_for_range(selection.start..selection.end)
9675 .collect::<String>();
9676 let is_empty = query.is_empty();
9677 let select_state = SelectNextState {
9678 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9679 wordwise: true,
9680 done: is_empty,
9681 };
9682 self.select_prev_state = Some(select_state);
9683 } else {
9684 self.select_prev_state = None;
9685 }
9686
9687 self.unfold_ranges(
9688 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9689 false,
9690 true,
9691 cx,
9692 );
9693 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9694 s.select(selections);
9695 });
9696 } else if let Some(selected_text) = selected_text {
9697 self.select_prev_state = Some(SelectNextState {
9698 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9699 wordwise: false,
9700 done: false,
9701 });
9702 self.select_previous(action, window, cx)?;
9703 }
9704 }
9705 Ok(())
9706 }
9707
9708 pub fn toggle_comments(
9709 &mut self,
9710 action: &ToggleComments,
9711 window: &mut Window,
9712 cx: &mut Context<Self>,
9713 ) {
9714 if self.read_only(cx) {
9715 return;
9716 }
9717 let text_layout_details = &self.text_layout_details(window);
9718 self.transact(window, cx, |this, window, cx| {
9719 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9720 let mut edits = Vec::new();
9721 let mut selection_edit_ranges = Vec::new();
9722 let mut last_toggled_row = None;
9723 let snapshot = this.buffer.read(cx).read(cx);
9724 let empty_str: Arc<str> = Arc::default();
9725 let mut suffixes_inserted = Vec::new();
9726 let ignore_indent = action.ignore_indent;
9727
9728 fn comment_prefix_range(
9729 snapshot: &MultiBufferSnapshot,
9730 row: MultiBufferRow,
9731 comment_prefix: &str,
9732 comment_prefix_whitespace: &str,
9733 ignore_indent: bool,
9734 ) -> Range<Point> {
9735 let indent_size = if ignore_indent {
9736 0
9737 } else {
9738 snapshot.indent_size_for_line(row).len
9739 };
9740
9741 let start = Point::new(row.0, indent_size);
9742
9743 let mut line_bytes = snapshot
9744 .bytes_in_range(start..snapshot.max_point())
9745 .flatten()
9746 .copied();
9747
9748 // If this line currently begins with the line comment prefix, then record
9749 // the range containing the prefix.
9750 if line_bytes
9751 .by_ref()
9752 .take(comment_prefix.len())
9753 .eq(comment_prefix.bytes())
9754 {
9755 // Include any whitespace that matches the comment prefix.
9756 let matching_whitespace_len = line_bytes
9757 .zip(comment_prefix_whitespace.bytes())
9758 .take_while(|(a, b)| a == b)
9759 .count() as u32;
9760 let end = Point::new(
9761 start.row,
9762 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9763 );
9764 start..end
9765 } else {
9766 start..start
9767 }
9768 }
9769
9770 fn comment_suffix_range(
9771 snapshot: &MultiBufferSnapshot,
9772 row: MultiBufferRow,
9773 comment_suffix: &str,
9774 comment_suffix_has_leading_space: bool,
9775 ) -> Range<Point> {
9776 let end = Point::new(row.0, snapshot.line_len(row));
9777 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9778
9779 let mut line_end_bytes = snapshot
9780 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9781 .flatten()
9782 .copied();
9783
9784 let leading_space_len = if suffix_start_column > 0
9785 && line_end_bytes.next() == Some(b' ')
9786 && comment_suffix_has_leading_space
9787 {
9788 1
9789 } else {
9790 0
9791 };
9792
9793 // If this line currently begins with the line comment prefix, then record
9794 // the range containing the prefix.
9795 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9796 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9797 start..end
9798 } else {
9799 end..end
9800 }
9801 }
9802
9803 // TODO: Handle selections that cross excerpts
9804 for selection in &mut selections {
9805 let start_column = snapshot
9806 .indent_size_for_line(MultiBufferRow(selection.start.row))
9807 .len;
9808 let language = if let Some(language) =
9809 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9810 {
9811 language
9812 } else {
9813 continue;
9814 };
9815
9816 selection_edit_ranges.clear();
9817
9818 // If multiple selections contain a given row, avoid processing that
9819 // row more than once.
9820 let mut start_row = MultiBufferRow(selection.start.row);
9821 if last_toggled_row == Some(start_row) {
9822 start_row = start_row.next_row();
9823 }
9824 let end_row =
9825 if selection.end.row > selection.start.row && selection.end.column == 0 {
9826 MultiBufferRow(selection.end.row - 1)
9827 } else {
9828 MultiBufferRow(selection.end.row)
9829 };
9830 last_toggled_row = Some(end_row);
9831
9832 if start_row > end_row {
9833 continue;
9834 }
9835
9836 // If the language has line comments, toggle those.
9837 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9838
9839 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9840 if ignore_indent {
9841 full_comment_prefixes = full_comment_prefixes
9842 .into_iter()
9843 .map(|s| Arc::from(s.trim_end()))
9844 .collect();
9845 }
9846
9847 if !full_comment_prefixes.is_empty() {
9848 let first_prefix = full_comment_prefixes
9849 .first()
9850 .expect("prefixes is non-empty");
9851 let prefix_trimmed_lengths = full_comment_prefixes
9852 .iter()
9853 .map(|p| p.trim_end_matches(' ').len())
9854 .collect::<SmallVec<[usize; 4]>>();
9855
9856 let mut all_selection_lines_are_comments = true;
9857
9858 for row in start_row.0..=end_row.0 {
9859 let row = MultiBufferRow(row);
9860 if start_row < end_row && snapshot.is_line_blank(row) {
9861 continue;
9862 }
9863
9864 let prefix_range = full_comment_prefixes
9865 .iter()
9866 .zip(prefix_trimmed_lengths.iter().copied())
9867 .map(|(prefix, trimmed_prefix_len)| {
9868 comment_prefix_range(
9869 snapshot.deref(),
9870 row,
9871 &prefix[..trimmed_prefix_len],
9872 &prefix[trimmed_prefix_len..],
9873 ignore_indent,
9874 )
9875 })
9876 .max_by_key(|range| range.end.column - range.start.column)
9877 .expect("prefixes is non-empty");
9878
9879 if prefix_range.is_empty() {
9880 all_selection_lines_are_comments = false;
9881 }
9882
9883 selection_edit_ranges.push(prefix_range);
9884 }
9885
9886 if all_selection_lines_are_comments {
9887 edits.extend(
9888 selection_edit_ranges
9889 .iter()
9890 .cloned()
9891 .map(|range| (range, empty_str.clone())),
9892 );
9893 } else {
9894 let min_column = selection_edit_ranges
9895 .iter()
9896 .map(|range| range.start.column)
9897 .min()
9898 .unwrap_or(0);
9899 edits.extend(selection_edit_ranges.iter().map(|range| {
9900 let position = Point::new(range.start.row, min_column);
9901 (position..position, first_prefix.clone())
9902 }));
9903 }
9904 } else if let Some((full_comment_prefix, comment_suffix)) =
9905 language.block_comment_delimiters()
9906 {
9907 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9908 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9909 let prefix_range = comment_prefix_range(
9910 snapshot.deref(),
9911 start_row,
9912 comment_prefix,
9913 comment_prefix_whitespace,
9914 ignore_indent,
9915 );
9916 let suffix_range = comment_suffix_range(
9917 snapshot.deref(),
9918 end_row,
9919 comment_suffix.trim_start_matches(' '),
9920 comment_suffix.starts_with(' '),
9921 );
9922
9923 if prefix_range.is_empty() || suffix_range.is_empty() {
9924 edits.push((
9925 prefix_range.start..prefix_range.start,
9926 full_comment_prefix.clone(),
9927 ));
9928 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9929 suffixes_inserted.push((end_row, comment_suffix.len()));
9930 } else {
9931 edits.push((prefix_range, empty_str.clone()));
9932 edits.push((suffix_range, empty_str.clone()));
9933 }
9934 } else {
9935 continue;
9936 }
9937 }
9938
9939 drop(snapshot);
9940 this.buffer.update(cx, |buffer, cx| {
9941 buffer.edit(edits, None, cx);
9942 });
9943
9944 // Adjust selections so that they end before any comment suffixes that
9945 // were inserted.
9946 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9947 let mut selections = this.selections.all::<Point>(cx);
9948 let snapshot = this.buffer.read(cx).read(cx);
9949 for selection in &mut selections {
9950 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9951 match row.cmp(&MultiBufferRow(selection.end.row)) {
9952 Ordering::Less => {
9953 suffixes_inserted.next();
9954 continue;
9955 }
9956 Ordering::Greater => break,
9957 Ordering::Equal => {
9958 if selection.end.column == snapshot.line_len(row) {
9959 if selection.is_empty() {
9960 selection.start.column -= suffix_len as u32;
9961 }
9962 selection.end.column -= suffix_len as u32;
9963 }
9964 break;
9965 }
9966 }
9967 }
9968 }
9969
9970 drop(snapshot);
9971 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9972 s.select(selections)
9973 });
9974
9975 let selections = this.selections.all::<Point>(cx);
9976 let selections_on_single_row = selections.windows(2).all(|selections| {
9977 selections[0].start.row == selections[1].start.row
9978 && selections[0].end.row == selections[1].end.row
9979 && selections[0].start.row == selections[0].end.row
9980 });
9981 let selections_selecting = selections
9982 .iter()
9983 .any(|selection| selection.start != selection.end);
9984 let advance_downwards = action.advance_downwards
9985 && selections_on_single_row
9986 && !selections_selecting
9987 && !matches!(this.mode, EditorMode::SingleLine { .. });
9988
9989 if advance_downwards {
9990 let snapshot = this.buffer.read(cx).snapshot(cx);
9991
9992 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9993 s.move_cursors_with(|display_snapshot, display_point, _| {
9994 let mut point = display_point.to_point(display_snapshot);
9995 point.row += 1;
9996 point = snapshot.clip_point(point, Bias::Left);
9997 let display_point = point.to_display_point(display_snapshot);
9998 let goal = SelectionGoal::HorizontalPosition(
9999 display_snapshot
10000 .x_for_display_point(display_point, text_layout_details)
10001 .into(),
10002 );
10003 (display_point, goal)
10004 })
10005 });
10006 }
10007 });
10008 }
10009
10010 pub fn select_enclosing_symbol(
10011 &mut self,
10012 _: &SelectEnclosingSymbol,
10013 window: &mut Window,
10014 cx: &mut Context<Self>,
10015 ) {
10016 let buffer = self.buffer.read(cx).snapshot(cx);
10017 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10018
10019 fn update_selection(
10020 selection: &Selection<usize>,
10021 buffer_snap: &MultiBufferSnapshot,
10022 ) -> Option<Selection<usize>> {
10023 let cursor = selection.head();
10024 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10025 for symbol in symbols.iter().rev() {
10026 let start = symbol.range.start.to_offset(buffer_snap);
10027 let end = symbol.range.end.to_offset(buffer_snap);
10028 let new_range = start..end;
10029 if start < selection.start || end > selection.end {
10030 return Some(Selection {
10031 id: selection.id,
10032 start: new_range.start,
10033 end: new_range.end,
10034 goal: SelectionGoal::None,
10035 reversed: selection.reversed,
10036 });
10037 }
10038 }
10039 None
10040 }
10041
10042 let mut selected_larger_symbol = false;
10043 let new_selections = old_selections
10044 .iter()
10045 .map(|selection| match update_selection(selection, &buffer) {
10046 Some(new_selection) => {
10047 if new_selection.range() != selection.range() {
10048 selected_larger_symbol = true;
10049 }
10050 new_selection
10051 }
10052 None => selection.clone(),
10053 })
10054 .collect::<Vec<_>>();
10055
10056 if selected_larger_symbol {
10057 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10058 s.select(new_selections);
10059 });
10060 }
10061 }
10062
10063 pub fn select_larger_syntax_node(
10064 &mut self,
10065 _: &SelectLargerSyntaxNode,
10066 window: &mut Window,
10067 cx: &mut Context<Self>,
10068 ) {
10069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10070 let buffer = self.buffer.read(cx).snapshot(cx);
10071 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10072
10073 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10074 let mut selected_larger_node = false;
10075 let new_selections = old_selections
10076 .iter()
10077 .map(|selection| {
10078 let old_range = selection.start..selection.end;
10079 let mut new_range = old_range.clone();
10080 let mut new_node = None;
10081 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10082 {
10083 new_node = Some(node);
10084 new_range = containing_range;
10085 if !display_map.intersects_fold(new_range.start)
10086 && !display_map.intersects_fold(new_range.end)
10087 {
10088 break;
10089 }
10090 }
10091
10092 if let Some(node) = new_node {
10093 // Log the ancestor, to support using this action as a way to explore TreeSitter
10094 // nodes. Parent and grandparent are also logged because this operation will not
10095 // visit nodes that have the same range as their parent.
10096 log::info!("Node: {node:?}");
10097 let parent = node.parent();
10098 log::info!("Parent: {parent:?}");
10099 let grandparent = parent.and_then(|x| x.parent());
10100 log::info!("Grandparent: {grandparent:?}");
10101 }
10102
10103 selected_larger_node |= new_range != old_range;
10104 Selection {
10105 id: selection.id,
10106 start: new_range.start,
10107 end: new_range.end,
10108 goal: SelectionGoal::None,
10109 reversed: selection.reversed,
10110 }
10111 })
10112 .collect::<Vec<_>>();
10113
10114 if selected_larger_node {
10115 stack.push(old_selections);
10116 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10117 s.select(new_selections);
10118 });
10119 }
10120 self.select_larger_syntax_node_stack = stack;
10121 }
10122
10123 pub fn select_smaller_syntax_node(
10124 &mut self,
10125 _: &SelectSmallerSyntaxNode,
10126 window: &mut Window,
10127 cx: &mut Context<Self>,
10128 ) {
10129 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10130 if let Some(selections) = stack.pop() {
10131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10132 s.select(selections.to_vec());
10133 });
10134 }
10135 self.select_larger_syntax_node_stack = stack;
10136 }
10137
10138 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10139 if !EditorSettings::get_global(cx).gutter.runnables {
10140 self.clear_tasks();
10141 return Task::ready(());
10142 }
10143 let project = self.project.as_ref().map(Entity::downgrade);
10144 cx.spawn_in(window, |this, mut cx| async move {
10145 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10146 let Some(project) = project.and_then(|p| p.upgrade()) else {
10147 return;
10148 };
10149 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10150 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10151 }) else {
10152 return;
10153 };
10154
10155 let hide_runnables = project
10156 .update(&mut cx, |project, cx| {
10157 // Do not display any test indicators in non-dev server remote projects.
10158 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10159 })
10160 .unwrap_or(true);
10161 if hide_runnables {
10162 return;
10163 }
10164 let new_rows =
10165 cx.background_spawn({
10166 let snapshot = display_snapshot.clone();
10167 async move {
10168 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10169 }
10170 })
10171 .await;
10172
10173 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10174 this.update(&mut cx, |this, _| {
10175 this.clear_tasks();
10176 for (key, value) in rows {
10177 this.insert_tasks(key, value);
10178 }
10179 })
10180 .ok();
10181 })
10182 }
10183 fn fetch_runnable_ranges(
10184 snapshot: &DisplaySnapshot,
10185 range: Range<Anchor>,
10186 ) -> Vec<language::RunnableRange> {
10187 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10188 }
10189
10190 fn runnable_rows(
10191 project: Entity<Project>,
10192 snapshot: DisplaySnapshot,
10193 runnable_ranges: Vec<RunnableRange>,
10194 mut cx: AsyncWindowContext,
10195 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10196 runnable_ranges
10197 .into_iter()
10198 .filter_map(|mut runnable| {
10199 let tasks = cx
10200 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10201 .ok()?;
10202 if tasks.is_empty() {
10203 return None;
10204 }
10205
10206 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10207
10208 let row = snapshot
10209 .buffer_snapshot
10210 .buffer_line_for_row(MultiBufferRow(point.row))?
10211 .1
10212 .start
10213 .row;
10214
10215 let context_range =
10216 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10217 Some((
10218 (runnable.buffer_id, row),
10219 RunnableTasks {
10220 templates: tasks,
10221 offset: MultiBufferOffset(runnable.run_range.start),
10222 context_range,
10223 column: point.column,
10224 extra_variables: runnable.extra_captures,
10225 },
10226 ))
10227 })
10228 .collect()
10229 }
10230
10231 fn templates_with_tags(
10232 project: &Entity<Project>,
10233 runnable: &mut Runnable,
10234 cx: &mut App,
10235 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10236 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10237 let (worktree_id, file) = project
10238 .buffer_for_id(runnable.buffer, cx)
10239 .and_then(|buffer| buffer.read(cx).file())
10240 .map(|file| (file.worktree_id(cx), file.clone()))
10241 .unzip();
10242
10243 (
10244 project.task_store().read(cx).task_inventory().cloned(),
10245 worktree_id,
10246 file,
10247 )
10248 });
10249
10250 let tags = mem::take(&mut runnable.tags);
10251 let mut tags: Vec<_> = tags
10252 .into_iter()
10253 .flat_map(|tag| {
10254 let tag = tag.0.clone();
10255 inventory
10256 .as_ref()
10257 .into_iter()
10258 .flat_map(|inventory| {
10259 inventory.read(cx).list_tasks(
10260 file.clone(),
10261 Some(runnable.language.clone()),
10262 worktree_id,
10263 cx,
10264 )
10265 })
10266 .filter(move |(_, template)| {
10267 template.tags.iter().any(|source_tag| source_tag == &tag)
10268 })
10269 })
10270 .sorted_by_key(|(kind, _)| kind.to_owned())
10271 .collect();
10272 if let Some((leading_tag_source, _)) = tags.first() {
10273 // Strongest source wins; if we have worktree tag binding, prefer that to
10274 // global and language bindings;
10275 // if we have a global binding, prefer that to language binding.
10276 let first_mismatch = tags
10277 .iter()
10278 .position(|(tag_source, _)| tag_source != leading_tag_source);
10279 if let Some(index) = first_mismatch {
10280 tags.truncate(index);
10281 }
10282 }
10283
10284 tags
10285 }
10286
10287 pub fn move_to_enclosing_bracket(
10288 &mut self,
10289 _: &MoveToEnclosingBracket,
10290 window: &mut Window,
10291 cx: &mut Context<Self>,
10292 ) {
10293 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10294 s.move_offsets_with(|snapshot, selection| {
10295 let Some(enclosing_bracket_ranges) =
10296 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10297 else {
10298 return;
10299 };
10300
10301 let mut best_length = usize::MAX;
10302 let mut best_inside = false;
10303 let mut best_in_bracket_range = false;
10304 let mut best_destination = None;
10305 for (open, close) in enclosing_bracket_ranges {
10306 let close = close.to_inclusive();
10307 let length = close.end() - open.start;
10308 let inside = selection.start >= open.end && selection.end <= *close.start();
10309 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10310 || close.contains(&selection.head());
10311
10312 // If best is next to a bracket and current isn't, skip
10313 if !in_bracket_range && best_in_bracket_range {
10314 continue;
10315 }
10316
10317 // Prefer smaller lengths unless best is inside and current isn't
10318 if length > best_length && (best_inside || !inside) {
10319 continue;
10320 }
10321
10322 best_length = length;
10323 best_inside = inside;
10324 best_in_bracket_range = in_bracket_range;
10325 best_destination = Some(
10326 if close.contains(&selection.start) && close.contains(&selection.end) {
10327 if inside {
10328 open.end
10329 } else {
10330 open.start
10331 }
10332 } else if inside {
10333 *close.start()
10334 } else {
10335 *close.end()
10336 },
10337 );
10338 }
10339
10340 if let Some(destination) = best_destination {
10341 selection.collapse_to(destination, SelectionGoal::None);
10342 }
10343 })
10344 });
10345 }
10346
10347 pub fn undo_selection(
10348 &mut self,
10349 _: &UndoSelection,
10350 window: &mut Window,
10351 cx: &mut Context<Self>,
10352 ) {
10353 self.end_selection(window, cx);
10354 self.selection_history.mode = SelectionHistoryMode::Undoing;
10355 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10356 self.change_selections(None, window, cx, |s| {
10357 s.select_anchors(entry.selections.to_vec())
10358 });
10359 self.select_next_state = entry.select_next_state;
10360 self.select_prev_state = entry.select_prev_state;
10361 self.add_selections_state = entry.add_selections_state;
10362 self.request_autoscroll(Autoscroll::newest(), cx);
10363 }
10364 self.selection_history.mode = SelectionHistoryMode::Normal;
10365 }
10366
10367 pub fn redo_selection(
10368 &mut self,
10369 _: &RedoSelection,
10370 window: &mut Window,
10371 cx: &mut Context<Self>,
10372 ) {
10373 self.end_selection(window, cx);
10374 self.selection_history.mode = SelectionHistoryMode::Redoing;
10375 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10376 self.change_selections(None, window, cx, |s| {
10377 s.select_anchors(entry.selections.to_vec())
10378 });
10379 self.select_next_state = entry.select_next_state;
10380 self.select_prev_state = entry.select_prev_state;
10381 self.add_selections_state = entry.add_selections_state;
10382 self.request_autoscroll(Autoscroll::newest(), cx);
10383 }
10384 self.selection_history.mode = SelectionHistoryMode::Normal;
10385 }
10386
10387 pub fn expand_excerpts(
10388 &mut self,
10389 action: &ExpandExcerpts,
10390 _: &mut Window,
10391 cx: &mut Context<Self>,
10392 ) {
10393 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10394 }
10395
10396 pub fn expand_excerpts_down(
10397 &mut self,
10398 action: &ExpandExcerptsDown,
10399 _: &mut Window,
10400 cx: &mut Context<Self>,
10401 ) {
10402 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10403 }
10404
10405 pub fn expand_excerpts_up(
10406 &mut self,
10407 action: &ExpandExcerptsUp,
10408 _: &mut Window,
10409 cx: &mut Context<Self>,
10410 ) {
10411 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10412 }
10413
10414 pub fn expand_excerpts_for_direction(
10415 &mut self,
10416 lines: u32,
10417 direction: ExpandExcerptDirection,
10418
10419 cx: &mut Context<Self>,
10420 ) {
10421 let selections = self.selections.disjoint_anchors();
10422
10423 let lines = if lines == 0 {
10424 EditorSettings::get_global(cx).expand_excerpt_lines
10425 } else {
10426 lines
10427 };
10428
10429 self.buffer.update(cx, |buffer, cx| {
10430 let snapshot = buffer.snapshot(cx);
10431 let mut excerpt_ids = selections
10432 .iter()
10433 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10434 .collect::<Vec<_>>();
10435 excerpt_ids.sort();
10436 excerpt_ids.dedup();
10437 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10438 })
10439 }
10440
10441 pub fn expand_excerpt(
10442 &mut self,
10443 excerpt: ExcerptId,
10444 direction: ExpandExcerptDirection,
10445 cx: &mut Context<Self>,
10446 ) {
10447 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10448 self.buffer.update(cx, |buffer, cx| {
10449 buffer.expand_excerpts([excerpt], lines, direction, cx)
10450 })
10451 }
10452
10453 pub fn go_to_singleton_buffer_point(
10454 &mut self,
10455 point: Point,
10456 window: &mut Window,
10457 cx: &mut Context<Self>,
10458 ) {
10459 self.go_to_singleton_buffer_range(point..point, window, cx);
10460 }
10461
10462 pub fn go_to_singleton_buffer_range(
10463 &mut self,
10464 range: Range<Point>,
10465 window: &mut Window,
10466 cx: &mut Context<Self>,
10467 ) {
10468 let multibuffer = self.buffer().read(cx);
10469 let Some(buffer) = multibuffer.as_singleton() else {
10470 return;
10471 };
10472 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10473 return;
10474 };
10475 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10476 return;
10477 };
10478 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10479 s.select_anchor_ranges([start..end])
10480 });
10481 }
10482
10483 fn go_to_diagnostic(
10484 &mut self,
10485 _: &GoToDiagnostic,
10486 window: &mut Window,
10487 cx: &mut Context<Self>,
10488 ) {
10489 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10490 }
10491
10492 fn go_to_prev_diagnostic(
10493 &mut self,
10494 _: &GoToPrevDiagnostic,
10495 window: &mut Window,
10496 cx: &mut Context<Self>,
10497 ) {
10498 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10499 }
10500
10501 pub fn go_to_diagnostic_impl(
10502 &mut self,
10503 direction: Direction,
10504 window: &mut Window,
10505 cx: &mut Context<Self>,
10506 ) {
10507 let buffer = self.buffer.read(cx).snapshot(cx);
10508 let selection = self.selections.newest::<usize>(cx);
10509
10510 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10511 if direction == Direction::Next {
10512 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10513 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10514 return;
10515 };
10516 self.activate_diagnostics(
10517 buffer_id,
10518 popover.local_diagnostic.diagnostic.group_id,
10519 window,
10520 cx,
10521 );
10522 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10523 let primary_range_start = active_diagnostics.primary_range.start;
10524 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10525 let mut new_selection = s.newest_anchor().clone();
10526 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10527 s.select_anchors(vec![new_selection.clone()]);
10528 });
10529 self.refresh_inline_completion(false, true, window, cx);
10530 }
10531 return;
10532 }
10533 }
10534
10535 let active_group_id = self
10536 .active_diagnostics
10537 .as_ref()
10538 .map(|active_group| active_group.group_id);
10539 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10540 active_diagnostics
10541 .primary_range
10542 .to_offset(&buffer)
10543 .to_inclusive()
10544 });
10545 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10546 if active_primary_range.contains(&selection.head()) {
10547 *active_primary_range.start()
10548 } else {
10549 selection.head()
10550 }
10551 } else {
10552 selection.head()
10553 };
10554
10555 let snapshot = self.snapshot(window, cx);
10556 let primary_diagnostics_before = buffer
10557 .diagnostics_in_range::<usize>(0..search_start)
10558 .filter(|entry| entry.diagnostic.is_primary)
10559 .filter(|entry| entry.range.start != entry.range.end)
10560 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10561 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10562 .collect::<Vec<_>>();
10563 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10564 primary_diagnostics_before
10565 .iter()
10566 .position(|entry| entry.diagnostic.group_id == active_group_id)
10567 });
10568
10569 let primary_diagnostics_after = buffer
10570 .diagnostics_in_range::<usize>(search_start..buffer.len())
10571 .filter(|entry| entry.diagnostic.is_primary)
10572 .filter(|entry| entry.range.start != entry.range.end)
10573 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10574 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10575 .collect::<Vec<_>>();
10576 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10577 primary_diagnostics_after
10578 .iter()
10579 .enumerate()
10580 .rev()
10581 .find_map(|(i, entry)| {
10582 if entry.diagnostic.group_id == active_group_id {
10583 Some(i)
10584 } else {
10585 None
10586 }
10587 })
10588 });
10589
10590 let next_primary_diagnostic = match direction {
10591 Direction::Prev => primary_diagnostics_before
10592 .iter()
10593 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10594 .rev()
10595 .next(),
10596 Direction::Next => primary_diagnostics_after
10597 .iter()
10598 .skip(
10599 last_same_group_diagnostic_after
10600 .map(|index| index + 1)
10601 .unwrap_or(0),
10602 )
10603 .next(),
10604 };
10605
10606 // Cycle around to the start of the buffer, potentially moving back to the start of
10607 // the currently active diagnostic.
10608 let cycle_around = || match direction {
10609 Direction::Prev => primary_diagnostics_after
10610 .iter()
10611 .rev()
10612 .chain(primary_diagnostics_before.iter().rev())
10613 .next(),
10614 Direction::Next => primary_diagnostics_before
10615 .iter()
10616 .chain(primary_diagnostics_after.iter())
10617 .next(),
10618 };
10619
10620 if let Some((primary_range, group_id)) = next_primary_diagnostic
10621 .or_else(cycle_around)
10622 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10623 {
10624 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10625 return;
10626 };
10627 self.activate_diagnostics(buffer_id, group_id, window, cx);
10628 if self.active_diagnostics.is_some() {
10629 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10630 s.select(vec![Selection {
10631 id: selection.id,
10632 start: primary_range.start,
10633 end: primary_range.start,
10634 reversed: false,
10635 goal: SelectionGoal::None,
10636 }]);
10637 });
10638 self.refresh_inline_completion(false, true, window, cx);
10639 }
10640 }
10641 }
10642
10643 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10644 let snapshot = self.snapshot(window, cx);
10645 let selection = self.selections.newest::<Point>(cx);
10646 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10647 }
10648
10649 fn go_to_hunk_after_position(
10650 &mut self,
10651 snapshot: &EditorSnapshot,
10652 position: Point,
10653 window: &mut Window,
10654 cx: &mut Context<Editor>,
10655 ) -> Option<MultiBufferDiffHunk> {
10656 let mut hunk = snapshot
10657 .buffer_snapshot
10658 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10659 .find(|hunk| hunk.row_range.start.0 > position.row);
10660 if hunk.is_none() {
10661 hunk = snapshot
10662 .buffer_snapshot
10663 .diff_hunks_in_range(Point::zero()..position)
10664 .find(|hunk| hunk.row_range.end.0 < position.row)
10665 }
10666 if let Some(hunk) = &hunk {
10667 let destination = Point::new(hunk.row_range.start.0, 0);
10668 self.unfold_ranges(&[destination..destination], false, false, cx);
10669 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10670 s.select_ranges(vec![destination..destination]);
10671 });
10672 }
10673
10674 hunk
10675 }
10676
10677 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10678 let snapshot = self.snapshot(window, cx);
10679 let selection = self.selections.newest::<Point>(cx);
10680 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10681 }
10682
10683 fn go_to_hunk_before_position(
10684 &mut self,
10685 snapshot: &EditorSnapshot,
10686 position: Point,
10687 window: &mut Window,
10688 cx: &mut Context<Editor>,
10689 ) -> Option<MultiBufferDiffHunk> {
10690 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10691 if hunk.is_none() {
10692 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10693 }
10694 if let Some(hunk) = &hunk {
10695 let destination = Point::new(hunk.row_range.start.0, 0);
10696 self.unfold_ranges(&[destination..destination], false, false, cx);
10697 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10698 s.select_ranges(vec![destination..destination]);
10699 });
10700 }
10701
10702 hunk
10703 }
10704
10705 pub fn go_to_definition(
10706 &mut self,
10707 _: &GoToDefinition,
10708 window: &mut Window,
10709 cx: &mut Context<Self>,
10710 ) -> Task<Result<Navigated>> {
10711 let definition =
10712 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10713 cx.spawn_in(window, |editor, mut cx| async move {
10714 if definition.await? == Navigated::Yes {
10715 return Ok(Navigated::Yes);
10716 }
10717 match editor.update_in(&mut cx, |editor, window, cx| {
10718 editor.find_all_references(&FindAllReferences, window, cx)
10719 })? {
10720 Some(references) => references.await,
10721 None => Ok(Navigated::No),
10722 }
10723 })
10724 }
10725
10726 pub fn go_to_declaration(
10727 &mut self,
10728 _: &GoToDeclaration,
10729 window: &mut Window,
10730 cx: &mut Context<Self>,
10731 ) -> Task<Result<Navigated>> {
10732 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10733 }
10734
10735 pub fn go_to_declaration_split(
10736 &mut self,
10737 _: &GoToDeclaration,
10738 window: &mut Window,
10739 cx: &mut Context<Self>,
10740 ) -> Task<Result<Navigated>> {
10741 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10742 }
10743
10744 pub fn go_to_implementation(
10745 &mut self,
10746 _: &GoToImplementation,
10747 window: &mut Window,
10748 cx: &mut Context<Self>,
10749 ) -> Task<Result<Navigated>> {
10750 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10751 }
10752
10753 pub fn go_to_implementation_split(
10754 &mut self,
10755 _: &GoToImplementationSplit,
10756 window: &mut Window,
10757 cx: &mut Context<Self>,
10758 ) -> Task<Result<Navigated>> {
10759 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10760 }
10761
10762 pub fn go_to_type_definition(
10763 &mut self,
10764 _: &GoToTypeDefinition,
10765 window: &mut Window,
10766 cx: &mut Context<Self>,
10767 ) -> Task<Result<Navigated>> {
10768 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10769 }
10770
10771 pub fn go_to_definition_split(
10772 &mut self,
10773 _: &GoToDefinitionSplit,
10774 window: &mut Window,
10775 cx: &mut Context<Self>,
10776 ) -> Task<Result<Navigated>> {
10777 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10778 }
10779
10780 pub fn go_to_type_definition_split(
10781 &mut self,
10782 _: &GoToTypeDefinitionSplit,
10783 window: &mut Window,
10784 cx: &mut Context<Self>,
10785 ) -> Task<Result<Navigated>> {
10786 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10787 }
10788
10789 fn go_to_definition_of_kind(
10790 &mut self,
10791 kind: GotoDefinitionKind,
10792 split: bool,
10793 window: &mut Window,
10794 cx: &mut Context<Self>,
10795 ) -> Task<Result<Navigated>> {
10796 let Some(provider) = self.semantics_provider.clone() else {
10797 return Task::ready(Ok(Navigated::No));
10798 };
10799 let head = self.selections.newest::<usize>(cx).head();
10800 let buffer = self.buffer.read(cx);
10801 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10802 text_anchor
10803 } else {
10804 return Task::ready(Ok(Navigated::No));
10805 };
10806
10807 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10808 return Task::ready(Ok(Navigated::No));
10809 };
10810
10811 cx.spawn_in(window, |editor, mut cx| async move {
10812 let definitions = definitions.await?;
10813 let navigated = editor
10814 .update_in(&mut cx, |editor, window, cx| {
10815 editor.navigate_to_hover_links(
10816 Some(kind),
10817 definitions
10818 .into_iter()
10819 .filter(|location| {
10820 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10821 })
10822 .map(HoverLink::Text)
10823 .collect::<Vec<_>>(),
10824 split,
10825 window,
10826 cx,
10827 )
10828 })?
10829 .await?;
10830 anyhow::Ok(navigated)
10831 })
10832 }
10833
10834 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10835 let selection = self.selections.newest_anchor();
10836 let head = selection.head();
10837 let tail = selection.tail();
10838
10839 let Some((buffer, start_position)) =
10840 self.buffer.read(cx).text_anchor_for_position(head, cx)
10841 else {
10842 return;
10843 };
10844
10845 let end_position = if head != tail {
10846 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10847 return;
10848 };
10849 Some(pos)
10850 } else {
10851 None
10852 };
10853
10854 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10855 let url = if let Some(end_pos) = end_position {
10856 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10857 } else {
10858 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10859 };
10860
10861 if let Some(url) = url {
10862 editor.update(&mut cx, |_, cx| {
10863 cx.open_url(&url);
10864 })
10865 } else {
10866 Ok(())
10867 }
10868 });
10869
10870 url_finder.detach();
10871 }
10872
10873 pub fn open_selected_filename(
10874 &mut self,
10875 _: &OpenSelectedFilename,
10876 window: &mut Window,
10877 cx: &mut Context<Self>,
10878 ) {
10879 let Some(workspace) = self.workspace() else {
10880 return;
10881 };
10882
10883 let position = self.selections.newest_anchor().head();
10884
10885 let Some((buffer, buffer_position)) =
10886 self.buffer.read(cx).text_anchor_for_position(position, cx)
10887 else {
10888 return;
10889 };
10890
10891 let project = self.project.clone();
10892
10893 cx.spawn_in(window, |_, mut cx| async move {
10894 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10895
10896 if let Some((_, path)) = result {
10897 workspace
10898 .update_in(&mut cx, |workspace, window, cx| {
10899 workspace.open_resolved_path(path, window, cx)
10900 })?
10901 .await?;
10902 }
10903 anyhow::Ok(())
10904 })
10905 .detach();
10906 }
10907
10908 pub(crate) fn navigate_to_hover_links(
10909 &mut self,
10910 kind: Option<GotoDefinitionKind>,
10911 mut definitions: Vec<HoverLink>,
10912 split: bool,
10913 window: &mut Window,
10914 cx: &mut Context<Editor>,
10915 ) -> Task<Result<Navigated>> {
10916 // If there is one definition, just open it directly
10917 if definitions.len() == 1 {
10918 let definition = definitions.pop().unwrap();
10919
10920 enum TargetTaskResult {
10921 Location(Option<Location>),
10922 AlreadyNavigated,
10923 }
10924
10925 let target_task = match definition {
10926 HoverLink::Text(link) => {
10927 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10928 }
10929 HoverLink::InlayHint(lsp_location, server_id) => {
10930 let computation =
10931 self.compute_target_location(lsp_location, server_id, window, cx);
10932 cx.background_spawn(async move {
10933 let location = computation.await?;
10934 Ok(TargetTaskResult::Location(location))
10935 })
10936 }
10937 HoverLink::Url(url) => {
10938 cx.open_url(&url);
10939 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10940 }
10941 HoverLink::File(path) => {
10942 if let Some(workspace) = self.workspace() {
10943 cx.spawn_in(window, |_, mut cx| async move {
10944 workspace
10945 .update_in(&mut cx, |workspace, window, cx| {
10946 workspace.open_resolved_path(path, window, cx)
10947 })?
10948 .await
10949 .map(|_| TargetTaskResult::AlreadyNavigated)
10950 })
10951 } else {
10952 Task::ready(Ok(TargetTaskResult::Location(None)))
10953 }
10954 }
10955 };
10956 cx.spawn_in(window, |editor, mut cx| async move {
10957 let target = match target_task.await.context("target resolution task")? {
10958 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10959 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10960 TargetTaskResult::Location(Some(target)) => target,
10961 };
10962
10963 editor.update_in(&mut cx, |editor, window, cx| {
10964 let Some(workspace) = editor.workspace() else {
10965 return Navigated::No;
10966 };
10967 let pane = workspace.read(cx).active_pane().clone();
10968
10969 let range = target.range.to_point(target.buffer.read(cx));
10970 let range = editor.range_for_match(&range);
10971 let range = collapse_multiline_range(range);
10972
10973 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10974 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10975 } else {
10976 window.defer(cx, move |window, cx| {
10977 let target_editor: Entity<Self> =
10978 workspace.update(cx, |workspace, cx| {
10979 let pane = if split {
10980 workspace.adjacent_pane(window, cx)
10981 } else {
10982 workspace.active_pane().clone()
10983 };
10984
10985 workspace.open_project_item(
10986 pane,
10987 target.buffer.clone(),
10988 true,
10989 true,
10990 window,
10991 cx,
10992 )
10993 });
10994 target_editor.update(cx, |target_editor, cx| {
10995 // When selecting a definition in a different buffer, disable the nav history
10996 // to avoid creating a history entry at the previous cursor location.
10997 pane.update(cx, |pane, _| pane.disable_history());
10998 target_editor.go_to_singleton_buffer_range(range, window, cx);
10999 pane.update(cx, |pane, _| pane.enable_history());
11000 });
11001 });
11002 }
11003 Navigated::Yes
11004 })
11005 })
11006 } else if !definitions.is_empty() {
11007 cx.spawn_in(window, |editor, mut cx| async move {
11008 let (title, location_tasks, workspace) = editor
11009 .update_in(&mut cx, |editor, window, cx| {
11010 let tab_kind = match kind {
11011 Some(GotoDefinitionKind::Implementation) => "Implementations",
11012 _ => "Definitions",
11013 };
11014 let title = definitions
11015 .iter()
11016 .find_map(|definition| match definition {
11017 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11018 let buffer = origin.buffer.read(cx);
11019 format!(
11020 "{} for {}",
11021 tab_kind,
11022 buffer
11023 .text_for_range(origin.range.clone())
11024 .collect::<String>()
11025 )
11026 }),
11027 HoverLink::InlayHint(_, _) => None,
11028 HoverLink::Url(_) => None,
11029 HoverLink::File(_) => None,
11030 })
11031 .unwrap_or(tab_kind.to_string());
11032 let location_tasks = definitions
11033 .into_iter()
11034 .map(|definition| match definition {
11035 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11036 HoverLink::InlayHint(lsp_location, server_id) => editor
11037 .compute_target_location(lsp_location, server_id, window, cx),
11038 HoverLink::Url(_) => Task::ready(Ok(None)),
11039 HoverLink::File(_) => Task::ready(Ok(None)),
11040 })
11041 .collect::<Vec<_>>();
11042 (title, location_tasks, editor.workspace().clone())
11043 })
11044 .context("location tasks preparation")?;
11045
11046 let locations = future::join_all(location_tasks)
11047 .await
11048 .into_iter()
11049 .filter_map(|location| location.transpose())
11050 .collect::<Result<_>>()
11051 .context("location tasks")?;
11052
11053 let Some(workspace) = workspace else {
11054 return Ok(Navigated::No);
11055 };
11056 let opened = workspace
11057 .update_in(&mut cx, |workspace, window, cx| {
11058 Self::open_locations_in_multibuffer(
11059 workspace,
11060 locations,
11061 title,
11062 split,
11063 MultibufferSelectionMode::First,
11064 window,
11065 cx,
11066 )
11067 })
11068 .ok();
11069
11070 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11071 })
11072 } else {
11073 Task::ready(Ok(Navigated::No))
11074 }
11075 }
11076
11077 fn compute_target_location(
11078 &self,
11079 lsp_location: lsp::Location,
11080 server_id: LanguageServerId,
11081 window: &mut Window,
11082 cx: &mut Context<Self>,
11083 ) -> Task<anyhow::Result<Option<Location>>> {
11084 let Some(project) = self.project.clone() else {
11085 return Task::ready(Ok(None));
11086 };
11087
11088 cx.spawn_in(window, move |editor, mut cx| async move {
11089 let location_task = editor.update(&mut cx, |_, cx| {
11090 project.update(cx, |project, cx| {
11091 let language_server_name = project
11092 .language_server_statuses(cx)
11093 .find(|(id, _)| server_id == *id)
11094 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11095 language_server_name.map(|language_server_name| {
11096 project.open_local_buffer_via_lsp(
11097 lsp_location.uri.clone(),
11098 server_id,
11099 language_server_name,
11100 cx,
11101 )
11102 })
11103 })
11104 })?;
11105 let location = match location_task {
11106 Some(task) => Some({
11107 let target_buffer_handle = task.await.context("open local buffer")?;
11108 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11109 let target_start = target_buffer
11110 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11111 let target_end = target_buffer
11112 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11113 target_buffer.anchor_after(target_start)
11114 ..target_buffer.anchor_before(target_end)
11115 })?;
11116 Location {
11117 buffer: target_buffer_handle,
11118 range,
11119 }
11120 }),
11121 None => None,
11122 };
11123 Ok(location)
11124 })
11125 }
11126
11127 pub fn find_all_references(
11128 &mut self,
11129 _: &FindAllReferences,
11130 window: &mut Window,
11131 cx: &mut Context<Self>,
11132 ) -> Option<Task<Result<Navigated>>> {
11133 let selection = self.selections.newest::<usize>(cx);
11134 let multi_buffer = self.buffer.read(cx);
11135 let head = selection.head();
11136
11137 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11138 let head_anchor = multi_buffer_snapshot.anchor_at(
11139 head,
11140 if head < selection.tail() {
11141 Bias::Right
11142 } else {
11143 Bias::Left
11144 },
11145 );
11146
11147 match self
11148 .find_all_references_task_sources
11149 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11150 {
11151 Ok(_) => {
11152 log::info!(
11153 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11154 );
11155 return None;
11156 }
11157 Err(i) => {
11158 self.find_all_references_task_sources.insert(i, head_anchor);
11159 }
11160 }
11161
11162 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11163 let workspace = self.workspace()?;
11164 let project = workspace.read(cx).project().clone();
11165 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11166 Some(cx.spawn_in(window, |editor, mut cx| async move {
11167 let _cleanup = defer({
11168 let mut cx = cx.clone();
11169 move || {
11170 let _ = editor.update(&mut cx, |editor, _| {
11171 if let Ok(i) =
11172 editor
11173 .find_all_references_task_sources
11174 .binary_search_by(|anchor| {
11175 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11176 })
11177 {
11178 editor.find_all_references_task_sources.remove(i);
11179 }
11180 });
11181 }
11182 });
11183
11184 let locations = references.await?;
11185 if locations.is_empty() {
11186 return anyhow::Ok(Navigated::No);
11187 }
11188
11189 workspace.update_in(&mut cx, |workspace, window, cx| {
11190 let title = locations
11191 .first()
11192 .as_ref()
11193 .map(|location| {
11194 let buffer = location.buffer.read(cx);
11195 format!(
11196 "References to `{}`",
11197 buffer
11198 .text_for_range(location.range.clone())
11199 .collect::<String>()
11200 )
11201 })
11202 .unwrap();
11203 Self::open_locations_in_multibuffer(
11204 workspace,
11205 locations,
11206 title,
11207 false,
11208 MultibufferSelectionMode::First,
11209 window,
11210 cx,
11211 );
11212 Navigated::Yes
11213 })
11214 }))
11215 }
11216
11217 /// Opens a multibuffer with the given project locations in it
11218 pub fn open_locations_in_multibuffer(
11219 workspace: &mut Workspace,
11220 mut locations: Vec<Location>,
11221 title: String,
11222 split: bool,
11223 multibuffer_selection_mode: MultibufferSelectionMode,
11224 window: &mut Window,
11225 cx: &mut Context<Workspace>,
11226 ) {
11227 // If there are multiple definitions, open them in a multibuffer
11228 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11229 let mut locations = locations.into_iter().peekable();
11230 let mut ranges = Vec::new();
11231 let capability = workspace.project().read(cx).capability();
11232
11233 let excerpt_buffer = cx.new(|cx| {
11234 let mut multibuffer = MultiBuffer::new(capability);
11235 while let Some(location) = locations.next() {
11236 let buffer = location.buffer.read(cx);
11237 let mut ranges_for_buffer = Vec::new();
11238 let range = location.range.to_offset(buffer);
11239 ranges_for_buffer.push(range.clone());
11240
11241 while let Some(next_location) = locations.peek() {
11242 if next_location.buffer == location.buffer {
11243 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11244 locations.next();
11245 } else {
11246 break;
11247 }
11248 }
11249
11250 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11251 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11252 location.buffer.clone(),
11253 ranges_for_buffer,
11254 DEFAULT_MULTIBUFFER_CONTEXT,
11255 cx,
11256 ))
11257 }
11258
11259 multibuffer.with_title(title)
11260 });
11261
11262 let editor = cx.new(|cx| {
11263 Editor::for_multibuffer(
11264 excerpt_buffer,
11265 Some(workspace.project().clone()),
11266 true,
11267 window,
11268 cx,
11269 )
11270 });
11271 editor.update(cx, |editor, cx| {
11272 match multibuffer_selection_mode {
11273 MultibufferSelectionMode::First => {
11274 if let Some(first_range) = ranges.first() {
11275 editor.change_selections(None, window, cx, |selections| {
11276 selections.clear_disjoint();
11277 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11278 });
11279 }
11280 editor.highlight_background::<Self>(
11281 &ranges,
11282 |theme| theme.editor_highlighted_line_background,
11283 cx,
11284 );
11285 }
11286 MultibufferSelectionMode::All => {
11287 editor.change_selections(None, window, cx, |selections| {
11288 selections.clear_disjoint();
11289 selections.select_anchor_ranges(ranges);
11290 });
11291 }
11292 }
11293 editor.register_buffers_with_language_servers(cx);
11294 });
11295
11296 let item = Box::new(editor);
11297 let item_id = item.item_id();
11298
11299 if split {
11300 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11301 } else {
11302 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11303 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11304 pane.close_current_preview_item(window, cx)
11305 } else {
11306 None
11307 }
11308 });
11309 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11310 }
11311 workspace.active_pane().update(cx, |pane, cx| {
11312 pane.set_preview_item_id(Some(item_id), cx);
11313 });
11314 }
11315
11316 pub fn rename(
11317 &mut self,
11318 _: &Rename,
11319 window: &mut Window,
11320 cx: &mut Context<Self>,
11321 ) -> Option<Task<Result<()>>> {
11322 use language::ToOffset as _;
11323
11324 let provider = self.semantics_provider.clone()?;
11325 let selection = self.selections.newest_anchor().clone();
11326 let (cursor_buffer, cursor_buffer_position) = self
11327 .buffer
11328 .read(cx)
11329 .text_anchor_for_position(selection.head(), cx)?;
11330 let (tail_buffer, cursor_buffer_position_end) = self
11331 .buffer
11332 .read(cx)
11333 .text_anchor_for_position(selection.tail(), cx)?;
11334 if tail_buffer != cursor_buffer {
11335 return None;
11336 }
11337
11338 let snapshot = cursor_buffer.read(cx).snapshot();
11339 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11340 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11341 let prepare_rename = provider
11342 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11343 .unwrap_or_else(|| Task::ready(Ok(None)));
11344 drop(snapshot);
11345
11346 Some(cx.spawn_in(window, |this, mut cx| async move {
11347 let rename_range = if let Some(range) = prepare_rename.await? {
11348 Some(range)
11349 } else {
11350 this.update(&mut cx, |this, cx| {
11351 let buffer = this.buffer.read(cx).snapshot(cx);
11352 let mut buffer_highlights = this
11353 .document_highlights_for_position(selection.head(), &buffer)
11354 .filter(|highlight| {
11355 highlight.start.excerpt_id == selection.head().excerpt_id
11356 && highlight.end.excerpt_id == selection.head().excerpt_id
11357 });
11358 buffer_highlights
11359 .next()
11360 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11361 })?
11362 };
11363 if let Some(rename_range) = rename_range {
11364 this.update_in(&mut cx, |this, window, cx| {
11365 let snapshot = cursor_buffer.read(cx).snapshot();
11366 let rename_buffer_range = rename_range.to_offset(&snapshot);
11367 let cursor_offset_in_rename_range =
11368 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11369 let cursor_offset_in_rename_range_end =
11370 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11371
11372 this.take_rename(false, window, cx);
11373 let buffer = this.buffer.read(cx).read(cx);
11374 let cursor_offset = selection.head().to_offset(&buffer);
11375 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11376 let rename_end = rename_start + rename_buffer_range.len();
11377 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11378 let mut old_highlight_id = None;
11379 let old_name: Arc<str> = buffer
11380 .chunks(rename_start..rename_end, true)
11381 .map(|chunk| {
11382 if old_highlight_id.is_none() {
11383 old_highlight_id = chunk.syntax_highlight_id;
11384 }
11385 chunk.text
11386 })
11387 .collect::<String>()
11388 .into();
11389
11390 drop(buffer);
11391
11392 // Position the selection in the rename editor so that it matches the current selection.
11393 this.show_local_selections = false;
11394 let rename_editor = cx.new(|cx| {
11395 let mut editor = Editor::single_line(window, cx);
11396 editor.buffer.update(cx, |buffer, cx| {
11397 buffer.edit([(0..0, old_name.clone())], None, cx)
11398 });
11399 let rename_selection_range = match cursor_offset_in_rename_range
11400 .cmp(&cursor_offset_in_rename_range_end)
11401 {
11402 Ordering::Equal => {
11403 editor.select_all(&SelectAll, window, cx);
11404 return editor;
11405 }
11406 Ordering::Less => {
11407 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11408 }
11409 Ordering::Greater => {
11410 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11411 }
11412 };
11413 if rename_selection_range.end > old_name.len() {
11414 editor.select_all(&SelectAll, window, cx);
11415 } else {
11416 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11417 s.select_ranges([rename_selection_range]);
11418 });
11419 }
11420 editor
11421 });
11422 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11423 if e == &EditorEvent::Focused {
11424 cx.emit(EditorEvent::FocusedIn)
11425 }
11426 })
11427 .detach();
11428
11429 let write_highlights =
11430 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11431 let read_highlights =
11432 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11433 let ranges = write_highlights
11434 .iter()
11435 .flat_map(|(_, ranges)| ranges.iter())
11436 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11437 .cloned()
11438 .collect();
11439
11440 this.highlight_text::<Rename>(
11441 ranges,
11442 HighlightStyle {
11443 fade_out: Some(0.6),
11444 ..Default::default()
11445 },
11446 cx,
11447 );
11448 let rename_focus_handle = rename_editor.focus_handle(cx);
11449 window.focus(&rename_focus_handle);
11450 let block_id = this.insert_blocks(
11451 [BlockProperties {
11452 style: BlockStyle::Flex,
11453 placement: BlockPlacement::Below(range.start),
11454 height: 1,
11455 render: Arc::new({
11456 let rename_editor = rename_editor.clone();
11457 move |cx: &mut BlockContext| {
11458 let mut text_style = cx.editor_style.text.clone();
11459 if let Some(highlight_style) = old_highlight_id
11460 .and_then(|h| h.style(&cx.editor_style.syntax))
11461 {
11462 text_style = text_style.highlight(highlight_style);
11463 }
11464 div()
11465 .block_mouse_down()
11466 .pl(cx.anchor_x)
11467 .child(EditorElement::new(
11468 &rename_editor,
11469 EditorStyle {
11470 background: cx.theme().system().transparent,
11471 local_player: cx.editor_style.local_player,
11472 text: text_style,
11473 scrollbar_width: cx.editor_style.scrollbar_width,
11474 syntax: cx.editor_style.syntax.clone(),
11475 status: cx.editor_style.status.clone(),
11476 inlay_hints_style: HighlightStyle {
11477 font_weight: Some(FontWeight::BOLD),
11478 ..make_inlay_hints_style(cx.app)
11479 },
11480 inline_completion_styles: make_suggestion_styles(
11481 cx.app,
11482 ),
11483 ..EditorStyle::default()
11484 },
11485 ))
11486 .into_any_element()
11487 }
11488 }),
11489 priority: 0,
11490 }],
11491 Some(Autoscroll::fit()),
11492 cx,
11493 )[0];
11494 this.pending_rename = Some(RenameState {
11495 range,
11496 old_name,
11497 editor: rename_editor,
11498 block_id,
11499 });
11500 })?;
11501 }
11502
11503 Ok(())
11504 }))
11505 }
11506
11507 pub fn confirm_rename(
11508 &mut self,
11509 _: &ConfirmRename,
11510 window: &mut Window,
11511 cx: &mut Context<Self>,
11512 ) -> Option<Task<Result<()>>> {
11513 let rename = self.take_rename(false, window, cx)?;
11514 let workspace = self.workspace()?.downgrade();
11515 let (buffer, start) = self
11516 .buffer
11517 .read(cx)
11518 .text_anchor_for_position(rename.range.start, cx)?;
11519 let (end_buffer, _) = self
11520 .buffer
11521 .read(cx)
11522 .text_anchor_for_position(rename.range.end, cx)?;
11523 if buffer != end_buffer {
11524 return None;
11525 }
11526
11527 let old_name = rename.old_name;
11528 let new_name = rename.editor.read(cx).text(cx);
11529
11530 let rename = self.semantics_provider.as_ref()?.perform_rename(
11531 &buffer,
11532 start,
11533 new_name.clone(),
11534 cx,
11535 )?;
11536
11537 Some(cx.spawn_in(window, |editor, mut cx| async move {
11538 let project_transaction = rename.await?;
11539 Self::open_project_transaction(
11540 &editor,
11541 workspace,
11542 project_transaction,
11543 format!("Rename: {} → {}", old_name, new_name),
11544 cx.clone(),
11545 )
11546 .await?;
11547
11548 editor.update(&mut cx, |editor, cx| {
11549 editor.refresh_document_highlights(cx);
11550 })?;
11551 Ok(())
11552 }))
11553 }
11554
11555 fn take_rename(
11556 &mut self,
11557 moving_cursor: bool,
11558 window: &mut Window,
11559 cx: &mut Context<Self>,
11560 ) -> Option<RenameState> {
11561 let rename = self.pending_rename.take()?;
11562 if rename.editor.focus_handle(cx).is_focused(window) {
11563 window.focus(&self.focus_handle);
11564 }
11565
11566 self.remove_blocks(
11567 [rename.block_id].into_iter().collect(),
11568 Some(Autoscroll::fit()),
11569 cx,
11570 );
11571 self.clear_highlights::<Rename>(cx);
11572 self.show_local_selections = true;
11573
11574 if moving_cursor {
11575 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11576 editor.selections.newest::<usize>(cx).head()
11577 });
11578
11579 // Update the selection to match the position of the selection inside
11580 // the rename editor.
11581 let snapshot = self.buffer.read(cx).read(cx);
11582 let rename_range = rename.range.to_offset(&snapshot);
11583 let cursor_in_editor = snapshot
11584 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11585 .min(rename_range.end);
11586 drop(snapshot);
11587
11588 self.change_selections(None, window, cx, |s| {
11589 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11590 });
11591 } else {
11592 self.refresh_document_highlights(cx);
11593 }
11594
11595 Some(rename)
11596 }
11597
11598 pub fn pending_rename(&self) -> Option<&RenameState> {
11599 self.pending_rename.as_ref()
11600 }
11601
11602 fn format(
11603 &mut self,
11604 _: &Format,
11605 window: &mut Window,
11606 cx: &mut Context<Self>,
11607 ) -> Option<Task<Result<()>>> {
11608 let project = match &self.project {
11609 Some(project) => project.clone(),
11610 None => return None,
11611 };
11612
11613 Some(self.perform_format(
11614 project,
11615 FormatTrigger::Manual,
11616 FormatTarget::Buffers,
11617 window,
11618 cx,
11619 ))
11620 }
11621
11622 fn format_selections(
11623 &mut self,
11624 _: &FormatSelections,
11625 window: &mut Window,
11626 cx: &mut Context<Self>,
11627 ) -> Option<Task<Result<()>>> {
11628 let project = match &self.project {
11629 Some(project) => project.clone(),
11630 None => return None,
11631 };
11632
11633 let ranges = self
11634 .selections
11635 .all_adjusted(cx)
11636 .into_iter()
11637 .map(|selection| selection.range())
11638 .collect_vec();
11639
11640 Some(self.perform_format(
11641 project,
11642 FormatTrigger::Manual,
11643 FormatTarget::Ranges(ranges),
11644 window,
11645 cx,
11646 ))
11647 }
11648
11649 fn perform_format(
11650 &mut self,
11651 project: Entity<Project>,
11652 trigger: FormatTrigger,
11653 target: FormatTarget,
11654 window: &mut Window,
11655 cx: &mut Context<Self>,
11656 ) -> Task<Result<()>> {
11657 let buffer = self.buffer.clone();
11658 let (buffers, target) = match target {
11659 FormatTarget::Buffers => {
11660 let mut buffers = buffer.read(cx).all_buffers();
11661 if trigger == FormatTrigger::Save {
11662 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11663 }
11664 (buffers, LspFormatTarget::Buffers)
11665 }
11666 FormatTarget::Ranges(selection_ranges) => {
11667 let multi_buffer = buffer.read(cx);
11668 let snapshot = multi_buffer.read(cx);
11669 let mut buffers = HashSet::default();
11670 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11671 BTreeMap::new();
11672 for selection_range in selection_ranges {
11673 for (buffer, buffer_range, _) in
11674 snapshot.range_to_buffer_ranges(selection_range)
11675 {
11676 let buffer_id = buffer.remote_id();
11677 let start = buffer.anchor_before(buffer_range.start);
11678 let end = buffer.anchor_after(buffer_range.end);
11679 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11680 buffer_id_to_ranges
11681 .entry(buffer_id)
11682 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11683 .or_insert_with(|| vec![start..end]);
11684 }
11685 }
11686 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11687 }
11688 };
11689
11690 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11691 let format = project.update(cx, |project, cx| {
11692 project.format(buffers, target, true, trigger, cx)
11693 });
11694
11695 cx.spawn_in(window, |_, mut cx| async move {
11696 let transaction = futures::select_biased! {
11697 () = timeout => {
11698 log::warn!("timed out waiting for formatting");
11699 None
11700 }
11701 transaction = format.log_err().fuse() => transaction,
11702 };
11703
11704 buffer
11705 .update(&mut cx, |buffer, cx| {
11706 if let Some(transaction) = transaction {
11707 if !buffer.is_singleton() {
11708 buffer.push_transaction(&transaction.0, cx);
11709 }
11710 }
11711
11712 cx.notify();
11713 })
11714 .ok();
11715
11716 Ok(())
11717 })
11718 }
11719
11720 fn restart_language_server(
11721 &mut self,
11722 _: &RestartLanguageServer,
11723 _: &mut Window,
11724 cx: &mut Context<Self>,
11725 ) {
11726 if let Some(project) = self.project.clone() {
11727 self.buffer.update(cx, |multi_buffer, cx| {
11728 project.update(cx, |project, cx| {
11729 project.restart_language_servers_for_buffers(
11730 multi_buffer.all_buffers().into_iter().collect(),
11731 cx,
11732 );
11733 });
11734 })
11735 }
11736 }
11737
11738 fn cancel_language_server_work(
11739 workspace: &mut Workspace,
11740 _: &actions::CancelLanguageServerWork,
11741 _: &mut Window,
11742 cx: &mut Context<Workspace>,
11743 ) {
11744 let project = workspace.project();
11745 let buffers = workspace
11746 .active_item(cx)
11747 .and_then(|item| item.act_as::<Editor>(cx))
11748 .map_or(HashSet::default(), |editor| {
11749 editor.read(cx).buffer.read(cx).all_buffers()
11750 });
11751 project.update(cx, |project, cx| {
11752 project.cancel_language_server_work_for_buffers(buffers, cx);
11753 });
11754 }
11755
11756 fn show_character_palette(
11757 &mut self,
11758 _: &ShowCharacterPalette,
11759 window: &mut Window,
11760 _: &mut Context<Self>,
11761 ) {
11762 window.show_character_palette();
11763 }
11764
11765 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11766 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11767 let buffer = self.buffer.read(cx).snapshot(cx);
11768 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11769 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11770 let is_valid = buffer
11771 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11772 .any(|entry| {
11773 entry.diagnostic.is_primary
11774 && !entry.range.is_empty()
11775 && entry.range.start == primary_range_start
11776 && entry.diagnostic.message == active_diagnostics.primary_message
11777 });
11778
11779 if is_valid != active_diagnostics.is_valid {
11780 active_diagnostics.is_valid = is_valid;
11781 let mut new_styles = HashMap::default();
11782 for (block_id, diagnostic) in &active_diagnostics.blocks {
11783 new_styles.insert(
11784 *block_id,
11785 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11786 );
11787 }
11788 self.display_map.update(cx, |display_map, _cx| {
11789 display_map.replace_blocks(new_styles)
11790 });
11791 }
11792 }
11793 }
11794
11795 fn activate_diagnostics(
11796 &mut self,
11797 buffer_id: BufferId,
11798 group_id: usize,
11799 window: &mut Window,
11800 cx: &mut Context<Self>,
11801 ) {
11802 self.dismiss_diagnostics(cx);
11803 let snapshot = self.snapshot(window, cx);
11804 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11805 let buffer = self.buffer.read(cx).snapshot(cx);
11806
11807 let mut primary_range = None;
11808 let mut primary_message = None;
11809 let diagnostic_group = buffer
11810 .diagnostic_group(buffer_id, group_id)
11811 .filter_map(|entry| {
11812 let start = entry.range.start;
11813 let end = entry.range.end;
11814 if snapshot.is_line_folded(MultiBufferRow(start.row))
11815 && (start.row == end.row
11816 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11817 {
11818 return None;
11819 }
11820 if entry.diagnostic.is_primary {
11821 primary_range = Some(entry.range.clone());
11822 primary_message = Some(entry.diagnostic.message.clone());
11823 }
11824 Some(entry)
11825 })
11826 .collect::<Vec<_>>();
11827 let primary_range = primary_range?;
11828 let primary_message = primary_message?;
11829
11830 let blocks = display_map
11831 .insert_blocks(
11832 diagnostic_group.iter().map(|entry| {
11833 let diagnostic = entry.diagnostic.clone();
11834 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11835 BlockProperties {
11836 style: BlockStyle::Fixed,
11837 placement: BlockPlacement::Below(
11838 buffer.anchor_after(entry.range.start),
11839 ),
11840 height: message_height,
11841 render: diagnostic_block_renderer(diagnostic, None, true, true),
11842 priority: 0,
11843 }
11844 }),
11845 cx,
11846 )
11847 .into_iter()
11848 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11849 .collect();
11850
11851 Some(ActiveDiagnosticGroup {
11852 primary_range: buffer.anchor_before(primary_range.start)
11853 ..buffer.anchor_after(primary_range.end),
11854 primary_message,
11855 group_id,
11856 blocks,
11857 is_valid: true,
11858 })
11859 });
11860 }
11861
11862 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11863 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11864 self.display_map.update(cx, |display_map, cx| {
11865 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11866 });
11867 cx.notify();
11868 }
11869 }
11870
11871 pub fn set_selections_from_remote(
11872 &mut self,
11873 selections: Vec<Selection<Anchor>>,
11874 pending_selection: Option<Selection<Anchor>>,
11875 window: &mut Window,
11876 cx: &mut Context<Self>,
11877 ) {
11878 let old_cursor_position = self.selections.newest_anchor().head();
11879 self.selections.change_with(cx, |s| {
11880 s.select_anchors(selections);
11881 if let Some(pending_selection) = pending_selection {
11882 s.set_pending(pending_selection, SelectMode::Character);
11883 } else {
11884 s.clear_pending();
11885 }
11886 });
11887 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11888 }
11889
11890 fn push_to_selection_history(&mut self) {
11891 self.selection_history.push(SelectionHistoryEntry {
11892 selections: self.selections.disjoint_anchors(),
11893 select_next_state: self.select_next_state.clone(),
11894 select_prev_state: self.select_prev_state.clone(),
11895 add_selections_state: self.add_selections_state.clone(),
11896 });
11897 }
11898
11899 pub fn transact(
11900 &mut self,
11901 window: &mut Window,
11902 cx: &mut Context<Self>,
11903 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11904 ) -> Option<TransactionId> {
11905 self.start_transaction_at(Instant::now(), window, cx);
11906 update(self, window, cx);
11907 self.end_transaction_at(Instant::now(), cx)
11908 }
11909
11910 pub fn start_transaction_at(
11911 &mut self,
11912 now: Instant,
11913 window: &mut Window,
11914 cx: &mut Context<Self>,
11915 ) {
11916 self.end_selection(window, cx);
11917 if let Some(tx_id) = self
11918 .buffer
11919 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11920 {
11921 self.selection_history
11922 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11923 cx.emit(EditorEvent::TransactionBegun {
11924 transaction_id: tx_id,
11925 })
11926 }
11927 }
11928
11929 pub fn end_transaction_at(
11930 &mut self,
11931 now: Instant,
11932 cx: &mut Context<Self>,
11933 ) -> Option<TransactionId> {
11934 if let Some(transaction_id) = self
11935 .buffer
11936 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11937 {
11938 if let Some((_, end_selections)) =
11939 self.selection_history.transaction_mut(transaction_id)
11940 {
11941 *end_selections = Some(self.selections.disjoint_anchors());
11942 } else {
11943 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11944 }
11945
11946 cx.emit(EditorEvent::Edited { transaction_id });
11947 Some(transaction_id)
11948 } else {
11949 None
11950 }
11951 }
11952
11953 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11954 if self.selection_mark_mode {
11955 self.change_selections(None, window, cx, |s| {
11956 s.move_with(|_, sel| {
11957 sel.collapse_to(sel.head(), SelectionGoal::None);
11958 });
11959 })
11960 }
11961 self.selection_mark_mode = true;
11962 cx.notify();
11963 }
11964
11965 pub fn swap_selection_ends(
11966 &mut self,
11967 _: &actions::SwapSelectionEnds,
11968 window: &mut Window,
11969 cx: &mut Context<Self>,
11970 ) {
11971 self.change_selections(None, window, cx, |s| {
11972 s.move_with(|_, sel| {
11973 if sel.start != sel.end {
11974 sel.reversed = !sel.reversed
11975 }
11976 });
11977 });
11978 self.request_autoscroll(Autoscroll::newest(), cx);
11979 cx.notify();
11980 }
11981
11982 pub fn toggle_fold(
11983 &mut self,
11984 _: &actions::ToggleFold,
11985 window: &mut Window,
11986 cx: &mut Context<Self>,
11987 ) {
11988 if self.is_singleton(cx) {
11989 let selection = self.selections.newest::<Point>(cx);
11990
11991 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11992 let range = if selection.is_empty() {
11993 let point = selection.head().to_display_point(&display_map);
11994 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11995 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11996 .to_point(&display_map);
11997 start..end
11998 } else {
11999 selection.range()
12000 };
12001 if display_map.folds_in_range(range).next().is_some() {
12002 self.unfold_lines(&Default::default(), window, cx)
12003 } else {
12004 self.fold(&Default::default(), window, cx)
12005 }
12006 } else {
12007 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12008 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12009 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12010 .map(|(snapshot, _, _)| snapshot.remote_id())
12011 .collect();
12012
12013 for buffer_id in buffer_ids {
12014 if self.is_buffer_folded(buffer_id, cx) {
12015 self.unfold_buffer(buffer_id, cx);
12016 } else {
12017 self.fold_buffer(buffer_id, cx);
12018 }
12019 }
12020 }
12021 }
12022
12023 pub fn toggle_fold_recursive(
12024 &mut self,
12025 _: &actions::ToggleFoldRecursive,
12026 window: &mut Window,
12027 cx: &mut Context<Self>,
12028 ) {
12029 let selection = self.selections.newest::<Point>(cx);
12030
12031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12032 let range = if selection.is_empty() {
12033 let point = selection.head().to_display_point(&display_map);
12034 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12035 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12036 .to_point(&display_map);
12037 start..end
12038 } else {
12039 selection.range()
12040 };
12041 if display_map.folds_in_range(range).next().is_some() {
12042 self.unfold_recursive(&Default::default(), window, cx)
12043 } else {
12044 self.fold_recursive(&Default::default(), window, cx)
12045 }
12046 }
12047
12048 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12049 if self.is_singleton(cx) {
12050 let mut to_fold = Vec::new();
12051 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12052 let selections = self.selections.all_adjusted(cx);
12053
12054 for selection in selections {
12055 let range = selection.range().sorted();
12056 let buffer_start_row = range.start.row;
12057
12058 if range.start.row != range.end.row {
12059 let mut found = false;
12060 let mut row = range.start.row;
12061 while row <= range.end.row {
12062 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12063 {
12064 found = true;
12065 row = crease.range().end.row + 1;
12066 to_fold.push(crease);
12067 } else {
12068 row += 1
12069 }
12070 }
12071 if found {
12072 continue;
12073 }
12074 }
12075
12076 for row in (0..=range.start.row).rev() {
12077 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12078 if crease.range().end.row >= buffer_start_row {
12079 to_fold.push(crease);
12080 if row <= range.start.row {
12081 break;
12082 }
12083 }
12084 }
12085 }
12086 }
12087
12088 self.fold_creases(to_fold, true, window, cx);
12089 } else {
12090 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12091
12092 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12093 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12094 .map(|(snapshot, _, _)| snapshot.remote_id())
12095 .collect();
12096 for buffer_id in buffer_ids {
12097 self.fold_buffer(buffer_id, cx);
12098 }
12099 }
12100 }
12101
12102 fn fold_at_level(
12103 &mut self,
12104 fold_at: &FoldAtLevel,
12105 window: &mut Window,
12106 cx: &mut Context<Self>,
12107 ) {
12108 if !self.buffer.read(cx).is_singleton() {
12109 return;
12110 }
12111
12112 let fold_at_level = fold_at.0;
12113 let snapshot = self.buffer.read(cx).snapshot(cx);
12114 let mut to_fold = Vec::new();
12115 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12116
12117 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12118 while start_row < end_row {
12119 match self
12120 .snapshot(window, cx)
12121 .crease_for_buffer_row(MultiBufferRow(start_row))
12122 {
12123 Some(crease) => {
12124 let nested_start_row = crease.range().start.row + 1;
12125 let nested_end_row = crease.range().end.row;
12126
12127 if current_level < fold_at_level {
12128 stack.push((nested_start_row, nested_end_row, current_level + 1));
12129 } else if current_level == fold_at_level {
12130 to_fold.push(crease);
12131 }
12132
12133 start_row = nested_end_row + 1;
12134 }
12135 None => start_row += 1,
12136 }
12137 }
12138 }
12139
12140 self.fold_creases(to_fold, true, window, cx);
12141 }
12142
12143 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12144 if self.buffer.read(cx).is_singleton() {
12145 let mut fold_ranges = Vec::new();
12146 let snapshot = self.buffer.read(cx).snapshot(cx);
12147
12148 for row in 0..snapshot.max_row().0 {
12149 if let Some(foldable_range) = self
12150 .snapshot(window, cx)
12151 .crease_for_buffer_row(MultiBufferRow(row))
12152 {
12153 fold_ranges.push(foldable_range);
12154 }
12155 }
12156
12157 self.fold_creases(fold_ranges, true, window, cx);
12158 } else {
12159 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12160 editor
12161 .update_in(&mut cx, |editor, _, cx| {
12162 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12163 editor.fold_buffer(buffer_id, cx);
12164 }
12165 })
12166 .ok();
12167 });
12168 }
12169 }
12170
12171 pub fn fold_function_bodies(
12172 &mut self,
12173 _: &actions::FoldFunctionBodies,
12174 window: &mut Window,
12175 cx: &mut Context<Self>,
12176 ) {
12177 let snapshot = self.buffer.read(cx).snapshot(cx);
12178
12179 let ranges = snapshot
12180 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12181 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12182 .collect::<Vec<_>>();
12183
12184 let creases = ranges
12185 .into_iter()
12186 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12187 .collect();
12188
12189 self.fold_creases(creases, true, window, cx);
12190 }
12191
12192 pub fn fold_recursive(
12193 &mut self,
12194 _: &actions::FoldRecursive,
12195 window: &mut Window,
12196 cx: &mut Context<Self>,
12197 ) {
12198 let mut to_fold = Vec::new();
12199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12200 let selections = self.selections.all_adjusted(cx);
12201
12202 for selection in selections {
12203 let range = selection.range().sorted();
12204 let buffer_start_row = range.start.row;
12205
12206 if range.start.row != range.end.row {
12207 let mut found = false;
12208 for row in range.start.row..=range.end.row {
12209 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12210 found = true;
12211 to_fold.push(crease);
12212 }
12213 }
12214 if found {
12215 continue;
12216 }
12217 }
12218
12219 for row in (0..=range.start.row).rev() {
12220 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12221 if crease.range().end.row >= buffer_start_row {
12222 to_fold.push(crease);
12223 } else {
12224 break;
12225 }
12226 }
12227 }
12228 }
12229
12230 self.fold_creases(to_fold, true, window, cx);
12231 }
12232
12233 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12234 let buffer_row = fold_at.buffer_row;
12235 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12236
12237 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12238 let autoscroll = self
12239 .selections
12240 .all::<Point>(cx)
12241 .iter()
12242 .any(|selection| crease.range().overlaps(&selection.range()));
12243
12244 self.fold_creases(vec![crease], autoscroll, window, cx);
12245 }
12246 }
12247
12248 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12249 if self.is_singleton(cx) {
12250 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12251 let buffer = &display_map.buffer_snapshot;
12252 let selections = self.selections.all::<Point>(cx);
12253 let ranges = selections
12254 .iter()
12255 .map(|s| {
12256 let range = s.display_range(&display_map).sorted();
12257 let mut start = range.start.to_point(&display_map);
12258 let mut end = range.end.to_point(&display_map);
12259 start.column = 0;
12260 end.column = buffer.line_len(MultiBufferRow(end.row));
12261 start..end
12262 })
12263 .collect::<Vec<_>>();
12264
12265 self.unfold_ranges(&ranges, true, true, cx);
12266 } else {
12267 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12268 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12269 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12270 .map(|(snapshot, _, _)| snapshot.remote_id())
12271 .collect();
12272 for buffer_id in buffer_ids {
12273 self.unfold_buffer(buffer_id, cx);
12274 }
12275 }
12276 }
12277
12278 pub fn unfold_recursive(
12279 &mut self,
12280 _: &UnfoldRecursive,
12281 _window: &mut Window,
12282 cx: &mut Context<Self>,
12283 ) {
12284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12285 let selections = self.selections.all::<Point>(cx);
12286 let ranges = selections
12287 .iter()
12288 .map(|s| {
12289 let mut range = s.display_range(&display_map).sorted();
12290 *range.start.column_mut() = 0;
12291 *range.end.column_mut() = display_map.line_len(range.end.row());
12292 let start = range.start.to_point(&display_map);
12293 let end = range.end.to_point(&display_map);
12294 start..end
12295 })
12296 .collect::<Vec<_>>();
12297
12298 self.unfold_ranges(&ranges, true, true, cx);
12299 }
12300
12301 pub fn unfold_at(
12302 &mut self,
12303 unfold_at: &UnfoldAt,
12304 _window: &mut Window,
12305 cx: &mut Context<Self>,
12306 ) {
12307 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12308
12309 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12310 ..Point::new(
12311 unfold_at.buffer_row.0,
12312 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12313 );
12314
12315 let autoscroll = self
12316 .selections
12317 .all::<Point>(cx)
12318 .iter()
12319 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12320
12321 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12322 }
12323
12324 pub fn unfold_all(
12325 &mut self,
12326 _: &actions::UnfoldAll,
12327 _window: &mut Window,
12328 cx: &mut Context<Self>,
12329 ) {
12330 if self.buffer.read(cx).is_singleton() {
12331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12332 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12333 } else {
12334 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12335 editor
12336 .update(&mut cx, |editor, cx| {
12337 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12338 editor.unfold_buffer(buffer_id, cx);
12339 }
12340 })
12341 .ok();
12342 });
12343 }
12344 }
12345
12346 pub fn fold_selected_ranges(
12347 &mut self,
12348 _: &FoldSelectedRanges,
12349 window: &mut Window,
12350 cx: &mut Context<Self>,
12351 ) {
12352 let selections = self.selections.all::<Point>(cx);
12353 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12354 let line_mode = self.selections.line_mode;
12355 let ranges = selections
12356 .into_iter()
12357 .map(|s| {
12358 if line_mode {
12359 let start = Point::new(s.start.row, 0);
12360 let end = Point::new(
12361 s.end.row,
12362 display_map
12363 .buffer_snapshot
12364 .line_len(MultiBufferRow(s.end.row)),
12365 );
12366 Crease::simple(start..end, display_map.fold_placeholder.clone())
12367 } else {
12368 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12369 }
12370 })
12371 .collect::<Vec<_>>();
12372 self.fold_creases(ranges, true, window, cx);
12373 }
12374
12375 pub fn fold_ranges<T: ToOffset + Clone>(
12376 &mut self,
12377 ranges: Vec<Range<T>>,
12378 auto_scroll: bool,
12379 window: &mut Window,
12380 cx: &mut Context<Self>,
12381 ) {
12382 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12383 let ranges = ranges
12384 .into_iter()
12385 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12386 .collect::<Vec<_>>();
12387 self.fold_creases(ranges, auto_scroll, window, cx);
12388 }
12389
12390 pub fn fold_creases<T: ToOffset + Clone>(
12391 &mut self,
12392 creases: Vec<Crease<T>>,
12393 auto_scroll: bool,
12394 window: &mut Window,
12395 cx: &mut Context<Self>,
12396 ) {
12397 if creases.is_empty() {
12398 return;
12399 }
12400
12401 let mut buffers_affected = HashSet::default();
12402 let multi_buffer = self.buffer().read(cx);
12403 for crease in &creases {
12404 if let Some((_, buffer, _)) =
12405 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12406 {
12407 buffers_affected.insert(buffer.read(cx).remote_id());
12408 };
12409 }
12410
12411 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12412
12413 if auto_scroll {
12414 self.request_autoscroll(Autoscroll::fit(), cx);
12415 }
12416
12417 cx.notify();
12418
12419 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12420 // Clear diagnostics block when folding a range that contains it.
12421 let snapshot = self.snapshot(window, cx);
12422 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12423 drop(snapshot);
12424 self.active_diagnostics = Some(active_diagnostics);
12425 self.dismiss_diagnostics(cx);
12426 } else {
12427 self.active_diagnostics = Some(active_diagnostics);
12428 }
12429 }
12430
12431 self.scrollbar_marker_state.dirty = true;
12432 }
12433
12434 /// Removes any folds whose ranges intersect any of the given ranges.
12435 pub fn unfold_ranges<T: ToOffset + Clone>(
12436 &mut self,
12437 ranges: &[Range<T>],
12438 inclusive: bool,
12439 auto_scroll: bool,
12440 cx: &mut Context<Self>,
12441 ) {
12442 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12443 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12444 });
12445 }
12446
12447 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12448 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12449 return;
12450 }
12451 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12452 self.display_map
12453 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12454 cx.emit(EditorEvent::BufferFoldToggled {
12455 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12456 folded: true,
12457 });
12458 cx.notify();
12459 }
12460
12461 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12462 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12463 return;
12464 }
12465 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12466 self.display_map.update(cx, |display_map, cx| {
12467 display_map.unfold_buffer(buffer_id, cx);
12468 });
12469 cx.emit(EditorEvent::BufferFoldToggled {
12470 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12471 folded: false,
12472 });
12473 cx.notify();
12474 }
12475
12476 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12477 self.display_map.read(cx).is_buffer_folded(buffer)
12478 }
12479
12480 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12481 self.display_map.read(cx).folded_buffers()
12482 }
12483
12484 /// Removes any folds with the given ranges.
12485 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12486 &mut self,
12487 ranges: &[Range<T>],
12488 type_id: TypeId,
12489 auto_scroll: bool,
12490 cx: &mut Context<Self>,
12491 ) {
12492 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12493 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12494 });
12495 }
12496
12497 fn remove_folds_with<T: ToOffset + Clone>(
12498 &mut self,
12499 ranges: &[Range<T>],
12500 auto_scroll: bool,
12501 cx: &mut Context<Self>,
12502 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12503 ) {
12504 if ranges.is_empty() {
12505 return;
12506 }
12507
12508 let mut buffers_affected = HashSet::default();
12509 let multi_buffer = self.buffer().read(cx);
12510 for range in ranges {
12511 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12512 buffers_affected.insert(buffer.read(cx).remote_id());
12513 };
12514 }
12515
12516 self.display_map.update(cx, update);
12517
12518 if auto_scroll {
12519 self.request_autoscroll(Autoscroll::fit(), cx);
12520 }
12521
12522 cx.notify();
12523 self.scrollbar_marker_state.dirty = true;
12524 self.active_indent_guides_state.dirty = true;
12525 }
12526
12527 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12528 self.display_map.read(cx).fold_placeholder.clone()
12529 }
12530
12531 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12532 self.buffer.update(cx, |buffer, cx| {
12533 buffer.set_all_diff_hunks_expanded(cx);
12534 });
12535 }
12536
12537 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12538 self.distinguish_unstaged_diff_hunks = true;
12539 }
12540
12541 pub fn expand_all_diff_hunks(
12542 &mut self,
12543 _: &ExpandAllHunkDiffs,
12544 _window: &mut Window,
12545 cx: &mut Context<Self>,
12546 ) {
12547 self.buffer.update(cx, |buffer, cx| {
12548 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12549 });
12550 }
12551
12552 pub fn toggle_selected_diff_hunks(
12553 &mut self,
12554 _: &ToggleSelectedDiffHunks,
12555 _window: &mut Window,
12556 cx: &mut Context<Self>,
12557 ) {
12558 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12559 self.toggle_diff_hunks_in_ranges(ranges, cx);
12560 }
12561
12562 fn diff_hunks_in_ranges<'a>(
12563 &'a self,
12564 ranges: &'a [Range<Anchor>],
12565 buffer: &'a MultiBufferSnapshot,
12566 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12567 ranges.iter().flat_map(move |range| {
12568 let end_excerpt_id = range.end.excerpt_id;
12569 let range = range.to_point(buffer);
12570 let mut peek_end = range.end;
12571 if range.end.row < buffer.max_row().0 {
12572 peek_end = Point::new(range.end.row + 1, 0);
12573 }
12574 buffer
12575 .diff_hunks_in_range(range.start..peek_end)
12576 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12577 })
12578 }
12579
12580 pub fn has_stageable_diff_hunks_in_ranges(
12581 &self,
12582 ranges: &[Range<Anchor>],
12583 snapshot: &MultiBufferSnapshot,
12584 ) -> bool {
12585 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12586 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12587 }
12588
12589 pub fn toggle_staged_selected_diff_hunks(
12590 &mut self,
12591 _: &::git::ToggleStaged,
12592 _window: &mut Window,
12593 cx: &mut Context<Self>,
12594 ) {
12595 let snapshot = self.buffer.read(cx).snapshot(cx);
12596 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12597 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12598 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12599 }
12600
12601 pub fn stage_and_next(
12602 &mut self,
12603 _: &::git::StageAndNext,
12604 window: &mut Window,
12605 cx: &mut Context<Self>,
12606 ) {
12607 let head = self.selections.newest_anchor().head();
12608 self.stage_or_unstage_diff_hunks(true, &[head..head], cx);
12609 self.go_to_next_hunk(&Default::default(), window, cx);
12610 }
12611
12612 pub fn unstage_and_next(
12613 &mut self,
12614 _: &::git::UnstageAndNext,
12615 window: &mut Window,
12616 cx: &mut Context<Self>,
12617 ) {
12618 let head = self.selections.newest_anchor().head();
12619 self.stage_or_unstage_diff_hunks(false, &[head..head], cx);
12620 self.go_to_next_hunk(&Default::default(), window, cx);
12621 }
12622
12623 pub fn stage_or_unstage_diff_hunks(
12624 &mut self,
12625 stage: bool,
12626 ranges: &[Range<Anchor>],
12627 cx: &mut Context<Self>,
12628 ) {
12629 let snapshot = self.buffer.read(cx).snapshot(cx);
12630 let Some(project) = &self.project else {
12631 return;
12632 };
12633
12634 let chunk_by = self
12635 .diff_hunks_in_ranges(&ranges, &snapshot)
12636 .chunk_by(|hunk| hunk.buffer_id);
12637 for (buffer_id, hunks) in &chunk_by {
12638 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12639 }
12640 }
12641
12642 fn do_stage_or_unstage(
12643 project: &Entity<Project>,
12644 stage: bool,
12645 buffer_id: BufferId,
12646 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12647 snapshot: &MultiBufferSnapshot,
12648 cx: &mut Context<Self>,
12649 ) {
12650 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12651 log::debug!("no buffer for id");
12652 return;
12653 };
12654 let buffer = buffer.read(cx).snapshot();
12655 let Some((repo, path)) = project
12656 .read(cx)
12657 .repository_and_path_for_buffer_id(buffer_id, cx)
12658 else {
12659 log::debug!("no git repo for buffer id");
12660 return;
12661 };
12662 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12663 log::debug!("no diff for buffer id");
12664 return;
12665 };
12666 let Some(secondary_diff) = diff.secondary_diff() else {
12667 log::debug!("no secondary diff for buffer id");
12668 return;
12669 };
12670
12671 let edits = diff.secondary_edits_for_stage_or_unstage(
12672 stage,
12673 hunks.filter_map(|hunk| {
12674 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12675 return None;
12676 } else if !stage
12677 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12678 {
12679 return None;
12680 }
12681 Some((
12682 hunk.diff_base_byte_range.clone(),
12683 hunk.secondary_diff_base_byte_range.clone(),
12684 hunk.buffer_range.clone(),
12685 ))
12686 }),
12687 &buffer,
12688 );
12689
12690 let Some(index_base) = secondary_diff
12691 .base_text()
12692 .map(|snapshot| snapshot.text.as_rope().clone())
12693 else {
12694 log::debug!("no index base");
12695 return;
12696 };
12697 let index_buffer = cx.new(|cx| {
12698 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12699 });
12700 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12701 index_buffer.edit(edits, None, cx);
12702 index_buffer.snapshot().as_rope().to_string()
12703 });
12704 let new_index_text = if new_index_text.is_empty()
12705 && (diff.is_single_insertion
12706 || buffer
12707 .file()
12708 .map_or(false, |file| file.disk_state() == DiskState::New))
12709 {
12710 log::debug!("removing from index");
12711 None
12712 } else {
12713 Some(new_index_text)
12714 };
12715
12716 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12717 }
12718
12719 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12720 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12721 self.buffer
12722 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12723 }
12724
12725 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12726 self.buffer.update(cx, |buffer, cx| {
12727 let ranges = vec![Anchor::min()..Anchor::max()];
12728 if !buffer.all_diff_hunks_expanded()
12729 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12730 {
12731 buffer.collapse_diff_hunks(ranges, cx);
12732 true
12733 } else {
12734 false
12735 }
12736 })
12737 }
12738
12739 fn toggle_diff_hunks_in_ranges(
12740 &mut self,
12741 ranges: Vec<Range<Anchor>>,
12742 cx: &mut Context<'_, Editor>,
12743 ) {
12744 self.buffer.update(cx, |buffer, cx| {
12745 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12746 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12747 })
12748 }
12749
12750 fn toggle_diff_hunks_in_ranges_narrow(
12751 &mut self,
12752 ranges: Vec<Range<Anchor>>,
12753 cx: &mut Context<'_, Editor>,
12754 ) {
12755 self.buffer.update(cx, |buffer, cx| {
12756 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12757 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12758 })
12759 }
12760
12761 pub(crate) fn apply_all_diff_hunks(
12762 &mut self,
12763 _: &ApplyAllDiffHunks,
12764 window: &mut Window,
12765 cx: &mut Context<Self>,
12766 ) {
12767 let buffers = self.buffer.read(cx).all_buffers();
12768 for branch_buffer in buffers {
12769 branch_buffer.update(cx, |branch_buffer, cx| {
12770 branch_buffer.merge_into_base(Vec::new(), cx);
12771 });
12772 }
12773
12774 if let Some(project) = self.project.clone() {
12775 self.save(true, project, window, cx).detach_and_log_err(cx);
12776 }
12777 }
12778
12779 pub(crate) fn apply_selected_diff_hunks(
12780 &mut self,
12781 _: &ApplyDiffHunk,
12782 window: &mut Window,
12783 cx: &mut Context<Self>,
12784 ) {
12785 let snapshot = self.snapshot(window, cx);
12786 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12787 let mut ranges_by_buffer = HashMap::default();
12788 self.transact(window, cx, |editor, _window, cx| {
12789 for hunk in hunks {
12790 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12791 ranges_by_buffer
12792 .entry(buffer.clone())
12793 .or_insert_with(Vec::new)
12794 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12795 }
12796 }
12797
12798 for (buffer, ranges) in ranges_by_buffer {
12799 buffer.update(cx, |buffer, cx| {
12800 buffer.merge_into_base(ranges, cx);
12801 });
12802 }
12803 });
12804
12805 if let Some(project) = self.project.clone() {
12806 self.save(true, project, window, cx).detach_and_log_err(cx);
12807 }
12808 }
12809
12810 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12811 if hovered != self.gutter_hovered {
12812 self.gutter_hovered = hovered;
12813 cx.notify();
12814 }
12815 }
12816
12817 pub fn insert_blocks(
12818 &mut self,
12819 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12820 autoscroll: Option<Autoscroll>,
12821 cx: &mut Context<Self>,
12822 ) -> Vec<CustomBlockId> {
12823 let blocks = self
12824 .display_map
12825 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12826 if let Some(autoscroll) = autoscroll {
12827 self.request_autoscroll(autoscroll, cx);
12828 }
12829 cx.notify();
12830 blocks
12831 }
12832
12833 pub fn resize_blocks(
12834 &mut self,
12835 heights: HashMap<CustomBlockId, u32>,
12836 autoscroll: Option<Autoscroll>,
12837 cx: &mut Context<Self>,
12838 ) {
12839 self.display_map
12840 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12841 if let Some(autoscroll) = autoscroll {
12842 self.request_autoscroll(autoscroll, cx);
12843 }
12844 cx.notify();
12845 }
12846
12847 pub fn replace_blocks(
12848 &mut self,
12849 renderers: HashMap<CustomBlockId, RenderBlock>,
12850 autoscroll: Option<Autoscroll>,
12851 cx: &mut Context<Self>,
12852 ) {
12853 self.display_map
12854 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12855 if let Some(autoscroll) = autoscroll {
12856 self.request_autoscroll(autoscroll, cx);
12857 }
12858 cx.notify();
12859 }
12860
12861 pub fn remove_blocks(
12862 &mut self,
12863 block_ids: HashSet<CustomBlockId>,
12864 autoscroll: Option<Autoscroll>,
12865 cx: &mut Context<Self>,
12866 ) {
12867 self.display_map.update(cx, |display_map, cx| {
12868 display_map.remove_blocks(block_ids, cx)
12869 });
12870 if let Some(autoscroll) = autoscroll {
12871 self.request_autoscroll(autoscroll, cx);
12872 }
12873 cx.notify();
12874 }
12875
12876 pub fn row_for_block(
12877 &self,
12878 block_id: CustomBlockId,
12879 cx: &mut Context<Self>,
12880 ) -> Option<DisplayRow> {
12881 self.display_map
12882 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12883 }
12884
12885 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12886 self.focused_block = Some(focused_block);
12887 }
12888
12889 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12890 self.focused_block.take()
12891 }
12892
12893 pub fn insert_creases(
12894 &mut self,
12895 creases: impl IntoIterator<Item = Crease<Anchor>>,
12896 cx: &mut Context<Self>,
12897 ) -> Vec<CreaseId> {
12898 self.display_map
12899 .update(cx, |map, cx| map.insert_creases(creases, cx))
12900 }
12901
12902 pub fn remove_creases(
12903 &mut self,
12904 ids: impl IntoIterator<Item = CreaseId>,
12905 cx: &mut Context<Self>,
12906 ) {
12907 self.display_map
12908 .update(cx, |map, cx| map.remove_creases(ids, cx));
12909 }
12910
12911 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12912 self.display_map
12913 .update(cx, |map, cx| map.snapshot(cx))
12914 .longest_row()
12915 }
12916
12917 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12918 self.display_map
12919 .update(cx, |map, cx| map.snapshot(cx))
12920 .max_point()
12921 }
12922
12923 pub fn text(&self, cx: &App) -> String {
12924 self.buffer.read(cx).read(cx).text()
12925 }
12926
12927 pub fn is_empty(&self, cx: &App) -> bool {
12928 self.buffer.read(cx).read(cx).is_empty()
12929 }
12930
12931 pub fn text_option(&self, cx: &App) -> Option<String> {
12932 let text = self.text(cx);
12933 let text = text.trim();
12934
12935 if text.is_empty() {
12936 return None;
12937 }
12938
12939 Some(text.to_string())
12940 }
12941
12942 pub fn set_text(
12943 &mut self,
12944 text: impl Into<Arc<str>>,
12945 window: &mut Window,
12946 cx: &mut Context<Self>,
12947 ) {
12948 self.transact(window, cx, |this, _, cx| {
12949 this.buffer
12950 .read(cx)
12951 .as_singleton()
12952 .expect("you can only call set_text on editors for singleton buffers")
12953 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12954 });
12955 }
12956
12957 pub fn display_text(&self, cx: &mut App) -> String {
12958 self.display_map
12959 .update(cx, |map, cx| map.snapshot(cx))
12960 .text()
12961 }
12962
12963 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12964 let mut wrap_guides = smallvec::smallvec![];
12965
12966 if self.show_wrap_guides == Some(false) {
12967 return wrap_guides;
12968 }
12969
12970 let settings = self.buffer.read(cx).settings_at(0, cx);
12971 if settings.show_wrap_guides {
12972 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12973 wrap_guides.push((soft_wrap as usize, true));
12974 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12975 wrap_guides.push((soft_wrap as usize, true));
12976 }
12977 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12978 }
12979
12980 wrap_guides
12981 }
12982
12983 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12984 let settings = self.buffer.read(cx).settings_at(0, cx);
12985 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12986 match mode {
12987 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12988 SoftWrap::None
12989 }
12990 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12991 language_settings::SoftWrap::PreferredLineLength => {
12992 SoftWrap::Column(settings.preferred_line_length)
12993 }
12994 language_settings::SoftWrap::Bounded => {
12995 SoftWrap::Bounded(settings.preferred_line_length)
12996 }
12997 }
12998 }
12999
13000 pub fn set_soft_wrap_mode(
13001 &mut self,
13002 mode: language_settings::SoftWrap,
13003
13004 cx: &mut Context<Self>,
13005 ) {
13006 self.soft_wrap_mode_override = Some(mode);
13007 cx.notify();
13008 }
13009
13010 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13011 self.text_style_refinement = Some(style);
13012 }
13013
13014 /// called by the Element so we know what style we were most recently rendered with.
13015 pub(crate) fn set_style(
13016 &mut self,
13017 style: EditorStyle,
13018 window: &mut Window,
13019 cx: &mut Context<Self>,
13020 ) {
13021 let rem_size = window.rem_size();
13022 self.display_map.update(cx, |map, cx| {
13023 map.set_font(
13024 style.text.font(),
13025 style.text.font_size.to_pixels(rem_size),
13026 cx,
13027 )
13028 });
13029 self.style = Some(style);
13030 }
13031
13032 pub fn style(&self) -> Option<&EditorStyle> {
13033 self.style.as_ref()
13034 }
13035
13036 // Called by the element. This method is not designed to be called outside of the editor
13037 // element's layout code because it does not notify when rewrapping is computed synchronously.
13038 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13039 self.display_map
13040 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13041 }
13042
13043 pub fn set_soft_wrap(&mut self) {
13044 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13045 }
13046
13047 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13048 if self.soft_wrap_mode_override.is_some() {
13049 self.soft_wrap_mode_override.take();
13050 } else {
13051 let soft_wrap = match self.soft_wrap_mode(cx) {
13052 SoftWrap::GitDiff => return,
13053 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13054 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13055 language_settings::SoftWrap::None
13056 }
13057 };
13058 self.soft_wrap_mode_override = Some(soft_wrap);
13059 }
13060 cx.notify();
13061 }
13062
13063 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13064 let Some(workspace) = self.workspace() else {
13065 return;
13066 };
13067 let fs = workspace.read(cx).app_state().fs.clone();
13068 let current_show = TabBarSettings::get_global(cx).show;
13069 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13070 setting.show = Some(!current_show);
13071 });
13072 }
13073
13074 pub fn toggle_indent_guides(
13075 &mut self,
13076 _: &ToggleIndentGuides,
13077 _: &mut Window,
13078 cx: &mut Context<Self>,
13079 ) {
13080 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13081 self.buffer
13082 .read(cx)
13083 .settings_at(0, cx)
13084 .indent_guides
13085 .enabled
13086 });
13087 self.show_indent_guides = Some(!currently_enabled);
13088 cx.notify();
13089 }
13090
13091 fn should_show_indent_guides(&self) -> Option<bool> {
13092 self.show_indent_guides
13093 }
13094
13095 pub fn toggle_line_numbers(
13096 &mut self,
13097 _: &ToggleLineNumbers,
13098 _: &mut Window,
13099 cx: &mut Context<Self>,
13100 ) {
13101 let mut editor_settings = EditorSettings::get_global(cx).clone();
13102 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13103 EditorSettings::override_global(editor_settings, cx);
13104 }
13105
13106 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13107 self.use_relative_line_numbers
13108 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13109 }
13110
13111 pub fn toggle_relative_line_numbers(
13112 &mut self,
13113 _: &ToggleRelativeLineNumbers,
13114 _: &mut Window,
13115 cx: &mut Context<Self>,
13116 ) {
13117 let is_relative = self.should_use_relative_line_numbers(cx);
13118 self.set_relative_line_number(Some(!is_relative), cx)
13119 }
13120
13121 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13122 self.use_relative_line_numbers = is_relative;
13123 cx.notify();
13124 }
13125
13126 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13127 self.show_gutter = show_gutter;
13128 cx.notify();
13129 }
13130
13131 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13132 self.show_scrollbars = show_scrollbars;
13133 cx.notify();
13134 }
13135
13136 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13137 self.show_line_numbers = Some(show_line_numbers);
13138 cx.notify();
13139 }
13140
13141 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13142 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13143 cx.notify();
13144 }
13145
13146 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13147 self.show_code_actions = Some(show_code_actions);
13148 cx.notify();
13149 }
13150
13151 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13152 self.show_runnables = Some(show_runnables);
13153 cx.notify();
13154 }
13155
13156 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13157 if self.display_map.read(cx).masked != masked {
13158 self.display_map.update(cx, |map, _| map.masked = masked);
13159 }
13160 cx.notify()
13161 }
13162
13163 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13164 self.show_wrap_guides = Some(show_wrap_guides);
13165 cx.notify();
13166 }
13167
13168 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13169 self.show_indent_guides = Some(show_indent_guides);
13170 cx.notify();
13171 }
13172
13173 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13174 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13175 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13176 if let Some(dir) = file.abs_path(cx).parent() {
13177 return Some(dir.to_owned());
13178 }
13179 }
13180
13181 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13182 return Some(project_path.path.to_path_buf());
13183 }
13184 }
13185
13186 None
13187 }
13188
13189 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13190 self.active_excerpt(cx)?
13191 .1
13192 .read(cx)
13193 .file()
13194 .and_then(|f| f.as_local())
13195 }
13196
13197 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13198 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13199 let buffer = buffer.read(cx);
13200 if let Some(project_path) = buffer.project_path(cx) {
13201 let project = self.project.as_ref()?.read(cx);
13202 project.absolute_path(&project_path, cx)
13203 } else {
13204 buffer
13205 .file()
13206 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13207 }
13208 })
13209 }
13210
13211 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13212 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13213 let project_path = buffer.read(cx).project_path(cx)?;
13214 let project = self.project.as_ref()?.read(cx);
13215 let entry = project.entry_for_path(&project_path, cx)?;
13216 let path = entry.path.to_path_buf();
13217 Some(path)
13218 })
13219 }
13220
13221 pub fn reveal_in_finder(
13222 &mut self,
13223 _: &RevealInFileManager,
13224 _window: &mut Window,
13225 cx: &mut Context<Self>,
13226 ) {
13227 if let Some(target) = self.target_file(cx) {
13228 cx.reveal_path(&target.abs_path(cx));
13229 }
13230 }
13231
13232 pub fn copy_path(
13233 &mut self,
13234 _: &zed_actions::workspace::CopyPath,
13235 _window: &mut Window,
13236 cx: &mut Context<Self>,
13237 ) {
13238 if let Some(path) = self.target_file_abs_path(cx) {
13239 if let Some(path) = path.to_str() {
13240 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13241 }
13242 }
13243 }
13244
13245 pub fn copy_relative_path(
13246 &mut self,
13247 _: &zed_actions::workspace::CopyRelativePath,
13248 _window: &mut Window,
13249 cx: &mut Context<Self>,
13250 ) {
13251 if let Some(path) = self.target_file_path(cx) {
13252 if let Some(path) = path.to_str() {
13253 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13254 }
13255 }
13256 }
13257
13258 pub fn copy_file_name_without_extension(
13259 &mut self,
13260 _: &CopyFileNameWithoutExtension,
13261 _: &mut Window,
13262 cx: &mut Context<Self>,
13263 ) {
13264 if let Some(file) = self.target_file(cx) {
13265 if let Some(file_stem) = file.path().file_stem() {
13266 if let Some(name) = file_stem.to_str() {
13267 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13268 }
13269 }
13270 }
13271 }
13272
13273 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13274 if let Some(file) = self.target_file(cx) {
13275 if let Some(file_name) = file.path().file_name() {
13276 if let Some(name) = file_name.to_str() {
13277 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13278 }
13279 }
13280 }
13281 }
13282
13283 pub fn toggle_git_blame(
13284 &mut self,
13285 _: &ToggleGitBlame,
13286 window: &mut Window,
13287 cx: &mut Context<Self>,
13288 ) {
13289 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13290
13291 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13292 self.start_git_blame(true, window, cx);
13293 }
13294
13295 cx.notify();
13296 }
13297
13298 pub fn toggle_git_blame_inline(
13299 &mut self,
13300 _: &ToggleGitBlameInline,
13301 window: &mut Window,
13302 cx: &mut Context<Self>,
13303 ) {
13304 self.toggle_git_blame_inline_internal(true, window, cx);
13305 cx.notify();
13306 }
13307
13308 pub fn git_blame_inline_enabled(&self) -> bool {
13309 self.git_blame_inline_enabled
13310 }
13311
13312 pub fn toggle_selection_menu(
13313 &mut self,
13314 _: &ToggleSelectionMenu,
13315 _: &mut Window,
13316 cx: &mut Context<Self>,
13317 ) {
13318 self.show_selection_menu = self
13319 .show_selection_menu
13320 .map(|show_selections_menu| !show_selections_menu)
13321 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13322
13323 cx.notify();
13324 }
13325
13326 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13327 self.show_selection_menu
13328 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13329 }
13330
13331 fn start_git_blame(
13332 &mut self,
13333 user_triggered: bool,
13334 window: &mut Window,
13335 cx: &mut Context<Self>,
13336 ) {
13337 if let Some(project) = self.project.as_ref() {
13338 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13339 return;
13340 };
13341
13342 if buffer.read(cx).file().is_none() {
13343 return;
13344 }
13345
13346 let focused = self.focus_handle(cx).contains_focused(window, cx);
13347
13348 let project = project.clone();
13349 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13350 self.blame_subscription =
13351 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13352 self.blame = Some(blame);
13353 }
13354 }
13355
13356 fn toggle_git_blame_inline_internal(
13357 &mut self,
13358 user_triggered: bool,
13359 window: &mut Window,
13360 cx: &mut Context<Self>,
13361 ) {
13362 if self.git_blame_inline_enabled {
13363 self.git_blame_inline_enabled = false;
13364 self.show_git_blame_inline = false;
13365 self.show_git_blame_inline_delay_task.take();
13366 } else {
13367 self.git_blame_inline_enabled = true;
13368 self.start_git_blame_inline(user_triggered, window, cx);
13369 }
13370
13371 cx.notify();
13372 }
13373
13374 fn start_git_blame_inline(
13375 &mut self,
13376 user_triggered: bool,
13377 window: &mut Window,
13378 cx: &mut Context<Self>,
13379 ) {
13380 self.start_git_blame(user_triggered, window, cx);
13381
13382 if ProjectSettings::get_global(cx)
13383 .git
13384 .inline_blame_delay()
13385 .is_some()
13386 {
13387 self.start_inline_blame_timer(window, cx);
13388 } else {
13389 self.show_git_blame_inline = true
13390 }
13391 }
13392
13393 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13394 self.blame.as_ref()
13395 }
13396
13397 pub fn show_git_blame_gutter(&self) -> bool {
13398 self.show_git_blame_gutter
13399 }
13400
13401 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13402 self.show_git_blame_gutter && self.has_blame_entries(cx)
13403 }
13404
13405 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13406 self.show_git_blame_inline
13407 && (self.focus_handle.is_focused(window)
13408 || self
13409 .git_blame_inline_tooltip
13410 .as_ref()
13411 .and_then(|t| t.upgrade())
13412 .is_some())
13413 && !self.newest_selection_head_on_empty_line(cx)
13414 && self.has_blame_entries(cx)
13415 }
13416
13417 fn has_blame_entries(&self, cx: &App) -> bool {
13418 self.blame()
13419 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13420 }
13421
13422 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13423 let cursor_anchor = self.selections.newest_anchor().head();
13424
13425 let snapshot = self.buffer.read(cx).snapshot(cx);
13426 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13427
13428 snapshot.line_len(buffer_row) == 0
13429 }
13430
13431 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13432 let buffer_and_selection = maybe!({
13433 let selection = self.selections.newest::<Point>(cx);
13434 let selection_range = selection.range();
13435
13436 let multi_buffer = self.buffer().read(cx);
13437 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13438 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13439
13440 let (buffer, range, _) = if selection.reversed {
13441 buffer_ranges.first()
13442 } else {
13443 buffer_ranges.last()
13444 }?;
13445
13446 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13447 ..text::ToPoint::to_point(&range.end, &buffer).row;
13448 Some((
13449 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13450 selection,
13451 ))
13452 });
13453
13454 let Some((buffer, selection)) = buffer_and_selection else {
13455 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13456 };
13457
13458 let Some(project) = self.project.as_ref() else {
13459 return Task::ready(Err(anyhow!("editor does not have project")));
13460 };
13461
13462 project.update(cx, |project, cx| {
13463 project.get_permalink_to_line(&buffer, selection, cx)
13464 })
13465 }
13466
13467 pub fn copy_permalink_to_line(
13468 &mut self,
13469 _: &CopyPermalinkToLine,
13470 window: &mut Window,
13471 cx: &mut Context<Self>,
13472 ) {
13473 let permalink_task = self.get_permalink_to_line(cx);
13474 let workspace = self.workspace();
13475
13476 cx.spawn_in(window, |_, mut cx| async move {
13477 match permalink_task.await {
13478 Ok(permalink) => {
13479 cx.update(|_, cx| {
13480 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13481 })
13482 .ok();
13483 }
13484 Err(err) => {
13485 let message = format!("Failed to copy permalink: {err}");
13486
13487 Err::<(), anyhow::Error>(err).log_err();
13488
13489 if let Some(workspace) = workspace {
13490 workspace
13491 .update_in(&mut cx, |workspace, _, cx| {
13492 struct CopyPermalinkToLine;
13493
13494 workspace.show_toast(
13495 Toast::new(
13496 NotificationId::unique::<CopyPermalinkToLine>(),
13497 message,
13498 ),
13499 cx,
13500 )
13501 })
13502 .ok();
13503 }
13504 }
13505 }
13506 })
13507 .detach();
13508 }
13509
13510 pub fn copy_file_location(
13511 &mut self,
13512 _: &CopyFileLocation,
13513 _: &mut Window,
13514 cx: &mut Context<Self>,
13515 ) {
13516 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13517 if let Some(file) = self.target_file(cx) {
13518 if let Some(path) = file.path().to_str() {
13519 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13520 }
13521 }
13522 }
13523
13524 pub fn open_permalink_to_line(
13525 &mut self,
13526 _: &OpenPermalinkToLine,
13527 window: &mut Window,
13528 cx: &mut Context<Self>,
13529 ) {
13530 let permalink_task = self.get_permalink_to_line(cx);
13531 let workspace = self.workspace();
13532
13533 cx.spawn_in(window, |_, mut cx| async move {
13534 match permalink_task.await {
13535 Ok(permalink) => {
13536 cx.update(|_, cx| {
13537 cx.open_url(permalink.as_ref());
13538 })
13539 .ok();
13540 }
13541 Err(err) => {
13542 let message = format!("Failed to open permalink: {err}");
13543
13544 Err::<(), anyhow::Error>(err).log_err();
13545
13546 if let Some(workspace) = workspace {
13547 workspace
13548 .update(&mut cx, |workspace, cx| {
13549 struct OpenPermalinkToLine;
13550
13551 workspace.show_toast(
13552 Toast::new(
13553 NotificationId::unique::<OpenPermalinkToLine>(),
13554 message,
13555 ),
13556 cx,
13557 )
13558 })
13559 .ok();
13560 }
13561 }
13562 }
13563 })
13564 .detach();
13565 }
13566
13567 pub fn insert_uuid_v4(
13568 &mut self,
13569 _: &InsertUuidV4,
13570 window: &mut Window,
13571 cx: &mut Context<Self>,
13572 ) {
13573 self.insert_uuid(UuidVersion::V4, window, cx);
13574 }
13575
13576 pub fn insert_uuid_v7(
13577 &mut self,
13578 _: &InsertUuidV7,
13579 window: &mut Window,
13580 cx: &mut Context<Self>,
13581 ) {
13582 self.insert_uuid(UuidVersion::V7, window, cx);
13583 }
13584
13585 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13586 self.transact(window, cx, |this, window, cx| {
13587 let edits = this
13588 .selections
13589 .all::<Point>(cx)
13590 .into_iter()
13591 .map(|selection| {
13592 let uuid = match version {
13593 UuidVersion::V4 => uuid::Uuid::new_v4(),
13594 UuidVersion::V7 => uuid::Uuid::now_v7(),
13595 };
13596
13597 (selection.range(), uuid.to_string())
13598 });
13599 this.edit(edits, cx);
13600 this.refresh_inline_completion(true, false, window, cx);
13601 });
13602 }
13603
13604 pub fn open_selections_in_multibuffer(
13605 &mut self,
13606 _: &OpenSelectionsInMultibuffer,
13607 window: &mut Window,
13608 cx: &mut Context<Self>,
13609 ) {
13610 let multibuffer = self.buffer.read(cx);
13611
13612 let Some(buffer) = multibuffer.as_singleton() else {
13613 return;
13614 };
13615
13616 let Some(workspace) = self.workspace() else {
13617 return;
13618 };
13619
13620 let locations = self
13621 .selections
13622 .disjoint_anchors()
13623 .iter()
13624 .map(|range| Location {
13625 buffer: buffer.clone(),
13626 range: range.start.text_anchor..range.end.text_anchor,
13627 })
13628 .collect::<Vec<_>>();
13629
13630 let title = multibuffer.title(cx).to_string();
13631
13632 cx.spawn_in(window, |_, mut cx| async move {
13633 workspace.update_in(&mut cx, |workspace, window, cx| {
13634 Self::open_locations_in_multibuffer(
13635 workspace,
13636 locations,
13637 format!("Selections for '{title}'"),
13638 false,
13639 MultibufferSelectionMode::All,
13640 window,
13641 cx,
13642 );
13643 })
13644 })
13645 .detach();
13646 }
13647
13648 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13649 /// last highlight added will be used.
13650 ///
13651 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13652 pub fn highlight_rows<T: 'static>(
13653 &mut self,
13654 range: Range<Anchor>,
13655 color: Hsla,
13656 should_autoscroll: bool,
13657 cx: &mut Context<Self>,
13658 ) {
13659 let snapshot = self.buffer().read(cx).snapshot(cx);
13660 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13661 let ix = row_highlights.binary_search_by(|highlight| {
13662 Ordering::Equal
13663 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13664 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13665 });
13666
13667 if let Err(mut ix) = ix {
13668 let index = post_inc(&mut self.highlight_order);
13669
13670 // If this range intersects with the preceding highlight, then merge it with
13671 // the preceding highlight. Otherwise insert a new highlight.
13672 let mut merged = false;
13673 if ix > 0 {
13674 let prev_highlight = &mut row_highlights[ix - 1];
13675 if prev_highlight
13676 .range
13677 .end
13678 .cmp(&range.start, &snapshot)
13679 .is_ge()
13680 {
13681 ix -= 1;
13682 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13683 prev_highlight.range.end = range.end;
13684 }
13685 merged = true;
13686 prev_highlight.index = index;
13687 prev_highlight.color = color;
13688 prev_highlight.should_autoscroll = should_autoscroll;
13689 }
13690 }
13691
13692 if !merged {
13693 row_highlights.insert(
13694 ix,
13695 RowHighlight {
13696 range: range.clone(),
13697 index,
13698 color,
13699 should_autoscroll,
13700 },
13701 );
13702 }
13703
13704 // If any of the following highlights intersect with this one, merge them.
13705 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13706 let highlight = &row_highlights[ix];
13707 if next_highlight
13708 .range
13709 .start
13710 .cmp(&highlight.range.end, &snapshot)
13711 .is_le()
13712 {
13713 if next_highlight
13714 .range
13715 .end
13716 .cmp(&highlight.range.end, &snapshot)
13717 .is_gt()
13718 {
13719 row_highlights[ix].range.end = next_highlight.range.end;
13720 }
13721 row_highlights.remove(ix + 1);
13722 } else {
13723 break;
13724 }
13725 }
13726 }
13727 }
13728
13729 /// Remove any highlighted row ranges of the given type that intersect the
13730 /// given ranges.
13731 pub fn remove_highlighted_rows<T: 'static>(
13732 &mut self,
13733 ranges_to_remove: Vec<Range<Anchor>>,
13734 cx: &mut Context<Self>,
13735 ) {
13736 let snapshot = self.buffer().read(cx).snapshot(cx);
13737 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13738 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13739 row_highlights.retain(|highlight| {
13740 while let Some(range_to_remove) = ranges_to_remove.peek() {
13741 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13742 Ordering::Less | Ordering::Equal => {
13743 ranges_to_remove.next();
13744 }
13745 Ordering::Greater => {
13746 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13747 Ordering::Less | Ordering::Equal => {
13748 return false;
13749 }
13750 Ordering::Greater => break,
13751 }
13752 }
13753 }
13754 }
13755
13756 true
13757 })
13758 }
13759
13760 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13761 pub fn clear_row_highlights<T: 'static>(&mut self) {
13762 self.highlighted_rows.remove(&TypeId::of::<T>());
13763 }
13764
13765 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13766 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13767 self.highlighted_rows
13768 .get(&TypeId::of::<T>())
13769 .map_or(&[] as &[_], |vec| vec.as_slice())
13770 .iter()
13771 .map(|highlight| (highlight.range.clone(), highlight.color))
13772 }
13773
13774 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13775 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13776 /// Allows to ignore certain kinds of highlights.
13777 pub fn highlighted_display_rows(
13778 &self,
13779 window: &mut Window,
13780 cx: &mut App,
13781 ) -> BTreeMap<DisplayRow, Background> {
13782 let snapshot = self.snapshot(window, cx);
13783 let mut used_highlight_orders = HashMap::default();
13784 self.highlighted_rows
13785 .iter()
13786 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13787 .fold(
13788 BTreeMap::<DisplayRow, Background>::new(),
13789 |mut unique_rows, highlight| {
13790 let start = highlight.range.start.to_display_point(&snapshot);
13791 let end = highlight.range.end.to_display_point(&snapshot);
13792 let start_row = start.row().0;
13793 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13794 && end.column() == 0
13795 {
13796 end.row().0.saturating_sub(1)
13797 } else {
13798 end.row().0
13799 };
13800 for row in start_row..=end_row {
13801 let used_index =
13802 used_highlight_orders.entry(row).or_insert(highlight.index);
13803 if highlight.index >= *used_index {
13804 *used_index = highlight.index;
13805 unique_rows.insert(DisplayRow(row), highlight.color.into());
13806 }
13807 }
13808 unique_rows
13809 },
13810 )
13811 }
13812
13813 pub fn highlighted_display_row_for_autoscroll(
13814 &self,
13815 snapshot: &DisplaySnapshot,
13816 ) -> Option<DisplayRow> {
13817 self.highlighted_rows
13818 .values()
13819 .flat_map(|highlighted_rows| highlighted_rows.iter())
13820 .filter_map(|highlight| {
13821 if highlight.should_autoscroll {
13822 Some(highlight.range.start.to_display_point(snapshot).row())
13823 } else {
13824 None
13825 }
13826 })
13827 .min()
13828 }
13829
13830 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13831 self.highlight_background::<SearchWithinRange>(
13832 ranges,
13833 |colors| colors.editor_document_highlight_read_background,
13834 cx,
13835 )
13836 }
13837
13838 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13839 self.breadcrumb_header = Some(new_header);
13840 }
13841
13842 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13843 self.clear_background_highlights::<SearchWithinRange>(cx);
13844 }
13845
13846 pub fn highlight_background<T: 'static>(
13847 &mut self,
13848 ranges: &[Range<Anchor>],
13849 color_fetcher: fn(&ThemeColors) -> Hsla,
13850 cx: &mut Context<Self>,
13851 ) {
13852 self.background_highlights
13853 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13854 self.scrollbar_marker_state.dirty = true;
13855 cx.notify();
13856 }
13857
13858 pub fn clear_background_highlights<T: 'static>(
13859 &mut self,
13860 cx: &mut Context<Self>,
13861 ) -> Option<BackgroundHighlight> {
13862 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13863 if !text_highlights.1.is_empty() {
13864 self.scrollbar_marker_state.dirty = true;
13865 cx.notify();
13866 }
13867 Some(text_highlights)
13868 }
13869
13870 pub fn highlight_gutter<T: 'static>(
13871 &mut self,
13872 ranges: &[Range<Anchor>],
13873 color_fetcher: fn(&App) -> Hsla,
13874 cx: &mut Context<Self>,
13875 ) {
13876 self.gutter_highlights
13877 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13878 cx.notify();
13879 }
13880
13881 pub fn clear_gutter_highlights<T: 'static>(
13882 &mut self,
13883 cx: &mut Context<Self>,
13884 ) -> Option<GutterHighlight> {
13885 cx.notify();
13886 self.gutter_highlights.remove(&TypeId::of::<T>())
13887 }
13888
13889 #[cfg(feature = "test-support")]
13890 pub fn all_text_background_highlights(
13891 &self,
13892 window: &mut Window,
13893 cx: &mut Context<Self>,
13894 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13895 let snapshot = self.snapshot(window, cx);
13896 let buffer = &snapshot.buffer_snapshot;
13897 let start = buffer.anchor_before(0);
13898 let end = buffer.anchor_after(buffer.len());
13899 let theme = cx.theme().colors();
13900 self.background_highlights_in_range(start..end, &snapshot, theme)
13901 }
13902
13903 #[cfg(feature = "test-support")]
13904 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13905 let snapshot = self.buffer().read(cx).snapshot(cx);
13906
13907 let highlights = self
13908 .background_highlights
13909 .get(&TypeId::of::<items::BufferSearchHighlights>());
13910
13911 if let Some((_color, ranges)) = highlights {
13912 ranges
13913 .iter()
13914 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13915 .collect_vec()
13916 } else {
13917 vec![]
13918 }
13919 }
13920
13921 fn document_highlights_for_position<'a>(
13922 &'a self,
13923 position: Anchor,
13924 buffer: &'a MultiBufferSnapshot,
13925 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13926 let read_highlights = self
13927 .background_highlights
13928 .get(&TypeId::of::<DocumentHighlightRead>())
13929 .map(|h| &h.1);
13930 let write_highlights = self
13931 .background_highlights
13932 .get(&TypeId::of::<DocumentHighlightWrite>())
13933 .map(|h| &h.1);
13934 let left_position = position.bias_left(buffer);
13935 let right_position = position.bias_right(buffer);
13936 read_highlights
13937 .into_iter()
13938 .chain(write_highlights)
13939 .flat_map(move |ranges| {
13940 let start_ix = match ranges.binary_search_by(|probe| {
13941 let cmp = probe.end.cmp(&left_position, buffer);
13942 if cmp.is_ge() {
13943 Ordering::Greater
13944 } else {
13945 Ordering::Less
13946 }
13947 }) {
13948 Ok(i) | Err(i) => i,
13949 };
13950
13951 ranges[start_ix..]
13952 .iter()
13953 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13954 })
13955 }
13956
13957 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13958 self.background_highlights
13959 .get(&TypeId::of::<T>())
13960 .map_or(false, |(_, highlights)| !highlights.is_empty())
13961 }
13962
13963 pub fn background_highlights_in_range(
13964 &self,
13965 search_range: Range<Anchor>,
13966 display_snapshot: &DisplaySnapshot,
13967 theme: &ThemeColors,
13968 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13969 let mut results = Vec::new();
13970 for (color_fetcher, ranges) in self.background_highlights.values() {
13971 let color = color_fetcher(theme);
13972 let start_ix = match ranges.binary_search_by(|probe| {
13973 let cmp = probe
13974 .end
13975 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13976 if cmp.is_gt() {
13977 Ordering::Greater
13978 } else {
13979 Ordering::Less
13980 }
13981 }) {
13982 Ok(i) | Err(i) => i,
13983 };
13984 for range in &ranges[start_ix..] {
13985 if range
13986 .start
13987 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13988 .is_ge()
13989 {
13990 break;
13991 }
13992
13993 let start = range.start.to_display_point(display_snapshot);
13994 let end = range.end.to_display_point(display_snapshot);
13995 results.push((start..end, color))
13996 }
13997 }
13998 results
13999 }
14000
14001 pub fn background_highlight_row_ranges<T: 'static>(
14002 &self,
14003 search_range: Range<Anchor>,
14004 display_snapshot: &DisplaySnapshot,
14005 count: usize,
14006 ) -> Vec<RangeInclusive<DisplayPoint>> {
14007 let mut results = Vec::new();
14008 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14009 return vec![];
14010 };
14011
14012 let start_ix = match ranges.binary_search_by(|probe| {
14013 let cmp = probe
14014 .end
14015 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14016 if cmp.is_gt() {
14017 Ordering::Greater
14018 } else {
14019 Ordering::Less
14020 }
14021 }) {
14022 Ok(i) | Err(i) => i,
14023 };
14024 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14025 if let (Some(start_display), Some(end_display)) = (start, end) {
14026 results.push(
14027 start_display.to_display_point(display_snapshot)
14028 ..=end_display.to_display_point(display_snapshot),
14029 );
14030 }
14031 };
14032 let mut start_row: Option<Point> = None;
14033 let mut end_row: Option<Point> = None;
14034 if ranges.len() > count {
14035 return Vec::new();
14036 }
14037 for range in &ranges[start_ix..] {
14038 if range
14039 .start
14040 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14041 .is_ge()
14042 {
14043 break;
14044 }
14045 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14046 if let Some(current_row) = &end_row {
14047 if end.row == current_row.row {
14048 continue;
14049 }
14050 }
14051 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14052 if start_row.is_none() {
14053 assert_eq!(end_row, None);
14054 start_row = Some(start);
14055 end_row = Some(end);
14056 continue;
14057 }
14058 if let Some(current_end) = end_row.as_mut() {
14059 if start.row > current_end.row + 1 {
14060 push_region(start_row, end_row);
14061 start_row = Some(start);
14062 end_row = Some(end);
14063 } else {
14064 // Merge two hunks.
14065 *current_end = end;
14066 }
14067 } else {
14068 unreachable!();
14069 }
14070 }
14071 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14072 push_region(start_row, end_row);
14073 results
14074 }
14075
14076 pub fn gutter_highlights_in_range(
14077 &self,
14078 search_range: Range<Anchor>,
14079 display_snapshot: &DisplaySnapshot,
14080 cx: &App,
14081 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14082 let mut results = Vec::new();
14083 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14084 let color = color_fetcher(cx);
14085 let start_ix = match ranges.binary_search_by(|probe| {
14086 let cmp = probe
14087 .end
14088 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14089 if cmp.is_gt() {
14090 Ordering::Greater
14091 } else {
14092 Ordering::Less
14093 }
14094 }) {
14095 Ok(i) | Err(i) => i,
14096 };
14097 for range in &ranges[start_ix..] {
14098 if range
14099 .start
14100 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14101 .is_ge()
14102 {
14103 break;
14104 }
14105
14106 let start = range.start.to_display_point(display_snapshot);
14107 let end = range.end.to_display_point(display_snapshot);
14108 results.push((start..end, color))
14109 }
14110 }
14111 results
14112 }
14113
14114 /// Get the text ranges corresponding to the redaction query
14115 pub fn redacted_ranges(
14116 &self,
14117 search_range: Range<Anchor>,
14118 display_snapshot: &DisplaySnapshot,
14119 cx: &App,
14120 ) -> Vec<Range<DisplayPoint>> {
14121 display_snapshot
14122 .buffer_snapshot
14123 .redacted_ranges(search_range, |file| {
14124 if let Some(file) = file {
14125 file.is_private()
14126 && EditorSettings::get(
14127 Some(SettingsLocation {
14128 worktree_id: file.worktree_id(cx),
14129 path: file.path().as_ref(),
14130 }),
14131 cx,
14132 )
14133 .redact_private_values
14134 } else {
14135 false
14136 }
14137 })
14138 .map(|range| {
14139 range.start.to_display_point(display_snapshot)
14140 ..range.end.to_display_point(display_snapshot)
14141 })
14142 .collect()
14143 }
14144
14145 pub fn highlight_text<T: 'static>(
14146 &mut self,
14147 ranges: Vec<Range<Anchor>>,
14148 style: HighlightStyle,
14149 cx: &mut Context<Self>,
14150 ) {
14151 self.display_map.update(cx, |map, _| {
14152 map.highlight_text(TypeId::of::<T>(), ranges, style)
14153 });
14154 cx.notify();
14155 }
14156
14157 pub(crate) fn highlight_inlays<T: 'static>(
14158 &mut self,
14159 highlights: Vec<InlayHighlight>,
14160 style: HighlightStyle,
14161 cx: &mut Context<Self>,
14162 ) {
14163 self.display_map.update(cx, |map, _| {
14164 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14165 });
14166 cx.notify();
14167 }
14168
14169 pub fn text_highlights<'a, T: 'static>(
14170 &'a self,
14171 cx: &'a App,
14172 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14173 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14174 }
14175
14176 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14177 let cleared = self
14178 .display_map
14179 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14180 if cleared {
14181 cx.notify();
14182 }
14183 }
14184
14185 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14186 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14187 && self.focus_handle.is_focused(window)
14188 }
14189
14190 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14191 self.show_cursor_when_unfocused = is_enabled;
14192 cx.notify();
14193 }
14194
14195 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14196 cx.notify();
14197 }
14198
14199 fn on_buffer_event(
14200 &mut self,
14201 multibuffer: &Entity<MultiBuffer>,
14202 event: &multi_buffer::Event,
14203 window: &mut Window,
14204 cx: &mut Context<Self>,
14205 ) {
14206 match event {
14207 multi_buffer::Event::Edited {
14208 singleton_buffer_edited,
14209 edited_buffer: buffer_edited,
14210 } => {
14211 self.scrollbar_marker_state.dirty = true;
14212 self.active_indent_guides_state.dirty = true;
14213 self.refresh_active_diagnostics(cx);
14214 self.refresh_code_actions(window, cx);
14215 if self.has_active_inline_completion() {
14216 self.update_visible_inline_completion(window, cx);
14217 }
14218 if let Some(buffer) = buffer_edited {
14219 let buffer_id = buffer.read(cx).remote_id();
14220 if !self.registered_buffers.contains_key(&buffer_id) {
14221 if let Some(project) = self.project.as_ref() {
14222 project.update(cx, |project, cx| {
14223 self.registered_buffers.insert(
14224 buffer_id,
14225 project.register_buffer_with_language_servers(&buffer, cx),
14226 );
14227 })
14228 }
14229 }
14230 }
14231 cx.emit(EditorEvent::BufferEdited);
14232 cx.emit(SearchEvent::MatchesInvalidated);
14233 if *singleton_buffer_edited {
14234 if let Some(project) = &self.project {
14235 #[allow(clippy::mutable_key_type)]
14236 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14237 multibuffer
14238 .all_buffers()
14239 .into_iter()
14240 .filter_map(|buffer| {
14241 buffer.update(cx, |buffer, cx| {
14242 let language = buffer.language()?;
14243 let should_discard = project.update(cx, |project, cx| {
14244 project.is_local()
14245 && !project.has_language_servers_for(buffer, cx)
14246 });
14247 should_discard.not().then_some(language.clone())
14248 })
14249 })
14250 .collect::<HashSet<_>>()
14251 });
14252 if !languages_affected.is_empty() {
14253 self.refresh_inlay_hints(
14254 InlayHintRefreshReason::BufferEdited(languages_affected),
14255 cx,
14256 );
14257 }
14258 }
14259 }
14260
14261 let Some(project) = &self.project else { return };
14262 let (telemetry, is_via_ssh) = {
14263 let project = project.read(cx);
14264 let telemetry = project.client().telemetry().clone();
14265 let is_via_ssh = project.is_via_ssh();
14266 (telemetry, is_via_ssh)
14267 };
14268 refresh_linked_ranges(self, window, cx);
14269 telemetry.log_edit_event("editor", is_via_ssh);
14270 }
14271 multi_buffer::Event::ExcerptsAdded {
14272 buffer,
14273 predecessor,
14274 excerpts,
14275 } => {
14276 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14277 let buffer_id = buffer.read(cx).remote_id();
14278 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14279 if let Some(project) = &self.project {
14280 get_uncommitted_diff_for_buffer(
14281 project,
14282 [buffer.clone()],
14283 self.buffer.clone(),
14284 cx,
14285 )
14286 .detach();
14287 }
14288 }
14289 cx.emit(EditorEvent::ExcerptsAdded {
14290 buffer: buffer.clone(),
14291 predecessor: *predecessor,
14292 excerpts: excerpts.clone(),
14293 });
14294 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14295 }
14296 multi_buffer::Event::ExcerptsRemoved { ids } => {
14297 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14298 let buffer = self.buffer.read(cx);
14299 self.registered_buffers
14300 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14301 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14302 }
14303 multi_buffer::Event::ExcerptsEdited { ids } => {
14304 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14305 }
14306 multi_buffer::Event::ExcerptsExpanded { ids } => {
14307 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14308 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14309 }
14310 multi_buffer::Event::Reparsed(buffer_id) => {
14311 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14312
14313 cx.emit(EditorEvent::Reparsed(*buffer_id));
14314 }
14315 multi_buffer::Event::DiffHunksToggled => {
14316 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14317 }
14318 multi_buffer::Event::LanguageChanged(buffer_id) => {
14319 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14320 cx.emit(EditorEvent::Reparsed(*buffer_id));
14321 cx.notify();
14322 }
14323 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14324 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14325 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14326 cx.emit(EditorEvent::TitleChanged)
14327 }
14328 // multi_buffer::Event::DiffBaseChanged => {
14329 // self.scrollbar_marker_state.dirty = true;
14330 // cx.emit(EditorEvent::DiffBaseChanged);
14331 // cx.notify();
14332 // }
14333 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14334 multi_buffer::Event::DiagnosticsUpdated => {
14335 self.refresh_active_diagnostics(cx);
14336 self.scrollbar_marker_state.dirty = true;
14337 cx.notify();
14338 }
14339 _ => {}
14340 };
14341 }
14342
14343 fn on_display_map_changed(
14344 &mut self,
14345 _: Entity<DisplayMap>,
14346 _: &mut Window,
14347 cx: &mut Context<Self>,
14348 ) {
14349 cx.notify();
14350 }
14351
14352 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14353 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14354 self.refresh_inline_completion(true, false, window, cx);
14355 self.refresh_inlay_hints(
14356 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14357 self.selections.newest_anchor().head(),
14358 &self.buffer.read(cx).snapshot(cx),
14359 cx,
14360 )),
14361 cx,
14362 );
14363
14364 let old_cursor_shape = self.cursor_shape;
14365
14366 {
14367 let editor_settings = EditorSettings::get_global(cx);
14368 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14369 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14370 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14371 self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
14372
14373 if !self.hide_mouse_while_typing {
14374 self.mouse_cursor_hidden = false;
14375 }
14376 }
14377
14378 if old_cursor_shape != self.cursor_shape {
14379 cx.emit(EditorEvent::CursorShapeChanged);
14380 }
14381
14382 let project_settings = ProjectSettings::get_global(cx);
14383 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14384
14385 if self.mode == EditorMode::Full {
14386 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14387 if self.git_blame_inline_enabled != inline_blame_enabled {
14388 self.toggle_git_blame_inline_internal(false, window, cx);
14389 }
14390 }
14391
14392 cx.notify();
14393 }
14394
14395 pub fn set_searchable(&mut self, searchable: bool) {
14396 self.searchable = searchable;
14397 }
14398
14399 pub fn searchable(&self) -> bool {
14400 self.searchable
14401 }
14402
14403 fn open_proposed_changes_editor(
14404 &mut self,
14405 _: &OpenProposedChangesEditor,
14406 window: &mut Window,
14407 cx: &mut Context<Self>,
14408 ) {
14409 let Some(workspace) = self.workspace() else {
14410 cx.propagate();
14411 return;
14412 };
14413
14414 let selections = self.selections.all::<usize>(cx);
14415 let multi_buffer = self.buffer.read(cx);
14416 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14417 let mut new_selections_by_buffer = HashMap::default();
14418 for selection in selections {
14419 for (buffer, range, _) in
14420 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14421 {
14422 let mut range = range.to_point(buffer);
14423 range.start.column = 0;
14424 range.end.column = buffer.line_len(range.end.row);
14425 new_selections_by_buffer
14426 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14427 .or_insert(Vec::new())
14428 .push(range)
14429 }
14430 }
14431
14432 let proposed_changes_buffers = new_selections_by_buffer
14433 .into_iter()
14434 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14435 .collect::<Vec<_>>();
14436 let proposed_changes_editor = cx.new(|cx| {
14437 ProposedChangesEditor::new(
14438 "Proposed changes",
14439 proposed_changes_buffers,
14440 self.project.clone(),
14441 window,
14442 cx,
14443 )
14444 });
14445
14446 window.defer(cx, move |window, cx| {
14447 workspace.update(cx, |workspace, cx| {
14448 workspace.active_pane().update(cx, |pane, cx| {
14449 pane.add_item(
14450 Box::new(proposed_changes_editor),
14451 true,
14452 true,
14453 None,
14454 window,
14455 cx,
14456 );
14457 });
14458 });
14459 });
14460 }
14461
14462 pub fn open_excerpts_in_split(
14463 &mut self,
14464 _: &OpenExcerptsSplit,
14465 window: &mut Window,
14466 cx: &mut Context<Self>,
14467 ) {
14468 self.open_excerpts_common(None, true, window, cx)
14469 }
14470
14471 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14472 self.open_excerpts_common(None, false, window, cx)
14473 }
14474
14475 fn open_excerpts_common(
14476 &mut self,
14477 jump_data: Option<JumpData>,
14478 split: bool,
14479 window: &mut Window,
14480 cx: &mut Context<Self>,
14481 ) {
14482 let Some(workspace) = self.workspace() else {
14483 cx.propagate();
14484 return;
14485 };
14486
14487 if self.buffer.read(cx).is_singleton() {
14488 cx.propagate();
14489 return;
14490 }
14491
14492 let mut new_selections_by_buffer = HashMap::default();
14493 match &jump_data {
14494 Some(JumpData::MultiBufferPoint {
14495 excerpt_id,
14496 position,
14497 anchor,
14498 line_offset_from_top,
14499 }) => {
14500 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14501 if let Some(buffer) = multi_buffer_snapshot
14502 .buffer_id_for_excerpt(*excerpt_id)
14503 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14504 {
14505 let buffer_snapshot = buffer.read(cx).snapshot();
14506 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14507 language::ToPoint::to_point(anchor, &buffer_snapshot)
14508 } else {
14509 buffer_snapshot.clip_point(*position, Bias::Left)
14510 };
14511 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14512 new_selections_by_buffer.insert(
14513 buffer,
14514 (
14515 vec![jump_to_offset..jump_to_offset],
14516 Some(*line_offset_from_top),
14517 ),
14518 );
14519 }
14520 }
14521 Some(JumpData::MultiBufferRow {
14522 row,
14523 line_offset_from_top,
14524 }) => {
14525 let point = MultiBufferPoint::new(row.0, 0);
14526 if let Some((buffer, buffer_point, _)) =
14527 self.buffer.read(cx).point_to_buffer_point(point, cx)
14528 {
14529 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14530 new_selections_by_buffer
14531 .entry(buffer)
14532 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14533 .0
14534 .push(buffer_offset..buffer_offset)
14535 }
14536 }
14537 None => {
14538 let selections = self.selections.all::<usize>(cx);
14539 let multi_buffer = self.buffer.read(cx);
14540 for selection in selections {
14541 for (buffer, mut range, _) in multi_buffer
14542 .snapshot(cx)
14543 .range_to_buffer_ranges(selection.range())
14544 {
14545 // When editing branch buffers, jump to the corresponding location
14546 // in their base buffer.
14547 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14548 let buffer = buffer_handle.read(cx);
14549 if let Some(base_buffer) = buffer.base_buffer() {
14550 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14551 buffer_handle = base_buffer;
14552 }
14553
14554 if selection.reversed {
14555 mem::swap(&mut range.start, &mut range.end);
14556 }
14557 new_selections_by_buffer
14558 .entry(buffer_handle)
14559 .or_insert((Vec::new(), None))
14560 .0
14561 .push(range)
14562 }
14563 }
14564 }
14565 }
14566
14567 if new_selections_by_buffer.is_empty() {
14568 return;
14569 }
14570
14571 // We defer the pane interaction because we ourselves are a workspace item
14572 // and activating a new item causes the pane to call a method on us reentrantly,
14573 // which panics if we're on the stack.
14574 window.defer(cx, move |window, cx| {
14575 workspace.update(cx, |workspace, cx| {
14576 let pane = if split {
14577 workspace.adjacent_pane(window, cx)
14578 } else {
14579 workspace.active_pane().clone()
14580 };
14581
14582 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14583 let editor = buffer
14584 .read(cx)
14585 .file()
14586 .is_none()
14587 .then(|| {
14588 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14589 // so `workspace.open_project_item` will never find them, always opening a new editor.
14590 // Instead, we try to activate the existing editor in the pane first.
14591 let (editor, pane_item_index) =
14592 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14593 let editor = item.downcast::<Editor>()?;
14594 let singleton_buffer =
14595 editor.read(cx).buffer().read(cx).as_singleton()?;
14596 if singleton_buffer == buffer {
14597 Some((editor, i))
14598 } else {
14599 None
14600 }
14601 })?;
14602 pane.update(cx, |pane, cx| {
14603 pane.activate_item(pane_item_index, true, true, window, cx)
14604 });
14605 Some(editor)
14606 })
14607 .flatten()
14608 .unwrap_or_else(|| {
14609 workspace.open_project_item::<Self>(
14610 pane.clone(),
14611 buffer,
14612 true,
14613 true,
14614 window,
14615 cx,
14616 )
14617 });
14618
14619 editor.update(cx, |editor, cx| {
14620 let autoscroll = match scroll_offset {
14621 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14622 None => Autoscroll::newest(),
14623 };
14624 let nav_history = editor.nav_history.take();
14625 editor.change_selections(Some(autoscroll), window, cx, |s| {
14626 s.select_ranges(ranges);
14627 });
14628 editor.nav_history = nav_history;
14629 });
14630 }
14631 })
14632 });
14633 }
14634
14635 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14636 let snapshot = self.buffer.read(cx).read(cx);
14637 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14638 Some(
14639 ranges
14640 .iter()
14641 .map(move |range| {
14642 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14643 })
14644 .collect(),
14645 )
14646 }
14647
14648 fn selection_replacement_ranges(
14649 &self,
14650 range: Range<OffsetUtf16>,
14651 cx: &mut App,
14652 ) -> Vec<Range<OffsetUtf16>> {
14653 let selections = self.selections.all::<OffsetUtf16>(cx);
14654 let newest_selection = selections
14655 .iter()
14656 .max_by_key(|selection| selection.id)
14657 .unwrap();
14658 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14659 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14660 let snapshot = self.buffer.read(cx).read(cx);
14661 selections
14662 .into_iter()
14663 .map(|mut selection| {
14664 selection.start.0 =
14665 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14666 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14667 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14668 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14669 })
14670 .collect()
14671 }
14672
14673 fn report_editor_event(
14674 &self,
14675 event_type: &'static str,
14676 file_extension: Option<String>,
14677 cx: &App,
14678 ) {
14679 if cfg!(any(test, feature = "test-support")) {
14680 return;
14681 }
14682
14683 let Some(project) = &self.project else { return };
14684
14685 // If None, we are in a file without an extension
14686 let file = self
14687 .buffer
14688 .read(cx)
14689 .as_singleton()
14690 .and_then(|b| b.read(cx).file());
14691 let file_extension = file_extension.or(file
14692 .as_ref()
14693 .and_then(|file| Path::new(file.file_name(cx)).extension())
14694 .and_then(|e| e.to_str())
14695 .map(|a| a.to_string()));
14696
14697 let vim_mode = cx
14698 .global::<SettingsStore>()
14699 .raw_user_settings()
14700 .get("vim_mode")
14701 == Some(&serde_json::Value::Bool(true));
14702
14703 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14704 let copilot_enabled = edit_predictions_provider
14705 == language::language_settings::EditPredictionProvider::Copilot;
14706 let copilot_enabled_for_language = self
14707 .buffer
14708 .read(cx)
14709 .settings_at(0, cx)
14710 .show_edit_predictions;
14711
14712 let project = project.read(cx);
14713 telemetry::event!(
14714 event_type,
14715 file_extension,
14716 vim_mode,
14717 copilot_enabled,
14718 copilot_enabled_for_language,
14719 edit_predictions_provider,
14720 is_via_ssh = project.is_via_ssh(),
14721 );
14722 }
14723
14724 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14725 /// with each line being an array of {text, highlight} objects.
14726 fn copy_highlight_json(
14727 &mut self,
14728 _: &CopyHighlightJson,
14729 window: &mut Window,
14730 cx: &mut Context<Self>,
14731 ) {
14732 #[derive(Serialize)]
14733 struct Chunk<'a> {
14734 text: String,
14735 highlight: Option<&'a str>,
14736 }
14737
14738 let snapshot = self.buffer.read(cx).snapshot(cx);
14739 let range = self
14740 .selected_text_range(false, window, cx)
14741 .and_then(|selection| {
14742 if selection.range.is_empty() {
14743 None
14744 } else {
14745 Some(selection.range)
14746 }
14747 })
14748 .unwrap_or_else(|| 0..snapshot.len());
14749
14750 let chunks = snapshot.chunks(range, true);
14751 let mut lines = Vec::new();
14752 let mut line: VecDeque<Chunk> = VecDeque::new();
14753
14754 let Some(style) = self.style.as_ref() else {
14755 return;
14756 };
14757
14758 for chunk in chunks {
14759 let highlight = chunk
14760 .syntax_highlight_id
14761 .and_then(|id| id.name(&style.syntax));
14762 let mut chunk_lines = chunk.text.split('\n').peekable();
14763 while let Some(text) = chunk_lines.next() {
14764 let mut merged_with_last_token = false;
14765 if let Some(last_token) = line.back_mut() {
14766 if last_token.highlight == highlight {
14767 last_token.text.push_str(text);
14768 merged_with_last_token = true;
14769 }
14770 }
14771
14772 if !merged_with_last_token {
14773 line.push_back(Chunk {
14774 text: text.into(),
14775 highlight,
14776 });
14777 }
14778
14779 if chunk_lines.peek().is_some() {
14780 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14781 line.pop_front();
14782 }
14783 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14784 line.pop_back();
14785 }
14786
14787 lines.push(mem::take(&mut line));
14788 }
14789 }
14790 }
14791
14792 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14793 return;
14794 };
14795 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14796 }
14797
14798 pub fn open_context_menu(
14799 &mut self,
14800 _: &OpenContextMenu,
14801 window: &mut Window,
14802 cx: &mut Context<Self>,
14803 ) {
14804 self.request_autoscroll(Autoscroll::newest(), cx);
14805 let position = self.selections.newest_display(cx).start;
14806 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14807 }
14808
14809 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14810 &self.inlay_hint_cache
14811 }
14812
14813 pub fn replay_insert_event(
14814 &mut self,
14815 text: &str,
14816 relative_utf16_range: Option<Range<isize>>,
14817 window: &mut Window,
14818 cx: &mut Context<Self>,
14819 ) {
14820 if !self.input_enabled {
14821 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14822 return;
14823 }
14824 if let Some(relative_utf16_range) = relative_utf16_range {
14825 let selections = self.selections.all::<OffsetUtf16>(cx);
14826 self.change_selections(None, window, cx, |s| {
14827 let new_ranges = selections.into_iter().map(|range| {
14828 let start = OffsetUtf16(
14829 range
14830 .head()
14831 .0
14832 .saturating_add_signed(relative_utf16_range.start),
14833 );
14834 let end = OffsetUtf16(
14835 range
14836 .head()
14837 .0
14838 .saturating_add_signed(relative_utf16_range.end),
14839 );
14840 start..end
14841 });
14842 s.select_ranges(new_ranges);
14843 });
14844 }
14845
14846 self.handle_input(text, window, cx);
14847 }
14848
14849 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14850 let Some(provider) = self.semantics_provider.as_ref() else {
14851 return false;
14852 };
14853
14854 let mut supports = false;
14855 self.buffer().update(cx, |this, cx| {
14856 this.for_each_buffer(|buffer| {
14857 supports |= provider.supports_inlay_hints(buffer, cx);
14858 });
14859 });
14860
14861 supports
14862 }
14863
14864 pub fn is_focused(&self, window: &Window) -> bool {
14865 self.focus_handle.is_focused(window)
14866 }
14867
14868 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14869 cx.emit(EditorEvent::Focused);
14870
14871 if let Some(descendant) = self
14872 .last_focused_descendant
14873 .take()
14874 .and_then(|descendant| descendant.upgrade())
14875 {
14876 window.focus(&descendant);
14877 } else {
14878 if let Some(blame) = self.blame.as_ref() {
14879 blame.update(cx, GitBlame::focus)
14880 }
14881
14882 self.blink_manager.update(cx, BlinkManager::enable);
14883 self.show_cursor_names(window, cx);
14884 self.buffer.update(cx, |buffer, cx| {
14885 buffer.finalize_last_transaction(cx);
14886 if self.leader_peer_id.is_none() {
14887 buffer.set_active_selections(
14888 &self.selections.disjoint_anchors(),
14889 self.selections.line_mode,
14890 self.cursor_shape,
14891 cx,
14892 );
14893 }
14894 });
14895 }
14896 }
14897
14898 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14899 cx.emit(EditorEvent::FocusedIn)
14900 }
14901
14902 fn handle_focus_out(
14903 &mut self,
14904 event: FocusOutEvent,
14905 _window: &mut Window,
14906 _cx: &mut Context<Self>,
14907 ) {
14908 if event.blurred != self.focus_handle {
14909 self.last_focused_descendant = Some(event.blurred);
14910 }
14911 }
14912
14913 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14914 self.blink_manager.update(cx, BlinkManager::disable);
14915 self.buffer
14916 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14917
14918 if let Some(blame) = self.blame.as_ref() {
14919 blame.update(cx, GitBlame::blur)
14920 }
14921 if !self.hover_state.focused(window, cx) {
14922 hide_hover(self, cx);
14923 }
14924 if !self
14925 .context_menu
14926 .borrow()
14927 .as_ref()
14928 .is_some_and(|context_menu| context_menu.focused(window, cx))
14929 {
14930 self.hide_context_menu(window, cx);
14931 }
14932 self.discard_inline_completion(false, cx);
14933 cx.emit(EditorEvent::Blurred);
14934 cx.notify();
14935 }
14936
14937 pub fn register_action<A: Action>(
14938 &mut self,
14939 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14940 ) -> Subscription {
14941 let id = self.next_editor_action_id.post_inc();
14942 let listener = Arc::new(listener);
14943 self.editor_actions.borrow_mut().insert(
14944 id,
14945 Box::new(move |window, _| {
14946 let listener = listener.clone();
14947 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14948 let action = action.downcast_ref().unwrap();
14949 if phase == DispatchPhase::Bubble {
14950 listener(action, window, cx)
14951 }
14952 })
14953 }),
14954 );
14955
14956 let editor_actions = self.editor_actions.clone();
14957 Subscription::new(move || {
14958 editor_actions.borrow_mut().remove(&id);
14959 })
14960 }
14961
14962 pub fn file_header_size(&self) -> u32 {
14963 FILE_HEADER_HEIGHT
14964 }
14965
14966 pub fn revert(
14967 &mut self,
14968 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14969 window: &mut Window,
14970 cx: &mut Context<Self>,
14971 ) {
14972 self.buffer().update(cx, |multi_buffer, cx| {
14973 for (buffer_id, changes) in revert_changes {
14974 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14975 buffer.update(cx, |buffer, cx| {
14976 buffer.edit(
14977 changes.into_iter().map(|(range, text)| {
14978 (range, text.to_string().map(Arc::<str>::from))
14979 }),
14980 None,
14981 cx,
14982 );
14983 });
14984 }
14985 }
14986 });
14987 self.change_selections(None, window, cx, |selections| selections.refresh());
14988 }
14989
14990 pub fn to_pixel_point(
14991 &self,
14992 source: multi_buffer::Anchor,
14993 editor_snapshot: &EditorSnapshot,
14994 window: &mut Window,
14995 ) -> Option<gpui::Point<Pixels>> {
14996 let source_point = source.to_display_point(editor_snapshot);
14997 self.display_to_pixel_point(source_point, editor_snapshot, window)
14998 }
14999
15000 pub fn display_to_pixel_point(
15001 &self,
15002 source: DisplayPoint,
15003 editor_snapshot: &EditorSnapshot,
15004 window: &mut Window,
15005 ) -> Option<gpui::Point<Pixels>> {
15006 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15007 let text_layout_details = self.text_layout_details(window);
15008 let scroll_top = text_layout_details
15009 .scroll_anchor
15010 .scroll_position(editor_snapshot)
15011 .y;
15012
15013 if source.row().as_f32() < scroll_top.floor() {
15014 return None;
15015 }
15016 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15017 let source_y = line_height * (source.row().as_f32() - scroll_top);
15018 Some(gpui::Point::new(source_x, source_y))
15019 }
15020
15021 pub fn has_visible_completions_menu(&self) -> bool {
15022 !self.edit_prediction_preview_is_active()
15023 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15024 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15025 })
15026 }
15027
15028 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15029 self.addons
15030 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15031 }
15032
15033 pub fn unregister_addon<T: Addon>(&mut self) {
15034 self.addons.remove(&std::any::TypeId::of::<T>());
15035 }
15036
15037 pub fn addon<T: Addon>(&self) -> Option<&T> {
15038 let type_id = std::any::TypeId::of::<T>();
15039 self.addons
15040 .get(&type_id)
15041 .and_then(|item| item.to_any().downcast_ref::<T>())
15042 }
15043
15044 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15045 let text_layout_details = self.text_layout_details(window);
15046 let style = &text_layout_details.editor_style;
15047 let font_id = window.text_system().resolve_font(&style.text.font());
15048 let font_size = style.text.font_size.to_pixels(window.rem_size());
15049 let line_height = style.text.line_height_in_pixels(window.rem_size());
15050 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15051
15052 gpui::Size::new(em_width, line_height)
15053 }
15054
15055 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15056 self.load_diff_task.clone()
15057 }
15058
15059 fn read_selections_from_db(
15060 &mut self,
15061 item_id: u64,
15062 workspace_id: WorkspaceId,
15063 window: &mut Window,
15064 cx: &mut Context<Editor>,
15065 ) {
15066 if !self.is_singleton(cx)
15067 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15068 {
15069 return;
15070 }
15071 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15072 return;
15073 };
15074 if selections.is_empty() {
15075 return;
15076 }
15077
15078 let snapshot = self.buffer.read(cx).snapshot(cx);
15079 self.change_selections(None, window, cx, |s| {
15080 s.select_ranges(selections.into_iter().map(|(start, end)| {
15081 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15082 }));
15083 });
15084 }
15085}
15086
15087fn insert_extra_newline_brackets(
15088 buffer: &MultiBufferSnapshot,
15089 range: Range<usize>,
15090 language: &language::LanguageScope,
15091) -> bool {
15092 let leading_whitespace_len = buffer
15093 .reversed_chars_at(range.start)
15094 .take_while(|c| c.is_whitespace() && *c != '\n')
15095 .map(|c| c.len_utf8())
15096 .sum::<usize>();
15097 let trailing_whitespace_len = buffer
15098 .chars_at(range.end)
15099 .take_while(|c| c.is_whitespace() && *c != '\n')
15100 .map(|c| c.len_utf8())
15101 .sum::<usize>();
15102 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15103
15104 language.brackets().any(|(pair, enabled)| {
15105 let pair_start = pair.start.trim_end();
15106 let pair_end = pair.end.trim_start();
15107
15108 enabled
15109 && pair.newline
15110 && buffer.contains_str_at(range.end, pair_end)
15111 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15112 })
15113}
15114
15115fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15116 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15117 [(buffer, range, _)] => (*buffer, range.clone()),
15118 _ => return false,
15119 };
15120 let pair = {
15121 let mut result: Option<BracketMatch> = None;
15122
15123 for pair in buffer
15124 .all_bracket_ranges(range.clone())
15125 .filter(move |pair| {
15126 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15127 })
15128 {
15129 let len = pair.close_range.end - pair.open_range.start;
15130
15131 if let Some(existing) = &result {
15132 let existing_len = existing.close_range.end - existing.open_range.start;
15133 if len > existing_len {
15134 continue;
15135 }
15136 }
15137
15138 result = Some(pair);
15139 }
15140
15141 result
15142 };
15143 let Some(pair) = pair else {
15144 return false;
15145 };
15146 pair.newline_only
15147 && buffer
15148 .chars_for_range(pair.open_range.end..range.start)
15149 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15150 .all(|c| c.is_whitespace() && c != '\n')
15151}
15152
15153fn get_uncommitted_diff_for_buffer(
15154 project: &Entity<Project>,
15155 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15156 buffer: Entity<MultiBuffer>,
15157 cx: &mut App,
15158) -> Task<()> {
15159 let mut tasks = Vec::new();
15160 project.update(cx, |project, cx| {
15161 for buffer in buffers {
15162 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15163 }
15164 });
15165 cx.spawn(|mut cx| async move {
15166 let diffs = futures::future::join_all(tasks).await;
15167 buffer
15168 .update(&mut cx, |buffer, cx| {
15169 for diff in diffs.into_iter().flatten() {
15170 buffer.add_diff(diff, cx);
15171 }
15172 })
15173 .ok();
15174 })
15175}
15176
15177fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15178 let tab_size = tab_size.get() as usize;
15179 let mut width = offset;
15180
15181 for ch in text.chars() {
15182 width += if ch == '\t' {
15183 tab_size - (width % tab_size)
15184 } else {
15185 1
15186 };
15187 }
15188
15189 width - offset
15190}
15191
15192#[cfg(test)]
15193mod tests {
15194 use super::*;
15195
15196 #[test]
15197 fn test_string_size_with_expanded_tabs() {
15198 let nz = |val| NonZeroU32::new(val).unwrap();
15199 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15200 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15201 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15202 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15203 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15204 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15205 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15206 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15207 }
15208}
15209
15210/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15211struct WordBreakingTokenizer<'a> {
15212 input: &'a str,
15213}
15214
15215impl<'a> WordBreakingTokenizer<'a> {
15216 fn new(input: &'a str) -> Self {
15217 Self { input }
15218 }
15219}
15220
15221fn is_char_ideographic(ch: char) -> bool {
15222 use unicode_script::Script::*;
15223 use unicode_script::UnicodeScript;
15224 matches!(ch.script(), Han | Tangut | Yi)
15225}
15226
15227fn is_grapheme_ideographic(text: &str) -> bool {
15228 text.chars().any(is_char_ideographic)
15229}
15230
15231fn is_grapheme_whitespace(text: &str) -> bool {
15232 text.chars().any(|x| x.is_whitespace())
15233}
15234
15235fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15236 text.chars().next().map_or(false, |ch| {
15237 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15238 })
15239}
15240
15241#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15242struct WordBreakToken<'a> {
15243 token: &'a str,
15244 grapheme_len: usize,
15245 is_whitespace: bool,
15246}
15247
15248impl<'a> Iterator for WordBreakingTokenizer<'a> {
15249 /// Yields a span, the count of graphemes in the token, and whether it was
15250 /// whitespace. Note that it also breaks at word boundaries.
15251 type Item = WordBreakToken<'a>;
15252
15253 fn next(&mut self) -> Option<Self::Item> {
15254 use unicode_segmentation::UnicodeSegmentation;
15255 if self.input.is_empty() {
15256 return None;
15257 }
15258
15259 let mut iter = self.input.graphemes(true).peekable();
15260 let mut offset = 0;
15261 let mut graphemes = 0;
15262 if let Some(first_grapheme) = iter.next() {
15263 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15264 offset += first_grapheme.len();
15265 graphemes += 1;
15266 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15267 if let Some(grapheme) = iter.peek().copied() {
15268 if should_stay_with_preceding_ideograph(grapheme) {
15269 offset += grapheme.len();
15270 graphemes += 1;
15271 }
15272 }
15273 } else {
15274 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15275 let mut next_word_bound = words.peek().copied();
15276 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15277 next_word_bound = words.next();
15278 }
15279 while let Some(grapheme) = iter.peek().copied() {
15280 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15281 break;
15282 };
15283 if is_grapheme_whitespace(grapheme) != is_whitespace {
15284 break;
15285 };
15286 offset += grapheme.len();
15287 graphemes += 1;
15288 iter.next();
15289 }
15290 }
15291 let token = &self.input[..offset];
15292 self.input = &self.input[offset..];
15293 if is_whitespace {
15294 Some(WordBreakToken {
15295 token: " ",
15296 grapheme_len: 1,
15297 is_whitespace: true,
15298 })
15299 } else {
15300 Some(WordBreakToken {
15301 token,
15302 grapheme_len: graphemes,
15303 is_whitespace: false,
15304 })
15305 }
15306 } else {
15307 None
15308 }
15309 }
15310}
15311
15312#[test]
15313fn test_word_breaking_tokenizer() {
15314 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15315 ("", &[]),
15316 (" ", &[(" ", 1, true)]),
15317 ("Ʒ", &[("Ʒ", 1, false)]),
15318 ("Ǽ", &[("Ǽ", 1, false)]),
15319 ("⋑", &[("⋑", 1, false)]),
15320 ("⋑⋑", &[("⋑⋑", 2, false)]),
15321 (
15322 "原理,进而",
15323 &[
15324 ("原", 1, false),
15325 ("理,", 2, false),
15326 ("进", 1, false),
15327 ("而", 1, false),
15328 ],
15329 ),
15330 (
15331 "hello world",
15332 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15333 ),
15334 (
15335 "hello, world",
15336 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15337 ),
15338 (
15339 " hello world",
15340 &[
15341 (" ", 1, true),
15342 ("hello", 5, false),
15343 (" ", 1, true),
15344 ("world", 5, false),
15345 ],
15346 ),
15347 (
15348 "这是什么 \n 钢笔",
15349 &[
15350 ("这", 1, false),
15351 ("是", 1, false),
15352 ("什", 1, false),
15353 ("么", 1, false),
15354 (" ", 1, true),
15355 ("钢", 1, false),
15356 ("笔", 1, false),
15357 ],
15358 ),
15359 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15360 ];
15361
15362 for (input, result) in tests {
15363 assert_eq!(
15364 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15365 result
15366 .iter()
15367 .copied()
15368 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15369 token,
15370 grapheme_len,
15371 is_whitespace,
15372 })
15373 .collect::<Vec<_>>()
15374 );
15375 }
15376}
15377
15378fn wrap_with_prefix(
15379 line_prefix: String,
15380 unwrapped_text: String,
15381 wrap_column: usize,
15382 tab_size: NonZeroU32,
15383) -> String {
15384 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15385 let mut wrapped_text = String::new();
15386 let mut current_line = line_prefix.clone();
15387
15388 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15389 let mut current_line_len = line_prefix_len;
15390 for WordBreakToken {
15391 token,
15392 grapheme_len,
15393 is_whitespace,
15394 } in tokenizer
15395 {
15396 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15397 wrapped_text.push_str(current_line.trim_end());
15398 wrapped_text.push('\n');
15399 current_line.truncate(line_prefix.len());
15400 current_line_len = line_prefix_len;
15401 if !is_whitespace {
15402 current_line.push_str(token);
15403 current_line_len += grapheme_len;
15404 }
15405 } else if !is_whitespace {
15406 current_line.push_str(token);
15407 current_line_len += grapheme_len;
15408 } else if current_line_len != line_prefix_len {
15409 current_line.push(' ');
15410 current_line_len += 1;
15411 }
15412 }
15413
15414 if !current_line.is_empty() {
15415 wrapped_text.push_str(¤t_line);
15416 }
15417 wrapped_text
15418}
15419
15420#[test]
15421fn test_wrap_with_prefix() {
15422 assert_eq!(
15423 wrap_with_prefix(
15424 "# ".to_string(),
15425 "abcdefg".to_string(),
15426 4,
15427 NonZeroU32::new(4).unwrap()
15428 ),
15429 "# abcdefg"
15430 );
15431 assert_eq!(
15432 wrap_with_prefix(
15433 "".to_string(),
15434 "\thello world".to_string(),
15435 8,
15436 NonZeroU32::new(4).unwrap()
15437 ),
15438 "hello\nworld"
15439 );
15440 assert_eq!(
15441 wrap_with_prefix(
15442 "// ".to_string(),
15443 "xx \nyy zz aa bb cc".to_string(),
15444 12,
15445 NonZeroU32::new(4).unwrap()
15446 ),
15447 "// xx yy zz\n// aa bb cc"
15448 );
15449 assert_eq!(
15450 wrap_with_prefix(
15451 String::new(),
15452 "这是什么 \n 钢笔".to_string(),
15453 3,
15454 NonZeroU32::new(4).unwrap()
15455 ),
15456 "这是什\n么 钢\n笔"
15457 );
15458}
15459
15460pub trait CollaborationHub {
15461 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15462 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15463 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15464}
15465
15466impl CollaborationHub for Entity<Project> {
15467 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15468 self.read(cx).collaborators()
15469 }
15470
15471 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15472 self.read(cx).user_store().read(cx).participant_indices()
15473 }
15474
15475 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15476 let this = self.read(cx);
15477 let user_ids = this.collaborators().values().map(|c| c.user_id);
15478 this.user_store().read_with(cx, |user_store, cx| {
15479 user_store.participant_names(user_ids, cx)
15480 })
15481 }
15482}
15483
15484pub trait SemanticsProvider {
15485 fn hover(
15486 &self,
15487 buffer: &Entity<Buffer>,
15488 position: text::Anchor,
15489 cx: &mut App,
15490 ) -> Option<Task<Vec<project::Hover>>>;
15491
15492 fn inlay_hints(
15493 &self,
15494 buffer_handle: Entity<Buffer>,
15495 range: Range<text::Anchor>,
15496 cx: &mut App,
15497 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15498
15499 fn resolve_inlay_hint(
15500 &self,
15501 hint: InlayHint,
15502 buffer_handle: Entity<Buffer>,
15503 server_id: LanguageServerId,
15504 cx: &mut App,
15505 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15506
15507 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15508
15509 fn document_highlights(
15510 &self,
15511 buffer: &Entity<Buffer>,
15512 position: text::Anchor,
15513 cx: &mut App,
15514 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15515
15516 fn definitions(
15517 &self,
15518 buffer: &Entity<Buffer>,
15519 position: text::Anchor,
15520 kind: GotoDefinitionKind,
15521 cx: &mut App,
15522 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15523
15524 fn range_for_rename(
15525 &self,
15526 buffer: &Entity<Buffer>,
15527 position: text::Anchor,
15528 cx: &mut App,
15529 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15530
15531 fn perform_rename(
15532 &self,
15533 buffer: &Entity<Buffer>,
15534 position: text::Anchor,
15535 new_name: String,
15536 cx: &mut App,
15537 ) -> Option<Task<Result<ProjectTransaction>>>;
15538}
15539
15540pub trait CompletionProvider {
15541 fn completions(
15542 &self,
15543 buffer: &Entity<Buffer>,
15544 buffer_position: text::Anchor,
15545 trigger: CompletionContext,
15546 window: &mut Window,
15547 cx: &mut Context<Editor>,
15548 ) -> Task<Result<Vec<Completion>>>;
15549
15550 fn resolve_completions(
15551 &self,
15552 buffer: Entity<Buffer>,
15553 completion_indices: Vec<usize>,
15554 completions: Rc<RefCell<Box<[Completion]>>>,
15555 cx: &mut Context<Editor>,
15556 ) -> Task<Result<bool>>;
15557
15558 fn apply_additional_edits_for_completion(
15559 &self,
15560 _buffer: Entity<Buffer>,
15561 _completions: Rc<RefCell<Box<[Completion]>>>,
15562 _completion_index: usize,
15563 _push_to_history: bool,
15564 _cx: &mut Context<Editor>,
15565 ) -> Task<Result<Option<language::Transaction>>> {
15566 Task::ready(Ok(None))
15567 }
15568
15569 fn is_completion_trigger(
15570 &self,
15571 buffer: &Entity<Buffer>,
15572 position: language::Anchor,
15573 text: &str,
15574 trigger_in_words: bool,
15575 cx: &mut Context<Editor>,
15576 ) -> bool;
15577
15578 fn sort_completions(&self) -> bool {
15579 true
15580 }
15581}
15582
15583pub trait CodeActionProvider {
15584 fn id(&self) -> Arc<str>;
15585
15586 fn code_actions(
15587 &self,
15588 buffer: &Entity<Buffer>,
15589 range: Range<text::Anchor>,
15590 window: &mut Window,
15591 cx: &mut App,
15592 ) -> Task<Result<Vec<CodeAction>>>;
15593
15594 fn apply_code_action(
15595 &self,
15596 buffer_handle: Entity<Buffer>,
15597 action: CodeAction,
15598 excerpt_id: ExcerptId,
15599 push_to_history: bool,
15600 window: &mut Window,
15601 cx: &mut App,
15602 ) -> Task<Result<ProjectTransaction>>;
15603}
15604
15605impl CodeActionProvider for Entity<Project> {
15606 fn id(&self) -> Arc<str> {
15607 "project".into()
15608 }
15609
15610 fn code_actions(
15611 &self,
15612 buffer: &Entity<Buffer>,
15613 range: Range<text::Anchor>,
15614 _window: &mut Window,
15615 cx: &mut App,
15616 ) -> Task<Result<Vec<CodeAction>>> {
15617 self.update(cx, |project, cx| {
15618 project.code_actions(buffer, range, None, cx)
15619 })
15620 }
15621
15622 fn apply_code_action(
15623 &self,
15624 buffer_handle: Entity<Buffer>,
15625 action: CodeAction,
15626 _excerpt_id: ExcerptId,
15627 push_to_history: bool,
15628 _window: &mut Window,
15629 cx: &mut App,
15630 ) -> Task<Result<ProjectTransaction>> {
15631 self.update(cx, |project, cx| {
15632 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15633 })
15634 }
15635}
15636
15637fn snippet_completions(
15638 project: &Project,
15639 buffer: &Entity<Buffer>,
15640 buffer_position: text::Anchor,
15641 cx: &mut App,
15642) -> Task<Result<Vec<Completion>>> {
15643 let language = buffer.read(cx).language_at(buffer_position);
15644 let language_name = language.as_ref().map(|language| language.lsp_id());
15645 let snippet_store = project.snippets().read(cx);
15646 let snippets = snippet_store.snippets_for(language_name, cx);
15647
15648 if snippets.is_empty() {
15649 return Task::ready(Ok(vec![]));
15650 }
15651 let snapshot = buffer.read(cx).text_snapshot();
15652 let chars: String = snapshot
15653 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15654 .collect();
15655
15656 let scope = language.map(|language| language.default_scope());
15657 let executor = cx.background_executor().clone();
15658
15659 cx.background_spawn(async move {
15660 let classifier = CharClassifier::new(scope).for_completion(true);
15661 let mut last_word = chars
15662 .chars()
15663 .take_while(|c| classifier.is_word(*c))
15664 .collect::<String>();
15665 last_word = last_word.chars().rev().collect();
15666
15667 if last_word.is_empty() {
15668 return Ok(vec![]);
15669 }
15670
15671 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15672 let to_lsp = |point: &text::Anchor| {
15673 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15674 point_to_lsp(end)
15675 };
15676 let lsp_end = to_lsp(&buffer_position);
15677
15678 let candidates = snippets
15679 .iter()
15680 .enumerate()
15681 .flat_map(|(ix, snippet)| {
15682 snippet
15683 .prefix
15684 .iter()
15685 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15686 })
15687 .collect::<Vec<StringMatchCandidate>>();
15688
15689 let mut matches = fuzzy::match_strings(
15690 &candidates,
15691 &last_word,
15692 last_word.chars().any(|c| c.is_uppercase()),
15693 100,
15694 &Default::default(),
15695 executor,
15696 )
15697 .await;
15698
15699 // Remove all candidates where the query's start does not match the start of any word in the candidate
15700 if let Some(query_start) = last_word.chars().next() {
15701 matches.retain(|string_match| {
15702 split_words(&string_match.string).any(|word| {
15703 // Check that the first codepoint of the word as lowercase matches the first
15704 // codepoint of the query as lowercase
15705 word.chars()
15706 .flat_map(|codepoint| codepoint.to_lowercase())
15707 .zip(query_start.to_lowercase())
15708 .all(|(word_cp, query_cp)| word_cp == query_cp)
15709 })
15710 });
15711 }
15712
15713 let matched_strings = matches
15714 .into_iter()
15715 .map(|m| m.string)
15716 .collect::<HashSet<_>>();
15717
15718 let result: Vec<Completion> = snippets
15719 .into_iter()
15720 .filter_map(|snippet| {
15721 let matching_prefix = snippet
15722 .prefix
15723 .iter()
15724 .find(|prefix| matched_strings.contains(*prefix))?;
15725 let start = as_offset - last_word.len();
15726 let start = snapshot.anchor_before(start);
15727 let range = start..buffer_position;
15728 let lsp_start = to_lsp(&start);
15729 let lsp_range = lsp::Range {
15730 start: lsp_start,
15731 end: lsp_end,
15732 };
15733 Some(Completion {
15734 old_range: range,
15735 new_text: snippet.body.clone(),
15736 resolved: false,
15737 label: CodeLabel {
15738 text: matching_prefix.clone(),
15739 runs: vec![],
15740 filter_range: 0..matching_prefix.len(),
15741 },
15742 server_id: LanguageServerId(usize::MAX),
15743 documentation: snippet
15744 .description
15745 .clone()
15746 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15747 lsp_completion: lsp::CompletionItem {
15748 label: snippet.prefix.first().unwrap().clone(),
15749 kind: Some(CompletionItemKind::SNIPPET),
15750 label_details: snippet.description.as_ref().map(|description| {
15751 lsp::CompletionItemLabelDetails {
15752 detail: Some(description.clone()),
15753 description: None,
15754 }
15755 }),
15756 insert_text_format: Some(InsertTextFormat::SNIPPET),
15757 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15758 lsp::InsertReplaceEdit {
15759 new_text: snippet.body.clone(),
15760 insert: lsp_range,
15761 replace: lsp_range,
15762 },
15763 )),
15764 filter_text: Some(snippet.body.clone()),
15765 sort_text: Some(char::MAX.to_string()),
15766 ..Default::default()
15767 },
15768 confirm: None,
15769 })
15770 })
15771 .collect();
15772
15773 Ok(result)
15774 })
15775}
15776
15777impl CompletionProvider for Entity<Project> {
15778 fn completions(
15779 &self,
15780 buffer: &Entity<Buffer>,
15781 buffer_position: text::Anchor,
15782 options: CompletionContext,
15783 _window: &mut Window,
15784 cx: &mut Context<Editor>,
15785 ) -> Task<Result<Vec<Completion>>> {
15786 self.update(cx, |project, cx| {
15787 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15788 let project_completions = project.completions(buffer, buffer_position, options, cx);
15789 cx.background_spawn(async move {
15790 let mut completions = project_completions.await?;
15791 let snippets_completions = snippets.await?;
15792 completions.extend(snippets_completions);
15793 Ok(completions)
15794 })
15795 })
15796 }
15797
15798 fn resolve_completions(
15799 &self,
15800 buffer: Entity<Buffer>,
15801 completion_indices: Vec<usize>,
15802 completions: Rc<RefCell<Box<[Completion]>>>,
15803 cx: &mut Context<Editor>,
15804 ) -> Task<Result<bool>> {
15805 self.update(cx, |project, cx| {
15806 project.lsp_store().update(cx, |lsp_store, cx| {
15807 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15808 })
15809 })
15810 }
15811
15812 fn apply_additional_edits_for_completion(
15813 &self,
15814 buffer: Entity<Buffer>,
15815 completions: Rc<RefCell<Box<[Completion]>>>,
15816 completion_index: usize,
15817 push_to_history: bool,
15818 cx: &mut Context<Editor>,
15819 ) -> Task<Result<Option<language::Transaction>>> {
15820 self.update(cx, |project, cx| {
15821 project.lsp_store().update(cx, |lsp_store, cx| {
15822 lsp_store.apply_additional_edits_for_completion(
15823 buffer,
15824 completions,
15825 completion_index,
15826 push_to_history,
15827 cx,
15828 )
15829 })
15830 })
15831 }
15832
15833 fn is_completion_trigger(
15834 &self,
15835 buffer: &Entity<Buffer>,
15836 position: language::Anchor,
15837 text: &str,
15838 trigger_in_words: bool,
15839 cx: &mut Context<Editor>,
15840 ) -> bool {
15841 let mut chars = text.chars();
15842 let char = if let Some(char) = chars.next() {
15843 char
15844 } else {
15845 return false;
15846 };
15847 if chars.next().is_some() {
15848 return false;
15849 }
15850
15851 let buffer = buffer.read(cx);
15852 let snapshot = buffer.snapshot();
15853 if !snapshot.settings_at(position, cx).show_completions_on_input {
15854 return false;
15855 }
15856 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15857 if trigger_in_words && classifier.is_word(char) {
15858 return true;
15859 }
15860
15861 buffer.completion_triggers().contains(text)
15862 }
15863}
15864
15865impl SemanticsProvider for Entity<Project> {
15866 fn hover(
15867 &self,
15868 buffer: &Entity<Buffer>,
15869 position: text::Anchor,
15870 cx: &mut App,
15871 ) -> Option<Task<Vec<project::Hover>>> {
15872 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15873 }
15874
15875 fn document_highlights(
15876 &self,
15877 buffer: &Entity<Buffer>,
15878 position: text::Anchor,
15879 cx: &mut App,
15880 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15881 Some(self.update(cx, |project, cx| {
15882 project.document_highlights(buffer, position, cx)
15883 }))
15884 }
15885
15886 fn definitions(
15887 &self,
15888 buffer: &Entity<Buffer>,
15889 position: text::Anchor,
15890 kind: GotoDefinitionKind,
15891 cx: &mut App,
15892 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15893 Some(self.update(cx, |project, cx| match kind {
15894 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15895 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15896 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15897 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15898 }))
15899 }
15900
15901 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15902 // TODO: make this work for remote projects
15903 self.update(cx, |this, cx| {
15904 buffer.update(cx, |buffer, cx| {
15905 this.any_language_server_supports_inlay_hints(buffer, cx)
15906 })
15907 })
15908 }
15909
15910 fn inlay_hints(
15911 &self,
15912 buffer_handle: Entity<Buffer>,
15913 range: Range<text::Anchor>,
15914 cx: &mut App,
15915 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15916 Some(self.update(cx, |project, cx| {
15917 project.inlay_hints(buffer_handle, range, cx)
15918 }))
15919 }
15920
15921 fn resolve_inlay_hint(
15922 &self,
15923 hint: InlayHint,
15924 buffer_handle: Entity<Buffer>,
15925 server_id: LanguageServerId,
15926 cx: &mut App,
15927 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15928 Some(self.update(cx, |project, cx| {
15929 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15930 }))
15931 }
15932
15933 fn range_for_rename(
15934 &self,
15935 buffer: &Entity<Buffer>,
15936 position: text::Anchor,
15937 cx: &mut App,
15938 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15939 Some(self.update(cx, |project, cx| {
15940 let buffer = buffer.clone();
15941 let task = project.prepare_rename(buffer.clone(), position, cx);
15942 cx.spawn(|_, mut cx| async move {
15943 Ok(match task.await? {
15944 PrepareRenameResponse::Success(range) => Some(range),
15945 PrepareRenameResponse::InvalidPosition => None,
15946 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15947 // Fallback on using TreeSitter info to determine identifier range
15948 buffer.update(&mut cx, |buffer, _| {
15949 let snapshot = buffer.snapshot();
15950 let (range, kind) = snapshot.surrounding_word(position);
15951 if kind != Some(CharKind::Word) {
15952 return None;
15953 }
15954 Some(
15955 snapshot.anchor_before(range.start)
15956 ..snapshot.anchor_after(range.end),
15957 )
15958 })?
15959 }
15960 })
15961 })
15962 }))
15963 }
15964
15965 fn perform_rename(
15966 &self,
15967 buffer: &Entity<Buffer>,
15968 position: text::Anchor,
15969 new_name: String,
15970 cx: &mut App,
15971 ) -> Option<Task<Result<ProjectTransaction>>> {
15972 Some(self.update(cx, |project, cx| {
15973 project.perform_rename(buffer.clone(), position, new_name, cx)
15974 }))
15975 }
15976}
15977
15978fn inlay_hint_settings(
15979 location: Anchor,
15980 snapshot: &MultiBufferSnapshot,
15981 cx: &mut Context<Editor>,
15982) -> InlayHintSettings {
15983 let file = snapshot.file_at(location);
15984 let language = snapshot.language_at(location).map(|l| l.name());
15985 language_settings(language, file, cx).inlay_hints
15986}
15987
15988fn consume_contiguous_rows(
15989 contiguous_row_selections: &mut Vec<Selection<Point>>,
15990 selection: &Selection<Point>,
15991 display_map: &DisplaySnapshot,
15992 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15993) -> (MultiBufferRow, MultiBufferRow) {
15994 contiguous_row_selections.push(selection.clone());
15995 let start_row = MultiBufferRow(selection.start.row);
15996 let mut end_row = ending_row(selection, display_map);
15997
15998 while let Some(next_selection) = selections.peek() {
15999 if next_selection.start.row <= end_row.0 {
16000 end_row = ending_row(next_selection, display_map);
16001 contiguous_row_selections.push(selections.next().unwrap().clone());
16002 } else {
16003 break;
16004 }
16005 }
16006 (start_row, end_row)
16007}
16008
16009fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16010 if next_selection.end.column > 0 || next_selection.is_empty() {
16011 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16012 } else {
16013 MultiBufferRow(next_selection.end.row)
16014 }
16015}
16016
16017impl EditorSnapshot {
16018 pub fn remote_selections_in_range<'a>(
16019 &'a self,
16020 range: &'a Range<Anchor>,
16021 collaboration_hub: &dyn CollaborationHub,
16022 cx: &'a App,
16023 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16024 let participant_names = collaboration_hub.user_names(cx);
16025 let participant_indices = collaboration_hub.user_participant_indices(cx);
16026 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16027 let collaborators_by_replica_id = collaborators_by_peer_id
16028 .iter()
16029 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16030 .collect::<HashMap<_, _>>();
16031 self.buffer_snapshot
16032 .selections_in_range(range, false)
16033 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16034 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16035 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16036 let user_name = participant_names.get(&collaborator.user_id).cloned();
16037 Some(RemoteSelection {
16038 replica_id,
16039 selection,
16040 cursor_shape,
16041 line_mode,
16042 participant_index,
16043 peer_id: collaborator.peer_id,
16044 user_name,
16045 })
16046 })
16047 }
16048
16049 pub fn hunks_for_ranges(
16050 &self,
16051 ranges: impl Iterator<Item = Range<Point>>,
16052 ) -> Vec<MultiBufferDiffHunk> {
16053 let mut hunks = Vec::new();
16054 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16055 HashMap::default();
16056 for query_range in ranges {
16057 let query_rows =
16058 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16059 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16060 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16061 ) {
16062 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16063 // when the caret is just above or just below the deleted hunk.
16064 let allow_adjacent = hunk.status().is_deleted();
16065 let related_to_selection = if allow_adjacent {
16066 hunk.row_range.overlaps(&query_rows)
16067 || hunk.row_range.start == query_rows.end
16068 || hunk.row_range.end == query_rows.start
16069 } else {
16070 hunk.row_range.overlaps(&query_rows)
16071 };
16072 if related_to_selection {
16073 if !processed_buffer_rows
16074 .entry(hunk.buffer_id)
16075 .or_default()
16076 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16077 {
16078 continue;
16079 }
16080 hunks.push(hunk);
16081 }
16082 }
16083 }
16084
16085 hunks
16086 }
16087
16088 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16089 self.display_snapshot.buffer_snapshot.language_at(position)
16090 }
16091
16092 pub fn is_focused(&self) -> bool {
16093 self.is_focused
16094 }
16095
16096 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16097 self.placeholder_text.as_ref()
16098 }
16099
16100 pub fn scroll_position(&self) -> gpui::Point<f32> {
16101 self.scroll_anchor.scroll_position(&self.display_snapshot)
16102 }
16103
16104 fn gutter_dimensions(
16105 &self,
16106 font_id: FontId,
16107 font_size: Pixels,
16108 max_line_number_width: Pixels,
16109 cx: &App,
16110 ) -> Option<GutterDimensions> {
16111 if !self.show_gutter {
16112 return None;
16113 }
16114
16115 let descent = cx.text_system().descent(font_id, font_size);
16116 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16117 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16118
16119 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16120 matches!(
16121 ProjectSettings::get_global(cx).git.git_gutter,
16122 Some(GitGutterSetting::TrackedFiles)
16123 )
16124 });
16125 let gutter_settings = EditorSettings::get_global(cx).gutter;
16126 let show_line_numbers = self
16127 .show_line_numbers
16128 .unwrap_or(gutter_settings.line_numbers);
16129 let line_gutter_width = if show_line_numbers {
16130 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16131 let min_width_for_number_on_gutter = em_advance * 4.0;
16132 max_line_number_width.max(min_width_for_number_on_gutter)
16133 } else {
16134 0.0.into()
16135 };
16136
16137 let show_code_actions = self
16138 .show_code_actions
16139 .unwrap_or(gutter_settings.code_actions);
16140
16141 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16142
16143 let git_blame_entries_width =
16144 self.git_blame_gutter_max_author_length
16145 .map(|max_author_length| {
16146 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16147
16148 /// The number of characters to dedicate to gaps and margins.
16149 const SPACING_WIDTH: usize = 4;
16150
16151 let max_char_count = max_author_length
16152 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16153 + ::git::SHORT_SHA_LENGTH
16154 + MAX_RELATIVE_TIMESTAMP.len()
16155 + SPACING_WIDTH;
16156
16157 em_advance * max_char_count
16158 });
16159
16160 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16161 left_padding += if show_code_actions || show_runnables {
16162 em_width * 3.0
16163 } else if show_git_gutter && show_line_numbers {
16164 em_width * 2.0
16165 } else if show_git_gutter || show_line_numbers {
16166 em_width
16167 } else {
16168 px(0.)
16169 };
16170
16171 let right_padding = if gutter_settings.folds && show_line_numbers {
16172 em_width * 4.0
16173 } else if gutter_settings.folds {
16174 em_width * 3.0
16175 } else if show_line_numbers {
16176 em_width
16177 } else {
16178 px(0.)
16179 };
16180
16181 Some(GutterDimensions {
16182 left_padding,
16183 right_padding,
16184 width: line_gutter_width + left_padding + right_padding,
16185 margin: -descent,
16186 git_blame_entries_width,
16187 })
16188 }
16189
16190 pub fn render_crease_toggle(
16191 &self,
16192 buffer_row: MultiBufferRow,
16193 row_contains_cursor: bool,
16194 editor: Entity<Editor>,
16195 window: &mut Window,
16196 cx: &mut App,
16197 ) -> Option<AnyElement> {
16198 let folded = self.is_line_folded(buffer_row);
16199 let mut is_foldable = false;
16200
16201 if let Some(crease) = self
16202 .crease_snapshot
16203 .query_row(buffer_row, &self.buffer_snapshot)
16204 {
16205 is_foldable = true;
16206 match crease {
16207 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16208 if let Some(render_toggle) = render_toggle {
16209 let toggle_callback =
16210 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16211 if folded {
16212 editor.update(cx, |editor, cx| {
16213 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16214 });
16215 } else {
16216 editor.update(cx, |editor, cx| {
16217 editor.unfold_at(
16218 &crate::UnfoldAt { buffer_row },
16219 window,
16220 cx,
16221 )
16222 });
16223 }
16224 });
16225 return Some((render_toggle)(
16226 buffer_row,
16227 folded,
16228 toggle_callback,
16229 window,
16230 cx,
16231 ));
16232 }
16233 }
16234 }
16235 }
16236
16237 is_foldable |= self.starts_indent(buffer_row);
16238
16239 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16240 Some(
16241 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16242 .toggle_state(folded)
16243 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16244 if folded {
16245 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16246 } else {
16247 this.fold_at(&FoldAt { buffer_row }, window, cx);
16248 }
16249 }))
16250 .into_any_element(),
16251 )
16252 } else {
16253 None
16254 }
16255 }
16256
16257 pub fn render_crease_trailer(
16258 &self,
16259 buffer_row: MultiBufferRow,
16260 window: &mut Window,
16261 cx: &mut App,
16262 ) -> Option<AnyElement> {
16263 let folded = self.is_line_folded(buffer_row);
16264 if let Crease::Inline { render_trailer, .. } = self
16265 .crease_snapshot
16266 .query_row(buffer_row, &self.buffer_snapshot)?
16267 {
16268 let render_trailer = render_trailer.as_ref()?;
16269 Some(render_trailer(buffer_row, folded, window, cx))
16270 } else {
16271 None
16272 }
16273 }
16274}
16275
16276impl Deref for EditorSnapshot {
16277 type Target = DisplaySnapshot;
16278
16279 fn deref(&self) -> &Self::Target {
16280 &self.display_snapshot
16281 }
16282}
16283
16284#[derive(Clone, Debug, PartialEq, Eq)]
16285pub enum EditorEvent {
16286 InputIgnored {
16287 text: Arc<str>,
16288 },
16289 InputHandled {
16290 utf16_range_to_replace: Option<Range<isize>>,
16291 text: Arc<str>,
16292 },
16293 ExcerptsAdded {
16294 buffer: Entity<Buffer>,
16295 predecessor: ExcerptId,
16296 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16297 },
16298 ExcerptsRemoved {
16299 ids: Vec<ExcerptId>,
16300 },
16301 BufferFoldToggled {
16302 ids: Vec<ExcerptId>,
16303 folded: bool,
16304 },
16305 ExcerptsEdited {
16306 ids: Vec<ExcerptId>,
16307 },
16308 ExcerptsExpanded {
16309 ids: Vec<ExcerptId>,
16310 },
16311 BufferEdited,
16312 Edited {
16313 transaction_id: clock::Lamport,
16314 },
16315 Reparsed(BufferId),
16316 Focused,
16317 FocusedIn,
16318 Blurred,
16319 DirtyChanged,
16320 Saved,
16321 TitleChanged,
16322 DiffBaseChanged,
16323 SelectionsChanged {
16324 local: bool,
16325 },
16326 ScrollPositionChanged {
16327 local: bool,
16328 autoscroll: bool,
16329 },
16330 Closed,
16331 TransactionUndone {
16332 transaction_id: clock::Lamport,
16333 },
16334 TransactionBegun {
16335 transaction_id: clock::Lamport,
16336 },
16337 Reloaded,
16338 CursorShapeChanged,
16339}
16340
16341impl EventEmitter<EditorEvent> for Editor {}
16342
16343impl Focusable for Editor {
16344 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16345 self.focus_handle.clone()
16346 }
16347}
16348
16349impl Render for Editor {
16350 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16351 let settings = ThemeSettings::get_global(cx);
16352
16353 let mut text_style = match self.mode {
16354 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16355 color: cx.theme().colors().editor_foreground,
16356 font_family: settings.ui_font.family.clone(),
16357 font_features: settings.ui_font.features.clone(),
16358 font_fallbacks: settings.ui_font.fallbacks.clone(),
16359 font_size: rems(0.875).into(),
16360 font_weight: settings.ui_font.weight,
16361 line_height: relative(settings.buffer_line_height.value()),
16362 ..Default::default()
16363 },
16364 EditorMode::Full => TextStyle {
16365 color: cx.theme().colors().editor_foreground,
16366 font_family: settings.buffer_font.family.clone(),
16367 font_features: settings.buffer_font.features.clone(),
16368 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16369 font_size: settings.buffer_font_size(cx).into(),
16370 font_weight: settings.buffer_font.weight,
16371 line_height: relative(settings.buffer_line_height.value()),
16372 ..Default::default()
16373 },
16374 };
16375 if let Some(text_style_refinement) = &self.text_style_refinement {
16376 text_style.refine(text_style_refinement)
16377 }
16378
16379 let background = match self.mode {
16380 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16381 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16382 EditorMode::Full => cx.theme().colors().editor_background,
16383 };
16384
16385 EditorElement::new(
16386 &cx.entity(),
16387 EditorStyle {
16388 background,
16389 local_player: cx.theme().players().local(),
16390 text: text_style,
16391 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16392 syntax: cx.theme().syntax().clone(),
16393 status: cx.theme().status().clone(),
16394 inlay_hints_style: make_inlay_hints_style(cx),
16395 inline_completion_styles: make_suggestion_styles(cx),
16396 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16397 },
16398 )
16399 }
16400}
16401
16402impl EntityInputHandler for Editor {
16403 fn text_for_range(
16404 &mut self,
16405 range_utf16: Range<usize>,
16406 adjusted_range: &mut Option<Range<usize>>,
16407 _: &mut Window,
16408 cx: &mut Context<Self>,
16409 ) -> Option<String> {
16410 let snapshot = self.buffer.read(cx).read(cx);
16411 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16412 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16413 if (start.0..end.0) != range_utf16 {
16414 adjusted_range.replace(start.0..end.0);
16415 }
16416 Some(snapshot.text_for_range(start..end).collect())
16417 }
16418
16419 fn selected_text_range(
16420 &mut self,
16421 ignore_disabled_input: bool,
16422 _: &mut Window,
16423 cx: &mut Context<Self>,
16424 ) -> Option<UTF16Selection> {
16425 // Prevent the IME menu from appearing when holding down an alphabetic key
16426 // while input is disabled.
16427 if !ignore_disabled_input && !self.input_enabled {
16428 return None;
16429 }
16430
16431 let selection = self.selections.newest::<OffsetUtf16>(cx);
16432 let range = selection.range();
16433
16434 Some(UTF16Selection {
16435 range: range.start.0..range.end.0,
16436 reversed: selection.reversed,
16437 })
16438 }
16439
16440 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16441 let snapshot = self.buffer.read(cx).read(cx);
16442 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16443 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16444 }
16445
16446 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16447 self.clear_highlights::<InputComposition>(cx);
16448 self.ime_transaction.take();
16449 }
16450
16451 fn replace_text_in_range(
16452 &mut self,
16453 range_utf16: Option<Range<usize>>,
16454 text: &str,
16455 window: &mut Window,
16456 cx: &mut Context<Self>,
16457 ) {
16458 if !self.input_enabled {
16459 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16460 return;
16461 }
16462
16463 self.transact(window, cx, |this, window, cx| {
16464 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16465 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16466 Some(this.selection_replacement_ranges(range_utf16, cx))
16467 } else {
16468 this.marked_text_ranges(cx)
16469 };
16470
16471 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16472 let newest_selection_id = this.selections.newest_anchor().id;
16473 this.selections
16474 .all::<OffsetUtf16>(cx)
16475 .iter()
16476 .zip(ranges_to_replace.iter())
16477 .find_map(|(selection, range)| {
16478 if selection.id == newest_selection_id {
16479 Some(
16480 (range.start.0 as isize - selection.head().0 as isize)
16481 ..(range.end.0 as isize - selection.head().0 as isize),
16482 )
16483 } else {
16484 None
16485 }
16486 })
16487 });
16488
16489 cx.emit(EditorEvent::InputHandled {
16490 utf16_range_to_replace: range_to_replace,
16491 text: text.into(),
16492 });
16493
16494 if let Some(new_selected_ranges) = new_selected_ranges {
16495 this.change_selections(None, window, cx, |selections| {
16496 selections.select_ranges(new_selected_ranges)
16497 });
16498 this.backspace(&Default::default(), window, cx);
16499 }
16500
16501 this.handle_input(text, window, cx);
16502 });
16503
16504 if let Some(transaction) = self.ime_transaction {
16505 self.buffer.update(cx, |buffer, cx| {
16506 buffer.group_until_transaction(transaction, cx);
16507 });
16508 }
16509
16510 self.unmark_text(window, cx);
16511 }
16512
16513 fn replace_and_mark_text_in_range(
16514 &mut self,
16515 range_utf16: Option<Range<usize>>,
16516 text: &str,
16517 new_selected_range_utf16: Option<Range<usize>>,
16518 window: &mut Window,
16519 cx: &mut Context<Self>,
16520 ) {
16521 if !self.input_enabled {
16522 return;
16523 }
16524
16525 let transaction = self.transact(window, cx, |this, window, cx| {
16526 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16527 let snapshot = this.buffer.read(cx).read(cx);
16528 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16529 for marked_range in &mut marked_ranges {
16530 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16531 marked_range.start.0 += relative_range_utf16.start;
16532 marked_range.start =
16533 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16534 marked_range.end =
16535 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16536 }
16537 }
16538 Some(marked_ranges)
16539 } else if let Some(range_utf16) = range_utf16 {
16540 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16541 Some(this.selection_replacement_ranges(range_utf16, cx))
16542 } else {
16543 None
16544 };
16545
16546 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16547 let newest_selection_id = this.selections.newest_anchor().id;
16548 this.selections
16549 .all::<OffsetUtf16>(cx)
16550 .iter()
16551 .zip(ranges_to_replace.iter())
16552 .find_map(|(selection, range)| {
16553 if selection.id == newest_selection_id {
16554 Some(
16555 (range.start.0 as isize - selection.head().0 as isize)
16556 ..(range.end.0 as isize - selection.head().0 as isize),
16557 )
16558 } else {
16559 None
16560 }
16561 })
16562 });
16563
16564 cx.emit(EditorEvent::InputHandled {
16565 utf16_range_to_replace: range_to_replace,
16566 text: text.into(),
16567 });
16568
16569 if let Some(ranges) = ranges_to_replace {
16570 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16571 }
16572
16573 let marked_ranges = {
16574 let snapshot = this.buffer.read(cx).read(cx);
16575 this.selections
16576 .disjoint_anchors()
16577 .iter()
16578 .map(|selection| {
16579 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16580 })
16581 .collect::<Vec<_>>()
16582 };
16583
16584 if text.is_empty() {
16585 this.unmark_text(window, cx);
16586 } else {
16587 this.highlight_text::<InputComposition>(
16588 marked_ranges.clone(),
16589 HighlightStyle {
16590 underline: Some(UnderlineStyle {
16591 thickness: px(1.),
16592 color: None,
16593 wavy: false,
16594 }),
16595 ..Default::default()
16596 },
16597 cx,
16598 );
16599 }
16600
16601 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16602 let use_autoclose = this.use_autoclose;
16603 let use_auto_surround = this.use_auto_surround;
16604 this.set_use_autoclose(false);
16605 this.set_use_auto_surround(false);
16606 this.handle_input(text, window, cx);
16607 this.set_use_autoclose(use_autoclose);
16608 this.set_use_auto_surround(use_auto_surround);
16609
16610 if let Some(new_selected_range) = new_selected_range_utf16 {
16611 let snapshot = this.buffer.read(cx).read(cx);
16612 let new_selected_ranges = marked_ranges
16613 .into_iter()
16614 .map(|marked_range| {
16615 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16616 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16617 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16618 snapshot.clip_offset_utf16(new_start, Bias::Left)
16619 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16620 })
16621 .collect::<Vec<_>>();
16622
16623 drop(snapshot);
16624 this.change_selections(None, window, cx, |selections| {
16625 selections.select_ranges(new_selected_ranges)
16626 });
16627 }
16628 });
16629
16630 self.ime_transaction = self.ime_transaction.or(transaction);
16631 if let Some(transaction) = self.ime_transaction {
16632 self.buffer.update(cx, |buffer, cx| {
16633 buffer.group_until_transaction(transaction, cx);
16634 });
16635 }
16636
16637 if self.text_highlights::<InputComposition>(cx).is_none() {
16638 self.ime_transaction.take();
16639 }
16640 }
16641
16642 fn bounds_for_range(
16643 &mut self,
16644 range_utf16: Range<usize>,
16645 element_bounds: gpui::Bounds<Pixels>,
16646 window: &mut Window,
16647 cx: &mut Context<Self>,
16648 ) -> Option<gpui::Bounds<Pixels>> {
16649 let text_layout_details = self.text_layout_details(window);
16650 let gpui::Size {
16651 width: em_width,
16652 height: line_height,
16653 } = self.character_size(window);
16654
16655 let snapshot = self.snapshot(window, cx);
16656 let scroll_position = snapshot.scroll_position();
16657 let scroll_left = scroll_position.x * em_width;
16658
16659 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16660 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16661 + self.gutter_dimensions.width
16662 + self.gutter_dimensions.margin;
16663 let y = line_height * (start.row().as_f32() - scroll_position.y);
16664
16665 Some(Bounds {
16666 origin: element_bounds.origin + point(x, y),
16667 size: size(em_width, line_height),
16668 })
16669 }
16670
16671 fn character_index_for_point(
16672 &mut self,
16673 point: gpui::Point<Pixels>,
16674 _window: &mut Window,
16675 _cx: &mut Context<Self>,
16676 ) -> Option<usize> {
16677 let position_map = self.last_position_map.as_ref()?;
16678 if !position_map.text_hitbox.contains(&point) {
16679 return None;
16680 }
16681 let display_point = position_map.point_for_position(point).previous_valid;
16682 let anchor = position_map
16683 .snapshot
16684 .display_point_to_anchor(display_point, Bias::Left);
16685 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16686 Some(utf16_offset.0)
16687 }
16688}
16689
16690trait SelectionExt {
16691 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16692 fn spanned_rows(
16693 &self,
16694 include_end_if_at_line_start: bool,
16695 map: &DisplaySnapshot,
16696 ) -> Range<MultiBufferRow>;
16697}
16698
16699impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16700 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16701 let start = self
16702 .start
16703 .to_point(&map.buffer_snapshot)
16704 .to_display_point(map);
16705 let end = self
16706 .end
16707 .to_point(&map.buffer_snapshot)
16708 .to_display_point(map);
16709 if self.reversed {
16710 end..start
16711 } else {
16712 start..end
16713 }
16714 }
16715
16716 fn spanned_rows(
16717 &self,
16718 include_end_if_at_line_start: bool,
16719 map: &DisplaySnapshot,
16720 ) -> Range<MultiBufferRow> {
16721 let start = self.start.to_point(&map.buffer_snapshot);
16722 let mut end = self.end.to_point(&map.buffer_snapshot);
16723 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16724 end.row -= 1;
16725 }
16726
16727 let buffer_start = map.prev_line_boundary(start).0;
16728 let buffer_end = map.next_line_boundary(end).0;
16729 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16730 }
16731}
16732
16733impl<T: InvalidationRegion> InvalidationStack<T> {
16734 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16735 where
16736 S: Clone + ToOffset,
16737 {
16738 while let Some(region) = self.last() {
16739 let all_selections_inside_invalidation_ranges =
16740 if selections.len() == region.ranges().len() {
16741 selections
16742 .iter()
16743 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16744 .all(|(selection, invalidation_range)| {
16745 let head = selection.head().to_offset(buffer);
16746 invalidation_range.start <= head && invalidation_range.end >= head
16747 })
16748 } else {
16749 false
16750 };
16751
16752 if all_selections_inside_invalidation_ranges {
16753 break;
16754 } else {
16755 self.pop();
16756 }
16757 }
16758 }
16759}
16760
16761impl<T> Default for InvalidationStack<T> {
16762 fn default() -> Self {
16763 Self(Default::default())
16764 }
16765}
16766
16767impl<T> Deref for InvalidationStack<T> {
16768 type Target = Vec<T>;
16769
16770 fn deref(&self) -> &Self::Target {
16771 &self.0
16772 }
16773}
16774
16775impl<T> DerefMut for InvalidationStack<T> {
16776 fn deref_mut(&mut self) -> &mut Self::Target {
16777 &mut self.0
16778 }
16779}
16780
16781impl InvalidationRegion for SnippetState {
16782 fn ranges(&self) -> &[Range<Anchor>] {
16783 &self.ranges[self.active_index]
16784 }
16785}
16786
16787pub fn diagnostic_block_renderer(
16788 diagnostic: Diagnostic,
16789 max_message_rows: Option<u8>,
16790 allow_closing: bool,
16791 _is_valid: bool,
16792) -> RenderBlock {
16793 let (text_without_backticks, code_ranges) =
16794 highlight_diagnostic_message(&diagnostic, max_message_rows);
16795
16796 Arc::new(move |cx: &mut BlockContext| {
16797 let group_id: SharedString = cx.block_id.to_string().into();
16798
16799 let mut text_style = cx.window.text_style().clone();
16800 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16801 let theme_settings = ThemeSettings::get_global(cx);
16802 text_style.font_family = theme_settings.buffer_font.family.clone();
16803 text_style.font_style = theme_settings.buffer_font.style;
16804 text_style.font_features = theme_settings.buffer_font.features.clone();
16805 text_style.font_weight = theme_settings.buffer_font.weight;
16806
16807 let multi_line_diagnostic = diagnostic.message.contains('\n');
16808
16809 let buttons = |diagnostic: &Diagnostic| {
16810 if multi_line_diagnostic {
16811 v_flex()
16812 } else {
16813 h_flex()
16814 }
16815 .when(allow_closing, |div| {
16816 div.children(diagnostic.is_primary.then(|| {
16817 IconButton::new("close-block", IconName::XCircle)
16818 .icon_color(Color::Muted)
16819 .size(ButtonSize::Compact)
16820 .style(ButtonStyle::Transparent)
16821 .visible_on_hover(group_id.clone())
16822 .on_click(move |_click, window, cx| {
16823 window.dispatch_action(Box::new(Cancel), cx)
16824 })
16825 .tooltip(|window, cx| {
16826 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16827 })
16828 }))
16829 })
16830 .child(
16831 IconButton::new("copy-block", IconName::Copy)
16832 .icon_color(Color::Muted)
16833 .size(ButtonSize::Compact)
16834 .style(ButtonStyle::Transparent)
16835 .visible_on_hover(group_id.clone())
16836 .on_click({
16837 let message = diagnostic.message.clone();
16838 move |_click, _, cx| {
16839 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16840 }
16841 })
16842 .tooltip(Tooltip::text("Copy diagnostic message")),
16843 )
16844 };
16845
16846 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16847 AvailableSpace::min_size(),
16848 cx.window,
16849 cx.app,
16850 );
16851
16852 h_flex()
16853 .id(cx.block_id)
16854 .group(group_id.clone())
16855 .relative()
16856 .size_full()
16857 .block_mouse_down()
16858 .pl(cx.gutter_dimensions.width)
16859 .w(cx.max_width - cx.gutter_dimensions.full_width())
16860 .child(
16861 div()
16862 .flex()
16863 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16864 .flex_shrink(),
16865 )
16866 .child(buttons(&diagnostic))
16867 .child(div().flex().flex_shrink_0().child(
16868 StyledText::new(text_without_backticks.clone()).with_highlights(
16869 &text_style,
16870 code_ranges.iter().map(|range| {
16871 (
16872 range.clone(),
16873 HighlightStyle {
16874 font_weight: Some(FontWeight::BOLD),
16875 ..Default::default()
16876 },
16877 )
16878 }),
16879 ),
16880 ))
16881 .into_any_element()
16882 })
16883}
16884
16885fn inline_completion_edit_text(
16886 current_snapshot: &BufferSnapshot,
16887 edits: &[(Range<Anchor>, String)],
16888 edit_preview: &EditPreview,
16889 include_deletions: bool,
16890 cx: &App,
16891) -> HighlightedText {
16892 let edits = edits
16893 .iter()
16894 .map(|(anchor, text)| {
16895 (
16896 anchor.start.text_anchor..anchor.end.text_anchor,
16897 text.clone(),
16898 )
16899 })
16900 .collect::<Vec<_>>();
16901
16902 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16903}
16904
16905pub fn highlight_diagnostic_message(
16906 diagnostic: &Diagnostic,
16907 mut max_message_rows: Option<u8>,
16908) -> (SharedString, Vec<Range<usize>>) {
16909 let mut text_without_backticks = String::new();
16910 let mut code_ranges = Vec::new();
16911
16912 if let Some(source) = &diagnostic.source {
16913 text_without_backticks.push_str(source);
16914 code_ranges.push(0..source.len());
16915 text_without_backticks.push_str(": ");
16916 }
16917
16918 let mut prev_offset = 0;
16919 let mut in_code_block = false;
16920 let has_row_limit = max_message_rows.is_some();
16921 let mut newline_indices = diagnostic
16922 .message
16923 .match_indices('\n')
16924 .filter(|_| has_row_limit)
16925 .map(|(ix, _)| ix)
16926 .fuse()
16927 .peekable();
16928
16929 for (quote_ix, _) in diagnostic
16930 .message
16931 .match_indices('`')
16932 .chain([(diagnostic.message.len(), "")])
16933 {
16934 let mut first_newline_ix = None;
16935 let mut last_newline_ix = None;
16936 while let Some(newline_ix) = newline_indices.peek() {
16937 if *newline_ix < quote_ix {
16938 if first_newline_ix.is_none() {
16939 first_newline_ix = Some(*newline_ix);
16940 }
16941 last_newline_ix = Some(*newline_ix);
16942
16943 if let Some(rows_left) = &mut max_message_rows {
16944 if *rows_left == 0 {
16945 break;
16946 } else {
16947 *rows_left -= 1;
16948 }
16949 }
16950 let _ = newline_indices.next();
16951 } else {
16952 break;
16953 }
16954 }
16955 let prev_len = text_without_backticks.len();
16956 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16957 text_without_backticks.push_str(new_text);
16958 if in_code_block {
16959 code_ranges.push(prev_len..text_without_backticks.len());
16960 }
16961 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16962 in_code_block = !in_code_block;
16963 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16964 text_without_backticks.push_str("...");
16965 break;
16966 }
16967 }
16968
16969 (text_without_backticks.into(), code_ranges)
16970}
16971
16972fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16973 match severity {
16974 DiagnosticSeverity::ERROR => colors.error,
16975 DiagnosticSeverity::WARNING => colors.warning,
16976 DiagnosticSeverity::INFORMATION => colors.info,
16977 DiagnosticSeverity::HINT => colors.info,
16978 _ => colors.ignored,
16979 }
16980}
16981
16982pub fn styled_runs_for_code_label<'a>(
16983 label: &'a CodeLabel,
16984 syntax_theme: &'a theme::SyntaxTheme,
16985) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16986 let fade_out = HighlightStyle {
16987 fade_out: Some(0.35),
16988 ..Default::default()
16989 };
16990
16991 let mut prev_end = label.filter_range.end;
16992 label
16993 .runs
16994 .iter()
16995 .enumerate()
16996 .flat_map(move |(ix, (range, highlight_id))| {
16997 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16998 style
16999 } else {
17000 return Default::default();
17001 };
17002 let mut muted_style = style;
17003 muted_style.highlight(fade_out);
17004
17005 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17006 if range.start >= label.filter_range.end {
17007 if range.start > prev_end {
17008 runs.push((prev_end..range.start, fade_out));
17009 }
17010 runs.push((range.clone(), muted_style));
17011 } else if range.end <= label.filter_range.end {
17012 runs.push((range.clone(), style));
17013 } else {
17014 runs.push((range.start..label.filter_range.end, style));
17015 runs.push((label.filter_range.end..range.end, muted_style));
17016 }
17017 prev_end = cmp::max(prev_end, range.end);
17018
17019 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17020 runs.push((prev_end..label.text.len(), fade_out));
17021 }
17022
17023 runs
17024 })
17025}
17026
17027pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17028 let mut prev_index = 0;
17029 let mut prev_codepoint: Option<char> = None;
17030 text.char_indices()
17031 .chain([(text.len(), '\0')])
17032 .filter_map(move |(index, codepoint)| {
17033 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17034 let is_boundary = index == text.len()
17035 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17036 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17037 if is_boundary {
17038 let chunk = &text[prev_index..index];
17039 prev_index = index;
17040 Some(chunk)
17041 } else {
17042 None
17043 }
17044 })
17045}
17046
17047pub trait RangeToAnchorExt: Sized {
17048 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17049
17050 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17051 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17052 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17053 }
17054}
17055
17056impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17057 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17058 let start_offset = self.start.to_offset(snapshot);
17059 let end_offset = self.end.to_offset(snapshot);
17060 if start_offset == end_offset {
17061 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17062 } else {
17063 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17064 }
17065 }
17066}
17067
17068pub trait RowExt {
17069 fn as_f32(&self) -> f32;
17070
17071 fn next_row(&self) -> Self;
17072
17073 fn previous_row(&self) -> Self;
17074
17075 fn minus(&self, other: Self) -> u32;
17076}
17077
17078impl RowExt for DisplayRow {
17079 fn as_f32(&self) -> f32 {
17080 self.0 as f32
17081 }
17082
17083 fn next_row(&self) -> Self {
17084 Self(self.0 + 1)
17085 }
17086
17087 fn previous_row(&self) -> Self {
17088 Self(self.0.saturating_sub(1))
17089 }
17090
17091 fn minus(&self, other: Self) -> u32 {
17092 self.0 - other.0
17093 }
17094}
17095
17096impl RowExt for MultiBufferRow {
17097 fn as_f32(&self) -> f32 {
17098 self.0 as f32
17099 }
17100
17101 fn next_row(&self) -> Self {
17102 Self(self.0 + 1)
17103 }
17104
17105 fn previous_row(&self) -> Self {
17106 Self(self.0.saturating_sub(1))
17107 }
17108
17109 fn minus(&self, other: Self) -> u32 {
17110 self.0 - other.0
17111 }
17112}
17113
17114trait RowRangeExt {
17115 type Row;
17116
17117 fn len(&self) -> usize;
17118
17119 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17120}
17121
17122impl RowRangeExt for Range<MultiBufferRow> {
17123 type Row = MultiBufferRow;
17124
17125 fn len(&self) -> usize {
17126 (self.end.0 - self.start.0) as usize
17127 }
17128
17129 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17130 (self.start.0..self.end.0).map(MultiBufferRow)
17131 }
17132}
17133
17134impl RowRangeExt for Range<DisplayRow> {
17135 type Row = DisplayRow;
17136
17137 fn len(&self) -> usize {
17138 (self.end.0 - self.start.0) as usize
17139 }
17140
17141 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17142 (self.start.0..self.end.0).map(DisplayRow)
17143 }
17144}
17145
17146/// If select range has more than one line, we
17147/// just point the cursor to range.start.
17148fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17149 if range.start.row == range.end.row {
17150 range
17151 } else {
17152 range.start..range.start
17153 }
17154}
17155pub struct KillRing(ClipboardItem);
17156impl Global for KillRing {}
17157
17158const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17159
17160fn all_edits_insertions_or_deletions(
17161 edits: &Vec<(Range<Anchor>, String)>,
17162 snapshot: &MultiBufferSnapshot,
17163) -> bool {
17164 let mut all_insertions = true;
17165 let mut all_deletions = true;
17166
17167 for (range, new_text) in edits.iter() {
17168 let range_is_empty = range.to_offset(&snapshot).is_empty();
17169 let text_is_empty = new_text.is_empty();
17170
17171 if range_is_empty != text_is_empty {
17172 if range_is_empty {
17173 all_deletions = false;
17174 } else {
17175 all_insertions = false;
17176 }
17177 } else {
17178 return false;
17179 }
17180
17181 if !all_insertions && !all_deletions {
17182 return false;
17183 }
17184 }
17185 all_insertions || all_deletions
17186}