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::{layout_line, 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::{status::FileStatus, 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, Edges, 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 smallvec::smallvec;
117use std::iter::Peekable;
118use task::{ResolvedTask, TaskTemplate, TaskVariables};
119
120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
121pub use lsp::CompletionContext;
122use lsp::{
123 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
124 LanguageServerId, LanguageServerName,
125};
126
127use language::BufferSnapshot;
128use movement::TextLayoutDetails;
129pub use multi_buffer::{
130 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
131 ToOffset, ToPoint,
132};
133use multi_buffer::{
134 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
135 ToOffsetUtf16,
136};
137use project::{
138 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
139 project_settings::{GitGutterSetting, ProjectSettings},
140 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
141 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
142};
143use rand::prelude::*;
144use rpc::{proto::*, ErrorExt};
145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
146use selections_collection::{
147 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
148};
149use serde::{Deserialize, Serialize};
150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
151use smallvec::SmallVec;
152use snippet::Snippet;
153use std::{
154 any::TypeId,
155 borrow::Cow,
156 cell::RefCell,
157 cmp::{self, Ordering, Reverse},
158 mem,
159 num::NonZeroU32,
160 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
161 path::{Path, PathBuf},
162 rc::Rc,
163 sync::Arc,
164 time::{Duration, Instant},
165};
166pub use sum_tree::Bias;
167use sum_tree::TreeMap;
168use text::{BufferId, OffsetUtf16, Rope};
169use theme::{
170 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
171 ThemeColors, ThemeSettings,
172};
173use ui::{
174 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
175 Tooltip,
176};
177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
178use workspace::{
179 item::{ItemHandle, PreviewTabsSettings},
180 ItemId, RestoreOnStartupBehavior,
181};
182use workspace::{
183 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
184 WorkspaceSettings,
185};
186use workspace::{
187 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
188};
189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
190
191use crate::hover_links::{find_url, find_url_from_range};
192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
193
194pub const FILE_HEADER_HEIGHT: u32 = 2;
195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
199const MAX_LINE_LEN: usize = 1024;
200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
203#[doc(hidden)]
204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
205
206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
208
209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
211
212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
213 alt: true,
214 shift: true,
215 control: false,
216 platform: false,
217 function: false,
218};
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum InlayId {
222 InlineCompletion(usize),
223 Hint(usize),
224}
225
226impl InlayId {
227 fn id(&self) -> usize {
228 match self {
229 Self::InlineCompletion(id) => *id,
230 Self::Hint(id) => *id,
231 }
232 }
233}
234
235enum DocumentHighlightRead {}
236enum DocumentHighlightWrite {}
237enum InputComposition {}
238enum SelectedTextHighlight {}
239
240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
241pub enum Navigated {
242 Yes,
243 No,
244}
245
246impl Navigated {
247 pub fn from_bool(yes: bool) -> Navigated {
248 if yes {
249 Navigated::Yes
250 } else {
251 Navigated::No
252 }
253 }
254}
255
256pub fn init_settings(cx: &mut App) {
257 EditorSettings::register(cx);
258}
259
260pub fn init(cx: &mut App) {
261 init_settings(cx);
262
263 workspace::register_project_item::<Editor>(cx);
264 workspace::FollowableViewRegistry::register::<Editor>(cx);
265 workspace::register_serializable_item::<Editor>(cx);
266
267 cx.observe_new(
268 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
269 workspace.register_action(Editor::new_file);
270 workspace.register_action(Editor::new_file_vertical);
271 workspace.register_action(Editor::new_file_horizontal);
272 workspace.register_action(Editor::cancel_language_server_work);
273 },
274 )
275 .detach();
276
277 cx.on_action(move |_: &workspace::NewFile, cx| {
278 let app_state = workspace::AppState::global(cx);
279 if let Some(app_state) = app_state.upgrade() {
280 workspace::open_new(
281 Default::default(),
282 app_state,
283 cx,
284 |workspace, window, cx| {
285 Editor::new_file(workspace, &Default::default(), window, cx)
286 },
287 )
288 .detach();
289 }
290 });
291 cx.on_action(move |_: &workspace::NewWindow, cx| {
292 let app_state = workspace::AppState::global(cx);
293 if let Some(app_state) = app_state.upgrade() {
294 workspace::open_new(
295 Default::default(),
296 app_state,
297 cx,
298 |workspace, window, cx| {
299 cx.activate(true);
300 Editor::new_file(workspace, &Default::default(), window, cx)
301 },
302 )
303 .detach();
304 }
305 });
306}
307
308pub struct SearchWithinRange;
309
310trait InvalidationRegion {
311 fn ranges(&self) -> &[Range<Anchor>];
312}
313
314#[derive(Clone, Debug, PartialEq)]
315pub enum SelectPhase {
316 Begin {
317 position: DisplayPoint,
318 add: bool,
319 click_count: usize,
320 },
321 BeginColumnar {
322 position: DisplayPoint,
323 reset: bool,
324 goal_column: u32,
325 },
326 Extend {
327 position: DisplayPoint,
328 click_count: usize,
329 },
330 Update {
331 position: DisplayPoint,
332 goal_column: u32,
333 scroll_delta: gpui::Point<f32>,
334 },
335 End,
336}
337
338#[derive(Clone, Debug)]
339pub enum SelectMode {
340 Character,
341 Word(Range<Anchor>),
342 Line(Range<Anchor>),
343 All,
344}
345
346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
347pub enum EditorMode {
348 SingleLine { auto_width: bool },
349 AutoHeight { max_lines: usize },
350 Full,
351}
352
353#[derive(Copy, Clone, Debug)]
354pub enum SoftWrap {
355 /// Prefer not to wrap at all.
356 ///
357 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
358 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
359 GitDiff,
360 /// Prefer a single line generally, unless an overly long line is encountered.
361 None,
362 /// Soft wrap lines that exceed the editor width.
363 EditorWidth,
364 /// Soft wrap lines at the preferred line length.
365 Column(u32),
366 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
367 Bounded(u32),
368}
369
370#[derive(Clone)]
371pub struct EditorStyle {
372 pub background: Hsla,
373 pub local_player: PlayerColor,
374 pub text: TextStyle,
375 pub scrollbar_width: Pixels,
376 pub syntax: Arc<SyntaxTheme>,
377 pub status: StatusColors,
378 pub inlay_hints_style: HighlightStyle,
379 pub inline_completion_styles: InlineCompletionStyles,
380 pub unnecessary_code_fade: f32,
381}
382
383impl Default for EditorStyle {
384 fn default() -> Self {
385 Self {
386 background: Hsla::default(),
387 local_player: PlayerColor::default(),
388 text: TextStyle::default(),
389 scrollbar_width: Pixels::default(),
390 syntax: Default::default(),
391 // HACK: Status colors don't have a real default.
392 // We should look into removing the status colors from the editor
393 // style and retrieve them directly from the theme.
394 status: StatusColors::dark(),
395 inlay_hints_style: HighlightStyle::default(),
396 inline_completion_styles: InlineCompletionStyles {
397 insertion: HighlightStyle::default(),
398 whitespace: HighlightStyle::default(),
399 },
400 unnecessary_code_fade: Default::default(),
401 }
402 }
403}
404
405pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
406 let show_background = language_settings::language_settings(None, None, cx)
407 .inlay_hints
408 .show_background;
409
410 HighlightStyle {
411 color: Some(cx.theme().status().hint),
412 background_color: show_background.then(|| cx.theme().status().hint_background),
413 ..HighlightStyle::default()
414 }
415}
416
417pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
418 InlineCompletionStyles {
419 insertion: HighlightStyle {
420 color: Some(cx.theme().status().predictive),
421 ..HighlightStyle::default()
422 },
423 whitespace: HighlightStyle {
424 background_color: Some(cx.theme().status().created_background),
425 ..HighlightStyle::default()
426 },
427 }
428}
429
430type CompletionId = usize;
431
432pub(crate) enum EditDisplayMode {
433 TabAccept,
434 DiffPopover,
435 Inline,
436}
437
438enum InlineCompletion {
439 Edit {
440 edits: Vec<(Range<Anchor>, String)>,
441 edit_preview: Option<EditPreview>,
442 display_mode: EditDisplayMode,
443 snapshot: BufferSnapshot,
444 },
445 Move {
446 target: Anchor,
447 snapshot: BufferSnapshot,
448 },
449}
450
451struct InlineCompletionState {
452 inlay_ids: Vec<InlayId>,
453 completion: InlineCompletion,
454 completion_id: Option<SharedString>,
455 invalidation_range: Range<Anchor>,
456}
457
458enum EditPredictionSettings {
459 Disabled,
460 Enabled {
461 show_in_menu: bool,
462 preview_requires_modifier: bool,
463 },
464}
465
466enum InlineCompletionHighlight {}
467
468#[derive(Debug, Clone)]
469struct InlineDiagnostic {
470 message: SharedString,
471 group_id: usize,
472 is_primary: bool,
473 start: Point,
474 severity: DiagnosticSeverity,
475}
476
477pub enum MenuInlineCompletionsPolicy {
478 Never,
479 ByProvider,
480}
481
482pub enum EditPredictionPreview {
483 /// Modifier is not pressed
484 Inactive,
485 /// Modifier pressed
486 Active {
487 previous_scroll_position: Option<ScrollAnchor>,
488 },
489}
490
491#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
492struct EditorActionId(usize);
493
494impl EditorActionId {
495 pub fn post_inc(&mut self) -> Self {
496 let answer = self.0;
497
498 *self = Self(answer + 1);
499
500 Self(answer)
501 }
502}
503
504// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
505// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
506
507type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
508type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
509
510#[derive(Default)]
511struct ScrollbarMarkerState {
512 scrollbar_size: Size<Pixels>,
513 dirty: bool,
514 markers: Arc<[PaintQuad]>,
515 pending_refresh: Option<Task<Result<()>>>,
516}
517
518impl ScrollbarMarkerState {
519 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
520 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
521 }
522}
523
524#[derive(Clone, Debug)]
525struct RunnableTasks {
526 templates: Vec<(TaskSourceKind, TaskTemplate)>,
527 offset: multi_buffer::Anchor,
528 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
529 column: u32,
530 // Values of all named captures, including those starting with '_'
531 extra_variables: HashMap<String, String>,
532 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
533 context_range: Range<BufferOffset>,
534}
535
536impl RunnableTasks {
537 fn resolve<'a>(
538 &'a self,
539 cx: &'a task::TaskContext,
540 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
541 self.templates.iter().filter_map(|(kind, template)| {
542 template
543 .resolve_task(&kind.to_id_base(), cx)
544 .map(|task| (kind.clone(), task))
545 })
546 }
547}
548
549#[derive(Clone)]
550struct ResolvedTasks {
551 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
552 position: Anchor,
553}
554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
555struct BufferOffset(usize);
556
557// Addons allow storing per-editor state in other crates (e.g. Vim)
558pub trait Addon: 'static {
559 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
560
561 fn render_buffer_header_controls(
562 &self,
563 _: &ExcerptInfo,
564 _: &Window,
565 _: &App,
566 ) -> Option<AnyElement> {
567 None
568 }
569
570 fn to_any(&self) -> &dyn std::any::Any;
571}
572
573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
574pub enum IsVimMode {
575 Yes,
576 No,
577}
578
579/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
580///
581/// See the [module level documentation](self) for more information.
582pub struct Editor {
583 focus_handle: FocusHandle,
584 last_focused_descendant: Option<WeakFocusHandle>,
585 /// The text buffer being edited
586 buffer: Entity<MultiBuffer>,
587 /// Map of how text in the buffer should be displayed.
588 /// Handles soft wraps, folds, fake inlay text insertions, etc.
589 pub display_map: Entity<DisplayMap>,
590 pub selections: SelectionsCollection,
591 pub scroll_manager: ScrollManager,
592 /// When inline assist editors are linked, they all render cursors because
593 /// typing enters text into each of them, even the ones that aren't focused.
594 pub(crate) show_cursor_when_unfocused: bool,
595 columnar_selection_tail: Option<Anchor>,
596 add_selections_state: Option<AddSelectionsState>,
597 select_next_state: Option<SelectNextState>,
598 select_prev_state: Option<SelectNextState>,
599 selection_history: SelectionHistory,
600 autoclose_regions: Vec<AutocloseRegion>,
601 snippet_stack: InvalidationStack<SnippetState>,
602 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
603 ime_transaction: Option<TransactionId>,
604 active_diagnostics: Option<ActiveDiagnosticGroup>,
605 show_inline_diagnostics: bool,
606 inline_diagnostics_update: Task<()>,
607 inline_diagnostics_enabled: bool,
608 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
609 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
610
611 // TODO: make this a access method
612 pub project: Option<Entity<Project>>,
613 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
614 completion_provider: Option<Box<dyn CompletionProvider>>,
615 collaboration_hub: Option<Box<dyn CollaborationHub>>,
616 blink_manager: Entity<BlinkManager>,
617 show_cursor_names: bool,
618 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
619 pub show_local_selections: bool,
620 mode: EditorMode,
621 show_breadcrumbs: bool,
622 show_gutter: bool,
623 show_scrollbars: bool,
624 show_line_numbers: Option<bool>,
625 use_relative_line_numbers: Option<bool>,
626 show_git_diff_gutter: Option<bool>,
627 show_code_actions: Option<bool>,
628 show_runnables: Option<bool>,
629 show_wrap_guides: Option<bool>,
630 show_indent_guides: Option<bool>,
631 placeholder_text: Option<Arc<str>>,
632 highlight_order: usize,
633 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
634 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
635 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
636 scrollbar_marker_state: ScrollbarMarkerState,
637 active_indent_guides_state: ActiveIndentGuidesState,
638 nav_history: Option<ItemNavHistory>,
639 context_menu: RefCell<Option<CodeContextMenu>>,
640 mouse_context_menu: Option<MouseContextMenu>,
641 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
642 signature_help_state: SignatureHelpState,
643 auto_signature_help: Option<bool>,
644 find_all_references_task_sources: Vec<Anchor>,
645 next_completion_id: CompletionId,
646 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
647 code_actions_task: Option<Task<Result<()>>>,
648 selection_highlight_task: Option<Task<()>>,
649 document_highlights_task: Option<Task<()>>,
650 linked_editing_range_task: Option<Task<Option<()>>>,
651 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
652 pending_rename: Option<RenameState>,
653 searchable: bool,
654 cursor_shape: CursorShape,
655 current_line_highlight: Option<CurrentLineHighlight>,
656 collapse_matches: bool,
657 autoindent_mode: Option<AutoindentMode>,
658 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
659 input_enabled: bool,
660 use_modal_editing: bool,
661 read_only: bool,
662 leader_peer_id: Option<PeerId>,
663 remote_id: Option<ViewId>,
664 hover_state: HoverState,
665 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
666 gutter_hovered: bool,
667 hovered_link_state: Option<HoveredLinkState>,
668 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
669 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
670 active_inline_completion: Option<InlineCompletionState>,
671 /// Used to prevent flickering as the user types while the menu is open
672 stale_inline_completion_in_menu: Option<InlineCompletionState>,
673 edit_prediction_settings: EditPredictionSettings,
674 inline_completions_hidden_for_vim_mode: bool,
675 show_inline_completions_override: Option<bool>,
676 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
677 edit_prediction_preview: EditPredictionPreview,
678 edit_prediction_indent_conflict: bool,
679 edit_prediction_requires_modifier_in_indent_conflict: bool,
680 inlay_hint_cache: InlayHintCache,
681 next_inlay_id: usize,
682 _subscriptions: Vec<Subscription>,
683 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
684 gutter_dimensions: GutterDimensions,
685 style: Option<EditorStyle>,
686 text_style_refinement: Option<TextStyleRefinement>,
687 next_editor_action_id: EditorActionId,
688 editor_actions:
689 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
690 use_autoclose: bool,
691 use_auto_surround: bool,
692 auto_replace_emoji_shortcode: bool,
693 show_git_blame_gutter: bool,
694 show_git_blame_inline: bool,
695 show_git_blame_inline_delay_task: Option<Task<()>>,
696 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
697 git_blame_inline_enabled: bool,
698 serialize_dirty_buffers: bool,
699 show_selection_menu: Option<bool>,
700 blame: Option<Entity<GitBlame>>,
701 blame_subscription: Option<Subscription>,
702 custom_context_menu: Option<
703 Box<
704 dyn 'static
705 + Fn(
706 &mut Self,
707 DisplayPoint,
708 &mut Window,
709 &mut Context<Self>,
710 ) -> Option<Entity<ui::ContextMenu>>,
711 >,
712 >,
713 last_bounds: Option<Bounds<Pixels>>,
714 last_position_map: Option<Rc<PositionMap>>,
715 expect_bounds_change: Option<Bounds<Pixels>>,
716 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
717 tasks_update_task: Option<Task<()>>,
718 in_project_search: bool,
719 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
720 breadcrumb_header: Option<String>,
721 focused_block: Option<FocusedBlock>,
722 next_scroll_position: NextScrollCursorCenterTopBottom,
723 addons: HashMap<TypeId, Box<dyn Addon>>,
724 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
725 load_diff_task: Option<Shared<Task<()>>>,
726 selection_mark_mode: bool,
727 toggle_fold_multiple_buffers: Task<()>,
728 _scroll_cursor_center_top_bottom_task: Task<()>,
729 serialize_selections: Task<()>,
730}
731
732#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
733enum NextScrollCursorCenterTopBottom {
734 #[default]
735 Center,
736 Top,
737 Bottom,
738}
739
740impl NextScrollCursorCenterTopBottom {
741 fn next(&self) -> Self {
742 match self {
743 Self::Center => Self::Top,
744 Self::Top => Self::Bottom,
745 Self::Bottom => Self::Center,
746 }
747 }
748}
749
750#[derive(Clone)]
751pub struct EditorSnapshot {
752 pub mode: EditorMode,
753 show_gutter: bool,
754 show_line_numbers: Option<bool>,
755 show_git_diff_gutter: Option<bool>,
756 show_code_actions: Option<bool>,
757 show_runnables: Option<bool>,
758 git_blame_gutter_max_author_length: Option<usize>,
759 pub display_snapshot: DisplaySnapshot,
760 pub placeholder_text: Option<Arc<str>>,
761 is_focused: bool,
762 scroll_anchor: ScrollAnchor,
763 ongoing_scroll: OngoingScroll,
764 current_line_highlight: CurrentLineHighlight,
765 gutter_hovered: bool,
766}
767
768const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
769
770#[derive(Default, Debug, Clone, Copy)]
771pub struct GutterDimensions {
772 pub left_padding: Pixels,
773 pub right_padding: Pixels,
774 pub width: Pixels,
775 pub margin: Pixels,
776 pub git_blame_entries_width: Option<Pixels>,
777}
778
779impl GutterDimensions {
780 /// The full width of the space taken up by the gutter.
781 pub fn full_width(&self) -> Pixels {
782 self.margin + self.width
783 }
784
785 /// The width of the space reserved for the fold indicators,
786 /// use alongside 'justify_end' and `gutter_width` to
787 /// right align content with the line numbers
788 pub fn fold_area_width(&self) -> Pixels {
789 self.margin + self.right_padding
790 }
791}
792
793#[derive(Debug)]
794pub struct RemoteSelection {
795 pub replica_id: ReplicaId,
796 pub selection: Selection<Anchor>,
797 pub cursor_shape: CursorShape,
798 pub peer_id: PeerId,
799 pub line_mode: bool,
800 pub participant_index: Option<ParticipantIndex>,
801 pub user_name: Option<SharedString>,
802}
803
804#[derive(Clone, Debug)]
805struct SelectionHistoryEntry {
806 selections: Arc<[Selection<Anchor>]>,
807 select_next_state: Option<SelectNextState>,
808 select_prev_state: Option<SelectNextState>,
809 add_selections_state: Option<AddSelectionsState>,
810}
811
812enum SelectionHistoryMode {
813 Normal,
814 Undoing,
815 Redoing,
816}
817
818#[derive(Clone, PartialEq, Eq, Hash)]
819struct HoveredCursor {
820 replica_id: u16,
821 selection_id: usize,
822}
823
824impl Default for SelectionHistoryMode {
825 fn default() -> Self {
826 Self::Normal
827 }
828}
829
830#[derive(Default)]
831struct SelectionHistory {
832 #[allow(clippy::type_complexity)]
833 selections_by_transaction:
834 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
835 mode: SelectionHistoryMode,
836 undo_stack: VecDeque<SelectionHistoryEntry>,
837 redo_stack: VecDeque<SelectionHistoryEntry>,
838}
839
840impl SelectionHistory {
841 fn insert_transaction(
842 &mut self,
843 transaction_id: TransactionId,
844 selections: Arc<[Selection<Anchor>]>,
845 ) {
846 self.selections_by_transaction
847 .insert(transaction_id, (selections, None));
848 }
849
850 #[allow(clippy::type_complexity)]
851 fn transaction(
852 &self,
853 transaction_id: TransactionId,
854 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
855 self.selections_by_transaction.get(&transaction_id)
856 }
857
858 #[allow(clippy::type_complexity)]
859 fn transaction_mut(
860 &mut self,
861 transaction_id: TransactionId,
862 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
863 self.selections_by_transaction.get_mut(&transaction_id)
864 }
865
866 fn push(&mut self, entry: SelectionHistoryEntry) {
867 if !entry.selections.is_empty() {
868 match self.mode {
869 SelectionHistoryMode::Normal => {
870 self.push_undo(entry);
871 self.redo_stack.clear();
872 }
873 SelectionHistoryMode::Undoing => self.push_redo(entry),
874 SelectionHistoryMode::Redoing => self.push_undo(entry),
875 }
876 }
877 }
878
879 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
880 if self
881 .undo_stack
882 .back()
883 .map_or(true, |e| e.selections != entry.selections)
884 {
885 self.undo_stack.push_back(entry);
886 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
887 self.undo_stack.pop_front();
888 }
889 }
890 }
891
892 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
893 if self
894 .redo_stack
895 .back()
896 .map_or(true, |e| e.selections != entry.selections)
897 {
898 self.redo_stack.push_back(entry);
899 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
900 self.redo_stack.pop_front();
901 }
902 }
903 }
904}
905
906struct RowHighlight {
907 index: usize,
908 range: Range<Anchor>,
909 color: Hsla,
910 should_autoscroll: bool,
911}
912
913#[derive(Clone, Debug)]
914struct AddSelectionsState {
915 above: bool,
916 stack: Vec<usize>,
917}
918
919#[derive(Clone)]
920struct SelectNextState {
921 query: AhoCorasick,
922 wordwise: bool,
923 done: bool,
924}
925
926impl std::fmt::Debug for SelectNextState {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 f.debug_struct(std::any::type_name::<Self>())
929 .field("wordwise", &self.wordwise)
930 .field("done", &self.done)
931 .finish()
932 }
933}
934
935#[derive(Debug)]
936struct AutocloseRegion {
937 selection_id: usize,
938 range: Range<Anchor>,
939 pair: BracketPair,
940}
941
942#[derive(Debug)]
943struct SnippetState {
944 ranges: Vec<Vec<Range<Anchor>>>,
945 active_index: usize,
946 choices: Vec<Option<Vec<String>>>,
947}
948
949#[doc(hidden)]
950pub struct RenameState {
951 pub range: Range<Anchor>,
952 pub old_name: Arc<str>,
953 pub editor: Entity<Editor>,
954 block_id: CustomBlockId,
955}
956
957struct InvalidationStack<T>(Vec<T>);
958
959struct RegisteredInlineCompletionProvider {
960 provider: Arc<dyn InlineCompletionProviderHandle>,
961 _subscription: Subscription,
962}
963
964#[derive(Debug)]
965struct ActiveDiagnosticGroup {
966 primary_range: Range<Anchor>,
967 primary_message: String,
968 group_id: usize,
969 blocks: HashMap<CustomBlockId, Diagnostic>,
970 is_valid: bool,
971}
972
973#[derive(Serialize, Deserialize, Clone, Debug)]
974pub struct ClipboardSelection {
975 /// The number of bytes in this selection.
976 pub len: usize,
977 /// Whether this was a full-line selection.
978 pub is_entire_line: bool,
979 /// The column where this selection originally started.
980 pub start_column: u32,
981}
982
983#[derive(Debug)]
984pub(crate) struct NavigationData {
985 cursor_anchor: Anchor,
986 cursor_position: Point,
987 scroll_anchor: ScrollAnchor,
988 scroll_top_row: u32,
989}
990
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum GotoDefinitionKind {
993 Symbol,
994 Declaration,
995 Type,
996 Implementation,
997}
998
999#[derive(Debug, Clone)]
1000enum InlayHintRefreshReason {
1001 Toggle(bool),
1002 SettingsChange(InlayHintSettings),
1003 NewLinesShown,
1004 BufferEdited(HashSet<Arc<Language>>),
1005 RefreshRequested,
1006 ExcerptsRemoved(Vec<ExcerptId>),
1007}
1008
1009impl InlayHintRefreshReason {
1010 fn description(&self) -> &'static str {
1011 match self {
1012 Self::Toggle(_) => "toggle",
1013 Self::SettingsChange(_) => "settings change",
1014 Self::NewLinesShown => "new lines shown",
1015 Self::BufferEdited(_) => "buffer edited",
1016 Self::RefreshRequested => "refresh requested",
1017 Self::ExcerptsRemoved(_) => "excerpts removed",
1018 }
1019 }
1020}
1021
1022pub enum FormatTarget {
1023 Buffers,
1024 Ranges(Vec<Range<MultiBufferPoint>>),
1025}
1026
1027pub(crate) struct FocusedBlock {
1028 id: BlockId,
1029 focus_handle: WeakFocusHandle,
1030}
1031
1032#[derive(Clone)]
1033enum JumpData {
1034 MultiBufferRow {
1035 row: MultiBufferRow,
1036 line_offset_from_top: u32,
1037 },
1038 MultiBufferPoint {
1039 excerpt_id: ExcerptId,
1040 position: Point,
1041 anchor: text::Anchor,
1042 line_offset_from_top: u32,
1043 },
1044}
1045
1046pub enum MultibufferSelectionMode {
1047 First,
1048 All,
1049}
1050
1051impl Editor {
1052 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1053 let buffer = cx.new(|cx| Buffer::local("", cx));
1054 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1055 Self::new(
1056 EditorMode::SingleLine { auto_width: false },
1057 buffer,
1058 None,
1059 false,
1060 window,
1061 cx,
1062 )
1063 }
1064
1065 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1066 let buffer = cx.new(|cx| Buffer::local("", cx));
1067 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1068 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1069 }
1070
1071 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1072 let buffer = cx.new(|cx| Buffer::local("", cx));
1073 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(
1075 EditorMode::SingleLine { auto_width: true },
1076 buffer,
1077 None,
1078 false,
1079 window,
1080 cx,
1081 )
1082 }
1083
1084 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1085 let buffer = cx.new(|cx| Buffer::local("", cx));
1086 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1087 Self::new(
1088 EditorMode::AutoHeight { max_lines },
1089 buffer,
1090 None,
1091 false,
1092 window,
1093 cx,
1094 )
1095 }
1096
1097 pub fn for_buffer(
1098 buffer: Entity<Buffer>,
1099 project: Option<Entity<Project>>,
1100 window: &mut Window,
1101 cx: &mut Context<Self>,
1102 ) -> Self {
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1105 }
1106
1107 pub fn for_multibuffer(
1108 buffer: Entity<MultiBuffer>,
1109 project: Option<Entity<Project>>,
1110 show_excerpt_controls: bool,
1111 window: &mut Window,
1112 cx: &mut Context<Self>,
1113 ) -> Self {
1114 Self::new(
1115 EditorMode::Full,
1116 buffer,
1117 project,
1118 show_excerpt_controls,
1119 window,
1120 cx,
1121 )
1122 }
1123
1124 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1125 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1126 let mut clone = Self::new(
1127 self.mode,
1128 self.buffer.clone(),
1129 self.project.clone(),
1130 show_excerpt_controls,
1131 window,
1132 cx,
1133 );
1134 self.display_map.update(cx, |display_map, cx| {
1135 let snapshot = display_map.snapshot(cx);
1136 clone.display_map.update(cx, |display_map, cx| {
1137 display_map.set_state(&snapshot, cx);
1138 });
1139 });
1140 clone.selections.clone_state(&self.selections);
1141 clone.scroll_manager.clone_state(&self.scroll_manager);
1142 clone.searchable = self.searchable;
1143 clone
1144 }
1145
1146 pub fn new(
1147 mode: EditorMode,
1148 buffer: Entity<MultiBuffer>,
1149 project: Option<Entity<Project>>,
1150 show_excerpt_controls: bool,
1151 window: &mut Window,
1152 cx: &mut Context<Self>,
1153 ) -> Self {
1154 let style = window.text_style();
1155 let font_size = style.font_size.to_pixels(window.rem_size());
1156 let editor = cx.entity().downgrade();
1157 let fold_placeholder = FoldPlaceholder {
1158 constrain_width: true,
1159 render: Arc::new(move |fold_id, fold_range, cx| {
1160 let editor = editor.clone();
1161 div()
1162 .id(fold_id)
1163 .bg(cx.theme().colors().ghost_element_background)
1164 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1165 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1166 .rounded_sm()
1167 .size_full()
1168 .cursor_pointer()
1169 .child("⋯")
1170 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1171 .on_click(move |_, _window, cx| {
1172 editor
1173 .update(cx, |editor, cx| {
1174 editor.unfold_ranges(
1175 &[fold_range.start..fold_range.end],
1176 true,
1177 false,
1178 cx,
1179 );
1180 cx.stop_propagation();
1181 })
1182 .ok();
1183 })
1184 .into_any()
1185 }),
1186 merge_adjacent: true,
1187 ..Default::default()
1188 };
1189 let display_map = cx.new(|cx| {
1190 DisplayMap::new(
1191 buffer.clone(),
1192 style.font(),
1193 font_size,
1194 None,
1195 show_excerpt_controls,
1196 FILE_HEADER_HEIGHT,
1197 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1198 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1199 fold_placeholder,
1200 cx,
1201 )
1202 });
1203
1204 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1205
1206 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1207
1208 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1209 .then(|| language_settings::SoftWrap::None);
1210
1211 let mut project_subscriptions = Vec::new();
1212 if mode == EditorMode::Full {
1213 if let Some(project) = project.as_ref() {
1214 if buffer.read(cx).is_singleton() {
1215 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1216 cx.emit(EditorEvent::TitleChanged);
1217 }));
1218 }
1219 project_subscriptions.push(cx.subscribe_in(
1220 project,
1221 window,
1222 |editor, _, event, window, cx| {
1223 if let project::Event::RefreshInlayHints = event {
1224 editor
1225 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1226 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1227 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1228 let focus_handle = editor.focus_handle(cx);
1229 if focus_handle.is_focused(window) {
1230 let snapshot = buffer.read(cx).snapshot();
1231 for (range, snippet) in snippet_edits {
1232 let editor_range =
1233 language::range_from_lsp(*range).to_offset(&snapshot);
1234 editor
1235 .insert_snippet(
1236 &[editor_range],
1237 snippet.clone(),
1238 window,
1239 cx,
1240 )
1241 .ok();
1242 }
1243 }
1244 }
1245 }
1246 },
1247 ));
1248 if let Some(task_inventory) = project
1249 .read(cx)
1250 .task_store()
1251 .read(cx)
1252 .task_inventory()
1253 .cloned()
1254 {
1255 project_subscriptions.push(cx.observe_in(
1256 &task_inventory,
1257 window,
1258 |editor, _, window, cx| {
1259 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1260 },
1261 ));
1262 }
1263 }
1264 }
1265
1266 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1267
1268 let inlay_hint_settings =
1269 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1270 let focus_handle = cx.focus_handle();
1271 cx.on_focus(&focus_handle, window, Self::handle_focus)
1272 .detach();
1273 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1274 .detach();
1275 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1276 .detach();
1277 cx.on_blur(&focus_handle, window, Self::handle_blur)
1278 .detach();
1279
1280 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1281 Some(false)
1282 } else {
1283 None
1284 };
1285
1286 let mut code_action_providers = Vec::new();
1287 let mut load_uncommitted_diff = None;
1288 if let Some(project) = project.clone() {
1289 load_uncommitted_diff = Some(
1290 get_uncommitted_diff_for_buffer(
1291 &project,
1292 buffer.read(cx).all_buffers(),
1293 buffer.clone(),
1294 cx,
1295 )
1296 .shared(),
1297 );
1298 code_action_providers.push(Rc::new(project) as Rc<_>);
1299 }
1300
1301 let mut this = Self {
1302 focus_handle,
1303 show_cursor_when_unfocused: false,
1304 last_focused_descendant: None,
1305 buffer: buffer.clone(),
1306 display_map: display_map.clone(),
1307 selections,
1308 scroll_manager: ScrollManager::new(cx),
1309 columnar_selection_tail: None,
1310 add_selections_state: None,
1311 select_next_state: None,
1312 select_prev_state: None,
1313 selection_history: Default::default(),
1314 autoclose_regions: Default::default(),
1315 snippet_stack: Default::default(),
1316 select_larger_syntax_node_stack: Vec::new(),
1317 ime_transaction: Default::default(),
1318 active_diagnostics: None,
1319 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1320 inline_diagnostics_update: Task::ready(()),
1321 inline_diagnostics: Vec::new(),
1322 soft_wrap_mode_override,
1323 completion_provider: project.clone().map(|project| Box::new(project) as _),
1324 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1325 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1326 project,
1327 blink_manager: blink_manager.clone(),
1328 show_local_selections: true,
1329 show_scrollbars: true,
1330 mode,
1331 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1332 show_gutter: mode == EditorMode::Full,
1333 show_line_numbers: None,
1334 use_relative_line_numbers: None,
1335 show_git_diff_gutter: None,
1336 show_code_actions: None,
1337 show_runnables: None,
1338 show_wrap_guides: None,
1339 show_indent_guides,
1340 placeholder_text: None,
1341 highlight_order: 0,
1342 highlighted_rows: HashMap::default(),
1343 background_highlights: Default::default(),
1344 gutter_highlights: TreeMap::default(),
1345 scrollbar_marker_state: ScrollbarMarkerState::default(),
1346 active_indent_guides_state: ActiveIndentGuidesState::default(),
1347 nav_history: None,
1348 context_menu: RefCell::new(None),
1349 mouse_context_menu: None,
1350 completion_tasks: Default::default(),
1351 signature_help_state: SignatureHelpState::default(),
1352 auto_signature_help: None,
1353 find_all_references_task_sources: Vec::new(),
1354 next_completion_id: 0,
1355 next_inlay_id: 0,
1356 code_action_providers,
1357 available_code_actions: Default::default(),
1358 code_actions_task: Default::default(),
1359 selection_highlight_task: Default::default(),
1360 document_highlights_task: Default::default(),
1361 linked_editing_range_task: Default::default(),
1362 pending_rename: Default::default(),
1363 searchable: true,
1364 cursor_shape: EditorSettings::get_global(cx)
1365 .cursor_shape
1366 .unwrap_or_default(),
1367 current_line_highlight: None,
1368 autoindent_mode: Some(AutoindentMode::EachLine),
1369 collapse_matches: false,
1370 workspace: None,
1371 input_enabled: true,
1372 use_modal_editing: mode == EditorMode::Full,
1373 read_only: false,
1374 use_autoclose: true,
1375 use_auto_surround: true,
1376 auto_replace_emoji_shortcode: false,
1377 leader_peer_id: None,
1378 remote_id: None,
1379 hover_state: Default::default(),
1380 pending_mouse_down: None,
1381 hovered_link_state: Default::default(),
1382 edit_prediction_provider: None,
1383 active_inline_completion: None,
1384 stale_inline_completion_in_menu: None,
1385 edit_prediction_preview: EditPredictionPreview::Inactive,
1386 inline_diagnostics_enabled: mode == EditorMode::Full,
1387 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1388
1389 gutter_hovered: false,
1390 pixel_position_of_newest_cursor: None,
1391 last_bounds: None,
1392 last_position_map: None,
1393 expect_bounds_change: None,
1394 gutter_dimensions: GutterDimensions::default(),
1395 style: None,
1396 show_cursor_names: false,
1397 hovered_cursors: Default::default(),
1398 next_editor_action_id: EditorActionId::default(),
1399 editor_actions: Rc::default(),
1400 inline_completions_hidden_for_vim_mode: false,
1401 show_inline_completions_override: None,
1402 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1403 edit_prediction_settings: EditPredictionSettings::Disabled,
1404 edit_prediction_indent_conflict: false,
1405 edit_prediction_requires_modifier_in_indent_conflict: true,
1406 custom_context_menu: None,
1407 show_git_blame_gutter: false,
1408 show_git_blame_inline: false,
1409 show_selection_menu: None,
1410 show_git_blame_inline_delay_task: None,
1411 git_blame_inline_tooltip: None,
1412 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1413 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1414 .session
1415 .restore_unsaved_buffers,
1416 blame: None,
1417 blame_subscription: None,
1418 tasks: Default::default(),
1419 _subscriptions: vec![
1420 cx.observe(&buffer, Self::on_buffer_changed),
1421 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1422 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1423 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1424 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1425 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1426 cx.observe_window_activation(window, |editor, window, cx| {
1427 let active = window.is_window_active();
1428 editor.blink_manager.update(cx, |blink_manager, cx| {
1429 if active {
1430 blink_manager.enable(cx);
1431 } else {
1432 blink_manager.disable(cx);
1433 }
1434 });
1435 }),
1436 ],
1437 tasks_update_task: None,
1438 linked_edit_ranges: Default::default(),
1439 in_project_search: false,
1440 previous_search_ranges: None,
1441 breadcrumb_header: None,
1442 focused_block: None,
1443 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1444 addons: HashMap::default(),
1445 registered_buffers: HashMap::default(),
1446 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1447 selection_mark_mode: false,
1448 toggle_fold_multiple_buffers: Task::ready(()),
1449 serialize_selections: Task::ready(()),
1450 text_style_refinement: None,
1451 load_diff_task: load_uncommitted_diff,
1452 };
1453 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1454 this._subscriptions.extend(project_subscriptions);
1455
1456 this.end_selection(window, cx);
1457 this.scroll_manager.show_scrollbar(window, cx);
1458
1459 if mode == EditorMode::Full {
1460 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1461 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1462
1463 if this.git_blame_inline_enabled {
1464 this.git_blame_inline_enabled = true;
1465 this.start_git_blame_inline(false, window, cx);
1466 }
1467
1468 if let Some(buffer) = buffer.read(cx).as_singleton() {
1469 if let Some(project) = this.project.as_ref() {
1470 let handle = project.update(cx, |project, cx| {
1471 project.register_buffer_with_language_servers(&buffer, cx)
1472 });
1473 this.registered_buffers
1474 .insert(buffer.read(cx).remote_id(), handle);
1475 }
1476 }
1477 }
1478
1479 this.report_editor_event("Editor Opened", None, cx);
1480 this
1481 }
1482
1483 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1484 self.mouse_context_menu
1485 .as_ref()
1486 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1487 }
1488
1489 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1490 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1491 }
1492
1493 fn key_context_internal(
1494 &self,
1495 has_active_edit_prediction: bool,
1496 window: &Window,
1497 cx: &App,
1498 ) -> KeyContext {
1499 let mut key_context = KeyContext::new_with_defaults();
1500 key_context.add("Editor");
1501 let mode = match self.mode {
1502 EditorMode::SingleLine { .. } => "single_line",
1503 EditorMode::AutoHeight { .. } => "auto_height",
1504 EditorMode::Full => "full",
1505 };
1506
1507 if EditorSettings::jupyter_enabled(cx) {
1508 key_context.add("jupyter");
1509 }
1510
1511 key_context.set("mode", mode);
1512 if self.pending_rename.is_some() {
1513 key_context.add("renaming");
1514 }
1515
1516 match self.context_menu.borrow().as_ref() {
1517 Some(CodeContextMenu::Completions(_)) => {
1518 key_context.add("menu");
1519 key_context.add("showing_completions");
1520 }
1521 Some(CodeContextMenu::CodeActions(_)) => {
1522 key_context.add("menu");
1523 key_context.add("showing_code_actions")
1524 }
1525 None => {}
1526 }
1527
1528 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1529 if !self.focus_handle(cx).contains_focused(window, cx)
1530 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1531 {
1532 for addon in self.addons.values() {
1533 addon.extend_key_context(&mut key_context, cx)
1534 }
1535 }
1536
1537 if let Some(extension) = self
1538 .buffer
1539 .read(cx)
1540 .as_singleton()
1541 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1542 {
1543 key_context.set("extension", extension.to_string());
1544 }
1545
1546 if has_active_edit_prediction {
1547 if self.edit_prediction_in_conflict() {
1548 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1549 } else {
1550 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1551 key_context.add("copilot_suggestion");
1552 }
1553 }
1554
1555 if self.selection_mark_mode {
1556 key_context.add("selection_mode");
1557 }
1558
1559 key_context
1560 }
1561
1562 pub fn edit_prediction_in_conflict(&self) -> bool {
1563 if !self.show_edit_predictions_in_menu() {
1564 return false;
1565 }
1566
1567 let showing_completions = self
1568 .context_menu
1569 .borrow()
1570 .as_ref()
1571 .map_or(false, |context| {
1572 matches!(context, CodeContextMenu::Completions(_))
1573 });
1574
1575 showing_completions
1576 || self.edit_prediction_requires_modifier()
1577 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1578 // bindings to insert tab characters.
1579 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1580 }
1581
1582 pub fn accept_edit_prediction_keybind(
1583 &self,
1584 window: &Window,
1585 cx: &App,
1586 ) -> AcceptEditPredictionBinding {
1587 let key_context = self.key_context_internal(true, window, cx);
1588 let in_conflict = self.edit_prediction_in_conflict();
1589
1590 AcceptEditPredictionBinding(
1591 window
1592 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1593 .into_iter()
1594 .filter(|binding| {
1595 !in_conflict
1596 || binding
1597 .keystrokes()
1598 .first()
1599 .map_or(false, |keystroke| keystroke.modifiers.modified())
1600 })
1601 .rev()
1602 .min_by_key(|binding| {
1603 binding
1604 .keystrokes()
1605 .first()
1606 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1607 }),
1608 )
1609 }
1610
1611 pub fn new_file(
1612 workspace: &mut Workspace,
1613 _: &workspace::NewFile,
1614 window: &mut Window,
1615 cx: &mut Context<Workspace>,
1616 ) {
1617 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1618 "Failed to create buffer",
1619 window,
1620 cx,
1621 |e, _, _| match e.error_code() {
1622 ErrorCode::RemoteUpgradeRequired => Some(format!(
1623 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1624 e.error_tag("required").unwrap_or("the latest version")
1625 )),
1626 _ => None,
1627 },
1628 );
1629 }
1630
1631 pub fn new_in_workspace(
1632 workspace: &mut Workspace,
1633 window: &mut Window,
1634 cx: &mut Context<Workspace>,
1635 ) -> Task<Result<Entity<Editor>>> {
1636 let project = workspace.project().clone();
1637 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1638
1639 cx.spawn_in(window, |workspace, mut cx| async move {
1640 let buffer = create.await?;
1641 workspace.update_in(&mut cx, |workspace, window, cx| {
1642 let editor =
1643 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1644 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1645 editor
1646 })
1647 })
1648 }
1649
1650 fn new_file_vertical(
1651 workspace: &mut Workspace,
1652 _: &workspace::NewFileSplitVertical,
1653 window: &mut Window,
1654 cx: &mut Context<Workspace>,
1655 ) {
1656 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1657 }
1658
1659 fn new_file_horizontal(
1660 workspace: &mut Workspace,
1661 _: &workspace::NewFileSplitHorizontal,
1662 window: &mut Window,
1663 cx: &mut Context<Workspace>,
1664 ) {
1665 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1666 }
1667
1668 fn new_file_in_direction(
1669 workspace: &mut Workspace,
1670 direction: SplitDirection,
1671 window: &mut Window,
1672 cx: &mut Context<Workspace>,
1673 ) {
1674 let project = workspace.project().clone();
1675 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1676
1677 cx.spawn_in(window, |workspace, mut cx| async move {
1678 let buffer = create.await?;
1679 workspace.update_in(&mut cx, move |workspace, window, cx| {
1680 workspace.split_item(
1681 direction,
1682 Box::new(
1683 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1684 ),
1685 window,
1686 cx,
1687 )
1688 })?;
1689 anyhow::Ok(())
1690 })
1691 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1692 match e.error_code() {
1693 ErrorCode::RemoteUpgradeRequired => Some(format!(
1694 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1695 e.error_tag("required").unwrap_or("the latest version")
1696 )),
1697 _ => None,
1698 }
1699 });
1700 }
1701
1702 pub fn leader_peer_id(&self) -> Option<PeerId> {
1703 self.leader_peer_id
1704 }
1705
1706 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1707 &self.buffer
1708 }
1709
1710 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1711 self.workspace.as_ref()?.0.upgrade()
1712 }
1713
1714 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1715 self.buffer().read(cx).title(cx)
1716 }
1717
1718 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1719 let git_blame_gutter_max_author_length = self
1720 .render_git_blame_gutter(cx)
1721 .then(|| {
1722 if let Some(blame) = self.blame.as_ref() {
1723 let max_author_length =
1724 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1725 Some(max_author_length)
1726 } else {
1727 None
1728 }
1729 })
1730 .flatten();
1731
1732 EditorSnapshot {
1733 mode: self.mode,
1734 show_gutter: self.show_gutter,
1735 show_line_numbers: self.show_line_numbers,
1736 show_git_diff_gutter: self.show_git_diff_gutter,
1737 show_code_actions: self.show_code_actions,
1738 show_runnables: self.show_runnables,
1739 git_blame_gutter_max_author_length,
1740 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1741 scroll_anchor: self.scroll_manager.anchor(),
1742 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1743 placeholder_text: self.placeholder_text.clone(),
1744 is_focused: self.focus_handle.is_focused(window),
1745 current_line_highlight: self
1746 .current_line_highlight
1747 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1748 gutter_hovered: self.gutter_hovered,
1749 }
1750 }
1751
1752 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1753 self.buffer.read(cx).language_at(point, cx)
1754 }
1755
1756 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1757 self.buffer.read(cx).read(cx).file_at(point).cloned()
1758 }
1759
1760 pub fn active_excerpt(
1761 &self,
1762 cx: &App,
1763 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1764 self.buffer
1765 .read(cx)
1766 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1767 }
1768
1769 pub fn mode(&self) -> EditorMode {
1770 self.mode
1771 }
1772
1773 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1774 self.collaboration_hub.as_deref()
1775 }
1776
1777 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1778 self.collaboration_hub = Some(hub);
1779 }
1780
1781 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1782 self.in_project_search = in_project_search;
1783 }
1784
1785 pub fn set_custom_context_menu(
1786 &mut self,
1787 f: impl 'static
1788 + Fn(
1789 &mut Self,
1790 DisplayPoint,
1791 &mut Window,
1792 &mut Context<Self>,
1793 ) -> Option<Entity<ui::ContextMenu>>,
1794 ) {
1795 self.custom_context_menu = Some(Box::new(f))
1796 }
1797
1798 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1799 self.completion_provider = provider;
1800 }
1801
1802 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1803 self.semantics_provider.clone()
1804 }
1805
1806 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1807 self.semantics_provider = provider;
1808 }
1809
1810 pub fn set_edit_prediction_provider<T>(
1811 &mut self,
1812 provider: Option<Entity<T>>,
1813 window: &mut Window,
1814 cx: &mut Context<Self>,
1815 ) where
1816 T: EditPredictionProvider,
1817 {
1818 self.edit_prediction_provider =
1819 provider.map(|provider| RegisteredInlineCompletionProvider {
1820 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1821 if this.focus_handle.is_focused(window) {
1822 this.update_visible_inline_completion(window, cx);
1823 }
1824 }),
1825 provider: Arc::new(provider),
1826 });
1827 self.update_edit_prediction_settings(cx);
1828 self.refresh_inline_completion(false, false, window, cx);
1829 }
1830
1831 pub fn placeholder_text(&self) -> Option<&str> {
1832 self.placeholder_text.as_deref()
1833 }
1834
1835 pub fn set_placeholder_text(
1836 &mut self,
1837 placeholder_text: impl Into<Arc<str>>,
1838 cx: &mut Context<Self>,
1839 ) {
1840 let placeholder_text = Some(placeholder_text.into());
1841 if self.placeholder_text != placeholder_text {
1842 self.placeholder_text = placeholder_text;
1843 cx.notify();
1844 }
1845 }
1846
1847 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1848 self.cursor_shape = cursor_shape;
1849
1850 // Disrupt blink for immediate user feedback that the cursor shape has changed
1851 self.blink_manager.update(cx, BlinkManager::show_cursor);
1852
1853 cx.notify();
1854 }
1855
1856 pub fn set_current_line_highlight(
1857 &mut self,
1858 current_line_highlight: Option<CurrentLineHighlight>,
1859 ) {
1860 self.current_line_highlight = current_line_highlight;
1861 }
1862
1863 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1864 self.collapse_matches = collapse_matches;
1865 }
1866
1867 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1868 let buffers = self.buffer.read(cx).all_buffers();
1869 let Some(project) = self.project.as_ref() else {
1870 return;
1871 };
1872 project.update(cx, |project, cx| {
1873 for buffer in buffers {
1874 self.registered_buffers
1875 .entry(buffer.read(cx).remote_id())
1876 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1877 }
1878 })
1879 }
1880
1881 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1882 if self.collapse_matches {
1883 return range.start..range.start;
1884 }
1885 range.clone()
1886 }
1887
1888 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1889 if self.display_map.read(cx).clip_at_line_ends != clip {
1890 self.display_map
1891 .update(cx, |map, _| map.clip_at_line_ends = clip);
1892 }
1893 }
1894
1895 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1896 self.input_enabled = input_enabled;
1897 }
1898
1899 pub fn set_inline_completions_hidden_for_vim_mode(
1900 &mut self,
1901 hidden: bool,
1902 window: &mut Window,
1903 cx: &mut Context<Self>,
1904 ) {
1905 if hidden != self.inline_completions_hidden_for_vim_mode {
1906 self.inline_completions_hidden_for_vim_mode = hidden;
1907 if hidden {
1908 self.update_visible_inline_completion(window, cx);
1909 } else {
1910 self.refresh_inline_completion(true, false, window, cx);
1911 }
1912 }
1913 }
1914
1915 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1916 self.menu_inline_completions_policy = value;
1917 }
1918
1919 pub fn set_autoindent(&mut self, autoindent: bool) {
1920 if autoindent {
1921 self.autoindent_mode = Some(AutoindentMode::EachLine);
1922 } else {
1923 self.autoindent_mode = None;
1924 }
1925 }
1926
1927 pub fn read_only(&self, cx: &App) -> bool {
1928 self.read_only || self.buffer.read(cx).read_only()
1929 }
1930
1931 pub fn set_read_only(&mut self, read_only: bool) {
1932 self.read_only = read_only;
1933 }
1934
1935 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1936 self.use_autoclose = autoclose;
1937 }
1938
1939 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1940 self.use_auto_surround = auto_surround;
1941 }
1942
1943 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1944 self.auto_replace_emoji_shortcode = auto_replace;
1945 }
1946
1947 pub fn toggle_edit_predictions(
1948 &mut self,
1949 _: &ToggleEditPrediction,
1950 window: &mut Window,
1951 cx: &mut Context<Self>,
1952 ) {
1953 if self.show_inline_completions_override.is_some() {
1954 self.set_show_edit_predictions(None, window, cx);
1955 } else {
1956 let show_edit_predictions = !self.edit_predictions_enabled();
1957 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1958 }
1959 }
1960
1961 pub fn set_show_edit_predictions(
1962 &mut self,
1963 show_edit_predictions: Option<bool>,
1964 window: &mut Window,
1965 cx: &mut Context<Self>,
1966 ) {
1967 self.show_inline_completions_override = show_edit_predictions;
1968 self.update_edit_prediction_settings(cx);
1969
1970 if let Some(false) = show_edit_predictions {
1971 self.discard_inline_completion(false, cx);
1972 } else {
1973 self.refresh_inline_completion(false, true, window, cx);
1974 }
1975 }
1976
1977 fn inline_completions_disabled_in_scope(
1978 &self,
1979 buffer: &Entity<Buffer>,
1980 buffer_position: language::Anchor,
1981 cx: &App,
1982 ) -> bool {
1983 let snapshot = buffer.read(cx).snapshot();
1984 let settings = snapshot.settings_at(buffer_position, cx);
1985
1986 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1987 return false;
1988 };
1989
1990 scope.override_name().map_or(false, |scope_name| {
1991 settings
1992 .edit_predictions_disabled_in
1993 .iter()
1994 .any(|s| s == scope_name)
1995 })
1996 }
1997
1998 pub fn set_use_modal_editing(&mut self, to: bool) {
1999 self.use_modal_editing = to;
2000 }
2001
2002 pub fn use_modal_editing(&self) -> bool {
2003 self.use_modal_editing
2004 }
2005
2006 fn selections_did_change(
2007 &mut self,
2008 local: bool,
2009 old_cursor_position: &Anchor,
2010 show_completions: bool,
2011 window: &mut Window,
2012 cx: &mut Context<Self>,
2013 ) {
2014 window.invalidate_character_coordinates();
2015
2016 // Copy selections to primary selection buffer
2017 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2018 if local {
2019 let selections = self.selections.all::<usize>(cx);
2020 let buffer_handle = self.buffer.read(cx).read(cx);
2021
2022 let mut text = String::new();
2023 for (index, selection) in selections.iter().enumerate() {
2024 let text_for_selection = buffer_handle
2025 .text_for_range(selection.start..selection.end)
2026 .collect::<String>();
2027
2028 text.push_str(&text_for_selection);
2029 if index != selections.len() - 1 {
2030 text.push('\n');
2031 }
2032 }
2033
2034 if !text.is_empty() {
2035 cx.write_to_primary(ClipboardItem::new_string(text));
2036 }
2037 }
2038
2039 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2040 self.buffer.update(cx, |buffer, cx| {
2041 buffer.set_active_selections(
2042 &self.selections.disjoint_anchors(),
2043 self.selections.line_mode,
2044 self.cursor_shape,
2045 cx,
2046 )
2047 });
2048 }
2049 let display_map = self
2050 .display_map
2051 .update(cx, |display_map, cx| display_map.snapshot(cx));
2052 let buffer = &display_map.buffer_snapshot;
2053 self.add_selections_state = None;
2054 self.select_next_state = None;
2055 self.select_prev_state = None;
2056 self.select_larger_syntax_node_stack.clear();
2057 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2058 self.snippet_stack
2059 .invalidate(&self.selections.disjoint_anchors(), buffer);
2060 self.take_rename(false, window, cx);
2061
2062 let new_cursor_position = self.selections.newest_anchor().head();
2063
2064 self.push_to_nav_history(
2065 *old_cursor_position,
2066 Some(new_cursor_position.to_point(buffer)),
2067 cx,
2068 );
2069
2070 if local {
2071 let new_cursor_position = self.selections.newest_anchor().head();
2072 let mut context_menu = self.context_menu.borrow_mut();
2073 let completion_menu = match context_menu.as_ref() {
2074 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2075 _ => {
2076 *context_menu = None;
2077 None
2078 }
2079 };
2080 if let Some(buffer_id) = new_cursor_position.buffer_id {
2081 if !self.registered_buffers.contains_key(&buffer_id) {
2082 if let Some(project) = self.project.as_ref() {
2083 project.update(cx, |project, cx| {
2084 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2085 return;
2086 };
2087 self.registered_buffers.insert(
2088 buffer_id,
2089 project.register_buffer_with_language_servers(&buffer, cx),
2090 );
2091 })
2092 }
2093 }
2094 }
2095
2096 if let Some(completion_menu) = completion_menu {
2097 let cursor_position = new_cursor_position.to_offset(buffer);
2098 let (word_range, kind) =
2099 buffer.surrounding_word(completion_menu.initial_position, true);
2100 if kind == Some(CharKind::Word)
2101 && word_range.to_inclusive().contains(&cursor_position)
2102 {
2103 let mut completion_menu = completion_menu.clone();
2104 drop(context_menu);
2105
2106 let query = Self::completion_query(buffer, cursor_position);
2107 cx.spawn(move |this, mut cx| async move {
2108 completion_menu
2109 .filter(query.as_deref(), cx.background_executor().clone())
2110 .await;
2111
2112 this.update(&mut cx, |this, cx| {
2113 let mut context_menu = this.context_menu.borrow_mut();
2114 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2115 else {
2116 return;
2117 };
2118
2119 if menu.id > completion_menu.id {
2120 return;
2121 }
2122
2123 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2124 drop(context_menu);
2125 cx.notify();
2126 })
2127 })
2128 .detach();
2129
2130 if show_completions {
2131 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2132 }
2133 } else {
2134 drop(context_menu);
2135 self.hide_context_menu(window, cx);
2136 }
2137 } else {
2138 drop(context_menu);
2139 }
2140
2141 hide_hover(self, cx);
2142
2143 if old_cursor_position.to_display_point(&display_map).row()
2144 != new_cursor_position.to_display_point(&display_map).row()
2145 {
2146 self.available_code_actions.take();
2147 }
2148 self.refresh_code_actions(window, cx);
2149 self.refresh_document_highlights(cx);
2150 self.refresh_selected_text_highlights(window, cx);
2151 refresh_matching_bracket_highlights(self, window, cx);
2152 self.update_visible_inline_completion(window, cx);
2153 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2154 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2155 if self.git_blame_inline_enabled {
2156 self.start_inline_blame_timer(window, cx);
2157 }
2158 }
2159
2160 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2161 cx.emit(EditorEvent::SelectionsChanged { local });
2162
2163 let selections = &self.selections.disjoint;
2164 if selections.len() == 1 {
2165 cx.emit(SearchEvent::ActiveMatchChanged)
2166 }
2167 if local
2168 && self.is_singleton(cx)
2169 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2170 {
2171 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2172 let background_executor = cx.background_executor().clone();
2173 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2174 let snapshot = self.buffer().read(cx).snapshot(cx);
2175 let selections = selections.clone();
2176 self.serialize_selections = cx.background_spawn(async move {
2177 background_executor.timer(Duration::from_millis(100)).await;
2178 let selections = selections
2179 .iter()
2180 .map(|selection| {
2181 (
2182 selection.start.to_offset(&snapshot),
2183 selection.end.to_offset(&snapshot),
2184 )
2185 })
2186 .collect();
2187 DB.save_editor_selections(editor_id, workspace_id, selections)
2188 .await
2189 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2190 .log_err();
2191 });
2192 }
2193 }
2194
2195 cx.notify();
2196 }
2197
2198 pub fn change_selections<R>(
2199 &mut self,
2200 autoscroll: Option<Autoscroll>,
2201 window: &mut Window,
2202 cx: &mut Context<Self>,
2203 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2204 ) -> R {
2205 self.change_selections_inner(autoscroll, true, window, cx, change)
2206 }
2207
2208 fn change_selections_inner<R>(
2209 &mut self,
2210 autoscroll: Option<Autoscroll>,
2211 request_completions: bool,
2212 window: &mut Window,
2213 cx: &mut Context<Self>,
2214 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2215 ) -> R {
2216 let old_cursor_position = self.selections.newest_anchor().head();
2217 self.push_to_selection_history();
2218
2219 let (changed, result) = self.selections.change_with(cx, change);
2220
2221 if changed {
2222 if let Some(autoscroll) = autoscroll {
2223 self.request_autoscroll(autoscroll, cx);
2224 }
2225 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2226
2227 if self.should_open_signature_help_automatically(
2228 &old_cursor_position,
2229 self.signature_help_state.backspace_pressed(),
2230 cx,
2231 ) {
2232 self.show_signature_help(&ShowSignatureHelp, window, cx);
2233 }
2234 self.signature_help_state.set_backspace_pressed(false);
2235 }
2236
2237 result
2238 }
2239
2240 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2241 where
2242 I: IntoIterator<Item = (Range<S>, T)>,
2243 S: ToOffset,
2244 T: Into<Arc<str>>,
2245 {
2246 if self.read_only(cx) {
2247 return;
2248 }
2249
2250 self.buffer
2251 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2252 }
2253
2254 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2255 where
2256 I: IntoIterator<Item = (Range<S>, T)>,
2257 S: ToOffset,
2258 T: Into<Arc<str>>,
2259 {
2260 if self.read_only(cx) {
2261 return;
2262 }
2263
2264 self.buffer.update(cx, |buffer, cx| {
2265 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2266 });
2267 }
2268
2269 pub fn edit_with_block_indent<I, S, T>(
2270 &mut self,
2271 edits: I,
2272 original_start_columns: Vec<u32>,
2273 cx: &mut Context<Self>,
2274 ) where
2275 I: IntoIterator<Item = (Range<S>, T)>,
2276 S: ToOffset,
2277 T: Into<Arc<str>>,
2278 {
2279 if self.read_only(cx) {
2280 return;
2281 }
2282
2283 self.buffer.update(cx, |buffer, cx| {
2284 buffer.edit(
2285 edits,
2286 Some(AutoindentMode::Block {
2287 original_start_columns,
2288 }),
2289 cx,
2290 )
2291 });
2292 }
2293
2294 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2295 self.hide_context_menu(window, cx);
2296
2297 match phase {
2298 SelectPhase::Begin {
2299 position,
2300 add,
2301 click_count,
2302 } => self.begin_selection(position, add, click_count, window, cx),
2303 SelectPhase::BeginColumnar {
2304 position,
2305 goal_column,
2306 reset,
2307 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2308 SelectPhase::Extend {
2309 position,
2310 click_count,
2311 } => self.extend_selection(position, click_count, window, cx),
2312 SelectPhase::Update {
2313 position,
2314 goal_column,
2315 scroll_delta,
2316 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2317 SelectPhase::End => self.end_selection(window, cx),
2318 }
2319 }
2320
2321 fn extend_selection(
2322 &mut self,
2323 position: DisplayPoint,
2324 click_count: usize,
2325 window: &mut Window,
2326 cx: &mut Context<Self>,
2327 ) {
2328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2329 let tail = self.selections.newest::<usize>(cx).tail();
2330 self.begin_selection(position, false, click_count, window, cx);
2331
2332 let position = position.to_offset(&display_map, Bias::Left);
2333 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2334
2335 let mut pending_selection = self
2336 .selections
2337 .pending_anchor()
2338 .expect("extend_selection not called with pending selection");
2339 if position >= tail {
2340 pending_selection.start = tail_anchor;
2341 } else {
2342 pending_selection.end = tail_anchor;
2343 pending_selection.reversed = true;
2344 }
2345
2346 let mut pending_mode = self.selections.pending_mode().unwrap();
2347 match &mut pending_mode {
2348 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2349 _ => {}
2350 }
2351
2352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2353 s.set_pending(pending_selection, pending_mode)
2354 });
2355 }
2356
2357 fn begin_selection(
2358 &mut self,
2359 position: DisplayPoint,
2360 add: bool,
2361 click_count: usize,
2362 window: &mut Window,
2363 cx: &mut Context<Self>,
2364 ) {
2365 if !self.focus_handle.is_focused(window) {
2366 self.last_focused_descendant = None;
2367 window.focus(&self.focus_handle);
2368 }
2369
2370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2371 let buffer = &display_map.buffer_snapshot;
2372 let newest_selection = self.selections.newest_anchor().clone();
2373 let position = display_map.clip_point(position, Bias::Left);
2374
2375 let start;
2376 let end;
2377 let mode;
2378 let mut auto_scroll;
2379 match click_count {
2380 1 => {
2381 start = buffer.anchor_before(position.to_point(&display_map));
2382 end = start;
2383 mode = SelectMode::Character;
2384 auto_scroll = true;
2385 }
2386 2 => {
2387 let range = movement::surrounding_word(&display_map, position);
2388 start = buffer.anchor_before(range.start.to_point(&display_map));
2389 end = buffer.anchor_before(range.end.to_point(&display_map));
2390 mode = SelectMode::Word(start..end);
2391 auto_scroll = true;
2392 }
2393 3 => {
2394 let position = display_map
2395 .clip_point(position, Bias::Left)
2396 .to_point(&display_map);
2397 let line_start = display_map.prev_line_boundary(position).0;
2398 let next_line_start = buffer.clip_point(
2399 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2400 Bias::Left,
2401 );
2402 start = buffer.anchor_before(line_start);
2403 end = buffer.anchor_before(next_line_start);
2404 mode = SelectMode::Line(start..end);
2405 auto_scroll = true;
2406 }
2407 _ => {
2408 start = buffer.anchor_before(0);
2409 end = buffer.anchor_before(buffer.len());
2410 mode = SelectMode::All;
2411 auto_scroll = false;
2412 }
2413 }
2414 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2415
2416 let point_to_delete: Option<usize> = {
2417 let selected_points: Vec<Selection<Point>> =
2418 self.selections.disjoint_in_range(start..end, cx);
2419
2420 if !add || click_count > 1 {
2421 None
2422 } else if !selected_points.is_empty() {
2423 Some(selected_points[0].id)
2424 } else {
2425 let clicked_point_already_selected =
2426 self.selections.disjoint.iter().find(|selection| {
2427 selection.start.to_point(buffer) == start.to_point(buffer)
2428 || selection.end.to_point(buffer) == end.to_point(buffer)
2429 });
2430
2431 clicked_point_already_selected.map(|selection| selection.id)
2432 }
2433 };
2434
2435 let selections_count = self.selections.count();
2436
2437 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2438 if let Some(point_to_delete) = point_to_delete {
2439 s.delete(point_to_delete);
2440
2441 if selections_count == 1 {
2442 s.set_pending_anchor_range(start..end, mode);
2443 }
2444 } else {
2445 if !add {
2446 s.clear_disjoint();
2447 } else if click_count > 1 {
2448 s.delete(newest_selection.id)
2449 }
2450
2451 s.set_pending_anchor_range(start..end, mode);
2452 }
2453 });
2454 }
2455
2456 fn begin_columnar_selection(
2457 &mut self,
2458 position: DisplayPoint,
2459 goal_column: u32,
2460 reset: bool,
2461 window: &mut Window,
2462 cx: &mut Context<Self>,
2463 ) {
2464 if !self.focus_handle.is_focused(window) {
2465 self.last_focused_descendant = None;
2466 window.focus(&self.focus_handle);
2467 }
2468
2469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2470
2471 if reset {
2472 let pointer_position = display_map
2473 .buffer_snapshot
2474 .anchor_before(position.to_point(&display_map));
2475
2476 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2477 s.clear_disjoint();
2478 s.set_pending_anchor_range(
2479 pointer_position..pointer_position,
2480 SelectMode::Character,
2481 );
2482 });
2483 }
2484
2485 let tail = self.selections.newest::<Point>(cx).tail();
2486 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2487
2488 if !reset {
2489 self.select_columns(
2490 tail.to_display_point(&display_map),
2491 position,
2492 goal_column,
2493 &display_map,
2494 window,
2495 cx,
2496 );
2497 }
2498 }
2499
2500 fn update_selection(
2501 &mut self,
2502 position: DisplayPoint,
2503 goal_column: u32,
2504 scroll_delta: gpui::Point<f32>,
2505 window: &mut Window,
2506 cx: &mut Context<Self>,
2507 ) {
2508 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2509
2510 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2511 let tail = tail.to_display_point(&display_map);
2512 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2513 } else if let Some(mut pending) = self.selections.pending_anchor() {
2514 let buffer = self.buffer.read(cx).snapshot(cx);
2515 let head;
2516 let tail;
2517 let mode = self.selections.pending_mode().unwrap();
2518 match &mode {
2519 SelectMode::Character => {
2520 head = position.to_point(&display_map);
2521 tail = pending.tail().to_point(&buffer);
2522 }
2523 SelectMode::Word(original_range) => {
2524 let original_display_range = original_range.start.to_display_point(&display_map)
2525 ..original_range.end.to_display_point(&display_map);
2526 let original_buffer_range = original_display_range.start.to_point(&display_map)
2527 ..original_display_range.end.to_point(&display_map);
2528 if movement::is_inside_word(&display_map, position)
2529 || original_display_range.contains(&position)
2530 {
2531 let word_range = movement::surrounding_word(&display_map, position);
2532 if word_range.start < original_display_range.start {
2533 head = word_range.start.to_point(&display_map);
2534 } else {
2535 head = word_range.end.to_point(&display_map);
2536 }
2537 } else {
2538 head = position.to_point(&display_map);
2539 }
2540
2541 if head <= original_buffer_range.start {
2542 tail = original_buffer_range.end;
2543 } else {
2544 tail = original_buffer_range.start;
2545 }
2546 }
2547 SelectMode::Line(original_range) => {
2548 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2549
2550 let position = display_map
2551 .clip_point(position, Bias::Left)
2552 .to_point(&display_map);
2553 let line_start = display_map.prev_line_boundary(position).0;
2554 let next_line_start = buffer.clip_point(
2555 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2556 Bias::Left,
2557 );
2558
2559 if line_start < original_range.start {
2560 head = line_start
2561 } else {
2562 head = next_line_start
2563 }
2564
2565 if head <= original_range.start {
2566 tail = original_range.end;
2567 } else {
2568 tail = original_range.start;
2569 }
2570 }
2571 SelectMode::All => {
2572 return;
2573 }
2574 };
2575
2576 if head < tail {
2577 pending.start = buffer.anchor_before(head);
2578 pending.end = buffer.anchor_before(tail);
2579 pending.reversed = true;
2580 } else {
2581 pending.start = buffer.anchor_before(tail);
2582 pending.end = buffer.anchor_before(head);
2583 pending.reversed = false;
2584 }
2585
2586 self.change_selections(None, window, cx, |s| {
2587 s.set_pending(pending, mode);
2588 });
2589 } else {
2590 log::error!("update_selection dispatched with no pending selection");
2591 return;
2592 }
2593
2594 self.apply_scroll_delta(scroll_delta, window, cx);
2595 cx.notify();
2596 }
2597
2598 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2599 self.columnar_selection_tail.take();
2600 if self.selections.pending_anchor().is_some() {
2601 let selections = self.selections.all::<usize>(cx);
2602 self.change_selections(None, window, cx, |s| {
2603 s.select(selections);
2604 s.clear_pending();
2605 });
2606 }
2607 }
2608
2609 fn select_columns(
2610 &mut self,
2611 tail: DisplayPoint,
2612 head: DisplayPoint,
2613 goal_column: u32,
2614 display_map: &DisplaySnapshot,
2615 window: &mut Window,
2616 cx: &mut Context<Self>,
2617 ) {
2618 let start_row = cmp::min(tail.row(), head.row());
2619 let end_row = cmp::max(tail.row(), head.row());
2620 let start_column = cmp::min(tail.column(), goal_column);
2621 let end_column = cmp::max(tail.column(), goal_column);
2622 let reversed = start_column < tail.column();
2623
2624 let selection_ranges = (start_row.0..=end_row.0)
2625 .map(DisplayRow)
2626 .filter_map(|row| {
2627 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2628 let start = display_map
2629 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2630 .to_point(display_map);
2631 let end = display_map
2632 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2633 .to_point(display_map);
2634 if reversed {
2635 Some(end..start)
2636 } else {
2637 Some(start..end)
2638 }
2639 } else {
2640 None
2641 }
2642 })
2643 .collect::<Vec<_>>();
2644
2645 self.change_selections(None, window, cx, |s| {
2646 s.select_ranges(selection_ranges);
2647 });
2648 cx.notify();
2649 }
2650
2651 pub fn has_pending_nonempty_selection(&self) -> bool {
2652 let pending_nonempty_selection = match self.selections.pending_anchor() {
2653 Some(Selection { start, end, .. }) => start != end,
2654 None => false,
2655 };
2656
2657 pending_nonempty_selection
2658 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2659 }
2660
2661 pub fn has_pending_selection(&self) -> bool {
2662 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2663 }
2664
2665 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2666 self.selection_mark_mode = false;
2667
2668 if self.clear_expanded_diff_hunks(cx) {
2669 cx.notify();
2670 return;
2671 }
2672 if self.dismiss_menus_and_popups(true, window, cx) {
2673 return;
2674 }
2675
2676 if self.mode == EditorMode::Full
2677 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2678 {
2679 return;
2680 }
2681
2682 cx.propagate();
2683 }
2684
2685 pub fn dismiss_menus_and_popups(
2686 &mut self,
2687 is_user_requested: bool,
2688 window: &mut Window,
2689 cx: &mut Context<Self>,
2690 ) -> bool {
2691 if self.take_rename(false, window, cx).is_some() {
2692 return true;
2693 }
2694
2695 if hide_hover(self, cx) {
2696 return true;
2697 }
2698
2699 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2700 return true;
2701 }
2702
2703 if self.hide_context_menu(window, cx).is_some() {
2704 return true;
2705 }
2706
2707 if self.mouse_context_menu.take().is_some() {
2708 return true;
2709 }
2710
2711 if is_user_requested && self.discard_inline_completion(true, cx) {
2712 return true;
2713 }
2714
2715 if self.snippet_stack.pop().is_some() {
2716 return true;
2717 }
2718
2719 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2720 self.dismiss_diagnostics(cx);
2721 return true;
2722 }
2723
2724 false
2725 }
2726
2727 fn linked_editing_ranges_for(
2728 &self,
2729 selection: Range<text::Anchor>,
2730 cx: &App,
2731 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2732 if self.linked_edit_ranges.is_empty() {
2733 return None;
2734 }
2735 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2736 selection.end.buffer_id.and_then(|end_buffer_id| {
2737 if selection.start.buffer_id != Some(end_buffer_id) {
2738 return None;
2739 }
2740 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2741 let snapshot = buffer.read(cx).snapshot();
2742 self.linked_edit_ranges
2743 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2744 .map(|ranges| (ranges, snapshot, buffer))
2745 })?;
2746 use text::ToOffset as TO;
2747 // find offset from the start of current range to current cursor position
2748 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2749
2750 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2751 let start_difference = start_offset - start_byte_offset;
2752 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2753 let end_difference = end_offset - start_byte_offset;
2754 // Current range has associated linked ranges.
2755 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2756 for range in linked_ranges.iter() {
2757 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2758 let end_offset = start_offset + end_difference;
2759 let start_offset = start_offset + start_difference;
2760 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2761 continue;
2762 }
2763 if self.selections.disjoint_anchor_ranges().any(|s| {
2764 if s.start.buffer_id != selection.start.buffer_id
2765 || s.end.buffer_id != selection.end.buffer_id
2766 {
2767 return false;
2768 }
2769 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2770 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2771 }) {
2772 continue;
2773 }
2774 let start = buffer_snapshot.anchor_after(start_offset);
2775 let end = buffer_snapshot.anchor_after(end_offset);
2776 linked_edits
2777 .entry(buffer.clone())
2778 .or_default()
2779 .push(start..end);
2780 }
2781 Some(linked_edits)
2782 }
2783
2784 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2785 let text: Arc<str> = text.into();
2786
2787 if self.read_only(cx) {
2788 return;
2789 }
2790
2791 let selections = self.selections.all_adjusted(cx);
2792 let mut bracket_inserted = false;
2793 let mut edits = Vec::new();
2794 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2795 let mut new_selections = Vec::with_capacity(selections.len());
2796 let mut new_autoclose_regions = Vec::new();
2797 let snapshot = self.buffer.read(cx).read(cx);
2798
2799 for (selection, autoclose_region) in
2800 self.selections_with_autoclose_regions(selections, &snapshot)
2801 {
2802 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2803 // Determine if the inserted text matches the opening or closing
2804 // bracket of any of this language's bracket pairs.
2805 let mut bracket_pair = None;
2806 let mut is_bracket_pair_start = false;
2807 let mut is_bracket_pair_end = false;
2808 if !text.is_empty() {
2809 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2810 // and they are removing the character that triggered IME popup.
2811 for (pair, enabled) in scope.brackets() {
2812 if !pair.close && !pair.surround {
2813 continue;
2814 }
2815
2816 if enabled && pair.start.ends_with(text.as_ref()) {
2817 let prefix_len = pair.start.len() - text.len();
2818 let preceding_text_matches_prefix = prefix_len == 0
2819 || (selection.start.column >= (prefix_len as u32)
2820 && snapshot.contains_str_at(
2821 Point::new(
2822 selection.start.row,
2823 selection.start.column - (prefix_len as u32),
2824 ),
2825 &pair.start[..prefix_len],
2826 ));
2827 if preceding_text_matches_prefix {
2828 bracket_pair = Some(pair.clone());
2829 is_bracket_pair_start = true;
2830 break;
2831 }
2832 }
2833 if pair.end.as_str() == text.as_ref() {
2834 bracket_pair = Some(pair.clone());
2835 is_bracket_pair_end = true;
2836 break;
2837 }
2838 }
2839 }
2840
2841 if let Some(bracket_pair) = bracket_pair {
2842 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2843 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2844 let auto_surround =
2845 self.use_auto_surround && snapshot_settings.use_auto_surround;
2846 if selection.is_empty() {
2847 if is_bracket_pair_start {
2848 // If the inserted text is a suffix of an opening bracket and the
2849 // selection is preceded by the rest of the opening bracket, then
2850 // insert the closing bracket.
2851 let following_text_allows_autoclose = snapshot
2852 .chars_at(selection.start)
2853 .next()
2854 .map_or(true, |c| scope.should_autoclose_before(c));
2855
2856 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2857 && bracket_pair.start.len() == 1
2858 {
2859 let target = bracket_pair.start.chars().next().unwrap();
2860 let current_line_count = snapshot
2861 .reversed_chars_at(selection.start)
2862 .take_while(|&c| c != '\n')
2863 .filter(|&c| c == target)
2864 .count();
2865 current_line_count % 2 == 1
2866 } else {
2867 false
2868 };
2869
2870 if autoclose
2871 && bracket_pair.close
2872 && following_text_allows_autoclose
2873 && !is_closing_quote
2874 {
2875 let anchor = snapshot.anchor_before(selection.end);
2876 new_selections.push((selection.map(|_| anchor), text.len()));
2877 new_autoclose_regions.push((
2878 anchor,
2879 text.len(),
2880 selection.id,
2881 bracket_pair.clone(),
2882 ));
2883 edits.push((
2884 selection.range(),
2885 format!("{}{}", text, bracket_pair.end).into(),
2886 ));
2887 bracket_inserted = true;
2888 continue;
2889 }
2890 }
2891
2892 if let Some(region) = autoclose_region {
2893 // If the selection is followed by an auto-inserted closing bracket,
2894 // then don't insert that closing bracket again; just move the selection
2895 // past the closing bracket.
2896 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2897 && text.as_ref() == region.pair.end.as_str();
2898 if should_skip {
2899 let anchor = snapshot.anchor_after(selection.end);
2900 new_selections
2901 .push((selection.map(|_| anchor), region.pair.end.len()));
2902 continue;
2903 }
2904 }
2905
2906 let always_treat_brackets_as_autoclosed = snapshot
2907 .settings_at(selection.start, cx)
2908 .always_treat_brackets_as_autoclosed;
2909 if always_treat_brackets_as_autoclosed
2910 && is_bracket_pair_end
2911 && snapshot.contains_str_at(selection.end, text.as_ref())
2912 {
2913 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2914 // and the inserted text is a closing bracket and the selection is followed
2915 // by the closing bracket then move the selection past the closing bracket.
2916 let anchor = snapshot.anchor_after(selection.end);
2917 new_selections.push((selection.map(|_| anchor), text.len()));
2918 continue;
2919 }
2920 }
2921 // If an opening bracket is 1 character long and is typed while
2922 // text is selected, then surround that text with the bracket pair.
2923 else if auto_surround
2924 && bracket_pair.surround
2925 && is_bracket_pair_start
2926 && bracket_pair.start.chars().count() == 1
2927 {
2928 edits.push((selection.start..selection.start, text.clone()));
2929 edits.push((
2930 selection.end..selection.end,
2931 bracket_pair.end.as_str().into(),
2932 ));
2933 bracket_inserted = true;
2934 new_selections.push((
2935 Selection {
2936 id: selection.id,
2937 start: snapshot.anchor_after(selection.start),
2938 end: snapshot.anchor_before(selection.end),
2939 reversed: selection.reversed,
2940 goal: selection.goal,
2941 },
2942 0,
2943 ));
2944 continue;
2945 }
2946 }
2947 }
2948
2949 if self.auto_replace_emoji_shortcode
2950 && selection.is_empty()
2951 && text.as_ref().ends_with(':')
2952 {
2953 if let Some(possible_emoji_short_code) =
2954 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2955 {
2956 if !possible_emoji_short_code.is_empty() {
2957 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2958 let emoji_shortcode_start = Point::new(
2959 selection.start.row,
2960 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2961 );
2962
2963 // Remove shortcode from buffer
2964 edits.push((
2965 emoji_shortcode_start..selection.start,
2966 "".to_string().into(),
2967 ));
2968 new_selections.push((
2969 Selection {
2970 id: selection.id,
2971 start: snapshot.anchor_after(emoji_shortcode_start),
2972 end: snapshot.anchor_before(selection.start),
2973 reversed: selection.reversed,
2974 goal: selection.goal,
2975 },
2976 0,
2977 ));
2978
2979 // Insert emoji
2980 let selection_start_anchor = snapshot.anchor_after(selection.start);
2981 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2982 edits.push((selection.start..selection.end, emoji.to_string().into()));
2983
2984 continue;
2985 }
2986 }
2987 }
2988 }
2989
2990 // If not handling any auto-close operation, then just replace the selected
2991 // text with the given input and move the selection to the end of the
2992 // newly inserted text.
2993 let anchor = snapshot.anchor_after(selection.end);
2994 if !self.linked_edit_ranges.is_empty() {
2995 let start_anchor = snapshot.anchor_before(selection.start);
2996
2997 let is_word_char = text.chars().next().map_or(true, |char| {
2998 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2999 classifier.is_word(char)
3000 });
3001
3002 if is_word_char {
3003 if let Some(ranges) = self
3004 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3005 {
3006 for (buffer, edits) in ranges {
3007 linked_edits
3008 .entry(buffer.clone())
3009 .or_default()
3010 .extend(edits.into_iter().map(|range| (range, text.clone())));
3011 }
3012 }
3013 }
3014 }
3015
3016 new_selections.push((selection.map(|_| anchor), 0));
3017 edits.push((selection.start..selection.end, text.clone()));
3018 }
3019
3020 drop(snapshot);
3021
3022 self.transact(window, cx, |this, window, cx| {
3023 this.buffer.update(cx, |buffer, cx| {
3024 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3025 });
3026 for (buffer, edits) in linked_edits {
3027 buffer.update(cx, |buffer, cx| {
3028 let snapshot = buffer.snapshot();
3029 let edits = edits
3030 .into_iter()
3031 .map(|(range, text)| {
3032 use text::ToPoint as TP;
3033 let end_point = TP::to_point(&range.end, &snapshot);
3034 let start_point = TP::to_point(&range.start, &snapshot);
3035 (start_point..end_point, text)
3036 })
3037 .sorted_by_key(|(range, _)| range.start)
3038 .collect::<Vec<_>>();
3039 buffer.edit(edits, None, cx);
3040 })
3041 }
3042 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3043 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3044 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3045 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3046 .zip(new_selection_deltas)
3047 .map(|(selection, delta)| Selection {
3048 id: selection.id,
3049 start: selection.start + delta,
3050 end: selection.end + delta,
3051 reversed: selection.reversed,
3052 goal: SelectionGoal::None,
3053 })
3054 .collect::<Vec<_>>();
3055
3056 let mut i = 0;
3057 for (position, delta, selection_id, pair) in new_autoclose_regions {
3058 let position = position.to_offset(&map.buffer_snapshot) + delta;
3059 let start = map.buffer_snapshot.anchor_before(position);
3060 let end = map.buffer_snapshot.anchor_after(position);
3061 while let Some(existing_state) = this.autoclose_regions.get(i) {
3062 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3063 Ordering::Less => i += 1,
3064 Ordering::Greater => break,
3065 Ordering::Equal => {
3066 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3067 Ordering::Less => i += 1,
3068 Ordering::Equal => break,
3069 Ordering::Greater => break,
3070 }
3071 }
3072 }
3073 }
3074 this.autoclose_regions.insert(
3075 i,
3076 AutocloseRegion {
3077 selection_id,
3078 range: start..end,
3079 pair,
3080 },
3081 );
3082 }
3083
3084 let had_active_inline_completion = this.has_active_inline_completion();
3085 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3086 s.select(new_selections)
3087 });
3088
3089 if !bracket_inserted {
3090 if let Some(on_type_format_task) =
3091 this.trigger_on_type_formatting(text.to_string(), window, cx)
3092 {
3093 on_type_format_task.detach_and_log_err(cx);
3094 }
3095 }
3096
3097 let editor_settings = EditorSettings::get_global(cx);
3098 if bracket_inserted
3099 && (editor_settings.auto_signature_help
3100 || editor_settings.show_signature_help_after_edits)
3101 {
3102 this.show_signature_help(&ShowSignatureHelp, window, cx);
3103 }
3104
3105 let trigger_in_words =
3106 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3107 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3108 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3109 this.refresh_inline_completion(true, false, window, cx);
3110 });
3111 }
3112
3113 fn find_possible_emoji_shortcode_at_position(
3114 snapshot: &MultiBufferSnapshot,
3115 position: Point,
3116 ) -> Option<String> {
3117 let mut chars = Vec::new();
3118 let mut found_colon = false;
3119 for char in snapshot.reversed_chars_at(position).take(100) {
3120 // Found a possible emoji shortcode in the middle of the buffer
3121 if found_colon {
3122 if char.is_whitespace() {
3123 chars.reverse();
3124 return Some(chars.iter().collect());
3125 }
3126 // If the previous character is not a whitespace, we are in the middle of a word
3127 // and we only want to complete the shortcode if the word is made up of other emojis
3128 let mut containing_word = String::new();
3129 for ch in snapshot
3130 .reversed_chars_at(position)
3131 .skip(chars.len() + 1)
3132 .take(100)
3133 {
3134 if ch.is_whitespace() {
3135 break;
3136 }
3137 containing_word.push(ch);
3138 }
3139 let containing_word = containing_word.chars().rev().collect::<String>();
3140 if util::word_consists_of_emojis(containing_word.as_str()) {
3141 chars.reverse();
3142 return Some(chars.iter().collect());
3143 }
3144 }
3145
3146 if char.is_whitespace() || !char.is_ascii() {
3147 return None;
3148 }
3149 if char == ':' {
3150 found_colon = true;
3151 } else {
3152 chars.push(char);
3153 }
3154 }
3155 // Found a possible emoji shortcode at the beginning of the buffer
3156 chars.reverse();
3157 Some(chars.iter().collect())
3158 }
3159
3160 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3161 self.transact(window, cx, |this, window, cx| {
3162 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3163 let selections = this.selections.all::<usize>(cx);
3164 let multi_buffer = this.buffer.read(cx);
3165 let buffer = multi_buffer.snapshot(cx);
3166 selections
3167 .iter()
3168 .map(|selection| {
3169 let start_point = selection.start.to_point(&buffer);
3170 let mut indent =
3171 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3172 indent.len = cmp::min(indent.len, start_point.column);
3173 let start = selection.start;
3174 let end = selection.end;
3175 let selection_is_empty = start == end;
3176 let language_scope = buffer.language_scope_at(start);
3177 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3178 &language_scope
3179 {
3180 let insert_extra_newline =
3181 insert_extra_newline_brackets(&buffer, start..end, language)
3182 || insert_extra_newline_tree_sitter(&buffer, start..end);
3183
3184 // Comment extension on newline is allowed only for cursor selections
3185 let comment_delimiter = maybe!({
3186 if !selection_is_empty {
3187 return None;
3188 }
3189
3190 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3191 return None;
3192 }
3193
3194 let delimiters = language.line_comment_prefixes();
3195 let max_len_of_delimiter =
3196 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3197 let (snapshot, range) =
3198 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3199
3200 let mut index_of_first_non_whitespace = 0;
3201 let comment_candidate = snapshot
3202 .chars_for_range(range)
3203 .skip_while(|c| {
3204 let should_skip = c.is_whitespace();
3205 if should_skip {
3206 index_of_first_non_whitespace += 1;
3207 }
3208 should_skip
3209 })
3210 .take(max_len_of_delimiter)
3211 .collect::<String>();
3212 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3213 comment_candidate.starts_with(comment_prefix.as_ref())
3214 })?;
3215 let cursor_is_placed_after_comment_marker =
3216 index_of_first_non_whitespace + comment_prefix.len()
3217 <= start_point.column as usize;
3218 if cursor_is_placed_after_comment_marker {
3219 Some(comment_prefix.clone())
3220 } else {
3221 None
3222 }
3223 });
3224 (comment_delimiter, insert_extra_newline)
3225 } else {
3226 (None, false)
3227 };
3228
3229 let capacity_for_delimiter = comment_delimiter
3230 .as_deref()
3231 .map(str::len)
3232 .unwrap_or_default();
3233 let mut new_text =
3234 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3235 new_text.push('\n');
3236 new_text.extend(indent.chars());
3237 if let Some(delimiter) = &comment_delimiter {
3238 new_text.push_str(delimiter);
3239 }
3240 if insert_extra_newline {
3241 new_text = new_text.repeat(2);
3242 }
3243
3244 let anchor = buffer.anchor_after(end);
3245 let new_selection = selection.map(|_| anchor);
3246 (
3247 (start..end, new_text),
3248 (insert_extra_newline, new_selection),
3249 )
3250 })
3251 .unzip()
3252 };
3253
3254 this.edit_with_autoindent(edits, cx);
3255 let buffer = this.buffer.read(cx).snapshot(cx);
3256 let new_selections = selection_fixup_info
3257 .into_iter()
3258 .map(|(extra_newline_inserted, new_selection)| {
3259 let mut cursor = new_selection.end.to_point(&buffer);
3260 if extra_newline_inserted {
3261 cursor.row -= 1;
3262 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3263 }
3264 new_selection.map(|_| cursor)
3265 })
3266 .collect();
3267
3268 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3269 s.select(new_selections)
3270 });
3271 this.refresh_inline_completion(true, false, window, cx);
3272 });
3273 }
3274
3275 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3276 let buffer = self.buffer.read(cx);
3277 let snapshot = buffer.snapshot(cx);
3278
3279 let mut edits = Vec::new();
3280 let mut rows = Vec::new();
3281
3282 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3283 let cursor = selection.head();
3284 let row = cursor.row;
3285
3286 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3287
3288 let newline = "\n".to_string();
3289 edits.push((start_of_line..start_of_line, newline));
3290
3291 rows.push(row + rows_inserted as u32);
3292 }
3293
3294 self.transact(window, cx, |editor, window, cx| {
3295 editor.edit(edits, cx);
3296
3297 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3298 let mut index = 0;
3299 s.move_cursors_with(|map, _, _| {
3300 let row = rows[index];
3301 index += 1;
3302
3303 let point = Point::new(row, 0);
3304 let boundary = map.next_line_boundary(point).1;
3305 let clipped = map.clip_point(boundary, Bias::Left);
3306
3307 (clipped, SelectionGoal::None)
3308 });
3309 });
3310
3311 let mut indent_edits = Vec::new();
3312 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3313 for row in rows {
3314 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3315 for (row, indent) in indents {
3316 if indent.len == 0 {
3317 continue;
3318 }
3319
3320 let text = match indent.kind {
3321 IndentKind::Space => " ".repeat(indent.len as usize),
3322 IndentKind::Tab => "\t".repeat(indent.len as usize),
3323 };
3324 let point = Point::new(row.0, 0);
3325 indent_edits.push((point..point, text));
3326 }
3327 }
3328 editor.edit(indent_edits, cx);
3329 });
3330 }
3331
3332 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3333 let buffer = self.buffer.read(cx);
3334 let snapshot = buffer.snapshot(cx);
3335
3336 let mut edits = Vec::new();
3337 let mut rows = Vec::new();
3338 let mut rows_inserted = 0;
3339
3340 for selection in self.selections.all_adjusted(cx) {
3341 let cursor = selection.head();
3342 let row = cursor.row;
3343
3344 let point = Point::new(row + 1, 0);
3345 let start_of_line = snapshot.clip_point(point, Bias::Left);
3346
3347 let newline = "\n".to_string();
3348 edits.push((start_of_line..start_of_line, newline));
3349
3350 rows_inserted += 1;
3351 rows.push(row + rows_inserted);
3352 }
3353
3354 self.transact(window, cx, |editor, window, cx| {
3355 editor.edit(edits, cx);
3356
3357 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3358 let mut index = 0;
3359 s.move_cursors_with(|map, _, _| {
3360 let row = rows[index];
3361 index += 1;
3362
3363 let point = Point::new(row, 0);
3364 let boundary = map.next_line_boundary(point).1;
3365 let clipped = map.clip_point(boundary, Bias::Left);
3366
3367 (clipped, SelectionGoal::None)
3368 });
3369 });
3370
3371 let mut indent_edits = Vec::new();
3372 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3373 for row in rows {
3374 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3375 for (row, indent) in indents {
3376 if indent.len == 0 {
3377 continue;
3378 }
3379
3380 let text = match indent.kind {
3381 IndentKind::Space => " ".repeat(indent.len as usize),
3382 IndentKind::Tab => "\t".repeat(indent.len as usize),
3383 };
3384 let point = Point::new(row.0, 0);
3385 indent_edits.push((point..point, text));
3386 }
3387 }
3388 editor.edit(indent_edits, cx);
3389 });
3390 }
3391
3392 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3393 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3394 original_start_columns: Vec::new(),
3395 });
3396 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3397 }
3398
3399 fn insert_with_autoindent_mode(
3400 &mut self,
3401 text: &str,
3402 autoindent_mode: Option<AutoindentMode>,
3403 window: &mut Window,
3404 cx: &mut Context<Self>,
3405 ) {
3406 if self.read_only(cx) {
3407 return;
3408 }
3409
3410 let text: Arc<str> = text.into();
3411 self.transact(window, cx, |this, window, cx| {
3412 let old_selections = this.selections.all_adjusted(cx);
3413 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3414 let anchors = {
3415 let snapshot = buffer.read(cx);
3416 old_selections
3417 .iter()
3418 .map(|s| {
3419 let anchor = snapshot.anchor_after(s.head());
3420 s.map(|_| anchor)
3421 })
3422 .collect::<Vec<_>>()
3423 };
3424 buffer.edit(
3425 old_selections
3426 .iter()
3427 .map(|s| (s.start..s.end, text.clone())),
3428 autoindent_mode,
3429 cx,
3430 );
3431 anchors
3432 });
3433
3434 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3435 s.select_anchors(selection_anchors);
3436 });
3437
3438 cx.notify();
3439 });
3440 }
3441
3442 fn trigger_completion_on_input(
3443 &mut self,
3444 text: &str,
3445 trigger_in_words: bool,
3446 window: &mut Window,
3447 cx: &mut Context<Self>,
3448 ) {
3449 if self.is_completion_trigger(text, trigger_in_words, cx) {
3450 self.show_completions(
3451 &ShowCompletions {
3452 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3453 },
3454 window,
3455 cx,
3456 );
3457 } else {
3458 self.hide_context_menu(window, cx);
3459 }
3460 }
3461
3462 fn is_completion_trigger(
3463 &self,
3464 text: &str,
3465 trigger_in_words: bool,
3466 cx: &mut Context<Self>,
3467 ) -> bool {
3468 let position = self.selections.newest_anchor().head();
3469 let multibuffer = self.buffer.read(cx);
3470 let Some(buffer) = position
3471 .buffer_id
3472 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3473 else {
3474 return false;
3475 };
3476
3477 if let Some(completion_provider) = &self.completion_provider {
3478 completion_provider.is_completion_trigger(
3479 &buffer,
3480 position.text_anchor,
3481 text,
3482 trigger_in_words,
3483 cx,
3484 )
3485 } else {
3486 false
3487 }
3488 }
3489
3490 /// If any empty selections is touching the start of its innermost containing autoclose
3491 /// region, expand it to select the brackets.
3492 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3493 let selections = self.selections.all::<usize>(cx);
3494 let buffer = self.buffer.read(cx).read(cx);
3495 let new_selections = self
3496 .selections_with_autoclose_regions(selections, &buffer)
3497 .map(|(mut selection, region)| {
3498 if !selection.is_empty() {
3499 return selection;
3500 }
3501
3502 if let Some(region) = region {
3503 let mut range = region.range.to_offset(&buffer);
3504 if selection.start == range.start && range.start >= region.pair.start.len() {
3505 range.start -= region.pair.start.len();
3506 if buffer.contains_str_at(range.start, ®ion.pair.start)
3507 && buffer.contains_str_at(range.end, ®ion.pair.end)
3508 {
3509 range.end += region.pair.end.len();
3510 selection.start = range.start;
3511 selection.end = range.end;
3512
3513 return selection;
3514 }
3515 }
3516 }
3517
3518 let always_treat_brackets_as_autoclosed = buffer
3519 .settings_at(selection.start, cx)
3520 .always_treat_brackets_as_autoclosed;
3521
3522 if !always_treat_brackets_as_autoclosed {
3523 return selection;
3524 }
3525
3526 if let Some(scope) = buffer.language_scope_at(selection.start) {
3527 for (pair, enabled) in scope.brackets() {
3528 if !enabled || !pair.close {
3529 continue;
3530 }
3531
3532 if buffer.contains_str_at(selection.start, &pair.end) {
3533 let pair_start_len = pair.start.len();
3534 if buffer.contains_str_at(
3535 selection.start.saturating_sub(pair_start_len),
3536 &pair.start,
3537 ) {
3538 selection.start -= pair_start_len;
3539 selection.end += pair.end.len();
3540
3541 return selection;
3542 }
3543 }
3544 }
3545 }
3546
3547 selection
3548 })
3549 .collect();
3550
3551 drop(buffer);
3552 self.change_selections(None, window, cx, |selections| {
3553 selections.select(new_selections)
3554 });
3555 }
3556
3557 /// Iterate the given selections, and for each one, find the smallest surrounding
3558 /// autoclose region. This uses the ordering of the selections and the autoclose
3559 /// regions to avoid repeated comparisons.
3560 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3561 &'a self,
3562 selections: impl IntoIterator<Item = Selection<D>>,
3563 buffer: &'a MultiBufferSnapshot,
3564 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3565 let mut i = 0;
3566 let mut regions = self.autoclose_regions.as_slice();
3567 selections.into_iter().map(move |selection| {
3568 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3569
3570 let mut enclosing = None;
3571 while let Some(pair_state) = regions.get(i) {
3572 if pair_state.range.end.to_offset(buffer) < range.start {
3573 regions = ®ions[i + 1..];
3574 i = 0;
3575 } else if pair_state.range.start.to_offset(buffer) > range.end {
3576 break;
3577 } else {
3578 if pair_state.selection_id == selection.id {
3579 enclosing = Some(pair_state);
3580 }
3581 i += 1;
3582 }
3583 }
3584
3585 (selection, enclosing)
3586 })
3587 }
3588
3589 /// Remove any autoclose regions that no longer contain their selection.
3590 fn invalidate_autoclose_regions(
3591 &mut self,
3592 mut selections: &[Selection<Anchor>],
3593 buffer: &MultiBufferSnapshot,
3594 ) {
3595 self.autoclose_regions.retain(|state| {
3596 let mut i = 0;
3597 while let Some(selection) = selections.get(i) {
3598 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3599 selections = &selections[1..];
3600 continue;
3601 }
3602 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3603 break;
3604 }
3605 if selection.id == state.selection_id {
3606 return true;
3607 } else {
3608 i += 1;
3609 }
3610 }
3611 false
3612 });
3613 }
3614
3615 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3616 let offset = position.to_offset(buffer);
3617 let (word_range, kind) = buffer.surrounding_word(offset, true);
3618 if offset > word_range.start && kind == Some(CharKind::Word) {
3619 Some(
3620 buffer
3621 .text_for_range(word_range.start..offset)
3622 .collect::<String>(),
3623 )
3624 } else {
3625 None
3626 }
3627 }
3628
3629 pub fn toggle_inlay_hints(
3630 &mut self,
3631 _: &ToggleInlayHints,
3632 _: &mut Window,
3633 cx: &mut Context<Self>,
3634 ) {
3635 self.refresh_inlay_hints(
3636 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3637 cx,
3638 );
3639 }
3640
3641 pub fn inlay_hints_enabled(&self) -> bool {
3642 self.inlay_hint_cache.enabled
3643 }
3644
3645 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3646 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3647 return;
3648 }
3649
3650 let reason_description = reason.description();
3651 let ignore_debounce = matches!(
3652 reason,
3653 InlayHintRefreshReason::SettingsChange(_)
3654 | InlayHintRefreshReason::Toggle(_)
3655 | InlayHintRefreshReason::ExcerptsRemoved(_)
3656 );
3657 let (invalidate_cache, required_languages) = match reason {
3658 InlayHintRefreshReason::Toggle(enabled) => {
3659 self.inlay_hint_cache.enabled = enabled;
3660 if enabled {
3661 (InvalidationStrategy::RefreshRequested, None)
3662 } else {
3663 self.inlay_hint_cache.clear();
3664 self.splice_inlays(
3665 &self
3666 .visible_inlay_hints(cx)
3667 .iter()
3668 .map(|inlay| inlay.id)
3669 .collect::<Vec<InlayId>>(),
3670 Vec::new(),
3671 cx,
3672 );
3673 return;
3674 }
3675 }
3676 InlayHintRefreshReason::SettingsChange(new_settings) => {
3677 match self.inlay_hint_cache.update_settings(
3678 &self.buffer,
3679 new_settings,
3680 self.visible_inlay_hints(cx),
3681 cx,
3682 ) {
3683 ControlFlow::Break(Some(InlaySplice {
3684 to_remove,
3685 to_insert,
3686 })) => {
3687 self.splice_inlays(&to_remove, to_insert, cx);
3688 return;
3689 }
3690 ControlFlow::Break(None) => return,
3691 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3692 }
3693 }
3694 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3695 if let Some(InlaySplice {
3696 to_remove,
3697 to_insert,
3698 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3699 {
3700 self.splice_inlays(&to_remove, to_insert, cx);
3701 }
3702 return;
3703 }
3704 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3705 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3706 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3707 }
3708 InlayHintRefreshReason::RefreshRequested => {
3709 (InvalidationStrategy::RefreshRequested, None)
3710 }
3711 };
3712
3713 if let Some(InlaySplice {
3714 to_remove,
3715 to_insert,
3716 }) = self.inlay_hint_cache.spawn_hint_refresh(
3717 reason_description,
3718 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3719 invalidate_cache,
3720 ignore_debounce,
3721 cx,
3722 ) {
3723 self.splice_inlays(&to_remove, to_insert, cx);
3724 }
3725 }
3726
3727 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3728 self.display_map
3729 .read(cx)
3730 .current_inlays()
3731 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3732 .cloned()
3733 .collect()
3734 }
3735
3736 pub fn excerpts_for_inlay_hints_query(
3737 &self,
3738 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3739 cx: &mut Context<Editor>,
3740 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3741 let Some(project) = self.project.as_ref() else {
3742 return HashMap::default();
3743 };
3744 let project = project.read(cx);
3745 let multi_buffer = self.buffer().read(cx);
3746 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3747 let multi_buffer_visible_start = self
3748 .scroll_manager
3749 .anchor()
3750 .anchor
3751 .to_point(&multi_buffer_snapshot);
3752 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3753 multi_buffer_visible_start
3754 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3755 Bias::Left,
3756 );
3757 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3758 multi_buffer_snapshot
3759 .range_to_buffer_ranges(multi_buffer_visible_range)
3760 .into_iter()
3761 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3762 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3763 let buffer_file = project::File::from_dyn(buffer.file())?;
3764 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3765 let worktree_entry = buffer_worktree
3766 .read(cx)
3767 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3768 if worktree_entry.is_ignored {
3769 return None;
3770 }
3771
3772 let language = buffer.language()?;
3773 if let Some(restrict_to_languages) = restrict_to_languages {
3774 if !restrict_to_languages.contains(language) {
3775 return None;
3776 }
3777 }
3778 Some((
3779 excerpt_id,
3780 (
3781 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3782 buffer.version().clone(),
3783 excerpt_visible_range,
3784 ),
3785 ))
3786 })
3787 .collect()
3788 }
3789
3790 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3791 TextLayoutDetails {
3792 text_system: window.text_system().clone(),
3793 editor_style: self.style.clone().unwrap(),
3794 rem_size: window.rem_size(),
3795 scroll_anchor: self.scroll_manager.anchor(),
3796 visible_rows: self.visible_line_count(),
3797 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3798 }
3799 }
3800
3801 pub fn splice_inlays(
3802 &self,
3803 to_remove: &[InlayId],
3804 to_insert: Vec<Inlay>,
3805 cx: &mut Context<Self>,
3806 ) {
3807 self.display_map.update(cx, |display_map, cx| {
3808 display_map.splice_inlays(to_remove, to_insert, cx)
3809 });
3810 cx.notify();
3811 }
3812
3813 fn trigger_on_type_formatting(
3814 &self,
3815 input: String,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) -> Option<Task<Result<()>>> {
3819 if input.len() != 1 {
3820 return None;
3821 }
3822
3823 let project = self.project.as_ref()?;
3824 let position = self.selections.newest_anchor().head();
3825 let (buffer, buffer_position) = self
3826 .buffer
3827 .read(cx)
3828 .text_anchor_for_position(position, cx)?;
3829
3830 let settings = language_settings::language_settings(
3831 buffer
3832 .read(cx)
3833 .language_at(buffer_position)
3834 .map(|l| l.name()),
3835 buffer.read(cx).file(),
3836 cx,
3837 );
3838 if !settings.use_on_type_format {
3839 return None;
3840 }
3841
3842 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3843 // hence we do LSP request & edit on host side only — add formats to host's history.
3844 let push_to_lsp_host_history = true;
3845 // If this is not the host, append its history with new edits.
3846 let push_to_client_history = project.read(cx).is_via_collab();
3847
3848 let on_type_formatting = project.update(cx, |project, cx| {
3849 project.on_type_format(
3850 buffer.clone(),
3851 buffer_position,
3852 input,
3853 push_to_lsp_host_history,
3854 cx,
3855 )
3856 });
3857 Some(cx.spawn_in(window, |editor, mut cx| async move {
3858 if let Some(transaction) = on_type_formatting.await? {
3859 if push_to_client_history {
3860 buffer
3861 .update(&mut cx, |buffer, _| {
3862 buffer.push_transaction(transaction, Instant::now());
3863 })
3864 .ok();
3865 }
3866 editor.update(&mut cx, |editor, cx| {
3867 editor.refresh_document_highlights(cx);
3868 })?;
3869 }
3870 Ok(())
3871 }))
3872 }
3873
3874 pub fn show_completions(
3875 &mut self,
3876 options: &ShowCompletions,
3877 window: &mut Window,
3878 cx: &mut Context<Self>,
3879 ) {
3880 if self.pending_rename.is_some() {
3881 return;
3882 }
3883
3884 let Some(provider) = self.completion_provider.as_ref() else {
3885 return;
3886 };
3887
3888 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3889 return;
3890 }
3891
3892 let position = self.selections.newest_anchor().head();
3893 if position.diff_base_anchor.is_some() {
3894 return;
3895 }
3896 let (buffer, buffer_position) =
3897 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3898 output
3899 } else {
3900 return;
3901 };
3902 let show_completion_documentation = buffer
3903 .read(cx)
3904 .snapshot()
3905 .settings_at(buffer_position, cx)
3906 .show_completion_documentation;
3907
3908 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3909
3910 let trigger_kind = match &options.trigger {
3911 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3912 CompletionTriggerKind::TRIGGER_CHARACTER
3913 }
3914 _ => CompletionTriggerKind::INVOKED,
3915 };
3916 let completion_context = CompletionContext {
3917 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3918 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3919 Some(String::from(trigger))
3920 } else {
3921 None
3922 }
3923 }),
3924 trigger_kind,
3925 };
3926 let completions =
3927 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3928 let sort_completions = provider.sort_completions();
3929
3930 let id = post_inc(&mut self.next_completion_id);
3931 let task = cx.spawn_in(window, |editor, mut cx| {
3932 async move {
3933 editor.update(&mut cx, |this, _| {
3934 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3935 })?;
3936 let completions = completions.await.log_err();
3937 let menu = if let Some(completions) = completions {
3938 let mut menu = CompletionsMenu::new(
3939 id,
3940 sort_completions,
3941 show_completion_documentation,
3942 position,
3943 buffer.clone(),
3944 completions.into(),
3945 );
3946
3947 menu.filter(query.as_deref(), cx.background_executor().clone())
3948 .await;
3949
3950 menu.visible().then_some(menu)
3951 } else {
3952 None
3953 };
3954
3955 editor.update_in(&mut cx, |editor, window, cx| {
3956 match editor.context_menu.borrow().as_ref() {
3957 None => {}
3958 Some(CodeContextMenu::Completions(prev_menu)) => {
3959 if prev_menu.id > id {
3960 return;
3961 }
3962 }
3963 _ => return,
3964 }
3965
3966 if editor.focus_handle.is_focused(window) && menu.is_some() {
3967 let mut menu = menu.unwrap();
3968 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3969
3970 *editor.context_menu.borrow_mut() =
3971 Some(CodeContextMenu::Completions(menu));
3972
3973 if editor.show_edit_predictions_in_menu() {
3974 editor.update_visible_inline_completion(window, cx);
3975 } else {
3976 editor.discard_inline_completion(false, cx);
3977 }
3978
3979 cx.notify();
3980 } else if editor.completion_tasks.len() <= 1 {
3981 // If there are no more completion tasks and the last menu was
3982 // empty, we should hide it.
3983 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3984 // If it was already hidden and we don't show inline
3985 // completions in the menu, we should also show the
3986 // inline-completion when available.
3987 if was_hidden && editor.show_edit_predictions_in_menu() {
3988 editor.update_visible_inline_completion(window, cx);
3989 }
3990 }
3991 })?;
3992
3993 Ok::<_, anyhow::Error>(())
3994 }
3995 .log_err()
3996 });
3997
3998 self.completion_tasks.push((id, task));
3999 }
4000
4001 pub fn confirm_completion(
4002 &mut self,
4003 action: &ConfirmCompletion,
4004 window: &mut Window,
4005 cx: &mut Context<Self>,
4006 ) -> Option<Task<Result<()>>> {
4007 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4008 }
4009
4010 pub fn compose_completion(
4011 &mut self,
4012 action: &ComposeCompletion,
4013 window: &mut Window,
4014 cx: &mut Context<Self>,
4015 ) -> Option<Task<Result<()>>> {
4016 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4017 }
4018
4019 fn do_completion(
4020 &mut self,
4021 item_ix: Option<usize>,
4022 intent: CompletionIntent,
4023 window: &mut Window,
4024 cx: &mut Context<Editor>,
4025 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4026 use language::ToOffset as _;
4027
4028 let completions_menu =
4029 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4030 menu
4031 } else {
4032 return None;
4033 };
4034
4035 let entries = completions_menu.entries.borrow();
4036 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4037 if self.show_edit_predictions_in_menu() {
4038 self.discard_inline_completion(true, cx);
4039 }
4040 let candidate_id = mat.candidate_id;
4041 drop(entries);
4042
4043 let buffer_handle = completions_menu.buffer;
4044 let completion = completions_menu
4045 .completions
4046 .borrow()
4047 .get(candidate_id)?
4048 .clone();
4049 cx.stop_propagation();
4050
4051 let snippet;
4052 let text;
4053
4054 if completion.is_snippet() {
4055 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4056 text = snippet.as_ref().unwrap().text.clone();
4057 } else {
4058 snippet = None;
4059 text = completion.new_text.clone();
4060 };
4061 let selections = self.selections.all::<usize>(cx);
4062 let buffer = buffer_handle.read(cx);
4063 let old_range = completion.old_range.to_offset(buffer);
4064 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4065
4066 let newest_selection = self.selections.newest_anchor();
4067 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4068 return None;
4069 }
4070
4071 let lookbehind = newest_selection
4072 .start
4073 .text_anchor
4074 .to_offset(buffer)
4075 .saturating_sub(old_range.start);
4076 let lookahead = old_range
4077 .end
4078 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4079 let mut common_prefix_len = old_text
4080 .bytes()
4081 .zip(text.bytes())
4082 .take_while(|(a, b)| a == b)
4083 .count();
4084
4085 let snapshot = self.buffer.read(cx).snapshot(cx);
4086 let mut range_to_replace: Option<Range<isize>> = None;
4087 let mut ranges = Vec::new();
4088 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4089 for selection in &selections {
4090 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4091 let start = selection.start.saturating_sub(lookbehind);
4092 let end = selection.end + lookahead;
4093 if selection.id == newest_selection.id {
4094 range_to_replace = Some(
4095 ((start + common_prefix_len) as isize - selection.start as isize)
4096 ..(end as isize - selection.start as isize),
4097 );
4098 }
4099 ranges.push(start + common_prefix_len..end);
4100 } else {
4101 common_prefix_len = 0;
4102 ranges.clear();
4103 ranges.extend(selections.iter().map(|s| {
4104 if s.id == newest_selection.id {
4105 range_to_replace = Some(
4106 old_range.start.to_offset_utf16(&snapshot).0 as isize
4107 - selection.start as isize
4108 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4109 - selection.start as isize,
4110 );
4111 old_range.clone()
4112 } else {
4113 s.start..s.end
4114 }
4115 }));
4116 break;
4117 }
4118 if !self.linked_edit_ranges.is_empty() {
4119 let start_anchor = snapshot.anchor_before(selection.head());
4120 let end_anchor = snapshot.anchor_after(selection.tail());
4121 if let Some(ranges) = self
4122 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4123 {
4124 for (buffer, edits) in ranges {
4125 linked_edits.entry(buffer.clone()).or_default().extend(
4126 edits
4127 .into_iter()
4128 .map(|range| (range, text[common_prefix_len..].to_owned())),
4129 );
4130 }
4131 }
4132 }
4133 }
4134 let text = &text[common_prefix_len..];
4135
4136 cx.emit(EditorEvent::InputHandled {
4137 utf16_range_to_replace: range_to_replace,
4138 text: text.into(),
4139 });
4140
4141 self.transact(window, cx, |this, window, cx| {
4142 if let Some(mut snippet) = snippet {
4143 snippet.text = text.to_string();
4144 for tabstop in snippet
4145 .tabstops
4146 .iter_mut()
4147 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4148 {
4149 tabstop.start -= common_prefix_len as isize;
4150 tabstop.end -= common_prefix_len as isize;
4151 }
4152
4153 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4154 } else {
4155 this.buffer.update(cx, |buffer, cx| {
4156 buffer.edit(
4157 ranges.iter().map(|range| (range.clone(), text)),
4158 this.autoindent_mode.clone(),
4159 cx,
4160 );
4161 });
4162 }
4163 for (buffer, edits) in linked_edits {
4164 buffer.update(cx, |buffer, cx| {
4165 let snapshot = buffer.snapshot();
4166 let edits = edits
4167 .into_iter()
4168 .map(|(range, text)| {
4169 use text::ToPoint as TP;
4170 let end_point = TP::to_point(&range.end, &snapshot);
4171 let start_point = TP::to_point(&range.start, &snapshot);
4172 (start_point..end_point, text)
4173 })
4174 .sorted_by_key(|(range, _)| range.start)
4175 .collect::<Vec<_>>();
4176 buffer.edit(edits, None, cx);
4177 })
4178 }
4179
4180 this.refresh_inline_completion(true, false, window, cx);
4181 });
4182
4183 let show_new_completions_on_confirm = completion
4184 .confirm
4185 .as_ref()
4186 .map_or(false, |confirm| confirm(intent, window, cx));
4187 if show_new_completions_on_confirm {
4188 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4189 }
4190
4191 let provider = self.completion_provider.as_ref()?;
4192 drop(completion);
4193 let apply_edits = provider.apply_additional_edits_for_completion(
4194 buffer_handle,
4195 completions_menu.completions.clone(),
4196 candidate_id,
4197 true,
4198 cx,
4199 );
4200
4201 let editor_settings = EditorSettings::get_global(cx);
4202 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4203 // After the code completion is finished, users often want to know what signatures are needed.
4204 // so we should automatically call signature_help
4205 self.show_signature_help(&ShowSignatureHelp, window, cx);
4206 }
4207
4208 Some(cx.foreground_executor().spawn(async move {
4209 apply_edits.await?;
4210 Ok(())
4211 }))
4212 }
4213
4214 pub fn toggle_code_actions(
4215 &mut self,
4216 action: &ToggleCodeActions,
4217 window: &mut Window,
4218 cx: &mut Context<Self>,
4219 ) {
4220 let mut context_menu = self.context_menu.borrow_mut();
4221 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4222 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4223 // Toggle if we're selecting the same one
4224 *context_menu = None;
4225 cx.notify();
4226 return;
4227 } else {
4228 // Otherwise, clear it and start a new one
4229 *context_menu = None;
4230 cx.notify();
4231 }
4232 }
4233 drop(context_menu);
4234 let snapshot = self.snapshot(window, cx);
4235 let deployed_from_indicator = action.deployed_from_indicator;
4236 let mut task = self.code_actions_task.take();
4237 let action = action.clone();
4238 cx.spawn_in(window, |editor, mut cx| async move {
4239 while let Some(prev_task) = task {
4240 prev_task.await.log_err();
4241 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4242 }
4243
4244 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4245 if editor.focus_handle.is_focused(window) {
4246 let multibuffer_point = action
4247 .deployed_from_indicator
4248 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4249 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4250 let (buffer, buffer_row) = snapshot
4251 .buffer_snapshot
4252 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4253 .and_then(|(buffer_snapshot, range)| {
4254 editor
4255 .buffer
4256 .read(cx)
4257 .buffer(buffer_snapshot.remote_id())
4258 .map(|buffer| (buffer, range.start.row))
4259 })?;
4260 let (_, code_actions) = editor
4261 .available_code_actions
4262 .clone()
4263 .and_then(|(location, code_actions)| {
4264 let snapshot = location.buffer.read(cx).snapshot();
4265 let point_range = location.range.to_point(&snapshot);
4266 let point_range = point_range.start.row..=point_range.end.row;
4267 if point_range.contains(&buffer_row) {
4268 Some((location, code_actions))
4269 } else {
4270 None
4271 }
4272 })
4273 .unzip();
4274 let buffer_id = buffer.read(cx).remote_id();
4275 let tasks = editor
4276 .tasks
4277 .get(&(buffer_id, buffer_row))
4278 .map(|t| Arc::new(t.to_owned()));
4279 if tasks.is_none() && code_actions.is_none() {
4280 return None;
4281 }
4282
4283 editor.completion_tasks.clear();
4284 editor.discard_inline_completion(false, cx);
4285 let task_context =
4286 tasks
4287 .as_ref()
4288 .zip(editor.project.clone())
4289 .map(|(tasks, project)| {
4290 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4291 });
4292
4293 Some(cx.spawn_in(window, |editor, mut cx| async move {
4294 let task_context = match task_context {
4295 Some(task_context) => task_context.await,
4296 None => None,
4297 };
4298 let resolved_tasks =
4299 tasks.zip(task_context).map(|(tasks, task_context)| {
4300 Rc::new(ResolvedTasks {
4301 templates: tasks.resolve(&task_context).collect(),
4302 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4303 multibuffer_point.row,
4304 tasks.column,
4305 )),
4306 })
4307 });
4308 let spawn_straight_away = resolved_tasks
4309 .as_ref()
4310 .map_or(false, |tasks| tasks.templates.len() == 1)
4311 && code_actions
4312 .as_ref()
4313 .map_or(true, |actions| actions.is_empty());
4314 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4315 *editor.context_menu.borrow_mut() =
4316 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4317 buffer,
4318 actions: CodeActionContents {
4319 tasks: resolved_tasks,
4320 actions: code_actions,
4321 },
4322 selected_item: Default::default(),
4323 scroll_handle: UniformListScrollHandle::default(),
4324 deployed_from_indicator,
4325 }));
4326 if spawn_straight_away {
4327 if let Some(task) = editor.confirm_code_action(
4328 &ConfirmCodeAction { item_ix: Some(0) },
4329 window,
4330 cx,
4331 ) {
4332 cx.notify();
4333 return task;
4334 }
4335 }
4336 cx.notify();
4337 Task::ready(Ok(()))
4338 }) {
4339 task.await
4340 } else {
4341 Ok(())
4342 }
4343 }))
4344 } else {
4345 Some(Task::ready(Ok(())))
4346 }
4347 })?;
4348 if let Some(task) = spawned_test_task {
4349 task.await?;
4350 }
4351
4352 Ok::<_, anyhow::Error>(())
4353 })
4354 .detach_and_log_err(cx);
4355 }
4356
4357 pub fn confirm_code_action(
4358 &mut self,
4359 action: &ConfirmCodeAction,
4360 window: &mut Window,
4361 cx: &mut Context<Self>,
4362 ) -> Option<Task<Result<()>>> {
4363 let actions_menu =
4364 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4365 menu
4366 } else {
4367 return None;
4368 };
4369 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4370 let action = actions_menu.actions.get(action_ix)?;
4371 let title = action.label();
4372 let buffer = actions_menu.buffer;
4373 let workspace = self.workspace()?;
4374
4375 match action {
4376 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4377 workspace.update(cx, |workspace, cx| {
4378 workspace::tasks::schedule_resolved_task(
4379 workspace,
4380 task_source_kind,
4381 resolved_task,
4382 false,
4383 cx,
4384 );
4385
4386 Some(Task::ready(Ok(())))
4387 })
4388 }
4389 CodeActionsItem::CodeAction {
4390 excerpt_id,
4391 action,
4392 provider,
4393 } => {
4394 let apply_code_action =
4395 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4396 let workspace = workspace.downgrade();
4397 Some(cx.spawn_in(window, |editor, cx| async move {
4398 let project_transaction = apply_code_action.await?;
4399 Self::open_project_transaction(
4400 &editor,
4401 workspace,
4402 project_transaction,
4403 title,
4404 cx,
4405 )
4406 .await
4407 }))
4408 }
4409 }
4410 }
4411
4412 pub async fn open_project_transaction(
4413 this: &WeakEntity<Editor>,
4414 workspace: WeakEntity<Workspace>,
4415 transaction: ProjectTransaction,
4416 title: String,
4417 mut cx: AsyncWindowContext,
4418 ) -> Result<()> {
4419 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4420 cx.update(|_, cx| {
4421 entries.sort_unstable_by_key(|(buffer, _)| {
4422 buffer.read(cx).file().map(|f| f.path().clone())
4423 });
4424 })?;
4425
4426 // If the project transaction's edits are all contained within this editor, then
4427 // avoid opening a new editor to display them.
4428
4429 if let Some((buffer, transaction)) = entries.first() {
4430 if entries.len() == 1 {
4431 let excerpt = this.update(&mut cx, |editor, cx| {
4432 editor
4433 .buffer()
4434 .read(cx)
4435 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4436 })?;
4437 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4438 if excerpted_buffer == *buffer {
4439 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4440 let excerpt_range = excerpt_range.to_offset(buffer);
4441 buffer
4442 .edited_ranges_for_transaction::<usize>(transaction)
4443 .all(|range| {
4444 excerpt_range.start <= range.start
4445 && excerpt_range.end >= range.end
4446 })
4447 })?;
4448
4449 if all_edits_within_excerpt {
4450 return Ok(());
4451 }
4452 }
4453 }
4454 }
4455 } else {
4456 return Ok(());
4457 }
4458
4459 let mut ranges_to_highlight = Vec::new();
4460 let excerpt_buffer = cx.new(|cx| {
4461 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4462 for (buffer_handle, transaction) in &entries {
4463 let buffer = buffer_handle.read(cx);
4464 ranges_to_highlight.extend(
4465 multibuffer.push_excerpts_with_context_lines(
4466 buffer_handle.clone(),
4467 buffer
4468 .edited_ranges_for_transaction::<usize>(transaction)
4469 .collect(),
4470 DEFAULT_MULTIBUFFER_CONTEXT,
4471 cx,
4472 ),
4473 );
4474 }
4475 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4476 multibuffer
4477 })?;
4478
4479 workspace.update_in(&mut cx, |workspace, window, cx| {
4480 let project = workspace.project().clone();
4481 let editor = cx
4482 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4483 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4484 editor.update(cx, |editor, cx| {
4485 editor.highlight_background::<Self>(
4486 &ranges_to_highlight,
4487 |theme| theme.editor_highlighted_line_background,
4488 cx,
4489 );
4490 });
4491 })?;
4492
4493 Ok(())
4494 }
4495
4496 pub fn clear_code_action_providers(&mut self) {
4497 self.code_action_providers.clear();
4498 self.available_code_actions.take();
4499 }
4500
4501 pub fn add_code_action_provider(
4502 &mut self,
4503 provider: Rc<dyn CodeActionProvider>,
4504 window: &mut Window,
4505 cx: &mut Context<Self>,
4506 ) {
4507 if self
4508 .code_action_providers
4509 .iter()
4510 .any(|existing_provider| existing_provider.id() == provider.id())
4511 {
4512 return;
4513 }
4514
4515 self.code_action_providers.push(provider);
4516 self.refresh_code_actions(window, cx);
4517 }
4518
4519 pub fn remove_code_action_provider(
4520 &mut self,
4521 id: Arc<str>,
4522 window: &mut Window,
4523 cx: &mut Context<Self>,
4524 ) {
4525 self.code_action_providers
4526 .retain(|provider| provider.id() != id);
4527 self.refresh_code_actions(window, cx);
4528 }
4529
4530 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4531 let buffer = self.buffer.read(cx);
4532 let newest_selection = self.selections.newest_anchor().clone();
4533 if newest_selection.head().diff_base_anchor.is_some() {
4534 return None;
4535 }
4536 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4537 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4538 if start_buffer != end_buffer {
4539 return None;
4540 }
4541
4542 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4543 cx.background_executor()
4544 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4545 .await;
4546
4547 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4548 let providers = this.code_action_providers.clone();
4549 let tasks = this
4550 .code_action_providers
4551 .iter()
4552 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4553 .collect::<Vec<_>>();
4554 (providers, tasks)
4555 })?;
4556
4557 let mut actions = Vec::new();
4558 for (provider, provider_actions) in
4559 providers.into_iter().zip(future::join_all(tasks).await)
4560 {
4561 if let Some(provider_actions) = provider_actions.log_err() {
4562 actions.extend(provider_actions.into_iter().map(|action| {
4563 AvailableCodeAction {
4564 excerpt_id: newest_selection.start.excerpt_id,
4565 action,
4566 provider: provider.clone(),
4567 }
4568 }));
4569 }
4570 }
4571
4572 this.update(&mut cx, |this, cx| {
4573 this.available_code_actions = if actions.is_empty() {
4574 None
4575 } else {
4576 Some((
4577 Location {
4578 buffer: start_buffer,
4579 range: start..end,
4580 },
4581 actions.into(),
4582 ))
4583 };
4584 cx.notify();
4585 })
4586 }));
4587 None
4588 }
4589
4590 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4591 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4592 self.show_git_blame_inline = false;
4593
4594 self.show_git_blame_inline_delay_task =
4595 Some(cx.spawn_in(window, |this, mut cx| async move {
4596 cx.background_executor().timer(delay).await;
4597
4598 this.update(&mut cx, |this, cx| {
4599 this.show_git_blame_inline = true;
4600 cx.notify();
4601 })
4602 .log_err();
4603 }));
4604 }
4605 }
4606
4607 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4608 if self.pending_rename.is_some() {
4609 return None;
4610 }
4611
4612 let provider = self.semantics_provider.clone()?;
4613 let buffer = self.buffer.read(cx);
4614 let newest_selection = self.selections.newest_anchor().clone();
4615 let cursor_position = newest_selection.head();
4616 let (cursor_buffer, cursor_buffer_position) =
4617 buffer.text_anchor_for_position(cursor_position, cx)?;
4618 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4619 if cursor_buffer != tail_buffer {
4620 return None;
4621 }
4622 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4623 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4624 cx.background_executor()
4625 .timer(Duration::from_millis(debounce))
4626 .await;
4627
4628 let highlights = if let Some(highlights) = cx
4629 .update(|cx| {
4630 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4631 })
4632 .ok()
4633 .flatten()
4634 {
4635 highlights.await.log_err()
4636 } else {
4637 None
4638 };
4639
4640 if let Some(highlights) = highlights {
4641 this.update(&mut cx, |this, cx| {
4642 if this.pending_rename.is_some() {
4643 return;
4644 }
4645
4646 let buffer_id = cursor_position.buffer_id;
4647 let buffer = this.buffer.read(cx);
4648 if !buffer
4649 .text_anchor_for_position(cursor_position, cx)
4650 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4651 {
4652 return;
4653 }
4654
4655 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4656 let mut write_ranges = Vec::new();
4657 let mut read_ranges = Vec::new();
4658 for highlight in highlights {
4659 for (excerpt_id, excerpt_range) in
4660 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4661 {
4662 let start = highlight
4663 .range
4664 .start
4665 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4666 let end = highlight
4667 .range
4668 .end
4669 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4670 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4671 continue;
4672 }
4673
4674 let range = Anchor {
4675 buffer_id,
4676 excerpt_id,
4677 text_anchor: start,
4678 diff_base_anchor: None,
4679 }..Anchor {
4680 buffer_id,
4681 excerpt_id,
4682 text_anchor: end,
4683 diff_base_anchor: None,
4684 };
4685 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4686 write_ranges.push(range);
4687 } else {
4688 read_ranges.push(range);
4689 }
4690 }
4691 }
4692
4693 this.highlight_background::<DocumentHighlightRead>(
4694 &read_ranges,
4695 |theme| theme.editor_document_highlight_read_background,
4696 cx,
4697 );
4698 this.highlight_background::<DocumentHighlightWrite>(
4699 &write_ranges,
4700 |theme| theme.editor_document_highlight_write_background,
4701 cx,
4702 );
4703 cx.notify();
4704 })
4705 .log_err();
4706 }
4707 }));
4708 None
4709 }
4710
4711 pub fn refresh_selected_text_highlights(
4712 &mut self,
4713 window: &mut Window,
4714 cx: &mut Context<Editor>,
4715 ) {
4716 self.selection_highlight_task.take();
4717 if !EditorSettings::get_global(cx).selection_highlight {
4718 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4719 return;
4720 }
4721 if self.selections.count() != 1 || self.selections.line_mode {
4722 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4723 return;
4724 }
4725 let selection = self.selections.newest::<Point>(cx);
4726 if selection.is_empty() || selection.start.row != selection.end.row {
4727 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4728 return;
4729 }
4730 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4731 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4732 cx.background_executor()
4733 .timer(Duration::from_millis(debounce))
4734 .await;
4735 let Some(Some(matches_task)) = editor
4736 .update_in(&mut cx, |editor, _, cx| {
4737 if editor.selections.count() != 1 || editor.selections.line_mode {
4738 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4739 return None;
4740 }
4741 let selection = editor.selections.newest::<Point>(cx);
4742 if selection.is_empty() || selection.start.row != selection.end.row {
4743 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4744 return None;
4745 }
4746 let buffer = editor.buffer().read(cx).snapshot(cx);
4747 let query = buffer.text_for_range(selection.range()).collect::<String>();
4748 if query.trim().is_empty() {
4749 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4750 return None;
4751 }
4752 Some(cx.background_spawn(async move {
4753 let mut ranges = Vec::new();
4754 let selection_anchors = selection.range().to_anchors(&buffer);
4755 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4756 for (search_buffer, search_range, excerpt_id) in
4757 buffer.range_to_buffer_ranges(range)
4758 {
4759 ranges.extend(
4760 project::search::SearchQuery::text(
4761 query.clone(),
4762 false,
4763 false,
4764 false,
4765 Default::default(),
4766 Default::default(),
4767 None,
4768 )
4769 .unwrap()
4770 .search(search_buffer, Some(search_range.clone()))
4771 .await
4772 .into_iter()
4773 .filter_map(
4774 |match_range| {
4775 let start = search_buffer.anchor_after(
4776 search_range.start + match_range.start,
4777 );
4778 let end = search_buffer.anchor_before(
4779 search_range.start + match_range.end,
4780 );
4781 let range = Anchor::range_in_buffer(
4782 excerpt_id,
4783 search_buffer.remote_id(),
4784 start..end,
4785 );
4786 (range != selection_anchors).then_some(range)
4787 },
4788 ),
4789 );
4790 }
4791 }
4792 ranges
4793 }))
4794 })
4795 .log_err()
4796 else {
4797 return;
4798 };
4799 let matches = matches_task.await;
4800 editor
4801 .update_in(&mut cx, |editor, _, cx| {
4802 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4803 if !matches.is_empty() {
4804 editor.highlight_background::<SelectedTextHighlight>(
4805 &matches,
4806 |theme| theme.editor_document_highlight_bracket_background,
4807 cx,
4808 )
4809 }
4810 })
4811 .log_err();
4812 }));
4813 }
4814
4815 pub fn refresh_inline_completion(
4816 &mut self,
4817 debounce: bool,
4818 user_requested: bool,
4819 window: &mut Window,
4820 cx: &mut Context<Self>,
4821 ) -> Option<()> {
4822 let provider = self.edit_prediction_provider()?;
4823 let cursor = self.selections.newest_anchor().head();
4824 let (buffer, cursor_buffer_position) =
4825 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4826
4827 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4828 self.discard_inline_completion(false, cx);
4829 return None;
4830 }
4831
4832 if !user_requested
4833 && (!self.should_show_edit_predictions()
4834 || !self.is_focused(window)
4835 || buffer.read(cx).is_empty())
4836 {
4837 self.discard_inline_completion(false, cx);
4838 return None;
4839 }
4840
4841 self.update_visible_inline_completion(window, cx);
4842 provider.refresh(
4843 self.project.clone(),
4844 buffer,
4845 cursor_buffer_position,
4846 debounce,
4847 cx,
4848 );
4849 Some(())
4850 }
4851
4852 fn show_edit_predictions_in_menu(&self) -> bool {
4853 match self.edit_prediction_settings {
4854 EditPredictionSettings::Disabled => false,
4855 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4856 }
4857 }
4858
4859 pub fn edit_predictions_enabled(&self) -> bool {
4860 match self.edit_prediction_settings {
4861 EditPredictionSettings::Disabled => false,
4862 EditPredictionSettings::Enabled { .. } => true,
4863 }
4864 }
4865
4866 fn edit_prediction_requires_modifier(&self) -> bool {
4867 match self.edit_prediction_settings {
4868 EditPredictionSettings::Disabled => false,
4869 EditPredictionSettings::Enabled {
4870 preview_requires_modifier,
4871 ..
4872 } => preview_requires_modifier,
4873 }
4874 }
4875
4876 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4877 if self.edit_prediction_provider.is_none() {
4878 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4879 } else {
4880 let selection = self.selections.newest_anchor();
4881 let cursor = selection.head();
4882
4883 if let Some((buffer, cursor_buffer_position)) =
4884 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4885 {
4886 self.edit_prediction_settings =
4887 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4888 }
4889 }
4890 }
4891
4892 fn edit_prediction_settings_at_position(
4893 &self,
4894 buffer: &Entity<Buffer>,
4895 buffer_position: language::Anchor,
4896 cx: &App,
4897 ) -> EditPredictionSettings {
4898 if self.mode != EditorMode::Full
4899 || !self.show_inline_completions_override.unwrap_or(true)
4900 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4901 {
4902 return EditPredictionSettings::Disabled;
4903 }
4904
4905 let buffer = buffer.read(cx);
4906
4907 let file = buffer.file();
4908
4909 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4910 return EditPredictionSettings::Disabled;
4911 };
4912
4913 let by_provider = matches!(
4914 self.menu_inline_completions_policy,
4915 MenuInlineCompletionsPolicy::ByProvider
4916 );
4917
4918 let show_in_menu = by_provider
4919 && self
4920 .edit_prediction_provider
4921 .as_ref()
4922 .map_or(false, |provider| {
4923 provider.provider.show_completions_in_menu()
4924 });
4925
4926 let preview_requires_modifier =
4927 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4928
4929 EditPredictionSettings::Enabled {
4930 show_in_menu,
4931 preview_requires_modifier,
4932 }
4933 }
4934
4935 fn should_show_edit_predictions(&self) -> bool {
4936 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4937 }
4938
4939 pub fn edit_prediction_preview_is_active(&self) -> bool {
4940 matches!(
4941 self.edit_prediction_preview,
4942 EditPredictionPreview::Active { .. }
4943 )
4944 }
4945
4946 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
4947 let cursor = self.selections.newest_anchor().head();
4948 if let Some((buffer, cursor_position)) =
4949 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4950 {
4951 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
4952 } else {
4953 false
4954 }
4955 }
4956
4957 fn edit_predictions_enabled_in_buffer(
4958 &self,
4959 buffer: &Entity<Buffer>,
4960 buffer_position: language::Anchor,
4961 cx: &App,
4962 ) -> bool {
4963 maybe!({
4964 let provider = self.edit_prediction_provider()?;
4965 if !provider.is_enabled(&buffer, buffer_position, cx) {
4966 return Some(false);
4967 }
4968 let buffer = buffer.read(cx);
4969 let Some(file) = buffer.file() else {
4970 return Some(true);
4971 };
4972 let settings = all_language_settings(Some(file), cx);
4973 Some(settings.inline_completions_enabled_for_path(file.path()))
4974 })
4975 .unwrap_or(false)
4976 }
4977
4978 fn cycle_inline_completion(
4979 &mut self,
4980 direction: Direction,
4981 window: &mut Window,
4982 cx: &mut Context<Self>,
4983 ) -> Option<()> {
4984 let provider = self.edit_prediction_provider()?;
4985 let cursor = self.selections.newest_anchor().head();
4986 let (buffer, cursor_buffer_position) =
4987 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4988 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4989 return None;
4990 }
4991
4992 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4993 self.update_visible_inline_completion(window, cx);
4994
4995 Some(())
4996 }
4997
4998 pub fn show_inline_completion(
4999 &mut self,
5000 _: &ShowEditPrediction,
5001 window: &mut Window,
5002 cx: &mut Context<Self>,
5003 ) {
5004 if !self.has_active_inline_completion() {
5005 self.refresh_inline_completion(false, true, window, cx);
5006 return;
5007 }
5008
5009 self.update_visible_inline_completion(window, cx);
5010 }
5011
5012 pub fn display_cursor_names(
5013 &mut self,
5014 _: &DisplayCursorNames,
5015 window: &mut Window,
5016 cx: &mut Context<Self>,
5017 ) {
5018 self.show_cursor_names(window, cx);
5019 }
5020
5021 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5022 self.show_cursor_names = true;
5023 cx.notify();
5024 cx.spawn_in(window, |this, mut cx| async move {
5025 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5026 this.update(&mut cx, |this, cx| {
5027 this.show_cursor_names = false;
5028 cx.notify()
5029 })
5030 .ok()
5031 })
5032 .detach();
5033 }
5034
5035 pub fn next_edit_prediction(
5036 &mut self,
5037 _: &NextEditPrediction,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 if self.has_active_inline_completion() {
5042 self.cycle_inline_completion(Direction::Next, window, cx);
5043 } else {
5044 let is_copilot_disabled = self
5045 .refresh_inline_completion(false, true, window, cx)
5046 .is_none();
5047 if is_copilot_disabled {
5048 cx.propagate();
5049 }
5050 }
5051 }
5052
5053 pub fn previous_edit_prediction(
5054 &mut self,
5055 _: &PreviousEditPrediction,
5056 window: &mut Window,
5057 cx: &mut Context<Self>,
5058 ) {
5059 if self.has_active_inline_completion() {
5060 self.cycle_inline_completion(Direction::Prev, window, cx);
5061 } else {
5062 let is_copilot_disabled = self
5063 .refresh_inline_completion(false, true, window, cx)
5064 .is_none();
5065 if is_copilot_disabled {
5066 cx.propagate();
5067 }
5068 }
5069 }
5070
5071 pub fn accept_edit_prediction(
5072 &mut self,
5073 _: &AcceptEditPrediction,
5074 window: &mut Window,
5075 cx: &mut Context<Self>,
5076 ) {
5077 if self.show_edit_predictions_in_menu() {
5078 self.hide_context_menu(window, cx);
5079 }
5080
5081 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5082 return;
5083 };
5084
5085 self.report_inline_completion_event(
5086 active_inline_completion.completion_id.clone(),
5087 true,
5088 cx,
5089 );
5090
5091 match &active_inline_completion.completion {
5092 InlineCompletion::Move { target, .. } => {
5093 let target = *target;
5094
5095 if let Some(position_map) = &self.last_position_map {
5096 if position_map
5097 .visible_row_range
5098 .contains(&target.to_display_point(&position_map.snapshot).row())
5099 || !self.edit_prediction_requires_modifier()
5100 {
5101 self.unfold_ranges(&[target..target], true, false, cx);
5102 // Note that this is also done in vim's handler of the Tab action.
5103 self.change_selections(
5104 Some(Autoscroll::newest()),
5105 window,
5106 cx,
5107 |selections| {
5108 selections.select_anchor_ranges([target..target]);
5109 },
5110 );
5111 self.clear_row_highlights::<EditPredictionPreview>();
5112
5113 self.edit_prediction_preview = EditPredictionPreview::Active {
5114 previous_scroll_position: None,
5115 };
5116 } else {
5117 self.edit_prediction_preview = EditPredictionPreview::Active {
5118 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5119 };
5120 self.highlight_rows::<EditPredictionPreview>(
5121 target..target,
5122 cx.theme().colors().editor_highlighted_line_background,
5123 true,
5124 cx,
5125 );
5126 self.request_autoscroll(Autoscroll::fit(), cx);
5127 }
5128 }
5129 }
5130 InlineCompletion::Edit { edits, .. } => {
5131 if let Some(provider) = self.edit_prediction_provider() {
5132 provider.accept(cx);
5133 }
5134
5135 let snapshot = self.buffer.read(cx).snapshot(cx);
5136 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5137
5138 self.buffer.update(cx, |buffer, cx| {
5139 buffer.edit(edits.iter().cloned(), None, cx)
5140 });
5141
5142 self.change_selections(None, window, cx, |s| {
5143 s.select_anchor_ranges([last_edit_end..last_edit_end])
5144 });
5145
5146 self.update_visible_inline_completion(window, cx);
5147 if self.active_inline_completion.is_none() {
5148 self.refresh_inline_completion(true, true, window, cx);
5149 }
5150
5151 cx.notify();
5152 }
5153 }
5154
5155 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5156 }
5157
5158 pub fn accept_partial_inline_completion(
5159 &mut self,
5160 _: &AcceptPartialEditPrediction,
5161 window: &mut Window,
5162 cx: &mut Context<Self>,
5163 ) {
5164 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5165 return;
5166 };
5167 if self.selections.count() != 1 {
5168 return;
5169 }
5170
5171 self.report_inline_completion_event(
5172 active_inline_completion.completion_id.clone(),
5173 true,
5174 cx,
5175 );
5176
5177 match &active_inline_completion.completion {
5178 InlineCompletion::Move { target, .. } => {
5179 let target = *target;
5180 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5181 selections.select_anchor_ranges([target..target]);
5182 });
5183 }
5184 InlineCompletion::Edit { edits, .. } => {
5185 // Find an insertion that starts at the cursor position.
5186 let snapshot = self.buffer.read(cx).snapshot(cx);
5187 let cursor_offset = self.selections.newest::<usize>(cx).head();
5188 let insertion = edits.iter().find_map(|(range, text)| {
5189 let range = range.to_offset(&snapshot);
5190 if range.is_empty() && range.start == cursor_offset {
5191 Some(text)
5192 } else {
5193 None
5194 }
5195 });
5196
5197 if let Some(text) = insertion {
5198 let mut partial_completion = text
5199 .chars()
5200 .by_ref()
5201 .take_while(|c| c.is_alphabetic())
5202 .collect::<String>();
5203 if partial_completion.is_empty() {
5204 partial_completion = text
5205 .chars()
5206 .by_ref()
5207 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5208 .collect::<String>();
5209 }
5210
5211 cx.emit(EditorEvent::InputHandled {
5212 utf16_range_to_replace: None,
5213 text: partial_completion.clone().into(),
5214 });
5215
5216 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5217
5218 self.refresh_inline_completion(true, true, window, cx);
5219 cx.notify();
5220 } else {
5221 self.accept_edit_prediction(&Default::default(), window, cx);
5222 }
5223 }
5224 }
5225 }
5226
5227 fn discard_inline_completion(
5228 &mut self,
5229 should_report_inline_completion_event: bool,
5230 cx: &mut Context<Self>,
5231 ) -> bool {
5232 if should_report_inline_completion_event {
5233 let completion_id = self
5234 .active_inline_completion
5235 .as_ref()
5236 .and_then(|active_completion| active_completion.completion_id.clone());
5237
5238 self.report_inline_completion_event(completion_id, false, cx);
5239 }
5240
5241 if let Some(provider) = self.edit_prediction_provider() {
5242 provider.discard(cx);
5243 }
5244
5245 self.take_active_inline_completion(cx)
5246 }
5247
5248 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5249 let Some(provider) = self.edit_prediction_provider() else {
5250 return;
5251 };
5252
5253 let Some((_, buffer, _)) = self
5254 .buffer
5255 .read(cx)
5256 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5257 else {
5258 return;
5259 };
5260
5261 let extension = buffer
5262 .read(cx)
5263 .file()
5264 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5265
5266 let event_type = match accepted {
5267 true => "Edit Prediction Accepted",
5268 false => "Edit Prediction Discarded",
5269 };
5270 telemetry::event!(
5271 event_type,
5272 provider = provider.name(),
5273 prediction_id = id,
5274 suggestion_accepted = accepted,
5275 file_extension = extension,
5276 );
5277 }
5278
5279 pub fn has_active_inline_completion(&self) -> bool {
5280 self.active_inline_completion.is_some()
5281 }
5282
5283 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5284 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5285 return false;
5286 };
5287
5288 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5289 self.clear_highlights::<InlineCompletionHighlight>(cx);
5290 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5291 true
5292 }
5293
5294 /// Returns true when we're displaying the edit prediction popover below the cursor
5295 /// like we are not previewing and the LSP autocomplete menu is visible
5296 /// or we are in `when_holding_modifier` mode.
5297 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5298 if self.edit_prediction_preview_is_active()
5299 || !self.show_edit_predictions_in_menu()
5300 || !self.edit_predictions_enabled()
5301 {
5302 return false;
5303 }
5304
5305 if self.has_visible_completions_menu() {
5306 return true;
5307 }
5308
5309 has_completion && self.edit_prediction_requires_modifier()
5310 }
5311
5312 fn handle_modifiers_changed(
5313 &mut self,
5314 modifiers: Modifiers,
5315 position_map: &PositionMap,
5316 window: &mut Window,
5317 cx: &mut Context<Self>,
5318 ) {
5319 if self.show_edit_predictions_in_menu() {
5320 self.update_edit_prediction_preview(&modifiers, window, cx);
5321 }
5322
5323 self.update_selection_mode(&modifiers, position_map, window, cx);
5324
5325 let mouse_position = window.mouse_position();
5326 if !position_map.text_hitbox.is_hovered(window) {
5327 return;
5328 }
5329
5330 self.update_hovered_link(
5331 position_map.point_for_position(mouse_position),
5332 &position_map.snapshot,
5333 modifiers,
5334 window,
5335 cx,
5336 )
5337 }
5338
5339 fn update_selection_mode(
5340 &mut self,
5341 modifiers: &Modifiers,
5342 position_map: &PositionMap,
5343 window: &mut Window,
5344 cx: &mut Context<Self>,
5345 ) {
5346 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5347 return;
5348 }
5349
5350 let mouse_position = window.mouse_position();
5351 let point_for_position = position_map.point_for_position(mouse_position);
5352 let position = point_for_position.previous_valid;
5353
5354 self.select(
5355 SelectPhase::BeginColumnar {
5356 position,
5357 reset: false,
5358 goal_column: point_for_position.exact_unclipped.column(),
5359 },
5360 window,
5361 cx,
5362 );
5363 }
5364
5365 fn update_edit_prediction_preview(
5366 &mut self,
5367 modifiers: &Modifiers,
5368 window: &mut Window,
5369 cx: &mut Context<Self>,
5370 ) {
5371 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5372 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5373 return;
5374 };
5375
5376 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5377 if matches!(
5378 self.edit_prediction_preview,
5379 EditPredictionPreview::Inactive
5380 ) {
5381 self.edit_prediction_preview = EditPredictionPreview::Active {
5382 previous_scroll_position: None,
5383 };
5384
5385 self.update_visible_inline_completion(window, cx);
5386 cx.notify();
5387 }
5388 } else if let EditPredictionPreview::Active {
5389 previous_scroll_position,
5390 } = self.edit_prediction_preview
5391 {
5392 if let (Some(previous_scroll_position), Some(position_map)) =
5393 (previous_scroll_position, self.last_position_map.as_ref())
5394 {
5395 self.set_scroll_position(
5396 previous_scroll_position
5397 .scroll_position(&position_map.snapshot.display_snapshot),
5398 window,
5399 cx,
5400 );
5401 }
5402
5403 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5404 self.clear_row_highlights::<EditPredictionPreview>();
5405 self.update_visible_inline_completion(window, cx);
5406 cx.notify();
5407 }
5408 }
5409
5410 fn update_visible_inline_completion(
5411 &mut self,
5412 _window: &mut Window,
5413 cx: &mut Context<Self>,
5414 ) -> Option<()> {
5415 let selection = self.selections.newest_anchor();
5416 let cursor = selection.head();
5417 let multibuffer = self.buffer.read(cx).snapshot(cx);
5418 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5419 let excerpt_id = cursor.excerpt_id;
5420
5421 let show_in_menu = self.show_edit_predictions_in_menu();
5422 let completions_menu_has_precedence = !show_in_menu
5423 && (self.context_menu.borrow().is_some()
5424 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5425
5426 if completions_menu_has_precedence
5427 || !offset_selection.is_empty()
5428 || self
5429 .active_inline_completion
5430 .as_ref()
5431 .map_or(false, |completion| {
5432 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5433 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5434 !invalidation_range.contains(&offset_selection.head())
5435 })
5436 {
5437 self.discard_inline_completion(false, cx);
5438 return None;
5439 }
5440
5441 self.take_active_inline_completion(cx);
5442 let Some(provider) = self.edit_prediction_provider() else {
5443 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5444 return None;
5445 };
5446
5447 let (buffer, cursor_buffer_position) =
5448 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5449
5450 self.edit_prediction_settings =
5451 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5452
5453 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5454
5455 if self.edit_prediction_indent_conflict {
5456 let cursor_point = cursor.to_point(&multibuffer);
5457
5458 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5459
5460 if let Some((_, indent)) = indents.iter().next() {
5461 if indent.len == cursor_point.column {
5462 self.edit_prediction_indent_conflict = false;
5463 }
5464 }
5465 }
5466
5467 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5468 let edits = inline_completion
5469 .edits
5470 .into_iter()
5471 .flat_map(|(range, new_text)| {
5472 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5473 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5474 Some((start..end, new_text))
5475 })
5476 .collect::<Vec<_>>();
5477 if edits.is_empty() {
5478 return None;
5479 }
5480
5481 let first_edit_start = edits.first().unwrap().0.start;
5482 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5483 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5484
5485 let last_edit_end = edits.last().unwrap().0.end;
5486 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5487 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5488
5489 let cursor_row = cursor.to_point(&multibuffer).row;
5490
5491 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5492
5493 let mut inlay_ids = Vec::new();
5494 let invalidation_row_range;
5495 let move_invalidation_row_range = if cursor_row < edit_start_row {
5496 Some(cursor_row..edit_end_row)
5497 } else if cursor_row > edit_end_row {
5498 Some(edit_start_row..cursor_row)
5499 } else {
5500 None
5501 };
5502 let is_move =
5503 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5504 let completion = if is_move {
5505 invalidation_row_range =
5506 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5507 let target = first_edit_start;
5508 InlineCompletion::Move { target, snapshot }
5509 } else {
5510 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5511 && !self.inline_completions_hidden_for_vim_mode;
5512
5513 if show_completions_in_buffer {
5514 if edits
5515 .iter()
5516 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5517 {
5518 let mut inlays = Vec::new();
5519 for (range, new_text) in &edits {
5520 let inlay = Inlay::inline_completion(
5521 post_inc(&mut self.next_inlay_id),
5522 range.start,
5523 new_text.as_str(),
5524 );
5525 inlay_ids.push(inlay.id);
5526 inlays.push(inlay);
5527 }
5528
5529 self.splice_inlays(&[], inlays, cx);
5530 } else {
5531 let background_color = cx.theme().status().deleted_background;
5532 self.highlight_text::<InlineCompletionHighlight>(
5533 edits.iter().map(|(range, _)| range.clone()).collect(),
5534 HighlightStyle {
5535 background_color: Some(background_color),
5536 ..Default::default()
5537 },
5538 cx,
5539 );
5540 }
5541 }
5542
5543 invalidation_row_range = edit_start_row..edit_end_row;
5544
5545 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5546 if provider.show_tab_accept_marker() {
5547 EditDisplayMode::TabAccept
5548 } else {
5549 EditDisplayMode::Inline
5550 }
5551 } else {
5552 EditDisplayMode::DiffPopover
5553 };
5554
5555 InlineCompletion::Edit {
5556 edits,
5557 edit_preview: inline_completion.edit_preview,
5558 display_mode,
5559 snapshot,
5560 }
5561 };
5562
5563 let invalidation_range = multibuffer
5564 .anchor_before(Point::new(invalidation_row_range.start, 0))
5565 ..multibuffer.anchor_after(Point::new(
5566 invalidation_row_range.end,
5567 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5568 ));
5569
5570 self.stale_inline_completion_in_menu = None;
5571 self.active_inline_completion = Some(InlineCompletionState {
5572 inlay_ids,
5573 completion,
5574 completion_id: inline_completion.id,
5575 invalidation_range,
5576 });
5577
5578 cx.notify();
5579
5580 Some(())
5581 }
5582
5583 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5584 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5585 }
5586
5587 fn render_code_actions_indicator(
5588 &self,
5589 _style: &EditorStyle,
5590 row: DisplayRow,
5591 is_active: bool,
5592 cx: &mut Context<Self>,
5593 ) -> Option<IconButton> {
5594 if self.available_code_actions.is_some() {
5595 Some(
5596 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5597 .shape(ui::IconButtonShape::Square)
5598 .icon_size(IconSize::XSmall)
5599 .icon_color(Color::Muted)
5600 .toggle_state(is_active)
5601 .tooltip({
5602 let focus_handle = self.focus_handle.clone();
5603 move |window, cx| {
5604 Tooltip::for_action_in(
5605 "Toggle Code Actions",
5606 &ToggleCodeActions {
5607 deployed_from_indicator: None,
5608 },
5609 &focus_handle,
5610 window,
5611 cx,
5612 )
5613 }
5614 })
5615 .on_click(cx.listener(move |editor, _e, window, cx| {
5616 window.focus(&editor.focus_handle(cx));
5617 editor.toggle_code_actions(
5618 &ToggleCodeActions {
5619 deployed_from_indicator: Some(row),
5620 },
5621 window,
5622 cx,
5623 );
5624 })),
5625 )
5626 } else {
5627 None
5628 }
5629 }
5630
5631 fn clear_tasks(&mut self) {
5632 self.tasks.clear()
5633 }
5634
5635 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5636 if self.tasks.insert(key, value).is_some() {
5637 // This case should hopefully be rare, but just in case...
5638 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5639 }
5640 }
5641
5642 fn build_tasks_context(
5643 project: &Entity<Project>,
5644 buffer: &Entity<Buffer>,
5645 buffer_row: u32,
5646 tasks: &Arc<RunnableTasks>,
5647 cx: &mut Context<Self>,
5648 ) -> Task<Option<task::TaskContext>> {
5649 let position = Point::new(buffer_row, tasks.column);
5650 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5651 let location = Location {
5652 buffer: buffer.clone(),
5653 range: range_start..range_start,
5654 };
5655 // Fill in the environmental variables from the tree-sitter captures
5656 let mut captured_task_variables = TaskVariables::default();
5657 for (capture_name, value) in tasks.extra_variables.clone() {
5658 captured_task_variables.insert(
5659 task::VariableName::Custom(capture_name.into()),
5660 value.clone(),
5661 );
5662 }
5663 project.update(cx, |project, cx| {
5664 project.task_store().update(cx, |task_store, cx| {
5665 task_store.task_context_for_location(captured_task_variables, location, cx)
5666 })
5667 })
5668 }
5669
5670 pub fn spawn_nearest_task(
5671 &mut self,
5672 action: &SpawnNearestTask,
5673 window: &mut Window,
5674 cx: &mut Context<Self>,
5675 ) {
5676 let Some((workspace, _)) = self.workspace.clone() else {
5677 return;
5678 };
5679 let Some(project) = self.project.clone() else {
5680 return;
5681 };
5682
5683 // Try to find a closest, enclosing node using tree-sitter that has a
5684 // task
5685 let Some((buffer, buffer_row, tasks)) = self
5686 .find_enclosing_node_task(cx)
5687 // Or find the task that's closest in row-distance.
5688 .or_else(|| self.find_closest_task(cx))
5689 else {
5690 return;
5691 };
5692
5693 let reveal_strategy = action.reveal;
5694 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5695 cx.spawn_in(window, |_, mut cx| async move {
5696 let context = task_context.await?;
5697 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5698
5699 let resolved = resolved_task.resolved.as_mut()?;
5700 resolved.reveal = reveal_strategy;
5701
5702 workspace
5703 .update(&mut cx, |workspace, cx| {
5704 workspace::tasks::schedule_resolved_task(
5705 workspace,
5706 task_source_kind,
5707 resolved_task,
5708 false,
5709 cx,
5710 );
5711 })
5712 .ok()
5713 })
5714 .detach();
5715 }
5716
5717 fn find_closest_task(
5718 &mut self,
5719 cx: &mut Context<Self>,
5720 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5721 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5722
5723 let ((buffer_id, row), tasks) = self
5724 .tasks
5725 .iter()
5726 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5727
5728 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5729 let tasks = Arc::new(tasks.to_owned());
5730 Some((buffer, *row, tasks))
5731 }
5732
5733 fn find_enclosing_node_task(
5734 &mut self,
5735 cx: &mut Context<Self>,
5736 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5737 let snapshot = self.buffer.read(cx).snapshot(cx);
5738 let offset = self.selections.newest::<usize>(cx).head();
5739 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5740 let buffer_id = excerpt.buffer().remote_id();
5741
5742 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5743 let mut cursor = layer.node().walk();
5744
5745 while cursor.goto_first_child_for_byte(offset).is_some() {
5746 if cursor.node().end_byte() == offset {
5747 cursor.goto_next_sibling();
5748 }
5749 }
5750
5751 // Ascend to the smallest ancestor that contains the range and has a task.
5752 loop {
5753 let node = cursor.node();
5754 let node_range = node.byte_range();
5755 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5756
5757 // Check if this node contains our offset
5758 if node_range.start <= offset && node_range.end >= offset {
5759 // If it contains offset, check for task
5760 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5761 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5762 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5763 }
5764 }
5765
5766 if !cursor.goto_parent() {
5767 break;
5768 }
5769 }
5770 None
5771 }
5772
5773 fn render_run_indicator(
5774 &self,
5775 _style: &EditorStyle,
5776 is_active: bool,
5777 row: DisplayRow,
5778 cx: &mut Context<Self>,
5779 ) -> IconButton {
5780 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5781 .shape(ui::IconButtonShape::Square)
5782 .icon_size(IconSize::XSmall)
5783 .icon_color(Color::Muted)
5784 .toggle_state(is_active)
5785 .on_click(cx.listener(move |editor, _e, window, cx| {
5786 window.focus(&editor.focus_handle(cx));
5787 editor.toggle_code_actions(
5788 &ToggleCodeActions {
5789 deployed_from_indicator: Some(row),
5790 },
5791 window,
5792 cx,
5793 );
5794 }))
5795 }
5796
5797 pub fn context_menu_visible(&self) -> bool {
5798 !self.edit_prediction_preview_is_active()
5799 && self
5800 .context_menu
5801 .borrow()
5802 .as_ref()
5803 .map_or(false, |menu| menu.visible())
5804 }
5805
5806 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5807 self.context_menu
5808 .borrow()
5809 .as_ref()
5810 .map(|menu| menu.origin())
5811 }
5812
5813 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5814 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5815
5816 #[allow(clippy::too_many_arguments)]
5817 fn render_edit_prediction_popover(
5818 &mut self,
5819 text_bounds: &Bounds<Pixels>,
5820 content_origin: gpui::Point<Pixels>,
5821 editor_snapshot: &EditorSnapshot,
5822 visible_row_range: Range<DisplayRow>,
5823 scroll_top: f32,
5824 scroll_bottom: f32,
5825 line_layouts: &[LineWithInvisibles],
5826 line_height: Pixels,
5827 scroll_pixel_position: gpui::Point<Pixels>,
5828 newest_selection_head: Option<DisplayPoint>,
5829 editor_width: Pixels,
5830 style: &EditorStyle,
5831 window: &mut Window,
5832 cx: &mut App,
5833 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5834 let active_inline_completion = self.active_inline_completion.as_ref()?;
5835
5836 if self.edit_prediction_visible_in_cursor_popover(true) {
5837 return None;
5838 }
5839
5840 match &active_inline_completion.completion {
5841 InlineCompletion::Move { target, .. } => {
5842 let target_display_point = target.to_display_point(editor_snapshot);
5843
5844 if self.edit_prediction_requires_modifier() {
5845 if !self.edit_prediction_preview_is_active() {
5846 return None;
5847 }
5848
5849 self.render_edit_prediction_modifier_jump_popover(
5850 text_bounds,
5851 content_origin,
5852 visible_row_range,
5853 line_layouts,
5854 line_height,
5855 scroll_pixel_position,
5856 newest_selection_head,
5857 target_display_point,
5858 window,
5859 cx,
5860 )
5861 } else {
5862 self.render_edit_prediction_eager_jump_popover(
5863 text_bounds,
5864 content_origin,
5865 editor_snapshot,
5866 visible_row_range,
5867 scroll_top,
5868 scroll_bottom,
5869 line_height,
5870 scroll_pixel_position,
5871 target_display_point,
5872 editor_width,
5873 window,
5874 cx,
5875 )
5876 }
5877 }
5878 InlineCompletion::Edit {
5879 display_mode: EditDisplayMode::Inline,
5880 ..
5881 } => None,
5882 InlineCompletion::Edit {
5883 display_mode: EditDisplayMode::TabAccept,
5884 edits,
5885 ..
5886 } => {
5887 let range = &edits.first()?.0;
5888 let target_display_point = range.end.to_display_point(editor_snapshot);
5889
5890 self.render_edit_prediction_end_of_line_popover(
5891 "Accept",
5892 editor_snapshot,
5893 visible_row_range,
5894 target_display_point,
5895 line_height,
5896 scroll_pixel_position,
5897 content_origin,
5898 editor_width,
5899 window,
5900 cx,
5901 )
5902 }
5903 InlineCompletion::Edit {
5904 edits,
5905 edit_preview,
5906 display_mode: EditDisplayMode::DiffPopover,
5907 snapshot,
5908 } => self.render_edit_prediction_diff_popover(
5909 text_bounds,
5910 content_origin,
5911 editor_snapshot,
5912 visible_row_range,
5913 line_layouts,
5914 line_height,
5915 scroll_pixel_position,
5916 newest_selection_head,
5917 editor_width,
5918 style,
5919 edits,
5920 edit_preview,
5921 snapshot,
5922 window,
5923 cx,
5924 ),
5925 }
5926 }
5927
5928 #[allow(clippy::too_many_arguments)]
5929 fn render_edit_prediction_modifier_jump_popover(
5930 &mut self,
5931 text_bounds: &Bounds<Pixels>,
5932 content_origin: gpui::Point<Pixels>,
5933 visible_row_range: Range<DisplayRow>,
5934 line_layouts: &[LineWithInvisibles],
5935 line_height: Pixels,
5936 scroll_pixel_position: gpui::Point<Pixels>,
5937 newest_selection_head: Option<DisplayPoint>,
5938 target_display_point: DisplayPoint,
5939 window: &mut Window,
5940 cx: &mut App,
5941 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5942 let scrolled_content_origin =
5943 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
5944
5945 const SCROLL_PADDING_Y: Pixels = px(12.);
5946
5947 if target_display_point.row() < visible_row_range.start {
5948 return self.render_edit_prediction_scroll_popover(
5949 |_| SCROLL_PADDING_Y,
5950 IconName::ArrowUp,
5951 visible_row_range,
5952 line_layouts,
5953 newest_selection_head,
5954 scrolled_content_origin,
5955 window,
5956 cx,
5957 );
5958 } else if target_display_point.row() >= visible_row_range.end {
5959 return self.render_edit_prediction_scroll_popover(
5960 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
5961 IconName::ArrowDown,
5962 visible_row_range,
5963 line_layouts,
5964 newest_selection_head,
5965 scrolled_content_origin,
5966 window,
5967 cx,
5968 );
5969 }
5970
5971 const POLE_WIDTH: Pixels = px(2.);
5972
5973 let mut element = v_flex()
5974 .items_end()
5975 .child(
5976 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
5977 .rounded_br(px(0.))
5978 .rounded_tr(px(0.))
5979 .border_r_2(),
5980 )
5981 .child(
5982 div()
5983 .w(POLE_WIDTH)
5984 .bg(Editor::edit_prediction_callout_popover_border_color(cx))
5985 .h(line_height),
5986 )
5987 .into_any();
5988
5989 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
5990
5991 let line_layout =
5992 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
5993 let target_column = target_display_point.column() as usize;
5994
5995 let target_x = line_layout.x_for_index(target_column);
5996 let target_y =
5997 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
5998
5999 let mut origin = scrolled_content_origin + point(target_x, target_y)
6000 - point(size.width - POLE_WIDTH, size.height - line_height);
6001
6002 origin.x = origin.x.max(content_origin.x);
6003
6004 element.prepaint_at(origin, window, cx);
6005
6006 Some((element, origin))
6007 }
6008
6009 #[allow(clippy::too_many_arguments)]
6010 fn render_edit_prediction_scroll_popover(
6011 &mut self,
6012 to_y: impl Fn(Size<Pixels>) -> Pixels,
6013 scroll_icon: IconName,
6014 visible_row_range: Range<DisplayRow>,
6015 line_layouts: &[LineWithInvisibles],
6016 newest_selection_head: Option<DisplayPoint>,
6017 scrolled_content_origin: gpui::Point<Pixels>,
6018 window: &mut Window,
6019 cx: &mut App,
6020 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6021 let mut element = self
6022 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6023 .into_any();
6024
6025 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6026
6027 let cursor = newest_selection_head?;
6028 let cursor_row_layout =
6029 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6030 let cursor_column = cursor.column() as usize;
6031
6032 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6033
6034 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6035
6036 element.prepaint_at(origin, window, cx);
6037 Some((element, origin))
6038 }
6039
6040 #[allow(clippy::too_many_arguments)]
6041 fn render_edit_prediction_eager_jump_popover(
6042 &mut self,
6043 text_bounds: &Bounds<Pixels>,
6044 content_origin: gpui::Point<Pixels>,
6045 editor_snapshot: &EditorSnapshot,
6046 visible_row_range: Range<DisplayRow>,
6047 scroll_top: f32,
6048 scroll_bottom: f32,
6049 line_height: Pixels,
6050 scroll_pixel_position: gpui::Point<Pixels>,
6051 target_display_point: DisplayPoint,
6052 editor_width: Pixels,
6053 window: &mut Window,
6054 cx: &mut App,
6055 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6056 if target_display_point.row().as_f32() < scroll_top {
6057 let mut element = self
6058 .render_edit_prediction_line_popover(
6059 "Jump to Edit",
6060 Some(IconName::ArrowUp),
6061 window,
6062 cx,
6063 )?
6064 .into_any();
6065
6066 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6067 let offset = point(
6068 (text_bounds.size.width - size.width) / 2.,
6069 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6070 );
6071
6072 let origin = text_bounds.origin + offset;
6073 element.prepaint_at(origin, window, cx);
6074 Some((element, origin))
6075 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6076 let mut element = self
6077 .render_edit_prediction_line_popover(
6078 "Jump to Edit",
6079 Some(IconName::ArrowDown),
6080 window,
6081 cx,
6082 )?
6083 .into_any();
6084
6085 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6086 let offset = point(
6087 (text_bounds.size.width - size.width) / 2.,
6088 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6089 );
6090
6091 let origin = text_bounds.origin + offset;
6092 element.prepaint_at(origin, window, cx);
6093 Some((element, origin))
6094 } else {
6095 self.render_edit_prediction_end_of_line_popover(
6096 "Jump to Edit",
6097 editor_snapshot,
6098 visible_row_range,
6099 target_display_point,
6100 line_height,
6101 scroll_pixel_position,
6102 content_origin,
6103 editor_width,
6104 window,
6105 cx,
6106 )
6107 }
6108 }
6109
6110 #[allow(clippy::too_many_arguments)]
6111 fn render_edit_prediction_end_of_line_popover(
6112 self: &mut Editor,
6113 label: &'static str,
6114 editor_snapshot: &EditorSnapshot,
6115 visible_row_range: Range<DisplayRow>,
6116 target_display_point: DisplayPoint,
6117 line_height: Pixels,
6118 scroll_pixel_position: gpui::Point<Pixels>,
6119 content_origin: gpui::Point<Pixels>,
6120 editor_width: Pixels,
6121 window: &mut Window,
6122 cx: &mut App,
6123 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6124 let target_line_end = DisplayPoint::new(
6125 target_display_point.row(),
6126 editor_snapshot.line_len(target_display_point.row()),
6127 );
6128
6129 let mut element = self
6130 .render_edit_prediction_line_popover(label, None, window, cx)?
6131 .into_any();
6132
6133 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6134
6135 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6136
6137 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6138 let mut origin = start_point
6139 + line_origin
6140 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6141 origin.x = origin.x.max(content_origin.x);
6142
6143 let max_x = content_origin.x + editor_width - size.width;
6144
6145 if origin.x > max_x {
6146 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6147
6148 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6149 origin.y += offset;
6150 IconName::ArrowUp
6151 } else {
6152 origin.y -= offset;
6153 IconName::ArrowDown
6154 };
6155
6156 element = self
6157 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6158 .into_any();
6159
6160 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6161
6162 origin.x = content_origin.x + editor_width - size.width - px(2.);
6163 }
6164
6165 element.prepaint_at(origin, window, cx);
6166 Some((element, origin))
6167 }
6168
6169 #[allow(clippy::too_many_arguments)]
6170 fn render_edit_prediction_diff_popover(
6171 self: &Editor,
6172 text_bounds: &Bounds<Pixels>,
6173 content_origin: gpui::Point<Pixels>,
6174 editor_snapshot: &EditorSnapshot,
6175 visible_row_range: Range<DisplayRow>,
6176 line_layouts: &[LineWithInvisibles],
6177 line_height: Pixels,
6178 scroll_pixel_position: gpui::Point<Pixels>,
6179 newest_selection_head: Option<DisplayPoint>,
6180 editor_width: Pixels,
6181 style: &EditorStyle,
6182 edits: &Vec<(Range<Anchor>, String)>,
6183 edit_preview: &Option<language::EditPreview>,
6184 snapshot: &language::BufferSnapshot,
6185 window: &mut Window,
6186 cx: &mut App,
6187 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6188 let edit_start = edits
6189 .first()
6190 .unwrap()
6191 .0
6192 .start
6193 .to_display_point(editor_snapshot);
6194 let edit_end = edits
6195 .last()
6196 .unwrap()
6197 .0
6198 .end
6199 .to_display_point(editor_snapshot);
6200
6201 let is_visible = visible_row_range.contains(&edit_start.row())
6202 || visible_row_range.contains(&edit_end.row());
6203 if !is_visible {
6204 return None;
6205 }
6206
6207 let highlighted_edits =
6208 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6209
6210 let styled_text = highlighted_edits.to_styled_text(&style.text);
6211 let line_count = highlighted_edits.text.lines().count();
6212
6213 const BORDER_WIDTH: Pixels = px(1.);
6214
6215 let mut element = h_flex()
6216 .items_start()
6217 .child(
6218 h_flex()
6219 .bg(cx.theme().colors().editor_background)
6220 .border(BORDER_WIDTH)
6221 .shadow_sm()
6222 .border_color(cx.theme().colors().border)
6223 .rounded_l_lg()
6224 .when(line_count > 1, |el| el.rounded_br_lg())
6225 .pr_1()
6226 .child(styled_text),
6227 )
6228 .child(
6229 h_flex()
6230 .h(line_height + BORDER_WIDTH * px(2.))
6231 .px_1p5()
6232 .gap_1()
6233 // Workaround: For some reason, there's a gap if we don't do this
6234 .ml(-BORDER_WIDTH)
6235 .shadow(smallvec![gpui::BoxShadow {
6236 color: gpui::black().opacity(0.05),
6237 offset: point(px(1.), px(1.)),
6238 blur_radius: px(2.),
6239 spread_radius: px(0.),
6240 }])
6241 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6242 .border(BORDER_WIDTH)
6243 .border_color(cx.theme().colors().border)
6244 .rounded_r_lg()
6245 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6246 )
6247 .into_any();
6248
6249 let longest_row =
6250 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6251 let longest_line_width = if visible_row_range.contains(&longest_row) {
6252 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6253 } else {
6254 layout_line(
6255 longest_row,
6256 editor_snapshot,
6257 style,
6258 editor_width,
6259 |_| false,
6260 window,
6261 cx,
6262 )
6263 .width
6264 };
6265
6266 let viewport_bounds =
6267 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6268 right: -EditorElement::SCROLLBAR_WIDTH,
6269 ..Default::default()
6270 });
6271
6272 let x_after_longest =
6273 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6274 - scroll_pixel_position.x;
6275
6276 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6277
6278 // Fully visible if it can be displayed within the window (allow overlapping other
6279 // panes). However, this is only allowed if the popover starts within text_bounds.
6280 let can_position_to_the_right = x_after_longest < text_bounds.right()
6281 && x_after_longest + element_bounds.width < viewport_bounds.right();
6282
6283 let mut origin = if can_position_to_the_right {
6284 point(
6285 x_after_longest,
6286 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6287 - scroll_pixel_position.y,
6288 )
6289 } else {
6290 let cursor_row = newest_selection_head.map(|head| head.row());
6291 let above_edit = edit_start
6292 .row()
6293 .0
6294 .checked_sub(line_count as u32)
6295 .map(DisplayRow);
6296 let below_edit = Some(edit_end.row() + 1);
6297 let above_cursor =
6298 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6299 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6300
6301 // Place the edit popover adjacent to the edit if there is a location
6302 // available that is onscreen and does not obscure the cursor. Otherwise,
6303 // place it adjacent to the cursor.
6304 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6305 .into_iter()
6306 .flatten()
6307 .find(|&start_row| {
6308 let end_row = start_row + line_count as u32;
6309 visible_row_range.contains(&start_row)
6310 && visible_row_range.contains(&end_row)
6311 && cursor_row.map_or(true, |cursor_row| {
6312 !((start_row..end_row).contains(&cursor_row))
6313 })
6314 })?;
6315
6316 content_origin
6317 + point(
6318 -scroll_pixel_position.x,
6319 row_target.as_f32() * line_height - scroll_pixel_position.y,
6320 )
6321 };
6322
6323 origin.x -= BORDER_WIDTH;
6324
6325 window.defer_draw(element, origin, 1);
6326
6327 // Do not return an element, since it will already be drawn due to defer_draw.
6328 None
6329 }
6330
6331 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6332 px(30.)
6333 }
6334
6335 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6336 if self.read_only(cx) {
6337 cx.theme().players().read_only()
6338 } else {
6339 self.style.as_ref().unwrap().local_player
6340 }
6341 }
6342
6343 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6344 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6345 let accept_keystroke = accept_binding.keystroke()?;
6346
6347 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6348
6349 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6350 Color::Accent
6351 } else {
6352 Color::Muted
6353 };
6354
6355 h_flex()
6356 .px_0p5()
6357 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6358 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6359 .text_size(TextSize::XSmall.rems(cx))
6360 .child(h_flex().children(ui::render_modifiers(
6361 &accept_keystroke.modifiers,
6362 PlatformStyle::platform(),
6363 Some(modifiers_color),
6364 Some(IconSize::XSmall.rems().into()),
6365 true,
6366 )))
6367 .when(is_platform_style_mac, |parent| {
6368 parent.child(accept_keystroke.key.clone())
6369 })
6370 .when(!is_platform_style_mac, |parent| {
6371 parent.child(
6372 Key::new(
6373 util::capitalize(&accept_keystroke.key),
6374 Some(Color::Default),
6375 )
6376 .size(Some(IconSize::XSmall.rems().into())),
6377 )
6378 })
6379 .into()
6380 }
6381
6382 fn render_edit_prediction_line_popover(
6383 &self,
6384 label: impl Into<SharedString>,
6385 icon: Option<IconName>,
6386 window: &mut Window,
6387 cx: &App,
6388 ) -> Option<Div> {
6389 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6390
6391 let result = h_flex()
6392 .py_0p5()
6393 .pl_1()
6394 .pr(padding_right)
6395 .gap_1()
6396 .rounded(px(6.))
6397 .border_1()
6398 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6399 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6400 .shadow_sm()
6401 .children(self.render_edit_prediction_accept_keybind(window, cx))
6402 .child(Label::new(label).size(LabelSize::Small))
6403 .when_some(icon, |element, icon| {
6404 element.child(
6405 div()
6406 .mt(px(1.5))
6407 .child(Icon::new(icon).size(IconSize::Small)),
6408 )
6409 });
6410
6411 Some(result)
6412 }
6413
6414 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6415 let accent_color = cx.theme().colors().text_accent;
6416 let editor_bg_color = cx.theme().colors().editor_background;
6417 editor_bg_color.blend(accent_color.opacity(0.1))
6418 }
6419
6420 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6421 let accent_color = cx.theme().colors().text_accent;
6422 let editor_bg_color = cx.theme().colors().editor_background;
6423 editor_bg_color.blend(accent_color.opacity(0.6))
6424 }
6425
6426 #[allow(clippy::too_many_arguments)]
6427 fn render_edit_prediction_cursor_popover(
6428 &self,
6429 min_width: Pixels,
6430 max_width: Pixels,
6431 cursor_point: Point,
6432 style: &EditorStyle,
6433 accept_keystroke: Option<&gpui::Keystroke>,
6434 _window: &Window,
6435 cx: &mut Context<Editor>,
6436 ) -> Option<AnyElement> {
6437 let provider = self.edit_prediction_provider.as_ref()?;
6438
6439 if provider.provider.needs_terms_acceptance(cx) {
6440 return Some(
6441 h_flex()
6442 .min_w(min_width)
6443 .flex_1()
6444 .px_2()
6445 .py_1()
6446 .gap_3()
6447 .elevation_2(cx)
6448 .hover(|style| style.bg(cx.theme().colors().element_hover))
6449 .id("accept-terms")
6450 .cursor_pointer()
6451 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6452 .on_click(cx.listener(|this, _event, window, cx| {
6453 cx.stop_propagation();
6454 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6455 window.dispatch_action(
6456 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6457 cx,
6458 );
6459 }))
6460 .child(
6461 h_flex()
6462 .flex_1()
6463 .gap_2()
6464 .child(Icon::new(IconName::ZedPredict))
6465 .child(Label::new("Accept Terms of Service"))
6466 .child(div().w_full())
6467 .child(
6468 Icon::new(IconName::ArrowUpRight)
6469 .color(Color::Muted)
6470 .size(IconSize::Small),
6471 )
6472 .into_any_element(),
6473 )
6474 .into_any(),
6475 );
6476 }
6477
6478 let is_refreshing = provider.provider.is_refreshing(cx);
6479
6480 fn pending_completion_container() -> Div {
6481 h_flex()
6482 .h_full()
6483 .flex_1()
6484 .gap_2()
6485 .child(Icon::new(IconName::ZedPredict))
6486 }
6487
6488 let completion = match &self.active_inline_completion {
6489 Some(completion) => match &completion.completion {
6490 InlineCompletion::Move {
6491 target, snapshot, ..
6492 } if !self.has_visible_completions_menu() => {
6493 use text::ToPoint as _;
6494
6495 return Some(
6496 h_flex()
6497 .px_2()
6498 .py_1()
6499 .gap_2()
6500 .elevation_2(cx)
6501 .border_color(cx.theme().colors().border)
6502 .rounded(px(6.))
6503 .rounded_tl(px(0.))
6504 .child(
6505 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6506 Icon::new(IconName::ZedPredictDown)
6507 } else {
6508 Icon::new(IconName::ZedPredictUp)
6509 },
6510 )
6511 .child(Label::new("Hold").size(LabelSize::Small))
6512 .child(h_flex().children(ui::render_modifiers(
6513 &accept_keystroke?.modifiers,
6514 PlatformStyle::platform(),
6515 Some(Color::Default),
6516 Some(IconSize::Small.rems().into()),
6517 false,
6518 )))
6519 .into_any(),
6520 );
6521 }
6522 _ => self.render_edit_prediction_cursor_popover_preview(
6523 completion,
6524 cursor_point,
6525 style,
6526 cx,
6527 )?,
6528 },
6529
6530 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6531 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6532 stale_completion,
6533 cursor_point,
6534 style,
6535 cx,
6536 )?,
6537
6538 None => {
6539 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6540 }
6541 },
6542
6543 None => pending_completion_container().child(Label::new("No Prediction")),
6544 };
6545
6546 let completion = if is_refreshing {
6547 completion
6548 .with_animation(
6549 "loading-completion",
6550 Animation::new(Duration::from_secs(2))
6551 .repeat()
6552 .with_easing(pulsating_between(0.4, 0.8)),
6553 |label, delta| label.opacity(delta),
6554 )
6555 .into_any_element()
6556 } else {
6557 completion.into_any_element()
6558 };
6559
6560 let has_completion = self.active_inline_completion.is_some();
6561
6562 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6563 Some(
6564 h_flex()
6565 .min_w(min_width)
6566 .max_w(max_width)
6567 .flex_1()
6568 .elevation_2(cx)
6569 .border_color(cx.theme().colors().border)
6570 .child(
6571 div()
6572 .flex_1()
6573 .py_1()
6574 .px_2()
6575 .overflow_hidden()
6576 .child(completion),
6577 )
6578 .when_some(accept_keystroke, |el, accept_keystroke| {
6579 if !accept_keystroke.modifiers.modified() {
6580 return el;
6581 }
6582
6583 el.child(
6584 h_flex()
6585 .h_full()
6586 .border_l_1()
6587 .rounded_r_lg()
6588 .border_color(cx.theme().colors().border)
6589 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6590 .gap_1()
6591 .py_1()
6592 .px_2()
6593 .child(
6594 h_flex()
6595 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6596 .when(is_platform_style_mac, |parent| parent.gap_1())
6597 .child(h_flex().children(ui::render_modifiers(
6598 &accept_keystroke.modifiers,
6599 PlatformStyle::platform(),
6600 Some(if !has_completion {
6601 Color::Muted
6602 } else {
6603 Color::Default
6604 }),
6605 None,
6606 false,
6607 ))),
6608 )
6609 .child(Label::new("Preview").into_any_element())
6610 .opacity(if has_completion { 1.0 } else { 0.4 }),
6611 )
6612 })
6613 .into_any(),
6614 )
6615 }
6616
6617 fn render_edit_prediction_cursor_popover_preview(
6618 &self,
6619 completion: &InlineCompletionState,
6620 cursor_point: Point,
6621 style: &EditorStyle,
6622 cx: &mut Context<Editor>,
6623 ) -> Option<Div> {
6624 use text::ToPoint as _;
6625
6626 fn render_relative_row_jump(
6627 prefix: impl Into<String>,
6628 current_row: u32,
6629 target_row: u32,
6630 ) -> Div {
6631 let (row_diff, arrow) = if target_row < current_row {
6632 (current_row - target_row, IconName::ArrowUp)
6633 } else {
6634 (target_row - current_row, IconName::ArrowDown)
6635 };
6636
6637 h_flex()
6638 .child(
6639 Label::new(format!("{}{}", prefix.into(), row_diff))
6640 .color(Color::Muted)
6641 .size(LabelSize::Small),
6642 )
6643 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6644 }
6645
6646 match &completion.completion {
6647 InlineCompletion::Move {
6648 target, snapshot, ..
6649 } => Some(
6650 h_flex()
6651 .px_2()
6652 .gap_2()
6653 .flex_1()
6654 .child(
6655 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6656 Icon::new(IconName::ZedPredictDown)
6657 } else {
6658 Icon::new(IconName::ZedPredictUp)
6659 },
6660 )
6661 .child(Label::new("Jump to Edit")),
6662 ),
6663
6664 InlineCompletion::Edit {
6665 edits,
6666 edit_preview,
6667 snapshot,
6668 display_mode: _,
6669 } => {
6670 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6671
6672 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6673 &snapshot,
6674 &edits,
6675 edit_preview.as_ref()?,
6676 true,
6677 cx,
6678 )
6679 .first_line_preview();
6680
6681 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6682 .with_highlights(&style.text, highlighted_edits.highlights);
6683
6684 let preview = h_flex()
6685 .gap_1()
6686 .min_w_16()
6687 .child(styled_text)
6688 .when(has_more_lines, |parent| parent.child("…"));
6689
6690 let left = if first_edit_row != cursor_point.row {
6691 render_relative_row_jump("", cursor_point.row, first_edit_row)
6692 .into_any_element()
6693 } else {
6694 Icon::new(IconName::ZedPredict).into_any_element()
6695 };
6696
6697 Some(
6698 h_flex()
6699 .h_full()
6700 .flex_1()
6701 .gap_2()
6702 .pr_1()
6703 .overflow_x_hidden()
6704 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6705 .child(left)
6706 .child(preview),
6707 )
6708 }
6709 }
6710 }
6711
6712 fn render_context_menu(
6713 &self,
6714 style: &EditorStyle,
6715 max_height_in_lines: u32,
6716 y_flipped: bool,
6717 window: &mut Window,
6718 cx: &mut Context<Editor>,
6719 ) -> Option<AnyElement> {
6720 let menu = self.context_menu.borrow();
6721 let menu = menu.as_ref()?;
6722 if !menu.visible() {
6723 return None;
6724 };
6725 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6726 }
6727
6728 fn render_context_menu_aside(
6729 &mut self,
6730 max_size: Size<Pixels>,
6731 window: &mut Window,
6732 cx: &mut Context<Editor>,
6733 ) -> Option<AnyElement> {
6734 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6735 if menu.visible() {
6736 menu.render_aside(self, max_size, window, cx)
6737 } else {
6738 None
6739 }
6740 })
6741 }
6742
6743 fn hide_context_menu(
6744 &mut self,
6745 window: &mut Window,
6746 cx: &mut Context<Self>,
6747 ) -> Option<CodeContextMenu> {
6748 cx.notify();
6749 self.completion_tasks.clear();
6750 let context_menu = self.context_menu.borrow_mut().take();
6751 self.stale_inline_completion_in_menu.take();
6752 self.update_visible_inline_completion(window, cx);
6753 context_menu
6754 }
6755
6756 fn show_snippet_choices(
6757 &mut self,
6758 choices: &Vec<String>,
6759 selection: Range<Anchor>,
6760 cx: &mut Context<Self>,
6761 ) {
6762 if selection.start.buffer_id.is_none() {
6763 return;
6764 }
6765 let buffer_id = selection.start.buffer_id.unwrap();
6766 let buffer = self.buffer().read(cx).buffer(buffer_id);
6767 let id = post_inc(&mut self.next_completion_id);
6768
6769 if let Some(buffer) = buffer {
6770 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6771 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6772 ));
6773 }
6774 }
6775
6776 pub fn insert_snippet(
6777 &mut self,
6778 insertion_ranges: &[Range<usize>],
6779 snippet: Snippet,
6780 window: &mut Window,
6781 cx: &mut Context<Self>,
6782 ) -> Result<()> {
6783 struct Tabstop<T> {
6784 is_end_tabstop: bool,
6785 ranges: Vec<Range<T>>,
6786 choices: Option<Vec<String>>,
6787 }
6788
6789 let tabstops = self.buffer.update(cx, |buffer, cx| {
6790 let snippet_text: Arc<str> = snippet.text.clone().into();
6791 buffer.edit(
6792 insertion_ranges
6793 .iter()
6794 .cloned()
6795 .map(|range| (range, snippet_text.clone())),
6796 Some(AutoindentMode::EachLine),
6797 cx,
6798 );
6799
6800 let snapshot = &*buffer.read(cx);
6801 let snippet = &snippet;
6802 snippet
6803 .tabstops
6804 .iter()
6805 .map(|tabstop| {
6806 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6807 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6808 });
6809 let mut tabstop_ranges = tabstop
6810 .ranges
6811 .iter()
6812 .flat_map(|tabstop_range| {
6813 let mut delta = 0_isize;
6814 insertion_ranges.iter().map(move |insertion_range| {
6815 let insertion_start = insertion_range.start as isize + delta;
6816 delta +=
6817 snippet.text.len() as isize - insertion_range.len() as isize;
6818
6819 let start = ((insertion_start + tabstop_range.start) as usize)
6820 .min(snapshot.len());
6821 let end = ((insertion_start + tabstop_range.end) as usize)
6822 .min(snapshot.len());
6823 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6824 })
6825 })
6826 .collect::<Vec<_>>();
6827 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6828
6829 Tabstop {
6830 is_end_tabstop,
6831 ranges: tabstop_ranges,
6832 choices: tabstop.choices.clone(),
6833 }
6834 })
6835 .collect::<Vec<_>>()
6836 });
6837 if let Some(tabstop) = tabstops.first() {
6838 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6839 s.select_ranges(tabstop.ranges.iter().cloned());
6840 });
6841
6842 if let Some(choices) = &tabstop.choices {
6843 if let Some(selection) = tabstop.ranges.first() {
6844 self.show_snippet_choices(choices, selection.clone(), cx)
6845 }
6846 }
6847
6848 // If we're already at the last tabstop and it's at the end of the snippet,
6849 // we're done, we don't need to keep the state around.
6850 if !tabstop.is_end_tabstop {
6851 let choices = tabstops
6852 .iter()
6853 .map(|tabstop| tabstop.choices.clone())
6854 .collect();
6855
6856 let ranges = tabstops
6857 .into_iter()
6858 .map(|tabstop| tabstop.ranges)
6859 .collect::<Vec<_>>();
6860
6861 self.snippet_stack.push(SnippetState {
6862 active_index: 0,
6863 ranges,
6864 choices,
6865 });
6866 }
6867
6868 // Check whether the just-entered snippet ends with an auto-closable bracket.
6869 if self.autoclose_regions.is_empty() {
6870 let snapshot = self.buffer.read(cx).snapshot(cx);
6871 for selection in &mut self.selections.all::<Point>(cx) {
6872 let selection_head = selection.head();
6873 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6874 continue;
6875 };
6876
6877 let mut bracket_pair = None;
6878 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6879 let prev_chars = snapshot
6880 .reversed_chars_at(selection_head)
6881 .collect::<String>();
6882 for (pair, enabled) in scope.brackets() {
6883 if enabled
6884 && pair.close
6885 && prev_chars.starts_with(pair.start.as_str())
6886 && next_chars.starts_with(pair.end.as_str())
6887 {
6888 bracket_pair = Some(pair.clone());
6889 break;
6890 }
6891 }
6892 if let Some(pair) = bracket_pair {
6893 let start = snapshot.anchor_after(selection_head);
6894 let end = snapshot.anchor_after(selection_head);
6895 self.autoclose_regions.push(AutocloseRegion {
6896 selection_id: selection.id,
6897 range: start..end,
6898 pair,
6899 });
6900 }
6901 }
6902 }
6903 }
6904 Ok(())
6905 }
6906
6907 pub fn move_to_next_snippet_tabstop(
6908 &mut self,
6909 window: &mut Window,
6910 cx: &mut Context<Self>,
6911 ) -> bool {
6912 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6913 }
6914
6915 pub fn move_to_prev_snippet_tabstop(
6916 &mut self,
6917 window: &mut Window,
6918 cx: &mut Context<Self>,
6919 ) -> bool {
6920 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6921 }
6922
6923 pub fn move_to_snippet_tabstop(
6924 &mut self,
6925 bias: Bias,
6926 window: &mut Window,
6927 cx: &mut Context<Self>,
6928 ) -> bool {
6929 if let Some(mut snippet) = self.snippet_stack.pop() {
6930 match bias {
6931 Bias::Left => {
6932 if snippet.active_index > 0 {
6933 snippet.active_index -= 1;
6934 } else {
6935 self.snippet_stack.push(snippet);
6936 return false;
6937 }
6938 }
6939 Bias::Right => {
6940 if snippet.active_index + 1 < snippet.ranges.len() {
6941 snippet.active_index += 1;
6942 } else {
6943 self.snippet_stack.push(snippet);
6944 return false;
6945 }
6946 }
6947 }
6948 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6949 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6950 s.select_anchor_ranges(current_ranges.iter().cloned())
6951 });
6952
6953 if let Some(choices) = &snippet.choices[snippet.active_index] {
6954 if let Some(selection) = current_ranges.first() {
6955 self.show_snippet_choices(&choices, selection.clone(), cx);
6956 }
6957 }
6958
6959 // If snippet state is not at the last tabstop, push it back on the stack
6960 if snippet.active_index + 1 < snippet.ranges.len() {
6961 self.snippet_stack.push(snippet);
6962 }
6963 return true;
6964 }
6965 }
6966
6967 false
6968 }
6969
6970 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6971 self.transact(window, cx, |this, window, cx| {
6972 this.select_all(&SelectAll, window, cx);
6973 this.insert("", window, cx);
6974 });
6975 }
6976
6977 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6978 self.transact(window, cx, |this, window, cx| {
6979 this.select_autoclose_pair(window, cx);
6980 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6981 if !this.linked_edit_ranges.is_empty() {
6982 let selections = this.selections.all::<MultiBufferPoint>(cx);
6983 let snapshot = this.buffer.read(cx).snapshot(cx);
6984
6985 for selection in selections.iter() {
6986 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6987 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6988 if selection_start.buffer_id != selection_end.buffer_id {
6989 continue;
6990 }
6991 if let Some(ranges) =
6992 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6993 {
6994 for (buffer, entries) in ranges {
6995 linked_ranges.entry(buffer).or_default().extend(entries);
6996 }
6997 }
6998 }
6999 }
7000
7001 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7002 if !this.selections.line_mode {
7003 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7004 for selection in &mut selections {
7005 if selection.is_empty() {
7006 let old_head = selection.head();
7007 let mut new_head =
7008 movement::left(&display_map, old_head.to_display_point(&display_map))
7009 .to_point(&display_map);
7010 if let Some((buffer, line_buffer_range)) = display_map
7011 .buffer_snapshot
7012 .buffer_line_for_row(MultiBufferRow(old_head.row))
7013 {
7014 let indent_size =
7015 buffer.indent_size_for_line(line_buffer_range.start.row);
7016 let indent_len = match indent_size.kind {
7017 IndentKind::Space => {
7018 buffer.settings_at(line_buffer_range.start, cx).tab_size
7019 }
7020 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7021 };
7022 if old_head.column <= indent_size.len && old_head.column > 0 {
7023 let indent_len = indent_len.get();
7024 new_head = cmp::min(
7025 new_head,
7026 MultiBufferPoint::new(
7027 old_head.row,
7028 ((old_head.column - 1) / indent_len) * indent_len,
7029 ),
7030 );
7031 }
7032 }
7033
7034 selection.set_head(new_head, SelectionGoal::None);
7035 }
7036 }
7037 }
7038
7039 this.signature_help_state.set_backspace_pressed(true);
7040 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7041 s.select(selections)
7042 });
7043 this.insert("", window, cx);
7044 let empty_str: Arc<str> = Arc::from("");
7045 for (buffer, edits) in linked_ranges {
7046 let snapshot = buffer.read(cx).snapshot();
7047 use text::ToPoint as TP;
7048
7049 let edits = edits
7050 .into_iter()
7051 .map(|range| {
7052 let end_point = TP::to_point(&range.end, &snapshot);
7053 let mut start_point = TP::to_point(&range.start, &snapshot);
7054
7055 if end_point == start_point {
7056 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7057 .saturating_sub(1);
7058 start_point =
7059 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7060 };
7061
7062 (start_point..end_point, empty_str.clone())
7063 })
7064 .sorted_by_key(|(range, _)| range.start)
7065 .collect::<Vec<_>>();
7066 buffer.update(cx, |this, cx| {
7067 this.edit(edits, None, cx);
7068 })
7069 }
7070 this.refresh_inline_completion(true, false, window, cx);
7071 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7072 });
7073 }
7074
7075 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7076 self.transact(window, cx, |this, window, cx| {
7077 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7078 let line_mode = s.line_mode;
7079 s.move_with(|map, selection| {
7080 if selection.is_empty() && !line_mode {
7081 let cursor = movement::right(map, selection.head());
7082 selection.end = cursor;
7083 selection.reversed = true;
7084 selection.goal = SelectionGoal::None;
7085 }
7086 })
7087 });
7088 this.insert("", window, cx);
7089 this.refresh_inline_completion(true, false, window, cx);
7090 });
7091 }
7092
7093 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
7094 if self.move_to_prev_snippet_tabstop(window, cx) {
7095 return;
7096 }
7097
7098 self.outdent(&Outdent, window, cx);
7099 }
7100
7101 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7102 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7103 return;
7104 }
7105
7106 let mut selections = self.selections.all_adjusted(cx);
7107 let buffer = self.buffer.read(cx);
7108 let snapshot = buffer.snapshot(cx);
7109 let rows_iter = selections.iter().map(|s| s.head().row);
7110 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7111
7112 let mut edits = Vec::new();
7113 let mut prev_edited_row = 0;
7114 let mut row_delta = 0;
7115 for selection in &mut selections {
7116 if selection.start.row != prev_edited_row {
7117 row_delta = 0;
7118 }
7119 prev_edited_row = selection.end.row;
7120
7121 // If the selection is non-empty, then increase the indentation of the selected lines.
7122 if !selection.is_empty() {
7123 row_delta =
7124 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7125 continue;
7126 }
7127
7128 // If the selection is empty and the cursor is in the leading whitespace before the
7129 // suggested indentation, then auto-indent the line.
7130 let cursor = selection.head();
7131 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7132 if let Some(suggested_indent) =
7133 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7134 {
7135 if cursor.column < suggested_indent.len
7136 && cursor.column <= current_indent.len
7137 && current_indent.len <= suggested_indent.len
7138 {
7139 selection.start = Point::new(cursor.row, suggested_indent.len);
7140 selection.end = selection.start;
7141 if row_delta == 0 {
7142 edits.extend(Buffer::edit_for_indent_size_adjustment(
7143 cursor.row,
7144 current_indent,
7145 suggested_indent,
7146 ));
7147 row_delta = suggested_indent.len - current_indent.len;
7148 }
7149 continue;
7150 }
7151 }
7152
7153 // Otherwise, insert a hard or soft tab.
7154 let settings = buffer.settings_at(cursor, cx);
7155 let tab_size = if settings.hard_tabs {
7156 IndentSize::tab()
7157 } else {
7158 let tab_size = settings.tab_size.get();
7159 let char_column = snapshot
7160 .text_for_range(Point::new(cursor.row, 0)..cursor)
7161 .flat_map(str::chars)
7162 .count()
7163 + row_delta as usize;
7164 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7165 IndentSize::spaces(chars_to_next_tab_stop)
7166 };
7167 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7168 selection.end = selection.start;
7169 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7170 row_delta += tab_size.len;
7171 }
7172
7173 self.transact(window, cx, |this, window, cx| {
7174 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7175 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7176 s.select(selections)
7177 });
7178 this.refresh_inline_completion(true, false, window, cx);
7179 });
7180 }
7181
7182 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7183 if self.read_only(cx) {
7184 return;
7185 }
7186 let mut selections = self.selections.all::<Point>(cx);
7187 let mut prev_edited_row = 0;
7188 let mut row_delta = 0;
7189 let mut edits = Vec::new();
7190 let buffer = self.buffer.read(cx);
7191 let snapshot = buffer.snapshot(cx);
7192 for selection in &mut selections {
7193 if selection.start.row != prev_edited_row {
7194 row_delta = 0;
7195 }
7196 prev_edited_row = selection.end.row;
7197
7198 row_delta =
7199 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7200 }
7201
7202 self.transact(window, cx, |this, window, cx| {
7203 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7204 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7205 s.select(selections)
7206 });
7207 });
7208 }
7209
7210 fn indent_selection(
7211 buffer: &MultiBuffer,
7212 snapshot: &MultiBufferSnapshot,
7213 selection: &mut Selection<Point>,
7214 edits: &mut Vec<(Range<Point>, String)>,
7215 delta_for_start_row: u32,
7216 cx: &App,
7217 ) -> u32 {
7218 let settings = buffer.settings_at(selection.start, cx);
7219 let tab_size = settings.tab_size.get();
7220 let indent_kind = if settings.hard_tabs {
7221 IndentKind::Tab
7222 } else {
7223 IndentKind::Space
7224 };
7225 let mut start_row = selection.start.row;
7226 let mut end_row = selection.end.row + 1;
7227
7228 // If a selection ends at the beginning of a line, don't indent
7229 // that last line.
7230 if selection.end.column == 0 && selection.end.row > selection.start.row {
7231 end_row -= 1;
7232 }
7233
7234 // Avoid re-indenting a row that has already been indented by a
7235 // previous selection, but still update this selection's column
7236 // to reflect that indentation.
7237 if delta_for_start_row > 0 {
7238 start_row += 1;
7239 selection.start.column += delta_for_start_row;
7240 if selection.end.row == selection.start.row {
7241 selection.end.column += delta_for_start_row;
7242 }
7243 }
7244
7245 let mut delta_for_end_row = 0;
7246 let has_multiple_rows = start_row + 1 != end_row;
7247 for row in start_row..end_row {
7248 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7249 let indent_delta = match (current_indent.kind, indent_kind) {
7250 (IndentKind::Space, IndentKind::Space) => {
7251 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7252 IndentSize::spaces(columns_to_next_tab_stop)
7253 }
7254 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7255 (_, IndentKind::Tab) => IndentSize::tab(),
7256 };
7257
7258 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7259 0
7260 } else {
7261 selection.start.column
7262 };
7263 let row_start = Point::new(row, start);
7264 edits.push((
7265 row_start..row_start,
7266 indent_delta.chars().collect::<String>(),
7267 ));
7268
7269 // Update this selection's endpoints to reflect the indentation.
7270 if row == selection.start.row {
7271 selection.start.column += indent_delta.len;
7272 }
7273 if row == selection.end.row {
7274 selection.end.column += indent_delta.len;
7275 delta_for_end_row = indent_delta.len;
7276 }
7277 }
7278
7279 if selection.start.row == selection.end.row {
7280 delta_for_start_row + delta_for_end_row
7281 } else {
7282 delta_for_end_row
7283 }
7284 }
7285
7286 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7287 if self.read_only(cx) {
7288 return;
7289 }
7290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7291 let selections = self.selections.all::<Point>(cx);
7292 let mut deletion_ranges = Vec::new();
7293 let mut last_outdent = None;
7294 {
7295 let buffer = self.buffer.read(cx);
7296 let snapshot = buffer.snapshot(cx);
7297 for selection in &selections {
7298 let settings = buffer.settings_at(selection.start, cx);
7299 let tab_size = settings.tab_size.get();
7300 let mut rows = selection.spanned_rows(false, &display_map);
7301
7302 // Avoid re-outdenting a row that has already been outdented by a
7303 // previous selection.
7304 if let Some(last_row) = last_outdent {
7305 if last_row == rows.start {
7306 rows.start = rows.start.next_row();
7307 }
7308 }
7309 let has_multiple_rows = rows.len() > 1;
7310 for row in rows.iter_rows() {
7311 let indent_size = snapshot.indent_size_for_line(row);
7312 if indent_size.len > 0 {
7313 let deletion_len = match indent_size.kind {
7314 IndentKind::Space => {
7315 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7316 if columns_to_prev_tab_stop == 0 {
7317 tab_size
7318 } else {
7319 columns_to_prev_tab_stop
7320 }
7321 }
7322 IndentKind::Tab => 1,
7323 };
7324 let start = if has_multiple_rows
7325 || deletion_len > selection.start.column
7326 || indent_size.len < selection.start.column
7327 {
7328 0
7329 } else {
7330 selection.start.column - deletion_len
7331 };
7332 deletion_ranges.push(
7333 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7334 );
7335 last_outdent = Some(row);
7336 }
7337 }
7338 }
7339 }
7340
7341 self.transact(window, cx, |this, window, cx| {
7342 this.buffer.update(cx, |buffer, cx| {
7343 let empty_str: Arc<str> = Arc::default();
7344 buffer.edit(
7345 deletion_ranges
7346 .into_iter()
7347 .map(|range| (range, empty_str.clone())),
7348 None,
7349 cx,
7350 );
7351 });
7352 let selections = this.selections.all::<usize>(cx);
7353 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7354 s.select(selections)
7355 });
7356 });
7357 }
7358
7359 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7360 if self.read_only(cx) {
7361 return;
7362 }
7363 let selections = self
7364 .selections
7365 .all::<usize>(cx)
7366 .into_iter()
7367 .map(|s| s.range());
7368
7369 self.transact(window, cx, |this, window, cx| {
7370 this.buffer.update(cx, |buffer, cx| {
7371 buffer.autoindent_ranges(selections, cx);
7372 });
7373 let selections = this.selections.all::<usize>(cx);
7374 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7375 s.select(selections)
7376 });
7377 });
7378 }
7379
7380 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7382 let selections = self.selections.all::<Point>(cx);
7383
7384 let mut new_cursors = Vec::new();
7385 let mut edit_ranges = Vec::new();
7386 let mut selections = selections.iter().peekable();
7387 while let Some(selection) = selections.next() {
7388 let mut rows = selection.spanned_rows(false, &display_map);
7389 let goal_display_column = selection.head().to_display_point(&display_map).column();
7390
7391 // Accumulate contiguous regions of rows that we want to delete.
7392 while let Some(next_selection) = selections.peek() {
7393 let next_rows = next_selection.spanned_rows(false, &display_map);
7394 if next_rows.start <= rows.end {
7395 rows.end = next_rows.end;
7396 selections.next().unwrap();
7397 } else {
7398 break;
7399 }
7400 }
7401
7402 let buffer = &display_map.buffer_snapshot;
7403 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7404 let edit_end;
7405 let cursor_buffer_row;
7406 if buffer.max_point().row >= rows.end.0 {
7407 // If there's a line after the range, delete the \n from the end of the row range
7408 // and position the cursor on the next line.
7409 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7410 cursor_buffer_row = rows.end;
7411 } else {
7412 // If there isn't a line after the range, delete the \n from the line before the
7413 // start of the row range and position the cursor there.
7414 edit_start = edit_start.saturating_sub(1);
7415 edit_end = buffer.len();
7416 cursor_buffer_row = rows.start.previous_row();
7417 }
7418
7419 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7420 *cursor.column_mut() =
7421 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7422
7423 new_cursors.push((
7424 selection.id,
7425 buffer.anchor_after(cursor.to_point(&display_map)),
7426 ));
7427 edit_ranges.push(edit_start..edit_end);
7428 }
7429
7430 self.transact(window, cx, |this, window, cx| {
7431 let buffer = this.buffer.update(cx, |buffer, cx| {
7432 let empty_str: Arc<str> = Arc::default();
7433 buffer.edit(
7434 edit_ranges
7435 .into_iter()
7436 .map(|range| (range, empty_str.clone())),
7437 None,
7438 cx,
7439 );
7440 buffer.snapshot(cx)
7441 });
7442 let new_selections = new_cursors
7443 .into_iter()
7444 .map(|(id, cursor)| {
7445 let cursor = cursor.to_point(&buffer);
7446 Selection {
7447 id,
7448 start: cursor,
7449 end: cursor,
7450 reversed: false,
7451 goal: SelectionGoal::None,
7452 }
7453 })
7454 .collect();
7455
7456 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7457 s.select(new_selections);
7458 });
7459 });
7460 }
7461
7462 pub fn join_lines_impl(
7463 &mut self,
7464 insert_whitespace: bool,
7465 window: &mut Window,
7466 cx: &mut Context<Self>,
7467 ) {
7468 if self.read_only(cx) {
7469 return;
7470 }
7471 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7472 for selection in self.selections.all::<Point>(cx) {
7473 let start = MultiBufferRow(selection.start.row);
7474 // Treat single line selections as if they include the next line. Otherwise this action
7475 // would do nothing for single line selections individual cursors.
7476 let end = if selection.start.row == selection.end.row {
7477 MultiBufferRow(selection.start.row + 1)
7478 } else {
7479 MultiBufferRow(selection.end.row)
7480 };
7481
7482 if let Some(last_row_range) = row_ranges.last_mut() {
7483 if start <= last_row_range.end {
7484 last_row_range.end = end;
7485 continue;
7486 }
7487 }
7488 row_ranges.push(start..end);
7489 }
7490
7491 let snapshot = self.buffer.read(cx).snapshot(cx);
7492 let mut cursor_positions = Vec::new();
7493 for row_range in &row_ranges {
7494 let anchor = snapshot.anchor_before(Point::new(
7495 row_range.end.previous_row().0,
7496 snapshot.line_len(row_range.end.previous_row()),
7497 ));
7498 cursor_positions.push(anchor..anchor);
7499 }
7500
7501 self.transact(window, cx, |this, window, cx| {
7502 for row_range in row_ranges.into_iter().rev() {
7503 for row in row_range.iter_rows().rev() {
7504 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7505 let next_line_row = row.next_row();
7506 let indent = snapshot.indent_size_for_line(next_line_row);
7507 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7508
7509 let replace =
7510 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7511 " "
7512 } else {
7513 ""
7514 };
7515
7516 this.buffer.update(cx, |buffer, cx| {
7517 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7518 });
7519 }
7520 }
7521
7522 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7523 s.select_anchor_ranges(cursor_positions)
7524 });
7525 });
7526 }
7527
7528 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7529 self.join_lines_impl(true, window, cx);
7530 }
7531
7532 pub fn sort_lines_case_sensitive(
7533 &mut self,
7534 _: &SortLinesCaseSensitive,
7535 window: &mut Window,
7536 cx: &mut Context<Self>,
7537 ) {
7538 self.manipulate_lines(window, cx, |lines| lines.sort())
7539 }
7540
7541 pub fn sort_lines_case_insensitive(
7542 &mut self,
7543 _: &SortLinesCaseInsensitive,
7544 window: &mut Window,
7545 cx: &mut Context<Self>,
7546 ) {
7547 self.manipulate_lines(window, cx, |lines| {
7548 lines.sort_by_key(|line| line.to_lowercase())
7549 })
7550 }
7551
7552 pub fn unique_lines_case_insensitive(
7553 &mut self,
7554 _: &UniqueLinesCaseInsensitive,
7555 window: &mut Window,
7556 cx: &mut Context<Self>,
7557 ) {
7558 self.manipulate_lines(window, cx, |lines| {
7559 let mut seen = HashSet::default();
7560 lines.retain(|line| seen.insert(line.to_lowercase()));
7561 })
7562 }
7563
7564 pub fn unique_lines_case_sensitive(
7565 &mut self,
7566 _: &UniqueLinesCaseSensitive,
7567 window: &mut Window,
7568 cx: &mut Context<Self>,
7569 ) {
7570 self.manipulate_lines(window, cx, |lines| {
7571 let mut seen = HashSet::default();
7572 lines.retain(|line| seen.insert(*line));
7573 })
7574 }
7575
7576 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7577 let Some(project) = self.project.clone() else {
7578 return;
7579 };
7580 self.reload(project, window, cx)
7581 .detach_and_notify_err(window, cx);
7582 }
7583
7584 pub fn restore_file(
7585 &mut self,
7586 _: &::git::RestoreFile,
7587 window: &mut Window,
7588 cx: &mut Context<Self>,
7589 ) {
7590 let mut buffer_ids = HashSet::default();
7591 let snapshot = self.buffer().read(cx).snapshot(cx);
7592 for selection in self.selections.all::<usize>(cx) {
7593 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7594 }
7595
7596 let buffer = self.buffer().read(cx);
7597 let ranges = buffer_ids
7598 .into_iter()
7599 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7600 .collect::<Vec<_>>();
7601
7602 self.restore_hunks_in_ranges(ranges, window, cx);
7603 }
7604
7605 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7606 let selections = self
7607 .selections
7608 .all(cx)
7609 .into_iter()
7610 .map(|s| s.range())
7611 .collect();
7612 self.restore_hunks_in_ranges(selections, window, cx);
7613 }
7614
7615 fn restore_hunks_in_ranges(
7616 &mut self,
7617 ranges: Vec<Range<Point>>,
7618 window: &mut Window,
7619 cx: &mut Context<Editor>,
7620 ) {
7621 let mut revert_changes = HashMap::default();
7622 let snapshot = self.buffer.read(cx).snapshot(cx);
7623 let Some(project) = &self.project else {
7624 return;
7625 };
7626
7627 let chunk_by = self
7628 .snapshot(window, cx)
7629 .hunks_for_ranges(ranges.into_iter())
7630 .into_iter()
7631 .chunk_by(|hunk| hunk.buffer_id);
7632 for (buffer_id, hunks) in &chunk_by {
7633 let hunks = hunks.collect::<Vec<_>>();
7634 for hunk in &hunks {
7635 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7636 }
7637 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7638 }
7639 drop(chunk_by);
7640 if !revert_changes.is_empty() {
7641 self.transact(window, cx, |editor, window, cx| {
7642 editor.revert(revert_changes, window, cx);
7643 });
7644 }
7645 }
7646
7647 pub fn open_active_item_in_terminal(
7648 &mut self,
7649 _: &OpenInTerminal,
7650 window: &mut Window,
7651 cx: &mut Context<Self>,
7652 ) {
7653 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7654 let project_path = buffer.read(cx).project_path(cx)?;
7655 let project = self.project.as_ref()?.read(cx);
7656 let entry = project.entry_for_path(&project_path, cx)?;
7657 let parent = match &entry.canonical_path {
7658 Some(canonical_path) => canonical_path.to_path_buf(),
7659 None => project.absolute_path(&project_path, cx)?,
7660 }
7661 .parent()?
7662 .to_path_buf();
7663 Some(parent)
7664 }) {
7665 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7666 }
7667 }
7668
7669 pub fn prepare_restore_change(
7670 &self,
7671 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7672 hunk: &MultiBufferDiffHunk,
7673 cx: &mut App,
7674 ) -> Option<()> {
7675 let buffer = self.buffer.read(cx);
7676 let diff = buffer.diff_for(hunk.buffer_id)?;
7677 let buffer = buffer.buffer(hunk.buffer_id)?;
7678 let buffer = buffer.read(cx);
7679 let original_text = diff
7680 .read(cx)
7681 .base_text()
7682 .as_ref()?
7683 .as_rope()
7684 .slice(hunk.diff_base_byte_range.clone());
7685 let buffer_snapshot = buffer.snapshot();
7686 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7687 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7688 probe
7689 .0
7690 .start
7691 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7692 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7693 }) {
7694 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7695 Some(())
7696 } else {
7697 None
7698 }
7699 }
7700
7701 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7702 self.manipulate_lines(window, cx, |lines| lines.reverse())
7703 }
7704
7705 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7706 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7707 }
7708
7709 fn manipulate_lines<Fn>(
7710 &mut self,
7711 window: &mut Window,
7712 cx: &mut Context<Self>,
7713 mut callback: Fn,
7714 ) where
7715 Fn: FnMut(&mut Vec<&str>),
7716 {
7717 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7718 let buffer = self.buffer.read(cx).snapshot(cx);
7719
7720 let mut edits = Vec::new();
7721
7722 let selections = self.selections.all::<Point>(cx);
7723 let mut selections = selections.iter().peekable();
7724 let mut contiguous_row_selections = Vec::new();
7725 let mut new_selections = Vec::new();
7726 let mut added_lines = 0;
7727 let mut removed_lines = 0;
7728
7729 while let Some(selection) = selections.next() {
7730 let (start_row, end_row) = consume_contiguous_rows(
7731 &mut contiguous_row_selections,
7732 selection,
7733 &display_map,
7734 &mut selections,
7735 );
7736
7737 let start_point = Point::new(start_row.0, 0);
7738 let end_point = Point::new(
7739 end_row.previous_row().0,
7740 buffer.line_len(end_row.previous_row()),
7741 );
7742 let text = buffer
7743 .text_for_range(start_point..end_point)
7744 .collect::<String>();
7745
7746 let mut lines = text.split('\n').collect_vec();
7747
7748 let lines_before = lines.len();
7749 callback(&mut lines);
7750 let lines_after = lines.len();
7751
7752 edits.push((start_point..end_point, lines.join("\n")));
7753
7754 // Selections must change based on added and removed line count
7755 let start_row =
7756 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7757 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7758 new_selections.push(Selection {
7759 id: selection.id,
7760 start: start_row,
7761 end: end_row,
7762 goal: SelectionGoal::None,
7763 reversed: selection.reversed,
7764 });
7765
7766 if lines_after > lines_before {
7767 added_lines += lines_after - lines_before;
7768 } else if lines_before > lines_after {
7769 removed_lines += lines_before - lines_after;
7770 }
7771 }
7772
7773 self.transact(window, cx, |this, window, cx| {
7774 let buffer = this.buffer.update(cx, |buffer, cx| {
7775 buffer.edit(edits, None, cx);
7776 buffer.snapshot(cx)
7777 });
7778
7779 // Recalculate offsets on newly edited buffer
7780 let new_selections = new_selections
7781 .iter()
7782 .map(|s| {
7783 let start_point = Point::new(s.start.0, 0);
7784 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7785 Selection {
7786 id: s.id,
7787 start: buffer.point_to_offset(start_point),
7788 end: buffer.point_to_offset(end_point),
7789 goal: s.goal,
7790 reversed: s.reversed,
7791 }
7792 })
7793 .collect();
7794
7795 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7796 s.select(new_selections);
7797 });
7798
7799 this.request_autoscroll(Autoscroll::fit(), cx);
7800 });
7801 }
7802
7803 pub fn convert_to_upper_case(
7804 &mut self,
7805 _: &ConvertToUpperCase,
7806 window: &mut Window,
7807 cx: &mut Context<Self>,
7808 ) {
7809 self.manipulate_text(window, cx, |text| text.to_uppercase())
7810 }
7811
7812 pub fn convert_to_lower_case(
7813 &mut self,
7814 _: &ConvertToLowerCase,
7815 window: &mut Window,
7816 cx: &mut Context<Self>,
7817 ) {
7818 self.manipulate_text(window, cx, |text| text.to_lowercase())
7819 }
7820
7821 pub fn convert_to_title_case(
7822 &mut self,
7823 _: &ConvertToTitleCase,
7824 window: &mut Window,
7825 cx: &mut Context<Self>,
7826 ) {
7827 self.manipulate_text(window, cx, |text| {
7828 text.split('\n')
7829 .map(|line| line.to_case(Case::Title))
7830 .join("\n")
7831 })
7832 }
7833
7834 pub fn convert_to_snake_case(
7835 &mut self,
7836 _: &ConvertToSnakeCase,
7837 window: &mut Window,
7838 cx: &mut Context<Self>,
7839 ) {
7840 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7841 }
7842
7843 pub fn convert_to_kebab_case(
7844 &mut self,
7845 _: &ConvertToKebabCase,
7846 window: &mut Window,
7847 cx: &mut Context<Self>,
7848 ) {
7849 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7850 }
7851
7852 pub fn convert_to_upper_camel_case(
7853 &mut self,
7854 _: &ConvertToUpperCamelCase,
7855 window: &mut Window,
7856 cx: &mut Context<Self>,
7857 ) {
7858 self.manipulate_text(window, cx, |text| {
7859 text.split('\n')
7860 .map(|line| line.to_case(Case::UpperCamel))
7861 .join("\n")
7862 })
7863 }
7864
7865 pub fn convert_to_lower_camel_case(
7866 &mut self,
7867 _: &ConvertToLowerCamelCase,
7868 window: &mut Window,
7869 cx: &mut Context<Self>,
7870 ) {
7871 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7872 }
7873
7874 pub fn convert_to_opposite_case(
7875 &mut self,
7876 _: &ConvertToOppositeCase,
7877 window: &mut Window,
7878 cx: &mut Context<Self>,
7879 ) {
7880 self.manipulate_text(window, cx, |text| {
7881 text.chars()
7882 .fold(String::with_capacity(text.len()), |mut t, c| {
7883 if c.is_uppercase() {
7884 t.extend(c.to_lowercase());
7885 } else {
7886 t.extend(c.to_uppercase());
7887 }
7888 t
7889 })
7890 })
7891 }
7892
7893 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7894 where
7895 Fn: FnMut(&str) -> String,
7896 {
7897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7898 let buffer = self.buffer.read(cx).snapshot(cx);
7899
7900 let mut new_selections = Vec::new();
7901 let mut edits = Vec::new();
7902 let mut selection_adjustment = 0i32;
7903
7904 for selection in self.selections.all::<usize>(cx) {
7905 let selection_is_empty = selection.is_empty();
7906
7907 let (start, end) = if selection_is_empty {
7908 let word_range = movement::surrounding_word(
7909 &display_map,
7910 selection.start.to_display_point(&display_map),
7911 );
7912 let start = word_range.start.to_offset(&display_map, Bias::Left);
7913 let end = word_range.end.to_offset(&display_map, Bias::Left);
7914 (start, end)
7915 } else {
7916 (selection.start, selection.end)
7917 };
7918
7919 let text = buffer.text_for_range(start..end).collect::<String>();
7920 let old_length = text.len() as i32;
7921 let text = callback(&text);
7922
7923 new_selections.push(Selection {
7924 start: (start as i32 - selection_adjustment) as usize,
7925 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7926 goal: SelectionGoal::None,
7927 ..selection
7928 });
7929
7930 selection_adjustment += old_length - text.len() as i32;
7931
7932 edits.push((start..end, text));
7933 }
7934
7935 self.transact(window, cx, |this, window, cx| {
7936 this.buffer.update(cx, |buffer, cx| {
7937 buffer.edit(edits, None, cx);
7938 });
7939
7940 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7941 s.select(new_selections);
7942 });
7943
7944 this.request_autoscroll(Autoscroll::fit(), cx);
7945 });
7946 }
7947
7948 pub fn duplicate(
7949 &mut self,
7950 upwards: bool,
7951 whole_lines: bool,
7952 window: &mut Window,
7953 cx: &mut Context<Self>,
7954 ) {
7955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7956 let buffer = &display_map.buffer_snapshot;
7957 let selections = self.selections.all::<Point>(cx);
7958
7959 let mut edits = Vec::new();
7960 let mut selections_iter = selections.iter().peekable();
7961 while let Some(selection) = selections_iter.next() {
7962 let mut rows = selection.spanned_rows(false, &display_map);
7963 // duplicate line-wise
7964 if whole_lines || selection.start == selection.end {
7965 // Avoid duplicating the same lines twice.
7966 while let Some(next_selection) = selections_iter.peek() {
7967 let next_rows = next_selection.spanned_rows(false, &display_map);
7968 if next_rows.start < rows.end {
7969 rows.end = next_rows.end;
7970 selections_iter.next().unwrap();
7971 } else {
7972 break;
7973 }
7974 }
7975
7976 // Copy the text from the selected row region and splice it either at the start
7977 // or end of the region.
7978 let start = Point::new(rows.start.0, 0);
7979 let end = Point::new(
7980 rows.end.previous_row().0,
7981 buffer.line_len(rows.end.previous_row()),
7982 );
7983 let text = buffer
7984 .text_for_range(start..end)
7985 .chain(Some("\n"))
7986 .collect::<String>();
7987 let insert_location = if upwards {
7988 Point::new(rows.end.0, 0)
7989 } else {
7990 start
7991 };
7992 edits.push((insert_location..insert_location, text));
7993 } else {
7994 // duplicate character-wise
7995 let start = selection.start;
7996 let end = selection.end;
7997 let text = buffer.text_for_range(start..end).collect::<String>();
7998 edits.push((selection.end..selection.end, text));
7999 }
8000 }
8001
8002 self.transact(window, cx, |this, _, cx| {
8003 this.buffer.update(cx, |buffer, cx| {
8004 buffer.edit(edits, None, cx);
8005 });
8006
8007 this.request_autoscroll(Autoscroll::fit(), cx);
8008 });
8009 }
8010
8011 pub fn duplicate_line_up(
8012 &mut self,
8013 _: &DuplicateLineUp,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 self.duplicate(true, true, window, cx);
8018 }
8019
8020 pub fn duplicate_line_down(
8021 &mut self,
8022 _: &DuplicateLineDown,
8023 window: &mut Window,
8024 cx: &mut Context<Self>,
8025 ) {
8026 self.duplicate(false, true, window, cx);
8027 }
8028
8029 pub fn duplicate_selection(
8030 &mut self,
8031 _: &DuplicateSelection,
8032 window: &mut Window,
8033 cx: &mut Context<Self>,
8034 ) {
8035 self.duplicate(false, false, window, cx);
8036 }
8037
8038 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8039 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8040 let buffer = self.buffer.read(cx).snapshot(cx);
8041
8042 let mut edits = Vec::new();
8043 let mut unfold_ranges = Vec::new();
8044 let mut refold_creases = Vec::new();
8045
8046 let selections = self.selections.all::<Point>(cx);
8047 let mut selections = selections.iter().peekable();
8048 let mut contiguous_row_selections = Vec::new();
8049 let mut new_selections = Vec::new();
8050
8051 while let Some(selection) = selections.next() {
8052 // Find all the selections that span a contiguous row range
8053 let (start_row, end_row) = consume_contiguous_rows(
8054 &mut contiguous_row_selections,
8055 selection,
8056 &display_map,
8057 &mut selections,
8058 );
8059
8060 // Move the text spanned by the row range to be before the line preceding the row range
8061 if start_row.0 > 0 {
8062 let range_to_move = Point::new(
8063 start_row.previous_row().0,
8064 buffer.line_len(start_row.previous_row()),
8065 )
8066 ..Point::new(
8067 end_row.previous_row().0,
8068 buffer.line_len(end_row.previous_row()),
8069 );
8070 let insertion_point = display_map
8071 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8072 .0;
8073
8074 // Don't move lines across excerpts
8075 if buffer
8076 .excerpt_containing(insertion_point..range_to_move.end)
8077 .is_some()
8078 {
8079 let text = buffer
8080 .text_for_range(range_to_move.clone())
8081 .flat_map(|s| s.chars())
8082 .skip(1)
8083 .chain(['\n'])
8084 .collect::<String>();
8085
8086 edits.push((
8087 buffer.anchor_after(range_to_move.start)
8088 ..buffer.anchor_before(range_to_move.end),
8089 String::new(),
8090 ));
8091 let insertion_anchor = buffer.anchor_after(insertion_point);
8092 edits.push((insertion_anchor..insertion_anchor, text));
8093
8094 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8095
8096 // Move selections up
8097 new_selections.extend(contiguous_row_selections.drain(..).map(
8098 |mut selection| {
8099 selection.start.row -= row_delta;
8100 selection.end.row -= row_delta;
8101 selection
8102 },
8103 ));
8104
8105 // Move folds up
8106 unfold_ranges.push(range_to_move.clone());
8107 for fold in display_map.folds_in_range(
8108 buffer.anchor_before(range_to_move.start)
8109 ..buffer.anchor_after(range_to_move.end),
8110 ) {
8111 let mut start = fold.range.start.to_point(&buffer);
8112 let mut end = fold.range.end.to_point(&buffer);
8113 start.row -= row_delta;
8114 end.row -= row_delta;
8115 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8116 }
8117 }
8118 }
8119
8120 // If we didn't move line(s), preserve the existing selections
8121 new_selections.append(&mut contiguous_row_selections);
8122 }
8123
8124 self.transact(window, cx, |this, window, cx| {
8125 this.unfold_ranges(&unfold_ranges, true, true, cx);
8126 this.buffer.update(cx, |buffer, cx| {
8127 for (range, text) in edits {
8128 buffer.edit([(range, text)], None, cx);
8129 }
8130 });
8131 this.fold_creases(refold_creases, true, window, cx);
8132 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8133 s.select(new_selections);
8134 })
8135 });
8136 }
8137
8138 pub fn move_line_down(
8139 &mut self,
8140 _: &MoveLineDown,
8141 window: &mut Window,
8142 cx: &mut Context<Self>,
8143 ) {
8144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8145 let buffer = self.buffer.read(cx).snapshot(cx);
8146
8147 let mut edits = Vec::new();
8148 let mut unfold_ranges = Vec::new();
8149 let mut refold_creases = Vec::new();
8150
8151 let selections = self.selections.all::<Point>(cx);
8152 let mut selections = selections.iter().peekable();
8153 let mut contiguous_row_selections = Vec::new();
8154 let mut new_selections = Vec::new();
8155
8156 while let Some(selection) = selections.next() {
8157 // Find all the selections that span a contiguous row range
8158 let (start_row, end_row) = consume_contiguous_rows(
8159 &mut contiguous_row_selections,
8160 selection,
8161 &display_map,
8162 &mut selections,
8163 );
8164
8165 // Move the text spanned by the row range to be after the last line of the row range
8166 if end_row.0 <= buffer.max_point().row {
8167 let range_to_move =
8168 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8169 let insertion_point = display_map
8170 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8171 .0;
8172
8173 // Don't move lines across excerpt boundaries
8174 if buffer
8175 .excerpt_containing(range_to_move.start..insertion_point)
8176 .is_some()
8177 {
8178 let mut text = String::from("\n");
8179 text.extend(buffer.text_for_range(range_to_move.clone()));
8180 text.pop(); // Drop trailing newline
8181 edits.push((
8182 buffer.anchor_after(range_to_move.start)
8183 ..buffer.anchor_before(range_to_move.end),
8184 String::new(),
8185 ));
8186 let insertion_anchor = buffer.anchor_after(insertion_point);
8187 edits.push((insertion_anchor..insertion_anchor, text));
8188
8189 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8190
8191 // Move selections down
8192 new_selections.extend(contiguous_row_selections.drain(..).map(
8193 |mut selection| {
8194 selection.start.row += row_delta;
8195 selection.end.row += row_delta;
8196 selection
8197 },
8198 ));
8199
8200 // Move folds down
8201 unfold_ranges.push(range_to_move.clone());
8202 for fold in display_map.folds_in_range(
8203 buffer.anchor_before(range_to_move.start)
8204 ..buffer.anchor_after(range_to_move.end),
8205 ) {
8206 let mut start = fold.range.start.to_point(&buffer);
8207 let mut end = fold.range.end.to_point(&buffer);
8208 start.row += row_delta;
8209 end.row += row_delta;
8210 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8211 }
8212 }
8213 }
8214
8215 // If we didn't move line(s), preserve the existing selections
8216 new_selections.append(&mut contiguous_row_selections);
8217 }
8218
8219 self.transact(window, cx, |this, window, cx| {
8220 this.unfold_ranges(&unfold_ranges, true, true, cx);
8221 this.buffer.update(cx, |buffer, cx| {
8222 for (range, text) in edits {
8223 buffer.edit([(range, text)], None, cx);
8224 }
8225 });
8226 this.fold_creases(refold_creases, true, window, cx);
8227 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8228 s.select(new_selections)
8229 });
8230 });
8231 }
8232
8233 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8234 let text_layout_details = &self.text_layout_details(window);
8235 self.transact(window, cx, |this, window, cx| {
8236 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8237 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8238 let line_mode = s.line_mode;
8239 s.move_with(|display_map, selection| {
8240 if !selection.is_empty() || line_mode {
8241 return;
8242 }
8243
8244 let mut head = selection.head();
8245 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8246 if head.column() == display_map.line_len(head.row()) {
8247 transpose_offset = display_map
8248 .buffer_snapshot
8249 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8250 }
8251
8252 if transpose_offset == 0 {
8253 return;
8254 }
8255
8256 *head.column_mut() += 1;
8257 head = display_map.clip_point(head, Bias::Right);
8258 let goal = SelectionGoal::HorizontalPosition(
8259 display_map
8260 .x_for_display_point(head, text_layout_details)
8261 .into(),
8262 );
8263 selection.collapse_to(head, goal);
8264
8265 let transpose_start = display_map
8266 .buffer_snapshot
8267 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8268 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8269 let transpose_end = display_map
8270 .buffer_snapshot
8271 .clip_offset(transpose_offset + 1, Bias::Right);
8272 if let Some(ch) =
8273 display_map.buffer_snapshot.chars_at(transpose_start).next()
8274 {
8275 edits.push((transpose_start..transpose_offset, String::new()));
8276 edits.push((transpose_end..transpose_end, ch.to_string()));
8277 }
8278 }
8279 });
8280 edits
8281 });
8282 this.buffer
8283 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8284 let selections = this.selections.all::<usize>(cx);
8285 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8286 s.select(selections);
8287 });
8288 });
8289 }
8290
8291 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8292 self.rewrap_impl(IsVimMode::No, cx)
8293 }
8294
8295 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8296 let buffer = self.buffer.read(cx).snapshot(cx);
8297 let selections = self.selections.all::<Point>(cx);
8298 let mut selections = selections.iter().peekable();
8299
8300 let mut edits = Vec::new();
8301 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8302
8303 while let Some(selection) = selections.next() {
8304 let mut start_row = selection.start.row;
8305 let mut end_row = selection.end.row;
8306
8307 // Skip selections that overlap with a range that has already been rewrapped.
8308 let selection_range = start_row..end_row;
8309 if rewrapped_row_ranges
8310 .iter()
8311 .any(|range| range.overlaps(&selection_range))
8312 {
8313 continue;
8314 }
8315
8316 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8317
8318 // Since not all lines in the selection may be at the same indent
8319 // level, choose the indent size that is the most common between all
8320 // of the lines.
8321 //
8322 // If there is a tie, we use the deepest indent.
8323 let (indent_size, indent_end) = {
8324 let mut indent_size_occurrences = HashMap::default();
8325 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8326
8327 for row in start_row..=end_row {
8328 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8329 rows_by_indent_size.entry(indent).or_default().push(row);
8330 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8331 }
8332
8333 let indent_size = indent_size_occurrences
8334 .into_iter()
8335 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8336 .map(|(indent, _)| indent)
8337 .unwrap_or_default();
8338 let row = rows_by_indent_size[&indent_size][0];
8339 let indent_end = Point::new(row, indent_size.len);
8340
8341 (indent_size, indent_end)
8342 };
8343
8344 let mut line_prefix = indent_size.chars().collect::<String>();
8345
8346 let mut inside_comment = false;
8347 if let Some(comment_prefix) =
8348 buffer
8349 .language_scope_at(selection.head())
8350 .and_then(|language| {
8351 language
8352 .line_comment_prefixes()
8353 .iter()
8354 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8355 .cloned()
8356 })
8357 {
8358 line_prefix.push_str(&comment_prefix);
8359 inside_comment = true;
8360 }
8361
8362 let language_settings = buffer.settings_at(selection.head(), cx);
8363 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8364 RewrapBehavior::InComments => inside_comment,
8365 RewrapBehavior::InSelections => !selection.is_empty(),
8366 RewrapBehavior::Anywhere => true,
8367 };
8368
8369 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8370 if !should_rewrap {
8371 continue;
8372 }
8373
8374 if selection.is_empty() {
8375 'expand_upwards: while start_row > 0 {
8376 let prev_row = start_row - 1;
8377 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8378 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8379 {
8380 start_row = prev_row;
8381 } else {
8382 break 'expand_upwards;
8383 }
8384 }
8385
8386 'expand_downwards: while end_row < buffer.max_point().row {
8387 let next_row = end_row + 1;
8388 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8389 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8390 {
8391 end_row = next_row;
8392 } else {
8393 break 'expand_downwards;
8394 }
8395 }
8396 }
8397
8398 let start = Point::new(start_row, 0);
8399 let start_offset = start.to_offset(&buffer);
8400 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8401 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8402 let Some(lines_without_prefixes) = selection_text
8403 .lines()
8404 .map(|line| {
8405 line.strip_prefix(&line_prefix)
8406 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8407 .ok_or_else(|| {
8408 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8409 })
8410 })
8411 .collect::<Result<Vec<_>, _>>()
8412 .log_err()
8413 else {
8414 continue;
8415 };
8416
8417 let wrap_column = buffer
8418 .settings_at(Point::new(start_row, 0), cx)
8419 .preferred_line_length as usize;
8420 let wrapped_text = wrap_with_prefix(
8421 line_prefix,
8422 lines_without_prefixes.join(" "),
8423 wrap_column,
8424 tab_size,
8425 );
8426
8427 // TODO: should always use char-based diff while still supporting cursor behavior that
8428 // matches vim.
8429 let mut diff_options = DiffOptions::default();
8430 if is_vim_mode == IsVimMode::Yes {
8431 diff_options.max_word_diff_len = 0;
8432 diff_options.max_word_diff_line_count = 0;
8433 } else {
8434 diff_options.max_word_diff_len = usize::MAX;
8435 diff_options.max_word_diff_line_count = usize::MAX;
8436 }
8437
8438 for (old_range, new_text) in
8439 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8440 {
8441 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8442 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8443 edits.push((edit_start..edit_end, new_text));
8444 }
8445
8446 rewrapped_row_ranges.push(start_row..=end_row);
8447 }
8448
8449 self.buffer
8450 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8451 }
8452
8453 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8454 let mut text = String::new();
8455 let buffer = self.buffer.read(cx).snapshot(cx);
8456 let mut selections = self.selections.all::<Point>(cx);
8457 let mut clipboard_selections = Vec::with_capacity(selections.len());
8458 {
8459 let max_point = buffer.max_point();
8460 let mut is_first = true;
8461 for selection in &mut selections {
8462 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8463 if is_entire_line {
8464 selection.start = Point::new(selection.start.row, 0);
8465 if !selection.is_empty() && selection.end.column == 0 {
8466 selection.end = cmp::min(max_point, selection.end);
8467 } else {
8468 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8469 }
8470 selection.goal = SelectionGoal::None;
8471 }
8472 if is_first {
8473 is_first = false;
8474 } else {
8475 text += "\n";
8476 }
8477 let mut len = 0;
8478 for chunk in buffer.text_for_range(selection.start..selection.end) {
8479 text.push_str(chunk);
8480 len += chunk.len();
8481 }
8482 clipboard_selections.push(ClipboardSelection {
8483 len,
8484 is_entire_line,
8485 start_column: selection.start.column,
8486 });
8487 }
8488 }
8489
8490 self.transact(window, cx, |this, window, cx| {
8491 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8492 s.select(selections);
8493 });
8494 this.insert("", window, cx);
8495 });
8496 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8497 }
8498
8499 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8500 let item = self.cut_common(window, cx);
8501 cx.write_to_clipboard(item);
8502 }
8503
8504 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8505 self.change_selections(None, window, cx, |s| {
8506 s.move_with(|snapshot, sel| {
8507 if sel.is_empty() {
8508 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8509 }
8510 });
8511 });
8512 let item = self.cut_common(window, cx);
8513 cx.set_global(KillRing(item))
8514 }
8515
8516 pub fn kill_ring_yank(
8517 &mut self,
8518 _: &KillRingYank,
8519 window: &mut Window,
8520 cx: &mut Context<Self>,
8521 ) {
8522 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8523 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8524 (kill_ring.text().to_string(), kill_ring.metadata_json())
8525 } else {
8526 return;
8527 }
8528 } else {
8529 return;
8530 };
8531 self.do_paste(&text, metadata, false, window, cx);
8532 }
8533
8534 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8535 let selections = self.selections.all::<Point>(cx);
8536 let buffer = self.buffer.read(cx).read(cx);
8537 let mut text = String::new();
8538
8539 let mut clipboard_selections = Vec::with_capacity(selections.len());
8540 {
8541 let max_point = buffer.max_point();
8542 let mut is_first = true;
8543 for selection in selections.iter() {
8544 let mut start = selection.start;
8545 let mut end = selection.end;
8546 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8547 if is_entire_line {
8548 start = Point::new(start.row, 0);
8549 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8550 }
8551 if is_first {
8552 is_first = false;
8553 } else {
8554 text += "\n";
8555 }
8556 let mut len = 0;
8557 for chunk in buffer.text_for_range(start..end) {
8558 text.push_str(chunk);
8559 len += chunk.len();
8560 }
8561 clipboard_selections.push(ClipboardSelection {
8562 len,
8563 is_entire_line,
8564 start_column: start.column,
8565 });
8566 }
8567 }
8568
8569 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8570 text,
8571 clipboard_selections,
8572 ));
8573 }
8574
8575 pub fn do_paste(
8576 &mut self,
8577 text: &String,
8578 clipboard_selections: Option<Vec<ClipboardSelection>>,
8579 handle_entire_lines: bool,
8580 window: &mut Window,
8581 cx: &mut Context<Self>,
8582 ) {
8583 if self.read_only(cx) {
8584 return;
8585 }
8586
8587 let clipboard_text = Cow::Borrowed(text);
8588
8589 self.transact(window, cx, |this, window, cx| {
8590 if let Some(mut clipboard_selections) = clipboard_selections {
8591 let old_selections = this.selections.all::<usize>(cx);
8592 let all_selections_were_entire_line =
8593 clipboard_selections.iter().all(|s| s.is_entire_line);
8594 let first_selection_start_column =
8595 clipboard_selections.first().map(|s| s.start_column);
8596 if clipboard_selections.len() != old_selections.len() {
8597 clipboard_selections.drain(..);
8598 }
8599 let cursor_offset = this.selections.last::<usize>(cx).head();
8600 let mut auto_indent_on_paste = true;
8601
8602 this.buffer.update(cx, |buffer, cx| {
8603 let snapshot = buffer.read(cx);
8604 auto_indent_on_paste =
8605 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8606
8607 let mut start_offset = 0;
8608 let mut edits = Vec::new();
8609 let mut original_start_columns = Vec::new();
8610 for (ix, selection) in old_selections.iter().enumerate() {
8611 let to_insert;
8612 let entire_line;
8613 let original_start_column;
8614 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8615 let end_offset = start_offset + clipboard_selection.len;
8616 to_insert = &clipboard_text[start_offset..end_offset];
8617 entire_line = clipboard_selection.is_entire_line;
8618 start_offset = end_offset + 1;
8619 original_start_column = Some(clipboard_selection.start_column);
8620 } else {
8621 to_insert = clipboard_text.as_str();
8622 entire_line = all_selections_were_entire_line;
8623 original_start_column = first_selection_start_column
8624 }
8625
8626 // If the corresponding selection was empty when this slice of the
8627 // clipboard text was written, then the entire line containing the
8628 // selection was copied. If this selection is also currently empty,
8629 // then paste the line before the current line of the buffer.
8630 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8631 let column = selection.start.to_point(&snapshot).column as usize;
8632 let line_start = selection.start - column;
8633 line_start..line_start
8634 } else {
8635 selection.range()
8636 };
8637
8638 edits.push((range, to_insert));
8639 original_start_columns.extend(original_start_column);
8640 }
8641 drop(snapshot);
8642
8643 buffer.edit(
8644 edits,
8645 if auto_indent_on_paste {
8646 Some(AutoindentMode::Block {
8647 original_start_columns,
8648 })
8649 } else {
8650 None
8651 },
8652 cx,
8653 );
8654 });
8655
8656 let selections = this.selections.all::<usize>(cx);
8657 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8658 s.select(selections)
8659 });
8660 } else {
8661 this.insert(&clipboard_text, window, cx);
8662 }
8663 });
8664 }
8665
8666 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8667 if let Some(item) = cx.read_from_clipboard() {
8668 let entries = item.entries();
8669
8670 match entries.first() {
8671 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8672 // of all the pasted entries.
8673 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8674 .do_paste(
8675 clipboard_string.text(),
8676 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8677 true,
8678 window,
8679 cx,
8680 ),
8681 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8682 }
8683 }
8684 }
8685
8686 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8687 if self.read_only(cx) {
8688 return;
8689 }
8690
8691 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8692 if let Some((selections, _)) =
8693 self.selection_history.transaction(transaction_id).cloned()
8694 {
8695 self.change_selections(None, window, cx, |s| {
8696 s.select_anchors(selections.to_vec());
8697 });
8698 }
8699 self.request_autoscroll(Autoscroll::fit(), cx);
8700 self.unmark_text(window, cx);
8701 self.refresh_inline_completion(true, false, window, cx);
8702 cx.emit(EditorEvent::Edited { transaction_id });
8703 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8704 }
8705 }
8706
8707 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8708 if self.read_only(cx) {
8709 return;
8710 }
8711
8712 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8713 if let Some((_, Some(selections))) =
8714 self.selection_history.transaction(transaction_id).cloned()
8715 {
8716 self.change_selections(None, window, cx, |s| {
8717 s.select_anchors(selections.to_vec());
8718 });
8719 }
8720 self.request_autoscroll(Autoscroll::fit(), cx);
8721 self.unmark_text(window, cx);
8722 self.refresh_inline_completion(true, false, window, cx);
8723 cx.emit(EditorEvent::Edited { transaction_id });
8724 }
8725 }
8726
8727 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8728 self.buffer
8729 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8730 }
8731
8732 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8733 self.buffer
8734 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8735 }
8736
8737 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8738 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8739 let line_mode = s.line_mode;
8740 s.move_with(|map, selection| {
8741 let cursor = if selection.is_empty() && !line_mode {
8742 movement::left(map, selection.start)
8743 } else {
8744 selection.start
8745 };
8746 selection.collapse_to(cursor, SelectionGoal::None);
8747 });
8748 })
8749 }
8750
8751 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8752 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8753 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8754 })
8755 }
8756
8757 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8758 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8759 let line_mode = s.line_mode;
8760 s.move_with(|map, selection| {
8761 let cursor = if selection.is_empty() && !line_mode {
8762 movement::right(map, selection.end)
8763 } else {
8764 selection.end
8765 };
8766 selection.collapse_to(cursor, SelectionGoal::None)
8767 });
8768 })
8769 }
8770
8771 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8774 })
8775 }
8776
8777 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8778 if self.take_rename(true, window, cx).is_some() {
8779 return;
8780 }
8781
8782 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8783 cx.propagate();
8784 return;
8785 }
8786
8787 let text_layout_details = &self.text_layout_details(window);
8788 let selection_count = self.selections.count();
8789 let first_selection = self.selections.first_anchor();
8790
8791 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8792 let line_mode = s.line_mode;
8793 s.move_with(|map, selection| {
8794 if !selection.is_empty() && !line_mode {
8795 selection.goal = SelectionGoal::None;
8796 }
8797 let (cursor, goal) = movement::up(
8798 map,
8799 selection.start,
8800 selection.goal,
8801 false,
8802 text_layout_details,
8803 );
8804 selection.collapse_to(cursor, goal);
8805 });
8806 });
8807
8808 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8809 {
8810 cx.propagate();
8811 }
8812 }
8813
8814 pub fn move_up_by_lines(
8815 &mut self,
8816 action: &MoveUpByLines,
8817 window: &mut Window,
8818 cx: &mut Context<Self>,
8819 ) {
8820 if self.take_rename(true, window, cx).is_some() {
8821 return;
8822 }
8823
8824 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8825 cx.propagate();
8826 return;
8827 }
8828
8829 let text_layout_details = &self.text_layout_details(window);
8830
8831 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8832 let line_mode = s.line_mode;
8833 s.move_with(|map, selection| {
8834 if !selection.is_empty() && !line_mode {
8835 selection.goal = SelectionGoal::None;
8836 }
8837 let (cursor, goal) = movement::up_by_rows(
8838 map,
8839 selection.start,
8840 action.lines,
8841 selection.goal,
8842 false,
8843 text_layout_details,
8844 );
8845 selection.collapse_to(cursor, goal);
8846 });
8847 })
8848 }
8849
8850 pub fn move_down_by_lines(
8851 &mut self,
8852 action: &MoveDownByLines,
8853 window: &mut Window,
8854 cx: &mut Context<Self>,
8855 ) {
8856 if self.take_rename(true, window, cx).is_some() {
8857 return;
8858 }
8859
8860 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8861 cx.propagate();
8862 return;
8863 }
8864
8865 let text_layout_details = &self.text_layout_details(window);
8866
8867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8868 let line_mode = s.line_mode;
8869 s.move_with(|map, selection| {
8870 if !selection.is_empty() && !line_mode {
8871 selection.goal = SelectionGoal::None;
8872 }
8873 let (cursor, goal) = movement::down_by_rows(
8874 map,
8875 selection.start,
8876 action.lines,
8877 selection.goal,
8878 false,
8879 text_layout_details,
8880 );
8881 selection.collapse_to(cursor, goal);
8882 });
8883 })
8884 }
8885
8886 pub fn select_down_by_lines(
8887 &mut self,
8888 action: &SelectDownByLines,
8889 window: &mut Window,
8890 cx: &mut Context<Self>,
8891 ) {
8892 let text_layout_details = &self.text_layout_details(window);
8893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8894 s.move_heads_with(|map, head, goal| {
8895 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8896 })
8897 })
8898 }
8899
8900 pub fn select_up_by_lines(
8901 &mut self,
8902 action: &SelectUpByLines,
8903 window: &mut Window,
8904 cx: &mut Context<Self>,
8905 ) {
8906 let text_layout_details = &self.text_layout_details(window);
8907 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8908 s.move_heads_with(|map, head, goal| {
8909 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8910 })
8911 })
8912 }
8913
8914 pub fn select_page_up(
8915 &mut self,
8916 _: &SelectPageUp,
8917 window: &mut Window,
8918 cx: &mut Context<Self>,
8919 ) {
8920 let Some(row_count) = self.visible_row_count() else {
8921 return;
8922 };
8923
8924 let text_layout_details = &self.text_layout_details(window);
8925
8926 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8927 s.move_heads_with(|map, head, goal| {
8928 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8929 })
8930 })
8931 }
8932
8933 pub fn move_page_up(
8934 &mut self,
8935 action: &MovePageUp,
8936 window: &mut Window,
8937 cx: &mut Context<Self>,
8938 ) {
8939 if self.take_rename(true, window, cx).is_some() {
8940 return;
8941 }
8942
8943 if self
8944 .context_menu
8945 .borrow_mut()
8946 .as_mut()
8947 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8948 .unwrap_or(false)
8949 {
8950 return;
8951 }
8952
8953 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8954 cx.propagate();
8955 return;
8956 }
8957
8958 let Some(row_count) = self.visible_row_count() else {
8959 return;
8960 };
8961
8962 let autoscroll = if action.center_cursor {
8963 Autoscroll::center()
8964 } else {
8965 Autoscroll::fit()
8966 };
8967
8968 let text_layout_details = &self.text_layout_details(window);
8969
8970 self.change_selections(Some(autoscroll), window, cx, |s| {
8971 let line_mode = s.line_mode;
8972 s.move_with(|map, selection| {
8973 if !selection.is_empty() && !line_mode {
8974 selection.goal = SelectionGoal::None;
8975 }
8976 let (cursor, goal) = movement::up_by_rows(
8977 map,
8978 selection.end,
8979 row_count,
8980 selection.goal,
8981 false,
8982 text_layout_details,
8983 );
8984 selection.collapse_to(cursor, goal);
8985 });
8986 });
8987 }
8988
8989 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8990 let text_layout_details = &self.text_layout_details(window);
8991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8992 s.move_heads_with(|map, head, goal| {
8993 movement::up(map, head, goal, false, text_layout_details)
8994 })
8995 })
8996 }
8997
8998 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8999 self.take_rename(true, window, cx);
9000
9001 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9002 cx.propagate();
9003 return;
9004 }
9005
9006 let text_layout_details = &self.text_layout_details(window);
9007 let selection_count = self.selections.count();
9008 let first_selection = self.selections.first_anchor();
9009
9010 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9011 let line_mode = s.line_mode;
9012 s.move_with(|map, selection| {
9013 if !selection.is_empty() && !line_mode {
9014 selection.goal = SelectionGoal::None;
9015 }
9016 let (cursor, goal) = movement::down(
9017 map,
9018 selection.end,
9019 selection.goal,
9020 false,
9021 text_layout_details,
9022 );
9023 selection.collapse_to(cursor, goal);
9024 });
9025 });
9026
9027 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9028 {
9029 cx.propagate();
9030 }
9031 }
9032
9033 pub fn select_page_down(
9034 &mut self,
9035 _: &SelectPageDown,
9036 window: &mut Window,
9037 cx: &mut Context<Self>,
9038 ) {
9039 let Some(row_count) = self.visible_row_count() else {
9040 return;
9041 };
9042
9043 let text_layout_details = &self.text_layout_details(window);
9044
9045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9046 s.move_heads_with(|map, head, goal| {
9047 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9048 })
9049 })
9050 }
9051
9052 pub fn move_page_down(
9053 &mut self,
9054 action: &MovePageDown,
9055 window: &mut Window,
9056 cx: &mut Context<Self>,
9057 ) {
9058 if self.take_rename(true, window, cx).is_some() {
9059 return;
9060 }
9061
9062 if self
9063 .context_menu
9064 .borrow_mut()
9065 .as_mut()
9066 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9067 .unwrap_or(false)
9068 {
9069 return;
9070 }
9071
9072 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9073 cx.propagate();
9074 return;
9075 }
9076
9077 let Some(row_count) = self.visible_row_count() else {
9078 return;
9079 };
9080
9081 let autoscroll = if action.center_cursor {
9082 Autoscroll::center()
9083 } else {
9084 Autoscroll::fit()
9085 };
9086
9087 let text_layout_details = &self.text_layout_details(window);
9088 self.change_selections(Some(autoscroll), window, cx, |s| {
9089 let line_mode = s.line_mode;
9090 s.move_with(|map, selection| {
9091 if !selection.is_empty() && !line_mode {
9092 selection.goal = SelectionGoal::None;
9093 }
9094 let (cursor, goal) = movement::down_by_rows(
9095 map,
9096 selection.end,
9097 row_count,
9098 selection.goal,
9099 false,
9100 text_layout_details,
9101 );
9102 selection.collapse_to(cursor, goal);
9103 });
9104 });
9105 }
9106
9107 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9108 let text_layout_details = &self.text_layout_details(window);
9109 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9110 s.move_heads_with(|map, head, goal| {
9111 movement::down(map, head, goal, false, text_layout_details)
9112 })
9113 });
9114 }
9115
9116 pub fn context_menu_first(
9117 &mut self,
9118 _: &ContextMenuFirst,
9119 _window: &mut Window,
9120 cx: &mut Context<Self>,
9121 ) {
9122 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9123 context_menu.select_first(self.completion_provider.as_deref(), cx);
9124 }
9125 }
9126
9127 pub fn context_menu_prev(
9128 &mut self,
9129 _: &ContextMenuPrev,
9130 _window: &mut Window,
9131 cx: &mut Context<Self>,
9132 ) {
9133 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9134 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9135 }
9136 }
9137
9138 pub fn context_menu_next(
9139 &mut self,
9140 _: &ContextMenuNext,
9141 _window: &mut Window,
9142 cx: &mut Context<Self>,
9143 ) {
9144 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9145 context_menu.select_next(self.completion_provider.as_deref(), cx);
9146 }
9147 }
9148
9149 pub fn context_menu_last(
9150 &mut self,
9151 _: &ContextMenuLast,
9152 _window: &mut Window,
9153 cx: &mut Context<Self>,
9154 ) {
9155 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9156 context_menu.select_last(self.completion_provider.as_deref(), cx);
9157 }
9158 }
9159
9160 pub fn move_to_previous_word_start(
9161 &mut self,
9162 _: &MoveToPreviousWordStart,
9163 window: &mut Window,
9164 cx: &mut Context<Self>,
9165 ) {
9166 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9167 s.move_cursors_with(|map, head, _| {
9168 (
9169 movement::previous_word_start(map, head),
9170 SelectionGoal::None,
9171 )
9172 });
9173 })
9174 }
9175
9176 pub fn move_to_previous_subword_start(
9177 &mut self,
9178 _: &MoveToPreviousSubwordStart,
9179 window: &mut Window,
9180 cx: &mut Context<Self>,
9181 ) {
9182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9183 s.move_cursors_with(|map, head, _| {
9184 (
9185 movement::previous_subword_start(map, head),
9186 SelectionGoal::None,
9187 )
9188 });
9189 })
9190 }
9191
9192 pub fn select_to_previous_word_start(
9193 &mut self,
9194 _: &SelectToPreviousWordStart,
9195 window: &mut Window,
9196 cx: &mut Context<Self>,
9197 ) {
9198 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9199 s.move_heads_with(|map, head, _| {
9200 (
9201 movement::previous_word_start(map, head),
9202 SelectionGoal::None,
9203 )
9204 });
9205 })
9206 }
9207
9208 pub fn select_to_previous_subword_start(
9209 &mut self,
9210 _: &SelectToPreviousSubwordStart,
9211 window: &mut Window,
9212 cx: &mut Context<Self>,
9213 ) {
9214 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9215 s.move_heads_with(|map, head, _| {
9216 (
9217 movement::previous_subword_start(map, head),
9218 SelectionGoal::None,
9219 )
9220 });
9221 })
9222 }
9223
9224 pub fn delete_to_previous_word_start(
9225 &mut self,
9226 action: &DeleteToPreviousWordStart,
9227 window: &mut Window,
9228 cx: &mut Context<Self>,
9229 ) {
9230 self.transact(window, cx, |this, window, cx| {
9231 this.select_autoclose_pair(window, cx);
9232 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9233 let line_mode = s.line_mode;
9234 s.move_with(|map, selection| {
9235 if selection.is_empty() && !line_mode {
9236 let cursor = if action.ignore_newlines {
9237 movement::previous_word_start(map, selection.head())
9238 } else {
9239 movement::previous_word_start_or_newline(map, selection.head())
9240 };
9241 selection.set_head(cursor, SelectionGoal::None);
9242 }
9243 });
9244 });
9245 this.insert("", window, cx);
9246 });
9247 }
9248
9249 pub fn delete_to_previous_subword_start(
9250 &mut self,
9251 _: &DeleteToPreviousSubwordStart,
9252 window: &mut Window,
9253 cx: &mut Context<Self>,
9254 ) {
9255 self.transact(window, cx, |this, window, cx| {
9256 this.select_autoclose_pair(window, cx);
9257 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9258 let line_mode = s.line_mode;
9259 s.move_with(|map, selection| {
9260 if selection.is_empty() && !line_mode {
9261 let cursor = movement::previous_subword_start(map, selection.head());
9262 selection.set_head(cursor, SelectionGoal::None);
9263 }
9264 });
9265 });
9266 this.insert("", window, cx);
9267 });
9268 }
9269
9270 pub fn move_to_next_word_end(
9271 &mut self,
9272 _: &MoveToNextWordEnd,
9273 window: &mut Window,
9274 cx: &mut Context<Self>,
9275 ) {
9276 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9277 s.move_cursors_with(|map, head, _| {
9278 (movement::next_word_end(map, head), SelectionGoal::None)
9279 });
9280 })
9281 }
9282
9283 pub fn move_to_next_subword_end(
9284 &mut self,
9285 _: &MoveToNextSubwordEnd,
9286 window: &mut Window,
9287 cx: &mut Context<Self>,
9288 ) {
9289 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9290 s.move_cursors_with(|map, head, _| {
9291 (movement::next_subword_end(map, head), SelectionGoal::None)
9292 });
9293 })
9294 }
9295
9296 pub fn select_to_next_word_end(
9297 &mut self,
9298 _: &SelectToNextWordEnd,
9299 window: &mut Window,
9300 cx: &mut Context<Self>,
9301 ) {
9302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9303 s.move_heads_with(|map, head, _| {
9304 (movement::next_word_end(map, head), SelectionGoal::None)
9305 });
9306 })
9307 }
9308
9309 pub fn select_to_next_subword_end(
9310 &mut self,
9311 _: &SelectToNextSubwordEnd,
9312 window: &mut Window,
9313 cx: &mut Context<Self>,
9314 ) {
9315 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9316 s.move_heads_with(|map, head, _| {
9317 (movement::next_subword_end(map, head), SelectionGoal::None)
9318 });
9319 })
9320 }
9321
9322 pub fn delete_to_next_word_end(
9323 &mut self,
9324 action: &DeleteToNextWordEnd,
9325 window: &mut Window,
9326 cx: &mut Context<Self>,
9327 ) {
9328 self.transact(window, cx, |this, window, cx| {
9329 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9330 let line_mode = s.line_mode;
9331 s.move_with(|map, selection| {
9332 if selection.is_empty() && !line_mode {
9333 let cursor = if action.ignore_newlines {
9334 movement::next_word_end(map, selection.head())
9335 } else {
9336 movement::next_word_end_or_newline(map, selection.head())
9337 };
9338 selection.set_head(cursor, SelectionGoal::None);
9339 }
9340 });
9341 });
9342 this.insert("", window, cx);
9343 });
9344 }
9345
9346 pub fn delete_to_next_subword_end(
9347 &mut self,
9348 _: &DeleteToNextSubwordEnd,
9349 window: &mut Window,
9350 cx: &mut Context<Self>,
9351 ) {
9352 self.transact(window, cx, |this, window, cx| {
9353 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9354 s.move_with(|map, selection| {
9355 if selection.is_empty() {
9356 let cursor = movement::next_subword_end(map, selection.head());
9357 selection.set_head(cursor, SelectionGoal::None);
9358 }
9359 });
9360 });
9361 this.insert("", window, cx);
9362 });
9363 }
9364
9365 pub fn move_to_beginning_of_line(
9366 &mut self,
9367 action: &MoveToBeginningOfLine,
9368 window: &mut Window,
9369 cx: &mut Context<Self>,
9370 ) {
9371 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9372 s.move_cursors_with(|map, head, _| {
9373 (
9374 movement::indented_line_beginning(
9375 map,
9376 head,
9377 action.stop_at_soft_wraps,
9378 action.stop_at_indent,
9379 ),
9380 SelectionGoal::None,
9381 )
9382 });
9383 })
9384 }
9385
9386 pub fn select_to_beginning_of_line(
9387 &mut self,
9388 action: &SelectToBeginningOfLine,
9389 window: &mut Window,
9390 cx: &mut Context<Self>,
9391 ) {
9392 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9393 s.move_heads_with(|map, head, _| {
9394 (
9395 movement::indented_line_beginning(
9396 map,
9397 head,
9398 action.stop_at_soft_wraps,
9399 action.stop_at_indent,
9400 ),
9401 SelectionGoal::None,
9402 )
9403 });
9404 });
9405 }
9406
9407 pub fn delete_to_beginning_of_line(
9408 &mut self,
9409 _: &DeleteToBeginningOfLine,
9410 window: &mut Window,
9411 cx: &mut Context<Self>,
9412 ) {
9413 self.transact(window, cx, |this, window, cx| {
9414 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9415 s.move_with(|_, selection| {
9416 selection.reversed = true;
9417 });
9418 });
9419
9420 this.select_to_beginning_of_line(
9421 &SelectToBeginningOfLine {
9422 stop_at_soft_wraps: false,
9423 stop_at_indent: false,
9424 },
9425 window,
9426 cx,
9427 );
9428 this.backspace(&Backspace, window, cx);
9429 });
9430 }
9431
9432 pub fn move_to_end_of_line(
9433 &mut self,
9434 action: &MoveToEndOfLine,
9435 window: &mut Window,
9436 cx: &mut Context<Self>,
9437 ) {
9438 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9439 s.move_cursors_with(|map, head, _| {
9440 (
9441 movement::line_end(map, head, action.stop_at_soft_wraps),
9442 SelectionGoal::None,
9443 )
9444 });
9445 })
9446 }
9447
9448 pub fn select_to_end_of_line(
9449 &mut self,
9450 action: &SelectToEndOfLine,
9451 window: &mut Window,
9452 cx: &mut Context<Self>,
9453 ) {
9454 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9455 s.move_heads_with(|map, head, _| {
9456 (
9457 movement::line_end(map, head, action.stop_at_soft_wraps),
9458 SelectionGoal::None,
9459 )
9460 });
9461 })
9462 }
9463
9464 pub fn delete_to_end_of_line(
9465 &mut self,
9466 _: &DeleteToEndOfLine,
9467 window: &mut Window,
9468 cx: &mut Context<Self>,
9469 ) {
9470 self.transact(window, cx, |this, window, cx| {
9471 this.select_to_end_of_line(
9472 &SelectToEndOfLine {
9473 stop_at_soft_wraps: false,
9474 },
9475 window,
9476 cx,
9477 );
9478 this.delete(&Delete, window, cx);
9479 });
9480 }
9481
9482 pub fn cut_to_end_of_line(
9483 &mut self,
9484 _: &CutToEndOfLine,
9485 window: &mut Window,
9486 cx: &mut Context<Self>,
9487 ) {
9488 self.transact(window, cx, |this, window, cx| {
9489 this.select_to_end_of_line(
9490 &SelectToEndOfLine {
9491 stop_at_soft_wraps: false,
9492 },
9493 window,
9494 cx,
9495 );
9496 this.cut(&Cut, window, cx);
9497 });
9498 }
9499
9500 pub fn move_to_start_of_paragraph(
9501 &mut self,
9502 _: &MoveToStartOfParagraph,
9503 window: &mut Window,
9504 cx: &mut Context<Self>,
9505 ) {
9506 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9507 cx.propagate();
9508 return;
9509 }
9510
9511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9512 s.move_with(|map, selection| {
9513 selection.collapse_to(
9514 movement::start_of_paragraph(map, selection.head(), 1),
9515 SelectionGoal::None,
9516 )
9517 });
9518 })
9519 }
9520
9521 pub fn move_to_end_of_paragraph(
9522 &mut self,
9523 _: &MoveToEndOfParagraph,
9524 window: &mut Window,
9525 cx: &mut Context<Self>,
9526 ) {
9527 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9528 cx.propagate();
9529 return;
9530 }
9531
9532 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9533 s.move_with(|map, selection| {
9534 selection.collapse_to(
9535 movement::end_of_paragraph(map, selection.head(), 1),
9536 SelectionGoal::None,
9537 )
9538 });
9539 })
9540 }
9541
9542 pub fn select_to_start_of_paragraph(
9543 &mut self,
9544 _: &SelectToStartOfParagraph,
9545 window: &mut Window,
9546 cx: &mut Context<Self>,
9547 ) {
9548 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9549 cx.propagate();
9550 return;
9551 }
9552
9553 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9554 s.move_heads_with(|map, head, _| {
9555 (
9556 movement::start_of_paragraph(map, head, 1),
9557 SelectionGoal::None,
9558 )
9559 });
9560 })
9561 }
9562
9563 pub fn select_to_end_of_paragraph(
9564 &mut self,
9565 _: &SelectToEndOfParagraph,
9566 window: &mut Window,
9567 cx: &mut Context<Self>,
9568 ) {
9569 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9570 cx.propagate();
9571 return;
9572 }
9573
9574 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9575 s.move_heads_with(|map, head, _| {
9576 (
9577 movement::end_of_paragraph(map, head, 1),
9578 SelectionGoal::None,
9579 )
9580 });
9581 })
9582 }
9583
9584 pub fn move_to_start_of_excerpt(
9585 &mut self,
9586 _: &MoveToStartOfExcerpt,
9587 window: &mut Window,
9588 cx: &mut Context<Self>,
9589 ) {
9590 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9591 cx.propagate();
9592 return;
9593 }
9594
9595 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9596 s.move_with(|map, selection| {
9597 selection.collapse_to(
9598 movement::start_of_excerpt(
9599 map,
9600 selection.head(),
9601 workspace::searchable::Direction::Prev,
9602 ),
9603 SelectionGoal::None,
9604 )
9605 });
9606 })
9607 }
9608
9609 pub fn move_to_end_of_excerpt(
9610 &mut self,
9611 _: &MoveToEndOfExcerpt,
9612 window: &mut Window,
9613 cx: &mut Context<Self>,
9614 ) {
9615 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9616 cx.propagate();
9617 return;
9618 }
9619
9620 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9621 s.move_with(|map, selection| {
9622 selection.collapse_to(
9623 movement::end_of_excerpt(
9624 map,
9625 selection.head(),
9626 workspace::searchable::Direction::Next,
9627 ),
9628 SelectionGoal::None,
9629 )
9630 });
9631 })
9632 }
9633
9634 pub fn select_to_start_of_excerpt(
9635 &mut self,
9636 _: &SelectToStartOfExcerpt,
9637 window: &mut Window,
9638 cx: &mut Context<Self>,
9639 ) {
9640 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9641 cx.propagate();
9642 return;
9643 }
9644
9645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9646 s.move_heads_with(|map, head, _| {
9647 (
9648 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9649 SelectionGoal::None,
9650 )
9651 });
9652 })
9653 }
9654
9655 pub fn select_to_end_of_excerpt(
9656 &mut self,
9657 _: &SelectToEndOfExcerpt,
9658 window: &mut Window,
9659 cx: &mut Context<Self>,
9660 ) {
9661 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9662 cx.propagate();
9663 return;
9664 }
9665
9666 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9667 s.move_heads_with(|map, head, _| {
9668 (
9669 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9670 SelectionGoal::None,
9671 )
9672 });
9673 })
9674 }
9675
9676 pub fn move_to_beginning(
9677 &mut self,
9678 _: &MoveToBeginning,
9679 window: &mut Window,
9680 cx: &mut Context<Self>,
9681 ) {
9682 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9683 cx.propagate();
9684 return;
9685 }
9686
9687 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9688 s.select_ranges(vec![0..0]);
9689 });
9690 }
9691
9692 pub fn select_to_beginning(
9693 &mut self,
9694 _: &SelectToBeginning,
9695 window: &mut Window,
9696 cx: &mut Context<Self>,
9697 ) {
9698 let mut selection = self.selections.last::<Point>(cx);
9699 selection.set_head(Point::zero(), SelectionGoal::None);
9700
9701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9702 s.select(vec![selection]);
9703 });
9704 }
9705
9706 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9707 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9708 cx.propagate();
9709 return;
9710 }
9711
9712 let cursor = self.buffer.read(cx).read(cx).len();
9713 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9714 s.select_ranges(vec![cursor..cursor])
9715 });
9716 }
9717
9718 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9719 self.nav_history = nav_history;
9720 }
9721
9722 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9723 self.nav_history.as_ref()
9724 }
9725
9726 fn push_to_nav_history(
9727 &mut self,
9728 cursor_anchor: Anchor,
9729 new_position: Option<Point>,
9730 cx: &mut Context<Self>,
9731 ) {
9732 if let Some(nav_history) = self.nav_history.as_mut() {
9733 let buffer = self.buffer.read(cx).read(cx);
9734 let cursor_position = cursor_anchor.to_point(&buffer);
9735 let scroll_state = self.scroll_manager.anchor();
9736 let scroll_top_row = scroll_state.top_row(&buffer);
9737 drop(buffer);
9738
9739 if let Some(new_position) = new_position {
9740 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9741 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9742 return;
9743 }
9744 }
9745
9746 nav_history.push(
9747 Some(NavigationData {
9748 cursor_anchor,
9749 cursor_position,
9750 scroll_anchor: scroll_state,
9751 scroll_top_row,
9752 }),
9753 cx,
9754 );
9755 }
9756 }
9757
9758 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9759 let buffer = self.buffer.read(cx).snapshot(cx);
9760 let mut selection = self.selections.first::<usize>(cx);
9761 selection.set_head(buffer.len(), SelectionGoal::None);
9762 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9763 s.select(vec![selection]);
9764 });
9765 }
9766
9767 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9768 let end = self.buffer.read(cx).read(cx).len();
9769 self.change_selections(None, window, cx, |s| {
9770 s.select_ranges(vec![0..end]);
9771 });
9772 }
9773
9774 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9776 let mut selections = self.selections.all::<Point>(cx);
9777 let max_point = display_map.buffer_snapshot.max_point();
9778 for selection in &mut selections {
9779 let rows = selection.spanned_rows(true, &display_map);
9780 selection.start = Point::new(rows.start.0, 0);
9781 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9782 selection.reversed = false;
9783 }
9784 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9785 s.select(selections);
9786 });
9787 }
9788
9789 pub fn split_selection_into_lines(
9790 &mut self,
9791 _: &SplitSelectionIntoLines,
9792 window: &mut Window,
9793 cx: &mut Context<Self>,
9794 ) {
9795 let selections = self
9796 .selections
9797 .all::<Point>(cx)
9798 .into_iter()
9799 .map(|selection| selection.start..selection.end)
9800 .collect::<Vec<_>>();
9801 self.unfold_ranges(&selections, true, true, cx);
9802
9803 let mut new_selection_ranges = Vec::new();
9804 {
9805 let buffer = self.buffer.read(cx).read(cx);
9806 for selection in selections {
9807 for row in selection.start.row..selection.end.row {
9808 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9809 new_selection_ranges.push(cursor..cursor);
9810 }
9811
9812 let is_multiline_selection = selection.start.row != selection.end.row;
9813 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9814 // so this action feels more ergonomic when paired with other selection operations
9815 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9816 if !should_skip_last {
9817 new_selection_ranges.push(selection.end..selection.end);
9818 }
9819 }
9820 }
9821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9822 s.select_ranges(new_selection_ranges);
9823 });
9824 }
9825
9826 pub fn add_selection_above(
9827 &mut self,
9828 _: &AddSelectionAbove,
9829 window: &mut Window,
9830 cx: &mut Context<Self>,
9831 ) {
9832 self.add_selection(true, window, cx);
9833 }
9834
9835 pub fn add_selection_below(
9836 &mut self,
9837 _: &AddSelectionBelow,
9838 window: &mut Window,
9839 cx: &mut Context<Self>,
9840 ) {
9841 self.add_selection(false, window, cx);
9842 }
9843
9844 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9846 let mut selections = self.selections.all::<Point>(cx);
9847 let text_layout_details = self.text_layout_details(window);
9848 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9849 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9850 let range = oldest_selection.display_range(&display_map).sorted();
9851
9852 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9853 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9854 let positions = start_x.min(end_x)..start_x.max(end_x);
9855
9856 selections.clear();
9857 let mut stack = Vec::new();
9858 for row in range.start.row().0..=range.end.row().0 {
9859 if let Some(selection) = self.selections.build_columnar_selection(
9860 &display_map,
9861 DisplayRow(row),
9862 &positions,
9863 oldest_selection.reversed,
9864 &text_layout_details,
9865 ) {
9866 stack.push(selection.id);
9867 selections.push(selection);
9868 }
9869 }
9870
9871 if above {
9872 stack.reverse();
9873 }
9874
9875 AddSelectionsState { above, stack }
9876 });
9877
9878 let last_added_selection = *state.stack.last().unwrap();
9879 let mut new_selections = Vec::new();
9880 if above == state.above {
9881 let end_row = if above {
9882 DisplayRow(0)
9883 } else {
9884 display_map.max_point().row()
9885 };
9886
9887 'outer: for selection in selections {
9888 if selection.id == last_added_selection {
9889 let range = selection.display_range(&display_map).sorted();
9890 debug_assert_eq!(range.start.row(), range.end.row());
9891 let mut row = range.start.row();
9892 let positions =
9893 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9894 px(start)..px(end)
9895 } else {
9896 let start_x =
9897 display_map.x_for_display_point(range.start, &text_layout_details);
9898 let end_x =
9899 display_map.x_for_display_point(range.end, &text_layout_details);
9900 start_x.min(end_x)..start_x.max(end_x)
9901 };
9902
9903 while row != end_row {
9904 if above {
9905 row.0 -= 1;
9906 } else {
9907 row.0 += 1;
9908 }
9909
9910 if let Some(new_selection) = self.selections.build_columnar_selection(
9911 &display_map,
9912 row,
9913 &positions,
9914 selection.reversed,
9915 &text_layout_details,
9916 ) {
9917 state.stack.push(new_selection.id);
9918 if above {
9919 new_selections.push(new_selection);
9920 new_selections.push(selection);
9921 } else {
9922 new_selections.push(selection);
9923 new_selections.push(new_selection);
9924 }
9925
9926 continue 'outer;
9927 }
9928 }
9929 }
9930
9931 new_selections.push(selection);
9932 }
9933 } else {
9934 new_selections = selections;
9935 new_selections.retain(|s| s.id != last_added_selection);
9936 state.stack.pop();
9937 }
9938
9939 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9940 s.select(new_selections);
9941 });
9942 if state.stack.len() > 1 {
9943 self.add_selections_state = Some(state);
9944 }
9945 }
9946
9947 pub fn select_next_match_internal(
9948 &mut self,
9949 display_map: &DisplaySnapshot,
9950 replace_newest: bool,
9951 autoscroll: Option<Autoscroll>,
9952 window: &mut Window,
9953 cx: &mut Context<Self>,
9954 ) -> Result<()> {
9955 fn select_next_match_ranges(
9956 this: &mut Editor,
9957 range: Range<usize>,
9958 replace_newest: bool,
9959 auto_scroll: Option<Autoscroll>,
9960 window: &mut Window,
9961 cx: &mut Context<Editor>,
9962 ) {
9963 this.unfold_ranges(&[range.clone()], false, true, cx);
9964 this.change_selections(auto_scroll, window, cx, |s| {
9965 if replace_newest {
9966 s.delete(s.newest_anchor().id);
9967 }
9968 s.insert_range(range.clone());
9969 });
9970 }
9971
9972 let buffer = &display_map.buffer_snapshot;
9973 let mut selections = self.selections.all::<usize>(cx);
9974 if let Some(mut select_next_state) = self.select_next_state.take() {
9975 let query = &select_next_state.query;
9976 if !select_next_state.done {
9977 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9978 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9979 let mut next_selected_range = None;
9980
9981 let bytes_after_last_selection =
9982 buffer.bytes_in_range(last_selection.end..buffer.len());
9983 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9984 let query_matches = query
9985 .stream_find_iter(bytes_after_last_selection)
9986 .map(|result| (last_selection.end, result))
9987 .chain(
9988 query
9989 .stream_find_iter(bytes_before_first_selection)
9990 .map(|result| (0, result)),
9991 );
9992
9993 for (start_offset, query_match) in query_matches {
9994 let query_match = query_match.unwrap(); // can only fail due to I/O
9995 let offset_range =
9996 start_offset + query_match.start()..start_offset + query_match.end();
9997 let display_range = offset_range.start.to_display_point(display_map)
9998 ..offset_range.end.to_display_point(display_map);
9999
10000 if !select_next_state.wordwise
10001 || (!movement::is_inside_word(display_map, display_range.start)
10002 && !movement::is_inside_word(display_map, display_range.end))
10003 {
10004 // TODO: This is n^2, because we might check all the selections
10005 if !selections
10006 .iter()
10007 .any(|selection| selection.range().overlaps(&offset_range))
10008 {
10009 next_selected_range = Some(offset_range);
10010 break;
10011 }
10012 }
10013 }
10014
10015 if let Some(next_selected_range) = next_selected_range {
10016 select_next_match_ranges(
10017 self,
10018 next_selected_range,
10019 replace_newest,
10020 autoscroll,
10021 window,
10022 cx,
10023 );
10024 } else {
10025 select_next_state.done = true;
10026 }
10027 }
10028
10029 self.select_next_state = Some(select_next_state);
10030 } else {
10031 let mut only_carets = true;
10032 let mut same_text_selected = true;
10033 let mut selected_text = None;
10034
10035 let mut selections_iter = selections.iter().peekable();
10036 while let Some(selection) = selections_iter.next() {
10037 if selection.start != selection.end {
10038 only_carets = false;
10039 }
10040
10041 if same_text_selected {
10042 if selected_text.is_none() {
10043 selected_text =
10044 Some(buffer.text_for_range(selection.range()).collect::<String>());
10045 }
10046
10047 if let Some(next_selection) = selections_iter.peek() {
10048 if next_selection.range().len() == selection.range().len() {
10049 let next_selected_text = buffer
10050 .text_for_range(next_selection.range())
10051 .collect::<String>();
10052 if Some(next_selected_text) != selected_text {
10053 same_text_selected = false;
10054 selected_text = None;
10055 }
10056 } else {
10057 same_text_selected = false;
10058 selected_text = None;
10059 }
10060 }
10061 }
10062 }
10063
10064 if only_carets {
10065 for selection in &mut selections {
10066 let word_range = movement::surrounding_word(
10067 display_map,
10068 selection.start.to_display_point(display_map),
10069 );
10070 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10071 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10072 selection.goal = SelectionGoal::None;
10073 selection.reversed = false;
10074 select_next_match_ranges(
10075 self,
10076 selection.start..selection.end,
10077 replace_newest,
10078 autoscroll,
10079 window,
10080 cx,
10081 );
10082 }
10083
10084 if selections.len() == 1 {
10085 let selection = selections
10086 .last()
10087 .expect("ensured that there's only one selection");
10088 let query = buffer
10089 .text_for_range(selection.start..selection.end)
10090 .collect::<String>();
10091 let is_empty = query.is_empty();
10092 let select_state = SelectNextState {
10093 query: AhoCorasick::new(&[query])?,
10094 wordwise: true,
10095 done: is_empty,
10096 };
10097 self.select_next_state = Some(select_state);
10098 } else {
10099 self.select_next_state = None;
10100 }
10101 } else if let Some(selected_text) = selected_text {
10102 self.select_next_state = Some(SelectNextState {
10103 query: AhoCorasick::new(&[selected_text])?,
10104 wordwise: false,
10105 done: false,
10106 });
10107 self.select_next_match_internal(
10108 display_map,
10109 replace_newest,
10110 autoscroll,
10111 window,
10112 cx,
10113 )?;
10114 }
10115 }
10116 Ok(())
10117 }
10118
10119 pub fn select_all_matches(
10120 &mut self,
10121 _action: &SelectAllMatches,
10122 window: &mut Window,
10123 cx: &mut Context<Self>,
10124 ) -> Result<()> {
10125 self.push_to_selection_history();
10126 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10127
10128 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10129 let Some(select_next_state) = self.select_next_state.as_mut() else {
10130 return Ok(());
10131 };
10132 if select_next_state.done {
10133 return Ok(());
10134 }
10135
10136 let mut new_selections = self.selections.all::<usize>(cx);
10137
10138 let buffer = &display_map.buffer_snapshot;
10139 let query_matches = select_next_state
10140 .query
10141 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10142
10143 for query_match in query_matches {
10144 let query_match = query_match.unwrap(); // can only fail due to I/O
10145 let offset_range = query_match.start()..query_match.end();
10146 let display_range = offset_range.start.to_display_point(&display_map)
10147 ..offset_range.end.to_display_point(&display_map);
10148
10149 if !select_next_state.wordwise
10150 || (!movement::is_inside_word(&display_map, display_range.start)
10151 && !movement::is_inside_word(&display_map, display_range.end))
10152 {
10153 self.selections.change_with(cx, |selections| {
10154 new_selections.push(Selection {
10155 id: selections.new_selection_id(),
10156 start: offset_range.start,
10157 end: offset_range.end,
10158 reversed: false,
10159 goal: SelectionGoal::None,
10160 });
10161 });
10162 }
10163 }
10164
10165 new_selections.sort_by_key(|selection| selection.start);
10166 let mut ix = 0;
10167 while ix + 1 < new_selections.len() {
10168 let current_selection = &new_selections[ix];
10169 let next_selection = &new_selections[ix + 1];
10170 if current_selection.range().overlaps(&next_selection.range()) {
10171 if current_selection.id < next_selection.id {
10172 new_selections.remove(ix + 1);
10173 } else {
10174 new_selections.remove(ix);
10175 }
10176 } else {
10177 ix += 1;
10178 }
10179 }
10180
10181 let reversed = self.selections.oldest::<usize>(cx).reversed;
10182
10183 for selection in new_selections.iter_mut() {
10184 selection.reversed = reversed;
10185 }
10186
10187 select_next_state.done = true;
10188 self.unfold_ranges(
10189 &new_selections
10190 .iter()
10191 .map(|selection| selection.range())
10192 .collect::<Vec<_>>(),
10193 false,
10194 false,
10195 cx,
10196 );
10197 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10198 selections.select(new_selections)
10199 });
10200
10201 Ok(())
10202 }
10203
10204 pub fn select_next(
10205 &mut self,
10206 action: &SelectNext,
10207 window: &mut Window,
10208 cx: &mut Context<Self>,
10209 ) -> Result<()> {
10210 self.push_to_selection_history();
10211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10212 self.select_next_match_internal(
10213 &display_map,
10214 action.replace_newest,
10215 Some(Autoscroll::newest()),
10216 window,
10217 cx,
10218 )?;
10219 Ok(())
10220 }
10221
10222 pub fn select_previous(
10223 &mut self,
10224 action: &SelectPrevious,
10225 window: &mut Window,
10226 cx: &mut Context<Self>,
10227 ) -> Result<()> {
10228 self.push_to_selection_history();
10229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10230 let buffer = &display_map.buffer_snapshot;
10231 let mut selections = self.selections.all::<usize>(cx);
10232 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10233 let query = &select_prev_state.query;
10234 if !select_prev_state.done {
10235 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10236 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10237 let mut next_selected_range = None;
10238 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10239 let bytes_before_last_selection =
10240 buffer.reversed_bytes_in_range(0..last_selection.start);
10241 let bytes_after_first_selection =
10242 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10243 let query_matches = query
10244 .stream_find_iter(bytes_before_last_selection)
10245 .map(|result| (last_selection.start, result))
10246 .chain(
10247 query
10248 .stream_find_iter(bytes_after_first_selection)
10249 .map(|result| (buffer.len(), result)),
10250 );
10251 for (end_offset, query_match) in query_matches {
10252 let query_match = query_match.unwrap(); // can only fail due to I/O
10253 let offset_range =
10254 end_offset - query_match.end()..end_offset - query_match.start();
10255 let display_range = offset_range.start.to_display_point(&display_map)
10256 ..offset_range.end.to_display_point(&display_map);
10257
10258 if !select_prev_state.wordwise
10259 || (!movement::is_inside_word(&display_map, display_range.start)
10260 && !movement::is_inside_word(&display_map, display_range.end))
10261 {
10262 next_selected_range = Some(offset_range);
10263 break;
10264 }
10265 }
10266
10267 if let Some(next_selected_range) = next_selected_range {
10268 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10269 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10270 if action.replace_newest {
10271 s.delete(s.newest_anchor().id);
10272 }
10273 s.insert_range(next_selected_range);
10274 });
10275 } else {
10276 select_prev_state.done = true;
10277 }
10278 }
10279
10280 self.select_prev_state = Some(select_prev_state);
10281 } else {
10282 let mut only_carets = true;
10283 let mut same_text_selected = true;
10284 let mut selected_text = None;
10285
10286 let mut selections_iter = selections.iter().peekable();
10287 while let Some(selection) = selections_iter.next() {
10288 if selection.start != selection.end {
10289 only_carets = false;
10290 }
10291
10292 if same_text_selected {
10293 if selected_text.is_none() {
10294 selected_text =
10295 Some(buffer.text_for_range(selection.range()).collect::<String>());
10296 }
10297
10298 if let Some(next_selection) = selections_iter.peek() {
10299 if next_selection.range().len() == selection.range().len() {
10300 let next_selected_text = buffer
10301 .text_for_range(next_selection.range())
10302 .collect::<String>();
10303 if Some(next_selected_text) != selected_text {
10304 same_text_selected = false;
10305 selected_text = None;
10306 }
10307 } else {
10308 same_text_selected = false;
10309 selected_text = None;
10310 }
10311 }
10312 }
10313 }
10314
10315 if only_carets {
10316 for selection in &mut selections {
10317 let word_range = movement::surrounding_word(
10318 &display_map,
10319 selection.start.to_display_point(&display_map),
10320 );
10321 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10322 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10323 selection.goal = SelectionGoal::None;
10324 selection.reversed = false;
10325 }
10326 if selections.len() == 1 {
10327 let selection = selections
10328 .last()
10329 .expect("ensured that there's only one selection");
10330 let query = buffer
10331 .text_for_range(selection.start..selection.end)
10332 .collect::<String>();
10333 let is_empty = query.is_empty();
10334 let select_state = SelectNextState {
10335 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10336 wordwise: true,
10337 done: is_empty,
10338 };
10339 self.select_prev_state = Some(select_state);
10340 } else {
10341 self.select_prev_state = None;
10342 }
10343
10344 self.unfold_ranges(
10345 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10346 false,
10347 true,
10348 cx,
10349 );
10350 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10351 s.select(selections);
10352 });
10353 } else if let Some(selected_text) = selected_text {
10354 self.select_prev_state = Some(SelectNextState {
10355 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10356 wordwise: false,
10357 done: false,
10358 });
10359 self.select_previous(action, window, cx)?;
10360 }
10361 }
10362 Ok(())
10363 }
10364
10365 pub fn toggle_comments(
10366 &mut self,
10367 action: &ToggleComments,
10368 window: &mut Window,
10369 cx: &mut Context<Self>,
10370 ) {
10371 if self.read_only(cx) {
10372 return;
10373 }
10374 let text_layout_details = &self.text_layout_details(window);
10375 self.transact(window, cx, |this, window, cx| {
10376 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10377 let mut edits = Vec::new();
10378 let mut selection_edit_ranges = Vec::new();
10379 let mut last_toggled_row = None;
10380 let snapshot = this.buffer.read(cx).read(cx);
10381 let empty_str: Arc<str> = Arc::default();
10382 let mut suffixes_inserted = Vec::new();
10383 let ignore_indent = action.ignore_indent;
10384
10385 fn comment_prefix_range(
10386 snapshot: &MultiBufferSnapshot,
10387 row: MultiBufferRow,
10388 comment_prefix: &str,
10389 comment_prefix_whitespace: &str,
10390 ignore_indent: bool,
10391 ) -> Range<Point> {
10392 let indent_size = if ignore_indent {
10393 0
10394 } else {
10395 snapshot.indent_size_for_line(row).len
10396 };
10397
10398 let start = Point::new(row.0, indent_size);
10399
10400 let mut line_bytes = snapshot
10401 .bytes_in_range(start..snapshot.max_point())
10402 .flatten()
10403 .copied();
10404
10405 // If this line currently begins with the line comment prefix, then record
10406 // the range containing the prefix.
10407 if line_bytes
10408 .by_ref()
10409 .take(comment_prefix.len())
10410 .eq(comment_prefix.bytes())
10411 {
10412 // Include any whitespace that matches the comment prefix.
10413 let matching_whitespace_len = line_bytes
10414 .zip(comment_prefix_whitespace.bytes())
10415 .take_while(|(a, b)| a == b)
10416 .count() as u32;
10417 let end = Point::new(
10418 start.row,
10419 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10420 );
10421 start..end
10422 } else {
10423 start..start
10424 }
10425 }
10426
10427 fn comment_suffix_range(
10428 snapshot: &MultiBufferSnapshot,
10429 row: MultiBufferRow,
10430 comment_suffix: &str,
10431 comment_suffix_has_leading_space: bool,
10432 ) -> Range<Point> {
10433 let end = Point::new(row.0, snapshot.line_len(row));
10434 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10435
10436 let mut line_end_bytes = snapshot
10437 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10438 .flatten()
10439 .copied();
10440
10441 let leading_space_len = if suffix_start_column > 0
10442 && line_end_bytes.next() == Some(b' ')
10443 && comment_suffix_has_leading_space
10444 {
10445 1
10446 } else {
10447 0
10448 };
10449
10450 // If this line currently begins with the line comment prefix, then record
10451 // the range containing the prefix.
10452 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10453 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10454 start..end
10455 } else {
10456 end..end
10457 }
10458 }
10459
10460 // TODO: Handle selections that cross excerpts
10461 for selection in &mut selections {
10462 let start_column = snapshot
10463 .indent_size_for_line(MultiBufferRow(selection.start.row))
10464 .len;
10465 let language = if let Some(language) =
10466 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10467 {
10468 language
10469 } else {
10470 continue;
10471 };
10472
10473 selection_edit_ranges.clear();
10474
10475 // If multiple selections contain a given row, avoid processing that
10476 // row more than once.
10477 let mut start_row = MultiBufferRow(selection.start.row);
10478 if last_toggled_row == Some(start_row) {
10479 start_row = start_row.next_row();
10480 }
10481 let end_row =
10482 if selection.end.row > selection.start.row && selection.end.column == 0 {
10483 MultiBufferRow(selection.end.row - 1)
10484 } else {
10485 MultiBufferRow(selection.end.row)
10486 };
10487 last_toggled_row = Some(end_row);
10488
10489 if start_row > end_row {
10490 continue;
10491 }
10492
10493 // If the language has line comments, toggle those.
10494 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10495
10496 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10497 if ignore_indent {
10498 full_comment_prefixes = full_comment_prefixes
10499 .into_iter()
10500 .map(|s| Arc::from(s.trim_end()))
10501 .collect();
10502 }
10503
10504 if !full_comment_prefixes.is_empty() {
10505 let first_prefix = full_comment_prefixes
10506 .first()
10507 .expect("prefixes is non-empty");
10508 let prefix_trimmed_lengths = full_comment_prefixes
10509 .iter()
10510 .map(|p| p.trim_end_matches(' ').len())
10511 .collect::<SmallVec<[usize; 4]>>();
10512
10513 let mut all_selection_lines_are_comments = true;
10514
10515 for row in start_row.0..=end_row.0 {
10516 let row = MultiBufferRow(row);
10517 if start_row < end_row && snapshot.is_line_blank(row) {
10518 continue;
10519 }
10520
10521 let prefix_range = full_comment_prefixes
10522 .iter()
10523 .zip(prefix_trimmed_lengths.iter().copied())
10524 .map(|(prefix, trimmed_prefix_len)| {
10525 comment_prefix_range(
10526 snapshot.deref(),
10527 row,
10528 &prefix[..trimmed_prefix_len],
10529 &prefix[trimmed_prefix_len..],
10530 ignore_indent,
10531 )
10532 })
10533 .max_by_key(|range| range.end.column - range.start.column)
10534 .expect("prefixes is non-empty");
10535
10536 if prefix_range.is_empty() {
10537 all_selection_lines_are_comments = false;
10538 }
10539
10540 selection_edit_ranges.push(prefix_range);
10541 }
10542
10543 if all_selection_lines_are_comments {
10544 edits.extend(
10545 selection_edit_ranges
10546 .iter()
10547 .cloned()
10548 .map(|range| (range, empty_str.clone())),
10549 );
10550 } else {
10551 let min_column = selection_edit_ranges
10552 .iter()
10553 .map(|range| range.start.column)
10554 .min()
10555 .unwrap_or(0);
10556 edits.extend(selection_edit_ranges.iter().map(|range| {
10557 let position = Point::new(range.start.row, min_column);
10558 (position..position, first_prefix.clone())
10559 }));
10560 }
10561 } else if let Some((full_comment_prefix, comment_suffix)) =
10562 language.block_comment_delimiters()
10563 {
10564 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10565 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10566 let prefix_range = comment_prefix_range(
10567 snapshot.deref(),
10568 start_row,
10569 comment_prefix,
10570 comment_prefix_whitespace,
10571 ignore_indent,
10572 );
10573 let suffix_range = comment_suffix_range(
10574 snapshot.deref(),
10575 end_row,
10576 comment_suffix.trim_start_matches(' '),
10577 comment_suffix.starts_with(' '),
10578 );
10579
10580 if prefix_range.is_empty() || suffix_range.is_empty() {
10581 edits.push((
10582 prefix_range.start..prefix_range.start,
10583 full_comment_prefix.clone(),
10584 ));
10585 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10586 suffixes_inserted.push((end_row, comment_suffix.len()));
10587 } else {
10588 edits.push((prefix_range, empty_str.clone()));
10589 edits.push((suffix_range, empty_str.clone()));
10590 }
10591 } else {
10592 continue;
10593 }
10594 }
10595
10596 drop(snapshot);
10597 this.buffer.update(cx, |buffer, cx| {
10598 buffer.edit(edits, None, cx);
10599 });
10600
10601 // Adjust selections so that they end before any comment suffixes that
10602 // were inserted.
10603 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10604 let mut selections = this.selections.all::<Point>(cx);
10605 let snapshot = this.buffer.read(cx).read(cx);
10606 for selection in &mut selections {
10607 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10608 match row.cmp(&MultiBufferRow(selection.end.row)) {
10609 Ordering::Less => {
10610 suffixes_inserted.next();
10611 continue;
10612 }
10613 Ordering::Greater => break,
10614 Ordering::Equal => {
10615 if selection.end.column == snapshot.line_len(row) {
10616 if selection.is_empty() {
10617 selection.start.column -= suffix_len as u32;
10618 }
10619 selection.end.column -= suffix_len as u32;
10620 }
10621 break;
10622 }
10623 }
10624 }
10625 }
10626
10627 drop(snapshot);
10628 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10629 s.select(selections)
10630 });
10631
10632 let selections = this.selections.all::<Point>(cx);
10633 let selections_on_single_row = selections.windows(2).all(|selections| {
10634 selections[0].start.row == selections[1].start.row
10635 && selections[0].end.row == selections[1].end.row
10636 && selections[0].start.row == selections[0].end.row
10637 });
10638 let selections_selecting = selections
10639 .iter()
10640 .any(|selection| selection.start != selection.end);
10641 let advance_downwards = action.advance_downwards
10642 && selections_on_single_row
10643 && !selections_selecting
10644 && !matches!(this.mode, EditorMode::SingleLine { .. });
10645
10646 if advance_downwards {
10647 let snapshot = this.buffer.read(cx).snapshot(cx);
10648
10649 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10650 s.move_cursors_with(|display_snapshot, display_point, _| {
10651 let mut point = display_point.to_point(display_snapshot);
10652 point.row += 1;
10653 point = snapshot.clip_point(point, Bias::Left);
10654 let display_point = point.to_display_point(display_snapshot);
10655 let goal = SelectionGoal::HorizontalPosition(
10656 display_snapshot
10657 .x_for_display_point(display_point, text_layout_details)
10658 .into(),
10659 );
10660 (display_point, goal)
10661 })
10662 });
10663 }
10664 });
10665 }
10666
10667 pub fn select_enclosing_symbol(
10668 &mut self,
10669 _: &SelectEnclosingSymbol,
10670 window: &mut Window,
10671 cx: &mut Context<Self>,
10672 ) {
10673 let buffer = self.buffer.read(cx).snapshot(cx);
10674 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10675
10676 fn update_selection(
10677 selection: &Selection<usize>,
10678 buffer_snap: &MultiBufferSnapshot,
10679 ) -> Option<Selection<usize>> {
10680 let cursor = selection.head();
10681 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10682 for symbol in symbols.iter().rev() {
10683 let start = symbol.range.start.to_offset(buffer_snap);
10684 let end = symbol.range.end.to_offset(buffer_snap);
10685 let new_range = start..end;
10686 if start < selection.start || end > selection.end {
10687 return Some(Selection {
10688 id: selection.id,
10689 start: new_range.start,
10690 end: new_range.end,
10691 goal: SelectionGoal::None,
10692 reversed: selection.reversed,
10693 });
10694 }
10695 }
10696 None
10697 }
10698
10699 let mut selected_larger_symbol = false;
10700 let new_selections = old_selections
10701 .iter()
10702 .map(|selection| match update_selection(selection, &buffer) {
10703 Some(new_selection) => {
10704 if new_selection.range() != selection.range() {
10705 selected_larger_symbol = true;
10706 }
10707 new_selection
10708 }
10709 None => selection.clone(),
10710 })
10711 .collect::<Vec<_>>();
10712
10713 if selected_larger_symbol {
10714 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10715 s.select(new_selections);
10716 });
10717 }
10718 }
10719
10720 pub fn select_larger_syntax_node(
10721 &mut self,
10722 _: &SelectLargerSyntaxNode,
10723 window: &mut Window,
10724 cx: &mut Context<Self>,
10725 ) {
10726 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10727 let buffer = self.buffer.read(cx).snapshot(cx);
10728 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10729
10730 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10731 let mut selected_larger_node = false;
10732 let new_selections = old_selections
10733 .iter()
10734 .map(|selection| {
10735 let old_range = selection.start..selection.end;
10736 let mut new_range = old_range.clone();
10737 let mut new_node = None;
10738 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10739 {
10740 new_node = Some(node);
10741 new_range = containing_range;
10742 if !display_map.intersects_fold(new_range.start)
10743 && !display_map.intersects_fold(new_range.end)
10744 {
10745 break;
10746 }
10747 }
10748
10749 if let Some(node) = new_node {
10750 // Log the ancestor, to support using this action as a way to explore TreeSitter
10751 // nodes. Parent and grandparent are also logged because this operation will not
10752 // visit nodes that have the same range as their parent.
10753 log::info!("Node: {node:?}");
10754 let parent = node.parent();
10755 log::info!("Parent: {parent:?}");
10756 let grandparent = parent.and_then(|x| x.parent());
10757 log::info!("Grandparent: {grandparent:?}");
10758 }
10759
10760 selected_larger_node |= new_range != old_range;
10761 Selection {
10762 id: selection.id,
10763 start: new_range.start,
10764 end: new_range.end,
10765 goal: SelectionGoal::None,
10766 reversed: selection.reversed,
10767 }
10768 })
10769 .collect::<Vec<_>>();
10770
10771 if selected_larger_node {
10772 stack.push(old_selections);
10773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10774 s.select(new_selections);
10775 });
10776 }
10777 self.select_larger_syntax_node_stack = stack;
10778 }
10779
10780 pub fn select_smaller_syntax_node(
10781 &mut self,
10782 _: &SelectSmallerSyntaxNode,
10783 window: &mut Window,
10784 cx: &mut Context<Self>,
10785 ) {
10786 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10787 if let Some(selections) = stack.pop() {
10788 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10789 s.select(selections.to_vec());
10790 });
10791 }
10792 self.select_larger_syntax_node_stack = stack;
10793 }
10794
10795 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10796 if !EditorSettings::get_global(cx).gutter.runnables {
10797 self.clear_tasks();
10798 return Task::ready(());
10799 }
10800 let project = self.project.as_ref().map(Entity::downgrade);
10801 cx.spawn_in(window, |this, mut cx| async move {
10802 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10803 let Some(project) = project.and_then(|p| p.upgrade()) else {
10804 return;
10805 };
10806 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10807 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10808 }) else {
10809 return;
10810 };
10811
10812 let hide_runnables = project
10813 .update(&mut cx, |project, cx| {
10814 // Do not display any test indicators in non-dev server remote projects.
10815 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10816 })
10817 .unwrap_or(true);
10818 if hide_runnables {
10819 return;
10820 }
10821 let new_rows =
10822 cx.background_spawn({
10823 let snapshot = display_snapshot.clone();
10824 async move {
10825 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10826 }
10827 })
10828 .await;
10829
10830 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10831 this.update(&mut cx, |this, _| {
10832 this.clear_tasks();
10833 for (key, value) in rows {
10834 this.insert_tasks(key, value);
10835 }
10836 })
10837 .ok();
10838 })
10839 }
10840 fn fetch_runnable_ranges(
10841 snapshot: &DisplaySnapshot,
10842 range: Range<Anchor>,
10843 ) -> Vec<language::RunnableRange> {
10844 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10845 }
10846
10847 fn runnable_rows(
10848 project: Entity<Project>,
10849 snapshot: DisplaySnapshot,
10850 runnable_ranges: Vec<RunnableRange>,
10851 mut cx: AsyncWindowContext,
10852 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10853 runnable_ranges
10854 .into_iter()
10855 .filter_map(|mut runnable| {
10856 let tasks = cx
10857 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10858 .ok()?;
10859 if tasks.is_empty() {
10860 return None;
10861 }
10862
10863 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10864
10865 let row = snapshot
10866 .buffer_snapshot
10867 .buffer_line_for_row(MultiBufferRow(point.row))?
10868 .1
10869 .start
10870 .row;
10871
10872 let context_range =
10873 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10874 Some((
10875 (runnable.buffer_id, row),
10876 RunnableTasks {
10877 templates: tasks,
10878 offset: snapshot
10879 .buffer_snapshot
10880 .anchor_before(runnable.run_range.start),
10881 context_range,
10882 column: point.column,
10883 extra_variables: runnable.extra_captures,
10884 },
10885 ))
10886 })
10887 .collect()
10888 }
10889
10890 fn templates_with_tags(
10891 project: &Entity<Project>,
10892 runnable: &mut Runnable,
10893 cx: &mut App,
10894 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10895 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10896 let (worktree_id, file) = project
10897 .buffer_for_id(runnable.buffer, cx)
10898 .and_then(|buffer| buffer.read(cx).file())
10899 .map(|file| (file.worktree_id(cx), file.clone()))
10900 .unzip();
10901
10902 (
10903 project.task_store().read(cx).task_inventory().cloned(),
10904 worktree_id,
10905 file,
10906 )
10907 });
10908
10909 let tags = mem::take(&mut runnable.tags);
10910 let mut tags: Vec<_> = tags
10911 .into_iter()
10912 .flat_map(|tag| {
10913 let tag = tag.0.clone();
10914 inventory
10915 .as_ref()
10916 .into_iter()
10917 .flat_map(|inventory| {
10918 inventory.read(cx).list_tasks(
10919 file.clone(),
10920 Some(runnable.language.clone()),
10921 worktree_id,
10922 cx,
10923 )
10924 })
10925 .filter(move |(_, template)| {
10926 template.tags.iter().any(|source_tag| source_tag == &tag)
10927 })
10928 })
10929 .sorted_by_key(|(kind, _)| kind.to_owned())
10930 .collect();
10931 if let Some((leading_tag_source, _)) = tags.first() {
10932 // Strongest source wins; if we have worktree tag binding, prefer that to
10933 // global and language bindings;
10934 // if we have a global binding, prefer that to language binding.
10935 let first_mismatch = tags
10936 .iter()
10937 .position(|(tag_source, _)| tag_source != leading_tag_source);
10938 if let Some(index) = first_mismatch {
10939 tags.truncate(index);
10940 }
10941 }
10942
10943 tags
10944 }
10945
10946 pub fn move_to_enclosing_bracket(
10947 &mut self,
10948 _: &MoveToEnclosingBracket,
10949 window: &mut Window,
10950 cx: &mut Context<Self>,
10951 ) {
10952 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10953 s.move_offsets_with(|snapshot, selection| {
10954 let Some(enclosing_bracket_ranges) =
10955 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10956 else {
10957 return;
10958 };
10959
10960 let mut best_length = usize::MAX;
10961 let mut best_inside = false;
10962 let mut best_in_bracket_range = false;
10963 let mut best_destination = None;
10964 for (open, close) in enclosing_bracket_ranges {
10965 let close = close.to_inclusive();
10966 let length = close.end() - open.start;
10967 let inside = selection.start >= open.end && selection.end <= *close.start();
10968 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10969 || close.contains(&selection.head());
10970
10971 // If best is next to a bracket and current isn't, skip
10972 if !in_bracket_range && best_in_bracket_range {
10973 continue;
10974 }
10975
10976 // Prefer smaller lengths unless best is inside and current isn't
10977 if length > best_length && (best_inside || !inside) {
10978 continue;
10979 }
10980
10981 best_length = length;
10982 best_inside = inside;
10983 best_in_bracket_range = in_bracket_range;
10984 best_destination = Some(
10985 if close.contains(&selection.start) && close.contains(&selection.end) {
10986 if inside {
10987 open.end
10988 } else {
10989 open.start
10990 }
10991 } else if inside {
10992 *close.start()
10993 } else {
10994 *close.end()
10995 },
10996 );
10997 }
10998
10999 if let Some(destination) = best_destination {
11000 selection.collapse_to(destination, SelectionGoal::None);
11001 }
11002 })
11003 });
11004 }
11005
11006 pub fn undo_selection(
11007 &mut self,
11008 _: &UndoSelection,
11009 window: &mut Window,
11010 cx: &mut Context<Self>,
11011 ) {
11012 self.end_selection(window, cx);
11013 self.selection_history.mode = SelectionHistoryMode::Undoing;
11014 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11015 self.change_selections(None, window, cx, |s| {
11016 s.select_anchors(entry.selections.to_vec())
11017 });
11018 self.select_next_state = entry.select_next_state;
11019 self.select_prev_state = entry.select_prev_state;
11020 self.add_selections_state = entry.add_selections_state;
11021 self.request_autoscroll(Autoscroll::newest(), cx);
11022 }
11023 self.selection_history.mode = SelectionHistoryMode::Normal;
11024 }
11025
11026 pub fn redo_selection(
11027 &mut self,
11028 _: &RedoSelection,
11029 window: &mut Window,
11030 cx: &mut Context<Self>,
11031 ) {
11032 self.end_selection(window, cx);
11033 self.selection_history.mode = SelectionHistoryMode::Redoing;
11034 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11035 self.change_selections(None, window, cx, |s| {
11036 s.select_anchors(entry.selections.to_vec())
11037 });
11038 self.select_next_state = entry.select_next_state;
11039 self.select_prev_state = entry.select_prev_state;
11040 self.add_selections_state = entry.add_selections_state;
11041 self.request_autoscroll(Autoscroll::newest(), cx);
11042 }
11043 self.selection_history.mode = SelectionHistoryMode::Normal;
11044 }
11045
11046 pub fn expand_excerpts(
11047 &mut self,
11048 action: &ExpandExcerpts,
11049 _: &mut Window,
11050 cx: &mut Context<Self>,
11051 ) {
11052 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11053 }
11054
11055 pub fn expand_excerpts_down(
11056 &mut self,
11057 action: &ExpandExcerptsDown,
11058 _: &mut Window,
11059 cx: &mut Context<Self>,
11060 ) {
11061 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11062 }
11063
11064 pub fn expand_excerpts_up(
11065 &mut self,
11066 action: &ExpandExcerptsUp,
11067 _: &mut Window,
11068 cx: &mut Context<Self>,
11069 ) {
11070 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11071 }
11072
11073 pub fn expand_excerpts_for_direction(
11074 &mut self,
11075 lines: u32,
11076 direction: ExpandExcerptDirection,
11077
11078 cx: &mut Context<Self>,
11079 ) {
11080 let selections = self.selections.disjoint_anchors();
11081
11082 let lines = if lines == 0 {
11083 EditorSettings::get_global(cx).expand_excerpt_lines
11084 } else {
11085 lines
11086 };
11087
11088 self.buffer.update(cx, |buffer, cx| {
11089 let snapshot = buffer.snapshot(cx);
11090 let mut excerpt_ids = selections
11091 .iter()
11092 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11093 .collect::<Vec<_>>();
11094 excerpt_ids.sort();
11095 excerpt_ids.dedup();
11096 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11097 })
11098 }
11099
11100 pub fn expand_excerpt(
11101 &mut self,
11102 excerpt: ExcerptId,
11103 direction: ExpandExcerptDirection,
11104 cx: &mut Context<Self>,
11105 ) {
11106 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11107 self.buffer.update(cx, |buffer, cx| {
11108 buffer.expand_excerpts([excerpt], lines, direction, cx)
11109 })
11110 }
11111
11112 pub fn go_to_singleton_buffer_point(
11113 &mut self,
11114 point: Point,
11115 window: &mut Window,
11116 cx: &mut Context<Self>,
11117 ) {
11118 self.go_to_singleton_buffer_range(point..point, window, cx);
11119 }
11120
11121 pub fn go_to_singleton_buffer_range(
11122 &mut self,
11123 range: Range<Point>,
11124 window: &mut Window,
11125 cx: &mut Context<Self>,
11126 ) {
11127 let multibuffer = self.buffer().read(cx);
11128 let Some(buffer) = multibuffer.as_singleton() else {
11129 return;
11130 };
11131 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11132 return;
11133 };
11134 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11135 return;
11136 };
11137 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11138 s.select_anchor_ranges([start..end])
11139 });
11140 }
11141
11142 fn go_to_diagnostic(
11143 &mut self,
11144 _: &GoToDiagnostic,
11145 window: &mut Window,
11146 cx: &mut Context<Self>,
11147 ) {
11148 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11149 }
11150
11151 fn go_to_prev_diagnostic(
11152 &mut self,
11153 _: &GoToPrevDiagnostic,
11154 window: &mut Window,
11155 cx: &mut Context<Self>,
11156 ) {
11157 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11158 }
11159
11160 pub fn go_to_diagnostic_impl(
11161 &mut self,
11162 direction: Direction,
11163 window: &mut Window,
11164 cx: &mut Context<Self>,
11165 ) {
11166 let buffer = self.buffer.read(cx).snapshot(cx);
11167 let selection = self.selections.newest::<usize>(cx);
11168
11169 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11170 if direction == Direction::Next {
11171 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11172 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11173 return;
11174 };
11175 self.activate_diagnostics(
11176 buffer_id,
11177 popover.local_diagnostic.diagnostic.group_id,
11178 window,
11179 cx,
11180 );
11181 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11182 let primary_range_start = active_diagnostics.primary_range.start;
11183 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11184 let mut new_selection = s.newest_anchor().clone();
11185 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11186 s.select_anchors(vec![new_selection.clone()]);
11187 });
11188 self.refresh_inline_completion(false, true, window, cx);
11189 }
11190 return;
11191 }
11192 }
11193
11194 let active_group_id = self
11195 .active_diagnostics
11196 .as_ref()
11197 .map(|active_group| active_group.group_id);
11198 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11199 active_diagnostics
11200 .primary_range
11201 .to_offset(&buffer)
11202 .to_inclusive()
11203 });
11204 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11205 if active_primary_range.contains(&selection.head()) {
11206 *active_primary_range.start()
11207 } else {
11208 selection.head()
11209 }
11210 } else {
11211 selection.head()
11212 };
11213
11214 let snapshot = self.snapshot(window, cx);
11215 let primary_diagnostics_before = buffer
11216 .diagnostics_in_range::<usize>(0..search_start)
11217 .filter(|entry| entry.diagnostic.is_primary)
11218 .filter(|entry| entry.range.start != entry.range.end)
11219 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11220 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11221 .collect::<Vec<_>>();
11222 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11223 primary_diagnostics_before
11224 .iter()
11225 .position(|entry| entry.diagnostic.group_id == active_group_id)
11226 });
11227
11228 let primary_diagnostics_after = buffer
11229 .diagnostics_in_range::<usize>(search_start..buffer.len())
11230 .filter(|entry| entry.diagnostic.is_primary)
11231 .filter(|entry| entry.range.start != entry.range.end)
11232 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11233 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11234 .collect::<Vec<_>>();
11235 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11236 primary_diagnostics_after
11237 .iter()
11238 .enumerate()
11239 .rev()
11240 .find_map(|(i, entry)| {
11241 if entry.diagnostic.group_id == active_group_id {
11242 Some(i)
11243 } else {
11244 None
11245 }
11246 })
11247 });
11248
11249 let next_primary_diagnostic = match direction {
11250 Direction::Prev => primary_diagnostics_before
11251 .iter()
11252 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11253 .rev()
11254 .next(),
11255 Direction::Next => primary_diagnostics_after
11256 .iter()
11257 .skip(
11258 last_same_group_diagnostic_after
11259 .map(|index| index + 1)
11260 .unwrap_or(0),
11261 )
11262 .next(),
11263 };
11264
11265 // Cycle around to the start of the buffer, potentially moving back to the start of
11266 // the currently active diagnostic.
11267 let cycle_around = || match direction {
11268 Direction::Prev => primary_diagnostics_after
11269 .iter()
11270 .rev()
11271 .chain(primary_diagnostics_before.iter().rev())
11272 .next(),
11273 Direction::Next => primary_diagnostics_before
11274 .iter()
11275 .chain(primary_diagnostics_after.iter())
11276 .next(),
11277 };
11278
11279 if let Some((primary_range, group_id)) = next_primary_diagnostic
11280 .or_else(cycle_around)
11281 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11282 {
11283 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11284 return;
11285 };
11286 self.activate_diagnostics(buffer_id, group_id, window, cx);
11287 if self.active_diagnostics.is_some() {
11288 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289 s.select(vec![Selection {
11290 id: selection.id,
11291 start: primary_range.start,
11292 end: primary_range.start,
11293 reversed: false,
11294 goal: SelectionGoal::None,
11295 }]);
11296 });
11297 self.refresh_inline_completion(false, true, window, cx);
11298 }
11299 }
11300 }
11301
11302 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11303 let snapshot = self.snapshot(window, cx);
11304 let selection = self.selections.newest::<Point>(cx);
11305 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11306 }
11307
11308 fn go_to_hunk_after_position(
11309 &mut self,
11310 snapshot: &EditorSnapshot,
11311 position: Point,
11312 window: &mut Window,
11313 cx: &mut Context<Editor>,
11314 ) -> Option<MultiBufferDiffHunk> {
11315 let mut hunk = snapshot
11316 .buffer_snapshot
11317 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11318 .find(|hunk| hunk.row_range.start.0 > position.row);
11319 if hunk.is_none() {
11320 hunk = snapshot
11321 .buffer_snapshot
11322 .diff_hunks_in_range(Point::zero()..position)
11323 .find(|hunk| hunk.row_range.end.0 < position.row)
11324 }
11325 if let Some(hunk) = &hunk {
11326 let destination = Point::new(hunk.row_range.start.0, 0);
11327 self.unfold_ranges(&[destination..destination], false, false, cx);
11328 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11329 s.select_ranges(vec![destination..destination]);
11330 });
11331 }
11332
11333 hunk
11334 }
11335
11336 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11337 let snapshot = self.snapshot(window, cx);
11338 let selection = self.selections.newest::<Point>(cx);
11339 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11340 }
11341
11342 fn go_to_hunk_before_position(
11343 &mut self,
11344 snapshot: &EditorSnapshot,
11345 position: Point,
11346 window: &mut Window,
11347 cx: &mut Context<Editor>,
11348 ) -> Option<MultiBufferDiffHunk> {
11349 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11350 if hunk.is_none() {
11351 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11352 }
11353 if let Some(hunk) = &hunk {
11354 let destination = Point::new(hunk.row_range.start.0, 0);
11355 self.unfold_ranges(&[destination..destination], false, false, cx);
11356 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11357 s.select_ranges(vec![destination..destination]);
11358 });
11359 }
11360
11361 hunk
11362 }
11363
11364 pub fn go_to_definition(
11365 &mut self,
11366 _: &GoToDefinition,
11367 window: &mut Window,
11368 cx: &mut Context<Self>,
11369 ) -> Task<Result<Navigated>> {
11370 let definition =
11371 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11372 cx.spawn_in(window, |editor, mut cx| async move {
11373 if definition.await? == Navigated::Yes {
11374 return Ok(Navigated::Yes);
11375 }
11376 match editor.update_in(&mut cx, |editor, window, cx| {
11377 editor.find_all_references(&FindAllReferences, window, cx)
11378 })? {
11379 Some(references) => references.await,
11380 None => Ok(Navigated::No),
11381 }
11382 })
11383 }
11384
11385 pub fn go_to_declaration(
11386 &mut self,
11387 _: &GoToDeclaration,
11388 window: &mut Window,
11389 cx: &mut Context<Self>,
11390 ) -> Task<Result<Navigated>> {
11391 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11392 }
11393
11394 pub fn go_to_declaration_split(
11395 &mut self,
11396 _: &GoToDeclaration,
11397 window: &mut Window,
11398 cx: &mut Context<Self>,
11399 ) -> Task<Result<Navigated>> {
11400 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11401 }
11402
11403 pub fn go_to_implementation(
11404 &mut self,
11405 _: &GoToImplementation,
11406 window: &mut Window,
11407 cx: &mut Context<Self>,
11408 ) -> Task<Result<Navigated>> {
11409 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11410 }
11411
11412 pub fn go_to_implementation_split(
11413 &mut self,
11414 _: &GoToImplementationSplit,
11415 window: &mut Window,
11416 cx: &mut Context<Self>,
11417 ) -> Task<Result<Navigated>> {
11418 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11419 }
11420
11421 pub fn go_to_type_definition(
11422 &mut self,
11423 _: &GoToTypeDefinition,
11424 window: &mut Window,
11425 cx: &mut Context<Self>,
11426 ) -> Task<Result<Navigated>> {
11427 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11428 }
11429
11430 pub fn go_to_definition_split(
11431 &mut self,
11432 _: &GoToDefinitionSplit,
11433 window: &mut Window,
11434 cx: &mut Context<Self>,
11435 ) -> Task<Result<Navigated>> {
11436 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11437 }
11438
11439 pub fn go_to_type_definition_split(
11440 &mut self,
11441 _: &GoToTypeDefinitionSplit,
11442 window: &mut Window,
11443 cx: &mut Context<Self>,
11444 ) -> Task<Result<Navigated>> {
11445 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11446 }
11447
11448 fn go_to_definition_of_kind(
11449 &mut self,
11450 kind: GotoDefinitionKind,
11451 split: bool,
11452 window: &mut Window,
11453 cx: &mut Context<Self>,
11454 ) -> Task<Result<Navigated>> {
11455 let Some(provider) = self.semantics_provider.clone() else {
11456 return Task::ready(Ok(Navigated::No));
11457 };
11458 let head = self.selections.newest::<usize>(cx).head();
11459 let buffer = self.buffer.read(cx);
11460 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11461 text_anchor
11462 } else {
11463 return Task::ready(Ok(Navigated::No));
11464 };
11465
11466 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11467 return Task::ready(Ok(Navigated::No));
11468 };
11469
11470 cx.spawn_in(window, |editor, mut cx| async move {
11471 let definitions = definitions.await?;
11472 let navigated = editor
11473 .update_in(&mut cx, |editor, window, cx| {
11474 editor.navigate_to_hover_links(
11475 Some(kind),
11476 definitions
11477 .into_iter()
11478 .filter(|location| {
11479 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11480 })
11481 .map(HoverLink::Text)
11482 .collect::<Vec<_>>(),
11483 split,
11484 window,
11485 cx,
11486 )
11487 })?
11488 .await?;
11489 anyhow::Ok(navigated)
11490 })
11491 }
11492
11493 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11494 let selection = self.selections.newest_anchor();
11495 let head = selection.head();
11496 let tail = selection.tail();
11497
11498 let Some((buffer, start_position)) =
11499 self.buffer.read(cx).text_anchor_for_position(head, cx)
11500 else {
11501 return;
11502 };
11503
11504 let end_position = if head != tail {
11505 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11506 return;
11507 };
11508 Some(pos)
11509 } else {
11510 None
11511 };
11512
11513 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11514 let url = if let Some(end_pos) = end_position {
11515 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11516 } else {
11517 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11518 };
11519
11520 if let Some(url) = url {
11521 editor.update(&mut cx, |_, cx| {
11522 cx.open_url(&url);
11523 })
11524 } else {
11525 Ok(())
11526 }
11527 });
11528
11529 url_finder.detach();
11530 }
11531
11532 pub fn open_selected_filename(
11533 &mut self,
11534 _: &OpenSelectedFilename,
11535 window: &mut Window,
11536 cx: &mut Context<Self>,
11537 ) {
11538 let Some(workspace) = self.workspace() else {
11539 return;
11540 };
11541
11542 let position = self.selections.newest_anchor().head();
11543
11544 let Some((buffer, buffer_position)) =
11545 self.buffer.read(cx).text_anchor_for_position(position, cx)
11546 else {
11547 return;
11548 };
11549
11550 let project = self.project.clone();
11551
11552 cx.spawn_in(window, |_, mut cx| async move {
11553 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11554
11555 if let Some((_, path)) = result {
11556 workspace
11557 .update_in(&mut cx, |workspace, window, cx| {
11558 workspace.open_resolved_path(path, window, cx)
11559 })?
11560 .await?;
11561 }
11562 anyhow::Ok(())
11563 })
11564 .detach();
11565 }
11566
11567 pub(crate) fn navigate_to_hover_links(
11568 &mut self,
11569 kind: Option<GotoDefinitionKind>,
11570 mut definitions: Vec<HoverLink>,
11571 split: bool,
11572 window: &mut Window,
11573 cx: &mut Context<Editor>,
11574 ) -> Task<Result<Navigated>> {
11575 // If there is one definition, just open it directly
11576 if definitions.len() == 1 {
11577 let definition = definitions.pop().unwrap();
11578
11579 enum TargetTaskResult {
11580 Location(Option<Location>),
11581 AlreadyNavigated,
11582 }
11583
11584 let target_task = match definition {
11585 HoverLink::Text(link) => {
11586 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11587 }
11588 HoverLink::InlayHint(lsp_location, server_id) => {
11589 let computation =
11590 self.compute_target_location(lsp_location, server_id, window, cx);
11591 cx.background_spawn(async move {
11592 let location = computation.await?;
11593 Ok(TargetTaskResult::Location(location))
11594 })
11595 }
11596 HoverLink::Url(url) => {
11597 cx.open_url(&url);
11598 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11599 }
11600 HoverLink::File(path) => {
11601 if let Some(workspace) = self.workspace() {
11602 cx.spawn_in(window, |_, mut cx| async move {
11603 workspace
11604 .update_in(&mut cx, |workspace, window, cx| {
11605 workspace.open_resolved_path(path, window, cx)
11606 })?
11607 .await
11608 .map(|_| TargetTaskResult::AlreadyNavigated)
11609 })
11610 } else {
11611 Task::ready(Ok(TargetTaskResult::Location(None)))
11612 }
11613 }
11614 };
11615 cx.spawn_in(window, |editor, mut cx| async move {
11616 let target = match target_task.await.context("target resolution task")? {
11617 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11618 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11619 TargetTaskResult::Location(Some(target)) => target,
11620 };
11621
11622 editor.update_in(&mut cx, |editor, window, cx| {
11623 let Some(workspace) = editor.workspace() else {
11624 return Navigated::No;
11625 };
11626 let pane = workspace.read(cx).active_pane().clone();
11627
11628 let range = target.range.to_point(target.buffer.read(cx));
11629 let range = editor.range_for_match(&range);
11630 let range = collapse_multiline_range(range);
11631
11632 if !split
11633 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11634 {
11635 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11636 } else {
11637 window.defer(cx, move |window, cx| {
11638 let target_editor: Entity<Self> =
11639 workspace.update(cx, |workspace, cx| {
11640 let pane = if split {
11641 workspace.adjacent_pane(window, cx)
11642 } else {
11643 workspace.active_pane().clone()
11644 };
11645
11646 workspace.open_project_item(
11647 pane,
11648 target.buffer.clone(),
11649 true,
11650 true,
11651 window,
11652 cx,
11653 )
11654 });
11655 target_editor.update(cx, |target_editor, cx| {
11656 // When selecting a definition in a different buffer, disable the nav history
11657 // to avoid creating a history entry at the previous cursor location.
11658 pane.update(cx, |pane, _| pane.disable_history());
11659 target_editor.go_to_singleton_buffer_range(range, window, cx);
11660 pane.update(cx, |pane, _| pane.enable_history());
11661 });
11662 });
11663 }
11664 Navigated::Yes
11665 })
11666 })
11667 } else if !definitions.is_empty() {
11668 cx.spawn_in(window, |editor, mut cx| async move {
11669 let (title, location_tasks, workspace) = editor
11670 .update_in(&mut cx, |editor, window, cx| {
11671 let tab_kind = match kind {
11672 Some(GotoDefinitionKind::Implementation) => "Implementations",
11673 _ => "Definitions",
11674 };
11675 let title = definitions
11676 .iter()
11677 .find_map(|definition| match definition {
11678 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11679 let buffer = origin.buffer.read(cx);
11680 format!(
11681 "{} for {}",
11682 tab_kind,
11683 buffer
11684 .text_for_range(origin.range.clone())
11685 .collect::<String>()
11686 )
11687 }),
11688 HoverLink::InlayHint(_, _) => None,
11689 HoverLink::Url(_) => None,
11690 HoverLink::File(_) => None,
11691 })
11692 .unwrap_or(tab_kind.to_string());
11693 let location_tasks = definitions
11694 .into_iter()
11695 .map(|definition| match definition {
11696 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11697 HoverLink::InlayHint(lsp_location, server_id) => editor
11698 .compute_target_location(lsp_location, server_id, window, cx),
11699 HoverLink::Url(_) => Task::ready(Ok(None)),
11700 HoverLink::File(_) => Task::ready(Ok(None)),
11701 })
11702 .collect::<Vec<_>>();
11703 (title, location_tasks, editor.workspace().clone())
11704 })
11705 .context("location tasks preparation")?;
11706
11707 let locations = future::join_all(location_tasks)
11708 .await
11709 .into_iter()
11710 .filter_map(|location| location.transpose())
11711 .collect::<Result<_>>()
11712 .context("location tasks")?;
11713
11714 let Some(workspace) = workspace else {
11715 return Ok(Navigated::No);
11716 };
11717 let opened = workspace
11718 .update_in(&mut cx, |workspace, window, cx| {
11719 Self::open_locations_in_multibuffer(
11720 workspace,
11721 locations,
11722 title,
11723 split,
11724 MultibufferSelectionMode::First,
11725 window,
11726 cx,
11727 )
11728 })
11729 .ok();
11730
11731 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11732 })
11733 } else {
11734 Task::ready(Ok(Navigated::No))
11735 }
11736 }
11737
11738 fn compute_target_location(
11739 &self,
11740 lsp_location: lsp::Location,
11741 server_id: LanguageServerId,
11742 window: &mut Window,
11743 cx: &mut Context<Self>,
11744 ) -> Task<anyhow::Result<Option<Location>>> {
11745 let Some(project) = self.project.clone() else {
11746 return Task::ready(Ok(None));
11747 };
11748
11749 cx.spawn_in(window, move |editor, mut cx| async move {
11750 let location_task = editor.update(&mut cx, |_, cx| {
11751 project.update(cx, |project, cx| {
11752 let language_server_name = project
11753 .language_server_statuses(cx)
11754 .find(|(id, _)| server_id == *id)
11755 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11756 language_server_name.map(|language_server_name| {
11757 project.open_local_buffer_via_lsp(
11758 lsp_location.uri.clone(),
11759 server_id,
11760 language_server_name,
11761 cx,
11762 )
11763 })
11764 })
11765 })?;
11766 let location = match location_task {
11767 Some(task) => Some({
11768 let target_buffer_handle = task.await.context("open local buffer")?;
11769 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11770 let target_start = target_buffer
11771 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11772 let target_end = target_buffer
11773 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11774 target_buffer.anchor_after(target_start)
11775 ..target_buffer.anchor_before(target_end)
11776 })?;
11777 Location {
11778 buffer: target_buffer_handle,
11779 range,
11780 }
11781 }),
11782 None => None,
11783 };
11784 Ok(location)
11785 })
11786 }
11787
11788 pub fn find_all_references(
11789 &mut self,
11790 _: &FindAllReferences,
11791 window: &mut Window,
11792 cx: &mut Context<Self>,
11793 ) -> Option<Task<Result<Navigated>>> {
11794 let selection = self.selections.newest::<usize>(cx);
11795 let multi_buffer = self.buffer.read(cx);
11796 let head = selection.head();
11797
11798 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11799 let head_anchor = multi_buffer_snapshot.anchor_at(
11800 head,
11801 if head < selection.tail() {
11802 Bias::Right
11803 } else {
11804 Bias::Left
11805 },
11806 );
11807
11808 match self
11809 .find_all_references_task_sources
11810 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11811 {
11812 Ok(_) => {
11813 log::info!(
11814 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11815 );
11816 return None;
11817 }
11818 Err(i) => {
11819 self.find_all_references_task_sources.insert(i, head_anchor);
11820 }
11821 }
11822
11823 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11824 let workspace = self.workspace()?;
11825 let project = workspace.read(cx).project().clone();
11826 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11827 Some(cx.spawn_in(window, |editor, mut cx| async move {
11828 let _cleanup = defer({
11829 let mut cx = cx.clone();
11830 move || {
11831 let _ = editor.update(&mut cx, |editor, _| {
11832 if let Ok(i) =
11833 editor
11834 .find_all_references_task_sources
11835 .binary_search_by(|anchor| {
11836 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11837 })
11838 {
11839 editor.find_all_references_task_sources.remove(i);
11840 }
11841 });
11842 }
11843 });
11844
11845 let locations = references.await?;
11846 if locations.is_empty() {
11847 return anyhow::Ok(Navigated::No);
11848 }
11849
11850 workspace.update_in(&mut cx, |workspace, window, cx| {
11851 let title = locations
11852 .first()
11853 .as_ref()
11854 .map(|location| {
11855 let buffer = location.buffer.read(cx);
11856 format!(
11857 "References to `{}`",
11858 buffer
11859 .text_for_range(location.range.clone())
11860 .collect::<String>()
11861 )
11862 })
11863 .unwrap();
11864 Self::open_locations_in_multibuffer(
11865 workspace,
11866 locations,
11867 title,
11868 false,
11869 MultibufferSelectionMode::First,
11870 window,
11871 cx,
11872 );
11873 Navigated::Yes
11874 })
11875 }))
11876 }
11877
11878 /// Opens a multibuffer with the given project locations in it
11879 pub fn open_locations_in_multibuffer(
11880 workspace: &mut Workspace,
11881 mut locations: Vec<Location>,
11882 title: String,
11883 split: bool,
11884 multibuffer_selection_mode: MultibufferSelectionMode,
11885 window: &mut Window,
11886 cx: &mut Context<Workspace>,
11887 ) {
11888 // If there are multiple definitions, open them in a multibuffer
11889 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11890 let mut locations = locations.into_iter().peekable();
11891 let mut ranges = Vec::new();
11892 let capability = workspace.project().read(cx).capability();
11893
11894 let excerpt_buffer = cx.new(|cx| {
11895 let mut multibuffer = MultiBuffer::new(capability);
11896 while let Some(location) = locations.next() {
11897 let buffer = location.buffer.read(cx);
11898 let mut ranges_for_buffer = Vec::new();
11899 let range = location.range.to_offset(buffer);
11900 ranges_for_buffer.push(range.clone());
11901
11902 while let Some(next_location) = locations.peek() {
11903 if next_location.buffer == location.buffer {
11904 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11905 locations.next();
11906 } else {
11907 break;
11908 }
11909 }
11910
11911 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11912 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11913 location.buffer.clone(),
11914 ranges_for_buffer,
11915 DEFAULT_MULTIBUFFER_CONTEXT,
11916 cx,
11917 ))
11918 }
11919
11920 multibuffer.with_title(title)
11921 });
11922
11923 let editor = cx.new(|cx| {
11924 Editor::for_multibuffer(
11925 excerpt_buffer,
11926 Some(workspace.project().clone()),
11927 true,
11928 window,
11929 cx,
11930 )
11931 });
11932 editor.update(cx, |editor, cx| {
11933 match multibuffer_selection_mode {
11934 MultibufferSelectionMode::First => {
11935 if let Some(first_range) = ranges.first() {
11936 editor.change_selections(None, window, cx, |selections| {
11937 selections.clear_disjoint();
11938 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11939 });
11940 }
11941 editor.highlight_background::<Self>(
11942 &ranges,
11943 |theme| theme.editor_highlighted_line_background,
11944 cx,
11945 );
11946 }
11947 MultibufferSelectionMode::All => {
11948 editor.change_selections(None, window, cx, |selections| {
11949 selections.clear_disjoint();
11950 selections.select_anchor_ranges(ranges);
11951 });
11952 }
11953 }
11954 editor.register_buffers_with_language_servers(cx);
11955 });
11956
11957 let item = Box::new(editor);
11958 let item_id = item.item_id();
11959
11960 if split {
11961 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11962 } else {
11963 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11964 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11965 pane.close_current_preview_item(window, cx)
11966 } else {
11967 None
11968 }
11969 });
11970 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11971 }
11972 workspace.active_pane().update(cx, |pane, cx| {
11973 pane.set_preview_item_id(Some(item_id), cx);
11974 });
11975 }
11976
11977 pub fn rename(
11978 &mut self,
11979 _: &Rename,
11980 window: &mut Window,
11981 cx: &mut Context<Self>,
11982 ) -> Option<Task<Result<()>>> {
11983 use language::ToOffset as _;
11984
11985 let provider = self.semantics_provider.clone()?;
11986 let selection = self.selections.newest_anchor().clone();
11987 let (cursor_buffer, cursor_buffer_position) = self
11988 .buffer
11989 .read(cx)
11990 .text_anchor_for_position(selection.head(), cx)?;
11991 let (tail_buffer, cursor_buffer_position_end) = self
11992 .buffer
11993 .read(cx)
11994 .text_anchor_for_position(selection.tail(), cx)?;
11995 if tail_buffer != cursor_buffer {
11996 return None;
11997 }
11998
11999 let snapshot = cursor_buffer.read(cx).snapshot();
12000 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12001 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12002 let prepare_rename = provider
12003 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12004 .unwrap_or_else(|| Task::ready(Ok(None)));
12005 drop(snapshot);
12006
12007 Some(cx.spawn_in(window, |this, mut cx| async move {
12008 let rename_range = if let Some(range) = prepare_rename.await? {
12009 Some(range)
12010 } else {
12011 this.update(&mut cx, |this, cx| {
12012 let buffer = this.buffer.read(cx).snapshot(cx);
12013 let mut buffer_highlights = this
12014 .document_highlights_for_position(selection.head(), &buffer)
12015 .filter(|highlight| {
12016 highlight.start.excerpt_id == selection.head().excerpt_id
12017 && highlight.end.excerpt_id == selection.head().excerpt_id
12018 });
12019 buffer_highlights
12020 .next()
12021 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12022 })?
12023 };
12024 if let Some(rename_range) = rename_range {
12025 this.update_in(&mut cx, |this, window, cx| {
12026 let snapshot = cursor_buffer.read(cx).snapshot();
12027 let rename_buffer_range = rename_range.to_offset(&snapshot);
12028 let cursor_offset_in_rename_range =
12029 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12030 let cursor_offset_in_rename_range_end =
12031 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12032
12033 this.take_rename(false, window, cx);
12034 let buffer = this.buffer.read(cx).read(cx);
12035 let cursor_offset = selection.head().to_offset(&buffer);
12036 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12037 let rename_end = rename_start + rename_buffer_range.len();
12038 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12039 let mut old_highlight_id = None;
12040 let old_name: Arc<str> = buffer
12041 .chunks(rename_start..rename_end, true)
12042 .map(|chunk| {
12043 if old_highlight_id.is_none() {
12044 old_highlight_id = chunk.syntax_highlight_id;
12045 }
12046 chunk.text
12047 })
12048 .collect::<String>()
12049 .into();
12050
12051 drop(buffer);
12052
12053 // Position the selection in the rename editor so that it matches the current selection.
12054 this.show_local_selections = false;
12055 let rename_editor = cx.new(|cx| {
12056 let mut editor = Editor::single_line(window, cx);
12057 editor.buffer.update(cx, |buffer, cx| {
12058 buffer.edit([(0..0, old_name.clone())], None, cx)
12059 });
12060 let rename_selection_range = match cursor_offset_in_rename_range
12061 .cmp(&cursor_offset_in_rename_range_end)
12062 {
12063 Ordering::Equal => {
12064 editor.select_all(&SelectAll, window, cx);
12065 return editor;
12066 }
12067 Ordering::Less => {
12068 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12069 }
12070 Ordering::Greater => {
12071 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12072 }
12073 };
12074 if rename_selection_range.end > old_name.len() {
12075 editor.select_all(&SelectAll, window, cx);
12076 } else {
12077 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12078 s.select_ranges([rename_selection_range]);
12079 });
12080 }
12081 editor
12082 });
12083 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12084 if e == &EditorEvent::Focused {
12085 cx.emit(EditorEvent::FocusedIn)
12086 }
12087 })
12088 .detach();
12089
12090 let write_highlights =
12091 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12092 let read_highlights =
12093 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12094 let ranges = write_highlights
12095 .iter()
12096 .flat_map(|(_, ranges)| ranges.iter())
12097 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12098 .cloned()
12099 .collect();
12100
12101 this.highlight_text::<Rename>(
12102 ranges,
12103 HighlightStyle {
12104 fade_out: Some(0.6),
12105 ..Default::default()
12106 },
12107 cx,
12108 );
12109 let rename_focus_handle = rename_editor.focus_handle(cx);
12110 window.focus(&rename_focus_handle);
12111 let block_id = this.insert_blocks(
12112 [BlockProperties {
12113 style: BlockStyle::Flex,
12114 placement: BlockPlacement::Below(range.start),
12115 height: 1,
12116 render: Arc::new({
12117 let rename_editor = rename_editor.clone();
12118 move |cx: &mut BlockContext| {
12119 let mut text_style = cx.editor_style.text.clone();
12120 if let Some(highlight_style) = old_highlight_id
12121 .and_then(|h| h.style(&cx.editor_style.syntax))
12122 {
12123 text_style = text_style.highlight(highlight_style);
12124 }
12125 div()
12126 .block_mouse_down()
12127 .pl(cx.anchor_x)
12128 .child(EditorElement::new(
12129 &rename_editor,
12130 EditorStyle {
12131 background: cx.theme().system().transparent,
12132 local_player: cx.editor_style.local_player,
12133 text: text_style,
12134 scrollbar_width: cx.editor_style.scrollbar_width,
12135 syntax: cx.editor_style.syntax.clone(),
12136 status: cx.editor_style.status.clone(),
12137 inlay_hints_style: HighlightStyle {
12138 font_weight: Some(FontWeight::BOLD),
12139 ..make_inlay_hints_style(cx.app)
12140 },
12141 inline_completion_styles: make_suggestion_styles(
12142 cx.app,
12143 ),
12144 ..EditorStyle::default()
12145 },
12146 ))
12147 .into_any_element()
12148 }
12149 }),
12150 priority: 0,
12151 }],
12152 Some(Autoscroll::fit()),
12153 cx,
12154 )[0];
12155 this.pending_rename = Some(RenameState {
12156 range,
12157 old_name,
12158 editor: rename_editor,
12159 block_id,
12160 });
12161 })?;
12162 }
12163
12164 Ok(())
12165 }))
12166 }
12167
12168 pub fn confirm_rename(
12169 &mut self,
12170 _: &ConfirmRename,
12171 window: &mut Window,
12172 cx: &mut Context<Self>,
12173 ) -> Option<Task<Result<()>>> {
12174 let rename = self.take_rename(false, window, cx)?;
12175 let workspace = self.workspace()?.downgrade();
12176 let (buffer, start) = self
12177 .buffer
12178 .read(cx)
12179 .text_anchor_for_position(rename.range.start, cx)?;
12180 let (end_buffer, _) = self
12181 .buffer
12182 .read(cx)
12183 .text_anchor_for_position(rename.range.end, cx)?;
12184 if buffer != end_buffer {
12185 return None;
12186 }
12187
12188 let old_name = rename.old_name;
12189 let new_name = rename.editor.read(cx).text(cx);
12190
12191 let rename = self.semantics_provider.as_ref()?.perform_rename(
12192 &buffer,
12193 start,
12194 new_name.clone(),
12195 cx,
12196 )?;
12197
12198 Some(cx.spawn_in(window, |editor, mut cx| async move {
12199 let project_transaction = rename.await?;
12200 Self::open_project_transaction(
12201 &editor,
12202 workspace,
12203 project_transaction,
12204 format!("Rename: {} → {}", old_name, new_name),
12205 cx.clone(),
12206 )
12207 .await?;
12208
12209 editor.update(&mut cx, |editor, cx| {
12210 editor.refresh_document_highlights(cx);
12211 })?;
12212 Ok(())
12213 }))
12214 }
12215
12216 fn take_rename(
12217 &mut self,
12218 moving_cursor: bool,
12219 window: &mut Window,
12220 cx: &mut Context<Self>,
12221 ) -> Option<RenameState> {
12222 let rename = self.pending_rename.take()?;
12223 if rename.editor.focus_handle(cx).is_focused(window) {
12224 window.focus(&self.focus_handle);
12225 }
12226
12227 self.remove_blocks(
12228 [rename.block_id].into_iter().collect(),
12229 Some(Autoscroll::fit()),
12230 cx,
12231 );
12232 self.clear_highlights::<Rename>(cx);
12233 self.show_local_selections = true;
12234
12235 if moving_cursor {
12236 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12237 editor.selections.newest::<usize>(cx).head()
12238 });
12239
12240 // Update the selection to match the position of the selection inside
12241 // the rename editor.
12242 let snapshot = self.buffer.read(cx).read(cx);
12243 let rename_range = rename.range.to_offset(&snapshot);
12244 let cursor_in_editor = snapshot
12245 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12246 .min(rename_range.end);
12247 drop(snapshot);
12248
12249 self.change_selections(None, window, cx, |s| {
12250 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12251 });
12252 } else {
12253 self.refresh_document_highlights(cx);
12254 }
12255
12256 Some(rename)
12257 }
12258
12259 pub fn pending_rename(&self) -> Option<&RenameState> {
12260 self.pending_rename.as_ref()
12261 }
12262
12263 fn format(
12264 &mut self,
12265 _: &Format,
12266 window: &mut Window,
12267 cx: &mut Context<Self>,
12268 ) -> Option<Task<Result<()>>> {
12269 let project = match &self.project {
12270 Some(project) => project.clone(),
12271 None => return None,
12272 };
12273
12274 Some(self.perform_format(
12275 project,
12276 FormatTrigger::Manual,
12277 FormatTarget::Buffers,
12278 window,
12279 cx,
12280 ))
12281 }
12282
12283 fn format_selections(
12284 &mut self,
12285 _: &FormatSelections,
12286 window: &mut Window,
12287 cx: &mut Context<Self>,
12288 ) -> Option<Task<Result<()>>> {
12289 let project = match &self.project {
12290 Some(project) => project.clone(),
12291 None => return None,
12292 };
12293
12294 let ranges = self
12295 .selections
12296 .all_adjusted(cx)
12297 .into_iter()
12298 .map(|selection| selection.range())
12299 .collect_vec();
12300
12301 Some(self.perform_format(
12302 project,
12303 FormatTrigger::Manual,
12304 FormatTarget::Ranges(ranges),
12305 window,
12306 cx,
12307 ))
12308 }
12309
12310 fn perform_format(
12311 &mut self,
12312 project: Entity<Project>,
12313 trigger: FormatTrigger,
12314 target: FormatTarget,
12315 window: &mut Window,
12316 cx: &mut Context<Self>,
12317 ) -> Task<Result<()>> {
12318 let buffer = self.buffer.clone();
12319 let (buffers, target) = match target {
12320 FormatTarget::Buffers => {
12321 let mut buffers = buffer.read(cx).all_buffers();
12322 if trigger == FormatTrigger::Save {
12323 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12324 }
12325 (buffers, LspFormatTarget::Buffers)
12326 }
12327 FormatTarget::Ranges(selection_ranges) => {
12328 let multi_buffer = buffer.read(cx);
12329 let snapshot = multi_buffer.read(cx);
12330 let mut buffers = HashSet::default();
12331 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12332 BTreeMap::new();
12333 for selection_range in selection_ranges {
12334 for (buffer, buffer_range, _) in
12335 snapshot.range_to_buffer_ranges(selection_range)
12336 {
12337 let buffer_id = buffer.remote_id();
12338 let start = buffer.anchor_before(buffer_range.start);
12339 let end = buffer.anchor_after(buffer_range.end);
12340 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12341 buffer_id_to_ranges
12342 .entry(buffer_id)
12343 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12344 .or_insert_with(|| vec![start..end]);
12345 }
12346 }
12347 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12348 }
12349 };
12350
12351 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12352 let format = project.update(cx, |project, cx| {
12353 project.format(buffers, target, true, trigger, cx)
12354 });
12355
12356 cx.spawn_in(window, |_, mut cx| async move {
12357 let transaction = futures::select_biased! {
12358 () = timeout => {
12359 log::warn!("timed out waiting for formatting");
12360 None
12361 }
12362 transaction = format.log_err().fuse() => transaction,
12363 };
12364
12365 buffer
12366 .update(&mut cx, |buffer, cx| {
12367 if let Some(transaction) = transaction {
12368 if !buffer.is_singleton() {
12369 buffer.push_transaction(&transaction.0, cx);
12370 }
12371 }
12372
12373 cx.notify();
12374 })
12375 .ok();
12376
12377 Ok(())
12378 })
12379 }
12380
12381 fn restart_language_server(
12382 &mut self,
12383 _: &RestartLanguageServer,
12384 _: &mut Window,
12385 cx: &mut Context<Self>,
12386 ) {
12387 if let Some(project) = self.project.clone() {
12388 self.buffer.update(cx, |multi_buffer, cx| {
12389 project.update(cx, |project, cx| {
12390 project.restart_language_servers_for_buffers(
12391 multi_buffer.all_buffers().into_iter().collect(),
12392 cx,
12393 );
12394 });
12395 })
12396 }
12397 }
12398
12399 fn cancel_language_server_work(
12400 workspace: &mut Workspace,
12401 _: &actions::CancelLanguageServerWork,
12402 _: &mut Window,
12403 cx: &mut Context<Workspace>,
12404 ) {
12405 let project = workspace.project();
12406 let buffers = workspace
12407 .active_item(cx)
12408 .and_then(|item| item.act_as::<Editor>(cx))
12409 .map_or(HashSet::default(), |editor| {
12410 editor.read(cx).buffer.read(cx).all_buffers()
12411 });
12412 project.update(cx, |project, cx| {
12413 project.cancel_language_server_work_for_buffers(buffers, cx);
12414 });
12415 }
12416
12417 fn show_character_palette(
12418 &mut self,
12419 _: &ShowCharacterPalette,
12420 window: &mut Window,
12421 _: &mut Context<Self>,
12422 ) {
12423 window.show_character_palette();
12424 }
12425
12426 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12427 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12428 let buffer = self.buffer.read(cx).snapshot(cx);
12429 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12430 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12431 let is_valid = buffer
12432 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12433 .any(|entry| {
12434 entry.diagnostic.is_primary
12435 && !entry.range.is_empty()
12436 && entry.range.start == primary_range_start
12437 && entry.diagnostic.message == active_diagnostics.primary_message
12438 });
12439
12440 if is_valid != active_diagnostics.is_valid {
12441 active_diagnostics.is_valid = is_valid;
12442 let mut new_styles = HashMap::default();
12443 for (block_id, diagnostic) in &active_diagnostics.blocks {
12444 new_styles.insert(
12445 *block_id,
12446 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12447 );
12448 }
12449 self.display_map.update(cx, |display_map, _cx| {
12450 display_map.replace_blocks(new_styles)
12451 });
12452 }
12453 }
12454 }
12455
12456 fn activate_diagnostics(
12457 &mut self,
12458 buffer_id: BufferId,
12459 group_id: usize,
12460 window: &mut Window,
12461 cx: &mut Context<Self>,
12462 ) {
12463 self.dismiss_diagnostics(cx);
12464 let snapshot = self.snapshot(window, cx);
12465 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12466 let buffer = self.buffer.read(cx).snapshot(cx);
12467
12468 let mut primary_range = None;
12469 let mut primary_message = None;
12470 let diagnostic_group = buffer
12471 .diagnostic_group(buffer_id, group_id)
12472 .filter_map(|entry| {
12473 let start = entry.range.start;
12474 let end = entry.range.end;
12475 if snapshot.is_line_folded(MultiBufferRow(start.row))
12476 && (start.row == end.row
12477 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12478 {
12479 return None;
12480 }
12481 if entry.diagnostic.is_primary {
12482 primary_range = Some(entry.range.clone());
12483 primary_message = Some(entry.diagnostic.message.clone());
12484 }
12485 Some(entry)
12486 })
12487 .collect::<Vec<_>>();
12488 let primary_range = primary_range?;
12489 let primary_message = primary_message?;
12490
12491 let blocks = display_map
12492 .insert_blocks(
12493 diagnostic_group.iter().map(|entry| {
12494 let diagnostic = entry.diagnostic.clone();
12495 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12496 BlockProperties {
12497 style: BlockStyle::Fixed,
12498 placement: BlockPlacement::Below(
12499 buffer.anchor_after(entry.range.start),
12500 ),
12501 height: message_height,
12502 render: diagnostic_block_renderer(diagnostic, None, true, true),
12503 priority: 0,
12504 }
12505 }),
12506 cx,
12507 )
12508 .into_iter()
12509 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12510 .collect();
12511
12512 Some(ActiveDiagnosticGroup {
12513 primary_range: buffer.anchor_before(primary_range.start)
12514 ..buffer.anchor_after(primary_range.end),
12515 primary_message,
12516 group_id,
12517 blocks,
12518 is_valid: true,
12519 })
12520 });
12521 }
12522
12523 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12524 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12525 self.display_map.update(cx, |display_map, cx| {
12526 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12527 });
12528 cx.notify();
12529 }
12530 }
12531
12532 /// Disable inline diagnostics rendering for this editor.
12533 pub fn disable_inline_diagnostics(&mut self) {
12534 self.inline_diagnostics_enabled = false;
12535 self.inline_diagnostics_update = Task::ready(());
12536 self.inline_diagnostics.clear();
12537 }
12538
12539 pub fn inline_diagnostics_enabled(&self) -> bool {
12540 self.inline_diagnostics_enabled
12541 }
12542
12543 pub fn show_inline_diagnostics(&self) -> bool {
12544 self.show_inline_diagnostics
12545 }
12546
12547 pub fn toggle_inline_diagnostics(
12548 &mut self,
12549 _: &ToggleInlineDiagnostics,
12550 window: &mut Window,
12551 cx: &mut Context<'_, Editor>,
12552 ) {
12553 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12554 self.refresh_inline_diagnostics(false, window, cx);
12555 }
12556
12557 fn refresh_inline_diagnostics(
12558 &mut self,
12559 debounce: bool,
12560 window: &mut Window,
12561 cx: &mut Context<Self>,
12562 ) {
12563 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12564 self.inline_diagnostics_update = Task::ready(());
12565 self.inline_diagnostics.clear();
12566 return;
12567 }
12568
12569 let debounce_ms = ProjectSettings::get_global(cx)
12570 .diagnostics
12571 .inline
12572 .update_debounce_ms;
12573 let debounce = if debounce && debounce_ms > 0 {
12574 Some(Duration::from_millis(debounce_ms))
12575 } else {
12576 None
12577 };
12578 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12579 if let Some(debounce) = debounce {
12580 cx.background_executor().timer(debounce).await;
12581 }
12582 let Some(snapshot) = editor
12583 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12584 .ok()
12585 else {
12586 return;
12587 };
12588
12589 let new_inline_diagnostics = cx
12590 .background_spawn(async move {
12591 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12592 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12593 let message = diagnostic_entry
12594 .diagnostic
12595 .message
12596 .split_once('\n')
12597 .map(|(line, _)| line)
12598 .map(SharedString::new)
12599 .unwrap_or_else(|| {
12600 SharedString::from(diagnostic_entry.diagnostic.message)
12601 });
12602 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12603 let (Ok(i) | Err(i)) = inline_diagnostics
12604 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12605 inline_diagnostics.insert(
12606 i,
12607 (
12608 start_anchor,
12609 InlineDiagnostic {
12610 message,
12611 group_id: diagnostic_entry.diagnostic.group_id,
12612 start: diagnostic_entry.range.start.to_point(&snapshot),
12613 is_primary: diagnostic_entry.diagnostic.is_primary,
12614 severity: diagnostic_entry.diagnostic.severity,
12615 },
12616 ),
12617 );
12618 }
12619 inline_diagnostics
12620 })
12621 .await;
12622
12623 editor
12624 .update(&mut cx, |editor, cx| {
12625 editor.inline_diagnostics = new_inline_diagnostics;
12626 cx.notify();
12627 })
12628 .ok();
12629 });
12630 }
12631
12632 pub fn set_selections_from_remote(
12633 &mut self,
12634 selections: Vec<Selection<Anchor>>,
12635 pending_selection: Option<Selection<Anchor>>,
12636 window: &mut Window,
12637 cx: &mut Context<Self>,
12638 ) {
12639 let old_cursor_position = self.selections.newest_anchor().head();
12640 self.selections.change_with(cx, |s| {
12641 s.select_anchors(selections);
12642 if let Some(pending_selection) = pending_selection {
12643 s.set_pending(pending_selection, SelectMode::Character);
12644 } else {
12645 s.clear_pending();
12646 }
12647 });
12648 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12649 }
12650
12651 fn push_to_selection_history(&mut self) {
12652 self.selection_history.push(SelectionHistoryEntry {
12653 selections: self.selections.disjoint_anchors(),
12654 select_next_state: self.select_next_state.clone(),
12655 select_prev_state: self.select_prev_state.clone(),
12656 add_selections_state: self.add_selections_state.clone(),
12657 });
12658 }
12659
12660 pub fn transact(
12661 &mut self,
12662 window: &mut Window,
12663 cx: &mut Context<Self>,
12664 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12665 ) -> Option<TransactionId> {
12666 self.start_transaction_at(Instant::now(), window, cx);
12667 update(self, window, cx);
12668 self.end_transaction_at(Instant::now(), cx)
12669 }
12670
12671 pub fn start_transaction_at(
12672 &mut self,
12673 now: Instant,
12674 window: &mut Window,
12675 cx: &mut Context<Self>,
12676 ) {
12677 self.end_selection(window, cx);
12678 if let Some(tx_id) = self
12679 .buffer
12680 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12681 {
12682 self.selection_history
12683 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12684 cx.emit(EditorEvent::TransactionBegun {
12685 transaction_id: tx_id,
12686 })
12687 }
12688 }
12689
12690 pub fn end_transaction_at(
12691 &mut self,
12692 now: Instant,
12693 cx: &mut Context<Self>,
12694 ) -> Option<TransactionId> {
12695 if let Some(transaction_id) = self
12696 .buffer
12697 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12698 {
12699 if let Some((_, end_selections)) =
12700 self.selection_history.transaction_mut(transaction_id)
12701 {
12702 *end_selections = Some(self.selections.disjoint_anchors());
12703 } else {
12704 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12705 }
12706
12707 cx.emit(EditorEvent::Edited { transaction_id });
12708 Some(transaction_id)
12709 } else {
12710 None
12711 }
12712 }
12713
12714 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12715 if self.selection_mark_mode {
12716 self.change_selections(None, window, cx, |s| {
12717 s.move_with(|_, sel| {
12718 sel.collapse_to(sel.head(), SelectionGoal::None);
12719 });
12720 })
12721 }
12722 self.selection_mark_mode = true;
12723 cx.notify();
12724 }
12725
12726 pub fn swap_selection_ends(
12727 &mut self,
12728 _: &actions::SwapSelectionEnds,
12729 window: &mut Window,
12730 cx: &mut Context<Self>,
12731 ) {
12732 self.change_selections(None, window, cx, |s| {
12733 s.move_with(|_, sel| {
12734 if sel.start != sel.end {
12735 sel.reversed = !sel.reversed
12736 }
12737 });
12738 });
12739 self.request_autoscroll(Autoscroll::newest(), cx);
12740 cx.notify();
12741 }
12742
12743 pub fn toggle_fold(
12744 &mut self,
12745 _: &actions::ToggleFold,
12746 window: &mut Window,
12747 cx: &mut Context<Self>,
12748 ) {
12749 if self.is_singleton(cx) {
12750 let selection = self.selections.newest::<Point>(cx);
12751
12752 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12753 let range = if selection.is_empty() {
12754 let point = selection.head().to_display_point(&display_map);
12755 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12756 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12757 .to_point(&display_map);
12758 start..end
12759 } else {
12760 selection.range()
12761 };
12762 if display_map.folds_in_range(range).next().is_some() {
12763 self.unfold_lines(&Default::default(), window, cx)
12764 } else {
12765 self.fold(&Default::default(), window, cx)
12766 }
12767 } else {
12768 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12769 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12770 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12771 .map(|(snapshot, _, _)| snapshot.remote_id())
12772 .collect();
12773
12774 for buffer_id in buffer_ids {
12775 if self.is_buffer_folded(buffer_id, cx) {
12776 self.unfold_buffer(buffer_id, cx);
12777 } else {
12778 self.fold_buffer(buffer_id, cx);
12779 }
12780 }
12781 }
12782 }
12783
12784 pub fn toggle_fold_recursive(
12785 &mut self,
12786 _: &actions::ToggleFoldRecursive,
12787 window: &mut Window,
12788 cx: &mut Context<Self>,
12789 ) {
12790 let selection = self.selections.newest::<Point>(cx);
12791
12792 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12793 let range = if selection.is_empty() {
12794 let point = selection.head().to_display_point(&display_map);
12795 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12796 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12797 .to_point(&display_map);
12798 start..end
12799 } else {
12800 selection.range()
12801 };
12802 if display_map.folds_in_range(range).next().is_some() {
12803 self.unfold_recursive(&Default::default(), window, cx)
12804 } else {
12805 self.fold_recursive(&Default::default(), window, cx)
12806 }
12807 }
12808
12809 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12810 if self.is_singleton(cx) {
12811 let mut to_fold = Vec::new();
12812 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12813 let selections = self.selections.all_adjusted(cx);
12814
12815 for selection in selections {
12816 let range = selection.range().sorted();
12817 let buffer_start_row = range.start.row;
12818
12819 if range.start.row != range.end.row {
12820 let mut found = false;
12821 let mut row = range.start.row;
12822 while row <= range.end.row {
12823 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12824 {
12825 found = true;
12826 row = crease.range().end.row + 1;
12827 to_fold.push(crease);
12828 } else {
12829 row += 1
12830 }
12831 }
12832 if found {
12833 continue;
12834 }
12835 }
12836
12837 for row in (0..=range.start.row).rev() {
12838 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12839 if crease.range().end.row >= buffer_start_row {
12840 to_fold.push(crease);
12841 if row <= range.start.row {
12842 break;
12843 }
12844 }
12845 }
12846 }
12847 }
12848
12849 self.fold_creases(to_fold, true, window, cx);
12850 } else {
12851 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12852
12853 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12854 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12855 .map(|(snapshot, _, _)| snapshot.remote_id())
12856 .collect();
12857 for buffer_id in buffer_ids {
12858 self.fold_buffer(buffer_id, cx);
12859 }
12860 }
12861 }
12862
12863 fn fold_at_level(
12864 &mut self,
12865 fold_at: &FoldAtLevel,
12866 window: &mut Window,
12867 cx: &mut Context<Self>,
12868 ) {
12869 if !self.buffer.read(cx).is_singleton() {
12870 return;
12871 }
12872
12873 let fold_at_level = fold_at.0;
12874 let snapshot = self.buffer.read(cx).snapshot(cx);
12875 let mut to_fold = Vec::new();
12876 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12877
12878 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12879 while start_row < end_row {
12880 match self
12881 .snapshot(window, cx)
12882 .crease_for_buffer_row(MultiBufferRow(start_row))
12883 {
12884 Some(crease) => {
12885 let nested_start_row = crease.range().start.row + 1;
12886 let nested_end_row = crease.range().end.row;
12887
12888 if current_level < fold_at_level {
12889 stack.push((nested_start_row, nested_end_row, current_level + 1));
12890 } else if current_level == fold_at_level {
12891 to_fold.push(crease);
12892 }
12893
12894 start_row = nested_end_row + 1;
12895 }
12896 None => start_row += 1,
12897 }
12898 }
12899 }
12900
12901 self.fold_creases(to_fold, true, window, cx);
12902 }
12903
12904 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12905 if self.buffer.read(cx).is_singleton() {
12906 let mut fold_ranges = Vec::new();
12907 let snapshot = self.buffer.read(cx).snapshot(cx);
12908
12909 for row in 0..snapshot.max_row().0 {
12910 if let Some(foldable_range) = self
12911 .snapshot(window, cx)
12912 .crease_for_buffer_row(MultiBufferRow(row))
12913 {
12914 fold_ranges.push(foldable_range);
12915 }
12916 }
12917
12918 self.fold_creases(fold_ranges, true, window, cx);
12919 } else {
12920 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12921 editor
12922 .update_in(&mut cx, |editor, _, cx| {
12923 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12924 editor.fold_buffer(buffer_id, cx);
12925 }
12926 })
12927 .ok();
12928 });
12929 }
12930 }
12931
12932 pub fn fold_function_bodies(
12933 &mut self,
12934 _: &actions::FoldFunctionBodies,
12935 window: &mut Window,
12936 cx: &mut Context<Self>,
12937 ) {
12938 let snapshot = self.buffer.read(cx).snapshot(cx);
12939
12940 let ranges = snapshot
12941 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12942 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12943 .collect::<Vec<_>>();
12944
12945 let creases = ranges
12946 .into_iter()
12947 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12948 .collect();
12949
12950 self.fold_creases(creases, true, window, cx);
12951 }
12952
12953 pub fn fold_recursive(
12954 &mut self,
12955 _: &actions::FoldRecursive,
12956 window: &mut Window,
12957 cx: &mut Context<Self>,
12958 ) {
12959 let mut to_fold = Vec::new();
12960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12961 let selections = self.selections.all_adjusted(cx);
12962
12963 for selection in selections {
12964 let range = selection.range().sorted();
12965 let buffer_start_row = range.start.row;
12966
12967 if range.start.row != range.end.row {
12968 let mut found = false;
12969 for row in range.start.row..=range.end.row {
12970 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12971 found = true;
12972 to_fold.push(crease);
12973 }
12974 }
12975 if found {
12976 continue;
12977 }
12978 }
12979
12980 for row in (0..=range.start.row).rev() {
12981 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12982 if crease.range().end.row >= buffer_start_row {
12983 to_fold.push(crease);
12984 } else {
12985 break;
12986 }
12987 }
12988 }
12989 }
12990
12991 self.fold_creases(to_fold, true, window, cx);
12992 }
12993
12994 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12995 let buffer_row = fold_at.buffer_row;
12996 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12997
12998 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12999 let autoscroll = self
13000 .selections
13001 .all::<Point>(cx)
13002 .iter()
13003 .any(|selection| crease.range().overlaps(&selection.range()));
13004
13005 self.fold_creases(vec![crease], autoscroll, window, cx);
13006 }
13007 }
13008
13009 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13010 if self.is_singleton(cx) {
13011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13012 let buffer = &display_map.buffer_snapshot;
13013 let selections = self.selections.all::<Point>(cx);
13014 let ranges = selections
13015 .iter()
13016 .map(|s| {
13017 let range = s.display_range(&display_map).sorted();
13018 let mut start = range.start.to_point(&display_map);
13019 let mut end = range.end.to_point(&display_map);
13020 start.column = 0;
13021 end.column = buffer.line_len(MultiBufferRow(end.row));
13022 start..end
13023 })
13024 .collect::<Vec<_>>();
13025
13026 self.unfold_ranges(&ranges, true, true, cx);
13027 } else {
13028 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13029 let buffer_ids: HashSet<_> = multi_buffer_snapshot
13030 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13031 .map(|(snapshot, _, _)| snapshot.remote_id())
13032 .collect();
13033 for buffer_id in buffer_ids {
13034 self.unfold_buffer(buffer_id, cx);
13035 }
13036 }
13037 }
13038
13039 pub fn unfold_recursive(
13040 &mut self,
13041 _: &UnfoldRecursive,
13042 _window: &mut Window,
13043 cx: &mut Context<Self>,
13044 ) {
13045 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13046 let selections = self.selections.all::<Point>(cx);
13047 let ranges = selections
13048 .iter()
13049 .map(|s| {
13050 let mut range = s.display_range(&display_map).sorted();
13051 *range.start.column_mut() = 0;
13052 *range.end.column_mut() = display_map.line_len(range.end.row());
13053 let start = range.start.to_point(&display_map);
13054 let end = range.end.to_point(&display_map);
13055 start..end
13056 })
13057 .collect::<Vec<_>>();
13058
13059 self.unfold_ranges(&ranges, true, true, cx);
13060 }
13061
13062 pub fn unfold_at(
13063 &mut self,
13064 unfold_at: &UnfoldAt,
13065 _window: &mut Window,
13066 cx: &mut Context<Self>,
13067 ) {
13068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13069
13070 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13071 ..Point::new(
13072 unfold_at.buffer_row.0,
13073 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13074 );
13075
13076 let autoscroll = self
13077 .selections
13078 .all::<Point>(cx)
13079 .iter()
13080 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13081
13082 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13083 }
13084
13085 pub fn unfold_all(
13086 &mut self,
13087 _: &actions::UnfoldAll,
13088 _window: &mut Window,
13089 cx: &mut Context<Self>,
13090 ) {
13091 if self.buffer.read(cx).is_singleton() {
13092 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13093 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13094 } else {
13095 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13096 editor
13097 .update(&mut cx, |editor, cx| {
13098 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13099 editor.unfold_buffer(buffer_id, cx);
13100 }
13101 })
13102 .ok();
13103 });
13104 }
13105 }
13106
13107 pub fn fold_selected_ranges(
13108 &mut self,
13109 _: &FoldSelectedRanges,
13110 window: &mut Window,
13111 cx: &mut Context<Self>,
13112 ) {
13113 let selections = self.selections.all::<Point>(cx);
13114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13115 let line_mode = self.selections.line_mode;
13116 let ranges = selections
13117 .into_iter()
13118 .map(|s| {
13119 if line_mode {
13120 let start = Point::new(s.start.row, 0);
13121 let end = Point::new(
13122 s.end.row,
13123 display_map
13124 .buffer_snapshot
13125 .line_len(MultiBufferRow(s.end.row)),
13126 );
13127 Crease::simple(start..end, display_map.fold_placeholder.clone())
13128 } else {
13129 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13130 }
13131 })
13132 .collect::<Vec<_>>();
13133 self.fold_creases(ranges, true, window, cx);
13134 }
13135
13136 pub fn fold_ranges<T: ToOffset + Clone>(
13137 &mut self,
13138 ranges: Vec<Range<T>>,
13139 auto_scroll: bool,
13140 window: &mut Window,
13141 cx: &mut Context<Self>,
13142 ) {
13143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13144 let ranges = ranges
13145 .into_iter()
13146 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13147 .collect::<Vec<_>>();
13148 self.fold_creases(ranges, auto_scroll, window, cx);
13149 }
13150
13151 pub fn fold_creases<T: ToOffset + Clone>(
13152 &mut self,
13153 creases: Vec<Crease<T>>,
13154 auto_scroll: bool,
13155 window: &mut Window,
13156 cx: &mut Context<Self>,
13157 ) {
13158 if creases.is_empty() {
13159 return;
13160 }
13161
13162 let mut buffers_affected = HashSet::default();
13163 let multi_buffer = self.buffer().read(cx);
13164 for crease in &creases {
13165 if let Some((_, buffer, _)) =
13166 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13167 {
13168 buffers_affected.insert(buffer.read(cx).remote_id());
13169 };
13170 }
13171
13172 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13173
13174 if auto_scroll {
13175 self.request_autoscroll(Autoscroll::fit(), cx);
13176 }
13177
13178 cx.notify();
13179
13180 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13181 // Clear diagnostics block when folding a range that contains it.
13182 let snapshot = self.snapshot(window, cx);
13183 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13184 drop(snapshot);
13185 self.active_diagnostics = Some(active_diagnostics);
13186 self.dismiss_diagnostics(cx);
13187 } else {
13188 self.active_diagnostics = Some(active_diagnostics);
13189 }
13190 }
13191
13192 self.scrollbar_marker_state.dirty = true;
13193 }
13194
13195 /// Removes any folds whose ranges intersect any of the given ranges.
13196 pub fn unfold_ranges<T: ToOffset + Clone>(
13197 &mut self,
13198 ranges: &[Range<T>],
13199 inclusive: bool,
13200 auto_scroll: bool,
13201 cx: &mut Context<Self>,
13202 ) {
13203 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13204 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13205 });
13206 }
13207
13208 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13209 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13210 return;
13211 }
13212 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13213 self.display_map
13214 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13215 cx.emit(EditorEvent::BufferFoldToggled {
13216 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13217 folded: true,
13218 });
13219 cx.notify();
13220 }
13221
13222 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13223 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13224 return;
13225 }
13226 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13227 self.display_map.update(cx, |display_map, cx| {
13228 display_map.unfold_buffer(buffer_id, cx);
13229 });
13230 cx.emit(EditorEvent::BufferFoldToggled {
13231 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13232 folded: false,
13233 });
13234 cx.notify();
13235 }
13236
13237 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13238 self.display_map.read(cx).is_buffer_folded(buffer)
13239 }
13240
13241 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13242 self.display_map.read(cx).folded_buffers()
13243 }
13244
13245 /// Removes any folds with the given ranges.
13246 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13247 &mut self,
13248 ranges: &[Range<T>],
13249 type_id: TypeId,
13250 auto_scroll: bool,
13251 cx: &mut Context<Self>,
13252 ) {
13253 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13254 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13255 });
13256 }
13257
13258 fn remove_folds_with<T: ToOffset + Clone>(
13259 &mut self,
13260 ranges: &[Range<T>],
13261 auto_scroll: bool,
13262 cx: &mut Context<Self>,
13263 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13264 ) {
13265 if ranges.is_empty() {
13266 return;
13267 }
13268
13269 let mut buffers_affected = HashSet::default();
13270 let multi_buffer = self.buffer().read(cx);
13271 for range in ranges {
13272 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13273 buffers_affected.insert(buffer.read(cx).remote_id());
13274 };
13275 }
13276
13277 self.display_map.update(cx, update);
13278
13279 if auto_scroll {
13280 self.request_autoscroll(Autoscroll::fit(), cx);
13281 }
13282
13283 cx.notify();
13284 self.scrollbar_marker_state.dirty = true;
13285 self.active_indent_guides_state.dirty = true;
13286 }
13287
13288 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13289 self.display_map.read(cx).fold_placeholder.clone()
13290 }
13291
13292 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13293 self.buffer.update(cx, |buffer, cx| {
13294 buffer.set_all_diff_hunks_expanded(cx);
13295 });
13296 }
13297
13298 pub fn expand_all_diff_hunks(
13299 &mut self,
13300 _: &ExpandAllDiffHunks,
13301 _window: &mut Window,
13302 cx: &mut Context<Self>,
13303 ) {
13304 self.buffer.update(cx, |buffer, cx| {
13305 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13306 });
13307 }
13308
13309 pub fn toggle_selected_diff_hunks(
13310 &mut self,
13311 _: &ToggleSelectedDiffHunks,
13312 _window: &mut Window,
13313 cx: &mut Context<Self>,
13314 ) {
13315 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13316 self.toggle_diff_hunks_in_ranges(ranges, cx);
13317 }
13318
13319 pub fn diff_hunks_in_ranges<'a>(
13320 &'a self,
13321 ranges: &'a [Range<Anchor>],
13322 buffer: &'a MultiBufferSnapshot,
13323 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13324 ranges.iter().flat_map(move |range| {
13325 let end_excerpt_id = range.end.excerpt_id;
13326 let range = range.to_point(buffer);
13327 let mut peek_end = range.end;
13328 if range.end.row < buffer.max_row().0 {
13329 peek_end = Point::new(range.end.row + 1, 0);
13330 }
13331 buffer
13332 .diff_hunks_in_range(range.start..peek_end)
13333 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13334 })
13335 }
13336
13337 pub fn has_stageable_diff_hunks_in_ranges(
13338 &self,
13339 ranges: &[Range<Anchor>],
13340 snapshot: &MultiBufferSnapshot,
13341 ) -> bool {
13342 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13343 hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13344 }
13345
13346 pub fn toggle_staged_selected_diff_hunks(
13347 &mut self,
13348 _: &::git::ToggleStaged,
13349 _window: &mut Window,
13350 cx: &mut Context<Self>,
13351 ) {
13352 let snapshot = self.buffer.read(cx).snapshot(cx);
13353 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13354 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13355 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13356 }
13357
13358 pub fn stage_and_next(
13359 &mut self,
13360 _: &::git::StageAndNext,
13361 window: &mut Window,
13362 cx: &mut Context<Self>,
13363 ) {
13364 self.do_stage_or_unstage_and_next(true, window, cx);
13365 }
13366
13367 pub fn unstage_and_next(
13368 &mut self,
13369 _: &::git::UnstageAndNext,
13370 window: &mut Window,
13371 cx: &mut Context<Self>,
13372 ) {
13373 self.do_stage_or_unstage_and_next(false, window, cx);
13374 }
13375
13376 pub fn stage_or_unstage_diff_hunks(
13377 &mut self,
13378 stage: bool,
13379 ranges: &[Range<Anchor>],
13380 cx: &mut Context<Self>,
13381 ) {
13382 let snapshot = self.buffer.read(cx).snapshot(cx);
13383 let Some(project) = &self.project else {
13384 return;
13385 };
13386
13387 let chunk_by = self
13388 .diff_hunks_in_ranges(&ranges, &snapshot)
13389 .chunk_by(|hunk| hunk.buffer_id);
13390 for (buffer_id, hunks) in &chunk_by {
13391 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13392 }
13393 }
13394
13395 fn do_stage_or_unstage_and_next(
13396 &mut self,
13397 stage: bool,
13398 window: &mut Window,
13399 cx: &mut Context<Self>,
13400 ) {
13401 let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13402 if ranges.iter().any(|range| range.start != range.end) {
13403 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13404 return;
13405 }
13406
13407 if !self.buffer().read(cx).is_singleton() {
13408 if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13409 if buffer.read(cx).is_empty() {
13410 let buffer = buffer.read(cx);
13411 let Some(file) = buffer.file() else {
13412 return;
13413 };
13414 let project_path = project::ProjectPath {
13415 worktree_id: file.worktree_id(cx),
13416 path: file.path().clone(),
13417 };
13418 let Some(project) = self.project.as_ref() else {
13419 return;
13420 };
13421 let project = project.read(cx);
13422
13423 let Some(repo) = project.git_store().read(cx).active_repository() else {
13424 return;
13425 };
13426
13427 repo.update(cx, |repo, cx| {
13428 let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13429 return;
13430 };
13431 let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13432 return;
13433 };
13434 if stage && status.status == FileStatus::Untracked {
13435 repo.stage_entries(vec![repo_path], cx)
13436 .detach_and_log_err(cx);
13437 return;
13438 }
13439 })
13440 }
13441 ranges = vec![multi_buffer::Anchor::range_in_buffer(
13442 excerpt_id,
13443 buffer.read(cx).remote_id(),
13444 range,
13445 )];
13446 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13447 let snapshot = self.buffer().read(cx).snapshot(cx);
13448 let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13449 if point.row < snapshot.max_row().0 {
13450 point.row += 1;
13451 point.column = 0;
13452 point = snapshot.clip_point(point, Bias::Right);
13453 self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13454 s.select_ranges([point..point]);
13455 })
13456 }
13457 return;
13458 }
13459 }
13460 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13461 self.go_to_next_hunk(&Default::default(), window, cx);
13462 }
13463
13464 fn do_stage_or_unstage(
13465 project: &Entity<Project>,
13466 stage: bool,
13467 buffer_id: BufferId,
13468 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13469 snapshot: &MultiBufferSnapshot,
13470 cx: &mut Context<Self>,
13471 ) {
13472 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13473 log::debug!("no buffer for id");
13474 return;
13475 };
13476 let buffer_snapshot = buffer.read(cx).snapshot();
13477 let Some((repo, path)) = project
13478 .read(cx)
13479 .repository_and_path_for_buffer_id(buffer_id, cx)
13480 else {
13481 log::debug!("no git repo for buffer id");
13482 return;
13483 };
13484 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13485 log::debug!("no diff for buffer id");
13486 return;
13487 };
13488
13489 let Some(new_index_text) = diff.new_secondary_text_for_stage_or_unstage(
13490 stage,
13491 hunks.filter_map(|hunk| {
13492 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13493 return None;
13494 } else if !stage
13495 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13496 {
13497 return None;
13498 }
13499 Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13500 }),
13501 &buffer_snapshot,
13502 cx,
13503 ) else {
13504 log::debug!("missing secondary diff or index text");
13505 return;
13506 };
13507 let new_index_text = if new_index_text.is_empty()
13508 && !stage
13509 && (diff.is_single_insertion
13510 || buffer_snapshot
13511 .file()
13512 .map_or(false, |file| file.disk_state() == DiskState::New))
13513 {
13514 log::debug!("removing from index");
13515 None
13516 } else {
13517 Some(new_index_text)
13518 };
13519 let buffer_store = project.read(cx).buffer_store().clone();
13520 buffer_store
13521 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13522 .detach_and_log_err(cx);
13523
13524 cx.background_spawn(
13525 repo.read(cx)
13526 .set_index_text(&path, new_index_text.map(|rope| rope.to_string()))
13527 .log_err(),
13528 )
13529 .detach();
13530 }
13531
13532 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13533 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13534 self.buffer
13535 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13536 }
13537
13538 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13539 self.buffer.update(cx, |buffer, cx| {
13540 let ranges = vec![Anchor::min()..Anchor::max()];
13541 if !buffer.all_diff_hunks_expanded()
13542 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13543 {
13544 buffer.collapse_diff_hunks(ranges, cx);
13545 true
13546 } else {
13547 false
13548 }
13549 })
13550 }
13551
13552 fn toggle_diff_hunks_in_ranges(
13553 &mut self,
13554 ranges: Vec<Range<Anchor>>,
13555 cx: &mut Context<'_, Editor>,
13556 ) {
13557 self.buffer.update(cx, |buffer, cx| {
13558 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13559 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13560 })
13561 }
13562
13563 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13564 self.buffer.update(cx, |buffer, cx| {
13565 let snapshot = buffer.snapshot(cx);
13566 let excerpt_id = range.end.excerpt_id;
13567 let point_range = range.to_point(&snapshot);
13568 let expand = !buffer.single_hunk_is_expanded(range, cx);
13569 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13570 })
13571 }
13572
13573 pub(crate) fn apply_all_diff_hunks(
13574 &mut self,
13575 _: &ApplyAllDiffHunks,
13576 window: &mut Window,
13577 cx: &mut Context<Self>,
13578 ) {
13579 let buffers = self.buffer.read(cx).all_buffers();
13580 for branch_buffer in buffers {
13581 branch_buffer.update(cx, |branch_buffer, cx| {
13582 branch_buffer.merge_into_base(Vec::new(), cx);
13583 });
13584 }
13585
13586 if let Some(project) = self.project.clone() {
13587 self.save(true, project, window, cx).detach_and_log_err(cx);
13588 }
13589 }
13590
13591 pub(crate) fn apply_selected_diff_hunks(
13592 &mut self,
13593 _: &ApplyDiffHunk,
13594 window: &mut Window,
13595 cx: &mut Context<Self>,
13596 ) {
13597 let snapshot = self.snapshot(window, cx);
13598 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13599 let mut ranges_by_buffer = HashMap::default();
13600 self.transact(window, cx, |editor, _window, cx| {
13601 for hunk in hunks {
13602 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13603 ranges_by_buffer
13604 .entry(buffer.clone())
13605 .or_insert_with(Vec::new)
13606 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13607 }
13608 }
13609
13610 for (buffer, ranges) in ranges_by_buffer {
13611 buffer.update(cx, |buffer, cx| {
13612 buffer.merge_into_base(ranges, cx);
13613 });
13614 }
13615 });
13616
13617 if let Some(project) = self.project.clone() {
13618 self.save(true, project, window, cx).detach_and_log_err(cx);
13619 }
13620 }
13621
13622 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13623 if hovered != self.gutter_hovered {
13624 self.gutter_hovered = hovered;
13625 cx.notify();
13626 }
13627 }
13628
13629 pub fn insert_blocks(
13630 &mut self,
13631 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13632 autoscroll: Option<Autoscroll>,
13633 cx: &mut Context<Self>,
13634 ) -> Vec<CustomBlockId> {
13635 let blocks = self
13636 .display_map
13637 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13638 if let Some(autoscroll) = autoscroll {
13639 self.request_autoscroll(autoscroll, cx);
13640 }
13641 cx.notify();
13642 blocks
13643 }
13644
13645 pub fn resize_blocks(
13646 &mut self,
13647 heights: HashMap<CustomBlockId, u32>,
13648 autoscroll: Option<Autoscroll>,
13649 cx: &mut Context<Self>,
13650 ) {
13651 self.display_map
13652 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13653 if let Some(autoscroll) = autoscroll {
13654 self.request_autoscroll(autoscroll, cx);
13655 }
13656 cx.notify();
13657 }
13658
13659 pub fn replace_blocks(
13660 &mut self,
13661 renderers: HashMap<CustomBlockId, RenderBlock>,
13662 autoscroll: Option<Autoscroll>,
13663 cx: &mut Context<Self>,
13664 ) {
13665 self.display_map
13666 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13667 if let Some(autoscroll) = autoscroll {
13668 self.request_autoscroll(autoscroll, cx);
13669 }
13670 cx.notify();
13671 }
13672
13673 pub fn remove_blocks(
13674 &mut self,
13675 block_ids: HashSet<CustomBlockId>,
13676 autoscroll: Option<Autoscroll>,
13677 cx: &mut Context<Self>,
13678 ) {
13679 self.display_map.update(cx, |display_map, cx| {
13680 display_map.remove_blocks(block_ids, cx)
13681 });
13682 if let Some(autoscroll) = autoscroll {
13683 self.request_autoscroll(autoscroll, cx);
13684 }
13685 cx.notify();
13686 }
13687
13688 pub fn row_for_block(
13689 &self,
13690 block_id: CustomBlockId,
13691 cx: &mut Context<Self>,
13692 ) -> Option<DisplayRow> {
13693 self.display_map
13694 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13695 }
13696
13697 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13698 self.focused_block = Some(focused_block);
13699 }
13700
13701 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13702 self.focused_block.take()
13703 }
13704
13705 pub fn insert_creases(
13706 &mut self,
13707 creases: impl IntoIterator<Item = Crease<Anchor>>,
13708 cx: &mut Context<Self>,
13709 ) -> Vec<CreaseId> {
13710 self.display_map
13711 .update(cx, |map, cx| map.insert_creases(creases, cx))
13712 }
13713
13714 pub fn remove_creases(
13715 &mut self,
13716 ids: impl IntoIterator<Item = CreaseId>,
13717 cx: &mut Context<Self>,
13718 ) {
13719 self.display_map
13720 .update(cx, |map, cx| map.remove_creases(ids, cx));
13721 }
13722
13723 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13724 self.display_map
13725 .update(cx, |map, cx| map.snapshot(cx))
13726 .longest_row()
13727 }
13728
13729 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13730 self.display_map
13731 .update(cx, |map, cx| map.snapshot(cx))
13732 .max_point()
13733 }
13734
13735 pub fn text(&self, cx: &App) -> String {
13736 self.buffer.read(cx).read(cx).text()
13737 }
13738
13739 pub fn is_empty(&self, cx: &App) -> bool {
13740 self.buffer.read(cx).read(cx).is_empty()
13741 }
13742
13743 pub fn text_option(&self, cx: &App) -> Option<String> {
13744 let text = self.text(cx);
13745 let text = text.trim();
13746
13747 if text.is_empty() {
13748 return None;
13749 }
13750
13751 Some(text.to_string())
13752 }
13753
13754 pub fn set_text(
13755 &mut self,
13756 text: impl Into<Arc<str>>,
13757 window: &mut Window,
13758 cx: &mut Context<Self>,
13759 ) {
13760 self.transact(window, cx, |this, _, cx| {
13761 this.buffer
13762 .read(cx)
13763 .as_singleton()
13764 .expect("you can only call set_text on editors for singleton buffers")
13765 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13766 });
13767 }
13768
13769 pub fn display_text(&self, cx: &mut App) -> String {
13770 self.display_map
13771 .update(cx, |map, cx| map.snapshot(cx))
13772 .text()
13773 }
13774
13775 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13776 let mut wrap_guides = smallvec::smallvec![];
13777
13778 if self.show_wrap_guides == Some(false) {
13779 return wrap_guides;
13780 }
13781
13782 let settings = self.buffer.read(cx).settings_at(0, cx);
13783 if settings.show_wrap_guides {
13784 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13785 wrap_guides.push((soft_wrap as usize, true));
13786 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13787 wrap_guides.push((soft_wrap as usize, true));
13788 }
13789 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13790 }
13791
13792 wrap_guides
13793 }
13794
13795 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13796 let settings = self.buffer.read(cx).settings_at(0, cx);
13797 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13798 match mode {
13799 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13800 SoftWrap::None
13801 }
13802 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13803 language_settings::SoftWrap::PreferredLineLength => {
13804 SoftWrap::Column(settings.preferred_line_length)
13805 }
13806 language_settings::SoftWrap::Bounded => {
13807 SoftWrap::Bounded(settings.preferred_line_length)
13808 }
13809 }
13810 }
13811
13812 pub fn set_soft_wrap_mode(
13813 &mut self,
13814 mode: language_settings::SoftWrap,
13815
13816 cx: &mut Context<Self>,
13817 ) {
13818 self.soft_wrap_mode_override = Some(mode);
13819 cx.notify();
13820 }
13821
13822 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13823 self.text_style_refinement = Some(style);
13824 }
13825
13826 /// called by the Element so we know what style we were most recently rendered with.
13827 pub(crate) fn set_style(
13828 &mut self,
13829 style: EditorStyle,
13830 window: &mut Window,
13831 cx: &mut Context<Self>,
13832 ) {
13833 let rem_size = window.rem_size();
13834 self.display_map.update(cx, |map, cx| {
13835 map.set_font(
13836 style.text.font(),
13837 style.text.font_size.to_pixels(rem_size),
13838 cx,
13839 )
13840 });
13841 self.style = Some(style);
13842 }
13843
13844 pub fn style(&self) -> Option<&EditorStyle> {
13845 self.style.as_ref()
13846 }
13847
13848 // Called by the element. This method is not designed to be called outside of the editor
13849 // element's layout code because it does not notify when rewrapping is computed synchronously.
13850 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13851 self.display_map
13852 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13853 }
13854
13855 pub fn set_soft_wrap(&mut self) {
13856 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13857 }
13858
13859 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13860 if self.soft_wrap_mode_override.is_some() {
13861 self.soft_wrap_mode_override.take();
13862 } else {
13863 let soft_wrap = match self.soft_wrap_mode(cx) {
13864 SoftWrap::GitDiff => return,
13865 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13866 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13867 language_settings::SoftWrap::None
13868 }
13869 };
13870 self.soft_wrap_mode_override = Some(soft_wrap);
13871 }
13872 cx.notify();
13873 }
13874
13875 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13876 let Some(workspace) = self.workspace() else {
13877 return;
13878 };
13879 let fs = workspace.read(cx).app_state().fs.clone();
13880 let current_show = TabBarSettings::get_global(cx).show;
13881 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13882 setting.show = Some(!current_show);
13883 });
13884 }
13885
13886 pub fn toggle_indent_guides(
13887 &mut self,
13888 _: &ToggleIndentGuides,
13889 _: &mut Window,
13890 cx: &mut Context<Self>,
13891 ) {
13892 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13893 self.buffer
13894 .read(cx)
13895 .settings_at(0, cx)
13896 .indent_guides
13897 .enabled
13898 });
13899 self.show_indent_guides = Some(!currently_enabled);
13900 cx.notify();
13901 }
13902
13903 fn should_show_indent_guides(&self) -> Option<bool> {
13904 self.show_indent_guides
13905 }
13906
13907 pub fn toggle_line_numbers(
13908 &mut self,
13909 _: &ToggleLineNumbers,
13910 _: &mut Window,
13911 cx: &mut Context<Self>,
13912 ) {
13913 let mut editor_settings = EditorSettings::get_global(cx).clone();
13914 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13915 EditorSettings::override_global(editor_settings, cx);
13916 }
13917
13918 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13919 self.use_relative_line_numbers
13920 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13921 }
13922
13923 pub fn toggle_relative_line_numbers(
13924 &mut self,
13925 _: &ToggleRelativeLineNumbers,
13926 _: &mut Window,
13927 cx: &mut Context<Self>,
13928 ) {
13929 let is_relative = self.should_use_relative_line_numbers(cx);
13930 self.set_relative_line_number(Some(!is_relative), cx)
13931 }
13932
13933 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13934 self.use_relative_line_numbers = is_relative;
13935 cx.notify();
13936 }
13937
13938 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13939 self.show_gutter = show_gutter;
13940 cx.notify();
13941 }
13942
13943 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13944 self.show_scrollbars = show_scrollbars;
13945 cx.notify();
13946 }
13947
13948 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13949 self.show_line_numbers = Some(show_line_numbers);
13950 cx.notify();
13951 }
13952
13953 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13954 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13955 cx.notify();
13956 }
13957
13958 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13959 self.show_code_actions = Some(show_code_actions);
13960 cx.notify();
13961 }
13962
13963 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13964 self.show_runnables = Some(show_runnables);
13965 cx.notify();
13966 }
13967
13968 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13969 if self.display_map.read(cx).masked != masked {
13970 self.display_map.update(cx, |map, _| map.masked = masked);
13971 }
13972 cx.notify()
13973 }
13974
13975 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13976 self.show_wrap_guides = Some(show_wrap_guides);
13977 cx.notify();
13978 }
13979
13980 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13981 self.show_indent_guides = Some(show_indent_guides);
13982 cx.notify();
13983 }
13984
13985 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13986 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13987 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13988 if let Some(dir) = file.abs_path(cx).parent() {
13989 return Some(dir.to_owned());
13990 }
13991 }
13992
13993 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13994 return Some(project_path.path.to_path_buf());
13995 }
13996 }
13997
13998 None
13999 }
14000
14001 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14002 self.active_excerpt(cx)?
14003 .1
14004 .read(cx)
14005 .file()
14006 .and_then(|f| f.as_local())
14007 }
14008
14009 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14010 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14011 let buffer = buffer.read(cx);
14012 if let Some(project_path) = buffer.project_path(cx) {
14013 let project = self.project.as_ref()?.read(cx);
14014 project.absolute_path(&project_path, cx)
14015 } else {
14016 buffer
14017 .file()
14018 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14019 }
14020 })
14021 }
14022
14023 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14024 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14025 let project_path = buffer.read(cx).project_path(cx)?;
14026 let project = self.project.as_ref()?.read(cx);
14027 let entry = project.entry_for_path(&project_path, cx)?;
14028 let path = entry.path.to_path_buf();
14029 Some(path)
14030 })
14031 }
14032
14033 pub fn reveal_in_finder(
14034 &mut self,
14035 _: &RevealInFileManager,
14036 _window: &mut Window,
14037 cx: &mut Context<Self>,
14038 ) {
14039 if let Some(target) = self.target_file(cx) {
14040 cx.reveal_path(&target.abs_path(cx));
14041 }
14042 }
14043
14044 pub fn copy_path(
14045 &mut self,
14046 _: &zed_actions::workspace::CopyPath,
14047 _window: &mut Window,
14048 cx: &mut Context<Self>,
14049 ) {
14050 if let Some(path) = self.target_file_abs_path(cx) {
14051 if let Some(path) = path.to_str() {
14052 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14053 }
14054 }
14055 }
14056
14057 pub fn copy_relative_path(
14058 &mut self,
14059 _: &zed_actions::workspace::CopyRelativePath,
14060 _window: &mut Window,
14061 cx: &mut Context<Self>,
14062 ) {
14063 if let Some(path) = self.target_file_path(cx) {
14064 if let Some(path) = path.to_str() {
14065 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14066 }
14067 }
14068 }
14069
14070 pub fn copy_file_name_without_extension(
14071 &mut self,
14072 _: &CopyFileNameWithoutExtension,
14073 _: &mut Window,
14074 cx: &mut Context<Self>,
14075 ) {
14076 if let Some(file) = self.target_file(cx) {
14077 if let Some(file_stem) = file.path().file_stem() {
14078 if let Some(name) = file_stem.to_str() {
14079 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14080 }
14081 }
14082 }
14083 }
14084
14085 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14086 if let Some(file) = self.target_file(cx) {
14087 if let Some(file_name) = file.path().file_name() {
14088 if let Some(name) = file_name.to_str() {
14089 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14090 }
14091 }
14092 }
14093 }
14094
14095 pub fn toggle_git_blame(
14096 &mut self,
14097 _: &ToggleGitBlame,
14098 window: &mut Window,
14099 cx: &mut Context<Self>,
14100 ) {
14101 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14102
14103 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14104 self.start_git_blame(true, window, cx);
14105 }
14106
14107 cx.notify();
14108 }
14109
14110 pub fn toggle_git_blame_inline(
14111 &mut self,
14112 _: &ToggleGitBlameInline,
14113 window: &mut Window,
14114 cx: &mut Context<Self>,
14115 ) {
14116 self.toggle_git_blame_inline_internal(true, window, cx);
14117 cx.notify();
14118 }
14119
14120 pub fn git_blame_inline_enabled(&self) -> bool {
14121 self.git_blame_inline_enabled
14122 }
14123
14124 pub fn toggle_selection_menu(
14125 &mut self,
14126 _: &ToggleSelectionMenu,
14127 _: &mut Window,
14128 cx: &mut Context<Self>,
14129 ) {
14130 self.show_selection_menu = self
14131 .show_selection_menu
14132 .map(|show_selections_menu| !show_selections_menu)
14133 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14134
14135 cx.notify();
14136 }
14137
14138 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14139 self.show_selection_menu
14140 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14141 }
14142
14143 fn start_git_blame(
14144 &mut self,
14145 user_triggered: bool,
14146 window: &mut Window,
14147 cx: &mut Context<Self>,
14148 ) {
14149 if let Some(project) = self.project.as_ref() {
14150 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14151 return;
14152 };
14153
14154 if buffer.read(cx).file().is_none() {
14155 return;
14156 }
14157
14158 let focused = self.focus_handle(cx).contains_focused(window, cx);
14159
14160 let project = project.clone();
14161 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14162 self.blame_subscription =
14163 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14164 self.blame = Some(blame);
14165 }
14166 }
14167
14168 fn toggle_git_blame_inline_internal(
14169 &mut self,
14170 user_triggered: bool,
14171 window: &mut Window,
14172 cx: &mut Context<Self>,
14173 ) {
14174 if self.git_blame_inline_enabled {
14175 self.git_blame_inline_enabled = false;
14176 self.show_git_blame_inline = false;
14177 self.show_git_blame_inline_delay_task.take();
14178 } else {
14179 self.git_blame_inline_enabled = true;
14180 self.start_git_blame_inline(user_triggered, window, cx);
14181 }
14182
14183 cx.notify();
14184 }
14185
14186 fn start_git_blame_inline(
14187 &mut self,
14188 user_triggered: bool,
14189 window: &mut Window,
14190 cx: &mut Context<Self>,
14191 ) {
14192 self.start_git_blame(user_triggered, window, cx);
14193
14194 if ProjectSettings::get_global(cx)
14195 .git
14196 .inline_blame_delay()
14197 .is_some()
14198 {
14199 self.start_inline_blame_timer(window, cx);
14200 } else {
14201 self.show_git_blame_inline = true
14202 }
14203 }
14204
14205 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14206 self.blame.as_ref()
14207 }
14208
14209 pub fn show_git_blame_gutter(&self) -> bool {
14210 self.show_git_blame_gutter
14211 }
14212
14213 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14214 self.show_git_blame_gutter && self.has_blame_entries(cx)
14215 }
14216
14217 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14218 self.show_git_blame_inline
14219 && (self.focus_handle.is_focused(window)
14220 || self
14221 .git_blame_inline_tooltip
14222 .as_ref()
14223 .and_then(|t| t.upgrade())
14224 .is_some())
14225 && !self.newest_selection_head_on_empty_line(cx)
14226 && self.has_blame_entries(cx)
14227 }
14228
14229 fn has_blame_entries(&self, cx: &App) -> bool {
14230 self.blame()
14231 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14232 }
14233
14234 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14235 let cursor_anchor = self.selections.newest_anchor().head();
14236
14237 let snapshot = self.buffer.read(cx).snapshot(cx);
14238 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14239
14240 snapshot.line_len(buffer_row) == 0
14241 }
14242
14243 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14244 let buffer_and_selection = maybe!({
14245 let selection = self.selections.newest::<Point>(cx);
14246 let selection_range = selection.range();
14247
14248 let multi_buffer = self.buffer().read(cx);
14249 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14250 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14251
14252 let (buffer, range, _) = if selection.reversed {
14253 buffer_ranges.first()
14254 } else {
14255 buffer_ranges.last()
14256 }?;
14257
14258 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14259 ..text::ToPoint::to_point(&range.end, &buffer).row;
14260 Some((
14261 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14262 selection,
14263 ))
14264 });
14265
14266 let Some((buffer, selection)) = buffer_and_selection else {
14267 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14268 };
14269
14270 let Some(project) = self.project.as_ref() else {
14271 return Task::ready(Err(anyhow!("editor does not have project")));
14272 };
14273
14274 project.update(cx, |project, cx| {
14275 project.get_permalink_to_line(&buffer, selection, cx)
14276 })
14277 }
14278
14279 pub fn copy_permalink_to_line(
14280 &mut self,
14281 _: &CopyPermalinkToLine,
14282 window: &mut Window,
14283 cx: &mut Context<Self>,
14284 ) {
14285 let permalink_task = self.get_permalink_to_line(cx);
14286 let workspace = self.workspace();
14287
14288 cx.spawn_in(window, |_, mut cx| async move {
14289 match permalink_task.await {
14290 Ok(permalink) => {
14291 cx.update(|_, cx| {
14292 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14293 })
14294 .ok();
14295 }
14296 Err(err) => {
14297 let message = format!("Failed to copy permalink: {err}");
14298
14299 Err::<(), anyhow::Error>(err).log_err();
14300
14301 if let Some(workspace) = workspace {
14302 workspace
14303 .update_in(&mut cx, |workspace, _, cx| {
14304 struct CopyPermalinkToLine;
14305
14306 workspace.show_toast(
14307 Toast::new(
14308 NotificationId::unique::<CopyPermalinkToLine>(),
14309 message,
14310 ),
14311 cx,
14312 )
14313 })
14314 .ok();
14315 }
14316 }
14317 }
14318 })
14319 .detach();
14320 }
14321
14322 pub fn copy_file_location(
14323 &mut self,
14324 _: &CopyFileLocation,
14325 _: &mut Window,
14326 cx: &mut Context<Self>,
14327 ) {
14328 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14329 if let Some(file) = self.target_file(cx) {
14330 if let Some(path) = file.path().to_str() {
14331 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14332 }
14333 }
14334 }
14335
14336 pub fn open_permalink_to_line(
14337 &mut self,
14338 _: &OpenPermalinkToLine,
14339 window: &mut Window,
14340 cx: &mut Context<Self>,
14341 ) {
14342 let permalink_task = self.get_permalink_to_line(cx);
14343 let workspace = self.workspace();
14344
14345 cx.spawn_in(window, |_, mut cx| async move {
14346 match permalink_task.await {
14347 Ok(permalink) => {
14348 cx.update(|_, cx| {
14349 cx.open_url(permalink.as_ref());
14350 })
14351 .ok();
14352 }
14353 Err(err) => {
14354 let message = format!("Failed to open permalink: {err}");
14355
14356 Err::<(), anyhow::Error>(err).log_err();
14357
14358 if let Some(workspace) = workspace {
14359 workspace
14360 .update(&mut cx, |workspace, cx| {
14361 struct OpenPermalinkToLine;
14362
14363 workspace.show_toast(
14364 Toast::new(
14365 NotificationId::unique::<OpenPermalinkToLine>(),
14366 message,
14367 ),
14368 cx,
14369 )
14370 })
14371 .ok();
14372 }
14373 }
14374 }
14375 })
14376 .detach();
14377 }
14378
14379 pub fn insert_uuid_v4(
14380 &mut self,
14381 _: &InsertUuidV4,
14382 window: &mut Window,
14383 cx: &mut Context<Self>,
14384 ) {
14385 self.insert_uuid(UuidVersion::V4, window, cx);
14386 }
14387
14388 pub fn insert_uuid_v7(
14389 &mut self,
14390 _: &InsertUuidV7,
14391 window: &mut Window,
14392 cx: &mut Context<Self>,
14393 ) {
14394 self.insert_uuid(UuidVersion::V7, window, cx);
14395 }
14396
14397 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14398 self.transact(window, cx, |this, window, cx| {
14399 let edits = this
14400 .selections
14401 .all::<Point>(cx)
14402 .into_iter()
14403 .map(|selection| {
14404 let uuid = match version {
14405 UuidVersion::V4 => uuid::Uuid::new_v4(),
14406 UuidVersion::V7 => uuid::Uuid::now_v7(),
14407 };
14408
14409 (selection.range(), uuid.to_string())
14410 });
14411 this.edit(edits, cx);
14412 this.refresh_inline_completion(true, false, window, cx);
14413 });
14414 }
14415
14416 pub fn open_selections_in_multibuffer(
14417 &mut self,
14418 _: &OpenSelectionsInMultibuffer,
14419 window: &mut Window,
14420 cx: &mut Context<Self>,
14421 ) {
14422 let multibuffer = self.buffer.read(cx);
14423
14424 let Some(buffer) = multibuffer.as_singleton() else {
14425 return;
14426 };
14427
14428 let Some(workspace) = self.workspace() else {
14429 return;
14430 };
14431
14432 let locations = self
14433 .selections
14434 .disjoint_anchors()
14435 .iter()
14436 .map(|range| Location {
14437 buffer: buffer.clone(),
14438 range: range.start.text_anchor..range.end.text_anchor,
14439 })
14440 .collect::<Vec<_>>();
14441
14442 let title = multibuffer.title(cx).to_string();
14443
14444 cx.spawn_in(window, |_, mut cx| async move {
14445 workspace.update_in(&mut cx, |workspace, window, cx| {
14446 Self::open_locations_in_multibuffer(
14447 workspace,
14448 locations,
14449 format!("Selections for '{title}'"),
14450 false,
14451 MultibufferSelectionMode::All,
14452 window,
14453 cx,
14454 );
14455 })
14456 })
14457 .detach();
14458 }
14459
14460 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14461 /// last highlight added will be used.
14462 ///
14463 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14464 pub fn highlight_rows<T: 'static>(
14465 &mut self,
14466 range: Range<Anchor>,
14467 color: Hsla,
14468 should_autoscroll: bool,
14469 cx: &mut Context<Self>,
14470 ) {
14471 let snapshot = self.buffer().read(cx).snapshot(cx);
14472 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14473 let ix = row_highlights.binary_search_by(|highlight| {
14474 Ordering::Equal
14475 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14476 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14477 });
14478
14479 if let Err(mut ix) = ix {
14480 let index = post_inc(&mut self.highlight_order);
14481
14482 // If this range intersects with the preceding highlight, then merge it with
14483 // the preceding highlight. Otherwise insert a new highlight.
14484 let mut merged = false;
14485 if ix > 0 {
14486 let prev_highlight = &mut row_highlights[ix - 1];
14487 if prev_highlight
14488 .range
14489 .end
14490 .cmp(&range.start, &snapshot)
14491 .is_ge()
14492 {
14493 ix -= 1;
14494 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14495 prev_highlight.range.end = range.end;
14496 }
14497 merged = true;
14498 prev_highlight.index = index;
14499 prev_highlight.color = color;
14500 prev_highlight.should_autoscroll = should_autoscroll;
14501 }
14502 }
14503
14504 if !merged {
14505 row_highlights.insert(
14506 ix,
14507 RowHighlight {
14508 range: range.clone(),
14509 index,
14510 color,
14511 should_autoscroll,
14512 },
14513 );
14514 }
14515
14516 // If any of the following highlights intersect with this one, merge them.
14517 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14518 let highlight = &row_highlights[ix];
14519 if next_highlight
14520 .range
14521 .start
14522 .cmp(&highlight.range.end, &snapshot)
14523 .is_le()
14524 {
14525 if next_highlight
14526 .range
14527 .end
14528 .cmp(&highlight.range.end, &snapshot)
14529 .is_gt()
14530 {
14531 row_highlights[ix].range.end = next_highlight.range.end;
14532 }
14533 row_highlights.remove(ix + 1);
14534 } else {
14535 break;
14536 }
14537 }
14538 }
14539 }
14540
14541 /// Remove any highlighted row ranges of the given type that intersect the
14542 /// given ranges.
14543 pub fn remove_highlighted_rows<T: 'static>(
14544 &mut self,
14545 ranges_to_remove: Vec<Range<Anchor>>,
14546 cx: &mut Context<Self>,
14547 ) {
14548 let snapshot = self.buffer().read(cx).snapshot(cx);
14549 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14550 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14551 row_highlights.retain(|highlight| {
14552 while let Some(range_to_remove) = ranges_to_remove.peek() {
14553 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14554 Ordering::Less | Ordering::Equal => {
14555 ranges_to_remove.next();
14556 }
14557 Ordering::Greater => {
14558 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14559 Ordering::Less | Ordering::Equal => {
14560 return false;
14561 }
14562 Ordering::Greater => break,
14563 }
14564 }
14565 }
14566 }
14567
14568 true
14569 })
14570 }
14571
14572 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14573 pub fn clear_row_highlights<T: 'static>(&mut self) {
14574 self.highlighted_rows.remove(&TypeId::of::<T>());
14575 }
14576
14577 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14578 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14579 self.highlighted_rows
14580 .get(&TypeId::of::<T>())
14581 .map_or(&[] as &[_], |vec| vec.as_slice())
14582 .iter()
14583 .map(|highlight| (highlight.range.clone(), highlight.color))
14584 }
14585
14586 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14587 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14588 /// Allows to ignore certain kinds of highlights.
14589 pub fn highlighted_display_rows(
14590 &self,
14591 window: &mut Window,
14592 cx: &mut App,
14593 ) -> BTreeMap<DisplayRow, Background> {
14594 let snapshot = self.snapshot(window, cx);
14595 let mut used_highlight_orders = HashMap::default();
14596 self.highlighted_rows
14597 .iter()
14598 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14599 .fold(
14600 BTreeMap::<DisplayRow, Background>::new(),
14601 |mut unique_rows, highlight| {
14602 let start = highlight.range.start.to_display_point(&snapshot);
14603 let end = highlight.range.end.to_display_point(&snapshot);
14604 let start_row = start.row().0;
14605 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14606 && end.column() == 0
14607 {
14608 end.row().0.saturating_sub(1)
14609 } else {
14610 end.row().0
14611 };
14612 for row in start_row..=end_row {
14613 let used_index =
14614 used_highlight_orders.entry(row).or_insert(highlight.index);
14615 if highlight.index >= *used_index {
14616 *used_index = highlight.index;
14617 unique_rows.insert(DisplayRow(row), highlight.color.into());
14618 }
14619 }
14620 unique_rows
14621 },
14622 )
14623 }
14624
14625 pub fn highlighted_display_row_for_autoscroll(
14626 &self,
14627 snapshot: &DisplaySnapshot,
14628 ) -> Option<DisplayRow> {
14629 self.highlighted_rows
14630 .values()
14631 .flat_map(|highlighted_rows| highlighted_rows.iter())
14632 .filter_map(|highlight| {
14633 if highlight.should_autoscroll {
14634 Some(highlight.range.start.to_display_point(snapshot).row())
14635 } else {
14636 None
14637 }
14638 })
14639 .min()
14640 }
14641
14642 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14643 self.highlight_background::<SearchWithinRange>(
14644 ranges,
14645 |colors| colors.editor_document_highlight_read_background,
14646 cx,
14647 )
14648 }
14649
14650 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14651 self.breadcrumb_header = Some(new_header);
14652 }
14653
14654 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14655 self.clear_background_highlights::<SearchWithinRange>(cx);
14656 }
14657
14658 pub fn highlight_background<T: 'static>(
14659 &mut self,
14660 ranges: &[Range<Anchor>],
14661 color_fetcher: fn(&ThemeColors) -> Hsla,
14662 cx: &mut Context<Self>,
14663 ) {
14664 self.background_highlights
14665 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14666 self.scrollbar_marker_state.dirty = true;
14667 cx.notify();
14668 }
14669
14670 pub fn clear_background_highlights<T: 'static>(
14671 &mut self,
14672 cx: &mut Context<Self>,
14673 ) -> Option<BackgroundHighlight> {
14674 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14675 if !text_highlights.1.is_empty() {
14676 self.scrollbar_marker_state.dirty = true;
14677 cx.notify();
14678 }
14679 Some(text_highlights)
14680 }
14681
14682 pub fn highlight_gutter<T: 'static>(
14683 &mut self,
14684 ranges: &[Range<Anchor>],
14685 color_fetcher: fn(&App) -> Hsla,
14686 cx: &mut Context<Self>,
14687 ) {
14688 self.gutter_highlights
14689 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14690 cx.notify();
14691 }
14692
14693 pub fn clear_gutter_highlights<T: 'static>(
14694 &mut self,
14695 cx: &mut Context<Self>,
14696 ) -> Option<GutterHighlight> {
14697 cx.notify();
14698 self.gutter_highlights.remove(&TypeId::of::<T>())
14699 }
14700
14701 #[cfg(feature = "test-support")]
14702 pub fn all_text_background_highlights(
14703 &self,
14704 window: &mut Window,
14705 cx: &mut Context<Self>,
14706 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14707 let snapshot = self.snapshot(window, cx);
14708 let buffer = &snapshot.buffer_snapshot;
14709 let start = buffer.anchor_before(0);
14710 let end = buffer.anchor_after(buffer.len());
14711 let theme = cx.theme().colors();
14712 self.background_highlights_in_range(start..end, &snapshot, theme)
14713 }
14714
14715 #[cfg(feature = "test-support")]
14716 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14717 let snapshot = self.buffer().read(cx).snapshot(cx);
14718
14719 let highlights = self
14720 .background_highlights
14721 .get(&TypeId::of::<items::BufferSearchHighlights>());
14722
14723 if let Some((_color, ranges)) = highlights {
14724 ranges
14725 .iter()
14726 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14727 .collect_vec()
14728 } else {
14729 vec![]
14730 }
14731 }
14732
14733 fn document_highlights_for_position<'a>(
14734 &'a self,
14735 position: Anchor,
14736 buffer: &'a MultiBufferSnapshot,
14737 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14738 let read_highlights = self
14739 .background_highlights
14740 .get(&TypeId::of::<DocumentHighlightRead>())
14741 .map(|h| &h.1);
14742 let write_highlights = self
14743 .background_highlights
14744 .get(&TypeId::of::<DocumentHighlightWrite>())
14745 .map(|h| &h.1);
14746 let left_position = position.bias_left(buffer);
14747 let right_position = position.bias_right(buffer);
14748 read_highlights
14749 .into_iter()
14750 .chain(write_highlights)
14751 .flat_map(move |ranges| {
14752 let start_ix = match ranges.binary_search_by(|probe| {
14753 let cmp = probe.end.cmp(&left_position, buffer);
14754 if cmp.is_ge() {
14755 Ordering::Greater
14756 } else {
14757 Ordering::Less
14758 }
14759 }) {
14760 Ok(i) | Err(i) => i,
14761 };
14762
14763 ranges[start_ix..]
14764 .iter()
14765 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14766 })
14767 }
14768
14769 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14770 self.background_highlights
14771 .get(&TypeId::of::<T>())
14772 .map_or(false, |(_, highlights)| !highlights.is_empty())
14773 }
14774
14775 pub fn background_highlights_in_range(
14776 &self,
14777 search_range: Range<Anchor>,
14778 display_snapshot: &DisplaySnapshot,
14779 theme: &ThemeColors,
14780 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14781 let mut results = Vec::new();
14782 for (color_fetcher, ranges) in self.background_highlights.values() {
14783 let color = color_fetcher(theme);
14784 let start_ix = match ranges.binary_search_by(|probe| {
14785 let cmp = probe
14786 .end
14787 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14788 if cmp.is_gt() {
14789 Ordering::Greater
14790 } else {
14791 Ordering::Less
14792 }
14793 }) {
14794 Ok(i) | Err(i) => i,
14795 };
14796 for range in &ranges[start_ix..] {
14797 if range
14798 .start
14799 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14800 .is_ge()
14801 {
14802 break;
14803 }
14804
14805 let start = range.start.to_display_point(display_snapshot);
14806 let end = range.end.to_display_point(display_snapshot);
14807 results.push((start..end, color))
14808 }
14809 }
14810 results
14811 }
14812
14813 pub fn background_highlight_row_ranges<T: 'static>(
14814 &self,
14815 search_range: Range<Anchor>,
14816 display_snapshot: &DisplaySnapshot,
14817 count: usize,
14818 ) -> Vec<RangeInclusive<DisplayPoint>> {
14819 let mut results = Vec::new();
14820 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14821 return vec![];
14822 };
14823
14824 let start_ix = match ranges.binary_search_by(|probe| {
14825 let cmp = probe
14826 .end
14827 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14828 if cmp.is_gt() {
14829 Ordering::Greater
14830 } else {
14831 Ordering::Less
14832 }
14833 }) {
14834 Ok(i) | Err(i) => i,
14835 };
14836 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14837 if let (Some(start_display), Some(end_display)) = (start, end) {
14838 results.push(
14839 start_display.to_display_point(display_snapshot)
14840 ..=end_display.to_display_point(display_snapshot),
14841 );
14842 }
14843 };
14844 let mut start_row: Option<Point> = None;
14845 let mut end_row: Option<Point> = None;
14846 if ranges.len() > count {
14847 return Vec::new();
14848 }
14849 for range in &ranges[start_ix..] {
14850 if range
14851 .start
14852 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14853 .is_ge()
14854 {
14855 break;
14856 }
14857 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14858 if let Some(current_row) = &end_row {
14859 if end.row == current_row.row {
14860 continue;
14861 }
14862 }
14863 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14864 if start_row.is_none() {
14865 assert_eq!(end_row, None);
14866 start_row = Some(start);
14867 end_row = Some(end);
14868 continue;
14869 }
14870 if let Some(current_end) = end_row.as_mut() {
14871 if start.row > current_end.row + 1 {
14872 push_region(start_row, end_row);
14873 start_row = Some(start);
14874 end_row = Some(end);
14875 } else {
14876 // Merge two hunks.
14877 *current_end = end;
14878 }
14879 } else {
14880 unreachable!();
14881 }
14882 }
14883 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14884 push_region(start_row, end_row);
14885 results
14886 }
14887
14888 pub fn gutter_highlights_in_range(
14889 &self,
14890 search_range: Range<Anchor>,
14891 display_snapshot: &DisplaySnapshot,
14892 cx: &App,
14893 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14894 let mut results = Vec::new();
14895 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14896 let color = color_fetcher(cx);
14897 let start_ix = match ranges.binary_search_by(|probe| {
14898 let cmp = probe
14899 .end
14900 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14901 if cmp.is_gt() {
14902 Ordering::Greater
14903 } else {
14904 Ordering::Less
14905 }
14906 }) {
14907 Ok(i) | Err(i) => i,
14908 };
14909 for range in &ranges[start_ix..] {
14910 if range
14911 .start
14912 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14913 .is_ge()
14914 {
14915 break;
14916 }
14917
14918 let start = range.start.to_display_point(display_snapshot);
14919 let end = range.end.to_display_point(display_snapshot);
14920 results.push((start..end, color))
14921 }
14922 }
14923 results
14924 }
14925
14926 /// Get the text ranges corresponding to the redaction query
14927 pub fn redacted_ranges(
14928 &self,
14929 search_range: Range<Anchor>,
14930 display_snapshot: &DisplaySnapshot,
14931 cx: &App,
14932 ) -> Vec<Range<DisplayPoint>> {
14933 display_snapshot
14934 .buffer_snapshot
14935 .redacted_ranges(search_range, |file| {
14936 if let Some(file) = file {
14937 file.is_private()
14938 && EditorSettings::get(
14939 Some(SettingsLocation {
14940 worktree_id: file.worktree_id(cx),
14941 path: file.path().as_ref(),
14942 }),
14943 cx,
14944 )
14945 .redact_private_values
14946 } else {
14947 false
14948 }
14949 })
14950 .map(|range| {
14951 range.start.to_display_point(display_snapshot)
14952 ..range.end.to_display_point(display_snapshot)
14953 })
14954 .collect()
14955 }
14956
14957 pub fn highlight_text<T: 'static>(
14958 &mut self,
14959 ranges: Vec<Range<Anchor>>,
14960 style: HighlightStyle,
14961 cx: &mut Context<Self>,
14962 ) {
14963 self.display_map.update(cx, |map, _| {
14964 map.highlight_text(TypeId::of::<T>(), ranges, style)
14965 });
14966 cx.notify();
14967 }
14968
14969 pub(crate) fn highlight_inlays<T: 'static>(
14970 &mut self,
14971 highlights: Vec<InlayHighlight>,
14972 style: HighlightStyle,
14973 cx: &mut Context<Self>,
14974 ) {
14975 self.display_map.update(cx, |map, _| {
14976 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14977 });
14978 cx.notify();
14979 }
14980
14981 pub fn text_highlights<'a, T: 'static>(
14982 &'a self,
14983 cx: &'a App,
14984 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14985 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14986 }
14987
14988 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14989 let cleared = self
14990 .display_map
14991 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14992 if cleared {
14993 cx.notify();
14994 }
14995 }
14996
14997 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14998 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14999 && self.focus_handle.is_focused(window)
15000 }
15001
15002 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15003 self.show_cursor_when_unfocused = is_enabled;
15004 cx.notify();
15005 }
15006
15007 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15008 cx.notify();
15009 }
15010
15011 fn on_buffer_event(
15012 &mut self,
15013 multibuffer: &Entity<MultiBuffer>,
15014 event: &multi_buffer::Event,
15015 window: &mut Window,
15016 cx: &mut Context<Self>,
15017 ) {
15018 match event {
15019 multi_buffer::Event::Edited {
15020 singleton_buffer_edited,
15021 edited_buffer: buffer_edited,
15022 } => {
15023 self.scrollbar_marker_state.dirty = true;
15024 self.active_indent_guides_state.dirty = true;
15025 self.refresh_active_diagnostics(cx);
15026 self.refresh_code_actions(window, cx);
15027 if self.has_active_inline_completion() {
15028 self.update_visible_inline_completion(window, cx);
15029 }
15030 if let Some(buffer) = buffer_edited {
15031 let buffer_id = buffer.read(cx).remote_id();
15032 if !self.registered_buffers.contains_key(&buffer_id) {
15033 if let Some(project) = self.project.as_ref() {
15034 project.update(cx, |project, cx| {
15035 self.registered_buffers.insert(
15036 buffer_id,
15037 project.register_buffer_with_language_servers(&buffer, cx),
15038 );
15039 })
15040 }
15041 }
15042 }
15043 cx.emit(EditorEvent::BufferEdited);
15044 cx.emit(SearchEvent::MatchesInvalidated);
15045 if *singleton_buffer_edited {
15046 if let Some(project) = &self.project {
15047 #[allow(clippy::mutable_key_type)]
15048 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15049 multibuffer
15050 .all_buffers()
15051 .into_iter()
15052 .filter_map(|buffer| {
15053 buffer.update(cx, |buffer, cx| {
15054 let language = buffer.language()?;
15055 let should_discard = project.update(cx, |project, cx| {
15056 project.is_local()
15057 && !project.has_language_servers_for(buffer, cx)
15058 });
15059 should_discard.not().then_some(language.clone())
15060 })
15061 })
15062 .collect::<HashSet<_>>()
15063 });
15064 if !languages_affected.is_empty() {
15065 self.refresh_inlay_hints(
15066 InlayHintRefreshReason::BufferEdited(languages_affected),
15067 cx,
15068 );
15069 }
15070 }
15071 }
15072
15073 let Some(project) = &self.project else { return };
15074 let (telemetry, is_via_ssh) = {
15075 let project = project.read(cx);
15076 let telemetry = project.client().telemetry().clone();
15077 let is_via_ssh = project.is_via_ssh();
15078 (telemetry, is_via_ssh)
15079 };
15080 refresh_linked_ranges(self, window, cx);
15081 telemetry.log_edit_event("editor", is_via_ssh);
15082 }
15083 multi_buffer::Event::ExcerptsAdded {
15084 buffer,
15085 predecessor,
15086 excerpts,
15087 } => {
15088 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15089 let buffer_id = buffer.read(cx).remote_id();
15090 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15091 if let Some(project) = &self.project {
15092 get_uncommitted_diff_for_buffer(
15093 project,
15094 [buffer.clone()],
15095 self.buffer.clone(),
15096 cx,
15097 )
15098 .detach();
15099 }
15100 }
15101 cx.emit(EditorEvent::ExcerptsAdded {
15102 buffer: buffer.clone(),
15103 predecessor: *predecessor,
15104 excerpts: excerpts.clone(),
15105 });
15106 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15107 }
15108 multi_buffer::Event::ExcerptsRemoved { ids } => {
15109 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15110 let buffer = self.buffer.read(cx);
15111 self.registered_buffers
15112 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15113 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15114 }
15115 multi_buffer::Event::ExcerptsEdited { ids } => {
15116 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15117 }
15118 multi_buffer::Event::ExcerptsExpanded { ids } => {
15119 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15120 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15121 }
15122 multi_buffer::Event::Reparsed(buffer_id) => {
15123 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15124
15125 cx.emit(EditorEvent::Reparsed(*buffer_id));
15126 }
15127 multi_buffer::Event::DiffHunksToggled => {
15128 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15129 }
15130 multi_buffer::Event::LanguageChanged(buffer_id) => {
15131 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15132 cx.emit(EditorEvent::Reparsed(*buffer_id));
15133 cx.notify();
15134 }
15135 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15136 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15137 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15138 cx.emit(EditorEvent::TitleChanged)
15139 }
15140 // multi_buffer::Event::DiffBaseChanged => {
15141 // self.scrollbar_marker_state.dirty = true;
15142 // cx.emit(EditorEvent::DiffBaseChanged);
15143 // cx.notify();
15144 // }
15145 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15146 multi_buffer::Event::DiagnosticsUpdated => {
15147 self.refresh_active_diagnostics(cx);
15148 self.refresh_inline_diagnostics(true, window, cx);
15149 self.scrollbar_marker_state.dirty = true;
15150 cx.notify();
15151 }
15152 _ => {}
15153 };
15154 }
15155
15156 fn on_display_map_changed(
15157 &mut self,
15158 _: Entity<DisplayMap>,
15159 _: &mut Window,
15160 cx: &mut Context<Self>,
15161 ) {
15162 cx.notify();
15163 }
15164
15165 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15166 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15167 self.update_edit_prediction_settings(cx);
15168 self.refresh_inline_completion(true, false, window, cx);
15169 self.refresh_inlay_hints(
15170 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15171 self.selections.newest_anchor().head(),
15172 &self.buffer.read(cx).snapshot(cx),
15173 cx,
15174 )),
15175 cx,
15176 );
15177
15178 let old_cursor_shape = self.cursor_shape;
15179
15180 {
15181 let editor_settings = EditorSettings::get_global(cx);
15182 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15183 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15184 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15185 }
15186
15187 if old_cursor_shape != self.cursor_shape {
15188 cx.emit(EditorEvent::CursorShapeChanged);
15189 }
15190
15191 let project_settings = ProjectSettings::get_global(cx);
15192 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15193
15194 if self.mode == EditorMode::Full {
15195 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15196 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15197 if self.show_inline_diagnostics != show_inline_diagnostics {
15198 self.show_inline_diagnostics = show_inline_diagnostics;
15199 self.refresh_inline_diagnostics(false, window, cx);
15200 }
15201
15202 if self.git_blame_inline_enabled != inline_blame_enabled {
15203 self.toggle_git_blame_inline_internal(false, window, cx);
15204 }
15205 }
15206
15207 cx.notify();
15208 }
15209
15210 pub fn set_searchable(&mut self, searchable: bool) {
15211 self.searchable = searchable;
15212 }
15213
15214 pub fn searchable(&self) -> bool {
15215 self.searchable
15216 }
15217
15218 fn open_proposed_changes_editor(
15219 &mut self,
15220 _: &OpenProposedChangesEditor,
15221 window: &mut Window,
15222 cx: &mut Context<Self>,
15223 ) {
15224 let Some(workspace) = self.workspace() else {
15225 cx.propagate();
15226 return;
15227 };
15228
15229 let selections = self.selections.all::<usize>(cx);
15230 let multi_buffer = self.buffer.read(cx);
15231 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15232 let mut new_selections_by_buffer = HashMap::default();
15233 for selection in selections {
15234 for (buffer, range, _) in
15235 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15236 {
15237 let mut range = range.to_point(buffer);
15238 range.start.column = 0;
15239 range.end.column = buffer.line_len(range.end.row);
15240 new_selections_by_buffer
15241 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15242 .or_insert(Vec::new())
15243 .push(range)
15244 }
15245 }
15246
15247 let proposed_changes_buffers = new_selections_by_buffer
15248 .into_iter()
15249 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15250 .collect::<Vec<_>>();
15251 let proposed_changes_editor = cx.new(|cx| {
15252 ProposedChangesEditor::new(
15253 "Proposed changes",
15254 proposed_changes_buffers,
15255 self.project.clone(),
15256 window,
15257 cx,
15258 )
15259 });
15260
15261 window.defer(cx, move |window, cx| {
15262 workspace.update(cx, |workspace, cx| {
15263 workspace.active_pane().update(cx, |pane, cx| {
15264 pane.add_item(
15265 Box::new(proposed_changes_editor),
15266 true,
15267 true,
15268 None,
15269 window,
15270 cx,
15271 );
15272 });
15273 });
15274 });
15275 }
15276
15277 pub fn open_excerpts_in_split(
15278 &mut self,
15279 _: &OpenExcerptsSplit,
15280 window: &mut Window,
15281 cx: &mut Context<Self>,
15282 ) {
15283 self.open_excerpts_common(None, true, window, cx)
15284 }
15285
15286 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15287 self.open_excerpts_common(None, false, window, cx)
15288 }
15289
15290 fn open_excerpts_common(
15291 &mut self,
15292 jump_data: Option<JumpData>,
15293 split: bool,
15294 window: &mut Window,
15295 cx: &mut Context<Self>,
15296 ) {
15297 let Some(workspace) = self.workspace() else {
15298 cx.propagate();
15299 return;
15300 };
15301
15302 if self.buffer.read(cx).is_singleton() {
15303 cx.propagate();
15304 return;
15305 }
15306
15307 let mut new_selections_by_buffer = HashMap::default();
15308 match &jump_data {
15309 Some(JumpData::MultiBufferPoint {
15310 excerpt_id,
15311 position,
15312 anchor,
15313 line_offset_from_top,
15314 }) => {
15315 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15316 if let Some(buffer) = multi_buffer_snapshot
15317 .buffer_id_for_excerpt(*excerpt_id)
15318 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15319 {
15320 let buffer_snapshot = buffer.read(cx).snapshot();
15321 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15322 language::ToPoint::to_point(anchor, &buffer_snapshot)
15323 } else {
15324 buffer_snapshot.clip_point(*position, Bias::Left)
15325 };
15326 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15327 new_selections_by_buffer.insert(
15328 buffer,
15329 (
15330 vec![jump_to_offset..jump_to_offset],
15331 Some(*line_offset_from_top),
15332 ),
15333 );
15334 }
15335 }
15336 Some(JumpData::MultiBufferRow {
15337 row,
15338 line_offset_from_top,
15339 }) => {
15340 let point = MultiBufferPoint::new(row.0, 0);
15341 if let Some((buffer, buffer_point, _)) =
15342 self.buffer.read(cx).point_to_buffer_point(point, cx)
15343 {
15344 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15345 new_selections_by_buffer
15346 .entry(buffer)
15347 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15348 .0
15349 .push(buffer_offset..buffer_offset)
15350 }
15351 }
15352 None => {
15353 let selections = self.selections.all::<usize>(cx);
15354 let multi_buffer = self.buffer.read(cx);
15355 for selection in selections {
15356 for (snapshot, range, _, anchor) in multi_buffer
15357 .snapshot(cx)
15358 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15359 {
15360 if let Some(anchor) = anchor {
15361 // selection is in a deleted hunk
15362 let Some(buffer_id) = anchor.buffer_id else {
15363 continue;
15364 };
15365 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15366 continue;
15367 };
15368 let offset = text::ToOffset::to_offset(
15369 &anchor.text_anchor,
15370 &buffer_handle.read(cx).snapshot(),
15371 );
15372 let range = offset..offset;
15373 new_selections_by_buffer
15374 .entry(buffer_handle)
15375 .or_insert((Vec::new(), None))
15376 .0
15377 .push(range)
15378 } else {
15379 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15380 else {
15381 continue;
15382 };
15383 new_selections_by_buffer
15384 .entry(buffer_handle)
15385 .or_insert((Vec::new(), None))
15386 .0
15387 .push(range)
15388 }
15389 }
15390 }
15391 }
15392 }
15393
15394 if new_selections_by_buffer.is_empty() {
15395 return;
15396 }
15397
15398 // We defer the pane interaction because we ourselves are a workspace item
15399 // and activating a new item causes the pane to call a method on us reentrantly,
15400 // which panics if we're on the stack.
15401 window.defer(cx, move |window, cx| {
15402 workspace.update(cx, |workspace, cx| {
15403 let pane = if split {
15404 workspace.adjacent_pane(window, cx)
15405 } else {
15406 workspace.active_pane().clone()
15407 };
15408
15409 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15410 let editor = buffer
15411 .read(cx)
15412 .file()
15413 .is_none()
15414 .then(|| {
15415 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15416 // so `workspace.open_project_item` will never find them, always opening a new editor.
15417 // Instead, we try to activate the existing editor in the pane first.
15418 let (editor, pane_item_index) =
15419 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15420 let editor = item.downcast::<Editor>()?;
15421 let singleton_buffer =
15422 editor.read(cx).buffer().read(cx).as_singleton()?;
15423 if singleton_buffer == buffer {
15424 Some((editor, i))
15425 } else {
15426 None
15427 }
15428 })?;
15429 pane.update(cx, |pane, cx| {
15430 pane.activate_item(pane_item_index, true, true, window, cx)
15431 });
15432 Some(editor)
15433 })
15434 .flatten()
15435 .unwrap_or_else(|| {
15436 workspace.open_project_item::<Self>(
15437 pane.clone(),
15438 buffer,
15439 true,
15440 true,
15441 window,
15442 cx,
15443 )
15444 });
15445
15446 editor.update(cx, |editor, cx| {
15447 let autoscroll = match scroll_offset {
15448 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15449 None => Autoscroll::newest(),
15450 };
15451 let nav_history = editor.nav_history.take();
15452 editor.change_selections(Some(autoscroll), window, cx, |s| {
15453 s.select_ranges(ranges);
15454 });
15455 editor.nav_history = nav_history;
15456 });
15457 }
15458 })
15459 });
15460 }
15461
15462 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15463 let snapshot = self.buffer.read(cx).read(cx);
15464 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15465 Some(
15466 ranges
15467 .iter()
15468 .map(move |range| {
15469 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15470 })
15471 .collect(),
15472 )
15473 }
15474
15475 fn selection_replacement_ranges(
15476 &self,
15477 range: Range<OffsetUtf16>,
15478 cx: &mut App,
15479 ) -> Vec<Range<OffsetUtf16>> {
15480 let selections = self.selections.all::<OffsetUtf16>(cx);
15481 let newest_selection = selections
15482 .iter()
15483 .max_by_key(|selection| selection.id)
15484 .unwrap();
15485 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15486 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15487 let snapshot = self.buffer.read(cx).read(cx);
15488 selections
15489 .into_iter()
15490 .map(|mut selection| {
15491 selection.start.0 =
15492 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15493 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15494 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15495 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15496 })
15497 .collect()
15498 }
15499
15500 fn report_editor_event(
15501 &self,
15502 event_type: &'static str,
15503 file_extension: Option<String>,
15504 cx: &App,
15505 ) {
15506 if cfg!(any(test, feature = "test-support")) {
15507 return;
15508 }
15509
15510 let Some(project) = &self.project else { return };
15511
15512 // If None, we are in a file without an extension
15513 let file = self
15514 .buffer
15515 .read(cx)
15516 .as_singleton()
15517 .and_then(|b| b.read(cx).file());
15518 let file_extension = file_extension.or(file
15519 .as_ref()
15520 .and_then(|file| Path::new(file.file_name(cx)).extension())
15521 .and_then(|e| e.to_str())
15522 .map(|a| a.to_string()));
15523
15524 let vim_mode = cx
15525 .global::<SettingsStore>()
15526 .raw_user_settings()
15527 .get("vim_mode")
15528 == Some(&serde_json::Value::Bool(true));
15529
15530 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15531 let copilot_enabled = edit_predictions_provider
15532 == language::language_settings::EditPredictionProvider::Copilot;
15533 let copilot_enabled_for_language = self
15534 .buffer
15535 .read(cx)
15536 .settings_at(0, cx)
15537 .show_edit_predictions;
15538
15539 let project = project.read(cx);
15540 telemetry::event!(
15541 event_type,
15542 file_extension,
15543 vim_mode,
15544 copilot_enabled,
15545 copilot_enabled_for_language,
15546 edit_predictions_provider,
15547 is_via_ssh = project.is_via_ssh(),
15548 );
15549 }
15550
15551 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15552 /// with each line being an array of {text, highlight} objects.
15553 fn copy_highlight_json(
15554 &mut self,
15555 _: &CopyHighlightJson,
15556 window: &mut Window,
15557 cx: &mut Context<Self>,
15558 ) {
15559 #[derive(Serialize)]
15560 struct Chunk<'a> {
15561 text: String,
15562 highlight: Option<&'a str>,
15563 }
15564
15565 let snapshot = self.buffer.read(cx).snapshot(cx);
15566 let range = self
15567 .selected_text_range(false, window, cx)
15568 .and_then(|selection| {
15569 if selection.range.is_empty() {
15570 None
15571 } else {
15572 Some(selection.range)
15573 }
15574 })
15575 .unwrap_or_else(|| 0..snapshot.len());
15576
15577 let chunks = snapshot.chunks(range, true);
15578 let mut lines = Vec::new();
15579 let mut line: VecDeque<Chunk> = VecDeque::new();
15580
15581 let Some(style) = self.style.as_ref() else {
15582 return;
15583 };
15584
15585 for chunk in chunks {
15586 let highlight = chunk
15587 .syntax_highlight_id
15588 .and_then(|id| id.name(&style.syntax));
15589 let mut chunk_lines = chunk.text.split('\n').peekable();
15590 while let Some(text) = chunk_lines.next() {
15591 let mut merged_with_last_token = false;
15592 if let Some(last_token) = line.back_mut() {
15593 if last_token.highlight == highlight {
15594 last_token.text.push_str(text);
15595 merged_with_last_token = true;
15596 }
15597 }
15598
15599 if !merged_with_last_token {
15600 line.push_back(Chunk {
15601 text: text.into(),
15602 highlight,
15603 });
15604 }
15605
15606 if chunk_lines.peek().is_some() {
15607 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15608 line.pop_front();
15609 }
15610 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15611 line.pop_back();
15612 }
15613
15614 lines.push(mem::take(&mut line));
15615 }
15616 }
15617 }
15618
15619 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15620 return;
15621 };
15622 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15623 }
15624
15625 pub fn open_context_menu(
15626 &mut self,
15627 _: &OpenContextMenu,
15628 window: &mut Window,
15629 cx: &mut Context<Self>,
15630 ) {
15631 self.request_autoscroll(Autoscroll::newest(), cx);
15632 let position = self.selections.newest_display(cx).start;
15633 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15634 }
15635
15636 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15637 &self.inlay_hint_cache
15638 }
15639
15640 pub fn replay_insert_event(
15641 &mut self,
15642 text: &str,
15643 relative_utf16_range: Option<Range<isize>>,
15644 window: &mut Window,
15645 cx: &mut Context<Self>,
15646 ) {
15647 if !self.input_enabled {
15648 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15649 return;
15650 }
15651 if let Some(relative_utf16_range) = relative_utf16_range {
15652 let selections = self.selections.all::<OffsetUtf16>(cx);
15653 self.change_selections(None, window, cx, |s| {
15654 let new_ranges = selections.into_iter().map(|range| {
15655 let start = OffsetUtf16(
15656 range
15657 .head()
15658 .0
15659 .saturating_add_signed(relative_utf16_range.start),
15660 );
15661 let end = OffsetUtf16(
15662 range
15663 .head()
15664 .0
15665 .saturating_add_signed(relative_utf16_range.end),
15666 );
15667 start..end
15668 });
15669 s.select_ranges(new_ranges);
15670 });
15671 }
15672
15673 self.handle_input(text, window, cx);
15674 }
15675
15676 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15677 let Some(provider) = self.semantics_provider.as_ref() else {
15678 return false;
15679 };
15680
15681 let mut supports = false;
15682 self.buffer().update(cx, |this, cx| {
15683 this.for_each_buffer(|buffer| {
15684 supports |= provider.supports_inlay_hints(buffer, cx);
15685 });
15686 });
15687
15688 supports
15689 }
15690
15691 pub fn is_focused(&self, window: &Window) -> bool {
15692 self.focus_handle.is_focused(window)
15693 }
15694
15695 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15696 cx.emit(EditorEvent::Focused);
15697
15698 if let Some(descendant) = self
15699 .last_focused_descendant
15700 .take()
15701 .and_then(|descendant| descendant.upgrade())
15702 {
15703 window.focus(&descendant);
15704 } else {
15705 if let Some(blame) = self.blame.as_ref() {
15706 blame.update(cx, GitBlame::focus)
15707 }
15708
15709 self.blink_manager.update(cx, BlinkManager::enable);
15710 self.show_cursor_names(window, cx);
15711 self.buffer.update(cx, |buffer, cx| {
15712 buffer.finalize_last_transaction(cx);
15713 if self.leader_peer_id.is_none() {
15714 buffer.set_active_selections(
15715 &self.selections.disjoint_anchors(),
15716 self.selections.line_mode,
15717 self.cursor_shape,
15718 cx,
15719 );
15720 }
15721 });
15722 }
15723 }
15724
15725 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15726 cx.emit(EditorEvent::FocusedIn)
15727 }
15728
15729 fn handle_focus_out(
15730 &mut self,
15731 event: FocusOutEvent,
15732 _window: &mut Window,
15733 _cx: &mut Context<Self>,
15734 ) {
15735 if event.blurred != self.focus_handle {
15736 self.last_focused_descendant = Some(event.blurred);
15737 }
15738 }
15739
15740 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15741 self.blink_manager.update(cx, BlinkManager::disable);
15742 self.buffer
15743 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15744
15745 if let Some(blame) = self.blame.as_ref() {
15746 blame.update(cx, GitBlame::blur)
15747 }
15748 if !self.hover_state.focused(window, cx) {
15749 hide_hover(self, cx);
15750 }
15751 if !self
15752 .context_menu
15753 .borrow()
15754 .as_ref()
15755 .is_some_and(|context_menu| context_menu.focused(window, cx))
15756 {
15757 self.hide_context_menu(window, cx);
15758 }
15759 self.discard_inline_completion(false, cx);
15760 cx.emit(EditorEvent::Blurred);
15761 cx.notify();
15762 }
15763
15764 pub fn register_action<A: Action>(
15765 &mut self,
15766 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15767 ) -> Subscription {
15768 let id = self.next_editor_action_id.post_inc();
15769 let listener = Arc::new(listener);
15770 self.editor_actions.borrow_mut().insert(
15771 id,
15772 Box::new(move |window, _| {
15773 let listener = listener.clone();
15774 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15775 let action = action.downcast_ref().unwrap();
15776 if phase == DispatchPhase::Bubble {
15777 listener(action, window, cx)
15778 }
15779 })
15780 }),
15781 );
15782
15783 let editor_actions = self.editor_actions.clone();
15784 Subscription::new(move || {
15785 editor_actions.borrow_mut().remove(&id);
15786 })
15787 }
15788
15789 pub fn file_header_size(&self) -> u32 {
15790 FILE_HEADER_HEIGHT
15791 }
15792
15793 pub fn revert(
15794 &mut self,
15795 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15796 window: &mut Window,
15797 cx: &mut Context<Self>,
15798 ) {
15799 self.buffer().update(cx, |multi_buffer, cx| {
15800 for (buffer_id, changes) in revert_changes {
15801 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15802 buffer.update(cx, |buffer, cx| {
15803 buffer.edit(
15804 changes.into_iter().map(|(range, text)| {
15805 (range, text.to_string().map(Arc::<str>::from))
15806 }),
15807 None,
15808 cx,
15809 );
15810 });
15811 }
15812 }
15813 });
15814 self.change_selections(None, window, cx, |selections| selections.refresh());
15815 }
15816
15817 pub fn to_pixel_point(
15818 &self,
15819 source: multi_buffer::Anchor,
15820 editor_snapshot: &EditorSnapshot,
15821 window: &mut Window,
15822 ) -> Option<gpui::Point<Pixels>> {
15823 let source_point = source.to_display_point(editor_snapshot);
15824 self.display_to_pixel_point(source_point, editor_snapshot, window)
15825 }
15826
15827 pub fn display_to_pixel_point(
15828 &self,
15829 source: DisplayPoint,
15830 editor_snapshot: &EditorSnapshot,
15831 window: &mut Window,
15832 ) -> Option<gpui::Point<Pixels>> {
15833 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15834 let text_layout_details = self.text_layout_details(window);
15835 let scroll_top = text_layout_details
15836 .scroll_anchor
15837 .scroll_position(editor_snapshot)
15838 .y;
15839
15840 if source.row().as_f32() < scroll_top.floor() {
15841 return None;
15842 }
15843 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15844 let source_y = line_height * (source.row().as_f32() - scroll_top);
15845 Some(gpui::Point::new(source_x, source_y))
15846 }
15847
15848 pub fn has_visible_completions_menu(&self) -> bool {
15849 !self.edit_prediction_preview_is_active()
15850 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15851 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15852 })
15853 }
15854
15855 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15856 self.addons
15857 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15858 }
15859
15860 pub fn unregister_addon<T: Addon>(&mut self) {
15861 self.addons.remove(&std::any::TypeId::of::<T>());
15862 }
15863
15864 pub fn addon<T: Addon>(&self) -> Option<&T> {
15865 let type_id = std::any::TypeId::of::<T>();
15866 self.addons
15867 .get(&type_id)
15868 .and_then(|item| item.to_any().downcast_ref::<T>())
15869 }
15870
15871 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15872 let text_layout_details = self.text_layout_details(window);
15873 let style = &text_layout_details.editor_style;
15874 let font_id = window.text_system().resolve_font(&style.text.font());
15875 let font_size = style.text.font_size.to_pixels(window.rem_size());
15876 let line_height = style.text.line_height_in_pixels(window.rem_size());
15877 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15878
15879 gpui::Size::new(em_width, line_height)
15880 }
15881
15882 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15883 self.load_diff_task.clone()
15884 }
15885
15886 fn read_selections_from_db(
15887 &mut self,
15888 item_id: u64,
15889 workspace_id: WorkspaceId,
15890 window: &mut Window,
15891 cx: &mut Context<Editor>,
15892 ) {
15893 if !self.is_singleton(cx)
15894 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15895 {
15896 return;
15897 }
15898 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15899 return;
15900 };
15901 if selections.is_empty() {
15902 return;
15903 }
15904
15905 let snapshot = self.buffer.read(cx).snapshot(cx);
15906 self.change_selections(None, window, cx, |s| {
15907 s.select_ranges(selections.into_iter().map(|(start, end)| {
15908 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15909 }));
15910 });
15911 }
15912}
15913
15914fn insert_extra_newline_brackets(
15915 buffer: &MultiBufferSnapshot,
15916 range: Range<usize>,
15917 language: &language::LanguageScope,
15918) -> bool {
15919 let leading_whitespace_len = buffer
15920 .reversed_chars_at(range.start)
15921 .take_while(|c| c.is_whitespace() && *c != '\n')
15922 .map(|c| c.len_utf8())
15923 .sum::<usize>();
15924 let trailing_whitespace_len = buffer
15925 .chars_at(range.end)
15926 .take_while(|c| c.is_whitespace() && *c != '\n')
15927 .map(|c| c.len_utf8())
15928 .sum::<usize>();
15929 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15930
15931 language.brackets().any(|(pair, enabled)| {
15932 let pair_start = pair.start.trim_end();
15933 let pair_end = pair.end.trim_start();
15934
15935 enabled
15936 && pair.newline
15937 && buffer.contains_str_at(range.end, pair_end)
15938 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15939 })
15940}
15941
15942fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15943 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15944 [(buffer, range, _)] => (*buffer, range.clone()),
15945 _ => return false,
15946 };
15947 let pair = {
15948 let mut result: Option<BracketMatch> = None;
15949
15950 for pair in buffer
15951 .all_bracket_ranges(range.clone())
15952 .filter(move |pair| {
15953 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15954 })
15955 {
15956 let len = pair.close_range.end - pair.open_range.start;
15957
15958 if let Some(existing) = &result {
15959 let existing_len = existing.close_range.end - existing.open_range.start;
15960 if len > existing_len {
15961 continue;
15962 }
15963 }
15964
15965 result = Some(pair);
15966 }
15967
15968 result
15969 };
15970 let Some(pair) = pair else {
15971 return false;
15972 };
15973 pair.newline_only
15974 && buffer
15975 .chars_for_range(pair.open_range.end..range.start)
15976 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15977 .all(|c| c.is_whitespace() && c != '\n')
15978}
15979
15980fn get_uncommitted_diff_for_buffer(
15981 project: &Entity<Project>,
15982 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15983 buffer: Entity<MultiBuffer>,
15984 cx: &mut App,
15985) -> Task<()> {
15986 let mut tasks = Vec::new();
15987 project.update(cx, |project, cx| {
15988 for buffer in buffers {
15989 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15990 }
15991 });
15992 cx.spawn(|mut cx| async move {
15993 let diffs = futures::future::join_all(tasks).await;
15994 buffer
15995 .update(&mut cx, |buffer, cx| {
15996 for diff in diffs.into_iter().flatten() {
15997 buffer.add_diff(diff, cx);
15998 }
15999 })
16000 .ok();
16001 })
16002}
16003
16004fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16005 let tab_size = tab_size.get() as usize;
16006 let mut width = offset;
16007
16008 for ch in text.chars() {
16009 width += if ch == '\t' {
16010 tab_size - (width % tab_size)
16011 } else {
16012 1
16013 };
16014 }
16015
16016 width - offset
16017}
16018
16019#[cfg(test)]
16020mod tests {
16021 use super::*;
16022
16023 #[test]
16024 fn test_string_size_with_expanded_tabs() {
16025 let nz = |val| NonZeroU32::new(val).unwrap();
16026 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16027 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16028 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16029 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16030 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16031 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16032 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16033 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16034 }
16035}
16036
16037/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16038struct WordBreakingTokenizer<'a> {
16039 input: &'a str,
16040}
16041
16042impl<'a> WordBreakingTokenizer<'a> {
16043 fn new(input: &'a str) -> Self {
16044 Self { input }
16045 }
16046}
16047
16048fn is_char_ideographic(ch: char) -> bool {
16049 use unicode_script::Script::*;
16050 use unicode_script::UnicodeScript;
16051 matches!(ch.script(), Han | Tangut | Yi)
16052}
16053
16054fn is_grapheme_ideographic(text: &str) -> bool {
16055 text.chars().any(is_char_ideographic)
16056}
16057
16058fn is_grapheme_whitespace(text: &str) -> bool {
16059 text.chars().any(|x| x.is_whitespace())
16060}
16061
16062fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16063 text.chars().next().map_or(false, |ch| {
16064 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16065 })
16066}
16067
16068#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16069struct WordBreakToken<'a> {
16070 token: &'a str,
16071 grapheme_len: usize,
16072 is_whitespace: bool,
16073}
16074
16075impl<'a> Iterator for WordBreakingTokenizer<'a> {
16076 /// Yields a span, the count of graphemes in the token, and whether it was
16077 /// whitespace. Note that it also breaks at word boundaries.
16078 type Item = WordBreakToken<'a>;
16079
16080 fn next(&mut self) -> Option<Self::Item> {
16081 use unicode_segmentation::UnicodeSegmentation;
16082 if self.input.is_empty() {
16083 return None;
16084 }
16085
16086 let mut iter = self.input.graphemes(true).peekable();
16087 let mut offset = 0;
16088 let mut graphemes = 0;
16089 if let Some(first_grapheme) = iter.next() {
16090 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16091 offset += first_grapheme.len();
16092 graphemes += 1;
16093 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16094 if let Some(grapheme) = iter.peek().copied() {
16095 if should_stay_with_preceding_ideograph(grapheme) {
16096 offset += grapheme.len();
16097 graphemes += 1;
16098 }
16099 }
16100 } else {
16101 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16102 let mut next_word_bound = words.peek().copied();
16103 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16104 next_word_bound = words.next();
16105 }
16106 while let Some(grapheme) = iter.peek().copied() {
16107 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16108 break;
16109 };
16110 if is_grapheme_whitespace(grapheme) != is_whitespace {
16111 break;
16112 };
16113 offset += grapheme.len();
16114 graphemes += 1;
16115 iter.next();
16116 }
16117 }
16118 let token = &self.input[..offset];
16119 self.input = &self.input[offset..];
16120 if is_whitespace {
16121 Some(WordBreakToken {
16122 token: " ",
16123 grapheme_len: 1,
16124 is_whitespace: true,
16125 })
16126 } else {
16127 Some(WordBreakToken {
16128 token,
16129 grapheme_len: graphemes,
16130 is_whitespace: false,
16131 })
16132 }
16133 } else {
16134 None
16135 }
16136 }
16137}
16138
16139#[test]
16140fn test_word_breaking_tokenizer() {
16141 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16142 ("", &[]),
16143 (" ", &[(" ", 1, true)]),
16144 ("Ʒ", &[("Ʒ", 1, false)]),
16145 ("Ǽ", &[("Ǽ", 1, false)]),
16146 ("⋑", &[("⋑", 1, false)]),
16147 ("⋑⋑", &[("⋑⋑", 2, false)]),
16148 (
16149 "原理,进而",
16150 &[
16151 ("原", 1, false),
16152 ("理,", 2, false),
16153 ("进", 1, false),
16154 ("而", 1, false),
16155 ],
16156 ),
16157 (
16158 "hello world",
16159 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16160 ),
16161 (
16162 "hello, world",
16163 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16164 ),
16165 (
16166 " hello world",
16167 &[
16168 (" ", 1, true),
16169 ("hello", 5, false),
16170 (" ", 1, true),
16171 ("world", 5, false),
16172 ],
16173 ),
16174 (
16175 "这是什么 \n 钢笔",
16176 &[
16177 ("这", 1, false),
16178 ("是", 1, false),
16179 ("什", 1, false),
16180 ("么", 1, false),
16181 (" ", 1, true),
16182 ("钢", 1, false),
16183 ("笔", 1, false),
16184 ],
16185 ),
16186 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16187 ];
16188
16189 for (input, result) in tests {
16190 assert_eq!(
16191 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16192 result
16193 .iter()
16194 .copied()
16195 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16196 token,
16197 grapheme_len,
16198 is_whitespace,
16199 })
16200 .collect::<Vec<_>>()
16201 );
16202 }
16203}
16204
16205fn wrap_with_prefix(
16206 line_prefix: String,
16207 unwrapped_text: String,
16208 wrap_column: usize,
16209 tab_size: NonZeroU32,
16210) -> String {
16211 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16212 let mut wrapped_text = String::new();
16213 let mut current_line = line_prefix.clone();
16214
16215 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16216 let mut current_line_len = line_prefix_len;
16217 for WordBreakToken {
16218 token,
16219 grapheme_len,
16220 is_whitespace,
16221 } in tokenizer
16222 {
16223 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16224 wrapped_text.push_str(current_line.trim_end());
16225 wrapped_text.push('\n');
16226 current_line.truncate(line_prefix.len());
16227 current_line_len = line_prefix_len;
16228 if !is_whitespace {
16229 current_line.push_str(token);
16230 current_line_len += grapheme_len;
16231 }
16232 } else if !is_whitespace {
16233 current_line.push_str(token);
16234 current_line_len += grapheme_len;
16235 } else if current_line_len != line_prefix_len {
16236 current_line.push(' ');
16237 current_line_len += 1;
16238 }
16239 }
16240
16241 if !current_line.is_empty() {
16242 wrapped_text.push_str(¤t_line);
16243 }
16244 wrapped_text
16245}
16246
16247#[test]
16248fn test_wrap_with_prefix() {
16249 assert_eq!(
16250 wrap_with_prefix(
16251 "# ".to_string(),
16252 "abcdefg".to_string(),
16253 4,
16254 NonZeroU32::new(4).unwrap()
16255 ),
16256 "# abcdefg"
16257 );
16258 assert_eq!(
16259 wrap_with_prefix(
16260 "".to_string(),
16261 "\thello world".to_string(),
16262 8,
16263 NonZeroU32::new(4).unwrap()
16264 ),
16265 "hello\nworld"
16266 );
16267 assert_eq!(
16268 wrap_with_prefix(
16269 "// ".to_string(),
16270 "xx \nyy zz aa bb cc".to_string(),
16271 12,
16272 NonZeroU32::new(4).unwrap()
16273 ),
16274 "// xx yy zz\n// aa bb cc"
16275 );
16276 assert_eq!(
16277 wrap_with_prefix(
16278 String::new(),
16279 "这是什么 \n 钢笔".to_string(),
16280 3,
16281 NonZeroU32::new(4).unwrap()
16282 ),
16283 "这是什\n么 钢\n笔"
16284 );
16285}
16286
16287pub trait CollaborationHub {
16288 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16289 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16290 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16291}
16292
16293impl CollaborationHub for Entity<Project> {
16294 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16295 self.read(cx).collaborators()
16296 }
16297
16298 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16299 self.read(cx).user_store().read(cx).participant_indices()
16300 }
16301
16302 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16303 let this = self.read(cx);
16304 let user_ids = this.collaborators().values().map(|c| c.user_id);
16305 this.user_store().read_with(cx, |user_store, cx| {
16306 user_store.participant_names(user_ids, cx)
16307 })
16308 }
16309}
16310
16311pub trait SemanticsProvider {
16312 fn hover(
16313 &self,
16314 buffer: &Entity<Buffer>,
16315 position: text::Anchor,
16316 cx: &mut App,
16317 ) -> Option<Task<Vec<project::Hover>>>;
16318
16319 fn inlay_hints(
16320 &self,
16321 buffer_handle: Entity<Buffer>,
16322 range: Range<text::Anchor>,
16323 cx: &mut App,
16324 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16325
16326 fn resolve_inlay_hint(
16327 &self,
16328 hint: InlayHint,
16329 buffer_handle: Entity<Buffer>,
16330 server_id: LanguageServerId,
16331 cx: &mut App,
16332 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16333
16334 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16335
16336 fn document_highlights(
16337 &self,
16338 buffer: &Entity<Buffer>,
16339 position: text::Anchor,
16340 cx: &mut App,
16341 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16342
16343 fn definitions(
16344 &self,
16345 buffer: &Entity<Buffer>,
16346 position: text::Anchor,
16347 kind: GotoDefinitionKind,
16348 cx: &mut App,
16349 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16350
16351 fn range_for_rename(
16352 &self,
16353 buffer: &Entity<Buffer>,
16354 position: text::Anchor,
16355 cx: &mut App,
16356 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16357
16358 fn perform_rename(
16359 &self,
16360 buffer: &Entity<Buffer>,
16361 position: text::Anchor,
16362 new_name: String,
16363 cx: &mut App,
16364 ) -> Option<Task<Result<ProjectTransaction>>>;
16365}
16366
16367pub trait CompletionProvider {
16368 fn completions(
16369 &self,
16370 buffer: &Entity<Buffer>,
16371 buffer_position: text::Anchor,
16372 trigger: CompletionContext,
16373 window: &mut Window,
16374 cx: &mut Context<Editor>,
16375 ) -> Task<Result<Vec<Completion>>>;
16376
16377 fn resolve_completions(
16378 &self,
16379 buffer: Entity<Buffer>,
16380 completion_indices: Vec<usize>,
16381 completions: Rc<RefCell<Box<[Completion]>>>,
16382 cx: &mut Context<Editor>,
16383 ) -> Task<Result<bool>>;
16384
16385 fn apply_additional_edits_for_completion(
16386 &self,
16387 _buffer: Entity<Buffer>,
16388 _completions: Rc<RefCell<Box<[Completion]>>>,
16389 _completion_index: usize,
16390 _push_to_history: bool,
16391 _cx: &mut Context<Editor>,
16392 ) -> Task<Result<Option<language::Transaction>>> {
16393 Task::ready(Ok(None))
16394 }
16395
16396 fn is_completion_trigger(
16397 &self,
16398 buffer: &Entity<Buffer>,
16399 position: language::Anchor,
16400 text: &str,
16401 trigger_in_words: bool,
16402 cx: &mut Context<Editor>,
16403 ) -> bool;
16404
16405 fn sort_completions(&self) -> bool {
16406 true
16407 }
16408}
16409
16410pub trait CodeActionProvider {
16411 fn id(&self) -> Arc<str>;
16412
16413 fn code_actions(
16414 &self,
16415 buffer: &Entity<Buffer>,
16416 range: Range<text::Anchor>,
16417 window: &mut Window,
16418 cx: &mut App,
16419 ) -> Task<Result<Vec<CodeAction>>>;
16420
16421 fn apply_code_action(
16422 &self,
16423 buffer_handle: Entity<Buffer>,
16424 action: CodeAction,
16425 excerpt_id: ExcerptId,
16426 push_to_history: bool,
16427 window: &mut Window,
16428 cx: &mut App,
16429 ) -> Task<Result<ProjectTransaction>>;
16430}
16431
16432impl CodeActionProvider for Entity<Project> {
16433 fn id(&self) -> Arc<str> {
16434 "project".into()
16435 }
16436
16437 fn code_actions(
16438 &self,
16439 buffer: &Entity<Buffer>,
16440 range: Range<text::Anchor>,
16441 _window: &mut Window,
16442 cx: &mut App,
16443 ) -> Task<Result<Vec<CodeAction>>> {
16444 self.update(cx, |project, cx| {
16445 project.code_actions(buffer, range, None, cx)
16446 })
16447 }
16448
16449 fn apply_code_action(
16450 &self,
16451 buffer_handle: Entity<Buffer>,
16452 action: CodeAction,
16453 _excerpt_id: ExcerptId,
16454 push_to_history: bool,
16455 _window: &mut Window,
16456 cx: &mut App,
16457 ) -> Task<Result<ProjectTransaction>> {
16458 self.update(cx, |project, cx| {
16459 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16460 })
16461 }
16462}
16463
16464fn snippet_completions(
16465 project: &Project,
16466 buffer: &Entity<Buffer>,
16467 buffer_position: text::Anchor,
16468 cx: &mut App,
16469) -> Task<Result<Vec<Completion>>> {
16470 let language = buffer.read(cx).language_at(buffer_position);
16471 let language_name = language.as_ref().map(|language| language.lsp_id());
16472 let snippet_store = project.snippets().read(cx);
16473 let snippets = snippet_store.snippets_for(language_name, cx);
16474
16475 if snippets.is_empty() {
16476 return Task::ready(Ok(vec![]));
16477 }
16478 let snapshot = buffer.read(cx).text_snapshot();
16479 let chars: String = snapshot
16480 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16481 .collect();
16482
16483 let scope = language.map(|language| language.default_scope());
16484 let executor = cx.background_executor().clone();
16485
16486 cx.background_spawn(async move {
16487 let classifier = CharClassifier::new(scope).for_completion(true);
16488 let mut last_word = chars
16489 .chars()
16490 .take_while(|c| classifier.is_word(*c))
16491 .collect::<String>();
16492 last_word = last_word.chars().rev().collect();
16493
16494 if last_word.is_empty() {
16495 return Ok(vec![]);
16496 }
16497
16498 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16499 let to_lsp = |point: &text::Anchor| {
16500 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16501 point_to_lsp(end)
16502 };
16503 let lsp_end = to_lsp(&buffer_position);
16504
16505 let candidates = snippets
16506 .iter()
16507 .enumerate()
16508 .flat_map(|(ix, snippet)| {
16509 snippet
16510 .prefix
16511 .iter()
16512 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16513 })
16514 .collect::<Vec<StringMatchCandidate>>();
16515
16516 let mut matches = fuzzy::match_strings(
16517 &candidates,
16518 &last_word,
16519 last_word.chars().any(|c| c.is_uppercase()),
16520 100,
16521 &Default::default(),
16522 executor,
16523 )
16524 .await;
16525
16526 // Remove all candidates where the query's start does not match the start of any word in the candidate
16527 if let Some(query_start) = last_word.chars().next() {
16528 matches.retain(|string_match| {
16529 split_words(&string_match.string).any(|word| {
16530 // Check that the first codepoint of the word as lowercase matches the first
16531 // codepoint of the query as lowercase
16532 word.chars()
16533 .flat_map(|codepoint| codepoint.to_lowercase())
16534 .zip(query_start.to_lowercase())
16535 .all(|(word_cp, query_cp)| word_cp == query_cp)
16536 })
16537 });
16538 }
16539
16540 let matched_strings = matches
16541 .into_iter()
16542 .map(|m| m.string)
16543 .collect::<HashSet<_>>();
16544
16545 let result: Vec<Completion> = snippets
16546 .into_iter()
16547 .filter_map(|snippet| {
16548 let matching_prefix = snippet
16549 .prefix
16550 .iter()
16551 .find(|prefix| matched_strings.contains(*prefix))?;
16552 let start = as_offset - last_word.len();
16553 let start = snapshot.anchor_before(start);
16554 let range = start..buffer_position;
16555 let lsp_start = to_lsp(&start);
16556 let lsp_range = lsp::Range {
16557 start: lsp_start,
16558 end: lsp_end,
16559 };
16560 Some(Completion {
16561 old_range: range,
16562 new_text: snippet.body.clone(),
16563 resolved: false,
16564 label: CodeLabel {
16565 text: matching_prefix.clone(),
16566 runs: vec![],
16567 filter_range: 0..matching_prefix.len(),
16568 },
16569 server_id: LanguageServerId(usize::MAX),
16570 documentation: snippet
16571 .description
16572 .clone()
16573 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16574 lsp_completion: lsp::CompletionItem {
16575 label: snippet.prefix.first().unwrap().clone(),
16576 kind: Some(CompletionItemKind::SNIPPET),
16577 label_details: snippet.description.as_ref().map(|description| {
16578 lsp::CompletionItemLabelDetails {
16579 detail: Some(description.clone()),
16580 description: None,
16581 }
16582 }),
16583 insert_text_format: Some(InsertTextFormat::SNIPPET),
16584 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16585 lsp::InsertReplaceEdit {
16586 new_text: snippet.body.clone(),
16587 insert: lsp_range,
16588 replace: lsp_range,
16589 },
16590 )),
16591 filter_text: Some(snippet.body.clone()),
16592 sort_text: Some(char::MAX.to_string()),
16593 ..Default::default()
16594 },
16595 confirm: None,
16596 })
16597 })
16598 .collect();
16599
16600 Ok(result)
16601 })
16602}
16603
16604impl CompletionProvider for Entity<Project> {
16605 fn completions(
16606 &self,
16607 buffer: &Entity<Buffer>,
16608 buffer_position: text::Anchor,
16609 options: CompletionContext,
16610 _window: &mut Window,
16611 cx: &mut Context<Editor>,
16612 ) -> Task<Result<Vec<Completion>>> {
16613 self.update(cx, |project, cx| {
16614 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16615 let project_completions = project.completions(buffer, buffer_position, options, cx);
16616 cx.background_spawn(async move {
16617 let mut completions = project_completions.await?;
16618 let snippets_completions = snippets.await?;
16619 completions.extend(snippets_completions);
16620 Ok(completions)
16621 })
16622 })
16623 }
16624
16625 fn resolve_completions(
16626 &self,
16627 buffer: Entity<Buffer>,
16628 completion_indices: Vec<usize>,
16629 completions: Rc<RefCell<Box<[Completion]>>>,
16630 cx: &mut Context<Editor>,
16631 ) -> Task<Result<bool>> {
16632 self.update(cx, |project, cx| {
16633 project.lsp_store().update(cx, |lsp_store, cx| {
16634 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16635 })
16636 })
16637 }
16638
16639 fn apply_additional_edits_for_completion(
16640 &self,
16641 buffer: Entity<Buffer>,
16642 completions: Rc<RefCell<Box<[Completion]>>>,
16643 completion_index: usize,
16644 push_to_history: bool,
16645 cx: &mut Context<Editor>,
16646 ) -> Task<Result<Option<language::Transaction>>> {
16647 self.update(cx, |project, cx| {
16648 project.lsp_store().update(cx, |lsp_store, cx| {
16649 lsp_store.apply_additional_edits_for_completion(
16650 buffer,
16651 completions,
16652 completion_index,
16653 push_to_history,
16654 cx,
16655 )
16656 })
16657 })
16658 }
16659
16660 fn is_completion_trigger(
16661 &self,
16662 buffer: &Entity<Buffer>,
16663 position: language::Anchor,
16664 text: &str,
16665 trigger_in_words: bool,
16666 cx: &mut Context<Editor>,
16667 ) -> bool {
16668 let mut chars = text.chars();
16669 let char = if let Some(char) = chars.next() {
16670 char
16671 } else {
16672 return false;
16673 };
16674 if chars.next().is_some() {
16675 return false;
16676 }
16677
16678 let buffer = buffer.read(cx);
16679 let snapshot = buffer.snapshot();
16680 if !snapshot.settings_at(position, cx).show_completions_on_input {
16681 return false;
16682 }
16683 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16684 if trigger_in_words && classifier.is_word(char) {
16685 return true;
16686 }
16687
16688 buffer.completion_triggers().contains(text)
16689 }
16690}
16691
16692impl SemanticsProvider for Entity<Project> {
16693 fn hover(
16694 &self,
16695 buffer: &Entity<Buffer>,
16696 position: text::Anchor,
16697 cx: &mut App,
16698 ) -> Option<Task<Vec<project::Hover>>> {
16699 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16700 }
16701
16702 fn document_highlights(
16703 &self,
16704 buffer: &Entity<Buffer>,
16705 position: text::Anchor,
16706 cx: &mut App,
16707 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16708 Some(self.update(cx, |project, cx| {
16709 project.document_highlights(buffer, position, cx)
16710 }))
16711 }
16712
16713 fn definitions(
16714 &self,
16715 buffer: &Entity<Buffer>,
16716 position: text::Anchor,
16717 kind: GotoDefinitionKind,
16718 cx: &mut App,
16719 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16720 Some(self.update(cx, |project, cx| match kind {
16721 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16722 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16723 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16724 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16725 }))
16726 }
16727
16728 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16729 // TODO: make this work for remote projects
16730 self.update(cx, |this, cx| {
16731 buffer.update(cx, |buffer, cx| {
16732 this.any_language_server_supports_inlay_hints(buffer, cx)
16733 })
16734 })
16735 }
16736
16737 fn inlay_hints(
16738 &self,
16739 buffer_handle: Entity<Buffer>,
16740 range: Range<text::Anchor>,
16741 cx: &mut App,
16742 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16743 Some(self.update(cx, |project, cx| {
16744 project.inlay_hints(buffer_handle, range, cx)
16745 }))
16746 }
16747
16748 fn resolve_inlay_hint(
16749 &self,
16750 hint: InlayHint,
16751 buffer_handle: Entity<Buffer>,
16752 server_id: LanguageServerId,
16753 cx: &mut App,
16754 ) -> Option<Task<anyhow::Result<InlayHint>>> {
16755 Some(self.update(cx, |project, cx| {
16756 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16757 }))
16758 }
16759
16760 fn range_for_rename(
16761 &self,
16762 buffer: &Entity<Buffer>,
16763 position: text::Anchor,
16764 cx: &mut App,
16765 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16766 Some(self.update(cx, |project, cx| {
16767 let buffer = buffer.clone();
16768 let task = project.prepare_rename(buffer.clone(), position, cx);
16769 cx.spawn(|_, mut cx| async move {
16770 Ok(match task.await? {
16771 PrepareRenameResponse::Success(range) => Some(range),
16772 PrepareRenameResponse::InvalidPosition => None,
16773 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16774 // Fallback on using TreeSitter info to determine identifier range
16775 buffer.update(&mut cx, |buffer, _| {
16776 let snapshot = buffer.snapshot();
16777 let (range, kind) = snapshot.surrounding_word(position);
16778 if kind != Some(CharKind::Word) {
16779 return None;
16780 }
16781 Some(
16782 snapshot.anchor_before(range.start)
16783 ..snapshot.anchor_after(range.end),
16784 )
16785 })?
16786 }
16787 })
16788 })
16789 }))
16790 }
16791
16792 fn perform_rename(
16793 &self,
16794 buffer: &Entity<Buffer>,
16795 position: text::Anchor,
16796 new_name: String,
16797 cx: &mut App,
16798 ) -> Option<Task<Result<ProjectTransaction>>> {
16799 Some(self.update(cx, |project, cx| {
16800 project.perform_rename(buffer.clone(), position, new_name, cx)
16801 }))
16802 }
16803}
16804
16805fn inlay_hint_settings(
16806 location: Anchor,
16807 snapshot: &MultiBufferSnapshot,
16808 cx: &mut Context<Editor>,
16809) -> InlayHintSettings {
16810 let file = snapshot.file_at(location);
16811 let language = snapshot.language_at(location).map(|l| l.name());
16812 language_settings(language, file, cx).inlay_hints
16813}
16814
16815fn consume_contiguous_rows(
16816 contiguous_row_selections: &mut Vec<Selection<Point>>,
16817 selection: &Selection<Point>,
16818 display_map: &DisplaySnapshot,
16819 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16820) -> (MultiBufferRow, MultiBufferRow) {
16821 contiguous_row_selections.push(selection.clone());
16822 let start_row = MultiBufferRow(selection.start.row);
16823 let mut end_row = ending_row(selection, display_map);
16824
16825 while let Some(next_selection) = selections.peek() {
16826 if next_selection.start.row <= end_row.0 {
16827 end_row = ending_row(next_selection, display_map);
16828 contiguous_row_selections.push(selections.next().unwrap().clone());
16829 } else {
16830 break;
16831 }
16832 }
16833 (start_row, end_row)
16834}
16835
16836fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16837 if next_selection.end.column > 0 || next_selection.is_empty() {
16838 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16839 } else {
16840 MultiBufferRow(next_selection.end.row)
16841 }
16842}
16843
16844impl EditorSnapshot {
16845 pub fn remote_selections_in_range<'a>(
16846 &'a self,
16847 range: &'a Range<Anchor>,
16848 collaboration_hub: &dyn CollaborationHub,
16849 cx: &'a App,
16850 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16851 let participant_names = collaboration_hub.user_names(cx);
16852 let participant_indices = collaboration_hub.user_participant_indices(cx);
16853 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16854 let collaborators_by_replica_id = collaborators_by_peer_id
16855 .iter()
16856 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16857 .collect::<HashMap<_, _>>();
16858 self.buffer_snapshot
16859 .selections_in_range(range, false)
16860 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16861 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16862 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16863 let user_name = participant_names.get(&collaborator.user_id).cloned();
16864 Some(RemoteSelection {
16865 replica_id,
16866 selection,
16867 cursor_shape,
16868 line_mode,
16869 participant_index,
16870 peer_id: collaborator.peer_id,
16871 user_name,
16872 })
16873 })
16874 }
16875
16876 pub fn hunks_for_ranges(
16877 &self,
16878 ranges: impl Iterator<Item = Range<Point>>,
16879 ) -> Vec<MultiBufferDiffHunk> {
16880 let mut hunks = Vec::new();
16881 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16882 HashMap::default();
16883 for query_range in ranges {
16884 let query_rows =
16885 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16886 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16887 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16888 ) {
16889 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16890 // when the caret is just above or just below the deleted hunk.
16891 let allow_adjacent = hunk.status().is_deleted();
16892 let related_to_selection = if allow_adjacent {
16893 hunk.row_range.overlaps(&query_rows)
16894 || hunk.row_range.start == query_rows.end
16895 || hunk.row_range.end == query_rows.start
16896 } else {
16897 hunk.row_range.overlaps(&query_rows)
16898 };
16899 if related_to_selection {
16900 if !processed_buffer_rows
16901 .entry(hunk.buffer_id)
16902 .or_default()
16903 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16904 {
16905 continue;
16906 }
16907 hunks.push(hunk);
16908 }
16909 }
16910 }
16911
16912 hunks
16913 }
16914
16915 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16916 self.display_snapshot.buffer_snapshot.language_at(position)
16917 }
16918
16919 pub fn is_focused(&self) -> bool {
16920 self.is_focused
16921 }
16922
16923 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16924 self.placeholder_text.as_ref()
16925 }
16926
16927 pub fn scroll_position(&self) -> gpui::Point<f32> {
16928 self.scroll_anchor.scroll_position(&self.display_snapshot)
16929 }
16930
16931 fn gutter_dimensions(
16932 &self,
16933 font_id: FontId,
16934 font_size: Pixels,
16935 max_line_number_width: Pixels,
16936 cx: &App,
16937 ) -> Option<GutterDimensions> {
16938 if !self.show_gutter {
16939 return None;
16940 }
16941
16942 let descent = cx.text_system().descent(font_id, font_size);
16943 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16944 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16945
16946 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16947 matches!(
16948 ProjectSettings::get_global(cx).git.git_gutter,
16949 Some(GitGutterSetting::TrackedFiles)
16950 )
16951 });
16952 let gutter_settings = EditorSettings::get_global(cx).gutter;
16953 let show_line_numbers = self
16954 .show_line_numbers
16955 .unwrap_or(gutter_settings.line_numbers);
16956 let line_gutter_width = if show_line_numbers {
16957 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16958 let min_width_for_number_on_gutter = em_advance * 4.0;
16959 max_line_number_width.max(min_width_for_number_on_gutter)
16960 } else {
16961 0.0.into()
16962 };
16963
16964 let show_code_actions = self
16965 .show_code_actions
16966 .unwrap_or(gutter_settings.code_actions);
16967
16968 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16969
16970 let git_blame_entries_width =
16971 self.git_blame_gutter_max_author_length
16972 .map(|max_author_length| {
16973 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16974
16975 /// The number of characters to dedicate to gaps and margins.
16976 const SPACING_WIDTH: usize = 4;
16977
16978 let max_char_count = max_author_length
16979 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16980 + ::git::SHORT_SHA_LENGTH
16981 + MAX_RELATIVE_TIMESTAMP.len()
16982 + SPACING_WIDTH;
16983
16984 em_advance * max_char_count
16985 });
16986
16987 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16988 left_padding += if show_code_actions || show_runnables {
16989 em_width * 3.0
16990 } else if show_git_gutter && show_line_numbers {
16991 em_width * 2.0
16992 } else if show_git_gutter || show_line_numbers {
16993 em_width
16994 } else {
16995 px(0.)
16996 };
16997
16998 let right_padding = if gutter_settings.folds && show_line_numbers {
16999 em_width * 4.0
17000 } else if gutter_settings.folds {
17001 em_width * 3.0
17002 } else if show_line_numbers {
17003 em_width
17004 } else {
17005 px(0.)
17006 };
17007
17008 Some(GutterDimensions {
17009 left_padding,
17010 right_padding,
17011 width: line_gutter_width + left_padding + right_padding,
17012 margin: -descent,
17013 git_blame_entries_width,
17014 })
17015 }
17016
17017 pub fn render_crease_toggle(
17018 &self,
17019 buffer_row: MultiBufferRow,
17020 row_contains_cursor: bool,
17021 editor: Entity<Editor>,
17022 window: &mut Window,
17023 cx: &mut App,
17024 ) -> Option<AnyElement> {
17025 let folded = self.is_line_folded(buffer_row);
17026 let mut is_foldable = false;
17027
17028 if let Some(crease) = self
17029 .crease_snapshot
17030 .query_row(buffer_row, &self.buffer_snapshot)
17031 {
17032 is_foldable = true;
17033 match crease {
17034 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17035 if let Some(render_toggle) = render_toggle {
17036 let toggle_callback =
17037 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17038 if folded {
17039 editor.update(cx, |editor, cx| {
17040 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17041 });
17042 } else {
17043 editor.update(cx, |editor, cx| {
17044 editor.unfold_at(
17045 &crate::UnfoldAt { buffer_row },
17046 window,
17047 cx,
17048 )
17049 });
17050 }
17051 });
17052 return Some((render_toggle)(
17053 buffer_row,
17054 folded,
17055 toggle_callback,
17056 window,
17057 cx,
17058 ));
17059 }
17060 }
17061 }
17062 }
17063
17064 is_foldable |= self.starts_indent(buffer_row);
17065
17066 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17067 Some(
17068 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17069 .toggle_state(folded)
17070 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17071 if folded {
17072 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17073 } else {
17074 this.fold_at(&FoldAt { buffer_row }, window, cx);
17075 }
17076 }))
17077 .into_any_element(),
17078 )
17079 } else {
17080 None
17081 }
17082 }
17083
17084 pub fn render_crease_trailer(
17085 &self,
17086 buffer_row: MultiBufferRow,
17087 window: &mut Window,
17088 cx: &mut App,
17089 ) -> Option<AnyElement> {
17090 let folded = self.is_line_folded(buffer_row);
17091 if let Crease::Inline { render_trailer, .. } = self
17092 .crease_snapshot
17093 .query_row(buffer_row, &self.buffer_snapshot)?
17094 {
17095 let render_trailer = render_trailer.as_ref()?;
17096 Some(render_trailer(buffer_row, folded, window, cx))
17097 } else {
17098 None
17099 }
17100 }
17101}
17102
17103impl Deref for EditorSnapshot {
17104 type Target = DisplaySnapshot;
17105
17106 fn deref(&self) -> &Self::Target {
17107 &self.display_snapshot
17108 }
17109}
17110
17111#[derive(Clone, Debug, PartialEq, Eq)]
17112pub enum EditorEvent {
17113 InputIgnored {
17114 text: Arc<str>,
17115 },
17116 InputHandled {
17117 utf16_range_to_replace: Option<Range<isize>>,
17118 text: Arc<str>,
17119 },
17120 ExcerptsAdded {
17121 buffer: Entity<Buffer>,
17122 predecessor: ExcerptId,
17123 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17124 },
17125 ExcerptsRemoved {
17126 ids: Vec<ExcerptId>,
17127 },
17128 BufferFoldToggled {
17129 ids: Vec<ExcerptId>,
17130 folded: bool,
17131 },
17132 ExcerptsEdited {
17133 ids: Vec<ExcerptId>,
17134 },
17135 ExcerptsExpanded {
17136 ids: Vec<ExcerptId>,
17137 },
17138 BufferEdited,
17139 Edited {
17140 transaction_id: clock::Lamport,
17141 },
17142 Reparsed(BufferId),
17143 Focused,
17144 FocusedIn,
17145 Blurred,
17146 DirtyChanged,
17147 Saved,
17148 TitleChanged,
17149 DiffBaseChanged,
17150 SelectionsChanged {
17151 local: bool,
17152 },
17153 ScrollPositionChanged {
17154 local: bool,
17155 autoscroll: bool,
17156 },
17157 Closed,
17158 TransactionUndone {
17159 transaction_id: clock::Lamport,
17160 },
17161 TransactionBegun {
17162 transaction_id: clock::Lamport,
17163 },
17164 Reloaded,
17165 CursorShapeChanged,
17166}
17167
17168impl EventEmitter<EditorEvent> for Editor {}
17169
17170impl Focusable for Editor {
17171 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17172 self.focus_handle.clone()
17173 }
17174}
17175
17176impl Render for Editor {
17177 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17178 let settings = ThemeSettings::get_global(cx);
17179
17180 let mut text_style = match self.mode {
17181 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17182 color: cx.theme().colors().editor_foreground,
17183 font_family: settings.ui_font.family.clone(),
17184 font_features: settings.ui_font.features.clone(),
17185 font_fallbacks: settings.ui_font.fallbacks.clone(),
17186 font_size: rems(0.875).into(),
17187 font_weight: settings.ui_font.weight,
17188 line_height: relative(settings.buffer_line_height.value()),
17189 ..Default::default()
17190 },
17191 EditorMode::Full => TextStyle {
17192 color: cx.theme().colors().editor_foreground,
17193 font_family: settings.buffer_font.family.clone(),
17194 font_features: settings.buffer_font.features.clone(),
17195 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17196 font_size: settings.buffer_font_size(cx).into(),
17197 font_weight: settings.buffer_font.weight,
17198 line_height: relative(settings.buffer_line_height.value()),
17199 ..Default::default()
17200 },
17201 };
17202 if let Some(text_style_refinement) = &self.text_style_refinement {
17203 text_style.refine(text_style_refinement)
17204 }
17205
17206 let background = match self.mode {
17207 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17208 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17209 EditorMode::Full => cx.theme().colors().editor_background,
17210 };
17211
17212 EditorElement::new(
17213 &cx.entity(),
17214 EditorStyle {
17215 background,
17216 local_player: cx.theme().players().local(),
17217 text: text_style,
17218 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17219 syntax: cx.theme().syntax().clone(),
17220 status: cx.theme().status().clone(),
17221 inlay_hints_style: make_inlay_hints_style(cx),
17222 inline_completion_styles: make_suggestion_styles(cx),
17223 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17224 },
17225 )
17226 }
17227}
17228
17229impl EntityInputHandler for Editor {
17230 fn text_for_range(
17231 &mut self,
17232 range_utf16: Range<usize>,
17233 adjusted_range: &mut Option<Range<usize>>,
17234 _: &mut Window,
17235 cx: &mut Context<Self>,
17236 ) -> Option<String> {
17237 let snapshot = self.buffer.read(cx).read(cx);
17238 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17239 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17240 if (start.0..end.0) != range_utf16 {
17241 adjusted_range.replace(start.0..end.0);
17242 }
17243 Some(snapshot.text_for_range(start..end).collect())
17244 }
17245
17246 fn selected_text_range(
17247 &mut self,
17248 ignore_disabled_input: bool,
17249 _: &mut Window,
17250 cx: &mut Context<Self>,
17251 ) -> Option<UTF16Selection> {
17252 // Prevent the IME menu from appearing when holding down an alphabetic key
17253 // while input is disabled.
17254 if !ignore_disabled_input && !self.input_enabled {
17255 return None;
17256 }
17257
17258 let selection = self.selections.newest::<OffsetUtf16>(cx);
17259 let range = selection.range();
17260
17261 Some(UTF16Selection {
17262 range: range.start.0..range.end.0,
17263 reversed: selection.reversed,
17264 })
17265 }
17266
17267 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17268 let snapshot = self.buffer.read(cx).read(cx);
17269 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17270 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17271 }
17272
17273 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17274 self.clear_highlights::<InputComposition>(cx);
17275 self.ime_transaction.take();
17276 }
17277
17278 fn replace_text_in_range(
17279 &mut self,
17280 range_utf16: Option<Range<usize>>,
17281 text: &str,
17282 window: &mut Window,
17283 cx: &mut Context<Self>,
17284 ) {
17285 if !self.input_enabled {
17286 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17287 return;
17288 }
17289
17290 self.transact(window, cx, |this, window, cx| {
17291 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17292 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17293 Some(this.selection_replacement_ranges(range_utf16, cx))
17294 } else {
17295 this.marked_text_ranges(cx)
17296 };
17297
17298 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17299 let newest_selection_id = this.selections.newest_anchor().id;
17300 this.selections
17301 .all::<OffsetUtf16>(cx)
17302 .iter()
17303 .zip(ranges_to_replace.iter())
17304 .find_map(|(selection, range)| {
17305 if selection.id == newest_selection_id {
17306 Some(
17307 (range.start.0 as isize - selection.head().0 as isize)
17308 ..(range.end.0 as isize - selection.head().0 as isize),
17309 )
17310 } else {
17311 None
17312 }
17313 })
17314 });
17315
17316 cx.emit(EditorEvent::InputHandled {
17317 utf16_range_to_replace: range_to_replace,
17318 text: text.into(),
17319 });
17320
17321 if let Some(new_selected_ranges) = new_selected_ranges {
17322 this.change_selections(None, window, cx, |selections| {
17323 selections.select_ranges(new_selected_ranges)
17324 });
17325 this.backspace(&Default::default(), window, cx);
17326 }
17327
17328 this.handle_input(text, window, cx);
17329 });
17330
17331 if let Some(transaction) = self.ime_transaction {
17332 self.buffer.update(cx, |buffer, cx| {
17333 buffer.group_until_transaction(transaction, cx);
17334 });
17335 }
17336
17337 self.unmark_text(window, cx);
17338 }
17339
17340 fn replace_and_mark_text_in_range(
17341 &mut self,
17342 range_utf16: Option<Range<usize>>,
17343 text: &str,
17344 new_selected_range_utf16: Option<Range<usize>>,
17345 window: &mut Window,
17346 cx: &mut Context<Self>,
17347 ) {
17348 if !self.input_enabled {
17349 return;
17350 }
17351
17352 let transaction = self.transact(window, cx, |this, window, cx| {
17353 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17354 let snapshot = this.buffer.read(cx).read(cx);
17355 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17356 for marked_range in &mut marked_ranges {
17357 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17358 marked_range.start.0 += relative_range_utf16.start;
17359 marked_range.start =
17360 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17361 marked_range.end =
17362 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17363 }
17364 }
17365 Some(marked_ranges)
17366 } else if let Some(range_utf16) = range_utf16 {
17367 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17368 Some(this.selection_replacement_ranges(range_utf16, cx))
17369 } else {
17370 None
17371 };
17372
17373 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17374 let newest_selection_id = this.selections.newest_anchor().id;
17375 this.selections
17376 .all::<OffsetUtf16>(cx)
17377 .iter()
17378 .zip(ranges_to_replace.iter())
17379 .find_map(|(selection, range)| {
17380 if selection.id == newest_selection_id {
17381 Some(
17382 (range.start.0 as isize - selection.head().0 as isize)
17383 ..(range.end.0 as isize - selection.head().0 as isize),
17384 )
17385 } else {
17386 None
17387 }
17388 })
17389 });
17390
17391 cx.emit(EditorEvent::InputHandled {
17392 utf16_range_to_replace: range_to_replace,
17393 text: text.into(),
17394 });
17395
17396 if let Some(ranges) = ranges_to_replace {
17397 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17398 }
17399
17400 let marked_ranges = {
17401 let snapshot = this.buffer.read(cx).read(cx);
17402 this.selections
17403 .disjoint_anchors()
17404 .iter()
17405 .map(|selection| {
17406 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17407 })
17408 .collect::<Vec<_>>()
17409 };
17410
17411 if text.is_empty() {
17412 this.unmark_text(window, cx);
17413 } else {
17414 this.highlight_text::<InputComposition>(
17415 marked_ranges.clone(),
17416 HighlightStyle {
17417 underline: Some(UnderlineStyle {
17418 thickness: px(1.),
17419 color: None,
17420 wavy: false,
17421 }),
17422 ..Default::default()
17423 },
17424 cx,
17425 );
17426 }
17427
17428 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17429 let use_autoclose = this.use_autoclose;
17430 let use_auto_surround = this.use_auto_surround;
17431 this.set_use_autoclose(false);
17432 this.set_use_auto_surround(false);
17433 this.handle_input(text, window, cx);
17434 this.set_use_autoclose(use_autoclose);
17435 this.set_use_auto_surround(use_auto_surround);
17436
17437 if let Some(new_selected_range) = new_selected_range_utf16 {
17438 let snapshot = this.buffer.read(cx).read(cx);
17439 let new_selected_ranges = marked_ranges
17440 .into_iter()
17441 .map(|marked_range| {
17442 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17443 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17444 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17445 snapshot.clip_offset_utf16(new_start, Bias::Left)
17446 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17447 })
17448 .collect::<Vec<_>>();
17449
17450 drop(snapshot);
17451 this.change_selections(None, window, cx, |selections| {
17452 selections.select_ranges(new_selected_ranges)
17453 });
17454 }
17455 });
17456
17457 self.ime_transaction = self.ime_transaction.or(transaction);
17458 if let Some(transaction) = self.ime_transaction {
17459 self.buffer.update(cx, |buffer, cx| {
17460 buffer.group_until_transaction(transaction, cx);
17461 });
17462 }
17463
17464 if self.text_highlights::<InputComposition>(cx).is_none() {
17465 self.ime_transaction.take();
17466 }
17467 }
17468
17469 fn bounds_for_range(
17470 &mut self,
17471 range_utf16: Range<usize>,
17472 element_bounds: gpui::Bounds<Pixels>,
17473 window: &mut Window,
17474 cx: &mut Context<Self>,
17475 ) -> Option<gpui::Bounds<Pixels>> {
17476 let text_layout_details = self.text_layout_details(window);
17477 let gpui::Size {
17478 width: em_width,
17479 height: line_height,
17480 } = self.character_size(window);
17481
17482 let snapshot = self.snapshot(window, cx);
17483 let scroll_position = snapshot.scroll_position();
17484 let scroll_left = scroll_position.x * em_width;
17485
17486 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17487 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17488 + self.gutter_dimensions.width
17489 + self.gutter_dimensions.margin;
17490 let y = line_height * (start.row().as_f32() - scroll_position.y);
17491
17492 Some(Bounds {
17493 origin: element_bounds.origin + point(x, y),
17494 size: size(em_width, line_height),
17495 })
17496 }
17497
17498 fn character_index_for_point(
17499 &mut self,
17500 point: gpui::Point<Pixels>,
17501 _window: &mut Window,
17502 _cx: &mut Context<Self>,
17503 ) -> Option<usize> {
17504 let position_map = self.last_position_map.as_ref()?;
17505 if !position_map.text_hitbox.contains(&point) {
17506 return None;
17507 }
17508 let display_point = position_map.point_for_position(point).previous_valid;
17509 let anchor = position_map
17510 .snapshot
17511 .display_point_to_anchor(display_point, Bias::Left);
17512 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17513 Some(utf16_offset.0)
17514 }
17515}
17516
17517trait SelectionExt {
17518 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17519 fn spanned_rows(
17520 &self,
17521 include_end_if_at_line_start: bool,
17522 map: &DisplaySnapshot,
17523 ) -> Range<MultiBufferRow>;
17524}
17525
17526impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17527 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17528 let start = self
17529 .start
17530 .to_point(&map.buffer_snapshot)
17531 .to_display_point(map);
17532 let end = self
17533 .end
17534 .to_point(&map.buffer_snapshot)
17535 .to_display_point(map);
17536 if self.reversed {
17537 end..start
17538 } else {
17539 start..end
17540 }
17541 }
17542
17543 fn spanned_rows(
17544 &self,
17545 include_end_if_at_line_start: bool,
17546 map: &DisplaySnapshot,
17547 ) -> Range<MultiBufferRow> {
17548 let start = self.start.to_point(&map.buffer_snapshot);
17549 let mut end = self.end.to_point(&map.buffer_snapshot);
17550 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17551 end.row -= 1;
17552 }
17553
17554 let buffer_start = map.prev_line_boundary(start).0;
17555 let buffer_end = map.next_line_boundary(end).0;
17556 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17557 }
17558}
17559
17560impl<T: InvalidationRegion> InvalidationStack<T> {
17561 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17562 where
17563 S: Clone + ToOffset,
17564 {
17565 while let Some(region) = self.last() {
17566 let all_selections_inside_invalidation_ranges =
17567 if selections.len() == region.ranges().len() {
17568 selections
17569 .iter()
17570 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17571 .all(|(selection, invalidation_range)| {
17572 let head = selection.head().to_offset(buffer);
17573 invalidation_range.start <= head && invalidation_range.end >= head
17574 })
17575 } else {
17576 false
17577 };
17578
17579 if all_selections_inside_invalidation_ranges {
17580 break;
17581 } else {
17582 self.pop();
17583 }
17584 }
17585 }
17586}
17587
17588impl<T> Default for InvalidationStack<T> {
17589 fn default() -> Self {
17590 Self(Default::default())
17591 }
17592}
17593
17594impl<T> Deref for InvalidationStack<T> {
17595 type Target = Vec<T>;
17596
17597 fn deref(&self) -> &Self::Target {
17598 &self.0
17599 }
17600}
17601
17602impl<T> DerefMut for InvalidationStack<T> {
17603 fn deref_mut(&mut self) -> &mut Self::Target {
17604 &mut self.0
17605 }
17606}
17607
17608impl InvalidationRegion for SnippetState {
17609 fn ranges(&self) -> &[Range<Anchor>] {
17610 &self.ranges[self.active_index]
17611 }
17612}
17613
17614pub fn diagnostic_block_renderer(
17615 diagnostic: Diagnostic,
17616 max_message_rows: Option<u8>,
17617 allow_closing: bool,
17618 _is_valid: bool,
17619) -> RenderBlock {
17620 let (text_without_backticks, code_ranges) =
17621 highlight_diagnostic_message(&diagnostic, max_message_rows);
17622
17623 Arc::new(move |cx: &mut BlockContext| {
17624 let group_id: SharedString = cx.block_id.to_string().into();
17625
17626 let mut text_style = cx.window.text_style().clone();
17627 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17628 let theme_settings = ThemeSettings::get_global(cx);
17629 text_style.font_family = theme_settings.buffer_font.family.clone();
17630 text_style.font_style = theme_settings.buffer_font.style;
17631 text_style.font_features = theme_settings.buffer_font.features.clone();
17632 text_style.font_weight = theme_settings.buffer_font.weight;
17633
17634 let multi_line_diagnostic = diagnostic.message.contains('\n');
17635
17636 let buttons = |diagnostic: &Diagnostic| {
17637 if multi_line_diagnostic {
17638 v_flex()
17639 } else {
17640 h_flex()
17641 }
17642 .when(allow_closing, |div| {
17643 div.children(diagnostic.is_primary.then(|| {
17644 IconButton::new("close-block", IconName::XCircle)
17645 .icon_color(Color::Muted)
17646 .size(ButtonSize::Compact)
17647 .style(ButtonStyle::Transparent)
17648 .visible_on_hover(group_id.clone())
17649 .on_click(move |_click, window, cx| {
17650 window.dispatch_action(Box::new(Cancel), cx)
17651 })
17652 .tooltip(|window, cx| {
17653 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17654 })
17655 }))
17656 })
17657 .child(
17658 IconButton::new("copy-block", IconName::Copy)
17659 .icon_color(Color::Muted)
17660 .size(ButtonSize::Compact)
17661 .style(ButtonStyle::Transparent)
17662 .visible_on_hover(group_id.clone())
17663 .on_click({
17664 let message = diagnostic.message.clone();
17665 move |_click, _, cx| {
17666 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17667 }
17668 })
17669 .tooltip(Tooltip::text("Copy diagnostic message")),
17670 )
17671 };
17672
17673 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17674 AvailableSpace::min_size(),
17675 cx.window,
17676 cx.app,
17677 );
17678
17679 h_flex()
17680 .id(cx.block_id)
17681 .group(group_id.clone())
17682 .relative()
17683 .size_full()
17684 .block_mouse_down()
17685 .pl(cx.gutter_dimensions.width)
17686 .w(cx.max_width - cx.gutter_dimensions.full_width())
17687 .child(
17688 div()
17689 .flex()
17690 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17691 .flex_shrink(),
17692 )
17693 .child(buttons(&diagnostic))
17694 .child(div().flex().flex_shrink_0().child(
17695 StyledText::new(text_without_backticks.clone()).with_highlights(
17696 &text_style,
17697 code_ranges.iter().map(|range| {
17698 (
17699 range.clone(),
17700 HighlightStyle {
17701 font_weight: Some(FontWeight::BOLD),
17702 ..Default::default()
17703 },
17704 )
17705 }),
17706 ),
17707 ))
17708 .into_any_element()
17709 })
17710}
17711
17712fn inline_completion_edit_text(
17713 current_snapshot: &BufferSnapshot,
17714 edits: &[(Range<Anchor>, String)],
17715 edit_preview: &EditPreview,
17716 include_deletions: bool,
17717 cx: &App,
17718) -> HighlightedText {
17719 let edits = edits
17720 .iter()
17721 .map(|(anchor, text)| {
17722 (
17723 anchor.start.text_anchor..anchor.end.text_anchor,
17724 text.clone(),
17725 )
17726 })
17727 .collect::<Vec<_>>();
17728
17729 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17730}
17731
17732pub fn highlight_diagnostic_message(
17733 diagnostic: &Diagnostic,
17734 mut max_message_rows: Option<u8>,
17735) -> (SharedString, Vec<Range<usize>>) {
17736 let mut text_without_backticks = String::new();
17737 let mut code_ranges = Vec::new();
17738
17739 if let Some(source) = &diagnostic.source {
17740 text_without_backticks.push_str(source);
17741 code_ranges.push(0..source.len());
17742 text_without_backticks.push_str(": ");
17743 }
17744
17745 let mut prev_offset = 0;
17746 let mut in_code_block = false;
17747 let has_row_limit = max_message_rows.is_some();
17748 let mut newline_indices = diagnostic
17749 .message
17750 .match_indices('\n')
17751 .filter(|_| has_row_limit)
17752 .map(|(ix, _)| ix)
17753 .fuse()
17754 .peekable();
17755
17756 for (quote_ix, _) in diagnostic
17757 .message
17758 .match_indices('`')
17759 .chain([(diagnostic.message.len(), "")])
17760 {
17761 let mut first_newline_ix = None;
17762 let mut last_newline_ix = None;
17763 while let Some(newline_ix) = newline_indices.peek() {
17764 if *newline_ix < quote_ix {
17765 if first_newline_ix.is_none() {
17766 first_newline_ix = Some(*newline_ix);
17767 }
17768 last_newline_ix = Some(*newline_ix);
17769
17770 if let Some(rows_left) = &mut max_message_rows {
17771 if *rows_left == 0 {
17772 break;
17773 } else {
17774 *rows_left -= 1;
17775 }
17776 }
17777 let _ = newline_indices.next();
17778 } else {
17779 break;
17780 }
17781 }
17782 let prev_len = text_without_backticks.len();
17783 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17784 text_without_backticks.push_str(new_text);
17785 if in_code_block {
17786 code_ranges.push(prev_len..text_without_backticks.len());
17787 }
17788 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17789 in_code_block = !in_code_block;
17790 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17791 text_without_backticks.push_str("...");
17792 break;
17793 }
17794 }
17795
17796 (text_without_backticks.into(), code_ranges)
17797}
17798
17799fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17800 match severity {
17801 DiagnosticSeverity::ERROR => colors.error,
17802 DiagnosticSeverity::WARNING => colors.warning,
17803 DiagnosticSeverity::INFORMATION => colors.info,
17804 DiagnosticSeverity::HINT => colors.info,
17805 _ => colors.ignored,
17806 }
17807}
17808
17809pub fn styled_runs_for_code_label<'a>(
17810 label: &'a CodeLabel,
17811 syntax_theme: &'a theme::SyntaxTheme,
17812) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17813 let fade_out = HighlightStyle {
17814 fade_out: Some(0.35),
17815 ..Default::default()
17816 };
17817
17818 let mut prev_end = label.filter_range.end;
17819 label
17820 .runs
17821 .iter()
17822 .enumerate()
17823 .flat_map(move |(ix, (range, highlight_id))| {
17824 let style = if let Some(style) = highlight_id.style(syntax_theme) {
17825 style
17826 } else {
17827 return Default::default();
17828 };
17829 let mut muted_style = style;
17830 muted_style.highlight(fade_out);
17831
17832 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17833 if range.start >= label.filter_range.end {
17834 if range.start > prev_end {
17835 runs.push((prev_end..range.start, fade_out));
17836 }
17837 runs.push((range.clone(), muted_style));
17838 } else if range.end <= label.filter_range.end {
17839 runs.push((range.clone(), style));
17840 } else {
17841 runs.push((range.start..label.filter_range.end, style));
17842 runs.push((label.filter_range.end..range.end, muted_style));
17843 }
17844 prev_end = cmp::max(prev_end, range.end);
17845
17846 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17847 runs.push((prev_end..label.text.len(), fade_out));
17848 }
17849
17850 runs
17851 })
17852}
17853
17854pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17855 let mut prev_index = 0;
17856 let mut prev_codepoint: Option<char> = None;
17857 text.char_indices()
17858 .chain([(text.len(), '\0')])
17859 .filter_map(move |(index, codepoint)| {
17860 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17861 let is_boundary = index == text.len()
17862 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17863 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17864 if is_boundary {
17865 let chunk = &text[prev_index..index];
17866 prev_index = index;
17867 Some(chunk)
17868 } else {
17869 None
17870 }
17871 })
17872}
17873
17874pub trait RangeToAnchorExt: Sized {
17875 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17876
17877 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17878 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17879 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17880 }
17881}
17882
17883impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17884 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17885 let start_offset = self.start.to_offset(snapshot);
17886 let end_offset = self.end.to_offset(snapshot);
17887 if start_offset == end_offset {
17888 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17889 } else {
17890 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17891 }
17892 }
17893}
17894
17895pub trait RowExt {
17896 fn as_f32(&self) -> f32;
17897
17898 fn next_row(&self) -> Self;
17899
17900 fn previous_row(&self) -> Self;
17901
17902 fn minus(&self, other: Self) -> u32;
17903}
17904
17905impl RowExt for DisplayRow {
17906 fn as_f32(&self) -> f32 {
17907 self.0 as f32
17908 }
17909
17910 fn next_row(&self) -> Self {
17911 Self(self.0 + 1)
17912 }
17913
17914 fn previous_row(&self) -> Self {
17915 Self(self.0.saturating_sub(1))
17916 }
17917
17918 fn minus(&self, other: Self) -> u32 {
17919 self.0 - other.0
17920 }
17921}
17922
17923impl RowExt for MultiBufferRow {
17924 fn as_f32(&self) -> f32 {
17925 self.0 as f32
17926 }
17927
17928 fn next_row(&self) -> Self {
17929 Self(self.0 + 1)
17930 }
17931
17932 fn previous_row(&self) -> Self {
17933 Self(self.0.saturating_sub(1))
17934 }
17935
17936 fn minus(&self, other: Self) -> u32 {
17937 self.0 - other.0
17938 }
17939}
17940
17941trait RowRangeExt {
17942 type Row;
17943
17944 fn len(&self) -> usize;
17945
17946 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17947}
17948
17949impl RowRangeExt for Range<MultiBufferRow> {
17950 type Row = MultiBufferRow;
17951
17952 fn len(&self) -> usize {
17953 (self.end.0 - self.start.0) as usize
17954 }
17955
17956 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17957 (self.start.0..self.end.0).map(MultiBufferRow)
17958 }
17959}
17960
17961impl RowRangeExt for Range<DisplayRow> {
17962 type Row = DisplayRow;
17963
17964 fn len(&self) -> usize {
17965 (self.end.0 - self.start.0) as usize
17966 }
17967
17968 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17969 (self.start.0..self.end.0).map(DisplayRow)
17970 }
17971}
17972
17973/// If select range has more than one line, we
17974/// just point the cursor to range.start.
17975fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17976 if range.start.row == range.end.row {
17977 range
17978 } else {
17979 range.start..range.start
17980 }
17981}
17982pub struct KillRing(ClipboardItem);
17983impl Global for KillRing {}
17984
17985const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17986
17987fn all_edits_insertions_or_deletions(
17988 edits: &Vec<(Range<Anchor>, String)>,
17989 snapshot: &MultiBufferSnapshot,
17990) -> bool {
17991 let mut all_insertions = true;
17992 let mut all_deletions = true;
17993
17994 for (range, new_text) in edits.iter() {
17995 let range_is_empty = range.to_offset(&snapshot).is_empty();
17996 let text_is_empty = new_text.is_empty();
17997
17998 if range_is_empty != text_is_empty {
17999 if range_is_empty {
18000 all_deletions = false;
18001 } else {
18002 all_insertions = false;
18003 }
18004 } else {
18005 return false;
18006 }
18007
18008 if !all_insertions && !all_deletions {
18009 return false;
18010 }
18011 }
18012 all_insertions || all_deletions
18013}