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}
720
721#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
722enum NextScrollCursorCenterTopBottom {
723 #[default]
724 Center,
725 Top,
726 Bottom,
727}
728
729impl NextScrollCursorCenterTopBottom {
730 fn next(&self) -> Self {
731 match self {
732 Self::Center => Self::Top,
733 Self::Top => Self::Bottom,
734 Self::Bottom => Self::Center,
735 }
736 }
737}
738
739#[derive(Clone)]
740pub struct EditorSnapshot {
741 pub mode: EditorMode,
742 show_gutter: bool,
743 show_line_numbers: Option<bool>,
744 show_git_diff_gutter: Option<bool>,
745 show_code_actions: Option<bool>,
746 show_runnables: Option<bool>,
747 git_blame_gutter_max_author_length: Option<usize>,
748 pub display_snapshot: DisplaySnapshot,
749 pub placeholder_text: Option<Arc<str>>,
750 is_focused: bool,
751 scroll_anchor: ScrollAnchor,
752 ongoing_scroll: OngoingScroll,
753 current_line_highlight: CurrentLineHighlight,
754 gutter_hovered: bool,
755}
756
757const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
758
759#[derive(Default, Debug, Clone, Copy)]
760pub struct GutterDimensions {
761 pub left_padding: Pixels,
762 pub right_padding: Pixels,
763 pub width: Pixels,
764 pub margin: Pixels,
765 pub git_blame_entries_width: Option<Pixels>,
766}
767
768impl GutterDimensions {
769 /// The full width of the space taken up by the gutter.
770 pub fn full_width(&self) -> Pixels {
771 self.margin + self.width
772 }
773
774 /// The width of the space reserved for the fold indicators,
775 /// use alongside 'justify_end' and `gutter_width` to
776 /// right align content with the line numbers
777 pub fn fold_area_width(&self) -> Pixels {
778 self.margin + self.right_padding
779 }
780}
781
782#[derive(Debug)]
783pub struct RemoteSelection {
784 pub replica_id: ReplicaId,
785 pub selection: Selection<Anchor>,
786 pub cursor_shape: CursorShape,
787 pub peer_id: PeerId,
788 pub line_mode: bool,
789 pub participant_index: Option<ParticipantIndex>,
790 pub user_name: Option<SharedString>,
791}
792
793#[derive(Clone, Debug)]
794struct SelectionHistoryEntry {
795 selections: Arc<[Selection<Anchor>]>,
796 select_next_state: Option<SelectNextState>,
797 select_prev_state: Option<SelectNextState>,
798 add_selections_state: Option<AddSelectionsState>,
799}
800
801enum SelectionHistoryMode {
802 Normal,
803 Undoing,
804 Redoing,
805}
806
807#[derive(Clone, PartialEq, Eq, Hash)]
808struct HoveredCursor {
809 replica_id: u16,
810 selection_id: usize,
811}
812
813impl Default for SelectionHistoryMode {
814 fn default() -> Self {
815 Self::Normal
816 }
817}
818
819#[derive(Default)]
820struct SelectionHistory {
821 #[allow(clippy::type_complexity)]
822 selections_by_transaction:
823 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
824 mode: SelectionHistoryMode,
825 undo_stack: VecDeque<SelectionHistoryEntry>,
826 redo_stack: VecDeque<SelectionHistoryEntry>,
827}
828
829impl SelectionHistory {
830 fn insert_transaction(
831 &mut self,
832 transaction_id: TransactionId,
833 selections: Arc<[Selection<Anchor>]>,
834 ) {
835 self.selections_by_transaction
836 .insert(transaction_id, (selections, None));
837 }
838
839 #[allow(clippy::type_complexity)]
840 fn transaction(
841 &self,
842 transaction_id: TransactionId,
843 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
844 self.selections_by_transaction.get(&transaction_id)
845 }
846
847 #[allow(clippy::type_complexity)]
848 fn transaction_mut(
849 &mut self,
850 transaction_id: TransactionId,
851 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
852 self.selections_by_transaction.get_mut(&transaction_id)
853 }
854
855 fn push(&mut self, entry: SelectionHistoryEntry) {
856 if !entry.selections.is_empty() {
857 match self.mode {
858 SelectionHistoryMode::Normal => {
859 self.push_undo(entry);
860 self.redo_stack.clear();
861 }
862 SelectionHistoryMode::Undoing => self.push_redo(entry),
863 SelectionHistoryMode::Redoing => self.push_undo(entry),
864 }
865 }
866 }
867
868 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
869 if self
870 .undo_stack
871 .back()
872 .map_or(true, |e| e.selections != entry.selections)
873 {
874 self.undo_stack.push_back(entry);
875 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
876 self.undo_stack.pop_front();
877 }
878 }
879 }
880
881 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
882 if self
883 .redo_stack
884 .back()
885 .map_or(true, |e| e.selections != entry.selections)
886 {
887 self.redo_stack.push_back(entry);
888 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
889 self.redo_stack.pop_front();
890 }
891 }
892 }
893}
894
895struct RowHighlight {
896 index: usize,
897 range: Range<Anchor>,
898 color: Hsla,
899 should_autoscroll: bool,
900}
901
902#[derive(Clone, Debug)]
903struct AddSelectionsState {
904 above: bool,
905 stack: Vec<usize>,
906}
907
908#[derive(Clone)]
909struct SelectNextState {
910 query: AhoCorasick,
911 wordwise: bool,
912 done: bool,
913}
914
915impl std::fmt::Debug for SelectNextState {
916 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
917 f.debug_struct(std::any::type_name::<Self>())
918 .field("wordwise", &self.wordwise)
919 .field("done", &self.done)
920 .finish()
921 }
922}
923
924#[derive(Debug)]
925struct AutocloseRegion {
926 selection_id: usize,
927 range: Range<Anchor>,
928 pair: BracketPair,
929}
930
931#[derive(Debug)]
932struct SnippetState {
933 ranges: Vec<Vec<Range<Anchor>>>,
934 active_index: usize,
935 choices: Vec<Option<Vec<String>>>,
936}
937
938#[doc(hidden)]
939pub struct RenameState {
940 pub range: Range<Anchor>,
941 pub old_name: Arc<str>,
942 pub editor: Entity<Editor>,
943 block_id: CustomBlockId,
944}
945
946struct InvalidationStack<T>(Vec<T>);
947
948struct RegisteredInlineCompletionProvider {
949 provider: Arc<dyn InlineCompletionProviderHandle>,
950 _subscription: Subscription,
951}
952
953#[derive(Debug)]
954struct ActiveDiagnosticGroup {
955 primary_range: Range<Anchor>,
956 primary_message: String,
957 group_id: usize,
958 blocks: HashMap<CustomBlockId, Diagnostic>,
959 is_valid: bool,
960}
961
962#[derive(Serialize, Deserialize, Clone, Debug)]
963pub struct ClipboardSelection {
964 pub len: usize,
965 pub is_entire_line: bool,
966 pub first_line_indent: u32,
967}
968
969#[derive(Debug)]
970pub(crate) struct NavigationData {
971 cursor_anchor: Anchor,
972 cursor_position: Point,
973 scroll_anchor: ScrollAnchor,
974 scroll_top_row: u32,
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
978pub enum GotoDefinitionKind {
979 Symbol,
980 Declaration,
981 Type,
982 Implementation,
983}
984
985#[derive(Debug, Clone)]
986enum InlayHintRefreshReason {
987 Toggle(bool),
988 SettingsChange(InlayHintSettings),
989 NewLinesShown,
990 BufferEdited(HashSet<Arc<Language>>),
991 RefreshRequested,
992 ExcerptsRemoved(Vec<ExcerptId>),
993}
994
995impl InlayHintRefreshReason {
996 fn description(&self) -> &'static str {
997 match self {
998 Self::Toggle(_) => "toggle",
999 Self::SettingsChange(_) => "settings change",
1000 Self::NewLinesShown => "new lines shown",
1001 Self::BufferEdited(_) => "buffer edited",
1002 Self::RefreshRequested => "refresh requested",
1003 Self::ExcerptsRemoved(_) => "excerpts removed",
1004 }
1005 }
1006}
1007
1008pub enum FormatTarget {
1009 Buffers,
1010 Ranges(Vec<Range<MultiBufferPoint>>),
1011}
1012
1013pub(crate) struct FocusedBlock {
1014 id: BlockId,
1015 focus_handle: WeakFocusHandle,
1016}
1017
1018#[derive(Clone)]
1019enum JumpData {
1020 MultiBufferRow {
1021 row: MultiBufferRow,
1022 line_offset_from_top: u32,
1023 },
1024 MultiBufferPoint {
1025 excerpt_id: ExcerptId,
1026 position: Point,
1027 anchor: text::Anchor,
1028 line_offset_from_top: u32,
1029 },
1030}
1031
1032pub enum MultibufferSelectionMode {
1033 First,
1034 All,
1035}
1036
1037impl Editor {
1038 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1039 let buffer = cx.new(|cx| Buffer::local("", cx));
1040 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1041 Self::new(
1042 EditorMode::SingleLine { auto_width: false },
1043 buffer,
1044 None,
1045 false,
1046 window,
1047 cx,
1048 )
1049 }
1050
1051 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1052 let buffer = cx.new(|cx| Buffer::local("", cx));
1053 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1054 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1055 }
1056
1057 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1058 let buffer = cx.new(|cx| Buffer::local("", cx));
1059 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1060 Self::new(
1061 EditorMode::SingleLine { auto_width: true },
1062 buffer,
1063 None,
1064 false,
1065 window,
1066 cx,
1067 )
1068 }
1069
1070 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1071 let buffer = cx.new(|cx| Buffer::local("", cx));
1072 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1073 Self::new(
1074 EditorMode::AutoHeight { max_lines },
1075 buffer,
1076 None,
1077 false,
1078 window,
1079 cx,
1080 )
1081 }
1082
1083 pub fn for_buffer(
1084 buffer: Entity<Buffer>,
1085 project: Option<Entity<Project>>,
1086 window: &mut Window,
1087 cx: &mut Context<Self>,
1088 ) -> Self {
1089 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1090 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1091 }
1092
1093 pub fn for_multibuffer(
1094 buffer: Entity<MultiBuffer>,
1095 project: Option<Entity<Project>>,
1096 show_excerpt_controls: bool,
1097 window: &mut Window,
1098 cx: &mut Context<Self>,
1099 ) -> Self {
1100 Self::new(
1101 EditorMode::Full,
1102 buffer,
1103 project,
1104 show_excerpt_controls,
1105 window,
1106 cx,
1107 )
1108 }
1109
1110 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1111 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1112 let mut clone = Self::new(
1113 self.mode,
1114 self.buffer.clone(),
1115 self.project.clone(),
1116 show_excerpt_controls,
1117 window,
1118 cx,
1119 );
1120 self.display_map.update(cx, |display_map, cx| {
1121 let snapshot = display_map.snapshot(cx);
1122 clone.display_map.update(cx, |display_map, cx| {
1123 display_map.set_state(&snapshot, cx);
1124 });
1125 });
1126 clone.selections.clone_state(&self.selections);
1127 clone.scroll_manager.clone_state(&self.scroll_manager);
1128 clone.searchable = self.searchable;
1129 clone
1130 }
1131
1132 pub fn new(
1133 mode: EditorMode,
1134 buffer: Entity<MultiBuffer>,
1135 project: Option<Entity<Project>>,
1136 show_excerpt_controls: bool,
1137 window: &mut Window,
1138 cx: &mut Context<Self>,
1139 ) -> Self {
1140 let style = window.text_style();
1141 let font_size = style.font_size.to_pixels(window.rem_size());
1142 let editor = cx.entity().downgrade();
1143 let fold_placeholder = FoldPlaceholder {
1144 constrain_width: true,
1145 render: Arc::new(move |fold_id, fold_range, cx| {
1146 let editor = editor.clone();
1147 div()
1148 .id(fold_id)
1149 .bg(cx.theme().colors().ghost_element_background)
1150 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1151 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1152 .rounded_sm()
1153 .size_full()
1154 .cursor_pointer()
1155 .child("⋯")
1156 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1157 .on_click(move |_, _window, cx| {
1158 editor
1159 .update(cx, |editor, cx| {
1160 editor.unfold_ranges(
1161 &[fold_range.start..fold_range.end],
1162 true,
1163 false,
1164 cx,
1165 );
1166 cx.stop_propagation();
1167 })
1168 .ok();
1169 })
1170 .into_any()
1171 }),
1172 merge_adjacent: true,
1173 ..Default::default()
1174 };
1175 let display_map = cx.new(|cx| {
1176 DisplayMap::new(
1177 buffer.clone(),
1178 style.font(),
1179 font_size,
1180 None,
1181 show_excerpt_controls,
1182 FILE_HEADER_HEIGHT,
1183 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1184 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1185 fold_placeholder,
1186 cx,
1187 )
1188 });
1189
1190 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1191
1192 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1193
1194 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1195 .then(|| language_settings::SoftWrap::None);
1196
1197 let mut project_subscriptions = Vec::new();
1198 if mode == EditorMode::Full {
1199 if let Some(project) = project.as_ref() {
1200 if buffer.read(cx).is_singleton() {
1201 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1202 cx.emit(EditorEvent::TitleChanged);
1203 }));
1204 }
1205 project_subscriptions.push(cx.subscribe_in(
1206 project,
1207 window,
1208 |editor, _, event, window, cx| {
1209 if let project::Event::RefreshInlayHints = event {
1210 editor
1211 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1212 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1213 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1214 let focus_handle = editor.focus_handle(cx);
1215 if focus_handle.is_focused(window) {
1216 let snapshot = buffer.read(cx).snapshot();
1217 for (range, snippet) in snippet_edits {
1218 let editor_range =
1219 language::range_from_lsp(*range).to_offset(&snapshot);
1220 editor
1221 .insert_snippet(
1222 &[editor_range],
1223 snippet.clone(),
1224 window,
1225 cx,
1226 )
1227 .ok();
1228 }
1229 }
1230 }
1231 }
1232 },
1233 ));
1234 if let Some(task_inventory) = project
1235 .read(cx)
1236 .task_store()
1237 .read(cx)
1238 .task_inventory()
1239 .cloned()
1240 {
1241 project_subscriptions.push(cx.observe_in(
1242 &task_inventory,
1243 window,
1244 |editor, _, window, cx| {
1245 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1246 },
1247 ));
1248 }
1249 }
1250 }
1251
1252 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1253
1254 let inlay_hint_settings =
1255 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1256 let focus_handle = cx.focus_handle();
1257 cx.on_focus(&focus_handle, window, Self::handle_focus)
1258 .detach();
1259 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1260 .detach();
1261 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1262 .detach();
1263 cx.on_blur(&focus_handle, window, Self::handle_blur)
1264 .detach();
1265
1266 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1267 Some(false)
1268 } else {
1269 None
1270 };
1271
1272 let mut code_action_providers = Vec::new();
1273 let mut load_uncommitted_diff = None;
1274 if let Some(project) = project.clone() {
1275 load_uncommitted_diff = Some(
1276 get_uncommitted_diff_for_buffer(
1277 &project,
1278 buffer.read(cx).all_buffers(),
1279 buffer.clone(),
1280 cx,
1281 )
1282 .shared(),
1283 );
1284 code_action_providers.push(Rc::new(project) as Rc<_>);
1285 }
1286
1287 let mut this = Self {
1288 focus_handle,
1289 show_cursor_when_unfocused: false,
1290 last_focused_descendant: None,
1291 buffer: buffer.clone(),
1292 display_map: display_map.clone(),
1293 selections,
1294 scroll_manager: ScrollManager::new(cx),
1295 columnar_selection_tail: None,
1296 add_selections_state: None,
1297 select_next_state: None,
1298 select_prev_state: None,
1299 selection_history: Default::default(),
1300 autoclose_regions: Default::default(),
1301 snippet_stack: Default::default(),
1302 select_larger_syntax_node_stack: Vec::new(),
1303 ime_transaction: Default::default(),
1304 active_diagnostics: None,
1305 soft_wrap_mode_override,
1306 completion_provider: project.clone().map(|project| Box::new(project) as _),
1307 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1308 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1309 project,
1310 blink_manager: blink_manager.clone(),
1311 show_local_selections: true,
1312 show_scrollbars: true,
1313 mode,
1314 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1315 show_gutter: mode == EditorMode::Full,
1316 show_line_numbers: None,
1317 use_relative_line_numbers: None,
1318 show_git_diff_gutter: None,
1319 show_code_actions: None,
1320 show_runnables: None,
1321 show_wrap_guides: None,
1322 show_indent_guides,
1323 placeholder_text: None,
1324 highlight_order: 0,
1325 highlighted_rows: HashMap::default(),
1326 background_highlights: Default::default(),
1327 gutter_highlights: TreeMap::default(),
1328 scrollbar_marker_state: ScrollbarMarkerState::default(),
1329 active_indent_guides_state: ActiveIndentGuidesState::default(),
1330 nav_history: None,
1331 context_menu: RefCell::new(None),
1332 mouse_context_menu: None,
1333 completion_tasks: Default::default(),
1334 signature_help_state: SignatureHelpState::default(),
1335 auto_signature_help: None,
1336 find_all_references_task_sources: Vec::new(),
1337 next_completion_id: 0,
1338 next_inlay_id: 0,
1339 code_action_providers,
1340 available_code_actions: Default::default(),
1341 code_actions_task: Default::default(),
1342 selection_highlight_task: Default::default(),
1343 document_highlights_task: Default::default(),
1344 linked_editing_range_task: Default::default(),
1345 pending_rename: Default::default(),
1346 searchable: true,
1347 cursor_shape: EditorSettings::get_global(cx)
1348 .cursor_shape
1349 .unwrap_or_default(),
1350 current_line_highlight: None,
1351 autoindent_mode: Some(AutoindentMode::EachLine),
1352 collapse_matches: false,
1353 workspace: None,
1354 input_enabled: true,
1355 use_modal_editing: mode == EditorMode::Full,
1356 read_only: false,
1357 use_autoclose: true,
1358 use_auto_surround: true,
1359 auto_replace_emoji_shortcode: false,
1360 leader_peer_id: None,
1361 remote_id: None,
1362 hover_state: Default::default(),
1363 pending_mouse_down: None,
1364 hovered_link_state: Default::default(),
1365 edit_prediction_provider: None,
1366 active_inline_completion: None,
1367 stale_inline_completion_in_menu: None,
1368 edit_prediction_preview: EditPredictionPreview::Inactive,
1369 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1370
1371 gutter_hovered: false,
1372 pixel_position_of_newest_cursor: None,
1373 last_bounds: None,
1374 last_position_map: None,
1375 expect_bounds_change: None,
1376 gutter_dimensions: GutterDimensions::default(),
1377 style: None,
1378 show_cursor_names: false,
1379 hovered_cursors: Default::default(),
1380 next_editor_action_id: EditorActionId::default(),
1381 editor_actions: Rc::default(),
1382 inline_completions_hidden_for_vim_mode: false,
1383 show_inline_completions_override: None,
1384 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1385 edit_prediction_settings: EditPredictionSettings::Disabled,
1386 edit_prediction_cursor_on_leading_whitespace: false,
1387 edit_prediction_requires_modifier_in_leading_space: true,
1388 custom_context_menu: None,
1389 show_git_blame_gutter: false,
1390 show_git_blame_inline: false,
1391 distinguish_unstaged_diff_hunks: false,
1392 show_selection_menu: None,
1393 show_git_blame_inline_delay_task: None,
1394 git_blame_inline_tooltip: None,
1395 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1396 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1397 .session
1398 .restore_unsaved_buffers,
1399 blame: None,
1400 blame_subscription: None,
1401 tasks: Default::default(),
1402 _subscriptions: vec![
1403 cx.observe(&buffer, Self::on_buffer_changed),
1404 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1405 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1406 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1407 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1408 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1409 cx.observe_window_activation(window, |editor, window, cx| {
1410 let active = window.is_window_active();
1411 editor.blink_manager.update(cx, |blink_manager, cx| {
1412 if active {
1413 blink_manager.enable(cx);
1414 } else {
1415 blink_manager.disable(cx);
1416 }
1417 });
1418 }),
1419 ],
1420 tasks_update_task: None,
1421 linked_edit_ranges: Default::default(),
1422 in_project_search: false,
1423 previous_search_ranges: None,
1424 breadcrumb_header: None,
1425 focused_block: None,
1426 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1427 addons: HashMap::default(),
1428 registered_buffers: HashMap::default(),
1429 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1430 selection_mark_mode: false,
1431 toggle_fold_multiple_buffers: Task::ready(()),
1432 serialize_selections: Task::ready(()),
1433 text_style_refinement: None,
1434 load_diff_task: load_uncommitted_diff,
1435 };
1436 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1437 this._subscriptions.extend(project_subscriptions);
1438
1439 this.end_selection(window, cx);
1440 this.scroll_manager.show_scrollbar(window, cx);
1441
1442 if mode == EditorMode::Full {
1443 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1444 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1445
1446 if this.git_blame_inline_enabled {
1447 this.git_blame_inline_enabled = true;
1448 this.start_git_blame_inline(false, window, cx);
1449 }
1450
1451 if let Some(buffer) = buffer.read(cx).as_singleton() {
1452 if let Some(project) = this.project.as_ref() {
1453 let handle = project.update(cx, |project, cx| {
1454 project.register_buffer_with_language_servers(&buffer, cx)
1455 });
1456 this.registered_buffers
1457 .insert(buffer.read(cx).remote_id(), handle);
1458 }
1459 }
1460 }
1461
1462 this.report_editor_event("Editor Opened", None, cx);
1463 this
1464 }
1465
1466 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1467 self.mouse_context_menu
1468 .as_ref()
1469 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1470 }
1471
1472 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1473 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1474 }
1475
1476 fn key_context_internal(
1477 &self,
1478 has_active_edit_prediction: bool,
1479 window: &Window,
1480 cx: &App,
1481 ) -> KeyContext {
1482 let mut key_context = KeyContext::new_with_defaults();
1483 key_context.add("Editor");
1484 let mode = match self.mode {
1485 EditorMode::SingleLine { .. } => "single_line",
1486 EditorMode::AutoHeight { .. } => "auto_height",
1487 EditorMode::Full => "full",
1488 };
1489
1490 if EditorSettings::jupyter_enabled(cx) {
1491 key_context.add("jupyter");
1492 }
1493
1494 key_context.set("mode", mode);
1495 if self.pending_rename.is_some() {
1496 key_context.add("renaming");
1497 }
1498
1499 match self.context_menu.borrow().as_ref() {
1500 Some(CodeContextMenu::Completions(_)) => {
1501 key_context.add("menu");
1502 key_context.add("showing_completions");
1503 }
1504 Some(CodeContextMenu::CodeActions(_)) => {
1505 key_context.add("menu");
1506 key_context.add("showing_code_actions")
1507 }
1508 None => {}
1509 }
1510
1511 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1512 if !self.focus_handle(cx).contains_focused(window, cx)
1513 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1514 {
1515 for addon in self.addons.values() {
1516 addon.extend_key_context(&mut key_context, cx)
1517 }
1518 }
1519
1520 if let Some(extension) = self
1521 .buffer
1522 .read(cx)
1523 .as_singleton()
1524 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1525 {
1526 key_context.set("extension", extension.to_string());
1527 }
1528
1529 if has_active_edit_prediction {
1530 if self.edit_prediction_in_conflict() {
1531 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1532 } else {
1533 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1534 key_context.add("copilot_suggestion");
1535 }
1536 }
1537
1538 if self.selection_mark_mode {
1539 key_context.add("selection_mode");
1540 }
1541
1542 key_context
1543 }
1544
1545 pub fn edit_prediction_in_conflict(&self) -> bool {
1546 if !self.show_edit_predictions_in_menu() {
1547 return false;
1548 }
1549
1550 let showing_completions = self
1551 .context_menu
1552 .borrow()
1553 .as_ref()
1554 .map_or(false, |context| {
1555 matches!(context, CodeContextMenu::Completions(_))
1556 });
1557
1558 showing_completions
1559 || self.edit_prediction_requires_modifier()
1560 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1561 // bindings to insert tab characters.
1562 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1563 }
1564
1565 pub fn accept_edit_prediction_keybind(
1566 &self,
1567 window: &Window,
1568 cx: &App,
1569 ) -> AcceptEditPredictionBinding {
1570 let key_context = self.key_context_internal(true, window, cx);
1571 let in_conflict = self.edit_prediction_in_conflict();
1572
1573 AcceptEditPredictionBinding(
1574 window
1575 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1576 .into_iter()
1577 .filter(|binding| {
1578 !in_conflict
1579 || binding
1580 .keystrokes()
1581 .first()
1582 .map_or(false, |keystroke| keystroke.modifiers.modified())
1583 })
1584 .rev()
1585 .min_by_key(|binding| {
1586 binding
1587 .keystrokes()
1588 .first()
1589 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1590 }),
1591 )
1592 }
1593
1594 pub fn new_file(
1595 workspace: &mut Workspace,
1596 _: &workspace::NewFile,
1597 window: &mut Window,
1598 cx: &mut Context<Workspace>,
1599 ) {
1600 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1601 "Failed to create buffer",
1602 window,
1603 cx,
1604 |e, _, _| match e.error_code() {
1605 ErrorCode::RemoteUpgradeRequired => Some(format!(
1606 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1607 e.error_tag("required").unwrap_or("the latest version")
1608 )),
1609 _ => None,
1610 },
1611 );
1612 }
1613
1614 pub fn new_in_workspace(
1615 workspace: &mut Workspace,
1616 window: &mut Window,
1617 cx: &mut Context<Workspace>,
1618 ) -> Task<Result<Entity<Editor>>> {
1619 let project = workspace.project().clone();
1620 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1621
1622 cx.spawn_in(window, |workspace, mut cx| async move {
1623 let buffer = create.await?;
1624 workspace.update_in(&mut cx, |workspace, window, cx| {
1625 let editor =
1626 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1627 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1628 editor
1629 })
1630 })
1631 }
1632
1633 fn new_file_vertical(
1634 workspace: &mut Workspace,
1635 _: &workspace::NewFileSplitVertical,
1636 window: &mut Window,
1637 cx: &mut Context<Workspace>,
1638 ) {
1639 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1640 }
1641
1642 fn new_file_horizontal(
1643 workspace: &mut Workspace,
1644 _: &workspace::NewFileSplitHorizontal,
1645 window: &mut Window,
1646 cx: &mut Context<Workspace>,
1647 ) {
1648 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1649 }
1650
1651 fn new_file_in_direction(
1652 workspace: &mut Workspace,
1653 direction: SplitDirection,
1654 window: &mut Window,
1655 cx: &mut Context<Workspace>,
1656 ) {
1657 let project = workspace.project().clone();
1658 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1659
1660 cx.spawn_in(window, |workspace, mut cx| async move {
1661 let buffer = create.await?;
1662 workspace.update_in(&mut cx, move |workspace, window, cx| {
1663 workspace.split_item(
1664 direction,
1665 Box::new(
1666 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1667 ),
1668 window,
1669 cx,
1670 )
1671 })?;
1672 anyhow::Ok(())
1673 })
1674 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1675 match e.error_code() {
1676 ErrorCode::RemoteUpgradeRequired => Some(format!(
1677 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1678 e.error_tag("required").unwrap_or("the latest version")
1679 )),
1680 _ => None,
1681 }
1682 });
1683 }
1684
1685 pub fn leader_peer_id(&self) -> Option<PeerId> {
1686 self.leader_peer_id
1687 }
1688
1689 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1690 &self.buffer
1691 }
1692
1693 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1694 self.workspace.as_ref()?.0.upgrade()
1695 }
1696
1697 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1698 self.buffer().read(cx).title(cx)
1699 }
1700
1701 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1702 let git_blame_gutter_max_author_length = self
1703 .render_git_blame_gutter(cx)
1704 .then(|| {
1705 if let Some(blame) = self.blame.as_ref() {
1706 let max_author_length =
1707 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1708 Some(max_author_length)
1709 } else {
1710 None
1711 }
1712 })
1713 .flatten();
1714
1715 EditorSnapshot {
1716 mode: self.mode,
1717 show_gutter: self.show_gutter,
1718 show_line_numbers: self.show_line_numbers,
1719 show_git_diff_gutter: self.show_git_diff_gutter,
1720 show_code_actions: self.show_code_actions,
1721 show_runnables: self.show_runnables,
1722 git_blame_gutter_max_author_length,
1723 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1724 scroll_anchor: self.scroll_manager.anchor(),
1725 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1726 placeholder_text: self.placeholder_text.clone(),
1727 is_focused: self.focus_handle.is_focused(window),
1728 current_line_highlight: self
1729 .current_line_highlight
1730 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1731 gutter_hovered: self.gutter_hovered,
1732 }
1733 }
1734
1735 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1736 self.buffer.read(cx).language_at(point, cx)
1737 }
1738
1739 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1740 self.buffer.read(cx).read(cx).file_at(point).cloned()
1741 }
1742
1743 pub fn active_excerpt(
1744 &self,
1745 cx: &App,
1746 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1747 self.buffer
1748 .read(cx)
1749 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1750 }
1751
1752 pub fn mode(&self) -> EditorMode {
1753 self.mode
1754 }
1755
1756 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1757 self.collaboration_hub.as_deref()
1758 }
1759
1760 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1761 self.collaboration_hub = Some(hub);
1762 }
1763
1764 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1765 self.in_project_search = in_project_search;
1766 }
1767
1768 pub fn set_custom_context_menu(
1769 &mut self,
1770 f: impl 'static
1771 + Fn(
1772 &mut Self,
1773 DisplayPoint,
1774 &mut Window,
1775 &mut Context<Self>,
1776 ) -> Option<Entity<ui::ContextMenu>>,
1777 ) {
1778 self.custom_context_menu = Some(Box::new(f))
1779 }
1780
1781 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1782 self.completion_provider = provider;
1783 }
1784
1785 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1786 self.semantics_provider.clone()
1787 }
1788
1789 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1790 self.semantics_provider = provider;
1791 }
1792
1793 pub fn set_edit_prediction_provider<T>(
1794 &mut self,
1795 provider: Option<Entity<T>>,
1796 window: &mut Window,
1797 cx: &mut Context<Self>,
1798 ) where
1799 T: EditPredictionProvider,
1800 {
1801 self.edit_prediction_provider =
1802 provider.map(|provider| RegisteredInlineCompletionProvider {
1803 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1804 if this.focus_handle.is_focused(window) {
1805 this.update_visible_inline_completion(window, cx);
1806 }
1807 }),
1808 provider: Arc::new(provider),
1809 });
1810 self.refresh_inline_completion(false, false, window, cx);
1811 }
1812
1813 pub fn placeholder_text(&self) -> Option<&str> {
1814 self.placeholder_text.as_deref()
1815 }
1816
1817 pub fn set_placeholder_text(
1818 &mut self,
1819 placeholder_text: impl Into<Arc<str>>,
1820 cx: &mut Context<Self>,
1821 ) {
1822 let placeholder_text = Some(placeholder_text.into());
1823 if self.placeholder_text != placeholder_text {
1824 self.placeholder_text = placeholder_text;
1825 cx.notify();
1826 }
1827 }
1828
1829 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1830 self.cursor_shape = cursor_shape;
1831
1832 // Disrupt blink for immediate user feedback that the cursor shape has changed
1833 self.blink_manager.update(cx, BlinkManager::show_cursor);
1834
1835 cx.notify();
1836 }
1837
1838 pub fn set_current_line_highlight(
1839 &mut self,
1840 current_line_highlight: Option<CurrentLineHighlight>,
1841 ) {
1842 self.current_line_highlight = current_line_highlight;
1843 }
1844
1845 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1846 self.collapse_matches = collapse_matches;
1847 }
1848
1849 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1850 let buffers = self.buffer.read(cx).all_buffers();
1851 let Some(project) = self.project.as_ref() else {
1852 return;
1853 };
1854 project.update(cx, |project, cx| {
1855 for buffer in buffers {
1856 self.registered_buffers
1857 .entry(buffer.read(cx).remote_id())
1858 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1859 }
1860 })
1861 }
1862
1863 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1864 if self.collapse_matches {
1865 return range.start..range.start;
1866 }
1867 range.clone()
1868 }
1869
1870 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1871 if self.display_map.read(cx).clip_at_line_ends != clip {
1872 self.display_map
1873 .update(cx, |map, _| map.clip_at_line_ends = clip);
1874 }
1875 }
1876
1877 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1878 self.input_enabled = input_enabled;
1879 }
1880
1881 pub fn set_inline_completions_hidden_for_vim_mode(
1882 &mut self,
1883 hidden: bool,
1884 window: &mut Window,
1885 cx: &mut Context<Self>,
1886 ) {
1887 if hidden != self.inline_completions_hidden_for_vim_mode {
1888 self.inline_completions_hidden_for_vim_mode = hidden;
1889 if hidden {
1890 self.update_visible_inline_completion(window, cx);
1891 } else {
1892 self.refresh_inline_completion(true, false, window, cx);
1893 }
1894 }
1895 }
1896
1897 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1898 self.menu_inline_completions_policy = value;
1899 }
1900
1901 pub fn set_autoindent(&mut self, autoindent: bool) {
1902 if autoindent {
1903 self.autoindent_mode = Some(AutoindentMode::EachLine);
1904 } else {
1905 self.autoindent_mode = None;
1906 }
1907 }
1908
1909 pub fn read_only(&self, cx: &App) -> bool {
1910 self.read_only || self.buffer.read(cx).read_only()
1911 }
1912
1913 pub fn set_read_only(&mut self, read_only: bool) {
1914 self.read_only = read_only;
1915 }
1916
1917 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1918 self.use_autoclose = autoclose;
1919 }
1920
1921 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1922 self.use_auto_surround = auto_surround;
1923 }
1924
1925 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1926 self.auto_replace_emoji_shortcode = auto_replace;
1927 }
1928
1929 pub fn toggle_inline_completions(
1930 &mut self,
1931 _: &ToggleEditPrediction,
1932 window: &mut Window,
1933 cx: &mut Context<Self>,
1934 ) {
1935 if self.show_inline_completions_override.is_some() {
1936 self.set_show_edit_predictions(None, window, cx);
1937 } else {
1938 let show_edit_predictions = !self.edit_predictions_enabled();
1939 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1940 }
1941 }
1942
1943 pub fn set_show_edit_predictions(
1944 &mut self,
1945 show_edit_predictions: Option<bool>,
1946 window: &mut Window,
1947 cx: &mut Context<Self>,
1948 ) {
1949 self.show_inline_completions_override = show_edit_predictions;
1950 self.refresh_inline_completion(false, true, window, cx);
1951 }
1952
1953 fn inline_completions_disabled_in_scope(
1954 &self,
1955 buffer: &Entity<Buffer>,
1956 buffer_position: language::Anchor,
1957 cx: &App,
1958 ) -> bool {
1959 let snapshot = buffer.read(cx).snapshot();
1960 let settings = snapshot.settings_at(buffer_position, cx);
1961
1962 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1963 return false;
1964 };
1965
1966 scope.override_name().map_or(false, |scope_name| {
1967 settings
1968 .edit_predictions_disabled_in
1969 .iter()
1970 .any(|s| s == scope_name)
1971 })
1972 }
1973
1974 pub fn set_use_modal_editing(&mut self, to: bool) {
1975 self.use_modal_editing = to;
1976 }
1977
1978 pub fn use_modal_editing(&self) -> bool {
1979 self.use_modal_editing
1980 }
1981
1982 fn selections_did_change(
1983 &mut self,
1984 local: bool,
1985 old_cursor_position: &Anchor,
1986 show_completions: bool,
1987 window: &mut Window,
1988 cx: &mut Context<Self>,
1989 ) {
1990 window.invalidate_character_coordinates();
1991
1992 // Copy selections to primary selection buffer
1993 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1994 if local {
1995 let selections = self.selections.all::<usize>(cx);
1996 let buffer_handle = self.buffer.read(cx).read(cx);
1997
1998 let mut text = String::new();
1999 for (index, selection) in selections.iter().enumerate() {
2000 let text_for_selection = buffer_handle
2001 .text_for_range(selection.start..selection.end)
2002 .collect::<String>();
2003
2004 text.push_str(&text_for_selection);
2005 if index != selections.len() - 1 {
2006 text.push('\n');
2007 }
2008 }
2009
2010 if !text.is_empty() {
2011 cx.write_to_primary(ClipboardItem::new_string(text));
2012 }
2013 }
2014
2015 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2016 self.buffer.update(cx, |buffer, cx| {
2017 buffer.set_active_selections(
2018 &self.selections.disjoint_anchors(),
2019 self.selections.line_mode,
2020 self.cursor_shape,
2021 cx,
2022 )
2023 });
2024 }
2025 let display_map = self
2026 .display_map
2027 .update(cx, |display_map, cx| display_map.snapshot(cx));
2028 let buffer = &display_map.buffer_snapshot;
2029 self.add_selections_state = None;
2030 self.select_next_state = None;
2031 self.select_prev_state = None;
2032 self.select_larger_syntax_node_stack.clear();
2033 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2034 self.snippet_stack
2035 .invalidate(&self.selections.disjoint_anchors(), buffer);
2036 self.take_rename(false, window, cx);
2037
2038 let new_cursor_position = self.selections.newest_anchor().head();
2039
2040 self.push_to_nav_history(
2041 *old_cursor_position,
2042 Some(new_cursor_position.to_point(buffer)),
2043 cx,
2044 );
2045
2046 if local {
2047 let new_cursor_position = self.selections.newest_anchor().head();
2048 let mut context_menu = self.context_menu.borrow_mut();
2049 let completion_menu = match context_menu.as_ref() {
2050 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2051 _ => {
2052 *context_menu = None;
2053 None
2054 }
2055 };
2056 if let Some(buffer_id) = new_cursor_position.buffer_id {
2057 if !self.registered_buffers.contains_key(&buffer_id) {
2058 if let Some(project) = self.project.as_ref() {
2059 project.update(cx, |project, cx| {
2060 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2061 return;
2062 };
2063 self.registered_buffers.insert(
2064 buffer_id,
2065 project.register_buffer_with_language_servers(&buffer, cx),
2066 );
2067 })
2068 }
2069 }
2070 }
2071
2072 if let Some(completion_menu) = completion_menu {
2073 let cursor_position = new_cursor_position.to_offset(buffer);
2074 let (word_range, kind) =
2075 buffer.surrounding_word(completion_menu.initial_position, true);
2076 if kind == Some(CharKind::Word)
2077 && word_range.to_inclusive().contains(&cursor_position)
2078 {
2079 let mut completion_menu = completion_menu.clone();
2080 drop(context_menu);
2081
2082 let query = Self::completion_query(buffer, cursor_position);
2083 cx.spawn(move |this, mut cx| async move {
2084 completion_menu
2085 .filter(query.as_deref(), cx.background_executor().clone())
2086 .await;
2087
2088 this.update(&mut cx, |this, cx| {
2089 let mut context_menu = this.context_menu.borrow_mut();
2090 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2091 else {
2092 return;
2093 };
2094
2095 if menu.id > completion_menu.id {
2096 return;
2097 }
2098
2099 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2100 drop(context_menu);
2101 cx.notify();
2102 })
2103 })
2104 .detach();
2105
2106 if show_completions {
2107 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2108 }
2109 } else {
2110 drop(context_menu);
2111 self.hide_context_menu(window, cx);
2112 }
2113 } else {
2114 drop(context_menu);
2115 }
2116
2117 hide_hover(self, cx);
2118
2119 if old_cursor_position.to_display_point(&display_map).row()
2120 != new_cursor_position.to_display_point(&display_map).row()
2121 {
2122 self.available_code_actions.take();
2123 }
2124 self.refresh_code_actions(window, cx);
2125 self.refresh_document_highlights(cx);
2126 self.refresh_selected_text_highlights(window, cx);
2127 refresh_matching_bracket_highlights(self, window, cx);
2128 self.update_visible_inline_completion(window, cx);
2129 self.edit_prediction_requires_modifier_in_leading_space = true;
2130 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2131 if self.git_blame_inline_enabled {
2132 self.start_inline_blame_timer(window, cx);
2133 }
2134 }
2135
2136 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2137 cx.emit(EditorEvent::SelectionsChanged { local });
2138
2139 let selections = &self.selections.disjoint;
2140 if selections.len() == 1 {
2141 cx.emit(SearchEvent::ActiveMatchChanged)
2142 }
2143 if local
2144 && self.is_singleton(cx)
2145 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2146 {
2147 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2148 let background_executor = cx.background_executor().clone();
2149 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2150 let snapshot = self.buffer().read(cx).snapshot(cx);
2151 let selections = selections.clone();
2152 self.serialize_selections = cx.background_spawn(async move {
2153 background_executor.timer(Duration::from_millis(100)).await;
2154 let selections = selections
2155 .iter()
2156 .map(|selection| {
2157 (
2158 selection.start.to_offset(&snapshot),
2159 selection.end.to_offset(&snapshot),
2160 )
2161 })
2162 .collect();
2163 DB.save_editor_selections(editor_id, workspace_id, selections)
2164 .await
2165 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2166 .log_err();
2167 });
2168 }
2169 }
2170
2171 cx.notify();
2172 }
2173
2174 pub fn change_selections<R>(
2175 &mut self,
2176 autoscroll: Option<Autoscroll>,
2177 window: &mut Window,
2178 cx: &mut Context<Self>,
2179 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2180 ) -> R {
2181 self.change_selections_inner(autoscroll, true, window, cx, change)
2182 }
2183
2184 fn change_selections_inner<R>(
2185 &mut self,
2186 autoscroll: Option<Autoscroll>,
2187 request_completions: bool,
2188 window: &mut Window,
2189 cx: &mut Context<Self>,
2190 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2191 ) -> R {
2192 let old_cursor_position = self.selections.newest_anchor().head();
2193 self.push_to_selection_history();
2194
2195 let (changed, result) = self.selections.change_with(cx, change);
2196
2197 if changed {
2198 if let Some(autoscroll) = autoscroll {
2199 self.request_autoscroll(autoscroll, cx);
2200 }
2201 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2202
2203 if self.should_open_signature_help_automatically(
2204 &old_cursor_position,
2205 self.signature_help_state.backspace_pressed(),
2206 cx,
2207 ) {
2208 self.show_signature_help(&ShowSignatureHelp, window, cx);
2209 }
2210 self.signature_help_state.set_backspace_pressed(false);
2211 }
2212
2213 result
2214 }
2215
2216 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2217 where
2218 I: IntoIterator<Item = (Range<S>, T)>,
2219 S: ToOffset,
2220 T: Into<Arc<str>>,
2221 {
2222 if self.read_only(cx) {
2223 return;
2224 }
2225
2226 self.buffer
2227 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2228 }
2229
2230 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2231 where
2232 I: IntoIterator<Item = (Range<S>, T)>,
2233 S: ToOffset,
2234 T: Into<Arc<str>>,
2235 {
2236 if self.read_only(cx) {
2237 return;
2238 }
2239
2240 self.buffer.update(cx, |buffer, cx| {
2241 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2242 });
2243 }
2244
2245 pub fn edit_with_block_indent<I, S, T>(
2246 &mut self,
2247 edits: I,
2248 original_indent_columns: Vec<u32>,
2249 cx: &mut Context<Self>,
2250 ) where
2251 I: IntoIterator<Item = (Range<S>, T)>,
2252 S: ToOffset,
2253 T: Into<Arc<str>>,
2254 {
2255 if self.read_only(cx) {
2256 return;
2257 }
2258
2259 self.buffer.update(cx, |buffer, cx| {
2260 buffer.edit(
2261 edits,
2262 Some(AutoindentMode::Block {
2263 original_indent_columns,
2264 }),
2265 cx,
2266 )
2267 });
2268 }
2269
2270 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2271 self.hide_context_menu(window, cx);
2272
2273 match phase {
2274 SelectPhase::Begin {
2275 position,
2276 add,
2277 click_count,
2278 } => self.begin_selection(position, add, click_count, window, cx),
2279 SelectPhase::BeginColumnar {
2280 position,
2281 goal_column,
2282 reset,
2283 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2284 SelectPhase::Extend {
2285 position,
2286 click_count,
2287 } => self.extend_selection(position, click_count, window, cx),
2288 SelectPhase::Update {
2289 position,
2290 goal_column,
2291 scroll_delta,
2292 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2293 SelectPhase::End => self.end_selection(window, cx),
2294 }
2295 }
2296
2297 fn extend_selection(
2298 &mut self,
2299 position: DisplayPoint,
2300 click_count: usize,
2301 window: &mut Window,
2302 cx: &mut Context<Self>,
2303 ) {
2304 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2305 let tail = self.selections.newest::<usize>(cx).tail();
2306 self.begin_selection(position, false, click_count, window, cx);
2307
2308 let position = position.to_offset(&display_map, Bias::Left);
2309 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2310
2311 let mut pending_selection = self
2312 .selections
2313 .pending_anchor()
2314 .expect("extend_selection not called with pending selection");
2315 if position >= tail {
2316 pending_selection.start = tail_anchor;
2317 } else {
2318 pending_selection.end = tail_anchor;
2319 pending_selection.reversed = true;
2320 }
2321
2322 let mut pending_mode = self.selections.pending_mode().unwrap();
2323 match &mut pending_mode {
2324 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2325 _ => {}
2326 }
2327
2328 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2329 s.set_pending(pending_selection, pending_mode)
2330 });
2331 }
2332
2333 fn begin_selection(
2334 &mut self,
2335 position: DisplayPoint,
2336 add: bool,
2337 click_count: usize,
2338 window: &mut Window,
2339 cx: &mut Context<Self>,
2340 ) {
2341 if !self.focus_handle.is_focused(window) {
2342 self.last_focused_descendant = None;
2343 window.focus(&self.focus_handle);
2344 }
2345
2346 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2347 let buffer = &display_map.buffer_snapshot;
2348 let newest_selection = self.selections.newest_anchor().clone();
2349 let position = display_map.clip_point(position, Bias::Left);
2350
2351 let start;
2352 let end;
2353 let mode;
2354 let mut auto_scroll;
2355 match click_count {
2356 1 => {
2357 start = buffer.anchor_before(position.to_point(&display_map));
2358 end = start;
2359 mode = SelectMode::Character;
2360 auto_scroll = true;
2361 }
2362 2 => {
2363 let range = movement::surrounding_word(&display_map, position);
2364 start = buffer.anchor_before(range.start.to_point(&display_map));
2365 end = buffer.anchor_before(range.end.to_point(&display_map));
2366 mode = SelectMode::Word(start..end);
2367 auto_scroll = true;
2368 }
2369 3 => {
2370 let position = display_map
2371 .clip_point(position, Bias::Left)
2372 .to_point(&display_map);
2373 let line_start = display_map.prev_line_boundary(position).0;
2374 let next_line_start = buffer.clip_point(
2375 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2376 Bias::Left,
2377 );
2378 start = buffer.anchor_before(line_start);
2379 end = buffer.anchor_before(next_line_start);
2380 mode = SelectMode::Line(start..end);
2381 auto_scroll = true;
2382 }
2383 _ => {
2384 start = buffer.anchor_before(0);
2385 end = buffer.anchor_before(buffer.len());
2386 mode = SelectMode::All;
2387 auto_scroll = false;
2388 }
2389 }
2390 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2391
2392 let point_to_delete: Option<usize> = {
2393 let selected_points: Vec<Selection<Point>> =
2394 self.selections.disjoint_in_range(start..end, cx);
2395
2396 if !add || click_count > 1 {
2397 None
2398 } else if !selected_points.is_empty() {
2399 Some(selected_points[0].id)
2400 } else {
2401 let clicked_point_already_selected =
2402 self.selections.disjoint.iter().find(|selection| {
2403 selection.start.to_point(buffer) == start.to_point(buffer)
2404 || selection.end.to_point(buffer) == end.to_point(buffer)
2405 });
2406
2407 clicked_point_already_selected.map(|selection| selection.id)
2408 }
2409 };
2410
2411 let selections_count = self.selections.count();
2412
2413 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2414 if let Some(point_to_delete) = point_to_delete {
2415 s.delete(point_to_delete);
2416
2417 if selections_count == 1 {
2418 s.set_pending_anchor_range(start..end, mode);
2419 }
2420 } else {
2421 if !add {
2422 s.clear_disjoint();
2423 } else if click_count > 1 {
2424 s.delete(newest_selection.id)
2425 }
2426
2427 s.set_pending_anchor_range(start..end, mode);
2428 }
2429 });
2430 }
2431
2432 fn begin_columnar_selection(
2433 &mut self,
2434 position: DisplayPoint,
2435 goal_column: u32,
2436 reset: bool,
2437 window: &mut Window,
2438 cx: &mut Context<Self>,
2439 ) {
2440 if !self.focus_handle.is_focused(window) {
2441 self.last_focused_descendant = None;
2442 window.focus(&self.focus_handle);
2443 }
2444
2445 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2446
2447 if reset {
2448 let pointer_position = display_map
2449 .buffer_snapshot
2450 .anchor_before(position.to_point(&display_map));
2451
2452 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2453 s.clear_disjoint();
2454 s.set_pending_anchor_range(
2455 pointer_position..pointer_position,
2456 SelectMode::Character,
2457 );
2458 });
2459 }
2460
2461 let tail = self.selections.newest::<Point>(cx).tail();
2462 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2463
2464 if !reset {
2465 self.select_columns(
2466 tail.to_display_point(&display_map),
2467 position,
2468 goal_column,
2469 &display_map,
2470 window,
2471 cx,
2472 );
2473 }
2474 }
2475
2476 fn update_selection(
2477 &mut self,
2478 position: DisplayPoint,
2479 goal_column: u32,
2480 scroll_delta: gpui::Point<f32>,
2481 window: &mut Window,
2482 cx: &mut Context<Self>,
2483 ) {
2484 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2485
2486 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2487 let tail = tail.to_display_point(&display_map);
2488 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2489 } else if let Some(mut pending) = self.selections.pending_anchor() {
2490 let buffer = self.buffer.read(cx).snapshot(cx);
2491 let head;
2492 let tail;
2493 let mode = self.selections.pending_mode().unwrap();
2494 match &mode {
2495 SelectMode::Character => {
2496 head = position.to_point(&display_map);
2497 tail = pending.tail().to_point(&buffer);
2498 }
2499 SelectMode::Word(original_range) => {
2500 let original_display_range = original_range.start.to_display_point(&display_map)
2501 ..original_range.end.to_display_point(&display_map);
2502 let original_buffer_range = original_display_range.start.to_point(&display_map)
2503 ..original_display_range.end.to_point(&display_map);
2504 if movement::is_inside_word(&display_map, position)
2505 || original_display_range.contains(&position)
2506 {
2507 let word_range = movement::surrounding_word(&display_map, position);
2508 if word_range.start < original_display_range.start {
2509 head = word_range.start.to_point(&display_map);
2510 } else {
2511 head = word_range.end.to_point(&display_map);
2512 }
2513 } else {
2514 head = position.to_point(&display_map);
2515 }
2516
2517 if head <= original_buffer_range.start {
2518 tail = original_buffer_range.end;
2519 } else {
2520 tail = original_buffer_range.start;
2521 }
2522 }
2523 SelectMode::Line(original_range) => {
2524 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2525
2526 let position = display_map
2527 .clip_point(position, Bias::Left)
2528 .to_point(&display_map);
2529 let line_start = display_map.prev_line_boundary(position).0;
2530 let next_line_start = buffer.clip_point(
2531 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2532 Bias::Left,
2533 );
2534
2535 if line_start < original_range.start {
2536 head = line_start
2537 } else {
2538 head = next_line_start
2539 }
2540
2541 if head <= original_range.start {
2542 tail = original_range.end;
2543 } else {
2544 tail = original_range.start;
2545 }
2546 }
2547 SelectMode::All => {
2548 return;
2549 }
2550 };
2551
2552 if head < tail {
2553 pending.start = buffer.anchor_before(head);
2554 pending.end = buffer.anchor_before(tail);
2555 pending.reversed = true;
2556 } else {
2557 pending.start = buffer.anchor_before(tail);
2558 pending.end = buffer.anchor_before(head);
2559 pending.reversed = false;
2560 }
2561
2562 self.change_selections(None, window, cx, |s| {
2563 s.set_pending(pending, mode);
2564 });
2565 } else {
2566 log::error!("update_selection dispatched with no pending selection");
2567 return;
2568 }
2569
2570 self.apply_scroll_delta(scroll_delta, window, cx);
2571 cx.notify();
2572 }
2573
2574 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2575 self.columnar_selection_tail.take();
2576 if self.selections.pending_anchor().is_some() {
2577 let selections = self.selections.all::<usize>(cx);
2578 self.change_selections(None, window, cx, |s| {
2579 s.select(selections);
2580 s.clear_pending();
2581 });
2582 }
2583 }
2584
2585 fn select_columns(
2586 &mut self,
2587 tail: DisplayPoint,
2588 head: DisplayPoint,
2589 goal_column: u32,
2590 display_map: &DisplaySnapshot,
2591 window: &mut Window,
2592 cx: &mut Context<Self>,
2593 ) {
2594 let start_row = cmp::min(tail.row(), head.row());
2595 let end_row = cmp::max(tail.row(), head.row());
2596 let start_column = cmp::min(tail.column(), goal_column);
2597 let end_column = cmp::max(tail.column(), goal_column);
2598 let reversed = start_column < tail.column();
2599
2600 let selection_ranges = (start_row.0..=end_row.0)
2601 .map(DisplayRow)
2602 .filter_map(|row| {
2603 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2604 let start = display_map
2605 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2606 .to_point(display_map);
2607 let end = display_map
2608 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2609 .to_point(display_map);
2610 if reversed {
2611 Some(end..start)
2612 } else {
2613 Some(start..end)
2614 }
2615 } else {
2616 None
2617 }
2618 })
2619 .collect::<Vec<_>>();
2620
2621 self.change_selections(None, window, cx, |s| {
2622 s.select_ranges(selection_ranges);
2623 });
2624 cx.notify();
2625 }
2626
2627 pub fn has_pending_nonempty_selection(&self) -> bool {
2628 let pending_nonempty_selection = match self.selections.pending_anchor() {
2629 Some(Selection { start, end, .. }) => start != end,
2630 None => false,
2631 };
2632
2633 pending_nonempty_selection
2634 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2635 }
2636
2637 pub fn has_pending_selection(&self) -> bool {
2638 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2639 }
2640
2641 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2642 self.selection_mark_mode = false;
2643
2644 if self.clear_expanded_diff_hunks(cx) {
2645 cx.notify();
2646 return;
2647 }
2648 if self.dismiss_menus_and_popups(true, window, cx) {
2649 return;
2650 }
2651
2652 if self.mode == EditorMode::Full
2653 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2654 {
2655 return;
2656 }
2657
2658 cx.propagate();
2659 }
2660
2661 pub fn dismiss_menus_and_popups(
2662 &mut self,
2663 is_user_requested: bool,
2664 window: &mut Window,
2665 cx: &mut Context<Self>,
2666 ) -> bool {
2667 if self.take_rename(false, window, cx).is_some() {
2668 return true;
2669 }
2670
2671 if hide_hover(self, cx) {
2672 return true;
2673 }
2674
2675 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2676 return true;
2677 }
2678
2679 if self.hide_context_menu(window, cx).is_some() {
2680 return true;
2681 }
2682
2683 if self.mouse_context_menu.take().is_some() {
2684 return true;
2685 }
2686
2687 if is_user_requested && self.discard_inline_completion(true, cx) {
2688 return true;
2689 }
2690
2691 if self.snippet_stack.pop().is_some() {
2692 return true;
2693 }
2694
2695 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2696 self.dismiss_diagnostics(cx);
2697 return true;
2698 }
2699
2700 false
2701 }
2702
2703 fn linked_editing_ranges_for(
2704 &self,
2705 selection: Range<text::Anchor>,
2706 cx: &App,
2707 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2708 if self.linked_edit_ranges.is_empty() {
2709 return None;
2710 }
2711 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2712 selection.end.buffer_id.and_then(|end_buffer_id| {
2713 if selection.start.buffer_id != Some(end_buffer_id) {
2714 return None;
2715 }
2716 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2717 let snapshot = buffer.read(cx).snapshot();
2718 self.linked_edit_ranges
2719 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2720 .map(|ranges| (ranges, snapshot, buffer))
2721 })?;
2722 use text::ToOffset as TO;
2723 // find offset from the start of current range to current cursor position
2724 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2725
2726 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2727 let start_difference = start_offset - start_byte_offset;
2728 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2729 let end_difference = end_offset - start_byte_offset;
2730 // Current range has associated linked ranges.
2731 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2732 for range in linked_ranges.iter() {
2733 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2734 let end_offset = start_offset + end_difference;
2735 let start_offset = start_offset + start_difference;
2736 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2737 continue;
2738 }
2739 if self.selections.disjoint_anchor_ranges().any(|s| {
2740 if s.start.buffer_id != selection.start.buffer_id
2741 || s.end.buffer_id != selection.end.buffer_id
2742 {
2743 return false;
2744 }
2745 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2746 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2747 }) {
2748 continue;
2749 }
2750 let start = buffer_snapshot.anchor_after(start_offset);
2751 let end = buffer_snapshot.anchor_after(end_offset);
2752 linked_edits
2753 .entry(buffer.clone())
2754 .or_default()
2755 .push(start..end);
2756 }
2757 Some(linked_edits)
2758 }
2759
2760 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2761 let text: Arc<str> = text.into();
2762
2763 if self.read_only(cx) {
2764 return;
2765 }
2766
2767 let selections = self.selections.all_adjusted(cx);
2768 let mut bracket_inserted = false;
2769 let mut edits = Vec::new();
2770 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2771 let mut new_selections = Vec::with_capacity(selections.len());
2772 let mut new_autoclose_regions = Vec::new();
2773 let snapshot = self.buffer.read(cx).read(cx);
2774
2775 for (selection, autoclose_region) in
2776 self.selections_with_autoclose_regions(selections, &snapshot)
2777 {
2778 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2779 // Determine if the inserted text matches the opening or closing
2780 // bracket of any of this language's bracket pairs.
2781 let mut bracket_pair = None;
2782 let mut is_bracket_pair_start = false;
2783 let mut is_bracket_pair_end = false;
2784 if !text.is_empty() {
2785 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2786 // and they are removing the character that triggered IME popup.
2787 for (pair, enabled) in scope.brackets() {
2788 if !pair.close && !pair.surround {
2789 continue;
2790 }
2791
2792 if enabled && pair.start.ends_with(text.as_ref()) {
2793 let prefix_len = pair.start.len() - text.len();
2794 let preceding_text_matches_prefix = prefix_len == 0
2795 || (selection.start.column >= (prefix_len as u32)
2796 && snapshot.contains_str_at(
2797 Point::new(
2798 selection.start.row,
2799 selection.start.column - (prefix_len as u32),
2800 ),
2801 &pair.start[..prefix_len],
2802 ));
2803 if preceding_text_matches_prefix {
2804 bracket_pair = Some(pair.clone());
2805 is_bracket_pair_start = true;
2806 break;
2807 }
2808 }
2809 if pair.end.as_str() == text.as_ref() {
2810 bracket_pair = Some(pair.clone());
2811 is_bracket_pair_end = true;
2812 break;
2813 }
2814 }
2815 }
2816
2817 if let Some(bracket_pair) = bracket_pair {
2818 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2819 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2820 let auto_surround =
2821 self.use_auto_surround && snapshot_settings.use_auto_surround;
2822 if selection.is_empty() {
2823 if is_bracket_pair_start {
2824 // If the inserted text is a suffix of an opening bracket and the
2825 // selection is preceded by the rest of the opening bracket, then
2826 // insert the closing bracket.
2827 let following_text_allows_autoclose = snapshot
2828 .chars_at(selection.start)
2829 .next()
2830 .map_or(true, |c| scope.should_autoclose_before(c));
2831
2832 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2833 && bracket_pair.start.len() == 1
2834 {
2835 let target = bracket_pair.start.chars().next().unwrap();
2836 let current_line_count = snapshot
2837 .reversed_chars_at(selection.start)
2838 .take_while(|&c| c != '\n')
2839 .filter(|&c| c == target)
2840 .count();
2841 current_line_count % 2 == 1
2842 } else {
2843 false
2844 };
2845
2846 if autoclose
2847 && bracket_pair.close
2848 && following_text_allows_autoclose
2849 && !is_closing_quote
2850 {
2851 let anchor = snapshot.anchor_before(selection.end);
2852 new_selections.push((selection.map(|_| anchor), text.len()));
2853 new_autoclose_regions.push((
2854 anchor,
2855 text.len(),
2856 selection.id,
2857 bracket_pair.clone(),
2858 ));
2859 edits.push((
2860 selection.range(),
2861 format!("{}{}", text, bracket_pair.end).into(),
2862 ));
2863 bracket_inserted = true;
2864 continue;
2865 }
2866 }
2867
2868 if let Some(region) = autoclose_region {
2869 // If the selection is followed by an auto-inserted closing bracket,
2870 // then don't insert that closing bracket again; just move the selection
2871 // past the closing bracket.
2872 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2873 && text.as_ref() == region.pair.end.as_str();
2874 if should_skip {
2875 let anchor = snapshot.anchor_after(selection.end);
2876 new_selections
2877 .push((selection.map(|_| anchor), region.pair.end.len()));
2878 continue;
2879 }
2880 }
2881
2882 let always_treat_brackets_as_autoclosed = snapshot
2883 .settings_at(selection.start, cx)
2884 .always_treat_brackets_as_autoclosed;
2885 if always_treat_brackets_as_autoclosed
2886 && is_bracket_pair_end
2887 && snapshot.contains_str_at(selection.end, text.as_ref())
2888 {
2889 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2890 // and the inserted text is a closing bracket and the selection is followed
2891 // by the closing bracket then move the selection past the closing bracket.
2892 let anchor = snapshot.anchor_after(selection.end);
2893 new_selections.push((selection.map(|_| anchor), text.len()));
2894 continue;
2895 }
2896 }
2897 // If an opening bracket is 1 character long and is typed while
2898 // text is selected, then surround that text with the bracket pair.
2899 else if auto_surround
2900 && bracket_pair.surround
2901 && is_bracket_pair_start
2902 && bracket_pair.start.chars().count() == 1
2903 {
2904 edits.push((selection.start..selection.start, text.clone()));
2905 edits.push((
2906 selection.end..selection.end,
2907 bracket_pair.end.as_str().into(),
2908 ));
2909 bracket_inserted = true;
2910 new_selections.push((
2911 Selection {
2912 id: selection.id,
2913 start: snapshot.anchor_after(selection.start),
2914 end: snapshot.anchor_before(selection.end),
2915 reversed: selection.reversed,
2916 goal: selection.goal,
2917 },
2918 0,
2919 ));
2920 continue;
2921 }
2922 }
2923 }
2924
2925 if self.auto_replace_emoji_shortcode
2926 && selection.is_empty()
2927 && text.as_ref().ends_with(':')
2928 {
2929 if let Some(possible_emoji_short_code) =
2930 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2931 {
2932 if !possible_emoji_short_code.is_empty() {
2933 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2934 let emoji_shortcode_start = Point::new(
2935 selection.start.row,
2936 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2937 );
2938
2939 // Remove shortcode from buffer
2940 edits.push((
2941 emoji_shortcode_start..selection.start,
2942 "".to_string().into(),
2943 ));
2944 new_selections.push((
2945 Selection {
2946 id: selection.id,
2947 start: snapshot.anchor_after(emoji_shortcode_start),
2948 end: snapshot.anchor_before(selection.start),
2949 reversed: selection.reversed,
2950 goal: selection.goal,
2951 },
2952 0,
2953 ));
2954
2955 // Insert emoji
2956 let selection_start_anchor = snapshot.anchor_after(selection.start);
2957 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2958 edits.push((selection.start..selection.end, emoji.to_string().into()));
2959
2960 continue;
2961 }
2962 }
2963 }
2964 }
2965
2966 // If not handling any auto-close operation, then just replace the selected
2967 // text with the given input and move the selection to the end of the
2968 // newly inserted text.
2969 let anchor = snapshot.anchor_after(selection.end);
2970 if !self.linked_edit_ranges.is_empty() {
2971 let start_anchor = snapshot.anchor_before(selection.start);
2972
2973 let is_word_char = text.chars().next().map_or(true, |char| {
2974 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2975 classifier.is_word(char)
2976 });
2977
2978 if is_word_char {
2979 if let Some(ranges) = self
2980 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2981 {
2982 for (buffer, edits) in ranges {
2983 linked_edits
2984 .entry(buffer.clone())
2985 .or_default()
2986 .extend(edits.into_iter().map(|range| (range, text.clone())));
2987 }
2988 }
2989 }
2990 }
2991
2992 new_selections.push((selection.map(|_| anchor), 0));
2993 edits.push((selection.start..selection.end, text.clone()));
2994 }
2995
2996 drop(snapshot);
2997
2998 self.transact(window, cx, |this, window, cx| {
2999 this.buffer.update(cx, |buffer, cx| {
3000 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3001 });
3002 for (buffer, edits) in linked_edits {
3003 buffer.update(cx, |buffer, cx| {
3004 let snapshot = buffer.snapshot();
3005 let edits = edits
3006 .into_iter()
3007 .map(|(range, text)| {
3008 use text::ToPoint as TP;
3009 let end_point = TP::to_point(&range.end, &snapshot);
3010 let start_point = TP::to_point(&range.start, &snapshot);
3011 (start_point..end_point, text)
3012 })
3013 .sorted_by_key(|(range, _)| range.start)
3014 .collect::<Vec<_>>();
3015 buffer.edit(edits, None, cx);
3016 })
3017 }
3018 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3019 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3020 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3021 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3022 .zip(new_selection_deltas)
3023 .map(|(selection, delta)| Selection {
3024 id: selection.id,
3025 start: selection.start + delta,
3026 end: selection.end + delta,
3027 reversed: selection.reversed,
3028 goal: SelectionGoal::None,
3029 })
3030 .collect::<Vec<_>>();
3031
3032 let mut i = 0;
3033 for (position, delta, selection_id, pair) in new_autoclose_regions {
3034 let position = position.to_offset(&map.buffer_snapshot) + delta;
3035 let start = map.buffer_snapshot.anchor_before(position);
3036 let end = map.buffer_snapshot.anchor_after(position);
3037 while let Some(existing_state) = this.autoclose_regions.get(i) {
3038 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3039 Ordering::Less => i += 1,
3040 Ordering::Greater => break,
3041 Ordering::Equal => {
3042 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3043 Ordering::Less => i += 1,
3044 Ordering::Equal => break,
3045 Ordering::Greater => break,
3046 }
3047 }
3048 }
3049 }
3050 this.autoclose_regions.insert(
3051 i,
3052 AutocloseRegion {
3053 selection_id,
3054 range: start..end,
3055 pair,
3056 },
3057 );
3058 }
3059
3060 let had_active_inline_completion = this.has_active_inline_completion();
3061 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3062 s.select(new_selections)
3063 });
3064
3065 if !bracket_inserted {
3066 if let Some(on_type_format_task) =
3067 this.trigger_on_type_formatting(text.to_string(), window, cx)
3068 {
3069 on_type_format_task.detach_and_log_err(cx);
3070 }
3071 }
3072
3073 let editor_settings = EditorSettings::get_global(cx);
3074 if bracket_inserted
3075 && (editor_settings.auto_signature_help
3076 || editor_settings.show_signature_help_after_edits)
3077 {
3078 this.show_signature_help(&ShowSignatureHelp, window, cx);
3079 }
3080
3081 let trigger_in_words =
3082 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3083 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3084 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3085 this.refresh_inline_completion(true, false, window, cx);
3086 });
3087 }
3088
3089 fn find_possible_emoji_shortcode_at_position(
3090 snapshot: &MultiBufferSnapshot,
3091 position: Point,
3092 ) -> Option<String> {
3093 let mut chars = Vec::new();
3094 let mut found_colon = false;
3095 for char in snapshot.reversed_chars_at(position).take(100) {
3096 // Found a possible emoji shortcode in the middle of the buffer
3097 if found_colon {
3098 if char.is_whitespace() {
3099 chars.reverse();
3100 return Some(chars.iter().collect());
3101 }
3102 // If the previous character is not a whitespace, we are in the middle of a word
3103 // and we only want to complete the shortcode if the word is made up of other emojis
3104 let mut containing_word = String::new();
3105 for ch in snapshot
3106 .reversed_chars_at(position)
3107 .skip(chars.len() + 1)
3108 .take(100)
3109 {
3110 if ch.is_whitespace() {
3111 break;
3112 }
3113 containing_word.push(ch);
3114 }
3115 let containing_word = containing_word.chars().rev().collect::<String>();
3116 if util::word_consists_of_emojis(containing_word.as_str()) {
3117 chars.reverse();
3118 return Some(chars.iter().collect());
3119 }
3120 }
3121
3122 if char.is_whitespace() || !char.is_ascii() {
3123 return None;
3124 }
3125 if char == ':' {
3126 found_colon = true;
3127 } else {
3128 chars.push(char);
3129 }
3130 }
3131 // Found a possible emoji shortcode at the beginning of the buffer
3132 chars.reverse();
3133 Some(chars.iter().collect())
3134 }
3135
3136 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3137 self.transact(window, cx, |this, window, cx| {
3138 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3139 let selections = this.selections.all::<usize>(cx);
3140 let multi_buffer = this.buffer.read(cx);
3141 let buffer = multi_buffer.snapshot(cx);
3142 selections
3143 .iter()
3144 .map(|selection| {
3145 let start_point = selection.start.to_point(&buffer);
3146 let mut indent =
3147 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3148 indent.len = cmp::min(indent.len, start_point.column);
3149 let start = selection.start;
3150 let end = selection.end;
3151 let selection_is_empty = start == end;
3152 let language_scope = buffer.language_scope_at(start);
3153 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3154 &language_scope
3155 {
3156 let insert_extra_newline =
3157 insert_extra_newline_brackets(&buffer, start..end, language)
3158 || insert_extra_newline_tree_sitter(&buffer, start..end);
3159
3160 // Comment extension on newline is allowed only for cursor selections
3161 let comment_delimiter = maybe!({
3162 if !selection_is_empty {
3163 return None;
3164 }
3165
3166 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3167 return None;
3168 }
3169
3170 let delimiters = language.line_comment_prefixes();
3171 let max_len_of_delimiter =
3172 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3173 let (snapshot, range) =
3174 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3175
3176 let mut index_of_first_non_whitespace = 0;
3177 let comment_candidate = snapshot
3178 .chars_for_range(range)
3179 .skip_while(|c| {
3180 let should_skip = c.is_whitespace();
3181 if should_skip {
3182 index_of_first_non_whitespace += 1;
3183 }
3184 should_skip
3185 })
3186 .take(max_len_of_delimiter)
3187 .collect::<String>();
3188 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3189 comment_candidate.starts_with(comment_prefix.as_ref())
3190 })?;
3191 let cursor_is_placed_after_comment_marker =
3192 index_of_first_non_whitespace + comment_prefix.len()
3193 <= start_point.column as usize;
3194 if cursor_is_placed_after_comment_marker {
3195 Some(comment_prefix.clone())
3196 } else {
3197 None
3198 }
3199 });
3200 (comment_delimiter, insert_extra_newline)
3201 } else {
3202 (None, false)
3203 };
3204
3205 let capacity_for_delimiter = comment_delimiter
3206 .as_deref()
3207 .map(str::len)
3208 .unwrap_or_default();
3209 let mut new_text =
3210 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3211 new_text.push('\n');
3212 new_text.extend(indent.chars());
3213 if let Some(delimiter) = &comment_delimiter {
3214 new_text.push_str(delimiter);
3215 }
3216 if insert_extra_newline {
3217 new_text = new_text.repeat(2);
3218 }
3219
3220 let anchor = buffer.anchor_after(end);
3221 let new_selection = selection.map(|_| anchor);
3222 (
3223 (start..end, new_text),
3224 (insert_extra_newline, new_selection),
3225 )
3226 })
3227 .unzip()
3228 };
3229
3230 this.edit_with_autoindent(edits, cx);
3231 let buffer = this.buffer.read(cx).snapshot(cx);
3232 let new_selections = selection_fixup_info
3233 .into_iter()
3234 .map(|(extra_newline_inserted, new_selection)| {
3235 let mut cursor = new_selection.end.to_point(&buffer);
3236 if extra_newline_inserted {
3237 cursor.row -= 1;
3238 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3239 }
3240 new_selection.map(|_| cursor)
3241 })
3242 .collect();
3243
3244 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3245 s.select(new_selections)
3246 });
3247 this.refresh_inline_completion(true, false, window, cx);
3248 });
3249 }
3250
3251 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3252 let buffer = self.buffer.read(cx);
3253 let snapshot = buffer.snapshot(cx);
3254
3255 let mut edits = Vec::new();
3256 let mut rows = Vec::new();
3257
3258 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3259 let cursor = selection.head();
3260 let row = cursor.row;
3261
3262 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3263
3264 let newline = "\n".to_string();
3265 edits.push((start_of_line..start_of_line, newline));
3266
3267 rows.push(row + rows_inserted as u32);
3268 }
3269
3270 self.transact(window, cx, |editor, window, cx| {
3271 editor.edit(edits, cx);
3272
3273 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3274 let mut index = 0;
3275 s.move_cursors_with(|map, _, _| {
3276 let row = rows[index];
3277 index += 1;
3278
3279 let point = Point::new(row, 0);
3280 let boundary = map.next_line_boundary(point).1;
3281 let clipped = map.clip_point(boundary, Bias::Left);
3282
3283 (clipped, SelectionGoal::None)
3284 });
3285 });
3286
3287 let mut indent_edits = Vec::new();
3288 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3289 for row in rows {
3290 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3291 for (row, indent) in indents {
3292 if indent.len == 0 {
3293 continue;
3294 }
3295
3296 let text = match indent.kind {
3297 IndentKind::Space => " ".repeat(indent.len as usize),
3298 IndentKind::Tab => "\t".repeat(indent.len as usize),
3299 };
3300 let point = Point::new(row.0, 0);
3301 indent_edits.push((point..point, text));
3302 }
3303 }
3304 editor.edit(indent_edits, cx);
3305 });
3306 }
3307
3308 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3309 let buffer = self.buffer.read(cx);
3310 let snapshot = buffer.snapshot(cx);
3311
3312 let mut edits = Vec::new();
3313 let mut rows = Vec::new();
3314 let mut rows_inserted = 0;
3315
3316 for selection in self.selections.all_adjusted(cx) {
3317 let cursor = selection.head();
3318 let row = cursor.row;
3319
3320 let point = Point::new(row + 1, 0);
3321 let start_of_line = snapshot.clip_point(point, Bias::Left);
3322
3323 let newline = "\n".to_string();
3324 edits.push((start_of_line..start_of_line, newline));
3325
3326 rows_inserted += 1;
3327 rows.push(row + rows_inserted);
3328 }
3329
3330 self.transact(window, cx, |editor, window, cx| {
3331 editor.edit(edits, cx);
3332
3333 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3334 let mut index = 0;
3335 s.move_cursors_with(|map, _, _| {
3336 let row = rows[index];
3337 index += 1;
3338
3339 let point = Point::new(row, 0);
3340 let boundary = map.next_line_boundary(point).1;
3341 let clipped = map.clip_point(boundary, Bias::Left);
3342
3343 (clipped, SelectionGoal::None)
3344 });
3345 });
3346
3347 let mut indent_edits = Vec::new();
3348 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3349 for row in rows {
3350 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3351 for (row, indent) in indents {
3352 if indent.len == 0 {
3353 continue;
3354 }
3355
3356 let text = match indent.kind {
3357 IndentKind::Space => " ".repeat(indent.len as usize),
3358 IndentKind::Tab => "\t".repeat(indent.len as usize),
3359 };
3360 let point = Point::new(row.0, 0);
3361 indent_edits.push((point..point, text));
3362 }
3363 }
3364 editor.edit(indent_edits, cx);
3365 });
3366 }
3367
3368 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3369 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3370 original_indent_columns: Vec::new(),
3371 });
3372 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3373 }
3374
3375 fn insert_with_autoindent_mode(
3376 &mut self,
3377 text: &str,
3378 autoindent_mode: Option<AutoindentMode>,
3379 window: &mut Window,
3380 cx: &mut Context<Self>,
3381 ) {
3382 if self.read_only(cx) {
3383 return;
3384 }
3385
3386 let text: Arc<str> = text.into();
3387 self.transact(window, cx, |this, window, cx| {
3388 let old_selections = this.selections.all_adjusted(cx);
3389 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3390 let anchors = {
3391 let snapshot = buffer.read(cx);
3392 old_selections
3393 .iter()
3394 .map(|s| {
3395 let anchor = snapshot.anchor_after(s.head());
3396 s.map(|_| anchor)
3397 })
3398 .collect::<Vec<_>>()
3399 };
3400 buffer.edit(
3401 old_selections
3402 .iter()
3403 .map(|s| (s.start..s.end, text.clone())),
3404 autoindent_mode,
3405 cx,
3406 );
3407 anchors
3408 });
3409
3410 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3411 s.select_anchors(selection_anchors);
3412 });
3413
3414 cx.notify();
3415 });
3416 }
3417
3418 fn trigger_completion_on_input(
3419 &mut self,
3420 text: &str,
3421 trigger_in_words: bool,
3422 window: &mut Window,
3423 cx: &mut Context<Self>,
3424 ) {
3425 if self.is_completion_trigger(text, trigger_in_words, cx) {
3426 self.show_completions(
3427 &ShowCompletions {
3428 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3429 },
3430 window,
3431 cx,
3432 );
3433 } else {
3434 self.hide_context_menu(window, cx);
3435 }
3436 }
3437
3438 fn is_completion_trigger(
3439 &self,
3440 text: &str,
3441 trigger_in_words: bool,
3442 cx: &mut Context<Self>,
3443 ) -> bool {
3444 let position = self.selections.newest_anchor().head();
3445 let multibuffer = self.buffer.read(cx);
3446 let Some(buffer) = position
3447 .buffer_id
3448 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3449 else {
3450 return false;
3451 };
3452
3453 if let Some(completion_provider) = &self.completion_provider {
3454 completion_provider.is_completion_trigger(
3455 &buffer,
3456 position.text_anchor,
3457 text,
3458 trigger_in_words,
3459 cx,
3460 )
3461 } else {
3462 false
3463 }
3464 }
3465
3466 /// If any empty selections is touching the start of its innermost containing autoclose
3467 /// region, expand it to select the brackets.
3468 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3469 let selections = self.selections.all::<usize>(cx);
3470 let buffer = self.buffer.read(cx).read(cx);
3471 let new_selections = self
3472 .selections_with_autoclose_regions(selections, &buffer)
3473 .map(|(mut selection, region)| {
3474 if !selection.is_empty() {
3475 return selection;
3476 }
3477
3478 if let Some(region) = region {
3479 let mut range = region.range.to_offset(&buffer);
3480 if selection.start == range.start && range.start >= region.pair.start.len() {
3481 range.start -= region.pair.start.len();
3482 if buffer.contains_str_at(range.start, ®ion.pair.start)
3483 && buffer.contains_str_at(range.end, ®ion.pair.end)
3484 {
3485 range.end += region.pair.end.len();
3486 selection.start = range.start;
3487 selection.end = range.end;
3488
3489 return selection;
3490 }
3491 }
3492 }
3493
3494 let always_treat_brackets_as_autoclosed = buffer
3495 .settings_at(selection.start, cx)
3496 .always_treat_brackets_as_autoclosed;
3497
3498 if !always_treat_brackets_as_autoclosed {
3499 return selection;
3500 }
3501
3502 if let Some(scope) = buffer.language_scope_at(selection.start) {
3503 for (pair, enabled) in scope.brackets() {
3504 if !enabled || !pair.close {
3505 continue;
3506 }
3507
3508 if buffer.contains_str_at(selection.start, &pair.end) {
3509 let pair_start_len = pair.start.len();
3510 if buffer.contains_str_at(
3511 selection.start.saturating_sub(pair_start_len),
3512 &pair.start,
3513 ) {
3514 selection.start -= pair_start_len;
3515 selection.end += pair.end.len();
3516
3517 return selection;
3518 }
3519 }
3520 }
3521 }
3522
3523 selection
3524 })
3525 .collect();
3526
3527 drop(buffer);
3528 self.change_selections(None, window, cx, |selections| {
3529 selections.select(new_selections)
3530 });
3531 }
3532
3533 /// Iterate the given selections, and for each one, find the smallest surrounding
3534 /// autoclose region. This uses the ordering of the selections and the autoclose
3535 /// regions to avoid repeated comparisons.
3536 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3537 &'a self,
3538 selections: impl IntoIterator<Item = Selection<D>>,
3539 buffer: &'a MultiBufferSnapshot,
3540 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3541 let mut i = 0;
3542 let mut regions = self.autoclose_regions.as_slice();
3543 selections.into_iter().map(move |selection| {
3544 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3545
3546 let mut enclosing = None;
3547 while let Some(pair_state) = regions.get(i) {
3548 if pair_state.range.end.to_offset(buffer) < range.start {
3549 regions = ®ions[i + 1..];
3550 i = 0;
3551 } else if pair_state.range.start.to_offset(buffer) > range.end {
3552 break;
3553 } else {
3554 if pair_state.selection_id == selection.id {
3555 enclosing = Some(pair_state);
3556 }
3557 i += 1;
3558 }
3559 }
3560
3561 (selection, enclosing)
3562 })
3563 }
3564
3565 /// Remove any autoclose regions that no longer contain their selection.
3566 fn invalidate_autoclose_regions(
3567 &mut self,
3568 mut selections: &[Selection<Anchor>],
3569 buffer: &MultiBufferSnapshot,
3570 ) {
3571 self.autoclose_regions.retain(|state| {
3572 let mut i = 0;
3573 while let Some(selection) = selections.get(i) {
3574 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3575 selections = &selections[1..];
3576 continue;
3577 }
3578 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3579 break;
3580 }
3581 if selection.id == state.selection_id {
3582 return true;
3583 } else {
3584 i += 1;
3585 }
3586 }
3587 false
3588 });
3589 }
3590
3591 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3592 let offset = position.to_offset(buffer);
3593 let (word_range, kind) = buffer.surrounding_word(offset, true);
3594 if offset > word_range.start && kind == Some(CharKind::Word) {
3595 Some(
3596 buffer
3597 .text_for_range(word_range.start..offset)
3598 .collect::<String>(),
3599 )
3600 } else {
3601 None
3602 }
3603 }
3604
3605 pub fn toggle_inlay_hints(
3606 &mut self,
3607 _: &ToggleInlayHints,
3608 _: &mut Window,
3609 cx: &mut Context<Self>,
3610 ) {
3611 self.refresh_inlay_hints(
3612 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3613 cx,
3614 );
3615 }
3616
3617 pub fn inlay_hints_enabled(&self) -> bool {
3618 self.inlay_hint_cache.enabled
3619 }
3620
3621 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3622 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3623 return;
3624 }
3625
3626 let reason_description = reason.description();
3627 let ignore_debounce = matches!(
3628 reason,
3629 InlayHintRefreshReason::SettingsChange(_)
3630 | InlayHintRefreshReason::Toggle(_)
3631 | InlayHintRefreshReason::ExcerptsRemoved(_)
3632 );
3633 let (invalidate_cache, required_languages) = match reason {
3634 InlayHintRefreshReason::Toggle(enabled) => {
3635 self.inlay_hint_cache.enabled = enabled;
3636 if enabled {
3637 (InvalidationStrategy::RefreshRequested, None)
3638 } else {
3639 self.inlay_hint_cache.clear();
3640 self.splice_inlays(
3641 &self
3642 .visible_inlay_hints(cx)
3643 .iter()
3644 .map(|inlay| inlay.id)
3645 .collect::<Vec<InlayId>>(),
3646 Vec::new(),
3647 cx,
3648 );
3649 return;
3650 }
3651 }
3652 InlayHintRefreshReason::SettingsChange(new_settings) => {
3653 match self.inlay_hint_cache.update_settings(
3654 &self.buffer,
3655 new_settings,
3656 self.visible_inlay_hints(cx),
3657 cx,
3658 ) {
3659 ControlFlow::Break(Some(InlaySplice {
3660 to_remove,
3661 to_insert,
3662 })) => {
3663 self.splice_inlays(&to_remove, to_insert, cx);
3664 return;
3665 }
3666 ControlFlow::Break(None) => return,
3667 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3668 }
3669 }
3670 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3671 if let Some(InlaySplice {
3672 to_remove,
3673 to_insert,
3674 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3675 {
3676 self.splice_inlays(&to_remove, to_insert, cx);
3677 }
3678 return;
3679 }
3680 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3681 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3682 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3683 }
3684 InlayHintRefreshReason::RefreshRequested => {
3685 (InvalidationStrategy::RefreshRequested, None)
3686 }
3687 };
3688
3689 if let Some(InlaySplice {
3690 to_remove,
3691 to_insert,
3692 }) = self.inlay_hint_cache.spawn_hint_refresh(
3693 reason_description,
3694 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3695 invalidate_cache,
3696 ignore_debounce,
3697 cx,
3698 ) {
3699 self.splice_inlays(&to_remove, to_insert, cx);
3700 }
3701 }
3702
3703 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3704 self.display_map
3705 .read(cx)
3706 .current_inlays()
3707 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3708 .cloned()
3709 .collect()
3710 }
3711
3712 pub fn excerpts_for_inlay_hints_query(
3713 &self,
3714 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3715 cx: &mut Context<Editor>,
3716 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3717 let Some(project) = self.project.as_ref() else {
3718 return HashMap::default();
3719 };
3720 let project = project.read(cx);
3721 let multi_buffer = self.buffer().read(cx);
3722 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3723 let multi_buffer_visible_start = self
3724 .scroll_manager
3725 .anchor()
3726 .anchor
3727 .to_point(&multi_buffer_snapshot);
3728 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3729 multi_buffer_visible_start
3730 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3731 Bias::Left,
3732 );
3733 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3734 multi_buffer_snapshot
3735 .range_to_buffer_ranges(multi_buffer_visible_range)
3736 .into_iter()
3737 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3738 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3739 let buffer_file = project::File::from_dyn(buffer.file())?;
3740 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3741 let worktree_entry = buffer_worktree
3742 .read(cx)
3743 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3744 if worktree_entry.is_ignored {
3745 return None;
3746 }
3747
3748 let language = buffer.language()?;
3749 if let Some(restrict_to_languages) = restrict_to_languages {
3750 if !restrict_to_languages.contains(language) {
3751 return None;
3752 }
3753 }
3754 Some((
3755 excerpt_id,
3756 (
3757 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3758 buffer.version().clone(),
3759 excerpt_visible_range,
3760 ),
3761 ))
3762 })
3763 .collect()
3764 }
3765
3766 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3767 TextLayoutDetails {
3768 text_system: window.text_system().clone(),
3769 editor_style: self.style.clone().unwrap(),
3770 rem_size: window.rem_size(),
3771 scroll_anchor: self.scroll_manager.anchor(),
3772 visible_rows: self.visible_line_count(),
3773 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3774 }
3775 }
3776
3777 pub fn splice_inlays(
3778 &self,
3779 to_remove: &[InlayId],
3780 to_insert: Vec<Inlay>,
3781 cx: &mut Context<Self>,
3782 ) {
3783 self.display_map.update(cx, |display_map, cx| {
3784 display_map.splice_inlays(to_remove, to_insert, cx)
3785 });
3786 cx.notify();
3787 }
3788
3789 fn trigger_on_type_formatting(
3790 &self,
3791 input: String,
3792 window: &mut Window,
3793 cx: &mut Context<Self>,
3794 ) -> Option<Task<Result<()>>> {
3795 if input.len() != 1 {
3796 return None;
3797 }
3798
3799 let project = self.project.as_ref()?;
3800 let position = self.selections.newest_anchor().head();
3801 let (buffer, buffer_position) = self
3802 .buffer
3803 .read(cx)
3804 .text_anchor_for_position(position, cx)?;
3805
3806 let settings = language_settings::language_settings(
3807 buffer
3808 .read(cx)
3809 .language_at(buffer_position)
3810 .map(|l| l.name()),
3811 buffer.read(cx).file(),
3812 cx,
3813 );
3814 if !settings.use_on_type_format {
3815 return None;
3816 }
3817
3818 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3819 // hence we do LSP request & edit on host side only — add formats to host's history.
3820 let push_to_lsp_host_history = true;
3821 // If this is not the host, append its history with new edits.
3822 let push_to_client_history = project.read(cx).is_via_collab();
3823
3824 let on_type_formatting = project.update(cx, |project, cx| {
3825 project.on_type_format(
3826 buffer.clone(),
3827 buffer_position,
3828 input,
3829 push_to_lsp_host_history,
3830 cx,
3831 )
3832 });
3833 Some(cx.spawn_in(window, |editor, mut cx| async move {
3834 if let Some(transaction) = on_type_formatting.await? {
3835 if push_to_client_history {
3836 buffer
3837 .update(&mut cx, |buffer, _| {
3838 buffer.push_transaction(transaction, Instant::now());
3839 })
3840 .ok();
3841 }
3842 editor.update(&mut cx, |editor, cx| {
3843 editor.refresh_document_highlights(cx);
3844 })?;
3845 }
3846 Ok(())
3847 }))
3848 }
3849
3850 pub fn show_completions(
3851 &mut self,
3852 options: &ShowCompletions,
3853 window: &mut Window,
3854 cx: &mut Context<Self>,
3855 ) {
3856 if self.pending_rename.is_some() {
3857 return;
3858 }
3859
3860 let Some(provider) = self.completion_provider.as_ref() else {
3861 return;
3862 };
3863
3864 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3865 return;
3866 }
3867
3868 let position = self.selections.newest_anchor().head();
3869 if position.diff_base_anchor.is_some() {
3870 return;
3871 }
3872 let (buffer, buffer_position) =
3873 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3874 output
3875 } else {
3876 return;
3877 };
3878 let show_completion_documentation = buffer
3879 .read(cx)
3880 .snapshot()
3881 .settings_at(buffer_position, cx)
3882 .show_completion_documentation;
3883
3884 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3885
3886 let trigger_kind = match &options.trigger {
3887 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3888 CompletionTriggerKind::TRIGGER_CHARACTER
3889 }
3890 _ => CompletionTriggerKind::INVOKED,
3891 };
3892 let completion_context = CompletionContext {
3893 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3894 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3895 Some(String::from(trigger))
3896 } else {
3897 None
3898 }
3899 }),
3900 trigger_kind,
3901 };
3902 let completions =
3903 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3904 let sort_completions = provider.sort_completions();
3905
3906 let id = post_inc(&mut self.next_completion_id);
3907 let task = cx.spawn_in(window, |editor, mut cx| {
3908 async move {
3909 editor.update(&mut cx, |this, _| {
3910 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3911 })?;
3912 let completions = completions.await.log_err();
3913 let menu = if let Some(completions) = completions {
3914 let mut menu = CompletionsMenu::new(
3915 id,
3916 sort_completions,
3917 show_completion_documentation,
3918 position,
3919 buffer.clone(),
3920 completions.into(),
3921 );
3922
3923 menu.filter(query.as_deref(), cx.background_executor().clone())
3924 .await;
3925
3926 menu.visible().then_some(menu)
3927 } else {
3928 None
3929 };
3930
3931 editor.update_in(&mut cx, |editor, window, cx| {
3932 match editor.context_menu.borrow().as_ref() {
3933 None => {}
3934 Some(CodeContextMenu::Completions(prev_menu)) => {
3935 if prev_menu.id > id {
3936 return;
3937 }
3938 }
3939 _ => return,
3940 }
3941
3942 if editor.focus_handle.is_focused(window) && menu.is_some() {
3943 let mut menu = menu.unwrap();
3944 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3945
3946 *editor.context_menu.borrow_mut() =
3947 Some(CodeContextMenu::Completions(menu));
3948
3949 if editor.show_edit_predictions_in_menu() {
3950 editor.update_visible_inline_completion(window, cx);
3951 } else {
3952 editor.discard_inline_completion(false, cx);
3953 }
3954
3955 cx.notify();
3956 } else if editor.completion_tasks.len() <= 1 {
3957 // If there are no more completion tasks and the last menu was
3958 // empty, we should hide it.
3959 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3960 // If it was already hidden and we don't show inline
3961 // completions in the menu, we should also show the
3962 // inline-completion when available.
3963 if was_hidden && editor.show_edit_predictions_in_menu() {
3964 editor.update_visible_inline_completion(window, cx);
3965 }
3966 }
3967 })?;
3968
3969 Ok::<_, anyhow::Error>(())
3970 }
3971 .log_err()
3972 });
3973
3974 self.completion_tasks.push((id, task));
3975 }
3976
3977 pub fn confirm_completion(
3978 &mut self,
3979 action: &ConfirmCompletion,
3980 window: &mut Window,
3981 cx: &mut Context<Self>,
3982 ) -> Option<Task<Result<()>>> {
3983 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3984 }
3985
3986 pub fn compose_completion(
3987 &mut self,
3988 action: &ComposeCompletion,
3989 window: &mut Window,
3990 cx: &mut Context<Self>,
3991 ) -> Option<Task<Result<()>>> {
3992 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3993 }
3994
3995 fn do_completion(
3996 &mut self,
3997 item_ix: Option<usize>,
3998 intent: CompletionIntent,
3999 window: &mut Window,
4000 cx: &mut Context<Editor>,
4001 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4002 use language::ToOffset as _;
4003
4004 let completions_menu =
4005 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4006 menu
4007 } else {
4008 return None;
4009 };
4010
4011 let entries = completions_menu.entries.borrow();
4012 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4013 if self.show_edit_predictions_in_menu() {
4014 self.discard_inline_completion(true, cx);
4015 }
4016 let candidate_id = mat.candidate_id;
4017 drop(entries);
4018
4019 let buffer_handle = completions_menu.buffer;
4020 let completion = completions_menu
4021 .completions
4022 .borrow()
4023 .get(candidate_id)?
4024 .clone();
4025 cx.stop_propagation();
4026
4027 let snippet;
4028 let text;
4029
4030 if completion.is_snippet() {
4031 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4032 text = snippet.as_ref().unwrap().text.clone();
4033 } else {
4034 snippet = None;
4035 text = completion.new_text.clone();
4036 };
4037 let selections = self.selections.all::<usize>(cx);
4038 let buffer = buffer_handle.read(cx);
4039 let old_range = completion.old_range.to_offset(buffer);
4040 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4041
4042 let newest_selection = self.selections.newest_anchor();
4043 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4044 return None;
4045 }
4046
4047 let lookbehind = newest_selection
4048 .start
4049 .text_anchor
4050 .to_offset(buffer)
4051 .saturating_sub(old_range.start);
4052 let lookahead = old_range
4053 .end
4054 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4055 let mut common_prefix_len = old_text
4056 .bytes()
4057 .zip(text.bytes())
4058 .take_while(|(a, b)| a == b)
4059 .count();
4060
4061 let snapshot = self.buffer.read(cx).snapshot(cx);
4062 let mut range_to_replace: Option<Range<isize>> = None;
4063 let mut ranges = Vec::new();
4064 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4065 for selection in &selections {
4066 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4067 let start = selection.start.saturating_sub(lookbehind);
4068 let end = selection.end + lookahead;
4069 if selection.id == newest_selection.id {
4070 range_to_replace = Some(
4071 ((start + common_prefix_len) as isize - selection.start as isize)
4072 ..(end as isize - selection.start as isize),
4073 );
4074 }
4075 ranges.push(start + common_prefix_len..end);
4076 } else {
4077 common_prefix_len = 0;
4078 ranges.clear();
4079 ranges.extend(selections.iter().map(|s| {
4080 if s.id == newest_selection.id {
4081 range_to_replace = Some(
4082 old_range.start.to_offset_utf16(&snapshot).0 as isize
4083 - selection.start as isize
4084 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4085 - selection.start as isize,
4086 );
4087 old_range.clone()
4088 } else {
4089 s.start..s.end
4090 }
4091 }));
4092 break;
4093 }
4094 if !self.linked_edit_ranges.is_empty() {
4095 let start_anchor = snapshot.anchor_before(selection.head());
4096 let end_anchor = snapshot.anchor_after(selection.tail());
4097 if let Some(ranges) = self
4098 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4099 {
4100 for (buffer, edits) in ranges {
4101 linked_edits.entry(buffer.clone()).or_default().extend(
4102 edits
4103 .into_iter()
4104 .map(|range| (range, text[common_prefix_len..].to_owned())),
4105 );
4106 }
4107 }
4108 }
4109 }
4110 let text = &text[common_prefix_len..];
4111
4112 cx.emit(EditorEvent::InputHandled {
4113 utf16_range_to_replace: range_to_replace,
4114 text: text.into(),
4115 });
4116
4117 self.transact(window, cx, |this, window, cx| {
4118 if let Some(mut snippet) = snippet {
4119 snippet.text = text.to_string();
4120 for tabstop in snippet
4121 .tabstops
4122 .iter_mut()
4123 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4124 {
4125 tabstop.start -= common_prefix_len as isize;
4126 tabstop.end -= common_prefix_len as isize;
4127 }
4128
4129 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4130 } else {
4131 this.buffer.update(cx, |buffer, cx| {
4132 buffer.edit(
4133 ranges.iter().map(|range| (range.clone(), text)),
4134 this.autoindent_mode.clone(),
4135 cx,
4136 );
4137 });
4138 }
4139 for (buffer, edits) in linked_edits {
4140 buffer.update(cx, |buffer, cx| {
4141 let snapshot = buffer.snapshot();
4142 let edits = edits
4143 .into_iter()
4144 .map(|(range, text)| {
4145 use text::ToPoint as TP;
4146 let end_point = TP::to_point(&range.end, &snapshot);
4147 let start_point = TP::to_point(&range.start, &snapshot);
4148 (start_point..end_point, text)
4149 })
4150 .sorted_by_key(|(range, _)| range.start)
4151 .collect::<Vec<_>>();
4152 buffer.edit(edits, None, cx);
4153 })
4154 }
4155
4156 this.refresh_inline_completion(true, false, window, cx);
4157 });
4158
4159 let show_new_completions_on_confirm = completion
4160 .confirm
4161 .as_ref()
4162 .map_or(false, |confirm| confirm(intent, window, cx));
4163 if show_new_completions_on_confirm {
4164 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4165 }
4166
4167 let provider = self.completion_provider.as_ref()?;
4168 drop(completion);
4169 let apply_edits = provider.apply_additional_edits_for_completion(
4170 buffer_handle,
4171 completions_menu.completions.clone(),
4172 candidate_id,
4173 true,
4174 cx,
4175 );
4176
4177 let editor_settings = EditorSettings::get_global(cx);
4178 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4179 // After the code completion is finished, users often want to know what signatures are needed.
4180 // so we should automatically call signature_help
4181 self.show_signature_help(&ShowSignatureHelp, window, cx);
4182 }
4183
4184 Some(cx.foreground_executor().spawn(async move {
4185 apply_edits.await?;
4186 Ok(())
4187 }))
4188 }
4189
4190 pub fn toggle_code_actions(
4191 &mut self,
4192 action: &ToggleCodeActions,
4193 window: &mut Window,
4194 cx: &mut Context<Self>,
4195 ) {
4196 let mut context_menu = self.context_menu.borrow_mut();
4197 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4198 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4199 // Toggle if we're selecting the same one
4200 *context_menu = None;
4201 cx.notify();
4202 return;
4203 } else {
4204 // Otherwise, clear it and start a new one
4205 *context_menu = None;
4206 cx.notify();
4207 }
4208 }
4209 drop(context_menu);
4210 let snapshot = self.snapshot(window, cx);
4211 let deployed_from_indicator = action.deployed_from_indicator;
4212 let mut task = self.code_actions_task.take();
4213 let action = action.clone();
4214 cx.spawn_in(window, |editor, mut cx| async move {
4215 while let Some(prev_task) = task {
4216 prev_task.await.log_err();
4217 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4218 }
4219
4220 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4221 if editor.focus_handle.is_focused(window) {
4222 let multibuffer_point = action
4223 .deployed_from_indicator
4224 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4225 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4226 let (buffer, buffer_row) = snapshot
4227 .buffer_snapshot
4228 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4229 .and_then(|(buffer_snapshot, range)| {
4230 editor
4231 .buffer
4232 .read(cx)
4233 .buffer(buffer_snapshot.remote_id())
4234 .map(|buffer| (buffer, range.start.row))
4235 })?;
4236 let (_, code_actions) = editor
4237 .available_code_actions
4238 .clone()
4239 .and_then(|(location, code_actions)| {
4240 let snapshot = location.buffer.read(cx).snapshot();
4241 let point_range = location.range.to_point(&snapshot);
4242 let point_range = point_range.start.row..=point_range.end.row;
4243 if point_range.contains(&buffer_row) {
4244 Some((location, code_actions))
4245 } else {
4246 None
4247 }
4248 })
4249 .unzip();
4250 let buffer_id = buffer.read(cx).remote_id();
4251 let tasks = editor
4252 .tasks
4253 .get(&(buffer_id, buffer_row))
4254 .map(|t| Arc::new(t.to_owned()));
4255 if tasks.is_none() && code_actions.is_none() {
4256 return None;
4257 }
4258
4259 editor.completion_tasks.clear();
4260 editor.discard_inline_completion(false, cx);
4261 let task_context =
4262 tasks
4263 .as_ref()
4264 .zip(editor.project.clone())
4265 .map(|(tasks, project)| {
4266 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4267 });
4268
4269 Some(cx.spawn_in(window, |editor, mut cx| async move {
4270 let task_context = match task_context {
4271 Some(task_context) => task_context.await,
4272 None => None,
4273 };
4274 let resolved_tasks =
4275 tasks.zip(task_context).map(|(tasks, task_context)| {
4276 Rc::new(ResolvedTasks {
4277 templates: tasks.resolve(&task_context).collect(),
4278 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4279 multibuffer_point.row,
4280 tasks.column,
4281 )),
4282 })
4283 });
4284 let spawn_straight_away = resolved_tasks
4285 .as_ref()
4286 .map_or(false, |tasks| tasks.templates.len() == 1)
4287 && code_actions
4288 .as_ref()
4289 .map_or(true, |actions| actions.is_empty());
4290 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4291 *editor.context_menu.borrow_mut() =
4292 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4293 buffer,
4294 actions: CodeActionContents {
4295 tasks: resolved_tasks,
4296 actions: code_actions,
4297 },
4298 selected_item: Default::default(),
4299 scroll_handle: UniformListScrollHandle::default(),
4300 deployed_from_indicator,
4301 }));
4302 if spawn_straight_away {
4303 if let Some(task) = editor.confirm_code_action(
4304 &ConfirmCodeAction { item_ix: Some(0) },
4305 window,
4306 cx,
4307 ) {
4308 cx.notify();
4309 return task;
4310 }
4311 }
4312 cx.notify();
4313 Task::ready(Ok(()))
4314 }) {
4315 task.await
4316 } else {
4317 Ok(())
4318 }
4319 }))
4320 } else {
4321 Some(Task::ready(Ok(())))
4322 }
4323 })?;
4324 if let Some(task) = spawned_test_task {
4325 task.await?;
4326 }
4327
4328 Ok::<_, anyhow::Error>(())
4329 })
4330 .detach_and_log_err(cx);
4331 }
4332
4333 pub fn confirm_code_action(
4334 &mut self,
4335 action: &ConfirmCodeAction,
4336 window: &mut Window,
4337 cx: &mut Context<Self>,
4338 ) -> Option<Task<Result<()>>> {
4339 let actions_menu =
4340 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4341 menu
4342 } else {
4343 return None;
4344 };
4345 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4346 let action = actions_menu.actions.get(action_ix)?;
4347 let title = action.label();
4348 let buffer = actions_menu.buffer;
4349 let workspace = self.workspace()?;
4350
4351 match action {
4352 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4353 workspace.update(cx, |workspace, cx| {
4354 workspace::tasks::schedule_resolved_task(
4355 workspace,
4356 task_source_kind,
4357 resolved_task,
4358 false,
4359 cx,
4360 );
4361
4362 Some(Task::ready(Ok(())))
4363 })
4364 }
4365 CodeActionsItem::CodeAction {
4366 excerpt_id,
4367 action,
4368 provider,
4369 } => {
4370 let apply_code_action =
4371 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4372 let workspace = workspace.downgrade();
4373 Some(cx.spawn_in(window, |editor, cx| async move {
4374 let project_transaction = apply_code_action.await?;
4375 Self::open_project_transaction(
4376 &editor,
4377 workspace,
4378 project_transaction,
4379 title,
4380 cx,
4381 )
4382 .await
4383 }))
4384 }
4385 }
4386 }
4387
4388 pub async fn open_project_transaction(
4389 this: &WeakEntity<Editor>,
4390 workspace: WeakEntity<Workspace>,
4391 transaction: ProjectTransaction,
4392 title: String,
4393 mut cx: AsyncWindowContext,
4394 ) -> Result<()> {
4395 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4396 cx.update(|_, cx| {
4397 entries.sort_unstable_by_key(|(buffer, _)| {
4398 buffer.read(cx).file().map(|f| f.path().clone())
4399 });
4400 })?;
4401
4402 // If the project transaction's edits are all contained within this editor, then
4403 // avoid opening a new editor to display them.
4404
4405 if let Some((buffer, transaction)) = entries.first() {
4406 if entries.len() == 1 {
4407 let excerpt = this.update(&mut cx, |editor, cx| {
4408 editor
4409 .buffer()
4410 .read(cx)
4411 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4412 })?;
4413 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4414 if excerpted_buffer == *buffer {
4415 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4416 let excerpt_range = excerpt_range.to_offset(buffer);
4417 buffer
4418 .edited_ranges_for_transaction::<usize>(transaction)
4419 .all(|range| {
4420 excerpt_range.start <= range.start
4421 && excerpt_range.end >= range.end
4422 })
4423 })?;
4424
4425 if all_edits_within_excerpt {
4426 return Ok(());
4427 }
4428 }
4429 }
4430 }
4431 } else {
4432 return Ok(());
4433 }
4434
4435 let mut ranges_to_highlight = Vec::new();
4436 let excerpt_buffer = cx.new(|cx| {
4437 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4438 for (buffer_handle, transaction) in &entries {
4439 let buffer = buffer_handle.read(cx);
4440 ranges_to_highlight.extend(
4441 multibuffer.push_excerpts_with_context_lines(
4442 buffer_handle.clone(),
4443 buffer
4444 .edited_ranges_for_transaction::<usize>(transaction)
4445 .collect(),
4446 DEFAULT_MULTIBUFFER_CONTEXT,
4447 cx,
4448 ),
4449 );
4450 }
4451 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4452 multibuffer
4453 })?;
4454
4455 workspace.update_in(&mut cx, |workspace, window, cx| {
4456 let project = workspace.project().clone();
4457 let editor = cx
4458 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4459 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4460 editor.update(cx, |editor, cx| {
4461 editor.highlight_background::<Self>(
4462 &ranges_to_highlight,
4463 |theme| theme.editor_highlighted_line_background,
4464 cx,
4465 );
4466 });
4467 })?;
4468
4469 Ok(())
4470 }
4471
4472 pub fn clear_code_action_providers(&mut self) {
4473 self.code_action_providers.clear();
4474 self.available_code_actions.take();
4475 }
4476
4477 pub fn add_code_action_provider(
4478 &mut self,
4479 provider: Rc<dyn CodeActionProvider>,
4480 window: &mut Window,
4481 cx: &mut Context<Self>,
4482 ) {
4483 if self
4484 .code_action_providers
4485 .iter()
4486 .any(|existing_provider| existing_provider.id() == provider.id())
4487 {
4488 return;
4489 }
4490
4491 self.code_action_providers.push(provider);
4492 self.refresh_code_actions(window, cx);
4493 }
4494
4495 pub fn remove_code_action_provider(
4496 &mut self,
4497 id: Arc<str>,
4498 window: &mut Window,
4499 cx: &mut Context<Self>,
4500 ) {
4501 self.code_action_providers
4502 .retain(|provider| provider.id() != id);
4503 self.refresh_code_actions(window, cx);
4504 }
4505
4506 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4507 let buffer = self.buffer.read(cx);
4508 let newest_selection = self.selections.newest_anchor().clone();
4509 if newest_selection.head().diff_base_anchor.is_some() {
4510 return None;
4511 }
4512 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4513 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4514 if start_buffer != end_buffer {
4515 return None;
4516 }
4517
4518 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4519 cx.background_executor()
4520 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4521 .await;
4522
4523 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4524 let providers = this.code_action_providers.clone();
4525 let tasks = this
4526 .code_action_providers
4527 .iter()
4528 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4529 .collect::<Vec<_>>();
4530 (providers, tasks)
4531 })?;
4532
4533 let mut actions = Vec::new();
4534 for (provider, provider_actions) in
4535 providers.into_iter().zip(future::join_all(tasks).await)
4536 {
4537 if let Some(provider_actions) = provider_actions.log_err() {
4538 actions.extend(provider_actions.into_iter().map(|action| {
4539 AvailableCodeAction {
4540 excerpt_id: newest_selection.start.excerpt_id,
4541 action,
4542 provider: provider.clone(),
4543 }
4544 }));
4545 }
4546 }
4547
4548 this.update(&mut cx, |this, cx| {
4549 this.available_code_actions = if actions.is_empty() {
4550 None
4551 } else {
4552 Some((
4553 Location {
4554 buffer: start_buffer,
4555 range: start..end,
4556 },
4557 actions.into(),
4558 ))
4559 };
4560 cx.notify();
4561 })
4562 }));
4563 None
4564 }
4565
4566 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4567 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4568 self.show_git_blame_inline = false;
4569
4570 self.show_git_blame_inline_delay_task =
4571 Some(cx.spawn_in(window, |this, mut cx| async move {
4572 cx.background_executor().timer(delay).await;
4573
4574 this.update(&mut cx, |this, cx| {
4575 this.show_git_blame_inline = true;
4576 cx.notify();
4577 })
4578 .log_err();
4579 }));
4580 }
4581 }
4582
4583 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4584 if self.pending_rename.is_some() {
4585 return None;
4586 }
4587
4588 let provider = self.semantics_provider.clone()?;
4589 let buffer = self.buffer.read(cx);
4590 let newest_selection = self.selections.newest_anchor().clone();
4591 let cursor_position = newest_selection.head();
4592 let (cursor_buffer, cursor_buffer_position) =
4593 buffer.text_anchor_for_position(cursor_position, cx)?;
4594 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4595 if cursor_buffer != tail_buffer {
4596 return None;
4597 }
4598 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4599 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4600 cx.background_executor()
4601 .timer(Duration::from_millis(debounce))
4602 .await;
4603
4604 let highlights = if let Some(highlights) = cx
4605 .update(|cx| {
4606 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4607 })
4608 .ok()
4609 .flatten()
4610 {
4611 highlights.await.log_err()
4612 } else {
4613 None
4614 };
4615
4616 if let Some(highlights) = highlights {
4617 this.update(&mut cx, |this, cx| {
4618 if this.pending_rename.is_some() {
4619 return;
4620 }
4621
4622 let buffer_id = cursor_position.buffer_id;
4623 let buffer = this.buffer.read(cx);
4624 if !buffer
4625 .text_anchor_for_position(cursor_position, cx)
4626 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4627 {
4628 return;
4629 }
4630
4631 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4632 let mut write_ranges = Vec::new();
4633 let mut read_ranges = Vec::new();
4634 for highlight in highlights {
4635 for (excerpt_id, excerpt_range) in
4636 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4637 {
4638 let start = highlight
4639 .range
4640 .start
4641 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4642 let end = highlight
4643 .range
4644 .end
4645 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4646 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4647 continue;
4648 }
4649
4650 let range = Anchor {
4651 buffer_id,
4652 excerpt_id,
4653 text_anchor: start,
4654 diff_base_anchor: None,
4655 }..Anchor {
4656 buffer_id,
4657 excerpt_id,
4658 text_anchor: end,
4659 diff_base_anchor: None,
4660 };
4661 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4662 write_ranges.push(range);
4663 } else {
4664 read_ranges.push(range);
4665 }
4666 }
4667 }
4668
4669 this.highlight_background::<DocumentHighlightRead>(
4670 &read_ranges,
4671 |theme| theme.editor_document_highlight_read_background,
4672 cx,
4673 );
4674 this.highlight_background::<DocumentHighlightWrite>(
4675 &write_ranges,
4676 |theme| theme.editor_document_highlight_write_background,
4677 cx,
4678 );
4679 cx.notify();
4680 })
4681 .log_err();
4682 }
4683 }));
4684 None
4685 }
4686
4687 pub fn refresh_selected_text_highlights(
4688 &mut self,
4689 window: &mut Window,
4690 cx: &mut Context<Editor>,
4691 ) {
4692 self.selection_highlight_task.take();
4693 if !EditorSettings::get_global(cx).selection_highlight {
4694 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4695 return;
4696 }
4697 if self.selections.count() != 1 || self.selections.line_mode {
4698 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4699 return;
4700 }
4701 let selection = self.selections.newest::<Point>(cx);
4702 if selection.is_empty() || selection.start.row != selection.end.row {
4703 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4704 return;
4705 }
4706 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4707 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4708 cx.background_executor()
4709 .timer(Duration::from_millis(debounce))
4710 .await;
4711 let Some(Some(matches_task)) = editor
4712 .update_in(&mut cx, |editor, _, cx| {
4713 if editor.selections.count() != 1 || editor.selections.line_mode {
4714 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4715 return None;
4716 }
4717 let selection = editor.selections.newest::<Point>(cx);
4718 if selection.is_empty() || selection.start.row != selection.end.row {
4719 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4720 return None;
4721 }
4722 let buffer = editor.buffer().read(cx).snapshot(cx);
4723 let query = buffer.text_for_range(selection.range()).collect::<String>();
4724 if query.trim().is_empty() {
4725 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4726 return None;
4727 }
4728 Some(cx.background_spawn(async move {
4729 let mut ranges = Vec::new();
4730 let selection_anchors = selection.range().to_anchors(&buffer);
4731 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4732 for (search_buffer, search_range, excerpt_id) in
4733 buffer.range_to_buffer_ranges(range)
4734 {
4735 ranges.extend(
4736 project::search::SearchQuery::text(
4737 query.clone(),
4738 false,
4739 false,
4740 false,
4741 Default::default(),
4742 Default::default(),
4743 None,
4744 )
4745 .unwrap()
4746 .search(search_buffer, Some(search_range.clone()))
4747 .await
4748 .into_iter()
4749 .filter_map(
4750 |match_range| {
4751 let start = search_buffer.anchor_after(
4752 search_range.start + match_range.start,
4753 );
4754 let end = search_buffer.anchor_before(
4755 search_range.start + match_range.end,
4756 );
4757 let range = Anchor::range_in_buffer(
4758 excerpt_id,
4759 search_buffer.remote_id(),
4760 start..end,
4761 );
4762 (range != selection_anchors).then_some(range)
4763 },
4764 ),
4765 );
4766 }
4767 }
4768 ranges
4769 }))
4770 })
4771 .log_err()
4772 else {
4773 return;
4774 };
4775 let matches = matches_task.await;
4776 editor
4777 .update_in(&mut cx, |editor, _, cx| {
4778 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4779 if !matches.is_empty() {
4780 editor.highlight_background::<SelectedTextHighlight>(
4781 &matches,
4782 |theme| theme.editor_document_highlight_bracket_background,
4783 cx,
4784 )
4785 }
4786 })
4787 .log_err();
4788 }));
4789 }
4790
4791 pub fn refresh_inline_completion(
4792 &mut self,
4793 debounce: bool,
4794 user_requested: bool,
4795 window: &mut Window,
4796 cx: &mut Context<Self>,
4797 ) -> Option<()> {
4798 let provider = self.edit_prediction_provider()?;
4799 let cursor = self.selections.newest_anchor().head();
4800 let (buffer, cursor_buffer_position) =
4801 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4802
4803 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4804 self.discard_inline_completion(false, cx);
4805 return None;
4806 }
4807
4808 if !user_requested
4809 && (!self.should_show_edit_predictions()
4810 || !self.is_focused(window)
4811 || buffer.read(cx).is_empty())
4812 {
4813 self.discard_inline_completion(false, cx);
4814 return None;
4815 }
4816
4817 self.update_visible_inline_completion(window, cx);
4818 provider.refresh(
4819 self.project.clone(),
4820 buffer,
4821 cursor_buffer_position,
4822 debounce,
4823 cx,
4824 );
4825 Some(())
4826 }
4827
4828 fn show_edit_predictions_in_menu(&self) -> bool {
4829 match self.edit_prediction_settings {
4830 EditPredictionSettings::Disabled => false,
4831 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4832 }
4833 }
4834
4835 pub fn edit_predictions_enabled(&self) -> bool {
4836 match self.edit_prediction_settings {
4837 EditPredictionSettings::Disabled => false,
4838 EditPredictionSettings::Enabled { .. } => true,
4839 }
4840 }
4841
4842 fn edit_prediction_requires_modifier(&self) -> bool {
4843 match self.edit_prediction_settings {
4844 EditPredictionSettings::Disabled => false,
4845 EditPredictionSettings::Enabled {
4846 preview_requires_modifier,
4847 ..
4848 } => preview_requires_modifier,
4849 }
4850 }
4851
4852 fn edit_prediction_settings_at_position(
4853 &self,
4854 buffer: &Entity<Buffer>,
4855 buffer_position: language::Anchor,
4856 cx: &App,
4857 ) -> EditPredictionSettings {
4858 if self.mode != EditorMode::Full
4859 || !self.show_inline_completions_override.unwrap_or(true)
4860 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4861 {
4862 return EditPredictionSettings::Disabled;
4863 }
4864
4865 let buffer = buffer.read(cx);
4866
4867 let file = buffer.file();
4868
4869 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4870 return EditPredictionSettings::Disabled;
4871 };
4872
4873 let by_provider = matches!(
4874 self.menu_inline_completions_policy,
4875 MenuInlineCompletionsPolicy::ByProvider
4876 );
4877
4878 let show_in_menu = by_provider
4879 && self
4880 .edit_prediction_provider
4881 .as_ref()
4882 .map_or(false, |provider| {
4883 provider.provider.show_completions_in_menu()
4884 });
4885
4886 let preview_requires_modifier =
4887 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4888
4889 EditPredictionSettings::Enabled {
4890 show_in_menu,
4891 preview_requires_modifier,
4892 }
4893 }
4894
4895 fn should_show_edit_predictions(&self) -> bool {
4896 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4897 }
4898
4899 pub fn edit_prediction_preview_is_active(&self) -> bool {
4900 matches!(
4901 self.edit_prediction_preview,
4902 EditPredictionPreview::Active { .. }
4903 )
4904 }
4905
4906 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4907 let cursor = self.selections.newest_anchor().head();
4908 if let Some((buffer, cursor_position)) =
4909 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4910 {
4911 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4912 } else {
4913 false
4914 }
4915 }
4916
4917 fn inline_completions_enabled_in_buffer(
4918 &self,
4919 buffer: &Entity<Buffer>,
4920 buffer_position: language::Anchor,
4921 cx: &App,
4922 ) -> bool {
4923 maybe!({
4924 let provider = self.edit_prediction_provider()?;
4925 if !provider.is_enabled(&buffer, buffer_position, cx) {
4926 return Some(false);
4927 }
4928 let buffer = buffer.read(cx);
4929 let Some(file) = buffer.file() else {
4930 return Some(true);
4931 };
4932 let settings = all_language_settings(Some(file), cx);
4933 Some(settings.inline_completions_enabled_for_path(file.path()))
4934 })
4935 .unwrap_or(false)
4936 }
4937
4938 fn cycle_inline_completion(
4939 &mut self,
4940 direction: Direction,
4941 window: &mut Window,
4942 cx: &mut Context<Self>,
4943 ) -> Option<()> {
4944 let provider = self.edit_prediction_provider()?;
4945 let cursor = self.selections.newest_anchor().head();
4946 let (buffer, cursor_buffer_position) =
4947 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4948 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4949 return None;
4950 }
4951
4952 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4953 self.update_visible_inline_completion(window, cx);
4954
4955 Some(())
4956 }
4957
4958 pub fn show_inline_completion(
4959 &mut self,
4960 _: &ShowEditPrediction,
4961 window: &mut Window,
4962 cx: &mut Context<Self>,
4963 ) {
4964 if !self.has_active_inline_completion() {
4965 self.refresh_inline_completion(false, true, window, cx);
4966 return;
4967 }
4968
4969 self.update_visible_inline_completion(window, cx);
4970 }
4971
4972 pub fn display_cursor_names(
4973 &mut self,
4974 _: &DisplayCursorNames,
4975 window: &mut Window,
4976 cx: &mut Context<Self>,
4977 ) {
4978 self.show_cursor_names(window, cx);
4979 }
4980
4981 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4982 self.show_cursor_names = true;
4983 cx.notify();
4984 cx.spawn_in(window, |this, mut cx| async move {
4985 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4986 this.update(&mut cx, |this, cx| {
4987 this.show_cursor_names = false;
4988 cx.notify()
4989 })
4990 .ok()
4991 })
4992 .detach();
4993 }
4994
4995 pub fn next_edit_prediction(
4996 &mut self,
4997 _: &NextEditPrediction,
4998 window: &mut Window,
4999 cx: &mut Context<Self>,
5000 ) {
5001 if self.has_active_inline_completion() {
5002 self.cycle_inline_completion(Direction::Next, window, cx);
5003 } else {
5004 let is_copilot_disabled = self
5005 .refresh_inline_completion(false, true, window, cx)
5006 .is_none();
5007 if is_copilot_disabled {
5008 cx.propagate();
5009 }
5010 }
5011 }
5012
5013 pub fn previous_edit_prediction(
5014 &mut self,
5015 _: &PreviousEditPrediction,
5016 window: &mut Window,
5017 cx: &mut Context<Self>,
5018 ) {
5019 if self.has_active_inline_completion() {
5020 self.cycle_inline_completion(Direction::Prev, window, cx);
5021 } else {
5022 let is_copilot_disabled = self
5023 .refresh_inline_completion(false, true, window, cx)
5024 .is_none();
5025 if is_copilot_disabled {
5026 cx.propagate();
5027 }
5028 }
5029 }
5030
5031 pub fn accept_edit_prediction(
5032 &mut self,
5033 _: &AcceptEditPrediction,
5034 window: &mut Window,
5035 cx: &mut Context<Self>,
5036 ) {
5037 if self.show_edit_predictions_in_menu() {
5038 self.hide_context_menu(window, cx);
5039 }
5040
5041 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5042 return;
5043 };
5044
5045 self.report_inline_completion_event(
5046 active_inline_completion.completion_id.clone(),
5047 true,
5048 cx,
5049 );
5050
5051 match &active_inline_completion.completion {
5052 InlineCompletion::Move { target, .. } => {
5053 let target = *target;
5054
5055 if let Some(position_map) = &self.last_position_map {
5056 if position_map
5057 .visible_row_range
5058 .contains(&target.to_display_point(&position_map.snapshot).row())
5059 || !self.edit_prediction_requires_modifier()
5060 {
5061 self.unfold_ranges(&[target..target], true, false, cx);
5062 // Note that this is also done in vim's handler of the Tab action.
5063 self.change_selections(
5064 Some(Autoscroll::newest()),
5065 window,
5066 cx,
5067 |selections| {
5068 selections.select_anchor_ranges([target..target]);
5069 },
5070 );
5071 self.clear_row_highlights::<EditPredictionPreview>();
5072
5073 self.edit_prediction_preview = EditPredictionPreview::Active {
5074 previous_scroll_position: None,
5075 };
5076 } else {
5077 self.edit_prediction_preview = EditPredictionPreview::Active {
5078 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5079 };
5080 self.highlight_rows::<EditPredictionPreview>(
5081 target..target,
5082 cx.theme().colors().editor_highlighted_line_background,
5083 true,
5084 cx,
5085 );
5086 self.request_autoscroll(Autoscroll::fit(), cx);
5087 }
5088 }
5089 }
5090 InlineCompletion::Edit { edits, .. } => {
5091 if let Some(provider) = self.edit_prediction_provider() {
5092 provider.accept(cx);
5093 }
5094
5095 let snapshot = self.buffer.read(cx).snapshot(cx);
5096 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5097
5098 self.buffer.update(cx, |buffer, cx| {
5099 buffer.edit(edits.iter().cloned(), None, cx)
5100 });
5101
5102 self.change_selections(None, window, cx, |s| {
5103 s.select_anchor_ranges([last_edit_end..last_edit_end])
5104 });
5105
5106 self.update_visible_inline_completion(window, cx);
5107 if self.active_inline_completion.is_none() {
5108 self.refresh_inline_completion(true, true, window, cx);
5109 }
5110
5111 cx.notify();
5112 }
5113 }
5114
5115 self.edit_prediction_requires_modifier_in_leading_space = false;
5116 }
5117
5118 pub fn accept_partial_inline_completion(
5119 &mut self,
5120 _: &AcceptPartialEditPrediction,
5121 window: &mut Window,
5122 cx: &mut Context<Self>,
5123 ) {
5124 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5125 return;
5126 };
5127 if self.selections.count() != 1 {
5128 return;
5129 }
5130
5131 self.report_inline_completion_event(
5132 active_inline_completion.completion_id.clone(),
5133 true,
5134 cx,
5135 );
5136
5137 match &active_inline_completion.completion {
5138 InlineCompletion::Move { target, .. } => {
5139 let target = *target;
5140 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5141 selections.select_anchor_ranges([target..target]);
5142 });
5143 }
5144 InlineCompletion::Edit { edits, .. } => {
5145 // Find an insertion that starts at the cursor position.
5146 let snapshot = self.buffer.read(cx).snapshot(cx);
5147 let cursor_offset = self.selections.newest::<usize>(cx).head();
5148 let insertion = edits.iter().find_map(|(range, text)| {
5149 let range = range.to_offset(&snapshot);
5150 if range.is_empty() && range.start == cursor_offset {
5151 Some(text)
5152 } else {
5153 None
5154 }
5155 });
5156
5157 if let Some(text) = insertion {
5158 let mut partial_completion = text
5159 .chars()
5160 .by_ref()
5161 .take_while(|c| c.is_alphabetic())
5162 .collect::<String>();
5163 if partial_completion.is_empty() {
5164 partial_completion = text
5165 .chars()
5166 .by_ref()
5167 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5168 .collect::<String>();
5169 }
5170
5171 cx.emit(EditorEvent::InputHandled {
5172 utf16_range_to_replace: None,
5173 text: partial_completion.clone().into(),
5174 });
5175
5176 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5177
5178 self.refresh_inline_completion(true, true, window, cx);
5179 cx.notify();
5180 } else {
5181 self.accept_edit_prediction(&Default::default(), window, cx);
5182 }
5183 }
5184 }
5185 }
5186
5187 fn discard_inline_completion(
5188 &mut self,
5189 should_report_inline_completion_event: bool,
5190 cx: &mut Context<Self>,
5191 ) -> bool {
5192 if should_report_inline_completion_event {
5193 let completion_id = self
5194 .active_inline_completion
5195 .as_ref()
5196 .and_then(|active_completion| active_completion.completion_id.clone());
5197
5198 self.report_inline_completion_event(completion_id, false, cx);
5199 }
5200
5201 if let Some(provider) = self.edit_prediction_provider() {
5202 provider.discard(cx);
5203 }
5204
5205 self.take_active_inline_completion(cx)
5206 }
5207
5208 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5209 let Some(provider) = self.edit_prediction_provider() else {
5210 return;
5211 };
5212
5213 let Some((_, buffer, _)) = self
5214 .buffer
5215 .read(cx)
5216 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5217 else {
5218 return;
5219 };
5220
5221 let extension = buffer
5222 .read(cx)
5223 .file()
5224 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5225
5226 let event_type = match accepted {
5227 true => "Edit Prediction Accepted",
5228 false => "Edit Prediction Discarded",
5229 };
5230 telemetry::event!(
5231 event_type,
5232 provider = provider.name(),
5233 prediction_id = id,
5234 suggestion_accepted = accepted,
5235 file_extension = extension,
5236 );
5237 }
5238
5239 pub fn has_active_inline_completion(&self) -> bool {
5240 self.active_inline_completion.is_some()
5241 }
5242
5243 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5244 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5245 return false;
5246 };
5247
5248 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5249 self.clear_highlights::<InlineCompletionHighlight>(cx);
5250 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5251 true
5252 }
5253
5254 /// Returns true when we're displaying the edit prediction popover below the cursor
5255 /// like we are not previewing and the LSP autocomplete menu is visible
5256 /// or we are in `when_holding_modifier` mode.
5257 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5258 if self.edit_prediction_preview_is_active()
5259 || !self.show_edit_predictions_in_menu()
5260 || !self.edit_predictions_enabled()
5261 {
5262 return false;
5263 }
5264
5265 if self.has_visible_completions_menu() {
5266 return true;
5267 }
5268
5269 has_completion && self.edit_prediction_requires_modifier()
5270 }
5271
5272 fn handle_modifiers_changed(
5273 &mut self,
5274 modifiers: Modifiers,
5275 position_map: &PositionMap,
5276 window: &mut Window,
5277 cx: &mut Context<Self>,
5278 ) {
5279 if self.show_edit_predictions_in_menu() {
5280 self.update_edit_prediction_preview(&modifiers, window, cx);
5281 }
5282
5283 self.update_selection_mode(&modifiers, position_map, window, cx);
5284
5285 let mouse_position = window.mouse_position();
5286 if !position_map.text_hitbox.is_hovered(window) {
5287 return;
5288 }
5289
5290 self.update_hovered_link(
5291 position_map.point_for_position(mouse_position),
5292 &position_map.snapshot,
5293 modifiers,
5294 window,
5295 cx,
5296 )
5297 }
5298
5299 fn update_selection_mode(
5300 &mut self,
5301 modifiers: &Modifiers,
5302 position_map: &PositionMap,
5303 window: &mut Window,
5304 cx: &mut Context<Self>,
5305 ) {
5306 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5307 return;
5308 }
5309
5310 let mouse_position = window.mouse_position();
5311 let point_for_position = position_map.point_for_position(mouse_position);
5312 let position = point_for_position.previous_valid;
5313
5314 self.select(
5315 SelectPhase::BeginColumnar {
5316 position,
5317 reset: false,
5318 goal_column: point_for_position.exact_unclipped.column(),
5319 },
5320 window,
5321 cx,
5322 );
5323 }
5324
5325 fn update_edit_prediction_preview(
5326 &mut self,
5327 modifiers: &Modifiers,
5328 window: &mut Window,
5329 cx: &mut Context<Self>,
5330 ) {
5331 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5332 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5333 return;
5334 };
5335
5336 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5337 if matches!(
5338 self.edit_prediction_preview,
5339 EditPredictionPreview::Inactive
5340 ) {
5341 self.edit_prediction_preview = EditPredictionPreview::Active {
5342 previous_scroll_position: None,
5343 };
5344
5345 self.update_visible_inline_completion(window, cx);
5346 cx.notify();
5347 }
5348 } else if let EditPredictionPreview::Active {
5349 previous_scroll_position,
5350 } = self.edit_prediction_preview
5351 {
5352 if let (Some(previous_scroll_position), Some(position_map)) =
5353 (previous_scroll_position, self.last_position_map.as_ref())
5354 {
5355 self.set_scroll_position(
5356 previous_scroll_position
5357 .scroll_position(&position_map.snapshot.display_snapshot),
5358 window,
5359 cx,
5360 );
5361 }
5362
5363 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5364 self.clear_row_highlights::<EditPredictionPreview>();
5365 self.update_visible_inline_completion(window, cx);
5366 cx.notify();
5367 }
5368 }
5369
5370 fn update_visible_inline_completion(
5371 &mut self,
5372 _window: &mut Window,
5373 cx: &mut Context<Self>,
5374 ) -> Option<()> {
5375 let selection = self.selections.newest_anchor();
5376 let cursor = selection.head();
5377 let multibuffer = self.buffer.read(cx).snapshot(cx);
5378 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5379 let excerpt_id = cursor.excerpt_id;
5380
5381 let show_in_menu = self.show_edit_predictions_in_menu();
5382 let completions_menu_has_precedence = !show_in_menu
5383 && (self.context_menu.borrow().is_some()
5384 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5385
5386 if completions_menu_has_precedence
5387 || !offset_selection.is_empty()
5388 || self
5389 .active_inline_completion
5390 .as_ref()
5391 .map_or(false, |completion| {
5392 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5393 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5394 !invalidation_range.contains(&offset_selection.head())
5395 })
5396 {
5397 self.discard_inline_completion(false, cx);
5398 return None;
5399 }
5400
5401 self.take_active_inline_completion(cx);
5402 let Some(provider) = self.edit_prediction_provider() else {
5403 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5404 return None;
5405 };
5406
5407 let (buffer, cursor_buffer_position) =
5408 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5409
5410 self.edit_prediction_settings =
5411 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5412
5413 self.edit_prediction_cursor_on_leading_whitespace =
5414 multibuffer.is_line_whitespace_upto(cursor);
5415
5416 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5417 let edits = inline_completion
5418 .edits
5419 .into_iter()
5420 .flat_map(|(range, new_text)| {
5421 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5422 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5423 Some((start..end, new_text))
5424 })
5425 .collect::<Vec<_>>();
5426 if edits.is_empty() {
5427 return None;
5428 }
5429
5430 let first_edit_start = edits.first().unwrap().0.start;
5431 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5432 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5433
5434 let last_edit_end = edits.last().unwrap().0.end;
5435 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5436 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5437
5438 let cursor_row = cursor.to_point(&multibuffer).row;
5439
5440 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5441
5442 let mut inlay_ids = Vec::new();
5443 let invalidation_row_range;
5444 let move_invalidation_row_range = if cursor_row < edit_start_row {
5445 Some(cursor_row..edit_end_row)
5446 } else if cursor_row > edit_end_row {
5447 Some(edit_start_row..cursor_row)
5448 } else {
5449 None
5450 };
5451 let is_move =
5452 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5453 let completion = if is_move {
5454 invalidation_row_range =
5455 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5456 let target = first_edit_start;
5457 InlineCompletion::Move { target, snapshot }
5458 } else {
5459 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5460 && !self.inline_completions_hidden_for_vim_mode;
5461
5462 if show_completions_in_buffer {
5463 if edits
5464 .iter()
5465 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5466 {
5467 let mut inlays = Vec::new();
5468 for (range, new_text) in &edits {
5469 let inlay = Inlay::inline_completion(
5470 post_inc(&mut self.next_inlay_id),
5471 range.start,
5472 new_text.as_str(),
5473 );
5474 inlay_ids.push(inlay.id);
5475 inlays.push(inlay);
5476 }
5477
5478 self.splice_inlays(&[], inlays, cx);
5479 } else {
5480 let background_color = cx.theme().status().deleted_background;
5481 self.highlight_text::<InlineCompletionHighlight>(
5482 edits.iter().map(|(range, _)| range.clone()).collect(),
5483 HighlightStyle {
5484 background_color: Some(background_color),
5485 ..Default::default()
5486 },
5487 cx,
5488 );
5489 }
5490 }
5491
5492 invalidation_row_range = edit_start_row..edit_end_row;
5493
5494 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5495 if provider.show_tab_accept_marker() {
5496 EditDisplayMode::TabAccept
5497 } else {
5498 EditDisplayMode::Inline
5499 }
5500 } else {
5501 EditDisplayMode::DiffPopover
5502 };
5503
5504 InlineCompletion::Edit {
5505 edits,
5506 edit_preview: inline_completion.edit_preview,
5507 display_mode,
5508 snapshot,
5509 }
5510 };
5511
5512 let invalidation_range = multibuffer
5513 .anchor_before(Point::new(invalidation_row_range.start, 0))
5514 ..multibuffer.anchor_after(Point::new(
5515 invalidation_row_range.end,
5516 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5517 ));
5518
5519 self.stale_inline_completion_in_menu = None;
5520 self.active_inline_completion = Some(InlineCompletionState {
5521 inlay_ids,
5522 completion,
5523 completion_id: inline_completion.id,
5524 invalidation_range,
5525 });
5526
5527 cx.notify();
5528
5529 Some(())
5530 }
5531
5532 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5533 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5534 }
5535
5536 fn render_code_actions_indicator(
5537 &self,
5538 _style: &EditorStyle,
5539 row: DisplayRow,
5540 is_active: bool,
5541 cx: &mut Context<Self>,
5542 ) -> Option<IconButton> {
5543 if self.available_code_actions.is_some() {
5544 Some(
5545 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5546 .shape(ui::IconButtonShape::Square)
5547 .icon_size(IconSize::XSmall)
5548 .icon_color(Color::Muted)
5549 .toggle_state(is_active)
5550 .tooltip({
5551 let focus_handle = self.focus_handle.clone();
5552 move |window, cx| {
5553 Tooltip::for_action_in(
5554 "Toggle Code Actions",
5555 &ToggleCodeActions {
5556 deployed_from_indicator: None,
5557 },
5558 &focus_handle,
5559 window,
5560 cx,
5561 )
5562 }
5563 })
5564 .on_click(cx.listener(move |editor, _e, window, cx| {
5565 window.focus(&editor.focus_handle(cx));
5566 editor.toggle_code_actions(
5567 &ToggleCodeActions {
5568 deployed_from_indicator: Some(row),
5569 },
5570 window,
5571 cx,
5572 );
5573 })),
5574 )
5575 } else {
5576 None
5577 }
5578 }
5579
5580 fn clear_tasks(&mut self) {
5581 self.tasks.clear()
5582 }
5583
5584 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5585 if self.tasks.insert(key, value).is_some() {
5586 // This case should hopefully be rare, but just in case...
5587 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5588 }
5589 }
5590
5591 fn build_tasks_context(
5592 project: &Entity<Project>,
5593 buffer: &Entity<Buffer>,
5594 buffer_row: u32,
5595 tasks: &Arc<RunnableTasks>,
5596 cx: &mut Context<Self>,
5597 ) -> Task<Option<task::TaskContext>> {
5598 let position = Point::new(buffer_row, tasks.column);
5599 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5600 let location = Location {
5601 buffer: buffer.clone(),
5602 range: range_start..range_start,
5603 };
5604 // Fill in the environmental variables from the tree-sitter captures
5605 let mut captured_task_variables = TaskVariables::default();
5606 for (capture_name, value) in tasks.extra_variables.clone() {
5607 captured_task_variables.insert(
5608 task::VariableName::Custom(capture_name.into()),
5609 value.clone(),
5610 );
5611 }
5612 project.update(cx, |project, cx| {
5613 project.task_store().update(cx, |task_store, cx| {
5614 task_store.task_context_for_location(captured_task_variables, location, cx)
5615 })
5616 })
5617 }
5618
5619 pub fn spawn_nearest_task(
5620 &mut self,
5621 action: &SpawnNearestTask,
5622 window: &mut Window,
5623 cx: &mut Context<Self>,
5624 ) {
5625 let Some((workspace, _)) = self.workspace.clone() else {
5626 return;
5627 };
5628 let Some(project) = self.project.clone() else {
5629 return;
5630 };
5631
5632 // Try to find a closest, enclosing node using tree-sitter that has a
5633 // task
5634 let Some((buffer, buffer_row, tasks)) = self
5635 .find_enclosing_node_task(cx)
5636 // Or find the task that's closest in row-distance.
5637 .or_else(|| self.find_closest_task(cx))
5638 else {
5639 return;
5640 };
5641
5642 let reveal_strategy = action.reveal;
5643 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5644 cx.spawn_in(window, |_, mut cx| async move {
5645 let context = task_context.await?;
5646 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5647
5648 let resolved = resolved_task.resolved.as_mut()?;
5649 resolved.reveal = reveal_strategy;
5650
5651 workspace
5652 .update(&mut cx, |workspace, cx| {
5653 workspace::tasks::schedule_resolved_task(
5654 workspace,
5655 task_source_kind,
5656 resolved_task,
5657 false,
5658 cx,
5659 );
5660 })
5661 .ok()
5662 })
5663 .detach();
5664 }
5665
5666 fn find_closest_task(
5667 &mut self,
5668 cx: &mut Context<Self>,
5669 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5670 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5671
5672 let ((buffer_id, row), tasks) = self
5673 .tasks
5674 .iter()
5675 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5676
5677 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5678 let tasks = Arc::new(tasks.to_owned());
5679 Some((buffer, *row, tasks))
5680 }
5681
5682 fn find_enclosing_node_task(
5683 &mut self,
5684 cx: &mut Context<Self>,
5685 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5686 let snapshot = self.buffer.read(cx).snapshot(cx);
5687 let offset = self.selections.newest::<usize>(cx).head();
5688 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5689 let buffer_id = excerpt.buffer().remote_id();
5690
5691 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5692 let mut cursor = layer.node().walk();
5693
5694 while cursor.goto_first_child_for_byte(offset).is_some() {
5695 if cursor.node().end_byte() == offset {
5696 cursor.goto_next_sibling();
5697 }
5698 }
5699
5700 // Ascend to the smallest ancestor that contains the range and has a task.
5701 loop {
5702 let node = cursor.node();
5703 let node_range = node.byte_range();
5704 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5705
5706 // Check if this node contains our offset
5707 if node_range.start <= offset && node_range.end >= offset {
5708 // If it contains offset, check for task
5709 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5710 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5711 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5712 }
5713 }
5714
5715 if !cursor.goto_parent() {
5716 break;
5717 }
5718 }
5719 None
5720 }
5721
5722 fn render_run_indicator(
5723 &self,
5724 _style: &EditorStyle,
5725 is_active: bool,
5726 row: DisplayRow,
5727 cx: &mut Context<Self>,
5728 ) -> IconButton {
5729 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5730 .shape(ui::IconButtonShape::Square)
5731 .icon_size(IconSize::XSmall)
5732 .icon_color(Color::Muted)
5733 .toggle_state(is_active)
5734 .on_click(cx.listener(move |editor, _e, window, cx| {
5735 window.focus(&editor.focus_handle(cx));
5736 editor.toggle_code_actions(
5737 &ToggleCodeActions {
5738 deployed_from_indicator: Some(row),
5739 },
5740 window,
5741 cx,
5742 );
5743 }))
5744 }
5745
5746 pub fn context_menu_visible(&self) -> bool {
5747 !self.edit_prediction_preview_is_active()
5748 && self
5749 .context_menu
5750 .borrow()
5751 .as_ref()
5752 .map_or(false, |menu| menu.visible())
5753 }
5754
5755 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5756 self.context_menu
5757 .borrow()
5758 .as_ref()
5759 .map(|menu| menu.origin())
5760 }
5761
5762 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5763 px(30.)
5764 }
5765
5766 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5767 if self.read_only(cx) {
5768 cx.theme().players().read_only()
5769 } else {
5770 self.style.as_ref().unwrap().local_player
5771 }
5772 }
5773
5774 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5775 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5776 let accept_keystroke = accept_binding.keystroke()?;
5777
5778 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5779
5780 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5781 Color::Accent
5782 } else {
5783 Color::Muted
5784 };
5785
5786 h_flex()
5787 .px_0p5()
5788 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5789 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5790 .text_size(TextSize::XSmall.rems(cx))
5791 .child(h_flex().children(ui::render_modifiers(
5792 &accept_keystroke.modifiers,
5793 PlatformStyle::platform(),
5794 Some(modifiers_color),
5795 Some(IconSize::XSmall.rems().into()),
5796 true,
5797 )))
5798 .when(is_platform_style_mac, |parent| {
5799 parent.child(accept_keystroke.key.clone())
5800 })
5801 .when(!is_platform_style_mac, |parent| {
5802 parent.child(
5803 Key::new(
5804 util::capitalize(&accept_keystroke.key),
5805 Some(Color::Default),
5806 )
5807 .size(Some(IconSize::XSmall.rems().into())),
5808 )
5809 })
5810 .into()
5811 }
5812
5813 fn render_edit_prediction_line_popover(
5814 &self,
5815 label: impl Into<SharedString>,
5816 icon: Option<IconName>,
5817 window: &mut Window,
5818 cx: &App,
5819 ) -> Option<Div> {
5820 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5821
5822 let result = h_flex()
5823 .py_0p5()
5824 .pl_1()
5825 .pr(padding_right)
5826 .gap_1()
5827 .rounded(px(6.))
5828 .border_1()
5829 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5830 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5831 .shadow_sm()
5832 .children(self.render_edit_prediction_accept_keybind(window, cx))
5833 .child(Label::new(label).size(LabelSize::Small))
5834 .when_some(icon, |element, icon| {
5835 element.child(
5836 div()
5837 .mt(px(1.5))
5838 .child(Icon::new(icon).size(IconSize::Small)),
5839 )
5840 });
5841
5842 Some(result)
5843 }
5844
5845 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5846 let accent_color = cx.theme().colors().text_accent;
5847 let editor_bg_color = cx.theme().colors().editor_background;
5848 editor_bg_color.blend(accent_color.opacity(0.1))
5849 }
5850
5851 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5852 let accent_color = cx.theme().colors().text_accent;
5853 let editor_bg_color = cx.theme().colors().editor_background;
5854 editor_bg_color.blend(accent_color.opacity(0.6))
5855 }
5856
5857 #[allow(clippy::too_many_arguments)]
5858 fn render_edit_prediction_cursor_popover(
5859 &self,
5860 min_width: Pixels,
5861 max_width: Pixels,
5862 cursor_point: Point,
5863 style: &EditorStyle,
5864 accept_keystroke: Option<&gpui::Keystroke>,
5865 _window: &Window,
5866 cx: &mut Context<Editor>,
5867 ) -> Option<AnyElement> {
5868 let provider = self.edit_prediction_provider.as_ref()?;
5869
5870 if provider.provider.needs_terms_acceptance(cx) {
5871 return Some(
5872 h_flex()
5873 .min_w(min_width)
5874 .flex_1()
5875 .px_2()
5876 .py_1()
5877 .gap_3()
5878 .elevation_2(cx)
5879 .hover(|style| style.bg(cx.theme().colors().element_hover))
5880 .id("accept-terms")
5881 .cursor_pointer()
5882 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5883 .on_click(cx.listener(|this, _event, window, cx| {
5884 cx.stop_propagation();
5885 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5886 window.dispatch_action(
5887 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5888 cx,
5889 );
5890 }))
5891 .child(
5892 h_flex()
5893 .flex_1()
5894 .gap_2()
5895 .child(Icon::new(IconName::ZedPredict))
5896 .child(Label::new("Accept Terms of Service"))
5897 .child(div().w_full())
5898 .child(
5899 Icon::new(IconName::ArrowUpRight)
5900 .color(Color::Muted)
5901 .size(IconSize::Small),
5902 )
5903 .into_any_element(),
5904 )
5905 .into_any(),
5906 );
5907 }
5908
5909 let is_refreshing = provider.provider.is_refreshing(cx);
5910
5911 fn pending_completion_container() -> Div {
5912 h_flex()
5913 .h_full()
5914 .flex_1()
5915 .gap_2()
5916 .child(Icon::new(IconName::ZedPredict))
5917 }
5918
5919 let completion = match &self.active_inline_completion {
5920 Some(completion) => match &completion.completion {
5921 InlineCompletion::Move {
5922 target, snapshot, ..
5923 } if !self.has_visible_completions_menu() => {
5924 use text::ToPoint as _;
5925
5926 return Some(
5927 h_flex()
5928 .px_2()
5929 .py_1()
5930 .gap_2()
5931 .elevation_2(cx)
5932 .border_color(cx.theme().colors().border)
5933 .rounded(px(6.))
5934 .rounded_tl(px(0.))
5935 .child(
5936 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5937 Icon::new(IconName::ZedPredictDown)
5938 } else {
5939 Icon::new(IconName::ZedPredictUp)
5940 },
5941 )
5942 .child(Label::new("Hold").size(LabelSize::Small))
5943 .child(h_flex().children(ui::render_modifiers(
5944 &accept_keystroke?.modifiers,
5945 PlatformStyle::platform(),
5946 Some(Color::Default),
5947 Some(IconSize::Small.rems().into()),
5948 false,
5949 )))
5950 .into_any(),
5951 );
5952 }
5953 _ => self.render_edit_prediction_cursor_popover_preview(
5954 completion,
5955 cursor_point,
5956 style,
5957 cx,
5958 )?,
5959 },
5960
5961 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5962 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5963 stale_completion,
5964 cursor_point,
5965 style,
5966 cx,
5967 )?,
5968
5969 None => {
5970 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5971 }
5972 },
5973
5974 None => pending_completion_container().child(Label::new("No Prediction")),
5975 };
5976
5977 let completion = if is_refreshing {
5978 completion
5979 .with_animation(
5980 "loading-completion",
5981 Animation::new(Duration::from_secs(2))
5982 .repeat()
5983 .with_easing(pulsating_between(0.4, 0.8)),
5984 |label, delta| label.opacity(delta),
5985 )
5986 .into_any_element()
5987 } else {
5988 completion.into_any_element()
5989 };
5990
5991 let has_completion = self.active_inline_completion.is_some();
5992
5993 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5994 Some(
5995 h_flex()
5996 .min_w(min_width)
5997 .max_w(max_width)
5998 .flex_1()
5999 .elevation_2(cx)
6000 .border_color(cx.theme().colors().border)
6001 .child(
6002 div()
6003 .flex_1()
6004 .py_1()
6005 .px_2()
6006 .overflow_hidden()
6007 .child(completion),
6008 )
6009 .when_some(accept_keystroke, |el, accept_keystroke| {
6010 if !accept_keystroke.modifiers.modified() {
6011 return el;
6012 }
6013
6014 el.child(
6015 h_flex()
6016 .h_full()
6017 .border_l_1()
6018 .rounded_r_lg()
6019 .border_color(cx.theme().colors().border)
6020 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6021 .gap_1()
6022 .py_1()
6023 .px_2()
6024 .child(
6025 h_flex()
6026 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6027 .when(is_platform_style_mac, |parent| parent.gap_1())
6028 .child(h_flex().children(ui::render_modifiers(
6029 &accept_keystroke.modifiers,
6030 PlatformStyle::platform(),
6031 Some(if !has_completion {
6032 Color::Muted
6033 } else {
6034 Color::Default
6035 }),
6036 None,
6037 false,
6038 ))),
6039 )
6040 .child(Label::new("Preview").into_any_element())
6041 .opacity(if has_completion { 1.0 } else { 0.4 }),
6042 )
6043 })
6044 .into_any(),
6045 )
6046 }
6047
6048 fn render_edit_prediction_cursor_popover_preview(
6049 &self,
6050 completion: &InlineCompletionState,
6051 cursor_point: Point,
6052 style: &EditorStyle,
6053 cx: &mut Context<Editor>,
6054 ) -> Option<Div> {
6055 use text::ToPoint as _;
6056
6057 fn render_relative_row_jump(
6058 prefix: impl Into<String>,
6059 current_row: u32,
6060 target_row: u32,
6061 ) -> Div {
6062 let (row_diff, arrow) = if target_row < current_row {
6063 (current_row - target_row, IconName::ArrowUp)
6064 } else {
6065 (target_row - current_row, IconName::ArrowDown)
6066 };
6067
6068 h_flex()
6069 .child(
6070 Label::new(format!("{}{}", prefix.into(), row_diff))
6071 .color(Color::Muted)
6072 .size(LabelSize::Small),
6073 )
6074 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6075 }
6076
6077 match &completion.completion {
6078 InlineCompletion::Move {
6079 target, snapshot, ..
6080 } => Some(
6081 h_flex()
6082 .px_2()
6083 .gap_2()
6084 .flex_1()
6085 .child(
6086 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6087 Icon::new(IconName::ZedPredictDown)
6088 } else {
6089 Icon::new(IconName::ZedPredictUp)
6090 },
6091 )
6092 .child(Label::new("Jump to Edit")),
6093 ),
6094
6095 InlineCompletion::Edit {
6096 edits,
6097 edit_preview,
6098 snapshot,
6099 display_mode: _,
6100 } => {
6101 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6102
6103 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6104 &snapshot,
6105 &edits,
6106 edit_preview.as_ref()?,
6107 true,
6108 cx,
6109 )
6110 .first_line_preview();
6111
6112 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6113 .with_highlights(&style.text, highlighted_edits.highlights);
6114
6115 let preview = h_flex()
6116 .gap_1()
6117 .min_w_16()
6118 .child(styled_text)
6119 .when(has_more_lines, |parent| parent.child("…"));
6120
6121 let left = if first_edit_row != cursor_point.row {
6122 render_relative_row_jump("", cursor_point.row, first_edit_row)
6123 .into_any_element()
6124 } else {
6125 Icon::new(IconName::ZedPredict).into_any_element()
6126 };
6127
6128 Some(
6129 h_flex()
6130 .h_full()
6131 .flex_1()
6132 .gap_2()
6133 .pr_1()
6134 .overflow_x_hidden()
6135 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6136 .child(left)
6137 .child(preview),
6138 )
6139 }
6140 }
6141 }
6142
6143 fn render_context_menu(
6144 &self,
6145 style: &EditorStyle,
6146 max_height_in_lines: u32,
6147 y_flipped: bool,
6148 window: &mut Window,
6149 cx: &mut Context<Editor>,
6150 ) -> Option<AnyElement> {
6151 let menu = self.context_menu.borrow();
6152 let menu = menu.as_ref()?;
6153 if !menu.visible() {
6154 return None;
6155 };
6156 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6157 }
6158
6159 fn render_context_menu_aside(
6160 &mut self,
6161 max_size: Size<Pixels>,
6162 window: &mut Window,
6163 cx: &mut Context<Editor>,
6164 ) -> Option<AnyElement> {
6165 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6166 if menu.visible() {
6167 menu.render_aside(self, max_size, window, cx)
6168 } else {
6169 None
6170 }
6171 })
6172 }
6173
6174 fn hide_context_menu(
6175 &mut self,
6176 window: &mut Window,
6177 cx: &mut Context<Self>,
6178 ) -> Option<CodeContextMenu> {
6179 cx.notify();
6180 self.completion_tasks.clear();
6181 let context_menu = self.context_menu.borrow_mut().take();
6182 self.stale_inline_completion_in_menu.take();
6183 self.update_visible_inline_completion(window, cx);
6184 context_menu
6185 }
6186
6187 fn show_snippet_choices(
6188 &mut self,
6189 choices: &Vec<String>,
6190 selection: Range<Anchor>,
6191 cx: &mut Context<Self>,
6192 ) {
6193 if selection.start.buffer_id.is_none() {
6194 return;
6195 }
6196 let buffer_id = selection.start.buffer_id.unwrap();
6197 let buffer = self.buffer().read(cx).buffer(buffer_id);
6198 let id = post_inc(&mut self.next_completion_id);
6199
6200 if let Some(buffer) = buffer {
6201 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6202 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6203 ));
6204 }
6205 }
6206
6207 pub fn insert_snippet(
6208 &mut self,
6209 insertion_ranges: &[Range<usize>],
6210 snippet: Snippet,
6211 window: &mut Window,
6212 cx: &mut Context<Self>,
6213 ) -> Result<()> {
6214 struct Tabstop<T> {
6215 is_end_tabstop: bool,
6216 ranges: Vec<Range<T>>,
6217 choices: Option<Vec<String>>,
6218 }
6219
6220 let tabstops = self.buffer.update(cx, |buffer, cx| {
6221 let snippet_text: Arc<str> = snippet.text.clone().into();
6222 buffer.edit(
6223 insertion_ranges
6224 .iter()
6225 .cloned()
6226 .map(|range| (range, snippet_text.clone())),
6227 Some(AutoindentMode::EachLine),
6228 cx,
6229 );
6230
6231 let snapshot = &*buffer.read(cx);
6232 let snippet = &snippet;
6233 snippet
6234 .tabstops
6235 .iter()
6236 .map(|tabstop| {
6237 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6238 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6239 });
6240 let mut tabstop_ranges = tabstop
6241 .ranges
6242 .iter()
6243 .flat_map(|tabstop_range| {
6244 let mut delta = 0_isize;
6245 insertion_ranges.iter().map(move |insertion_range| {
6246 let insertion_start = insertion_range.start as isize + delta;
6247 delta +=
6248 snippet.text.len() as isize - insertion_range.len() as isize;
6249
6250 let start = ((insertion_start + tabstop_range.start) as usize)
6251 .min(snapshot.len());
6252 let end = ((insertion_start + tabstop_range.end) as usize)
6253 .min(snapshot.len());
6254 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6255 })
6256 })
6257 .collect::<Vec<_>>();
6258 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6259
6260 Tabstop {
6261 is_end_tabstop,
6262 ranges: tabstop_ranges,
6263 choices: tabstop.choices.clone(),
6264 }
6265 })
6266 .collect::<Vec<_>>()
6267 });
6268 if let Some(tabstop) = tabstops.first() {
6269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6270 s.select_ranges(tabstop.ranges.iter().cloned());
6271 });
6272
6273 if let Some(choices) = &tabstop.choices {
6274 if let Some(selection) = tabstop.ranges.first() {
6275 self.show_snippet_choices(choices, selection.clone(), cx)
6276 }
6277 }
6278
6279 // If we're already at the last tabstop and it's at the end of the snippet,
6280 // we're done, we don't need to keep the state around.
6281 if !tabstop.is_end_tabstop {
6282 let choices = tabstops
6283 .iter()
6284 .map(|tabstop| tabstop.choices.clone())
6285 .collect();
6286
6287 let ranges = tabstops
6288 .into_iter()
6289 .map(|tabstop| tabstop.ranges)
6290 .collect::<Vec<_>>();
6291
6292 self.snippet_stack.push(SnippetState {
6293 active_index: 0,
6294 ranges,
6295 choices,
6296 });
6297 }
6298
6299 // Check whether the just-entered snippet ends with an auto-closable bracket.
6300 if self.autoclose_regions.is_empty() {
6301 let snapshot = self.buffer.read(cx).snapshot(cx);
6302 for selection in &mut self.selections.all::<Point>(cx) {
6303 let selection_head = selection.head();
6304 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6305 continue;
6306 };
6307
6308 let mut bracket_pair = None;
6309 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6310 let prev_chars = snapshot
6311 .reversed_chars_at(selection_head)
6312 .collect::<String>();
6313 for (pair, enabled) in scope.brackets() {
6314 if enabled
6315 && pair.close
6316 && prev_chars.starts_with(pair.start.as_str())
6317 && next_chars.starts_with(pair.end.as_str())
6318 {
6319 bracket_pair = Some(pair.clone());
6320 break;
6321 }
6322 }
6323 if let Some(pair) = bracket_pair {
6324 let start = snapshot.anchor_after(selection_head);
6325 let end = snapshot.anchor_after(selection_head);
6326 self.autoclose_regions.push(AutocloseRegion {
6327 selection_id: selection.id,
6328 range: start..end,
6329 pair,
6330 });
6331 }
6332 }
6333 }
6334 }
6335 Ok(())
6336 }
6337
6338 pub fn move_to_next_snippet_tabstop(
6339 &mut self,
6340 window: &mut Window,
6341 cx: &mut Context<Self>,
6342 ) -> bool {
6343 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6344 }
6345
6346 pub fn move_to_prev_snippet_tabstop(
6347 &mut self,
6348 window: &mut Window,
6349 cx: &mut Context<Self>,
6350 ) -> bool {
6351 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6352 }
6353
6354 pub fn move_to_snippet_tabstop(
6355 &mut self,
6356 bias: Bias,
6357 window: &mut Window,
6358 cx: &mut Context<Self>,
6359 ) -> bool {
6360 if let Some(mut snippet) = self.snippet_stack.pop() {
6361 match bias {
6362 Bias::Left => {
6363 if snippet.active_index > 0 {
6364 snippet.active_index -= 1;
6365 } else {
6366 self.snippet_stack.push(snippet);
6367 return false;
6368 }
6369 }
6370 Bias::Right => {
6371 if snippet.active_index + 1 < snippet.ranges.len() {
6372 snippet.active_index += 1;
6373 } else {
6374 self.snippet_stack.push(snippet);
6375 return false;
6376 }
6377 }
6378 }
6379 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6380 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6381 s.select_anchor_ranges(current_ranges.iter().cloned())
6382 });
6383
6384 if let Some(choices) = &snippet.choices[snippet.active_index] {
6385 if let Some(selection) = current_ranges.first() {
6386 self.show_snippet_choices(&choices, selection.clone(), cx);
6387 }
6388 }
6389
6390 // If snippet state is not at the last tabstop, push it back on the stack
6391 if snippet.active_index + 1 < snippet.ranges.len() {
6392 self.snippet_stack.push(snippet);
6393 }
6394 return true;
6395 }
6396 }
6397
6398 false
6399 }
6400
6401 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6402 self.transact(window, cx, |this, window, cx| {
6403 this.select_all(&SelectAll, window, cx);
6404 this.insert("", window, cx);
6405 });
6406 }
6407
6408 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6409 self.transact(window, cx, |this, window, cx| {
6410 this.select_autoclose_pair(window, cx);
6411 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6412 if !this.linked_edit_ranges.is_empty() {
6413 let selections = this.selections.all::<MultiBufferPoint>(cx);
6414 let snapshot = this.buffer.read(cx).snapshot(cx);
6415
6416 for selection in selections.iter() {
6417 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6418 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6419 if selection_start.buffer_id != selection_end.buffer_id {
6420 continue;
6421 }
6422 if let Some(ranges) =
6423 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6424 {
6425 for (buffer, entries) in ranges {
6426 linked_ranges.entry(buffer).or_default().extend(entries);
6427 }
6428 }
6429 }
6430 }
6431
6432 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6433 if !this.selections.line_mode {
6434 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6435 for selection in &mut selections {
6436 if selection.is_empty() {
6437 let old_head = selection.head();
6438 let mut new_head =
6439 movement::left(&display_map, old_head.to_display_point(&display_map))
6440 .to_point(&display_map);
6441 if let Some((buffer, line_buffer_range)) = display_map
6442 .buffer_snapshot
6443 .buffer_line_for_row(MultiBufferRow(old_head.row))
6444 {
6445 let indent_size =
6446 buffer.indent_size_for_line(line_buffer_range.start.row);
6447 let indent_len = match indent_size.kind {
6448 IndentKind::Space => {
6449 buffer.settings_at(line_buffer_range.start, cx).tab_size
6450 }
6451 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6452 };
6453 if old_head.column <= indent_size.len && old_head.column > 0 {
6454 let indent_len = indent_len.get();
6455 new_head = cmp::min(
6456 new_head,
6457 MultiBufferPoint::new(
6458 old_head.row,
6459 ((old_head.column - 1) / indent_len) * indent_len,
6460 ),
6461 );
6462 }
6463 }
6464
6465 selection.set_head(new_head, SelectionGoal::None);
6466 }
6467 }
6468 }
6469
6470 this.signature_help_state.set_backspace_pressed(true);
6471 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6472 s.select(selections)
6473 });
6474 this.insert("", window, cx);
6475 let empty_str: Arc<str> = Arc::from("");
6476 for (buffer, edits) in linked_ranges {
6477 let snapshot = buffer.read(cx).snapshot();
6478 use text::ToPoint as TP;
6479
6480 let edits = edits
6481 .into_iter()
6482 .map(|range| {
6483 let end_point = TP::to_point(&range.end, &snapshot);
6484 let mut start_point = TP::to_point(&range.start, &snapshot);
6485
6486 if end_point == start_point {
6487 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6488 .saturating_sub(1);
6489 start_point =
6490 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6491 };
6492
6493 (start_point..end_point, empty_str.clone())
6494 })
6495 .sorted_by_key(|(range, _)| range.start)
6496 .collect::<Vec<_>>();
6497 buffer.update(cx, |this, cx| {
6498 this.edit(edits, None, cx);
6499 })
6500 }
6501 this.refresh_inline_completion(true, false, window, cx);
6502 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6503 });
6504 }
6505
6506 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6507 self.transact(window, cx, |this, window, cx| {
6508 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6509 let line_mode = s.line_mode;
6510 s.move_with(|map, selection| {
6511 if selection.is_empty() && !line_mode {
6512 let cursor = movement::right(map, selection.head());
6513 selection.end = cursor;
6514 selection.reversed = true;
6515 selection.goal = SelectionGoal::None;
6516 }
6517 })
6518 });
6519 this.insert("", window, cx);
6520 this.refresh_inline_completion(true, false, window, cx);
6521 });
6522 }
6523
6524 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6525 if self.move_to_prev_snippet_tabstop(window, cx) {
6526 return;
6527 }
6528
6529 self.outdent(&Outdent, window, cx);
6530 }
6531
6532 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6533 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6534 return;
6535 }
6536
6537 let mut selections = self.selections.all_adjusted(cx);
6538 let buffer = self.buffer.read(cx);
6539 let snapshot = buffer.snapshot(cx);
6540 let rows_iter = selections.iter().map(|s| s.head().row);
6541 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6542
6543 let mut edits = Vec::new();
6544 let mut prev_edited_row = 0;
6545 let mut row_delta = 0;
6546 for selection in &mut selections {
6547 if selection.start.row != prev_edited_row {
6548 row_delta = 0;
6549 }
6550 prev_edited_row = selection.end.row;
6551
6552 // If the selection is non-empty, then increase the indentation of the selected lines.
6553 if !selection.is_empty() {
6554 row_delta =
6555 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6556 continue;
6557 }
6558
6559 // If the selection is empty and the cursor is in the leading whitespace before the
6560 // suggested indentation, then auto-indent the line.
6561 let cursor = selection.head();
6562 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6563 if let Some(suggested_indent) =
6564 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6565 {
6566 if cursor.column < suggested_indent.len
6567 && cursor.column <= current_indent.len
6568 && current_indent.len <= suggested_indent.len
6569 {
6570 selection.start = Point::new(cursor.row, suggested_indent.len);
6571 selection.end = selection.start;
6572 if row_delta == 0 {
6573 edits.extend(Buffer::edit_for_indent_size_adjustment(
6574 cursor.row,
6575 current_indent,
6576 suggested_indent,
6577 ));
6578 row_delta = suggested_indent.len - current_indent.len;
6579 }
6580 continue;
6581 }
6582 }
6583
6584 // Otherwise, insert a hard or soft tab.
6585 let settings = buffer.settings_at(cursor, cx);
6586 let tab_size = if settings.hard_tabs {
6587 IndentSize::tab()
6588 } else {
6589 let tab_size = settings.tab_size.get();
6590 let char_column = snapshot
6591 .text_for_range(Point::new(cursor.row, 0)..cursor)
6592 .flat_map(str::chars)
6593 .count()
6594 + row_delta as usize;
6595 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6596 IndentSize::spaces(chars_to_next_tab_stop)
6597 };
6598 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6599 selection.end = selection.start;
6600 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6601 row_delta += tab_size.len;
6602 }
6603
6604 self.transact(window, cx, |this, window, cx| {
6605 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6606 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6607 s.select(selections)
6608 });
6609 this.refresh_inline_completion(true, false, window, cx);
6610 });
6611 }
6612
6613 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6614 if self.read_only(cx) {
6615 return;
6616 }
6617 let mut selections = self.selections.all::<Point>(cx);
6618 let mut prev_edited_row = 0;
6619 let mut row_delta = 0;
6620 let mut edits = Vec::new();
6621 let buffer = self.buffer.read(cx);
6622 let snapshot = buffer.snapshot(cx);
6623 for selection in &mut selections {
6624 if selection.start.row != prev_edited_row {
6625 row_delta = 0;
6626 }
6627 prev_edited_row = selection.end.row;
6628
6629 row_delta =
6630 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6631 }
6632
6633 self.transact(window, cx, |this, window, cx| {
6634 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6635 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6636 s.select(selections)
6637 });
6638 });
6639 }
6640
6641 fn indent_selection(
6642 buffer: &MultiBuffer,
6643 snapshot: &MultiBufferSnapshot,
6644 selection: &mut Selection<Point>,
6645 edits: &mut Vec<(Range<Point>, String)>,
6646 delta_for_start_row: u32,
6647 cx: &App,
6648 ) -> u32 {
6649 let settings = buffer.settings_at(selection.start, cx);
6650 let tab_size = settings.tab_size.get();
6651 let indent_kind = if settings.hard_tabs {
6652 IndentKind::Tab
6653 } else {
6654 IndentKind::Space
6655 };
6656 let mut start_row = selection.start.row;
6657 let mut end_row = selection.end.row + 1;
6658
6659 // If a selection ends at the beginning of a line, don't indent
6660 // that last line.
6661 if selection.end.column == 0 && selection.end.row > selection.start.row {
6662 end_row -= 1;
6663 }
6664
6665 // Avoid re-indenting a row that has already been indented by a
6666 // previous selection, but still update this selection's column
6667 // to reflect that indentation.
6668 if delta_for_start_row > 0 {
6669 start_row += 1;
6670 selection.start.column += delta_for_start_row;
6671 if selection.end.row == selection.start.row {
6672 selection.end.column += delta_for_start_row;
6673 }
6674 }
6675
6676 let mut delta_for_end_row = 0;
6677 let has_multiple_rows = start_row + 1 != end_row;
6678 for row in start_row..end_row {
6679 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6680 let indent_delta = match (current_indent.kind, indent_kind) {
6681 (IndentKind::Space, IndentKind::Space) => {
6682 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6683 IndentSize::spaces(columns_to_next_tab_stop)
6684 }
6685 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6686 (_, IndentKind::Tab) => IndentSize::tab(),
6687 };
6688
6689 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6690 0
6691 } else {
6692 selection.start.column
6693 };
6694 let row_start = Point::new(row, start);
6695 edits.push((
6696 row_start..row_start,
6697 indent_delta.chars().collect::<String>(),
6698 ));
6699
6700 // Update this selection's endpoints to reflect the indentation.
6701 if row == selection.start.row {
6702 selection.start.column += indent_delta.len;
6703 }
6704 if row == selection.end.row {
6705 selection.end.column += indent_delta.len;
6706 delta_for_end_row = indent_delta.len;
6707 }
6708 }
6709
6710 if selection.start.row == selection.end.row {
6711 delta_for_start_row + delta_for_end_row
6712 } else {
6713 delta_for_end_row
6714 }
6715 }
6716
6717 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6718 if self.read_only(cx) {
6719 return;
6720 }
6721 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6722 let selections = self.selections.all::<Point>(cx);
6723 let mut deletion_ranges = Vec::new();
6724 let mut last_outdent = None;
6725 {
6726 let buffer = self.buffer.read(cx);
6727 let snapshot = buffer.snapshot(cx);
6728 for selection in &selections {
6729 let settings = buffer.settings_at(selection.start, cx);
6730 let tab_size = settings.tab_size.get();
6731 let mut rows = selection.spanned_rows(false, &display_map);
6732
6733 // Avoid re-outdenting a row that has already been outdented by a
6734 // previous selection.
6735 if let Some(last_row) = last_outdent {
6736 if last_row == rows.start {
6737 rows.start = rows.start.next_row();
6738 }
6739 }
6740 let has_multiple_rows = rows.len() > 1;
6741 for row in rows.iter_rows() {
6742 let indent_size = snapshot.indent_size_for_line(row);
6743 if indent_size.len > 0 {
6744 let deletion_len = match indent_size.kind {
6745 IndentKind::Space => {
6746 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6747 if columns_to_prev_tab_stop == 0 {
6748 tab_size
6749 } else {
6750 columns_to_prev_tab_stop
6751 }
6752 }
6753 IndentKind::Tab => 1,
6754 };
6755 let start = if has_multiple_rows
6756 || deletion_len > selection.start.column
6757 || indent_size.len < selection.start.column
6758 {
6759 0
6760 } else {
6761 selection.start.column - deletion_len
6762 };
6763 deletion_ranges.push(
6764 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6765 );
6766 last_outdent = Some(row);
6767 }
6768 }
6769 }
6770 }
6771
6772 self.transact(window, cx, |this, window, cx| {
6773 this.buffer.update(cx, |buffer, cx| {
6774 let empty_str: Arc<str> = Arc::default();
6775 buffer.edit(
6776 deletion_ranges
6777 .into_iter()
6778 .map(|range| (range, empty_str.clone())),
6779 None,
6780 cx,
6781 );
6782 });
6783 let selections = this.selections.all::<usize>(cx);
6784 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6785 s.select(selections)
6786 });
6787 });
6788 }
6789
6790 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6791 if self.read_only(cx) {
6792 return;
6793 }
6794 let selections = self
6795 .selections
6796 .all::<usize>(cx)
6797 .into_iter()
6798 .map(|s| s.range());
6799
6800 self.transact(window, cx, |this, window, cx| {
6801 this.buffer.update(cx, |buffer, cx| {
6802 buffer.autoindent_ranges(selections, cx);
6803 });
6804 let selections = this.selections.all::<usize>(cx);
6805 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6806 s.select(selections)
6807 });
6808 });
6809 }
6810
6811 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6812 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6813 let selections = self.selections.all::<Point>(cx);
6814
6815 let mut new_cursors = Vec::new();
6816 let mut edit_ranges = Vec::new();
6817 let mut selections = selections.iter().peekable();
6818 while let Some(selection) = selections.next() {
6819 let mut rows = selection.spanned_rows(false, &display_map);
6820 let goal_display_column = selection.head().to_display_point(&display_map).column();
6821
6822 // Accumulate contiguous regions of rows that we want to delete.
6823 while let Some(next_selection) = selections.peek() {
6824 let next_rows = next_selection.spanned_rows(false, &display_map);
6825 if next_rows.start <= rows.end {
6826 rows.end = next_rows.end;
6827 selections.next().unwrap();
6828 } else {
6829 break;
6830 }
6831 }
6832
6833 let buffer = &display_map.buffer_snapshot;
6834 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6835 let edit_end;
6836 let cursor_buffer_row;
6837 if buffer.max_point().row >= rows.end.0 {
6838 // If there's a line after the range, delete the \n from the end of the row range
6839 // and position the cursor on the next line.
6840 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6841 cursor_buffer_row = rows.end;
6842 } else {
6843 // If there isn't a line after the range, delete the \n from the line before the
6844 // start of the row range and position the cursor there.
6845 edit_start = edit_start.saturating_sub(1);
6846 edit_end = buffer.len();
6847 cursor_buffer_row = rows.start.previous_row();
6848 }
6849
6850 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6851 *cursor.column_mut() =
6852 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6853
6854 new_cursors.push((
6855 selection.id,
6856 buffer.anchor_after(cursor.to_point(&display_map)),
6857 ));
6858 edit_ranges.push(edit_start..edit_end);
6859 }
6860
6861 self.transact(window, cx, |this, window, cx| {
6862 let buffer = this.buffer.update(cx, |buffer, cx| {
6863 let empty_str: Arc<str> = Arc::default();
6864 buffer.edit(
6865 edit_ranges
6866 .into_iter()
6867 .map(|range| (range, empty_str.clone())),
6868 None,
6869 cx,
6870 );
6871 buffer.snapshot(cx)
6872 });
6873 let new_selections = new_cursors
6874 .into_iter()
6875 .map(|(id, cursor)| {
6876 let cursor = cursor.to_point(&buffer);
6877 Selection {
6878 id,
6879 start: cursor,
6880 end: cursor,
6881 reversed: false,
6882 goal: SelectionGoal::None,
6883 }
6884 })
6885 .collect();
6886
6887 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6888 s.select(new_selections);
6889 });
6890 });
6891 }
6892
6893 pub fn join_lines_impl(
6894 &mut self,
6895 insert_whitespace: bool,
6896 window: &mut Window,
6897 cx: &mut Context<Self>,
6898 ) {
6899 if self.read_only(cx) {
6900 return;
6901 }
6902 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6903 for selection in self.selections.all::<Point>(cx) {
6904 let start = MultiBufferRow(selection.start.row);
6905 // Treat single line selections as if they include the next line. Otherwise this action
6906 // would do nothing for single line selections individual cursors.
6907 let end = if selection.start.row == selection.end.row {
6908 MultiBufferRow(selection.start.row + 1)
6909 } else {
6910 MultiBufferRow(selection.end.row)
6911 };
6912
6913 if let Some(last_row_range) = row_ranges.last_mut() {
6914 if start <= last_row_range.end {
6915 last_row_range.end = end;
6916 continue;
6917 }
6918 }
6919 row_ranges.push(start..end);
6920 }
6921
6922 let snapshot = self.buffer.read(cx).snapshot(cx);
6923 let mut cursor_positions = Vec::new();
6924 for row_range in &row_ranges {
6925 let anchor = snapshot.anchor_before(Point::new(
6926 row_range.end.previous_row().0,
6927 snapshot.line_len(row_range.end.previous_row()),
6928 ));
6929 cursor_positions.push(anchor..anchor);
6930 }
6931
6932 self.transact(window, cx, |this, window, cx| {
6933 for row_range in row_ranges.into_iter().rev() {
6934 for row in row_range.iter_rows().rev() {
6935 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6936 let next_line_row = row.next_row();
6937 let indent = snapshot.indent_size_for_line(next_line_row);
6938 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6939
6940 let replace =
6941 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6942 " "
6943 } else {
6944 ""
6945 };
6946
6947 this.buffer.update(cx, |buffer, cx| {
6948 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6949 });
6950 }
6951 }
6952
6953 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6954 s.select_anchor_ranges(cursor_positions)
6955 });
6956 });
6957 }
6958
6959 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6960 self.join_lines_impl(true, window, cx);
6961 }
6962
6963 pub fn sort_lines_case_sensitive(
6964 &mut self,
6965 _: &SortLinesCaseSensitive,
6966 window: &mut Window,
6967 cx: &mut Context<Self>,
6968 ) {
6969 self.manipulate_lines(window, cx, |lines| lines.sort())
6970 }
6971
6972 pub fn sort_lines_case_insensitive(
6973 &mut self,
6974 _: &SortLinesCaseInsensitive,
6975 window: &mut Window,
6976 cx: &mut Context<Self>,
6977 ) {
6978 self.manipulate_lines(window, cx, |lines| {
6979 lines.sort_by_key(|line| line.to_lowercase())
6980 })
6981 }
6982
6983 pub fn unique_lines_case_insensitive(
6984 &mut self,
6985 _: &UniqueLinesCaseInsensitive,
6986 window: &mut Window,
6987 cx: &mut Context<Self>,
6988 ) {
6989 self.manipulate_lines(window, cx, |lines| {
6990 let mut seen = HashSet::default();
6991 lines.retain(|line| seen.insert(line.to_lowercase()));
6992 })
6993 }
6994
6995 pub fn unique_lines_case_sensitive(
6996 &mut self,
6997 _: &UniqueLinesCaseSensitive,
6998 window: &mut Window,
6999 cx: &mut Context<Self>,
7000 ) {
7001 self.manipulate_lines(window, cx, |lines| {
7002 let mut seen = HashSet::default();
7003 lines.retain(|line| seen.insert(*line));
7004 })
7005 }
7006
7007 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7008 let Some(project) = self.project.clone() else {
7009 return;
7010 };
7011 self.reload(project, window, cx)
7012 .detach_and_notify_err(window, cx);
7013 }
7014
7015 pub fn restore_file(
7016 &mut self,
7017 _: &::git::RestoreFile,
7018 window: &mut Window,
7019 cx: &mut Context<Self>,
7020 ) {
7021 let mut buffer_ids = HashSet::default();
7022 let snapshot = self.buffer().read(cx).snapshot(cx);
7023 for selection in self.selections.all::<usize>(cx) {
7024 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7025 }
7026
7027 let buffer = self.buffer().read(cx);
7028 let ranges = buffer_ids
7029 .into_iter()
7030 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7031 .collect::<Vec<_>>();
7032
7033 self.restore_hunks_in_ranges(ranges, window, cx);
7034 }
7035
7036 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7037 let selections = self
7038 .selections
7039 .all(cx)
7040 .into_iter()
7041 .map(|s| s.range())
7042 .collect();
7043 self.restore_hunks_in_ranges(selections, window, cx);
7044 }
7045
7046 fn restore_hunks_in_ranges(
7047 &mut self,
7048 ranges: Vec<Range<Point>>,
7049 window: &mut Window,
7050 cx: &mut Context<Editor>,
7051 ) {
7052 let mut revert_changes = HashMap::default();
7053 let snapshot = self.buffer.read(cx).snapshot(cx);
7054 let Some(project) = &self.project else {
7055 return;
7056 };
7057
7058 let chunk_by = self
7059 .snapshot(window, cx)
7060 .hunks_for_ranges(ranges.into_iter())
7061 .into_iter()
7062 .chunk_by(|hunk| hunk.buffer_id);
7063 for (buffer_id, hunks) in &chunk_by {
7064 let hunks = hunks.collect::<Vec<_>>();
7065 for hunk in &hunks {
7066 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7067 }
7068 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7069 }
7070 drop(chunk_by);
7071 if !revert_changes.is_empty() {
7072 self.transact(window, cx, |editor, window, cx| {
7073 editor.revert(revert_changes, window, cx);
7074 });
7075 }
7076 }
7077
7078 pub fn open_active_item_in_terminal(
7079 &mut self,
7080 _: &OpenInTerminal,
7081 window: &mut Window,
7082 cx: &mut Context<Self>,
7083 ) {
7084 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7085 let project_path = buffer.read(cx).project_path(cx)?;
7086 let project = self.project.as_ref()?.read(cx);
7087 let entry = project.entry_for_path(&project_path, cx)?;
7088 let parent = match &entry.canonical_path {
7089 Some(canonical_path) => canonical_path.to_path_buf(),
7090 None => project.absolute_path(&project_path, cx)?,
7091 }
7092 .parent()?
7093 .to_path_buf();
7094 Some(parent)
7095 }) {
7096 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7097 }
7098 }
7099
7100 pub fn prepare_restore_change(
7101 &self,
7102 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7103 hunk: &MultiBufferDiffHunk,
7104 cx: &mut App,
7105 ) -> Option<()> {
7106 let buffer = self.buffer.read(cx);
7107 let diff = buffer.diff_for(hunk.buffer_id)?;
7108 let buffer = buffer.buffer(hunk.buffer_id)?;
7109 let buffer = buffer.read(cx);
7110 let original_text = diff
7111 .read(cx)
7112 .base_text()
7113 .as_ref()?
7114 .as_rope()
7115 .slice(hunk.diff_base_byte_range.clone());
7116 let buffer_snapshot = buffer.snapshot();
7117 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7118 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7119 probe
7120 .0
7121 .start
7122 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7123 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7124 }) {
7125 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7126 Some(())
7127 } else {
7128 None
7129 }
7130 }
7131
7132 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7133 self.manipulate_lines(window, cx, |lines| lines.reverse())
7134 }
7135
7136 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7137 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7138 }
7139
7140 fn manipulate_lines<Fn>(
7141 &mut self,
7142 window: &mut Window,
7143 cx: &mut Context<Self>,
7144 mut callback: Fn,
7145 ) where
7146 Fn: FnMut(&mut Vec<&str>),
7147 {
7148 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7149 let buffer = self.buffer.read(cx).snapshot(cx);
7150
7151 let mut edits = Vec::new();
7152
7153 let selections = self.selections.all::<Point>(cx);
7154 let mut selections = selections.iter().peekable();
7155 let mut contiguous_row_selections = Vec::new();
7156 let mut new_selections = Vec::new();
7157 let mut added_lines = 0;
7158 let mut removed_lines = 0;
7159
7160 while let Some(selection) = selections.next() {
7161 let (start_row, end_row) = consume_contiguous_rows(
7162 &mut contiguous_row_selections,
7163 selection,
7164 &display_map,
7165 &mut selections,
7166 );
7167
7168 let start_point = Point::new(start_row.0, 0);
7169 let end_point = Point::new(
7170 end_row.previous_row().0,
7171 buffer.line_len(end_row.previous_row()),
7172 );
7173 let text = buffer
7174 .text_for_range(start_point..end_point)
7175 .collect::<String>();
7176
7177 let mut lines = text.split('\n').collect_vec();
7178
7179 let lines_before = lines.len();
7180 callback(&mut lines);
7181 let lines_after = lines.len();
7182
7183 edits.push((start_point..end_point, lines.join("\n")));
7184
7185 // Selections must change based on added and removed line count
7186 let start_row =
7187 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7188 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7189 new_selections.push(Selection {
7190 id: selection.id,
7191 start: start_row,
7192 end: end_row,
7193 goal: SelectionGoal::None,
7194 reversed: selection.reversed,
7195 });
7196
7197 if lines_after > lines_before {
7198 added_lines += lines_after - lines_before;
7199 } else if lines_before > lines_after {
7200 removed_lines += lines_before - lines_after;
7201 }
7202 }
7203
7204 self.transact(window, cx, |this, window, cx| {
7205 let buffer = this.buffer.update(cx, |buffer, cx| {
7206 buffer.edit(edits, None, cx);
7207 buffer.snapshot(cx)
7208 });
7209
7210 // Recalculate offsets on newly edited buffer
7211 let new_selections = new_selections
7212 .iter()
7213 .map(|s| {
7214 let start_point = Point::new(s.start.0, 0);
7215 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7216 Selection {
7217 id: s.id,
7218 start: buffer.point_to_offset(start_point),
7219 end: buffer.point_to_offset(end_point),
7220 goal: s.goal,
7221 reversed: s.reversed,
7222 }
7223 })
7224 .collect();
7225
7226 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7227 s.select(new_selections);
7228 });
7229
7230 this.request_autoscroll(Autoscroll::fit(), cx);
7231 });
7232 }
7233
7234 pub fn convert_to_upper_case(
7235 &mut self,
7236 _: &ConvertToUpperCase,
7237 window: &mut Window,
7238 cx: &mut Context<Self>,
7239 ) {
7240 self.manipulate_text(window, cx, |text| text.to_uppercase())
7241 }
7242
7243 pub fn convert_to_lower_case(
7244 &mut self,
7245 _: &ConvertToLowerCase,
7246 window: &mut Window,
7247 cx: &mut Context<Self>,
7248 ) {
7249 self.manipulate_text(window, cx, |text| text.to_lowercase())
7250 }
7251
7252 pub fn convert_to_title_case(
7253 &mut self,
7254 _: &ConvertToTitleCase,
7255 window: &mut Window,
7256 cx: &mut Context<Self>,
7257 ) {
7258 self.manipulate_text(window, cx, |text| {
7259 text.split('\n')
7260 .map(|line| line.to_case(Case::Title))
7261 .join("\n")
7262 })
7263 }
7264
7265 pub fn convert_to_snake_case(
7266 &mut self,
7267 _: &ConvertToSnakeCase,
7268 window: &mut Window,
7269 cx: &mut Context<Self>,
7270 ) {
7271 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7272 }
7273
7274 pub fn convert_to_kebab_case(
7275 &mut self,
7276 _: &ConvertToKebabCase,
7277 window: &mut Window,
7278 cx: &mut Context<Self>,
7279 ) {
7280 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7281 }
7282
7283 pub fn convert_to_upper_camel_case(
7284 &mut self,
7285 _: &ConvertToUpperCamelCase,
7286 window: &mut Window,
7287 cx: &mut Context<Self>,
7288 ) {
7289 self.manipulate_text(window, cx, |text| {
7290 text.split('\n')
7291 .map(|line| line.to_case(Case::UpperCamel))
7292 .join("\n")
7293 })
7294 }
7295
7296 pub fn convert_to_lower_camel_case(
7297 &mut self,
7298 _: &ConvertToLowerCamelCase,
7299 window: &mut Window,
7300 cx: &mut Context<Self>,
7301 ) {
7302 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7303 }
7304
7305 pub fn convert_to_opposite_case(
7306 &mut self,
7307 _: &ConvertToOppositeCase,
7308 window: &mut Window,
7309 cx: &mut Context<Self>,
7310 ) {
7311 self.manipulate_text(window, cx, |text| {
7312 text.chars()
7313 .fold(String::with_capacity(text.len()), |mut t, c| {
7314 if c.is_uppercase() {
7315 t.extend(c.to_lowercase());
7316 } else {
7317 t.extend(c.to_uppercase());
7318 }
7319 t
7320 })
7321 })
7322 }
7323
7324 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7325 where
7326 Fn: FnMut(&str) -> String,
7327 {
7328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7329 let buffer = self.buffer.read(cx).snapshot(cx);
7330
7331 let mut new_selections = Vec::new();
7332 let mut edits = Vec::new();
7333 let mut selection_adjustment = 0i32;
7334
7335 for selection in self.selections.all::<usize>(cx) {
7336 let selection_is_empty = selection.is_empty();
7337
7338 let (start, end) = if selection_is_empty {
7339 let word_range = movement::surrounding_word(
7340 &display_map,
7341 selection.start.to_display_point(&display_map),
7342 );
7343 let start = word_range.start.to_offset(&display_map, Bias::Left);
7344 let end = word_range.end.to_offset(&display_map, Bias::Left);
7345 (start, end)
7346 } else {
7347 (selection.start, selection.end)
7348 };
7349
7350 let text = buffer.text_for_range(start..end).collect::<String>();
7351 let old_length = text.len() as i32;
7352 let text = callback(&text);
7353
7354 new_selections.push(Selection {
7355 start: (start as i32 - selection_adjustment) as usize,
7356 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7357 goal: SelectionGoal::None,
7358 ..selection
7359 });
7360
7361 selection_adjustment += old_length - text.len() as i32;
7362
7363 edits.push((start..end, text));
7364 }
7365
7366 self.transact(window, cx, |this, window, cx| {
7367 this.buffer.update(cx, |buffer, cx| {
7368 buffer.edit(edits, None, cx);
7369 });
7370
7371 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7372 s.select(new_selections);
7373 });
7374
7375 this.request_autoscroll(Autoscroll::fit(), cx);
7376 });
7377 }
7378
7379 pub fn duplicate(
7380 &mut self,
7381 upwards: bool,
7382 whole_lines: bool,
7383 window: &mut Window,
7384 cx: &mut Context<Self>,
7385 ) {
7386 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7387 let buffer = &display_map.buffer_snapshot;
7388 let selections = self.selections.all::<Point>(cx);
7389
7390 let mut edits = Vec::new();
7391 let mut selections_iter = selections.iter().peekable();
7392 while let Some(selection) = selections_iter.next() {
7393 let mut rows = selection.spanned_rows(false, &display_map);
7394 // duplicate line-wise
7395 if whole_lines || selection.start == selection.end {
7396 // Avoid duplicating the same lines twice.
7397 while let Some(next_selection) = selections_iter.peek() {
7398 let next_rows = next_selection.spanned_rows(false, &display_map);
7399 if next_rows.start < rows.end {
7400 rows.end = next_rows.end;
7401 selections_iter.next().unwrap();
7402 } else {
7403 break;
7404 }
7405 }
7406
7407 // Copy the text from the selected row region and splice it either at the start
7408 // or end of the region.
7409 let start = Point::new(rows.start.0, 0);
7410 let end = Point::new(
7411 rows.end.previous_row().0,
7412 buffer.line_len(rows.end.previous_row()),
7413 );
7414 let text = buffer
7415 .text_for_range(start..end)
7416 .chain(Some("\n"))
7417 .collect::<String>();
7418 let insert_location = if upwards {
7419 Point::new(rows.end.0, 0)
7420 } else {
7421 start
7422 };
7423 edits.push((insert_location..insert_location, text));
7424 } else {
7425 // duplicate character-wise
7426 let start = selection.start;
7427 let end = selection.end;
7428 let text = buffer.text_for_range(start..end).collect::<String>();
7429 edits.push((selection.end..selection.end, text));
7430 }
7431 }
7432
7433 self.transact(window, cx, |this, _, cx| {
7434 this.buffer.update(cx, |buffer, cx| {
7435 buffer.edit(edits, None, cx);
7436 });
7437
7438 this.request_autoscroll(Autoscroll::fit(), cx);
7439 });
7440 }
7441
7442 pub fn duplicate_line_up(
7443 &mut self,
7444 _: &DuplicateLineUp,
7445 window: &mut Window,
7446 cx: &mut Context<Self>,
7447 ) {
7448 self.duplicate(true, true, window, cx);
7449 }
7450
7451 pub fn duplicate_line_down(
7452 &mut self,
7453 _: &DuplicateLineDown,
7454 window: &mut Window,
7455 cx: &mut Context<Self>,
7456 ) {
7457 self.duplicate(false, true, window, cx);
7458 }
7459
7460 pub fn duplicate_selection(
7461 &mut self,
7462 _: &DuplicateSelection,
7463 window: &mut Window,
7464 cx: &mut Context<Self>,
7465 ) {
7466 self.duplicate(false, false, window, cx);
7467 }
7468
7469 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7471 let buffer = self.buffer.read(cx).snapshot(cx);
7472
7473 let mut edits = Vec::new();
7474 let mut unfold_ranges = Vec::new();
7475 let mut refold_creases = Vec::new();
7476
7477 let selections = self.selections.all::<Point>(cx);
7478 let mut selections = selections.iter().peekable();
7479 let mut contiguous_row_selections = Vec::new();
7480 let mut new_selections = Vec::new();
7481
7482 while let Some(selection) = selections.next() {
7483 // Find all the selections that span a contiguous row range
7484 let (start_row, end_row) = consume_contiguous_rows(
7485 &mut contiguous_row_selections,
7486 selection,
7487 &display_map,
7488 &mut selections,
7489 );
7490
7491 // Move the text spanned by the row range to be before the line preceding the row range
7492 if start_row.0 > 0 {
7493 let range_to_move = Point::new(
7494 start_row.previous_row().0,
7495 buffer.line_len(start_row.previous_row()),
7496 )
7497 ..Point::new(
7498 end_row.previous_row().0,
7499 buffer.line_len(end_row.previous_row()),
7500 );
7501 let insertion_point = display_map
7502 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7503 .0;
7504
7505 // Don't move lines across excerpts
7506 if buffer
7507 .excerpt_containing(insertion_point..range_to_move.end)
7508 .is_some()
7509 {
7510 let text = buffer
7511 .text_for_range(range_to_move.clone())
7512 .flat_map(|s| s.chars())
7513 .skip(1)
7514 .chain(['\n'])
7515 .collect::<String>();
7516
7517 edits.push((
7518 buffer.anchor_after(range_to_move.start)
7519 ..buffer.anchor_before(range_to_move.end),
7520 String::new(),
7521 ));
7522 let insertion_anchor = buffer.anchor_after(insertion_point);
7523 edits.push((insertion_anchor..insertion_anchor, text));
7524
7525 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7526
7527 // Move selections up
7528 new_selections.extend(contiguous_row_selections.drain(..).map(
7529 |mut selection| {
7530 selection.start.row -= row_delta;
7531 selection.end.row -= row_delta;
7532 selection
7533 },
7534 ));
7535
7536 // Move folds up
7537 unfold_ranges.push(range_to_move.clone());
7538 for fold in display_map.folds_in_range(
7539 buffer.anchor_before(range_to_move.start)
7540 ..buffer.anchor_after(range_to_move.end),
7541 ) {
7542 let mut start = fold.range.start.to_point(&buffer);
7543 let mut end = fold.range.end.to_point(&buffer);
7544 start.row -= row_delta;
7545 end.row -= row_delta;
7546 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7547 }
7548 }
7549 }
7550
7551 // If we didn't move line(s), preserve the existing selections
7552 new_selections.append(&mut contiguous_row_selections);
7553 }
7554
7555 self.transact(window, cx, |this, window, cx| {
7556 this.unfold_ranges(&unfold_ranges, true, true, cx);
7557 this.buffer.update(cx, |buffer, cx| {
7558 for (range, text) in edits {
7559 buffer.edit([(range, text)], None, cx);
7560 }
7561 });
7562 this.fold_creases(refold_creases, true, window, cx);
7563 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7564 s.select(new_selections);
7565 })
7566 });
7567 }
7568
7569 pub fn move_line_down(
7570 &mut self,
7571 _: &MoveLineDown,
7572 window: &mut Window,
7573 cx: &mut Context<Self>,
7574 ) {
7575 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7576 let buffer = self.buffer.read(cx).snapshot(cx);
7577
7578 let mut edits = Vec::new();
7579 let mut unfold_ranges = Vec::new();
7580 let mut refold_creases = Vec::new();
7581
7582 let selections = self.selections.all::<Point>(cx);
7583 let mut selections = selections.iter().peekable();
7584 let mut contiguous_row_selections = Vec::new();
7585 let mut new_selections = Vec::new();
7586
7587 while let Some(selection) = selections.next() {
7588 // Find all the selections that span a contiguous row range
7589 let (start_row, end_row) = consume_contiguous_rows(
7590 &mut contiguous_row_selections,
7591 selection,
7592 &display_map,
7593 &mut selections,
7594 );
7595
7596 // Move the text spanned by the row range to be after the last line of the row range
7597 if end_row.0 <= buffer.max_point().row {
7598 let range_to_move =
7599 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7600 let insertion_point = display_map
7601 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7602 .0;
7603
7604 // Don't move lines across excerpt boundaries
7605 if buffer
7606 .excerpt_containing(range_to_move.start..insertion_point)
7607 .is_some()
7608 {
7609 let mut text = String::from("\n");
7610 text.extend(buffer.text_for_range(range_to_move.clone()));
7611 text.pop(); // Drop trailing newline
7612 edits.push((
7613 buffer.anchor_after(range_to_move.start)
7614 ..buffer.anchor_before(range_to_move.end),
7615 String::new(),
7616 ));
7617 let insertion_anchor = buffer.anchor_after(insertion_point);
7618 edits.push((insertion_anchor..insertion_anchor, text));
7619
7620 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7621
7622 // Move selections down
7623 new_selections.extend(contiguous_row_selections.drain(..).map(
7624 |mut selection| {
7625 selection.start.row += row_delta;
7626 selection.end.row += row_delta;
7627 selection
7628 },
7629 ));
7630
7631 // Move folds down
7632 unfold_ranges.push(range_to_move.clone());
7633 for fold in display_map.folds_in_range(
7634 buffer.anchor_before(range_to_move.start)
7635 ..buffer.anchor_after(range_to_move.end),
7636 ) {
7637 let mut start = fold.range.start.to_point(&buffer);
7638 let mut end = fold.range.end.to_point(&buffer);
7639 start.row += row_delta;
7640 end.row += row_delta;
7641 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7642 }
7643 }
7644 }
7645
7646 // If we didn't move line(s), preserve the existing selections
7647 new_selections.append(&mut contiguous_row_selections);
7648 }
7649
7650 self.transact(window, cx, |this, window, cx| {
7651 this.unfold_ranges(&unfold_ranges, true, true, cx);
7652 this.buffer.update(cx, |buffer, cx| {
7653 for (range, text) in edits {
7654 buffer.edit([(range, text)], None, cx);
7655 }
7656 });
7657 this.fold_creases(refold_creases, true, window, cx);
7658 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7659 s.select(new_selections)
7660 });
7661 });
7662 }
7663
7664 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7665 let text_layout_details = &self.text_layout_details(window);
7666 self.transact(window, cx, |this, window, cx| {
7667 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7668 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7669 let line_mode = s.line_mode;
7670 s.move_with(|display_map, selection| {
7671 if !selection.is_empty() || line_mode {
7672 return;
7673 }
7674
7675 let mut head = selection.head();
7676 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7677 if head.column() == display_map.line_len(head.row()) {
7678 transpose_offset = display_map
7679 .buffer_snapshot
7680 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7681 }
7682
7683 if transpose_offset == 0 {
7684 return;
7685 }
7686
7687 *head.column_mut() += 1;
7688 head = display_map.clip_point(head, Bias::Right);
7689 let goal = SelectionGoal::HorizontalPosition(
7690 display_map
7691 .x_for_display_point(head, text_layout_details)
7692 .into(),
7693 );
7694 selection.collapse_to(head, goal);
7695
7696 let transpose_start = display_map
7697 .buffer_snapshot
7698 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7699 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7700 let transpose_end = display_map
7701 .buffer_snapshot
7702 .clip_offset(transpose_offset + 1, Bias::Right);
7703 if let Some(ch) =
7704 display_map.buffer_snapshot.chars_at(transpose_start).next()
7705 {
7706 edits.push((transpose_start..transpose_offset, String::new()));
7707 edits.push((transpose_end..transpose_end, ch.to_string()));
7708 }
7709 }
7710 });
7711 edits
7712 });
7713 this.buffer
7714 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7715 let selections = this.selections.all::<usize>(cx);
7716 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7717 s.select(selections);
7718 });
7719 });
7720 }
7721
7722 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7723 self.rewrap_impl(IsVimMode::No, cx)
7724 }
7725
7726 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7727 let buffer = self.buffer.read(cx).snapshot(cx);
7728 let selections = self.selections.all::<Point>(cx);
7729 let mut selections = selections.iter().peekable();
7730
7731 let mut edits = Vec::new();
7732 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7733
7734 while let Some(selection) = selections.next() {
7735 let mut start_row = selection.start.row;
7736 let mut end_row = selection.end.row;
7737
7738 // Skip selections that overlap with a range that has already been rewrapped.
7739 let selection_range = start_row..end_row;
7740 if rewrapped_row_ranges
7741 .iter()
7742 .any(|range| range.overlaps(&selection_range))
7743 {
7744 continue;
7745 }
7746
7747 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7748
7749 // Since not all lines in the selection may be at the same indent
7750 // level, choose the indent size that is the most common between all
7751 // of the lines.
7752 //
7753 // If there is a tie, we use the deepest indent.
7754 let (indent_size, indent_end) = {
7755 let mut indent_size_occurrences = HashMap::default();
7756 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7757
7758 for row in start_row..=end_row {
7759 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7760 rows_by_indent_size.entry(indent).or_default().push(row);
7761 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7762 }
7763
7764 let indent_size = indent_size_occurrences
7765 .into_iter()
7766 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7767 .map(|(indent, _)| indent)
7768 .unwrap_or_default();
7769 let row = rows_by_indent_size[&indent_size][0];
7770 let indent_end = Point::new(row, indent_size.len);
7771
7772 (indent_size, indent_end)
7773 };
7774
7775 let mut line_prefix = indent_size.chars().collect::<String>();
7776
7777 let mut inside_comment = false;
7778 if let Some(comment_prefix) =
7779 buffer
7780 .language_scope_at(selection.head())
7781 .and_then(|language| {
7782 language
7783 .line_comment_prefixes()
7784 .iter()
7785 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7786 .cloned()
7787 })
7788 {
7789 line_prefix.push_str(&comment_prefix);
7790 inside_comment = true;
7791 }
7792
7793 let language_settings = buffer.settings_at(selection.head(), cx);
7794 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
7795 RewrapBehavior::InComments => inside_comment,
7796 RewrapBehavior::InSelections => !selection.is_empty(),
7797 RewrapBehavior::Anywhere => true,
7798 };
7799
7800 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
7801 if !should_rewrap {
7802 continue;
7803 }
7804
7805 if selection.is_empty() {
7806 'expand_upwards: while start_row > 0 {
7807 let prev_row = start_row - 1;
7808 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7809 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7810 {
7811 start_row = prev_row;
7812 } else {
7813 break 'expand_upwards;
7814 }
7815 }
7816
7817 'expand_downwards: while end_row < buffer.max_point().row {
7818 let next_row = end_row + 1;
7819 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7820 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7821 {
7822 end_row = next_row;
7823 } else {
7824 break 'expand_downwards;
7825 }
7826 }
7827 }
7828
7829 let start = Point::new(start_row, 0);
7830 let start_offset = start.to_offset(&buffer);
7831 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7832 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7833 let Some(lines_without_prefixes) = selection_text
7834 .lines()
7835 .map(|line| {
7836 line.strip_prefix(&line_prefix)
7837 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7838 .ok_or_else(|| {
7839 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7840 })
7841 })
7842 .collect::<Result<Vec<_>, _>>()
7843 .log_err()
7844 else {
7845 continue;
7846 };
7847
7848 let wrap_column = buffer
7849 .settings_at(Point::new(start_row, 0), cx)
7850 .preferred_line_length as usize;
7851 let wrapped_text = wrap_with_prefix(
7852 line_prefix,
7853 lines_without_prefixes.join(" "),
7854 wrap_column,
7855 tab_size,
7856 );
7857
7858 // TODO: should always use char-based diff while still supporting cursor behavior that
7859 // matches vim.
7860 let mut diff_options = DiffOptions::default();
7861 if is_vim_mode == IsVimMode::Yes {
7862 diff_options.max_word_diff_len = 0;
7863 diff_options.max_word_diff_line_count = 0;
7864 } else {
7865 diff_options.max_word_diff_len = usize::MAX;
7866 diff_options.max_word_diff_line_count = usize::MAX;
7867 }
7868
7869 for (old_range, new_text) in
7870 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
7871 {
7872 let edit_start = buffer.anchor_after(start_offset + old_range.start);
7873 let edit_end = buffer.anchor_after(start_offset + old_range.end);
7874 edits.push((edit_start..edit_end, new_text));
7875 }
7876
7877 rewrapped_row_ranges.push(start_row..=end_row);
7878 }
7879
7880 self.buffer
7881 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7882 }
7883
7884 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7885 let mut text = String::new();
7886 let buffer = self.buffer.read(cx).snapshot(cx);
7887 let mut selections = self.selections.all::<Point>(cx);
7888 let mut clipboard_selections = Vec::with_capacity(selections.len());
7889 {
7890 let max_point = buffer.max_point();
7891 let mut is_first = true;
7892 for selection in &mut selections {
7893 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7894 if is_entire_line {
7895 selection.start = Point::new(selection.start.row, 0);
7896 if !selection.is_empty() && selection.end.column == 0 {
7897 selection.end = cmp::min(max_point, selection.end);
7898 } else {
7899 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7900 }
7901 selection.goal = SelectionGoal::None;
7902 }
7903 if is_first {
7904 is_first = false;
7905 } else {
7906 text += "\n";
7907 }
7908 let mut len = 0;
7909 for chunk in buffer.text_for_range(selection.start..selection.end) {
7910 text.push_str(chunk);
7911 len += chunk.len();
7912 }
7913 clipboard_selections.push(ClipboardSelection {
7914 len,
7915 is_entire_line,
7916 first_line_indent: buffer
7917 .indent_size_for_line(MultiBufferRow(selection.start.row))
7918 .len,
7919 });
7920 }
7921 }
7922
7923 self.transact(window, cx, |this, window, cx| {
7924 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7925 s.select(selections);
7926 });
7927 this.insert("", window, cx);
7928 });
7929 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7930 }
7931
7932 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7933 let item = self.cut_common(window, cx);
7934 cx.write_to_clipboard(item);
7935 }
7936
7937 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7938 self.change_selections(None, window, cx, |s| {
7939 s.move_with(|snapshot, sel| {
7940 if sel.is_empty() {
7941 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7942 }
7943 });
7944 });
7945 let item = self.cut_common(window, cx);
7946 cx.set_global(KillRing(item))
7947 }
7948
7949 pub fn kill_ring_yank(
7950 &mut self,
7951 _: &KillRingYank,
7952 window: &mut Window,
7953 cx: &mut Context<Self>,
7954 ) {
7955 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7956 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7957 (kill_ring.text().to_string(), kill_ring.metadata_json())
7958 } else {
7959 return;
7960 }
7961 } else {
7962 return;
7963 };
7964 self.do_paste(&text, metadata, false, window, cx);
7965 }
7966
7967 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7968 let selections = self.selections.all::<Point>(cx);
7969 let buffer = self.buffer.read(cx).read(cx);
7970 let mut text = String::new();
7971
7972 let mut clipboard_selections = Vec::with_capacity(selections.len());
7973 {
7974 let max_point = buffer.max_point();
7975 let mut is_first = true;
7976 for selection in selections.iter() {
7977 let mut start = selection.start;
7978 let mut end = selection.end;
7979 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7980 if is_entire_line {
7981 start = Point::new(start.row, 0);
7982 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7983 }
7984 if is_first {
7985 is_first = false;
7986 } else {
7987 text += "\n";
7988 }
7989 let mut len = 0;
7990 for chunk in buffer.text_for_range(start..end) {
7991 text.push_str(chunk);
7992 len += chunk.len();
7993 }
7994 clipboard_selections.push(ClipboardSelection {
7995 len,
7996 is_entire_line,
7997 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7998 });
7999 }
8000 }
8001
8002 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8003 text,
8004 clipboard_selections,
8005 ));
8006 }
8007
8008 pub fn do_paste(
8009 &mut self,
8010 text: &String,
8011 clipboard_selections: Option<Vec<ClipboardSelection>>,
8012 handle_entire_lines: bool,
8013 window: &mut Window,
8014 cx: &mut Context<Self>,
8015 ) {
8016 if self.read_only(cx) {
8017 return;
8018 }
8019
8020 let clipboard_text = Cow::Borrowed(text);
8021
8022 self.transact(window, cx, |this, window, cx| {
8023 if let Some(mut clipboard_selections) = clipboard_selections {
8024 let old_selections = this.selections.all::<usize>(cx);
8025 let all_selections_were_entire_line =
8026 clipboard_selections.iter().all(|s| s.is_entire_line);
8027 let first_selection_indent_column =
8028 clipboard_selections.first().map(|s| s.first_line_indent);
8029 if clipboard_selections.len() != old_selections.len() {
8030 clipboard_selections.drain(..);
8031 }
8032 let cursor_offset = this.selections.last::<usize>(cx).head();
8033 let mut auto_indent_on_paste = true;
8034
8035 this.buffer.update(cx, |buffer, cx| {
8036 let snapshot = buffer.read(cx);
8037 auto_indent_on_paste =
8038 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8039
8040 let mut start_offset = 0;
8041 let mut edits = Vec::new();
8042 let mut original_indent_columns = Vec::new();
8043 for (ix, selection) in old_selections.iter().enumerate() {
8044 let to_insert;
8045 let entire_line;
8046 let original_indent_column;
8047 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8048 let end_offset = start_offset + clipboard_selection.len;
8049 to_insert = &clipboard_text[start_offset..end_offset];
8050 entire_line = clipboard_selection.is_entire_line;
8051 start_offset = end_offset + 1;
8052 original_indent_column = Some(clipboard_selection.first_line_indent);
8053 } else {
8054 to_insert = clipboard_text.as_str();
8055 entire_line = all_selections_were_entire_line;
8056 original_indent_column = first_selection_indent_column
8057 }
8058
8059 // If the corresponding selection was empty when this slice of the
8060 // clipboard text was written, then the entire line containing the
8061 // selection was copied. If this selection is also currently empty,
8062 // then paste the line before the current line of the buffer.
8063 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8064 let column = selection.start.to_point(&snapshot).column as usize;
8065 let line_start = selection.start - column;
8066 line_start..line_start
8067 } else {
8068 selection.range()
8069 };
8070
8071 edits.push((range, to_insert));
8072 original_indent_columns.extend(original_indent_column);
8073 }
8074 drop(snapshot);
8075
8076 buffer.edit(
8077 edits,
8078 if auto_indent_on_paste {
8079 Some(AutoindentMode::Block {
8080 original_indent_columns,
8081 })
8082 } else {
8083 None
8084 },
8085 cx,
8086 );
8087 });
8088
8089 let selections = this.selections.all::<usize>(cx);
8090 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8091 s.select(selections)
8092 });
8093 } else {
8094 this.insert(&clipboard_text, window, cx);
8095 }
8096 });
8097 }
8098
8099 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8100 if let Some(item) = cx.read_from_clipboard() {
8101 let entries = item.entries();
8102
8103 match entries.first() {
8104 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8105 // of all the pasted entries.
8106 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8107 .do_paste(
8108 clipboard_string.text(),
8109 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8110 true,
8111 window,
8112 cx,
8113 ),
8114 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8115 }
8116 }
8117 }
8118
8119 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8120 if self.read_only(cx) {
8121 return;
8122 }
8123
8124 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8125 if let Some((selections, _)) =
8126 self.selection_history.transaction(transaction_id).cloned()
8127 {
8128 self.change_selections(None, window, cx, |s| {
8129 s.select_anchors(selections.to_vec());
8130 });
8131 }
8132 self.request_autoscroll(Autoscroll::fit(), cx);
8133 self.unmark_text(window, cx);
8134 self.refresh_inline_completion(true, false, window, cx);
8135 cx.emit(EditorEvent::Edited { transaction_id });
8136 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8137 }
8138 }
8139
8140 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8141 if self.read_only(cx) {
8142 return;
8143 }
8144
8145 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8146 if let Some((_, Some(selections))) =
8147 self.selection_history.transaction(transaction_id).cloned()
8148 {
8149 self.change_selections(None, window, cx, |s| {
8150 s.select_anchors(selections.to_vec());
8151 });
8152 }
8153 self.request_autoscroll(Autoscroll::fit(), cx);
8154 self.unmark_text(window, cx);
8155 self.refresh_inline_completion(true, false, window, cx);
8156 cx.emit(EditorEvent::Edited { transaction_id });
8157 }
8158 }
8159
8160 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8161 self.buffer
8162 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8163 }
8164
8165 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8166 self.buffer
8167 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8168 }
8169
8170 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8171 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8172 let line_mode = s.line_mode;
8173 s.move_with(|map, selection| {
8174 let cursor = if selection.is_empty() && !line_mode {
8175 movement::left(map, selection.start)
8176 } else {
8177 selection.start
8178 };
8179 selection.collapse_to(cursor, SelectionGoal::None);
8180 });
8181 })
8182 }
8183
8184 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8185 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8186 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8187 })
8188 }
8189
8190 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8191 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8192 let line_mode = s.line_mode;
8193 s.move_with(|map, selection| {
8194 let cursor = if selection.is_empty() && !line_mode {
8195 movement::right(map, selection.end)
8196 } else {
8197 selection.end
8198 };
8199 selection.collapse_to(cursor, SelectionGoal::None)
8200 });
8201 })
8202 }
8203
8204 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8206 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8207 })
8208 }
8209
8210 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8211 if self.take_rename(true, window, cx).is_some() {
8212 return;
8213 }
8214
8215 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8216 cx.propagate();
8217 return;
8218 }
8219
8220 let text_layout_details = &self.text_layout_details(window);
8221 let selection_count = self.selections.count();
8222 let first_selection = self.selections.first_anchor();
8223
8224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8225 let line_mode = s.line_mode;
8226 s.move_with(|map, selection| {
8227 if !selection.is_empty() && !line_mode {
8228 selection.goal = SelectionGoal::None;
8229 }
8230 let (cursor, goal) = movement::up(
8231 map,
8232 selection.start,
8233 selection.goal,
8234 false,
8235 text_layout_details,
8236 );
8237 selection.collapse_to(cursor, goal);
8238 });
8239 });
8240
8241 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8242 {
8243 cx.propagate();
8244 }
8245 }
8246
8247 pub fn move_up_by_lines(
8248 &mut self,
8249 action: &MoveUpByLines,
8250 window: &mut Window,
8251 cx: &mut Context<Self>,
8252 ) {
8253 if self.take_rename(true, window, cx).is_some() {
8254 return;
8255 }
8256
8257 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8258 cx.propagate();
8259 return;
8260 }
8261
8262 let text_layout_details = &self.text_layout_details(window);
8263
8264 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8265 let line_mode = s.line_mode;
8266 s.move_with(|map, selection| {
8267 if !selection.is_empty() && !line_mode {
8268 selection.goal = SelectionGoal::None;
8269 }
8270 let (cursor, goal) = movement::up_by_rows(
8271 map,
8272 selection.start,
8273 action.lines,
8274 selection.goal,
8275 false,
8276 text_layout_details,
8277 );
8278 selection.collapse_to(cursor, goal);
8279 });
8280 })
8281 }
8282
8283 pub fn move_down_by_lines(
8284 &mut self,
8285 action: &MoveDownByLines,
8286 window: &mut Window,
8287 cx: &mut Context<Self>,
8288 ) {
8289 if self.take_rename(true, window, cx).is_some() {
8290 return;
8291 }
8292
8293 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8294 cx.propagate();
8295 return;
8296 }
8297
8298 let text_layout_details = &self.text_layout_details(window);
8299
8300 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8301 let line_mode = s.line_mode;
8302 s.move_with(|map, selection| {
8303 if !selection.is_empty() && !line_mode {
8304 selection.goal = SelectionGoal::None;
8305 }
8306 let (cursor, goal) = movement::down_by_rows(
8307 map,
8308 selection.start,
8309 action.lines,
8310 selection.goal,
8311 false,
8312 text_layout_details,
8313 );
8314 selection.collapse_to(cursor, goal);
8315 });
8316 })
8317 }
8318
8319 pub fn select_down_by_lines(
8320 &mut self,
8321 action: &SelectDownByLines,
8322 window: &mut Window,
8323 cx: &mut Context<Self>,
8324 ) {
8325 let text_layout_details = &self.text_layout_details(window);
8326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8327 s.move_heads_with(|map, head, goal| {
8328 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8329 })
8330 })
8331 }
8332
8333 pub fn select_up_by_lines(
8334 &mut self,
8335 action: &SelectUpByLines,
8336 window: &mut Window,
8337 cx: &mut Context<Self>,
8338 ) {
8339 let text_layout_details = &self.text_layout_details(window);
8340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8341 s.move_heads_with(|map, head, goal| {
8342 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8343 })
8344 })
8345 }
8346
8347 pub fn select_page_up(
8348 &mut self,
8349 _: &SelectPageUp,
8350 window: &mut Window,
8351 cx: &mut Context<Self>,
8352 ) {
8353 let Some(row_count) = self.visible_row_count() else {
8354 return;
8355 };
8356
8357 let text_layout_details = &self.text_layout_details(window);
8358
8359 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8360 s.move_heads_with(|map, head, goal| {
8361 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8362 })
8363 })
8364 }
8365
8366 pub fn move_page_up(
8367 &mut self,
8368 action: &MovePageUp,
8369 window: &mut Window,
8370 cx: &mut Context<Self>,
8371 ) {
8372 if self.take_rename(true, window, cx).is_some() {
8373 return;
8374 }
8375
8376 if self
8377 .context_menu
8378 .borrow_mut()
8379 .as_mut()
8380 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8381 .unwrap_or(false)
8382 {
8383 return;
8384 }
8385
8386 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8387 cx.propagate();
8388 return;
8389 }
8390
8391 let Some(row_count) = self.visible_row_count() else {
8392 return;
8393 };
8394
8395 let autoscroll = if action.center_cursor {
8396 Autoscroll::center()
8397 } else {
8398 Autoscroll::fit()
8399 };
8400
8401 let text_layout_details = &self.text_layout_details(window);
8402
8403 self.change_selections(Some(autoscroll), window, cx, |s| {
8404 let line_mode = s.line_mode;
8405 s.move_with(|map, selection| {
8406 if !selection.is_empty() && !line_mode {
8407 selection.goal = SelectionGoal::None;
8408 }
8409 let (cursor, goal) = movement::up_by_rows(
8410 map,
8411 selection.end,
8412 row_count,
8413 selection.goal,
8414 false,
8415 text_layout_details,
8416 );
8417 selection.collapse_to(cursor, goal);
8418 });
8419 });
8420 }
8421
8422 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8423 let text_layout_details = &self.text_layout_details(window);
8424 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8425 s.move_heads_with(|map, head, goal| {
8426 movement::up(map, head, goal, false, text_layout_details)
8427 })
8428 })
8429 }
8430
8431 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8432 self.take_rename(true, window, cx);
8433
8434 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8435 cx.propagate();
8436 return;
8437 }
8438
8439 let text_layout_details = &self.text_layout_details(window);
8440 let selection_count = self.selections.count();
8441 let first_selection = self.selections.first_anchor();
8442
8443 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8444 let line_mode = s.line_mode;
8445 s.move_with(|map, selection| {
8446 if !selection.is_empty() && !line_mode {
8447 selection.goal = SelectionGoal::None;
8448 }
8449 let (cursor, goal) = movement::down(
8450 map,
8451 selection.end,
8452 selection.goal,
8453 false,
8454 text_layout_details,
8455 );
8456 selection.collapse_to(cursor, goal);
8457 });
8458 });
8459
8460 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8461 {
8462 cx.propagate();
8463 }
8464 }
8465
8466 pub fn select_page_down(
8467 &mut self,
8468 _: &SelectPageDown,
8469 window: &mut Window,
8470 cx: &mut Context<Self>,
8471 ) {
8472 let Some(row_count) = self.visible_row_count() else {
8473 return;
8474 };
8475
8476 let text_layout_details = &self.text_layout_details(window);
8477
8478 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8479 s.move_heads_with(|map, head, goal| {
8480 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8481 })
8482 })
8483 }
8484
8485 pub fn move_page_down(
8486 &mut self,
8487 action: &MovePageDown,
8488 window: &mut Window,
8489 cx: &mut Context<Self>,
8490 ) {
8491 if self.take_rename(true, window, cx).is_some() {
8492 return;
8493 }
8494
8495 if self
8496 .context_menu
8497 .borrow_mut()
8498 .as_mut()
8499 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8500 .unwrap_or(false)
8501 {
8502 return;
8503 }
8504
8505 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8506 cx.propagate();
8507 return;
8508 }
8509
8510 let Some(row_count) = self.visible_row_count() else {
8511 return;
8512 };
8513
8514 let autoscroll = if action.center_cursor {
8515 Autoscroll::center()
8516 } else {
8517 Autoscroll::fit()
8518 };
8519
8520 let text_layout_details = &self.text_layout_details(window);
8521 self.change_selections(Some(autoscroll), window, cx, |s| {
8522 let line_mode = s.line_mode;
8523 s.move_with(|map, selection| {
8524 if !selection.is_empty() && !line_mode {
8525 selection.goal = SelectionGoal::None;
8526 }
8527 let (cursor, goal) = movement::down_by_rows(
8528 map,
8529 selection.end,
8530 row_count,
8531 selection.goal,
8532 false,
8533 text_layout_details,
8534 );
8535 selection.collapse_to(cursor, goal);
8536 });
8537 });
8538 }
8539
8540 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8541 let text_layout_details = &self.text_layout_details(window);
8542 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8543 s.move_heads_with(|map, head, goal| {
8544 movement::down(map, head, goal, false, text_layout_details)
8545 })
8546 });
8547 }
8548
8549 pub fn context_menu_first(
8550 &mut self,
8551 _: &ContextMenuFirst,
8552 _window: &mut Window,
8553 cx: &mut Context<Self>,
8554 ) {
8555 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8556 context_menu.select_first(self.completion_provider.as_deref(), cx);
8557 }
8558 }
8559
8560 pub fn context_menu_prev(
8561 &mut self,
8562 _: &ContextMenuPrev,
8563 _window: &mut Window,
8564 cx: &mut Context<Self>,
8565 ) {
8566 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8567 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8568 }
8569 }
8570
8571 pub fn context_menu_next(
8572 &mut self,
8573 _: &ContextMenuNext,
8574 _window: &mut Window,
8575 cx: &mut Context<Self>,
8576 ) {
8577 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8578 context_menu.select_next(self.completion_provider.as_deref(), cx);
8579 }
8580 }
8581
8582 pub fn context_menu_last(
8583 &mut self,
8584 _: &ContextMenuLast,
8585 _window: &mut Window,
8586 cx: &mut Context<Self>,
8587 ) {
8588 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8589 context_menu.select_last(self.completion_provider.as_deref(), cx);
8590 }
8591 }
8592
8593 pub fn move_to_previous_word_start(
8594 &mut self,
8595 _: &MoveToPreviousWordStart,
8596 window: &mut Window,
8597 cx: &mut Context<Self>,
8598 ) {
8599 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8600 s.move_cursors_with(|map, head, _| {
8601 (
8602 movement::previous_word_start(map, head),
8603 SelectionGoal::None,
8604 )
8605 });
8606 })
8607 }
8608
8609 pub fn move_to_previous_subword_start(
8610 &mut self,
8611 _: &MoveToPreviousSubwordStart,
8612 window: &mut Window,
8613 cx: &mut Context<Self>,
8614 ) {
8615 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8616 s.move_cursors_with(|map, head, _| {
8617 (
8618 movement::previous_subword_start(map, head),
8619 SelectionGoal::None,
8620 )
8621 });
8622 })
8623 }
8624
8625 pub fn select_to_previous_word_start(
8626 &mut self,
8627 _: &SelectToPreviousWordStart,
8628 window: &mut Window,
8629 cx: &mut Context<Self>,
8630 ) {
8631 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8632 s.move_heads_with(|map, head, _| {
8633 (
8634 movement::previous_word_start(map, head),
8635 SelectionGoal::None,
8636 )
8637 });
8638 })
8639 }
8640
8641 pub fn select_to_previous_subword_start(
8642 &mut self,
8643 _: &SelectToPreviousSubwordStart,
8644 window: &mut Window,
8645 cx: &mut Context<Self>,
8646 ) {
8647 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8648 s.move_heads_with(|map, head, _| {
8649 (
8650 movement::previous_subword_start(map, head),
8651 SelectionGoal::None,
8652 )
8653 });
8654 })
8655 }
8656
8657 pub fn delete_to_previous_word_start(
8658 &mut self,
8659 action: &DeleteToPreviousWordStart,
8660 window: &mut Window,
8661 cx: &mut Context<Self>,
8662 ) {
8663 self.transact(window, cx, |this, window, cx| {
8664 this.select_autoclose_pair(window, cx);
8665 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8666 let line_mode = s.line_mode;
8667 s.move_with(|map, selection| {
8668 if selection.is_empty() && !line_mode {
8669 let cursor = if action.ignore_newlines {
8670 movement::previous_word_start(map, selection.head())
8671 } else {
8672 movement::previous_word_start_or_newline(map, selection.head())
8673 };
8674 selection.set_head(cursor, SelectionGoal::None);
8675 }
8676 });
8677 });
8678 this.insert("", window, cx);
8679 });
8680 }
8681
8682 pub fn delete_to_previous_subword_start(
8683 &mut self,
8684 _: &DeleteToPreviousSubwordStart,
8685 window: &mut Window,
8686 cx: &mut Context<Self>,
8687 ) {
8688 self.transact(window, cx, |this, window, cx| {
8689 this.select_autoclose_pair(window, cx);
8690 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8691 let line_mode = s.line_mode;
8692 s.move_with(|map, selection| {
8693 if selection.is_empty() && !line_mode {
8694 let cursor = movement::previous_subword_start(map, selection.head());
8695 selection.set_head(cursor, SelectionGoal::None);
8696 }
8697 });
8698 });
8699 this.insert("", window, cx);
8700 });
8701 }
8702
8703 pub fn move_to_next_word_end(
8704 &mut self,
8705 _: &MoveToNextWordEnd,
8706 window: &mut Window,
8707 cx: &mut Context<Self>,
8708 ) {
8709 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8710 s.move_cursors_with(|map, head, _| {
8711 (movement::next_word_end(map, head), SelectionGoal::None)
8712 });
8713 })
8714 }
8715
8716 pub fn move_to_next_subword_end(
8717 &mut self,
8718 _: &MoveToNextSubwordEnd,
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_subword_end(map, head), SelectionGoal::None)
8725 });
8726 })
8727 }
8728
8729 pub fn select_to_next_word_end(
8730 &mut self,
8731 _: &SelectToNextWordEnd,
8732 window: &mut Window,
8733 cx: &mut Context<Self>,
8734 ) {
8735 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8736 s.move_heads_with(|map, head, _| {
8737 (movement::next_word_end(map, head), SelectionGoal::None)
8738 });
8739 })
8740 }
8741
8742 pub fn select_to_next_subword_end(
8743 &mut self,
8744 _: &SelectToNextSubwordEnd,
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_subword_end(map, head), SelectionGoal::None)
8751 });
8752 })
8753 }
8754
8755 pub fn delete_to_next_word_end(
8756 &mut self,
8757 action: &DeleteToNextWordEnd,
8758 window: &mut Window,
8759 cx: &mut Context<Self>,
8760 ) {
8761 self.transact(window, cx, |this, window, cx| {
8762 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8763 let line_mode = s.line_mode;
8764 s.move_with(|map, selection| {
8765 if selection.is_empty() && !line_mode {
8766 let cursor = if action.ignore_newlines {
8767 movement::next_word_end(map, selection.head())
8768 } else {
8769 movement::next_word_end_or_newline(map, selection.head())
8770 };
8771 selection.set_head(cursor, SelectionGoal::None);
8772 }
8773 });
8774 });
8775 this.insert("", window, cx);
8776 });
8777 }
8778
8779 pub fn delete_to_next_subword_end(
8780 &mut self,
8781 _: &DeleteToNextSubwordEnd,
8782 window: &mut Window,
8783 cx: &mut Context<Self>,
8784 ) {
8785 self.transact(window, cx, |this, window, cx| {
8786 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8787 s.move_with(|map, selection| {
8788 if selection.is_empty() {
8789 let cursor = movement::next_subword_end(map, selection.head());
8790 selection.set_head(cursor, SelectionGoal::None);
8791 }
8792 });
8793 });
8794 this.insert("", window, cx);
8795 });
8796 }
8797
8798 pub fn move_to_beginning_of_line(
8799 &mut self,
8800 action: &MoveToBeginningOfLine,
8801 window: &mut Window,
8802 cx: &mut Context<Self>,
8803 ) {
8804 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8805 s.move_cursors_with(|map, head, _| {
8806 (
8807 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8808 SelectionGoal::None,
8809 )
8810 });
8811 })
8812 }
8813
8814 pub fn select_to_beginning_of_line(
8815 &mut self,
8816 action: &SelectToBeginningOfLine,
8817 window: &mut Window,
8818 cx: &mut Context<Self>,
8819 ) {
8820 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8821 s.move_heads_with(|map, head, _| {
8822 (
8823 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8824 SelectionGoal::None,
8825 )
8826 });
8827 });
8828 }
8829
8830 pub fn delete_to_beginning_of_line(
8831 &mut self,
8832 _: &DeleteToBeginningOfLine,
8833 window: &mut Window,
8834 cx: &mut Context<Self>,
8835 ) {
8836 self.transact(window, cx, |this, window, cx| {
8837 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8838 s.move_with(|_, selection| {
8839 selection.reversed = true;
8840 });
8841 });
8842
8843 this.select_to_beginning_of_line(
8844 &SelectToBeginningOfLine {
8845 stop_at_soft_wraps: false,
8846 },
8847 window,
8848 cx,
8849 );
8850 this.backspace(&Backspace, window, cx);
8851 });
8852 }
8853
8854 pub fn move_to_end_of_line(
8855 &mut self,
8856 action: &MoveToEndOfLine,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) {
8860 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8861 s.move_cursors_with(|map, head, _| {
8862 (
8863 movement::line_end(map, head, action.stop_at_soft_wraps),
8864 SelectionGoal::None,
8865 )
8866 });
8867 })
8868 }
8869
8870 pub fn select_to_end_of_line(
8871 &mut self,
8872 action: &SelectToEndOfLine,
8873 window: &mut Window,
8874 cx: &mut Context<Self>,
8875 ) {
8876 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8877 s.move_heads_with(|map, head, _| {
8878 (
8879 movement::line_end(map, head, action.stop_at_soft_wraps),
8880 SelectionGoal::None,
8881 )
8882 });
8883 })
8884 }
8885
8886 pub fn delete_to_end_of_line(
8887 &mut self,
8888 _: &DeleteToEndOfLine,
8889 window: &mut Window,
8890 cx: &mut Context<Self>,
8891 ) {
8892 self.transact(window, cx, |this, window, cx| {
8893 this.select_to_end_of_line(
8894 &SelectToEndOfLine {
8895 stop_at_soft_wraps: false,
8896 },
8897 window,
8898 cx,
8899 );
8900 this.delete(&Delete, window, cx);
8901 });
8902 }
8903
8904 pub fn cut_to_end_of_line(
8905 &mut self,
8906 _: &CutToEndOfLine,
8907 window: &mut Window,
8908 cx: &mut Context<Self>,
8909 ) {
8910 self.transact(window, cx, |this, window, cx| {
8911 this.select_to_end_of_line(
8912 &SelectToEndOfLine {
8913 stop_at_soft_wraps: false,
8914 },
8915 window,
8916 cx,
8917 );
8918 this.cut(&Cut, window, cx);
8919 });
8920 }
8921
8922 pub fn move_to_start_of_paragraph(
8923 &mut self,
8924 _: &MoveToStartOfParagraph,
8925 window: &mut Window,
8926 cx: &mut Context<Self>,
8927 ) {
8928 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8929 cx.propagate();
8930 return;
8931 }
8932
8933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8934 s.move_with(|map, selection| {
8935 selection.collapse_to(
8936 movement::start_of_paragraph(map, selection.head(), 1),
8937 SelectionGoal::None,
8938 )
8939 });
8940 })
8941 }
8942
8943 pub fn move_to_end_of_paragraph(
8944 &mut self,
8945 _: &MoveToEndOfParagraph,
8946 window: &mut Window,
8947 cx: &mut Context<Self>,
8948 ) {
8949 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8950 cx.propagate();
8951 return;
8952 }
8953
8954 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8955 s.move_with(|map, selection| {
8956 selection.collapse_to(
8957 movement::end_of_paragraph(map, selection.head(), 1),
8958 SelectionGoal::None,
8959 )
8960 });
8961 })
8962 }
8963
8964 pub fn select_to_start_of_paragraph(
8965 &mut self,
8966 _: &SelectToStartOfParagraph,
8967 window: &mut Window,
8968 cx: &mut Context<Self>,
8969 ) {
8970 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8971 cx.propagate();
8972 return;
8973 }
8974
8975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8976 s.move_heads_with(|map, head, _| {
8977 (
8978 movement::start_of_paragraph(map, head, 1),
8979 SelectionGoal::None,
8980 )
8981 });
8982 })
8983 }
8984
8985 pub fn select_to_end_of_paragraph(
8986 &mut self,
8987 _: &SelectToEndOfParagraph,
8988 window: &mut Window,
8989 cx: &mut Context<Self>,
8990 ) {
8991 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8992 cx.propagate();
8993 return;
8994 }
8995
8996 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8997 s.move_heads_with(|map, head, _| {
8998 (
8999 movement::end_of_paragraph(map, head, 1),
9000 SelectionGoal::None,
9001 )
9002 });
9003 })
9004 }
9005
9006 pub fn move_to_beginning(
9007 &mut self,
9008 _: &MoveToBeginning,
9009 window: &mut Window,
9010 cx: &mut Context<Self>,
9011 ) {
9012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9013 cx.propagate();
9014 return;
9015 }
9016
9017 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9018 s.select_ranges(vec![0..0]);
9019 });
9020 }
9021
9022 pub fn select_to_beginning(
9023 &mut self,
9024 _: &SelectToBeginning,
9025 window: &mut Window,
9026 cx: &mut Context<Self>,
9027 ) {
9028 let mut selection = self.selections.last::<Point>(cx);
9029 selection.set_head(Point::zero(), SelectionGoal::None);
9030
9031 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9032 s.select(vec![selection]);
9033 });
9034 }
9035
9036 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9037 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9038 cx.propagate();
9039 return;
9040 }
9041
9042 let cursor = self.buffer.read(cx).read(cx).len();
9043 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9044 s.select_ranges(vec![cursor..cursor])
9045 });
9046 }
9047
9048 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9049 self.nav_history = nav_history;
9050 }
9051
9052 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9053 self.nav_history.as_ref()
9054 }
9055
9056 fn push_to_nav_history(
9057 &mut self,
9058 cursor_anchor: Anchor,
9059 new_position: Option<Point>,
9060 cx: &mut Context<Self>,
9061 ) {
9062 if let Some(nav_history) = self.nav_history.as_mut() {
9063 let buffer = self.buffer.read(cx).read(cx);
9064 let cursor_position = cursor_anchor.to_point(&buffer);
9065 let scroll_state = self.scroll_manager.anchor();
9066 let scroll_top_row = scroll_state.top_row(&buffer);
9067 drop(buffer);
9068
9069 if let Some(new_position) = new_position {
9070 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9071 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9072 return;
9073 }
9074 }
9075
9076 nav_history.push(
9077 Some(NavigationData {
9078 cursor_anchor,
9079 cursor_position,
9080 scroll_anchor: scroll_state,
9081 scroll_top_row,
9082 }),
9083 cx,
9084 );
9085 }
9086 }
9087
9088 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9089 let buffer = self.buffer.read(cx).snapshot(cx);
9090 let mut selection = self.selections.first::<usize>(cx);
9091 selection.set_head(buffer.len(), SelectionGoal::None);
9092 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9093 s.select(vec![selection]);
9094 });
9095 }
9096
9097 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9098 let end = self.buffer.read(cx).read(cx).len();
9099 self.change_selections(None, window, cx, |s| {
9100 s.select_ranges(vec![0..end]);
9101 });
9102 }
9103
9104 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9106 let mut selections = self.selections.all::<Point>(cx);
9107 let max_point = display_map.buffer_snapshot.max_point();
9108 for selection in &mut selections {
9109 let rows = selection.spanned_rows(true, &display_map);
9110 selection.start = Point::new(rows.start.0, 0);
9111 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9112 selection.reversed = false;
9113 }
9114 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9115 s.select(selections);
9116 });
9117 }
9118
9119 pub fn split_selection_into_lines(
9120 &mut self,
9121 _: &SplitSelectionIntoLines,
9122 window: &mut Window,
9123 cx: &mut Context<Self>,
9124 ) {
9125 let selections = self
9126 .selections
9127 .all::<Point>(cx)
9128 .into_iter()
9129 .map(|selection| selection.start..selection.end)
9130 .collect::<Vec<_>>();
9131 self.unfold_ranges(&selections, true, true, cx);
9132
9133 let mut new_selection_ranges = Vec::new();
9134 {
9135 let buffer = self.buffer.read(cx).read(cx);
9136 for selection in selections {
9137 for row in selection.start.row..selection.end.row {
9138 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9139 new_selection_ranges.push(cursor..cursor);
9140 }
9141
9142 let is_multiline_selection = selection.start.row != selection.end.row;
9143 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9144 // so this action feels more ergonomic when paired with other selection operations
9145 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9146 if !should_skip_last {
9147 new_selection_ranges.push(selection.end..selection.end);
9148 }
9149 }
9150 }
9151 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9152 s.select_ranges(new_selection_ranges);
9153 });
9154 }
9155
9156 pub fn add_selection_above(
9157 &mut self,
9158 _: &AddSelectionAbove,
9159 window: &mut Window,
9160 cx: &mut Context<Self>,
9161 ) {
9162 self.add_selection(true, window, cx);
9163 }
9164
9165 pub fn add_selection_below(
9166 &mut self,
9167 _: &AddSelectionBelow,
9168 window: &mut Window,
9169 cx: &mut Context<Self>,
9170 ) {
9171 self.add_selection(false, window, cx);
9172 }
9173
9174 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9175 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9176 let mut selections = self.selections.all::<Point>(cx);
9177 let text_layout_details = self.text_layout_details(window);
9178 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9179 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9180 let range = oldest_selection.display_range(&display_map).sorted();
9181
9182 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9183 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9184 let positions = start_x.min(end_x)..start_x.max(end_x);
9185
9186 selections.clear();
9187 let mut stack = Vec::new();
9188 for row in range.start.row().0..=range.end.row().0 {
9189 if let Some(selection) = self.selections.build_columnar_selection(
9190 &display_map,
9191 DisplayRow(row),
9192 &positions,
9193 oldest_selection.reversed,
9194 &text_layout_details,
9195 ) {
9196 stack.push(selection.id);
9197 selections.push(selection);
9198 }
9199 }
9200
9201 if above {
9202 stack.reverse();
9203 }
9204
9205 AddSelectionsState { above, stack }
9206 });
9207
9208 let last_added_selection = *state.stack.last().unwrap();
9209 let mut new_selections = Vec::new();
9210 if above == state.above {
9211 let end_row = if above {
9212 DisplayRow(0)
9213 } else {
9214 display_map.max_point().row()
9215 };
9216
9217 'outer: for selection in selections {
9218 if selection.id == last_added_selection {
9219 let range = selection.display_range(&display_map).sorted();
9220 debug_assert_eq!(range.start.row(), range.end.row());
9221 let mut row = range.start.row();
9222 let positions =
9223 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9224 px(start)..px(end)
9225 } else {
9226 let start_x =
9227 display_map.x_for_display_point(range.start, &text_layout_details);
9228 let end_x =
9229 display_map.x_for_display_point(range.end, &text_layout_details);
9230 start_x.min(end_x)..start_x.max(end_x)
9231 };
9232
9233 while row != end_row {
9234 if above {
9235 row.0 -= 1;
9236 } else {
9237 row.0 += 1;
9238 }
9239
9240 if let Some(new_selection) = self.selections.build_columnar_selection(
9241 &display_map,
9242 row,
9243 &positions,
9244 selection.reversed,
9245 &text_layout_details,
9246 ) {
9247 state.stack.push(new_selection.id);
9248 if above {
9249 new_selections.push(new_selection);
9250 new_selections.push(selection);
9251 } else {
9252 new_selections.push(selection);
9253 new_selections.push(new_selection);
9254 }
9255
9256 continue 'outer;
9257 }
9258 }
9259 }
9260
9261 new_selections.push(selection);
9262 }
9263 } else {
9264 new_selections = selections;
9265 new_selections.retain(|s| s.id != last_added_selection);
9266 state.stack.pop();
9267 }
9268
9269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9270 s.select(new_selections);
9271 });
9272 if state.stack.len() > 1 {
9273 self.add_selections_state = Some(state);
9274 }
9275 }
9276
9277 pub fn select_next_match_internal(
9278 &mut self,
9279 display_map: &DisplaySnapshot,
9280 replace_newest: bool,
9281 autoscroll: Option<Autoscroll>,
9282 window: &mut Window,
9283 cx: &mut Context<Self>,
9284 ) -> Result<()> {
9285 fn select_next_match_ranges(
9286 this: &mut Editor,
9287 range: Range<usize>,
9288 replace_newest: bool,
9289 auto_scroll: Option<Autoscroll>,
9290 window: &mut Window,
9291 cx: &mut Context<Editor>,
9292 ) {
9293 this.unfold_ranges(&[range.clone()], false, true, cx);
9294 this.change_selections(auto_scroll, window, cx, |s| {
9295 if replace_newest {
9296 s.delete(s.newest_anchor().id);
9297 }
9298 s.insert_range(range.clone());
9299 });
9300 }
9301
9302 let buffer = &display_map.buffer_snapshot;
9303 let mut selections = self.selections.all::<usize>(cx);
9304 if let Some(mut select_next_state) = self.select_next_state.take() {
9305 let query = &select_next_state.query;
9306 if !select_next_state.done {
9307 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9308 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9309 let mut next_selected_range = None;
9310
9311 let bytes_after_last_selection =
9312 buffer.bytes_in_range(last_selection.end..buffer.len());
9313 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9314 let query_matches = query
9315 .stream_find_iter(bytes_after_last_selection)
9316 .map(|result| (last_selection.end, result))
9317 .chain(
9318 query
9319 .stream_find_iter(bytes_before_first_selection)
9320 .map(|result| (0, result)),
9321 );
9322
9323 for (start_offset, query_match) in query_matches {
9324 let query_match = query_match.unwrap(); // can only fail due to I/O
9325 let offset_range =
9326 start_offset + query_match.start()..start_offset + query_match.end();
9327 let display_range = offset_range.start.to_display_point(display_map)
9328 ..offset_range.end.to_display_point(display_map);
9329
9330 if !select_next_state.wordwise
9331 || (!movement::is_inside_word(display_map, display_range.start)
9332 && !movement::is_inside_word(display_map, display_range.end))
9333 {
9334 // TODO: This is n^2, because we might check all the selections
9335 if !selections
9336 .iter()
9337 .any(|selection| selection.range().overlaps(&offset_range))
9338 {
9339 next_selected_range = Some(offset_range);
9340 break;
9341 }
9342 }
9343 }
9344
9345 if let Some(next_selected_range) = next_selected_range {
9346 select_next_match_ranges(
9347 self,
9348 next_selected_range,
9349 replace_newest,
9350 autoscroll,
9351 window,
9352 cx,
9353 );
9354 } else {
9355 select_next_state.done = true;
9356 }
9357 }
9358
9359 self.select_next_state = Some(select_next_state);
9360 } else {
9361 let mut only_carets = true;
9362 let mut same_text_selected = true;
9363 let mut selected_text = None;
9364
9365 let mut selections_iter = selections.iter().peekable();
9366 while let Some(selection) = selections_iter.next() {
9367 if selection.start != selection.end {
9368 only_carets = false;
9369 }
9370
9371 if same_text_selected {
9372 if selected_text.is_none() {
9373 selected_text =
9374 Some(buffer.text_for_range(selection.range()).collect::<String>());
9375 }
9376
9377 if let Some(next_selection) = selections_iter.peek() {
9378 if next_selection.range().len() == selection.range().len() {
9379 let next_selected_text = buffer
9380 .text_for_range(next_selection.range())
9381 .collect::<String>();
9382 if Some(next_selected_text) != selected_text {
9383 same_text_selected = false;
9384 selected_text = None;
9385 }
9386 } else {
9387 same_text_selected = false;
9388 selected_text = None;
9389 }
9390 }
9391 }
9392 }
9393
9394 if only_carets {
9395 for selection in &mut selections {
9396 let word_range = movement::surrounding_word(
9397 display_map,
9398 selection.start.to_display_point(display_map),
9399 );
9400 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9401 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9402 selection.goal = SelectionGoal::None;
9403 selection.reversed = false;
9404 select_next_match_ranges(
9405 self,
9406 selection.start..selection.end,
9407 replace_newest,
9408 autoscroll,
9409 window,
9410 cx,
9411 );
9412 }
9413
9414 if selections.len() == 1 {
9415 let selection = selections
9416 .last()
9417 .expect("ensured that there's only one selection");
9418 let query = buffer
9419 .text_for_range(selection.start..selection.end)
9420 .collect::<String>();
9421 let is_empty = query.is_empty();
9422 let select_state = SelectNextState {
9423 query: AhoCorasick::new(&[query])?,
9424 wordwise: true,
9425 done: is_empty,
9426 };
9427 self.select_next_state = Some(select_state);
9428 } else {
9429 self.select_next_state = None;
9430 }
9431 } else if let Some(selected_text) = selected_text {
9432 self.select_next_state = Some(SelectNextState {
9433 query: AhoCorasick::new(&[selected_text])?,
9434 wordwise: false,
9435 done: false,
9436 });
9437 self.select_next_match_internal(
9438 display_map,
9439 replace_newest,
9440 autoscroll,
9441 window,
9442 cx,
9443 )?;
9444 }
9445 }
9446 Ok(())
9447 }
9448
9449 pub fn select_all_matches(
9450 &mut self,
9451 _action: &SelectAllMatches,
9452 window: &mut Window,
9453 cx: &mut Context<Self>,
9454 ) -> Result<()> {
9455 self.push_to_selection_history();
9456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9457
9458 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9459 let Some(select_next_state) = self.select_next_state.as_mut() else {
9460 return Ok(());
9461 };
9462 if select_next_state.done {
9463 return Ok(());
9464 }
9465
9466 let mut new_selections = self.selections.all::<usize>(cx);
9467
9468 let buffer = &display_map.buffer_snapshot;
9469 let query_matches = select_next_state
9470 .query
9471 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9472
9473 for query_match in query_matches {
9474 let query_match = query_match.unwrap(); // can only fail due to I/O
9475 let offset_range = query_match.start()..query_match.end();
9476 let display_range = offset_range.start.to_display_point(&display_map)
9477 ..offset_range.end.to_display_point(&display_map);
9478
9479 if !select_next_state.wordwise
9480 || (!movement::is_inside_word(&display_map, display_range.start)
9481 && !movement::is_inside_word(&display_map, display_range.end))
9482 {
9483 self.selections.change_with(cx, |selections| {
9484 new_selections.push(Selection {
9485 id: selections.new_selection_id(),
9486 start: offset_range.start,
9487 end: offset_range.end,
9488 reversed: false,
9489 goal: SelectionGoal::None,
9490 });
9491 });
9492 }
9493 }
9494
9495 new_selections.sort_by_key(|selection| selection.start);
9496 let mut ix = 0;
9497 while ix + 1 < new_selections.len() {
9498 let current_selection = &new_selections[ix];
9499 let next_selection = &new_selections[ix + 1];
9500 if current_selection.range().overlaps(&next_selection.range()) {
9501 if current_selection.id < next_selection.id {
9502 new_selections.remove(ix + 1);
9503 } else {
9504 new_selections.remove(ix);
9505 }
9506 } else {
9507 ix += 1;
9508 }
9509 }
9510
9511 let reversed = self.selections.oldest::<usize>(cx).reversed;
9512
9513 for selection in new_selections.iter_mut() {
9514 selection.reversed = reversed;
9515 }
9516
9517 select_next_state.done = true;
9518 self.unfold_ranges(
9519 &new_selections
9520 .iter()
9521 .map(|selection| selection.range())
9522 .collect::<Vec<_>>(),
9523 false,
9524 false,
9525 cx,
9526 );
9527 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9528 selections.select(new_selections)
9529 });
9530
9531 Ok(())
9532 }
9533
9534 pub fn select_next(
9535 &mut self,
9536 action: &SelectNext,
9537 window: &mut Window,
9538 cx: &mut Context<Self>,
9539 ) -> Result<()> {
9540 self.push_to_selection_history();
9541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9542 self.select_next_match_internal(
9543 &display_map,
9544 action.replace_newest,
9545 Some(Autoscroll::newest()),
9546 window,
9547 cx,
9548 )?;
9549 Ok(())
9550 }
9551
9552 pub fn select_previous(
9553 &mut self,
9554 action: &SelectPrevious,
9555 window: &mut Window,
9556 cx: &mut Context<Self>,
9557 ) -> Result<()> {
9558 self.push_to_selection_history();
9559 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9560 let buffer = &display_map.buffer_snapshot;
9561 let mut selections = self.selections.all::<usize>(cx);
9562 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9563 let query = &select_prev_state.query;
9564 if !select_prev_state.done {
9565 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9566 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9567 let mut next_selected_range = None;
9568 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9569 let bytes_before_last_selection =
9570 buffer.reversed_bytes_in_range(0..last_selection.start);
9571 let bytes_after_first_selection =
9572 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9573 let query_matches = query
9574 .stream_find_iter(bytes_before_last_selection)
9575 .map(|result| (last_selection.start, result))
9576 .chain(
9577 query
9578 .stream_find_iter(bytes_after_first_selection)
9579 .map(|result| (buffer.len(), result)),
9580 );
9581 for (end_offset, query_match) in query_matches {
9582 let query_match = query_match.unwrap(); // can only fail due to I/O
9583 let offset_range =
9584 end_offset - query_match.end()..end_offset - query_match.start();
9585 let display_range = offset_range.start.to_display_point(&display_map)
9586 ..offset_range.end.to_display_point(&display_map);
9587
9588 if !select_prev_state.wordwise
9589 || (!movement::is_inside_word(&display_map, display_range.start)
9590 && !movement::is_inside_word(&display_map, display_range.end))
9591 {
9592 next_selected_range = Some(offset_range);
9593 break;
9594 }
9595 }
9596
9597 if let Some(next_selected_range) = next_selected_range {
9598 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9599 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9600 if action.replace_newest {
9601 s.delete(s.newest_anchor().id);
9602 }
9603 s.insert_range(next_selected_range);
9604 });
9605 } else {
9606 select_prev_state.done = true;
9607 }
9608 }
9609
9610 self.select_prev_state = Some(select_prev_state);
9611 } else {
9612 let mut only_carets = true;
9613 let mut same_text_selected = true;
9614 let mut selected_text = None;
9615
9616 let mut selections_iter = selections.iter().peekable();
9617 while let Some(selection) = selections_iter.next() {
9618 if selection.start != selection.end {
9619 only_carets = false;
9620 }
9621
9622 if same_text_selected {
9623 if selected_text.is_none() {
9624 selected_text =
9625 Some(buffer.text_for_range(selection.range()).collect::<String>());
9626 }
9627
9628 if let Some(next_selection) = selections_iter.peek() {
9629 if next_selection.range().len() == selection.range().len() {
9630 let next_selected_text = buffer
9631 .text_for_range(next_selection.range())
9632 .collect::<String>();
9633 if Some(next_selected_text) != selected_text {
9634 same_text_selected = false;
9635 selected_text = None;
9636 }
9637 } else {
9638 same_text_selected = false;
9639 selected_text = None;
9640 }
9641 }
9642 }
9643 }
9644
9645 if only_carets {
9646 for selection in &mut selections {
9647 let word_range = movement::surrounding_word(
9648 &display_map,
9649 selection.start.to_display_point(&display_map),
9650 );
9651 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9652 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9653 selection.goal = SelectionGoal::None;
9654 selection.reversed = false;
9655 }
9656 if selections.len() == 1 {
9657 let selection = selections
9658 .last()
9659 .expect("ensured that there's only one selection");
9660 let query = buffer
9661 .text_for_range(selection.start..selection.end)
9662 .collect::<String>();
9663 let is_empty = query.is_empty();
9664 let select_state = SelectNextState {
9665 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9666 wordwise: true,
9667 done: is_empty,
9668 };
9669 self.select_prev_state = Some(select_state);
9670 } else {
9671 self.select_prev_state = None;
9672 }
9673
9674 self.unfold_ranges(
9675 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9676 false,
9677 true,
9678 cx,
9679 );
9680 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9681 s.select(selections);
9682 });
9683 } else if let Some(selected_text) = selected_text {
9684 self.select_prev_state = Some(SelectNextState {
9685 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9686 wordwise: false,
9687 done: false,
9688 });
9689 self.select_previous(action, window, cx)?;
9690 }
9691 }
9692 Ok(())
9693 }
9694
9695 pub fn toggle_comments(
9696 &mut self,
9697 action: &ToggleComments,
9698 window: &mut Window,
9699 cx: &mut Context<Self>,
9700 ) {
9701 if self.read_only(cx) {
9702 return;
9703 }
9704 let text_layout_details = &self.text_layout_details(window);
9705 self.transact(window, cx, |this, window, cx| {
9706 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9707 let mut edits = Vec::new();
9708 let mut selection_edit_ranges = Vec::new();
9709 let mut last_toggled_row = None;
9710 let snapshot = this.buffer.read(cx).read(cx);
9711 let empty_str: Arc<str> = Arc::default();
9712 let mut suffixes_inserted = Vec::new();
9713 let ignore_indent = action.ignore_indent;
9714
9715 fn comment_prefix_range(
9716 snapshot: &MultiBufferSnapshot,
9717 row: MultiBufferRow,
9718 comment_prefix: &str,
9719 comment_prefix_whitespace: &str,
9720 ignore_indent: bool,
9721 ) -> Range<Point> {
9722 let indent_size = if ignore_indent {
9723 0
9724 } else {
9725 snapshot.indent_size_for_line(row).len
9726 };
9727
9728 let start = Point::new(row.0, indent_size);
9729
9730 let mut line_bytes = snapshot
9731 .bytes_in_range(start..snapshot.max_point())
9732 .flatten()
9733 .copied();
9734
9735 // If this line currently begins with the line comment prefix, then record
9736 // the range containing the prefix.
9737 if line_bytes
9738 .by_ref()
9739 .take(comment_prefix.len())
9740 .eq(comment_prefix.bytes())
9741 {
9742 // Include any whitespace that matches the comment prefix.
9743 let matching_whitespace_len = line_bytes
9744 .zip(comment_prefix_whitespace.bytes())
9745 .take_while(|(a, b)| a == b)
9746 .count() as u32;
9747 let end = Point::new(
9748 start.row,
9749 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9750 );
9751 start..end
9752 } else {
9753 start..start
9754 }
9755 }
9756
9757 fn comment_suffix_range(
9758 snapshot: &MultiBufferSnapshot,
9759 row: MultiBufferRow,
9760 comment_suffix: &str,
9761 comment_suffix_has_leading_space: bool,
9762 ) -> Range<Point> {
9763 let end = Point::new(row.0, snapshot.line_len(row));
9764 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9765
9766 let mut line_end_bytes = snapshot
9767 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9768 .flatten()
9769 .copied();
9770
9771 let leading_space_len = if suffix_start_column > 0
9772 && line_end_bytes.next() == Some(b' ')
9773 && comment_suffix_has_leading_space
9774 {
9775 1
9776 } else {
9777 0
9778 };
9779
9780 // If this line currently begins with the line comment prefix, then record
9781 // the range containing the prefix.
9782 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9783 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9784 start..end
9785 } else {
9786 end..end
9787 }
9788 }
9789
9790 // TODO: Handle selections that cross excerpts
9791 for selection in &mut selections {
9792 let start_column = snapshot
9793 .indent_size_for_line(MultiBufferRow(selection.start.row))
9794 .len;
9795 let language = if let Some(language) =
9796 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9797 {
9798 language
9799 } else {
9800 continue;
9801 };
9802
9803 selection_edit_ranges.clear();
9804
9805 // If multiple selections contain a given row, avoid processing that
9806 // row more than once.
9807 let mut start_row = MultiBufferRow(selection.start.row);
9808 if last_toggled_row == Some(start_row) {
9809 start_row = start_row.next_row();
9810 }
9811 let end_row =
9812 if selection.end.row > selection.start.row && selection.end.column == 0 {
9813 MultiBufferRow(selection.end.row - 1)
9814 } else {
9815 MultiBufferRow(selection.end.row)
9816 };
9817 last_toggled_row = Some(end_row);
9818
9819 if start_row > end_row {
9820 continue;
9821 }
9822
9823 // If the language has line comments, toggle those.
9824 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9825
9826 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9827 if ignore_indent {
9828 full_comment_prefixes = full_comment_prefixes
9829 .into_iter()
9830 .map(|s| Arc::from(s.trim_end()))
9831 .collect();
9832 }
9833
9834 if !full_comment_prefixes.is_empty() {
9835 let first_prefix = full_comment_prefixes
9836 .first()
9837 .expect("prefixes is non-empty");
9838 let prefix_trimmed_lengths = full_comment_prefixes
9839 .iter()
9840 .map(|p| p.trim_end_matches(' ').len())
9841 .collect::<SmallVec<[usize; 4]>>();
9842
9843 let mut all_selection_lines_are_comments = true;
9844
9845 for row in start_row.0..=end_row.0 {
9846 let row = MultiBufferRow(row);
9847 if start_row < end_row && snapshot.is_line_blank(row) {
9848 continue;
9849 }
9850
9851 let prefix_range = full_comment_prefixes
9852 .iter()
9853 .zip(prefix_trimmed_lengths.iter().copied())
9854 .map(|(prefix, trimmed_prefix_len)| {
9855 comment_prefix_range(
9856 snapshot.deref(),
9857 row,
9858 &prefix[..trimmed_prefix_len],
9859 &prefix[trimmed_prefix_len..],
9860 ignore_indent,
9861 )
9862 })
9863 .max_by_key(|range| range.end.column - range.start.column)
9864 .expect("prefixes is non-empty");
9865
9866 if prefix_range.is_empty() {
9867 all_selection_lines_are_comments = false;
9868 }
9869
9870 selection_edit_ranges.push(prefix_range);
9871 }
9872
9873 if all_selection_lines_are_comments {
9874 edits.extend(
9875 selection_edit_ranges
9876 .iter()
9877 .cloned()
9878 .map(|range| (range, empty_str.clone())),
9879 );
9880 } else {
9881 let min_column = selection_edit_ranges
9882 .iter()
9883 .map(|range| range.start.column)
9884 .min()
9885 .unwrap_or(0);
9886 edits.extend(selection_edit_ranges.iter().map(|range| {
9887 let position = Point::new(range.start.row, min_column);
9888 (position..position, first_prefix.clone())
9889 }));
9890 }
9891 } else if let Some((full_comment_prefix, comment_suffix)) =
9892 language.block_comment_delimiters()
9893 {
9894 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9895 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9896 let prefix_range = comment_prefix_range(
9897 snapshot.deref(),
9898 start_row,
9899 comment_prefix,
9900 comment_prefix_whitespace,
9901 ignore_indent,
9902 );
9903 let suffix_range = comment_suffix_range(
9904 snapshot.deref(),
9905 end_row,
9906 comment_suffix.trim_start_matches(' '),
9907 comment_suffix.starts_with(' '),
9908 );
9909
9910 if prefix_range.is_empty() || suffix_range.is_empty() {
9911 edits.push((
9912 prefix_range.start..prefix_range.start,
9913 full_comment_prefix.clone(),
9914 ));
9915 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9916 suffixes_inserted.push((end_row, comment_suffix.len()));
9917 } else {
9918 edits.push((prefix_range, empty_str.clone()));
9919 edits.push((suffix_range, empty_str.clone()));
9920 }
9921 } else {
9922 continue;
9923 }
9924 }
9925
9926 drop(snapshot);
9927 this.buffer.update(cx, |buffer, cx| {
9928 buffer.edit(edits, None, cx);
9929 });
9930
9931 // Adjust selections so that they end before any comment suffixes that
9932 // were inserted.
9933 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9934 let mut selections = this.selections.all::<Point>(cx);
9935 let snapshot = this.buffer.read(cx).read(cx);
9936 for selection in &mut selections {
9937 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9938 match row.cmp(&MultiBufferRow(selection.end.row)) {
9939 Ordering::Less => {
9940 suffixes_inserted.next();
9941 continue;
9942 }
9943 Ordering::Greater => break,
9944 Ordering::Equal => {
9945 if selection.end.column == snapshot.line_len(row) {
9946 if selection.is_empty() {
9947 selection.start.column -= suffix_len as u32;
9948 }
9949 selection.end.column -= suffix_len as u32;
9950 }
9951 break;
9952 }
9953 }
9954 }
9955 }
9956
9957 drop(snapshot);
9958 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9959 s.select(selections)
9960 });
9961
9962 let selections = this.selections.all::<Point>(cx);
9963 let selections_on_single_row = selections.windows(2).all(|selections| {
9964 selections[0].start.row == selections[1].start.row
9965 && selections[0].end.row == selections[1].end.row
9966 && selections[0].start.row == selections[0].end.row
9967 });
9968 let selections_selecting = selections
9969 .iter()
9970 .any(|selection| selection.start != selection.end);
9971 let advance_downwards = action.advance_downwards
9972 && selections_on_single_row
9973 && !selections_selecting
9974 && !matches!(this.mode, EditorMode::SingleLine { .. });
9975
9976 if advance_downwards {
9977 let snapshot = this.buffer.read(cx).snapshot(cx);
9978
9979 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9980 s.move_cursors_with(|display_snapshot, display_point, _| {
9981 let mut point = display_point.to_point(display_snapshot);
9982 point.row += 1;
9983 point = snapshot.clip_point(point, Bias::Left);
9984 let display_point = point.to_display_point(display_snapshot);
9985 let goal = SelectionGoal::HorizontalPosition(
9986 display_snapshot
9987 .x_for_display_point(display_point, text_layout_details)
9988 .into(),
9989 );
9990 (display_point, goal)
9991 })
9992 });
9993 }
9994 });
9995 }
9996
9997 pub fn select_enclosing_symbol(
9998 &mut self,
9999 _: &SelectEnclosingSymbol,
10000 window: &mut Window,
10001 cx: &mut Context<Self>,
10002 ) {
10003 let buffer = self.buffer.read(cx).snapshot(cx);
10004 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10005
10006 fn update_selection(
10007 selection: &Selection<usize>,
10008 buffer_snap: &MultiBufferSnapshot,
10009 ) -> Option<Selection<usize>> {
10010 let cursor = selection.head();
10011 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10012 for symbol in symbols.iter().rev() {
10013 let start = symbol.range.start.to_offset(buffer_snap);
10014 let end = symbol.range.end.to_offset(buffer_snap);
10015 let new_range = start..end;
10016 if start < selection.start || end > selection.end {
10017 return Some(Selection {
10018 id: selection.id,
10019 start: new_range.start,
10020 end: new_range.end,
10021 goal: SelectionGoal::None,
10022 reversed: selection.reversed,
10023 });
10024 }
10025 }
10026 None
10027 }
10028
10029 let mut selected_larger_symbol = false;
10030 let new_selections = old_selections
10031 .iter()
10032 .map(|selection| match update_selection(selection, &buffer) {
10033 Some(new_selection) => {
10034 if new_selection.range() != selection.range() {
10035 selected_larger_symbol = true;
10036 }
10037 new_selection
10038 }
10039 None => selection.clone(),
10040 })
10041 .collect::<Vec<_>>();
10042
10043 if selected_larger_symbol {
10044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10045 s.select(new_selections);
10046 });
10047 }
10048 }
10049
10050 pub fn select_larger_syntax_node(
10051 &mut self,
10052 _: &SelectLargerSyntaxNode,
10053 window: &mut Window,
10054 cx: &mut Context<Self>,
10055 ) {
10056 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10057 let buffer = self.buffer.read(cx).snapshot(cx);
10058 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10059
10060 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10061 let mut selected_larger_node = false;
10062 let new_selections = old_selections
10063 .iter()
10064 .map(|selection| {
10065 let old_range = selection.start..selection.end;
10066 let mut new_range = old_range.clone();
10067 let mut new_node = None;
10068 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10069 {
10070 new_node = Some(node);
10071 new_range = containing_range;
10072 if !display_map.intersects_fold(new_range.start)
10073 && !display_map.intersects_fold(new_range.end)
10074 {
10075 break;
10076 }
10077 }
10078
10079 if let Some(node) = new_node {
10080 // Log the ancestor, to support using this action as a way to explore TreeSitter
10081 // nodes. Parent and grandparent are also logged because this operation will not
10082 // visit nodes that have the same range as their parent.
10083 log::info!("Node: {node:?}");
10084 let parent = node.parent();
10085 log::info!("Parent: {parent:?}");
10086 let grandparent = parent.and_then(|x| x.parent());
10087 log::info!("Grandparent: {grandparent:?}");
10088 }
10089
10090 selected_larger_node |= new_range != old_range;
10091 Selection {
10092 id: selection.id,
10093 start: new_range.start,
10094 end: new_range.end,
10095 goal: SelectionGoal::None,
10096 reversed: selection.reversed,
10097 }
10098 })
10099 .collect::<Vec<_>>();
10100
10101 if selected_larger_node {
10102 stack.push(old_selections);
10103 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10104 s.select(new_selections);
10105 });
10106 }
10107 self.select_larger_syntax_node_stack = stack;
10108 }
10109
10110 pub fn select_smaller_syntax_node(
10111 &mut self,
10112 _: &SelectSmallerSyntaxNode,
10113 window: &mut Window,
10114 cx: &mut Context<Self>,
10115 ) {
10116 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10117 if let Some(selections) = stack.pop() {
10118 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10119 s.select(selections.to_vec());
10120 });
10121 }
10122 self.select_larger_syntax_node_stack = stack;
10123 }
10124
10125 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10126 if !EditorSettings::get_global(cx).gutter.runnables {
10127 self.clear_tasks();
10128 return Task::ready(());
10129 }
10130 let project = self.project.as_ref().map(Entity::downgrade);
10131 cx.spawn_in(window, |this, mut cx| async move {
10132 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10133 let Some(project) = project.and_then(|p| p.upgrade()) else {
10134 return;
10135 };
10136 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10137 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10138 }) else {
10139 return;
10140 };
10141
10142 let hide_runnables = project
10143 .update(&mut cx, |project, cx| {
10144 // Do not display any test indicators in non-dev server remote projects.
10145 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10146 })
10147 .unwrap_or(true);
10148 if hide_runnables {
10149 return;
10150 }
10151 let new_rows =
10152 cx.background_spawn({
10153 let snapshot = display_snapshot.clone();
10154 async move {
10155 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10156 }
10157 })
10158 .await;
10159
10160 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10161 this.update(&mut cx, |this, _| {
10162 this.clear_tasks();
10163 for (key, value) in rows {
10164 this.insert_tasks(key, value);
10165 }
10166 })
10167 .ok();
10168 })
10169 }
10170 fn fetch_runnable_ranges(
10171 snapshot: &DisplaySnapshot,
10172 range: Range<Anchor>,
10173 ) -> Vec<language::RunnableRange> {
10174 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10175 }
10176
10177 fn runnable_rows(
10178 project: Entity<Project>,
10179 snapshot: DisplaySnapshot,
10180 runnable_ranges: Vec<RunnableRange>,
10181 mut cx: AsyncWindowContext,
10182 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10183 runnable_ranges
10184 .into_iter()
10185 .filter_map(|mut runnable| {
10186 let tasks = cx
10187 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10188 .ok()?;
10189 if tasks.is_empty() {
10190 return None;
10191 }
10192
10193 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10194
10195 let row = snapshot
10196 .buffer_snapshot
10197 .buffer_line_for_row(MultiBufferRow(point.row))?
10198 .1
10199 .start
10200 .row;
10201
10202 let context_range =
10203 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10204 Some((
10205 (runnable.buffer_id, row),
10206 RunnableTasks {
10207 templates: tasks,
10208 offset: MultiBufferOffset(runnable.run_range.start),
10209 context_range,
10210 column: point.column,
10211 extra_variables: runnable.extra_captures,
10212 },
10213 ))
10214 })
10215 .collect()
10216 }
10217
10218 fn templates_with_tags(
10219 project: &Entity<Project>,
10220 runnable: &mut Runnable,
10221 cx: &mut App,
10222 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10223 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10224 let (worktree_id, file) = project
10225 .buffer_for_id(runnable.buffer, cx)
10226 .and_then(|buffer| buffer.read(cx).file())
10227 .map(|file| (file.worktree_id(cx), file.clone()))
10228 .unzip();
10229
10230 (
10231 project.task_store().read(cx).task_inventory().cloned(),
10232 worktree_id,
10233 file,
10234 )
10235 });
10236
10237 let tags = mem::take(&mut runnable.tags);
10238 let mut tags: Vec<_> = tags
10239 .into_iter()
10240 .flat_map(|tag| {
10241 let tag = tag.0.clone();
10242 inventory
10243 .as_ref()
10244 .into_iter()
10245 .flat_map(|inventory| {
10246 inventory.read(cx).list_tasks(
10247 file.clone(),
10248 Some(runnable.language.clone()),
10249 worktree_id,
10250 cx,
10251 )
10252 })
10253 .filter(move |(_, template)| {
10254 template.tags.iter().any(|source_tag| source_tag == &tag)
10255 })
10256 })
10257 .sorted_by_key(|(kind, _)| kind.to_owned())
10258 .collect();
10259 if let Some((leading_tag_source, _)) = tags.first() {
10260 // Strongest source wins; if we have worktree tag binding, prefer that to
10261 // global and language bindings;
10262 // if we have a global binding, prefer that to language binding.
10263 let first_mismatch = tags
10264 .iter()
10265 .position(|(tag_source, _)| tag_source != leading_tag_source);
10266 if let Some(index) = first_mismatch {
10267 tags.truncate(index);
10268 }
10269 }
10270
10271 tags
10272 }
10273
10274 pub fn move_to_enclosing_bracket(
10275 &mut self,
10276 _: &MoveToEnclosingBracket,
10277 window: &mut Window,
10278 cx: &mut Context<Self>,
10279 ) {
10280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10281 s.move_offsets_with(|snapshot, selection| {
10282 let Some(enclosing_bracket_ranges) =
10283 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10284 else {
10285 return;
10286 };
10287
10288 let mut best_length = usize::MAX;
10289 let mut best_inside = false;
10290 let mut best_in_bracket_range = false;
10291 let mut best_destination = None;
10292 for (open, close) in enclosing_bracket_ranges {
10293 let close = close.to_inclusive();
10294 let length = close.end() - open.start;
10295 let inside = selection.start >= open.end && selection.end <= *close.start();
10296 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10297 || close.contains(&selection.head());
10298
10299 // If best is next to a bracket and current isn't, skip
10300 if !in_bracket_range && best_in_bracket_range {
10301 continue;
10302 }
10303
10304 // Prefer smaller lengths unless best is inside and current isn't
10305 if length > best_length && (best_inside || !inside) {
10306 continue;
10307 }
10308
10309 best_length = length;
10310 best_inside = inside;
10311 best_in_bracket_range = in_bracket_range;
10312 best_destination = Some(
10313 if close.contains(&selection.start) && close.contains(&selection.end) {
10314 if inside {
10315 open.end
10316 } else {
10317 open.start
10318 }
10319 } else if inside {
10320 *close.start()
10321 } else {
10322 *close.end()
10323 },
10324 );
10325 }
10326
10327 if let Some(destination) = best_destination {
10328 selection.collapse_to(destination, SelectionGoal::None);
10329 }
10330 })
10331 });
10332 }
10333
10334 pub fn undo_selection(
10335 &mut self,
10336 _: &UndoSelection,
10337 window: &mut Window,
10338 cx: &mut Context<Self>,
10339 ) {
10340 self.end_selection(window, cx);
10341 self.selection_history.mode = SelectionHistoryMode::Undoing;
10342 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10343 self.change_selections(None, window, cx, |s| {
10344 s.select_anchors(entry.selections.to_vec())
10345 });
10346 self.select_next_state = entry.select_next_state;
10347 self.select_prev_state = entry.select_prev_state;
10348 self.add_selections_state = entry.add_selections_state;
10349 self.request_autoscroll(Autoscroll::newest(), cx);
10350 }
10351 self.selection_history.mode = SelectionHistoryMode::Normal;
10352 }
10353
10354 pub fn redo_selection(
10355 &mut self,
10356 _: &RedoSelection,
10357 window: &mut Window,
10358 cx: &mut Context<Self>,
10359 ) {
10360 self.end_selection(window, cx);
10361 self.selection_history.mode = SelectionHistoryMode::Redoing;
10362 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10363 self.change_selections(None, window, cx, |s| {
10364 s.select_anchors(entry.selections.to_vec())
10365 });
10366 self.select_next_state = entry.select_next_state;
10367 self.select_prev_state = entry.select_prev_state;
10368 self.add_selections_state = entry.add_selections_state;
10369 self.request_autoscroll(Autoscroll::newest(), cx);
10370 }
10371 self.selection_history.mode = SelectionHistoryMode::Normal;
10372 }
10373
10374 pub fn expand_excerpts(
10375 &mut self,
10376 action: &ExpandExcerpts,
10377 _: &mut Window,
10378 cx: &mut Context<Self>,
10379 ) {
10380 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10381 }
10382
10383 pub fn expand_excerpts_down(
10384 &mut self,
10385 action: &ExpandExcerptsDown,
10386 _: &mut Window,
10387 cx: &mut Context<Self>,
10388 ) {
10389 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10390 }
10391
10392 pub fn expand_excerpts_up(
10393 &mut self,
10394 action: &ExpandExcerptsUp,
10395 _: &mut Window,
10396 cx: &mut Context<Self>,
10397 ) {
10398 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10399 }
10400
10401 pub fn expand_excerpts_for_direction(
10402 &mut self,
10403 lines: u32,
10404 direction: ExpandExcerptDirection,
10405
10406 cx: &mut Context<Self>,
10407 ) {
10408 let selections = self.selections.disjoint_anchors();
10409
10410 let lines = if lines == 0 {
10411 EditorSettings::get_global(cx).expand_excerpt_lines
10412 } else {
10413 lines
10414 };
10415
10416 self.buffer.update(cx, |buffer, cx| {
10417 let snapshot = buffer.snapshot(cx);
10418 let mut excerpt_ids = selections
10419 .iter()
10420 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10421 .collect::<Vec<_>>();
10422 excerpt_ids.sort();
10423 excerpt_ids.dedup();
10424 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10425 })
10426 }
10427
10428 pub fn expand_excerpt(
10429 &mut self,
10430 excerpt: ExcerptId,
10431 direction: ExpandExcerptDirection,
10432 cx: &mut Context<Self>,
10433 ) {
10434 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10435 self.buffer.update(cx, |buffer, cx| {
10436 buffer.expand_excerpts([excerpt], lines, direction, cx)
10437 })
10438 }
10439
10440 pub fn go_to_singleton_buffer_point(
10441 &mut self,
10442 point: Point,
10443 window: &mut Window,
10444 cx: &mut Context<Self>,
10445 ) {
10446 self.go_to_singleton_buffer_range(point..point, window, cx);
10447 }
10448
10449 pub fn go_to_singleton_buffer_range(
10450 &mut self,
10451 range: Range<Point>,
10452 window: &mut Window,
10453 cx: &mut Context<Self>,
10454 ) {
10455 let multibuffer = self.buffer().read(cx);
10456 let Some(buffer) = multibuffer.as_singleton() else {
10457 return;
10458 };
10459 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10460 return;
10461 };
10462 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10463 return;
10464 };
10465 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10466 s.select_anchor_ranges([start..end])
10467 });
10468 }
10469
10470 fn go_to_diagnostic(
10471 &mut self,
10472 _: &GoToDiagnostic,
10473 window: &mut Window,
10474 cx: &mut Context<Self>,
10475 ) {
10476 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10477 }
10478
10479 fn go_to_prev_diagnostic(
10480 &mut self,
10481 _: &GoToPrevDiagnostic,
10482 window: &mut Window,
10483 cx: &mut Context<Self>,
10484 ) {
10485 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10486 }
10487
10488 pub fn go_to_diagnostic_impl(
10489 &mut self,
10490 direction: Direction,
10491 window: &mut Window,
10492 cx: &mut Context<Self>,
10493 ) {
10494 let buffer = self.buffer.read(cx).snapshot(cx);
10495 let selection = self.selections.newest::<usize>(cx);
10496
10497 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10498 if direction == Direction::Next {
10499 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10500 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10501 return;
10502 };
10503 self.activate_diagnostics(
10504 buffer_id,
10505 popover.local_diagnostic.diagnostic.group_id,
10506 window,
10507 cx,
10508 );
10509 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10510 let primary_range_start = active_diagnostics.primary_range.start;
10511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10512 let mut new_selection = s.newest_anchor().clone();
10513 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10514 s.select_anchors(vec![new_selection.clone()]);
10515 });
10516 self.refresh_inline_completion(false, true, window, cx);
10517 }
10518 return;
10519 }
10520 }
10521
10522 let active_group_id = self
10523 .active_diagnostics
10524 .as_ref()
10525 .map(|active_group| active_group.group_id);
10526 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10527 active_diagnostics
10528 .primary_range
10529 .to_offset(&buffer)
10530 .to_inclusive()
10531 });
10532 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10533 if active_primary_range.contains(&selection.head()) {
10534 *active_primary_range.start()
10535 } else {
10536 selection.head()
10537 }
10538 } else {
10539 selection.head()
10540 };
10541
10542 let snapshot = self.snapshot(window, cx);
10543 let primary_diagnostics_before = buffer
10544 .diagnostics_in_range::<usize>(0..search_start)
10545 .filter(|entry| entry.diagnostic.is_primary)
10546 .filter(|entry| entry.range.start != entry.range.end)
10547 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10548 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10549 .collect::<Vec<_>>();
10550 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10551 primary_diagnostics_before
10552 .iter()
10553 .position(|entry| entry.diagnostic.group_id == active_group_id)
10554 });
10555
10556 let primary_diagnostics_after = buffer
10557 .diagnostics_in_range::<usize>(search_start..buffer.len())
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(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10562 .collect::<Vec<_>>();
10563 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10564 primary_diagnostics_after
10565 .iter()
10566 .enumerate()
10567 .rev()
10568 .find_map(|(i, entry)| {
10569 if entry.diagnostic.group_id == active_group_id {
10570 Some(i)
10571 } else {
10572 None
10573 }
10574 })
10575 });
10576
10577 let next_primary_diagnostic = match direction {
10578 Direction::Prev => primary_diagnostics_before
10579 .iter()
10580 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10581 .rev()
10582 .next(),
10583 Direction::Next => primary_diagnostics_after
10584 .iter()
10585 .skip(
10586 last_same_group_diagnostic_after
10587 .map(|index| index + 1)
10588 .unwrap_or(0),
10589 )
10590 .next(),
10591 };
10592
10593 // Cycle around to the start of the buffer, potentially moving back to the start of
10594 // the currently active diagnostic.
10595 let cycle_around = || match direction {
10596 Direction::Prev => primary_diagnostics_after
10597 .iter()
10598 .rev()
10599 .chain(primary_diagnostics_before.iter().rev())
10600 .next(),
10601 Direction::Next => primary_diagnostics_before
10602 .iter()
10603 .chain(primary_diagnostics_after.iter())
10604 .next(),
10605 };
10606
10607 if let Some((primary_range, group_id)) = next_primary_diagnostic
10608 .or_else(cycle_around)
10609 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10610 {
10611 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10612 return;
10613 };
10614 self.activate_diagnostics(buffer_id, group_id, window, cx);
10615 if self.active_diagnostics.is_some() {
10616 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10617 s.select(vec![Selection {
10618 id: selection.id,
10619 start: primary_range.start,
10620 end: primary_range.start,
10621 reversed: false,
10622 goal: SelectionGoal::None,
10623 }]);
10624 });
10625 self.refresh_inline_completion(false, true, window, cx);
10626 }
10627 }
10628 }
10629
10630 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10631 let snapshot = self.snapshot(window, cx);
10632 let selection = self.selections.newest::<Point>(cx);
10633 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10634 }
10635
10636 fn go_to_hunk_after_position(
10637 &mut self,
10638 snapshot: &EditorSnapshot,
10639 position: Point,
10640 window: &mut Window,
10641 cx: &mut Context<Editor>,
10642 ) -> Option<MultiBufferDiffHunk> {
10643 let mut hunk = snapshot
10644 .buffer_snapshot
10645 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10646 .find(|hunk| hunk.row_range.start.0 > position.row);
10647 if hunk.is_none() {
10648 hunk = snapshot
10649 .buffer_snapshot
10650 .diff_hunks_in_range(Point::zero()..position)
10651 .find(|hunk| hunk.row_range.end.0 < position.row)
10652 }
10653 if let Some(hunk) = &hunk {
10654 let destination = Point::new(hunk.row_range.start.0, 0);
10655 self.unfold_ranges(&[destination..destination], false, false, cx);
10656 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10657 s.select_ranges(vec![destination..destination]);
10658 });
10659 }
10660
10661 hunk
10662 }
10663
10664 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10665 let snapshot = self.snapshot(window, cx);
10666 let selection = self.selections.newest::<Point>(cx);
10667 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10668 }
10669
10670 fn go_to_hunk_before_position(
10671 &mut self,
10672 snapshot: &EditorSnapshot,
10673 position: Point,
10674 window: &mut Window,
10675 cx: &mut Context<Editor>,
10676 ) -> Option<MultiBufferDiffHunk> {
10677 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10678 if hunk.is_none() {
10679 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10680 }
10681 if let Some(hunk) = &hunk {
10682 let destination = Point::new(hunk.row_range.start.0, 0);
10683 self.unfold_ranges(&[destination..destination], false, false, cx);
10684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10685 s.select_ranges(vec![destination..destination]);
10686 });
10687 }
10688
10689 hunk
10690 }
10691
10692 pub fn go_to_definition(
10693 &mut self,
10694 _: &GoToDefinition,
10695 window: &mut Window,
10696 cx: &mut Context<Self>,
10697 ) -> Task<Result<Navigated>> {
10698 let definition =
10699 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10700 cx.spawn_in(window, |editor, mut cx| async move {
10701 if definition.await? == Navigated::Yes {
10702 return Ok(Navigated::Yes);
10703 }
10704 match editor.update_in(&mut cx, |editor, window, cx| {
10705 editor.find_all_references(&FindAllReferences, window, cx)
10706 })? {
10707 Some(references) => references.await,
10708 None => Ok(Navigated::No),
10709 }
10710 })
10711 }
10712
10713 pub fn go_to_declaration(
10714 &mut self,
10715 _: &GoToDeclaration,
10716 window: &mut Window,
10717 cx: &mut Context<Self>,
10718 ) -> Task<Result<Navigated>> {
10719 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10720 }
10721
10722 pub fn go_to_declaration_split(
10723 &mut self,
10724 _: &GoToDeclaration,
10725 window: &mut Window,
10726 cx: &mut Context<Self>,
10727 ) -> Task<Result<Navigated>> {
10728 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10729 }
10730
10731 pub fn go_to_implementation(
10732 &mut self,
10733 _: &GoToImplementation,
10734 window: &mut Window,
10735 cx: &mut Context<Self>,
10736 ) -> Task<Result<Navigated>> {
10737 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10738 }
10739
10740 pub fn go_to_implementation_split(
10741 &mut self,
10742 _: &GoToImplementationSplit,
10743 window: &mut Window,
10744 cx: &mut Context<Self>,
10745 ) -> Task<Result<Navigated>> {
10746 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10747 }
10748
10749 pub fn go_to_type_definition(
10750 &mut self,
10751 _: &GoToTypeDefinition,
10752 window: &mut Window,
10753 cx: &mut Context<Self>,
10754 ) -> Task<Result<Navigated>> {
10755 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10756 }
10757
10758 pub fn go_to_definition_split(
10759 &mut self,
10760 _: &GoToDefinitionSplit,
10761 window: &mut Window,
10762 cx: &mut Context<Self>,
10763 ) -> Task<Result<Navigated>> {
10764 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10765 }
10766
10767 pub fn go_to_type_definition_split(
10768 &mut self,
10769 _: &GoToTypeDefinitionSplit,
10770 window: &mut Window,
10771 cx: &mut Context<Self>,
10772 ) -> Task<Result<Navigated>> {
10773 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10774 }
10775
10776 fn go_to_definition_of_kind(
10777 &mut self,
10778 kind: GotoDefinitionKind,
10779 split: bool,
10780 window: &mut Window,
10781 cx: &mut Context<Self>,
10782 ) -> Task<Result<Navigated>> {
10783 let Some(provider) = self.semantics_provider.clone() else {
10784 return Task::ready(Ok(Navigated::No));
10785 };
10786 let head = self.selections.newest::<usize>(cx).head();
10787 let buffer = self.buffer.read(cx);
10788 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10789 text_anchor
10790 } else {
10791 return Task::ready(Ok(Navigated::No));
10792 };
10793
10794 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10795 return Task::ready(Ok(Navigated::No));
10796 };
10797
10798 cx.spawn_in(window, |editor, mut cx| async move {
10799 let definitions = definitions.await?;
10800 let navigated = editor
10801 .update_in(&mut cx, |editor, window, cx| {
10802 editor.navigate_to_hover_links(
10803 Some(kind),
10804 definitions
10805 .into_iter()
10806 .filter(|location| {
10807 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10808 })
10809 .map(HoverLink::Text)
10810 .collect::<Vec<_>>(),
10811 split,
10812 window,
10813 cx,
10814 )
10815 })?
10816 .await?;
10817 anyhow::Ok(navigated)
10818 })
10819 }
10820
10821 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10822 let selection = self.selections.newest_anchor();
10823 let head = selection.head();
10824 let tail = selection.tail();
10825
10826 let Some((buffer, start_position)) =
10827 self.buffer.read(cx).text_anchor_for_position(head, cx)
10828 else {
10829 return;
10830 };
10831
10832 let end_position = if head != tail {
10833 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10834 return;
10835 };
10836 Some(pos)
10837 } else {
10838 None
10839 };
10840
10841 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10842 let url = if let Some(end_pos) = end_position {
10843 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10844 } else {
10845 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10846 };
10847
10848 if let Some(url) = url {
10849 editor.update(&mut cx, |_, cx| {
10850 cx.open_url(&url);
10851 })
10852 } else {
10853 Ok(())
10854 }
10855 });
10856
10857 url_finder.detach();
10858 }
10859
10860 pub fn open_selected_filename(
10861 &mut self,
10862 _: &OpenSelectedFilename,
10863 window: &mut Window,
10864 cx: &mut Context<Self>,
10865 ) {
10866 let Some(workspace) = self.workspace() else {
10867 return;
10868 };
10869
10870 let position = self.selections.newest_anchor().head();
10871
10872 let Some((buffer, buffer_position)) =
10873 self.buffer.read(cx).text_anchor_for_position(position, cx)
10874 else {
10875 return;
10876 };
10877
10878 let project = self.project.clone();
10879
10880 cx.spawn_in(window, |_, mut cx| async move {
10881 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10882
10883 if let Some((_, path)) = result {
10884 workspace
10885 .update_in(&mut cx, |workspace, window, cx| {
10886 workspace.open_resolved_path(path, window, cx)
10887 })?
10888 .await?;
10889 }
10890 anyhow::Ok(())
10891 })
10892 .detach();
10893 }
10894
10895 pub(crate) fn navigate_to_hover_links(
10896 &mut self,
10897 kind: Option<GotoDefinitionKind>,
10898 mut definitions: Vec<HoverLink>,
10899 split: bool,
10900 window: &mut Window,
10901 cx: &mut Context<Editor>,
10902 ) -> Task<Result<Navigated>> {
10903 // If there is one definition, just open it directly
10904 if definitions.len() == 1 {
10905 let definition = definitions.pop().unwrap();
10906
10907 enum TargetTaskResult {
10908 Location(Option<Location>),
10909 AlreadyNavigated,
10910 }
10911
10912 let target_task = match definition {
10913 HoverLink::Text(link) => {
10914 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10915 }
10916 HoverLink::InlayHint(lsp_location, server_id) => {
10917 let computation =
10918 self.compute_target_location(lsp_location, server_id, window, cx);
10919 cx.background_spawn(async move {
10920 let location = computation.await?;
10921 Ok(TargetTaskResult::Location(location))
10922 })
10923 }
10924 HoverLink::Url(url) => {
10925 cx.open_url(&url);
10926 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10927 }
10928 HoverLink::File(path) => {
10929 if let Some(workspace) = self.workspace() {
10930 cx.spawn_in(window, |_, mut cx| async move {
10931 workspace
10932 .update_in(&mut cx, |workspace, window, cx| {
10933 workspace.open_resolved_path(path, window, cx)
10934 })?
10935 .await
10936 .map(|_| TargetTaskResult::AlreadyNavigated)
10937 })
10938 } else {
10939 Task::ready(Ok(TargetTaskResult::Location(None)))
10940 }
10941 }
10942 };
10943 cx.spawn_in(window, |editor, mut cx| async move {
10944 let target = match target_task.await.context("target resolution task")? {
10945 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10946 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10947 TargetTaskResult::Location(Some(target)) => target,
10948 };
10949
10950 editor.update_in(&mut cx, |editor, window, cx| {
10951 let Some(workspace) = editor.workspace() else {
10952 return Navigated::No;
10953 };
10954 let pane = workspace.read(cx).active_pane().clone();
10955
10956 let range = target.range.to_point(target.buffer.read(cx));
10957 let range = editor.range_for_match(&range);
10958 let range = collapse_multiline_range(range);
10959
10960 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10961 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10962 } else {
10963 window.defer(cx, move |window, cx| {
10964 let target_editor: Entity<Self> =
10965 workspace.update(cx, |workspace, cx| {
10966 let pane = if split {
10967 workspace.adjacent_pane(window, cx)
10968 } else {
10969 workspace.active_pane().clone()
10970 };
10971
10972 workspace.open_project_item(
10973 pane,
10974 target.buffer.clone(),
10975 true,
10976 true,
10977 window,
10978 cx,
10979 )
10980 });
10981 target_editor.update(cx, |target_editor, cx| {
10982 // When selecting a definition in a different buffer, disable the nav history
10983 // to avoid creating a history entry at the previous cursor location.
10984 pane.update(cx, |pane, _| pane.disable_history());
10985 target_editor.go_to_singleton_buffer_range(range, window, cx);
10986 pane.update(cx, |pane, _| pane.enable_history());
10987 });
10988 });
10989 }
10990 Navigated::Yes
10991 })
10992 })
10993 } else if !definitions.is_empty() {
10994 cx.spawn_in(window, |editor, mut cx| async move {
10995 let (title, location_tasks, workspace) = editor
10996 .update_in(&mut cx, |editor, window, cx| {
10997 let tab_kind = match kind {
10998 Some(GotoDefinitionKind::Implementation) => "Implementations",
10999 _ => "Definitions",
11000 };
11001 let title = definitions
11002 .iter()
11003 .find_map(|definition| match definition {
11004 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11005 let buffer = origin.buffer.read(cx);
11006 format!(
11007 "{} for {}",
11008 tab_kind,
11009 buffer
11010 .text_for_range(origin.range.clone())
11011 .collect::<String>()
11012 )
11013 }),
11014 HoverLink::InlayHint(_, _) => None,
11015 HoverLink::Url(_) => None,
11016 HoverLink::File(_) => None,
11017 })
11018 .unwrap_or(tab_kind.to_string());
11019 let location_tasks = definitions
11020 .into_iter()
11021 .map(|definition| match definition {
11022 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11023 HoverLink::InlayHint(lsp_location, server_id) => editor
11024 .compute_target_location(lsp_location, server_id, window, cx),
11025 HoverLink::Url(_) => Task::ready(Ok(None)),
11026 HoverLink::File(_) => Task::ready(Ok(None)),
11027 })
11028 .collect::<Vec<_>>();
11029 (title, location_tasks, editor.workspace().clone())
11030 })
11031 .context("location tasks preparation")?;
11032
11033 let locations = future::join_all(location_tasks)
11034 .await
11035 .into_iter()
11036 .filter_map(|location| location.transpose())
11037 .collect::<Result<_>>()
11038 .context("location tasks")?;
11039
11040 let Some(workspace) = workspace else {
11041 return Ok(Navigated::No);
11042 };
11043 let opened = workspace
11044 .update_in(&mut cx, |workspace, window, cx| {
11045 Self::open_locations_in_multibuffer(
11046 workspace,
11047 locations,
11048 title,
11049 split,
11050 MultibufferSelectionMode::First,
11051 window,
11052 cx,
11053 )
11054 })
11055 .ok();
11056
11057 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11058 })
11059 } else {
11060 Task::ready(Ok(Navigated::No))
11061 }
11062 }
11063
11064 fn compute_target_location(
11065 &self,
11066 lsp_location: lsp::Location,
11067 server_id: LanguageServerId,
11068 window: &mut Window,
11069 cx: &mut Context<Self>,
11070 ) -> Task<anyhow::Result<Option<Location>>> {
11071 let Some(project) = self.project.clone() else {
11072 return Task::ready(Ok(None));
11073 };
11074
11075 cx.spawn_in(window, move |editor, mut cx| async move {
11076 let location_task = editor.update(&mut cx, |_, cx| {
11077 project.update(cx, |project, cx| {
11078 let language_server_name = project
11079 .language_server_statuses(cx)
11080 .find(|(id, _)| server_id == *id)
11081 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11082 language_server_name.map(|language_server_name| {
11083 project.open_local_buffer_via_lsp(
11084 lsp_location.uri.clone(),
11085 server_id,
11086 language_server_name,
11087 cx,
11088 )
11089 })
11090 })
11091 })?;
11092 let location = match location_task {
11093 Some(task) => Some({
11094 let target_buffer_handle = task.await.context("open local buffer")?;
11095 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11096 let target_start = target_buffer
11097 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11098 let target_end = target_buffer
11099 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11100 target_buffer.anchor_after(target_start)
11101 ..target_buffer.anchor_before(target_end)
11102 })?;
11103 Location {
11104 buffer: target_buffer_handle,
11105 range,
11106 }
11107 }),
11108 None => None,
11109 };
11110 Ok(location)
11111 })
11112 }
11113
11114 pub fn find_all_references(
11115 &mut self,
11116 _: &FindAllReferences,
11117 window: &mut Window,
11118 cx: &mut Context<Self>,
11119 ) -> Option<Task<Result<Navigated>>> {
11120 let selection = self.selections.newest::<usize>(cx);
11121 let multi_buffer = self.buffer.read(cx);
11122 let head = selection.head();
11123
11124 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11125 let head_anchor = multi_buffer_snapshot.anchor_at(
11126 head,
11127 if head < selection.tail() {
11128 Bias::Right
11129 } else {
11130 Bias::Left
11131 },
11132 );
11133
11134 match self
11135 .find_all_references_task_sources
11136 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11137 {
11138 Ok(_) => {
11139 log::info!(
11140 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11141 );
11142 return None;
11143 }
11144 Err(i) => {
11145 self.find_all_references_task_sources.insert(i, head_anchor);
11146 }
11147 }
11148
11149 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11150 let workspace = self.workspace()?;
11151 let project = workspace.read(cx).project().clone();
11152 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11153 Some(cx.spawn_in(window, |editor, mut cx| async move {
11154 let _cleanup = defer({
11155 let mut cx = cx.clone();
11156 move || {
11157 let _ = editor.update(&mut cx, |editor, _| {
11158 if let Ok(i) =
11159 editor
11160 .find_all_references_task_sources
11161 .binary_search_by(|anchor| {
11162 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11163 })
11164 {
11165 editor.find_all_references_task_sources.remove(i);
11166 }
11167 });
11168 }
11169 });
11170
11171 let locations = references.await?;
11172 if locations.is_empty() {
11173 return anyhow::Ok(Navigated::No);
11174 }
11175
11176 workspace.update_in(&mut cx, |workspace, window, cx| {
11177 let title = locations
11178 .first()
11179 .as_ref()
11180 .map(|location| {
11181 let buffer = location.buffer.read(cx);
11182 format!(
11183 "References to `{}`",
11184 buffer
11185 .text_for_range(location.range.clone())
11186 .collect::<String>()
11187 )
11188 })
11189 .unwrap();
11190 Self::open_locations_in_multibuffer(
11191 workspace,
11192 locations,
11193 title,
11194 false,
11195 MultibufferSelectionMode::First,
11196 window,
11197 cx,
11198 );
11199 Navigated::Yes
11200 })
11201 }))
11202 }
11203
11204 /// Opens a multibuffer with the given project locations in it
11205 pub fn open_locations_in_multibuffer(
11206 workspace: &mut Workspace,
11207 mut locations: Vec<Location>,
11208 title: String,
11209 split: bool,
11210 multibuffer_selection_mode: MultibufferSelectionMode,
11211 window: &mut Window,
11212 cx: &mut Context<Workspace>,
11213 ) {
11214 // If there are multiple definitions, open them in a multibuffer
11215 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11216 let mut locations = locations.into_iter().peekable();
11217 let mut ranges = Vec::new();
11218 let capability = workspace.project().read(cx).capability();
11219
11220 let excerpt_buffer = cx.new(|cx| {
11221 let mut multibuffer = MultiBuffer::new(capability);
11222 while let Some(location) = locations.next() {
11223 let buffer = location.buffer.read(cx);
11224 let mut ranges_for_buffer = Vec::new();
11225 let range = location.range.to_offset(buffer);
11226 ranges_for_buffer.push(range.clone());
11227
11228 while let Some(next_location) = locations.peek() {
11229 if next_location.buffer == location.buffer {
11230 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11231 locations.next();
11232 } else {
11233 break;
11234 }
11235 }
11236
11237 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11238 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11239 location.buffer.clone(),
11240 ranges_for_buffer,
11241 DEFAULT_MULTIBUFFER_CONTEXT,
11242 cx,
11243 ))
11244 }
11245
11246 multibuffer.with_title(title)
11247 });
11248
11249 let editor = cx.new(|cx| {
11250 Editor::for_multibuffer(
11251 excerpt_buffer,
11252 Some(workspace.project().clone()),
11253 true,
11254 window,
11255 cx,
11256 )
11257 });
11258 editor.update(cx, |editor, cx| {
11259 match multibuffer_selection_mode {
11260 MultibufferSelectionMode::First => {
11261 if let Some(first_range) = ranges.first() {
11262 editor.change_selections(None, window, cx, |selections| {
11263 selections.clear_disjoint();
11264 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11265 });
11266 }
11267 editor.highlight_background::<Self>(
11268 &ranges,
11269 |theme| theme.editor_highlighted_line_background,
11270 cx,
11271 );
11272 }
11273 MultibufferSelectionMode::All => {
11274 editor.change_selections(None, window, cx, |selections| {
11275 selections.clear_disjoint();
11276 selections.select_anchor_ranges(ranges);
11277 });
11278 }
11279 }
11280 editor.register_buffers_with_language_servers(cx);
11281 });
11282
11283 let item = Box::new(editor);
11284 let item_id = item.item_id();
11285
11286 if split {
11287 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11288 } else {
11289 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11290 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11291 pane.close_current_preview_item(window, cx)
11292 } else {
11293 None
11294 }
11295 });
11296 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11297 }
11298 workspace.active_pane().update(cx, |pane, cx| {
11299 pane.set_preview_item_id(Some(item_id), cx);
11300 });
11301 }
11302
11303 pub fn rename(
11304 &mut self,
11305 _: &Rename,
11306 window: &mut Window,
11307 cx: &mut Context<Self>,
11308 ) -> Option<Task<Result<()>>> {
11309 use language::ToOffset as _;
11310
11311 let provider = self.semantics_provider.clone()?;
11312 let selection = self.selections.newest_anchor().clone();
11313 let (cursor_buffer, cursor_buffer_position) = self
11314 .buffer
11315 .read(cx)
11316 .text_anchor_for_position(selection.head(), cx)?;
11317 let (tail_buffer, cursor_buffer_position_end) = self
11318 .buffer
11319 .read(cx)
11320 .text_anchor_for_position(selection.tail(), cx)?;
11321 if tail_buffer != cursor_buffer {
11322 return None;
11323 }
11324
11325 let snapshot = cursor_buffer.read(cx).snapshot();
11326 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11327 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11328 let prepare_rename = provider
11329 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11330 .unwrap_or_else(|| Task::ready(Ok(None)));
11331 drop(snapshot);
11332
11333 Some(cx.spawn_in(window, |this, mut cx| async move {
11334 let rename_range = if let Some(range) = prepare_rename.await? {
11335 Some(range)
11336 } else {
11337 this.update(&mut cx, |this, cx| {
11338 let buffer = this.buffer.read(cx).snapshot(cx);
11339 let mut buffer_highlights = this
11340 .document_highlights_for_position(selection.head(), &buffer)
11341 .filter(|highlight| {
11342 highlight.start.excerpt_id == selection.head().excerpt_id
11343 && highlight.end.excerpt_id == selection.head().excerpt_id
11344 });
11345 buffer_highlights
11346 .next()
11347 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11348 })?
11349 };
11350 if let Some(rename_range) = rename_range {
11351 this.update_in(&mut cx, |this, window, cx| {
11352 let snapshot = cursor_buffer.read(cx).snapshot();
11353 let rename_buffer_range = rename_range.to_offset(&snapshot);
11354 let cursor_offset_in_rename_range =
11355 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11356 let cursor_offset_in_rename_range_end =
11357 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11358
11359 this.take_rename(false, window, cx);
11360 let buffer = this.buffer.read(cx).read(cx);
11361 let cursor_offset = selection.head().to_offset(&buffer);
11362 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11363 let rename_end = rename_start + rename_buffer_range.len();
11364 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11365 let mut old_highlight_id = None;
11366 let old_name: Arc<str> = buffer
11367 .chunks(rename_start..rename_end, true)
11368 .map(|chunk| {
11369 if old_highlight_id.is_none() {
11370 old_highlight_id = chunk.syntax_highlight_id;
11371 }
11372 chunk.text
11373 })
11374 .collect::<String>()
11375 .into();
11376
11377 drop(buffer);
11378
11379 // Position the selection in the rename editor so that it matches the current selection.
11380 this.show_local_selections = false;
11381 let rename_editor = cx.new(|cx| {
11382 let mut editor = Editor::single_line(window, cx);
11383 editor.buffer.update(cx, |buffer, cx| {
11384 buffer.edit([(0..0, old_name.clone())], None, cx)
11385 });
11386 let rename_selection_range = match cursor_offset_in_rename_range
11387 .cmp(&cursor_offset_in_rename_range_end)
11388 {
11389 Ordering::Equal => {
11390 editor.select_all(&SelectAll, window, cx);
11391 return editor;
11392 }
11393 Ordering::Less => {
11394 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11395 }
11396 Ordering::Greater => {
11397 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11398 }
11399 };
11400 if rename_selection_range.end > old_name.len() {
11401 editor.select_all(&SelectAll, window, cx);
11402 } else {
11403 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11404 s.select_ranges([rename_selection_range]);
11405 });
11406 }
11407 editor
11408 });
11409 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11410 if e == &EditorEvent::Focused {
11411 cx.emit(EditorEvent::FocusedIn)
11412 }
11413 })
11414 .detach();
11415
11416 let write_highlights =
11417 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11418 let read_highlights =
11419 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11420 let ranges = write_highlights
11421 .iter()
11422 .flat_map(|(_, ranges)| ranges.iter())
11423 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11424 .cloned()
11425 .collect();
11426
11427 this.highlight_text::<Rename>(
11428 ranges,
11429 HighlightStyle {
11430 fade_out: Some(0.6),
11431 ..Default::default()
11432 },
11433 cx,
11434 );
11435 let rename_focus_handle = rename_editor.focus_handle(cx);
11436 window.focus(&rename_focus_handle);
11437 let block_id = this.insert_blocks(
11438 [BlockProperties {
11439 style: BlockStyle::Flex,
11440 placement: BlockPlacement::Below(range.start),
11441 height: 1,
11442 render: Arc::new({
11443 let rename_editor = rename_editor.clone();
11444 move |cx: &mut BlockContext| {
11445 let mut text_style = cx.editor_style.text.clone();
11446 if let Some(highlight_style) = old_highlight_id
11447 .and_then(|h| h.style(&cx.editor_style.syntax))
11448 {
11449 text_style = text_style.highlight(highlight_style);
11450 }
11451 div()
11452 .block_mouse_down()
11453 .pl(cx.anchor_x)
11454 .child(EditorElement::new(
11455 &rename_editor,
11456 EditorStyle {
11457 background: cx.theme().system().transparent,
11458 local_player: cx.editor_style.local_player,
11459 text: text_style,
11460 scrollbar_width: cx.editor_style.scrollbar_width,
11461 syntax: cx.editor_style.syntax.clone(),
11462 status: cx.editor_style.status.clone(),
11463 inlay_hints_style: HighlightStyle {
11464 font_weight: Some(FontWeight::BOLD),
11465 ..make_inlay_hints_style(cx.app)
11466 },
11467 inline_completion_styles: make_suggestion_styles(
11468 cx.app,
11469 ),
11470 ..EditorStyle::default()
11471 },
11472 ))
11473 .into_any_element()
11474 }
11475 }),
11476 priority: 0,
11477 }],
11478 Some(Autoscroll::fit()),
11479 cx,
11480 )[0];
11481 this.pending_rename = Some(RenameState {
11482 range,
11483 old_name,
11484 editor: rename_editor,
11485 block_id,
11486 });
11487 })?;
11488 }
11489
11490 Ok(())
11491 }))
11492 }
11493
11494 pub fn confirm_rename(
11495 &mut self,
11496 _: &ConfirmRename,
11497 window: &mut Window,
11498 cx: &mut Context<Self>,
11499 ) -> Option<Task<Result<()>>> {
11500 let rename = self.take_rename(false, window, cx)?;
11501 let workspace = self.workspace()?.downgrade();
11502 let (buffer, start) = self
11503 .buffer
11504 .read(cx)
11505 .text_anchor_for_position(rename.range.start, cx)?;
11506 let (end_buffer, _) = self
11507 .buffer
11508 .read(cx)
11509 .text_anchor_for_position(rename.range.end, cx)?;
11510 if buffer != end_buffer {
11511 return None;
11512 }
11513
11514 let old_name = rename.old_name;
11515 let new_name = rename.editor.read(cx).text(cx);
11516
11517 let rename = self.semantics_provider.as_ref()?.perform_rename(
11518 &buffer,
11519 start,
11520 new_name.clone(),
11521 cx,
11522 )?;
11523
11524 Some(cx.spawn_in(window, |editor, mut cx| async move {
11525 let project_transaction = rename.await?;
11526 Self::open_project_transaction(
11527 &editor,
11528 workspace,
11529 project_transaction,
11530 format!("Rename: {} → {}", old_name, new_name),
11531 cx.clone(),
11532 )
11533 .await?;
11534
11535 editor.update(&mut cx, |editor, cx| {
11536 editor.refresh_document_highlights(cx);
11537 })?;
11538 Ok(())
11539 }))
11540 }
11541
11542 fn take_rename(
11543 &mut self,
11544 moving_cursor: bool,
11545 window: &mut Window,
11546 cx: &mut Context<Self>,
11547 ) -> Option<RenameState> {
11548 let rename = self.pending_rename.take()?;
11549 if rename.editor.focus_handle(cx).is_focused(window) {
11550 window.focus(&self.focus_handle);
11551 }
11552
11553 self.remove_blocks(
11554 [rename.block_id].into_iter().collect(),
11555 Some(Autoscroll::fit()),
11556 cx,
11557 );
11558 self.clear_highlights::<Rename>(cx);
11559 self.show_local_selections = true;
11560
11561 if moving_cursor {
11562 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11563 editor.selections.newest::<usize>(cx).head()
11564 });
11565
11566 // Update the selection to match the position of the selection inside
11567 // the rename editor.
11568 let snapshot = self.buffer.read(cx).read(cx);
11569 let rename_range = rename.range.to_offset(&snapshot);
11570 let cursor_in_editor = snapshot
11571 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11572 .min(rename_range.end);
11573 drop(snapshot);
11574
11575 self.change_selections(None, window, cx, |s| {
11576 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11577 });
11578 } else {
11579 self.refresh_document_highlights(cx);
11580 }
11581
11582 Some(rename)
11583 }
11584
11585 pub fn pending_rename(&self) -> Option<&RenameState> {
11586 self.pending_rename.as_ref()
11587 }
11588
11589 fn format(
11590 &mut self,
11591 _: &Format,
11592 window: &mut Window,
11593 cx: &mut Context<Self>,
11594 ) -> Option<Task<Result<()>>> {
11595 let project = match &self.project {
11596 Some(project) => project.clone(),
11597 None => return None,
11598 };
11599
11600 Some(self.perform_format(
11601 project,
11602 FormatTrigger::Manual,
11603 FormatTarget::Buffers,
11604 window,
11605 cx,
11606 ))
11607 }
11608
11609 fn format_selections(
11610 &mut self,
11611 _: &FormatSelections,
11612 window: &mut Window,
11613 cx: &mut Context<Self>,
11614 ) -> Option<Task<Result<()>>> {
11615 let project = match &self.project {
11616 Some(project) => project.clone(),
11617 None => return None,
11618 };
11619
11620 let ranges = self
11621 .selections
11622 .all_adjusted(cx)
11623 .into_iter()
11624 .map(|selection| selection.range())
11625 .collect_vec();
11626
11627 Some(self.perform_format(
11628 project,
11629 FormatTrigger::Manual,
11630 FormatTarget::Ranges(ranges),
11631 window,
11632 cx,
11633 ))
11634 }
11635
11636 fn perform_format(
11637 &mut self,
11638 project: Entity<Project>,
11639 trigger: FormatTrigger,
11640 target: FormatTarget,
11641 window: &mut Window,
11642 cx: &mut Context<Self>,
11643 ) -> Task<Result<()>> {
11644 let buffer = self.buffer.clone();
11645 let (buffers, target) = match target {
11646 FormatTarget::Buffers => {
11647 let mut buffers = buffer.read(cx).all_buffers();
11648 if trigger == FormatTrigger::Save {
11649 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11650 }
11651 (buffers, LspFormatTarget::Buffers)
11652 }
11653 FormatTarget::Ranges(selection_ranges) => {
11654 let multi_buffer = buffer.read(cx);
11655 let snapshot = multi_buffer.read(cx);
11656 let mut buffers = HashSet::default();
11657 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11658 BTreeMap::new();
11659 for selection_range in selection_ranges {
11660 for (buffer, buffer_range, _) in
11661 snapshot.range_to_buffer_ranges(selection_range)
11662 {
11663 let buffer_id = buffer.remote_id();
11664 let start = buffer.anchor_before(buffer_range.start);
11665 let end = buffer.anchor_after(buffer_range.end);
11666 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11667 buffer_id_to_ranges
11668 .entry(buffer_id)
11669 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11670 .or_insert_with(|| vec![start..end]);
11671 }
11672 }
11673 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11674 }
11675 };
11676
11677 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11678 let format = project.update(cx, |project, cx| {
11679 project.format(buffers, target, true, trigger, cx)
11680 });
11681
11682 cx.spawn_in(window, |_, mut cx| async move {
11683 let transaction = futures::select_biased! {
11684 () = timeout => {
11685 log::warn!("timed out waiting for formatting");
11686 None
11687 }
11688 transaction = format.log_err().fuse() => transaction,
11689 };
11690
11691 buffer
11692 .update(&mut cx, |buffer, cx| {
11693 if let Some(transaction) = transaction {
11694 if !buffer.is_singleton() {
11695 buffer.push_transaction(&transaction.0, cx);
11696 }
11697 }
11698
11699 cx.notify();
11700 })
11701 .ok();
11702
11703 Ok(())
11704 })
11705 }
11706
11707 fn restart_language_server(
11708 &mut self,
11709 _: &RestartLanguageServer,
11710 _: &mut Window,
11711 cx: &mut Context<Self>,
11712 ) {
11713 if let Some(project) = self.project.clone() {
11714 self.buffer.update(cx, |multi_buffer, cx| {
11715 project.update(cx, |project, cx| {
11716 project.restart_language_servers_for_buffers(
11717 multi_buffer.all_buffers().into_iter().collect(),
11718 cx,
11719 );
11720 });
11721 })
11722 }
11723 }
11724
11725 fn cancel_language_server_work(
11726 workspace: &mut Workspace,
11727 _: &actions::CancelLanguageServerWork,
11728 _: &mut Window,
11729 cx: &mut Context<Workspace>,
11730 ) {
11731 let project = workspace.project();
11732 let buffers = workspace
11733 .active_item(cx)
11734 .and_then(|item| item.act_as::<Editor>(cx))
11735 .map_or(HashSet::default(), |editor| {
11736 editor.read(cx).buffer.read(cx).all_buffers()
11737 });
11738 project.update(cx, |project, cx| {
11739 project.cancel_language_server_work_for_buffers(buffers, cx);
11740 });
11741 }
11742
11743 fn show_character_palette(
11744 &mut self,
11745 _: &ShowCharacterPalette,
11746 window: &mut Window,
11747 _: &mut Context<Self>,
11748 ) {
11749 window.show_character_palette();
11750 }
11751
11752 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11753 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11754 let buffer = self.buffer.read(cx).snapshot(cx);
11755 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11756 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11757 let is_valid = buffer
11758 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11759 .any(|entry| {
11760 entry.diagnostic.is_primary
11761 && !entry.range.is_empty()
11762 && entry.range.start == primary_range_start
11763 && entry.diagnostic.message == active_diagnostics.primary_message
11764 });
11765
11766 if is_valid != active_diagnostics.is_valid {
11767 active_diagnostics.is_valid = is_valid;
11768 let mut new_styles = HashMap::default();
11769 for (block_id, diagnostic) in &active_diagnostics.blocks {
11770 new_styles.insert(
11771 *block_id,
11772 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11773 );
11774 }
11775 self.display_map.update(cx, |display_map, _cx| {
11776 display_map.replace_blocks(new_styles)
11777 });
11778 }
11779 }
11780 }
11781
11782 fn activate_diagnostics(
11783 &mut self,
11784 buffer_id: BufferId,
11785 group_id: usize,
11786 window: &mut Window,
11787 cx: &mut Context<Self>,
11788 ) {
11789 self.dismiss_diagnostics(cx);
11790 let snapshot = self.snapshot(window, cx);
11791 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11792 let buffer = self.buffer.read(cx).snapshot(cx);
11793
11794 let mut primary_range = None;
11795 let mut primary_message = None;
11796 let diagnostic_group = buffer
11797 .diagnostic_group(buffer_id, group_id)
11798 .filter_map(|entry| {
11799 let start = entry.range.start;
11800 let end = entry.range.end;
11801 if snapshot.is_line_folded(MultiBufferRow(start.row))
11802 && (start.row == end.row
11803 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11804 {
11805 return None;
11806 }
11807 if entry.diagnostic.is_primary {
11808 primary_range = Some(entry.range.clone());
11809 primary_message = Some(entry.diagnostic.message.clone());
11810 }
11811 Some(entry)
11812 })
11813 .collect::<Vec<_>>();
11814 let primary_range = primary_range?;
11815 let primary_message = primary_message?;
11816
11817 let blocks = display_map
11818 .insert_blocks(
11819 diagnostic_group.iter().map(|entry| {
11820 let diagnostic = entry.diagnostic.clone();
11821 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11822 BlockProperties {
11823 style: BlockStyle::Fixed,
11824 placement: BlockPlacement::Below(
11825 buffer.anchor_after(entry.range.start),
11826 ),
11827 height: message_height,
11828 render: diagnostic_block_renderer(diagnostic, None, true, true),
11829 priority: 0,
11830 }
11831 }),
11832 cx,
11833 )
11834 .into_iter()
11835 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11836 .collect();
11837
11838 Some(ActiveDiagnosticGroup {
11839 primary_range: buffer.anchor_before(primary_range.start)
11840 ..buffer.anchor_after(primary_range.end),
11841 primary_message,
11842 group_id,
11843 blocks,
11844 is_valid: true,
11845 })
11846 });
11847 }
11848
11849 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11850 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11851 self.display_map.update(cx, |display_map, cx| {
11852 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11853 });
11854 cx.notify();
11855 }
11856 }
11857
11858 pub fn set_selections_from_remote(
11859 &mut self,
11860 selections: Vec<Selection<Anchor>>,
11861 pending_selection: Option<Selection<Anchor>>,
11862 window: &mut Window,
11863 cx: &mut Context<Self>,
11864 ) {
11865 let old_cursor_position = self.selections.newest_anchor().head();
11866 self.selections.change_with(cx, |s| {
11867 s.select_anchors(selections);
11868 if let Some(pending_selection) = pending_selection {
11869 s.set_pending(pending_selection, SelectMode::Character);
11870 } else {
11871 s.clear_pending();
11872 }
11873 });
11874 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11875 }
11876
11877 fn push_to_selection_history(&mut self) {
11878 self.selection_history.push(SelectionHistoryEntry {
11879 selections: self.selections.disjoint_anchors(),
11880 select_next_state: self.select_next_state.clone(),
11881 select_prev_state: self.select_prev_state.clone(),
11882 add_selections_state: self.add_selections_state.clone(),
11883 });
11884 }
11885
11886 pub fn transact(
11887 &mut self,
11888 window: &mut Window,
11889 cx: &mut Context<Self>,
11890 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11891 ) -> Option<TransactionId> {
11892 self.start_transaction_at(Instant::now(), window, cx);
11893 update(self, window, cx);
11894 self.end_transaction_at(Instant::now(), cx)
11895 }
11896
11897 pub fn start_transaction_at(
11898 &mut self,
11899 now: Instant,
11900 window: &mut Window,
11901 cx: &mut Context<Self>,
11902 ) {
11903 self.end_selection(window, cx);
11904 if let Some(tx_id) = self
11905 .buffer
11906 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11907 {
11908 self.selection_history
11909 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11910 cx.emit(EditorEvent::TransactionBegun {
11911 transaction_id: tx_id,
11912 })
11913 }
11914 }
11915
11916 pub fn end_transaction_at(
11917 &mut self,
11918 now: Instant,
11919 cx: &mut Context<Self>,
11920 ) -> Option<TransactionId> {
11921 if let Some(transaction_id) = self
11922 .buffer
11923 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11924 {
11925 if let Some((_, end_selections)) =
11926 self.selection_history.transaction_mut(transaction_id)
11927 {
11928 *end_selections = Some(self.selections.disjoint_anchors());
11929 } else {
11930 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11931 }
11932
11933 cx.emit(EditorEvent::Edited { transaction_id });
11934 Some(transaction_id)
11935 } else {
11936 None
11937 }
11938 }
11939
11940 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11941 if self.selection_mark_mode {
11942 self.change_selections(None, window, cx, |s| {
11943 s.move_with(|_, sel| {
11944 sel.collapse_to(sel.head(), SelectionGoal::None);
11945 });
11946 })
11947 }
11948 self.selection_mark_mode = true;
11949 cx.notify();
11950 }
11951
11952 pub fn swap_selection_ends(
11953 &mut self,
11954 _: &actions::SwapSelectionEnds,
11955 window: &mut Window,
11956 cx: &mut Context<Self>,
11957 ) {
11958 self.change_selections(None, window, cx, |s| {
11959 s.move_with(|_, sel| {
11960 if sel.start != sel.end {
11961 sel.reversed = !sel.reversed
11962 }
11963 });
11964 });
11965 self.request_autoscroll(Autoscroll::newest(), cx);
11966 cx.notify();
11967 }
11968
11969 pub fn toggle_fold(
11970 &mut self,
11971 _: &actions::ToggleFold,
11972 window: &mut Window,
11973 cx: &mut Context<Self>,
11974 ) {
11975 if self.is_singleton(cx) {
11976 let selection = self.selections.newest::<Point>(cx);
11977
11978 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11979 let range = if selection.is_empty() {
11980 let point = selection.head().to_display_point(&display_map);
11981 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11982 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11983 .to_point(&display_map);
11984 start..end
11985 } else {
11986 selection.range()
11987 };
11988 if display_map.folds_in_range(range).next().is_some() {
11989 self.unfold_lines(&Default::default(), window, cx)
11990 } else {
11991 self.fold(&Default::default(), window, cx)
11992 }
11993 } else {
11994 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11995 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11996 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11997 .map(|(snapshot, _, _)| snapshot.remote_id())
11998 .collect();
11999
12000 for buffer_id in buffer_ids {
12001 if self.is_buffer_folded(buffer_id, cx) {
12002 self.unfold_buffer(buffer_id, cx);
12003 } else {
12004 self.fold_buffer(buffer_id, cx);
12005 }
12006 }
12007 }
12008 }
12009
12010 pub fn toggle_fold_recursive(
12011 &mut self,
12012 _: &actions::ToggleFoldRecursive,
12013 window: &mut Window,
12014 cx: &mut Context<Self>,
12015 ) {
12016 let selection = self.selections.newest::<Point>(cx);
12017
12018 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12019 let range = if selection.is_empty() {
12020 let point = selection.head().to_display_point(&display_map);
12021 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12022 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12023 .to_point(&display_map);
12024 start..end
12025 } else {
12026 selection.range()
12027 };
12028 if display_map.folds_in_range(range).next().is_some() {
12029 self.unfold_recursive(&Default::default(), window, cx)
12030 } else {
12031 self.fold_recursive(&Default::default(), window, cx)
12032 }
12033 }
12034
12035 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12036 if self.is_singleton(cx) {
12037 let mut to_fold = Vec::new();
12038 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12039 let selections = self.selections.all_adjusted(cx);
12040
12041 for selection in selections {
12042 let range = selection.range().sorted();
12043 let buffer_start_row = range.start.row;
12044
12045 if range.start.row != range.end.row {
12046 let mut found = false;
12047 let mut row = range.start.row;
12048 while row <= range.end.row {
12049 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12050 {
12051 found = true;
12052 row = crease.range().end.row + 1;
12053 to_fold.push(crease);
12054 } else {
12055 row += 1
12056 }
12057 }
12058 if found {
12059 continue;
12060 }
12061 }
12062
12063 for row in (0..=range.start.row).rev() {
12064 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12065 if crease.range().end.row >= buffer_start_row {
12066 to_fold.push(crease);
12067 if row <= range.start.row {
12068 break;
12069 }
12070 }
12071 }
12072 }
12073 }
12074
12075 self.fold_creases(to_fold, true, window, cx);
12076 } else {
12077 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12078
12079 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12080 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12081 .map(|(snapshot, _, _)| snapshot.remote_id())
12082 .collect();
12083 for buffer_id in buffer_ids {
12084 self.fold_buffer(buffer_id, cx);
12085 }
12086 }
12087 }
12088
12089 fn fold_at_level(
12090 &mut self,
12091 fold_at: &FoldAtLevel,
12092 window: &mut Window,
12093 cx: &mut Context<Self>,
12094 ) {
12095 if !self.buffer.read(cx).is_singleton() {
12096 return;
12097 }
12098
12099 let fold_at_level = fold_at.0;
12100 let snapshot = self.buffer.read(cx).snapshot(cx);
12101 let mut to_fold = Vec::new();
12102 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12103
12104 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12105 while start_row < end_row {
12106 match self
12107 .snapshot(window, cx)
12108 .crease_for_buffer_row(MultiBufferRow(start_row))
12109 {
12110 Some(crease) => {
12111 let nested_start_row = crease.range().start.row + 1;
12112 let nested_end_row = crease.range().end.row;
12113
12114 if current_level < fold_at_level {
12115 stack.push((nested_start_row, nested_end_row, current_level + 1));
12116 } else if current_level == fold_at_level {
12117 to_fold.push(crease);
12118 }
12119
12120 start_row = nested_end_row + 1;
12121 }
12122 None => start_row += 1,
12123 }
12124 }
12125 }
12126
12127 self.fold_creases(to_fold, true, window, cx);
12128 }
12129
12130 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12131 if self.buffer.read(cx).is_singleton() {
12132 let mut fold_ranges = Vec::new();
12133 let snapshot = self.buffer.read(cx).snapshot(cx);
12134
12135 for row in 0..snapshot.max_row().0 {
12136 if let Some(foldable_range) = self
12137 .snapshot(window, cx)
12138 .crease_for_buffer_row(MultiBufferRow(row))
12139 {
12140 fold_ranges.push(foldable_range);
12141 }
12142 }
12143
12144 self.fold_creases(fold_ranges, true, window, cx);
12145 } else {
12146 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12147 editor
12148 .update_in(&mut cx, |editor, _, cx| {
12149 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12150 editor.fold_buffer(buffer_id, cx);
12151 }
12152 })
12153 .ok();
12154 });
12155 }
12156 }
12157
12158 pub fn fold_function_bodies(
12159 &mut self,
12160 _: &actions::FoldFunctionBodies,
12161 window: &mut Window,
12162 cx: &mut Context<Self>,
12163 ) {
12164 let snapshot = self.buffer.read(cx).snapshot(cx);
12165
12166 let ranges = snapshot
12167 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12168 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12169 .collect::<Vec<_>>();
12170
12171 let creases = ranges
12172 .into_iter()
12173 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12174 .collect();
12175
12176 self.fold_creases(creases, true, window, cx);
12177 }
12178
12179 pub fn fold_recursive(
12180 &mut self,
12181 _: &actions::FoldRecursive,
12182 window: &mut Window,
12183 cx: &mut Context<Self>,
12184 ) {
12185 let mut to_fold = Vec::new();
12186 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12187 let selections = self.selections.all_adjusted(cx);
12188
12189 for selection in selections {
12190 let range = selection.range().sorted();
12191 let buffer_start_row = range.start.row;
12192
12193 if range.start.row != range.end.row {
12194 let mut found = false;
12195 for row in range.start.row..=range.end.row {
12196 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12197 found = true;
12198 to_fold.push(crease);
12199 }
12200 }
12201 if found {
12202 continue;
12203 }
12204 }
12205
12206 for row in (0..=range.start.row).rev() {
12207 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12208 if crease.range().end.row >= buffer_start_row {
12209 to_fold.push(crease);
12210 } else {
12211 break;
12212 }
12213 }
12214 }
12215 }
12216
12217 self.fold_creases(to_fold, true, window, cx);
12218 }
12219
12220 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12221 let buffer_row = fold_at.buffer_row;
12222 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12223
12224 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12225 let autoscroll = self
12226 .selections
12227 .all::<Point>(cx)
12228 .iter()
12229 .any(|selection| crease.range().overlaps(&selection.range()));
12230
12231 self.fold_creases(vec![crease], autoscroll, window, cx);
12232 }
12233 }
12234
12235 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12236 if self.is_singleton(cx) {
12237 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12238 let buffer = &display_map.buffer_snapshot;
12239 let selections = self.selections.all::<Point>(cx);
12240 let ranges = selections
12241 .iter()
12242 .map(|s| {
12243 let range = s.display_range(&display_map).sorted();
12244 let mut start = range.start.to_point(&display_map);
12245 let mut end = range.end.to_point(&display_map);
12246 start.column = 0;
12247 end.column = buffer.line_len(MultiBufferRow(end.row));
12248 start..end
12249 })
12250 .collect::<Vec<_>>();
12251
12252 self.unfold_ranges(&ranges, true, true, cx);
12253 } else {
12254 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12255 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12256 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12257 .map(|(snapshot, _, _)| snapshot.remote_id())
12258 .collect();
12259 for buffer_id in buffer_ids {
12260 self.unfold_buffer(buffer_id, cx);
12261 }
12262 }
12263 }
12264
12265 pub fn unfold_recursive(
12266 &mut self,
12267 _: &UnfoldRecursive,
12268 _window: &mut Window,
12269 cx: &mut Context<Self>,
12270 ) {
12271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12272 let selections = self.selections.all::<Point>(cx);
12273 let ranges = selections
12274 .iter()
12275 .map(|s| {
12276 let mut range = s.display_range(&display_map).sorted();
12277 *range.start.column_mut() = 0;
12278 *range.end.column_mut() = display_map.line_len(range.end.row());
12279 let start = range.start.to_point(&display_map);
12280 let end = range.end.to_point(&display_map);
12281 start..end
12282 })
12283 .collect::<Vec<_>>();
12284
12285 self.unfold_ranges(&ranges, true, true, cx);
12286 }
12287
12288 pub fn unfold_at(
12289 &mut self,
12290 unfold_at: &UnfoldAt,
12291 _window: &mut Window,
12292 cx: &mut Context<Self>,
12293 ) {
12294 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12295
12296 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12297 ..Point::new(
12298 unfold_at.buffer_row.0,
12299 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12300 );
12301
12302 let autoscroll = self
12303 .selections
12304 .all::<Point>(cx)
12305 .iter()
12306 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12307
12308 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12309 }
12310
12311 pub fn unfold_all(
12312 &mut self,
12313 _: &actions::UnfoldAll,
12314 _window: &mut Window,
12315 cx: &mut Context<Self>,
12316 ) {
12317 if self.buffer.read(cx).is_singleton() {
12318 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12319 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12320 } else {
12321 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12322 editor
12323 .update(&mut cx, |editor, cx| {
12324 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12325 editor.unfold_buffer(buffer_id, cx);
12326 }
12327 })
12328 .ok();
12329 });
12330 }
12331 }
12332
12333 pub fn fold_selected_ranges(
12334 &mut self,
12335 _: &FoldSelectedRanges,
12336 window: &mut Window,
12337 cx: &mut Context<Self>,
12338 ) {
12339 let selections = self.selections.all::<Point>(cx);
12340 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12341 let line_mode = self.selections.line_mode;
12342 let ranges = selections
12343 .into_iter()
12344 .map(|s| {
12345 if line_mode {
12346 let start = Point::new(s.start.row, 0);
12347 let end = Point::new(
12348 s.end.row,
12349 display_map
12350 .buffer_snapshot
12351 .line_len(MultiBufferRow(s.end.row)),
12352 );
12353 Crease::simple(start..end, display_map.fold_placeholder.clone())
12354 } else {
12355 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12356 }
12357 })
12358 .collect::<Vec<_>>();
12359 self.fold_creases(ranges, true, window, cx);
12360 }
12361
12362 pub fn fold_ranges<T: ToOffset + Clone>(
12363 &mut self,
12364 ranges: Vec<Range<T>>,
12365 auto_scroll: bool,
12366 window: &mut Window,
12367 cx: &mut Context<Self>,
12368 ) {
12369 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12370 let ranges = ranges
12371 .into_iter()
12372 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12373 .collect::<Vec<_>>();
12374 self.fold_creases(ranges, auto_scroll, window, cx);
12375 }
12376
12377 pub fn fold_creases<T: ToOffset + Clone>(
12378 &mut self,
12379 creases: Vec<Crease<T>>,
12380 auto_scroll: bool,
12381 window: &mut Window,
12382 cx: &mut Context<Self>,
12383 ) {
12384 if creases.is_empty() {
12385 return;
12386 }
12387
12388 let mut buffers_affected = HashSet::default();
12389 let multi_buffer = self.buffer().read(cx);
12390 for crease in &creases {
12391 if let Some((_, buffer, _)) =
12392 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12393 {
12394 buffers_affected.insert(buffer.read(cx).remote_id());
12395 };
12396 }
12397
12398 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12399
12400 if auto_scroll {
12401 self.request_autoscroll(Autoscroll::fit(), cx);
12402 }
12403
12404 cx.notify();
12405
12406 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12407 // Clear diagnostics block when folding a range that contains it.
12408 let snapshot = self.snapshot(window, cx);
12409 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12410 drop(snapshot);
12411 self.active_diagnostics = Some(active_diagnostics);
12412 self.dismiss_diagnostics(cx);
12413 } else {
12414 self.active_diagnostics = Some(active_diagnostics);
12415 }
12416 }
12417
12418 self.scrollbar_marker_state.dirty = true;
12419 }
12420
12421 /// Removes any folds whose ranges intersect any of the given ranges.
12422 pub fn unfold_ranges<T: ToOffset + Clone>(
12423 &mut self,
12424 ranges: &[Range<T>],
12425 inclusive: bool,
12426 auto_scroll: bool,
12427 cx: &mut Context<Self>,
12428 ) {
12429 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12430 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12431 });
12432 }
12433
12434 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12435 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12436 return;
12437 }
12438 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12439 self.display_map
12440 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12441 cx.emit(EditorEvent::BufferFoldToggled {
12442 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12443 folded: true,
12444 });
12445 cx.notify();
12446 }
12447
12448 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12449 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12450 return;
12451 }
12452 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12453 self.display_map.update(cx, |display_map, cx| {
12454 display_map.unfold_buffer(buffer_id, cx);
12455 });
12456 cx.emit(EditorEvent::BufferFoldToggled {
12457 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12458 folded: false,
12459 });
12460 cx.notify();
12461 }
12462
12463 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12464 self.display_map.read(cx).is_buffer_folded(buffer)
12465 }
12466
12467 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12468 self.display_map.read(cx).folded_buffers()
12469 }
12470
12471 /// Removes any folds with the given ranges.
12472 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12473 &mut self,
12474 ranges: &[Range<T>],
12475 type_id: TypeId,
12476 auto_scroll: bool,
12477 cx: &mut Context<Self>,
12478 ) {
12479 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12480 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12481 });
12482 }
12483
12484 fn remove_folds_with<T: ToOffset + Clone>(
12485 &mut self,
12486 ranges: &[Range<T>],
12487 auto_scroll: bool,
12488 cx: &mut Context<Self>,
12489 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12490 ) {
12491 if ranges.is_empty() {
12492 return;
12493 }
12494
12495 let mut buffers_affected = HashSet::default();
12496 let multi_buffer = self.buffer().read(cx);
12497 for range in ranges {
12498 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12499 buffers_affected.insert(buffer.read(cx).remote_id());
12500 };
12501 }
12502
12503 self.display_map.update(cx, update);
12504
12505 if auto_scroll {
12506 self.request_autoscroll(Autoscroll::fit(), cx);
12507 }
12508
12509 cx.notify();
12510 self.scrollbar_marker_state.dirty = true;
12511 self.active_indent_guides_state.dirty = true;
12512 }
12513
12514 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12515 self.display_map.read(cx).fold_placeholder.clone()
12516 }
12517
12518 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12519 self.buffer.update(cx, |buffer, cx| {
12520 buffer.set_all_diff_hunks_expanded(cx);
12521 });
12522 }
12523
12524 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12525 self.distinguish_unstaged_diff_hunks = true;
12526 }
12527
12528 pub fn expand_all_diff_hunks(
12529 &mut self,
12530 _: &ExpandAllHunkDiffs,
12531 _window: &mut Window,
12532 cx: &mut Context<Self>,
12533 ) {
12534 self.buffer.update(cx, |buffer, cx| {
12535 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12536 });
12537 }
12538
12539 pub fn toggle_selected_diff_hunks(
12540 &mut self,
12541 _: &ToggleSelectedDiffHunks,
12542 _window: &mut Window,
12543 cx: &mut Context<Self>,
12544 ) {
12545 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12546 self.toggle_diff_hunks_in_ranges(ranges, cx);
12547 }
12548
12549 fn diff_hunks_in_ranges<'a>(
12550 &'a self,
12551 ranges: &'a [Range<Anchor>],
12552 buffer: &'a MultiBufferSnapshot,
12553 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12554 ranges.iter().flat_map(move |range| {
12555 let end_excerpt_id = range.end.excerpt_id;
12556 let range = range.to_point(buffer);
12557 let mut peek_end = range.end;
12558 if range.end.row < buffer.max_row().0 {
12559 peek_end = Point::new(range.end.row + 1, 0);
12560 }
12561 buffer
12562 .diff_hunks_in_range(range.start..peek_end)
12563 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12564 })
12565 }
12566
12567 pub fn has_stageable_diff_hunks_in_ranges(
12568 &self,
12569 ranges: &[Range<Anchor>],
12570 snapshot: &MultiBufferSnapshot,
12571 ) -> bool {
12572 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12573 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12574 }
12575
12576 pub fn toggle_staged_selected_diff_hunks(
12577 &mut self,
12578 _: &::git::ToggleStaged,
12579 _window: &mut Window,
12580 cx: &mut Context<Self>,
12581 ) {
12582 let snapshot = self.buffer.read(cx).snapshot(cx);
12583 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12584 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12585 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12586 }
12587
12588 pub fn stage_and_next(
12589 &mut self,
12590 _: &::git::StageAndNext,
12591 window: &mut Window,
12592 cx: &mut Context<Self>,
12593 ) {
12594 let head = self.selections.newest_anchor().head();
12595 self.stage_or_unstage_diff_hunks(true, &[head..head], cx);
12596 self.go_to_next_hunk(&Default::default(), window, cx);
12597 }
12598
12599 pub fn unstage_and_next(
12600 &mut self,
12601 _: &::git::UnstageAndNext,
12602 window: &mut Window,
12603 cx: &mut Context<Self>,
12604 ) {
12605 let head = self.selections.newest_anchor().head();
12606 self.stage_or_unstage_diff_hunks(false, &[head..head], cx);
12607 self.go_to_next_hunk(&Default::default(), window, cx);
12608 }
12609
12610 pub fn stage_or_unstage_diff_hunks(
12611 &mut self,
12612 stage: bool,
12613 ranges: &[Range<Anchor>],
12614 cx: &mut Context<Self>,
12615 ) {
12616 let snapshot = self.buffer.read(cx).snapshot(cx);
12617 let Some(project) = &self.project else {
12618 return;
12619 };
12620
12621 let chunk_by = self
12622 .diff_hunks_in_ranges(&ranges, &snapshot)
12623 .chunk_by(|hunk| hunk.buffer_id);
12624 for (buffer_id, hunks) in &chunk_by {
12625 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12626 }
12627 }
12628
12629 fn do_stage_or_unstage(
12630 project: &Entity<Project>,
12631 stage: bool,
12632 buffer_id: BufferId,
12633 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12634 snapshot: &MultiBufferSnapshot,
12635 cx: &mut Context<Self>,
12636 ) {
12637 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12638 log::debug!("no buffer for id");
12639 return;
12640 };
12641 let buffer = buffer.read(cx).snapshot();
12642 let Some((repo, path)) = project
12643 .read(cx)
12644 .repository_and_path_for_buffer_id(buffer_id, cx)
12645 else {
12646 log::debug!("no git repo for buffer id");
12647 return;
12648 };
12649 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12650 log::debug!("no diff for buffer id");
12651 return;
12652 };
12653 let Some(secondary_diff) = diff.secondary_diff() else {
12654 log::debug!("no secondary diff for buffer id");
12655 return;
12656 };
12657
12658 let edits = diff.secondary_edits_for_stage_or_unstage(
12659 stage,
12660 hunks.filter_map(|hunk| {
12661 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12662 return None;
12663 } else if !stage
12664 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12665 {
12666 return None;
12667 }
12668 Some((
12669 hunk.diff_base_byte_range.clone(),
12670 hunk.secondary_diff_base_byte_range.clone(),
12671 hunk.buffer_range.clone(),
12672 ))
12673 }),
12674 &buffer,
12675 );
12676
12677 let Some(index_base) = secondary_diff
12678 .base_text()
12679 .map(|snapshot| snapshot.text.as_rope().clone())
12680 else {
12681 log::debug!("no index base");
12682 return;
12683 };
12684 let index_buffer = cx.new(|cx| {
12685 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12686 });
12687 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12688 index_buffer.edit(edits, None, cx);
12689 index_buffer.snapshot().as_rope().to_string()
12690 });
12691 let new_index_text = if new_index_text.is_empty()
12692 && (diff.is_single_insertion
12693 || buffer
12694 .file()
12695 .map_or(false, |file| file.disk_state() == DiskState::New))
12696 {
12697 log::debug!("removing from index");
12698 None
12699 } else {
12700 Some(new_index_text)
12701 };
12702
12703 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12704 }
12705
12706 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12707 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12708 self.buffer
12709 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12710 }
12711
12712 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12713 self.buffer.update(cx, |buffer, cx| {
12714 let ranges = vec![Anchor::min()..Anchor::max()];
12715 if !buffer.all_diff_hunks_expanded()
12716 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12717 {
12718 buffer.collapse_diff_hunks(ranges, cx);
12719 true
12720 } else {
12721 false
12722 }
12723 })
12724 }
12725
12726 fn toggle_diff_hunks_in_ranges(
12727 &mut self,
12728 ranges: Vec<Range<Anchor>>,
12729 cx: &mut Context<'_, Editor>,
12730 ) {
12731 self.buffer.update(cx, |buffer, cx| {
12732 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12733 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12734 })
12735 }
12736
12737 fn toggle_diff_hunks_in_ranges_narrow(
12738 &mut self,
12739 ranges: Vec<Range<Anchor>>,
12740 cx: &mut Context<'_, Editor>,
12741 ) {
12742 self.buffer.update(cx, |buffer, cx| {
12743 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12744 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12745 })
12746 }
12747
12748 pub(crate) fn apply_all_diff_hunks(
12749 &mut self,
12750 _: &ApplyAllDiffHunks,
12751 window: &mut Window,
12752 cx: &mut Context<Self>,
12753 ) {
12754 let buffers = self.buffer.read(cx).all_buffers();
12755 for branch_buffer in buffers {
12756 branch_buffer.update(cx, |branch_buffer, cx| {
12757 branch_buffer.merge_into_base(Vec::new(), cx);
12758 });
12759 }
12760
12761 if let Some(project) = self.project.clone() {
12762 self.save(true, project, window, cx).detach_and_log_err(cx);
12763 }
12764 }
12765
12766 pub(crate) fn apply_selected_diff_hunks(
12767 &mut self,
12768 _: &ApplyDiffHunk,
12769 window: &mut Window,
12770 cx: &mut Context<Self>,
12771 ) {
12772 let snapshot = self.snapshot(window, cx);
12773 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12774 let mut ranges_by_buffer = HashMap::default();
12775 self.transact(window, cx, |editor, _window, cx| {
12776 for hunk in hunks {
12777 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12778 ranges_by_buffer
12779 .entry(buffer.clone())
12780 .or_insert_with(Vec::new)
12781 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12782 }
12783 }
12784
12785 for (buffer, ranges) in ranges_by_buffer {
12786 buffer.update(cx, |buffer, cx| {
12787 buffer.merge_into_base(ranges, cx);
12788 });
12789 }
12790 });
12791
12792 if let Some(project) = self.project.clone() {
12793 self.save(true, project, window, cx).detach_and_log_err(cx);
12794 }
12795 }
12796
12797 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12798 if hovered != self.gutter_hovered {
12799 self.gutter_hovered = hovered;
12800 cx.notify();
12801 }
12802 }
12803
12804 pub fn insert_blocks(
12805 &mut self,
12806 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12807 autoscroll: Option<Autoscroll>,
12808 cx: &mut Context<Self>,
12809 ) -> Vec<CustomBlockId> {
12810 let blocks = self
12811 .display_map
12812 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12813 if let Some(autoscroll) = autoscroll {
12814 self.request_autoscroll(autoscroll, cx);
12815 }
12816 cx.notify();
12817 blocks
12818 }
12819
12820 pub fn resize_blocks(
12821 &mut self,
12822 heights: HashMap<CustomBlockId, u32>,
12823 autoscroll: Option<Autoscroll>,
12824 cx: &mut Context<Self>,
12825 ) {
12826 self.display_map
12827 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12828 if let Some(autoscroll) = autoscroll {
12829 self.request_autoscroll(autoscroll, cx);
12830 }
12831 cx.notify();
12832 }
12833
12834 pub fn replace_blocks(
12835 &mut self,
12836 renderers: HashMap<CustomBlockId, RenderBlock>,
12837 autoscroll: Option<Autoscroll>,
12838 cx: &mut Context<Self>,
12839 ) {
12840 self.display_map
12841 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12842 if let Some(autoscroll) = autoscroll {
12843 self.request_autoscroll(autoscroll, cx);
12844 }
12845 cx.notify();
12846 }
12847
12848 pub fn remove_blocks(
12849 &mut self,
12850 block_ids: HashSet<CustomBlockId>,
12851 autoscroll: Option<Autoscroll>,
12852 cx: &mut Context<Self>,
12853 ) {
12854 self.display_map.update(cx, |display_map, cx| {
12855 display_map.remove_blocks(block_ids, cx)
12856 });
12857 if let Some(autoscroll) = autoscroll {
12858 self.request_autoscroll(autoscroll, cx);
12859 }
12860 cx.notify();
12861 }
12862
12863 pub fn row_for_block(
12864 &self,
12865 block_id: CustomBlockId,
12866 cx: &mut Context<Self>,
12867 ) -> Option<DisplayRow> {
12868 self.display_map
12869 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12870 }
12871
12872 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12873 self.focused_block = Some(focused_block);
12874 }
12875
12876 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12877 self.focused_block.take()
12878 }
12879
12880 pub fn insert_creases(
12881 &mut self,
12882 creases: impl IntoIterator<Item = Crease<Anchor>>,
12883 cx: &mut Context<Self>,
12884 ) -> Vec<CreaseId> {
12885 self.display_map
12886 .update(cx, |map, cx| map.insert_creases(creases, cx))
12887 }
12888
12889 pub fn remove_creases(
12890 &mut self,
12891 ids: impl IntoIterator<Item = CreaseId>,
12892 cx: &mut Context<Self>,
12893 ) {
12894 self.display_map
12895 .update(cx, |map, cx| map.remove_creases(ids, cx));
12896 }
12897
12898 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12899 self.display_map
12900 .update(cx, |map, cx| map.snapshot(cx))
12901 .longest_row()
12902 }
12903
12904 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12905 self.display_map
12906 .update(cx, |map, cx| map.snapshot(cx))
12907 .max_point()
12908 }
12909
12910 pub fn text(&self, cx: &App) -> String {
12911 self.buffer.read(cx).read(cx).text()
12912 }
12913
12914 pub fn is_empty(&self, cx: &App) -> bool {
12915 self.buffer.read(cx).read(cx).is_empty()
12916 }
12917
12918 pub fn text_option(&self, cx: &App) -> Option<String> {
12919 let text = self.text(cx);
12920 let text = text.trim();
12921
12922 if text.is_empty() {
12923 return None;
12924 }
12925
12926 Some(text.to_string())
12927 }
12928
12929 pub fn set_text(
12930 &mut self,
12931 text: impl Into<Arc<str>>,
12932 window: &mut Window,
12933 cx: &mut Context<Self>,
12934 ) {
12935 self.transact(window, cx, |this, _, cx| {
12936 this.buffer
12937 .read(cx)
12938 .as_singleton()
12939 .expect("you can only call set_text on editors for singleton buffers")
12940 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12941 });
12942 }
12943
12944 pub fn display_text(&self, cx: &mut App) -> String {
12945 self.display_map
12946 .update(cx, |map, cx| map.snapshot(cx))
12947 .text()
12948 }
12949
12950 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12951 let mut wrap_guides = smallvec::smallvec![];
12952
12953 if self.show_wrap_guides == Some(false) {
12954 return wrap_guides;
12955 }
12956
12957 let settings = self.buffer.read(cx).settings_at(0, cx);
12958 if settings.show_wrap_guides {
12959 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12960 wrap_guides.push((soft_wrap as usize, true));
12961 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12962 wrap_guides.push((soft_wrap as usize, true));
12963 }
12964 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12965 }
12966
12967 wrap_guides
12968 }
12969
12970 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12971 let settings = self.buffer.read(cx).settings_at(0, cx);
12972 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12973 match mode {
12974 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12975 SoftWrap::None
12976 }
12977 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12978 language_settings::SoftWrap::PreferredLineLength => {
12979 SoftWrap::Column(settings.preferred_line_length)
12980 }
12981 language_settings::SoftWrap::Bounded => {
12982 SoftWrap::Bounded(settings.preferred_line_length)
12983 }
12984 }
12985 }
12986
12987 pub fn set_soft_wrap_mode(
12988 &mut self,
12989 mode: language_settings::SoftWrap,
12990
12991 cx: &mut Context<Self>,
12992 ) {
12993 self.soft_wrap_mode_override = Some(mode);
12994 cx.notify();
12995 }
12996
12997 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12998 self.text_style_refinement = Some(style);
12999 }
13000
13001 /// called by the Element so we know what style we were most recently rendered with.
13002 pub(crate) fn set_style(
13003 &mut self,
13004 style: EditorStyle,
13005 window: &mut Window,
13006 cx: &mut Context<Self>,
13007 ) {
13008 let rem_size = window.rem_size();
13009 self.display_map.update(cx, |map, cx| {
13010 map.set_font(
13011 style.text.font(),
13012 style.text.font_size.to_pixels(rem_size),
13013 cx,
13014 )
13015 });
13016 self.style = Some(style);
13017 }
13018
13019 pub fn style(&self) -> Option<&EditorStyle> {
13020 self.style.as_ref()
13021 }
13022
13023 // Called by the element. This method is not designed to be called outside of the editor
13024 // element's layout code because it does not notify when rewrapping is computed synchronously.
13025 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13026 self.display_map
13027 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13028 }
13029
13030 pub fn set_soft_wrap(&mut self) {
13031 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13032 }
13033
13034 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13035 if self.soft_wrap_mode_override.is_some() {
13036 self.soft_wrap_mode_override.take();
13037 } else {
13038 let soft_wrap = match self.soft_wrap_mode(cx) {
13039 SoftWrap::GitDiff => return,
13040 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13041 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13042 language_settings::SoftWrap::None
13043 }
13044 };
13045 self.soft_wrap_mode_override = Some(soft_wrap);
13046 }
13047 cx.notify();
13048 }
13049
13050 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13051 let Some(workspace) = self.workspace() else {
13052 return;
13053 };
13054 let fs = workspace.read(cx).app_state().fs.clone();
13055 let current_show = TabBarSettings::get_global(cx).show;
13056 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13057 setting.show = Some(!current_show);
13058 });
13059 }
13060
13061 pub fn toggle_indent_guides(
13062 &mut self,
13063 _: &ToggleIndentGuides,
13064 _: &mut Window,
13065 cx: &mut Context<Self>,
13066 ) {
13067 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13068 self.buffer
13069 .read(cx)
13070 .settings_at(0, cx)
13071 .indent_guides
13072 .enabled
13073 });
13074 self.show_indent_guides = Some(!currently_enabled);
13075 cx.notify();
13076 }
13077
13078 fn should_show_indent_guides(&self) -> Option<bool> {
13079 self.show_indent_guides
13080 }
13081
13082 pub fn toggle_line_numbers(
13083 &mut self,
13084 _: &ToggleLineNumbers,
13085 _: &mut Window,
13086 cx: &mut Context<Self>,
13087 ) {
13088 let mut editor_settings = EditorSettings::get_global(cx).clone();
13089 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13090 EditorSettings::override_global(editor_settings, cx);
13091 }
13092
13093 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13094 self.use_relative_line_numbers
13095 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13096 }
13097
13098 pub fn toggle_relative_line_numbers(
13099 &mut self,
13100 _: &ToggleRelativeLineNumbers,
13101 _: &mut Window,
13102 cx: &mut Context<Self>,
13103 ) {
13104 let is_relative = self.should_use_relative_line_numbers(cx);
13105 self.set_relative_line_number(Some(!is_relative), cx)
13106 }
13107
13108 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13109 self.use_relative_line_numbers = is_relative;
13110 cx.notify();
13111 }
13112
13113 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13114 self.show_gutter = show_gutter;
13115 cx.notify();
13116 }
13117
13118 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13119 self.show_scrollbars = show_scrollbars;
13120 cx.notify();
13121 }
13122
13123 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13124 self.show_line_numbers = Some(show_line_numbers);
13125 cx.notify();
13126 }
13127
13128 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13129 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13130 cx.notify();
13131 }
13132
13133 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13134 self.show_code_actions = Some(show_code_actions);
13135 cx.notify();
13136 }
13137
13138 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13139 self.show_runnables = Some(show_runnables);
13140 cx.notify();
13141 }
13142
13143 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13144 if self.display_map.read(cx).masked != masked {
13145 self.display_map.update(cx, |map, _| map.masked = masked);
13146 }
13147 cx.notify()
13148 }
13149
13150 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13151 self.show_wrap_guides = Some(show_wrap_guides);
13152 cx.notify();
13153 }
13154
13155 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13156 self.show_indent_guides = Some(show_indent_guides);
13157 cx.notify();
13158 }
13159
13160 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13161 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13162 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13163 if let Some(dir) = file.abs_path(cx).parent() {
13164 return Some(dir.to_owned());
13165 }
13166 }
13167
13168 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13169 return Some(project_path.path.to_path_buf());
13170 }
13171 }
13172
13173 None
13174 }
13175
13176 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13177 self.active_excerpt(cx)?
13178 .1
13179 .read(cx)
13180 .file()
13181 .and_then(|f| f.as_local())
13182 }
13183
13184 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13185 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13186 let buffer = buffer.read(cx);
13187 if let Some(project_path) = buffer.project_path(cx) {
13188 let project = self.project.as_ref()?.read(cx);
13189 project.absolute_path(&project_path, cx)
13190 } else {
13191 buffer
13192 .file()
13193 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13194 }
13195 })
13196 }
13197
13198 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13199 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13200 let project_path = buffer.read(cx).project_path(cx)?;
13201 let project = self.project.as_ref()?.read(cx);
13202 let entry = project.entry_for_path(&project_path, cx)?;
13203 let path = entry.path.to_path_buf();
13204 Some(path)
13205 })
13206 }
13207
13208 pub fn reveal_in_finder(
13209 &mut self,
13210 _: &RevealInFileManager,
13211 _window: &mut Window,
13212 cx: &mut Context<Self>,
13213 ) {
13214 if let Some(target) = self.target_file(cx) {
13215 cx.reveal_path(&target.abs_path(cx));
13216 }
13217 }
13218
13219 pub fn copy_path(
13220 &mut self,
13221 _: &zed_actions::workspace::CopyPath,
13222 _window: &mut Window,
13223 cx: &mut Context<Self>,
13224 ) {
13225 if let Some(path) = self.target_file_abs_path(cx) {
13226 if let Some(path) = path.to_str() {
13227 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13228 }
13229 }
13230 }
13231
13232 pub fn copy_relative_path(
13233 &mut self,
13234 _: &zed_actions::workspace::CopyRelativePath,
13235 _window: &mut Window,
13236 cx: &mut Context<Self>,
13237 ) {
13238 if let Some(path) = self.target_file_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_file_name_without_extension(
13246 &mut self,
13247 _: &CopyFileNameWithoutExtension,
13248 _: &mut Window,
13249 cx: &mut Context<Self>,
13250 ) {
13251 if let Some(file) = self.target_file(cx) {
13252 if let Some(file_stem) = file.path().file_stem() {
13253 if let Some(name) = file_stem.to_str() {
13254 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13255 }
13256 }
13257 }
13258 }
13259
13260 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13261 if let Some(file) = self.target_file(cx) {
13262 if let Some(file_name) = file.path().file_name() {
13263 if let Some(name) = file_name.to_str() {
13264 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13265 }
13266 }
13267 }
13268 }
13269
13270 pub fn toggle_git_blame(
13271 &mut self,
13272 _: &ToggleGitBlame,
13273 window: &mut Window,
13274 cx: &mut Context<Self>,
13275 ) {
13276 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13277
13278 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13279 self.start_git_blame(true, window, cx);
13280 }
13281
13282 cx.notify();
13283 }
13284
13285 pub fn toggle_git_blame_inline(
13286 &mut self,
13287 _: &ToggleGitBlameInline,
13288 window: &mut Window,
13289 cx: &mut Context<Self>,
13290 ) {
13291 self.toggle_git_blame_inline_internal(true, window, cx);
13292 cx.notify();
13293 }
13294
13295 pub fn git_blame_inline_enabled(&self) -> bool {
13296 self.git_blame_inline_enabled
13297 }
13298
13299 pub fn toggle_selection_menu(
13300 &mut self,
13301 _: &ToggleSelectionMenu,
13302 _: &mut Window,
13303 cx: &mut Context<Self>,
13304 ) {
13305 self.show_selection_menu = self
13306 .show_selection_menu
13307 .map(|show_selections_menu| !show_selections_menu)
13308 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13309
13310 cx.notify();
13311 }
13312
13313 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13314 self.show_selection_menu
13315 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13316 }
13317
13318 fn start_git_blame(
13319 &mut self,
13320 user_triggered: bool,
13321 window: &mut Window,
13322 cx: &mut Context<Self>,
13323 ) {
13324 if let Some(project) = self.project.as_ref() {
13325 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13326 return;
13327 };
13328
13329 if buffer.read(cx).file().is_none() {
13330 return;
13331 }
13332
13333 let focused = self.focus_handle(cx).contains_focused(window, cx);
13334
13335 let project = project.clone();
13336 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13337 self.blame_subscription =
13338 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13339 self.blame = Some(blame);
13340 }
13341 }
13342
13343 fn toggle_git_blame_inline_internal(
13344 &mut self,
13345 user_triggered: bool,
13346 window: &mut Window,
13347 cx: &mut Context<Self>,
13348 ) {
13349 if self.git_blame_inline_enabled {
13350 self.git_blame_inline_enabled = false;
13351 self.show_git_blame_inline = false;
13352 self.show_git_blame_inline_delay_task.take();
13353 } else {
13354 self.git_blame_inline_enabled = true;
13355 self.start_git_blame_inline(user_triggered, window, cx);
13356 }
13357
13358 cx.notify();
13359 }
13360
13361 fn start_git_blame_inline(
13362 &mut self,
13363 user_triggered: bool,
13364 window: &mut Window,
13365 cx: &mut Context<Self>,
13366 ) {
13367 self.start_git_blame(user_triggered, window, cx);
13368
13369 if ProjectSettings::get_global(cx)
13370 .git
13371 .inline_blame_delay()
13372 .is_some()
13373 {
13374 self.start_inline_blame_timer(window, cx);
13375 } else {
13376 self.show_git_blame_inline = true
13377 }
13378 }
13379
13380 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13381 self.blame.as_ref()
13382 }
13383
13384 pub fn show_git_blame_gutter(&self) -> bool {
13385 self.show_git_blame_gutter
13386 }
13387
13388 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13389 self.show_git_blame_gutter && self.has_blame_entries(cx)
13390 }
13391
13392 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13393 self.show_git_blame_inline
13394 && (self.focus_handle.is_focused(window)
13395 || self
13396 .git_blame_inline_tooltip
13397 .as_ref()
13398 .and_then(|t| t.upgrade())
13399 .is_some())
13400 && !self.newest_selection_head_on_empty_line(cx)
13401 && self.has_blame_entries(cx)
13402 }
13403
13404 fn has_blame_entries(&self, cx: &App) -> bool {
13405 self.blame()
13406 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13407 }
13408
13409 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13410 let cursor_anchor = self.selections.newest_anchor().head();
13411
13412 let snapshot = self.buffer.read(cx).snapshot(cx);
13413 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13414
13415 snapshot.line_len(buffer_row) == 0
13416 }
13417
13418 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13419 let buffer_and_selection = maybe!({
13420 let selection = self.selections.newest::<Point>(cx);
13421 let selection_range = selection.range();
13422
13423 let multi_buffer = self.buffer().read(cx);
13424 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13425 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13426
13427 let (buffer, range, _) = if selection.reversed {
13428 buffer_ranges.first()
13429 } else {
13430 buffer_ranges.last()
13431 }?;
13432
13433 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13434 ..text::ToPoint::to_point(&range.end, &buffer).row;
13435 Some((
13436 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13437 selection,
13438 ))
13439 });
13440
13441 let Some((buffer, selection)) = buffer_and_selection else {
13442 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13443 };
13444
13445 let Some(project) = self.project.as_ref() else {
13446 return Task::ready(Err(anyhow!("editor does not have project")));
13447 };
13448
13449 project.update(cx, |project, cx| {
13450 project.get_permalink_to_line(&buffer, selection, cx)
13451 })
13452 }
13453
13454 pub fn copy_permalink_to_line(
13455 &mut self,
13456 _: &CopyPermalinkToLine,
13457 window: &mut Window,
13458 cx: &mut Context<Self>,
13459 ) {
13460 let permalink_task = self.get_permalink_to_line(cx);
13461 let workspace = self.workspace();
13462
13463 cx.spawn_in(window, |_, mut cx| async move {
13464 match permalink_task.await {
13465 Ok(permalink) => {
13466 cx.update(|_, cx| {
13467 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13468 })
13469 .ok();
13470 }
13471 Err(err) => {
13472 let message = format!("Failed to copy permalink: {err}");
13473
13474 Err::<(), anyhow::Error>(err).log_err();
13475
13476 if let Some(workspace) = workspace {
13477 workspace
13478 .update_in(&mut cx, |workspace, _, cx| {
13479 struct CopyPermalinkToLine;
13480
13481 workspace.show_toast(
13482 Toast::new(
13483 NotificationId::unique::<CopyPermalinkToLine>(),
13484 message,
13485 ),
13486 cx,
13487 )
13488 })
13489 .ok();
13490 }
13491 }
13492 }
13493 })
13494 .detach();
13495 }
13496
13497 pub fn copy_file_location(
13498 &mut self,
13499 _: &CopyFileLocation,
13500 _: &mut Window,
13501 cx: &mut Context<Self>,
13502 ) {
13503 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13504 if let Some(file) = self.target_file(cx) {
13505 if let Some(path) = file.path().to_str() {
13506 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13507 }
13508 }
13509 }
13510
13511 pub fn open_permalink_to_line(
13512 &mut self,
13513 _: &OpenPermalinkToLine,
13514 window: &mut Window,
13515 cx: &mut Context<Self>,
13516 ) {
13517 let permalink_task = self.get_permalink_to_line(cx);
13518 let workspace = self.workspace();
13519
13520 cx.spawn_in(window, |_, mut cx| async move {
13521 match permalink_task.await {
13522 Ok(permalink) => {
13523 cx.update(|_, cx| {
13524 cx.open_url(permalink.as_ref());
13525 })
13526 .ok();
13527 }
13528 Err(err) => {
13529 let message = format!("Failed to open permalink: {err}");
13530
13531 Err::<(), anyhow::Error>(err).log_err();
13532
13533 if let Some(workspace) = workspace {
13534 workspace
13535 .update(&mut cx, |workspace, cx| {
13536 struct OpenPermalinkToLine;
13537
13538 workspace.show_toast(
13539 Toast::new(
13540 NotificationId::unique::<OpenPermalinkToLine>(),
13541 message,
13542 ),
13543 cx,
13544 )
13545 })
13546 .ok();
13547 }
13548 }
13549 }
13550 })
13551 .detach();
13552 }
13553
13554 pub fn insert_uuid_v4(
13555 &mut self,
13556 _: &InsertUuidV4,
13557 window: &mut Window,
13558 cx: &mut Context<Self>,
13559 ) {
13560 self.insert_uuid(UuidVersion::V4, window, cx);
13561 }
13562
13563 pub fn insert_uuid_v7(
13564 &mut self,
13565 _: &InsertUuidV7,
13566 window: &mut Window,
13567 cx: &mut Context<Self>,
13568 ) {
13569 self.insert_uuid(UuidVersion::V7, window, cx);
13570 }
13571
13572 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13573 self.transact(window, cx, |this, window, cx| {
13574 let edits = this
13575 .selections
13576 .all::<Point>(cx)
13577 .into_iter()
13578 .map(|selection| {
13579 let uuid = match version {
13580 UuidVersion::V4 => uuid::Uuid::new_v4(),
13581 UuidVersion::V7 => uuid::Uuid::now_v7(),
13582 };
13583
13584 (selection.range(), uuid.to_string())
13585 });
13586 this.edit(edits, cx);
13587 this.refresh_inline_completion(true, false, window, cx);
13588 });
13589 }
13590
13591 pub fn open_selections_in_multibuffer(
13592 &mut self,
13593 _: &OpenSelectionsInMultibuffer,
13594 window: &mut Window,
13595 cx: &mut Context<Self>,
13596 ) {
13597 let multibuffer = self.buffer.read(cx);
13598
13599 let Some(buffer) = multibuffer.as_singleton() else {
13600 return;
13601 };
13602
13603 let Some(workspace) = self.workspace() else {
13604 return;
13605 };
13606
13607 let locations = self
13608 .selections
13609 .disjoint_anchors()
13610 .iter()
13611 .map(|range| Location {
13612 buffer: buffer.clone(),
13613 range: range.start.text_anchor..range.end.text_anchor,
13614 })
13615 .collect::<Vec<_>>();
13616
13617 let title = multibuffer.title(cx).to_string();
13618
13619 cx.spawn_in(window, |_, mut cx| async move {
13620 workspace.update_in(&mut cx, |workspace, window, cx| {
13621 Self::open_locations_in_multibuffer(
13622 workspace,
13623 locations,
13624 format!("Selections for '{title}'"),
13625 false,
13626 MultibufferSelectionMode::All,
13627 window,
13628 cx,
13629 );
13630 })
13631 })
13632 .detach();
13633 }
13634
13635 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13636 /// last highlight added will be used.
13637 ///
13638 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13639 pub fn highlight_rows<T: 'static>(
13640 &mut self,
13641 range: Range<Anchor>,
13642 color: Hsla,
13643 should_autoscroll: bool,
13644 cx: &mut Context<Self>,
13645 ) {
13646 let snapshot = self.buffer().read(cx).snapshot(cx);
13647 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13648 let ix = row_highlights.binary_search_by(|highlight| {
13649 Ordering::Equal
13650 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13651 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13652 });
13653
13654 if let Err(mut ix) = ix {
13655 let index = post_inc(&mut self.highlight_order);
13656
13657 // If this range intersects with the preceding highlight, then merge it with
13658 // the preceding highlight. Otherwise insert a new highlight.
13659 let mut merged = false;
13660 if ix > 0 {
13661 let prev_highlight = &mut row_highlights[ix - 1];
13662 if prev_highlight
13663 .range
13664 .end
13665 .cmp(&range.start, &snapshot)
13666 .is_ge()
13667 {
13668 ix -= 1;
13669 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13670 prev_highlight.range.end = range.end;
13671 }
13672 merged = true;
13673 prev_highlight.index = index;
13674 prev_highlight.color = color;
13675 prev_highlight.should_autoscroll = should_autoscroll;
13676 }
13677 }
13678
13679 if !merged {
13680 row_highlights.insert(
13681 ix,
13682 RowHighlight {
13683 range: range.clone(),
13684 index,
13685 color,
13686 should_autoscroll,
13687 },
13688 );
13689 }
13690
13691 // If any of the following highlights intersect with this one, merge them.
13692 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13693 let highlight = &row_highlights[ix];
13694 if next_highlight
13695 .range
13696 .start
13697 .cmp(&highlight.range.end, &snapshot)
13698 .is_le()
13699 {
13700 if next_highlight
13701 .range
13702 .end
13703 .cmp(&highlight.range.end, &snapshot)
13704 .is_gt()
13705 {
13706 row_highlights[ix].range.end = next_highlight.range.end;
13707 }
13708 row_highlights.remove(ix + 1);
13709 } else {
13710 break;
13711 }
13712 }
13713 }
13714 }
13715
13716 /// Remove any highlighted row ranges of the given type that intersect the
13717 /// given ranges.
13718 pub fn remove_highlighted_rows<T: 'static>(
13719 &mut self,
13720 ranges_to_remove: Vec<Range<Anchor>>,
13721 cx: &mut Context<Self>,
13722 ) {
13723 let snapshot = self.buffer().read(cx).snapshot(cx);
13724 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13725 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13726 row_highlights.retain(|highlight| {
13727 while let Some(range_to_remove) = ranges_to_remove.peek() {
13728 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13729 Ordering::Less | Ordering::Equal => {
13730 ranges_to_remove.next();
13731 }
13732 Ordering::Greater => {
13733 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13734 Ordering::Less | Ordering::Equal => {
13735 return false;
13736 }
13737 Ordering::Greater => break,
13738 }
13739 }
13740 }
13741 }
13742
13743 true
13744 })
13745 }
13746
13747 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13748 pub fn clear_row_highlights<T: 'static>(&mut self) {
13749 self.highlighted_rows.remove(&TypeId::of::<T>());
13750 }
13751
13752 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13753 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13754 self.highlighted_rows
13755 .get(&TypeId::of::<T>())
13756 .map_or(&[] as &[_], |vec| vec.as_slice())
13757 .iter()
13758 .map(|highlight| (highlight.range.clone(), highlight.color))
13759 }
13760
13761 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13762 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13763 /// Allows to ignore certain kinds of highlights.
13764 pub fn highlighted_display_rows(
13765 &self,
13766 window: &mut Window,
13767 cx: &mut App,
13768 ) -> BTreeMap<DisplayRow, Background> {
13769 let snapshot = self.snapshot(window, cx);
13770 let mut used_highlight_orders = HashMap::default();
13771 self.highlighted_rows
13772 .iter()
13773 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13774 .fold(
13775 BTreeMap::<DisplayRow, Background>::new(),
13776 |mut unique_rows, highlight| {
13777 let start = highlight.range.start.to_display_point(&snapshot);
13778 let end = highlight.range.end.to_display_point(&snapshot);
13779 let start_row = start.row().0;
13780 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13781 && end.column() == 0
13782 {
13783 end.row().0.saturating_sub(1)
13784 } else {
13785 end.row().0
13786 };
13787 for row in start_row..=end_row {
13788 let used_index =
13789 used_highlight_orders.entry(row).or_insert(highlight.index);
13790 if highlight.index >= *used_index {
13791 *used_index = highlight.index;
13792 unique_rows.insert(DisplayRow(row), highlight.color.into());
13793 }
13794 }
13795 unique_rows
13796 },
13797 )
13798 }
13799
13800 pub fn highlighted_display_row_for_autoscroll(
13801 &self,
13802 snapshot: &DisplaySnapshot,
13803 ) -> Option<DisplayRow> {
13804 self.highlighted_rows
13805 .values()
13806 .flat_map(|highlighted_rows| highlighted_rows.iter())
13807 .filter_map(|highlight| {
13808 if highlight.should_autoscroll {
13809 Some(highlight.range.start.to_display_point(snapshot).row())
13810 } else {
13811 None
13812 }
13813 })
13814 .min()
13815 }
13816
13817 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13818 self.highlight_background::<SearchWithinRange>(
13819 ranges,
13820 |colors| colors.editor_document_highlight_read_background,
13821 cx,
13822 )
13823 }
13824
13825 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13826 self.breadcrumb_header = Some(new_header);
13827 }
13828
13829 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13830 self.clear_background_highlights::<SearchWithinRange>(cx);
13831 }
13832
13833 pub fn highlight_background<T: 'static>(
13834 &mut self,
13835 ranges: &[Range<Anchor>],
13836 color_fetcher: fn(&ThemeColors) -> Hsla,
13837 cx: &mut Context<Self>,
13838 ) {
13839 self.background_highlights
13840 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13841 self.scrollbar_marker_state.dirty = true;
13842 cx.notify();
13843 }
13844
13845 pub fn clear_background_highlights<T: 'static>(
13846 &mut self,
13847 cx: &mut Context<Self>,
13848 ) -> Option<BackgroundHighlight> {
13849 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13850 if !text_highlights.1.is_empty() {
13851 self.scrollbar_marker_state.dirty = true;
13852 cx.notify();
13853 }
13854 Some(text_highlights)
13855 }
13856
13857 pub fn highlight_gutter<T: 'static>(
13858 &mut self,
13859 ranges: &[Range<Anchor>],
13860 color_fetcher: fn(&App) -> Hsla,
13861 cx: &mut Context<Self>,
13862 ) {
13863 self.gutter_highlights
13864 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13865 cx.notify();
13866 }
13867
13868 pub fn clear_gutter_highlights<T: 'static>(
13869 &mut self,
13870 cx: &mut Context<Self>,
13871 ) -> Option<GutterHighlight> {
13872 cx.notify();
13873 self.gutter_highlights.remove(&TypeId::of::<T>())
13874 }
13875
13876 #[cfg(feature = "test-support")]
13877 pub fn all_text_background_highlights(
13878 &self,
13879 window: &mut Window,
13880 cx: &mut Context<Self>,
13881 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13882 let snapshot = self.snapshot(window, cx);
13883 let buffer = &snapshot.buffer_snapshot;
13884 let start = buffer.anchor_before(0);
13885 let end = buffer.anchor_after(buffer.len());
13886 let theme = cx.theme().colors();
13887 self.background_highlights_in_range(start..end, &snapshot, theme)
13888 }
13889
13890 #[cfg(feature = "test-support")]
13891 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13892 let snapshot = self.buffer().read(cx).snapshot(cx);
13893
13894 let highlights = self
13895 .background_highlights
13896 .get(&TypeId::of::<items::BufferSearchHighlights>());
13897
13898 if let Some((_color, ranges)) = highlights {
13899 ranges
13900 .iter()
13901 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13902 .collect_vec()
13903 } else {
13904 vec![]
13905 }
13906 }
13907
13908 fn document_highlights_for_position<'a>(
13909 &'a self,
13910 position: Anchor,
13911 buffer: &'a MultiBufferSnapshot,
13912 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13913 let read_highlights = self
13914 .background_highlights
13915 .get(&TypeId::of::<DocumentHighlightRead>())
13916 .map(|h| &h.1);
13917 let write_highlights = self
13918 .background_highlights
13919 .get(&TypeId::of::<DocumentHighlightWrite>())
13920 .map(|h| &h.1);
13921 let left_position = position.bias_left(buffer);
13922 let right_position = position.bias_right(buffer);
13923 read_highlights
13924 .into_iter()
13925 .chain(write_highlights)
13926 .flat_map(move |ranges| {
13927 let start_ix = match ranges.binary_search_by(|probe| {
13928 let cmp = probe.end.cmp(&left_position, buffer);
13929 if cmp.is_ge() {
13930 Ordering::Greater
13931 } else {
13932 Ordering::Less
13933 }
13934 }) {
13935 Ok(i) | Err(i) => i,
13936 };
13937
13938 ranges[start_ix..]
13939 .iter()
13940 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13941 })
13942 }
13943
13944 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13945 self.background_highlights
13946 .get(&TypeId::of::<T>())
13947 .map_or(false, |(_, highlights)| !highlights.is_empty())
13948 }
13949
13950 pub fn background_highlights_in_range(
13951 &self,
13952 search_range: Range<Anchor>,
13953 display_snapshot: &DisplaySnapshot,
13954 theme: &ThemeColors,
13955 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13956 let mut results = Vec::new();
13957 for (color_fetcher, ranges) in self.background_highlights.values() {
13958 let color = color_fetcher(theme);
13959 let start_ix = match ranges.binary_search_by(|probe| {
13960 let cmp = probe
13961 .end
13962 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13963 if cmp.is_gt() {
13964 Ordering::Greater
13965 } else {
13966 Ordering::Less
13967 }
13968 }) {
13969 Ok(i) | Err(i) => i,
13970 };
13971 for range in &ranges[start_ix..] {
13972 if range
13973 .start
13974 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13975 .is_ge()
13976 {
13977 break;
13978 }
13979
13980 let start = range.start.to_display_point(display_snapshot);
13981 let end = range.end.to_display_point(display_snapshot);
13982 results.push((start..end, color))
13983 }
13984 }
13985 results
13986 }
13987
13988 pub fn background_highlight_row_ranges<T: 'static>(
13989 &self,
13990 search_range: Range<Anchor>,
13991 display_snapshot: &DisplaySnapshot,
13992 count: usize,
13993 ) -> Vec<RangeInclusive<DisplayPoint>> {
13994 let mut results = Vec::new();
13995 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13996 return vec![];
13997 };
13998
13999 let start_ix = match ranges.binary_search_by(|probe| {
14000 let cmp = probe
14001 .end
14002 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14003 if cmp.is_gt() {
14004 Ordering::Greater
14005 } else {
14006 Ordering::Less
14007 }
14008 }) {
14009 Ok(i) | Err(i) => i,
14010 };
14011 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14012 if let (Some(start_display), Some(end_display)) = (start, end) {
14013 results.push(
14014 start_display.to_display_point(display_snapshot)
14015 ..=end_display.to_display_point(display_snapshot),
14016 );
14017 }
14018 };
14019 let mut start_row: Option<Point> = None;
14020 let mut end_row: Option<Point> = None;
14021 if ranges.len() > count {
14022 return Vec::new();
14023 }
14024 for range in &ranges[start_ix..] {
14025 if range
14026 .start
14027 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14028 .is_ge()
14029 {
14030 break;
14031 }
14032 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14033 if let Some(current_row) = &end_row {
14034 if end.row == current_row.row {
14035 continue;
14036 }
14037 }
14038 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14039 if start_row.is_none() {
14040 assert_eq!(end_row, None);
14041 start_row = Some(start);
14042 end_row = Some(end);
14043 continue;
14044 }
14045 if let Some(current_end) = end_row.as_mut() {
14046 if start.row > current_end.row + 1 {
14047 push_region(start_row, end_row);
14048 start_row = Some(start);
14049 end_row = Some(end);
14050 } else {
14051 // Merge two hunks.
14052 *current_end = end;
14053 }
14054 } else {
14055 unreachable!();
14056 }
14057 }
14058 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14059 push_region(start_row, end_row);
14060 results
14061 }
14062
14063 pub fn gutter_highlights_in_range(
14064 &self,
14065 search_range: Range<Anchor>,
14066 display_snapshot: &DisplaySnapshot,
14067 cx: &App,
14068 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14069 let mut results = Vec::new();
14070 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14071 let color = color_fetcher(cx);
14072 let start_ix = match ranges.binary_search_by(|probe| {
14073 let cmp = probe
14074 .end
14075 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14076 if cmp.is_gt() {
14077 Ordering::Greater
14078 } else {
14079 Ordering::Less
14080 }
14081 }) {
14082 Ok(i) | Err(i) => i,
14083 };
14084 for range in &ranges[start_ix..] {
14085 if range
14086 .start
14087 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14088 .is_ge()
14089 {
14090 break;
14091 }
14092
14093 let start = range.start.to_display_point(display_snapshot);
14094 let end = range.end.to_display_point(display_snapshot);
14095 results.push((start..end, color))
14096 }
14097 }
14098 results
14099 }
14100
14101 /// Get the text ranges corresponding to the redaction query
14102 pub fn redacted_ranges(
14103 &self,
14104 search_range: Range<Anchor>,
14105 display_snapshot: &DisplaySnapshot,
14106 cx: &App,
14107 ) -> Vec<Range<DisplayPoint>> {
14108 display_snapshot
14109 .buffer_snapshot
14110 .redacted_ranges(search_range, |file| {
14111 if let Some(file) = file {
14112 file.is_private()
14113 && EditorSettings::get(
14114 Some(SettingsLocation {
14115 worktree_id: file.worktree_id(cx),
14116 path: file.path().as_ref(),
14117 }),
14118 cx,
14119 )
14120 .redact_private_values
14121 } else {
14122 false
14123 }
14124 })
14125 .map(|range| {
14126 range.start.to_display_point(display_snapshot)
14127 ..range.end.to_display_point(display_snapshot)
14128 })
14129 .collect()
14130 }
14131
14132 pub fn highlight_text<T: 'static>(
14133 &mut self,
14134 ranges: Vec<Range<Anchor>>,
14135 style: HighlightStyle,
14136 cx: &mut Context<Self>,
14137 ) {
14138 self.display_map.update(cx, |map, _| {
14139 map.highlight_text(TypeId::of::<T>(), ranges, style)
14140 });
14141 cx.notify();
14142 }
14143
14144 pub(crate) fn highlight_inlays<T: 'static>(
14145 &mut self,
14146 highlights: Vec<InlayHighlight>,
14147 style: HighlightStyle,
14148 cx: &mut Context<Self>,
14149 ) {
14150 self.display_map.update(cx, |map, _| {
14151 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14152 });
14153 cx.notify();
14154 }
14155
14156 pub fn text_highlights<'a, T: 'static>(
14157 &'a self,
14158 cx: &'a App,
14159 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14160 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14161 }
14162
14163 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14164 let cleared = self
14165 .display_map
14166 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14167 if cleared {
14168 cx.notify();
14169 }
14170 }
14171
14172 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14173 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14174 && self.focus_handle.is_focused(window)
14175 }
14176
14177 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14178 self.show_cursor_when_unfocused = is_enabled;
14179 cx.notify();
14180 }
14181
14182 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14183 cx.notify();
14184 }
14185
14186 fn on_buffer_event(
14187 &mut self,
14188 multibuffer: &Entity<MultiBuffer>,
14189 event: &multi_buffer::Event,
14190 window: &mut Window,
14191 cx: &mut Context<Self>,
14192 ) {
14193 match event {
14194 multi_buffer::Event::Edited {
14195 singleton_buffer_edited,
14196 edited_buffer: buffer_edited,
14197 } => {
14198 self.scrollbar_marker_state.dirty = true;
14199 self.active_indent_guides_state.dirty = true;
14200 self.refresh_active_diagnostics(cx);
14201 self.refresh_code_actions(window, cx);
14202 if self.has_active_inline_completion() {
14203 self.update_visible_inline_completion(window, cx);
14204 }
14205 if let Some(buffer) = buffer_edited {
14206 let buffer_id = buffer.read(cx).remote_id();
14207 if !self.registered_buffers.contains_key(&buffer_id) {
14208 if let Some(project) = self.project.as_ref() {
14209 project.update(cx, |project, cx| {
14210 self.registered_buffers.insert(
14211 buffer_id,
14212 project.register_buffer_with_language_servers(&buffer, cx),
14213 );
14214 })
14215 }
14216 }
14217 }
14218 cx.emit(EditorEvent::BufferEdited);
14219 cx.emit(SearchEvent::MatchesInvalidated);
14220 if *singleton_buffer_edited {
14221 if let Some(project) = &self.project {
14222 #[allow(clippy::mutable_key_type)]
14223 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14224 multibuffer
14225 .all_buffers()
14226 .into_iter()
14227 .filter_map(|buffer| {
14228 buffer.update(cx, |buffer, cx| {
14229 let language = buffer.language()?;
14230 let should_discard = project.update(cx, |project, cx| {
14231 project.is_local()
14232 && !project.has_language_servers_for(buffer, cx)
14233 });
14234 should_discard.not().then_some(language.clone())
14235 })
14236 })
14237 .collect::<HashSet<_>>()
14238 });
14239 if !languages_affected.is_empty() {
14240 self.refresh_inlay_hints(
14241 InlayHintRefreshReason::BufferEdited(languages_affected),
14242 cx,
14243 );
14244 }
14245 }
14246 }
14247
14248 let Some(project) = &self.project else { return };
14249 let (telemetry, is_via_ssh) = {
14250 let project = project.read(cx);
14251 let telemetry = project.client().telemetry().clone();
14252 let is_via_ssh = project.is_via_ssh();
14253 (telemetry, is_via_ssh)
14254 };
14255 refresh_linked_ranges(self, window, cx);
14256 telemetry.log_edit_event("editor", is_via_ssh);
14257 }
14258 multi_buffer::Event::ExcerptsAdded {
14259 buffer,
14260 predecessor,
14261 excerpts,
14262 } => {
14263 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14264 let buffer_id = buffer.read(cx).remote_id();
14265 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14266 if let Some(project) = &self.project {
14267 get_uncommitted_diff_for_buffer(
14268 project,
14269 [buffer.clone()],
14270 self.buffer.clone(),
14271 cx,
14272 )
14273 .detach();
14274 }
14275 }
14276 cx.emit(EditorEvent::ExcerptsAdded {
14277 buffer: buffer.clone(),
14278 predecessor: *predecessor,
14279 excerpts: excerpts.clone(),
14280 });
14281 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14282 }
14283 multi_buffer::Event::ExcerptsRemoved { ids } => {
14284 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14285 let buffer = self.buffer.read(cx);
14286 self.registered_buffers
14287 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14288 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14289 }
14290 multi_buffer::Event::ExcerptsEdited { ids } => {
14291 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14292 }
14293 multi_buffer::Event::ExcerptsExpanded { ids } => {
14294 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14295 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14296 }
14297 multi_buffer::Event::Reparsed(buffer_id) => {
14298 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14299
14300 cx.emit(EditorEvent::Reparsed(*buffer_id));
14301 }
14302 multi_buffer::Event::DiffHunksToggled => {
14303 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14304 }
14305 multi_buffer::Event::LanguageChanged(buffer_id) => {
14306 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14307 cx.emit(EditorEvent::Reparsed(*buffer_id));
14308 cx.notify();
14309 }
14310 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14311 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14312 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14313 cx.emit(EditorEvent::TitleChanged)
14314 }
14315 // multi_buffer::Event::DiffBaseChanged => {
14316 // self.scrollbar_marker_state.dirty = true;
14317 // cx.emit(EditorEvent::DiffBaseChanged);
14318 // cx.notify();
14319 // }
14320 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14321 multi_buffer::Event::DiagnosticsUpdated => {
14322 self.refresh_active_diagnostics(cx);
14323 self.scrollbar_marker_state.dirty = true;
14324 cx.notify();
14325 }
14326 _ => {}
14327 };
14328 }
14329
14330 fn on_display_map_changed(
14331 &mut self,
14332 _: Entity<DisplayMap>,
14333 _: &mut Window,
14334 cx: &mut Context<Self>,
14335 ) {
14336 cx.notify();
14337 }
14338
14339 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14340 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14341 self.refresh_inline_completion(true, false, window, cx);
14342 self.refresh_inlay_hints(
14343 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14344 self.selections.newest_anchor().head(),
14345 &self.buffer.read(cx).snapshot(cx),
14346 cx,
14347 )),
14348 cx,
14349 );
14350
14351 let old_cursor_shape = self.cursor_shape;
14352
14353 {
14354 let editor_settings = EditorSettings::get_global(cx);
14355 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14356 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14357 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14358 }
14359
14360 if old_cursor_shape != self.cursor_shape {
14361 cx.emit(EditorEvent::CursorShapeChanged);
14362 }
14363
14364 let project_settings = ProjectSettings::get_global(cx);
14365 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14366
14367 if self.mode == EditorMode::Full {
14368 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14369 if self.git_blame_inline_enabled != inline_blame_enabled {
14370 self.toggle_git_blame_inline_internal(false, window, cx);
14371 }
14372 }
14373
14374 cx.notify();
14375 }
14376
14377 pub fn set_searchable(&mut self, searchable: bool) {
14378 self.searchable = searchable;
14379 }
14380
14381 pub fn searchable(&self) -> bool {
14382 self.searchable
14383 }
14384
14385 fn open_proposed_changes_editor(
14386 &mut self,
14387 _: &OpenProposedChangesEditor,
14388 window: &mut Window,
14389 cx: &mut Context<Self>,
14390 ) {
14391 let Some(workspace) = self.workspace() else {
14392 cx.propagate();
14393 return;
14394 };
14395
14396 let selections = self.selections.all::<usize>(cx);
14397 let multi_buffer = self.buffer.read(cx);
14398 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14399 let mut new_selections_by_buffer = HashMap::default();
14400 for selection in selections {
14401 for (buffer, range, _) in
14402 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14403 {
14404 let mut range = range.to_point(buffer);
14405 range.start.column = 0;
14406 range.end.column = buffer.line_len(range.end.row);
14407 new_selections_by_buffer
14408 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14409 .or_insert(Vec::new())
14410 .push(range)
14411 }
14412 }
14413
14414 let proposed_changes_buffers = new_selections_by_buffer
14415 .into_iter()
14416 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14417 .collect::<Vec<_>>();
14418 let proposed_changes_editor = cx.new(|cx| {
14419 ProposedChangesEditor::new(
14420 "Proposed changes",
14421 proposed_changes_buffers,
14422 self.project.clone(),
14423 window,
14424 cx,
14425 )
14426 });
14427
14428 window.defer(cx, move |window, cx| {
14429 workspace.update(cx, |workspace, cx| {
14430 workspace.active_pane().update(cx, |pane, cx| {
14431 pane.add_item(
14432 Box::new(proposed_changes_editor),
14433 true,
14434 true,
14435 None,
14436 window,
14437 cx,
14438 );
14439 });
14440 });
14441 });
14442 }
14443
14444 pub fn open_excerpts_in_split(
14445 &mut self,
14446 _: &OpenExcerptsSplit,
14447 window: &mut Window,
14448 cx: &mut Context<Self>,
14449 ) {
14450 self.open_excerpts_common(None, true, window, cx)
14451 }
14452
14453 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14454 self.open_excerpts_common(None, false, window, cx)
14455 }
14456
14457 fn open_excerpts_common(
14458 &mut self,
14459 jump_data: Option<JumpData>,
14460 split: bool,
14461 window: &mut Window,
14462 cx: &mut Context<Self>,
14463 ) {
14464 let Some(workspace) = self.workspace() else {
14465 cx.propagate();
14466 return;
14467 };
14468
14469 if self.buffer.read(cx).is_singleton() {
14470 cx.propagate();
14471 return;
14472 }
14473
14474 let mut new_selections_by_buffer = HashMap::default();
14475 match &jump_data {
14476 Some(JumpData::MultiBufferPoint {
14477 excerpt_id,
14478 position,
14479 anchor,
14480 line_offset_from_top,
14481 }) => {
14482 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14483 if let Some(buffer) = multi_buffer_snapshot
14484 .buffer_id_for_excerpt(*excerpt_id)
14485 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14486 {
14487 let buffer_snapshot = buffer.read(cx).snapshot();
14488 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14489 language::ToPoint::to_point(anchor, &buffer_snapshot)
14490 } else {
14491 buffer_snapshot.clip_point(*position, Bias::Left)
14492 };
14493 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14494 new_selections_by_buffer.insert(
14495 buffer,
14496 (
14497 vec![jump_to_offset..jump_to_offset],
14498 Some(*line_offset_from_top),
14499 ),
14500 );
14501 }
14502 }
14503 Some(JumpData::MultiBufferRow {
14504 row,
14505 line_offset_from_top,
14506 }) => {
14507 let point = MultiBufferPoint::new(row.0, 0);
14508 if let Some((buffer, buffer_point, _)) =
14509 self.buffer.read(cx).point_to_buffer_point(point, cx)
14510 {
14511 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14512 new_selections_by_buffer
14513 .entry(buffer)
14514 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14515 .0
14516 .push(buffer_offset..buffer_offset)
14517 }
14518 }
14519 None => {
14520 let selections = self.selections.all::<usize>(cx);
14521 let multi_buffer = self.buffer.read(cx);
14522 for selection in selections {
14523 for (buffer, mut range, _) in multi_buffer
14524 .snapshot(cx)
14525 .range_to_buffer_ranges(selection.range())
14526 {
14527 // When editing branch buffers, jump to the corresponding location
14528 // in their base buffer.
14529 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14530 let buffer = buffer_handle.read(cx);
14531 if let Some(base_buffer) = buffer.base_buffer() {
14532 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14533 buffer_handle = base_buffer;
14534 }
14535
14536 if selection.reversed {
14537 mem::swap(&mut range.start, &mut range.end);
14538 }
14539 new_selections_by_buffer
14540 .entry(buffer_handle)
14541 .or_insert((Vec::new(), None))
14542 .0
14543 .push(range)
14544 }
14545 }
14546 }
14547 }
14548
14549 if new_selections_by_buffer.is_empty() {
14550 return;
14551 }
14552
14553 // We defer the pane interaction because we ourselves are a workspace item
14554 // and activating a new item causes the pane to call a method on us reentrantly,
14555 // which panics if we're on the stack.
14556 window.defer(cx, move |window, cx| {
14557 workspace.update(cx, |workspace, cx| {
14558 let pane = if split {
14559 workspace.adjacent_pane(window, cx)
14560 } else {
14561 workspace.active_pane().clone()
14562 };
14563
14564 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14565 let editor = buffer
14566 .read(cx)
14567 .file()
14568 .is_none()
14569 .then(|| {
14570 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14571 // so `workspace.open_project_item` will never find them, always opening a new editor.
14572 // Instead, we try to activate the existing editor in the pane first.
14573 let (editor, pane_item_index) =
14574 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14575 let editor = item.downcast::<Editor>()?;
14576 let singleton_buffer =
14577 editor.read(cx).buffer().read(cx).as_singleton()?;
14578 if singleton_buffer == buffer {
14579 Some((editor, i))
14580 } else {
14581 None
14582 }
14583 })?;
14584 pane.update(cx, |pane, cx| {
14585 pane.activate_item(pane_item_index, true, true, window, cx)
14586 });
14587 Some(editor)
14588 })
14589 .flatten()
14590 .unwrap_or_else(|| {
14591 workspace.open_project_item::<Self>(
14592 pane.clone(),
14593 buffer,
14594 true,
14595 true,
14596 window,
14597 cx,
14598 )
14599 });
14600
14601 editor.update(cx, |editor, cx| {
14602 let autoscroll = match scroll_offset {
14603 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14604 None => Autoscroll::newest(),
14605 };
14606 let nav_history = editor.nav_history.take();
14607 editor.change_selections(Some(autoscroll), window, cx, |s| {
14608 s.select_ranges(ranges);
14609 });
14610 editor.nav_history = nav_history;
14611 });
14612 }
14613 })
14614 });
14615 }
14616
14617 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14618 let snapshot = self.buffer.read(cx).read(cx);
14619 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14620 Some(
14621 ranges
14622 .iter()
14623 .map(move |range| {
14624 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14625 })
14626 .collect(),
14627 )
14628 }
14629
14630 fn selection_replacement_ranges(
14631 &self,
14632 range: Range<OffsetUtf16>,
14633 cx: &mut App,
14634 ) -> Vec<Range<OffsetUtf16>> {
14635 let selections = self.selections.all::<OffsetUtf16>(cx);
14636 let newest_selection = selections
14637 .iter()
14638 .max_by_key(|selection| selection.id)
14639 .unwrap();
14640 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14641 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14642 let snapshot = self.buffer.read(cx).read(cx);
14643 selections
14644 .into_iter()
14645 .map(|mut selection| {
14646 selection.start.0 =
14647 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14648 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14649 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14650 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14651 })
14652 .collect()
14653 }
14654
14655 fn report_editor_event(
14656 &self,
14657 event_type: &'static str,
14658 file_extension: Option<String>,
14659 cx: &App,
14660 ) {
14661 if cfg!(any(test, feature = "test-support")) {
14662 return;
14663 }
14664
14665 let Some(project) = &self.project else { return };
14666
14667 // If None, we are in a file without an extension
14668 let file = self
14669 .buffer
14670 .read(cx)
14671 .as_singleton()
14672 .and_then(|b| b.read(cx).file());
14673 let file_extension = file_extension.or(file
14674 .as_ref()
14675 .and_then(|file| Path::new(file.file_name(cx)).extension())
14676 .and_then(|e| e.to_str())
14677 .map(|a| a.to_string()));
14678
14679 let vim_mode = cx
14680 .global::<SettingsStore>()
14681 .raw_user_settings()
14682 .get("vim_mode")
14683 == Some(&serde_json::Value::Bool(true));
14684
14685 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14686 let copilot_enabled = edit_predictions_provider
14687 == language::language_settings::EditPredictionProvider::Copilot;
14688 let copilot_enabled_for_language = self
14689 .buffer
14690 .read(cx)
14691 .settings_at(0, cx)
14692 .show_edit_predictions;
14693
14694 let project = project.read(cx);
14695 telemetry::event!(
14696 event_type,
14697 file_extension,
14698 vim_mode,
14699 copilot_enabled,
14700 copilot_enabled_for_language,
14701 edit_predictions_provider,
14702 is_via_ssh = project.is_via_ssh(),
14703 );
14704 }
14705
14706 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14707 /// with each line being an array of {text, highlight} objects.
14708 fn copy_highlight_json(
14709 &mut self,
14710 _: &CopyHighlightJson,
14711 window: &mut Window,
14712 cx: &mut Context<Self>,
14713 ) {
14714 #[derive(Serialize)]
14715 struct Chunk<'a> {
14716 text: String,
14717 highlight: Option<&'a str>,
14718 }
14719
14720 let snapshot = self.buffer.read(cx).snapshot(cx);
14721 let range = self
14722 .selected_text_range(false, window, cx)
14723 .and_then(|selection| {
14724 if selection.range.is_empty() {
14725 None
14726 } else {
14727 Some(selection.range)
14728 }
14729 })
14730 .unwrap_or_else(|| 0..snapshot.len());
14731
14732 let chunks = snapshot.chunks(range, true);
14733 let mut lines = Vec::new();
14734 let mut line: VecDeque<Chunk> = VecDeque::new();
14735
14736 let Some(style) = self.style.as_ref() else {
14737 return;
14738 };
14739
14740 for chunk in chunks {
14741 let highlight = chunk
14742 .syntax_highlight_id
14743 .and_then(|id| id.name(&style.syntax));
14744 let mut chunk_lines = chunk.text.split('\n').peekable();
14745 while let Some(text) = chunk_lines.next() {
14746 let mut merged_with_last_token = false;
14747 if let Some(last_token) = line.back_mut() {
14748 if last_token.highlight == highlight {
14749 last_token.text.push_str(text);
14750 merged_with_last_token = true;
14751 }
14752 }
14753
14754 if !merged_with_last_token {
14755 line.push_back(Chunk {
14756 text: text.into(),
14757 highlight,
14758 });
14759 }
14760
14761 if chunk_lines.peek().is_some() {
14762 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14763 line.pop_front();
14764 }
14765 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14766 line.pop_back();
14767 }
14768
14769 lines.push(mem::take(&mut line));
14770 }
14771 }
14772 }
14773
14774 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14775 return;
14776 };
14777 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14778 }
14779
14780 pub fn open_context_menu(
14781 &mut self,
14782 _: &OpenContextMenu,
14783 window: &mut Window,
14784 cx: &mut Context<Self>,
14785 ) {
14786 self.request_autoscroll(Autoscroll::newest(), cx);
14787 let position = self.selections.newest_display(cx).start;
14788 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14789 }
14790
14791 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14792 &self.inlay_hint_cache
14793 }
14794
14795 pub fn replay_insert_event(
14796 &mut self,
14797 text: &str,
14798 relative_utf16_range: Option<Range<isize>>,
14799 window: &mut Window,
14800 cx: &mut Context<Self>,
14801 ) {
14802 if !self.input_enabled {
14803 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14804 return;
14805 }
14806 if let Some(relative_utf16_range) = relative_utf16_range {
14807 let selections = self.selections.all::<OffsetUtf16>(cx);
14808 self.change_selections(None, window, cx, |s| {
14809 let new_ranges = selections.into_iter().map(|range| {
14810 let start = OffsetUtf16(
14811 range
14812 .head()
14813 .0
14814 .saturating_add_signed(relative_utf16_range.start),
14815 );
14816 let end = OffsetUtf16(
14817 range
14818 .head()
14819 .0
14820 .saturating_add_signed(relative_utf16_range.end),
14821 );
14822 start..end
14823 });
14824 s.select_ranges(new_ranges);
14825 });
14826 }
14827
14828 self.handle_input(text, window, cx);
14829 }
14830
14831 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14832 let Some(provider) = self.semantics_provider.as_ref() else {
14833 return false;
14834 };
14835
14836 let mut supports = false;
14837 self.buffer().update(cx, |this, cx| {
14838 this.for_each_buffer(|buffer| {
14839 supports |= provider.supports_inlay_hints(buffer, cx);
14840 });
14841 });
14842
14843 supports
14844 }
14845
14846 pub fn is_focused(&self, window: &Window) -> bool {
14847 self.focus_handle.is_focused(window)
14848 }
14849
14850 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14851 cx.emit(EditorEvent::Focused);
14852
14853 if let Some(descendant) = self
14854 .last_focused_descendant
14855 .take()
14856 .and_then(|descendant| descendant.upgrade())
14857 {
14858 window.focus(&descendant);
14859 } else {
14860 if let Some(blame) = self.blame.as_ref() {
14861 blame.update(cx, GitBlame::focus)
14862 }
14863
14864 self.blink_manager.update(cx, BlinkManager::enable);
14865 self.show_cursor_names(window, cx);
14866 self.buffer.update(cx, |buffer, cx| {
14867 buffer.finalize_last_transaction(cx);
14868 if self.leader_peer_id.is_none() {
14869 buffer.set_active_selections(
14870 &self.selections.disjoint_anchors(),
14871 self.selections.line_mode,
14872 self.cursor_shape,
14873 cx,
14874 );
14875 }
14876 });
14877 }
14878 }
14879
14880 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14881 cx.emit(EditorEvent::FocusedIn)
14882 }
14883
14884 fn handle_focus_out(
14885 &mut self,
14886 event: FocusOutEvent,
14887 _window: &mut Window,
14888 _cx: &mut Context<Self>,
14889 ) {
14890 if event.blurred != self.focus_handle {
14891 self.last_focused_descendant = Some(event.blurred);
14892 }
14893 }
14894
14895 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14896 self.blink_manager.update(cx, BlinkManager::disable);
14897 self.buffer
14898 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14899
14900 if let Some(blame) = self.blame.as_ref() {
14901 blame.update(cx, GitBlame::blur)
14902 }
14903 if !self.hover_state.focused(window, cx) {
14904 hide_hover(self, cx);
14905 }
14906 if !self
14907 .context_menu
14908 .borrow()
14909 .as_ref()
14910 .is_some_and(|context_menu| context_menu.focused(window, cx))
14911 {
14912 self.hide_context_menu(window, cx);
14913 }
14914 self.discard_inline_completion(false, cx);
14915 cx.emit(EditorEvent::Blurred);
14916 cx.notify();
14917 }
14918
14919 pub fn register_action<A: Action>(
14920 &mut self,
14921 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14922 ) -> Subscription {
14923 let id = self.next_editor_action_id.post_inc();
14924 let listener = Arc::new(listener);
14925 self.editor_actions.borrow_mut().insert(
14926 id,
14927 Box::new(move |window, _| {
14928 let listener = listener.clone();
14929 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14930 let action = action.downcast_ref().unwrap();
14931 if phase == DispatchPhase::Bubble {
14932 listener(action, window, cx)
14933 }
14934 })
14935 }),
14936 );
14937
14938 let editor_actions = self.editor_actions.clone();
14939 Subscription::new(move || {
14940 editor_actions.borrow_mut().remove(&id);
14941 })
14942 }
14943
14944 pub fn file_header_size(&self) -> u32 {
14945 FILE_HEADER_HEIGHT
14946 }
14947
14948 pub fn revert(
14949 &mut self,
14950 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14951 window: &mut Window,
14952 cx: &mut Context<Self>,
14953 ) {
14954 self.buffer().update(cx, |multi_buffer, cx| {
14955 for (buffer_id, changes) in revert_changes {
14956 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14957 buffer.update(cx, |buffer, cx| {
14958 buffer.edit(
14959 changes.into_iter().map(|(range, text)| {
14960 (range, text.to_string().map(Arc::<str>::from))
14961 }),
14962 None,
14963 cx,
14964 );
14965 });
14966 }
14967 }
14968 });
14969 self.change_selections(None, window, cx, |selections| selections.refresh());
14970 }
14971
14972 pub fn to_pixel_point(
14973 &self,
14974 source: multi_buffer::Anchor,
14975 editor_snapshot: &EditorSnapshot,
14976 window: &mut Window,
14977 ) -> Option<gpui::Point<Pixels>> {
14978 let source_point = source.to_display_point(editor_snapshot);
14979 self.display_to_pixel_point(source_point, editor_snapshot, window)
14980 }
14981
14982 pub fn display_to_pixel_point(
14983 &self,
14984 source: DisplayPoint,
14985 editor_snapshot: &EditorSnapshot,
14986 window: &mut Window,
14987 ) -> Option<gpui::Point<Pixels>> {
14988 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14989 let text_layout_details = self.text_layout_details(window);
14990 let scroll_top = text_layout_details
14991 .scroll_anchor
14992 .scroll_position(editor_snapshot)
14993 .y;
14994
14995 if source.row().as_f32() < scroll_top.floor() {
14996 return None;
14997 }
14998 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14999 let source_y = line_height * (source.row().as_f32() - scroll_top);
15000 Some(gpui::Point::new(source_x, source_y))
15001 }
15002
15003 pub fn has_visible_completions_menu(&self) -> bool {
15004 !self.edit_prediction_preview_is_active()
15005 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15006 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15007 })
15008 }
15009
15010 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15011 self.addons
15012 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15013 }
15014
15015 pub fn unregister_addon<T: Addon>(&mut self) {
15016 self.addons.remove(&std::any::TypeId::of::<T>());
15017 }
15018
15019 pub fn addon<T: Addon>(&self) -> Option<&T> {
15020 let type_id = std::any::TypeId::of::<T>();
15021 self.addons
15022 .get(&type_id)
15023 .and_then(|item| item.to_any().downcast_ref::<T>())
15024 }
15025
15026 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15027 let text_layout_details = self.text_layout_details(window);
15028 let style = &text_layout_details.editor_style;
15029 let font_id = window.text_system().resolve_font(&style.text.font());
15030 let font_size = style.text.font_size.to_pixels(window.rem_size());
15031 let line_height = style.text.line_height_in_pixels(window.rem_size());
15032 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15033
15034 gpui::Size::new(em_width, line_height)
15035 }
15036
15037 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15038 self.load_diff_task.clone()
15039 }
15040
15041 fn read_selections_from_db(
15042 &mut self,
15043 item_id: u64,
15044 workspace_id: WorkspaceId,
15045 window: &mut Window,
15046 cx: &mut Context<Editor>,
15047 ) {
15048 if !self.is_singleton(cx)
15049 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15050 {
15051 return;
15052 }
15053 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15054 return;
15055 };
15056 if selections.is_empty() {
15057 return;
15058 }
15059
15060 let snapshot = self.buffer.read(cx).snapshot(cx);
15061 self.change_selections(None, window, cx, |s| {
15062 s.select_ranges(selections.into_iter().map(|(start, end)| {
15063 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15064 }));
15065 });
15066 }
15067}
15068
15069fn insert_extra_newline_brackets(
15070 buffer: &MultiBufferSnapshot,
15071 range: Range<usize>,
15072 language: &language::LanguageScope,
15073) -> bool {
15074 let leading_whitespace_len = buffer
15075 .reversed_chars_at(range.start)
15076 .take_while(|c| c.is_whitespace() && *c != '\n')
15077 .map(|c| c.len_utf8())
15078 .sum::<usize>();
15079 let trailing_whitespace_len = buffer
15080 .chars_at(range.end)
15081 .take_while(|c| c.is_whitespace() && *c != '\n')
15082 .map(|c| c.len_utf8())
15083 .sum::<usize>();
15084 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15085
15086 language.brackets().any(|(pair, enabled)| {
15087 let pair_start = pair.start.trim_end();
15088 let pair_end = pair.end.trim_start();
15089
15090 enabled
15091 && pair.newline
15092 && buffer.contains_str_at(range.end, pair_end)
15093 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15094 })
15095}
15096
15097fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15098 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15099 [(buffer, range, _)] => (*buffer, range.clone()),
15100 _ => return false,
15101 };
15102 let pair = {
15103 let mut result: Option<BracketMatch> = None;
15104
15105 for pair in buffer
15106 .all_bracket_ranges(range.clone())
15107 .filter(move |pair| {
15108 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15109 })
15110 {
15111 let len = pair.close_range.end - pair.open_range.start;
15112
15113 if let Some(existing) = &result {
15114 let existing_len = existing.close_range.end - existing.open_range.start;
15115 if len > existing_len {
15116 continue;
15117 }
15118 }
15119
15120 result = Some(pair);
15121 }
15122
15123 result
15124 };
15125 let Some(pair) = pair else {
15126 return false;
15127 };
15128 pair.newline_only
15129 && buffer
15130 .chars_for_range(pair.open_range.end..range.start)
15131 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15132 .all(|c| c.is_whitespace() && c != '\n')
15133}
15134
15135fn get_uncommitted_diff_for_buffer(
15136 project: &Entity<Project>,
15137 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15138 buffer: Entity<MultiBuffer>,
15139 cx: &mut App,
15140) -> Task<()> {
15141 let mut tasks = Vec::new();
15142 project.update(cx, |project, cx| {
15143 for buffer in buffers {
15144 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15145 }
15146 });
15147 cx.spawn(|mut cx| async move {
15148 let diffs = futures::future::join_all(tasks).await;
15149 buffer
15150 .update(&mut cx, |buffer, cx| {
15151 for diff in diffs.into_iter().flatten() {
15152 buffer.add_diff(diff, cx);
15153 }
15154 })
15155 .ok();
15156 })
15157}
15158
15159fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15160 let tab_size = tab_size.get() as usize;
15161 let mut width = offset;
15162
15163 for ch in text.chars() {
15164 width += if ch == '\t' {
15165 tab_size - (width % tab_size)
15166 } else {
15167 1
15168 };
15169 }
15170
15171 width - offset
15172}
15173
15174#[cfg(test)]
15175mod tests {
15176 use super::*;
15177
15178 #[test]
15179 fn test_string_size_with_expanded_tabs() {
15180 let nz = |val| NonZeroU32::new(val).unwrap();
15181 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15182 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15183 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15184 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15185 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15186 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15187 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15188 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15189 }
15190}
15191
15192/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15193struct WordBreakingTokenizer<'a> {
15194 input: &'a str,
15195}
15196
15197impl<'a> WordBreakingTokenizer<'a> {
15198 fn new(input: &'a str) -> Self {
15199 Self { input }
15200 }
15201}
15202
15203fn is_char_ideographic(ch: char) -> bool {
15204 use unicode_script::Script::*;
15205 use unicode_script::UnicodeScript;
15206 matches!(ch.script(), Han | Tangut | Yi)
15207}
15208
15209fn is_grapheme_ideographic(text: &str) -> bool {
15210 text.chars().any(is_char_ideographic)
15211}
15212
15213fn is_grapheme_whitespace(text: &str) -> bool {
15214 text.chars().any(|x| x.is_whitespace())
15215}
15216
15217fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15218 text.chars().next().map_or(false, |ch| {
15219 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15220 })
15221}
15222
15223#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15224struct WordBreakToken<'a> {
15225 token: &'a str,
15226 grapheme_len: usize,
15227 is_whitespace: bool,
15228}
15229
15230impl<'a> Iterator for WordBreakingTokenizer<'a> {
15231 /// Yields a span, the count of graphemes in the token, and whether it was
15232 /// whitespace. Note that it also breaks at word boundaries.
15233 type Item = WordBreakToken<'a>;
15234
15235 fn next(&mut self) -> Option<Self::Item> {
15236 use unicode_segmentation::UnicodeSegmentation;
15237 if self.input.is_empty() {
15238 return None;
15239 }
15240
15241 let mut iter = self.input.graphemes(true).peekable();
15242 let mut offset = 0;
15243 let mut graphemes = 0;
15244 if let Some(first_grapheme) = iter.next() {
15245 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15246 offset += first_grapheme.len();
15247 graphemes += 1;
15248 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15249 if let Some(grapheme) = iter.peek().copied() {
15250 if should_stay_with_preceding_ideograph(grapheme) {
15251 offset += grapheme.len();
15252 graphemes += 1;
15253 }
15254 }
15255 } else {
15256 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15257 let mut next_word_bound = words.peek().copied();
15258 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15259 next_word_bound = words.next();
15260 }
15261 while let Some(grapheme) = iter.peek().copied() {
15262 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15263 break;
15264 };
15265 if is_grapheme_whitespace(grapheme) != is_whitespace {
15266 break;
15267 };
15268 offset += grapheme.len();
15269 graphemes += 1;
15270 iter.next();
15271 }
15272 }
15273 let token = &self.input[..offset];
15274 self.input = &self.input[offset..];
15275 if is_whitespace {
15276 Some(WordBreakToken {
15277 token: " ",
15278 grapheme_len: 1,
15279 is_whitespace: true,
15280 })
15281 } else {
15282 Some(WordBreakToken {
15283 token,
15284 grapheme_len: graphemes,
15285 is_whitespace: false,
15286 })
15287 }
15288 } else {
15289 None
15290 }
15291 }
15292}
15293
15294#[test]
15295fn test_word_breaking_tokenizer() {
15296 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15297 ("", &[]),
15298 (" ", &[(" ", 1, true)]),
15299 ("Ʒ", &[("Ʒ", 1, false)]),
15300 ("Ǽ", &[("Ǽ", 1, false)]),
15301 ("⋑", &[("⋑", 1, false)]),
15302 ("⋑⋑", &[("⋑⋑", 2, false)]),
15303 (
15304 "原理,进而",
15305 &[
15306 ("原", 1, false),
15307 ("理,", 2, false),
15308 ("进", 1, false),
15309 ("而", 1, false),
15310 ],
15311 ),
15312 (
15313 "hello world",
15314 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15315 ),
15316 (
15317 "hello, world",
15318 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15319 ),
15320 (
15321 " hello world",
15322 &[
15323 (" ", 1, true),
15324 ("hello", 5, false),
15325 (" ", 1, true),
15326 ("world", 5, false),
15327 ],
15328 ),
15329 (
15330 "这是什么 \n 钢笔",
15331 &[
15332 ("这", 1, false),
15333 ("是", 1, false),
15334 ("什", 1, false),
15335 ("么", 1, false),
15336 (" ", 1, true),
15337 ("钢", 1, false),
15338 ("笔", 1, false),
15339 ],
15340 ),
15341 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15342 ];
15343
15344 for (input, result) in tests {
15345 assert_eq!(
15346 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15347 result
15348 .iter()
15349 .copied()
15350 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15351 token,
15352 grapheme_len,
15353 is_whitespace,
15354 })
15355 .collect::<Vec<_>>()
15356 );
15357 }
15358}
15359
15360fn wrap_with_prefix(
15361 line_prefix: String,
15362 unwrapped_text: String,
15363 wrap_column: usize,
15364 tab_size: NonZeroU32,
15365) -> String {
15366 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15367 let mut wrapped_text = String::new();
15368 let mut current_line = line_prefix.clone();
15369
15370 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15371 let mut current_line_len = line_prefix_len;
15372 for WordBreakToken {
15373 token,
15374 grapheme_len,
15375 is_whitespace,
15376 } in tokenizer
15377 {
15378 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15379 wrapped_text.push_str(current_line.trim_end());
15380 wrapped_text.push('\n');
15381 current_line.truncate(line_prefix.len());
15382 current_line_len = line_prefix_len;
15383 if !is_whitespace {
15384 current_line.push_str(token);
15385 current_line_len += grapheme_len;
15386 }
15387 } else if !is_whitespace {
15388 current_line.push_str(token);
15389 current_line_len += grapheme_len;
15390 } else if current_line_len != line_prefix_len {
15391 current_line.push(' ');
15392 current_line_len += 1;
15393 }
15394 }
15395
15396 if !current_line.is_empty() {
15397 wrapped_text.push_str(¤t_line);
15398 }
15399 wrapped_text
15400}
15401
15402#[test]
15403fn test_wrap_with_prefix() {
15404 assert_eq!(
15405 wrap_with_prefix(
15406 "# ".to_string(),
15407 "abcdefg".to_string(),
15408 4,
15409 NonZeroU32::new(4).unwrap()
15410 ),
15411 "# abcdefg"
15412 );
15413 assert_eq!(
15414 wrap_with_prefix(
15415 "".to_string(),
15416 "\thello world".to_string(),
15417 8,
15418 NonZeroU32::new(4).unwrap()
15419 ),
15420 "hello\nworld"
15421 );
15422 assert_eq!(
15423 wrap_with_prefix(
15424 "// ".to_string(),
15425 "xx \nyy zz aa bb cc".to_string(),
15426 12,
15427 NonZeroU32::new(4).unwrap()
15428 ),
15429 "// xx yy zz\n// aa bb cc"
15430 );
15431 assert_eq!(
15432 wrap_with_prefix(
15433 String::new(),
15434 "这是什么 \n 钢笔".to_string(),
15435 3,
15436 NonZeroU32::new(4).unwrap()
15437 ),
15438 "这是什\n么 钢\n笔"
15439 );
15440}
15441
15442pub trait CollaborationHub {
15443 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15444 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15445 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15446}
15447
15448impl CollaborationHub for Entity<Project> {
15449 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15450 self.read(cx).collaborators()
15451 }
15452
15453 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15454 self.read(cx).user_store().read(cx).participant_indices()
15455 }
15456
15457 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15458 let this = self.read(cx);
15459 let user_ids = this.collaborators().values().map(|c| c.user_id);
15460 this.user_store().read_with(cx, |user_store, cx| {
15461 user_store.participant_names(user_ids, cx)
15462 })
15463 }
15464}
15465
15466pub trait SemanticsProvider {
15467 fn hover(
15468 &self,
15469 buffer: &Entity<Buffer>,
15470 position: text::Anchor,
15471 cx: &mut App,
15472 ) -> Option<Task<Vec<project::Hover>>>;
15473
15474 fn inlay_hints(
15475 &self,
15476 buffer_handle: Entity<Buffer>,
15477 range: Range<text::Anchor>,
15478 cx: &mut App,
15479 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15480
15481 fn resolve_inlay_hint(
15482 &self,
15483 hint: InlayHint,
15484 buffer_handle: Entity<Buffer>,
15485 server_id: LanguageServerId,
15486 cx: &mut App,
15487 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15488
15489 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15490
15491 fn document_highlights(
15492 &self,
15493 buffer: &Entity<Buffer>,
15494 position: text::Anchor,
15495 cx: &mut App,
15496 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15497
15498 fn definitions(
15499 &self,
15500 buffer: &Entity<Buffer>,
15501 position: text::Anchor,
15502 kind: GotoDefinitionKind,
15503 cx: &mut App,
15504 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15505
15506 fn range_for_rename(
15507 &self,
15508 buffer: &Entity<Buffer>,
15509 position: text::Anchor,
15510 cx: &mut App,
15511 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15512
15513 fn perform_rename(
15514 &self,
15515 buffer: &Entity<Buffer>,
15516 position: text::Anchor,
15517 new_name: String,
15518 cx: &mut App,
15519 ) -> Option<Task<Result<ProjectTransaction>>>;
15520}
15521
15522pub trait CompletionProvider {
15523 fn completions(
15524 &self,
15525 buffer: &Entity<Buffer>,
15526 buffer_position: text::Anchor,
15527 trigger: CompletionContext,
15528 window: &mut Window,
15529 cx: &mut Context<Editor>,
15530 ) -> Task<Result<Vec<Completion>>>;
15531
15532 fn resolve_completions(
15533 &self,
15534 buffer: Entity<Buffer>,
15535 completion_indices: Vec<usize>,
15536 completions: Rc<RefCell<Box<[Completion]>>>,
15537 cx: &mut Context<Editor>,
15538 ) -> Task<Result<bool>>;
15539
15540 fn apply_additional_edits_for_completion(
15541 &self,
15542 _buffer: Entity<Buffer>,
15543 _completions: Rc<RefCell<Box<[Completion]>>>,
15544 _completion_index: usize,
15545 _push_to_history: bool,
15546 _cx: &mut Context<Editor>,
15547 ) -> Task<Result<Option<language::Transaction>>> {
15548 Task::ready(Ok(None))
15549 }
15550
15551 fn is_completion_trigger(
15552 &self,
15553 buffer: &Entity<Buffer>,
15554 position: language::Anchor,
15555 text: &str,
15556 trigger_in_words: bool,
15557 cx: &mut Context<Editor>,
15558 ) -> bool;
15559
15560 fn sort_completions(&self) -> bool {
15561 true
15562 }
15563}
15564
15565pub trait CodeActionProvider {
15566 fn id(&self) -> Arc<str>;
15567
15568 fn code_actions(
15569 &self,
15570 buffer: &Entity<Buffer>,
15571 range: Range<text::Anchor>,
15572 window: &mut Window,
15573 cx: &mut App,
15574 ) -> Task<Result<Vec<CodeAction>>>;
15575
15576 fn apply_code_action(
15577 &self,
15578 buffer_handle: Entity<Buffer>,
15579 action: CodeAction,
15580 excerpt_id: ExcerptId,
15581 push_to_history: bool,
15582 window: &mut Window,
15583 cx: &mut App,
15584 ) -> Task<Result<ProjectTransaction>>;
15585}
15586
15587impl CodeActionProvider for Entity<Project> {
15588 fn id(&self) -> Arc<str> {
15589 "project".into()
15590 }
15591
15592 fn code_actions(
15593 &self,
15594 buffer: &Entity<Buffer>,
15595 range: Range<text::Anchor>,
15596 _window: &mut Window,
15597 cx: &mut App,
15598 ) -> Task<Result<Vec<CodeAction>>> {
15599 self.update(cx, |project, cx| {
15600 project.code_actions(buffer, range, None, cx)
15601 })
15602 }
15603
15604 fn apply_code_action(
15605 &self,
15606 buffer_handle: Entity<Buffer>,
15607 action: CodeAction,
15608 _excerpt_id: ExcerptId,
15609 push_to_history: bool,
15610 _window: &mut Window,
15611 cx: &mut App,
15612 ) -> Task<Result<ProjectTransaction>> {
15613 self.update(cx, |project, cx| {
15614 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15615 })
15616 }
15617}
15618
15619fn snippet_completions(
15620 project: &Project,
15621 buffer: &Entity<Buffer>,
15622 buffer_position: text::Anchor,
15623 cx: &mut App,
15624) -> Task<Result<Vec<Completion>>> {
15625 let language = buffer.read(cx).language_at(buffer_position);
15626 let language_name = language.as_ref().map(|language| language.lsp_id());
15627 let snippet_store = project.snippets().read(cx);
15628 let snippets = snippet_store.snippets_for(language_name, cx);
15629
15630 if snippets.is_empty() {
15631 return Task::ready(Ok(vec![]));
15632 }
15633 let snapshot = buffer.read(cx).text_snapshot();
15634 let chars: String = snapshot
15635 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15636 .collect();
15637
15638 let scope = language.map(|language| language.default_scope());
15639 let executor = cx.background_executor().clone();
15640
15641 cx.background_spawn(async move {
15642 let classifier = CharClassifier::new(scope).for_completion(true);
15643 let mut last_word = chars
15644 .chars()
15645 .take_while(|c| classifier.is_word(*c))
15646 .collect::<String>();
15647 last_word = last_word.chars().rev().collect();
15648
15649 if last_word.is_empty() {
15650 return Ok(vec![]);
15651 }
15652
15653 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15654 let to_lsp = |point: &text::Anchor| {
15655 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15656 point_to_lsp(end)
15657 };
15658 let lsp_end = to_lsp(&buffer_position);
15659
15660 let candidates = snippets
15661 .iter()
15662 .enumerate()
15663 .flat_map(|(ix, snippet)| {
15664 snippet
15665 .prefix
15666 .iter()
15667 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15668 })
15669 .collect::<Vec<StringMatchCandidate>>();
15670
15671 let mut matches = fuzzy::match_strings(
15672 &candidates,
15673 &last_word,
15674 last_word.chars().any(|c| c.is_uppercase()),
15675 100,
15676 &Default::default(),
15677 executor,
15678 )
15679 .await;
15680
15681 // Remove all candidates where the query's start does not match the start of any word in the candidate
15682 if let Some(query_start) = last_word.chars().next() {
15683 matches.retain(|string_match| {
15684 split_words(&string_match.string).any(|word| {
15685 // Check that the first codepoint of the word as lowercase matches the first
15686 // codepoint of the query as lowercase
15687 word.chars()
15688 .flat_map(|codepoint| codepoint.to_lowercase())
15689 .zip(query_start.to_lowercase())
15690 .all(|(word_cp, query_cp)| word_cp == query_cp)
15691 })
15692 });
15693 }
15694
15695 let matched_strings = matches
15696 .into_iter()
15697 .map(|m| m.string)
15698 .collect::<HashSet<_>>();
15699
15700 let result: Vec<Completion> = snippets
15701 .into_iter()
15702 .filter_map(|snippet| {
15703 let matching_prefix = snippet
15704 .prefix
15705 .iter()
15706 .find(|prefix| matched_strings.contains(*prefix))?;
15707 let start = as_offset - last_word.len();
15708 let start = snapshot.anchor_before(start);
15709 let range = start..buffer_position;
15710 let lsp_start = to_lsp(&start);
15711 let lsp_range = lsp::Range {
15712 start: lsp_start,
15713 end: lsp_end,
15714 };
15715 Some(Completion {
15716 old_range: range,
15717 new_text: snippet.body.clone(),
15718 resolved: false,
15719 label: CodeLabel {
15720 text: matching_prefix.clone(),
15721 runs: vec![],
15722 filter_range: 0..matching_prefix.len(),
15723 },
15724 server_id: LanguageServerId(usize::MAX),
15725 documentation: snippet
15726 .description
15727 .clone()
15728 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15729 lsp_completion: lsp::CompletionItem {
15730 label: snippet.prefix.first().unwrap().clone(),
15731 kind: Some(CompletionItemKind::SNIPPET),
15732 label_details: snippet.description.as_ref().map(|description| {
15733 lsp::CompletionItemLabelDetails {
15734 detail: Some(description.clone()),
15735 description: None,
15736 }
15737 }),
15738 insert_text_format: Some(InsertTextFormat::SNIPPET),
15739 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15740 lsp::InsertReplaceEdit {
15741 new_text: snippet.body.clone(),
15742 insert: lsp_range,
15743 replace: lsp_range,
15744 },
15745 )),
15746 filter_text: Some(snippet.body.clone()),
15747 sort_text: Some(char::MAX.to_string()),
15748 ..Default::default()
15749 },
15750 confirm: None,
15751 })
15752 })
15753 .collect();
15754
15755 Ok(result)
15756 })
15757}
15758
15759impl CompletionProvider for Entity<Project> {
15760 fn completions(
15761 &self,
15762 buffer: &Entity<Buffer>,
15763 buffer_position: text::Anchor,
15764 options: CompletionContext,
15765 _window: &mut Window,
15766 cx: &mut Context<Editor>,
15767 ) -> Task<Result<Vec<Completion>>> {
15768 self.update(cx, |project, cx| {
15769 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15770 let project_completions = project.completions(buffer, buffer_position, options, cx);
15771 cx.background_spawn(async move {
15772 let mut completions = project_completions.await?;
15773 let snippets_completions = snippets.await?;
15774 completions.extend(snippets_completions);
15775 Ok(completions)
15776 })
15777 })
15778 }
15779
15780 fn resolve_completions(
15781 &self,
15782 buffer: Entity<Buffer>,
15783 completion_indices: Vec<usize>,
15784 completions: Rc<RefCell<Box<[Completion]>>>,
15785 cx: &mut Context<Editor>,
15786 ) -> Task<Result<bool>> {
15787 self.update(cx, |project, cx| {
15788 project.lsp_store().update(cx, |lsp_store, cx| {
15789 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15790 })
15791 })
15792 }
15793
15794 fn apply_additional_edits_for_completion(
15795 &self,
15796 buffer: Entity<Buffer>,
15797 completions: Rc<RefCell<Box<[Completion]>>>,
15798 completion_index: usize,
15799 push_to_history: bool,
15800 cx: &mut Context<Editor>,
15801 ) -> Task<Result<Option<language::Transaction>>> {
15802 self.update(cx, |project, cx| {
15803 project.lsp_store().update(cx, |lsp_store, cx| {
15804 lsp_store.apply_additional_edits_for_completion(
15805 buffer,
15806 completions,
15807 completion_index,
15808 push_to_history,
15809 cx,
15810 )
15811 })
15812 })
15813 }
15814
15815 fn is_completion_trigger(
15816 &self,
15817 buffer: &Entity<Buffer>,
15818 position: language::Anchor,
15819 text: &str,
15820 trigger_in_words: bool,
15821 cx: &mut Context<Editor>,
15822 ) -> bool {
15823 let mut chars = text.chars();
15824 let char = if let Some(char) = chars.next() {
15825 char
15826 } else {
15827 return false;
15828 };
15829 if chars.next().is_some() {
15830 return false;
15831 }
15832
15833 let buffer = buffer.read(cx);
15834 let snapshot = buffer.snapshot();
15835 if !snapshot.settings_at(position, cx).show_completions_on_input {
15836 return false;
15837 }
15838 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15839 if trigger_in_words && classifier.is_word(char) {
15840 return true;
15841 }
15842
15843 buffer.completion_triggers().contains(text)
15844 }
15845}
15846
15847impl SemanticsProvider for Entity<Project> {
15848 fn hover(
15849 &self,
15850 buffer: &Entity<Buffer>,
15851 position: text::Anchor,
15852 cx: &mut App,
15853 ) -> Option<Task<Vec<project::Hover>>> {
15854 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15855 }
15856
15857 fn document_highlights(
15858 &self,
15859 buffer: &Entity<Buffer>,
15860 position: text::Anchor,
15861 cx: &mut App,
15862 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15863 Some(self.update(cx, |project, cx| {
15864 project.document_highlights(buffer, position, cx)
15865 }))
15866 }
15867
15868 fn definitions(
15869 &self,
15870 buffer: &Entity<Buffer>,
15871 position: text::Anchor,
15872 kind: GotoDefinitionKind,
15873 cx: &mut App,
15874 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15875 Some(self.update(cx, |project, cx| match kind {
15876 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15877 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15878 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15879 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15880 }))
15881 }
15882
15883 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15884 // TODO: make this work for remote projects
15885 self.update(cx, |this, cx| {
15886 buffer.update(cx, |buffer, cx| {
15887 this.any_language_server_supports_inlay_hints(buffer, cx)
15888 })
15889 })
15890 }
15891
15892 fn inlay_hints(
15893 &self,
15894 buffer_handle: Entity<Buffer>,
15895 range: Range<text::Anchor>,
15896 cx: &mut App,
15897 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15898 Some(self.update(cx, |project, cx| {
15899 project.inlay_hints(buffer_handle, range, cx)
15900 }))
15901 }
15902
15903 fn resolve_inlay_hint(
15904 &self,
15905 hint: InlayHint,
15906 buffer_handle: Entity<Buffer>,
15907 server_id: LanguageServerId,
15908 cx: &mut App,
15909 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15910 Some(self.update(cx, |project, cx| {
15911 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15912 }))
15913 }
15914
15915 fn range_for_rename(
15916 &self,
15917 buffer: &Entity<Buffer>,
15918 position: text::Anchor,
15919 cx: &mut App,
15920 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15921 Some(self.update(cx, |project, cx| {
15922 let buffer = buffer.clone();
15923 let task = project.prepare_rename(buffer.clone(), position, cx);
15924 cx.spawn(|_, mut cx| async move {
15925 Ok(match task.await? {
15926 PrepareRenameResponse::Success(range) => Some(range),
15927 PrepareRenameResponse::InvalidPosition => None,
15928 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15929 // Fallback on using TreeSitter info to determine identifier range
15930 buffer.update(&mut cx, |buffer, _| {
15931 let snapshot = buffer.snapshot();
15932 let (range, kind) = snapshot.surrounding_word(position);
15933 if kind != Some(CharKind::Word) {
15934 return None;
15935 }
15936 Some(
15937 snapshot.anchor_before(range.start)
15938 ..snapshot.anchor_after(range.end),
15939 )
15940 })?
15941 }
15942 })
15943 })
15944 }))
15945 }
15946
15947 fn perform_rename(
15948 &self,
15949 buffer: &Entity<Buffer>,
15950 position: text::Anchor,
15951 new_name: String,
15952 cx: &mut App,
15953 ) -> Option<Task<Result<ProjectTransaction>>> {
15954 Some(self.update(cx, |project, cx| {
15955 project.perform_rename(buffer.clone(), position, new_name, cx)
15956 }))
15957 }
15958}
15959
15960fn inlay_hint_settings(
15961 location: Anchor,
15962 snapshot: &MultiBufferSnapshot,
15963 cx: &mut Context<Editor>,
15964) -> InlayHintSettings {
15965 let file = snapshot.file_at(location);
15966 let language = snapshot.language_at(location).map(|l| l.name());
15967 language_settings(language, file, cx).inlay_hints
15968}
15969
15970fn consume_contiguous_rows(
15971 contiguous_row_selections: &mut Vec<Selection<Point>>,
15972 selection: &Selection<Point>,
15973 display_map: &DisplaySnapshot,
15974 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15975) -> (MultiBufferRow, MultiBufferRow) {
15976 contiguous_row_selections.push(selection.clone());
15977 let start_row = MultiBufferRow(selection.start.row);
15978 let mut end_row = ending_row(selection, display_map);
15979
15980 while let Some(next_selection) = selections.peek() {
15981 if next_selection.start.row <= end_row.0 {
15982 end_row = ending_row(next_selection, display_map);
15983 contiguous_row_selections.push(selections.next().unwrap().clone());
15984 } else {
15985 break;
15986 }
15987 }
15988 (start_row, end_row)
15989}
15990
15991fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15992 if next_selection.end.column > 0 || next_selection.is_empty() {
15993 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15994 } else {
15995 MultiBufferRow(next_selection.end.row)
15996 }
15997}
15998
15999impl EditorSnapshot {
16000 pub fn remote_selections_in_range<'a>(
16001 &'a self,
16002 range: &'a Range<Anchor>,
16003 collaboration_hub: &dyn CollaborationHub,
16004 cx: &'a App,
16005 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16006 let participant_names = collaboration_hub.user_names(cx);
16007 let participant_indices = collaboration_hub.user_participant_indices(cx);
16008 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16009 let collaborators_by_replica_id = collaborators_by_peer_id
16010 .iter()
16011 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16012 .collect::<HashMap<_, _>>();
16013 self.buffer_snapshot
16014 .selections_in_range(range, false)
16015 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16016 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16017 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16018 let user_name = participant_names.get(&collaborator.user_id).cloned();
16019 Some(RemoteSelection {
16020 replica_id,
16021 selection,
16022 cursor_shape,
16023 line_mode,
16024 participant_index,
16025 peer_id: collaborator.peer_id,
16026 user_name,
16027 })
16028 })
16029 }
16030
16031 pub fn hunks_for_ranges(
16032 &self,
16033 ranges: impl Iterator<Item = Range<Point>>,
16034 ) -> Vec<MultiBufferDiffHunk> {
16035 let mut hunks = Vec::new();
16036 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16037 HashMap::default();
16038 for query_range in ranges {
16039 let query_rows =
16040 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16041 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16042 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16043 ) {
16044 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16045 // when the caret is just above or just below the deleted hunk.
16046 let allow_adjacent = hunk.status().is_deleted();
16047 let related_to_selection = if allow_adjacent {
16048 hunk.row_range.overlaps(&query_rows)
16049 || hunk.row_range.start == query_rows.end
16050 || hunk.row_range.end == query_rows.start
16051 } else {
16052 hunk.row_range.overlaps(&query_rows)
16053 };
16054 if related_to_selection {
16055 if !processed_buffer_rows
16056 .entry(hunk.buffer_id)
16057 .or_default()
16058 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16059 {
16060 continue;
16061 }
16062 hunks.push(hunk);
16063 }
16064 }
16065 }
16066
16067 hunks
16068 }
16069
16070 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16071 self.display_snapshot.buffer_snapshot.language_at(position)
16072 }
16073
16074 pub fn is_focused(&self) -> bool {
16075 self.is_focused
16076 }
16077
16078 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16079 self.placeholder_text.as_ref()
16080 }
16081
16082 pub fn scroll_position(&self) -> gpui::Point<f32> {
16083 self.scroll_anchor.scroll_position(&self.display_snapshot)
16084 }
16085
16086 fn gutter_dimensions(
16087 &self,
16088 font_id: FontId,
16089 font_size: Pixels,
16090 max_line_number_width: Pixels,
16091 cx: &App,
16092 ) -> Option<GutterDimensions> {
16093 if !self.show_gutter {
16094 return None;
16095 }
16096
16097 let descent = cx.text_system().descent(font_id, font_size);
16098 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16099 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16100
16101 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16102 matches!(
16103 ProjectSettings::get_global(cx).git.git_gutter,
16104 Some(GitGutterSetting::TrackedFiles)
16105 )
16106 });
16107 let gutter_settings = EditorSettings::get_global(cx).gutter;
16108 let show_line_numbers = self
16109 .show_line_numbers
16110 .unwrap_or(gutter_settings.line_numbers);
16111 let line_gutter_width = if show_line_numbers {
16112 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16113 let min_width_for_number_on_gutter = em_advance * 4.0;
16114 max_line_number_width.max(min_width_for_number_on_gutter)
16115 } else {
16116 0.0.into()
16117 };
16118
16119 let show_code_actions = self
16120 .show_code_actions
16121 .unwrap_or(gutter_settings.code_actions);
16122
16123 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16124
16125 let git_blame_entries_width =
16126 self.git_blame_gutter_max_author_length
16127 .map(|max_author_length| {
16128 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16129
16130 /// The number of characters to dedicate to gaps and margins.
16131 const SPACING_WIDTH: usize = 4;
16132
16133 let max_char_count = max_author_length
16134 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16135 + ::git::SHORT_SHA_LENGTH
16136 + MAX_RELATIVE_TIMESTAMP.len()
16137 + SPACING_WIDTH;
16138
16139 em_advance * max_char_count
16140 });
16141
16142 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16143 left_padding += if show_code_actions || show_runnables {
16144 em_width * 3.0
16145 } else if show_git_gutter && show_line_numbers {
16146 em_width * 2.0
16147 } else if show_git_gutter || show_line_numbers {
16148 em_width
16149 } else {
16150 px(0.)
16151 };
16152
16153 let right_padding = if gutter_settings.folds && show_line_numbers {
16154 em_width * 4.0
16155 } else if gutter_settings.folds {
16156 em_width * 3.0
16157 } else if show_line_numbers {
16158 em_width
16159 } else {
16160 px(0.)
16161 };
16162
16163 Some(GutterDimensions {
16164 left_padding,
16165 right_padding,
16166 width: line_gutter_width + left_padding + right_padding,
16167 margin: -descent,
16168 git_blame_entries_width,
16169 })
16170 }
16171
16172 pub fn render_crease_toggle(
16173 &self,
16174 buffer_row: MultiBufferRow,
16175 row_contains_cursor: bool,
16176 editor: Entity<Editor>,
16177 window: &mut Window,
16178 cx: &mut App,
16179 ) -> Option<AnyElement> {
16180 let folded = self.is_line_folded(buffer_row);
16181 let mut is_foldable = false;
16182
16183 if let Some(crease) = self
16184 .crease_snapshot
16185 .query_row(buffer_row, &self.buffer_snapshot)
16186 {
16187 is_foldable = true;
16188 match crease {
16189 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16190 if let Some(render_toggle) = render_toggle {
16191 let toggle_callback =
16192 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16193 if folded {
16194 editor.update(cx, |editor, cx| {
16195 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16196 });
16197 } else {
16198 editor.update(cx, |editor, cx| {
16199 editor.unfold_at(
16200 &crate::UnfoldAt { buffer_row },
16201 window,
16202 cx,
16203 )
16204 });
16205 }
16206 });
16207 return Some((render_toggle)(
16208 buffer_row,
16209 folded,
16210 toggle_callback,
16211 window,
16212 cx,
16213 ));
16214 }
16215 }
16216 }
16217 }
16218
16219 is_foldable |= self.starts_indent(buffer_row);
16220
16221 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16222 Some(
16223 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16224 .toggle_state(folded)
16225 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16226 if folded {
16227 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16228 } else {
16229 this.fold_at(&FoldAt { buffer_row }, window, cx);
16230 }
16231 }))
16232 .into_any_element(),
16233 )
16234 } else {
16235 None
16236 }
16237 }
16238
16239 pub fn render_crease_trailer(
16240 &self,
16241 buffer_row: MultiBufferRow,
16242 window: &mut Window,
16243 cx: &mut App,
16244 ) -> Option<AnyElement> {
16245 let folded = self.is_line_folded(buffer_row);
16246 if let Crease::Inline { render_trailer, .. } = self
16247 .crease_snapshot
16248 .query_row(buffer_row, &self.buffer_snapshot)?
16249 {
16250 let render_trailer = render_trailer.as_ref()?;
16251 Some(render_trailer(buffer_row, folded, window, cx))
16252 } else {
16253 None
16254 }
16255 }
16256}
16257
16258impl Deref for EditorSnapshot {
16259 type Target = DisplaySnapshot;
16260
16261 fn deref(&self) -> &Self::Target {
16262 &self.display_snapshot
16263 }
16264}
16265
16266#[derive(Clone, Debug, PartialEq, Eq)]
16267pub enum EditorEvent {
16268 InputIgnored {
16269 text: Arc<str>,
16270 },
16271 InputHandled {
16272 utf16_range_to_replace: Option<Range<isize>>,
16273 text: Arc<str>,
16274 },
16275 ExcerptsAdded {
16276 buffer: Entity<Buffer>,
16277 predecessor: ExcerptId,
16278 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16279 },
16280 ExcerptsRemoved {
16281 ids: Vec<ExcerptId>,
16282 },
16283 BufferFoldToggled {
16284 ids: Vec<ExcerptId>,
16285 folded: bool,
16286 },
16287 ExcerptsEdited {
16288 ids: Vec<ExcerptId>,
16289 },
16290 ExcerptsExpanded {
16291 ids: Vec<ExcerptId>,
16292 },
16293 BufferEdited,
16294 Edited {
16295 transaction_id: clock::Lamport,
16296 },
16297 Reparsed(BufferId),
16298 Focused,
16299 FocusedIn,
16300 Blurred,
16301 DirtyChanged,
16302 Saved,
16303 TitleChanged,
16304 DiffBaseChanged,
16305 SelectionsChanged {
16306 local: bool,
16307 },
16308 ScrollPositionChanged {
16309 local: bool,
16310 autoscroll: bool,
16311 },
16312 Closed,
16313 TransactionUndone {
16314 transaction_id: clock::Lamport,
16315 },
16316 TransactionBegun {
16317 transaction_id: clock::Lamport,
16318 },
16319 Reloaded,
16320 CursorShapeChanged,
16321}
16322
16323impl EventEmitter<EditorEvent> for Editor {}
16324
16325impl Focusable for Editor {
16326 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16327 self.focus_handle.clone()
16328 }
16329}
16330
16331impl Render for Editor {
16332 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16333 let settings = ThemeSettings::get_global(cx);
16334
16335 let mut text_style = match self.mode {
16336 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16337 color: cx.theme().colors().editor_foreground,
16338 font_family: settings.ui_font.family.clone(),
16339 font_features: settings.ui_font.features.clone(),
16340 font_fallbacks: settings.ui_font.fallbacks.clone(),
16341 font_size: rems(0.875).into(),
16342 font_weight: settings.ui_font.weight,
16343 line_height: relative(settings.buffer_line_height.value()),
16344 ..Default::default()
16345 },
16346 EditorMode::Full => TextStyle {
16347 color: cx.theme().colors().editor_foreground,
16348 font_family: settings.buffer_font.family.clone(),
16349 font_features: settings.buffer_font.features.clone(),
16350 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16351 font_size: settings.buffer_font_size(cx).into(),
16352 font_weight: settings.buffer_font.weight,
16353 line_height: relative(settings.buffer_line_height.value()),
16354 ..Default::default()
16355 },
16356 };
16357 if let Some(text_style_refinement) = &self.text_style_refinement {
16358 text_style.refine(text_style_refinement)
16359 }
16360
16361 let background = match self.mode {
16362 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16363 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16364 EditorMode::Full => cx.theme().colors().editor_background,
16365 };
16366
16367 EditorElement::new(
16368 &cx.entity(),
16369 EditorStyle {
16370 background,
16371 local_player: cx.theme().players().local(),
16372 text: text_style,
16373 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16374 syntax: cx.theme().syntax().clone(),
16375 status: cx.theme().status().clone(),
16376 inlay_hints_style: make_inlay_hints_style(cx),
16377 inline_completion_styles: make_suggestion_styles(cx),
16378 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16379 },
16380 )
16381 }
16382}
16383
16384impl EntityInputHandler for Editor {
16385 fn text_for_range(
16386 &mut self,
16387 range_utf16: Range<usize>,
16388 adjusted_range: &mut Option<Range<usize>>,
16389 _: &mut Window,
16390 cx: &mut Context<Self>,
16391 ) -> Option<String> {
16392 let snapshot = self.buffer.read(cx).read(cx);
16393 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16394 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16395 if (start.0..end.0) != range_utf16 {
16396 adjusted_range.replace(start.0..end.0);
16397 }
16398 Some(snapshot.text_for_range(start..end).collect())
16399 }
16400
16401 fn selected_text_range(
16402 &mut self,
16403 ignore_disabled_input: bool,
16404 _: &mut Window,
16405 cx: &mut Context<Self>,
16406 ) -> Option<UTF16Selection> {
16407 // Prevent the IME menu from appearing when holding down an alphabetic key
16408 // while input is disabled.
16409 if !ignore_disabled_input && !self.input_enabled {
16410 return None;
16411 }
16412
16413 let selection = self.selections.newest::<OffsetUtf16>(cx);
16414 let range = selection.range();
16415
16416 Some(UTF16Selection {
16417 range: range.start.0..range.end.0,
16418 reversed: selection.reversed,
16419 })
16420 }
16421
16422 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16423 let snapshot = self.buffer.read(cx).read(cx);
16424 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16425 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16426 }
16427
16428 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16429 self.clear_highlights::<InputComposition>(cx);
16430 self.ime_transaction.take();
16431 }
16432
16433 fn replace_text_in_range(
16434 &mut self,
16435 range_utf16: Option<Range<usize>>,
16436 text: &str,
16437 window: &mut Window,
16438 cx: &mut Context<Self>,
16439 ) {
16440 if !self.input_enabled {
16441 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16442 return;
16443 }
16444
16445 self.transact(window, cx, |this, window, cx| {
16446 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16447 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16448 Some(this.selection_replacement_ranges(range_utf16, cx))
16449 } else {
16450 this.marked_text_ranges(cx)
16451 };
16452
16453 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16454 let newest_selection_id = this.selections.newest_anchor().id;
16455 this.selections
16456 .all::<OffsetUtf16>(cx)
16457 .iter()
16458 .zip(ranges_to_replace.iter())
16459 .find_map(|(selection, range)| {
16460 if selection.id == newest_selection_id {
16461 Some(
16462 (range.start.0 as isize - selection.head().0 as isize)
16463 ..(range.end.0 as isize - selection.head().0 as isize),
16464 )
16465 } else {
16466 None
16467 }
16468 })
16469 });
16470
16471 cx.emit(EditorEvent::InputHandled {
16472 utf16_range_to_replace: range_to_replace,
16473 text: text.into(),
16474 });
16475
16476 if let Some(new_selected_ranges) = new_selected_ranges {
16477 this.change_selections(None, window, cx, |selections| {
16478 selections.select_ranges(new_selected_ranges)
16479 });
16480 this.backspace(&Default::default(), window, cx);
16481 }
16482
16483 this.handle_input(text, window, cx);
16484 });
16485
16486 if let Some(transaction) = self.ime_transaction {
16487 self.buffer.update(cx, |buffer, cx| {
16488 buffer.group_until_transaction(transaction, cx);
16489 });
16490 }
16491
16492 self.unmark_text(window, cx);
16493 }
16494
16495 fn replace_and_mark_text_in_range(
16496 &mut self,
16497 range_utf16: Option<Range<usize>>,
16498 text: &str,
16499 new_selected_range_utf16: Option<Range<usize>>,
16500 window: &mut Window,
16501 cx: &mut Context<Self>,
16502 ) {
16503 if !self.input_enabled {
16504 return;
16505 }
16506
16507 let transaction = self.transact(window, cx, |this, window, cx| {
16508 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16509 let snapshot = this.buffer.read(cx).read(cx);
16510 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16511 for marked_range in &mut marked_ranges {
16512 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16513 marked_range.start.0 += relative_range_utf16.start;
16514 marked_range.start =
16515 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16516 marked_range.end =
16517 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16518 }
16519 }
16520 Some(marked_ranges)
16521 } else if let Some(range_utf16) = range_utf16 {
16522 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16523 Some(this.selection_replacement_ranges(range_utf16, cx))
16524 } else {
16525 None
16526 };
16527
16528 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16529 let newest_selection_id = this.selections.newest_anchor().id;
16530 this.selections
16531 .all::<OffsetUtf16>(cx)
16532 .iter()
16533 .zip(ranges_to_replace.iter())
16534 .find_map(|(selection, range)| {
16535 if selection.id == newest_selection_id {
16536 Some(
16537 (range.start.0 as isize - selection.head().0 as isize)
16538 ..(range.end.0 as isize - selection.head().0 as isize),
16539 )
16540 } else {
16541 None
16542 }
16543 })
16544 });
16545
16546 cx.emit(EditorEvent::InputHandled {
16547 utf16_range_to_replace: range_to_replace,
16548 text: text.into(),
16549 });
16550
16551 if let Some(ranges) = ranges_to_replace {
16552 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16553 }
16554
16555 let marked_ranges = {
16556 let snapshot = this.buffer.read(cx).read(cx);
16557 this.selections
16558 .disjoint_anchors()
16559 .iter()
16560 .map(|selection| {
16561 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16562 })
16563 .collect::<Vec<_>>()
16564 };
16565
16566 if text.is_empty() {
16567 this.unmark_text(window, cx);
16568 } else {
16569 this.highlight_text::<InputComposition>(
16570 marked_ranges.clone(),
16571 HighlightStyle {
16572 underline: Some(UnderlineStyle {
16573 thickness: px(1.),
16574 color: None,
16575 wavy: false,
16576 }),
16577 ..Default::default()
16578 },
16579 cx,
16580 );
16581 }
16582
16583 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16584 let use_autoclose = this.use_autoclose;
16585 let use_auto_surround = this.use_auto_surround;
16586 this.set_use_autoclose(false);
16587 this.set_use_auto_surround(false);
16588 this.handle_input(text, window, cx);
16589 this.set_use_autoclose(use_autoclose);
16590 this.set_use_auto_surround(use_auto_surround);
16591
16592 if let Some(new_selected_range) = new_selected_range_utf16 {
16593 let snapshot = this.buffer.read(cx).read(cx);
16594 let new_selected_ranges = marked_ranges
16595 .into_iter()
16596 .map(|marked_range| {
16597 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16598 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16599 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16600 snapshot.clip_offset_utf16(new_start, Bias::Left)
16601 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16602 })
16603 .collect::<Vec<_>>();
16604
16605 drop(snapshot);
16606 this.change_selections(None, window, cx, |selections| {
16607 selections.select_ranges(new_selected_ranges)
16608 });
16609 }
16610 });
16611
16612 self.ime_transaction = self.ime_transaction.or(transaction);
16613 if let Some(transaction) = self.ime_transaction {
16614 self.buffer.update(cx, |buffer, cx| {
16615 buffer.group_until_transaction(transaction, cx);
16616 });
16617 }
16618
16619 if self.text_highlights::<InputComposition>(cx).is_none() {
16620 self.ime_transaction.take();
16621 }
16622 }
16623
16624 fn bounds_for_range(
16625 &mut self,
16626 range_utf16: Range<usize>,
16627 element_bounds: gpui::Bounds<Pixels>,
16628 window: &mut Window,
16629 cx: &mut Context<Self>,
16630 ) -> Option<gpui::Bounds<Pixels>> {
16631 let text_layout_details = self.text_layout_details(window);
16632 let gpui::Size {
16633 width: em_width,
16634 height: line_height,
16635 } = self.character_size(window);
16636
16637 let snapshot = self.snapshot(window, cx);
16638 let scroll_position = snapshot.scroll_position();
16639 let scroll_left = scroll_position.x * em_width;
16640
16641 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16642 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16643 + self.gutter_dimensions.width
16644 + self.gutter_dimensions.margin;
16645 let y = line_height * (start.row().as_f32() - scroll_position.y);
16646
16647 Some(Bounds {
16648 origin: element_bounds.origin + point(x, y),
16649 size: size(em_width, line_height),
16650 })
16651 }
16652
16653 fn character_index_for_point(
16654 &mut self,
16655 point: gpui::Point<Pixels>,
16656 _window: &mut Window,
16657 _cx: &mut Context<Self>,
16658 ) -> Option<usize> {
16659 let position_map = self.last_position_map.as_ref()?;
16660 if !position_map.text_hitbox.contains(&point) {
16661 return None;
16662 }
16663 let display_point = position_map.point_for_position(point).previous_valid;
16664 let anchor = position_map
16665 .snapshot
16666 .display_point_to_anchor(display_point, Bias::Left);
16667 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16668 Some(utf16_offset.0)
16669 }
16670}
16671
16672trait SelectionExt {
16673 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16674 fn spanned_rows(
16675 &self,
16676 include_end_if_at_line_start: bool,
16677 map: &DisplaySnapshot,
16678 ) -> Range<MultiBufferRow>;
16679}
16680
16681impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16682 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16683 let start = self
16684 .start
16685 .to_point(&map.buffer_snapshot)
16686 .to_display_point(map);
16687 let end = self
16688 .end
16689 .to_point(&map.buffer_snapshot)
16690 .to_display_point(map);
16691 if self.reversed {
16692 end..start
16693 } else {
16694 start..end
16695 }
16696 }
16697
16698 fn spanned_rows(
16699 &self,
16700 include_end_if_at_line_start: bool,
16701 map: &DisplaySnapshot,
16702 ) -> Range<MultiBufferRow> {
16703 let start = self.start.to_point(&map.buffer_snapshot);
16704 let mut end = self.end.to_point(&map.buffer_snapshot);
16705 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16706 end.row -= 1;
16707 }
16708
16709 let buffer_start = map.prev_line_boundary(start).0;
16710 let buffer_end = map.next_line_boundary(end).0;
16711 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16712 }
16713}
16714
16715impl<T: InvalidationRegion> InvalidationStack<T> {
16716 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16717 where
16718 S: Clone + ToOffset,
16719 {
16720 while let Some(region) = self.last() {
16721 let all_selections_inside_invalidation_ranges =
16722 if selections.len() == region.ranges().len() {
16723 selections
16724 .iter()
16725 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16726 .all(|(selection, invalidation_range)| {
16727 let head = selection.head().to_offset(buffer);
16728 invalidation_range.start <= head && invalidation_range.end >= head
16729 })
16730 } else {
16731 false
16732 };
16733
16734 if all_selections_inside_invalidation_ranges {
16735 break;
16736 } else {
16737 self.pop();
16738 }
16739 }
16740 }
16741}
16742
16743impl<T> Default for InvalidationStack<T> {
16744 fn default() -> Self {
16745 Self(Default::default())
16746 }
16747}
16748
16749impl<T> Deref for InvalidationStack<T> {
16750 type Target = Vec<T>;
16751
16752 fn deref(&self) -> &Self::Target {
16753 &self.0
16754 }
16755}
16756
16757impl<T> DerefMut for InvalidationStack<T> {
16758 fn deref_mut(&mut self) -> &mut Self::Target {
16759 &mut self.0
16760 }
16761}
16762
16763impl InvalidationRegion for SnippetState {
16764 fn ranges(&self) -> &[Range<Anchor>] {
16765 &self.ranges[self.active_index]
16766 }
16767}
16768
16769pub fn diagnostic_block_renderer(
16770 diagnostic: Diagnostic,
16771 max_message_rows: Option<u8>,
16772 allow_closing: bool,
16773 _is_valid: bool,
16774) -> RenderBlock {
16775 let (text_without_backticks, code_ranges) =
16776 highlight_diagnostic_message(&diagnostic, max_message_rows);
16777
16778 Arc::new(move |cx: &mut BlockContext| {
16779 let group_id: SharedString = cx.block_id.to_string().into();
16780
16781 let mut text_style = cx.window.text_style().clone();
16782 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16783 let theme_settings = ThemeSettings::get_global(cx);
16784 text_style.font_family = theme_settings.buffer_font.family.clone();
16785 text_style.font_style = theme_settings.buffer_font.style;
16786 text_style.font_features = theme_settings.buffer_font.features.clone();
16787 text_style.font_weight = theme_settings.buffer_font.weight;
16788
16789 let multi_line_diagnostic = diagnostic.message.contains('\n');
16790
16791 let buttons = |diagnostic: &Diagnostic| {
16792 if multi_line_diagnostic {
16793 v_flex()
16794 } else {
16795 h_flex()
16796 }
16797 .when(allow_closing, |div| {
16798 div.children(diagnostic.is_primary.then(|| {
16799 IconButton::new("close-block", IconName::XCircle)
16800 .icon_color(Color::Muted)
16801 .size(ButtonSize::Compact)
16802 .style(ButtonStyle::Transparent)
16803 .visible_on_hover(group_id.clone())
16804 .on_click(move |_click, window, cx| {
16805 window.dispatch_action(Box::new(Cancel), cx)
16806 })
16807 .tooltip(|window, cx| {
16808 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16809 })
16810 }))
16811 })
16812 .child(
16813 IconButton::new("copy-block", IconName::Copy)
16814 .icon_color(Color::Muted)
16815 .size(ButtonSize::Compact)
16816 .style(ButtonStyle::Transparent)
16817 .visible_on_hover(group_id.clone())
16818 .on_click({
16819 let message = diagnostic.message.clone();
16820 move |_click, _, cx| {
16821 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16822 }
16823 })
16824 .tooltip(Tooltip::text("Copy diagnostic message")),
16825 )
16826 };
16827
16828 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16829 AvailableSpace::min_size(),
16830 cx.window,
16831 cx.app,
16832 );
16833
16834 h_flex()
16835 .id(cx.block_id)
16836 .group(group_id.clone())
16837 .relative()
16838 .size_full()
16839 .block_mouse_down()
16840 .pl(cx.gutter_dimensions.width)
16841 .w(cx.max_width - cx.gutter_dimensions.full_width())
16842 .child(
16843 div()
16844 .flex()
16845 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16846 .flex_shrink(),
16847 )
16848 .child(buttons(&diagnostic))
16849 .child(div().flex().flex_shrink_0().child(
16850 StyledText::new(text_without_backticks.clone()).with_highlights(
16851 &text_style,
16852 code_ranges.iter().map(|range| {
16853 (
16854 range.clone(),
16855 HighlightStyle {
16856 font_weight: Some(FontWeight::BOLD),
16857 ..Default::default()
16858 },
16859 )
16860 }),
16861 ),
16862 ))
16863 .into_any_element()
16864 })
16865}
16866
16867fn inline_completion_edit_text(
16868 current_snapshot: &BufferSnapshot,
16869 edits: &[(Range<Anchor>, String)],
16870 edit_preview: &EditPreview,
16871 include_deletions: bool,
16872 cx: &App,
16873) -> HighlightedText {
16874 let edits = edits
16875 .iter()
16876 .map(|(anchor, text)| {
16877 (
16878 anchor.start.text_anchor..anchor.end.text_anchor,
16879 text.clone(),
16880 )
16881 })
16882 .collect::<Vec<_>>();
16883
16884 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16885}
16886
16887pub fn highlight_diagnostic_message(
16888 diagnostic: &Diagnostic,
16889 mut max_message_rows: Option<u8>,
16890) -> (SharedString, Vec<Range<usize>>) {
16891 let mut text_without_backticks = String::new();
16892 let mut code_ranges = Vec::new();
16893
16894 if let Some(source) = &diagnostic.source {
16895 text_without_backticks.push_str(source);
16896 code_ranges.push(0..source.len());
16897 text_without_backticks.push_str(": ");
16898 }
16899
16900 let mut prev_offset = 0;
16901 let mut in_code_block = false;
16902 let has_row_limit = max_message_rows.is_some();
16903 let mut newline_indices = diagnostic
16904 .message
16905 .match_indices('\n')
16906 .filter(|_| has_row_limit)
16907 .map(|(ix, _)| ix)
16908 .fuse()
16909 .peekable();
16910
16911 for (quote_ix, _) in diagnostic
16912 .message
16913 .match_indices('`')
16914 .chain([(diagnostic.message.len(), "")])
16915 {
16916 let mut first_newline_ix = None;
16917 let mut last_newline_ix = None;
16918 while let Some(newline_ix) = newline_indices.peek() {
16919 if *newline_ix < quote_ix {
16920 if first_newline_ix.is_none() {
16921 first_newline_ix = Some(*newline_ix);
16922 }
16923 last_newline_ix = Some(*newline_ix);
16924
16925 if let Some(rows_left) = &mut max_message_rows {
16926 if *rows_left == 0 {
16927 break;
16928 } else {
16929 *rows_left -= 1;
16930 }
16931 }
16932 let _ = newline_indices.next();
16933 } else {
16934 break;
16935 }
16936 }
16937 let prev_len = text_without_backticks.len();
16938 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16939 text_without_backticks.push_str(new_text);
16940 if in_code_block {
16941 code_ranges.push(prev_len..text_without_backticks.len());
16942 }
16943 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16944 in_code_block = !in_code_block;
16945 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16946 text_without_backticks.push_str("...");
16947 break;
16948 }
16949 }
16950
16951 (text_without_backticks.into(), code_ranges)
16952}
16953
16954fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16955 match severity {
16956 DiagnosticSeverity::ERROR => colors.error,
16957 DiagnosticSeverity::WARNING => colors.warning,
16958 DiagnosticSeverity::INFORMATION => colors.info,
16959 DiagnosticSeverity::HINT => colors.info,
16960 _ => colors.ignored,
16961 }
16962}
16963
16964pub fn styled_runs_for_code_label<'a>(
16965 label: &'a CodeLabel,
16966 syntax_theme: &'a theme::SyntaxTheme,
16967) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16968 let fade_out = HighlightStyle {
16969 fade_out: Some(0.35),
16970 ..Default::default()
16971 };
16972
16973 let mut prev_end = label.filter_range.end;
16974 label
16975 .runs
16976 .iter()
16977 .enumerate()
16978 .flat_map(move |(ix, (range, highlight_id))| {
16979 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16980 style
16981 } else {
16982 return Default::default();
16983 };
16984 let mut muted_style = style;
16985 muted_style.highlight(fade_out);
16986
16987 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16988 if range.start >= label.filter_range.end {
16989 if range.start > prev_end {
16990 runs.push((prev_end..range.start, fade_out));
16991 }
16992 runs.push((range.clone(), muted_style));
16993 } else if range.end <= label.filter_range.end {
16994 runs.push((range.clone(), style));
16995 } else {
16996 runs.push((range.start..label.filter_range.end, style));
16997 runs.push((label.filter_range.end..range.end, muted_style));
16998 }
16999 prev_end = cmp::max(prev_end, range.end);
17000
17001 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17002 runs.push((prev_end..label.text.len(), fade_out));
17003 }
17004
17005 runs
17006 })
17007}
17008
17009pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17010 let mut prev_index = 0;
17011 let mut prev_codepoint: Option<char> = None;
17012 text.char_indices()
17013 .chain([(text.len(), '\0')])
17014 .filter_map(move |(index, codepoint)| {
17015 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17016 let is_boundary = index == text.len()
17017 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17018 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17019 if is_boundary {
17020 let chunk = &text[prev_index..index];
17021 prev_index = index;
17022 Some(chunk)
17023 } else {
17024 None
17025 }
17026 })
17027}
17028
17029pub trait RangeToAnchorExt: Sized {
17030 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17031
17032 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17033 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17034 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17035 }
17036}
17037
17038impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17039 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17040 let start_offset = self.start.to_offset(snapshot);
17041 let end_offset = self.end.to_offset(snapshot);
17042 if start_offset == end_offset {
17043 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17044 } else {
17045 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17046 }
17047 }
17048}
17049
17050pub trait RowExt {
17051 fn as_f32(&self) -> f32;
17052
17053 fn next_row(&self) -> Self;
17054
17055 fn previous_row(&self) -> Self;
17056
17057 fn minus(&self, other: Self) -> u32;
17058}
17059
17060impl RowExt for DisplayRow {
17061 fn as_f32(&self) -> f32 {
17062 self.0 as f32
17063 }
17064
17065 fn next_row(&self) -> Self {
17066 Self(self.0 + 1)
17067 }
17068
17069 fn previous_row(&self) -> Self {
17070 Self(self.0.saturating_sub(1))
17071 }
17072
17073 fn minus(&self, other: Self) -> u32 {
17074 self.0 - other.0
17075 }
17076}
17077
17078impl RowExt for MultiBufferRow {
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
17096trait RowRangeExt {
17097 type Row;
17098
17099 fn len(&self) -> usize;
17100
17101 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17102}
17103
17104impl RowRangeExt for Range<MultiBufferRow> {
17105 type Row = MultiBufferRow;
17106
17107 fn len(&self) -> usize {
17108 (self.end.0 - self.start.0) as usize
17109 }
17110
17111 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17112 (self.start.0..self.end.0).map(MultiBufferRow)
17113 }
17114}
17115
17116impl RowRangeExt for Range<DisplayRow> {
17117 type Row = DisplayRow;
17118
17119 fn len(&self) -> usize {
17120 (self.end.0 - self.start.0) as usize
17121 }
17122
17123 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17124 (self.start.0..self.end.0).map(DisplayRow)
17125 }
17126}
17127
17128/// If select range has more than one line, we
17129/// just point the cursor to range.start.
17130fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17131 if range.start.row == range.end.row {
17132 range
17133 } else {
17134 range.start..range.start
17135 }
17136}
17137pub struct KillRing(ClipboardItem);
17138impl Global for KillRing {}
17139
17140const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17141
17142fn all_edits_insertions_or_deletions(
17143 edits: &Vec<(Range<Anchor>, String)>,
17144 snapshot: &MultiBufferSnapshot,
17145) -> bool {
17146 let mut all_insertions = true;
17147 let mut all_deletions = true;
17148
17149 for (range, new_text) in edits.iter() {
17150 let range_is_empty = range.to_offset(&snapshot).is_empty();
17151 let text_is_empty = new_text.is_empty();
17152
17153 if range_is_empty != text_is_empty {
17154 if range_is_empty {
17155 all_deletions = false;
17156 } else {
17157 all_insertions = false;
17158 }
17159 } else {
17160 return false;
17161 }
17162
17163 if !all_insertions && !all_deletions {
17164 return false;
17165 }
17166 }
17167 all_insertions || all_deletions
17168}