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
467#[derive(Debug, Clone)]
468struct InlineDiagnostic {
469 message: SharedString,
470 group_id: usize,
471 is_primary: bool,
472 start: Point,
473 severity: DiagnosticSeverity,
474}
475
476pub enum MenuInlineCompletionsPolicy {
477 Never,
478 ByProvider,
479}
480
481pub enum EditPredictionPreview {
482 /// Modifier is not pressed
483 Inactive,
484 /// Modifier pressed
485 Active {
486 previous_scroll_position: Option<ScrollAnchor>,
487 },
488}
489
490#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
491struct EditorActionId(usize);
492
493impl EditorActionId {
494 pub fn post_inc(&mut self) -> Self {
495 let answer = self.0;
496
497 *self = Self(answer + 1);
498
499 Self(answer)
500 }
501}
502
503// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
504// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
505
506type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
507type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
508
509#[derive(Default)]
510struct ScrollbarMarkerState {
511 scrollbar_size: Size<Pixels>,
512 dirty: bool,
513 markers: Arc<[PaintQuad]>,
514 pending_refresh: Option<Task<Result<()>>>,
515}
516
517impl ScrollbarMarkerState {
518 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
519 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
520 }
521}
522
523#[derive(Clone, Debug)]
524struct RunnableTasks {
525 templates: Vec<(TaskSourceKind, TaskTemplate)>,
526 offset: MultiBufferOffset,
527 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
528 column: u32,
529 // Values of all named captures, including those starting with '_'
530 extra_variables: HashMap<String, String>,
531 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
532 context_range: Range<BufferOffset>,
533}
534
535impl RunnableTasks {
536 fn resolve<'a>(
537 &'a self,
538 cx: &'a task::TaskContext,
539 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
540 self.templates.iter().filter_map(|(kind, template)| {
541 template
542 .resolve_task(&kind.to_id_base(), cx)
543 .map(|task| (kind.clone(), task))
544 })
545 }
546}
547
548#[derive(Clone)]
549struct ResolvedTasks {
550 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
551 position: Anchor,
552}
553#[derive(Copy, Clone, Debug)]
554struct MultiBufferOffset(usize);
555#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
556struct BufferOffset(usize);
557
558// Addons allow storing per-editor state in other crates (e.g. Vim)
559pub trait Addon: 'static {
560 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
561
562 fn render_buffer_header_controls(
563 &self,
564 _: &ExcerptInfo,
565 _: &Window,
566 _: &App,
567 ) -> Option<AnyElement> {
568 None
569 }
570
571 fn to_any(&self) -> &dyn std::any::Any;
572}
573
574#[derive(Debug, Copy, Clone, PartialEq, Eq)]
575pub enum IsVimMode {
576 Yes,
577 No,
578}
579
580/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
581///
582/// See the [module level documentation](self) for more information.
583pub struct Editor {
584 focus_handle: FocusHandle,
585 last_focused_descendant: Option<WeakFocusHandle>,
586 /// The text buffer being edited
587 buffer: Entity<MultiBuffer>,
588 /// Map of how text in the buffer should be displayed.
589 /// Handles soft wraps, folds, fake inlay text insertions, etc.
590 pub display_map: Entity<DisplayMap>,
591 pub selections: SelectionsCollection,
592 pub scroll_manager: ScrollManager,
593 /// When inline assist editors are linked, they all render cursors because
594 /// typing enters text into each of them, even the ones that aren't focused.
595 pub(crate) show_cursor_when_unfocused: bool,
596 columnar_selection_tail: Option<Anchor>,
597 add_selections_state: Option<AddSelectionsState>,
598 select_next_state: Option<SelectNextState>,
599 select_prev_state: Option<SelectNextState>,
600 selection_history: SelectionHistory,
601 autoclose_regions: Vec<AutocloseRegion>,
602 snippet_stack: InvalidationStack<SnippetState>,
603 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
604 ime_transaction: Option<TransactionId>,
605 active_diagnostics: Option<ActiveDiagnosticGroup>,
606 show_inline_diagnostics: bool,
607 inline_diagnostics_update: Task<()>,
608 inline_diagnostics_enabled: bool,
609 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
610 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
611
612 // TODO: make this a access method
613 pub project: Option<Entity<Project>>,
614 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
615 completion_provider: Option<Box<dyn CompletionProvider>>,
616 collaboration_hub: Option<Box<dyn CollaborationHub>>,
617 blink_manager: Entity<BlinkManager>,
618 show_cursor_names: bool,
619 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
620 pub show_local_selections: bool,
621 mode: EditorMode,
622 show_breadcrumbs: bool,
623 show_gutter: bool,
624 show_scrollbars: bool,
625 show_line_numbers: Option<bool>,
626 use_relative_line_numbers: Option<bool>,
627 show_git_diff_gutter: Option<bool>,
628 show_code_actions: Option<bool>,
629 show_runnables: Option<bool>,
630 show_wrap_guides: Option<bool>,
631 show_indent_guides: Option<bool>,
632 placeholder_text: Option<Arc<str>>,
633 highlight_order: usize,
634 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
635 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
636 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
637 scrollbar_marker_state: ScrollbarMarkerState,
638 active_indent_guides_state: ActiveIndentGuidesState,
639 nav_history: Option<ItemNavHistory>,
640 context_menu: RefCell<Option<CodeContextMenu>>,
641 mouse_context_menu: Option<MouseContextMenu>,
642 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
643 signature_help_state: SignatureHelpState,
644 auto_signature_help: Option<bool>,
645 find_all_references_task_sources: Vec<Anchor>,
646 next_completion_id: CompletionId,
647 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
648 code_actions_task: Option<Task<Result<()>>>,
649 selection_highlight_task: Option<Task<()>>,
650 document_highlights_task: Option<Task<()>>,
651 linked_editing_range_task: Option<Task<Option<()>>>,
652 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
653 pending_rename: Option<RenameState>,
654 searchable: bool,
655 cursor_shape: CursorShape,
656 current_line_highlight: Option<CurrentLineHighlight>,
657 collapse_matches: bool,
658 autoindent_mode: Option<AutoindentMode>,
659 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
660 input_enabled: bool,
661 use_modal_editing: bool,
662 read_only: bool,
663 leader_peer_id: Option<PeerId>,
664 remote_id: Option<ViewId>,
665 hover_state: HoverState,
666 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
667 gutter_hovered: bool,
668 hovered_link_state: Option<HoveredLinkState>,
669 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
670 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
671 active_inline_completion: Option<InlineCompletionState>,
672 /// Used to prevent flickering as the user types while the menu is open
673 stale_inline_completion_in_menu: Option<InlineCompletionState>,
674 edit_prediction_settings: EditPredictionSettings,
675 inline_completions_hidden_for_vim_mode: bool,
676 show_inline_completions_override: Option<bool>,
677 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
678 edit_prediction_preview: EditPredictionPreview,
679 edit_prediction_cursor_on_leading_whitespace: bool,
680 edit_prediction_requires_modifier_in_leading_space: bool,
681 inlay_hint_cache: InlayHintCache,
682 next_inlay_id: usize,
683 _subscriptions: Vec<Subscription>,
684 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
685 gutter_dimensions: GutterDimensions,
686 style: Option<EditorStyle>,
687 text_style_refinement: Option<TextStyleRefinement>,
688 next_editor_action_id: EditorActionId,
689 editor_actions:
690 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
691 use_autoclose: bool,
692 use_auto_surround: bool,
693 auto_replace_emoji_shortcode: bool,
694 show_git_blame_gutter: bool,
695 show_git_blame_inline: bool,
696 show_git_blame_inline_delay_task: Option<Task<()>>,
697 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
698 distinguish_unstaged_diff_hunks: bool,
699 git_blame_inline_enabled: bool,
700 serialize_dirty_buffers: bool,
701 show_selection_menu: Option<bool>,
702 blame: Option<Entity<GitBlame>>,
703 blame_subscription: Option<Subscription>,
704 custom_context_menu: Option<
705 Box<
706 dyn 'static
707 + Fn(
708 &mut Self,
709 DisplayPoint,
710 &mut Window,
711 &mut Context<Self>,
712 ) -> Option<Entity<ui::ContextMenu>>,
713 >,
714 >,
715 last_bounds: Option<Bounds<Pixels>>,
716 last_position_map: Option<Rc<PositionMap>>,
717 expect_bounds_change: Option<Bounds<Pixels>>,
718 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
719 tasks_update_task: Option<Task<()>>,
720 in_project_search: bool,
721 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
722 breadcrumb_header: Option<String>,
723 focused_block: Option<FocusedBlock>,
724 next_scroll_position: NextScrollCursorCenterTopBottom,
725 addons: HashMap<TypeId, Box<dyn Addon>>,
726 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
727 load_diff_task: Option<Shared<Task<()>>>,
728 selection_mark_mode: bool,
729 toggle_fold_multiple_buffers: Task<()>,
730 _scroll_cursor_center_top_bottom_task: Task<()>,
731 serialize_selections: Task<()>,
732 mouse_cursor_hidden: bool,
733 hide_mouse_while_typing: bool,
734}
735
736#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
737enum NextScrollCursorCenterTopBottom {
738 #[default]
739 Center,
740 Top,
741 Bottom,
742}
743
744impl NextScrollCursorCenterTopBottom {
745 fn next(&self) -> Self {
746 match self {
747 Self::Center => Self::Top,
748 Self::Top => Self::Bottom,
749 Self::Bottom => Self::Center,
750 }
751 }
752}
753
754#[derive(Clone)]
755pub struct EditorSnapshot {
756 pub mode: EditorMode,
757 show_gutter: bool,
758 show_line_numbers: Option<bool>,
759 show_git_diff_gutter: Option<bool>,
760 show_code_actions: Option<bool>,
761 show_runnables: Option<bool>,
762 git_blame_gutter_max_author_length: Option<usize>,
763 pub display_snapshot: DisplaySnapshot,
764 pub placeholder_text: Option<Arc<str>>,
765 is_focused: bool,
766 scroll_anchor: ScrollAnchor,
767 ongoing_scroll: OngoingScroll,
768 current_line_highlight: CurrentLineHighlight,
769 gutter_hovered: bool,
770}
771
772const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
773
774#[derive(Default, Debug, Clone, Copy)]
775pub struct GutterDimensions {
776 pub left_padding: Pixels,
777 pub right_padding: Pixels,
778 pub width: Pixels,
779 pub margin: Pixels,
780 pub git_blame_entries_width: Option<Pixels>,
781}
782
783impl GutterDimensions {
784 /// The full width of the space taken up by the gutter.
785 pub fn full_width(&self) -> Pixels {
786 self.margin + self.width
787 }
788
789 /// The width of the space reserved for the fold indicators,
790 /// use alongside 'justify_end' and `gutter_width` to
791 /// right align content with the line numbers
792 pub fn fold_area_width(&self) -> Pixels {
793 self.margin + self.right_padding
794 }
795}
796
797#[derive(Debug)]
798pub struct RemoteSelection {
799 pub replica_id: ReplicaId,
800 pub selection: Selection<Anchor>,
801 pub cursor_shape: CursorShape,
802 pub peer_id: PeerId,
803 pub line_mode: bool,
804 pub participant_index: Option<ParticipantIndex>,
805 pub user_name: Option<SharedString>,
806}
807
808#[derive(Clone, Debug)]
809struct SelectionHistoryEntry {
810 selections: Arc<[Selection<Anchor>]>,
811 select_next_state: Option<SelectNextState>,
812 select_prev_state: Option<SelectNextState>,
813 add_selections_state: Option<AddSelectionsState>,
814}
815
816enum SelectionHistoryMode {
817 Normal,
818 Undoing,
819 Redoing,
820}
821
822#[derive(Clone, PartialEq, Eq, Hash)]
823struct HoveredCursor {
824 replica_id: u16,
825 selection_id: usize,
826}
827
828impl Default for SelectionHistoryMode {
829 fn default() -> Self {
830 Self::Normal
831 }
832}
833
834#[derive(Default)]
835struct SelectionHistory {
836 #[allow(clippy::type_complexity)]
837 selections_by_transaction:
838 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
839 mode: SelectionHistoryMode,
840 undo_stack: VecDeque<SelectionHistoryEntry>,
841 redo_stack: VecDeque<SelectionHistoryEntry>,
842}
843
844impl SelectionHistory {
845 fn insert_transaction(
846 &mut self,
847 transaction_id: TransactionId,
848 selections: Arc<[Selection<Anchor>]>,
849 ) {
850 self.selections_by_transaction
851 .insert(transaction_id, (selections, None));
852 }
853
854 #[allow(clippy::type_complexity)]
855 fn transaction(
856 &self,
857 transaction_id: TransactionId,
858 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
859 self.selections_by_transaction.get(&transaction_id)
860 }
861
862 #[allow(clippy::type_complexity)]
863 fn transaction_mut(
864 &mut self,
865 transaction_id: TransactionId,
866 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
867 self.selections_by_transaction.get_mut(&transaction_id)
868 }
869
870 fn push(&mut self, entry: SelectionHistoryEntry) {
871 if !entry.selections.is_empty() {
872 match self.mode {
873 SelectionHistoryMode::Normal => {
874 self.push_undo(entry);
875 self.redo_stack.clear();
876 }
877 SelectionHistoryMode::Undoing => self.push_redo(entry),
878 SelectionHistoryMode::Redoing => self.push_undo(entry),
879 }
880 }
881 }
882
883 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
884 if self
885 .undo_stack
886 .back()
887 .map_or(true, |e| e.selections != entry.selections)
888 {
889 self.undo_stack.push_back(entry);
890 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
891 self.undo_stack.pop_front();
892 }
893 }
894 }
895
896 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
897 if self
898 .redo_stack
899 .back()
900 .map_or(true, |e| e.selections != entry.selections)
901 {
902 self.redo_stack.push_back(entry);
903 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
904 self.redo_stack.pop_front();
905 }
906 }
907 }
908}
909
910struct RowHighlight {
911 index: usize,
912 range: Range<Anchor>,
913 color: Hsla,
914 should_autoscroll: bool,
915}
916
917#[derive(Clone, Debug)]
918struct AddSelectionsState {
919 above: bool,
920 stack: Vec<usize>,
921}
922
923#[derive(Clone)]
924struct SelectNextState {
925 query: AhoCorasick,
926 wordwise: bool,
927 done: bool,
928}
929
930impl std::fmt::Debug for SelectNextState {
931 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932 f.debug_struct(std::any::type_name::<Self>())
933 .field("wordwise", &self.wordwise)
934 .field("done", &self.done)
935 .finish()
936 }
937}
938
939#[derive(Debug)]
940struct AutocloseRegion {
941 selection_id: usize,
942 range: Range<Anchor>,
943 pair: BracketPair,
944}
945
946#[derive(Debug)]
947struct SnippetState {
948 ranges: Vec<Vec<Range<Anchor>>>,
949 active_index: usize,
950 choices: Vec<Option<Vec<String>>>,
951}
952
953#[doc(hidden)]
954pub struct RenameState {
955 pub range: Range<Anchor>,
956 pub old_name: Arc<str>,
957 pub editor: Entity<Editor>,
958 block_id: CustomBlockId,
959}
960
961struct InvalidationStack<T>(Vec<T>);
962
963struct RegisteredInlineCompletionProvider {
964 provider: Arc<dyn InlineCompletionProviderHandle>,
965 _subscription: Subscription,
966}
967
968#[derive(Debug)]
969struct ActiveDiagnosticGroup {
970 primary_range: Range<Anchor>,
971 primary_message: String,
972 group_id: usize,
973 blocks: HashMap<CustomBlockId, Diagnostic>,
974 is_valid: bool,
975}
976
977#[derive(Serialize, Deserialize, Clone, Debug)]
978pub struct ClipboardSelection {
979 /// The number of bytes in this selection.
980 pub len: usize,
981 /// Whether this was a full-line selection.
982 pub is_entire_line: bool,
983 /// The column where this selection originally started.
984 pub start_column: u32,
985}
986
987#[derive(Debug)]
988pub(crate) struct NavigationData {
989 cursor_anchor: Anchor,
990 cursor_position: Point,
991 scroll_anchor: ScrollAnchor,
992 scroll_top_row: u32,
993}
994
995#[derive(Debug, Clone, Copy, PartialEq, Eq)]
996pub enum GotoDefinitionKind {
997 Symbol,
998 Declaration,
999 Type,
1000 Implementation,
1001}
1002
1003#[derive(Debug, Clone)]
1004enum InlayHintRefreshReason {
1005 Toggle(bool),
1006 SettingsChange(InlayHintSettings),
1007 NewLinesShown,
1008 BufferEdited(HashSet<Arc<Language>>),
1009 RefreshRequested,
1010 ExcerptsRemoved(Vec<ExcerptId>),
1011}
1012
1013impl InlayHintRefreshReason {
1014 fn description(&self) -> &'static str {
1015 match self {
1016 Self::Toggle(_) => "toggle",
1017 Self::SettingsChange(_) => "settings change",
1018 Self::NewLinesShown => "new lines shown",
1019 Self::BufferEdited(_) => "buffer edited",
1020 Self::RefreshRequested => "refresh requested",
1021 Self::ExcerptsRemoved(_) => "excerpts removed",
1022 }
1023 }
1024}
1025
1026pub enum FormatTarget {
1027 Buffers,
1028 Ranges(Vec<Range<MultiBufferPoint>>),
1029}
1030
1031pub(crate) struct FocusedBlock {
1032 id: BlockId,
1033 focus_handle: WeakFocusHandle,
1034}
1035
1036#[derive(Clone)]
1037enum JumpData {
1038 MultiBufferRow {
1039 row: MultiBufferRow,
1040 line_offset_from_top: u32,
1041 },
1042 MultiBufferPoint {
1043 excerpt_id: ExcerptId,
1044 position: Point,
1045 anchor: text::Anchor,
1046 line_offset_from_top: u32,
1047 },
1048}
1049
1050pub enum MultibufferSelectionMode {
1051 First,
1052 All,
1053}
1054
1055impl Editor {
1056 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1057 let buffer = cx.new(|cx| Buffer::local("", cx));
1058 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1059 Self::new(
1060 EditorMode::SingleLine { auto_width: false },
1061 buffer,
1062 None,
1063 false,
1064 window,
1065 cx,
1066 )
1067 }
1068
1069 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1070 let buffer = cx.new(|cx| Buffer::local("", cx));
1071 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1072 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1073 }
1074
1075 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1076 let buffer = cx.new(|cx| Buffer::local("", cx));
1077 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1078 Self::new(
1079 EditorMode::SingleLine { auto_width: true },
1080 buffer,
1081 None,
1082 false,
1083 window,
1084 cx,
1085 )
1086 }
1087
1088 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1089 let buffer = cx.new(|cx| Buffer::local("", cx));
1090 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1091 Self::new(
1092 EditorMode::AutoHeight { max_lines },
1093 buffer,
1094 None,
1095 false,
1096 window,
1097 cx,
1098 )
1099 }
1100
1101 pub fn for_buffer(
1102 buffer: Entity<Buffer>,
1103 project: Option<Entity<Project>>,
1104 window: &mut Window,
1105 cx: &mut Context<Self>,
1106 ) -> Self {
1107 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1108 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1109 }
1110
1111 pub fn for_multibuffer(
1112 buffer: Entity<MultiBuffer>,
1113 project: Option<Entity<Project>>,
1114 show_excerpt_controls: bool,
1115 window: &mut Window,
1116 cx: &mut Context<Self>,
1117 ) -> Self {
1118 Self::new(
1119 EditorMode::Full,
1120 buffer,
1121 project,
1122 show_excerpt_controls,
1123 window,
1124 cx,
1125 )
1126 }
1127
1128 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1129 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1130 let mut clone = Self::new(
1131 self.mode,
1132 self.buffer.clone(),
1133 self.project.clone(),
1134 show_excerpt_controls,
1135 window,
1136 cx,
1137 );
1138 self.display_map.update(cx, |display_map, cx| {
1139 let snapshot = display_map.snapshot(cx);
1140 clone.display_map.update(cx, |display_map, cx| {
1141 display_map.set_state(&snapshot, cx);
1142 });
1143 });
1144 clone.selections.clone_state(&self.selections);
1145 clone.scroll_manager.clone_state(&self.scroll_manager);
1146 clone.searchable = self.searchable;
1147 clone
1148 }
1149
1150 pub fn new(
1151 mode: EditorMode,
1152 buffer: Entity<MultiBuffer>,
1153 project: Option<Entity<Project>>,
1154 show_excerpt_controls: bool,
1155 window: &mut Window,
1156 cx: &mut Context<Self>,
1157 ) -> Self {
1158 let style = window.text_style();
1159 let font_size = style.font_size.to_pixels(window.rem_size());
1160 let editor = cx.entity().downgrade();
1161 let fold_placeholder = FoldPlaceholder {
1162 constrain_width: true,
1163 render: Arc::new(move |fold_id, fold_range, cx| {
1164 let editor = editor.clone();
1165 div()
1166 .id(fold_id)
1167 .bg(cx.theme().colors().ghost_element_background)
1168 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1169 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1170 .rounded_sm()
1171 .size_full()
1172 .cursor_pointer()
1173 .child("⋯")
1174 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1175 .on_click(move |_, _window, cx| {
1176 editor
1177 .update(cx, |editor, cx| {
1178 editor.unfold_ranges(
1179 &[fold_range.start..fold_range.end],
1180 true,
1181 false,
1182 cx,
1183 );
1184 cx.stop_propagation();
1185 })
1186 .ok();
1187 })
1188 .into_any()
1189 }),
1190 merge_adjacent: true,
1191 ..Default::default()
1192 };
1193 let display_map = cx.new(|cx| {
1194 DisplayMap::new(
1195 buffer.clone(),
1196 style.font(),
1197 font_size,
1198 None,
1199 show_excerpt_controls,
1200 FILE_HEADER_HEIGHT,
1201 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1202 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1203 fold_placeholder,
1204 cx,
1205 )
1206 });
1207
1208 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1209
1210 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1211
1212 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1213 .then(|| language_settings::SoftWrap::None);
1214
1215 let mut project_subscriptions = Vec::new();
1216 if mode == EditorMode::Full {
1217 if let Some(project) = project.as_ref() {
1218 if buffer.read(cx).is_singleton() {
1219 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1220 cx.emit(EditorEvent::TitleChanged);
1221 }));
1222 }
1223 project_subscriptions.push(cx.subscribe_in(
1224 project,
1225 window,
1226 |editor, _, event, window, cx| {
1227 if let project::Event::RefreshInlayHints = event {
1228 editor
1229 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1230 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1231 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1232 let focus_handle = editor.focus_handle(cx);
1233 if focus_handle.is_focused(window) {
1234 let snapshot = buffer.read(cx).snapshot();
1235 for (range, snippet) in snippet_edits {
1236 let editor_range =
1237 language::range_from_lsp(*range).to_offset(&snapshot);
1238 editor
1239 .insert_snippet(
1240 &[editor_range],
1241 snippet.clone(),
1242 window,
1243 cx,
1244 )
1245 .ok();
1246 }
1247 }
1248 }
1249 }
1250 },
1251 ));
1252 if let Some(task_inventory) = project
1253 .read(cx)
1254 .task_store()
1255 .read(cx)
1256 .task_inventory()
1257 .cloned()
1258 {
1259 project_subscriptions.push(cx.observe_in(
1260 &task_inventory,
1261 window,
1262 |editor, _, window, cx| {
1263 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1264 },
1265 ));
1266 }
1267 }
1268 }
1269
1270 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1271
1272 let inlay_hint_settings =
1273 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1274 let focus_handle = cx.focus_handle();
1275 cx.on_focus(&focus_handle, window, Self::handle_focus)
1276 .detach();
1277 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1278 .detach();
1279 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1280 .detach();
1281 cx.on_blur(&focus_handle, window, Self::handle_blur)
1282 .detach();
1283
1284 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1285 Some(false)
1286 } else {
1287 None
1288 };
1289
1290 let mut code_action_providers = Vec::new();
1291 let mut load_uncommitted_diff = None;
1292 if let Some(project) = project.clone() {
1293 load_uncommitted_diff = Some(
1294 get_uncommitted_diff_for_buffer(
1295 &project,
1296 buffer.read(cx).all_buffers(),
1297 buffer.clone(),
1298 cx,
1299 )
1300 .shared(),
1301 );
1302 code_action_providers.push(Rc::new(project) as Rc<_>);
1303 }
1304
1305 let mut this = Self {
1306 focus_handle,
1307 show_cursor_when_unfocused: false,
1308 last_focused_descendant: None,
1309 buffer: buffer.clone(),
1310 display_map: display_map.clone(),
1311 selections,
1312 scroll_manager: ScrollManager::new(cx),
1313 columnar_selection_tail: None,
1314 add_selections_state: None,
1315 select_next_state: None,
1316 select_prev_state: None,
1317 selection_history: Default::default(),
1318 autoclose_regions: Default::default(),
1319 snippet_stack: Default::default(),
1320 select_larger_syntax_node_stack: Vec::new(),
1321 ime_transaction: Default::default(),
1322 active_diagnostics: None,
1323 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1324 inline_diagnostics_update: Task::ready(()),
1325 inline_diagnostics: Vec::new(),
1326 soft_wrap_mode_override,
1327 completion_provider: project.clone().map(|project| Box::new(project) as _),
1328 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1329 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1330 project,
1331 blink_manager: blink_manager.clone(),
1332 show_local_selections: true,
1333 show_scrollbars: true,
1334 mode,
1335 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1336 show_gutter: mode == EditorMode::Full,
1337 show_line_numbers: None,
1338 use_relative_line_numbers: None,
1339 show_git_diff_gutter: None,
1340 show_code_actions: None,
1341 show_runnables: None,
1342 show_wrap_guides: None,
1343 show_indent_guides,
1344 placeholder_text: None,
1345 highlight_order: 0,
1346 highlighted_rows: HashMap::default(),
1347 background_highlights: Default::default(),
1348 gutter_highlights: TreeMap::default(),
1349 scrollbar_marker_state: ScrollbarMarkerState::default(),
1350 active_indent_guides_state: ActiveIndentGuidesState::default(),
1351 nav_history: None,
1352 context_menu: RefCell::new(None),
1353 mouse_context_menu: None,
1354 completion_tasks: Default::default(),
1355 signature_help_state: SignatureHelpState::default(),
1356 auto_signature_help: None,
1357 find_all_references_task_sources: Vec::new(),
1358 next_completion_id: 0,
1359 next_inlay_id: 0,
1360 code_action_providers,
1361 available_code_actions: Default::default(),
1362 code_actions_task: Default::default(),
1363 selection_highlight_task: Default::default(),
1364 document_highlights_task: Default::default(),
1365 linked_editing_range_task: Default::default(),
1366 pending_rename: Default::default(),
1367 searchable: true,
1368 cursor_shape: EditorSettings::get_global(cx)
1369 .cursor_shape
1370 .unwrap_or_default(),
1371 current_line_highlight: None,
1372 autoindent_mode: Some(AutoindentMode::EachLine),
1373 collapse_matches: false,
1374 workspace: None,
1375 input_enabled: true,
1376 use_modal_editing: mode == EditorMode::Full,
1377 read_only: false,
1378 use_autoclose: true,
1379 use_auto_surround: true,
1380 auto_replace_emoji_shortcode: false,
1381 leader_peer_id: None,
1382 remote_id: None,
1383 hover_state: Default::default(),
1384 pending_mouse_down: None,
1385 hovered_link_state: Default::default(),
1386 edit_prediction_provider: None,
1387 active_inline_completion: None,
1388 stale_inline_completion_in_menu: None,
1389 edit_prediction_preview: EditPredictionPreview::Inactive,
1390 inline_diagnostics_enabled: mode == EditorMode::Full,
1391 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1392
1393 gutter_hovered: false,
1394 pixel_position_of_newest_cursor: None,
1395 last_bounds: None,
1396 last_position_map: None,
1397 expect_bounds_change: None,
1398 gutter_dimensions: GutterDimensions::default(),
1399 style: None,
1400 show_cursor_names: false,
1401 hovered_cursors: Default::default(),
1402 next_editor_action_id: EditorActionId::default(),
1403 editor_actions: Rc::default(),
1404 inline_completions_hidden_for_vim_mode: false,
1405 show_inline_completions_override: None,
1406 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1407 edit_prediction_settings: EditPredictionSettings::Disabled,
1408 edit_prediction_cursor_on_leading_whitespace: false,
1409 edit_prediction_requires_modifier_in_leading_space: true,
1410 custom_context_menu: None,
1411 show_git_blame_gutter: false,
1412 show_git_blame_inline: false,
1413 distinguish_unstaged_diff_hunks: false,
1414 show_selection_menu: None,
1415 show_git_blame_inline_delay_task: None,
1416 git_blame_inline_tooltip: None,
1417 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1418 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1419 .session
1420 .restore_unsaved_buffers,
1421 blame: None,
1422 blame_subscription: None,
1423 tasks: Default::default(),
1424 _subscriptions: vec![
1425 cx.observe(&buffer, Self::on_buffer_changed),
1426 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1427 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1428 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1429 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1430 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1431 cx.observe_window_activation(window, |editor, window, cx| {
1432 let active = window.is_window_active();
1433 editor.blink_manager.update(cx, |blink_manager, cx| {
1434 if active {
1435 blink_manager.enable(cx);
1436 } else {
1437 blink_manager.disable(cx);
1438 }
1439 });
1440 }),
1441 ],
1442 tasks_update_task: None,
1443 linked_edit_ranges: Default::default(),
1444 in_project_search: false,
1445 previous_search_ranges: None,
1446 breadcrumb_header: None,
1447 focused_block: None,
1448 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1449 addons: HashMap::default(),
1450 registered_buffers: HashMap::default(),
1451 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1452 selection_mark_mode: false,
1453 toggle_fold_multiple_buffers: Task::ready(()),
1454 serialize_selections: Task::ready(()),
1455 text_style_refinement: None,
1456 load_diff_task: load_uncommitted_diff,
1457 mouse_cursor_hidden: false,
1458 hide_mouse_while_typing: EditorSettings::get_global(cx)
1459 .hide_mouse_while_typing
1460 .unwrap_or(true),
1461 };
1462 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1463 this._subscriptions.extend(project_subscriptions);
1464
1465 this.end_selection(window, cx);
1466 this.scroll_manager.show_scrollbar(window, cx);
1467
1468 if mode == EditorMode::Full {
1469 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1470 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1471
1472 if this.git_blame_inline_enabled {
1473 this.git_blame_inline_enabled = true;
1474 this.start_git_blame_inline(false, window, cx);
1475 }
1476
1477 if let Some(buffer) = buffer.read(cx).as_singleton() {
1478 if let Some(project) = this.project.as_ref() {
1479 let handle = project.update(cx, |project, cx| {
1480 project.register_buffer_with_language_servers(&buffer, cx)
1481 });
1482 this.registered_buffers
1483 .insert(buffer.read(cx).remote_id(), handle);
1484 }
1485 }
1486 }
1487
1488 this.report_editor_event("Editor Opened", None, cx);
1489 this
1490 }
1491
1492 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1493 self.mouse_context_menu
1494 .as_ref()
1495 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1496 }
1497
1498 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1499 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1500 }
1501
1502 fn key_context_internal(
1503 &self,
1504 has_active_edit_prediction: bool,
1505 window: &Window,
1506 cx: &App,
1507 ) -> KeyContext {
1508 let mut key_context = KeyContext::new_with_defaults();
1509 key_context.add("Editor");
1510 let mode = match self.mode {
1511 EditorMode::SingleLine { .. } => "single_line",
1512 EditorMode::AutoHeight { .. } => "auto_height",
1513 EditorMode::Full => "full",
1514 };
1515
1516 if EditorSettings::jupyter_enabled(cx) {
1517 key_context.add("jupyter");
1518 }
1519
1520 key_context.set("mode", mode);
1521 if self.pending_rename.is_some() {
1522 key_context.add("renaming");
1523 }
1524
1525 match self.context_menu.borrow().as_ref() {
1526 Some(CodeContextMenu::Completions(_)) => {
1527 key_context.add("menu");
1528 key_context.add("showing_completions");
1529 }
1530 Some(CodeContextMenu::CodeActions(_)) => {
1531 key_context.add("menu");
1532 key_context.add("showing_code_actions")
1533 }
1534 None => {}
1535 }
1536
1537 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1538 if !self.focus_handle(cx).contains_focused(window, cx)
1539 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1540 {
1541 for addon in self.addons.values() {
1542 addon.extend_key_context(&mut key_context, cx)
1543 }
1544 }
1545
1546 if let Some(extension) = self
1547 .buffer
1548 .read(cx)
1549 .as_singleton()
1550 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1551 {
1552 key_context.set("extension", extension.to_string());
1553 }
1554
1555 if has_active_edit_prediction {
1556 if self.edit_prediction_in_conflict() {
1557 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1558 } else {
1559 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1560 key_context.add("copilot_suggestion");
1561 }
1562 }
1563
1564 if self.selection_mark_mode {
1565 key_context.add("selection_mode");
1566 }
1567
1568 key_context
1569 }
1570
1571 pub fn edit_prediction_in_conflict(&self) -> bool {
1572 if !self.show_edit_predictions_in_menu() {
1573 return false;
1574 }
1575
1576 let showing_completions = self
1577 .context_menu
1578 .borrow()
1579 .as_ref()
1580 .map_or(false, |context| {
1581 matches!(context, CodeContextMenu::Completions(_))
1582 });
1583
1584 showing_completions
1585 || self.edit_prediction_requires_modifier()
1586 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1587 // bindings to insert tab characters.
1588 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1589 }
1590
1591 pub fn accept_edit_prediction_keybind(
1592 &self,
1593 window: &Window,
1594 cx: &App,
1595 ) -> AcceptEditPredictionBinding {
1596 let key_context = self.key_context_internal(true, window, cx);
1597 let in_conflict = self.edit_prediction_in_conflict();
1598
1599 AcceptEditPredictionBinding(
1600 window
1601 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1602 .into_iter()
1603 .filter(|binding| {
1604 !in_conflict
1605 || binding
1606 .keystrokes()
1607 .first()
1608 .map_or(false, |keystroke| keystroke.modifiers.modified())
1609 })
1610 .rev()
1611 .min_by_key(|binding| {
1612 binding
1613 .keystrokes()
1614 .first()
1615 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1616 }),
1617 )
1618 }
1619
1620 pub fn new_file(
1621 workspace: &mut Workspace,
1622 _: &workspace::NewFile,
1623 window: &mut Window,
1624 cx: &mut Context<Workspace>,
1625 ) {
1626 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1627 "Failed to create buffer",
1628 window,
1629 cx,
1630 |e, _, _| match e.error_code() {
1631 ErrorCode::RemoteUpgradeRequired => Some(format!(
1632 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1633 e.error_tag("required").unwrap_or("the latest version")
1634 )),
1635 _ => None,
1636 },
1637 );
1638 }
1639
1640 pub fn new_in_workspace(
1641 workspace: &mut Workspace,
1642 window: &mut Window,
1643 cx: &mut Context<Workspace>,
1644 ) -> Task<Result<Entity<Editor>>> {
1645 let project = workspace.project().clone();
1646 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1647
1648 cx.spawn_in(window, |workspace, mut cx| async move {
1649 let buffer = create.await?;
1650 workspace.update_in(&mut cx, |workspace, window, cx| {
1651 let editor =
1652 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1653 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1654 editor
1655 })
1656 })
1657 }
1658
1659 fn new_file_vertical(
1660 workspace: &mut Workspace,
1661 _: &workspace::NewFileSplitVertical,
1662 window: &mut Window,
1663 cx: &mut Context<Workspace>,
1664 ) {
1665 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1666 }
1667
1668 fn new_file_horizontal(
1669 workspace: &mut Workspace,
1670 _: &workspace::NewFileSplitHorizontal,
1671 window: &mut Window,
1672 cx: &mut Context<Workspace>,
1673 ) {
1674 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1675 }
1676
1677 fn new_file_in_direction(
1678 workspace: &mut Workspace,
1679 direction: SplitDirection,
1680 window: &mut Window,
1681 cx: &mut Context<Workspace>,
1682 ) {
1683 let project = workspace.project().clone();
1684 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1685
1686 cx.spawn_in(window, |workspace, mut cx| async move {
1687 let buffer = create.await?;
1688 workspace.update_in(&mut cx, move |workspace, window, cx| {
1689 workspace.split_item(
1690 direction,
1691 Box::new(
1692 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1693 ),
1694 window,
1695 cx,
1696 )
1697 })?;
1698 anyhow::Ok(())
1699 })
1700 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1701 match e.error_code() {
1702 ErrorCode::RemoteUpgradeRequired => Some(format!(
1703 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1704 e.error_tag("required").unwrap_or("the latest version")
1705 )),
1706 _ => None,
1707 }
1708 });
1709 }
1710
1711 pub fn leader_peer_id(&self) -> Option<PeerId> {
1712 self.leader_peer_id
1713 }
1714
1715 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1716 &self.buffer
1717 }
1718
1719 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1720 self.workspace.as_ref()?.0.upgrade()
1721 }
1722
1723 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1724 self.buffer().read(cx).title(cx)
1725 }
1726
1727 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1728 let git_blame_gutter_max_author_length = self
1729 .render_git_blame_gutter(cx)
1730 .then(|| {
1731 if let Some(blame) = self.blame.as_ref() {
1732 let max_author_length =
1733 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1734 Some(max_author_length)
1735 } else {
1736 None
1737 }
1738 })
1739 .flatten();
1740
1741 EditorSnapshot {
1742 mode: self.mode,
1743 show_gutter: self.show_gutter,
1744 show_line_numbers: self.show_line_numbers,
1745 show_git_diff_gutter: self.show_git_diff_gutter,
1746 show_code_actions: self.show_code_actions,
1747 show_runnables: self.show_runnables,
1748 git_blame_gutter_max_author_length,
1749 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1750 scroll_anchor: self.scroll_manager.anchor(),
1751 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1752 placeholder_text: self.placeholder_text.clone(),
1753 is_focused: self.focus_handle.is_focused(window),
1754 current_line_highlight: self
1755 .current_line_highlight
1756 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1757 gutter_hovered: self.gutter_hovered,
1758 }
1759 }
1760
1761 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1762 self.buffer.read(cx).language_at(point, cx)
1763 }
1764
1765 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1766 self.buffer.read(cx).read(cx).file_at(point).cloned()
1767 }
1768
1769 pub fn active_excerpt(
1770 &self,
1771 cx: &App,
1772 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1773 self.buffer
1774 .read(cx)
1775 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1776 }
1777
1778 pub fn mode(&self) -> EditorMode {
1779 self.mode
1780 }
1781
1782 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1783 self.collaboration_hub.as_deref()
1784 }
1785
1786 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1787 self.collaboration_hub = Some(hub);
1788 }
1789
1790 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1791 self.in_project_search = in_project_search;
1792 }
1793
1794 pub fn set_custom_context_menu(
1795 &mut self,
1796 f: impl 'static
1797 + Fn(
1798 &mut Self,
1799 DisplayPoint,
1800 &mut Window,
1801 &mut Context<Self>,
1802 ) -> Option<Entity<ui::ContextMenu>>,
1803 ) {
1804 self.custom_context_menu = Some(Box::new(f))
1805 }
1806
1807 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1808 self.completion_provider = provider;
1809 }
1810
1811 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1812 self.semantics_provider.clone()
1813 }
1814
1815 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1816 self.semantics_provider = provider;
1817 }
1818
1819 pub fn set_edit_prediction_provider<T>(
1820 &mut self,
1821 provider: Option<Entity<T>>,
1822 window: &mut Window,
1823 cx: &mut Context<Self>,
1824 ) where
1825 T: EditPredictionProvider,
1826 {
1827 self.edit_prediction_provider =
1828 provider.map(|provider| RegisteredInlineCompletionProvider {
1829 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1830 if this.focus_handle.is_focused(window) {
1831 this.update_visible_inline_completion(window, cx);
1832 }
1833 }),
1834 provider: Arc::new(provider),
1835 });
1836 self.refresh_inline_completion(false, false, window, cx);
1837 }
1838
1839 pub fn placeholder_text(&self) -> Option<&str> {
1840 self.placeholder_text.as_deref()
1841 }
1842
1843 pub fn set_placeholder_text(
1844 &mut self,
1845 placeholder_text: impl Into<Arc<str>>,
1846 cx: &mut Context<Self>,
1847 ) {
1848 let placeholder_text = Some(placeholder_text.into());
1849 if self.placeholder_text != placeholder_text {
1850 self.placeholder_text = placeholder_text;
1851 cx.notify();
1852 }
1853 }
1854
1855 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1856 self.cursor_shape = cursor_shape;
1857
1858 // Disrupt blink for immediate user feedback that the cursor shape has changed
1859 self.blink_manager.update(cx, BlinkManager::show_cursor);
1860
1861 cx.notify();
1862 }
1863
1864 pub fn set_current_line_highlight(
1865 &mut self,
1866 current_line_highlight: Option<CurrentLineHighlight>,
1867 ) {
1868 self.current_line_highlight = current_line_highlight;
1869 }
1870
1871 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1872 self.collapse_matches = collapse_matches;
1873 }
1874
1875 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1876 let buffers = self.buffer.read(cx).all_buffers();
1877 let Some(project) = self.project.as_ref() else {
1878 return;
1879 };
1880 project.update(cx, |project, cx| {
1881 for buffer in buffers {
1882 self.registered_buffers
1883 .entry(buffer.read(cx).remote_id())
1884 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1885 }
1886 })
1887 }
1888
1889 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1890 if self.collapse_matches {
1891 return range.start..range.start;
1892 }
1893 range.clone()
1894 }
1895
1896 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1897 if self.display_map.read(cx).clip_at_line_ends != clip {
1898 self.display_map
1899 .update(cx, |map, _| map.clip_at_line_ends = clip);
1900 }
1901 }
1902
1903 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1904 self.input_enabled = input_enabled;
1905 }
1906
1907 pub fn set_inline_completions_hidden_for_vim_mode(
1908 &mut self,
1909 hidden: bool,
1910 window: &mut Window,
1911 cx: &mut Context<Self>,
1912 ) {
1913 if hidden != self.inline_completions_hidden_for_vim_mode {
1914 self.inline_completions_hidden_for_vim_mode = hidden;
1915 if hidden {
1916 self.update_visible_inline_completion(window, cx);
1917 } else {
1918 self.refresh_inline_completion(true, false, window, cx);
1919 }
1920 }
1921 }
1922
1923 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1924 self.menu_inline_completions_policy = value;
1925 }
1926
1927 pub fn set_autoindent(&mut self, autoindent: bool) {
1928 if autoindent {
1929 self.autoindent_mode = Some(AutoindentMode::EachLine);
1930 } else {
1931 self.autoindent_mode = None;
1932 }
1933 }
1934
1935 pub fn read_only(&self, cx: &App) -> bool {
1936 self.read_only || self.buffer.read(cx).read_only()
1937 }
1938
1939 pub fn set_read_only(&mut self, read_only: bool) {
1940 self.read_only = read_only;
1941 }
1942
1943 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1944 self.use_autoclose = autoclose;
1945 }
1946
1947 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1948 self.use_auto_surround = auto_surround;
1949 }
1950
1951 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1952 self.auto_replace_emoji_shortcode = auto_replace;
1953 }
1954
1955 pub fn toggle_inline_completions(
1956 &mut self,
1957 _: &ToggleEditPrediction,
1958 window: &mut Window,
1959 cx: &mut Context<Self>,
1960 ) {
1961 if self.show_inline_completions_override.is_some() {
1962 self.set_show_edit_predictions(None, window, cx);
1963 } else {
1964 let show_edit_predictions = !self.edit_predictions_enabled();
1965 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1966 }
1967 }
1968
1969 pub fn set_show_edit_predictions(
1970 &mut self,
1971 show_edit_predictions: Option<bool>,
1972 window: &mut Window,
1973 cx: &mut Context<Self>,
1974 ) {
1975 self.show_inline_completions_override = show_edit_predictions;
1976
1977 if let Some(false) = show_edit_predictions {
1978 self.discard_inline_completion(false, cx);
1979 } else {
1980 self.refresh_inline_completion(false, true, window, cx);
1981 }
1982 }
1983
1984 fn inline_completions_disabled_in_scope(
1985 &self,
1986 buffer: &Entity<Buffer>,
1987 buffer_position: language::Anchor,
1988 cx: &App,
1989 ) -> bool {
1990 let snapshot = buffer.read(cx).snapshot();
1991 let settings = snapshot.settings_at(buffer_position, cx);
1992
1993 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1994 return false;
1995 };
1996
1997 scope.override_name().map_or(false, |scope_name| {
1998 settings
1999 .edit_predictions_disabled_in
2000 .iter()
2001 .any(|s| s == scope_name)
2002 })
2003 }
2004
2005 pub fn set_use_modal_editing(&mut self, to: bool) {
2006 self.use_modal_editing = to;
2007 }
2008
2009 pub fn use_modal_editing(&self) -> bool {
2010 self.use_modal_editing
2011 }
2012
2013 fn selections_did_change(
2014 &mut self,
2015 local: bool,
2016 old_cursor_position: &Anchor,
2017 show_completions: bool,
2018 window: &mut Window,
2019 cx: &mut Context<Self>,
2020 ) {
2021 window.invalidate_character_coordinates();
2022
2023 // Copy selections to primary selection buffer
2024 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2025 if local {
2026 let selections = self.selections.all::<usize>(cx);
2027 let buffer_handle = self.buffer.read(cx).read(cx);
2028
2029 let mut text = String::new();
2030 for (index, selection) in selections.iter().enumerate() {
2031 let text_for_selection = buffer_handle
2032 .text_for_range(selection.start..selection.end)
2033 .collect::<String>();
2034
2035 text.push_str(&text_for_selection);
2036 if index != selections.len() - 1 {
2037 text.push('\n');
2038 }
2039 }
2040
2041 if !text.is_empty() {
2042 cx.write_to_primary(ClipboardItem::new_string(text));
2043 }
2044 }
2045
2046 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2047 self.buffer.update(cx, |buffer, cx| {
2048 buffer.set_active_selections(
2049 &self.selections.disjoint_anchors(),
2050 self.selections.line_mode,
2051 self.cursor_shape,
2052 cx,
2053 )
2054 });
2055 }
2056 let display_map = self
2057 .display_map
2058 .update(cx, |display_map, cx| display_map.snapshot(cx));
2059 let buffer = &display_map.buffer_snapshot;
2060 self.add_selections_state = None;
2061 self.select_next_state = None;
2062 self.select_prev_state = None;
2063 self.select_larger_syntax_node_stack.clear();
2064 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2065 self.snippet_stack
2066 .invalidate(&self.selections.disjoint_anchors(), buffer);
2067 self.take_rename(false, window, cx);
2068
2069 let new_cursor_position = self.selections.newest_anchor().head();
2070
2071 self.push_to_nav_history(
2072 *old_cursor_position,
2073 Some(new_cursor_position.to_point(buffer)),
2074 cx,
2075 );
2076
2077 if local {
2078 let new_cursor_position = self.selections.newest_anchor().head();
2079 let mut context_menu = self.context_menu.borrow_mut();
2080 let completion_menu = match context_menu.as_ref() {
2081 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2082 _ => {
2083 *context_menu = None;
2084 None
2085 }
2086 };
2087 if let Some(buffer_id) = new_cursor_position.buffer_id {
2088 if !self.registered_buffers.contains_key(&buffer_id) {
2089 if let Some(project) = self.project.as_ref() {
2090 project.update(cx, |project, cx| {
2091 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2092 return;
2093 };
2094 self.registered_buffers.insert(
2095 buffer_id,
2096 project.register_buffer_with_language_servers(&buffer, cx),
2097 );
2098 })
2099 }
2100 }
2101 }
2102
2103 if let Some(completion_menu) = completion_menu {
2104 let cursor_position = new_cursor_position.to_offset(buffer);
2105 let (word_range, kind) =
2106 buffer.surrounding_word(completion_menu.initial_position, true);
2107 if kind == Some(CharKind::Word)
2108 && word_range.to_inclusive().contains(&cursor_position)
2109 {
2110 let mut completion_menu = completion_menu.clone();
2111 drop(context_menu);
2112
2113 let query = Self::completion_query(buffer, cursor_position);
2114 cx.spawn(move |this, mut cx| async move {
2115 completion_menu
2116 .filter(query.as_deref(), cx.background_executor().clone())
2117 .await;
2118
2119 this.update(&mut cx, |this, cx| {
2120 let mut context_menu = this.context_menu.borrow_mut();
2121 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2122 else {
2123 return;
2124 };
2125
2126 if menu.id > completion_menu.id {
2127 return;
2128 }
2129
2130 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2131 drop(context_menu);
2132 cx.notify();
2133 })
2134 })
2135 .detach();
2136
2137 if show_completions {
2138 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2139 }
2140 } else {
2141 drop(context_menu);
2142 self.hide_context_menu(window, cx);
2143 }
2144 } else {
2145 drop(context_menu);
2146 }
2147
2148 hide_hover(self, cx);
2149
2150 if old_cursor_position.to_display_point(&display_map).row()
2151 != new_cursor_position.to_display_point(&display_map).row()
2152 {
2153 self.available_code_actions.take();
2154 }
2155 self.refresh_code_actions(window, cx);
2156 self.refresh_document_highlights(cx);
2157 self.refresh_selected_text_highlights(window, cx);
2158 refresh_matching_bracket_highlights(self, window, cx);
2159 self.update_visible_inline_completion(window, cx);
2160 self.edit_prediction_requires_modifier_in_leading_space = true;
2161 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2162 if self.git_blame_inline_enabled {
2163 self.start_inline_blame_timer(window, cx);
2164 }
2165 }
2166
2167 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2168 cx.emit(EditorEvent::SelectionsChanged { local });
2169
2170 let selections = &self.selections.disjoint;
2171 if selections.len() == 1 {
2172 cx.emit(SearchEvent::ActiveMatchChanged)
2173 }
2174 if local
2175 && self.is_singleton(cx)
2176 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2177 {
2178 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2179 let background_executor = cx.background_executor().clone();
2180 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2181 let snapshot = self.buffer().read(cx).snapshot(cx);
2182 let selections = selections.clone();
2183 self.serialize_selections = cx.background_spawn(async move {
2184 background_executor.timer(Duration::from_millis(100)).await;
2185 let selections = selections
2186 .iter()
2187 .map(|selection| {
2188 (
2189 selection.start.to_offset(&snapshot),
2190 selection.end.to_offset(&snapshot),
2191 )
2192 })
2193 .collect();
2194 DB.save_editor_selections(editor_id, workspace_id, selections)
2195 .await
2196 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2197 .log_err();
2198 });
2199 }
2200 }
2201
2202 cx.notify();
2203 }
2204
2205 pub fn change_selections<R>(
2206 &mut self,
2207 autoscroll: Option<Autoscroll>,
2208 window: &mut Window,
2209 cx: &mut Context<Self>,
2210 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2211 ) -> R {
2212 self.change_selections_inner(autoscroll, true, window, cx, change)
2213 }
2214
2215 fn change_selections_inner<R>(
2216 &mut self,
2217 autoscroll: Option<Autoscroll>,
2218 request_completions: bool,
2219 window: &mut Window,
2220 cx: &mut Context<Self>,
2221 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2222 ) -> R {
2223 let old_cursor_position = self.selections.newest_anchor().head();
2224 self.push_to_selection_history();
2225
2226 let (changed, result) = self.selections.change_with(cx, change);
2227
2228 if changed {
2229 if let Some(autoscroll) = autoscroll {
2230 self.request_autoscroll(autoscroll, cx);
2231 }
2232 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2233
2234 if self.should_open_signature_help_automatically(
2235 &old_cursor_position,
2236 self.signature_help_state.backspace_pressed(),
2237 cx,
2238 ) {
2239 self.show_signature_help(&ShowSignatureHelp, window, cx);
2240 }
2241 self.signature_help_state.set_backspace_pressed(false);
2242 }
2243
2244 result
2245 }
2246
2247 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2248 where
2249 I: IntoIterator<Item = (Range<S>, T)>,
2250 S: ToOffset,
2251 T: Into<Arc<str>>,
2252 {
2253 if self.read_only(cx) {
2254 return;
2255 }
2256
2257 self.buffer
2258 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2259 }
2260
2261 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2262 where
2263 I: IntoIterator<Item = (Range<S>, T)>,
2264 S: ToOffset,
2265 T: Into<Arc<str>>,
2266 {
2267 if self.read_only(cx) {
2268 return;
2269 }
2270
2271 self.buffer.update(cx, |buffer, cx| {
2272 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2273 });
2274 }
2275
2276 pub fn edit_with_block_indent<I, S, T>(
2277 &mut self,
2278 edits: I,
2279 original_start_columns: Vec<u32>,
2280 cx: &mut Context<Self>,
2281 ) where
2282 I: IntoIterator<Item = (Range<S>, T)>,
2283 S: ToOffset,
2284 T: Into<Arc<str>>,
2285 {
2286 if self.read_only(cx) {
2287 return;
2288 }
2289
2290 self.buffer.update(cx, |buffer, cx| {
2291 buffer.edit(
2292 edits,
2293 Some(AutoindentMode::Block {
2294 original_start_columns,
2295 }),
2296 cx,
2297 )
2298 });
2299 }
2300
2301 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2302 self.hide_context_menu(window, cx);
2303
2304 match phase {
2305 SelectPhase::Begin {
2306 position,
2307 add,
2308 click_count,
2309 } => self.begin_selection(position, add, click_count, window, cx),
2310 SelectPhase::BeginColumnar {
2311 position,
2312 goal_column,
2313 reset,
2314 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2315 SelectPhase::Extend {
2316 position,
2317 click_count,
2318 } => self.extend_selection(position, click_count, window, cx),
2319 SelectPhase::Update {
2320 position,
2321 goal_column,
2322 scroll_delta,
2323 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2324 SelectPhase::End => self.end_selection(window, cx),
2325 }
2326 }
2327
2328 fn extend_selection(
2329 &mut self,
2330 position: DisplayPoint,
2331 click_count: usize,
2332 window: &mut Window,
2333 cx: &mut Context<Self>,
2334 ) {
2335 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2336 let tail = self.selections.newest::<usize>(cx).tail();
2337 self.begin_selection(position, false, click_count, window, cx);
2338
2339 let position = position.to_offset(&display_map, Bias::Left);
2340 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2341
2342 let mut pending_selection = self
2343 .selections
2344 .pending_anchor()
2345 .expect("extend_selection not called with pending selection");
2346 if position >= tail {
2347 pending_selection.start = tail_anchor;
2348 } else {
2349 pending_selection.end = tail_anchor;
2350 pending_selection.reversed = true;
2351 }
2352
2353 let mut pending_mode = self.selections.pending_mode().unwrap();
2354 match &mut pending_mode {
2355 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2356 _ => {}
2357 }
2358
2359 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2360 s.set_pending(pending_selection, pending_mode)
2361 });
2362 }
2363
2364 fn begin_selection(
2365 &mut self,
2366 position: DisplayPoint,
2367 add: bool,
2368 click_count: usize,
2369 window: &mut Window,
2370 cx: &mut Context<Self>,
2371 ) {
2372 if !self.focus_handle.is_focused(window) {
2373 self.last_focused_descendant = None;
2374 window.focus(&self.focus_handle);
2375 }
2376
2377 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2378 let buffer = &display_map.buffer_snapshot;
2379 let newest_selection = self.selections.newest_anchor().clone();
2380 let position = display_map.clip_point(position, Bias::Left);
2381
2382 let start;
2383 let end;
2384 let mode;
2385 let mut auto_scroll;
2386 match click_count {
2387 1 => {
2388 start = buffer.anchor_before(position.to_point(&display_map));
2389 end = start;
2390 mode = SelectMode::Character;
2391 auto_scroll = true;
2392 }
2393 2 => {
2394 let range = movement::surrounding_word(&display_map, position);
2395 start = buffer.anchor_before(range.start.to_point(&display_map));
2396 end = buffer.anchor_before(range.end.to_point(&display_map));
2397 mode = SelectMode::Word(start..end);
2398 auto_scroll = true;
2399 }
2400 3 => {
2401 let position = display_map
2402 .clip_point(position, Bias::Left)
2403 .to_point(&display_map);
2404 let line_start = display_map.prev_line_boundary(position).0;
2405 let next_line_start = buffer.clip_point(
2406 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2407 Bias::Left,
2408 );
2409 start = buffer.anchor_before(line_start);
2410 end = buffer.anchor_before(next_line_start);
2411 mode = SelectMode::Line(start..end);
2412 auto_scroll = true;
2413 }
2414 _ => {
2415 start = buffer.anchor_before(0);
2416 end = buffer.anchor_before(buffer.len());
2417 mode = SelectMode::All;
2418 auto_scroll = false;
2419 }
2420 }
2421 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2422
2423 let point_to_delete: Option<usize> = {
2424 let selected_points: Vec<Selection<Point>> =
2425 self.selections.disjoint_in_range(start..end, cx);
2426
2427 if !add || click_count > 1 {
2428 None
2429 } else if !selected_points.is_empty() {
2430 Some(selected_points[0].id)
2431 } else {
2432 let clicked_point_already_selected =
2433 self.selections.disjoint.iter().find(|selection| {
2434 selection.start.to_point(buffer) == start.to_point(buffer)
2435 || selection.end.to_point(buffer) == end.to_point(buffer)
2436 });
2437
2438 clicked_point_already_selected.map(|selection| selection.id)
2439 }
2440 };
2441
2442 let selections_count = self.selections.count();
2443
2444 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2445 if let Some(point_to_delete) = point_to_delete {
2446 s.delete(point_to_delete);
2447
2448 if selections_count == 1 {
2449 s.set_pending_anchor_range(start..end, mode);
2450 }
2451 } else {
2452 if !add {
2453 s.clear_disjoint();
2454 } else if click_count > 1 {
2455 s.delete(newest_selection.id)
2456 }
2457
2458 s.set_pending_anchor_range(start..end, mode);
2459 }
2460 });
2461 }
2462
2463 fn begin_columnar_selection(
2464 &mut self,
2465 position: DisplayPoint,
2466 goal_column: u32,
2467 reset: bool,
2468 window: &mut Window,
2469 cx: &mut Context<Self>,
2470 ) {
2471 if !self.focus_handle.is_focused(window) {
2472 self.last_focused_descendant = None;
2473 window.focus(&self.focus_handle);
2474 }
2475
2476 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2477
2478 if reset {
2479 let pointer_position = display_map
2480 .buffer_snapshot
2481 .anchor_before(position.to_point(&display_map));
2482
2483 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2484 s.clear_disjoint();
2485 s.set_pending_anchor_range(
2486 pointer_position..pointer_position,
2487 SelectMode::Character,
2488 );
2489 });
2490 }
2491
2492 let tail = self.selections.newest::<Point>(cx).tail();
2493 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2494
2495 if !reset {
2496 self.select_columns(
2497 tail.to_display_point(&display_map),
2498 position,
2499 goal_column,
2500 &display_map,
2501 window,
2502 cx,
2503 );
2504 }
2505 }
2506
2507 fn update_selection(
2508 &mut self,
2509 position: DisplayPoint,
2510 goal_column: u32,
2511 scroll_delta: gpui::Point<f32>,
2512 window: &mut Window,
2513 cx: &mut Context<Self>,
2514 ) {
2515 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2516
2517 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2518 let tail = tail.to_display_point(&display_map);
2519 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2520 } else if let Some(mut pending) = self.selections.pending_anchor() {
2521 let buffer = self.buffer.read(cx).snapshot(cx);
2522 let head;
2523 let tail;
2524 let mode = self.selections.pending_mode().unwrap();
2525 match &mode {
2526 SelectMode::Character => {
2527 head = position.to_point(&display_map);
2528 tail = pending.tail().to_point(&buffer);
2529 }
2530 SelectMode::Word(original_range) => {
2531 let original_display_range = original_range.start.to_display_point(&display_map)
2532 ..original_range.end.to_display_point(&display_map);
2533 let original_buffer_range = original_display_range.start.to_point(&display_map)
2534 ..original_display_range.end.to_point(&display_map);
2535 if movement::is_inside_word(&display_map, position)
2536 || original_display_range.contains(&position)
2537 {
2538 let word_range = movement::surrounding_word(&display_map, position);
2539 if word_range.start < original_display_range.start {
2540 head = word_range.start.to_point(&display_map);
2541 } else {
2542 head = word_range.end.to_point(&display_map);
2543 }
2544 } else {
2545 head = position.to_point(&display_map);
2546 }
2547
2548 if head <= original_buffer_range.start {
2549 tail = original_buffer_range.end;
2550 } else {
2551 tail = original_buffer_range.start;
2552 }
2553 }
2554 SelectMode::Line(original_range) => {
2555 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2556
2557 let position = display_map
2558 .clip_point(position, Bias::Left)
2559 .to_point(&display_map);
2560 let line_start = display_map.prev_line_boundary(position).0;
2561 let next_line_start = buffer.clip_point(
2562 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2563 Bias::Left,
2564 );
2565
2566 if line_start < original_range.start {
2567 head = line_start
2568 } else {
2569 head = next_line_start
2570 }
2571
2572 if head <= original_range.start {
2573 tail = original_range.end;
2574 } else {
2575 tail = original_range.start;
2576 }
2577 }
2578 SelectMode::All => {
2579 return;
2580 }
2581 };
2582
2583 if head < tail {
2584 pending.start = buffer.anchor_before(head);
2585 pending.end = buffer.anchor_before(tail);
2586 pending.reversed = true;
2587 } else {
2588 pending.start = buffer.anchor_before(tail);
2589 pending.end = buffer.anchor_before(head);
2590 pending.reversed = false;
2591 }
2592
2593 self.change_selections(None, window, cx, |s| {
2594 s.set_pending(pending, mode);
2595 });
2596 } else {
2597 log::error!("update_selection dispatched with no pending selection");
2598 return;
2599 }
2600
2601 self.apply_scroll_delta(scroll_delta, window, cx);
2602 cx.notify();
2603 }
2604
2605 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2606 self.columnar_selection_tail.take();
2607 if self.selections.pending_anchor().is_some() {
2608 let selections = self.selections.all::<usize>(cx);
2609 self.change_selections(None, window, cx, |s| {
2610 s.select(selections);
2611 s.clear_pending();
2612 });
2613 }
2614 }
2615
2616 fn select_columns(
2617 &mut self,
2618 tail: DisplayPoint,
2619 head: DisplayPoint,
2620 goal_column: u32,
2621 display_map: &DisplaySnapshot,
2622 window: &mut Window,
2623 cx: &mut Context<Self>,
2624 ) {
2625 let start_row = cmp::min(tail.row(), head.row());
2626 let end_row = cmp::max(tail.row(), head.row());
2627 let start_column = cmp::min(tail.column(), goal_column);
2628 let end_column = cmp::max(tail.column(), goal_column);
2629 let reversed = start_column < tail.column();
2630
2631 let selection_ranges = (start_row.0..=end_row.0)
2632 .map(DisplayRow)
2633 .filter_map(|row| {
2634 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2635 let start = display_map
2636 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2637 .to_point(display_map);
2638 let end = display_map
2639 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2640 .to_point(display_map);
2641 if reversed {
2642 Some(end..start)
2643 } else {
2644 Some(start..end)
2645 }
2646 } else {
2647 None
2648 }
2649 })
2650 .collect::<Vec<_>>();
2651
2652 self.change_selections(None, window, cx, |s| {
2653 s.select_ranges(selection_ranges);
2654 });
2655 cx.notify();
2656 }
2657
2658 pub fn has_pending_nonempty_selection(&self) -> bool {
2659 let pending_nonempty_selection = match self.selections.pending_anchor() {
2660 Some(Selection { start, end, .. }) => start != end,
2661 None => false,
2662 };
2663
2664 pending_nonempty_selection
2665 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2666 }
2667
2668 pub fn has_pending_selection(&self) -> bool {
2669 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2670 }
2671
2672 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2673 self.selection_mark_mode = false;
2674
2675 if self.clear_expanded_diff_hunks(cx) {
2676 cx.notify();
2677 return;
2678 }
2679 if self.dismiss_menus_and_popups(true, window, cx) {
2680 return;
2681 }
2682
2683 if self.mode == EditorMode::Full
2684 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2685 {
2686 return;
2687 }
2688
2689 cx.propagate();
2690 }
2691
2692 pub fn dismiss_menus_and_popups(
2693 &mut self,
2694 is_user_requested: bool,
2695 window: &mut Window,
2696 cx: &mut Context<Self>,
2697 ) -> bool {
2698 if self.take_rename(false, window, cx).is_some() {
2699 return true;
2700 }
2701
2702 if hide_hover(self, cx) {
2703 return true;
2704 }
2705
2706 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2707 return true;
2708 }
2709
2710 if self.hide_context_menu(window, cx).is_some() {
2711 return true;
2712 }
2713
2714 if self.mouse_context_menu.take().is_some() {
2715 return true;
2716 }
2717
2718 if is_user_requested && self.discard_inline_completion(true, cx) {
2719 return true;
2720 }
2721
2722 if self.snippet_stack.pop().is_some() {
2723 return true;
2724 }
2725
2726 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2727 self.dismiss_diagnostics(cx);
2728 return true;
2729 }
2730
2731 false
2732 }
2733
2734 fn linked_editing_ranges_for(
2735 &self,
2736 selection: Range<text::Anchor>,
2737 cx: &App,
2738 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2739 if self.linked_edit_ranges.is_empty() {
2740 return None;
2741 }
2742 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2743 selection.end.buffer_id.and_then(|end_buffer_id| {
2744 if selection.start.buffer_id != Some(end_buffer_id) {
2745 return None;
2746 }
2747 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2748 let snapshot = buffer.read(cx).snapshot();
2749 self.linked_edit_ranges
2750 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2751 .map(|ranges| (ranges, snapshot, buffer))
2752 })?;
2753 use text::ToOffset as TO;
2754 // find offset from the start of current range to current cursor position
2755 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2756
2757 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2758 let start_difference = start_offset - start_byte_offset;
2759 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2760 let end_difference = end_offset - start_byte_offset;
2761 // Current range has associated linked ranges.
2762 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2763 for range in linked_ranges.iter() {
2764 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2765 let end_offset = start_offset + end_difference;
2766 let start_offset = start_offset + start_difference;
2767 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2768 continue;
2769 }
2770 if self.selections.disjoint_anchor_ranges().any(|s| {
2771 if s.start.buffer_id != selection.start.buffer_id
2772 || s.end.buffer_id != selection.end.buffer_id
2773 {
2774 return false;
2775 }
2776 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2777 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2778 }) {
2779 continue;
2780 }
2781 let start = buffer_snapshot.anchor_after(start_offset);
2782 let end = buffer_snapshot.anchor_after(end_offset);
2783 linked_edits
2784 .entry(buffer.clone())
2785 .or_default()
2786 .push(start..end);
2787 }
2788 Some(linked_edits)
2789 }
2790
2791 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2792 let text: Arc<str> = text.into();
2793
2794 if self.read_only(cx) {
2795 return;
2796 }
2797
2798 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
2799
2800 let selections = self.selections.all_adjusted(cx);
2801 let mut bracket_inserted = false;
2802 let mut edits = Vec::new();
2803 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2804 let mut new_selections = Vec::with_capacity(selections.len());
2805 let mut new_autoclose_regions = Vec::new();
2806 let snapshot = self.buffer.read(cx).read(cx);
2807
2808 for (selection, autoclose_region) in
2809 self.selections_with_autoclose_regions(selections, &snapshot)
2810 {
2811 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2812 // Determine if the inserted text matches the opening or closing
2813 // bracket of any of this language's bracket pairs.
2814 let mut bracket_pair = None;
2815 let mut is_bracket_pair_start = false;
2816 let mut is_bracket_pair_end = false;
2817 if !text.is_empty() {
2818 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2819 // and they are removing the character that triggered IME popup.
2820 for (pair, enabled) in scope.brackets() {
2821 if !pair.close && !pair.surround {
2822 continue;
2823 }
2824
2825 if enabled && pair.start.ends_with(text.as_ref()) {
2826 let prefix_len = pair.start.len() - text.len();
2827 let preceding_text_matches_prefix = prefix_len == 0
2828 || (selection.start.column >= (prefix_len as u32)
2829 && snapshot.contains_str_at(
2830 Point::new(
2831 selection.start.row,
2832 selection.start.column - (prefix_len as u32),
2833 ),
2834 &pair.start[..prefix_len],
2835 ));
2836 if preceding_text_matches_prefix {
2837 bracket_pair = Some(pair.clone());
2838 is_bracket_pair_start = true;
2839 break;
2840 }
2841 }
2842 if pair.end.as_str() == text.as_ref() {
2843 bracket_pair = Some(pair.clone());
2844 is_bracket_pair_end = true;
2845 break;
2846 }
2847 }
2848 }
2849
2850 if let Some(bracket_pair) = bracket_pair {
2851 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2852 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2853 let auto_surround =
2854 self.use_auto_surround && snapshot_settings.use_auto_surround;
2855 if selection.is_empty() {
2856 if is_bracket_pair_start {
2857 // If the inserted text is a suffix of an opening bracket and the
2858 // selection is preceded by the rest of the opening bracket, then
2859 // insert the closing bracket.
2860 let following_text_allows_autoclose = snapshot
2861 .chars_at(selection.start)
2862 .next()
2863 .map_or(true, |c| scope.should_autoclose_before(c));
2864
2865 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2866 && bracket_pair.start.len() == 1
2867 {
2868 let target = bracket_pair.start.chars().next().unwrap();
2869 let current_line_count = snapshot
2870 .reversed_chars_at(selection.start)
2871 .take_while(|&c| c != '\n')
2872 .filter(|&c| c == target)
2873 .count();
2874 current_line_count % 2 == 1
2875 } else {
2876 false
2877 };
2878
2879 if autoclose
2880 && bracket_pair.close
2881 && following_text_allows_autoclose
2882 && !is_closing_quote
2883 {
2884 let anchor = snapshot.anchor_before(selection.end);
2885 new_selections.push((selection.map(|_| anchor), text.len()));
2886 new_autoclose_regions.push((
2887 anchor,
2888 text.len(),
2889 selection.id,
2890 bracket_pair.clone(),
2891 ));
2892 edits.push((
2893 selection.range(),
2894 format!("{}{}", text, bracket_pair.end).into(),
2895 ));
2896 bracket_inserted = true;
2897 continue;
2898 }
2899 }
2900
2901 if let Some(region) = autoclose_region {
2902 // If the selection is followed by an auto-inserted closing bracket,
2903 // then don't insert that closing bracket again; just move the selection
2904 // past the closing bracket.
2905 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2906 && text.as_ref() == region.pair.end.as_str();
2907 if should_skip {
2908 let anchor = snapshot.anchor_after(selection.end);
2909 new_selections
2910 .push((selection.map(|_| anchor), region.pair.end.len()));
2911 continue;
2912 }
2913 }
2914
2915 let always_treat_brackets_as_autoclosed = snapshot
2916 .settings_at(selection.start, cx)
2917 .always_treat_brackets_as_autoclosed;
2918 if always_treat_brackets_as_autoclosed
2919 && is_bracket_pair_end
2920 && snapshot.contains_str_at(selection.end, text.as_ref())
2921 {
2922 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2923 // and the inserted text is a closing bracket and the selection is followed
2924 // by the closing bracket then move the selection past the closing bracket.
2925 let anchor = snapshot.anchor_after(selection.end);
2926 new_selections.push((selection.map(|_| anchor), text.len()));
2927 continue;
2928 }
2929 }
2930 // If an opening bracket is 1 character long and is typed while
2931 // text is selected, then surround that text with the bracket pair.
2932 else if auto_surround
2933 && bracket_pair.surround
2934 && is_bracket_pair_start
2935 && bracket_pair.start.chars().count() == 1
2936 {
2937 edits.push((selection.start..selection.start, text.clone()));
2938 edits.push((
2939 selection.end..selection.end,
2940 bracket_pair.end.as_str().into(),
2941 ));
2942 bracket_inserted = true;
2943 new_selections.push((
2944 Selection {
2945 id: selection.id,
2946 start: snapshot.anchor_after(selection.start),
2947 end: snapshot.anchor_before(selection.end),
2948 reversed: selection.reversed,
2949 goal: selection.goal,
2950 },
2951 0,
2952 ));
2953 continue;
2954 }
2955 }
2956 }
2957
2958 if self.auto_replace_emoji_shortcode
2959 && selection.is_empty()
2960 && text.as_ref().ends_with(':')
2961 {
2962 if let Some(possible_emoji_short_code) =
2963 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2964 {
2965 if !possible_emoji_short_code.is_empty() {
2966 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2967 let emoji_shortcode_start = Point::new(
2968 selection.start.row,
2969 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2970 );
2971
2972 // Remove shortcode from buffer
2973 edits.push((
2974 emoji_shortcode_start..selection.start,
2975 "".to_string().into(),
2976 ));
2977 new_selections.push((
2978 Selection {
2979 id: selection.id,
2980 start: snapshot.anchor_after(emoji_shortcode_start),
2981 end: snapshot.anchor_before(selection.start),
2982 reversed: selection.reversed,
2983 goal: selection.goal,
2984 },
2985 0,
2986 ));
2987
2988 // Insert emoji
2989 let selection_start_anchor = snapshot.anchor_after(selection.start);
2990 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2991 edits.push((selection.start..selection.end, emoji.to_string().into()));
2992
2993 continue;
2994 }
2995 }
2996 }
2997 }
2998
2999 // If not handling any auto-close operation, then just replace the selected
3000 // text with the given input and move the selection to the end of the
3001 // newly inserted text.
3002 let anchor = snapshot.anchor_after(selection.end);
3003 if !self.linked_edit_ranges.is_empty() {
3004 let start_anchor = snapshot.anchor_before(selection.start);
3005
3006 let is_word_char = text.chars().next().map_or(true, |char| {
3007 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3008 classifier.is_word(char)
3009 });
3010
3011 if is_word_char {
3012 if let Some(ranges) = self
3013 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3014 {
3015 for (buffer, edits) in ranges {
3016 linked_edits
3017 .entry(buffer.clone())
3018 .or_default()
3019 .extend(edits.into_iter().map(|range| (range, text.clone())));
3020 }
3021 }
3022 }
3023 }
3024
3025 new_selections.push((selection.map(|_| anchor), 0));
3026 edits.push((selection.start..selection.end, text.clone()));
3027 }
3028
3029 drop(snapshot);
3030
3031 self.transact(window, cx, |this, window, cx| {
3032 this.buffer.update(cx, |buffer, cx| {
3033 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3034 });
3035 for (buffer, edits) in linked_edits {
3036 buffer.update(cx, |buffer, cx| {
3037 let snapshot = buffer.snapshot();
3038 let edits = edits
3039 .into_iter()
3040 .map(|(range, text)| {
3041 use text::ToPoint as TP;
3042 let end_point = TP::to_point(&range.end, &snapshot);
3043 let start_point = TP::to_point(&range.start, &snapshot);
3044 (start_point..end_point, text)
3045 })
3046 .sorted_by_key(|(range, _)| range.start)
3047 .collect::<Vec<_>>();
3048 buffer.edit(edits, None, cx);
3049 })
3050 }
3051 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3052 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3053 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3054 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3055 .zip(new_selection_deltas)
3056 .map(|(selection, delta)| Selection {
3057 id: selection.id,
3058 start: selection.start + delta,
3059 end: selection.end + delta,
3060 reversed: selection.reversed,
3061 goal: SelectionGoal::None,
3062 })
3063 .collect::<Vec<_>>();
3064
3065 let mut i = 0;
3066 for (position, delta, selection_id, pair) in new_autoclose_regions {
3067 let position = position.to_offset(&map.buffer_snapshot) + delta;
3068 let start = map.buffer_snapshot.anchor_before(position);
3069 let end = map.buffer_snapshot.anchor_after(position);
3070 while let Some(existing_state) = this.autoclose_regions.get(i) {
3071 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3072 Ordering::Less => i += 1,
3073 Ordering::Greater => break,
3074 Ordering::Equal => {
3075 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3076 Ordering::Less => i += 1,
3077 Ordering::Equal => break,
3078 Ordering::Greater => break,
3079 }
3080 }
3081 }
3082 }
3083 this.autoclose_regions.insert(
3084 i,
3085 AutocloseRegion {
3086 selection_id,
3087 range: start..end,
3088 pair,
3089 },
3090 );
3091 }
3092
3093 let had_active_inline_completion = this.has_active_inline_completion();
3094 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3095 s.select(new_selections)
3096 });
3097
3098 if !bracket_inserted {
3099 if let Some(on_type_format_task) =
3100 this.trigger_on_type_formatting(text.to_string(), window, cx)
3101 {
3102 on_type_format_task.detach_and_log_err(cx);
3103 }
3104 }
3105
3106 let editor_settings = EditorSettings::get_global(cx);
3107 if bracket_inserted
3108 && (editor_settings.auto_signature_help
3109 || editor_settings.show_signature_help_after_edits)
3110 {
3111 this.show_signature_help(&ShowSignatureHelp, window, cx);
3112 }
3113
3114 let trigger_in_words =
3115 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3116 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3117 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3118 this.refresh_inline_completion(true, false, window, cx);
3119 });
3120 }
3121
3122 fn find_possible_emoji_shortcode_at_position(
3123 snapshot: &MultiBufferSnapshot,
3124 position: Point,
3125 ) -> Option<String> {
3126 let mut chars = Vec::new();
3127 let mut found_colon = false;
3128 for char in snapshot.reversed_chars_at(position).take(100) {
3129 // Found a possible emoji shortcode in the middle of the buffer
3130 if found_colon {
3131 if char.is_whitespace() {
3132 chars.reverse();
3133 return Some(chars.iter().collect());
3134 }
3135 // If the previous character is not a whitespace, we are in the middle of a word
3136 // and we only want to complete the shortcode if the word is made up of other emojis
3137 let mut containing_word = String::new();
3138 for ch in snapshot
3139 .reversed_chars_at(position)
3140 .skip(chars.len() + 1)
3141 .take(100)
3142 {
3143 if ch.is_whitespace() {
3144 break;
3145 }
3146 containing_word.push(ch);
3147 }
3148 let containing_word = containing_word.chars().rev().collect::<String>();
3149 if util::word_consists_of_emojis(containing_word.as_str()) {
3150 chars.reverse();
3151 return Some(chars.iter().collect());
3152 }
3153 }
3154
3155 if char.is_whitespace() || !char.is_ascii() {
3156 return None;
3157 }
3158 if char == ':' {
3159 found_colon = true;
3160 } else {
3161 chars.push(char);
3162 }
3163 }
3164 // Found a possible emoji shortcode at the beginning of the buffer
3165 chars.reverse();
3166 Some(chars.iter().collect())
3167 }
3168
3169 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3170 self.transact(window, cx, |this, window, cx| {
3171 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3172 let selections = this.selections.all::<usize>(cx);
3173 let multi_buffer = this.buffer.read(cx);
3174 let buffer = multi_buffer.snapshot(cx);
3175 selections
3176 .iter()
3177 .map(|selection| {
3178 let start_point = selection.start.to_point(&buffer);
3179 let mut indent =
3180 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3181 indent.len = cmp::min(indent.len, start_point.column);
3182 let start = selection.start;
3183 let end = selection.end;
3184 let selection_is_empty = start == end;
3185 let language_scope = buffer.language_scope_at(start);
3186 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3187 &language_scope
3188 {
3189 let insert_extra_newline =
3190 insert_extra_newline_brackets(&buffer, start..end, language)
3191 || insert_extra_newline_tree_sitter(&buffer, start..end);
3192
3193 // Comment extension on newline is allowed only for cursor selections
3194 let comment_delimiter = maybe!({
3195 if !selection_is_empty {
3196 return None;
3197 }
3198
3199 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3200 return None;
3201 }
3202
3203 let delimiters = language.line_comment_prefixes();
3204 let max_len_of_delimiter =
3205 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3206 let (snapshot, range) =
3207 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3208
3209 let mut index_of_first_non_whitespace = 0;
3210 let comment_candidate = snapshot
3211 .chars_for_range(range)
3212 .skip_while(|c| {
3213 let should_skip = c.is_whitespace();
3214 if should_skip {
3215 index_of_first_non_whitespace += 1;
3216 }
3217 should_skip
3218 })
3219 .take(max_len_of_delimiter)
3220 .collect::<String>();
3221 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3222 comment_candidate.starts_with(comment_prefix.as_ref())
3223 })?;
3224 let cursor_is_placed_after_comment_marker =
3225 index_of_first_non_whitespace + comment_prefix.len()
3226 <= start_point.column as usize;
3227 if cursor_is_placed_after_comment_marker {
3228 Some(comment_prefix.clone())
3229 } else {
3230 None
3231 }
3232 });
3233 (comment_delimiter, insert_extra_newline)
3234 } else {
3235 (None, false)
3236 };
3237
3238 let capacity_for_delimiter = comment_delimiter
3239 .as_deref()
3240 .map(str::len)
3241 .unwrap_or_default();
3242 let mut new_text =
3243 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3244 new_text.push('\n');
3245 new_text.extend(indent.chars());
3246 if let Some(delimiter) = &comment_delimiter {
3247 new_text.push_str(delimiter);
3248 }
3249 if insert_extra_newline {
3250 new_text = new_text.repeat(2);
3251 }
3252
3253 let anchor = buffer.anchor_after(end);
3254 let new_selection = selection.map(|_| anchor);
3255 (
3256 (start..end, new_text),
3257 (insert_extra_newline, new_selection),
3258 )
3259 })
3260 .unzip()
3261 };
3262
3263 this.edit_with_autoindent(edits, cx);
3264 let buffer = this.buffer.read(cx).snapshot(cx);
3265 let new_selections = selection_fixup_info
3266 .into_iter()
3267 .map(|(extra_newline_inserted, new_selection)| {
3268 let mut cursor = new_selection.end.to_point(&buffer);
3269 if extra_newline_inserted {
3270 cursor.row -= 1;
3271 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3272 }
3273 new_selection.map(|_| cursor)
3274 })
3275 .collect();
3276
3277 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3278 s.select(new_selections)
3279 });
3280 this.refresh_inline_completion(true, false, window, cx);
3281 });
3282 }
3283
3284 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3285 let buffer = self.buffer.read(cx);
3286 let snapshot = buffer.snapshot(cx);
3287
3288 let mut edits = Vec::new();
3289 let mut rows = Vec::new();
3290
3291 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3292 let cursor = selection.head();
3293 let row = cursor.row;
3294
3295 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3296
3297 let newline = "\n".to_string();
3298 edits.push((start_of_line..start_of_line, newline));
3299
3300 rows.push(row + rows_inserted as u32);
3301 }
3302
3303 self.transact(window, cx, |editor, window, cx| {
3304 editor.edit(edits, cx);
3305
3306 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3307 let mut index = 0;
3308 s.move_cursors_with(|map, _, _| {
3309 let row = rows[index];
3310 index += 1;
3311
3312 let point = Point::new(row, 0);
3313 let boundary = map.next_line_boundary(point).1;
3314 let clipped = map.clip_point(boundary, Bias::Left);
3315
3316 (clipped, SelectionGoal::None)
3317 });
3318 });
3319
3320 let mut indent_edits = Vec::new();
3321 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3322 for row in rows {
3323 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3324 for (row, indent) in indents {
3325 if indent.len == 0 {
3326 continue;
3327 }
3328
3329 let text = match indent.kind {
3330 IndentKind::Space => " ".repeat(indent.len as usize),
3331 IndentKind::Tab => "\t".repeat(indent.len as usize),
3332 };
3333 let point = Point::new(row.0, 0);
3334 indent_edits.push((point..point, text));
3335 }
3336 }
3337 editor.edit(indent_edits, cx);
3338 });
3339 }
3340
3341 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3342 let buffer = self.buffer.read(cx);
3343 let snapshot = buffer.snapshot(cx);
3344
3345 let mut edits = Vec::new();
3346 let mut rows = Vec::new();
3347 let mut rows_inserted = 0;
3348
3349 for selection in self.selections.all_adjusted(cx) {
3350 let cursor = selection.head();
3351 let row = cursor.row;
3352
3353 let point = Point::new(row + 1, 0);
3354 let start_of_line = snapshot.clip_point(point, Bias::Left);
3355
3356 let newline = "\n".to_string();
3357 edits.push((start_of_line..start_of_line, newline));
3358
3359 rows_inserted += 1;
3360 rows.push(row + rows_inserted);
3361 }
3362
3363 self.transact(window, cx, |editor, window, cx| {
3364 editor.edit(edits, cx);
3365
3366 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3367 let mut index = 0;
3368 s.move_cursors_with(|map, _, _| {
3369 let row = rows[index];
3370 index += 1;
3371
3372 let point = Point::new(row, 0);
3373 let boundary = map.next_line_boundary(point).1;
3374 let clipped = map.clip_point(boundary, Bias::Left);
3375
3376 (clipped, SelectionGoal::None)
3377 });
3378 });
3379
3380 let mut indent_edits = Vec::new();
3381 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3382 for row in rows {
3383 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3384 for (row, indent) in indents {
3385 if indent.len == 0 {
3386 continue;
3387 }
3388
3389 let text = match indent.kind {
3390 IndentKind::Space => " ".repeat(indent.len as usize),
3391 IndentKind::Tab => "\t".repeat(indent.len as usize),
3392 };
3393 let point = Point::new(row.0, 0);
3394 indent_edits.push((point..point, text));
3395 }
3396 }
3397 editor.edit(indent_edits, cx);
3398 });
3399 }
3400
3401 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3402 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3403 original_start_columns: Vec::new(),
3404 });
3405 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3406 }
3407
3408 fn insert_with_autoindent_mode(
3409 &mut self,
3410 text: &str,
3411 autoindent_mode: Option<AutoindentMode>,
3412 window: &mut Window,
3413 cx: &mut Context<Self>,
3414 ) {
3415 if self.read_only(cx) {
3416 return;
3417 }
3418
3419 let text: Arc<str> = text.into();
3420 self.transact(window, cx, |this, window, cx| {
3421 let old_selections = this.selections.all_adjusted(cx);
3422 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3423 let anchors = {
3424 let snapshot = buffer.read(cx);
3425 old_selections
3426 .iter()
3427 .map(|s| {
3428 let anchor = snapshot.anchor_after(s.head());
3429 s.map(|_| anchor)
3430 })
3431 .collect::<Vec<_>>()
3432 };
3433 buffer.edit(
3434 old_selections
3435 .iter()
3436 .map(|s| (s.start..s.end, text.clone())),
3437 autoindent_mode,
3438 cx,
3439 );
3440 anchors
3441 });
3442
3443 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3444 s.select_anchors(selection_anchors);
3445 });
3446
3447 cx.notify();
3448 });
3449 }
3450
3451 fn trigger_completion_on_input(
3452 &mut self,
3453 text: &str,
3454 trigger_in_words: bool,
3455 window: &mut Window,
3456 cx: &mut Context<Self>,
3457 ) {
3458 if self.is_completion_trigger(text, trigger_in_words, cx) {
3459 self.show_completions(
3460 &ShowCompletions {
3461 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3462 },
3463 window,
3464 cx,
3465 );
3466 } else {
3467 self.hide_context_menu(window, cx);
3468 }
3469 }
3470
3471 fn is_completion_trigger(
3472 &self,
3473 text: &str,
3474 trigger_in_words: bool,
3475 cx: &mut Context<Self>,
3476 ) -> bool {
3477 let position = self.selections.newest_anchor().head();
3478 let multibuffer = self.buffer.read(cx);
3479 let Some(buffer) = position
3480 .buffer_id
3481 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3482 else {
3483 return false;
3484 };
3485
3486 if let Some(completion_provider) = &self.completion_provider {
3487 completion_provider.is_completion_trigger(
3488 &buffer,
3489 position.text_anchor,
3490 text,
3491 trigger_in_words,
3492 cx,
3493 )
3494 } else {
3495 false
3496 }
3497 }
3498
3499 /// If any empty selections is touching the start of its innermost containing autoclose
3500 /// region, expand it to select the brackets.
3501 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3502 let selections = self.selections.all::<usize>(cx);
3503 let buffer = self.buffer.read(cx).read(cx);
3504 let new_selections = self
3505 .selections_with_autoclose_regions(selections, &buffer)
3506 .map(|(mut selection, region)| {
3507 if !selection.is_empty() {
3508 return selection;
3509 }
3510
3511 if let Some(region) = region {
3512 let mut range = region.range.to_offset(&buffer);
3513 if selection.start == range.start && range.start >= region.pair.start.len() {
3514 range.start -= region.pair.start.len();
3515 if buffer.contains_str_at(range.start, ®ion.pair.start)
3516 && buffer.contains_str_at(range.end, ®ion.pair.end)
3517 {
3518 range.end += region.pair.end.len();
3519 selection.start = range.start;
3520 selection.end = range.end;
3521
3522 return selection;
3523 }
3524 }
3525 }
3526
3527 let always_treat_brackets_as_autoclosed = buffer
3528 .settings_at(selection.start, cx)
3529 .always_treat_brackets_as_autoclosed;
3530
3531 if !always_treat_brackets_as_autoclosed {
3532 return selection;
3533 }
3534
3535 if let Some(scope) = buffer.language_scope_at(selection.start) {
3536 for (pair, enabled) in scope.brackets() {
3537 if !enabled || !pair.close {
3538 continue;
3539 }
3540
3541 if buffer.contains_str_at(selection.start, &pair.end) {
3542 let pair_start_len = pair.start.len();
3543 if buffer.contains_str_at(
3544 selection.start.saturating_sub(pair_start_len),
3545 &pair.start,
3546 ) {
3547 selection.start -= pair_start_len;
3548 selection.end += pair.end.len();
3549
3550 return selection;
3551 }
3552 }
3553 }
3554 }
3555
3556 selection
3557 })
3558 .collect();
3559
3560 drop(buffer);
3561 self.change_selections(None, window, cx, |selections| {
3562 selections.select(new_selections)
3563 });
3564 }
3565
3566 /// Iterate the given selections, and for each one, find the smallest surrounding
3567 /// autoclose region. This uses the ordering of the selections and the autoclose
3568 /// regions to avoid repeated comparisons.
3569 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3570 &'a self,
3571 selections: impl IntoIterator<Item = Selection<D>>,
3572 buffer: &'a MultiBufferSnapshot,
3573 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3574 let mut i = 0;
3575 let mut regions = self.autoclose_regions.as_slice();
3576 selections.into_iter().map(move |selection| {
3577 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3578
3579 let mut enclosing = None;
3580 while let Some(pair_state) = regions.get(i) {
3581 if pair_state.range.end.to_offset(buffer) < range.start {
3582 regions = ®ions[i + 1..];
3583 i = 0;
3584 } else if pair_state.range.start.to_offset(buffer) > range.end {
3585 break;
3586 } else {
3587 if pair_state.selection_id == selection.id {
3588 enclosing = Some(pair_state);
3589 }
3590 i += 1;
3591 }
3592 }
3593
3594 (selection, enclosing)
3595 })
3596 }
3597
3598 /// Remove any autoclose regions that no longer contain their selection.
3599 fn invalidate_autoclose_regions(
3600 &mut self,
3601 mut selections: &[Selection<Anchor>],
3602 buffer: &MultiBufferSnapshot,
3603 ) {
3604 self.autoclose_regions.retain(|state| {
3605 let mut i = 0;
3606 while let Some(selection) = selections.get(i) {
3607 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3608 selections = &selections[1..];
3609 continue;
3610 }
3611 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3612 break;
3613 }
3614 if selection.id == state.selection_id {
3615 return true;
3616 } else {
3617 i += 1;
3618 }
3619 }
3620 false
3621 });
3622 }
3623
3624 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3625 let offset = position.to_offset(buffer);
3626 let (word_range, kind) = buffer.surrounding_word(offset, true);
3627 if offset > word_range.start && kind == Some(CharKind::Word) {
3628 Some(
3629 buffer
3630 .text_for_range(word_range.start..offset)
3631 .collect::<String>(),
3632 )
3633 } else {
3634 None
3635 }
3636 }
3637
3638 pub fn toggle_inlay_hints(
3639 &mut self,
3640 _: &ToggleInlayHints,
3641 _: &mut Window,
3642 cx: &mut Context<Self>,
3643 ) {
3644 self.refresh_inlay_hints(
3645 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3646 cx,
3647 );
3648 }
3649
3650 pub fn inlay_hints_enabled(&self) -> bool {
3651 self.inlay_hint_cache.enabled
3652 }
3653
3654 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3655 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3656 return;
3657 }
3658
3659 let reason_description = reason.description();
3660 let ignore_debounce = matches!(
3661 reason,
3662 InlayHintRefreshReason::SettingsChange(_)
3663 | InlayHintRefreshReason::Toggle(_)
3664 | InlayHintRefreshReason::ExcerptsRemoved(_)
3665 );
3666 let (invalidate_cache, required_languages) = match reason {
3667 InlayHintRefreshReason::Toggle(enabled) => {
3668 self.inlay_hint_cache.enabled = enabled;
3669 if enabled {
3670 (InvalidationStrategy::RefreshRequested, None)
3671 } else {
3672 self.inlay_hint_cache.clear();
3673 self.splice_inlays(
3674 &self
3675 .visible_inlay_hints(cx)
3676 .iter()
3677 .map(|inlay| inlay.id)
3678 .collect::<Vec<InlayId>>(),
3679 Vec::new(),
3680 cx,
3681 );
3682 return;
3683 }
3684 }
3685 InlayHintRefreshReason::SettingsChange(new_settings) => {
3686 match self.inlay_hint_cache.update_settings(
3687 &self.buffer,
3688 new_settings,
3689 self.visible_inlay_hints(cx),
3690 cx,
3691 ) {
3692 ControlFlow::Break(Some(InlaySplice {
3693 to_remove,
3694 to_insert,
3695 })) => {
3696 self.splice_inlays(&to_remove, to_insert, cx);
3697 return;
3698 }
3699 ControlFlow::Break(None) => return,
3700 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3701 }
3702 }
3703 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3704 if let Some(InlaySplice {
3705 to_remove,
3706 to_insert,
3707 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3708 {
3709 self.splice_inlays(&to_remove, to_insert, cx);
3710 }
3711 return;
3712 }
3713 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3714 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3715 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3716 }
3717 InlayHintRefreshReason::RefreshRequested => {
3718 (InvalidationStrategy::RefreshRequested, None)
3719 }
3720 };
3721
3722 if let Some(InlaySplice {
3723 to_remove,
3724 to_insert,
3725 }) = self.inlay_hint_cache.spawn_hint_refresh(
3726 reason_description,
3727 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3728 invalidate_cache,
3729 ignore_debounce,
3730 cx,
3731 ) {
3732 self.splice_inlays(&to_remove, to_insert, cx);
3733 }
3734 }
3735
3736 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3737 self.display_map
3738 .read(cx)
3739 .current_inlays()
3740 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3741 .cloned()
3742 .collect()
3743 }
3744
3745 pub fn excerpts_for_inlay_hints_query(
3746 &self,
3747 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3748 cx: &mut Context<Editor>,
3749 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3750 let Some(project) = self.project.as_ref() else {
3751 return HashMap::default();
3752 };
3753 let project = project.read(cx);
3754 let multi_buffer = self.buffer().read(cx);
3755 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3756 let multi_buffer_visible_start = self
3757 .scroll_manager
3758 .anchor()
3759 .anchor
3760 .to_point(&multi_buffer_snapshot);
3761 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3762 multi_buffer_visible_start
3763 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3764 Bias::Left,
3765 );
3766 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3767 multi_buffer_snapshot
3768 .range_to_buffer_ranges(multi_buffer_visible_range)
3769 .into_iter()
3770 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3771 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3772 let buffer_file = project::File::from_dyn(buffer.file())?;
3773 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3774 let worktree_entry = buffer_worktree
3775 .read(cx)
3776 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3777 if worktree_entry.is_ignored {
3778 return None;
3779 }
3780
3781 let language = buffer.language()?;
3782 if let Some(restrict_to_languages) = restrict_to_languages {
3783 if !restrict_to_languages.contains(language) {
3784 return None;
3785 }
3786 }
3787 Some((
3788 excerpt_id,
3789 (
3790 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3791 buffer.version().clone(),
3792 excerpt_visible_range,
3793 ),
3794 ))
3795 })
3796 .collect()
3797 }
3798
3799 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3800 TextLayoutDetails {
3801 text_system: window.text_system().clone(),
3802 editor_style: self.style.clone().unwrap(),
3803 rem_size: window.rem_size(),
3804 scroll_anchor: self.scroll_manager.anchor(),
3805 visible_rows: self.visible_line_count(),
3806 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3807 }
3808 }
3809
3810 pub fn splice_inlays(
3811 &self,
3812 to_remove: &[InlayId],
3813 to_insert: Vec<Inlay>,
3814 cx: &mut Context<Self>,
3815 ) {
3816 self.display_map.update(cx, |display_map, cx| {
3817 display_map.splice_inlays(to_remove, to_insert, cx)
3818 });
3819 cx.notify();
3820 }
3821
3822 fn trigger_on_type_formatting(
3823 &self,
3824 input: String,
3825 window: &mut Window,
3826 cx: &mut Context<Self>,
3827 ) -> Option<Task<Result<()>>> {
3828 if input.len() != 1 {
3829 return None;
3830 }
3831
3832 let project = self.project.as_ref()?;
3833 let position = self.selections.newest_anchor().head();
3834 let (buffer, buffer_position) = self
3835 .buffer
3836 .read(cx)
3837 .text_anchor_for_position(position, cx)?;
3838
3839 let settings = language_settings::language_settings(
3840 buffer
3841 .read(cx)
3842 .language_at(buffer_position)
3843 .map(|l| l.name()),
3844 buffer.read(cx).file(),
3845 cx,
3846 );
3847 if !settings.use_on_type_format {
3848 return None;
3849 }
3850
3851 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3852 // hence we do LSP request & edit on host side only — add formats to host's history.
3853 let push_to_lsp_host_history = true;
3854 // If this is not the host, append its history with new edits.
3855 let push_to_client_history = project.read(cx).is_via_collab();
3856
3857 let on_type_formatting = project.update(cx, |project, cx| {
3858 project.on_type_format(
3859 buffer.clone(),
3860 buffer_position,
3861 input,
3862 push_to_lsp_host_history,
3863 cx,
3864 )
3865 });
3866 Some(cx.spawn_in(window, |editor, mut cx| async move {
3867 if let Some(transaction) = on_type_formatting.await? {
3868 if push_to_client_history {
3869 buffer
3870 .update(&mut cx, |buffer, _| {
3871 buffer.push_transaction(transaction, Instant::now());
3872 })
3873 .ok();
3874 }
3875 editor.update(&mut cx, |editor, cx| {
3876 editor.refresh_document_highlights(cx);
3877 })?;
3878 }
3879 Ok(())
3880 }))
3881 }
3882
3883 pub fn show_completions(
3884 &mut self,
3885 options: &ShowCompletions,
3886 window: &mut Window,
3887 cx: &mut Context<Self>,
3888 ) {
3889 if self.pending_rename.is_some() {
3890 return;
3891 }
3892
3893 let Some(provider) = self.completion_provider.as_ref() else {
3894 return;
3895 };
3896
3897 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3898 return;
3899 }
3900
3901 let position = self.selections.newest_anchor().head();
3902 if position.diff_base_anchor.is_some() {
3903 return;
3904 }
3905 let (buffer, buffer_position) =
3906 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3907 output
3908 } else {
3909 return;
3910 };
3911 let show_completion_documentation = buffer
3912 .read(cx)
3913 .snapshot()
3914 .settings_at(buffer_position, cx)
3915 .show_completion_documentation;
3916
3917 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3918
3919 let trigger_kind = match &options.trigger {
3920 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3921 CompletionTriggerKind::TRIGGER_CHARACTER
3922 }
3923 _ => CompletionTriggerKind::INVOKED,
3924 };
3925 let completion_context = CompletionContext {
3926 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3927 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3928 Some(String::from(trigger))
3929 } else {
3930 None
3931 }
3932 }),
3933 trigger_kind,
3934 };
3935 let completions =
3936 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3937 let sort_completions = provider.sort_completions();
3938
3939 let id = post_inc(&mut self.next_completion_id);
3940 let task = cx.spawn_in(window, |editor, mut cx| {
3941 async move {
3942 editor.update(&mut cx, |this, _| {
3943 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3944 })?;
3945 let completions = completions.await.log_err();
3946 let menu = if let Some(completions) = completions {
3947 let mut menu = CompletionsMenu::new(
3948 id,
3949 sort_completions,
3950 show_completion_documentation,
3951 position,
3952 buffer.clone(),
3953 completions.into(),
3954 );
3955
3956 menu.filter(query.as_deref(), cx.background_executor().clone())
3957 .await;
3958
3959 menu.visible().then_some(menu)
3960 } else {
3961 None
3962 };
3963
3964 editor.update_in(&mut cx, |editor, window, cx| {
3965 match editor.context_menu.borrow().as_ref() {
3966 None => {}
3967 Some(CodeContextMenu::Completions(prev_menu)) => {
3968 if prev_menu.id > id {
3969 return;
3970 }
3971 }
3972 _ => return,
3973 }
3974
3975 if editor.focus_handle.is_focused(window) && menu.is_some() {
3976 let mut menu = menu.unwrap();
3977 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3978
3979 *editor.context_menu.borrow_mut() =
3980 Some(CodeContextMenu::Completions(menu));
3981
3982 if editor.show_edit_predictions_in_menu() {
3983 editor.update_visible_inline_completion(window, cx);
3984 } else {
3985 editor.discard_inline_completion(false, cx);
3986 }
3987
3988 cx.notify();
3989 } else if editor.completion_tasks.len() <= 1 {
3990 // If there are no more completion tasks and the last menu was
3991 // empty, we should hide it.
3992 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3993 // If it was already hidden and we don't show inline
3994 // completions in the menu, we should also show the
3995 // inline-completion when available.
3996 if was_hidden && editor.show_edit_predictions_in_menu() {
3997 editor.update_visible_inline_completion(window, cx);
3998 }
3999 }
4000 })?;
4001
4002 Ok::<_, anyhow::Error>(())
4003 }
4004 .log_err()
4005 });
4006
4007 self.completion_tasks.push((id, task));
4008 }
4009
4010 pub fn confirm_completion(
4011 &mut self,
4012 action: &ConfirmCompletion,
4013 window: &mut Window,
4014 cx: &mut Context<Self>,
4015 ) -> Option<Task<Result<()>>> {
4016 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4017 }
4018
4019 pub fn compose_completion(
4020 &mut self,
4021 action: &ComposeCompletion,
4022 window: &mut Window,
4023 cx: &mut Context<Self>,
4024 ) -> Option<Task<Result<()>>> {
4025 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4026 }
4027
4028 fn do_completion(
4029 &mut self,
4030 item_ix: Option<usize>,
4031 intent: CompletionIntent,
4032 window: &mut Window,
4033 cx: &mut Context<Editor>,
4034 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4035 use language::ToOffset as _;
4036
4037 let completions_menu =
4038 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4039 menu
4040 } else {
4041 return None;
4042 };
4043
4044 let entries = completions_menu.entries.borrow();
4045 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4046 if self.show_edit_predictions_in_menu() {
4047 self.discard_inline_completion(true, cx);
4048 }
4049 let candidate_id = mat.candidate_id;
4050 drop(entries);
4051
4052 let buffer_handle = completions_menu.buffer;
4053 let completion = completions_menu
4054 .completions
4055 .borrow()
4056 .get(candidate_id)?
4057 .clone();
4058 cx.stop_propagation();
4059
4060 let snippet;
4061 let text;
4062
4063 if completion.is_snippet() {
4064 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4065 text = snippet.as_ref().unwrap().text.clone();
4066 } else {
4067 snippet = None;
4068 text = completion.new_text.clone();
4069 };
4070 let selections = self.selections.all::<usize>(cx);
4071 let buffer = buffer_handle.read(cx);
4072 let old_range = completion.old_range.to_offset(buffer);
4073 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4074
4075 let newest_selection = self.selections.newest_anchor();
4076 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4077 return None;
4078 }
4079
4080 let lookbehind = newest_selection
4081 .start
4082 .text_anchor
4083 .to_offset(buffer)
4084 .saturating_sub(old_range.start);
4085 let lookahead = old_range
4086 .end
4087 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4088 let mut common_prefix_len = old_text
4089 .bytes()
4090 .zip(text.bytes())
4091 .take_while(|(a, b)| a == b)
4092 .count();
4093
4094 let snapshot = self.buffer.read(cx).snapshot(cx);
4095 let mut range_to_replace: Option<Range<isize>> = None;
4096 let mut ranges = Vec::new();
4097 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4098 for selection in &selections {
4099 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4100 let start = selection.start.saturating_sub(lookbehind);
4101 let end = selection.end + lookahead;
4102 if selection.id == newest_selection.id {
4103 range_to_replace = Some(
4104 ((start + common_prefix_len) as isize - selection.start as isize)
4105 ..(end as isize - selection.start as isize),
4106 );
4107 }
4108 ranges.push(start + common_prefix_len..end);
4109 } else {
4110 common_prefix_len = 0;
4111 ranges.clear();
4112 ranges.extend(selections.iter().map(|s| {
4113 if s.id == newest_selection.id {
4114 range_to_replace = Some(
4115 old_range.start.to_offset_utf16(&snapshot).0 as isize
4116 - selection.start as isize
4117 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4118 - selection.start as isize,
4119 );
4120 old_range.clone()
4121 } else {
4122 s.start..s.end
4123 }
4124 }));
4125 break;
4126 }
4127 if !self.linked_edit_ranges.is_empty() {
4128 let start_anchor = snapshot.anchor_before(selection.head());
4129 let end_anchor = snapshot.anchor_after(selection.tail());
4130 if let Some(ranges) = self
4131 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4132 {
4133 for (buffer, edits) in ranges {
4134 linked_edits.entry(buffer.clone()).or_default().extend(
4135 edits
4136 .into_iter()
4137 .map(|range| (range, text[common_prefix_len..].to_owned())),
4138 );
4139 }
4140 }
4141 }
4142 }
4143 let text = &text[common_prefix_len..];
4144
4145 cx.emit(EditorEvent::InputHandled {
4146 utf16_range_to_replace: range_to_replace,
4147 text: text.into(),
4148 });
4149
4150 self.transact(window, cx, |this, window, cx| {
4151 if let Some(mut snippet) = snippet {
4152 snippet.text = text.to_string();
4153 for tabstop in snippet
4154 .tabstops
4155 .iter_mut()
4156 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4157 {
4158 tabstop.start -= common_prefix_len as isize;
4159 tabstop.end -= common_prefix_len as isize;
4160 }
4161
4162 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4163 } else {
4164 this.buffer.update(cx, |buffer, cx| {
4165 buffer.edit(
4166 ranges.iter().map(|range| (range.clone(), text)),
4167 this.autoindent_mode.clone(),
4168 cx,
4169 );
4170 });
4171 }
4172 for (buffer, edits) in linked_edits {
4173 buffer.update(cx, |buffer, cx| {
4174 let snapshot = buffer.snapshot();
4175 let edits = edits
4176 .into_iter()
4177 .map(|(range, text)| {
4178 use text::ToPoint as TP;
4179 let end_point = TP::to_point(&range.end, &snapshot);
4180 let start_point = TP::to_point(&range.start, &snapshot);
4181 (start_point..end_point, text)
4182 })
4183 .sorted_by_key(|(range, _)| range.start)
4184 .collect::<Vec<_>>();
4185 buffer.edit(edits, None, cx);
4186 })
4187 }
4188
4189 this.refresh_inline_completion(true, false, window, cx);
4190 });
4191
4192 let show_new_completions_on_confirm = completion
4193 .confirm
4194 .as_ref()
4195 .map_or(false, |confirm| confirm(intent, window, cx));
4196 if show_new_completions_on_confirm {
4197 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4198 }
4199
4200 let provider = self.completion_provider.as_ref()?;
4201 drop(completion);
4202 let apply_edits = provider.apply_additional_edits_for_completion(
4203 buffer_handle,
4204 completions_menu.completions.clone(),
4205 candidate_id,
4206 true,
4207 cx,
4208 );
4209
4210 let editor_settings = EditorSettings::get_global(cx);
4211 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4212 // After the code completion is finished, users often want to know what signatures are needed.
4213 // so we should automatically call signature_help
4214 self.show_signature_help(&ShowSignatureHelp, window, cx);
4215 }
4216
4217 Some(cx.foreground_executor().spawn(async move {
4218 apply_edits.await?;
4219 Ok(())
4220 }))
4221 }
4222
4223 pub fn toggle_code_actions(
4224 &mut self,
4225 action: &ToggleCodeActions,
4226 window: &mut Window,
4227 cx: &mut Context<Self>,
4228 ) {
4229 let mut context_menu = self.context_menu.borrow_mut();
4230 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4231 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4232 // Toggle if we're selecting the same one
4233 *context_menu = None;
4234 cx.notify();
4235 return;
4236 } else {
4237 // Otherwise, clear it and start a new one
4238 *context_menu = None;
4239 cx.notify();
4240 }
4241 }
4242 drop(context_menu);
4243 let snapshot = self.snapshot(window, cx);
4244 let deployed_from_indicator = action.deployed_from_indicator;
4245 let mut task = self.code_actions_task.take();
4246 let action = action.clone();
4247 cx.spawn_in(window, |editor, mut cx| async move {
4248 while let Some(prev_task) = task {
4249 prev_task.await.log_err();
4250 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4251 }
4252
4253 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4254 if editor.focus_handle.is_focused(window) {
4255 let multibuffer_point = action
4256 .deployed_from_indicator
4257 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4258 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4259 let (buffer, buffer_row) = snapshot
4260 .buffer_snapshot
4261 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4262 .and_then(|(buffer_snapshot, range)| {
4263 editor
4264 .buffer
4265 .read(cx)
4266 .buffer(buffer_snapshot.remote_id())
4267 .map(|buffer| (buffer, range.start.row))
4268 })?;
4269 let (_, code_actions) = editor
4270 .available_code_actions
4271 .clone()
4272 .and_then(|(location, code_actions)| {
4273 let snapshot = location.buffer.read(cx).snapshot();
4274 let point_range = location.range.to_point(&snapshot);
4275 let point_range = point_range.start.row..=point_range.end.row;
4276 if point_range.contains(&buffer_row) {
4277 Some((location, code_actions))
4278 } else {
4279 None
4280 }
4281 })
4282 .unzip();
4283 let buffer_id = buffer.read(cx).remote_id();
4284 let tasks = editor
4285 .tasks
4286 .get(&(buffer_id, buffer_row))
4287 .map(|t| Arc::new(t.to_owned()));
4288 if tasks.is_none() && code_actions.is_none() {
4289 return None;
4290 }
4291
4292 editor.completion_tasks.clear();
4293 editor.discard_inline_completion(false, cx);
4294 let task_context =
4295 tasks
4296 .as_ref()
4297 .zip(editor.project.clone())
4298 .map(|(tasks, project)| {
4299 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4300 });
4301
4302 Some(cx.spawn_in(window, |editor, mut cx| async move {
4303 let task_context = match task_context {
4304 Some(task_context) => task_context.await,
4305 None => None,
4306 };
4307 let resolved_tasks =
4308 tasks.zip(task_context).map(|(tasks, task_context)| {
4309 Rc::new(ResolvedTasks {
4310 templates: tasks.resolve(&task_context).collect(),
4311 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4312 multibuffer_point.row,
4313 tasks.column,
4314 )),
4315 })
4316 });
4317 let spawn_straight_away = resolved_tasks
4318 .as_ref()
4319 .map_or(false, |tasks| tasks.templates.len() == 1)
4320 && code_actions
4321 .as_ref()
4322 .map_or(true, |actions| actions.is_empty());
4323 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4324 *editor.context_menu.borrow_mut() =
4325 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4326 buffer,
4327 actions: CodeActionContents {
4328 tasks: resolved_tasks,
4329 actions: code_actions,
4330 },
4331 selected_item: Default::default(),
4332 scroll_handle: UniformListScrollHandle::default(),
4333 deployed_from_indicator,
4334 }));
4335 if spawn_straight_away {
4336 if let Some(task) = editor.confirm_code_action(
4337 &ConfirmCodeAction { item_ix: Some(0) },
4338 window,
4339 cx,
4340 ) {
4341 cx.notify();
4342 return task;
4343 }
4344 }
4345 cx.notify();
4346 Task::ready(Ok(()))
4347 }) {
4348 task.await
4349 } else {
4350 Ok(())
4351 }
4352 }))
4353 } else {
4354 Some(Task::ready(Ok(())))
4355 }
4356 })?;
4357 if let Some(task) = spawned_test_task {
4358 task.await?;
4359 }
4360
4361 Ok::<_, anyhow::Error>(())
4362 })
4363 .detach_and_log_err(cx);
4364 }
4365
4366 pub fn confirm_code_action(
4367 &mut self,
4368 action: &ConfirmCodeAction,
4369 window: &mut Window,
4370 cx: &mut Context<Self>,
4371 ) -> Option<Task<Result<()>>> {
4372 let actions_menu =
4373 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4374 menu
4375 } else {
4376 return None;
4377 };
4378 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4379 let action = actions_menu.actions.get(action_ix)?;
4380 let title = action.label();
4381 let buffer = actions_menu.buffer;
4382 let workspace = self.workspace()?;
4383
4384 match action {
4385 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4386 workspace.update(cx, |workspace, cx| {
4387 workspace::tasks::schedule_resolved_task(
4388 workspace,
4389 task_source_kind,
4390 resolved_task,
4391 false,
4392 cx,
4393 );
4394
4395 Some(Task::ready(Ok(())))
4396 })
4397 }
4398 CodeActionsItem::CodeAction {
4399 excerpt_id,
4400 action,
4401 provider,
4402 } => {
4403 let apply_code_action =
4404 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4405 let workspace = workspace.downgrade();
4406 Some(cx.spawn_in(window, |editor, cx| async move {
4407 let project_transaction = apply_code_action.await?;
4408 Self::open_project_transaction(
4409 &editor,
4410 workspace,
4411 project_transaction,
4412 title,
4413 cx,
4414 )
4415 .await
4416 }))
4417 }
4418 }
4419 }
4420
4421 pub async fn open_project_transaction(
4422 this: &WeakEntity<Editor>,
4423 workspace: WeakEntity<Workspace>,
4424 transaction: ProjectTransaction,
4425 title: String,
4426 mut cx: AsyncWindowContext,
4427 ) -> Result<()> {
4428 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4429 cx.update(|_, cx| {
4430 entries.sort_unstable_by_key(|(buffer, _)| {
4431 buffer.read(cx).file().map(|f| f.path().clone())
4432 });
4433 })?;
4434
4435 // If the project transaction's edits are all contained within this editor, then
4436 // avoid opening a new editor to display them.
4437
4438 if let Some((buffer, transaction)) = entries.first() {
4439 if entries.len() == 1 {
4440 let excerpt = this.update(&mut cx, |editor, cx| {
4441 editor
4442 .buffer()
4443 .read(cx)
4444 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4445 })?;
4446 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4447 if excerpted_buffer == *buffer {
4448 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4449 let excerpt_range = excerpt_range.to_offset(buffer);
4450 buffer
4451 .edited_ranges_for_transaction::<usize>(transaction)
4452 .all(|range| {
4453 excerpt_range.start <= range.start
4454 && excerpt_range.end >= range.end
4455 })
4456 })?;
4457
4458 if all_edits_within_excerpt {
4459 return Ok(());
4460 }
4461 }
4462 }
4463 }
4464 } else {
4465 return Ok(());
4466 }
4467
4468 let mut ranges_to_highlight = Vec::new();
4469 let excerpt_buffer = cx.new(|cx| {
4470 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4471 for (buffer_handle, transaction) in &entries {
4472 let buffer = buffer_handle.read(cx);
4473 ranges_to_highlight.extend(
4474 multibuffer.push_excerpts_with_context_lines(
4475 buffer_handle.clone(),
4476 buffer
4477 .edited_ranges_for_transaction::<usize>(transaction)
4478 .collect(),
4479 DEFAULT_MULTIBUFFER_CONTEXT,
4480 cx,
4481 ),
4482 );
4483 }
4484 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4485 multibuffer
4486 })?;
4487
4488 workspace.update_in(&mut cx, |workspace, window, cx| {
4489 let project = workspace.project().clone();
4490 let editor = cx
4491 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4492 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4493 editor.update(cx, |editor, cx| {
4494 editor.highlight_background::<Self>(
4495 &ranges_to_highlight,
4496 |theme| theme.editor_highlighted_line_background,
4497 cx,
4498 );
4499 });
4500 })?;
4501
4502 Ok(())
4503 }
4504
4505 pub fn clear_code_action_providers(&mut self) {
4506 self.code_action_providers.clear();
4507 self.available_code_actions.take();
4508 }
4509
4510 pub fn add_code_action_provider(
4511 &mut self,
4512 provider: Rc<dyn CodeActionProvider>,
4513 window: &mut Window,
4514 cx: &mut Context<Self>,
4515 ) {
4516 if self
4517 .code_action_providers
4518 .iter()
4519 .any(|existing_provider| existing_provider.id() == provider.id())
4520 {
4521 return;
4522 }
4523
4524 self.code_action_providers.push(provider);
4525 self.refresh_code_actions(window, cx);
4526 }
4527
4528 pub fn remove_code_action_provider(
4529 &mut self,
4530 id: Arc<str>,
4531 window: &mut Window,
4532 cx: &mut Context<Self>,
4533 ) {
4534 self.code_action_providers
4535 .retain(|provider| provider.id() != id);
4536 self.refresh_code_actions(window, cx);
4537 }
4538
4539 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4540 let buffer = self.buffer.read(cx);
4541 let newest_selection = self.selections.newest_anchor().clone();
4542 if newest_selection.head().diff_base_anchor.is_some() {
4543 return None;
4544 }
4545 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4546 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4547 if start_buffer != end_buffer {
4548 return None;
4549 }
4550
4551 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4552 cx.background_executor()
4553 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4554 .await;
4555
4556 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4557 let providers = this.code_action_providers.clone();
4558 let tasks = this
4559 .code_action_providers
4560 .iter()
4561 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4562 .collect::<Vec<_>>();
4563 (providers, tasks)
4564 })?;
4565
4566 let mut actions = Vec::new();
4567 for (provider, provider_actions) in
4568 providers.into_iter().zip(future::join_all(tasks).await)
4569 {
4570 if let Some(provider_actions) = provider_actions.log_err() {
4571 actions.extend(provider_actions.into_iter().map(|action| {
4572 AvailableCodeAction {
4573 excerpt_id: newest_selection.start.excerpt_id,
4574 action,
4575 provider: provider.clone(),
4576 }
4577 }));
4578 }
4579 }
4580
4581 this.update(&mut cx, |this, cx| {
4582 this.available_code_actions = if actions.is_empty() {
4583 None
4584 } else {
4585 Some((
4586 Location {
4587 buffer: start_buffer,
4588 range: start..end,
4589 },
4590 actions.into(),
4591 ))
4592 };
4593 cx.notify();
4594 })
4595 }));
4596 None
4597 }
4598
4599 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4600 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4601 self.show_git_blame_inline = false;
4602
4603 self.show_git_blame_inline_delay_task =
4604 Some(cx.spawn_in(window, |this, mut cx| async move {
4605 cx.background_executor().timer(delay).await;
4606
4607 this.update(&mut cx, |this, cx| {
4608 this.show_git_blame_inline = true;
4609 cx.notify();
4610 })
4611 .log_err();
4612 }));
4613 }
4614 }
4615
4616 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4617 if self.pending_rename.is_some() {
4618 return None;
4619 }
4620
4621 let provider = self.semantics_provider.clone()?;
4622 let buffer = self.buffer.read(cx);
4623 let newest_selection = self.selections.newest_anchor().clone();
4624 let cursor_position = newest_selection.head();
4625 let (cursor_buffer, cursor_buffer_position) =
4626 buffer.text_anchor_for_position(cursor_position, cx)?;
4627 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4628 if cursor_buffer != tail_buffer {
4629 return None;
4630 }
4631 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4632 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4633 cx.background_executor()
4634 .timer(Duration::from_millis(debounce))
4635 .await;
4636
4637 let highlights = if let Some(highlights) = cx
4638 .update(|cx| {
4639 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4640 })
4641 .ok()
4642 .flatten()
4643 {
4644 highlights.await.log_err()
4645 } else {
4646 None
4647 };
4648
4649 if let Some(highlights) = highlights {
4650 this.update(&mut cx, |this, cx| {
4651 if this.pending_rename.is_some() {
4652 return;
4653 }
4654
4655 let buffer_id = cursor_position.buffer_id;
4656 let buffer = this.buffer.read(cx);
4657 if !buffer
4658 .text_anchor_for_position(cursor_position, cx)
4659 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4660 {
4661 return;
4662 }
4663
4664 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4665 let mut write_ranges = Vec::new();
4666 let mut read_ranges = Vec::new();
4667 for highlight in highlights {
4668 for (excerpt_id, excerpt_range) in
4669 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4670 {
4671 let start = highlight
4672 .range
4673 .start
4674 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4675 let end = highlight
4676 .range
4677 .end
4678 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4679 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4680 continue;
4681 }
4682
4683 let range = Anchor {
4684 buffer_id,
4685 excerpt_id,
4686 text_anchor: start,
4687 diff_base_anchor: None,
4688 }..Anchor {
4689 buffer_id,
4690 excerpt_id,
4691 text_anchor: end,
4692 diff_base_anchor: None,
4693 };
4694 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4695 write_ranges.push(range);
4696 } else {
4697 read_ranges.push(range);
4698 }
4699 }
4700 }
4701
4702 this.highlight_background::<DocumentHighlightRead>(
4703 &read_ranges,
4704 |theme| theme.editor_document_highlight_read_background,
4705 cx,
4706 );
4707 this.highlight_background::<DocumentHighlightWrite>(
4708 &write_ranges,
4709 |theme| theme.editor_document_highlight_write_background,
4710 cx,
4711 );
4712 cx.notify();
4713 })
4714 .log_err();
4715 }
4716 }));
4717 None
4718 }
4719
4720 pub fn refresh_selected_text_highlights(
4721 &mut self,
4722 window: &mut Window,
4723 cx: &mut Context<Editor>,
4724 ) {
4725 self.selection_highlight_task.take();
4726 if !EditorSettings::get_global(cx).selection_highlight {
4727 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4728 return;
4729 }
4730 if self.selections.count() != 1 || self.selections.line_mode {
4731 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4732 return;
4733 }
4734 let selection = self.selections.newest::<Point>(cx);
4735 if selection.is_empty() || selection.start.row != selection.end.row {
4736 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4737 return;
4738 }
4739 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4740 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4741 cx.background_executor()
4742 .timer(Duration::from_millis(debounce))
4743 .await;
4744 let Some(Some(matches_task)) = editor
4745 .update_in(&mut cx, |editor, _, cx| {
4746 if editor.selections.count() != 1 || editor.selections.line_mode {
4747 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4748 return None;
4749 }
4750 let selection = editor.selections.newest::<Point>(cx);
4751 if selection.is_empty() || selection.start.row != selection.end.row {
4752 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4753 return None;
4754 }
4755 let buffer = editor.buffer().read(cx).snapshot(cx);
4756 let query = buffer.text_for_range(selection.range()).collect::<String>();
4757 if query.trim().is_empty() {
4758 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4759 return None;
4760 }
4761 Some(cx.background_spawn(async move {
4762 let mut ranges = Vec::new();
4763 let selection_anchors = selection.range().to_anchors(&buffer);
4764 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4765 for (search_buffer, search_range, excerpt_id) in
4766 buffer.range_to_buffer_ranges(range)
4767 {
4768 ranges.extend(
4769 project::search::SearchQuery::text(
4770 query.clone(),
4771 false,
4772 false,
4773 false,
4774 Default::default(),
4775 Default::default(),
4776 None,
4777 )
4778 .unwrap()
4779 .search(search_buffer, Some(search_range.clone()))
4780 .await
4781 .into_iter()
4782 .filter_map(
4783 |match_range| {
4784 let start = search_buffer.anchor_after(
4785 search_range.start + match_range.start,
4786 );
4787 let end = search_buffer.anchor_before(
4788 search_range.start + match_range.end,
4789 );
4790 let range = Anchor::range_in_buffer(
4791 excerpt_id,
4792 search_buffer.remote_id(),
4793 start..end,
4794 );
4795 (range != selection_anchors).then_some(range)
4796 },
4797 ),
4798 );
4799 }
4800 }
4801 ranges
4802 }))
4803 })
4804 .log_err()
4805 else {
4806 return;
4807 };
4808 let matches = matches_task.await;
4809 editor
4810 .update_in(&mut cx, |editor, _, cx| {
4811 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4812 if !matches.is_empty() {
4813 editor.highlight_background::<SelectedTextHighlight>(
4814 &matches,
4815 |theme| theme.editor_document_highlight_bracket_background,
4816 cx,
4817 )
4818 }
4819 })
4820 .log_err();
4821 }));
4822 }
4823
4824 pub fn refresh_inline_completion(
4825 &mut self,
4826 debounce: bool,
4827 user_requested: bool,
4828 window: &mut Window,
4829 cx: &mut Context<Self>,
4830 ) -> Option<()> {
4831 let provider = self.edit_prediction_provider()?;
4832 let cursor = self.selections.newest_anchor().head();
4833 let (buffer, cursor_buffer_position) =
4834 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4835
4836 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4837 self.discard_inline_completion(false, cx);
4838 return None;
4839 }
4840
4841 if !user_requested
4842 && (!self.should_show_edit_predictions()
4843 || !self.is_focused(window)
4844 || buffer.read(cx).is_empty())
4845 {
4846 self.discard_inline_completion(false, cx);
4847 return None;
4848 }
4849
4850 self.update_visible_inline_completion(window, cx);
4851 provider.refresh(
4852 self.project.clone(),
4853 buffer,
4854 cursor_buffer_position,
4855 debounce,
4856 cx,
4857 );
4858 Some(())
4859 }
4860
4861 fn show_edit_predictions_in_menu(&self) -> bool {
4862 match self.edit_prediction_settings {
4863 EditPredictionSettings::Disabled => false,
4864 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4865 }
4866 }
4867
4868 pub fn edit_predictions_enabled(&self) -> bool {
4869 match self.edit_prediction_settings {
4870 EditPredictionSettings::Disabled => false,
4871 EditPredictionSettings::Enabled { .. } => true,
4872 }
4873 }
4874
4875 fn edit_prediction_requires_modifier(&self) -> bool {
4876 match self.edit_prediction_settings {
4877 EditPredictionSettings::Disabled => false,
4878 EditPredictionSettings::Enabled {
4879 preview_requires_modifier,
4880 ..
4881 } => preview_requires_modifier,
4882 }
4883 }
4884
4885 fn edit_prediction_settings_at_position(
4886 &self,
4887 buffer: &Entity<Buffer>,
4888 buffer_position: language::Anchor,
4889 cx: &App,
4890 ) -> EditPredictionSettings {
4891 if self.mode != EditorMode::Full
4892 || !self.show_inline_completions_override.unwrap_or(true)
4893 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4894 {
4895 return EditPredictionSettings::Disabled;
4896 }
4897
4898 let buffer = buffer.read(cx);
4899
4900 let file = buffer.file();
4901
4902 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4903 return EditPredictionSettings::Disabled;
4904 };
4905
4906 let by_provider = matches!(
4907 self.menu_inline_completions_policy,
4908 MenuInlineCompletionsPolicy::ByProvider
4909 );
4910
4911 let show_in_menu = by_provider
4912 && self
4913 .edit_prediction_provider
4914 .as_ref()
4915 .map_or(false, |provider| {
4916 provider.provider.show_completions_in_menu()
4917 });
4918
4919 let preview_requires_modifier =
4920 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4921
4922 EditPredictionSettings::Enabled {
4923 show_in_menu,
4924 preview_requires_modifier,
4925 }
4926 }
4927
4928 fn should_show_edit_predictions(&self) -> bool {
4929 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4930 }
4931
4932 pub fn edit_prediction_preview_is_active(&self) -> bool {
4933 matches!(
4934 self.edit_prediction_preview,
4935 EditPredictionPreview::Active { .. }
4936 )
4937 }
4938
4939 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4940 let cursor = self.selections.newest_anchor().head();
4941 if let Some((buffer, cursor_position)) =
4942 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4943 {
4944 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4945 } else {
4946 false
4947 }
4948 }
4949
4950 fn inline_completions_enabled_in_buffer(
4951 &self,
4952 buffer: &Entity<Buffer>,
4953 buffer_position: language::Anchor,
4954 cx: &App,
4955 ) -> bool {
4956 maybe!({
4957 let provider = self.edit_prediction_provider()?;
4958 if !provider.is_enabled(&buffer, buffer_position, cx) {
4959 return Some(false);
4960 }
4961 let buffer = buffer.read(cx);
4962 let Some(file) = buffer.file() else {
4963 return Some(true);
4964 };
4965 let settings = all_language_settings(Some(file), cx);
4966 Some(settings.inline_completions_enabled_for_path(file.path()))
4967 })
4968 .unwrap_or(false)
4969 }
4970
4971 fn cycle_inline_completion(
4972 &mut self,
4973 direction: Direction,
4974 window: &mut Window,
4975 cx: &mut Context<Self>,
4976 ) -> Option<()> {
4977 let provider = self.edit_prediction_provider()?;
4978 let cursor = self.selections.newest_anchor().head();
4979 let (buffer, cursor_buffer_position) =
4980 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4981 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4982 return None;
4983 }
4984
4985 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4986 self.update_visible_inline_completion(window, cx);
4987
4988 Some(())
4989 }
4990
4991 pub fn show_inline_completion(
4992 &mut self,
4993 _: &ShowEditPrediction,
4994 window: &mut Window,
4995 cx: &mut Context<Self>,
4996 ) {
4997 if !self.has_active_inline_completion() {
4998 self.refresh_inline_completion(false, true, window, cx);
4999 return;
5000 }
5001
5002 self.update_visible_inline_completion(window, cx);
5003 }
5004
5005 pub fn display_cursor_names(
5006 &mut self,
5007 _: &DisplayCursorNames,
5008 window: &mut Window,
5009 cx: &mut Context<Self>,
5010 ) {
5011 self.show_cursor_names(window, cx);
5012 }
5013
5014 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5015 self.show_cursor_names = true;
5016 cx.notify();
5017 cx.spawn_in(window, |this, mut cx| async move {
5018 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5019 this.update(&mut cx, |this, cx| {
5020 this.show_cursor_names = false;
5021 cx.notify()
5022 })
5023 .ok()
5024 })
5025 .detach();
5026 }
5027
5028 pub fn next_edit_prediction(
5029 &mut self,
5030 _: &NextEditPrediction,
5031 window: &mut Window,
5032 cx: &mut Context<Self>,
5033 ) {
5034 if self.has_active_inline_completion() {
5035 self.cycle_inline_completion(Direction::Next, window, cx);
5036 } else {
5037 let is_copilot_disabled = self
5038 .refresh_inline_completion(false, true, window, cx)
5039 .is_none();
5040 if is_copilot_disabled {
5041 cx.propagate();
5042 }
5043 }
5044 }
5045
5046 pub fn previous_edit_prediction(
5047 &mut self,
5048 _: &PreviousEditPrediction,
5049 window: &mut Window,
5050 cx: &mut Context<Self>,
5051 ) {
5052 if self.has_active_inline_completion() {
5053 self.cycle_inline_completion(Direction::Prev, window, cx);
5054 } else {
5055 let is_copilot_disabled = self
5056 .refresh_inline_completion(false, true, window, cx)
5057 .is_none();
5058 if is_copilot_disabled {
5059 cx.propagate();
5060 }
5061 }
5062 }
5063
5064 pub fn accept_edit_prediction(
5065 &mut self,
5066 _: &AcceptEditPrediction,
5067 window: &mut Window,
5068 cx: &mut Context<Self>,
5069 ) {
5070 if self.show_edit_predictions_in_menu() {
5071 self.hide_context_menu(window, cx);
5072 }
5073
5074 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5075 return;
5076 };
5077
5078 self.report_inline_completion_event(
5079 active_inline_completion.completion_id.clone(),
5080 true,
5081 cx,
5082 );
5083
5084 match &active_inline_completion.completion {
5085 InlineCompletion::Move { target, .. } => {
5086 let target = *target;
5087
5088 if let Some(position_map) = &self.last_position_map {
5089 if position_map
5090 .visible_row_range
5091 .contains(&target.to_display_point(&position_map.snapshot).row())
5092 || !self.edit_prediction_requires_modifier()
5093 {
5094 self.unfold_ranges(&[target..target], true, false, cx);
5095 // Note that this is also done in vim's handler of the Tab action.
5096 self.change_selections(
5097 Some(Autoscroll::newest()),
5098 window,
5099 cx,
5100 |selections| {
5101 selections.select_anchor_ranges([target..target]);
5102 },
5103 );
5104 self.clear_row_highlights::<EditPredictionPreview>();
5105
5106 self.edit_prediction_preview = EditPredictionPreview::Active {
5107 previous_scroll_position: None,
5108 };
5109 } else {
5110 self.edit_prediction_preview = EditPredictionPreview::Active {
5111 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5112 };
5113 self.highlight_rows::<EditPredictionPreview>(
5114 target..target,
5115 cx.theme().colors().editor_highlighted_line_background,
5116 true,
5117 cx,
5118 );
5119 self.request_autoscroll(Autoscroll::fit(), cx);
5120 }
5121 }
5122 }
5123 InlineCompletion::Edit { edits, .. } => {
5124 if let Some(provider) = self.edit_prediction_provider() {
5125 provider.accept(cx);
5126 }
5127
5128 let snapshot = self.buffer.read(cx).snapshot(cx);
5129 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5130
5131 self.buffer.update(cx, |buffer, cx| {
5132 buffer.edit(edits.iter().cloned(), None, cx)
5133 });
5134
5135 self.change_selections(None, window, cx, |s| {
5136 s.select_anchor_ranges([last_edit_end..last_edit_end])
5137 });
5138
5139 self.update_visible_inline_completion(window, cx);
5140 if self.active_inline_completion.is_none() {
5141 self.refresh_inline_completion(true, true, window, cx);
5142 }
5143
5144 cx.notify();
5145 }
5146 }
5147
5148 self.edit_prediction_requires_modifier_in_leading_space = false;
5149 }
5150
5151 pub fn accept_partial_inline_completion(
5152 &mut self,
5153 _: &AcceptPartialEditPrediction,
5154 window: &mut Window,
5155 cx: &mut Context<Self>,
5156 ) {
5157 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5158 return;
5159 };
5160 if self.selections.count() != 1 {
5161 return;
5162 }
5163
5164 self.report_inline_completion_event(
5165 active_inline_completion.completion_id.clone(),
5166 true,
5167 cx,
5168 );
5169
5170 match &active_inline_completion.completion {
5171 InlineCompletion::Move { target, .. } => {
5172 let target = *target;
5173 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5174 selections.select_anchor_ranges([target..target]);
5175 });
5176 }
5177 InlineCompletion::Edit { edits, .. } => {
5178 // Find an insertion that starts at the cursor position.
5179 let snapshot = self.buffer.read(cx).snapshot(cx);
5180 let cursor_offset = self.selections.newest::<usize>(cx).head();
5181 let insertion = edits.iter().find_map(|(range, text)| {
5182 let range = range.to_offset(&snapshot);
5183 if range.is_empty() && range.start == cursor_offset {
5184 Some(text)
5185 } else {
5186 None
5187 }
5188 });
5189
5190 if let Some(text) = insertion {
5191 let mut partial_completion = text
5192 .chars()
5193 .by_ref()
5194 .take_while(|c| c.is_alphabetic())
5195 .collect::<String>();
5196 if partial_completion.is_empty() {
5197 partial_completion = text
5198 .chars()
5199 .by_ref()
5200 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5201 .collect::<String>();
5202 }
5203
5204 cx.emit(EditorEvent::InputHandled {
5205 utf16_range_to_replace: None,
5206 text: partial_completion.clone().into(),
5207 });
5208
5209 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5210
5211 self.refresh_inline_completion(true, true, window, cx);
5212 cx.notify();
5213 } else {
5214 self.accept_edit_prediction(&Default::default(), window, cx);
5215 }
5216 }
5217 }
5218 }
5219
5220 fn discard_inline_completion(
5221 &mut self,
5222 should_report_inline_completion_event: bool,
5223 cx: &mut Context<Self>,
5224 ) -> bool {
5225 if should_report_inline_completion_event {
5226 let completion_id = self
5227 .active_inline_completion
5228 .as_ref()
5229 .and_then(|active_completion| active_completion.completion_id.clone());
5230
5231 self.report_inline_completion_event(completion_id, false, cx);
5232 }
5233
5234 if let Some(provider) = self.edit_prediction_provider() {
5235 provider.discard(cx);
5236 }
5237
5238 self.take_active_inline_completion(cx)
5239 }
5240
5241 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5242 let Some(provider) = self.edit_prediction_provider() else {
5243 return;
5244 };
5245
5246 let Some((_, buffer, _)) = self
5247 .buffer
5248 .read(cx)
5249 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5250 else {
5251 return;
5252 };
5253
5254 let extension = buffer
5255 .read(cx)
5256 .file()
5257 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5258
5259 let event_type = match accepted {
5260 true => "Edit Prediction Accepted",
5261 false => "Edit Prediction Discarded",
5262 };
5263 telemetry::event!(
5264 event_type,
5265 provider = provider.name(),
5266 prediction_id = id,
5267 suggestion_accepted = accepted,
5268 file_extension = extension,
5269 );
5270 }
5271
5272 pub fn has_active_inline_completion(&self) -> bool {
5273 self.active_inline_completion.is_some()
5274 }
5275
5276 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5277 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5278 return false;
5279 };
5280
5281 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5282 self.clear_highlights::<InlineCompletionHighlight>(cx);
5283 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5284 true
5285 }
5286
5287 /// Returns true when we're displaying the edit prediction popover below the cursor
5288 /// like we are not previewing and the LSP autocomplete menu is visible
5289 /// or we are in `when_holding_modifier` mode.
5290 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5291 if self.edit_prediction_preview_is_active()
5292 || !self.show_edit_predictions_in_menu()
5293 || !self.edit_predictions_enabled()
5294 {
5295 return false;
5296 }
5297
5298 if self.has_visible_completions_menu() {
5299 return true;
5300 }
5301
5302 has_completion && self.edit_prediction_requires_modifier()
5303 }
5304
5305 fn handle_modifiers_changed(
5306 &mut self,
5307 modifiers: Modifiers,
5308 position_map: &PositionMap,
5309 window: &mut Window,
5310 cx: &mut Context<Self>,
5311 ) {
5312 if self.show_edit_predictions_in_menu() {
5313 self.update_edit_prediction_preview(&modifiers, window, cx);
5314 }
5315
5316 self.update_selection_mode(&modifiers, position_map, window, cx);
5317
5318 let mouse_position = window.mouse_position();
5319 if !position_map.text_hitbox.is_hovered(window) {
5320 return;
5321 }
5322
5323 self.update_hovered_link(
5324 position_map.point_for_position(mouse_position),
5325 &position_map.snapshot,
5326 modifiers,
5327 window,
5328 cx,
5329 )
5330 }
5331
5332 fn update_selection_mode(
5333 &mut self,
5334 modifiers: &Modifiers,
5335 position_map: &PositionMap,
5336 window: &mut Window,
5337 cx: &mut Context<Self>,
5338 ) {
5339 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5340 return;
5341 }
5342
5343 let mouse_position = window.mouse_position();
5344 let point_for_position = position_map.point_for_position(mouse_position);
5345 let position = point_for_position.previous_valid;
5346
5347 self.select(
5348 SelectPhase::BeginColumnar {
5349 position,
5350 reset: false,
5351 goal_column: point_for_position.exact_unclipped.column(),
5352 },
5353 window,
5354 cx,
5355 );
5356 }
5357
5358 fn update_edit_prediction_preview(
5359 &mut self,
5360 modifiers: &Modifiers,
5361 window: &mut Window,
5362 cx: &mut Context<Self>,
5363 ) {
5364 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5365 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5366 return;
5367 };
5368
5369 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5370 if matches!(
5371 self.edit_prediction_preview,
5372 EditPredictionPreview::Inactive
5373 ) {
5374 self.edit_prediction_preview = EditPredictionPreview::Active {
5375 previous_scroll_position: None,
5376 };
5377
5378 self.update_visible_inline_completion(window, cx);
5379 cx.notify();
5380 }
5381 } else if let EditPredictionPreview::Active {
5382 previous_scroll_position,
5383 } = self.edit_prediction_preview
5384 {
5385 if let (Some(previous_scroll_position), Some(position_map)) =
5386 (previous_scroll_position, self.last_position_map.as_ref())
5387 {
5388 self.set_scroll_position(
5389 previous_scroll_position
5390 .scroll_position(&position_map.snapshot.display_snapshot),
5391 window,
5392 cx,
5393 );
5394 }
5395
5396 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5397 self.clear_row_highlights::<EditPredictionPreview>();
5398 self.update_visible_inline_completion(window, cx);
5399 cx.notify();
5400 }
5401 }
5402
5403 fn update_visible_inline_completion(
5404 &mut self,
5405 _window: &mut Window,
5406 cx: &mut Context<Self>,
5407 ) -> Option<()> {
5408 let selection = self.selections.newest_anchor();
5409 let cursor = selection.head();
5410 let multibuffer = self.buffer.read(cx).snapshot(cx);
5411 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5412 let excerpt_id = cursor.excerpt_id;
5413
5414 let show_in_menu = self.show_edit_predictions_in_menu();
5415 let completions_menu_has_precedence = !show_in_menu
5416 && (self.context_menu.borrow().is_some()
5417 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5418
5419 if completions_menu_has_precedence
5420 || !offset_selection.is_empty()
5421 || self
5422 .active_inline_completion
5423 .as_ref()
5424 .map_or(false, |completion| {
5425 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5426 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5427 !invalidation_range.contains(&offset_selection.head())
5428 })
5429 {
5430 self.discard_inline_completion(false, cx);
5431 return None;
5432 }
5433
5434 self.take_active_inline_completion(cx);
5435 let Some(provider) = self.edit_prediction_provider() else {
5436 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5437 return None;
5438 };
5439
5440 let (buffer, cursor_buffer_position) =
5441 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5442
5443 self.edit_prediction_settings =
5444 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5445
5446 self.edit_prediction_cursor_on_leading_whitespace =
5447 multibuffer.is_line_whitespace_upto(cursor);
5448
5449 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5450 let edits = inline_completion
5451 .edits
5452 .into_iter()
5453 .flat_map(|(range, new_text)| {
5454 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5455 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5456 Some((start..end, new_text))
5457 })
5458 .collect::<Vec<_>>();
5459 if edits.is_empty() {
5460 return None;
5461 }
5462
5463 let first_edit_start = edits.first().unwrap().0.start;
5464 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5465 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5466
5467 let last_edit_end = edits.last().unwrap().0.end;
5468 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5469 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5470
5471 let cursor_row = cursor.to_point(&multibuffer).row;
5472
5473 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5474
5475 let mut inlay_ids = Vec::new();
5476 let invalidation_row_range;
5477 let move_invalidation_row_range = if cursor_row < edit_start_row {
5478 Some(cursor_row..edit_end_row)
5479 } else if cursor_row > edit_end_row {
5480 Some(edit_start_row..cursor_row)
5481 } else {
5482 None
5483 };
5484 let is_move =
5485 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5486 let completion = if is_move {
5487 invalidation_row_range =
5488 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5489 let target = first_edit_start;
5490 InlineCompletion::Move { target, snapshot }
5491 } else {
5492 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5493 && !self.inline_completions_hidden_for_vim_mode;
5494
5495 if show_completions_in_buffer {
5496 if edits
5497 .iter()
5498 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5499 {
5500 let mut inlays = Vec::new();
5501 for (range, new_text) in &edits {
5502 let inlay = Inlay::inline_completion(
5503 post_inc(&mut self.next_inlay_id),
5504 range.start,
5505 new_text.as_str(),
5506 );
5507 inlay_ids.push(inlay.id);
5508 inlays.push(inlay);
5509 }
5510
5511 self.splice_inlays(&[], inlays, cx);
5512 } else {
5513 let background_color = cx.theme().status().deleted_background;
5514 self.highlight_text::<InlineCompletionHighlight>(
5515 edits.iter().map(|(range, _)| range.clone()).collect(),
5516 HighlightStyle {
5517 background_color: Some(background_color),
5518 ..Default::default()
5519 },
5520 cx,
5521 );
5522 }
5523 }
5524
5525 invalidation_row_range = edit_start_row..edit_end_row;
5526
5527 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5528 if provider.show_tab_accept_marker() {
5529 EditDisplayMode::TabAccept
5530 } else {
5531 EditDisplayMode::Inline
5532 }
5533 } else {
5534 EditDisplayMode::DiffPopover
5535 };
5536
5537 InlineCompletion::Edit {
5538 edits,
5539 edit_preview: inline_completion.edit_preview,
5540 display_mode,
5541 snapshot,
5542 }
5543 };
5544
5545 let invalidation_range = multibuffer
5546 .anchor_before(Point::new(invalidation_row_range.start, 0))
5547 ..multibuffer.anchor_after(Point::new(
5548 invalidation_row_range.end,
5549 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5550 ));
5551
5552 self.stale_inline_completion_in_menu = None;
5553 self.active_inline_completion = Some(InlineCompletionState {
5554 inlay_ids,
5555 completion,
5556 completion_id: inline_completion.id,
5557 invalidation_range,
5558 });
5559
5560 cx.notify();
5561
5562 Some(())
5563 }
5564
5565 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5566 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5567 }
5568
5569 fn render_code_actions_indicator(
5570 &self,
5571 _style: &EditorStyle,
5572 row: DisplayRow,
5573 is_active: bool,
5574 cx: &mut Context<Self>,
5575 ) -> Option<IconButton> {
5576 if self.available_code_actions.is_some() {
5577 Some(
5578 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5579 .shape(ui::IconButtonShape::Square)
5580 .icon_size(IconSize::XSmall)
5581 .icon_color(Color::Muted)
5582 .toggle_state(is_active)
5583 .tooltip({
5584 let focus_handle = self.focus_handle.clone();
5585 move |window, cx| {
5586 Tooltip::for_action_in(
5587 "Toggle Code Actions",
5588 &ToggleCodeActions {
5589 deployed_from_indicator: None,
5590 },
5591 &focus_handle,
5592 window,
5593 cx,
5594 )
5595 }
5596 })
5597 .on_click(cx.listener(move |editor, _e, window, cx| {
5598 window.focus(&editor.focus_handle(cx));
5599 editor.toggle_code_actions(
5600 &ToggleCodeActions {
5601 deployed_from_indicator: Some(row),
5602 },
5603 window,
5604 cx,
5605 );
5606 })),
5607 )
5608 } else {
5609 None
5610 }
5611 }
5612
5613 fn clear_tasks(&mut self) {
5614 self.tasks.clear()
5615 }
5616
5617 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5618 if self.tasks.insert(key, value).is_some() {
5619 // This case should hopefully be rare, but just in case...
5620 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5621 }
5622 }
5623
5624 fn build_tasks_context(
5625 project: &Entity<Project>,
5626 buffer: &Entity<Buffer>,
5627 buffer_row: u32,
5628 tasks: &Arc<RunnableTasks>,
5629 cx: &mut Context<Self>,
5630 ) -> Task<Option<task::TaskContext>> {
5631 let position = Point::new(buffer_row, tasks.column);
5632 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5633 let location = Location {
5634 buffer: buffer.clone(),
5635 range: range_start..range_start,
5636 };
5637 // Fill in the environmental variables from the tree-sitter captures
5638 let mut captured_task_variables = TaskVariables::default();
5639 for (capture_name, value) in tasks.extra_variables.clone() {
5640 captured_task_variables.insert(
5641 task::VariableName::Custom(capture_name.into()),
5642 value.clone(),
5643 );
5644 }
5645 project.update(cx, |project, cx| {
5646 project.task_store().update(cx, |task_store, cx| {
5647 task_store.task_context_for_location(captured_task_variables, location, cx)
5648 })
5649 })
5650 }
5651
5652 pub fn spawn_nearest_task(
5653 &mut self,
5654 action: &SpawnNearestTask,
5655 window: &mut Window,
5656 cx: &mut Context<Self>,
5657 ) {
5658 let Some((workspace, _)) = self.workspace.clone() else {
5659 return;
5660 };
5661 let Some(project) = self.project.clone() else {
5662 return;
5663 };
5664
5665 // Try to find a closest, enclosing node using tree-sitter that has a
5666 // task
5667 let Some((buffer, buffer_row, tasks)) = self
5668 .find_enclosing_node_task(cx)
5669 // Or find the task that's closest in row-distance.
5670 .or_else(|| self.find_closest_task(cx))
5671 else {
5672 return;
5673 };
5674
5675 let reveal_strategy = action.reveal;
5676 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5677 cx.spawn_in(window, |_, mut cx| async move {
5678 let context = task_context.await?;
5679 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5680
5681 let resolved = resolved_task.resolved.as_mut()?;
5682 resolved.reveal = reveal_strategy;
5683
5684 workspace
5685 .update(&mut cx, |workspace, cx| {
5686 workspace::tasks::schedule_resolved_task(
5687 workspace,
5688 task_source_kind,
5689 resolved_task,
5690 false,
5691 cx,
5692 );
5693 })
5694 .ok()
5695 })
5696 .detach();
5697 }
5698
5699 fn find_closest_task(
5700 &mut self,
5701 cx: &mut Context<Self>,
5702 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5703 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5704
5705 let ((buffer_id, row), tasks) = self
5706 .tasks
5707 .iter()
5708 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5709
5710 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5711 let tasks = Arc::new(tasks.to_owned());
5712 Some((buffer, *row, tasks))
5713 }
5714
5715 fn find_enclosing_node_task(
5716 &mut self,
5717 cx: &mut Context<Self>,
5718 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5719 let snapshot = self.buffer.read(cx).snapshot(cx);
5720 let offset = self.selections.newest::<usize>(cx).head();
5721 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5722 let buffer_id = excerpt.buffer().remote_id();
5723
5724 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5725 let mut cursor = layer.node().walk();
5726
5727 while cursor.goto_first_child_for_byte(offset).is_some() {
5728 if cursor.node().end_byte() == offset {
5729 cursor.goto_next_sibling();
5730 }
5731 }
5732
5733 // Ascend to the smallest ancestor that contains the range and has a task.
5734 loop {
5735 let node = cursor.node();
5736 let node_range = node.byte_range();
5737 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5738
5739 // Check if this node contains our offset
5740 if node_range.start <= offset && node_range.end >= offset {
5741 // If it contains offset, check for task
5742 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5743 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5744 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5745 }
5746 }
5747
5748 if !cursor.goto_parent() {
5749 break;
5750 }
5751 }
5752 None
5753 }
5754
5755 fn render_run_indicator(
5756 &self,
5757 _style: &EditorStyle,
5758 is_active: bool,
5759 row: DisplayRow,
5760 cx: &mut Context<Self>,
5761 ) -> IconButton {
5762 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5763 .shape(ui::IconButtonShape::Square)
5764 .icon_size(IconSize::XSmall)
5765 .icon_color(Color::Muted)
5766 .toggle_state(is_active)
5767 .on_click(cx.listener(move |editor, _e, window, cx| {
5768 window.focus(&editor.focus_handle(cx));
5769 editor.toggle_code_actions(
5770 &ToggleCodeActions {
5771 deployed_from_indicator: Some(row),
5772 },
5773 window,
5774 cx,
5775 );
5776 }))
5777 }
5778
5779 pub fn context_menu_visible(&self) -> bool {
5780 !self.edit_prediction_preview_is_active()
5781 && self
5782 .context_menu
5783 .borrow()
5784 .as_ref()
5785 .map_or(false, |menu| menu.visible())
5786 }
5787
5788 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5789 self.context_menu
5790 .borrow()
5791 .as_ref()
5792 .map(|menu| menu.origin())
5793 }
5794
5795 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5796 px(30.)
5797 }
5798
5799 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5800 if self.read_only(cx) {
5801 cx.theme().players().read_only()
5802 } else {
5803 self.style.as_ref().unwrap().local_player
5804 }
5805 }
5806
5807 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5808 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5809 let accept_keystroke = accept_binding.keystroke()?;
5810
5811 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5812
5813 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5814 Color::Accent
5815 } else {
5816 Color::Muted
5817 };
5818
5819 h_flex()
5820 .px_0p5()
5821 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5822 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5823 .text_size(TextSize::XSmall.rems(cx))
5824 .child(h_flex().children(ui::render_modifiers(
5825 &accept_keystroke.modifiers,
5826 PlatformStyle::platform(),
5827 Some(modifiers_color),
5828 Some(IconSize::XSmall.rems().into()),
5829 true,
5830 )))
5831 .when(is_platform_style_mac, |parent| {
5832 parent.child(accept_keystroke.key.clone())
5833 })
5834 .when(!is_platform_style_mac, |parent| {
5835 parent.child(
5836 Key::new(
5837 util::capitalize(&accept_keystroke.key),
5838 Some(Color::Default),
5839 )
5840 .size(Some(IconSize::XSmall.rems().into())),
5841 )
5842 })
5843 .into()
5844 }
5845
5846 fn render_edit_prediction_line_popover(
5847 &self,
5848 label: impl Into<SharedString>,
5849 icon: Option<IconName>,
5850 window: &mut Window,
5851 cx: &App,
5852 ) -> Option<Div> {
5853 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5854
5855 let result = h_flex()
5856 .py_0p5()
5857 .pl_1()
5858 .pr(padding_right)
5859 .gap_1()
5860 .rounded(px(6.))
5861 .border_1()
5862 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5863 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5864 .shadow_sm()
5865 .children(self.render_edit_prediction_accept_keybind(window, cx))
5866 .child(Label::new(label).size(LabelSize::Small))
5867 .when_some(icon, |element, icon| {
5868 element.child(
5869 div()
5870 .mt(px(1.5))
5871 .child(Icon::new(icon).size(IconSize::Small)),
5872 )
5873 });
5874
5875 Some(result)
5876 }
5877
5878 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5879 let accent_color = cx.theme().colors().text_accent;
5880 let editor_bg_color = cx.theme().colors().editor_background;
5881 editor_bg_color.blend(accent_color.opacity(0.1))
5882 }
5883
5884 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5885 let accent_color = cx.theme().colors().text_accent;
5886 let editor_bg_color = cx.theme().colors().editor_background;
5887 editor_bg_color.blend(accent_color.opacity(0.6))
5888 }
5889
5890 #[allow(clippy::too_many_arguments)]
5891 fn render_edit_prediction_cursor_popover(
5892 &self,
5893 min_width: Pixels,
5894 max_width: Pixels,
5895 cursor_point: Point,
5896 style: &EditorStyle,
5897 accept_keystroke: Option<&gpui::Keystroke>,
5898 _window: &Window,
5899 cx: &mut Context<Editor>,
5900 ) -> Option<AnyElement> {
5901 let provider = self.edit_prediction_provider.as_ref()?;
5902
5903 if provider.provider.needs_terms_acceptance(cx) {
5904 return Some(
5905 h_flex()
5906 .min_w(min_width)
5907 .flex_1()
5908 .px_2()
5909 .py_1()
5910 .gap_3()
5911 .elevation_2(cx)
5912 .hover(|style| style.bg(cx.theme().colors().element_hover))
5913 .id("accept-terms")
5914 .cursor_pointer()
5915 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5916 .on_click(cx.listener(|this, _event, window, cx| {
5917 cx.stop_propagation();
5918 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5919 window.dispatch_action(
5920 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5921 cx,
5922 );
5923 }))
5924 .child(
5925 h_flex()
5926 .flex_1()
5927 .gap_2()
5928 .child(Icon::new(IconName::ZedPredict))
5929 .child(Label::new("Accept Terms of Service"))
5930 .child(div().w_full())
5931 .child(
5932 Icon::new(IconName::ArrowUpRight)
5933 .color(Color::Muted)
5934 .size(IconSize::Small),
5935 )
5936 .into_any_element(),
5937 )
5938 .into_any(),
5939 );
5940 }
5941
5942 let is_refreshing = provider.provider.is_refreshing(cx);
5943
5944 fn pending_completion_container() -> Div {
5945 h_flex()
5946 .h_full()
5947 .flex_1()
5948 .gap_2()
5949 .child(Icon::new(IconName::ZedPredict))
5950 }
5951
5952 let completion = match &self.active_inline_completion {
5953 Some(completion) => match &completion.completion {
5954 InlineCompletion::Move {
5955 target, snapshot, ..
5956 } if !self.has_visible_completions_menu() => {
5957 use text::ToPoint as _;
5958
5959 return Some(
5960 h_flex()
5961 .px_2()
5962 .py_1()
5963 .gap_2()
5964 .elevation_2(cx)
5965 .border_color(cx.theme().colors().border)
5966 .rounded(px(6.))
5967 .rounded_tl(px(0.))
5968 .child(
5969 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5970 Icon::new(IconName::ZedPredictDown)
5971 } else {
5972 Icon::new(IconName::ZedPredictUp)
5973 },
5974 )
5975 .child(Label::new("Hold").size(LabelSize::Small))
5976 .child(h_flex().children(ui::render_modifiers(
5977 &accept_keystroke?.modifiers,
5978 PlatformStyle::platform(),
5979 Some(Color::Default),
5980 Some(IconSize::Small.rems().into()),
5981 false,
5982 )))
5983 .into_any(),
5984 );
5985 }
5986 _ => self.render_edit_prediction_cursor_popover_preview(
5987 completion,
5988 cursor_point,
5989 style,
5990 cx,
5991 )?,
5992 },
5993
5994 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5995 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5996 stale_completion,
5997 cursor_point,
5998 style,
5999 cx,
6000 )?,
6001
6002 None => {
6003 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6004 }
6005 },
6006
6007 None => pending_completion_container().child(Label::new("No Prediction")),
6008 };
6009
6010 let completion = if is_refreshing {
6011 completion
6012 .with_animation(
6013 "loading-completion",
6014 Animation::new(Duration::from_secs(2))
6015 .repeat()
6016 .with_easing(pulsating_between(0.4, 0.8)),
6017 |label, delta| label.opacity(delta),
6018 )
6019 .into_any_element()
6020 } else {
6021 completion.into_any_element()
6022 };
6023
6024 let has_completion = self.active_inline_completion.is_some();
6025
6026 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6027 Some(
6028 h_flex()
6029 .min_w(min_width)
6030 .max_w(max_width)
6031 .flex_1()
6032 .elevation_2(cx)
6033 .border_color(cx.theme().colors().border)
6034 .child(
6035 div()
6036 .flex_1()
6037 .py_1()
6038 .px_2()
6039 .overflow_hidden()
6040 .child(completion),
6041 )
6042 .when_some(accept_keystroke, |el, accept_keystroke| {
6043 if !accept_keystroke.modifiers.modified() {
6044 return el;
6045 }
6046
6047 el.child(
6048 h_flex()
6049 .h_full()
6050 .border_l_1()
6051 .rounded_r_lg()
6052 .border_color(cx.theme().colors().border)
6053 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6054 .gap_1()
6055 .py_1()
6056 .px_2()
6057 .child(
6058 h_flex()
6059 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6060 .when(is_platform_style_mac, |parent| parent.gap_1())
6061 .child(h_flex().children(ui::render_modifiers(
6062 &accept_keystroke.modifiers,
6063 PlatformStyle::platform(),
6064 Some(if !has_completion {
6065 Color::Muted
6066 } else {
6067 Color::Default
6068 }),
6069 None,
6070 false,
6071 ))),
6072 )
6073 .child(Label::new("Preview").into_any_element())
6074 .opacity(if has_completion { 1.0 } else { 0.4 }),
6075 )
6076 })
6077 .into_any(),
6078 )
6079 }
6080
6081 fn render_edit_prediction_cursor_popover_preview(
6082 &self,
6083 completion: &InlineCompletionState,
6084 cursor_point: Point,
6085 style: &EditorStyle,
6086 cx: &mut Context<Editor>,
6087 ) -> Option<Div> {
6088 use text::ToPoint as _;
6089
6090 fn render_relative_row_jump(
6091 prefix: impl Into<String>,
6092 current_row: u32,
6093 target_row: u32,
6094 ) -> Div {
6095 let (row_diff, arrow) = if target_row < current_row {
6096 (current_row - target_row, IconName::ArrowUp)
6097 } else {
6098 (target_row - current_row, IconName::ArrowDown)
6099 };
6100
6101 h_flex()
6102 .child(
6103 Label::new(format!("{}{}", prefix.into(), row_diff))
6104 .color(Color::Muted)
6105 .size(LabelSize::Small),
6106 )
6107 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6108 }
6109
6110 match &completion.completion {
6111 InlineCompletion::Move {
6112 target, snapshot, ..
6113 } => Some(
6114 h_flex()
6115 .px_2()
6116 .gap_2()
6117 .flex_1()
6118 .child(
6119 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6120 Icon::new(IconName::ZedPredictDown)
6121 } else {
6122 Icon::new(IconName::ZedPredictUp)
6123 },
6124 )
6125 .child(Label::new("Jump to Edit")),
6126 ),
6127
6128 InlineCompletion::Edit {
6129 edits,
6130 edit_preview,
6131 snapshot,
6132 display_mode: _,
6133 } => {
6134 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6135
6136 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6137 &snapshot,
6138 &edits,
6139 edit_preview.as_ref()?,
6140 true,
6141 cx,
6142 )
6143 .first_line_preview();
6144
6145 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6146 .with_highlights(&style.text, highlighted_edits.highlights);
6147
6148 let preview = h_flex()
6149 .gap_1()
6150 .min_w_16()
6151 .child(styled_text)
6152 .when(has_more_lines, |parent| parent.child("…"));
6153
6154 let left = if first_edit_row != cursor_point.row {
6155 render_relative_row_jump("", cursor_point.row, first_edit_row)
6156 .into_any_element()
6157 } else {
6158 Icon::new(IconName::ZedPredict).into_any_element()
6159 };
6160
6161 Some(
6162 h_flex()
6163 .h_full()
6164 .flex_1()
6165 .gap_2()
6166 .pr_1()
6167 .overflow_x_hidden()
6168 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6169 .child(left)
6170 .child(preview),
6171 )
6172 }
6173 }
6174 }
6175
6176 fn render_context_menu(
6177 &self,
6178 style: &EditorStyle,
6179 max_height_in_lines: u32,
6180 y_flipped: bool,
6181 window: &mut Window,
6182 cx: &mut Context<Editor>,
6183 ) -> Option<AnyElement> {
6184 let menu = self.context_menu.borrow();
6185 let menu = menu.as_ref()?;
6186 if !menu.visible() {
6187 return None;
6188 };
6189 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6190 }
6191
6192 fn render_context_menu_aside(
6193 &mut self,
6194 max_size: Size<Pixels>,
6195 window: &mut Window,
6196 cx: &mut Context<Editor>,
6197 ) -> Option<AnyElement> {
6198 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6199 if menu.visible() {
6200 menu.render_aside(self, max_size, window, cx)
6201 } else {
6202 None
6203 }
6204 })
6205 }
6206
6207 fn hide_context_menu(
6208 &mut self,
6209 window: &mut Window,
6210 cx: &mut Context<Self>,
6211 ) -> Option<CodeContextMenu> {
6212 cx.notify();
6213 self.completion_tasks.clear();
6214 let context_menu = self.context_menu.borrow_mut().take();
6215 self.stale_inline_completion_in_menu.take();
6216 self.update_visible_inline_completion(window, cx);
6217 context_menu
6218 }
6219
6220 fn show_snippet_choices(
6221 &mut self,
6222 choices: &Vec<String>,
6223 selection: Range<Anchor>,
6224 cx: &mut Context<Self>,
6225 ) {
6226 if selection.start.buffer_id.is_none() {
6227 return;
6228 }
6229 let buffer_id = selection.start.buffer_id.unwrap();
6230 let buffer = self.buffer().read(cx).buffer(buffer_id);
6231 let id = post_inc(&mut self.next_completion_id);
6232
6233 if let Some(buffer) = buffer {
6234 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6235 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6236 ));
6237 }
6238 }
6239
6240 pub fn insert_snippet(
6241 &mut self,
6242 insertion_ranges: &[Range<usize>],
6243 snippet: Snippet,
6244 window: &mut Window,
6245 cx: &mut Context<Self>,
6246 ) -> Result<()> {
6247 struct Tabstop<T> {
6248 is_end_tabstop: bool,
6249 ranges: Vec<Range<T>>,
6250 choices: Option<Vec<String>>,
6251 }
6252
6253 let tabstops = self.buffer.update(cx, |buffer, cx| {
6254 let snippet_text: Arc<str> = snippet.text.clone().into();
6255 buffer.edit(
6256 insertion_ranges
6257 .iter()
6258 .cloned()
6259 .map(|range| (range, snippet_text.clone())),
6260 Some(AutoindentMode::EachLine),
6261 cx,
6262 );
6263
6264 let snapshot = &*buffer.read(cx);
6265 let snippet = &snippet;
6266 snippet
6267 .tabstops
6268 .iter()
6269 .map(|tabstop| {
6270 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6271 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6272 });
6273 let mut tabstop_ranges = tabstop
6274 .ranges
6275 .iter()
6276 .flat_map(|tabstop_range| {
6277 let mut delta = 0_isize;
6278 insertion_ranges.iter().map(move |insertion_range| {
6279 let insertion_start = insertion_range.start as isize + delta;
6280 delta +=
6281 snippet.text.len() as isize - insertion_range.len() as isize;
6282
6283 let start = ((insertion_start + tabstop_range.start) as usize)
6284 .min(snapshot.len());
6285 let end = ((insertion_start + tabstop_range.end) as usize)
6286 .min(snapshot.len());
6287 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6288 })
6289 })
6290 .collect::<Vec<_>>();
6291 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6292
6293 Tabstop {
6294 is_end_tabstop,
6295 ranges: tabstop_ranges,
6296 choices: tabstop.choices.clone(),
6297 }
6298 })
6299 .collect::<Vec<_>>()
6300 });
6301 if let Some(tabstop) = tabstops.first() {
6302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6303 s.select_ranges(tabstop.ranges.iter().cloned());
6304 });
6305
6306 if let Some(choices) = &tabstop.choices {
6307 if let Some(selection) = tabstop.ranges.first() {
6308 self.show_snippet_choices(choices, selection.clone(), cx)
6309 }
6310 }
6311
6312 // If we're already at the last tabstop and it's at the end of the snippet,
6313 // we're done, we don't need to keep the state around.
6314 if !tabstop.is_end_tabstop {
6315 let choices = tabstops
6316 .iter()
6317 .map(|tabstop| tabstop.choices.clone())
6318 .collect();
6319
6320 let ranges = tabstops
6321 .into_iter()
6322 .map(|tabstop| tabstop.ranges)
6323 .collect::<Vec<_>>();
6324
6325 self.snippet_stack.push(SnippetState {
6326 active_index: 0,
6327 ranges,
6328 choices,
6329 });
6330 }
6331
6332 // Check whether the just-entered snippet ends with an auto-closable bracket.
6333 if self.autoclose_regions.is_empty() {
6334 let snapshot = self.buffer.read(cx).snapshot(cx);
6335 for selection in &mut self.selections.all::<Point>(cx) {
6336 let selection_head = selection.head();
6337 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6338 continue;
6339 };
6340
6341 let mut bracket_pair = None;
6342 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6343 let prev_chars = snapshot
6344 .reversed_chars_at(selection_head)
6345 .collect::<String>();
6346 for (pair, enabled) in scope.brackets() {
6347 if enabled
6348 && pair.close
6349 && prev_chars.starts_with(pair.start.as_str())
6350 && next_chars.starts_with(pair.end.as_str())
6351 {
6352 bracket_pair = Some(pair.clone());
6353 break;
6354 }
6355 }
6356 if let Some(pair) = bracket_pair {
6357 let start = snapshot.anchor_after(selection_head);
6358 let end = snapshot.anchor_after(selection_head);
6359 self.autoclose_regions.push(AutocloseRegion {
6360 selection_id: selection.id,
6361 range: start..end,
6362 pair,
6363 });
6364 }
6365 }
6366 }
6367 }
6368 Ok(())
6369 }
6370
6371 pub fn move_to_next_snippet_tabstop(
6372 &mut self,
6373 window: &mut Window,
6374 cx: &mut Context<Self>,
6375 ) -> bool {
6376 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6377 }
6378
6379 pub fn move_to_prev_snippet_tabstop(
6380 &mut self,
6381 window: &mut Window,
6382 cx: &mut Context<Self>,
6383 ) -> bool {
6384 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6385 }
6386
6387 pub fn move_to_snippet_tabstop(
6388 &mut self,
6389 bias: Bias,
6390 window: &mut Window,
6391 cx: &mut Context<Self>,
6392 ) -> bool {
6393 if let Some(mut snippet) = self.snippet_stack.pop() {
6394 match bias {
6395 Bias::Left => {
6396 if snippet.active_index > 0 {
6397 snippet.active_index -= 1;
6398 } else {
6399 self.snippet_stack.push(snippet);
6400 return false;
6401 }
6402 }
6403 Bias::Right => {
6404 if snippet.active_index + 1 < snippet.ranges.len() {
6405 snippet.active_index += 1;
6406 } else {
6407 self.snippet_stack.push(snippet);
6408 return false;
6409 }
6410 }
6411 }
6412 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6414 s.select_anchor_ranges(current_ranges.iter().cloned())
6415 });
6416
6417 if let Some(choices) = &snippet.choices[snippet.active_index] {
6418 if let Some(selection) = current_ranges.first() {
6419 self.show_snippet_choices(&choices, selection.clone(), cx);
6420 }
6421 }
6422
6423 // If snippet state is not at the last tabstop, push it back on the stack
6424 if snippet.active_index + 1 < snippet.ranges.len() {
6425 self.snippet_stack.push(snippet);
6426 }
6427 return true;
6428 }
6429 }
6430
6431 false
6432 }
6433
6434 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6435 self.transact(window, cx, |this, window, cx| {
6436 this.select_all(&SelectAll, window, cx);
6437 this.insert("", window, cx);
6438 });
6439 }
6440
6441 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6442 self.transact(window, cx, |this, window, cx| {
6443 this.select_autoclose_pair(window, cx);
6444 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6445 if !this.linked_edit_ranges.is_empty() {
6446 let selections = this.selections.all::<MultiBufferPoint>(cx);
6447 let snapshot = this.buffer.read(cx).snapshot(cx);
6448
6449 for selection in selections.iter() {
6450 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6451 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6452 if selection_start.buffer_id != selection_end.buffer_id {
6453 continue;
6454 }
6455 if let Some(ranges) =
6456 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6457 {
6458 for (buffer, entries) in ranges {
6459 linked_ranges.entry(buffer).or_default().extend(entries);
6460 }
6461 }
6462 }
6463 }
6464
6465 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6466 if !this.selections.line_mode {
6467 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6468 for selection in &mut selections {
6469 if selection.is_empty() {
6470 let old_head = selection.head();
6471 let mut new_head =
6472 movement::left(&display_map, old_head.to_display_point(&display_map))
6473 .to_point(&display_map);
6474 if let Some((buffer, line_buffer_range)) = display_map
6475 .buffer_snapshot
6476 .buffer_line_for_row(MultiBufferRow(old_head.row))
6477 {
6478 let indent_size =
6479 buffer.indent_size_for_line(line_buffer_range.start.row);
6480 let indent_len = match indent_size.kind {
6481 IndentKind::Space => {
6482 buffer.settings_at(line_buffer_range.start, cx).tab_size
6483 }
6484 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6485 };
6486 if old_head.column <= indent_size.len && old_head.column > 0 {
6487 let indent_len = indent_len.get();
6488 new_head = cmp::min(
6489 new_head,
6490 MultiBufferPoint::new(
6491 old_head.row,
6492 ((old_head.column - 1) / indent_len) * indent_len,
6493 ),
6494 );
6495 }
6496 }
6497
6498 selection.set_head(new_head, SelectionGoal::None);
6499 }
6500 }
6501 }
6502
6503 this.signature_help_state.set_backspace_pressed(true);
6504 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6505 s.select(selections)
6506 });
6507 this.insert("", window, cx);
6508 let empty_str: Arc<str> = Arc::from("");
6509 for (buffer, edits) in linked_ranges {
6510 let snapshot = buffer.read(cx).snapshot();
6511 use text::ToPoint as TP;
6512
6513 let edits = edits
6514 .into_iter()
6515 .map(|range| {
6516 let end_point = TP::to_point(&range.end, &snapshot);
6517 let mut start_point = TP::to_point(&range.start, &snapshot);
6518
6519 if end_point == start_point {
6520 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6521 .saturating_sub(1);
6522 start_point =
6523 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6524 };
6525
6526 (start_point..end_point, empty_str.clone())
6527 })
6528 .sorted_by_key(|(range, _)| range.start)
6529 .collect::<Vec<_>>();
6530 buffer.update(cx, |this, cx| {
6531 this.edit(edits, None, cx);
6532 })
6533 }
6534 this.refresh_inline_completion(true, false, window, cx);
6535 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6536 });
6537 }
6538
6539 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6540 self.transact(window, cx, |this, window, cx| {
6541 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6542 let line_mode = s.line_mode;
6543 s.move_with(|map, selection| {
6544 if selection.is_empty() && !line_mode {
6545 let cursor = movement::right(map, selection.head());
6546 selection.end = cursor;
6547 selection.reversed = true;
6548 selection.goal = SelectionGoal::None;
6549 }
6550 })
6551 });
6552 this.insert("", window, cx);
6553 this.refresh_inline_completion(true, false, window, cx);
6554 });
6555 }
6556
6557 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6558 if self.move_to_prev_snippet_tabstop(window, cx) {
6559 return;
6560 }
6561
6562 self.outdent(&Outdent, window, cx);
6563 }
6564
6565 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6566 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6567 return;
6568 }
6569
6570 let mut selections = self.selections.all_adjusted(cx);
6571 let buffer = self.buffer.read(cx);
6572 let snapshot = buffer.snapshot(cx);
6573 let rows_iter = selections.iter().map(|s| s.head().row);
6574 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6575
6576 let mut edits = Vec::new();
6577 let mut prev_edited_row = 0;
6578 let mut row_delta = 0;
6579 for selection in &mut selections {
6580 if selection.start.row != prev_edited_row {
6581 row_delta = 0;
6582 }
6583 prev_edited_row = selection.end.row;
6584
6585 // If the selection is non-empty, then increase the indentation of the selected lines.
6586 if !selection.is_empty() {
6587 row_delta =
6588 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6589 continue;
6590 }
6591
6592 // If the selection is empty and the cursor is in the leading whitespace before the
6593 // suggested indentation, then auto-indent the line.
6594 let cursor = selection.head();
6595 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6596 if let Some(suggested_indent) =
6597 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6598 {
6599 if cursor.column < suggested_indent.len
6600 && cursor.column <= current_indent.len
6601 && current_indent.len <= suggested_indent.len
6602 {
6603 selection.start = Point::new(cursor.row, suggested_indent.len);
6604 selection.end = selection.start;
6605 if row_delta == 0 {
6606 edits.extend(Buffer::edit_for_indent_size_adjustment(
6607 cursor.row,
6608 current_indent,
6609 suggested_indent,
6610 ));
6611 row_delta = suggested_indent.len - current_indent.len;
6612 }
6613 continue;
6614 }
6615 }
6616
6617 // Otherwise, insert a hard or soft tab.
6618 let settings = buffer.settings_at(cursor, cx);
6619 let tab_size = if settings.hard_tabs {
6620 IndentSize::tab()
6621 } else {
6622 let tab_size = settings.tab_size.get();
6623 let char_column = snapshot
6624 .text_for_range(Point::new(cursor.row, 0)..cursor)
6625 .flat_map(str::chars)
6626 .count()
6627 + row_delta as usize;
6628 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6629 IndentSize::spaces(chars_to_next_tab_stop)
6630 };
6631 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6632 selection.end = selection.start;
6633 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6634 row_delta += tab_size.len;
6635 }
6636
6637 self.transact(window, cx, |this, window, cx| {
6638 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6639 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6640 s.select(selections)
6641 });
6642 this.refresh_inline_completion(true, false, window, cx);
6643 });
6644 }
6645
6646 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6647 if self.read_only(cx) {
6648 return;
6649 }
6650 let mut selections = self.selections.all::<Point>(cx);
6651 let mut prev_edited_row = 0;
6652 let mut row_delta = 0;
6653 let mut edits = Vec::new();
6654 let buffer = self.buffer.read(cx);
6655 let snapshot = buffer.snapshot(cx);
6656 for selection in &mut selections {
6657 if selection.start.row != prev_edited_row {
6658 row_delta = 0;
6659 }
6660 prev_edited_row = selection.end.row;
6661
6662 row_delta =
6663 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6664 }
6665
6666 self.transact(window, cx, |this, window, cx| {
6667 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6668 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6669 s.select(selections)
6670 });
6671 });
6672 }
6673
6674 fn indent_selection(
6675 buffer: &MultiBuffer,
6676 snapshot: &MultiBufferSnapshot,
6677 selection: &mut Selection<Point>,
6678 edits: &mut Vec<(Range<Point>, String)>,
6679 delta_for_start_row: u32,
6680 cx: &App,
6681 ) -> u32 {
6682 let settings = buffer.settings_at(selection.start, cx);
6683 let tab_size = settings.tab_size.get();
6684 let indent_kind = if settings.hard_tabs {
6685 IndentKind::Tab
6686 } else {
6687 IndentKind::Space
6688 };
6689 let mut start_row = selection.start.row;
6690 let mut end_row = selection.end.row + 1;
6691
6692 // If a selection ends at the beginning of a line, don't indent
6693 // that last line.
6694 if selection.end.column == 0 && selection.end.row > selection.start.row {
6695 end_row -= 1;
6696 }
6697
6698 // Avoid re-indenting a row that has already been indented by a
6699 // previous selection, but still update this selection's column
6700 // to reflect that indentation.
6701 if delta_for_start_row > 0 {
6702 start_row += 1;
6703 selection.start.column += delta_for_start_row;
6704 if selection.end.row == selection.start.row {
6705 selection.end.column += delta_for_start_row;
6706 }
6707 }
6708
6709 let mut delta_for_end_row = 0;
6710 let has_multiple_rows = start_row + 1 != end_row;
6711 for row in start_row..end_row {
6712 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6713 let indent_delta = match (current_indent.kind, indent_kind) {
6714 (IndentKind::Space, IndentKind::Space) => {
6715 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6716 IndentSize::spaces(columns_to_next_tab_stop)
6717 }
6718 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6719 (_, IndentKind::Tab) => IndentSize::tab(),
6720 };
6721
6722 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6723 0
6724 } else {
6725 selection.start.column
6726 };
6727 let row_start = Point::new(row, start);
6728 edits.push((
6729 row_start..row_start,
6730 indent_delta.chars().collect::<String>(),
6731 ));
6732
6733 // Update this selection's endpoints to reflect the indentation.
6734 if row == selection.start.row {
6735 selection.start.column += indent_delta.len;
6736 }
6737 if row == selection.end.row {
6738 selection.end.column += indent_delta.len;
6739 delta_for_end_row = indent_delta.len;
6740 }
6741 }
6742
6743 if selection.start.row == selection.end.row {
6744 delta_for_start_row + delta_for_end_row
6745 } else {
6746 delta_for_end_row
6747 }
6748 }
6749
6750 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6751 if self.read_only(cx) {
6752 return;
6753 }
6754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6755 let selections = self.selections.all::<Point>(cx);
6756 let mut deletion_ranges = Vec::new();
6757 let mut last_outdent = None;
6758 {
6759 let buffer = self.buffer.read(cx);
6760 let snapshot = buffer.snapshot(cx);
6761 for selection in &selections {
6762 let settings = buffer.settings_at(selection.start, cx);
6763 let tab_size = settings.tab_size.get();
6764 let mut rows = selection.spanned_rows(false, &display_map);
6765
6766 // Avoid re-outdenting a row that has already been outdented by a
6767 // previous selection.
6768 if let Some(last_row) = last_outdent {
6769 if last_row == rows.start {
6770 rows.start = rows.start.next_row();
6771 }
6772 }
6773 let has_multiple_rows = rows.len() > 1;
6774 for row in rows.iter_rows() {
6775 let indent_size = snapshot.indent_size_for_line(row);
6776 if indent_size.len > 0 {
6777 let deletion_len = match indent_size.kind {
6778 IndentKind::Space => {
6779 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6780 if columns_to_prev_tab_stop == 0 {
6781 tab_size
6782 } else {
6783 columns_to_prev_tab_stop
6784 }
6785 }
6786 IndentKind::Tab => 1,
6787 };
6788 let start = if has_multiple_rows
6789 || deletion_len > selection.start.column
6790 || indent_size.len < selection.start.column
6791 {
6792 0
6793 } else {
6794 selection.start.column - deletion_len
6795 };
6796 deletion_ranges.push(
6797 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6798 );
6799 last_outdent = Some(row);
6800 }
6801 }
6802 }
6803 }
6804
6805 self.transact(window, cx, |this, window, cx| {
6806 this.buffer.update(cx, |buffer, cx| {
6807 let empty_str: Arc<str> = Arc::default();
6808 buffer.edit(
6809 deletion_ranges
6810 .into_iter()
6811 .map(|range| (range, empty_str.clone())),
6812 None,
6813 cx,
6814 );
6815 });
6816 let selections = this.selections.all::<usize>(cx);
6817 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6818 s.select(selections)
6819 });
6820 });
6821 }
6822
6823 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6824 if self.read_only(cx) {
6825 return;
6826 }
6827 let selections = self
6828 .selections
6829 .all::<usize>(cx)
6830 .into_iter()
6831 .map(|s| s.range());
6832
6833 self.transact(window, cx, |this, window, cx| {
6834 this.buffer.update(cx, |buffer, cx| {
6835 buffer.autoindent_ranges(selections, cx);
6836 });
6837 let selections = this.selections.all::<usize>(cx);
6838 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6839 s.select(selections)
6840 });
6841 });
6842 }
6843
6844 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6846 let selections = self.selections.all::<Point>(cx);
6847
6848 let mut new_cursors = Vec::new();
6849 let mut edit_ranges = Vec::new();
6850 let mut selections = selections.iter().peekable();
6851 while let Some(selection) = selections.next() {
6852 let mut rows = selection.spanned_rows(false, &display_map);
6853 let goal_display_column = selection.head().to_display_point(&display_map).column();
6854
6855 // Accumulate contiguous regions of rows that we want to delete.
6856 while let Some(next_selection) = selections.peek() {
6857 let next_rows = next_selection.spanned_rows(false, &display_map);
6858 if next_rows.start <= rows.end {
6859 rows.end = next_rows.end;
6860 selections.next().unwrap();
6861 } else {
6862 break;
6863 }
6864 }
6865
6866 let buffer = &display_map.buffer_snapshot;
6867 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6868 let edit_end;
6869 let cursor_buffer_row;
6870 if buffer.max_point().row >= rows.end.0 {
6871 // If there's a line after the range, delete the \n from the end of the row range
6872 // and position the cursor on the next line.
6873 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6874 cursor_buffer_row = rows.end;
6875 } else {
6876 // If there isn't a line after the range, delete the \n from the line before the
6877 // start of the row range and position the cursor there.
6878 edit_start = edit_start.saturating_sub(1);
6879 edit_end = buffer.len();
6880 cursor_buffer_row = rows.start.previous_row();
6881 }
6882
6883 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6884 *cursor.column_mut() =
6885 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6886
6887 new_cursors.push((
6888 selection.id,
6889 buffer.anchor_after(cursor.to_point(&display_map)),
6890 ));
6891 edit_ranges.push(edit_start..edit_end);
6892 }
6893
6894 self.transact(window, cx, |this, window, cx| {
6895 let buffer = this.buffer.update(cx, |buffer, cx| {
6896 let empty_str: Arc<str> = Arc::default();
6897 buffer.edit(
6898 edit_ranges
6899 .into_iter()
6900 .map(|range| (range, empty_str.clone())),
6901 None,
6902 cx,
6903 );
6904 buffer.snapshot(cx)
6905 });
6906 let new_selections = new_cursors
6907 .into_iter()
6908 .map(|(id, cursor)| {
6909 let cursor = cursor.to_point(&buffer);
6910 Selection {
6911 id,
6912 start: cursor,
6913 end: cursor,
6914 reversed: false,
6915 goal: SelectionGoal::None,
6916 }
6917 })
6918 .collect();
6919
6920 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6921 s.select(new_selections);
6922 });
6923 });
6924 }
6925
6926 pub fn join_lines_impl(
6927 &mut self,
6928 insert_whitespace: bool,
6929 window: &mut Window,
6930 cx: &mut Context<Self>,
6931 ) {
6932 if self.read_only(cx) {
6933 return;
6934 }
6935 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6936 for selection in self.selections.all::<Point>(cx) {
6937 let start = MultiBufferRow(selection.start.row);
6938 // Treat single line selections as if they include the next line. Otherwise this action
6939 // would do nothing for single line selections individual cursors.
6940 let end = if selection.start.row == selection.end.row {
6941 MultiBufferRow(selection.start.row + 1)
6942 } else {
6943 MultiBufferRow(selection.end.row)
6944 };
6945
6946 if let Some(last_row_range) = row_ranges.last_mut() {
6947 if start <= last_row_range.end {
6948 last_row_range.end = end;
6949 continue;
6950 }
6951 }
6952 row_ranges.push(start..end);
6953 }
6954
6955 let snapshot = self.buffer.read(cx).snapshot(cx);
6956 let mut cursor_positions = Vec::new();
6957 for row_range in &row_ranges {
6958 let anchor = snapshot.anchor_before(Point::new(
6959 row_range.end.previous_row().0,
6960 snapshot.line_len(row_range.end.previous_row()),
6961 ));
6962 cursor_positions.push(anchor..anchor);
6963 }
6964
6965 self.transact(window, cx, |this, window, cx| {
6966 for row_range in row_ranges.into_iter().rev() {
6967 for row in row_range.iter_rows().rev() {
6968 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6969 let next_line_row = row.next_row();
6970 let indent = snapshot.indent_size_for_line(next_line_row);
6971 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6972
6973 let replace =
6974 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6975 " "
6976 } else {
6977 ""
6978 };
6979
6980 this.buffer.update(cx, |buffer, cx| {
6981 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6982 });
6983 }
6984 }
6985
6986 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6987 s.select_anchor_ranges(cursor_positions)
6988 });
6989 });
6990 }
6991
6992 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6993 self.join_lines_impl(true, window, cx);
6994 }
6995
6996 pub fn sort_lines_case_sensitive(
6997 &mut self,
6998 _: &SortLinesCaseSensitive,
6999 window: &mut Window,
7000 cx: &mut Context<Self>,
7001 ) {
7002 self.manipulate_lines(window, cx, |lines| lines.sort())
7003 }
7004
7005 pub fn sort_lines_case_insensitive(
7006 &mut self,
7007 _: &SortLinesCaseInsensitive,
7008 window: &mut Window,
7009 cx: &mut Context<Self>,
7010 ) {
7011 self.manipulate_lines(window, cx, |lines| {
7012 lines.sort_by_key(|line| line.to_lowercase())
7013 })
7014 }
7015
7016 pub fn unique_lines_case_insensitive(
7017 &mut self,
7018 _: &UniqueLinesCaseInsensitive,
7019 window: &mut Window,
7020 cx: &mut Context<Self>,
7021 ) {
7022 self.manipulate_lines(window, cx, |lines| {
7023 let mut seen = HashSet::default();
7024 lines.retain(|line| seen.insert(line.to_lowercase()));
7025 })
7026 }
7027
7028 pub fn unique_lines_case_sensitive(
7029 &mut self,
7030 _: &UniqueLinesCaseSensitive,
7031 window: &mut Window,
7032 cx: &mut Context<Self>,
7033 ) {
7034 self.manipulate_lines(window, cx, |lines| {
7035 let mut seen = HashSet::default();
7036 lines.retain(|line| seen.insert(*line));
7037 })
7038 }
7039
7040 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7041 let Some(project) = self.project.clone() else {
7042 return;
7043 };
7044 self.reload(project, window, cx)
7045 .detach_and_notify_err(window, cx);
7046 }
7047
7048 pub fn restore_file(
7049 &mut self,
7050 _: &::git::RestoreFile,
7051 window: &mut Window,
7052 cx: &mut Context<Self>,
7053 ) {
7054 let mut buffer_ids = HashSet::default();
7055 let snapshot = self.buffer().read(cx).snapshot(cx);
7056 for selection in self.selections.all::<usize>(cx) {
7057 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7058 }
7059
7060 let buffer = self.buffer().read(cx);
7061 let ranges = buffer_ids
7062 .into_iter()
7063 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7064 .collect::<Vec<_>>();
7065
7066 self.restore_hunks_in_ranges(ranges, window, cx);
7067 }
7068
7069 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7070 let selections = self
7071 .selections
7072 .all(cx)
7073 .into_iter()
7074 .map(|s| s.range())
7075 .collect();
7076 self.restore_hunks_in_ranges(selections, window, cx);
7077 }
7078
7079 fn restore_hunks_in_ranges(
7080 &mut self,
7081 ranges: Vec<Range<Point>>,
7082 window: &mut Window,
7083 cx: &mut Context<Editor>,
7084 ) {
7085 let mut revert_changes = HashMap::default();
7086 let snapshot = self.buffer.read(cx).snapshot(cx);
7087 let Some(project) = &self.project else {
7088 return;
7089 };
7090
7091 let chunk_by = self
7092 .snapshot(window, cx)
7093 .hunks_for_ranges(ranges.into_iter())
7094 .into_iter()
7095 .chunk_by(|hunk| hunk.buffer_id);
7096 for (buffer_id, hunks) in &chunk_by {
7097 let hunks = hunks.collect::<Vec<_>>();
7098 for hunk in &hunks {
7099 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7100 }
7101 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7102 }
7103 drop(chunk_by);
7104 if !revert_changes.is_empty() {
7105 self.transact(window, cx, |editor, window, cx| {
7106 editor.revert(revert_changes, window, cx);
7107 });
7108 }
7109 }
7110
7111 pub fn open_active_item_in_terminal(
7112 &mut self,
7113 _: &OpenInTerminal,
7114 window: &mut Window,
7115 cx: &mut Context<Self>,
7116 ) {
7117 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7118 let project_path = buffer.read(cx).project_path(cx)?;
7119 let project = self.project.as_ref()?.read(cx);
7120 let entry = project.entry_for_path(&project_path, cx)?;
7121 let parent = match &entry.canonical_path {
7122 Some(canonical_path) => canonical_path.to_path_buf(),
7123 None => project.absolute_path(&project_path, cx)?,
7124 }
7125 .parent()?
7126 .to_path_buf();
7127 Some(parent)
7128 }) {
7129 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7130 }
7131 }
7132
7133 pub fn prepare_restore_change(
7134 &self,
7135 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7136 hunk: &MultiBufferDiffHunk,
7137 cx: &mut App,
7138 ) -> Option<()> {
7139 let buffer = self.buffer.read(cx);
7140 let diff = buffer.diff_for(hunk.buffer_id)?;
7141 let buffer = buffer.buffer(hunk.buffer_id)?;
7142 let buffer = buffer.read(cx);
7143 let original_text = diff
7144 .read(cx)
7145 .base_text()
7146 .as_ref()?
7147 .as_rope()
7148 .slice(hunk.diff_base_byte_range.clone());
7149 let buffer_snapshot = buffer.snapshot();
7150 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7151 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7152 probe
7153 .0
7154 .start
7155 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7156 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7157 }) {
7158 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7159 Some(())
7160 } else {
7161 None
7162 }
7163 }
7164
7165 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7166 self.manipulate_lines(window, cx, |lines| lines.reverse())
7167 }
7168
7169 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7170 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7171 }
7172
7173 fn manipulate_lines<Fn>(
7174 &mut self,
7175 window: &mut Window,
7176 cx: &mut Context<Self>,
7177 mut callback: Fn,
7178 ) where
7179 Fn: FnMut(&mut Vec<&str>),
7180 {
7181 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7182 let buffer = self.buffer.read(cx).snapshot(cx);
7183
7184 let mut edits = Vec::new();
7185
7186 let selections = self.selections.all::<Point>(cx);
7187 let mut selections = selections.iter().peekable();
7188 let mut contiguous_row_selections = Vec::new();
7189 let mut new_selections = Vec::new();
7190 let mut added_lines = 0;
7191 let mut removed_lines = 0;
7192
7193 while let Some(selection) = selections.next() {
7194 let (start_row, end_row) = consume_contiguous_rows(
7195 &mut contiguous_row_selections,
7196 selection,
7197 &display_map,
7198 &mut selections,
7199 );
7200
7201 let start_point = Point::new(start_row.0, 0);
7202 let end_point = Point::new(
7203 end_row.previous_row().0,
7204 buffer.line_len(end_row.previous_row()),
7205 );
7206 let text = buffer
7207 .text_for_range(start_point..end_point)
7208 .collect::<String>();
7209
7210 let mut lines = text.split('\n').collect_vec();
7211
7212 let lines_before = lines.len();
7213 callback(&mut lines);
7214 let lines_after = lines.len();
7215
7216 edits.push((start_point..end_point, lines.join("\n")));
7217
7218 // Selections must change based on added and removed line count
7219 let start_row =
7220 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7221 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7222 new_selections.push(Selection {
7223 id: selection.id,
7224 start: start_row,
7225 end: end_row,
7226 goal: SelectionGoal::None,
7227 reversed: selection.reversed,
7228 });
7229
7230 if lines_after > lines_before {
7231 added_lines += lines_after - lines_before;
7232 } else if lines_before > lines_after {
7233 removed_lines += lines_before - lines_after;
7234 }
7235 }
7236
7237 self.transact(window, cx, |this, window, cx| {
7238 let buffer = this.buffer.update(cx, |buffer, cx| {
7239 buffer.edit(edits, None, cx);
7240 buffer.snapshot(cx)
7241 });
7242
7243 // Recalculate offsets on newly edited buffer
7244 let new_selections = new_selections
7245 .iter()
7246 .map(|s| {
7247 let start_point = Point::new(s.start.0, 0);
7248 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7249 Selection {
7250 id: s.id,
7251 start: buffer.point_to_offset(start_point),
7252 end: buffer.point_to_offset(end_point),
7253 goal: s.goal,
7254 reversed: s.reversed,
7255 }
7256 })
7257 .collect();
7258
7259 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7260 s.select(new_selections);
7261 });
7262
7263 this.request_autoscroll(Autoscroll::fit(), cx);
7264 });
7265 }
7266
7267 pub fn convert_to_upper_case(
7268 &mut self,
7269 _: &ConvertToUpperCase,
7270 window: &mut Window,
7271 cx: &mut Context<Self>,
7272 ) {
7273 self.manipulate_text(window, cx, |text| text.to_uppercase())
7274 }
7275
7276 pub fn convert_to_lower_case(
7277 &mut self,
7278 _: &ConvertToLowerCase,
7279 window: &mut Window,
7280 cx: &mut Context<Self>,
7281 ) {
7282 self.manipulate_text(window, cx, |text| text.to_lowercase())
7283 }
7284
7285 pub fn convert_to_title_case(
7286 &mut self,
7287 _: &ConvertToTitleCase,
7288 window: &mut Window,
7289 cx: &mut Context<Self>,
7290 ) {
7291 self.manipulate_text(window, cx, |text| {
7292 text.split('\n')
7293 .map(|line| line.to_case(Case::Title))
7294 .join("\n")
7295 })
7296 }
7297
7298 pub fn convert_to_snake_case(
7299 &mut self,
7300 _: &ConvertToSnakeCase,
7301 window: &mut Window,
7302 cx: &mut Context<Self>,
7303 ) {
7304 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7305 }
7306
7307 pub fn convert_to_kebab_case(
7308 &mut self,
7309 _: &ConvertToKebabCase,
7310 window: &mut Window,
7311 cx: &mut Context<Self>,
7312 ) {
7313 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7314 }
7315
7316 pub fn convert_to_upper_camel_case(
7317 &mut self,
7318 _: &ConvertToUpperCamelCase,
7319 window: &mut Window,
7320 cx: &mut Context<Self>,
7321 ) {
7322 self.manipulate_text(window, cx, |text| {
7323 text.split('\n')
7324 .map(|line| line.to_case(Case::UpperCamel))
7325 .join("\n")
7326 })
7327 }
7328
7329 pub fn convert_to_lower_camel_case(
7330 &mut self,
7331 _: &ConvertToLowerCamelCase,
7332 window: &mut Window,
7333 cx: &mut Context<Self>,
7334 ) {
7335 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7336 }
7337
7338 pub fn convert_to_opposite_case(
7339 &mut self,
7340 _: &ConvertToOppositeCase,
7341 window: &mut Window,
7342 cx: &mut Context<Self>,
7343 ) {
7344 self.manipulate_text(window, cx, |text| {
7345 text.chars()
7346 .fold(String::with_capacity(text.len()), |mut t, c| {
7347 if c.is_uppercase() {
7348 t.extend(c.to_lowercase());
7349 } else {
7350 t.extend(c.to_uppercase());
7351 }
7352 t
7353 })
7354 })
7355 }
7356
7357 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7358 where
7359 Fn: FnMut(&str) -> String,
7360 {
7361 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7362 let buffer = self.buffer.read(cx).snapshot(cx);
7363
7364 let mut new_selections = Vec::new();
7365 let mut edits = Vec::new();
7366 let mut selection_adjustment = 0i32;
7367
7368 for selection in self.selections.all::<usize>(cx) {
7369 let selection_is_empty = selection.is_empty();
7370
7371 let (start, end) = if selection_is_empty {
7372 let word_range = movement::surrounding_word(
7373 &display_map,
7374 selection.start.to_display_point(&display_map),
7375 );
7376 let start = word_range.start.to_offset(&display_map, Bias::Left);
7377 let end = word_range.end.to_offset(&display_map, Bias::Left);
7378 (start, end)
7379 } else {
7380 (selection.start, selection.end)
7381 };
7382
7383 let text = buffer.text_for_range(start..end).collect::<String>();
7384 let old_length = text.len() as i32;
7385 let text = callback(&text);
7386
7387 new_selections.push(Selection {
7388 start: (start as i32 - selection_adjustment) as usize,
7389 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7390 goal: SelectionGoal::None,
7391 ..selection
7392 });
7393
7394 selection_adjustment += old_length - text.len() as i32;
7395
7396 edits.push((start..end, text));
7397 }
7398
7399 self.transact(window, cx, |this, window, cx| {
7400 this.buffer.update(cx, |buffer, cx| {
7401 buffer.edit(edits, None, cx);
7402 });
7403
7404 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7405 s.select(new_selections);
7406 });
7407
7408 this.request_autoscroll(Autoscroll::fit(), cx);
7409 });
7410 }
7411
7412 pub fn duplicate(
7413 &mut self,
7414 upwards: bool,
7415 whole_lines: bool,
7416 window: &mut Window,
7417 cx: &mut Context<Self>,
7418 ) {
7419 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7420 let buffer = &display_map.buffer_snapshot;
7421 let selections = self.selections.all::<Point>(cx);
7422
7423 let mut edits = Vec::new();
7424 let mut selections_iter = selections.iter().peekable();
7425 while let Some(selection) = selections_iter.next() {
7426 let mut rows = selection.spanned_rows(false, &display_map);
7427 // duplicate line-wise
7428 if whole_lines || selection.start == selection.end {
7429 // Avoid duplicating the same lines twice.
7430 while let Some(next_selection) = selections_iter.peek() {
7431 let next_rows = next_selection.spanned_rows(false, &display_map);
7432 if next_rows.start < rows.end {
7433 rows.end = next_rows.end;
7434 selections_iter.next().unwrap();
7435 } else {
7436 break;
7437 }
7438 }
7439
7440 // Copy the text from the selected row region and splice it either at the start
7441 // or end of the region.
7442 let start = Point::new(rows.start.0, 0);
7443 let end = Point::new(
7444 rows.end.previous_row().0,
7445 buffer.line_len(rows.end.previous_row()),
7446 );
7447 let text = buffer
7448 .text_for_range(start..end)
7449 .chain(Some("\n"))
7450 .collect::<String>();
7451 let insert_location = if upwards {
7452 Point::new(rows.end.0, 0)
7453 } else {
7454 start
7455 };
7456 edits.push((insert_location..insert_location, text));
7457 } else {
7458 // duplicate character-wise
7459 let start = selection.start;
7460 let end = selection.end;
7461 let text = buffer.text_for_range(start..end).collect::<String>();
7462 edits.push((selection.end..selection.end, text));
7463 }
7464 }
7465
7466 self.transact(window, cx, |this, _, cx| {
7467 this.buffer.update(cx, |buffer, cx| {
7468 buffer.edit(edits, None, cx);
7469 });
7470
7471 this.request_autoscroll(Autoscroll::fit(), cx);
7472 });
7473 }
7474
7475 pub fn duplicate_line_up(
7476 &mut self,
7477 _: &DuplicateLineUp,
7478 window: &mut Window,
7479 cx: &mut Context<Self>,
7480 ) {
7481 self.duplicate(true, true, window, cx);
7482 }
7483
7484 pub fn duplicate_line_down(
7485 &mut self,
7486 _: &DuplicateLineDown,
7487 window: &mut Window,
7488 cx: &mut Context<Self>,
7489 ) {
7490 self.duplicate(false, true, window, cx);
7491 }
7492
7493 pub fn duplicate_selection(
7494 &mut self,
7495 _: &DuplicateSelection,
7496 window: &mut Window,
7497 cx: &mut Context<Self>,
7498 ) {
7499 self.duplicate(false, false, window, cx);
7500 }
7501
7502 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7503 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7504 let buffer = self.buffer.read(cx).snapshot(cx);
7505
7506 let mut edits = Vec::new();
7507 let mut unfold_ranges = Vec::new();
7508 let mut refold_creases = Vec::new();
7509
7510 let selections = self.selections.all::<Point>(cx);
7511 let mut selections = selections.iter().peekable();
7512 let mut contiguous_row_selections = Vec::new();
7513 let mut new_selections = Vec::new();
7514
7515 while let Some(selection) = selections.next() {
7516 // Find all the selections that span a contiguous row range
7517 let (start_row, end_row) = consume_contiguous_rows(
7518 &mut contiguous_row_selections,
7519 selection,
7520 &display_map,
7521 &mut selections,
7522 );
7523
7524 // Move the text spanned by the row range to be before the line preceding the row range
7525 if start_row.0 > 0 {
7526 let range_to_move = Point::new(
7527 start_row.previous_row().0,
7528 buffer.line_len(start_row.previous_row()),
7529 )
7530 ..Point::new(
7531 end_row.previous_row().0,
7532 buffer.line_len(end_row.previous_row()),
7533 );
7534 let insertion_point = display_map
7535 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7536 .0;
7537
7538 // Don't move lines across excerpts
7539 if buffer
7540 .excerpt_containing(insertion_point..range_to_move.end)
7541 .is_some()
7542 {
7543 let text = buffer
7544 .text_for_range(range_to_move.clone())
7545 .flat_map(|s| s.chars())
7546 .skip(1)
7547 .chain(['\n'])
7548 .collect::<String>();
7549
7550 edits.push((
7551 buffer.anchor_after(range_to_move.start)
7552 ..buffer.anchor_before(range_to_move.end),
7553 String::new(),
7554 ));
7555 let insertion_anchor = buffer.anchor_after(insertion_point);
7556 edits.push((insertion_anchor..insertion_anchor, text));
7557
7558 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7559
7560 // Move selections up
7561 new_selections.extend(contiguous_row_selections.drain(..).map(
7562 |mut selection| {
7563 selection.start.row -= row_delta;
7564 selection.end.row -= row_delta;
7565 selection
7566 },
7567 ));
7568
7569 // Move folds up
7570 unfold_ranges.push(range_to_move.clone());
7571 for fold in display_map.folds_in_range(
7572 buffer.anchor_before(range_to_move.start)
7573 ..buffer.anchor_after(range_to_move.end),
7574 ) {
7575 let mut start = fold.range.start.to_point(&buffer);
7576 let mut end = fold.range.end.to_point(&buffer);
7577 start.row -= row_delta;
7578 end.row -= row_delta;
7579 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7580 }
7581 }
7582 }
7583
7584 // If we didn't move line(s), preserve the existing selections
7585 new_selections.append(&mut contiguous_row_selections);
7586 }
7587
7588 self.transact(window, cx, |this, window, cx| {
7589 this.unfold_ranges(&unfold_ranges, true, true, cx);
7590 this.buffer.update(cx, |buffer, cx| {
7591 for (range, text) in edits {
7592 buffer.edit([(range, text)], None, cx);
7593 }
7594 });
7595 this.fold_creases(refold_creases, true, window, cx);
7596 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7597 s.select(new_selections);
7598 })
7599 });
7600 }
7601
7602 pub fn move_line_down(
7603 &mut self,
7604 _: &MoveLineDown,
7605 window: &mut Window,
7606 cx: &mut Context<Self>,
7607 ) {
7608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7609 let buffer = self.buffer.read(cx).snapshot(cx);
7610
7611 let mut edits = Vec::new();
7612 let mut unfold_ranges = Vec::new();
7613 let mut refold_creases = Vec::new();
7614
7615 let selections = self.selections.all::<Point>(cx);
7616 let mut selections = selections.iter().peekable();
7617 let mut contiguous_row_selections = Vec::new();
7618 let mut new_selections = Vec::new();
7619
7620 while let Some(selection) = selections.next() {
7621 // Find all the selections that span a contiguous row range
7622 let (start_row, end_row) = consume_contiguous_rows(
7623 &mut contiguous_row_selections,
7624 selection,
7625 &display_map,
7626 &mut selections,
7627 );
7628
7629 // Move the text spanned by the row range to be after the last line of the row range
7630 if end_row.0 <= buffer.max_point().row {
7631 let range_to_move =
7632 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7633 let insertion_point = display_map
7634 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7635 .0;
7636
7637 // Don't move lines across excerpt boundaries
7638 if buffer
7639 .excerpt_containing(range_to_move.start..insertion_point)
7640 .is_some()
7641 {
7642 let mut text = String::from("\n");
7643 text.extend(buffer.text_for_range(range_to_move.clone()));
7644 text.pop(); // Drop trailing newline
7645 edits.push((
7646 buffer.anchor_after(range_to_move.start)
7647 ..buffer.anchor_before(range_to_move.end),
7648 String::new(),
7649 ));
7650 let insertion_anchor = buffer.anchor_after(insertion_point);
7651 edits.push((insertion_anchor..insertion_anchor, text));
7652
7653 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7654
7655 // Move selections down
7656 new_selections.extend(contiguous_row_selections.drain(..).map(
7657 |mut selection| {
7658 selection.start.row += row_delta;
7659 selection.end.row += row_delta;
7660 selection
7661 },
7662 ));
7663
7664 // Move folds down
7665 unfold_ranges.push(range_to_move.clone());
7666 for fold in display_map.folds_in_range(
7667 buffer.anchor_before(range_to_move.start)
7668 ..buffer.anchor_after(range_to_move.end),
7669 ) {
7670 let mut start = fold.range.start.to_point(&buffer);
7671 let mut end = fold.range.end.to_point(&buffer);
7672 start.row += row_delta;
7673 end.row += row_delta;
7674 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7675 }
7676 }
7677 }
7678
7679 // If we didn't move line(s), preserve the existing selections
7680 new_selections.append(&mut contiguous_row_selections);
7681 }
7682
7683 self.transact(window, cx, |this, window, cx| {
7684 this.unfold_ranges(&unfold_ranges, true, true, cx);
7685 this.buffer.update(cx, |buffer, cx| {
7686 for (range, text) in edits {
7687 buffer.edit([(range, text)], None, cx);
7688 }
7689 });
7690 this.fold_creases(refold_creases, true, window, cx);
7691 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7692 s.select(new_selections)
7693 });
7694 });
7695 }
7696
7697 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7698 let text_layout_details = &self.text_layout_details(window);
7699 self.transact(window, cx, |this, window, cx| {
7700 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7701 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7702 let line_mode = s.line_mode;
7703 s.move_with(|display_map, selection| {
7704 if !selection.is_empty() || line_mode {
7705 return;
7706 }
7707
7708 let mut head = selection.head();
7709 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7710 if head.column() == display_map.line_len(head.row()) {
7711 transpose_offset = display_map
7712 .buffer_snapshot
7713 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7714 }
7715
7716 if transpose_offset == 0 {
7717 return;
7718 }
7719
7720 *head.column_mut() += 1;
7721 head = display_map.clip_point(head, Bias::Right);
7722 let goal = SelectionGoal::HorizontalPosition(
7723 display_map
7724 .x_for_display_point(head, text_layout_details)
7725 .into(),
7726 );
7727 selection.collapse_to(head, goal);
7728
7729 let transpose_start = display_map
7730 .buffer_snapshot
7731 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7732 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7733 let transpose_end = display_map
7734 .buffer_snapshot
7735 .clip_offset(transpose_offset + 1, Bias::Right);
7736 if let Some(ch) =
7737 display_map.buffer_snapshot.chars_at(transpose_start).next()
7738 {
7739 edits.push((transpose_start..transpose_offset, String::new()));
7740 edits.push((transpose_end..transpose_end, ch.to_string()));
7741 }
7742 }
7743 });
7744 edits
7745 });
7746 this.buffer
7747 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7748 let selections = this.selections.all::<usize>(cx);
7749 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7750 s.select(selections);
7751 });
7752 });
7753 }
7754
7755 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7756 self.rewrap_impl(IsVimMode::No, cx)
7757 }
7758
7759 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7760 let buffer = self.buffer.read(cx).snapshot(cx);
7761 let selections = self.selections.all::<Point>(cx);
7762 let mut selections = selections.iter().peekable();
7763
7764 let mut edits = Vec::new();
7765 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7766
7767 while let Some(selection) = selections.next() {
7768 let mut start_row = selection.start.row;
7769 let mut end_row = selection.end.row;
7770
7771 // Skip selections that overlap with a range that has already been rewrapped.
7772 let selection_range = start_row..end_row;
7773 if rewrapped_row_ranges
7774 .iter()
7775 .any(|range| range.overlaps(&selection_range))
7776 {
7777 continue;
7778 }
7779
7780 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7781
7782 // Since not all lines in the selection may be at the same indent
7783 // level, choose the indent size that is the most common between all
7784 // of the lines.
7785 //
7786 // If there is a tie, we use the deepest indent.
7787 let (indent_size, indent_end) = {
7788 let mut indent_size_occurrences = HashMap::default();
7789 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7790
7791 for row in start_row..=end_row {
7792 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7793 rows_by_indent_size.entry(indent).or_default().push(row);
7794 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7795 }
7796
7797 let indent_size = indent_size_occurrences
7798 .into_iter()
7799 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7800 .map(|(indent, _)| indent)
7801 .unwrap_or_default();
7802 let row = rows_by_indent_size[&indent_size][0];
7803 let indent_end = Point::new(row, indent_size.len);
7804
7805 (indent_size, indent_end)
7806 };
7807
7808 let mut line_prefix = indent_size.chars().collect::<String>();
7809
7810 let mut inside_comment = false;
7811 if let Some(comment_prefix) =
7812 buffer
7813 .language_scope_at(selection.head())
7814 .and_then(|language| {
7815 language
7816 .line_comment_prefixes()
7817 .iter()
7818 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7819 .cloned()
7820 })
7821 {
7822 line_prefix.push_str(&comment_prefix);
7823 inside_comment = true;
7824 }
7825
7826 let language_settings = buffer.settings_at(selection.head(), cx);
7827 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
7828 RewrapBehavior::InComments => inside_comment,
7829 RewrapBehavior::InSelections => !selection.is_empty(),
7830 RewrapBehavior::Anywhere => true,
7831 };
7832
7833 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
7834 if !should_rewrap {
7835 continue;
7836 }
7837
7838 if selection.is_empty() {
7839 'expand_upwards: while start_row > 0 {
7840 let prev_row = start_row - 1;
7841 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7842 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7843 {
7844 start_row = prev_row;
7845 } else {
7846 break 'expand_upwards;
7847 }
7848 }
7849
7850 'expand_downwards: while end_row < buffer.max_point().row {
7851 let next_row = end_row + 1;
7852 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7853 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7854 {
7855 end_row = next_row;
7856 } else {
7857 break 'expand_downwards;
7858 }
7859 }
7860 }
7861
7862 let start = Point::new(start_row, 0);
7863 let start_offset = start.to_offset(&buffer);
7864 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7865 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7866 let Some(lines_without_prefixes) = selection_text
7867 .lines()
7868 .map(|line| {
7869 line.strip_prefix(&line_prefix)
7870 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7871 .ok_or_else(|| {
7872 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7873 })
7874 })
7875 .collect::<Result<Vec<_>, _>>()
7876 .log_err()
7877 else {
7878 continue;
7879 };
7880
7881 let wrap_column = buffer
7882 .settings_at(Point::new(start_row, 0), cx)
7883 .preferred_line_length as usize;
7884 let wrapped_text = wrap_with_prefix(
7885 line_prefix,
7886 lines_without_prefixes.join(" "),
7887 wrap_column,
7888 tab_size,
7889 );
7890
7891 // TODO: should always use char-based diff while still supporting cursor behavior that
7892 // matches vim.
7893 let mut diff_options = DiffOptions::default();
7894 if is_vim_mode == IsVimMode::Yes {
7895 diff_options.max_word_diff_len = 0;
7896 diff_options.max_word_diff_line_count = 0;
7897 } else {
7898 diff_options.max_word_diff_len = usize::MAX;
7899 diff_options.max_word_diff_line_count = usize::MAX;
7900 }
7901
7902 for (old_range, new_text) in
7903 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
7904 {
7905 let edit_start = buffer.anchor_after(start_offset + old_range.start);
7906 let edit_end = buffer.anchor_after(start_offset + old_range.end);
7907 edits.push((edit_start..edit_end, new_text));
7908 }
7909
7910 rewrapped_row_ranges.push(start_row..=end_row);
7911 }
7912
7913 self.buffer
7914 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7915 }
7916
7917 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7918 let mut text = String::new();
7919 let buffer = self.buffer.read(cx).snapshot(cx);
7920 let mut selections = self.selections.all::<Point>(cx);
7921 let mut clipboard_selections = Vec::with_capacity(selections.len());
7922 {
7923 let max_point = buffer.max_point();
7924 let mut is_first = true;
7925 for selection in &mut selections {
7926 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7927 if is_entire_line {
7928 selection.start = Point::new(selection.start.row, 0);
7929 if !selection.is_empty() && selection.end.column == 0 {
7930 selection.end = cmp::min(max_point, selection.end);
7931 } else {
7932 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7933 }
7934 selection.goal = SelectionGoal::None;
7935 }
7936 if is_first {
7937 is_first = false;
7938 } else {
7939 text += "\n";
7940 }
7941 let mut len = 0;
7942 for chunk in buffer.text_for_range(selection.start..selection.end) {
7943 text.push_str(chunk);
7944 len += chunk.len();
7945 }
7946 clipboard_selections.push(ClipboardSelection {
7947 len,
7948 is_entire_line,
7949 start_column: selection.start.column,
7950 });
7951 }
7952 }
7953
7954 self.transact(window, cx, |this, window, cx| {
7955 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7956 s.select(selections);
7957 });
7958 this.insert("", window, cx);
7959 });
7960 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7961 }
7962
7963 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7964 let item = self.cut_common(window, cx);
7965 cx.write_to_clipboard(item);
7966 }
7967
7968 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7969 self.change_selections(None, window, cx, |s| {
7970 s.move_with(|snapshot, sel| {
7971 if sel.is_empty() {
7972 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7973 }
7974 });
7975 });
7976 let item = self.cut_common(window, cx);
7977 cx.set_global(KillRing(item))
7978 }
7979
7980 pub fn kill_ring_yank(
7981 &mut self,
7982 _: &KillRingYank,
7983 window: &mut Window,
7984 cx: &mut Context<Self>,
7985 ) {
7986 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7987 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7988 (kill_ring.text().to_string(), kill_ring.metadata_json())
7989 } else {
7990 return;
7991 }
7992 } else {
7993 return;
7994 };
7995 self.do_paste(&text, metadata, false, window, cx);
7996 }
7997
7998 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7999 let selections = self.selections.all::<Point>(cx);
8000 let buffer = self.buffer.read(cx).read(cx);
8001 let mut text = String::new();
8002
8003 let mut clipboard_selections = Vec::with_capacity(selections.len());
8004 {
8005 let max_point = buffer.max_point();
8006 let mut is_first = true;
8007 for selection in selections.iter() {
8008 let mut start = selection.start;
8009 let mut end = selection.end;
8010 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8011 if is_entire_line {
8012 start = Point::new(start.row, 0);
8013 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8014 }
8015 if is_first {
8016 is_first = false;
8017 } else {
8018 text += "\n";
8019 }
8020 let mut len = 0;
8021 for chunk in buffer.text_for_range(start..end) {
8022 text.push_str(chunk);
8023 len += chunk.len();
8024 }
8025 clipboard_selections.push(ClipboardSelection {
8026 len,
8027 is_entire_line,
8028 start_column: start.column,
8029 });
8030 }
8031 }
8032
8033 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8034 text,
8035 clipboard_selections,
8036 ));
8037 }
8038
8039 pub fn do_paste(
8040 &mut self,
8041 text: &String,
8042 clipboard_selections: Option<Vec<ClipboardSelection>>,
8043 handle_entire_lines: bool,
8044 window: &mut Window,
8045 cx: &mut Context<Self>,
8046 ) {
8047 if self.read_only(cx) {
8048 return;
8049 }
8050
8051 let clipboard_text = Cow::Borrowed(text);
8052
8053 self.transact(window, cx, |this, window, cx| {
8054 if let Some(mut clipboard_selections) = clipboard_selections {
8055 let old_selections = this.selections.all::<usize>(cx);
8056 let all_selections_were_entire_line =
8057 clipboard_selections.iter().all(|s| s.is_entire_line);
8058 let first_selection_start_column =
8059 clipboard_selections.first().map(|s| s.start_column);
8060 if clipboard_selections.len() != old_selections.len() {
8061 clipboard_selections.drain(..);
8062 }
8063 let cursor_offset = this.selections.last::<usize>(cx).head();
8064 let mut auto_indent_on_paste = true;
8065
8066 this.buffer.update(cx, |buffer, cx| {
8067 let snapshot = buffer.read(cx);
8068 auto_indent_on_paste =
8069 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8070
8071 let mut start_offset = 0;
8072 let mut edits = Vec::new();
8073 let mut original_start_columns = Vec::new();
8074 for (ix, selection) in old_selections.iter().enumerate() {
8075 let to_insert;
8076 let entire_line;
8077 let original_start_column;
8078 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8079 let end_offset = start_offset + clipboard_selection.len;
8080 to_insert = &clipboard_text[start_offset..end_offset];
8081 entire_line = clipboard_selection.is_entire_line;
8082 start_offset = end_offset + 1;
8083 original_start_column = Some(clipboard_selection.start_column);
8084 } else {
8085 to_insert = clipboard_text.as_str();
8086 entire_line = all_selections_were_entire_line;
8087 original_start_column = first_selection_start_column
8088 }
8089
8090 // If the corresponding selection was empty when this slice of the
8091 // clipboard text was written, then the entire line containing the
8092 // selection was copied. If this selection is also currently empty,
8093 // then paste the line before the current line of the buffer.
8094 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8095 let column = selection.start.to_point(&snapshot).column as usize;
8096 let line_start = selection.start - column;
8097 line_start..line_start
8098 } else {
8099 selection.range()
8100 };
8101
8102 edits.push((range, to_insert));
8103 original_start_columns.extend(original_start_column);
8104 }
8105 drop(snapshot);
8106
8107 buffer.edit(
8108 edits,
8109 if auto_indent_on_paste {
8110 Some(AutoindentMode::Block {
8111 original_start_columns,
8112 })
8113 } else {
8114 None
8115 },
8116 cx,
8117 );
8118 });
8119
8120 let selections = this.selections.all::<usize>(cx);
8121 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8122 s.select(selections)
8123 });
8124 } else {
8125 this.insert(&clipboard_text, window, cx);
8126 }
8127 });
8128 }
8129
8130 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8131 if let Some(item) = cx.read_from_clipboard() {
8132 let entries = item.entries();
8133
8134 match entries.first() {
8135 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8136 // of all the pasted entries.
8137 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8138 .do_paste(
8139 clipboard_string.text(),
8140 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8141 true,
8142 window,
8143 cx,
8144 ),
8145 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8146 }
8147 }
8148 }
8149
8150 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8151 if self.read_only(cx) {
8152 return;
8153 }
8154
8155 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8156 if let Some((selections, _)) =
8157 self.selection_history.transaction(transaction_id).cloned()
8158 {
8159 self.change_selections(None, window, cx, |s| {
8160 s.select_anchors(selections.to_vec());
8161 });
8162 }
8163 self.request_autoscroll(Autoscroll::fit(), cx);
8164 self.unmark_text(window, cx);
8165 self.refresh_inline_completion(true, false, window, cx);
8166 cx.emit(EditorEvent::Edited { transaction_id });
8167 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8168 }
8169 }
8170
8171 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8172 if self.read_only(cx) {
8173 return;
8174 }
8175
8176 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8177 if let Some((_, Some(selections))) =
8178 self.selection_history.transaction(transaction_id).cloned()
8179 {
8180 self.change_selections(None, window, cx, |s| {
8181 s.select_anchors(selections.to_vec());
8182 });
8183 }
8184 self.request_autoscroll(Autoscroll::fit(), cx);
8185 self.unmark_text(window, cx);
8186 self.refresh_inline_completion(true, false, window, cx);
8187 cx.emit(EditorEvent::Edited { transaction_id });
8188 }
8189 }
8190
8191 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8192 self.buffer
8193 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8194 }
8195
8196 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8197 self.buffer
8198 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8199 }
8200
8201 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8202 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8203 let line_mode = s.line_mode;
8204 s.move_with(|map, selection| {
8205 let cursor = if selection.is_empty() && !line_mode {
8206 movement::left(map, selection.start)
8207 } else {
8208 selection.start
8209 };
8210 selection.collapse_to(cursor, SelectionGoal::None);
8211 });
8212 })
8213 }
8214
8215 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8216 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8217 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8218 })
8219 }
8220
8221 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8222 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8223 let line_mode = s.line_mode;
8224 s.move_with(|map, selection| {
8225 let cursor = if selection.is_empty() && !line_mode {
8226 movement::right(map, selection.end)
8227 } else {
8228 selection.end
8229 };
8230 selection.collapse_to(cursor, SelectionGoal::None)
8231 });
8232 })
8233 }
8234
8235 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8236 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8237 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8238 })
8239 }
8240
8241 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8242 if self.take_rename(true, window, cx).is_some() {
8243 return;
8244 }
8245
8246 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8247 cx.propagate();
8248 return;
8249 }
8250
8251 let text_layout_details = &self.text_layout_details(window);
8252 let selection_count = self.selections.count();
8253 let first_selection = self.selections.first_anchor();
8254
8255 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8256 let line_mode = s.line_mode;
8257 s.move_with(|map, selection| {
8258 if !selection.is_empty() && !line_mode {
8259 selection.goal = SelectionGoal::None;
8260 }
8261 let (cursor, goal) = movement::up(
8262 map,
8263 selection.start,
8264 selection.goal,
8265 false,
8266 text_layout_details,
8267 );
8268 selection.collapse_to(cursor, goal);
8269 });
8270 });
8271
8272 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8273 {
8274 cx.propagate();
8275 }
8276 }
8277
8278 pub fn move_up_by_lines(
8279 &mut self,
8280 action: &MoveUpByLines,
8281 window: &mut Window,
8282 cx: &mut Context<Self>,
8283 ) {
8284 if self.take_rename(true, window, cx).is_some() {
8285 return;
8286 }
8287
8288 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8289 cx.propagate();
8290 return;
8291 }
8292
8293 let text_layout_details = &self.text_layout_details(window);
8294
8295 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8296 let line_mode = s.line_mode;
8297 s.move_with(|map, selection| {
8298 if !selection.is_empty() && !line_mode {
8299 selection.goal = SelectionGoal::None;
8300 }
8301 let (cursor, goal) = movement::up_by_rows(
8302 map,
8303 selection.start,
8304 action.lines,
8305 selection.goal,
8306 false,
8307 text_layout_details,
8308 );
8309 selection.collapse_to(cursor, goal);
8310 });
8311 })
8312 }
8313
8314 pub fn move_down_by_lines(
8315 &mut self,
8316 action: &MoveDownByLines,
8317 window: &mut Window,
8318 cx: &mut Context<Self>,
8319 ) {
8320 if self.take_rename(true, window, cx).is_some() {
8321 return;
8322 }
8323
8324 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8325 cx.propagate();
8326 return;
8327 }
8328
8329 let text_layout_details = &self.text_layout_details(window);
8330
8331 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8332 let line_mode = s.line_mode;
8333 s.move_with(|map, selection| {
8334 if !selection.is_empty() && !line_mode {
8335 selection.goal = SelectionGoal::None;
8336 }
8337 let (cursor, goal) = movement::down_by_rows(
8338 map,
8339 selection.start,
8340 action.lines,
8341 selection.goal,
8342 false,
8343 text_layout_details,
8344 );
8345 selection.collapse_to(cursor, goal);
8346 });
8347 })
8348 }
8349
8350 pub fn select_down_by_lines(
8351 &mut self,
8352 action: &SelectDownByLines,
8353 window: &mut Window,
8354 cx: &mut Context<Self>,
8355 ) {
8356 let text_layout_details = &self.text_layout_details(window);
8357 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8358 s.move_heads_with(|map, head, goal| {
8359 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8360 })
8361 })
8362 }
8363
8364 pub fn select_up_by_lines(
8365 &mut self,
8366 action: &SelectUpByLines,
8367 window: &mut Window,
8368 cx: &mut Context<Self>,
8369 ) {
8370 let text_layout_details = &self.text_layout_details(window);
8371 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8372 s.move_heads_with(|map, head, goal| {
8373 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8374 })
8375 })
8376 }
8377
8378 pub fn select_page_up(
8379 &mut self,
8380 _: &SelectPageUp,
8381 window: &mut Window,
8382 cx: &mut Context<Self>,
8383 ) {
8384 let Some(row_count) = self.visible_row_count() else {
8385 return;
8386 };
8387
8388 let text_layout_details = &self.text_layout_details(window);
8389
8390 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8391 s.move_heads_with(|map, head, goal| {
8392 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8393 })
8394 })
8395 }
8396
8397 pub fn move_page_up(
8398 &mut self,
8399 action: &MovePageUp,
8400 window: &mut Window,
8401 cx: &mut Context<Self>,
8402 ) {
8403 if self.take_rename(true, window, cx).is_some() {
8404 return;
8405 }
8406
8407 if self
8408 .context_menu
8409 .borrow_mut()
8410 .as_mut()
8411 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8412 .unwrap_or(false)
8413 {
8414 return;
8415 }
8416
8417 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8418 cx.propagate();
8419 return;
8420 }
8421
8422 let Some(row_count) = self.visible_row_count() else {
8423 return;
8424 };
8425
8426 let autoscroll = if action.center_cursor {
8427 Autoscroll::center()
8428 } else {
8429 Autoscroll::fit()
8430 };
8431
8432 let text_layout_details = &self.text_layout_details(window);
8433
8434 self.change_selections(Some(autoscroll), window, cx, |s| {
8435 let line_mode = s.line_mode;
8436 s.move_with(|map, selection| {
8437 if !selection.is_empty() && !line_mode {
8438 selection.goal = SelectionGoal::None;
8439 }
8440 let (cursor, goal) = movement::up_by_rows(
8441 map,
8442 selection.end,
8443 row_count,
8444 selection.goal,
8445 false,
8446 text_layout_details,
8447 );
8448 selection.collapse_to(cursor, goal);
8449 });
8450 });
8451 }
8452
8453 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8454 let text_layout_details = &self.text_layout_details(window);
8455 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8456 s.move_heads_with(|map, head, goal| {
8457 movement::up(map, head, goal, false, text_layout_details)
8458 })
8459 })
8460 }
8461
8462 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8463 self.take_rename(true, window, cx);
8464
8465 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8466 cx.propagate();
8467 return;
8468 }
8469
8470 let text_layout_details = &self.text_layout_details(window);
8471 let selection_count = self.selections.count();
8472 let first_selection = self.selections.first_anchor();
8473
8474 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8475 let line_mode = s.line_mode;
8476 s.move_with(|map, selection| {
8477 if !selection.is_empty() && !line_mode {
8478 selection.goal = SelectionGoal::None;
8479 }
8480 let (cursor, goal) = movement::down(
8481 map,
8482 selection.end,
8483 selection.goal,
8484 false,
8485 text_layout_details,
8486 );
8487 selection.collapse_to(cursor, goal);
8488 });
8489 });
8490
8491 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8492 {
8493 cx.propagate();
8494 }
8495 }
8496
8497 pub fn select_page_down(
8498 &mut self,
8499 _: &SelectPageDown,
8500 window: &mut Window,
8501 cx: &mut Context<Self>,
8502 ) {
8503 let Some(row_count) = self.visible_row_count() else {
8504 return;
8505 };
8506
8507 let text_layout_details = &self.text_layout_details(window);
8508
8509 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8510 s.move_heads_with(|map, head, goal| {
8511 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8512 })
8513 })
8514 }
8515
8516 pub fn move_page_down(
8517 &mut self,
8518 action: &MovePageDown,
8519 window: &mut Window,
8520 cx: &mut Context<Self>,
8521 ) {
8522 if self.take_rename(true, window, cx).is_some() {
8523 return;
8524 }
8525
8526 if self
8527 .context_menu
8528 .borrow_mut()
8529 .as_mut()
8530 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8531 .unwrap_or(false)
8532 {
8533 return;
8534 }
8535
8536 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8537 cx.propagate();
8538 return;
8539 }
8540
8541 let Some(row_count) = self.visible_row_count() else {
8542 return;
8543 };
8544
8545 let autoscroll = if action.center_cursor {
8546 Autoscroll::center()
8547 } else {
8548 Autoscroll::fit()
8549 };
8550
8551 let text_layout_details = &self.text_layout_details(window);
8552 self.change_selections(Some(autoscroll), window, cx, |s| {
8553 let line_mode = s.line_mode;
8554 s.move_with(|map, selection| {
8555 if !selection.is_empty() && !line_mode {
8556 selection.goal = SelectionGoal::None;
8557 }
8558 let (cursor, goal) = movement::down_by_rows(
8559 map,
8560 selection.end,
8561 row_count,
8562 selection.goal,
8563 false,
8564 text_layout_details,
8565 );
8566 selection.collapse_to(cursor, goal);
8567 });
8568 });
8569 }
8570
8571 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8572 let text_layout_details = &self.text_layout_details(window);
8573 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8574 s.move_heads_with(|map, head, goal| {
8575 movement::down(map, head, goal, false, text_layout_details)
8576 })
8577 });
8578 }
8579
8580 pub fn context_menu_first(
8581 &mut self,
8582 _: &ContextMenuFirst,
8583 _window: &mut Window,
8584 cx: &mut Context<Self>,
8585 ) {
8586 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8587 context_menu.select_first(self.completion_provider.as_deref(), cx);
8588 }
8589 }
8590
8591 pub fn context_menu_prev(
8592 &mut self,
8593 _: &ContextMenuPrev,
8594 _window: &mut Window,
8595 cx: &mut Context<Self>,
8596 ) {
8597 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8598 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8599 }
8600 }
8601
8602 pub fn context_menu_next(
8603 &mut self,
8604 _: &ContextMenuNext,
8605 _window: &mut Window,
8606 cx: &mut Context<Self>,
8607 ) {
8608 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8609 context_menu.select_next(self.completion_provider.as_deref(), cx);
8610 }
8611 }
8612
8613 pub fn context_menu_last(
8614 &mut self,
8615 _: &ContextMenuLast,
8616 _window: &mut Window,
8617 cx: &mut Context<Self>,
8618 ) {
8619 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8620 context_menu.select_last(self.completion_provider.as_deref(), cx);
8621 }
8622 }
8623
8624 pub fn move_to_previous_word_start(
8625 &mut self,
8626 _: &MoveToPreviousWordStart,
8627 window: &mut Window,
8628 cx: &mut Context<Self>,
8629 ) {
8630 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8631 s.move_cursors_with(|map, head, _| {
8632 (
8633 movement::previous_word_start(map, head),
8634 SelectionGoal::None,
8635 )
8636 });
8637 })
8638 }
8639
8640 pub fn move_to_previous_subword_start(
8641 &mut self,
8642 _: &MoveToPreviousSubwordStart,
8643 window: &mut Window,
8644 cx: &mut Context<Self>,
8645 ) {
8646 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8647 s.move_cursors_with(|map, head, _| {
8648 (
8649 movement::previous_subword_start(map, head),
8650 SelectionGoal::None,
8651 )
8652 });
8653 })
8654 }
8655
8656 pub fn select_to_previous_word_start(
8657 &mut self,
8658 _: &SelectToPreviousWordStart,
8659 window: &mut Window,
8660 cx: &mut Context<Self>,
8661 ) {
8662 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8663 s.move_heads_with(|map, head, _| {
8664 (
8665 movement::previous_word_start(map, head),
8666 SelectionGoal::None,
8667 )
8668 });
8669 })
8670 }
8671
8672 pub fn select_to_previous_subword_start(
8673 &mut self,
8674 _: &SelectToPreviousSubwordStart,
8675 window: &mut Window,
8676 cx: &mut Context<Self>,
8677 ) {
8678 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8679 s.move_heads_with(|map, head, _| {
8680 (
8681 movement::previous_subword_start(map, head),
8682 SelectionGoal::None,
8683 )
8684 });
8685 })
8686 }
8687
8688 pub fn delete_to_previous_word_start(
8689 &mut self,
8690 action: &DeleteToPreviousWordStart,
8691 window: &mut Window,
8692 cx: &mut Context<Self>,
8693 ) {
8694 self.transact(window, cx, |this, window, cx| {
8695 this.select_autoclose_pair(window, cx);
8696 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8697 let line_mode = s.line_mode;
8698 s.move_with(|map, selection| {
8699 if selection.is_empty() && !line_mode {
8700 let cursor = if action.ignore_newlines {
8701 movement::previous_word_start(map, selection.head())
8702 } else {
8703 movement::previous_word_start_or_newline(map, selection.head())
8704 };
8705 selection.set_head(cursor, SelectionGoal::None);
8706 }
8707 });
8708 });
8709 this.insert("", window, cx);
8710 });
8711 }
8712
8713 pub fn delete_to_previous_subword_start(
8714 &mut self,
8715 _: &DeleteToPreviousSubwordStart,
8716 window: &mut Window,
8717 cx: &mut Context<Self>,
8718 ) {
8719 self.transact(window, cx, |this, window, cx| {
8720 this.select_autoclose_pair(window, cx);
8721 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8722 let line_mode = s.line_mode;
8723 s.move_with(|map, selection| {
8724 if selection.is_empty() && !line_mode {
8725 let cursor = movement::previous_subword_start(map, selection.head());
8726 selection.set_head(cursor, SelectionGoal::None);
8727 }
8728 });
8729 });
8730 this.insert("", window, cx);
8731 });
8732 }
8733
8734 pub fn move_to_next_word_end(
8735 &mut self,
8736 _: &MoveToNextWordEnd,
8737 window: &mut Window,
8738 cx: &mut Context<Self>,
8739 ) {
8740 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8741 s.move_cursors_with(|map, head, _| {
8742 (movement::next_word_end(map, head), SelectionGoal::None)
8743 });
8744 })
8745 }
8746
8747 pub fn move_to_next_subword_end(
8748 &mut self,
8749 _: &MoveToNextSubwordEnd,
8750 window: &mut Window,
8751 cx: &mut Context<Self>,
8752 ) {
8753 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8754 s.move_cursors_with(|map, head, _| {
8755 (movement::next_subword_end(map, head), SelectionGoal::None)
8756 });
8757 })
8758 }
8759
8760 pub fn select_to_next_word_end(
8761 &mut self,
8762 _: &SelectToNextWordEnd,
8763 window: &mut Window,
8764 cx: &mut Context<Self>,
8765 ) {
8766 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8767 s.move_heads_with(|map, head, _| {
8768 (movement::next_word_end(map, head), SelectionGoal::None)
8769 });
8770 })
8771 }
8772
8773 pub fn select_to_next_subword_end(
8774 &mut self,
8775 _: &SelectToNextSubwordEnd,
8776 window: &mut Window,
8777 cx: &mut Context<Self>,
8778 ) {
8779 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8780 s.move_heads_with(|map, head, _| {
8781 (movement::next_subword_end(map, head), SelectionGoal::None)
8782 });
8783 })
8784 }
8785
8786 pub fn delete_to_next_word_end(
8787 &mut self,
8788 action: &DeleteToNextWordEnd,
8789 window: &mut Window,
8790 cx: &mut Context<Self>,
8791 ) {
8792 self.transact(window, cx, |this, window, cx| {
8793 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8794 let line_mode = s.line_mode;
8795 s.move_with(|map, selection| {
8796 if selection.is_empty() && !line_mode {
8797 let cursor = if action.ignore_newlines {
8798 movement::next_word_end(map, selection.head())
8799 } else {
8800 movement::next_word_end_or_newline(map, selection.head())
8801 };
8802 selection.set_head(cursor, SelectionGoal::None);
8803 }
8804 });
8805 });
8806 this.insert("", window, cx);
8807 });
8808 }
8809
8810 pub fn delete_to_next_subword_end(
8811 &mut self,
8812 _: &DeleteToNextSubwordEnd,
8813 window: &mut Window,
8814 cx: &mut Context<Self>,
8815 ) {
8816 self.transact(window, cx, |this, window, cx| {
8817 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8818 s.move_with(|map, selection| {
8819 if selection.is_empty() {
8820 let cursor = movement::next_subword_end(map, selection.head());
8821 selection.set_head(cursor, SelectionGoal::None);
8822 }
8823 });
8824 });
8825 this.insert("", window, cx);
8826 });
8827 }
8828
8829 pub fn move_to_beginning_of_line(
8830 &mut self,
8831 action: &MoveToBeginningOfLine,
8832 window: &mut Window,
8833 cx: &mut Context<Self>,
8834 ) {
8835 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8836 s.move_cursors_with(|map, head, _| {
8837 (
8838 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8839 SelectionGoal::None,
8840 )
8841 });
8842 })
8843 }
8844
8845 pub fn select_to_beginning_of_line(
8846 &mut self,
8847 action: &SelectToBeginningOfLine,
8848 window: &mut Window,
8849 cx: &mut Context<Self>,
8850 ) {
8851 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8852 s.move_heads_with(|map, head, _| {
8853 (
8854 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8855 SelectionGoal::None,
8856 )
8857 });
8858 });
8859 }
8860
8861 pub fn delete_to_beginning_of_line(
8862 &mut self,
8863 _: &DeleteToBeginningOfLine,
8864 window: &mut Window,
8865 cx: &mut Context<Self>,
8866 ) {
8867 self.transact(window, cx, |this, window, cx| {
8868 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8869 s.move_with(|_, selection| {
8870 selection.reversed = true;
8871 });
8872 });
8873
8874 this.select_to_beginning_of_line(
8875 &SelectToBeginningOfLine {
8876 stop_at_soft_wraps: false,
8877 },
8878 window,
8879 cx,
8880 );
8881 this.backspace(&Backspace, window, cx);
8882 });
8883 }
8884
8885 pub fn move_to_end_of_line(
8886 &mut self,
8887 action: &MoveToEndOfLine,
8888 window: &mut Window,
8889 cx: &mut Context<Self>,
8890 ) {
8891 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8892 s.move_cursors_with(|map, head, _| {
8893 (
8894 movement::line_end(map, head, action.stop_at_soft_wraps),
8895 SelectionGoal::None,
8896 )
8897 });
8898 })
8899 }
8900
8901 pub fn select_to_end_of_line(
8902 &mut self,
8903 action: &SelectToEndOfLine,
8904 window: &mut Window,
8905 cx: &mut Context<Self>,
8906 ) {
8907 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8908 s.move_heads_with(|map, head, _| {
8909 (
8910 movement::line_end(map, head, action.stop_at_soft_wraps),
8911 SelectionGoal::None,
8912 )
8913 });
8914 })
8915 }
8916
8917 pub fn delete_to_end_of_line(
8918 &mut self,
8919 _: &DeleteToEndOfLine,
8920 window: &mut Window,
8921 cx: &mut Context<Self>,
8922 ) {
8923 self.transact(window, cx, |this, window, cx| {
8924 this.select_to_end_of_line(
8925 &SelectToEndOfLine {
8926 stop_at_soft_wraps: false,
8927 },
8928 window,
8929 cx,
8930 );
8931 this.delete(&Delete, window, cx);
8932 });
8933 }
8934
8935 pub fn cut_to_end_of_line(
8936 &mut self,
8937 _: &CutToEndOfLine,
8938 window: &mut Window,
8939 cx: &mut Context<Self>,
8940 ) {
8941 self.transact(window, cx, |this, window, cx| {
8942 this.select_to_end_of_line(
8943 &SelectToEndOfLine {
8944 stop_at_soft_wraps: false,
8945 },
8946 window,
8947 cx,
8948 );
8949 this.cut(&Cut, window, cx);
8950 });
8951 }
8952
8953 pub fn move_to_start_of_paragraph(
8954 &mut self,
8955 _: &MoveToStartOfParagraph,
8956 window: &mut Window,
8957 cx: &mut Context<Self>,
8958 ) {
8959 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8960 cx.propagate();
8961 return;
8962 }
8963
8964 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8965 s.move_with(|map, selection| {
8966 selection.collapse_to(
8967 movement::start_of_paragraph(map, selection.head(), 1),
8968 SelectionGoal::None,
8969 )
8970 });
8971 })
8972 }
8973
8974 pub fn move_to_end_of_paragraph(
8975 &mut self,
8976 _: &MoveToEndOfParagraph,
8977 window: &mut Window,
8978 cx: &mut Context<Self>,
8979 ) {
8980 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8981 cx.propagate();
8982 return;
8983 }
8984
8985 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8986 s.move_with(|map, selection| {
8987 selection.collapse_to(
8988 movement::end_of_paragraph(map, selection.head(), 1),
8989 SelectionGoal::None,
8990 )
8991 });
8992 })
8993 }
8994
8995 pub fn select_to_start_of_paragraph(
8996 &mut self,
8997 _: &SelectToStartOfParagraph,
8998 window: &mut Window,
8999 cx: &mut Context<Self>,
9000 ) {
9001 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9002 cx.propagate();
9003 return;
9004 }
9005
9006 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9007 s.move_heads_with(|map, head, _| {
9008 (
9009 movement::start_of_paragraph(map, head, 1),
9010 SelectionGoal::None,
9011 )
9012 });
9013 })
9014 }
9015
9016 pub fn select_to_end_of_paragraph(
9017 &mut self,
9018 _: &SelectToEndOfParagraph,
9019 window: &mut Window,
9020 cx: &mut Context<Self>,
9021 ) {
9022 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9023 cx.propagate();
9024 return;
9025 }
9026
9027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9028 s.move_heads_with(|map, head, _| {
9029 (
9030 movement::end_of_paragraph(map, head, 1),
9031 SelectionGoal::None,
9032 )
9033 });
9034 })
9035 }
9036
9037 pub fn move_to_start_of_excerpt(
9038 &mut self,
9039 _: &MoveToStartOfExcerpt,
9040 window: &mut Window,
9041 cx: &mut Context<Self>,
9042 ) {
9043 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9044 cx.propagate();
9045 return;
9046 }
9047
9048 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9049 s.move_with(|map, selection| {
9050 selection.collapse_to(
9051 movement::start_of_excerpt(
9052 map,
9053 selection.head(),
9054 workspace::searchable::Direction::Prev,
9055 ),
9056 SelectionGoal::None,
9057 )
9058 });
9059 })
9060 }
9061
9062 pub fn move_to_end_of_excerpt(
9063 &mut self,
9064 _: &MoveToEndOfExcerpt,
9065 window: &mut Window,
9066 cx: &mut Context<Self>,
9067 ) {
9068 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9069 cx.propagate();
9070 return;
9071 }
9072
9073 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9074 s.move_with(|map, selection| {
9075 selection.collapse_to(
9076 movement::end_of_excerpt(
9077 map,
9078 selection.head(),
9079 workspace::searchable::Direction::Next,
9080 ),
9081 SelectionGoal::None,
9082 )
9083 });
9084 })
9085 }
9086
9087 pub fn select_to_start_of_excerpt(
9088 &mut self,
9089 _: &SelectToStartOfExcerpt,
9090 window: &mut Window,
9091 cx: &mut Context<Self>,
9092 ) {
9093 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9094 cx.propagate();
9095 return;
9096 }
9097
9098 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9099 s.move_heads_with(|map, head, _| {
9100 (
9101 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9102 SelectionGoal::None,
9103 )
9104 });
9105 })
9106 }
9107
9108 pub fn select_to_end_of_excerpt(
9109 &mut self,
9110 _: &SelectToEndOfExcerpt,
9111 window: &mut Window,
9112 cx: &mut Context<Self>,
9113 ) {
9114 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9115 cx.propagate();
9116 return;
9117 }
9118
9119 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9120 s.move_heads_with(|map, head, _| {
9121 (
9122 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9123 SelectionGoal::None,
9124 )
9125 });
9126 })
9127 }
9128
9129 pub fn move_to_beginning(
9130 &mut self,
9131 _: &MoveToBeginning,
9132 window: &mut Window,
9133 cx: &mut Context<Self>,
9134 ) {
9135 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9136 cx.propagate();
9137 return;
9138 }
9139
9140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9141 s.select_ranges(vec![0..0]);
9142 });
9143 }
9144
9145 pub fn select_to_beginning(
9146 &mut self,
9147 _: &SelectToBeginning,
9148 window: &mut Window,
9149 cx: &mut Context<Self>,
9150 ) {
9151 let mut selection = self.selections.last::<Point>(cx);
9152 selection.set_head(Point::zero(), SelectionGoal::None);
9153
9154 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9155 s.select(vec![selection]);
9156 });
9157 }
9158
9159 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9160 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9161 cx.propagate();
9162 return;
9163 }
9164
9165 let cursor = self.buffer.read(cx).read(cx).len();
9166 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9167 s.select_ranges(vec![cursor..cursor])
9168 });
9169 }
9170
9171 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9172 self.nav_history = nav_history;
9173 }
9174
9175 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9176 self.nav_history.as_ref()
9177 }
9178
9179 fn push_to_nav_history(
9180 &mut self,
9181 cursor_anchor: Anchor,
9182 new_position: Option<Point>,
9183 cx: &mut Context<Self>,
9184 ) {
9185 if let Some(nav_history) = self.nav_history.as_mut() {
9186 let buffer = self.buffer.read(cx).read(cx);
9187 let cursor_position = cursor_anchor.to_point(&buffer);
9188 let scroll_state = self.scroll_manager.anchor();
9189 let scroll_top_row = scroll_state.top_row(&buffer);
9190 drop(buffer);
9191
9192 if let Some(new_position) = new_position {
9193 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9194 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9195 return;
9196 }
9197 }
9198
9199 nav_history.push(
9200 Some(NavigationData {
9201 cursor_anchor,
9202 cursor_position,
9203 scroll_anchor: scroll_state,
9204 scroll_top_row,
9205 }),
9206 cx,
9207 );
9208 }
9209 }
9210
9211 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9212 let buffer = self.buffer.read(cx).snapshot(cx);
9213 let mut selection = self.selections.first::<usize>(cx);
9214 selection.set_head(buffer.len(), SelectionGoal::None);
9215 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9216 s.select(vec![selection]);
9217 });
9218 }
9219
9220 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9221 let end = self.buffer.read(cx).read(cx).len();
9222 self.change_selections(None, window, cx, |s| {
9223 s.select_ranges(vec![0..end]);
9224 });
9225 }
9226
9227 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9229 let mut selections = self.selections.all::<Point>(cx);
9230 let max_point = display_map.buffer_snapshot.max_point();
9231 for selection in &mut selections {
9232 let rows = selection.spanned_rows(true, &display_map);
9233 selection.start = Point::new(rows.start.0, 0);
9234 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9235 selection.reversed = false;
9236 }
9237 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9238 s.select(selections);
9239 });
9240 }
9241
9242 pub fn split_selection_into_lines(
9243 &mut self,
9244 _: &SplitSelectionIntoLines,
9245 window: &mut Window,
9246 cx: &mut Context<Self>,
9247 ) {
9248 let selections = self
9249 .selections
9250 .all::<Point>(cx)
9251 .into_iter()
9252 .map(|selection| selection.start..selection.end)
9253 .collect::<Vec<_>>();
9254 self.unfold_ranges(&selections, true, true, cx);
9255
9256 let mut new_selection_ranges = Vec::new();
9257 {
9258 let buffer = self.buffer.read(cx).read(cx);
9259 for selection in selections {
9260 for row in selection.start.row..selection.end.row {
9261 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9262 new_selection_ranges.push(cursor..cursor);
9263 }
9264
9265 let is_multiline_selection = selection.start.row != selection.end.row;
9266 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9267 // so this action feels more ergonomic when paired with other selection operations
9268 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9269 if !should_skip_last {
9270 new_selection_ranges.push(selection.end..selection.end);
9271 }
9272 }
9273 }
9274 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9275 s.select_ranges(new_selection_ranges);
9276 });
9277 }
9278
9279 pub fn add_selection_above(
9280 &mut self,
9281 _: &AddSelectionAbove,
9282 window: &mut Window,
9283 cx: &mut Context<Self>,
9284 ) {
9285 self.add_selection(true, window, cx);
9286 }
9287
9288 pub fn add_selection_below(
9289 &mut self,
9290 _: &AddSelectionBelow,
9291 window: &mut Window,
9292 cx: &mut Context<Self>,
9293 ) {
9294 self.add_selection(false, window, cx);
9295 }
9296
9297 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9298 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9299 let mut selections = self.selections.all::<Point>(cx);
9300 let text_layout_details = self.text_layout_details(window);
9301 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9302 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9303 let range = oldest_selection.display_range(&display_map).sorted();
9304
9305 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9306 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9307 let positions = start_x.min(end_x)..start_x.max(end_x);
9308
9309 selections.clear();
9310 let mut stack = Vec::new();
9311 for row in range.start.row().0..=range.end.row().0 {
9312 if let Some(selection) = self.selections.build_columnar_selection(
9313 &display_map,
9314 DisplayRow(row),
9315 &positions,
9316 oldest_selection.reversed,
9317 &text_layout_details,
9318 ) {
9319 stack.push(selection.id);
9320 selections.push(selection);
9321 }
9322 }
9323
9324 if above {
9325 stack.reverse();
9326 }
9327
9328 AddSelectionsState { above, stack }
9329 });
9330
9331 let last_added_selection = *state.stack.last().unwrap();
9332 let mut new_selections = Vec::new();
9333 if above == state.above {
9334 let end_row = if above {
9335 DisplayRow(0)
9336 } else {
9337 display_map.max_point().row()
9338 };
9339
9340 'outer: for selection in selections {
9341 if selection.id == last_added_selection {
9342 let range = selection.display_range(&display_map).sorted();
9343 debug_assert_eq!(range.start.row(), range.end.row());
9344 let mut row = range.start.row();
9345 let positions =
9346 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9347 px(start)..px(end)
9348 } else {
9349 let start_x =
9350 display_map.x_for_display_point(range.start, &text_layout_details);
9351 let end_x =
9352 display_map.x_for_display_point(range.end, &text_layout_details);
9353 start_x.min(end_x)..start_x.max(end_x)
9354 };
9355
9356 while row != end_row {
9357 if above {
9358 row.0 -= 1;
9359 } else {
9360 row.0 += 1;
9361 }
9362
9363 if let Some(new_selection) = self.selections.build_columnar_selection(
9364 &display_map,
9365 row,
9366 &positions,
9367 selection.reversed,
9368 &text_layout_details,
9369 ) {
9370 state.stack.push(new_selection.id);
9371 if above {
9372 new_selections.push(new_selection);
9373 new_selections.push(selection);
9374 } else {
9375 new_selections.push(selection);
9376 new_selections.push(new_selection);
9377 }
9378
9379 continue 'outer;
9380 }
9381 }
9382 }
9383
9384 new_selections.push(selection);
9385 }
9386 } else {
9387 new_selections = selections;
9388 new_selections.retain(|s| s.id != last_added_selection);
9389 state.stack.pop();
9390 }
9391
9392 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9393 s.select(new_selections);
9394 });
9395 if state.stack.len() > 1 {
9396 self.add_selections_state = Some(state);
9397 }
9398 }
9399
9400 pub fn select_next_match_internal(
9401 &mut self,
9402 display_map: &DisplaySnapshot,
9403 replace_newest: bool,
9404 autoscroll: Option<Autoscroll>,
9405 window: &mut Window,
9406 cx: &mut Context<Self>,
9407 ) -> Result<()> {
9408 fn select_next_match_ranges(
9409 this: &mut Editor,
9410 range: Range<usize>,
9411 replace_newest: bool,
9412 auto_scroll: Option<Autoscroll>,
9413 window: &mut Window,
9414 cx: &mut Context<Editor>,
9415 ) {
9416 this.unfold_ranges(&[range.clone()], false, true, cx);
9417 this.change_selections(auto_scroll, window, cx, |s| {
9418 if replace_newest {
9419 s.delete(s.newest_anchor().id);
9420 }
9421 s.insert_range(range.clone());
9422 });
9423 }
9424
9425 let buffer = &display_map.buffer_snapshot;
9426 let mut selections = self.selections.all::<usize>(cx);
9427 if let Some(mut select_next_state) = self.select_next_state.take() {
9428 let query = &select_next_state.query;
9429 if !select_next_state.done {
9430 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9431 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9432 let mut next_selected_range = None;
9433
9434 let bytes_after_last_selection =
9435 buffer.bytes_in_range(last_selection.end..buffer.len());
9436 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9437 let query_matches = query
9438 .stream_find_iter(bytes_after_last_selection)
9439 .map(|result| (last_selection.end, result))
9440 .chain(
9441 query
9442 .stream_find_iter(bytes_before_first_selection)
9443 .map(|result| (0, result)),
9444 );
9445
9446 for (start_offset, query_match) in query_matches {
9447 let query_match = query_match.unwrap(); // can only fail due to I/O
9448 let offset_range =
9449 start_offset + query_match.start()..start_offset + query_match.end();
9450 let display_range = offset_range.start.to_display_point(display_map)
9451 ..offset_range.end.to_display_point(display_map);
9452
9453 if !select_next_state.wordwise
9454 || (!movement::is_inside_word(display_map, display_range.start)
9455 && !movement::is_inside_word(display_map, display_range.end))
9456 {
9457 // TODO: This is n^2, because we might check all the selections
9458 if !selections
9459 .iter()
9460 .any(|selection| selection.range().overlaps(&offset_range))
9461 {
9462 next_selected_range = Some(offset_range);
9463 break;
9464 }
9465 }
9466 }
9467
9468 if let Some(next_selected_range) = next_selected_range {
9469 select_next_match_ranges(
9470 self,
9471 next_selected_range,
9472 replace_newest,
9473 autoscroll,
9474 window,
9475 cx,
9476 );
9477 } else {
9478 select_next_state.done = true;
9479 }
9480 }
9481
9482 self.select_next_state = Some(select_next_state);
9483 } else {
9484 let mut only_carets = true;
9485 let mut same_text_selected = true;
9486 let mut selected_text = None;
9487
9488 let mut selections_iter = selections.iter().peekable();
9489 while let Some(selection) = selections_iter.next() {
9490 if selection.start != selection.end {
9491 only_carets = false;
9492 }
9493
9494 if same_text_selected {
9495 if selected_text.is_none() {
9496 selected_text =
9497 Some(buffer.text_for_range(selection.range()).collect::<String>());
9498 }
9499
9500 if let Some(next_selection) = selections_iter.peek() {
9501 if next_selection.range().len() == selection.range().len() {
9502 let next_selected_text = buffer
9503 .text_for_range(next_selection.range())
9504 .collect::<String>();
9505 if Some(next_selected_text) != selected_text {
9506 same_text_selected = false;
9507 selected_text = None;
9508 }
9509 } else {
9510 same_text_selected = false;
9511 selected_text = None;
9512 }
9513 }
9514 }
9515 }
9516
9517 if only_carets {
9518 for selection in &mut selections {
9519 let word_range = movement::surrounding_word(
9520 display_map,
9521 selection.start.to_display_point(display_map),
9522 );
9523 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9524 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9525 selection.goal = SelectionGoal::None;
9526 selection.reversed = false;
9527 select_next_match_ranges(
9528 self,
9529 selection.start..selection.end,
9530 replace_newest,
9531 autoscroll,
9532 window,
9533 cx,
9534 );
9535 }
9536
9537 if selections.len() == 1 {
9538 let selection = selections
9539 .last()
9540 .expect("ensured that there's only one selection");
9541 let query = buffer
9542 .text_for_range(selection.start..selection.end)
9543 .collect::<String>();
9544 let is_empty = query.is_empty();
9545 let select_state = SelectNextState {
9546 query: AhoCorasick::new(&[query])?,
9547 wordwise: true,
9548 done: is_empty,
9549 };
9550 self.select_next_state = Some(select_state);
9551 } else {
9552 self.select_next_state = None;
9553 }
9554 } else if let Some(selected_text) = selected_text {
9555 self.select_next_state = Some(SelectNextState {
9556 query: AhoCorasick::new(&[selected_text])?,
9557 wordwise: false,
9558 done: false,
9559 });
9560 self.select_next_match_internal(
9561 display_map,
9562 replace_newest,
9563 autoscroll,
9564 window,
9565 cx,
9566 )?;
9567 }
9568 }
9569 Ok(())
9570 }
9571
9572 pub fn select_all_matches(
9573 &mut self,
9574 _action: &SelectAllMatches,
9575 window: &mut Window,
9576 cx: &mut Context<Self>,
9577 ) -> Result<()> {
9578 self.push_to_selection_history();
9579 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9580
9581 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9582 let Some(select_next_state) = self.select_next_state.as_mut() else {
9583 return Ok(());
9584 };
9585 if select_next_state.done {
9586 return Ok(());
9587 }
9588
9589 let mut new_selections = self.selections.all::<usize>(cx);
9590
9591 let buffer = &display_map.buffer_snapshot;
9592 let query_matches = select_next_state
9593 .query
9594 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9595
9596 for query_match in query_matches {
9597 let query_match = query_match.unwrap(); // can only fail due to I/O
9598 let offset_range = query_match.start()..query_match.end();
9599 let display_range = offset_range.start.to_display_point(&display_map)
9600 ..offset_range.end.to_display_point(&display_map);
9601
9602 if !select_next_state.wordwise
9603 || (!movement::is_inside_word(&display_map, display_range.start)
9604 && !movement::is_inside_word(&display_map, display_range.end))
9605 {
9606 self.selections.change_with(cx, |selections| {
9607 new_selections.push(Selection {
9608 id: selections.new_selection_id(),
9609 start: offset_range.start,
9610 end: offset_range.end,
9611 reversed: false,
9612 goal: SelectionGoal::None,
9613 });
9614 });
9615 }
9616 }
9617
9618 new_selections.sort_by_key(|selection| selection.start);
9619 let mut ix = 0;
9620 while ix + 1 < new_selections.len() {
9621 let current_selection = &new_selections[ix];
9622 let next_selection = &new_selections[ix + 1];
9623 if current_selection.range().overlaps(&next_selection.range()) {
9624 if current_selection.id < next_selection.id {
9625 new_selections.remove(ix + 1);
9626 } else {
9627 new_selections.remove(ix);
9628 }
9629 } else {
9630 ix += 1;
9631 }
9632 }
9633
9634 let reversed = self.selections.oldest::<usize>(cx).reversed;
9635
9636 for selection in new_selections.iter_mut() {
9637 selection.reversed = reversed;
9638 }
9639
9640 select_next_state.done = true;
9641 self.unfold_ranges(
9642 &new_selections
9643 .iter()
9644 .map(|selection| selection.range())
9645 .collect::<Vec<_>>(),
9646 false,
9647 false,
9648 cx,
9649 );
9650 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9651 selections.select(new_selections)
9652 });
9653
9654 Ok(())
9655 }
9656
9657 pub fn select_next(
9658 &mut self,
9659 action: &SelectNext,
9660 window: &mut Window,
9661 cx: &mut Context<Self>,
9662 ) -> Result<()> {
9663 self.push_to_selection_history();
9664 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9665 self.select_next_match_internal(
9666 &display_map,
9667 action.replace_newest,
9668 Some(Autoscroll::newest()),
9669 window,
9670 cx,
9671 )?;
9672 Ok(())
9673 }
9674
9675 pub fn select_previous(
9676 &mut self,
9677 action: &SelectPrevious,
9678 window: &mut Window,
9679 cx: &mut Context<Self>,
9680 ) -> Result<()> {
9681 self.push_to_selection_history();
9682 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9683 let buffer = &display_map.buffer_snapshot;
9684 let mut selections = self.selections.all::<usize>(cx);
9685 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9686 let query = &select_prev_state.query;
9687 if !select_prev_state.done {
9688 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9689 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9690 let mut next_selected_range = None;
9691 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9692 let bytes_before_last_selection =
9693 buffer.reversed_bytes_in_range(0..last_selection.start);
9694 let bytes_after_first_selection =
9695 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9696 let query_matches = query
9697 .stream_find_iter(bytes_before_last_selection)
9698 .map(|result| (last_selection.start, result))
9699 .chain(
9700 query
9701 .stream_find_iter(bytes_after_first_selection)
9702 .map(|result| (buffer.len(), result)),
9703 );
9704 for (end_offset, query_match) in query_matches {
9705 let query_match = query_match.unwrap(); // can only fail due to I/O
9706 let offset_range =
9707 end_offset - query_match.end()..end_offset - query_match.start();
9708 let display_range = offset_range.start.to_display_point(&display_map)
9709 ..offset_range.end.to_display_point(&display_map);
9710
9711 if !select_prev_state.wordwise
9712 || (!movement::is_inside_word(&display_map, display_range.start)
9713 && !movement::is_inside_word(&display_map, display_range.end))
9714 {
9715 next_selected_range = Some(offset_range);
9716 break;
9717 }
9718 }
9719
9720 if let Some(next_selected_range) = next_selected_range {
9721 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9722 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9723 if action.replace_newest {
9724 s.delete(s.newest_anchor().id);
9725 }
9726 s.insert_range(next_selected_range);
9727 });
9728 } else {
9729 select_prev_state.done = true;
9730 }
9731 }
9732
9733 self.select_prev_state = Some(select_prev_state);
9734 } else {
9735 let mut only_carets = true;
9736 let mut same_text_selected = true;
9737 let mut selected_text = None;
9738
9739 let mut selections_iter = selections.iter().peekable();
9740 while let Some(selection) = selections_iter.next() {
9741 if selection.start != selection.end {
9742 only_carets = false;
9743 }
9744
9745 if same_text_selected {
9746 if selected_text.is_none() {
9747 selected_text =
9748 Some(buffer.text_for_range(selection.range()).collect::<String>());
9749 }
9750
9751 if let Some(next_selection) = selections_iter.peek() {
9752 if next_selection.range().len() == selection.range().len() {
9753 let next_selected_text = buffer
9754 .text_for_range(next_selection.range())
9755 .collect::<String>();
9756 if Some(next_selected_text) != selected_text {
9757 same_text_selected = false;
9758 selected_text = None;
9759 }
9760 } else {
9761 same_text_selected = false;
9762 selected_text = None;
9763 }
9764 }
9765 }
9766 }
9767
9768 if only_carets {
9769 for selection in &mut selections {
9770 let word_range = movement::surrounding_word(
9771 &display_map,
9772 selection.start.to_display_point(&display_map),
9773 );
9774 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9775 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9776 selection.goal = SelectionGoal::None;
9777 selection.reversed = false;
9778 }
9779 if selections.len() == 1 {
9780 let selection = selections
9781 .last()
9782 .expect("ensured that there's only one selection");
9783 let query = buffer
9784 .text_for_range(selection.start..selection.end)
9785 .collect::<String>();
9786 let is_empty = query.is_empty();
9787 let select_state = SelectNextState {
9788 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9789 wordwise: true,
9790 done: is_empty,
9791 };
9792 self.select_prev_state = Some(select_state);
9793 } else {
9794 self.select_prev_state = None;
9795 }
9796
9797 self.unfold_ranges(
9798 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9799 false,
9800 true,
9801 cx,
9802 );
9803 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9804 s.select(selections);
9805 });
9806 } else if let Some(selected_text) = selected_text {
9807 self.select_prev_state = Some(SelectNextState {
9808 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9809 wordwise: false,
9810 done: false,
9811 });
9812 self.select_previous(action, window, cx)?;
9813 }
9814 }
9815 Ok(())
9816 }
9817
9818 pub fn toggle_comments(
9819 &mut self,
9820 action: &ToggleComments,
9821 window: &mut Window,
9822 cx: &mut Context<Self>,
9823 ) {
9824 if self.read_only(cx) {
9825 return;
9826 }
9827 let text_layout_details = &self.text_layout_details(window);
9828 self.transact(window, cx, |this, window, cx| {
9829 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9830 let mut edits = Vec::new();
9831 let mut selection_edit_ranges = Vec::new();
9832 let mut last_toggled_row = None;
9833 let snapshot = this.buffer.read(cx).read(cx);
9834 let empty_str: Arc<str> = Arc::default();
9835 let mut suffixes_inserted = Vec::new();
9836 let ignore_indent = action.ignore_indent;
9837
9838 fn comment_prefix_range(
9839 snapshot: &MultiBufferSnapshot,
9840 row: MultiBufferRow,
9841 comment_prefix: &str,
9842 comment_prefix_whitespace: &str,
9843 ignore_indent: bool,
9844 ) -> Range<Point> {
9845 let indent_size = if ignore_indent {
9846 0
9847 } else {
9848 snapshot.indent_size_for_line(row).len
9849 };
9850
9851 let start = Point::new(row.0, indent_size);
9852
9853 let mut line_bytes = snapshot
9854 .bytes_in_range(start..snapshot.max_point())
9855 .flatten()
9856 .copied();
9857
9858 // If this line currently begins with the line comment prefix, then record
9859 // the range containing the prefix.
9860 if line_bytes
9861 .by_ref()
9862 .take(comment_prefix.len())
9863 .eq(comment_prefix.bytes())
9864 {
9865 // Include any whitespace that matches the comment prefix.
9866 let matching_whitespace_len = line_bytes
9867 .zip(comment_prefix_whitespace.bytes())
9868 .take_while(|(a, b)| a == b)
9869 .count() as u32;
9870 let end = Point::new(
9871 start.row,
9872 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9873 );
9874 start..end
9875 } else {
9876 start..start
9877 }
9878 }
9879
9880 fn comment_suffix_range(
9881 snapshot: &MultiBufferSnapshot,
9882 row: MultiBufferRow,
9883 comment_suffix: &str,
9884 comment_suffix_has_leading_space: bool,
9885 ) -> Range<Point> {
9886 let end = Point::new(row.0, snapshot.line_len(row));
9887 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9888
9889 let mut line_end_bytes = snapshot
9890 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9891 .flatten()
9892 .copied();
9893
9894 let leading_space_len = if suffix_start_column > 0
9895 && line_end_bytes.next() == Some(b' ')
9896 && comment_suffix_has_leading_space
9897 {
9898 1
9899 } else {
9900 0
9901 };
9902
9903 // If this line currently begins with the line comment prefix, then record
9904 // the range containing the prefix.
9905 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9906 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9907 start..end
9908 } else {
9909 end..end
9910 }
9911 }
9912
9913 // TODO: Handle selections that cross excerpts
9914 for selection in &mut selections {
9915 let start_column = snapshot
9916 .indent_size_for_line(MultiBufferRow(selection.start.row))
9917 .len;
9918 let language = if let Some(language) =
9919 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9920 {
9921 language
9922 } else {
9923 continue;
9924 };
9925
9926 selection_edit_ranges.clear();
9927
9928 // If multiple selections contain a given row, avoid processing that
9929 // row more than once.
9930 let mut start_row = MultiBufferRow(selection.start.row);
9931 if last_toggled_row == Some(start_row) {
9932 start_row = start_row.next_row();
9933 }
9934 let end_row =
9935 if selection.end.row > selection.start.row && selection.end.column == 0 {
9936 MultiBufferRow(selection.end.row - 1)
9937 } else {
9938 MultiBufferRow(selection.end.row)
9939 };
9940 last_toggled_row = Some(end_row);
9941
9942 if start_row > end_row {
9943 continue;
9944 }
9945
9946 // If the language has line comments, toggle those.
9947 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9948
9949 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9950 if ignore_indent {
9951 full_comment_prefixes = full_comment_prefixes
9952 .into_iter()
9953 .map(|s| Arc::from(s.trim_end()))
9954 .collect();
9955 }
9956
9957 if !full_comment_prefixes.is_empty() {
9958 let first_prefix = full_comment_prefixes
9959 .first()
9960 .expect("prefixes is non-empty");
9961 let prefix_trimmed_lengths = full_comment_prefixes
9962 .iter()
9963 .map(|p| p.trim_end_matches(' ').len())
9964 .collect::<SmallVec<[usize; 4]>>();
9965
9966 let mut all_selection_lines_are_comments = true;
9967
9968 for row in start_row.0..=end_row.0 {
9969 let row = MultiBufferRow(row);
9970 if start_row < end_row && snapshot.is_line_blank(row) {
9971 continue;
9972 }
9973
9974 let prefix_range = full_comment_prefixes
9975 .iter()
9976 .zip(prefix_trimmed_lengths.iter().copied())
9977 .map(|(prefix, trimmed_prefix_len)| {
9978 comment_prefix_range(
9979 snapshot.deref(),
9980 row,
9981 &prefix[..trimmed_prefix_len],
9982 &prefix[trimmed_prefix_len..],
9983 ignore_indent,
9984 )
9985 })
9986 .max_by_key(|range| range.end.column - range.start.column)
9987 .expect("prefixes is non-empty");
9988
9989 if prefix_range.is_empty() {
9990 all_selection_lines_are_comments = false;
9991 }
9992
9993 selection_edit_ranges.push(prefix_range);
9994 }
9995
9996 if all_selection_lines_are_comments {
9997 edits.extend(
9998 selection_edit_ranges
9999 .iter()
10000 .cloned()
10001 .map(|range| (range, empty_str.clone())),
10002 );
10003 } else {
10004 let min_column = selection_edit_ranges
10005 .iter()
10006 .map(|range| range.start.column)
10007 .min()
10008 .unwrap_or(0);
10009 edits.extend(selection_edit_ranges.iter().map(|range| {
10010 let position = Point::new(range.start.row, min_column);
10011 (position..position, first_prefix.clone())
10012 }));
10013 }
10014 } else if let Some((full_comment_prefix, comment_suffix)) =
10015 language.block_comment_delimiters()
10016 {
10017 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10018 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10019 let prefix_range = comment_prefix_range(
10020 snapshot.deref(),
10021 start_row,
10022 comment_prefix,
10023 comment_prefix_whitespace,
10024 ignore_indent,
10025 );
10026 let suffix_range = comment_suffix_range(
10027 snapshot.deref(),
10028 end_row,
10029 comment_suffix.trim_start_matches(' '),
10030 comment_suffix.starts_with(' '),
10031 );
10032
10033 if prefix_range.is_empty() || suffix_range.is_empty() {
10034 edits.push((
10035 prefix_range.start..prefix_range.start,
10036 full_comment_prefix.clone(),
10037 ));
10038 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10039 suffixes_inserted.push((end_row, comment_suffix.len()));
10040 } else {
10041 edits.push((prefix_range, empty_str.clone()));
10042 edits.push((suffix_range, empty_str.clone()));
10043 }
10044 } else {
10045 continue;
10046 }
10047 }
10048
10049 drop(snapshot);
10050 this.buffer.update(cx, |buffer, cx| {
10051 buffer.edit(edits, None, cx);
10052 });
10053
10054 // Adjust selections so that they end before any comment suffixes that
10055 // were inserted.
10056 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10057 let mut selections = this.selections.all::<Point>(cx);
10058 let snapshot = this.buffer.read(cx).read(cx);
10059 for selection in &mut selections {
10060 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10061 match row.cmp(&MultiBufferRow(selection.end.row)) {
10062 Ordering::Less => {
10063 suffixes_inserted.next();
10064 continue;
10065 }
10066 Ordering::Greater => break,
10067 Ordering::Equal => {
10068 if selection.end.column == snapshot.line_len(row) {
10069 if selection.is_empty() {
10070 selection.start.column -= suffix_len as u32;
10071 }
10072 selection.end.column -= suffix_len as u32;
10073 }
10074 break;
10075 }
10076 }
10077 }
10078 }
10079
10080 drop(snapshot);
10081 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10082 s.select(selections)
10083 });
10084
10085 let selections = this.selections.all::<Point>(cx);
10086 let selections_on_single_row = selections.windows(2).all(|selections| {
10087 selections[0].start.row == selections[1].start.row
10088 && selections[0].end.row == selections[1].end.row
10089 && selections[0].start.row == selections[0].end.row
10090 });
10091 let selections_selecting = selections
10092 .iter()
10093 .any(|selection| selection.start != selection.end);
10094 let advance_downwards = action.advance_downwards
10095 && selections_on_single_row
10096 && !selections_selecting
10097 && !matches!(this.mode, EditorMode::SingleLine { .. });
10098
10099 if advance_downwards {
10100 let snapshot = this.buffer.read(cx).snapshot(cx);
10101
10102 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10103 s.move_cursors_with(|display_snapshot, display_point, _| {
10104 let mut point = display_point.to_point(display_snapshot);
10105 point.row += 1;
10106 point = snapshot.clip_point(point, Bias::Left);
10107 let display_point = point.to_display_point(display_snapshot);
10108 let goal = SelectionGoal::HorizontalPosition(
10109 display_snapshot
10110 .x_for_display_point(display_point, text_layout_details)
10111 .into(),
10112 );
10113 (display_point, goal)
10114 })
10115 });
10116 }
10117 });
10118 }
10119
10120 pub fn select_enclosing_symbol(
10121 &mut self,
10122 _: &SelectEnclosingSymbol,
10123 window: &mut Window,
10124 cx: &mut Context<Self>,
10125 ) {
10126 let buffer = self.buffer.read(cx).snapshot(cx);
10127 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10128
10129 fn update_selection(
10130 selection: &Selection<usize>,
10131 buffer_snap: &MultiBufferSnapshot,
10132 ) -> Option<Selection<usize>> {
10133 let cursor = selection.head();
10134 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10135 for symbol in symbols.iter().rev() {
10136 let start = symbol.range.start.to_offset(buffer_snap);
10137 let end = symbol.range.end.to_offset(buffer_snap);
10138 let new_range = start..end;
10139 if start < selection.start || end > selection.end {
10140 return Some(Selection {
10141 id: selection.id,
10142 start: new_range.start,
10143 end: new_range.end,
10144 goal: SelectionGoal::None,
10145 reversed: selection.reversed,
10146 });
10147 }
10148 }
10149 None
10150 }
10151
10152 let mut selected_larger_symbol = false;
10153 let new_selections = old_selections
10154 .iter()
10155 .map(|selection| match update_selection(selection, &buffer) {
10156 Some(new_selection) => {
10157 if new_selection.range() != selection.range() {
10158 selected_larger_symbol = true;
10159 }
10160 new_selection
10161 }
10162 None => selection.clone(),
10163 })
10164 .collect::<Vec<_>>();
10165
10166 if selected_larger_symbol {
10167 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10168 s.select(new_selections);
10169 });
10170 }
10171 }
10172
10173 pub fn select_larger_syntax_node(
10174 &mut self,
10175 _: &SelectLargerSyntaxNode,
10176 window: &mut Window,
10177 cx: &mut Context<Self>,
10178 ) {
10179 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10180 let buffer = self.buffer.read(cx).snapshot(cx);
10181 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10182
10183 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10184 let mut selected_larger_node = false;
10185 let new_selections = old_selections
10186 .iter()
10187 .map(|selection| {
10188 let old_range = selection.start..selection.end;
10189 let mut new_range = old_range.clone();
10190 let mut new_node = None;
10191 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10192 {
10193 new_node = Some(node);
10194 new_range = containing_range;
10195 if !display_map.intersects_fold(new_range.start)
10196 && !display_map.intersects_fold(new_range.end)
10197 {
10198 break;
10199 }
10200 }
10201
10202 if let Some(node) = new_node {
10203 // Log the ancestor, to support using this action as a way to explore TreeSitter
10204 // nodes. Parent and grandparent are also logged because this operation will not
10205 // visit nodes that have the same range as their parent.
10206 log::info!("Node: {node:?}");
10207 let parent = node.parent();
10208 log::info!("Parent: {parent:?}");
10209 let grandparent = parent.and_then(|x| x.parent());
10210 log::info!("Grandparent: {grandparent:?}");
10211 }
10212
10213 selected_larger_node |= new_range != old_range;
10214 Selection {
10215 id: selection.id,
10216 start: new_range.start,
10217 end: new_range.end,
10218 goal: SelectionGoal::None,
10219 reversed: selection.reversed,
10220 }
10221 })
10222 .collect::<Vec<_>>();
10223
10224 if selected_larger_node {
10225 stack.push(old_selections);
10226 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10227 s.select(new_selections);
10228 });
10229 }
10230 self.select_larger_syntax_node_stack = stack;
10231 }
10232
10233 pub fn select_smaller_syntax_node(
10234 &mut self,
10235 _: &SelectSmallerSyntaxNode,
10236 window: &mut Window,
10237 cx: &mut Context<Self>,
10238 ) {
10239 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10240 if let Some(selections) = stack.pop() {
10241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10242 s.select(selections.to_vec());
10243 });
10244 }
10245 self.select_larger_syntax_node_stack = stack;
10246 }
10247
10248 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10249 if !EditorSettings::get_global(cx).gutter.runnables {
10250 self.clear_tasks();
10251 return Task::ready(());
10252 }
10253 let project = self.project.as_ref().map(Entity::downgrade);
10254 cx.spawn_in(window, |this, mut cx| async move {
10255 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10256 let Some(project) = project.and_then(|p| p.upgrade()) else {
10257 return;
10258 };
10259 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10260 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10261 }) else {
10262 return;
10263 };
10264
10265 let hide_runnables = project
10266 .update(&mut cx, |project, cx| {
10267 // Do not display any test indicators in non-dev server remote projects.
10268 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10269 })
10270 .unwrap_or(true);
10271 if hide_runnables {
10272 return;
10273 }
10274 let new_rows =
10275 cx.background_spawn({
10276 let snapshot = display_snapshot.clone();
10277 async move {
10278 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10279 }
10280 })
10281 .await;
10282
10283 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10284 this.update(&mut cx, |this, _| {
10285 this.clear_tasks();
10286 for (key, value) in rows {
10287 this.insert_tasks(key, value);
10288 }
10289 })
10290 .ok();
10291 })
10292 }
10293 fn fetch_runnable_ranges(
10294 snapshot: &DisplaySnapshot,
10295 range: Range<Anchor>,
10296 ) -> Vec<language::RunnableRange> {
10297 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10298 }
10299
10300 fn runnable_rows(
10301 project: Entity<Project>,
10302 snapshot: DisplaySnapshot,
10303 runnable_ranges: Vec<RunnableRange>,
10304 mut cx: AsyncWindowContext,
10305 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10306 runnable_ranges
10307 .into_iter()
10308 .filter_map(|mut runnable| {
10309 let tasks = cx
10310 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10311 .ok()?;
10312 if tasks.is_empty() {
10313 return None;
10314 }
10315
10316 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10317
10318 let row = snapshot
10319 .buffer_snapshot
10320 .buffer_line_for_row(MultiBufferRow(point.row))?
10321 .1
10322 .start
10323 .row;
10324
10325 let context_range =
10326 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10327 Some((
10328 (runnable.buffer_id, row),
10329 RunnableTasks {
10330 templates: tasks,
10331 offset: MultiBufferOffset(runnable.run_range.start),
10332 context_range,
10333 column: point.column,
10334 extra_variables: runnable.extra_captures,
10335 },
10336 ))
10337 })
10338 .collect()
10339 }
10340
10341 fn templates_with_tags(
10342 project: &Entity<Project>,
10343 runnable: &mut Runnable,
10344 cx: &mut App,
10345 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10346 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10347 let (worktree_id, file) = project
10348 .buffer_for_id(runnable.buffer, cx)
10349 .and_then(|buffer| buffer.read(cx).file())
10350 .map(|file| (file.worktree_id(cx), file.clone()))
10351 .unzip();
10352
10353 (
10354 project.task_store().read(cx).task_inventory().cloned(),
10355 worktree_id,
10356 file,
10357 )
10358 });
10359
10360 let tags = mem::take(&mut runnable.tags);
10361 let mut tags: Vec<_> = tags
10362 .into_iter()
10363 .flat_map(|tag| {
10364 let tag = tag.0.clone();
10365 inventory
10366 .as_ref()
10367 .into_iter()
10368 .flat_map(|inventory| {
10369 inventory.read(cx).list_tasks(
10370 file.clone(),
10371 Some(runnable.language.clone()),
10372 worktree_id,
10373 cx,
10374 )
10375 })
10376 .filter(move |(_, template)| {
10377 template.tags.iter().any(|source_tag| source_tag == &tag)
10378 })
10379 })
10380 .sorted_by_key(|(kind, _)| kind.to_owned())
10381 .collect();
10382 if let Some((leading_tag_source, _)) = tags.first() {
10383 // Strongest source wins; if we have worktree tag binding, prefer that to
10384 // global and language bindings;
10385 // if we have a global binding, prefer that to language binding.
10386 let first_mismatch = tags
10387 .iter()
10388 .position(|(tag_source, _)| tag_source != leading_tag_source);
10389 if let Some(index) = first_mismatch {
10390 tags.truncate(index);
10391 }
10392 }
10393
10394 tags
10395 }
10396
10397 pub fn move_to_enclosing_bracket(
10398 &mut self,
10399 _: &MoveToEnclosingBracket,
10400 window: &mut Window,
10401 cx: &mut Context<Self>,
10402 ) {
10403 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10404 s.move_offsets_with(|snapshot, selection| {
10405 let Some(enclosing_bracket_ranges) =
10406 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10407 else {
10408 return;
10409 };
10410
10411 let mut best_length = usize::MAX;
10412 let mut best_inside = false;
10413 let mut best_in_bracket_range = false;
10414 let mut best_destination = None;
10415 for (open, close) in enclosing_bracket_ranges {
10416 let close = close.to_inclusive();
10417 let length = close.end() - open.start;
10418 let inside = selection.start >= open.end && selection.end <= *close.start();
10419 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10420 || close.contains(&selection.head());
10421
10422 // If best is next to a bracket and current isn't, skip
10423 if !in_bracket_range && best_in_bracket_range {
10424 continue;
10425 }
10426
10427 // Prefer smaller lengths unless best is inside and current isn't
10428 if length > best_length && (best_inside || !inside) {
10429 continue;
10430 }
10431
10432 best_length = length;
10433 best_inside = inside;
10434 best_in_bracket_range = in_bracket_range;
10435 best_destination = Some(
10436 if close.contains(&selection.start) && close.contains(&selection.end) {
10437 if inside {
10438 open.end
10439 } else {
10440 open.start
10441 }
10442 } else if inside {
10443 *close.start()
10444 } else {
10445 *close.end()
10446 },
10447 );
10448 }
10449
10450 if let Some(destination) = best_destination {
10451 selection.collapse_to(destination, SelectionGoal::None);
10452 }
10453 })
10454 });
10455 }
10456
10457 pub fn undo_selection(
10458 &mut self,
10459 _: &UndoSelection,
10460 window: &mut Window,
10461 cx: &mut Context<Self>,
10462 ) {
10463 self.end_selection(window, cx);
10464 self.selection_history.mode = SelectionHistoryMode::Undoing;
10465 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10466 self.change_selections(None, window, cx, |s| {
10467 s.select_anchors(entry.selections.to_vec())
10468 });
10469 self.select_next_state = entry.select_next_state;
10470 self.select_prev_state = entry.select_prev_state;
10471 self.add_selections_state = entry.add_selections_state;
10472 self.request_autoscroll(Autoscroll::newest(), cx);
10473 }
10474 self.selection_history.mode = SelectionHistoryMode::Normal;
10475 }
10476
10477 pub fn redo_selection(
10478 &mut self,
10479 _: &RedoSelection,
10480 window: &mut Window,
10481 cx: &mut Context<Self>,
10482 ) {
10483 self.end_selection(window, cx);
10484 self.selection_history.mode = SelectionHistoryMode::Redoing;
10485 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10486 self.change_selections(None, window, cx, |s| {
10487 s.select_anchors(entry.selections.to_vec())
10488 });
10489 self.select_next_state = entry.select_next_state;
10490 self.select_prev_state = entry.select_prev_state;
10491 self.add_selections_state = entry.add_selections_state;
10492 self.request_autoscroll(Autoscroll::newest(), cx);
10493 }
10494 self.selection_history.mode = SelectionHistoryMode::Normal;
10495 }
10496
10497 pub fn expand_excerpts(
10498 &mut self,
10499 action: &ExpandExcerpts,
10500 _: &mut Window,
10501 cx: &mut Context<Self>,
10502 ) {
10503 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10504 }
10505
10506 pub fn expand_excerpts_down(
10507 &mut self,
10508 action: &ExpandExcerptsDown,
10509 _: &mut Window,
10510 cx: &mut Context<Self>,
10511 ) {
10512 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10513 }
10514
10515 pub fn expand_excerpts_up(
10516 &mut self,
10517 action: &ExpandExcerptsUp,
10518 _: &mut Window,
10519 cx: &mut Context<Self>,
10520 ) {
10521 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10522 }
10523
10524 pub fn expand_excerpts_for_direction(
10525 &mut self,
10526 lines: u32,
10527 direction: ExpandExcerptDirection,
10528
10529 cx: &mut Context<Self>,
10530 ) {
10531 let selections = self.selections.disjoint_anchors();
10532
10533 let lines = if lines == 0 {
10534 EditorSettings::get_global(cx).expand_excerpt_lines
10535 } else {
10536 lines
10537 };
10538
10539 self.buffer.update(cx, |buffer, cx| {
10540 let snapshot = buffer.snapshot(cx);
10541 let mut excerpt_ids = selections
10542 .iter()
10543 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10544 .collect::<Vec<_>>();
10545 excerpt_ids.sort();
10546 excerpt_ids.dedup();
10547 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10548 })
10549 }
10550
10551 pub fn expand_excerpt(
10552 &mut self,
10553 excerpt: ExcerptId,
10554 direction: ExpandExcerptDirection,
10555 cx: &mut Context<Self>,
10556 ) {
10557 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10558 self.buffer.update(cx, |buffer, cx| {
10559 buffer.expand_excerpts([excerpt], lines, direction, cx)
10560 })
10561 }
10562
10563 pub fn go_to_singleton_buffer_point(
10564 &mut self,
10565 point: Point,
10566 window: &mut Window,
10567 cx: &mut Context<Self>,
10568 ) {
10569 self.go_to_singleton_buffer_range(point..point, window, cx);
10570 }
10571
10572 pub fn go_to_singleton_buffer_range(
10573 &mut self,
10574 range: Range<Point>,
10575 window: &mut Window,
10576 cx: &mut Context<Self>,
10577 ) {
10578 let multibuffer = self.buffer().read(cx);
10579 let Some(buffer) = multibuffer.as_singleton() else {
10580 return;
10581 };
10582 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10583 return;
10584 };
10585 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10586 return;
10587 };
10588 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10589 s.select_anchor_ranges([start..end])
10590 });
10591 }
10592
10593 fn go_to_diagnostic(
10594 &mut self,
10595 _: &GoToDiagnostic,
10596 window: &mut Window,
10597 cx: &mut Context<Self>,
10598 ) {
10599 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10600 }
10601
10602 fn go_to_prev_diagnostic(
10603 &mut self,
10604 _: &GoToPrevDiagnostic,
10605 window: &mut Window,
10606 cx: &mut Context<Self>,
10607 ) {
10608 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10609 }
10610
10611 pub fn go_to_diagnostic_impl(
10612 &mut self,
10613 direction: Direction,
10614 window: &mut Window,
10615 cx: &mut Context<Self>,
10616 ) {
10617 let buffer = self.buffer.read(cx).snapshot(cx);
10618 let selection = self.selections.newest::<usize>(cx);
10619
10620 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10621 if direction == Direction::Next {
10622 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10623 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10624 return;
10625 };
10626 self.activate_diagnostics(
10627 buffer_id,
10628 popover.local_diagnostic.diagnostic.group_id,
10629 window,
10630 cx,
10631 );
10632 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10633 let primary_range_start = active_diagnostics.primary_range.start;
10634 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10635 let mut new_selection = s.newest_anchor().clone();
10636 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10637 s.select_anchors(vec![new_selection.clone()]);
10638 });
10639 self.refresh_inline_completion(false, true, window, cx);
10640 }
10641 return;
10642 }
10643 }
10644
10645 let active_group_id = self
10646 .active_diagnostics
10647 .as_ref()
10648 .map(|active_group| active_group.group_id);
10649 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10650 active_diagnostics
10651 .primary_range
10652 .to_offset(&buffer)
10653 .to_inclusive()
10654 });
10655 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10656 if active_primary_range.contains(&selection.head()) {
10657 *active_primary_range.start()
10658 } else {
10659 selection.head()
10660 }
10661 } else {
10662 selection.head()
10663 };
10664
10665 let snapshot = self.snapshot(window, cx);
10666 let primary_diagnostics_before = buffer
10667 .diagnostics_in_range::<usize>(0..search_start)
10668 .filter(|entry| entry.diagnostic.is_primary)
10669 .filter(|entry| entry.range.start != entry.range.end)
10670 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10671 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10672 .collect::<Vec<_>>();
10673 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10674 primary_diagnostics_before
10675 .iter()
10676 .position(|entry| entry.diagnostic.group_id == active_group_id)
10677 });
10678
10679 let primary_diagnostics_after = buffer
10680 .diagnostics_in_range::<usize>(search_start..buffer.len())
10681 .filter(|entry| entry.diagnostic.is_primary)
10682 .filter(|entry| entry.range.start != entry.range.end)
10683 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10684 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10685 .collect::<Vec<_>>();
10686 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10687 primary_diagnostics_after
10688 .iter()
10689 .enumerate()
10690 .rev()
10691 .find_map(|(i, entry)| {
10692 if entry.diagnostic.group_id == active_group_id {
10693 Some(i)
10694 } else {
10695 None
10696 }
10697 })
10698 });
10699
10700 let next_primary_diagnostic = match direction {
10701 Direction::Prev => primary_diagnostics_before
10702 .iter()
10703 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10704 .rev()
10705 .next(),
10706 Direction::Next => primary_diagnostics_after
10707 .iter()
10708 .skip(
10709 last_same_group_diagnostic_after
10710 .map(|index| index + 1)
10711 .unwrap_or(0),
10712 )
10713 .next(),
10714 };
10715
10716 // Cycle around to the start of the buffer, potentially moving back to the start of
10717 // the currently active diagnostic.
10718 let cycle_around = || match direction {
10719 Direction::Prev => primary_diagnostics_after
10720 .iter()
10721 .rev()
10722 .chain(primary_diagnostics_before.iter().rev())
10723 .next(),
10724 Direction::Next => primary_diagnostics_before
10725 .iter()
10726 .chain(primary_diagnostics_after.iter())
10727 .next(),
10728 };
10729
10730 if let Some((primary_range, group_id)) = next_primary_diagnostic
10731 .or_else(cycle_around)
10732 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10733 {
10734 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10735 return;
10736 };
10737 self.activate_diagnostics(buffer_id, group_id, window, cx);
10738 if self.active_diagnostics.is_some() {
10739 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10740 s.select(vec![Selection {
10741 id: selection.id,
10742 start: primary_range.start,
10743 end: primary_range.start,
10744 reversed: false,
10745 goal: SelectionGoal::None,
10746 }]);
10747 });
10748 self.refresh_inline_completion(false, true, window, cx);
10749 }
10750 }
10751 }
10752
10753 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10754 let snapshot = self.snapshot(window, cx);
10755 let selection = self.selections.newest::<Point>(cx);
10756 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10757 }
10758
10759 fn go_to_hunk_after_position(
10760 &mut self,
10761 snapshot: &EditorSnapshot,
10762 position: Point,
10763 window: &mut Window,
10764 cx: &mut Context<Editor>,
10765 ) -> Option<MultiBufferDiffHunk> {
10766 let mut hunk = snapshot
10767 .buffer_snapshot
10768 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10769 .find(|hunk| hunk.row_range.start.0 > position.row);
10770 if hunk.is_none() {
10771 hunk = snapshot
10772 .buffer_snapshot
10773 .diff_hunks_in_range(Point::zero()..position)
10774 .find(|hunk| hunk.row_range.end.0 < position.row)
10775 }
10776 if let Some(hunk) = &hunk {
10777 let destination = Point::new(hunk.row_range.start.0, 0);
10778 self.unfold_ranges(&[destination..destination], false, false, cx);
10779 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10780 s.select_ranges(vec![destination..destination]);
10781 });
10782 }
10783
10784 hunk
10785 }
10786
10787 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10788 let snapshot = self.snapshot(window, cx);
10789 let selection = self.selections.newest::<Point>(cx);
10790 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10791 }
10792
10793 fn go_to_hunk_before_position(
10794 &mut self,
10795 snapshot: &EditorSnapshot,
10796 position: Point,
10797 window: &mut Window,
10798 cx: &mut Context<Editor>,
10799 ) -> Option<MultiBufferDiffHunk> {
10800 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10801 if hunk.is_none() {
10802 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10803 }
10804 if let Some(hunk) = &hunk {
10805 let destination = Point::new(hunk.row_range.start.0, 0);
10806 self.unfold_ranges(&[destination..destination], false, false, cx);
10807 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10808 s.select_ranges(vec![destination..destination]);
10809 });
10810 }
10811
10812 hunk
10813 }
10814
10815 pub fn go_to_definition(
10816 &mut self,
10817 _: &GoToDefinition,
10818 window: &mut Window,
10819 cx: &mut Context<Self>,
10820 ) -> Task<Result<Navigated>> {
10821 let definition =
10822 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10823 cx.spawn_in(window, |editor, mut cx| async move {
10824 if definition.await? == Navigated::Yes {
10825 return Ok(Navigated::Yes);
10826 }
10827 match editor.update_in(&mut cx, |editor, window, cx| {
10828 editor.find_all_references(&FindAllReferences, window, cx)
10829 })? {
10830 Some(references) => references.await,
10831 None => Ok(Navigated::No),
10832 }
10833 })
10834 }
10835
10836 pub fn go_to_declaration(
10837 &mut self,
10838 _: &GoToDeclaration,
10839 window: &mut Window,
10840 cx: &mut Context<Self>,
10841 ) -> Task<Result<Navigated>> {
10842 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10843 }
10844
10845 pub fn go_to_declaration_split(
10846 &mut self,
10847 _: &GoToDeclaration,
10848 window: &mut Window,
10849 cx: &mut Context<Self>,
10850 ) -> Task<Result<Navigated>> {
10851 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10852 }
10853
10854 pub fn go_to_implementation(
10855 &mut self,
10856 _: &GoToImplementation,
10857 window: &mut Window,
10858 cx: &mut Context<Self>,
10859 ) -> Task<Result<Navigated>> {
10860 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10861 }
10862
10863 pub fn go_to_implementation_split(
10864 &mut self,
10865 _: &GoToImplementationSplit,
10866 window: &mut Window,
10867 cx: &mut Context<Self>,
10868 ) -> Task<Result<Navigated>> {
10869 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10870 }
10871
10872 pub fn go_to_type_definition(
10873 &mut self,
10874 _: &GoToTypeDefinition,
10875 window: &mut Window,
10876 cx: &mut Context<Self>,
10877 ) -> Task<Result<Navigated>> {
10878 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10879 }
10880
10881 pub fn go_to_definition_split(
10882 &mut self,
10883 _: &GoToDefinitionSplit,
10884 window: &mut Window,
10885 cx: &mut Context<Self>,
10886 ) -> Task<Result<Navigated>> {
10887 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10888 }
10889
10890 pub fn go_to_type_definition_split(
10891 &mut self,
10892 _: &GoToTypeDefinitionSplit,
10893 window: &mut Window,
10894 cx: &mut Context<Self>,
10895 ) -> Task<Result<Navigated>> {
10896 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10897 }
10898
10899 fn go_to_definition_of_kind(
10900 &mut self,
10901 kind: GotoDefinitionKind,
10902 split: bool,
10903 window: &mut Window,
10904 cx: &mut Context<Self>,
10905 ) -> Task<Result<Navigated>> {
10906 let Some(provider) = self.semantics_provider.clone() else {
10907 return Task::ready(Ok(Navigated::No));
10908 };
10909 let head = self.selections.newest::<usize>(cx).head();
10910 let buffer = self.buffer.read(cx);
10911 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10912 text_anchor
10913 } else {
10914 return Task::ready(Ok(Navigated::No));
10915 };
10916
10917 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10918 return Task::ready(Ok(Navigated::No));
10919 };
10920
10921 cx.spawn_in(window, |editor, mut cx| async move {
10922 let definitions = definitions.await?;
10923 let navigated = editor
10924 .update_in(&mut cx, |editor, window, cx| {
10925 editor.navigate_to_hover_links(
10926 Some(kind),
10927 definitions
10928 .into_iter()
10929 .filter(|location| {
10930 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10931 })
10932 .map(HoverLink::Text)
10933 .collect::<Vec<_>>(),
10934 split,
10935 window,
10936 cx,
10937 )
10938 })?
10939 .await?;
10940 anyhow::Ok(navigated)
10941 })
10942 }
10943
10944 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10945 let selection = self.selections.newest_anchor();
10946 let head = selection.head();
10947 let tail = selection.tail();
10948
10949 let Some((buffer, start_position)) =
10950 self.buffer.read(cx).text_anchor_for_position(head, cx)
10951 else {
10952 return;
10953 };
10954
10955 let end_position = if head != tail {
10956 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10957 return;
10958 };
10959 Some(pos)
10960 } else {
10961 None
10962 };
10963
10964 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10965 let url = if let Some(end_pos) = end_position {
10966 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10967 } else {
10968 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10969 };
10970
10971 if let Some(url) = url {
10972 editor.update(&mut cx, |_, cx| {
10973 cx.open_url(&url);
10974 })
10975 } else {
10976 Ok(())
10977 }
10978 });
10979
10980 url_finder.detach();
10981 }
10982
10983 pub fn open_selected_filename(
10984 &mut self,
10985 _: &OpenSelectedFilename,
10986 window: &mut Window,
10987 cx: &mut Context<Self>,
10988 ) {
10989 let Some(workspace) = self.workspace() else {
10990 return;
10991 };
10992
10993 let position = self.selections.newest_anchor().head();
10994
10995 let Some((buffer, buffer_position)) =
10996 self.buffer.read(cx).text_anchor_for_position(position, cx)
10997 else {
10998 return;
10999 };
11000
11001 let project = self.project.clone();
11002
11003 cx.spawn_in(window, |_, mut cx| async move {
11004 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11005
11006 if let Some((_, path)) = result {
11007 workspace
11008 .update_in(&mut cx, |workspace, window, cx| {
11009 workspace.open_resolved_path(path, window, cx)
11010 })?
11011 .await?;
11012 }
11013 anyhow::Ok(())
11014 })
11015 .detach();
11016 }
11017
11018 pub(crate) fn navigate_to_hover_links(
11019 &mut self,
11020 kind: Option<GotoDefinitionKind>,
11021 mut definitions: Vec<HoverLink>,
11022 split: bool,
11023 window: &mut Window,
11024 cx: &mut Context<Editor>,
11025 ) -> Task<Result<Navigated>> {
11026 // If there is one definition, just open it directly
11027 if definitions.len() == 1 {
11028 let definition = definitions.pop().unwrap();
11029
11030 enum TargetTaskResult {
11031 Location(Option<Location>),
11032 AlreadyNavigated,
11033 }
11034
11035 let target_task = match definition {
11036 HoverLink::Text(link) => {
11037 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11038 }
11039 HoverLink::InlayHint(lsp_location, server_id) => {
11040 let computation =
11041 self.compute_target_location(lsp_location, server_id, window, cx);
11042 cx.background_spawn(async move {
11043 let location = computation.await?;
11044 Ok(TargetTaskResult::Location(location))
11045 })
11046 }
11047 HoverLink::Url(url) => {
11048 cx.open_url(&url);
11049 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11050 }
11051 HoverLink::File(path) => {
11052 if let Some(workspace) = self.workspace() {
11053 cx.spawn_in(window, |_, mut cx| async move {
11054 workspace
11055 .update_in(&mut cx, |workspace, window, cx| {
11056 workspace.open_resolved_path(path, window, cx)
11057 })?
11058 .await
11059 .map(|_| TargetTaskResult::AlreadyNavigated)
11060 })
11061 } else {
11062 Task::ready(Ok(TargetTaskResult::Location(None)))
11063 }
11064 }
11065 };
11066 cx.spawn_in(window, |editor, mut cx| async move {
11067 let target = match target_task.await.context("target resolution task")? {
11068 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11069 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11070 TargetTaskResult::Location(Some(target)) => target,
11071 };
11072
11073 editor.update_in(&mut cx, |editor, window, cx| {
11074 let Some(workspace) = editor.workspace() else {
11075 return Navigated::No;
11076 };
11077 let pane = workspace.read(cx).active_pane().clone();
11078
11079 let range = target.range.to_point(target.buffer.read(cx));
11080 let range = editor.range_for_match(&range);
11081 let range = collapse_multiline_range(range);
11082
11083 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11084 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11085 } else {
11086 window.defer(cx, move |window, cx| {
11087 let target_editor: Entity<Self> =
11088 workspace.update(cx, |workspace, cx| {
11089 let pane = if split {
11090 workspace.adjacent_pane(window, cx)
11091 } else {
11092 workspace.active_pane().clone()
11093 };
11094
11095 workspace.open_project_item(
11096 pane,
11097 target.buffer.clone(),
11098 true,
11099 true,
11100 window,
11101 cx,
11102 )
11103 });
11104 target_editor.update(cx, |target_editor, cx| {
11105 // When selecting a definition in a different buffer, disable the nav history
11106 // to avoid creating a history entry at the previous cursor location.
11107 pane.update(cx, |pane, _| pane.disable_history());
11108 target_editor.go_to_singleton_buffer_range(range, window, cx);
11109 pane.update(cx, |pane, _| pane.enable_history());
11110 });
11111 });
11112 }
11113 Navigated::Yes
11114 })
11115 })
11116 } else if !definitions.is_empty() {
11117 cx.spawn_in(window, |editor, mut cx| async move {
11118 let (title, location_tasks, workspace) = editor
11119 .update_in(&mut cx, |editor, window, cx| {
11120 let tab_kind = match kind {
11121 Some(GotoDefinitionKind::Implementation) => "Implementations",
11122 _ => "Definitions",
11123 };
11124 let title = definitions
11125 .iter()
11126 .find_map(|definition| match definition {
11127 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11128 let buffer = origin.buffer.read(cx);
11129 format!(
11130 "{} for {}",
11131 tab_kind,
11132 buffer
11133 .text_for_range(origin.range.clone())
11134 .collect::<String>()
11135 )
11136 }),
11137 HoverLink::InlayHint(_, _) => None,
11138 HoverLink::Url(_) => None,
11139 HoverLink::File(_) => None,
11140 })
11141 .unwrap_or(tab_kind.to_string());
11142 let location_tasks = definitions
11143 .into_iter()
11144 .map(|definition| match definition {
11145 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11146 HoverLink::InlayHint(lsp_location, server_id) => editor
11147 .compute_target_location(lsp_location, server_id, window, cx),
11148 HoverLink::Url(_) => Task::ready(Ok(None)),
11149 HoverLink::File(_) => Task::ready(Ok(None)),
11150 })
11151 .collect::<Vec<_>>();
11152 (title, location_tasks, editor.workspace().clone())
11153 })
11154 .context("location tasks preparation")?;
11155
11156 let locations = future::join_all(location_tasks)
11157 .await
11158 .into_iter()
11159 .filter_map(|location| location.transpose())
11160 .collect::<Result<_>>()
11161 .context("location tasks")?;
11162
11163 let Some(workspace) = workspace else {
11164 return Ok(Navigated::No);
11165 };
11166 let opened = workspace
11167 .update_in(&mut cx, |workspace, window, cx| {
11168 Self::open_locations_in_multibuffer(
11169 workspace,
11170 locations,
11171 title,
11172 split,
11173 MultibufferSelectionMode::First,
11174 window,
11175 cx,
11176 )
11177 })
11178 .ok();
11179
11180 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11181 })
11182 } else {
11183 Task::ready(Ok(Navigated::No))
11184 }
11185 }
11186
11187 fn compute_target_location(
11188 &self,
11189 lsp_location: lsp::Location,
11190 server_id: LanguageServerId,
11191 window: &mut Window,
11192 cx: &mut Context<Self>,
11193 ) -> Task<anyhow::Result<Option<Location>>> {
11194 let Some(project) = self.project.clone() else {
11195 return Task::ready(Ok(None));
11196 };
11197
11198 cx.spawn_in(window, move |editor, mut cx| async move {
11199 let location_task = editor.update(&mut cx, |_, cx| {
11200 project.update(cx, |project, cx| {
11201 let language_server_name = project
11202 .language_server_statuses(cx)
11203 .find(|(id, _)| server_id == *id)
11204 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11205 language_server_name.map(|language_server_name| {
11206 project.open_local_buffer_via_lsp(
11207 lsp_location.uri.clone(),
11208 server_id,
11209 language_server_name,
11210 cx,
11211 )
11212 })
11213 })
11214 })?;
11215 let location = match location_task {
11216 Some(task) => Some({
11217 let target_buffer_handle = task.await.context("open local buffer")?;
11218 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11219 let target_start = target_buffer
11220 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11221 let target_end = target_buffer
11222 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11223 target_buffer.anchor_after(target_start)
11224 ..target_buffer.anchor_before(target_end)
11225 })?;
11226 Location {
11227 buffer: target_buffer_handle,
11228 range,
11229 }
11230 }),
11231 None => None,
11232 };
11233 Ok(location)
11234 })
11235 }
11236
11237 pub fn find_all_references(
11238 &mut self,
11239 _: &FindAllReferences,
11240 window: &mut Window,
11241 cx: &mut Context<Self>,
11242 ) -> Option<Task<Result<Navigated>>> {
11243 let selection = self.selections.newest::<usize>(cx);
11244 let multi_buffer = self.buffer.read(cx);
11245 let head = selection.head();
11246
11247 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11248 let head_anchor = multi_buffer_snapshot.anchor_at(
11249 head,
11250 if head < selection.tail() {
11251 Bias::Right
11252 } else {
11253 Bias::Left
11254 },
11255 );
11256
11257 match self
11258 .find_all_references_task_sources
11259 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11260 {
11261 Ok(_) => {
11262 log::info!(
11263 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11264 );
11265 return None;
11266 }
11267 Err(i) => {
11268 self.find_all_references_task_sources.insert(i, head_anchor);
11269 }
11270 }
11271
11272 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11273 let workspace = self.workspace()?;
11274 let project = workspace.read(cx).project().clone();
11275 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11276 Some(cx.spawn_in(window, |editor, mut cx| async move {
11277 let _cleanup = defer({
11278 let mut cx = cx.clone();
11279 move || {
11280 let _ = editor.update(&mut cx, |editor, _| {
11281 if let Ok(i) =
11282 editor
11283 .find_all_references_task_sources
11284 .binary_search_by(|anchor| {
11285 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11286 })
11287 {
11288 editor.find_all_references_task_sources.remove(i);
11289 }
11290 });
11291 }
11292 });
11293
11294 let locations = references.await?;
11295 if locations.is_empty() {
11296 return anyhow::Ok(Navigated::No);
11297 }
11298
11299 workspace.update_in(&mut cx, |workspace, window, cx| {
11300 let title = locations
11301 .first()
11302 .as_ref()
11303 .map(|location| {
11304 let buffer = location.buffer.read(cx);
11305 format!(
11306 "References to `{}`",
11307 buffer
11308 .text_for_range(location.range.clone())
11309 .collect::<String>()
11310 )
11311 })
11312 .unwrap();
11313 Self::open_locations_in_multibuffer(
11314 workspace,
11315 locations,
11316 title,
11317 false,
11318 MultibufferSelectionMode::First,
11319 window,
11320 cx,
11321 );
11322 Navigated::Yes
11323 })
11324 }))
11325 }
11326
11327 /// Opens a multibuffer with the given project locations in it
11328 pub fn open_locations_in_multibuffer(
11329 workspace: &mut Workspace,
11330 mut locations: Vec<Location>,
11331 title: String,
11332 split: bool,
11333 multibuffer_selection_mode: MultibufferSelectionMode,
11334 window: &mut Window,
11335 cx: &mut Context<Workspace>,
11336 ) {
11337 // If there are multiple definitions, open them in a multibuffer
11338 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11339 let mut locations = locations.into_iter().peekable();
11340 let mut ranges = Vec::new();
11341 let capability = workspace.project().read(cx).capability();
11342
11343 let excerpt_buffer = cx.new(|cx| {
11344 let mut multibuffer = MultiBuffer::new(capability);
11345 while let Some(location) = locations.next() {
11346 let buffer = location.buffer.read(cx);
11347 let mut ranges_for_buffer = Vec::new();
11348 let range = location.range.to_offset(buffer);
11349 ranges_for_buffer.push(range.clone());
11350
11351 while let Some(next_location) = locations.peek() {
11352 if next_location.buffer == location.buffer {
11353 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11354 locations.next();
11355 } else {
11356 break;
11357 }
11358 }
11359
11360 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11361 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11362 location.buffer.clone(),
11363 ranges_for_buffer,
11364 DEFAULT_MULTIBUFFER_CONTEXT,
11365 cx,
11366 ))
11367 }
11368
11369 multibuffer.with_title(title)
11370 });
11371
11372 let editor = cx.new(|cx| {
11373 Editor::for_multibuffer(
11374 excerpt_buffer,
11375 Some(workspace.project().clone()),
11376 true,
11377 window,
11378 cx,
11379 )
11380 });
11381 editor.update(cx, |editor, cx| {
11382 match multibuffer_selection_mode {
11383 MultibufferSelectionMode::First => {
11384 if let Some(first_range) = ranges.first() {
11385 editor.change_selections(None, window, cx, |selections| {
11386 selections.clear_disjoint();
11387 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11388 });
11389 }
11390 editor.highlight_background::<Self>(
11391 &ranges,
11392 |theme| theme.editor_highlighted_line_background,
11393 cx,
11394 );
11395 }
11396 MultibufferSelectionMode::All => {
11397 editor.change_selections(None, window, cx, |selections| {
11398 selections.clear_disjoint();
11399 selections.select_anchor_ranges(ranges);
11400 });
11401 }
11402 }
11403 editor.register_buffers_with_language_servers(cx);
11404 });
11405
11406 let item = Box::new(editor);
11407 let item_id = item.item_id();
11408
11409 if split {
11410 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11411 } else {
11412 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11413 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11414 pane.close_current_preview_item(window, cx)
11415 } else {
11416 None
11417 }
11418 });
11419 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11420 }
11421 workspace.active_pane().update(cx, |pane, cx| {
11422 pane.set_preview_item_id(Some(item_id), cx);
11423 });
11424 }
11425
11426 pub fn rename(
11427 &mut self,
11428 _: &Rename,
11429 window: &mut Window,
11430 cx: &mut Context<Self>,
11431 ) -> Option<Task<Result<()>>> {
11432 use language::ToOffset as _;
11433
11434 let provider = self.semantics_provider.clone()?;
11435 let selection = self.selections.newest_anchor().clone();
11436 let (cursor_buffer, cursor_buffer_position) = self
11437 .buffer
11438 .read(cx)
11439 .text_anchor_for_position(selection.head(), cx)?;
11440 let (tail_buffer, cursor_buffer_position_end) = self
11441 .buffer
11442 .read(cx)
11443 .text_anchor_for_position(selection.tail(), cx)?;
11444 if tail_buffer != cursor_buffer {
11445 return None;
11446 }
11447
11448 let snapshot = cursor_buffer.read(cx).snapshot();
11449 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11450 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11451 let prepare_rename = provider
11452 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11453 .unwrap_or_else(|| Task::ready(Ok(None)));
11454 drop(snapshot);
11455
11456 Some(cx.spawn_in(window, |this, mut cx| async move {
11457 let rename_range = if let Some(range) = prepare_rename.await? {
11458 Some(range)
11459 } else {
11460 this.update(&mut cx, |this, cx| {
11461 let buffer = this.buffer.read(cx).snapshot(cx);
11462 let mut buffer_highlights = this
11463 .document_highlights_for_position(selection.head(), &buffer)
11464 .filter(|highlight| {
11465 highlight.start.excerpt_id == selection.head().excerpt_id
11466 && highlight.end.excerpt_id == selection.head().excerpt_id
11467 });
11468 buffer_highlights
11469 .next()
11470 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11471 })?
11472 };
11473 if let Some(rename_range) = rename_range {
11474 this.update_in(&mut cx, |this, window, cx| {
11475 let snapshot = cursor_buffer.read(cx).snapshot();
11476 let rename_buffer_range = rename_range.to_offset(&snapshot);
11477 let cursor_offset_in_rename_range =
11478 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11479 let cursor_offset_in_rename_range_end =
11480 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11481
11482 this.take_rename(false, window, cx);
11483 let buffer = this.buffer.read(cx).read(cx);
11484 let cursor_offset = selection.head().to_offset(&buffer);
11485 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11486 let rename_end = rename_start + rename_buffer_range.len();
11487 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11488 let mut old_highlight_id = None;
11489 let old_name: Arc<str> = buffer
11490 .chunks(rename_start..rename_end, true)
11491 .map(|chunk| {
11492 if old_highlight_id.is_none() {
11493 old_highlight_id = chunk.syntax_highlight_id;
11494 }
11495 chunk.text
11496 })
11497 .collect::<String>()
11498 .into();
11499
11500 drop(buffer);
11501
11502 // Position the selection in the rename editor so that it matches the current selection.
11503 this.show_local_selections = false;
11504 let rename_editor = cx.new(|cx| {
11505 let mut editor = Editor::single_line(window, cx);
11506 editor.buffer.update(cx, |buffer, cx| {
11507 buffer.edit([(0..0, old_name.clone())], None, cx)
11508 });
11509 let rename_selection_range = match cursor_offset_in_rename_range
11510 .cmp(&cursor_offset_in_rename_range_end)
11511 {
11512 Ordering::Equal => {
11513 editor.select_all(&SelectAll, window, cx);
11514 return editor;
11515 }
11516 Ordering::Less => {
11517 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11518 }
11519 Ordering::Greater => {
11520 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11521 }
11522 };
11523 if rename_selection_range.end > old_name.len() {
11524 editor.select_all(&SelectAll, window, cx);
11525 } else {
11526 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11527 s.select_ranges([rename_selection_range]);
11528 });
11529 }
11530 editor
11531 });
11532 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11533 if e == &EditorEvent::Focused {
11534 cx.emit(EditorEvent::FocusedIn)
11535 }
11536 })
11537 .detach();
11538
11539 let write_highlights =
11540 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11541 let read_highlights =
11542 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11543 let ranges = write_highlights
11544 .iter()
11545 .flat_map(|(_, ranges)| ranges.iter())
11546 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11547 .cloned()
11548 .collect();
11549
11550 this.highlight_text::<Rename>(
11551 ranges,
11552 HighlightStyle {
11553 fade_out: Some(0.6),
11554 ..Default::default()
11555 },
11556 cx,
11557 );
11558 let rename_focus_handle = rename_editor.focus_handle(cx);
11559 window.focus(&rename_focus_handle);
11560 let block_id = this.insert_blocks(
11561 [BlockProperties {
11562 style: BlockStyle::Flex,
11563 placement: BlockPlacement::Below(range.start),
11564 height: 1,
11565 render: Arc::new({
11566 let rename_editor = rename_editor.clone();
11567 move |cx: &mut BlockContext| {
11568 let mut text_style = cx.editor_style.text.clone();
11569 if let Some(highlight_style) = old_highlight_id
11570 .and_then(|h| h.style(&cx.editor_style.syntax))
11571 {
11572 text_style = text_style.highlight(highlight_style);
11573 }
11574 div()
11575 .block_mouse_down()
11576 .pl(cx.anchor_x)
11577 .child(EditorElement::new(
11578 &rename_editor,
11579 EditorStyle {
11580 background: cx.theme().system().transparent,
11581 local_player: cx.editor_style.local_player,
11582 text: text_style,
11583 scrollbar_width: cx.editor_style.scrollbar_width,
11584 syntax: cx.editor_style.syntax.clone(),
11585 status: cx.editor_style.status.clone(),
11586 inlay_hints_style: HighlightStyle {
11587 font_weight: Some(FontWeight::BOLD),
11588 ..make_inlay_hints_style(cx.app)
11589 },
11590 inline_completion_styles: make_suggestion_styles(
11591 cx.app,
11592 ),
11593 ..EditorStyle::default()
11594 },
11595 ))
11596 .into_any_element()
11597 }
11598 }),
11599 priority: 0,
11600 }],
11601 Some(Autoscroll::fit()),
11602 cx,
11603 )[0];
11604 this.pending_rename = Some(RenameState {
11605 range,
11606 old_name,
11607 editor: rename_editor,
11608 block_id,
11609 });
11610 })?;
11611 }
11612
11613 Ok(())
11614 }))
11615 }
11616
11617 pub fn confirm_rename(
11618 &mut self,
11619 _: &ConfirmRename,
11620 window: &mut Window,
11621 cx: &mut Context<Self>,
11622 ) -> Option<Task<Result<()>>> {
11623 let rename = self.take_rename(false, window, cx)?;
11624 let workspace = self.workspace()?.downgrade();
11625 let (buffer, start) = self
11626 .buffer
11627 .read(cx)
11628 .text_anchor_for_position(rename.range.start, cx)?;
11629 let (end_buffer, _) = self
11630 .buffer
11631 .read(cx)
11632 .text_anchor_for_position(rename.range.end, cx)?;
11633 if buffer != end_buffer {
11634 return None;
11635 }
11636
11637 let old_name = rename.old_name;
11638 let new_name = rename.editor.read(cx).text(cx);
11639
11640 let rename = self.semantics_provider.as_ref()?.perform_rename(
11641 &buffer,
11642 start,
11643 new_name.clone(),
11644 cx,
11645 )?;
11646
11647 Some(cx.spawn_in(window, |editor, mut cx| async move {
11648 let project_transaction = rename.await?;
11649 Self::open_project_transaction(
11650 &editor,
11651 workspace,
11652 project_transaction,
11653 format!("Rename: {} → {}", old_name, new_name),
11654 cx.clone(),
11655 )
11656 .await?;
11657
11658 editor.update(&mut cx, |editor, cx| {
11659 editor.refresh_document_highlights(cx);
11660 })?;
11661 Ok(())
11662 }))
11663 }
11664
11665 fn take_rename(
11666 &mut self,
11667 moving_cursor: bool,
11668 window: &mut Window,
11669 cx: &mut Context<Self>,
11670 ) -> Option<RenameState> {
11671 let rename = self.pending_rename.take()?;
11672 if rename.editor.focus_handle(cx).is_focused(window) {
11673 window.focus(&self.focus_handle);
11674 }
11675
11676 self.remove_blocks(
11677 [rename.block_id].into_iter().collect(),
11678 Some(Autoscroll::fit()),
11679 cx,
11680 );
11681 self.clear_highlights::<Rename>(cx);
11682 self.show_local_selections = true;
11683
11684 if moving_cursor {
11685 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11686 editor.selections.newest::<usize>(cx).head()
11687 });
11688
11689 // Update the selection to match the position of the selection inside
11690 // the rename editor.
11691 let snapshot = self.buffer.read(cx).read(cx);
11692 let rename_range = rename.range.to_offset(&snapshot);
11693 let cursor_in_editor = snapshot
11694 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11695 .min(rename_range.end);
11696 drop(snapshot);
11697
11698 self.change_selections(None, window, cx, |s| {
11699 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11700 });
11701 } else {
11702 self.refresh_document_highlights(cx);
11703 }
11704
11705 Some(rename)
11706 }
11707
11708 pub fn pending_rename(&self) -> Option<&RenameState> {
11709 self.pending_rename.as_ref()
11710 }
11711
11712 fn format(
11713 &mut self,
11714 _: &Format,
11715 window: &mut Window,
11716 cx: &mut Context<Self>,
11717 ) -> Option<Task<Result<()>>> {
11718 let project = match &self.project {
11719 Some(project) => project.clone(),
11720 None => return None,
11721 };
11722
11723 Some(self.perform_format(
11724 project,
11725 FormatTrigger::Manual,
11726 FormatTarget::Buffers,
11727 window,
11728 cx,
11729 ))
11730 }
11731
11732 fn format_selections(
11733 &mut self,
11734 _: &FormatSelections,
11735 window: &mut Window,
11736 cx: &mut Context<Self>,
11737 ) -> Option<Task<Result<()>>> {
11738 let project = match &self.project {
11739 Some(project) => project.clone(),
11740 None => return None,
11741 };
11742
11743 let ranges = self
11744 .selections
11745 .all_adjusted(cx)
11746 .into_iter()
11747 .map(|selection| selection.range())
11748 .collect_vec();
11749
11750 Some(self.perform_format(
11751 project,
11752 FormatTrigger::Manual,
11753 FormatTarget::Ranges(ranges),
11754 window,
11755 cx,
11756 ))
11757 }
11758
11759 fn perform_format(
11760 &mut self,
11761 project: Entity<Project>,
11762 trigger: FormatTrigger,
11763 target: FormatTarget,
11764 window: &mut Window,
11765 cx: &mut Context<Self>,
11766 ) -> Task<Result<()>> {
11767 let buffer = self.buffer.clone();
11768 let (buffers, target) = match target {
11769 FormatTarget::Buffers => {
11770 let mut buffers = buffer.read(cx).all_buffers();
11771 if trigger == FormatTrigger::Save {
11772 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11773 }
11774 (buffers, LspFormatTarget::Buffers)
11775 }
11776 FormatTarget::Ranges(selection_ranges) => {
11777 let multi_buffer = buffer.read(cx);
11778 let snapshot = multi_buffer.read(cx);
11779 let mut buffers = HashSet::default();
11780 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11781 BTreeMap::new();
11782 for selection_range in selection_ranges {
11783 for (buffer, buffer_range, _) in
11784 snapshot.range_to_buffer_ranges(selection_range)
11785 {
11786 let buffer_id = buffer.remote_id();
11787 let start = buffer.anchor_before(buffer_range.start);
11788 let end = buffer.anchor_after(buffer_range.end);
11789 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11790 buffer_id_to_ranges
11791 .entry(buffer_id)
11792 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11793 .or_insert_with(|| vec![start..end]);
11794 }
11795 }
11796 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11797 }
11798 };
11799
11800 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11801 let format = project.update(cx, |project, cx| {
11802 project.format(buffers, target, true, trigger, cx)
11803 });
11804
11805 cx.spawn_in(window, |_, mut cx| async move {
11806 let transaction = futures::select_biased! {
11807 () = timeout => {
11808 log::warn!("timed out waiting for formatting");
11809 None
11810 }
11811 transaction = format.log_err().fuse() => transaction,
11812 };
11813
11814 buffer
11815 .update(&mut cx, |buffer, cx| {
11816 if let Some(transaction) = transaction {
11817 if !buffer.is_singleton() {
11818 buffer.push_transaction(&transaction.0, cx);
11819 }
11820 }
11821
11822 cx.notify();
11823 })
11824 .ok();
11825
11826 Ok(())
11827 })
11828 }
11829
11830 fn restart_language_server(
11831 &mut self,
11832 _: &RestartLanguageServer,
11833 _: &mut Window,
11834 cx: &mut Context<Self>,
11835 ) {
11836 if let Some(project) = self.project.clone() {
11837 self.buffer.update(cx, |multi_buffer, cx| {
11838 project.update(cx, |project, cx| {
11839 project.restart_language_servers_for_buffers(
11840 multi_buffer.all_buffers().into_iter().collect(),
11841 cx,
11842 );
11843 });
11844 })
11845 }
11846 }
11847
11848 fn cancel_language_server_work(
11849 workspace: &mut Workspace,
11850 _: &actions::CancelLanguageServerWork,
11851 _: &mut Window,
11852 cx: &mut Context<Workspace>,
11853 ) {
11854 let project = workspace.project();
11855 let buffers = workspace
11856 .active_item(cx)
11857 .and_then(|item| item.act_as::<Editor>(cx))
11858 .map_or(HashSet::default(), |editor| {
11859 editor.read(cx).buffer.read(cx).all_buffers()
11860 });
11861 project.update(cx, |project, cx| {
11862 project.cancel_language_server_work_for_buffers(buffers, cx);
11863 });
11864 }
11865
11866 fn show_character_palette(
11867 &mut self,
11868 _: &ShowCharacterPalette,
11869 window: &mut Window,
11870 _: &mut Context<Self>,
11871 ) {
11872 window.show_character_palette();
11873 }
11874
11875 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11876 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11877 let buffer = self.buffer.read(cx).snapshot(cx);
11878 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11879 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11880 let is_valid = buffer
11881 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11882 .any(|entry| {
11883 entry.diagnostic.is_primary
11884 && !entry.range.is_empty()
11885 && entry.range.start == primary_range_start
11886 && entry.diagnostic.message == active_diagnostics.primary_message
11887 });
11888
11889 if is_valid != active_diagnostics.is_valid {
11890 active_diagnostics.is_valid = is_valid;
11891 let mut new_styles = HashMap::default();
11892 for (block_id, diagnostic) in &active_diagnostics.blocks {
11893 new_styles.insert(
11894 *block_id,
11895 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11896 );
11897 }
11898 self.display_map.update(cx, |display_map, _cx| {
11899 display_map.replace_blocks(new_styles)
11900 });
11901 }
11902 }
11903 }
11904
11905 fn activate_diagnostics(
11906 &mut self,
11907 buffer_id: BufferId,
11908 group_id: usize,
11909 window: &mut Window,
11910 cx: &mut Context<Self>,
11911 ) {
11912 self.dismiss_diagnostics(cx);
11913 let snapshot = self.snapshot(window, cx);
11914 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11915 let buffer = self.buffer.read(cx).snapshot(cx);
11916
11917 let mut primary_range = None;
11918 let mut primary_message = None;
11919 let diagnostic_group = buffer
11920 .diagnostic_group(buffer_id, group_id)
11921 .filter_map(|entry| {
11922 let start = entry.range.start;
11923 let end = entry.range.end;
11924 if snapshot.is_line_folded(MultiBufferRow(start.row))
11925 && (start.row == end.row
11926 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11927 {
11928 return None;
11929 }
11930 if entry.diagnostic.is_primary {
11931 primary_range = Some(entry.range.clone());
11932 primary_message = Some(entry.diagnostic.message.clone());
11933 }
11934 Some(entry)
11935 })
11936 .collect::<Vec<_>>();
11937 let primary_range = primary_range?;
11938 let primary_message = primary_message?;
11939
11940 let blocks = display_map
11941 .insert_blocks(
11942 diagnostic_group.iter().map(|entry| {
11943 let diagnostic = entry.diagnostic.clone();
11944 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11945 BlockProperties {
11946 style: BlockStyle::Fixed,
11947 placement: BlockPlacement::Below(
11948 buffer.anchor_after(entry.range.start),
11949 ),
11950 height: message_height,
11951 render: diagnostic_block_renderer(diagnostic, None, true, true),
11952 priority: 0,
11953 }
11954 }),
11955 cx,
11956 )
11957 .into_iter()
11958 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11959 .collect();
11960
11961 Some(ActiveDiagnosticGroup {
11962 primary_range: buffer.anchor_before(primary_range.start)
11963 ..buffer.anchor_after(primary_range.end),
11964 primary_message,
11965 group_id,
11966 blocks,
11967 is_valid: true,
11968 })
11969 });
11970 }
11971
11972 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11973 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11974 self.display_map.update(cx, |display_map, cx| {
11975 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11976 });
11977 cx.notify();
11978 }
11979 }
11980
11981 /// Disable inline diagnostics rendering for this editor.
11982 pub fn disable_inline_diagnostics(&mut self) {
11983 self.inline_diagnostics_enabled = false;
11984 self.inline_diagnostics_update = Task::ready(());
11985 self.inline_diagnostics.clear();
11986 }
11987
11988 pub fn inline_diagnostics_enabled(&self) -> bool {
11989 self.inline_diagnostics_enabled
11990 }
11991
11992 pub fn show_inline_diagnostics(&self) -> bool {
11993 self.show_inline_diagnostics
11994 }
11995
11996 pub fn toggle_inline_diagnostics(
11997 &mut self,
11998 _: &ToggleInlineDiagnostics,
11999 window: &mut Window,
12000 cx: &mut Context<'_, Editor>,
12001 ) {
12002 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12003 self.refresh_inline_diagnostics(false, window, cx);
12004 }
12005
12006 fn refresh_inline_diagnostics(
12007 &mut self,
12008 debounce: bool,
12009 window: &mut Window,
12010 cx: &mut Context<Self>,
12011 ) {
12012 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12013 self.inline_diagnostics_update = Task::ready(());
12014 self.inline_diagnostics.clear();
12015 return;
12016 }
12017
12018 let debounce_ms = ProjectSettings::get_global(cx)
12019 .diagnostics
12020 .inline
12021 .update_debounce_ms;
12022 let debounce = if debounce && debounce_ms > 0 {
12023 Some(Duration::from_millis(debounce_ms))
12024 } else {
12025 None
12026 };
12027 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12028 if let Some(debounce) = debounce {
12029 cx.background_executor().timer(debounce).await;
12030 }
12031 let Some(snapshot) = editor
12032 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12033 .ok()
12034 else {
12035 return;
12036 };
12037
12038 let new_inline_diagnostics = cx
12039 .background_spawn(async move {
12040 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12041 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12042 let message = diagnostic_entry
12043 .diagnostic
12044 .message
12045 .split_once('\n')
12046 .map(|(line, _)| line)
12047 .map(SharedString::new)
12048 .unwrap_or_else(|| {
12049 SharedString::from(diagnostic_entry.diagnostic.message)
12050 });
12051 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12052 let (Ok(i) | Err(i)) = inline_diagnostics
12053 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12054 inline_diagnostics.insert(
12055 i,
12056 (
12057 start_anchor,
12058 InlineDiagnostic {
12059 message,
12060 group_id: diagnostic_entry.diagnostic.group_id,
12061 start: diagnostic_entry.range.start.to_point(&snapshot),
12062 is_primary: diagnostic_entry.diagnostic.is_primary,
12063 severity: diagnostic_entry.diagnostic.severity,
12064 },
12065 ),
12066 );
12067 }
12068 inline_diagnostics
12069 })
12070 .await;
12071
12072 editor
12073 .update(&mut cx, |editor, cx| {
12074 editor.inline_diagnostics = new_inline_diagnostics;
12075 cx.notify();
12076 })
12077 .ok();
12078 });
12079 }
12080
12081 pub fn set_selections_from_remote(
12082 &mut self,
12083 selections: Vec<Selection<Anchor>>,
12084 pending_selection: Option<Selection<Anchor>>,
12085 window: &mut Window,
12086 cx: &mut Context<Self>,
12087 ) {
12088 let old_cursor_position = self.selections.newest_anchor().head();
12089 self.selections.change_with(cx, |s| {
12090 s.select_anchors(selections);
12091 if let Some(pending_selection) = pending_selection {
12092 s.set_pending(pending_selection, SelectMode::Character);
12093 } else {
12094 s.clear_pending();
12095 }
12096 });
12097 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12098 }
12099
12100 fn push_to_selection_history(&mut self) {
12101 self.selection_history.push(SelectionHistoryEntry {
12102 selections: self.selections.disjoint_anchors(),
12103 select_next_state: self.select_next_state.clone(),
12104 select_prev_state: self.select_prev_state.clone(),
12105 add_selections_state: self.add_selections_state.clone(),
12106 });
12107 }
12108
12109 pub fn transact(
12110 &mut self,
12111 window: &mut Window,
12112 cx: &mut Context<Self>,
12113 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12114 ) -> Option<TransactionId> {
12115 self.start_transaction_at(Instant::now(), window, cx);
12116 update(self, window, cx);
12117 self.end_transaction_at(Instant::now(), cx)
12118 }
12119
12120 pub fn start_transaction_at(
12121 &mut self,
12122 now: Instant,
12123 window: &mut Window,
12124 cx: &mut Context<Self>,
12125 ) {
12126 self.end_selection(window, cx);
12127 if let Some(tx_id) = self
12128 .buffer
12129 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12130 {
12131 self.selection_history
12132 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12133 cx.emit(EditorEvent::TransactionBegun {
12134 transaction_id: tx_id,
12135 })
12136 }
12137 }
12138
12139 pub fn end_transaction_at(
12140 &mut self,
12141 now: Instant,
12142 cx: &mut Context<Self>,
12143 ) -> Option<TransactionId> {
12144 if let Some(transaction_id) = self
12145 .buffer
12146 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12147 {
12148 if let Some((_, end_selections)) =
12149 self.selection_history.transaction_mut(transaction_id)
12150 {
12151 *end_selections = Some(self.selections.disjoint_anchors());
12152 } else {
12153 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12154 }
12155
12156 cx.emit(EditorEvent::Edited { transaction_id });
12157 Some(transaction_id)
12158 } else {
12159 None
12160 }
12161 }
12162
12163 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12164 if self.selection_mark_mode {
12165 self.change_selections(None, window, cx, |s| {
12166 s.move_with(|_, sel| {
12167 sel.collapse_to(sel.head(), SelectionGoal::None);
12168 });
12169 })
12170 }
12171 self.selection_mark_mode = true;
12172 cx.notify();
12173 }
12174
12175 pub fn swap_selection_ends(
12176 &mut self,
12177 _: &actions::SwapSelectionEnds,
12178 window: &mut Window,
12179 cx: &mut Context<Self>,
12180 ) {
12181 self.change_selections(None, window, cx, |s| {
12182 s.move_with(|_, sel| {
12183 if sel.start != sel.end {
12184 sel.reversed = !sel.reversed
12185 }
12186 });
12187 });
12188 self.request_autoscroll(Autoscroll::newest(), cx);
12189 cx.notify();
12190 }
12191
12192 pub fn toggle_fold(
12193 &mut self,
12194 _: &actions::ToggleFold,
12195 window: &mut Window,
12196 cx: &mut Context<Self>,
12197 ) {
12198 if self.is_singleton(cx) {
12199 let selection = self.selections.newest::<Point>(cx);
12200
12201 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12202 let range = if selection.is_empty() {
12203 let point = selection.head().to_display_point(&display_map);
12204 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12205 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12206 .to_point(&display_map);
12207 start..end
12208 } else {
12209 selection.range()
12210 };
12211 if display_map.folds_in_range(range).next().is_some() {
12212 self.unfold_lines(&Default::default(), window, cx)
12213 } else {
12214 self.fold(&Default::default(), window, cx)
12215 }
12216 } else {
12217 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12218 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12219 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12220 .map(|(snapshot, _, _)| snapshot.remote_id())
12221 .collect();
12222
12223 for buffer_id in buffer_ids {
12224 if self.is_buffer_folded(buffer_id, cx) {
12225 self.unfold_buffer(buffer_id, cx);
12226 } else {
12227 self.fold_buffer(buffer_id, cx);
12228 }
12229 }
12230 }
12231 }
12232
12233 pub fn toggle_fold_recursive(
12234 &mut self,
12235 _: &actions::ToggleFoldRecursive,
12236 window: &mut Window,
12237 cx: &mut Context<Self>,
12238 ) {
12239 let selection = self.selections.newest::<Point>(cx);
12240
12241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12242 let range = if selection.is_empty() {
12243 let point = selection.head().to_display_point(&display_map);
12244 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12245 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12246 .to_point(&display_map);
12247 start..end
12248 } else {
12249 selection.range()
12250 };
12251 if display_map.folds_in_range(range).next().is_some() {
12252 self.unfold_recursive(&Default::default(), window, cx)
12253 } else {
12254 self.fold_recursive(&Default::default(), window, cx)
12255 }
12256 }
12257
12258 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12259 if self.is_singleton(cx) {
12260 let mut to_fold = Vec::new();
12261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12262 let selections = self.selections.all_adjusted(cx);
12263
12264 for selection in selections {
12265 let range = selection.range().sorted();
12266 let buffer_start_row = range.start.row;
12267
12268 if range.start.row != range.end.row {
12269 let mut found = false;
12270 let mut row = range.start.row;
12271 while row <= range.end.row {
12272 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12273 {
12274 found = true;
12275 row = crease.range().end.row + 1;
12276 to_fold.push(crease);
12277 } else {
12278 row += 1
12279 }
12280 }
12281 if found {
12282 continue;
12283 }
12284 }
12285
12286 for row in (0..=range.start.row).rev() {
12287 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12288 if crease.range().end.row >= buffer_start_row {
12289 to_fold.push(crease);
12290 if row <= range.start.row {
12291 break;
12292 }
12293 }
12294 }
12295 }
12296 }
12297
12298 self.fold_creases(to_fold, true, window, cx);
12299 } else {
12300 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12301
12302 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12303 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12304 .map(|(snapshot, _, _)| snapshot.remote_id())
12305 .collect();
12306 for buffer_id in buffer_ids {
12307 self.fold_buffer(buffer_id, cx);
12308 }
12309 }
12310 }
12311
12312 fn fold_at_level(
12313 &mut self,
12314 fold_at: &FoldAtLevel,
12315 window: &mut Window,
12316 cx: &mut Context<Self>,
12317 ) {
12318 if !self.buffer.read(cx).is_singleton() {
12319 return;
12320 }
12321
12322 let fold_at_level = fold_at.0;
12323 let snapshot = self.buffer.read(cx).snapshot(cx);
12324 let mut to_fold = Vec::new();
12325 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12326
12327 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12328 while start_row < end_row {
12329 match self
12330 .snapshot(window, cx)
12331 .crease_for_buffer_row(MultiBufferRow(start_row))
12332 {
12333 Some(crease) => {
12334 let nested_start_row = crease.range().start.row + 1;
12335 let nested_end_row = crease.range().end.row;
12336
12337 if current_level < fold_at_level {
12338 stack.push((nested_start_row, nested_end_row, current_level + 1));
12339 } else if current_level == fold_at_level {
12340 to_fold.push(crease);
12341 }
12342
12343 start_row = nested_end_row + 1;
12344 }
12345 None => start_row += 1,
12346 }
12347 }
12348 }
12349
12350 self.fold_creases(to_fold, true, window, cx);
12351 }
12352
12353 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12354 if self.buffer.read(cx).is_singleton() {
12355 let mut fold_ranges = Vec::new();
12356 let snapshot = self.buffer.read(cx).snapshot(cx);
12357
12358 for row in 0..snapshot.max_row().0 {
12359 if let Some(foldable_range) = self
12360 .snapshot(window, cx)
12361 .crease_for_buffer_row(MultiBufferRow(row))
12362 {
12363 fold_ranges.push(foldable_range);
12364 }
12365 }
12366
12367 self.fold_creases(fold_ranges, true, window, cx);
12368 } else {
12369 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12370 editor
12371 .update_in(&mut cx, |editor, _, cx| {
12372 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12373 editor.fold_buffer(buffer_id, cx);
12374 }
12375 })
12376 .ok();
12377 });
12378 }
12379 }
12380
12381 pub fn fold_function_bodies(
12382 &mut self,
12383 _: &actions::FoldFunctionBodies,
12384 window: &mut Window,
12385 cx: &mut Context<Self>,
12386 ) {
12387 let snapshot = self.buffer.read(cx).snapshot(cx);
12388
12389 let ranges = snapshot
12390 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12391 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12392 .collect::<Vec<_>>();
12393
12394 let creases = ranges
12395 .into_iter()
12396 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12397 .collect();
12398
12399 self.fold_creases(creases, true, window, cx);
12400 }
12401
12402 pub fn fold_recursive(
12403 &mut self,
12404 _: &actions::FoldRecursive,
12405 window: &mut Window,
12406 cx: &mut Context<Self>,
12407 ) {
12408 let mut to_fold = Vec::new();
12409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12410 let selections = self.selections.all_adjusted(cx);
12411
12412 for selection in selections {
12413 let range = selection.range().sorted();
12414 let buffer_start_row = range.start.row;
12415
12416 if range.start.row != range.end.row {
12417 let mut found = false;
12418 for row in range.start.row..=range.end.row {
12419 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12420 found = true;
12421 to_fold.push(crease);
12422 }
12423 }
12424 if found {
12425 continue;
12426 }
12427 }
12428
12429 for row in (0..=range.start.row).rev() {
12430 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12431 if crease.range().end.row >= buffer_start_row {
12432 to_fold.push(crease);
12433 } else {
12434 break;
12435 }
12436 }
12437 }
12438 }
12439
12440 self.fold_creases(to_fold, true, window, cx);
12441 }
12442
12443 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12444 let buffer_row = fold_at.buffer_row;
12445 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12446
12447 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12448 let autoscroll = self
12449 .selections
12450 .all::<Point>(cx)
12451 .iter()
12452 .any(|selection| crease.range().overlaps(&selection.range()));
12453
12454 self.fold_creases(vec![crease], autoscroll, window, cx);
12455 }
12456 }
12457
12458 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12459 if self.is_singleton(cx) {
12460 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12461 let buffer = &display_map.buffer_snapshot;
12462 let selections = self.selections.all::<Point>(cx);
12463 let ranges = selections
12464 .iter()
12465 .map(|s| {
12466 let range = s.display_range(&display_map).sorted();
12467 let mut start = range.start.to_point(&display_map);
12468 let mut end = range.end.to_point(&display_map);
12469 start.column = 0;
12470 end.column = buffer.line_len(MultiBufferRow(end.row));
12471 start..end
12472 })
12473 .collect::<Vec<_>>();
12474
12475 self.unfold_ranges(&ranges, true, true, cx);
12476 } else {
12477 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12478 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12479 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12480 .map(|(snapshot, _, _)| snapshot.remote_id())
12481 .collect();
12482 for buffer_id in buffer_ids {
12483 self.unfold_buffer(buffer_id, cx);
12484 }
12485 }
12486 }
12487
12488 pub fn unfold_recursive(
12489 &mut self,
12490 _: &UnfoldRecursive,
12491 _window: &mut Window,
12492 cx: &mut Context<Self>,
12493 ) {
12494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12495 let selections = self.selections.all::<Point>(cx);
12496 let ranges = selections
12497 .iter()
12498 .map(|s| {
12499 let mut range = s.display_range(&display_map).sorted();
12500 *range.start.column_mut() = 0;
12501 *range.end.column_mut() = display_map.line_len(range.end.row());
12502 let start = range.start.to_point(&display_map);
12503 let end = range.end.to_point(&display_map);
12504 start..end
12505 })
12506 .collect::<Vec<_>>();
12507
12508 self.unfold_ranges(&ranges, true, true, cx);
12509 }
12510
12511 pub fn unfold_at(
12512 &mut self,
12513 unfold_at: &UnfoldAt,
12514 _window: &mut Window,
12515 cx: &mut Context<Self>,
12516 ) {
12517 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12518
12519 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12520 ..Point::new(
12521 unfold_at.buffer_row.0,
12522 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12523 );
12524
12525 let autoscroll = self
12526 .selections
12527 .all::<Point>(cx)
12528 .iter()
12529 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12530
12531 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12532 }
12533
12534 pub fn unfold_all(
12535 &mut self,
12536 _: &actions::UnfoldAll,
12537 _window: &mut Window,
12538 cx: &mut Context<Self>,
12539 ) {
12540 if self.buffer.read(cx).is_singleton() {
12541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12542 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12543 } else {
12544 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12545 editor
12546 .update(&mut cx, |editor, cx| {
12547 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12548 editor.unfold_buffer(buffer_id, cx);
12549 }
12550 })
12551 .ok();
12552 });
12553 }
12554 }
12555
12556 pub fn fold_selected_ranges(
12557 &mut self,
12558 _: &FoldSelectedRanges,
12559 window: &mut Window,
12560 cx: &mut Context<Self>,
12561 ) {
12562 let selections = self.selections.all::<Point>(cx);
12563 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12564 let line_mode = self.selections.line_mode;
12565 let ranges = selections
12566 .into_iter()
12567 .map(|s| {
12568 if line_mode {
12569 let start = Point::new(s.start.row, 0);
12570 let end = Point::new(
12571 s.end.row,
12572 display_map
12573 .buffer_snapshot
12574 .line_len(MultiBufferRow(s.end.row)),
12575 );
12576 Crease::simple(start..end, display_map.fold_placeholder.clone())
12577 } else {
12578 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12579 }
12580 })
12581 .collect::<Vec<_>>();
12582 self.fold_creases(ranges, true, window, cx);
12583 }
12584
12585 pub fn fold_ranges<T: ToOffset + Clone>(
12586 &mut self,
12587 ranges: Vec<Range<T>>,
12588 auto_scroll: bool,
12589 window: &mut Window,
12590 cx: &mut Context<Self>,
12591 ) {
12592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12593 let ranges = ranges
12594 .into_iter()
12595 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12596 .collect::<Vec<_>>();
12597 self.fold_creases(ranges, auto_scroll, window, cx);
12598 }
12599
12600 pub fn fold_creases<T: ToOffset + Clone>(
12601 &mut self,
12602 creases: Vec<Crease<T>>,
12603 auto_scroll: bool,
12604 window: &mut Window,
12605 cx: &mut Context<Self>,
12606 ) {
12607 if creases.is_empty() {
12608 return;
12609 }
12610
12611 let mut buffers_affected = HashSet::default();
12612 let multi_buffer = self.buffer().read(cx);
12613 for crease in &creases {
12614 if let Some((_, buffer, _)) =
12615 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12616 {
12617 buffers_affected.insert(buffer.read(cx).remote_id());
12618 };
12619 }
12620
12621 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12622
12623 if auto_scroll {
12624 self.request_autoscroll(Autoscroll::fit(), cx);
12625 }
12626
12627 cx.notify();
12628
12629 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12630 // Clear diagnostics block when folding a range that contains it.
12631 let snapshot = self.snapshot(window, cx);
12632 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12633 drop(snapshot);
12634 self.active_diagnostics = Some(active_diagnostics);
12635 self.dismiss_diagnostics(cx);
12636 } else {
12637 self.active_diagnostics = Some(active_diagnostics);
12638 }
12639 }
12640
12641 self.scrollbar_marker_state.dirty = true;
12642 }
12643
12644 /// Removes any folds whose ranges intersect any of the given ranges.
12645 pub fn unfold_ranges<T: ToOffset + Clone>(
12646 &mut self,
12647 ranges: &[Range<T>],
12648 inclusive: bool,
12649 auto_scroll: bool,
12650 cx: &mut Context<Self>,
12651 ) {
12652 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12653 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12654 });
12655 }
12656
12657 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12658 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12659 return;
12660 }
12661 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12662 self.display_map
12663 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12664 cx.emit(EditorEvent::BufferFoldToggled {
12665 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12666 folded: true,
12667 });
12668 cx.notify();
12669 }
12670
12671 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12672 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12673 return;
12674 }
12675 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12676 self.display_map.update(cx, |display_map, cx| {
12677 display_map.unfold_buffer(buffer_id, cx);
12678 });
12679 cx.emit(EditorEvent::BufferFoldToggled {
12680 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12681 folded: false,
12682 });
12683 cx.notify();
12684 }
12685
12686 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12687 self.display_map.read(cx).is_buffer_folded(buffer)
12688 }
12689
12690 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12691 self.display_map.read(cx).folded_buffers()
12692 }
12693
12694 /// Removes any folds with the given ranges.
12695 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12696 &mut self,
12697 ranges: &[Range<T>],
12698 type_id: TypeId,
12699 auto_scroll: bool,
12700 cx: &mut Context<Self>,
12701 ) {
12702 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12703 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12704 });
12705 }
12706
12707 fn remove_folds_with<T: ToOffset + Clone>(
12708 &mut self,
12709 ranges: &[Range<T>],
12710 auto_scroll: bool,
12711 cx: &mut Context<Self>,
12712 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12713 ) {
12714 if ranges.is_empty() {
12715 return;
12716 }
12717
12718 let mut buffers_affected = HashSet::default();
12719 let multi_buffer = self.buffer().read(cx);
12720 for range in ranges {
12721 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12722 buffers_affected.insert(buffer.read(cx).remote_id());
12723 };
12724 }
12725
12726 self.display_map.update(cx, update);
12727
12728 if auto_scroll {
12729 self.request_autoscroll(Autoscroll::fit(), cx);
12730 }
12731
12732 cx.notify();
12733 self.scrollbar_marker_state.dirty = true;
12734 self.active_indent_guides_state.dirty = true;
12735 }
12736
12737 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12738 self.display_map.read(cx).fold_placeholder.clone()
12739 }
12740
12741 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12742 self.buffer.update(cx, |buffer, cx| {
12743 buffer.set_all_diff_hunks_expanded(cx);
12744 });
12745 }
12746
12747 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12748 self.distinguish_unstaged_diff_hunks = true;
12749 }
12750
12751 pub fn expand_all_diff_hunks(
12752 &mut self,
12753 _: &ExpandAllDiffHunks,
12754 _window: &mut Window,
12755 cx: &mut Context<Self>,
12756 ) {
12757 self.buffer.update(cx, |buffer, cx| {
12758 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12759 });
12760 }
12761
12762 pub fn toggle_selected_diff_hunks(
12763 &mut self,
12764 _: &ToggleSelectedDiffHunks,
12765 _window: &mut Window,
12766 cx: &mut Context<Self>,
12767 ) {
12768 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12769 self.toggle_diff_hunks_in_ranges(ranges, cx);
12770 }
12771
12772 pub fn diff_hunks_in_ranges<'a>(
12773 &'a self,
12774 ranges: &'a [Range<Anchor>],
12775 buffer: &'a MultiBufferSnapshot,
12776 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12777 ranges.iter().flat_map(move |range| {
12778 let end_excerpt_id = range.end.excerpt_id;
12779 let range = range.to_point(buffer);
12780 let mut peek_end = range.end;
12781 if range.end.row < buffer.max_row().0 {
12782 peek_end = Point::new(range.end.row + 1, 0);
12783 }
12784 buffer
12785 .diff_hunks_in_range(range.start..peek_end)
12786 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12787 })
12788 }
12789
12790 pub fn has_stageable_diff_hunks_in_ranges(
12791 &self,
12792 ranges: &[Range<Anchor>],
12793 snapshot: &MultiBufferSnapshot,
12794 ) -> bool {
12795 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12796 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12797 }
12798
12799 pub fn toggle_staged_selected_diff_hunks(
12800 &mut self,
12801 _: &::git::ToggleStaged,
12802 _window: &mut Window,
12803 cx: &mut Context<Self>,
12804 ) {
12805 let snapshot = self.buffer.read(cx).snapshot(cx);
12806 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12807 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12808 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12809 }
12810
12811 pub fn stage_and_next(
12812 &mut self,
12813 _: &::git::StageAndNext,
12814 window: &mut Window,
12815 cx: &mut Context<Self>,
12816 ) {
12817 self.do_stage_or_unstage_and_next(true, window, cx);
12818 }
12819
12820 pub fn unstage_and_next(
12821 &mut self,
12822 _: &::git::UnstageAndNext,
12823 window: &mut Window,
12824 cx: &mut Context<Self>,
12825 ) {
12826 self.do_stage_or_unstage_and_next(false, window, cx);
12827 }
12828
12829 pub fn stage_or_unstage_diff_hunks(
12830 &mut self,
12831 stage: bool,
12832 ranges: &[Range<Anchor>],
12833 cx: &mut Context<Self>,
12834 ) {
12835 let snapshot = self.buffer.read(cx).snapshot(cx);
12836 let Some(project) = &self.project else {
12837 return;
12838 };
12839
12840 let chunk_by = self
12841 .diff_hunks_in_ranges(&ranges, &snapshot)
12842 .chunk_by(|hunk| hunk.buffer_id);
12843 for (buffer_id, hunks) in &chunk_by {
12844 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12845 }
12846 }
12847
12848 fn do_stage_or_unstage_and_next(
12849 &mut self,
12850 stage: bool,
12851 window: &mut Window,
12852 cx: &mut Context<Self>,
12853 ) {
12854 let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
12855 if ranges.iter().any(|range| range.start != range.end) {
12856 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
12857 return;
12858 }
12859
12860 if !self.buffer().read(cx).is_singleton() {
12861 if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
12862 ranges = vec![multi_buffer::Anchor::range_in_buffer(
12863 excerpt_id,
12864 buffer.read(cx).remote_id(),
12865 range,
12866 )];
12867 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
12868 let snapshot = self.buffer().read(cx).snapshot(cx);
12869 let mut point = ranges.last().unwrap().end.to_point(&snapshot);
12870 if point.row < snapshot.max_row().0 {
12871 point.row += 1;
12872 point.column = 0;
12873 point = snapshot.clip_point(point, Bias::Right);
12874 self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
12875 s.select_ranges([point..point]);
12876 })
12877 }
12878 return;
12879 }
12880 }
12881 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
12882 self.go_to_next_hunk(&Default::default(), window, cx);
12883 }
12884
12885 fn do_stage_or_unstage(
12886 project: &Entity<Project>,
12887 stage: bool,
12888 buffer_id: BufferId,
12889 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12890 snapshot: &MultiBufferSnapshot,
12891 cx: &mut Context<Self>,
12892 ) {
12893 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12894 log::debug!("no buffer for id");
12895 return;
12896 };
12897 let buffer = buffer.read(cx).snapshot();
12898 let Some((repo, path)) = project
12899 .read(cx)
12900 .repository_and_path_for_buffer_id(buffer_id, cx)
12901 else {
12902 log::debug!("no git repo for buffer id");
12903 return;
12904 };
12905 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12906 log::debug!("no diff for buffer id");
12907 return;
12908 };
12909 let Some(secondary_diff) = diff.secondary_diff() else {
12910 log::debug!("no secondary diff for buffer id");
12911 return;
12912 };
12913
12914 let edits = diff.secondary_edits_for_stage_or_unstage(
12915 stage,
12916 hunks.filter_map(|hunk| {
12917 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12918 return None;
12919 } else if !stage
12920 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12921 {
12922 return None;
12923 }
12924 Some((
12925 hunk.diff_base_byte_range.clone(),
12926 hunk.secondary_diff_base_byte_range.clone(),
12927 hunk.buffer_range.clone(),
12928 ))
12929 }),
12930 &buffer,
12931 );
12932
12933 let Some(index_base) = secondary_diff
12934 .base_text()
12935 .map(|snapshot| snapshot.text.as_rope().clone())
12936 else {
12937 log::debug!("no index base");
12938 return;
12939 };
12940 let index_buffer = cx.new(|cx| {
12941 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12942 });
12943 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12944 index_buffer.edit(edits, None, cx);
12945 index_buffer.snapshot().as_rope().to_string()
12946 });
12947 let new_index_text = if new_index_text.is_empty()
12948 && (diff.is_single_insertion
12949 || buffer
12950 .file()
12951 .map_or(false, |file| file.disk_state() == DiskState::New))
12952 {
12953 log::debug!("removing from index");
12954 None
12955 } else {
12956 Some(new_index_text)
12957 };
12958
12959 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12960 }
12961
12962 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12963 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12964 self.buffer
12965 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12966 }
12967
12968 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12969 self.buffer.update(cx, |buffer, cx| {
12970 let ranges = vec![Anchor::min()..Anchor::max()];
12971 if !buffer.all_diff_hunks_expanded()
12972 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12973 {
12974 buffer.collapse_diff_hunks(ranges, cx);
12975 true
12976 } else {
12977 false
12978 }
12979 })
12980 }
12981
12982 fn toggle_diff_hunks_in_ranges(
12983 &mut self,
12984 ranges: Vec<Range<Anchor>>,
12985 cx: &mut Context<'_, Editor>,
12986 ) {
12987 self.buffer.update(cx, |buffer, cx| {
12988 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12989 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12990 })
12991 }
12992
12993 fn toggle_diff_hunks_in_ranges_narrow(
12994 &mut self,
12995 ranges: Vec<Range<Anchor>>,
12996 cx: &mut Context<'_, Editor>,
12997 ) {
12998 self.buffer.update(cx, |buffer, cx| {
12999 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13000 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
13001 })
13002 }
13003
13004 pub(crate) fn apply_all_diff_hunks(
13005 &mut self,
13006 _: &ApplyAllDiffHunks,
13007 window: &mut Window,
13008 cx: &mut Context<Self>,
13009 ) {
13010 let buffers = self.buffer.read(cx).all_buffers();
13011 for branch_buffer in buffers {
13012 branch_buffer.update(cx, |branch_buffer, cx| {
13013 branch_buffer.merge_into_base(Vec::new(), cx);
13014 });
13015 }
13016
13017 if let Some(project) = self.project.clone() {
13018 self.save(true, project, window, cx).detach_and_log_err(cx);
13019 }
13020 }
13021
13022 pub(crate) fn apply_selected_diff_hunks(
13023 &mut self,
13024 _: &ApplyDiffHunk,
13025 window: &mut Window,
13026 cx: &mut Context<Self>,
13027 ) {
13028 let snapshot = self.snapshot(window, cx);
13029 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13030 let mut ranges_by_buffer = HashMap::default();
13031 self.transact(window, cx, |editor, _window, cx| {
13032 for hunk in hunks {
13033 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13034 ranges_by_buffer
13035 .entry(buffer.clone())
13036 .or_insert_with(Vec::new)
13037 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13038 }
13039 }
13040
13041 for (buffer, ranges) in ranges_by_buffer {
13042 buffer.update(cx, |buffer, cx| {
13043 buffer.merge_into_base(ranges, cx);
13044 });
13045 }
13046 });
13047
13048 if let Some(project) = self.project.clone() {
13049 self.save(true, project, window, cx).detach_and_log_err(cx);
13050 }
13051 }
13052
13053 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13054 if hovered != self.gutter_hovered {
13055 self.gutter_hovered = hovered;
13056 cx.notify();
13057 }
13058 }
13059
13060 pub fn insert_blocks(
13061 &mut self,
13062 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13063 autoscroll: Option<Autoscroll>,
13064 cx: &mut Context<Self>,
13065 ) -> Vec<CustomBlockId> {
13066 let blocks = self
13067 .display_map
13068 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13069 if let Some(autoscroll) = autoscroll {
13070 self.request_autoscroll(autoscroll, cx);
13071 }
13072 cx.notify();
13073 blocks
13074 }
13075
13076 pub fn resize_blocks(
13077 &mut self,
13078 heights: HashMap<CustomBlockId, u32>,
13079 autoscroll: Option<Autoscroll>,
13080 cx: &mut Context<Self>,
13081 ) {
13082 self.display_map
13083 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13084 if let Some(autoscroll) = autoscroll {
13085 self.request_autoscroll(autoscroll, cx);
13086 }
13087 cx.notify();
13088 }
13089
13090 pub fn replace_blocks(
13091 &mut self,
13092 renderers: HashMap<CustomBlockId, RenderBlock>,
13093 autoscroll: Option<Autoscroll>,
13094 cx: &mut Context<Self>,
13095 ) {
13096 self.display_map
13097 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13098 if let Some(autoscroll) = autoscroll {
13099 self.request_autoscroll(autoscroll, cx);
13100 }
13101 cx.notify();
13102 }
13103
13104 pub fn remove_blocks(
13105 &mut self,
13106 block_ids: HashSet<CustomBlockId>,
13107 autoscroll: Option<Autoscroll>,
13108 cx: &mut Context<Self>,
13109 ) {
13110 self.display_map.update(cx, |display_map, cx| {
13111 display_map.remove_blocks(block_ids, cx)
13112 });
13113 if let Some(autoscroll) = autoscroll {
13114 self.request_autoscroll(autoscroll, cx);
13115 }
13116 cx.notify();
13117 }
13118
13119 pub fn row_for_block(
13120 &self,
13121 block_id: CustomBlockId,
13122 cx: &mut Context<Self>,
13123 ) -> Option<DisplayRow> {
13124 self.display_map
13125 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13126 }
13127
13128 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13129 self.focused_block = Some(focused_block);
13130 }
13131
13132 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13133 self.focused_block.take()
13134 }
13135
13136 pub fn insert_creases(
13137 &mut self,
13138 creases: impl IntoIterator<Item = Crease<Anchor>>,
13139 cx: &mut Context<Self>,
13140 ) -> Vec<CreaseId> {
13141 self.display_map
13142 .update(cx, |map, cx| map.insert_creases(creases, cx))
13143 }
13144
13145 pub fn remove_creases(
13146 &mut self,
13147 ids: impl IntoIterator<Item = CreaseId>,
13148 cx: &mut Context<Self>,
13149 ) {
13150 self.display_map
13151 .update(cx, |map, cx| map.remove_creases(ids, cx));
13152 }
13153
13154 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13155 self.display_map
13156 .update(cx, |map, cx| map.snapshot(cx))
13157 .longest_row()
13158 }
13159
13160 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13161 self.display_map
13162 .update(cx, |map, cx| map.snapshot(cx))
13163 .max_point()
13164 }
13165
13166 pub fn text(&self, cx: &App) -> String {
13167 self.buffer.read(cx).read(cx).text()
13168 }
13169
13170 pub fn is_empty(&self, cx: &App) -> bool {
13171 self.buffer.read(cx).read(cx).is_empty()
13172 }
13173
13174 pub fn text_option(&self, cx: &App) -> Option<String> {
13175 let text = self.text(cx);
13176 let text = text.trim();
13177
13178 if text.is_empty() {
13179 return None;
13180 }
13181
13182 Some(text.to_string())
13183 }
13184
13185 pub fn set_text(
13186 &mut self,
13187 text: impl Into<Arc<str>>,
13188 window: &mut Window,
13189 cx: &mut Context<Self>,
13190 ) {
13191 self.transact(window, cx, |this, _, cx| {
13192 this.buffer
13193 .read(cx)
13194 .as_singleton()
13195 .expect("you can only call set_text on editors for singleton buffers")
13196 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13197 });
13198 }
13199
13200 pub fn display_text(&self, cx: &mut App) -> String {
13201 self.display_map
13202 .update(cx, |map, cx| map.snapshot(cx))
13203 .text()
13204 }
13205
13206 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13207 let mut wrap_guides = smallvec::smallvec![];
13208
13209 if self.show_wrap_guides == Some(false) {
13210 return wrap_guides;
13211 }
13212
13213 let settings = self.buffer.read(cx).settings_at(0, cx);
13214 if settings.show_wrap_guides {
13215 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13216 wrap_guides.push((soft_wrap as usize, true));
13217 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13218 wrap_guides.push((soft_wrap as usize, true));
13219 }
13220 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13221 }
13222
13223 wrap_guides
13224 }
13225
13226 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13227 let settings = self.buffer.read(cx).settings_at(0, cx);
13228 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13229 match mode {
13230 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13231 SoftWrap::None
13232 }
13233 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13234 language_settings::SoftWrap::PreferredLineLength => {
13235 SoftWrap::Column(settings.preferred_line_length)
13236 }
13237 language_settings::SoftWrap::Bounded => {
13238 SoftWrap::Bounded(settings.preferred_line_length)
13239 }
13240 }
13241 }
13242
13243 pub fn set_soft_wrap_mode(
13244 &mut self,
13245 mode: language_settings::SoftWrap,
13246
13247 cx: &mut Context<Self>,
13248 ) {
13249 self.soft_wrap_mode_override = Some(mode);
13250 cx.notify();
13251 }
13252
13253 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13254 self.text_style_refinement = Some(style);
13255 }
13256
13257 /// called by the Element so we know what style we were most recently rendered with.
13258 pub(crate) fn set_style(
13259 &mut self,
13260 style: EditorStyle,
13261 window: &mut Window,
13262 cx: &mut Context<Self>,
13263 ) {
13264 let rem_size = window.rem_size();
13265 self.display_map.update(cx, |map, cx| {
13266 map.set_font(
13267 style.text.font(),
13268 style.text.font_size.to_pixels(rem_size),
13269 cx,
13270 )
13271 });
13272 self.style = Some(style);
13273 }
13274
13275 pub fn style(&self) -> Option<&EditorStyle> {
13276 self.style.as_ref()
13277 }
13278
13279 // Called by the element. This method is not designed to be called outside of the editor
13280 // element's layout code because it does not notify when rewrapping is computed synchronously.
13281 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13282 self.display_map
13283 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13284 }
13285
13286 pub fn set_soft_wrap(&mut self) {
13287 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13288 }
13289
13290 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13291 if self.soft_wrap_mode_override.is_some() {
13292 self.soft_wrap_mode_override.take();
13293 } else {
13294 let soft_wrap = match self.soft_wrap_mode(cx) {
13295 SoftWrap::GitDiff => return,
13296 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13297 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13298 language_settings::SoftWrap::None
13299 }
13300 };
13301 self.soft_wrap_mode_override = Some(soft_wrap);
13302 }
13303 cx.notify();
13304 }
13305
13306 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13307 let Some(workspace) = self.workspace() else {
13308 return;
13309 };
13310 let fs = workspace.read(cx).app_state().fs.clone();
13311 let current_show = TabBarSettings::get_global(cx).show;
13312 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13313 setting.show = Some(!current_show);
13314 });
13315 }
13316
13317 pub fn toggle_indent_guides(
13318 &mut self,
13319 _: &ToggleIndentGuides,
13320 _: &mut Window,
13321 cx: &mut Context<Self>,
13322 ) {
13323 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13324 self.buffer
13325 .read(cx)
13326 .settings_at(0, cx)
13327 .indent_guides
13328 .enabled
13329 });
13330 self.show_indent_guides = Some(!currently_enabled);
13331 cx.notify();
13332 }
13333
13334 fn should_show_indent_guides(&self) -> Option<bool> {
13335 self.show_indent_guides
13336 }
13337
13338 pub fn toggle_line_numbers(
13339 &mut self,
13340 _: &ToggleLineNumbers,
13341 _: &mut Window,
13342 cx: &mut Context<Self>,
13343 ) {
13344 let mut editor_settings = EditorSettings::get_global(cx).clone();
13345 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13346 EditorSettings::override_global(editor_settings, cx);
13347 }
13348
13349 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13350 self.use_relative_line_numbers
13351 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13352 }
13353
13354 pub fn toggle_relative_line_numbers(
13355 &mut self,
13356 _: &ToggleRelativeLineNumbers,
13357 _: &mut Window,
13358 cx: &mut Context<Self>,
13359 ) {
13360 let is_relative = self.should_use_relative_line_numbers(cx);
13361 self.set_relative_line_number(Some(!is_relative), cx)
13362 }
13363
13364 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13365 self.use_relative_line_numbers = is_relative;
13366 cx.notify();
13367 }
13368
13369 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13370 self.show_gutter = show_gutter;
13371 cx.notify();
13372 }
13373
13374 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13375 self.show_scrollbars = show_scrollbars;
13376 cx.notify();
13377 }
13378
13379 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13380 self.show_line_numbers = Some(show_line_numbers);
13381 cx.notify();
13382 }
13383
13384 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13385 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13386 cx.notify();
13387 }
13388
13389 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13390 self.show_code_actions = Some(show_code_actions);
13391 cx.notify();
13392 }
13393
13394 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13395 self.show_runnables = Some(show_runnables);
13396 cx.notify();
13397 }
13398
13399 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13400 if self.display_map.read(cx).masked != masked {
13401 self.display_map.update(cx, |map, _| map.masked = masked);
13402 }
13403 cx.notify()
13404 }
13405
13406 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13407 self.show_wrap_guides = Some(show_wrap_guides);
13408 cx.notify();
13409 }
13410
13411 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13412 self.show_indent_guides = Some(show_indent_guides);
13413 cx.notify();
13414 }
13415
13416 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13417 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13418 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13419 if let Some(dir) = file.abs_path(cx).parent() {
13420 return Some(dir.to_owned());
13421 }
13422 }
13423
13424 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13425 return Some(project_path.path.to_path_buf());
13426 }
13427 }
13428
13429 None
13430 }
13431
13432 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13433 self.active_excerpt(cx)?
13434 .1
13435 .read(cx)
13436 .file()
13437 .and_then(|f| f.as_local())
13438 }
13439
13440 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13441 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13442 let buffer = buffer.read(cx);
13443 if let Some(project_path) = buffer.project_path(cx) {
13444 let project = self.project.as_ref()?.read(cx);
13445 project.absolute_path(&project_path, cx)
13446 } else {
13447 buffer
13448 .file()
13449 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13450 }
13451 })
13452 }
13453
13454 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13455 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13456 let project_path = buffer.read(cx).project_path(cx)?;
13457 let project = self.project.as_ref()?.read(cx);
13458 let entry = project.entry_for_path(&project_path, cx)?;
13459 let path = entry.path.to_path_buf();
13460 Some(path)
13461 })
13462 }
13463
13464 pub fn reveal_in_finder(
13465 &mut self,
13466 _: &RevealInFileManager,
13467 _window: &mut Window,
13468 cx: &mut Context<Self>,
13469 ) {
13470 if let Some(target) = self.target_file(cx) {
13471 cx.reveal_path(&target.abs_path(cx));
13472 }
13473 }
13474
13475 pub fn copy_path(
13476 &mut self,
13477 _: &zed_actions::workspace::CopyPath,
13478 _window: &mut Window,
13479 cx: &mut Context<Self>,
13480 ) {
13481 if let Some(path) = self.target_file_abs_path(cx) {
13482 if let Some(path) = path.to_str() {
13483 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13484 }
13485 }
13486 }
13487
13488 pub fn copy_relative_path(
13489 &mut self,
13490 _: &zed_actions::workspace::CopyRelativePath,
13491 _window: &mut Window,
13492 cx: &mut Context<Self>,
13493 ) {
13494 if let Some(path) = self.target_file_path(cx) {
13495 if let Some(path) = path.to_str() {
13496 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13497 }
13498 }
13499 }
13500
13501 pub fn copy_file_name_without_extension(
13502 &mut self,
13503 _: &CopyFileNameWithoutExtension,
13504 _: &mut Window,
13505 cx: &mut Context<Self>,
13506 ) {
13507 if let Some(file) = self.target_file(cx) {
13508 if let Some(file_stem) = file.path().file_stem() {
13509 if let Some(name) = file_stem.to_str() {
13510 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13511 }
13512 }
13513 }
13514 }
13515
13516 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13517 if let Some(file) = self.target_file(cx) {
13518 if let Some(file_name) = file.path().file_name() {
13519 if let Some(name) = file_name.to_str() {
13520 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13521 }
13522 }
13523 }
13524 }
13525
13526 pub fn toggle_git_blame(
13527 &mut self,
13528 _: &ToggleGitBlame,
13529 window: &mut Window,
13530 cx: &mut Context<Self>,
13531 ) {
13532 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13533
13534 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13535 self.start_git_blame(true, window, cx);
13536 }
13537
13538 cx.notify();
13539 }
13540
13541 pub fn toggle_git_blame_inline(
13542 &mut self,
13543 _: &ToggleGitBlameInline,
13544 window: &mut Window,
13545 cx: &mut Context<Self>,
13546 ) {
13547 self.toggle_git_blame_inline_internal(true, window, cx);
13548 cx.notify();
13549 }
13550
13551 pub fn git_blame_inline_enabled(&self) -> bool {
13552 self.git_blame_inline_enabled
13553 }
13554
13555 pub fn toggle_selection_menu(
13556 &mut self,
13557 _: &ToggleSelectionMenu,
13558 _: &mut Window,
13559 cx: &mut Context<Self>,
13560 ) {
13561 self.show_selection_menu = self
13562 .show_selection_menu
13563 .map(|show_selections_menu| !show_selections_menu)
13564 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13565
13566 cx.notify();
13567 }
13568
13569 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13570 self.show_selection_menu
13571 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13572 }
13573
13574 fn start_git_blame(
13575 &mut self,
13576 user_triggered: bool,
13577 window: &mut Window,
13578 cx: &mut Context<Self>,
13579 ) {
13580 if let Some(project) = self.project.as_ref() {
13581 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13582 return;
13583 };
13584
13585 if buffer.read(cx).file().is_none() {
13586 return;
13587 }
13588
13589 let focused = self.focus_handle(cx).contains_focused(window, cx);
13590
13591 let project = project.clone();
13592 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13593 self.blame_subscription =
13594 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13595 self.blame = Some(blame);
13596 }
13597 }
13598
13599 fn toggle_git_blame_inline_internal(
13600 &mut self,
13601 user_triggered: bool,
13602 window: &mut Window,
13603 cx: &mut Context<Self>,
13604 ) {
13605 if self.git_blame_inline_enabled {
13606 self.git_blame_inline_enabled = false;
13607 self.show_git_blame_inline = false;
13608 self.show_git_blame_inline_delay_task.take();
13609 } else {
13610 self.git_blame_inline_enabled = true;
13611 self.start_git_blame_inline(user_triggered, window, cx);
13612 }
13613
13614 cx.notify();
13615 }
13616
13617 fn start_git_blame_inline(
13618 &mut self,
13619 user_triggered: bool,
13620 window: &mut Window,
13621 cx: &mut Context<Self>,
13622 ) {
13623 self.start_git_blame(user_triggered, window, cx);
13624
13625 if ProjectSettings::get_global(cx)
13626 .git
13627 .inline_blame_delay()
13628 .is_some()
13629 {
13630 self.start_inline_blame_timer(window, cx);
13631 } else {
13632 self.show_git_blame_inline = true
13633 }
13634 }
13635
13636 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13637 self.blame.as_ref()
13638 }
13639
13640 pub fn show_git_blame_gutter(&self) -> bool {
13641 self.show_git_blame_gutter
13642 }
13643
13644 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13645 self.show_git_blame_gutter && self.has_blame_entries(cx)
13646 }
13647
13648 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13649 self.show_git_blame_inline
13650 && (self.focus_handle.is_focused(window)
13651 || self
13652 .git_blame_inline_tooltip
13653 .as_ref()
13654 .and_then(|t| t.upgrade())
13655 .is_some())
13656 && !self.newest_selection_head_on_empty_line(cx)
13657 && self.has_blame_entries(cx)
13658 }
13659
13660 fn has_blame_entries(&self, cx: &App) -> bool {
13661 self.blame()
13662 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13663 }
13664
13665 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13666 let cursor_anchor = self.selections.newest_anchor().head();
13667
13668 let snapshot = self.buffer.read(cx).snapshot(cx);
13669 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13670
13671 snapshot.line_len(buffer_row) == 0
13672 }
13673
13674 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13675 let buffer_and_selection = maybe!({
13676 let selection = self.selections.newest::<Point>(cx);
13677 let selection_range = selection.range();
13678
13679 let multi_buffer = self.buffer().read(cx);
13680 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13681 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13682
13683 let (buffer, range, _) = if selection.reversed {
13684 buffer_ranges.first()
13685 } else {
13686 buffer_ranges.last()
13687 }?;
13688
13689 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13690 ..text::ToPoint::to_point(&range.end, &buffer).row;
13691 Some((
13692 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13693 selection,
13694 ))
13695 });
13696
13697 let Some((buffer, selection)) = buffer_and_selection else {
13698 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13699 };
13700
13701 let Some(project) = self.project.as_ref() else {
13702 return Task::ready(Err(anyhow!("editor does not have project")));
13703 };
13704
13705 project.update(cx, |project, cx| {
13706 project.get_permalink_to_line(&buffer, selection, cx)
13707 })
13708 }
13709
13710 pub fn copy_permalink_to_line(
13711 &mut self,
13712 _: &CopyPermalinkToLine,
13713 window: &mut Window,
13714 cx: &mut Context<Self>,
13715 ) {
13716 let permalink_task = self.get_permalink_to_line(cx);
13717 let workspace = self.workspace();
13718
13719 cx.spawn_in(window, |_, mut cx| async move {
13720 match permalink_task.await {
13721 Ok(permalink) => {
13722 cx.update(|_, cx| {
13723 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13724 })
13725 .ok();
13726 }
13727 Err(err) => {
13728 let message = format!("Failed to copy permalink: {err}");
13729
13730 Err::<(), anyhow::Error>(err).log_err();
13731
13732 if let Some(workspace) = workspace {
13733 workspace
13734 .update_in(&mut cx, |workspace, _, cx| {
13735 struct CopyPermalinkToLine;
13736
13737 workspace.show_toast(
13738 Toast::new(
13739 NotificationId::unique::<CopyPermalinkToLine>(),
13740 message,
13741 ),
13742 cx,
13743 )
13744 })
13745 .ok();
13746 }
13747 }
13748 }
13749 })
13750 .detach();
13751 }
13752
13753 pub fn copy_file_location(
13754 &mut self,
13755 _: &CopyFileLocation,
13756 _: &mut Window,
13757 cx: &mut Context<Self>,
13758 ) {
13759 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13760 if let Some(file) = self.target_file(cx) {
13761 if let Some(path) = file.path().to_str() {
13762 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13763 }
13764 }
13765 }
13766
13767 pub fn open_permalink_to_line(
13768 &mut self,
13769 _: &OpenPermalinkToLine,
13770 window: &mut Window,
13771 cx: &mut Context<Self>,
13772 ) {
13773 let permalink_task = self.get_permalink_to_line(cx);
13774 let workspace = self.workspace();
13775
13776 cx.spawn_in(window, |_, mut cx| async move {
13777 match permalink_task.await {
13778 Ok(permalink) => {
13779 cx.update(|_, cx| {
13780 cx.open_url(permalink.as_ref());
13781 })
13782 .ok();
13783 }
13784 Err(err) => {
13785 let message = format!("Failed to open permalink: {err}");
13786
13787 Err::<(), anyhow::Error>(err).log_err();
13788
13789 if let Some(workspace) = workspace {
13790 workspace
13791 .update(&mut cx, |workspace, cx| {
13792 struct OpenPermalinkToLine;
13793
13794 workspace.show_toast(
13795 Toast::new(
13796 NotificationId::unique::<OpenPermalinkToLine>(),
13797 message,
13798 ),
13799 cx,
13800 )
13801 })
13802 .ok();
13803 }
13804 }
13805 }
13806 })
13807 .detach();
13808 }
13809
13810 pub fn insert_uuid_v4(
13811 &mut self,
13812 _: &InsertUuidV4,
13813 window: &mut Window,
13814 cx: &mut Context<Self>,
13815 ) {
13816 self.insert_uuid(UuidVersion::V4, window, cx);
13817 }
13818
13819 pub fn insert_uuid_v7(
13820 &mut self,
13821 _: &InsertUuidV7,
13822 window: &mut Window,
13823 cx: &mut Context<Self>,
13824 ) {
13825 self.insert_uuid(UuidVersion::V7, window, cx);
13826 }
13827
13828 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13829 self.transact(window, cx, |this, window, cx| {
13830 let edits = this
13831 .selections
13832 .all::<Point>(cx)
13833 .into_iter()
13834 .map(|selection| {
13835 let uuid = match version {
13836 UuidVersion::V4 => uuid::Uuid::new_v4(),
13837 UuidVersion::V7 => uuid::Uuid::now_v7(),
13838 };
13839
13840 (selection.range(), uuid.to_string())
13841 });
13842 this.edit(edits, cx);
13843 this.refresh_inline_completion(true, false, window, cx);
13844 });
13845 }
13846
13847 pub fn open_selections_in_multibuffer(
13848 &mut self,
13849 _: &OpenSelectionsInMultibuffer,
13850 window: &mut Window,
13851 cx: &mut Context<Self>,
13852 ) {
13853 let multibuffer = self.buffer.read(cx);
13854
13855 let Some(buffer) = multibuffer.as_singleton() else {
13856 return;
13857 };
13858
13859 let Some(workspace) = self.workspace() else {
13860 return;
13861 };
13862
13863 let locations = self
13864 .selections
13865 .disjoint_anchors()
13866 .iter()
13867 .map(|range| Location {
13868 buffer: buffer.clone(),
13869 range: range.start.text_anchor..range.end.text_anchor,
13870 })
13871 .collect::<Vec<_>>();
13872
13873 let title = multibuffer.title(cx).to_string();
13874
13875 cx.spawn_in(window, |_, mut cx| async move {
13876 workspace.update_in(&mut cx, |workspace, window, cx| {
13877 Self::open_locations_in_multibuffer(
13878 workspace,
13879 locations,
13880 format!("Selections for '{title}'"),
13881 false,
13882 MultibufferSelectionMode::All,
13883 window,
13884 cx,
13885 );
13886 })
13887 })
13888 .detach();
13889 }
13890
13891 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13892 /// last highlight added will be used.
13893 ///
13894 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13895 pub fn highlight_rows<T: 'static>(
13896 &mut self,
13897 range: Range<Anchor>,
13898 color: Hsla,
13899 should_autoscroll: bool,
13900 cx: &mut Context<Self>,
13901 ) {
13902 let snapshot = self.buffer().read(cx).snapshot(cx);
13903 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13904 let ix = row_highlights.binary_search_by(|highlight| {
13905 Ordering::Equal
13906 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13907 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13908 });
13909
13910 if let Err(mut ix) = ix {
13911 let index = post_inc(&mut self.highlight_order);
13912
13913 // If this range intersects with the preceding highlight, then merge it with
13914 // the preceding highlight. Otherwise insert a new highlight.
13915 let mut merged = false;
13916 if ix > 0 {
13917 let prev_highlight = &mut row_highlights[ix - 1];
13918 if prev_highlight
13919 .range
13920 .end
13921 .cmp(&range.start, &snapshot)
13922 .is_ge()
13923 {
13924 ix -= 1;
13925 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13926 prev_highlight.range.end = range.end;
13927 }
13928 merged = true;
13929 prev_highlight.index = index;
13930 prev_highlight.color = color;
13931 prev_highlight.should_autoscroll = should_autoscroll;
13932 }
13933 }
13934
13935 if !merged {
13936 row_highlights.insert(
13937 ix,
13938 RowHighlight {
13939 range: range.clone(),
13940 index,
13941 color,
13942 should_autoscroll,
13943 },
13944 );
13945 }
13946
13947 // If any of the following highlights intersect with this one, merge them.
13948 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13949 let highlight = &row_highlights[ix];
13950 if next_highlight
13951 .range
13952 .start
13953 .cmp(&highlight.range.end, &snapshot)
13954 .is_le()
13955 {
13956 if next_highlight
13957 .range
13958 .end
13959 .cmp(&highlight.range.end, &snapshot)
13960 .is_gt()
13961 {
13962 row_highlights[ix].range.end = next_highlight.range.end;
13963 }
13964 row_highlights.remove(ix + 1);
13965 } else {
13966 break;
13967 }
13968 }
13969 }
13970 }
13971
13972 /// Remove any highlighted row ranges of the given type that intersect the
13973 /// given ranges.
13974 pub fn remove_highlighted_rows<T: 'static>(
13975 &mut self,
13976 ranges_to_remove: Vec<Range<Anchor>>,
13977 cx: &mut Context<Self>,
13978 ) {
13979 let snapshot = self.buffer().read(cx).snapshot(cx);
13980 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13981 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13982 row_highlights.retain(|highlight| {
13983 while let Some(range_to_remove) = ranges_to_remove.peek() {
13984 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13985 Ordering::Less | Ordering::Equal => {
13986 ranges_to_remove.next();
13987 }
13988 Ordering::Greater => {
13989 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13990 Ordering::Less | Ordering::Equal => {
13991 return false;
13992 }
13993 Ordering::Greater => break,
13994 }
13995 }
13996 }
13997 }
13998
13999 true
14000 })
14001 }
14002
14003 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14004 pub fn clear_row_highlights<T: 'static>(&mut self) {
14005 self.highlighted_rows.remove(&TypeId::of::<T>());
14006 }
14007
14008 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14009 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14010 self.highlighted_rows
14011 .get(&TypeId::of::<T>())
14012 .map_or(&[] as &[_], |vec| vec.as_slice())
14013 .iter()
14014 .map(|highlight| (highlight.range.clone(), highlight.color))
14015 }
14016
14017 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14018 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14019 /// Allows to ignore certain kinds of highlights.
14020 pub fn highlighted_display_rows(
14021 &self,
14022 window: &mut Window,
14023 cx: &mut App,
14024 ) -> BTreeMap<DisplayRow, Background> {
14025 let snapshot = self.snapshot(window, cx);
14026 let mut used_highlight_orders = HashMap::default();
14027 self.highlighted_rows
14028 .iter()
14029 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14030 .fold(
14031 BTreeMap::<DisplayRow, Background>::new(),
14032 |mut unique_rows, highlight| {
14033 let start = highlight.range.start.to_display_point(&snapshot);
14034 let end = highlight.range.end.to_display_point(&snapshot);
14035 let start_row = start.row().0;
14036 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14037 && end.column() == 0
14038 {
14039 end.row().0.saturating_sub(1)
14040 } else {
14041 end.row().0
14042 };
14043 for row in start_row..=end_row {
14044 let used_index =
14045 used_highlight_orders.entry(row).or_insert(highlight.index);
14046 if highlight.index >= *used_index {
14047 *used_index = highlight.index;
14048 unique_rows.insert(DisplayRow(row), highlight.color.into());
14049 }
14050 }
14051 unique_rows
14052 },
14053 )
14054 }
14055
14056 pub fn highlighted_display_row_for_autoscroll(
14057 &self,
14058 snapshot: &DisplaySnapshot,
14059 ) -> Option<DisplayRow> {
14060 self.highlighted_rows
14061 .values()
14062 .flat_map(|highlighted_rows| highlighted_rows.iter())
14063 .filter_map(|highlight| {
14064 if highlight.should_autoscroll {
14065 Some(highlight.range.start.to_display_point(snapshot).row())
14066 } else {
14067 None
14068 }
14069 })
14070 .min()
14071 }
14072
14073 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14074 self.highlight_background::<SearchWithinRange>(
14075 ranges,
14076 |colors| colors.editor_document_highlight_read_background,
14077 cx,
14078 )
14079 }
14080
14081 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14082 self.breadcrumb_header = Some(new_header);
14083 }
14084
14085 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14086 self.clear_background_highlights::<SearchWithinRange>(cx);
14087 }
14088
14089 pub fn highlight_background<T: 'static>(
14090 &mut self,
14091 ranges: &[Range<Anchor>],
14092 color_fetcher: fn(&ThemeColors) -> Hsla,
14093 cx: &mut Context<Self>,
14094 ) {
14095 self.background_highlights
14096 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14097 self.scrollbar_marker_state.dirty = true;
14098 cx.notify();
14099 }
14100
14101 pub fn clear_background_highlights<T: 'static>(
14102 &mut self,
14103 cx: &mut Context<Self>,
14104 ) -> Option<BackgroundHighlight> {
14105 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14106 if !text_highlights.1.is_empty() {
14107 self.scrollbar_marker_state.dirty = true;
14108 cx.notify();
14109 }
14110 Some(text_highlights)
14111 }
14112
14113 pub fn highlight_gutter<T: 'static>(
14114 &mut self,
14115 ranges: &[Range<Anchor>],
14116 color_fetcher: fn(&App) -> Hsla,
14117 cx: &mut Context<Self>,
14118 ) {
14119 self.gutter_highlights
14120 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14121 cx.notify();
14122 }
14123
14124 pub fn clear_gutter_highlights<T: 'static>(
14125 &mut self,
14126 cx: &mut Context<Self>,
14127 ) -> Option<GutterHighlight> {
14128 cx.notify();
14129 self.gutter_highlights.remove(&TypeId::of::<T>())
14130 }
14131
14132 #[cfg(feature = "test-support")]
14133 pub fn all_text_background_highlights(
14134 &self,
14135 window: &mut Window,
14136 cx: &mut Context<Self>,
14137 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14138 let snapshot = self.snapshot(window, cx);
14139 let buffer = &snapshot.buffer_snapshot;
14140 let start = buffer.anchor_before(0);
14141 let end = buffer.anchor_after(buffer.len());
14142 let theme = cx.theme().colors();
14143 self.background_highlights_in_range(start..end, &snapshot, theme)
14144 }
14145
14146 #[cfg(feature = "test-support")]
14147 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14148 let snapshot = self.buffer().read(cx).snapshot(cx);
14149
14150 let highlights = self
14151 .background_highlights
14152 .get(&TypeId::of::<items::BufferSearchHighlights>());
14153
14154 if let Some((_color, ranges)) = highlights {
14155 ranges
14156 .iter()
14157 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14158 .collect_vec()
14159 } else {
14160 vec![]
14161 }
14162 }
14163
14164 fn document_highlights_for_position<'a>(
14165 &'a self,
14166 position: Anchor,
14167 buffer: &'a MultiBufferSnapshot,
14168 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14169 let read_highlights = self
14170 .background_highlights
14171 .get(&TypeId::of::<DocumentHighlightRead>())
14172 .map(|h| &h.1);
14173 let write_highlights = self
14174 .background_highlights
14175 .get(&TypeId::of::<DocumentHighlightWrite>())
14176 .map(|h| &h.1);
14177 let left_position = position.bias_left(buffer);
14178 let right_position = position.bias_right(buffer);
14179 read_highlights
14180 .into_iter()
14181 .chain(write_highlights)
14182 .flat_map(move |ranges| {
14183 let start_ix = match ranges.binary_search_by(|probe| {
14184 let cmp = probe.end.cmp(&left_position, buffer);
14185 if cmp.is_ge() {
14186 Ordering::Greater
14187 } else {
14188 Ordering::Less
14189 }
14190 }) {
14191 Ok(i) | Err(i) => i,
14192 };
14193
14194 ranges[start_ix..]
14195 .iter()
14196 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14197 })
14198 }
14199
14200 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14201 self.background_highlights
14202 .get(&TypeId::of::<T>())
14203 .map_or(false, |(_, highlights)| !highlights.is_empty())
14204 }
14205
14206 pub fn background_highlights_in_range(
14207 &self,
14208 search_range: Range<Anchor>,
14209 display_snapshot: &DisplaySnapshot,
14210 theme: &ThemeColors,
14211 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14212 let mut results = Vec::new();
14213 for (color_fetcher, ranges) in self.background_highlights.values() {
14214 let color = color_fetcher(theme);
14215 let start_ix = match ranges.binary_search_by(|probe| {
14216 let cmp = probe
14217 .end
14218 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14219 if cmp.is_gt() {
14220 Ordering::Greater
14221 } else {
14222 Ordering::Less
14223 }
14224 }) {
14225 Ok(i) | Err(i) => i,
14226 };
14227 for range in &ranges[start_ix..] {
14228 if range
14229 .start
14230 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14231 .is_ge()
14232 {
14233 break;
14234 }
14235
14236 let start = range.start.to_display_point(display_snapshot);
14237 let end = range.end.to_display_point(display_snapshot);
14238 results.push((start..end, color))
14239 }
14240 }
14241 results
14242 }
14243
14244 pub fn background_highlight_row_ranges<T: 'static>(
14245 &self,
14246 search_range: Range<Anchor>,
14247 display_snapshot: &DisplaySnapshot,
14248 count: usize,
14249 ) -> Vec<RangeInclusive<DisplayPoint>> {
14250 let mut results = Vec::new();
14251 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14252 return vec![];
14253 };
14254
14255 let start_ix = match ranges.binary_search_by(|probe| {
14256 let cmp = probe
14257 .end
14258 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14259 if cmp.is_gt() {
14260 Ordering::Greater
14261 } else {
14262 Ordering::Less
14263 }
14264 }) {
14265 Ok(i) | Err(i) => i,
14266 };
14267 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14268 if let (Some(start_display), Some(end_display)) = (start, end) {
14269 results.push(
14270 start_display.to_display_point(display_snapshot)
14271 ..=end_display.to_display_point(display_snapshot),
14272 );
14273 }
14274 };
14275 let mut start_row: Option<Point> = None;
14276 let mut end_row: Option<Point> = None;
14277 if ranges.len() > count {
14278 return Vec::new();
14279 }
14280 for range in &ranges[start_ix..] {
14281 if range
14282 .start
14283 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14284 .is_ge()
14285 {
14286 break;
14287 }
14288 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14289 if let Some(current_row) = &end_row {
14290 if end.row == current_row.row {
14291 continue;
14292 }
14293 }
14294 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14295 if start_row.is_none() {
14296 assert_eq!(end_row, None);
14297 start_row = Some(start);
14298 end_row = Some(end);
14299 continue;
14300 }
14301 if let Some(current_end) = end_row.as_mut() {
14302 if start.row > current_end.row + 1 {
14303 push_region(start_row, end_row);
14304 start_row = Some(start);
14305 end_row = Some(end);
14306 } else {
14307 // Merge two hunks.
14308 *current_end = end;
14309 }
14310 } else {
14311 unreachable!();
14312 }
14313 }
14314 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14315 push_region(start_row, end_row);
14316 results
14317 }
14318
14319 pub fn gutter_highlights_in_range(
14320 &self,
14321 search_range: Range<Anchor>,
14322 display_snapshot: &DisplaySnapshot,
14323 cx: &App,
14324 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14325 let mut results = Vec::new();
14326 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14327 let color = color_fetcher(cx);
14328 let start_ix = match ranges.binary_search_by(|probe| {
14329 let cmp = probe
14330 .end
14331 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14332 if cmp.is_gt() {
14333 Ordering::Greater
14334 } else {
14335 Ordering::Less
14336 }
14337 }) {
14338 Ok(i) | Err(i) => i,
14339 };
14340 for range in &ranges[start_ix..] {
14341 if range
14342 .start
14343 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14344 .is_ge()
14345 {
14346 break;
14347 }
14348
14349 let start = range.start.to_display_point(display_snapshot);
14350 let end = range.end.to_display_point(display_snapshot);
14351 results.push((start..end, color))
14352 }
14353 }
14354 results
14355 }
14356
14357 /// Get the text ranges corresponding to the redaction query
14358 pub fn redacted_ranges(
14359 &self,
14360 search_range: Range<Anchor>,
14361 display_snapshot: &DisplaySnapshot,
14362 cx: &App,
14363 ) -> Vec<Range<DisplayPoint>> {
14364 display_snapshot
14365 .buffer_snapshot
14366 .redacted_ranges(search_range, |file| {
14367 if let Some(file) = file {
14368 file.is_private()
14369 && EditorSettings::get(
14370 Some(SettingsLocation {
14371 worktree_id: file.worktree_id(cx),
14372 path: file.path().as_ref(),
14373 }),
14374 cx,
14375 )
14376 .redact_private_values
14377 } else {
14378 false
14379 }
14380 })
14381 .map(|range| {
14382 range.start.to_display_point(display_snapshot)
14383 ..range.end.to_display_point(display_snapshot)
14384 })
14385 .collect()
14386 }
14387
14388 pub fn highlight_text<T: 'static>(
14389 &mut self,
14390 ranges: Vec<Range<Anchor>>,
14391 style: HighlightStyle,
14392 cx: &mut Context<Self>,
14393 ) {
14394 self.display_map.update(cx, |map, _| {
14395 map.highlight_text(TypeId::of::<T>(), ranges, style)
14396 });
14397 cx.notify();
14398 }
14399
14400 pub(crate) fn highlight_inlays<T: 'static>(
14401 &mut self,
14402 highlights: Vec<InlayHighlight>,
14403 style: HighlightStyle,
14404 cx: &mut Context<Self>,
14405 ) {
14406 self.display_map.update(cx, |map, _| {
14407 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14408 });
14409 cx.notify();
14410 }
14411
14412 pub fn text_highlights<'a, T: 'static>(
14413 &'a self,
14414 cx: &'a App,
14415 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14416 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14417 }
14418
14419 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14420 let cleared = self
14421 .display_map
14422 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14423 if cleared {
14424 cx.notify();
14425 }
14426 }
14427
14428 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14429 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14430 && self.focus_handle.is_focused(window)
14431 }
14432
14433 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14434 self.show_cursor_when_unfocused = is_enabled;
14435 cx.notify();
14436 }
14437
14438 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14439 cx.notify();
14440 }
14441
14442 fn on_buffer_event(
14443 &mut self,
14444 multibuffer: &Entity<MultiBuffer>,
14445 event: &multi_buffer::Event,
14446 window: &mut Window,
14447 cx: &mut Context<Self>,
14448 ) {
14449 match event {
14450 multi_buffer::Event::Edited {
14451 singleton_buffer_edited,
14452 edited_buffer: buffer_edited,
14453 } => {
14454 self.scrollbar_marker_state.dirty = true;
14455 self.active_indent_guides_state.dirty = true;
14456 self.refresh_active_diagnostics(cx);
14457 self.refresh_code_actions(window, cx);
14458 if self.has_active_inline_completion() {
14459 self.update_visible_inline_completion(window, cx);
14460 }
14461 if let Some(buffer) = buffer_edited {
14462 let buffer_id = buffer.read(cx).remote_id();
14463 if !self.registered_buffers.contains_key(&buffer_id) {
14464 if let Some(project) = self.project.as_ref() {
14465 project.update(cx, |project, cx| {
14466 self.registered_buffers.insert(
14467 buffer_id,
14468 project.register_buffer_with_language_servers(&buffer, cx),
14469 );
14470 })
14471 }
14472 }
14473 }
14474 cx.emit(EditorEvent::BufferEdited);
14475 cx.emit(SearchEvent::MatchesInvalidated);
14476 if *singleton_buffer_edited {
14477 if let Some(project) = &self.project {
14478 #[allow(clippy::mutable_key_type)]
14479 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14480 multibuffer
14481 .all_buffers()
14482 .into_iter()
14483 .filter_map(|buffer| {
14484 buffer.update(cx, |buffer, cx| {
14485 let language = buffer.language()?;
14486 let should_discard = project.update(cx, |project, cx| {
14487 project.is_local()
14488 && !project.has_language_servers_for(buffer, cx)
14489 });
14490 should_discard.not().then_some(language.clone())
14491 })
14492 })
14493 .collect::<HashSet<_>>()
14494 });
14495 if !languages_affected.is_empty() {
14496 self.refresh_inlay_hints(
14497 InlayHintRefreshReason::BufferEdited(languages_affected),
14498 cx,
14499 );
14500 }
14501 }
14502 }
14503
14504 let Some(project) = &self.project else { return };
14505 let (telemetry, is_via_ssh) = {
14506 let project = project.read(cx);
14507 let telemetry = project.client().telemetry().clone();
14508 let is_via_ssh = project.is_via_ssh();
14509 (telemetry, is_via_ssh)
14510 };
14511 refresh_linked_ranges(self, window, cx);
14512 telemetry.log_edit_event("editor", is_via_ssh);
14513 }
14514 multi_buffer::Event::ExcerptsAdded {
14515 buffer,
14516 predecessor,
14517 excerpts,
14518 } => {
14519 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14520 let buffer_id = buffer.read(cx).remote_id();
14521 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14522 if let Some(project) = &self.project {
14523 get_uncommitted_diff_for_buffer(
14524 project,
14525 [buffer.clone()],
14526 self.buffer.clone(),
14527 cx,
14528 )
14529 .detach();
14530 }
14531 }
14532 cx.emit(EditorEvent::ExcerptsAdded {
14533 buffer: buffer.clone(),
14534 predecessor: *predecessor,
14535 excerpts: excerpts.clone(),
14536 });
14537 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14538 }
14539 multi_buffer::Event::ExcerptsRemoved { ids } => {
14540 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14541 let buffer = self.buffer.read(cx);
14542 self.registered_buffers
14543 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14544 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14545 }
14546 multi_buffer::Event::ExcerptsEdited { ids } => {
14547 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14548 }
14549 multi_buffer::Event::ExcerptsExpanded { ids } => {
14550 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14551 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14552 }
14553 multi_buffer::Event::Reparsed(buffer_id) => {
14554 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14555
14556 cx.emit(EditorEvent::Reparsed(*buffer_id));
14557 }
14558 multi_buffer::Event::DiffHunksToggled => {
14559 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14560 }
14561 multi_buffer::Event::LanguageChanged(buffer_id) => {
14562 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14563 cx.emit(EditorEvent::Reparsed(*buffer_id));
14564 cx.notify();
14565 }
14566 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14567 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14568 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14569 cx.emit(EditorEvent::TitleChanged)
14570 }
14571 // multi_buffer::Event::DiffBaseChanged => {
14572 // self.scrollbar_marker_state.dirty = true;
14573 // cx.emit(EditorEvent::DiffBaseChanged);
14574 // cx.notify();
14575 // }
14576 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14577 multi_buffer::Event::DiagnosticsUpdated => {
14578 self.refresh_active_diagnostics(cx);
14579 self.refresh_inline_diagnostics(true, window, cx);
14580 self.scrollbar_marker_state.dirty = true;
14581 cx.notify();
14582 }
14583 _ => {}
14584 };
14585 }
14586
14587 fn on_display_map_changed(
14588 &mut self,
14589 _: Entity<DisplayMap>,
14590 _: &mut Window,
14591 cx: &mut Context<Self>,
14592 ) {
14593 cx.notify();
14594 }
14595
14596 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14597 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14598 self.refresh_inline_completion(true, false, window, cx);
14599 self.refresh_inlay_hints(
14600 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14601 self.selections.newest_anchor().head(),
14602 &self.buffer.read(cx).snapshot(cx),
14603 cx,
14604 )),
14605 cx,
14606 );
14607
14608 let old_cursor_shape = self.cursor_shape;
14609
14610 {
14611 let editor_settings = EditorSettings::get_global(cx);
14612 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14613 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14614 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14615 self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
14616
14617 if !self.hide_mouse_while_typing {
14618 self.mouse_cursor_hidden = false;
14619 }
14620 }
14621
14622 if old_cursor_shape != self.cursor_shape {
14623 cx.emit(EditorEvent::CursorShapeChanged);
14624 }
14625
14626 let project_settings = ProjectSettings::get_global(cx);
14627 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14628
14629 if self.mode == EditorMode::Full {
14630 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
14631 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14632 if self.show_inline_diagnostics != show_inline_diagnostics {
14633 self.show_inline_diagnostics = show_inline_diagnostics;
14634 self.refresh_inline_diagnostics(false, window, cx);
14635 }
14636
14637 if self.git_blame_inline_enabled != inline_blame_enabled {
14638 self.toggle_git_blame_inline_internal(false, window, cx);
14639 }
14640 }
14641
14642 cx.notify();
14643 }
14644
14645 pub fn set_searchable(&mut self, searchable: bool) {
14646 self.searchable = searchable;
14647 }
14648
14649 pub fn searchable(&self) -> bool {
14650 self.searchable
14651 }
14652
14653 fn open_proposed_changes_editor(
14654 &mut self,
14655 _: &OpenProposedChangesEditor,
14656 window: &mut Window,
14657 cx: &mut Context<Self>,
14658 ) {
14659 let Some(workspace) = self.workspace() else {
14660 cx.propagate();
14661 return;
14662 };
14663
14664 let selections = self.selections.all::<usize>(cx);
14665 let multi_buffer = self.buffer.read(cx);
14666 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14667 let mut new_selections_by_buffer = HashMap::default();
14668 for selection in selections {
14669 for (buffer, range, _) in
14670 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14671 {
14672 let mut range = range.to_point(buffer);
14673 range.start.column = 0;
14674 range.end.column = buffer.line_len(range.end.row);
14675 new_selections_by_buffer
14676 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14677 .or_insert(Vec::new())
14678 .push(range)
14679 }
14680 }
14681
14682 let proposed_changes_buffers = new_selections_by_buffer
14683 .into_iter()
14684 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14685 .collect::<Vec<_>>();
14686 let proposed_changes_editor = cx.new(|cx| {
14687 ProposedChangesEditor::new(
14688 "Proposed changes",
14689 proposed_changes_buffers,
14690 self.project.clone(),
14691 window,
14692 cx,
14693 )
14694 });
14695
14696 window.defer(cx, move |window, cx| {
14697 workspace.update(cx, |workspace, cx| {
14698 workspace.active_pane().update(cx, |pane, cx| {
14699 pane.add_item(
14700 Box::new(proposed_changes_editor),
14701 true,
14702 true,
14703 None,
14704 window,
14705 cx,
14706 );
14707 });
14708 });
14709 });
14710 }
14711
14712 pub fn open_excerpts_in_split(
14713 &mut self,
14714 _: &OpenExcerptsSplit,
14715 window: &mut Window,
14716 cx: &mut Context<Self>,
14717 ) {
14718 self.open_excerpts_common(None, true, window, cx)
14719 }
14720
14721 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14722 self.open_excerpts_common(None, false, window, cx)
14723 }
14724
14725 fn open_excerpts_common(
14726 &mut self,
14727 jump_data: Option<JumpData>,
14728 split: bool,
14729 window: &mut Window,
14730 cx: &mut Context<Self>,
14731 ) {
14732 let Some(workspace) = self.workspace() else {
14733 cx.propagate();
14734 return;
14735 };
14736
14737 if self.buffer.read(cx).is_singleton() {
14738 cx.propagate();
14739 return;
14740 }
14741
14742 let mut new_selections_by_buffer = HashMap::default();
14743 match &jump_data {
14744 Some(JumpData::MultiBufferPoint {
14745 excerpt_id,
14746 position,
14747 anchor,
14748 line_offset_from_top,
14749 }) => {
14750 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14751 if let Some(buffer) = multi_buffer_snapshot
14752 .buffer_id_for_excerpt(*excerpt_id)
14753 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14754 {
14755 let buffer_snapshot = buffer.read(cx).snapshot();
14756 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14757 language::ToPoint::to_point(anchor, &buffer_snapshot)
14758 } else {
14759 buffer_snapshot.clip_point(*position, Bias::Left)
14760 };
14761 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14762 new_selections_by_buffer.insert(
14763 buffer,
14764 (
14765 vec![jump_to_offset..jump_to_offset],
14766 Some(*line_offset_from_top),
14767 ),
14768 );
14769 }
14770 }
14771 Some(JumpData::MultiBufferRow {
14772 row,
14773 line_offset_from_top,
14774 }) => {
14775 let point = MultiBufferPoint::new(row.0, 0);
14776 if let Some((buffer, buffer_point, _)) =
14777 self.buffer.read(cx).point_to_buffer_point(point, cx)
14778 {
14779 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14780 new_selections_by_buffer
14781 .entry(buffer)
14782 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14783 .0
14784 .push(buffer_offset..buffer_offset)
14785 }
14786 }
14787 None => {
14788 let selections = self.selections.all::<usize>(cx);
14789 let multi_buffer = self.buffer.read(cx);
14790 for selection in selections {
14791 for (buffer, mut range, _) in multi_buffer
14792 .snapshot(cx)
14793 .range_to_buffer_ranges(selection.range())
14794 {
14795 // When editing branch buffers, jump to the corresponding location
14796 // in their base buffer.
14797 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14798 let buffer = buffer_handle.read(cx);
14799 if let Some(base_buffer) = buffer.base_buffer() {
14800 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14801 buffer_handle = base_buffer;
14802 }
14803
14804 if selection.reversed {
14805 mem::swap(&mut range.start, &mut range.end);
14806 }
14807 new_selections_by_buffer
14808 .entry(buffer_handle)
14809 .or_insert((Vec::new(), None))
14810 .0
14811 .push(range)
14812 }
14813 }
14814 }
14815 }
14816
14817 if new_selections_by_buffer.is_empty() {
14818 return;
14819 }
14820
14821 // We defer the pane interaction because we ourselves are a workspace item
14822 // and activating a new item causes the pane to call a method on us reentrantly,
14823 // which panics if we're on the stack.
14824 window.defer(cx, move |window, cx| {
14825 workspace.update(cx, |workspace, cx| {
14826 let pane = if split {
14827 workspace.adjacent_pane(window, cx)
14828 } else {
14829 workspace.active_pane().clone()
14830 };
14831
14832 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14833 let editor = buffer
14834 .read(cx)
14835 .file()
14836 .is_none()
14837 .then(|| {
14838 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14839 // so `workspace.open_project_item` will never find them, always opening a new editor.
14840 // Instead, we try to activate the existing editor in the pane first.
14841 let (editor, pane_item_index) =
14842 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14843 let editor = item.downcast::<Editor>()?;
14844 let singleton_buffer =
14845 editor.read(cx).buffer().read(cx).as_singleton()?;
14846 if singleton_buffer == buffer {
14847 Some((editor, i))
14848 } else {
14849 None
14850 }
14851 })?;
14852 pane.update(cx, |pane, cx| {
14853 pane.activate_item(pane_item_index, true, true, window, cx)
14854 });
14855 Some(editor)
14856 })
14857 .flatten()
14858 .unwrap_or_else(|| {
14859 workspace.open_project_item::<Self>(
14860 pane.clone(),
14861 buffer,
14862 true,
14863 true,
14864 window,
14865 cx,
14866 )
14867 });
14868
14869 editor.update(cx, |editor, cx| {
14870 let autoscroll = match scroll_offset {
14871 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14872 None => Autoscroll::newest(),
14873 };
14874 let nav_history = editor.nav_history.take();
14875 editor.change_selections(Some(autoscroll), window, cx, |s| {
14876 s.select_ranges(ranges);
14877 });
14878 editor.nav_history = nav_history;
14879 });
14880 }
14881 })
14882 });
14883 }
14884
14885 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14886 let snapshot = self.buffer.read(cx).read(cx);
14887 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14888 Some(
14889 ranges
14890 .iter()
14891 .map(move |range| {
14892 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14893 })
14894 .collect(),
14895 )
14896 }
14897
14898 fn selection_replacement_ranges(
14899 &self,
14900 range: Range<OffsetUtf16>,
14901 cx: &mut App,
14902 ) -> Vec<Range<OffsetUtf16>> {
14903 let selections = self.selections.all::<OffsetUtf16>(cx);
14904 let newest_selection = selections
14905 .iter()
14906 .max_by_key(|selection| selection.id)
14907 .unwrap();
14908 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14909 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14910 let snapshot = self.buffer.read(cx).read(cx);
14911 selections
14912 .into_iter()
14913 .map(|mut selection| {
14914 selection.start.0 =
14915 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14916 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14917 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14918 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14919 })
14920 .collect()
14921 }
14922
14923 fn report_editor_event(
14924 &self,
14925 event_type: &'static str,
14926 file_extension: Option<String>,
14927 cx: &App,
14928 ) {
14929 if cfg!(any(test, feature = "test-support")) {
14930 return;
14931 }
14932
14933 let Some(project) = &self.project else { return };
14934
14935 // If None, we are in a file without an extension
14936 let file = self
14937 .buffer
14938 .read(cx)
14939 .as_singleton()
14940 .and_then(|b| b.read(cx).file());
14941 let file_extension = file_extension.or(file
14942 .as_ref()
14943 .and_then(|file| Path::new(file.file_name(cx)).extension())
14944 .and_then(|e| e.to_str())
14945 .map(|a| a.to_string()));
14946
14947 let vim_mode = cx
14948 .global::<SettingsStore>()
14949 .raw_user_settings()
14950 .get("vim_mode")
14951 == Some(&serde_json::Value::Bool(true));
14952
14953 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14954 let copilot_enabled = edit_predictions_provider
14955 == language::language_settings::EditPredictionProvider::Copilot;
14956 let copilot_enabled_for_language = self
14957 .buffer
14958 .read(cx)
14959 .settings_at(0, cx)
14960 .show_edit_predictions;
14961
14962 let project = project.read(cx);
14963 telemetry::event!(
14964 event_type,
14965 file_extension,
14966 vim_mode,
14967 copilot_enabled,
14968 copilot_enabled_for_language,
14969 edit_predictions_provider,
14970 is_via_ssh = project.is_via_ssh(),
14971 );
14972 }
14973
14974 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14975 /// with each line being an array of {text, highlight} objects.
14976 fn copy_highlight_json(
14977 &mut self,
14978 _: &CopyHighlightJson,
14979 window: &mut Window,
14980 cx: &mut Context<Self>,
14981 ) {
14982 #[derive(Serialize)]
14983 struct Chunk<'a> {
14984 text: String,
14985 highlight: Option<&'a str>,
14986 }
14987
14988 let snapshot = self.buffer.read(cx).snapshot(cx);
14989 let range = self
14990 .selected_text_range(false, window, cx)
14991 .and_then(|selection| {
14992 if selection.range.is_empty() {
14993 None
14994 } else {
14995 Some(selection.range)
14996 }
14997 })
14998 .unwrap_or_else(|| 0..snapshot.len());
14999
15000 let chunks = snapshot.chunks(range, true);
15001 let mut lines = Vec::new();
15002 let mut line: VecDeque<Chunk> = VecDeque::new();
15003
15004 let Some(style) = self.style.as_ref() else {
15005 return;
15006 };
15007
15008 for chunk in chunks {
15009 let highlight = chunk
15010 .syntax_highlight_id
15011 .and_then(|id| id.name(&style.syntax));
15012 let mut chunk_lines = chunk.text.split('\n').peekable();
15013 while let Some(text) = chunk_lines.next() {
15014 let mut merged_with_last_token = false;
15015 if let Some(last_token) = line.back_mut() {
15016 if last_token.highlight == highlight {
15017 last_token.text.push_str(text);
15018 merged_with_last_token = true;
15019 }
15020 }
15021
15022 if !merged_with_last_token {
15023 line.push_back(Chunk {
15024 text: text.into(),
15025 highlight,
15026 });
15027 }
15028
15029 if chunk_lines.peek().is_some() {
15030 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15031 line.pop_front();
15032 }
15033 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15034 line.pop_back();
15035 }
15036
15037 lines.push(mem::take(&mut line));
15038 }
15039 }
15040 }
15041
15042 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15043 return;
15044 };
15045 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15046 }
15047
15048 pub fn open_context_menu(
15049 &mut self,
15050 _: &OpenContextMenu,
15051 window: &mut Window,
15052 cx: &mut Context<Self>,
15053 ) {
15054 self.request_autoscroll(Autoscroll::newest(), cx);
15055 let position = self.selections.newest_display(cx).start;
15056 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15057 }
15058
15059 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15060 &self.inlay_hint_cache
15061 }
15062
15063 pub fn replay_insert_event(
15064 &mut self,
15065 text: &str,
15066 relative_utf16_range: Option<Range<isize>>,
15067 window: &mut Window,
15068 cx: &mut Context<Self>,
15069 ) {
15070 if !self.input_enabled {
15071 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15072 return;
15073 }
15074 if let Some(relative_utf16_range) = relative_utf16_range {
15075 let selections = self.selections.all::<OffsetUtf16>(cx);
15076 self.change_selections(None, window, cx, |s| {
15077 let new_ranges = selections.into_iter().map(|range| {
15078 let start = OffsetUtf16(
15079 range
15080 .head()
15081 .0
15082 .saturating_add_signed(relative_utf16_range.start),
15083 );
15084 let end = OffsetUtf16(
15085 range
15086 .head()
15087 .0
15088 .saturating_add_signed(relative_utf16_range.end),
15089 );
15090 start..end
15091 });
15092 s.select_ranges(new_ranges);
15093 });
15094 }
15095
15096 self.handle_input(text, window, cx);
15097 }
15098
15099 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15100 let Some(provider) = self.semantics_provider.as_ref() else {
15101 return false;
15102 };
15103
15104 let mut supports = false;
15105 self.buffer().update(cx, |this, cx| {
15106 this.for_each_buffer(|buffer| {
15107 supports |= provider.supports_inlay_hints(buffer, cx);
15108 });
15109 });
15110
15111 supports
15112 }
15113
15114 pub fn is_focused(&self, window: &Window) -> bool {
15115 self.focus_handle.is_focused(window)
15116 }
15117
15118 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15119 cx.emit(EditorEvent::Focused);
15120
15121 if let Some(descendant) = self
15122 .last_focused_descendant
15123 .take()
15124 .and_then(|descendant| descendant.upgrade())
15125 {
15126 window.focus(&descendant);
15127 } else {
15128 if let Some(blame) = self.blame.as_ref() {
15129 blame.update(cx, GitBlame::focus)
15130 }
15131
15132 self.blink_manager.update(cx, BlinkManager::enable);
15133 self.show_cursor_names(window, cx);
15134 self.buffer.update(cx, |buffer, cx| {
15135 buffer.finalize_last_transaction(cx);
15136 if self.leader_peer_id.is_none() {
15137 buffer.set_active_selections(
15138 &self.selections.disjoint_anchors(),
15139 self.selections.line_mode,
15140 self.cursor_shape,
15141 cx,
15142 );
15143 }
15144 });
15145 }
15146 }
15147
15148 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15149 cx.emit(EditorEvent::FocusedIn)
15150 }
15151
15152 fn handle_focus_out(
15153 &mut self,
15154 event: FocusOutEvent,
15155 _window: &mut Window,
15156 _cx: &mut Context<Self>,
15157 ) {
15158 if event.blurred != self.focus_handle {
15159 self.last_focused_descendant = Some(event.blurred);
15160 }
15161 }
15162
15163 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15164 self.blink_manager.update(cx, BlinkManager::disable);
15165 self.buffer
15166 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15167
15168 if let Some(blame) = self.blame.as_ref() {
15169 blame.update(cx, GitBlame::blur)
15170 }
15171 if !self.hover_state.focused(window, cx) {
15172 hide_hover(self, cx);
15173 }
15174 if !self
15175 .context_menu
15176 .borrow()
15177 .as_ref()
15178 .is_some_and(|context_menu| context_menu.focused(window, cx))
15179 {
15180 self.hide_context_menu(window, cx);
15181 }
15182 self.discard_inline_completion(false, cx);
15183 cx.emit(EditorEvent::Blurred);
15184 cx.notify();
15185 }
15186
15187 pub fn register_action<A: Action>(
15188 &mut self,
15189 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15190 ) -> Subscription {
15191 let id = self.next_editor_action_id.post_inc();
15192 let listener = Arc::new(listener);
15193 self.editor_actions.borrow_mut().insert(
15194 id,
15195 Box::new(move |window, _| {
15196 let listener = listener.clone();
15197 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15198 let action = action.downcast_ref().unwrap();
15199 if phase == DispatchPhase::Bubble {
15200 listener(action, window, cx)
15201 }
15202 })
15203 }),
15204 );
15205
15206 let editor_actions = self.editor_actions.clone();
15207 Subscription::new(move || {
15208 editor_actions.borrow_mut().remove(&id);
15209 })
15210 }
15211
15212 pub fn file_header_size(&self) -> u32 {
15213 FILE_HEADER_HEIGHT
15214 }
15215
15216 pub fn revert(
15217 &mut self,
15218 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15219 window: &mut Window,
15220 cx: &mut Context<Self>,
15221 ) {
15222 self.buffer().update(cx, |multi_buffer, cx| {
15223 for (buffer_id, changes) in revert_changes {
15224 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15225 buffer.update(cx, |buffer, cx| {
15226 buffer.edit(
15227 changes.into_iter().map(|(range, text)| {
15228 (range, text.to_string().map(Arc::<str>::from))
15229 }),
15230 None,
15231 cx,
15232 );
15233 });
15234 }
15235 }
15236 });
15237 self.change_selections(None, window, cx, |selections| selections.refresh());
15238 }
15239
15240 pub fn to_pixel_point(
15241 &self,
15242 source: multi_buffer::Anchor,
15243 editor_snapshot: &EditorSnapshot,
15244 window: &mut Window,
15245 ) -> Option<gpui::Point<Pixels>> {
15246 let source_point = source.to_display_point(editor_snapshot);
15247 self.display_to_pixel_point(source_point, editor_snapshot, window)
15248 }
15249
15250 pub fn display_to_pixel_point(
15251 &self,
15252 source: DisplayPoint,
15253 editor_snapshot: &EditorSnapshot,
15254 window: &mut Window,
15255 ) -> Option<gpui::Point<Pixels>> {
15256 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15257 let text_layout_details = self.text_layout_details(window);
15258 let scroll_top = text_layout_details
15259 .scroll_anchor
15260 .scroll_position(editor_snapshot)
15261 .y;
15262
15263 if source.row().as_f32() < scroll_top.floor() {
15264 return None;
15265 }
15266 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15267 let source_y = line_height * (source.row().as_f32() - scroll_top);
15268 Some(gpui::Point::new(source_x, source_y))
15269 }
15270
15271 pub fn has_visible_completions_menu(&self) -> bool {
15272 !self.edit_prediction_preview_is_active()
15273 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15274 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15275 })
15276 }
15277
15278 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15279 self.addons
15280 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15281 }
15282
15283 pub fn unregister_addon<T: Addon>(&mut self) {
15284 self.addons.remove(&std::any::TypeId::of::<T>());
15285 }
15286
15287 pub fn addon<T: Addon>(&self) -> Option<&T> {
15288 let type_id = std::any::TypeId::of::<T>();
15289 self.addons
15290 .get(&type_id)
15291 .and_then(|item| item.to_any().downcast_ref::<T>())
15292 }
15293
15294 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15295 let text_layout_details = self.text_layout_details(window);
15296 let style = &text_layout_details.editor_style;
15297 let font_id = window.text_system().resolve_font(&style.text.font());
15298 let font_size = style.text.font_size.to_pixels(window.rem_size());
15299 let line_height = style.text.line_height_in_pixels(window.rem_size());
15300 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15301
15302 gpui::Size::new(em_width, line_height)
15303 }
15304
15305 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15306 self.load_diff_task.clone()
15307 }
15308
15309 fn read_selections_from_db(
15310 &mut self,
15311 item_id: u64,
15312 workspace_id: WorkspaceId,
15313 window: &mut Window,
15314 cx: &mut Context<Editor>,
15315 ) {
15316 if !self.is_singleton(cx)
15317 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15318 {
15319 return;
15320 }
15321 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15322 return;
15323 };
15324 if selections.is_empty() {
15325 return;
15326 }
15327
15328 let snapshot = self.buffer.read(cx).snapshot(cx);
15329 self.change_selections(None, window, cx, |s| {
15330 s.select_ranges(selections.into_iter().map(|(start, end)| {
15331 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15332 }));
15333 });
15334 }
15335}
15336
15337fn insert_extra_newline_brackets(
15338 buffer: &MultiBufferSnapshot,
15339 range: Range<usize>,
15340 language: &language::LanguageScope,
15341) -> bool {
15342 let leading_whitespace_len = buffer
15343 .reversed_chars_at(range.start)
15344 .take_while(|c| c.is_whitespace() && *c != '\n')
15345 .map(|c| c.len_utf8())
15346 .sum::<usize>();
15347 let trailing_whitespace_len = buffer
15348 .chars_at(range.end)
15349 .take_while(|c| c.is_whitespace() && *c != '\n')
15350 .map(|c| c.len_utf8())
15351 .sum::<usize>();
15352 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15353
15354 language.brackets().any(|(pair, enabled)| {
15355 let pair_start = pair.start.trim_end();
15356 let pair_end = pair.end.trim_start();
15357
15358 enabled
15359 && pair.newline
15360 && buffer.contains_str_at(range.end, pair_end)
15361 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15362 })
15363}
15364
15365fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15366 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15367 [(buffer, range, _)] => (*buffer, range.clone()),
15368 _ => return false,
15369 };
15370 let pair = {
15371 let mut result: Option<BracketMatch> = None;
15372
15373 for pair in buffer
15374 .all_bracket_ranges(range.clone())
15375 .filter(move |pair| {
15376 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15377 })
15378 {
15379 let len = pair.close_range.end - pair.open_range.start;
15380
15381 if let Some(existing) = &result {
15382 let existing_len = existing.close_range.end - existing.open_range.start;
15383 if len > existing_len {
15384 continue;
15385 }
15386 }
15387
15388 result = Some(pair);
15389 }
15390
15391 result
15392 };
15393 let Some(pair) = pair else {
15394 return false;
15395 };
15396 pair.newline_only
15397 && buffer
15398 .chars_for_range(pair.open_range.end..range.start)
15399 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15400 .all(|c| c.is_whitespace() && c != '\n')
15401}
15402
15403fn get_uncommitted_diff_for_buffer(
15404 project: &Entity<Project>,
15405 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15406 buffer: Entity<MultiBuffer>,
15407 cx: &mut App,
15408) -> Task<()> {
15409 let mut tasks = Vec::new();
15410 project.update(cx, |project, cx| {
15411 for buffer in buffers {
15412 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15413 }
15414 });
15415 cx.spawn(|mut cx| async move {
15416 let diffs = futures::future::join_all(tasks).await;
15417 buffer
15418 .update(&mut cx, |buffer, cx| {
15419 for diff in diffs.into_iter().flatten() {
15420 buffer.add_diff(diff, cx);
15421 }
15422 })
15423 .ok();
15424 })
15425}
15426
15427fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15428 let tab_size = tab_size.get() as usize;
15429 let mut width = offset;
15430
15431 for ch in text.chars() {
15432 width += if ch == '\t' {
15433 tab_size - (width % tab_size)
15434 } else {
15435 1
15436 };
15437 }
15438
15439 width - offset
15440}
15441
15442#[cfg(test)]
15443mod tests {
15444 use super::*;
15445
15446 #[test]
15447 fn test_string_size_with_expanded_tabs() {
15448 let nz = |val| NonZeroU32::new(val).unwrap();
15449 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15450 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15451 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15452 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15453 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15454 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15455 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15456 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15457 }
15458}
15459
15460/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15461struct WordBreakingTokenizer<'a> {
15462 input: &'a str,
15463}
15464
15465impl<'a> WordBreakingTokenizer<'a> {
15466 fn new(input: &'a str) -> Self {
15467 Self { input }
15468 }
15469}
15470
15471fn is_char_ideographic(ch: char) -> bool {
15472 use unicode_script::Script::*;
15473 use unicode_script::UnicodeScript;
15474 matches!(ch.script(), Han | Tangut | Yi)
15475}
15476
15477fn is_grapheme_ideographic(text: &str) -> bool {
15478 text.chars().any(is_char_ideographic)
15479}
15480
15481fn is_grapheme_whitespace(text: &str) -> bool {
15482 text.chars().any(|x| x.is_whitespace())
15483}
15484
15485fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15486 text.chars().next().map_or(false, |ch| {
15487 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15488 })
15489}
15490
15491#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15492struct WordBreakToken<'a> {
15493 token: &'a str,
15494 grapheme_len: usize,
15495 is_whitespace: bool,
15496}
15497
15498impl<'a> Iterator for WordBreakingTokenizer<'a> {
15499 /// Yields a span, the count of graphemes in the token, and whether it was
15500 /// whitespace. Note that it also breaks at word boundaries.
15501 type Item = WordBreakToken<'a>;
15502
15503 fn next(&mut self) -> Option<Self::Item> {
15504 use unicode_segmentation::UnicodeSegmentation;
15505 if self.input.is_empty() {
15506 return None;
15507 }
15508
15509 let mut iter = self.input.graphemes(true).peekable();
15510 let mut offset = 0;
15511 let mut graphemes = 0;
15512 if let Some(first_grapheme) = iter.next() {
15513 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15514 offset += first_grapheme.len();
15515 graphemes += 1;
15516 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15517 if let Some(grapheme) = iter.peek().copied() {
15518 if should_stay_with_preceding_ideograph(grapheme) {
15519 offset += grapheme.len();
15520 graphemes += 1;
15521 }
15522 }
15523 } else {
15524 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15525 let mut next_word_bound = words.peek().copied();
15526 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15527 next_word_bound = words.next();
15528 }
15529 while let Some(grapheme) = iter.peek().copied() {
15530 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15531 break;
15532 };
15533 if is_grapheme_whitespace(grapheme) != is_whitespace {
15534 break;
15535 };
15536 offset += grapheme.len();
15537 graphemes += 1;
15538 iter.next();
15539 }
15540 }
15541 let token = &self.input[..offset];
15542 self.input = &self.input[offset..];
15543 if is_whitespace {
15544 Some(WordBreakToken {
15545 token: " ",
15546 grapheme_len: 1,
15547 is_whitespace: true,
15548 })
15549 } else {
15550 Some(WordBreakToken {
15551 token,
15552 grapheme_len: graphemes,
15553 is_whitespace: false,
15554 })
15555 }
15556 } else {
15557 None
15558 }
15559 }
15560}
15561
15562#[test]
15563fn test_word_breaking_tokenizer() {
15564 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15565 ("", &[]),
15566 (" ", &[(" ", 1, true)]),
15567 ("Ʒ", &[("Ʒ", 1, false)]),
15568 ("Ǽ", &[("Ǽ", 1, false)]),
15569 ("⋑", &[("⋑", 1, false)]),
15570 ("⋑⋑", &[("⋑⋑", 2, false)]),
15571 (
15572 "原理,进而",
15573 &[
15574 ("原", 1, false),
15575 ("理,", 2, false),
15576 ("进", 1, false),
15577 ("而", 1, false),
15578 ],
15579 ),
15580 (
15581 "hello world",
15582 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15583 ),
15584 (
15585 "hello, world",
15586 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15587 ),
15588 (
15589 " hello world",
15590 &[
15591 (" ", 1, true),
15592 ("hello", 5, false),
15593 (" ", 1, true),
15594 ("world", 5, false),
15595 ],
15596 ),
15597 (
15598 "这是什么 \n 钢笔",
15599 &[
15600 ("这", 1, false),
15601 ("是", 1, false),
15602 ("什", 1, false),
15603 ("么", 1, false),
15604 (" ", 1, true),
15605 ("钢", 1, false),
15606 ("笔", 1, false),
15607 ],
15608 ),
15609 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15610 ];
15611
15612 for (input, result) in tests {
15613 assert_eq!(
15614 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15615 result
15616 .iter()
15617 .copied()
15618 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15619 token,
15620 grapheme_len,
15621 is_whitespace,
15622 })
15623 .collect::<Vec<_>>()
15624 );
15625 }
15626}
15627
15628fn wrap_with_prefix(
15629 line_prefix: String,
15630 unwrapped_text: String,
15631 wrap_column: usize,
15632 tab_size: NonZeroU32,
15633) -> String {
15634 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15635 let mut wrapped_text = String::new();
15636 let mut current_line = line_prefix.clone();
15637
15638 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15639 let mut current_line_len = line_prefix_len;
15640 for WordBreakToken {
15641 token,
15642 grapheme_len,
15643 is_whitespace,
15644 } in tokenizer
15645 {
15646 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15647 wrapped_text.push_str(current_line.trim_end());
15648 wrapped_text.push('\n');
15649 current_line.truncate(line_prefix.len());
15650 current_line_len = line_prefix_len;
15651 if !is_whitespace {
15652 current_line.push_str(token);
15653 current_line_len += grapheme_len;
15654 }
15655 } else if !is_whitespace {
15656 current_line.push_str(token);
15657 current_line_len += grapheme_len;
15658 } else if current_line_len != line_prefix_len {
15659 current_line.push(' ');
15660 current_line_len += 1;
15661 }
15662 }
15663
15664 if !current_line.is_empty() {
15665 wrapped_text.push_str(¤t_line);
15666 }
15667 wrapped_text
15668}
15669
15670#[test]
15671fn test_wrap_with_prefix() {
15672 assert_eq!(
15673 wrap_with_prefix(
15674 "# ".to_string(),
15675 "abcdefg".to_string(),
15676 4,
15677 NonZeroU32::new(4).unwrap()
15678 ),
15679 "# abcdefg"
15680 );
15681 assert_eq!(
15682 wrap_with_prefix(
15683 "".to_string(),
15684 "\thello world".to_string(),
15685 8,
15686 NonZeroU32::new(4).unwrap()
15687 ),
15688 "hello\nworld"
15689 );
15690 assert_eq!(
15691 wrap_with_prefix(
15692 "// ".to_string(),
15693 "xx \nyy zz aa bb cc".to_string(),
15694 12,
15695 NonZeroU32::new(4).unwrap()
15696 ),
15697 "// xx yy zz\n// aa bb cc"
15698 );
15699 assert_eq!(
15700 wrap_with_prefix(
15701 String::new(),
15702 "这是什么 \n 钢笔".to_string(),
15703 3,
15704 NonZeroU32::new(4).unwrap()
15705 ),
15706 "这是什\n么 钢\n笔"
15707 );
15708}
15709
15710pub trait CollaborationHub {
15711 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15712 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15713 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15714}
15715
15716impl CollaborationHub for Entity<Project> {
15717 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15718 self.read(cx).collaborators()
15719 }
15720
15721 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15722 self.read(cx).user_store().read(cx).participant_indices()
15723 }
15724
15725 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15726 let this = self.read(cx);
15727 let user_ids = this.collaborators().values().map(|c| c.user_id);
15728 this.user_store().read_with(cx, |user_store, cx| {
15729 user_store.participant_names(user_ids, cx)
15730 })
15731 }
15732}
15733
15734pub trait SemanticsProvider {
15735 fn hover(
15736 &self,
15737 buffer: &Entity<Buffer>,
15738 position: text::Anchor,
15739 cx: &mut App,
15740 ) -> Option<Task<Vec<project::Hover>>>;
15741
15742 fn inlay_hints(
15743 &self,
15744 buffer_handle: Entity<Buffer>,
15745 range: Range<text::Anchor>,
15746 cx: &mut App,
15747 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15748
15749 fn resolve_inlay_hint(
15750 &self,
15751 hint: InlayHint,
15752 buffer_handle: Entity<Buffer>,
15753 server_id: LanguageServerId,
15754 cx: &mut App,
15755 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15756
15757 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15758
15759 fn document_highlights(
15760 &self,
15761 buffer: &Entity<Buffer>,
15762 position: text::Anchor,
15763 cx: &mut App,
15764 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15765
15766 fn definitions(
15767 &self,
15768 buffer: &Entity<Buffer>,
15769 position: text::Anchor,
15770 kind: GotoDefinitionKind,
15771 cx: &mut App,
15772 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15773
15774 fn range_for_rename(
15775 &self,
15776 buffer: &Entity<Buffer>,
15777 position: text::Anchor,
15778 cx: &mut App,
15779 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15780
15781 fn perform_rename(
15782 &self,
15783 buffer: &Entity<Buffer>,
15784 position: text::Anchor,
15785 new_name: String,
15786 cx: &mut App,
15787 ) -> Option<Task<Result<ProjectTransaction>>>;
15788}
15789
15790pub trait CompletionProvider {
15791 fn completions(
15792 &self,
15793 buffer: &Entity<Buffer>,
15794 buffer_position: text::Anchor,
15795 trigger: CompletionContext,
15796 window: &mut Window,
15797 cx: &mut Context<Editor>,
15798 ) -> Task<Result<Vec<Completion>>>;
15799
15800 fn resolve_completions(
15801 &self,
15802 buffer: Entity<Buffer>,
15803 completion_indices: Vec<usize>,
15804 completions: Rc<RefCell<Box<[Completion]>>>,
15805 cx: &mut Context<Editor>,
15806 ) -> Task<Result<bool>>;
15807
15808 fn apply_additional_edits_for_completion(
15809 &self,
15810 _buffer: Entity<Buffer>,
15811 _completions: Rc<RefCell<Box<[Completion]>>>,
15812 _completion_index: usize,
15813 _push_to_history: bool,
15814 _cx: &mut Context<Editor>,
15815 ) -> Task<Result<Option<language::Transaction>>> {
15816 Task::ready(Ok(None))
15817 }
15818
15819 fn is_completion_trigger(
15820 &self,
15821 buffer: &Entity<Buffer>,
15822 position: language::Anchor,
15823 text: &str,
15824 trigger_in_words: bool,
15825 cx: &mut Context<Editor>,
15826 ) -> bool;
15827
15828 fn sort_completions(&self) -> bool {
15829 true
15830 }
15831}
15832
15833pub trait CodeActionProvider {
15834 fn id(&self) -> Arc<str>;
15835
15836 fn code_actions(
15837 &self,
15838 buffer: &Entity<Buffer>,
15839 range: Range<text::Anchor>,
15840 window: &mut Window,
15841 cx: &mut App,
15842 ) -> Task<Result<Vec<CodeAction>>>;
15843
15844 fn apply_code_action(
15845 &self,
15846 buffer_handle: Entity<Buffer>,
15847 action: CodeAction,
15848 excerpt_id: ExcerptId,
15849 push_to_history: bool,
15850 window: &mut Window,
15851 cx: &mut App,
15852 ) -> Task<Result<ProjectTransaction>>;
15853}
15854
15855impl CodeActionProvider for Entity<Project> {
15856 fn id(&self) -> Arc<str> {
15857 "project".into()
15858 }
15859
15860 fn code_actions(
15861 &self,
15862 buffer: &Entity<Buffer>,
15863 range: Range<text::Anchor>,
15864 _window: &mut Window,
15865 cx: &mut App,
15866 ) -> Task<Result<Vec<CodeAction>>> {
15867 self.update(cx, |project, cx| {
15868 project.code_actions(buffer, range, None, cx)
15869 })
15870 }
15871
15872 fn apply_code_action(
15873 &self,
15874 buffer_handle: Entity<Buffer>,
15875 action: CodeAction,
15876 _excerpt_id: ExcerptId,
15877 push_to_history: bool,
15878 _window: &mut Window,
15879 cx: &mut App,
15880 ) -> Task<Result<ProjectTransaction>> {
15881 self.update(cx, |project, cx| {
15882 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15883 })
15884 }
15885}
15886
15887fn snippet_completions(
15888 project: &Project,
15889 buffer: &Entity<Buffer>,
15890 buffer_position: text::Anchor,
15891 cx: &mut App,
15892) -> Task<Result<Vec<Completion>>> {
15893 let language = buffer.read(cx).language_at(buffer_position);
15894 let language_name = language.as_ref().map(|language| language.lsp_id());
15895 let snippet_store = project.snippets().read(cx);
15896 let snippets = snippet_store.snippets_for(language_name, cx);
15897
15898 if snippets.is_empty() {
15899 return Task::ready(Ok(vec![]));
15900 }
15901 let snapshot = buffer.read(cx).text_snapshot();
15902 let chars: String = snapshot
15903 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15904 .collect();
15905
15906 let scope = language.map(|language| language.default_scope());
15907 let executor = cx.background_executor().clone();
15908
15909 cx.background_spawn(async move {
15910 let classifier = CharClassifier::new(scope).for_completion(true);
15911 let mut last_word = chars
15912 .chars()
15913 .take_while(|c| classifier.is_word(*c))
15914 .collect::<String>();
15915 last_word = last_word.chars().rev().collect();
15916
15917 if last_word.is_empty() {
15918 return Ok(vec![]);
15919 }
15920
15921 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15922 let to_lsp = |point: &text::Anchor| {
15923 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15924 point_to_lsp(end)
15925 };
15926 let lsp_end = to_lsp(&buffer_position);
15927
15928 let candidates = snippets
15929 .iter()
15930 .enumerate()
15931 .flat_map(|(ix, snippet)| {
15932 snippet
15933 .prefix
15934 .iter()
15935 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15936 })
15937 .collect::<Vec<StringMatchCandidate>>();
15938
15939 let mut matches = fuzzy::match_strings(
15940 &candidates,
15941 &last_word,
15942 last_word.chars().any(|c| c.is_uppercase()),
15943 100,
15944 &Default::default(),
15945 executor,
15946 )
15947 .await;
15948
15949 // Remove all candidates where the query's start does not match the start of any word in the candidate
15950 if let Some(query_start) = last_word.chars().next() {
15951 matches.retain(|string_match| {
15952 split_words(&string_match.string).any(|word| {
15953 // Check that the first codepoint of the word as lowercase matches the first
15954 // codepoint of the query as lowercase
15955 word.chars()
15956 .flat_map(|codepoint| codepoint.to_lowercase())
15957 .zip(query_start.to_lowercase())
15958 .all(|(word_cp, query_cp)| word_cp == query_cp)
15959 })
15960 });
15961 }
15962
15963 let matched_strings = matches
15964 .into_iter()
15965 .map(|m| m.string)
15966 .collect::<HashSet<_>>();
15967
15968 let result: Vec<Completion> = snippets
15969 .into_iter()
15970 .filter_map(|snippet| {
15971 let matching_prefix = snippet
15972 .prefix
15973 .iter()
15974 .find(|prefix| matched_strings.contains(*prefix))?;
15975 let start = as_offset - last_word.len();
15976 let start = snapshot.anchor_before(start);
15977 let range = start..buffer_position;
15978 let lsp_start = to_lsp(&start);
15979 let lsp_range = lsp::Range {
15980 start: lsp_start,
15981 end: lsp_end,
15982 };
15983 Some(Completion {
15984 old_range: range,
15985 new_text: snippet.body.clone(),
15986 resolved: false,
15987 label: CodeLabel {
15988 text: matching_prefix.clone(),
15989 runs: vec![],
15990 filter_range: 0..matching_prefix.len(),
15991 },
15992 server_id: LanguageServerId(usize::MAX),
15993 documentation: snippet
15994 .description
15995 .clone()
15996 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15997 lsp_completion: lsp::CompletionItem {
15998 label: snippet.prefix.first().unwrap().clone(),
15999 kind: Some(CompletionItemKind::SNIPPET),
16000 label_details: snippet.description.as_ref().map(|description| {
16001 lsp::CompletionItemLabelDetails {
16002 detail: Some(description.clone()),
16003 description: None,
16004 }
16005 }),
16006 insert_text_format: Some(InsertTextFormat::SNIPPET),
16007 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16008 lsp::InsertReplaceEdit {
16009 new_text: snippet.body.clone(),
16010 insert: lsp_range,
16011 replace: lsp_range,
16012 },
16013 )),
16014 filter_text: Some(snippet.body.clone()),
16015 sort_text: Some(char::MAX.to_string()),
16016 ..Default::default()
16017 },
16018 confirm: None,
16019 })
16020 })
16021 .collect();
16022
16023 Ok(result)
16024 })
16025}
16026
16027impl CompletionProvider for Entity<Project> {
16028 fn completions(
16029 &self,
16030 buffer: &Entity<Buffer>,
16031 buffer_position: text::Anchor,
16032 options: CompletionContext,
16033 _window: &mut Window,
16034 cx: &mut Context<Editor>,
16035 ) -> Task<Result<Vec<Completion>>> {
16036 self.update(cx, |project, cx| {
16037 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16038 let project_completions = project.completions(buffer, buffer_position, options, cx);
16039 cx.background_spawn(async move {
16040 let mut completions = project_completions.await?;
16041 let snippets_completions = snippets.await?;
16042 completions.extend(snippets_completions);
16043 Ok(completions)
16044 })
16045 })
16046 }
16047
16048 fn resolve_completions(
16049 &self,
16050 buffer: Entity<Buffer>,
16051 completion_indices: Vec<usize>,
16052 completions: Rc<RefCell<Box<[Completion]>>>,
16053 cx: &mut Context<Editor>,
16054 ) -> Task<Result<bool>> {
16055 self.update(cx, |project, cx| {
16056 project.lsp_store().update(cx, |lsp_store, cx| {
16057 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16058 })
16059 })
16060 }
16061
16062 fn apply_additional_edits_for_completion(
16063 &self,
16064 buffer: Entity<Buffer>,
16065 completions: Rc<RefCell<Box<[Completion]>>>,
16066 completion_index: usize,
16067 push_to_history: bool,
16068 cx: &mut Context<Editor>,
16069 ) -> Task<Result<Option<language::Transaction>>> {
16070 self.update(cx, |project, cx| {
16071 project.lsp_store().update(cx, |lsp_store, cx| {
16072 lsp_store.apply_additional_edits_for_completion(
16073 buffer,
16074 completions,
16075 completion_index,
16076 push_to_history,
16077 cx,
16078 )
16079 })
16080 })
16081 }
16082
16083 fn is_completion_trigger(
16084 &self,
16085 buffer: &Entity<Buffer>,
16086 position: language::Anchor,
16087 text: &str,
16088 trigger_in_words: bool,
16089 cx: &mut Context<Editor>,
16090 ) -> bool {
16091 let mut chars = text.chars();
16092 let char = if let Some(char) = chars.next() {
16093 char
16094 } else {
16095 return false;
16096 };
16097 if chars.next().is_some() {
16098 return false;
16099 }
16100
16101 let buffer = buffer.read(cx);
16102 let snapshot = buffer.snapshot();
16103 if !snapshot.settings_at(position, cx).show_completions_on_input {
16104 return false;
16105 }
16106 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16107 if trigger_in_words && classifier.is_word(char) {
16108 return true;
16109 }
16110
16111 buffer.completion_triggers().contains(text)
16112 }
16113}
16114
16115impl SemanticsProvider for Entity<Project> {
16116 fn hover(
16117 &self,
16118 buffer: &Entity<Buffer>,
16119 position: text::Anchor,
16120 cx: &mut App,
16121 ) -> Option<Task<Vec<project::Hover>>> {
16122 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16123 }
16124
16125 fn document_highlights(
16126 &self,
16127 buffer: &Entity<Buffer>,
16128 position: text::Anchor,
16129 cx: &mut App,
16130 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16131 Some(self.update(cx, |project, cx| {
16132 project.document_highlights(buffer, position, cx)
16133 }))
16134 }
16135
16136 fn definitions(
16137 &self,
16138 buffer: &Entity<Buffer>,
16139 position: text::Anchor,
16140 kind: GotoDefinitionKind,
16141 cx: &mut App,
16142 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16143 Some(self.update(cx, |project, cx| match kind {
16144 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16145 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16146 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16147 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16148 }))
16149 }
16150
16151 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16152 // TODO: make this work for remote projects
16153 self.update(cx, |this, cx| {
16154 buffer.update(cx, |buffer, cx| {
16155 this.any_language_server_supports_inlay_hints(buffer, cx)
16156 })
16157 })
16158 }
16159
16160 fn inlay_hints(
16161 &self,
16162 buffer_handle: Entity<Buffer>,
16163 range: Range<text::Anchor>,
16164 cx: &mut App,
16165 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16166 Some(self.update(cx, |project, cx| {
16167 project.inlay_hints(buffer_handle, range, cx)
16168 }))
16169 }
16170
16171 fn resolve_inlay_hint(
16172 &self,
16173 hint: InlayHint,
16174 buffer_handle: Entity<Buffer>,
16175 server_id: LanguageServerId,
16176 cx: &mut App,
16177 ) -> Option<Task<anyhow::Result<InlayHint>>> {
16178 Some(self.update(cx, |project, cx| {
16179 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16180 }))
16181 }
16182
16183 fn range_for_rename(
16184 &self,
16185 buffer: &Entity<Buffer>,
16186 position: text::Anchor,
16187 cx: &mut App,
16188 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16189 Some(self.update(cx, |project, cx| {
16190 let buffer = buffer.clone();
16191 let task = project.prepare_rename(buffer.clone(), position, cx);
16192 cx.spawn(|_, mut cx| async move {
16193 Ok(match task.await? {
16194 PrepareRenameResponse::Success(range) => Some(range),
16195 PrepareRenameResponse::InvalidPosition => None,
16196 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16197 // Fallback on using TreeSitter info to determine identifier range
16198 buffer.update(&mut cx, |buffer, _| {
16199 let snapshot = buffer.snapshot();
16200 let (range, kind) = snapshot.surrounding_word(position);
16201 if kind != Some(CharKind::Word) {
16202 return None;
16203 }
16204 Some(
16205 snapshot.anchor_before(range.start)
16206 ..snapshot.anchor_after(range.end),
16207 )
16208 })?
16209 }
16210 })
16211 })
16212 }))
16213 }
16214
16215 fn perform_rename(
16216 &self,
16217 buffer: &Entity<Buffer>,
16218 position: text::Anchor,
16219 new_name: String,
16220 cx: &mut App,
16221 ) -> Option<Task<Result<ProjectTransaction>>> {
16222 Some(self.update(cx, |project, cx| {
16223 project.perform_rename(buffer.clone(), position, new_name, cx)
16224 }))
16225 }
16226}
16227
16228fn inlay_hint_settings(
16229 location: Anchor,
16230 snapshot: &MultiBufferSnapshot,
16231 cx: &mut Context<Editor>,
16232) -> InlayHintSettings {
16233 let file = snapshot.file_at(location);
16234 let language = snapshot.language_at(location).map(|l| l.name());
16235 language_settings(language, file, cx).inlay_hints
16236}
16237
16238fn consume_contiguous_rows(
16239 contiguous_row_selections: &mut Vec<Selection<Point>>,
16240 selection: &Selection<Point>,
16241 display_map: &DisplaySnapshot,
16242 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16243) -> (MultiBufferRow, MultiBufferRow) {
16244 contiguous_row_selections.push(selection.clone());
16245 let start_row = MultiBufferRow(selection.start.row);
16246 let mut end_row = ending_row(selection, display_map);
16247
16248 while let Some(next_selection) = selections.peek() {
16249 if next_selection.start.row <= end_row.0 {
16250 end_row = ending_row(next_selection, display_map);
16251 contiguous_row_selections.push(selections.next().unwrap().clone());
16252 } else {
16253 break;
16254 }
16255 }
16256 (start_row, end_row)
16257}
16258
16259fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16260 if next_selection.end.column > 0 || next_selection.is_empty() {
16261 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16262 } else {
16263 MultiBufferRow(next_selection.end.row)
16264 }
16265}
16266
16267impl EditorSnapshot {
16268 pub fn remote_selections_in_range<'a>(
16269 &'a self,
16270 range: &'a Range<Anchor>,
16271 collaboration_hub: &dyn CollaborationHub,
16272 cx: &'a App,
16273 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16274 let participant_names = collaboration_hub.user_names(cx);
16275 let participant_indices = collaboration_hub.user_participant_indices(cx);
16276 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16277 let collaborators_by_replica_id = collaborators_by_peer_id
16278 .iter()
16279 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16280 .collect::<HashMap<_, _>>();
16281 self.buffer_snapshot
16282 .selections_in_range(range, false)
16283 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16284 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16285 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16286 let user_name = participant_names.get(&collaborator.user_id).cloned();
16287 Some(RemoteSelection {
16288 replica_id,
16289 selection,
16290 cursor_shape,
16291 line_mode,
16292 participant_index,
16293 peer_id: collaborator.peer_id,
16294 user_name,
16295 })
16296 })
16297 }
16298
16299 pub fn hunks_for_ranges(
16300 &self,
16301 ranges: impl Iterator<Item = Range<Point>>,
16302 ) -> Vec<MultiBufferDiffHunk> {
16303 let mut hunks = Vec::new();
16304 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16305 HashMap::default();
16306 for query_range in ranges {
16307 let query_rows =
16308 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16309 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16310 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16311 ) {
16312 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16313 // when the caret is just above or just below the deleted hunk.
16314 let allow_adjacent = hunk.status().is_deleted();
16315 let related_to_selection = if allow_adjacent {
16316 hunk.row_range.overlaps(&query_rows)
16317 || hunk.row_range.start == query_rows.end
16318 || hunk.row_range.end == query_rows.start
16319 } else {
16320 hunk.row_range.overlaps(&query_rows)
16321 };
16322 if related_to_selection {
16323 if !processed_buffer_rows
16324 .entry(hunk.buffer_id)
16325 .or_default()
16326 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16327 {
16328 continue;
16329 }
16330 hunks.push(hunk);
16331 }
16332 }
16333 }
16334
16335 hunks
16336 }
16337
16338 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16339 self.display_snapshot.buffer_snapshot.language_at(position)
16340 }
16341
16342 pub fn is_focused(&self) -> bool {
16343 self.is_focused
16344 }
16345
16346 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16347 self.placeholder_text.as_ref()
16348 }
16349
16350 pub fn scroll_position(&self) -> gpui::Point<f32> {
16351 self.scroll_anchor.scroll_position(&self.display_snapshot)
16352 }
16353
16354 fn gutter_dimensions(
16355 &self,
16356 font_id: FontId,
16357 font_size: Pixels,
16358 max_line_number_width: Pixels,
16359 cx: &App,
16360 ) -> Option<GutterDimensions> {
16361 if !self.show_gutter {
16362 return None;
16363 }
16364
16365 let descent = cx.text_system().descent(font_id, font_size);
16366 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16367 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16368
16369 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16370 matches!(
16371 ProjectSettings::get_global(cx).git.git_gutter,
16372 Some(GitGutterSetting::TrackedFiles)
16373 )
16374 });
16375 let gutter_settings = EditorSettings::get_global(cx).gutter;
16376 let show_line_numbers = self
16377 .show_line_numbers
16378 .unwrap_or(gutter_settings.line_numbers);
16379 let line_gutter_width = if show_line_numbers {
16380 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16381 let min_width_for_number_on_gutter = em_advance * 4.0;
16382 max_line_number_width.max(min_width_for_number_on_gutter)
16383 } else {
16384 0.0.into()
16385 };
16386
16387 let show_code_actions = self
16388 .show_code_actions
16389 .unwrap_or(gutter_settings.code_actions);
16390
16391 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16392
16393 let git_blame_entries_width =
16394 self.git_blame_gutter_max_author_length
16395 .map(|max_author_length| {
16396 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16397
16398 /// The number of characters to dedicate to gaps and margins.
16399 const SPACING_WIDTH: usize = 4;
16400
16401 let max_char_count = max_author_length
16402 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16403 + ::git::SHORT_SHA_LENGTH
16404 + MAX_RELATIVE_TIMESTAMP.len()
16405 + SPACING_WIDTH;
16406
16407 em_advance * max_char_count
16408 });
16409
16410 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16411 left_padding += if show_code_actions || show_runnables {
16412 em_width * 3.0
16413 } else if show_git_gutter && show_line_numbers {
16414 em_width * 2.0
16415 } else if show_git_gutter || show_line_numbers {
16416 em_width
16417 } else {
16418 px(0.)
16419 };
16420
16421 let right_padding = if gutter_settings.folds && show_line_numbers {
16422 em_width * 4.0
16423 } else if gutter_settings.folds {
16424 em_width * 3.0
16425 } else if show_line_numbers {
16426 em_width
16427 } else {
16428 px(0.)
16429 };
16430
16431 Some(GutterDimensions {
16432 left_padding,
16433 right_padding,
16434 width: line_gutter_width + left_padding + right_padding,
16435 margin: -descent,
16436 git_blame_entries_width,
16437 })
16438 }
16439
16440 pub fn render_crease_toggle(
16441 &self,
16442 buffer_row: MultiBufferRow,
16443 row_contains_cursor: bool,
16444 editor: Entity<Editor>,
16445 window: &mut Window,
16446 cx: &mut App,
16447 ) -> Option<AnyElement> {
16448 let folded = self.is_line_folded(buffer_row);
16449 let mut is_foldable = false;
16450
16451 if let Some(crease) = self
16452 .crease_snapshot
16453 .query_row(buffer_row, &self.buffer_snapshot)
16454 {
16455 is_foldable = true;
16456 match crease {
16457 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16458 if let Some(render_toggle) = render_toggle {
16459 let toggle_callback =
16460 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16461 if folded {
16462 editor.update(cx, |editor, cx| {
16463 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16464 });
16465 } else {
16466 editor.update(cx, |editor, cx| {
16467 editor.unfold_at(
16468 &crate::UnfoldAt { buffer_row },
16469 window,
16470 cx,
16471 )
16472 });
16473 }
16474 });
16475 return Some((render_toggle)(
16476 buffer_row,
16477 folded,
16478 toggle_callback,
16479 window,
16480 cx,
16481 ));
16482 }
16483 }
16484 }
16485 }
16486
16487 is_foldable |= self.starts_indent(buffer_row);
16488
16489 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16490 Some(
16491 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16492 .toggle_state(folded)
16493 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16494 if folded {
16495 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16496 } else {
16497 this.fold_at(&FoldAt { buffer_row }, window, cx);
16498 }
16499 }))
16500 .into_any_element(),
16501 )
16502 } else {
16503 None
16504 }
16505 }
16506
16507 pub fn render_crease_trailer(
16508 &self,
16509 buffer_row: MultiBufferRow,
16510 window: &mut Window,
16511 cx: &mut App,
16512 ) -> Option<AnyElement> {
16513 let folded = self.is_line_folded(buffer_row);
16514 if let Crease::Inline { render_trailer, .. } = self
16515 .crease_snapshot
16516 .query_row(buffer_row, &self.buffer_snapshot)?
16517 {
16518 let render_trailer = render_trailer.as_ref()?;
16519 Some(render_trailer(buffer_row, folded, window, cx))
16520 } else {
16521 None
16522 }
16523 }
16524}
16525
16526impl Deref for EditorSnapshot {
16527 type Target = DisplaySnapshot;
16528
16529 fn deref(&self) -> &Self::Target {
16530 &self.display_snapshot
16531 }
16532}
16533
16534#[derive(Clone, Debug, PartialEq, Eq)]
16535pub enum EditorEvent {
16536 InputIgnored {
16537 text: Arc<str>,
16538 },
16539 InputHandled {
16540 utf16_range_to_replace: Option<Range<isize>>,
16541 text: Arc<str>,
16542 },
16543 ExcerptsAdded {
16544 buffer: Entity<Buffer>,
16545 predecessor: ExcerptId,
16546 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16547 },
16548 ExcerptsRemoved {
16549 ids: Vec<ExcerptId>,
16550 },
16551 BufferFoldToggled {
16552 ids: Vec<ExcerptId>,
16553 folded: bool,
16554 },
16555 ExcerptsEdited {
16556 ids: Vec<ExcerptId>,
16557 },
16558 ExcerptsExpanded {
16559 ids: Vec<ExcerptId>,
16560 },
16561 BufferEdited,
16562 Edited {
16563 transaction_id: clock::Lamport,
16564 },
16565 Reparsed(BufferId),
16566 Focused,
16567 FocusedIn,
16568 Blurred,
16569 DirtyChanged,
16570 Saved,
16571 TitleChanged,
16572 DiffBaseChanged,
16573 SelectionsChanged {
16574 local: bool,
16575 },
16576 ScrollPositionChanged {
16577 local: bool,
16578 autoscroll: bool,
16579 },
16580 Closed,
16581 TransactionUndone {
16582 transaction_id: clock::Lamport,
16583 },
16584 TransactionBegun {
16585 transaction_id: clock::Lamport,
16586 },
16587 Reloaded,
16588 CursorShapeChanged,
16589}
16590
16591impl EventEmitter<EditorEvent> for Editor {}
16592
16593impl Focusable for Editor {
16594 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16595 self.focus_handle.clone()
16596 }
16597}
16598
16599impl Render for Editor {
16600 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16601 let settings = ThemeSettings::get_global(cx);
16602
16603 let mut text_style = match self.mode {
16604 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16605 color: cx.theme().colors().editor_foreground,
16606 font_family: settings.ui_font.family.clone(),
16607 font_features: settings.ui_font.features.clone(),
16608 font_fallbacks: settings.ui_font.fallbacks.clone(),
16609 font_size: rems(0.875).into(),
16610 font_weight: settings.ui_font.weight,
16611 line_height: relative(settings.buffer_line_height.value()),
16612 ..Default::default()
16613 },
16614 EditorMode::Full => TextStyle {
16615 color: cx.theme().colors().editor_foreground,
16616 font_family: settings.buffer_font.family.clone(),
16617 font_features: settings.buffer_font.features.clone(),
16618 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16619 font_size: settings.buffer_font_size(cx).into(),
16620 font_weight: settings.buffer_font.weight,
16621 line_height: relative(settings.buffer_line_height.value()),
16622 ..Default::default()
16623 },
16624 };
16625 if let Some(text_style_refinement) = &self.text_style_refinement {
16626 text_style.refine(text_style_refinement)
16627 }
16628
16629 let background = match self.mode {
16630 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16631 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16632 EditorMode::Full => cx.theme().colors().editor_background,
16633 };
16634
16635 EditorElement::new(
16636 &cx.entity(),
16637 EditorStyle {
16638 background,
16639 local_player: cx.theme().players().local(),
16640 text: text_style,
16641 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16642 syntax: cx.theme().syntax().clone(),
16643 status: cx.theme().status().clone(),
16644 inlay_hints_style: make_inlay_hints_style(cx),
16645 inline_completion_styles: make_suggestion_styles(cx),
16646 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16647 },
16648 )
16649 }
16650}
16651
16652impl EntityInputHandler for Editor {
16653 fn text_for_range(
16654 &mut self,
16655 range_utf16: Range<usize>,
16656 adjusted_range: &mut Option<Range<usize>>,
16657 _: &mut Window,
16658 cx: &mut Context<Self>,
16659 ) -> Option<String> {
16660 let snapshot = self.buffer.read(cx).read(cx);
16661 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16662 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16663 if (start.0..end.0) != range_utf16 {
16664 adjusted_range.replace(start.0..end.0);
16665 }
16666 Some(snapshot.text_for_range(start..end).collect())
16667 }
16668
16669 fn selected_text_range(
16670 &mut self,
16671 ignore_disabled_input: bool,
16672 _: &mut Window,
16673 cx: &mut Context<Self>,
16674 ) -> Option<UTF16Selection> {
16675 // Prevent the IME menu from appearing when holding down an alphabetic key
16676 // while input is disabled.
16677 if !ignore_disabled_input && !self.input_enabled {
16678 return None;
16679 }
16680
16681 let selection = self.selections.newest::<OffsetUtf16>(cx);
16682 let range = selection.range();
16683
16684 Some(UTF16Selection {
16685 range: range.start.0..range.end.0,
16686 reversed: selection.reversed,
16687 })
16688 }
16689
16690 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16691 let snapshot = self.buffer.read(cx).read(cx);
16692 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16693 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16694 }
16695
16696 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16697 self.clear_highlights::<InputComposition>(cx);
16698 self.ime_transaction.take();
16699 }
16700
16701 fn replace_text_in_range(
16702 &mut self,
16703 range_utf16: Option<Range<usize>>,
16704 text: &str,
16705 window: &mut Window,
16706 cx: &mut Context<Self>,
16707 ) {
16708 if !self.input_enabled {
16709 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16710 return;
16711 }
16712
16713 self.transact(window, cx, |this, window, cx| {
16714 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16715 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16716 Some(this.selection_replacement_ranges(range_utf16, cx))
16717 } else {
16718 this.marked_text_ranges(cx)
16719 };
16720
16721 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16722 let newest_selection_id = this.selections.newest_anchor().id;
16723 this.selections
16724 .all::<OffsetUtf16>(cx)
16725 .iter()
16726 .zip(ranges_to_replace.iter())
16727 .find_map(|(selection, range)| {
16728 if selection.id == newest_selection_id {
16729 Some(
16730 (range.start.0 as isize - selection.head().0 as isize)
16731 ..(range.end.0 as isize - selection.head().0 as isize),
16732 )
16733 } else {
16734 None
16735 }
16736 })
16737 });
16738
16739 cx.emit(EditorEvent::InputHandled {
16740 utf16_range_to_replace: range_to_replace,
16741 text: text.into(),
16742 });
16743
16744 if let Some(new_selected_ranges) = new_selected_ranges {
16745 this.change_selections(None, window, cx, |selections| {
16746 selections.select_ranges(new_selected_ranges)
16747 });
16748 this.backspace(&Default::default(), window, cx);
16749 }
16750
16751 this.handle_input(text, window, cx);
16752 });
16753
16754 if let Some(transaction) = self.ime_transaction {
16755 self.buffer.update(cx, |buffer, cx| {
16756 buffer.group_until_transaction(transaction, cx);
16757 });
16758 }
16759
16760 self.unmark_text(window, cx);
16761 }
16762
16763 fn replace_and_mark_text_in_range(
16764 &mut self,
16765 range_utf16: Option<Range<usize>>,
16766 text: &str,
16767 new_selected_range_utf16: Option<Range<usize>>,
16768 window: &mut Window,
16769 cx: &mut Context<Self>,
16770 ) {
16771 if !self.input_enabled {
16772 return;
16773 }
16774
16775 let transaction = self.transact(window, cx, |this, window, cx| {
16776 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16777 let snapshot = this.buffer.read(cx).read(cx);
16778 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16779 for marked_range in &mut marked_ranges {
16780 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16781 marked_range.start.0 += relative_range_utf16.start;
16782 marked_range.start =
16783 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16784 marked_range.end =
16785 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16786 }
16787 }
16788 Some(marked_ranges)
16789 } else if let Some(range_utf16) = range_utf16 {
16790 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16791 Some(this.selection_replacement_ranges(range_utf16, cx))
16792 } else {
16793 None
16794 };
16795
16796 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16797 let newest_selection_id = this.selections.newest_anchor().id;
16798 this.selections
16799 .all::<OffsetUtf16>(cx)
16800 .iter()
16801 .zip(ranges_to_replace.iter())
16802 .find_map(|(selection, range)| {
16803 if selection.id == newest_selection_id {
16804 Some(
16805 (range.start.0 as isize - selection.head().0 as isize)
16806 ..(range.end.0 as isize - selection.head().0 as isize),
16807 )
16808 } else {
16809 None
16810 }
16811 })
16812 });
16813
16814 cx.emit(EditorEvent::InputHandled {
16815 utf16_range_to_replace: range_to_replace,
16816 text: text.into(),
16817 });
16818
16819 if let Some(ranges) = ranges_to_replace {
16820 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16821 }
16822
16823 let marked_ranges = {
16824 let snapshot = this.buffer.read(cx).read(cx);
16825 this.selections
16826 .disjoint_anchors()
16827 .iter()
16828 .map(|selection| {
16829 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16830 })
16831 .collect::<Vec<_>>()
16832 };
16833
16834 if text.is_empty() {
16835 this.unmark_text(window, cx);
16836 } else {
16837 this.highlight_text::<InputComposition>(
16838 marked_ranges.clone(),
16839 HighlightStyle {
16840 underline: Some(UnderlineStyle {
16841 thickness: px(1.),
16842 color: None,
16843 wavy: false,
16844 }),
16845 ..Default::default()
16846 },
16847 cx,
16848 );
16849 }
16850
16851 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16852 let use_autoclose = this.use_autoclose;
16853 let use_auto_surround = this.use_auto_surround;
16854 this.set_use_autoclose(false);
16855 this.set_use_auto_surround(false);
16856 this.handle_input(text, window, cx);
16857 this.set_use_autoclose(use_autoclose);
16858 this.set_use_auto_surround(use_auto_surround);
16859
16860 if let Some(new_selected_range) = new_selected_range_utf16 {
16861 let snapshot = this.buffer.read(cx).read(cx);
16862 let new_selected_ranges = marked_ranges
16863 .into_iter()
16864 .map(|marked_range| {
16865 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16866 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16867 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16868 snapshot.clip_offset_utf16(new_start, Bias::Left)
16869 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16870 })
16871 .collect::<Vec<_>>();
16872
16873 drop(snapshot);
16874 this.change_selections(None, window, cx, |selections| {
16875 selections.select_ranges(new_selected_ranges)
16876 });
16877 }
16878 });
16879
16880 self.ime_transaction = self.ime_transaction.or(transaction);
16881 if let Some(transaction) = self.ime_transaction {
16882 self.buffer.update(cx, |buffer, cx| {
16883 buffer.group_until_transaction(transaction, cx);
16884 });
16885 }
16886
16887 if self.text_highlights::<InputComposition>(cx).is_none() {
16888 self.ime_transaction.take();
16889 }
16890 }
16891
16892 fn bounds_for_range(
16893 &mut self,
16894 range_utf16: Range<usize>,
16895 element_bounds: gpui::Bounds<Pixels>,
16896 window: &mut Window,
16897 cx: &mut Context<Self>,
16898 ) -> Option<gpui::Bounds<Pixels>> {
16899 let text_layout_details = self.text_layout_details(window);
16900 let gpui::Size {
16901 width: em_width,
16902 height: line_height,
16903 } = self.character_size(window);
16904
16905 let snapshot = self.snapshot(window, cx);
16906 let scroll_position = snapshot.scroll_position();
16907 let scroll_left = scroll_position.x * em_width;
16908
16909 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16910 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16911 + self.gutter_dimensions.width
16912 + self.gutter_dimensions.margin;
16913 let y = line_height * (start.row().as_f32() - scroll_position.y);
16914
16915 Some(Bounds {
16916 origin: element_bounds.origin + point(x, y),
16917 size: size(em_width, line_height),
16918 })
16919 }
16920
16921 fn character_index_for_point(
16922 &mut self,
16923 point: gpui::Point<Pixels>,
16924 _window: &mut Window,
16925 _cx: &mut Context<Self>,
16926 ) -> Option<usize> {
16927 let position_map = self.last_position_map.as_ref()?;
16928 if !position_map.text_hitbox.contains(&point) {
16929 return None;
16930 }
16931 let display_point = position_map.point_for_position(point).previous_valid;
16932 let anchor = position_map
16933 .snapshot
16934 .display_point_to_anchor(display_point, Bias::Left);
16935 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16936 Some(utf16_offset.0)
16937 }
16938}
16939
16940trait SelectionExt {
16941 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16942 fn spanned_rows(
16943 &self,
16944 include_end_if_at_line_start: bool,
16945 map: &DisplaySnapshot,
16946 ) -> Range<MultiBufferRow>;
16947}
16948
16949impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16950 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16951 let start = self
16952 .start
16953 .to_point(&map.buffer_snapshot)
16954 .to_display_point(map);
16955 let end = self
16956 .end
16957 .to_point(&map.buffer_snapshot)
16958 .to_display_point(map);
16959 if self.reversed {
16960 end..start
16961 } else {
16962 start..end
16963 }
16964 }
16965
16966 fn spanned_rows(
16967 &self,
16968 include_end_if_at_line_start: bool,
16969 map: &DisplaySnapshot,
16970 ) -> Range<MultiBufferRow> {
16971 let start = self.start.to_point(&map.buffer_snapshot);
16972 let mut end = self.end.to_point(&map.buffer_snapshot);
16973 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16974 end.row -= 1;
16975 }
16976
16977 let buffer_start = map.prev_line_boundary(start).0;
16978 let buffer_end = map.next_line_boundary(end).0;
16979 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16980 }
16981}
16982
16983impl<T: InvalidationRegion> InvalidationStack<T> {
16984 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16985 where
16986 S: Clone + ToOffset,
16987 {
16988 while let Some(region) = self.last() {
16989 let all_selections_inside_invalidation_ranges =
16990 if selections.len() == region.ranges().len() {
16991 selections
16992 .iter()
16993 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16994 .all(|(selection, invalidation_range)| {
16995 let head = selection.head().to_offset(buffer);
16996 invalidation_range.start <= head && invalidation_range.end >= head
16997 })
16998 } else {
16999 false
17000 };
17001
17002 if all_selections_inside_invalidation_ranges {
17003 break;
17004 } else {
17005 self.pop();
17006 }
17007 }
17008 }
17009}
17010
17011impl<T> Default for InvalidationStack<T> {
17012 fn default() -> Self {
17013 Self(Default::default())
17014 }
17015}
17016
17017impl<T> Deref for InvalidationStack<T> {
17018 type Target = Vec<T>;
17019
17020 fn deref(&self) -> &Self::Target {
17021 &self.0
17022 }
17023}
17024
17025impl<T> DerefMut for InvalidationStack<T> {
17026 fn deref_mut(&mut self) -> &mut Self::Target {
17027 &mut self.0
17028 }
17029}
17030
17031impl InvalidationRegion for SnippetState {
17032 fn ranges(&self) -> &[Range<Anchor>] {
17033 &self.ranges[self.active_index]
17034 }
17035}
17036
17037pub fn diagnostic_block_renderer(
17038 diagnostic: Diagnostic,
17039 max_message_rows: Option<u8>,
17040 allow_closing: bool,
17041 _is_valid: bool,
17042) -> RenderBlock {
17043 let (text_without_backticks, code_ranges) =
17044 highlight_diagnostic_message(&diagnostic, max_message_rows);
17045
17046 Arc::new(move |cx: &mut BlockContext| {
17047 let group_id: SharedString = cx.block_id.to_string().into();
17048
17049 let mut text_style = cx.window.text_style().clone();
17050 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17051 let theme_settings = ThemeSettings::get_global(cx);
17052 text_style.font_family = theme_settings.buffer_font.family.clone();
17053 text_style.font_style = theme_settings.buffer_font.style;
17054 text_style.font_features = theme_settings.buffer_font.features.clone();
17055 text_style.font_weight = theme_settings.buffer_font.weight;
17056
17057 let multi_line_diagnostic = diagnostic.message.contains('\n');
17058
17059 let buttons = |diagnostic: &Diagnostic| {
17060 if multi_line_diagnostic {
17061 v_flex()
17062 } else {
17063 h_flex()
17064 }
17065 .when(allow_closing, |div| {
17066 div.children(diagnostic.is_primary.then(|| {
17067 IconButton::new("close-block", IconName::XCircle)
17068 .icon_color(Color::Muted)
17069 .size(ButtonSize::Compact)
17070 .style(ButtonStyle::Transparent)
17071 .visible_on_hover(group_id.clone())
17072 .on_click(move |_click, window, cx| {
17073 window.dispatch_action(Box::new(Cancel), cx)
17074 })
17075 .tooltip(|window, cx| {
17076 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17077 })
17078 }))
17079 })
17080 .child(
17081 IconButton::new("copy-block", IconName::Copy)
17082 .icon_color(Color::Muted)
17083 .size(ButtonSize::Compact)
17084 .style(ButtonStyle::Transparent)
17085 .visible_on_hover(group_id.clone())
17086 .on_click({
17087 let message = diagnostic.message.clone();
17088 move |_click, _, cx| {
17089 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17090 }
17091 })
17092 .tooltip(Tooltip::text("Copy diagnostic message")),
17093 )
17094 };
17095
17096 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17097 AvailableSpace::min_size(),
17098 cx.window,
17099 cx.app,
17100 );
17101
17102 h_flex()
17103 .id(cx.block_id)
17104 .group(group_id.clone())
17105 .relative()
17106 .size_full()
17107 .block_mouse_down()
17108 .pl(cx.gutter_dimensions.width)
17109 .w(cx.max_width - cx.gutter_dimensions.full_width())
17110 .child(
17111 div()
17112 .flex()
17113 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17114 .flex_shrink(),
17115 )
17116 .child(buttons(&diagnostic))
17117 .child(div().flex().flex_shrink_0().child(
17118 StyledText::new(text_without_backticks.clone()).with_highlights(
17119 &text_style,
17120 code_ranges.iter().map(|range| {
17121 (
17122 range.clone(),
17123 HighlightStyle {
17124 font_weight: Some(FontWeight::BOLD),
17125 ..Default::default()
17126 },
17127 )
17128 }),
17129 ),
17130 ))
17131 .into_any_element()
17132 })
17133}
17134
17135fn inline_completion_edit_text(
17136 current_snapshot: &BufferSnapshot,
17137 edits: &[(Range<Anchor>, String)],
17138 edit_preview: &EditPreview,
17139 include_deletions: bool,
17140 cx: &App,
17141) -> HighlightedText {
17142 let edits = edits
17143 .iter()
17144 .map(|(anchor, text)| {
17145 (
17146 anchor.start.text_anchor..anchor.end.text_anchor,
17147 text.clone(),
17148 )
17149 })
17150 .collect::<Vec<_>>();
17151
17152 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17153}
17154
17155pub fn highlight_diagnostic_message(
17156 diagnostic: &Diagnostic,
17157 mut max_message_rows: Option<u8>,
17158) -> (SharedString, Vec<Range<usize>>) {
17159 let mut text_without_backticks = String::new();
17160 let mut code_ranges = Vec::new();
17161
17162 if let Some(source) = &diagnostic.source {
17163 text_without_backticks.push_str(source);
17164 code_ranges.push(0..source.len());
17165 text_without_backticks.push_str(": ");
17166 }
17167
17168 let mut prev_offset = 0;
17169 let mut in_code_block = false;
17170 let has_row_limit = max_message_rows.is_some();
17171 let mut newline_indices = diagnostic
17172 .message
17173 .match_indices('\n')
17174 .filter(|_| has_row_limit)
17175 .map(|(ix, _)| ix)
17176 .fuse()
17177 .peekable();
17178
17179 for (quote_ix, _) in diagnostic
17180 .message
17181 .match_indices('`')
17182 .chain([(diagnostic.message.len(), "")])
17183 {
17184 let mut first_newline_ix = None;
17185 let mut last_newline_ix = None;
17186 while let Some(newline_ix) = newline_indices.peek() {
17187 if *newline_ix < quote_ix {
17188 if first_newline_ix.is_none() {
17189 first_newline_ix = Some(*newline_ix);
17190 }
17191 last_newline_ix = Some(*newline_ix);
17192
17193 if let Some(rows_left) = &mut max_message_rows {
17194 if *rows_left == 0 {
17195 break;
17196 } else {
17197 *rows_left -= 1;
17198 }
17199 }
17200 let _ = newline_indices.next();
17201 } else {
17202 break;
17203 }
17204 }
17205 let prev_len = text_without_backticks.len();
17206 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17207 text_without_backticks.push_str(new_text);
17208 if in_code_block {
17209 code_ranges.push(prev_len..text_without_backticks.len());
17210 }
17211 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17212 in_code_block = !in_code_block;
17213 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17214 text_without_backticks.push_str("...");
17215 break;
17216 }
17217 }
17218
17219 (text_without_backticks.into(), code_ranges)
17220}
17221
17222fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17223 match severity {
17224 DiagnosticSeverity::ERROR => colors.error,
17225 DiagnosticSeverity::WARNING => colors.warning,
17226 DiagnosticSeverity::INFORMATION => colors.info,
17227 DiagnosticSeverity::HINT => colors.info,
17228 _ => colors.ignored,
17229 }
17230}
17231
17232pub fn styled_runs_for_code_label<'a>(
17233 label: &'a CodeLabel,
17234 syntax_theme: &'a theme::SyntaxTheme,
17235) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17236 let fade_out = HighlightStyle {
17237 fade_out: Some(0.35),
17238 ..Default::default()
17239 };
17240
17241 let mut prev_end = label.filter_range.end;
17242 label
17243 .runs
17244 .iter()
17245 .enumerate()
17246 .flat_map(move |(ix, (range, highlight_id))| {
17247 let style = if let Some(style) = highlight_id.style(syntax_theme) {
17248 style
17249 } else {
17250 return Default::default();
17251 };
17252 let mut muted_style = style;
17253 muted_style.highlight(fade_out);
17254
17255 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17256 if range.start >= label.filter_range.end {
17257 if range.start > prev_end {
17258 runs.push((prev_end..range.start, fade_out));
17259 }
17260 runs.push((range.clone(), muted_style));
17261 } else if range.end <= label.filter_range.end {
17262 runs.push((range.clone(), style));
17263 } else {
17264 runs.push((range.start..label.filter_range.end, style));
17265 runs.push((label.filter_range.end..range.end, muted_style));
17266 }
17267 prev_end = cmp::max(prev_end, range.end);
17268
17269 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17270 runs.push((prev_end..label.text.len(), fade_out));
17271 }
17272
17273 runs
17274 })
17275}
17276
17277pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17278 let mut prev_index = 0;
17279 let mut prev_codepoint: Option<char> = None;
17280 text.char_indices()
17281 .chain([(text.len(), '\0')])
17282 .filter_map(move |(index, codepoint)| {
17283 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17284 let is_boundary = index == text.len()
17285 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17286 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17287 if is_boundary {
17288 let chunk = &text[prev_index..index];
17289 prev_index = index;
17290 Some(chunk)
17291 } else {
17292 None
17293 }
17294 })
17295}
17296
17297pub trait RangeToAnchorExt: Sized {
17298 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17299
17300 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17301 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17302 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17303 }
17304}
17305
17306impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17307 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17308 let start_offset = self.start.to_offset(snapshot);
17309 let end_offset = self.end.to_offset(snapshot);
17310 if start_offset == end_offset {
17311 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17312 } else {
17313 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17314 }
17315 }
17316}
17317
17318pub trait RowExt {
17319 fn as_f32(&self) -> f32;
17320
17321 fn next_row(&self) -> Self;
17322
17323 fn previous_row(&self) -> Self;
17324
17325 fn minus(&self, other: Self) -> u32;
17326}
17327
17328impl RowExt for DisplayRow {
17329 fn as_f32(&self) -> f32 {
17330 self.0 as f32
17331 }
17332
17333 fn next_row(&self) -> Self {
17334 Self(self.0 + 1)
17335 }
17336
17337 fn previous_row(&self) -> Self {
17338 Self(self.0.saturating_sub(1))
17339 }
17340
17341 fn minus(&self, other: Self) -> u32 {
17342 self.0 - other.0
17343 }
17344}
17345
17346impl RowExt for MultiBufferRow {
17347 fn as_f32(&self) -> f32 {
17348 self.0 as f32
17349 }
17350
17351 fn next_row(&self) -> Self {
17352 Self(self.0 + 1)
17353 }
17354
17355 fn previous_row(&self) -> Self {
17356 Self(self.0.saturating_sub(1))
17357 }
17358
17359 fn minus(&self, other: Self) -> u32 {
17360 self.0 - other.0
17361 }
17362}
17363
17364trait RowRangeExt {
17365 type Row;
17366
17367 fn len(&self) -> usize;
17368
17369 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17370}
17371
17372impl RowRangeExt for Range<MultiBufferRow> {
17373 type Row = MultiBufferRow;
17374
17375 fn len(&self) -> usize {
17376 (self.end.0 - self.start.0) as usize
17377 }
17378
17379 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17380 (self.start.0..self.end.0).map(MultiBufferRow)
17381 }
17382}
17383
17384impl RowRangeExt for Range<DisplayRow> {
17385 type Row = DisplayRow;
17386
17387 fn len(&self) -> usize {
17388 (self.end.0 - self.start.0) as usize
17389 }
17390
17391 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17392 (self.start.0..self.end.0).map(DisplayRow)
17393 }
17394}
17395
17396/// If select range has more than one line, we
17397/// just point the cursor to range.start.
17398fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17399 if range.start.row == range.end.row {
17400 range
17401 } else {
17402 range.start..range.start
17403 }
17404}
17405pub struct KillRing(ClipboardItem);
17406impl Global for KillRing {}
17407
17408const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17409
17410fn all_edits_insertions_or_deletions(
17411 edits: &Vec<(Range<Anchor>, String)>,
17412 snapshot: &MultiBufferSnapshot,
17413) -> bool {
17414 let mut all_insertions = true;
17415 let mut all_deletions = true;
17416
17417 for (range, new_text) in edits.iter() {
17418 let range_is_empty = range.to_offset(&snapshot).is_empty();
17419 let text_is_empty = new_text.is_empty();
17420
17421 if range_is_empty != text_is_empty {
17422 if range_is_empty {
17423 all_deletions = false;
17424 } else {
17425 all_insertions = false;
17426 }
17427 } else {
17428 return false;
17429 }
17430
17431 if !all_insertions && !all_deletions {
17432 return false;
17433 }
17434 }
17435 all_insertions || all_deletions
17436}