1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
84 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Entity, EntityInputHandler,
85 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
86 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
87 ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
88 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
89 WeakEntity, WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{
101 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
102 },
103 point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
104 CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
105 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
106 TransactionId, TreeSitterOptions,
107};
108use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
109use linked_editing_ranges::refresh_linked_ranges;
110use mouse_context_menu::MouseContextMenu;
111use persistence::DB;
112pub use proposed_changes_editor::{
113 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
114};
115use similar::{ChangeTag, TextDiff};
116use std::iter::Peekable;
117use task::{ResolvedTask, TaskTemplate, TaskVariables};
118
119use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
120pub use lsp::CompletionContext;
121use lsp::{
122 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
123 LanguageServerId, LanguageServerName,
124};
125
126use language::BufferSnapshot;
127use movement::TextLayoutDetails;
128pub use multi_buffer::{
129 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
130 ToOffset, ToPoint,
131};
132use multi_buffer::{
133 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
134 ToOffsetUtf16,
135};
136use project::{
137 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
138 project_settings::{GitGutterSetting, ProjectSettings},
139 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
140 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
141};
142use rand::prelude::*;
143use rpc::{proto::*, ErrorExt};
144use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
145use selections_collection::{
146 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
147};
148use serde::{Deserialize, Serialize};
149use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
150use smallvec::SmallVec;
151use snippet::Snippet;
152use std::{
153 any::TypeId,
154 borrow::Cow,
155 cell::RefCell,
156 cmp::{self, Ordering, Reverse},
157 mem,
158 num::NonZeroU32,
159 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
160 path::{Path, PathBuf},
161 rc::Rc,
162 sync::Arc,
163 time::{Duration, Instant},
164};
165pub use sum_tree::Bias;
166use sum_tree::TreeMap;
167use text::{BufferId, OffsetUtf16, Rope};
168use theme::{
169 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
170 ThemeColors, ThemeSettings,
171};
172use ui::{
173 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
174 Tooltip,
175};
176use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
177use workspace::{
178 item::{ItemHandle, PreviewTabsSettings},
179 ItemId, RestoreOnStartupBehavior,
180};
181use workspace::{
182 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
183 WorkspaceSettings,
184};
185use workspace::{
186 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
187};
188use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
189
190use crate::hover_links::{find_url, find_url_from_range};
191use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
192
193pub const FILE_HEADER_HEIGHT: u32 = 2;
194pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
195pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
196pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
197const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
198const MAX_LINE_LEN: usize = 1024;
199const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
200const MAX_SELECTION_HISTORY_LEN: usize = 1024;
201pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
202#[doc(hidden)]
203pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
204
205pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
206pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
207
208pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
209pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
210
211const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
212 alt: true,
213 shift: true,
214 control: false,
215 platform: false,
216 function: false,
217};
218
219#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub enum InlayId {
221 InlineCompletion(usize),
222 Hint(usize),
223}
224
225impl InlayId {
226 fn id(&self) -> usize {
227 match self {
228 Self::InlineCompletion(id) => *id,
229 Self::Hint(id) => *id,
230 }
231 }
232}
233
234enum DocumentHighlightRead {}
235enum DocumentHighlightWrite {}
236enum InputComposition {}
237enum SelectedTextHighlight {}
238
239#[derive(Debug, Copy, Clone, PartialEq, Eq)]
240pub enum Navigated {
241 Yes,
242 No,
243}
244
245impl Navigated {
246 pub fn from_bool(yes: bool) -> Navigated {
247 if yes {
248 Navigated::Yes
249 } else {
250 Navigated::No
251 }
252 }
253}
254
255pub fn init_settings(cx: &mut App) {
256 EditorSettings::register(cx);
257}
258
259pub fn init(cx: &mut App) {
260 init_settings(cx);
261
262 workspace::register_project_item::<Editor>(cx);
263 workspace::FollowableViewRegistry::register::<Editor>(cx);
264 workspace::register_serializable_item::<Editor>(cx);
265
266 cx.observe_new(
267 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
268 workspace.register_action(Editor::new_file);
269 workspace.register_action(Editor::new_file_vertical);
270 workspace.register_action(Editor::new_file_horizontal);
271 workspace.register_action(Editor::cancel_language_server_work);
272 },
273 )
274 .detach();
275
276 cx.on_action(move |_: &workspace::NewFile, cx| {
277 let app_state = workspace::AppState::global(cx);
278 if let Some(app_state) = app_state.upgrade() {
279 workspace::open_new(
280 Default::default(),
281 app_state,
282 cx,
283 |workspace, window, cx| {
284 Editor::new_file(workspace, &Default::default(), window, cx)
285 },
286 )
287 .detach();
288 }
289 });
290 cx.on_action(move |_: &workspace::NewWindow, cx| {
291 let app_state = workspace::AppState::global(cx);
292 if let Some(app_state) = app_state.upgrade() {
293 workspace::open_new(
294 Default::default(),
295 app_state,
296 cx,
297 |workspace, window, cx| {
298 cx.activate(true);
299 Editor::new_file(workspace, &Default::default(), window, cx)
300 },
301 )
302 .detach();
303 }
304 });
305}
306
307pub struct SearchWithinRange;
308
309trait InvalidationRegion {
310 fn ranges(&self) -> &[Range<Anchor>];
311}
312
313#[derive(Clone, Debug, PartialEq)]
314pub enum SelectPhase {
315 Begin {
316 position: DisplayPoint,
317 add: bool,
318 click_count: usize,
319 },
320 BeginColumnar {
321 position: DisplayPoint,
322 reset: bool,
323 goal_column: u32,
324 },
325 Extend {
326 position: DisplayPoint,
327 click_count: usize,
328 },
329 Update {
330 position: DisplayPoint,
331 goal_column: u32,
332 scroll_delta: gpui::Point<f32>,
333 },
334 End,
335}
336
337#[derive(Clone, Debug)]
338pub enum SelectMode {
339 Character,
340 Word(Range<Anchor>),
341 Line(Range<Anchor>),
342 All,
343}
344
345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
346pub enum EditorMode {
347 SingleLine { auto_width: bool },
348 AutoHeight { max_lines: usize },
349 Full,
350}
351
352#[derive(Copy, Clone, Debug)]
353pub enum SoftWrap {
354 /// Prefer not to wrap at all.
355 ///
356 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
357 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
358 GitDiff,
359 /// Prefer a single line generally, unless an overly long line is encountered.
360 None,
361 /// Soft wrap lines that exceed the editor width.
362 EditorWidth,
363 /// Soft wrap lines at the preferred line length.
364 Column(u32),
365 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
366 Bounded(u32),
367}
368
369#[derive(Clone)]
370pub struct EditorStyle {
371 pub background: Hsla,
372 pub local_player: PlayerColor,
373 pub text: TextStyle,
374 pub scrollbar_width: Pixels,
375 pub syntax: Arc<SyntaxTheme>,
376 pub status: StatusColors,
377 pub inlay_hints_style: HighlightStyle,
378 pub inline_completion_styles: InlineCompletionStyles,
379 pub unnecessary_code_fade: f32,
380}
381
382impl Default for EditorStyle {
383 fn default() -> Self {
384 Self {
385 background: Hsla::default(),
386 local_player: PlayerColor::default(),
387 text: TextStyle::default(),
388 scrollbar_width: Pixels::default(),
389 syntax: Default::default(),
390 // HACK: Status colors don't have a real default.
391 // We should look into removing the status colors from the editor
392 // style and retrieve them directly from the theme.
393 status: StatusColors::dark(),
394 inlay_hints_style: HighlightStyle::default(),
395 inline_completion_styles: InlineCompletionStyles {
396 insertion: HighlightStyle::default(),
397 whitespace: HighlightStyle::default(),
398 },
399 unnecessary_code_fade: Default::default(),
400 }
401 }
402}
403
404pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
405 let show_background = language_settings::language_settings(None, None, cx)
406 .inlay_hints
407 .show_background;
408
409 HighlightStyle {
410 color: Some(cx.theme().status().hint),
411 background_color: show_background.then(|| cx.theme().status().hint_background),
412 ..HighlightStyle::default()
413 }
414}
415
416pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
417 InlineCompletionStyles {
418 insertion: HighlightStyle {
419 color: Some(cx.theme().status().predictive),
420 ..HighlightStyle::default()
421 },
422 whitespace: HighlightStyle {
423 background_color: Some(cx.theme().status().created_background),
424 ..HighlightStyle::default()
425 },
426 }
427}
428
429type CompletionId = usize;
430
431pub(crate) enum EditDisplayMode {
432 TabAccept,
433 DiffPopover,
434 Inline,
435}
436
437enum InlineCompletion {
438 Edit {
439 edits: Vec<(Range<Anchor>, String)>,
440 edit_preview: Option<EditPreview>,
441 display_mode: EditDisplayMode,
442 snapshot: BufferSnapshot,
443 },
444 Move {
445 target: Anchor,
446 snapshot: BufferSnapshot,
447 },
448}
449
450struct InlineCompletionState {
451 inlay_ids: Vec<InlayId>,
452 completion: InlineCompletion,
453 completion_id: Option<SharedString>,
454 invalidation_range: Range<Anchor>,
455}
456
457enum EditPredictionSettings {
458 Disabled,
459 Enabled {
460 show_in_menu: bool,
461 preview_requires_modifier: bool,
462 },
463}
464
465enum InlineCompletionHighlight {}
466
467pub enum MenuInlineCompletionsPolicy {
468 Never,
469 ByProvider,
470}
471
472pub enum EditPredictionPreview {
473 /// Modifier is not pressed
474 Inactive,
475 /// Modifier pressed
476 Active {
477 previous_scroll_position: Option<ScrollAnchor>,
478 },
479}
480
481#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
482struct EditorActionId(usize);
483
484impl EditorActionId {
485 pub fn post_inc(&mut self) -> Self {
486 let answer = self.0;
487
488 *self = Self(answer + 1);
489
490 Self(answer)
491 }
492}
493
494// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
495// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
496
497type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
498type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
499
500#[derive(Default)]
501struct ScrollbarMarkerState {
502 scrollbar_size: Size<Pixels>,
503 dirty: bool,
504 markers: Arc<[PaintQuad]>,
505 pending_refresh: Option<Task<Result<()>>>,
506}
507
508impl ScrollbarMarkerState {
509 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
510 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
511 }
512}
513
514#[derive(Clone, Debug)]
515struct RunnableTasks {
516 templates: Vec<(TaskSourceKind, TaskTemplate)>,
517 offset: MultiBufferOffset,
518 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
519 column: u32,
520 // Values of all named captures, including those starting with '_'
521 extra_variables: HashMap<String, String>,
522 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
523 context_range: Range<BufferOffset>,
524}
525
526impl RunnableTasks {
527 fn resolve<'a>(
528 &'a self,
529 cx: &'a task::TaskContext,
530 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
531 self.templates.iter().filter_map(|(kind, template)| {
532 template
533 .resolve_task(&kind.to_id_base(), cx)
534 .map(|task| (kind.clone(), task))
535 })
536 }
537}
538
539#[derive(Clone)]
540struct ResolvedTasks {
541 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
542 position: Anchor,
543}
544#[derive(Copy, Clone, Debug)]
545struct MultiBufferOffset(usize);
546#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
547struct BufferOffset(usize);
548
549// Addons allow storing per-editor state in other crates (e.g. Vim)
550pub trait Addon: 'static {
551 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
552
553 fn render_buffer_header_controls(
554 &self,
555 _: &ExcerptInfo,
556 _: &Window,
557 _: &App,
558 ) -> Option<AnyElement> {
559 None
560 }
561
562 fn to_any(&self) -> &dyn std::any::Any;
563}
564
565#[derive(Debug, Copy, Clone, PartialEq, Eq)]
566pub enum IsVimMode {
567 Yes,
568 No,
569}
570
571/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
572///
573/// See the [module level documentation](self) for more information.
574pub struct Editor {
575 focus_handle: FocusHandle,
576 last_focused_descendant: Option<WeakFocusHandle>,
577 /// The text buffer being edited
578 buffer: Entity<MultiBuffer>,
579 /// Map of how text in the buffer should be displayed.
580 /// Handles soft wraps, folds, fake inlay text insertions, etc.
581 pub display_map: Entity<DisplayMap>,
582 pub selections: SelectionsCollection,
583 pub scroll_manager: ScrollManager,
584 /// When inline assist editors are linked, they all render cursors because
585 /// typing enters text into each of them, even the ones that aren't focused.
586 pub(crate) show_cursor_when_unfocused: bool,
587 columnar_selection_tail: Option<Anchor>,
588 add_selections_state: Option<AddSelectionsState>,
589 select_next_state: Option<SelectNextState>,
590 select_prev_state: Option<SelectNextState>,
591 selection_history: SelectionHistory,
592 autoclose_regions: Vec<AutocloseRegion>,
593 snippet_stack: InvalidationStack<SnippetState>,
594 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
595 ime_transaction: Option<TransactionId>,
596 active_diagnostics: Option<ActiveDiagnosticGroup>,
597 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
598
599 // TODO: make this a access method
600 pub project: Option<Entity<Project>>,
601 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
602 completion_provider: Option<Box<dyn CompletionProvider>>,
603 collaboration_hub: Option<Box<dyn CollaborationHub>>,
604 blink_manager: Entity<BlinkManager>,
605 show_cursor_names: bool,
606 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
607 pub show_local_selections: bool,
608 mode: EditorMode,
609 show_breadcrumbs: bool,
610 show_gutter: bool,
611 show_scrollbars: bool,
612 show_line_numbers: Option<bool>,
613 use_relative_line_numbers: Option<bool>,
614 show_git_diff_gutter: Option<bool>,
615 show_code_actions: Option<bool>,
616 show_runnables: Option<bool>,
617 show_wrap_guides: Option<bool>,
618 show_indent_guides: Option<bool>,
619 placeholder_text: Option<Arc<str>>,
620 highlight_order: usize,
621 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
622 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
623 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
624 scrollbar_marker_state: ScrollbarMarkerState,
625 active_indent_guides_state: ActiveIndentGuidesState,
626 nav_history: Option<ItemNavHistory>,
627 context_menu: RefCell<Option<CodeContextMenu>>,
628 mouse_context_menu: Option<MouseContextMenu>,
629 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
630 signature_help_state: SignatureHelpState,
631 auto_signature_help: Option<bool>,
632 find_all_references_task_sources: Vec<Anchor>,
633 next_completion_id: CompletionId,
634 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
635 code_actions_task: Option<Task<Result<()>>>,
636 selection_highlight_task: Option<Task<()>>,
637 document_highlights_task: Option<Task<()>>,
638 linked_editing_range_task: Option<Task<Option<()>>>,
639 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
640 pending_rename: Option<RenameState>,
641 searchable: bool,
642 cursor_shape: CursorShape,
643 current_line_highlight: Option<CurrentLineHighlight>,
644 collapse_matches: bool,
645 autoindent_mode: Option<AutoindentMode>,
646 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
647 input_enabled: bool,
648 use_modal_editing: bool,
649 read_only: bool,
650 leader_peer_id: Option<PeerId>,
651 remote_id: Option<ViewId>,
652 hover_state: HoverState,
653 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
654 gutter_hovered: bool,
655 hovered_link_state: Option<HoveredLinkState>,
656 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
657 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
658 active_inline_completion: Option<InlineCompletionState>,
659 /// Used to prevent flickering as the user types while the menu is open
660 stale_inline_completion_in_menu: Option<InlineCompletionState>,
661 edit_prediction_settings: EditPredictionSettings,
662 inline_completions_hidden_for_vim_mode: bool,
663 show_inline_completions_override: Option<bool>,
664 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
665 edit_prediction_preview: EditPredictionPreview,
666 edit_prediction_cursor_on_leading_whitespace: bool,
667 edit_prediction_requires_modifier_in_leading_space: bool,
668 inlay_hint_cache: InlayHintCache,
669 next_inlay_id: usize,
670 _subscriptions: Vec<Subscription>,
671 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
672 gutter_dimensions: GutterDimensions,
673 style: Option<EditorStyle>,
674 text_style_refinement: Option<TextStyleRefinement>,
675 next_editor_action_id: EditorActionId,
676 editor_actions:
677 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
678 use_autoclose: bool,
679 use_auto_surround: bool,
680 auto_replace_emoji_shortcode: bool,
681 show_git_blame_gutter: bool,
682 show_git_blame_inline: bool,
683 show_git_blame_inline_delay_task: Option<Task<()>>,
684 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
685 distinguish_unstaged_diff_hunks: bool,
686 git_blame_inline_enabled: bool,
687 serialize_dirty_buffers: bool,
688 show_selection_menu: Option<bool>,
689 blame: Option<Entity<GitBlame>>,
690 blame_subscription: Option<Subscription>,
691 custom_context_menu: Option<
692 Box<
693 dyn 'static
694 + Fn(
695 &mut Self,
696 DisplayPoint,
697 &mut Window,
698 &mut Context<Self>,
699 ) -> Option<Entity<ui::ContextMenu>>,
700 >,
701 >,
702 last_bounds: Option<Bounds<Pixels>>,
703 last_position_map: Option<Rc<PositionMap>>,
704 expect_bounds_change: Option<Bounds<Pixels>>,
705 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
706 tasks_update_task: Option<Task<()>>,
707 in_project_search: bool,
708 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
709 breadcrumb_header: Option<String>,
710 focused_block: Option<FocusedBlock>,
711 next_scroll_position: NextScrollCursorCenterTopBottom,
712 addons: HashMap<TypeId, Box<dyn Addon>>,
713 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
714 load_diff_task: Option<Shared<Task<()>>>,
715 selection_mark_mode: bool,
716 toggle_fold_multiple_buffers: Task<()>,
717 _scroll_cursor_center_top_bottom_task: Task<()>,
718 serialize_selections: Task<()>,
719}
720
721#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
722enum NextScrollCursorCenterTopBottom {
723 #[default]
724 Center,
725 Top,
726 Bottom,
727}
728
729impl NextScrollCursorCenterTopBottom {
730 fn next(&self) -> Self {
731 match self {
732 Self::Center => Self::Top,
733 Self::Top => Self::Bottom,
734 Self::Bottom => Self::Center,
735 }
736 }
737}
738
739#[derive(Clone)]
740pub struct EditorSnapshot {
741 pub mode: EditorMode,
742 show_gutter: bool,
743 show_line_numbers: Option<bool>,
744 show_git_diff_gutter: Option<bool>,
745 show_code_actions: Option<bool>,
746 show_runnables: Option<bool>,
747 git_blame_gutter_max_author_length: Option<usize>,
748 pub display_snapshot: DisplaySnapshot,
749 pub placeholder_text: Option<Arc<str>>,
750 is_focused: bool,
751 scroll_anchor: ScrollAnchor,
752 ongoing_scroll: OngoingScroll,
753 current_line_highlight: CurrentLineHighlight,
754 gutter_hovered: bool,
755}
756
757const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
758
759#[derive(Default, Debug, Clone, Copy)]
760pub struct GutterDimensions {
761 pub left_padding: Pixels,
762 pub right_padding: Pixels,
763 pub width: Pixels,
764 pub margin: Pixels,
765 pub git_blame_entries_width: Option<Pixels>,
766}
767
768impl GutterDimensions {
769 /// The full width of the space taken up by the gutter.
770 pub fn full_width(&self) -> Pixels {
771 self.margin + self.width
772 }
773
774 /// The width of the space reserved for the fold indicators,
775 /// use alongside 'justify_end' and `gutter_width` to
776 /// right align content with the line numbers
777 pub fn fold_area_width(&self) -> Pixels {
778 self.margin + self.right_padding
779 }
780}
781
782#[derive(Debug)]
783pub struct RemoteSelection {
784 pub replica_id: ReplicaId,
785 pub selection: Selection<Anchor>,
786 pub cursor_shape: CursorShape,
787 pub peer_id: PeerId,
788 pub line_mode: bool,
789 pub participant_index: Option<ParticipantIndex>,
790 pub user_name: Option<SharedString>,
791}
792
793#[derive(Clone, Debug)]
794struct SelectionHistoryEntry {
795 selections: Arc<[Selection<Anchor>]>,
796 select_next_state: Option<SelectNextState>,
797 select_prev_state: Option<SelectNextState>,
798 add_selections_state: Option<AddSelectionsState>,
799}
800
801enum SelectionHistoryMode {
802 Normal,
803 Undoing,
804 Redoing,
805}
806
807#[derive(Clone, PartialEq, Eq, Hash)]
808struct HoveredCursor {
809 replica_id: u16,
810 selection_id: usize,
811}
812
813impl Default for SelectionHistoryMode {
814 fn default() -> Self {
815 Self::Normal
816 }
817}
818
819#[derive(Default)]
820struct SelectionHistory {
821 #[allow(clippy::type_complexity)]
822 selections_by_transaction:
823 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
824 mode: SelectionHistoryMode,
825 undo_stack: VecDeque<SelectionHistoryEntry>,
826 redo_stack: VecDeque<SelectionHistoryEntry>,
827}
828
829impl SelectionHistory {
830 fn insert_transaction(
831 &mut self,
832 transaction_id: TransactionId,
833 selections: Arc<[Selection<Anchor>]>,
834 ) {
835 self.selections_by_transaction
836 .insert(transaction_id, (selections, None));
837 }
838
839 #[allow(clippy::type_complexity)]
840 fn transaction(
841 &self,
842 transaction_id: TransactionId,
843 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
844 self.selections_by_transaction.get(&transaction_id)
845 }
846
847 #[allow(clippy::type_complexity)]
848 fn transaction_mut(
849 &mut self,
850 transaction_id: TransactionId,
851 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
852 self.selections_by_transaction.get_mut(&transaction_id)
853 }
854
855 fn push(&mut self, entry: SelectionHistoryEntry) {
856 if !entry.selections.is_empty() {
857 match self.mode {
858 SelectionHistoryMode::Normal => {
859 self.push_undo(entry);
860 self.redo_stack.clear();
861 }
862 SelectionHistoryMode::Undoing => self.push_redo(entry),
863 SelectionHistoryMode::Redoing => self.push_undo(entry),
864 }
865 }
866 }
867
868 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
869 if self
870 .undo_stack
871 .back()
872 .map_or(true, |e| e.selections != entry.selections)
873 {
874 self.undo_stack.push_back(entry);
875 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
876 self.undo_stack.pop_front();
877 }
878 }
879 }
880
881 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
882 if self
883 .redo_stack
884 .back()
885 .map_or(true, |e| e.selections != entry.selections)
886 {
887 self.redo_stack.push_back(entry);
888 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
889 self.redo_stack.pop_front();
890 }
891 }
892 }
893}
894
895struct RowHighlight {
896 index: usize,
897 range: Range<Anchor>,
898 color: Hsla,
899 should_autoscroll: bool,
900}
901
902#[derive(Clone, Debug)]
903struct AddSelectionsState {
904 above: bool,
905 stack: Vec<usize>,
906}
907
908#[derive(Clone)]
909struct SelectNextState {
910 query: AhoCorasick,
911 wordwise: bool,
912 done: bool,
913}
914
915impl std::fmt::Debug for SelectNextState {
916 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
917 f.debug_struct(std::any::type_name::<Self>())
918 .field("wordwise", &self.wordwise)
919 .field("done", &self.done)
920 .finish()
921 }
922}
923
924#[derive(Debug)]
925struct AutocloseRegion {
926 selection_id: usize,
927 range: Range<Anchor>,
928 pair: BracketPair,
929}
930
931#[derive(Debug)]
932struct SnippetState {
933 ranges: Vec<Vec<Range<Anchor>>>,
934 active_index: usize,
935 choices: Vec<Option<Vec<String>>>,
936}
937
938#[doc(hidden)]
939pub struct RenameState {
940 pub range: Range<Anchor>,
941 pub old_name: Arc<str>,
942 pub editor: Entity<Editor>,
943 block_id: CustomBlockId,
944}
945
946struct InvalidationStack<T>(Vec<T>);
947
948struct RegisteredInlineCompletionProvider {
949 provider: Arc<dyn InlineCompletionProviderHandle>,
950 _subscription: Subscription,
951}
952
953#[derive(Debug)]
954struct ActiveDiagnosticGroup {
955 primary_range: Range<Anchor>,
956 primary_message: String,
957 group_id: usize,
958 blocks: HashMap<CustomBlockId, Diagnostic>,
959 is_valid: bool,
960}
961
962#[derive(Serialize, Deserialize, Clone, Debug)]
963pub struct ClipboardSelection {
964 pub len: usize,
965 pub is_entire_line: bool,
966 pub first_line_indent: u32,
967}
968
969#[derive(Debug)]
970pub(crate) struct NavigationData {
971 cursor_anchor: Anchor,
972 cursor_position: Point,
973 scroll_anchor: ScrollAnchor,
974 scroll_top_row: u32,
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
978pub enum GotoDefinitionKind {
979 Symbol,
980 Declaration,
981 Type,
982 Implementation,
983}
984
985#[derive(Debug, Clone)]
986enum InlayHintRefreshReason {
987 Toggle(bool),
988 SettingsChange(InlayHintSettings),
989 NewLinesShown,
990 BufferEdited(HashSet<Arc<Language>>),
991 RefreshRequested,
992 ExcerptsRemoved(Vec<ExcerptId>),
993}
994
995impl InlayHintRefreshReason {
996 fn description(&self) -> &'static str {
997 match self {
998 Self::Toggle(_) => "toggle",
999 Self::SettingsChange(_) => "settings change",
1000 Self::NewLinesShown => "new lines shown",
1001 Self::BufferEdited(_) => "buffer edited",
1002 Self::RefreshRequested => "refresh requested",
1003 Self::ExcerptsRemoved(_) => "excerpts removed",
1004 }
1005 }
1006}
1007
1008pub enum FormatTarget {
1009 Buffers,
1010 Ranges(Vec<Range<MultiBufferPoint>>),
1011}
1012
1013pub(crate) struct FocusedBlock {
1014 id: BlockId,
1015 focus_handle: WeakFocusHandle,
1016}
1017
1018#[derive(Clone)]
1019enum JumpData {
1020 MultiBufferRow {
1021 row: MultiBufferRow,
1022 line_offset_from_top: u32,
1023 },
1024 MultiBufferPoint {
1025 excerpt_id: ExcerptId,
1026 position: Point,
1027 anchor: text::Anchor,
1028 line_offset_from_top: u32,
1029 },
1030}
1031
1032pub enum MultibufferSelectionMode {
1033 First,
1034 All,
1035}
1036
1037impl Editor {
1038 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1039 let buffer = cx.new(|cx| Buffer::local("", cx));
1040 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1041 Self::new(
1042 EditorMode::SingleLine { auto_width: false },
1043 buffer,
1044 None,
1045 false,
1046 window,
1047 cx,
1048 )
1049 }
1050
1051 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1052 let buffer = cx.new(|cx| Buffer::local("", cx));
1053 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1054 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1055 }
1056
1057 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1058 let buffer = cx.new(|cx| Buffer::local("", cx));
1059 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1060 Self::new(
1061 EditorMode::SingleLine { auto_width: true },
1062 buffer,
1063 None,
1064 false,
1065 window,
1066 cx,
1067 )
1068 }
1069
1070 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1071 let buffer = cx.new(|cx| Buffer::local("", cx));
1072 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1073 Self::new(
1074 EditorMode::AutoHeight { max_lines },
1075 buffer,
1076 None,
1077 false,
1078 window,
1079 cx,
1080 )
1081 }
1082
1083 pub fn for_buffer(
1084 buffer: Entity<Buffer>,
1085 project: Option<Entity<Project>>,
1086 window: &mut Window,
1087 cx: &mut Context<Self>,
1088 ) -> Self {
1089 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1090 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1091 }
1092
1093 pub fn for_multibuffer(
1094 buffer: Entity<MultiBuffer>,
1095 project: Option<Entity<Project>>,
1096 show_excerpt_controls: bool,
1097 window: &mut Window,
1098 cx: &mut Context<Self>,
1099 ) -> Self {
1100 Self::new(
1101 EditorMode::Full,
1102 buffer,
1103 project,
1104 show_excerpt_controls,
1105 window,
1106 cx,
1107 )
1108 }
1109
1110 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1111 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1112 let mut clone = Self::new(
1113 self.mode,
1114 self.buffer.clone(),
1115 self.project.clone(),
1116 show_excerpt_controls,
1117 window,
1118 cx,
1119 );
1120 self.display_map.update(cx, |display_map, cx| {
1121 let snapshot = display_map.snapshot(cx);
1122 clone.display_map.update(cx, |display_map, cx| {
1123 display_map.set_state(&snapshot, cx);
1124 });
1125 });
1126 clone.selections.clone_state(&self.selections);
1127 clone.scroll_manager.clone_state(&self.scroll_manager);
1128 clone.searchable = self.searchable;
1129 clone
1130 }
1131
1132 pub fn new(
1133 mode: EditorMode,
1134 buffer: Entity<MultiBuffer>,
1135 project: Option<Entity<Project>>,
1136 show_excerpt_controls: bool,
1137 window: &mut Window,
1138 cx: &mut Context<Self>,
1139 ) -> Self {
1140 let style = window.text_style();
1141 let font_size = style.font_size.to_pixels(window.rem_size());
1142 let editor = cx.entity().downgrade();
1143 let fold_placeholder = FoldPlaceholder {
1144 constrain_width: true,
1145 render: Arc::new(move |fold_id, fold_range, _, cx| {
1146 let editor = editor.clone();
1147 div()
1148 .id(fold_id)
1149 .bg(cx.theme().colors().ghost_element_background)
1150 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1151 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1152 .rounded_sm()
1153 .size_full()
1154 .cursor_pointer()
1155 .child("⋯")
1156 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1157 .on_click(move |_, _window, cx| {
1158 editor
1159 .update(cx, |editor, cx| {
1160 editor.unfold_ranges(
1161 &[fold_range.start..fold_range.end],
1162 true,
1163 false,
1164 cx,
1165 );
1166 cx.stop_propagation();
1167 })
1168 .ok();
1169 })
1170 .into_any()
1171 }),
1172 merge_adjacent: true,
1173 ..Default::default()
1174 };
1175 let display_map = cx.new(|cx| {
1176 DisplayMap::new(
1177 buffer.clone(),
1178 style.font(),
1179 font_size,
1180 None,
1181 show_excerpt_controls,
1182 FILE_HEADER_HEIGHT,
1183 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1184 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1185 fold_placeholder,
1186 cx,
1187 )
1188 });
1189
1190 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1191
1192 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1193
1194 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1195 .then(|| language_settings::SoftWrap::None);
1196
1197 let mut project_subscriptions = Vec::new();
1198 if mode == EditorMode::Full {
1199 if let Some(project) = project.as_ref() {
1200 if buffer.read(cx).is_singleton() {
1201 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1202 cx.emit(EditorEvent::TitleChanged);
1203 }));
1204 }
1205 project_subscriptions.push(cx.subscribe_in(
1206 project,
1207 window,
1208 |editor, _, event, window, cx| {
1209 if let project::Event::RefreshInlayHints = event {
1210 editor
1211 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1212 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1213 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1214 let focus_handle = editor.focus_handle(cx);
1215 if focus_handle.is_focused(window) {
1216 let snapshot = buffer.read(cx).snapshot();
1217 for (range, snippet) in snippet_edits {
1218 let editor_range =
1219 language::range_from_lsp(*range).to_offset(&snapshot);
1220 editor
1221 .insert_snippet(
1222 &[editor_range],
1223 snippet.clone(),
1224 window,
1225 cx,
1226 )
1227 .ok();
1228 }
1229 }
1230 }
1231 }
1232 },
1233 ));
1234 if let Some(task_inventory) = project
1235 .read(cx)
1236 .task_store()
1237 .read(cx)
1238 .task_inventory()
1239 .cloned()
1240 {
1241 project_subscriptions.push(cx.observe_in(
1242 &task_inventory,
1243 window,
1244 |editor, _, window, cx| {
1245 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1246 },
1247 ));
1248 }
1249 }
1250 }
1251
1252 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1253
1254 let inlay_hint_settings =
1255 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1256 let focus_handle = cx.focus_handle();
1257 cx.on_focus(&focus_handle, window, Self::handle_focus)
1258 .detach();
1259 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1260 .detach();
1261 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1262 .detach();
1263 cx.on_blur(&focus_handle, window, Self::handle_blur)
1264 .detach();
1265
1266 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1267 Some(false)
1268 } else {
1269 None
1270 };
1271
1272 let mut code_action_providers = Vec::new();
1273 let mut load_uncommitted_diff = None;
1274 if let Some(project) = project.clone() {
1275 load_uncommitted_diff = Some(
1276 get_uncommitted_diff_for_buffer(
1277 &project,
1278 buffer.read(cx).all_buffers(),
1279 buffer.clone(),
1280 cx,
1281 )
1282 .shared(),
1283 );
1284 code_action_providers.push(Rc::new(project) as Rc<_>);
1285 }
1286
1287 let mut this = Self {
1288 focus_handle,
1289 show_cursor_when_unfocused: false,
1290 last_focused_descendant: None,
1291 buffer: buffer.clone(),
1292 display_map: display_map.clone(),
1293 selections,
1294 scroll_manager: ScrollManager::new(cx),
1295 columnar_selection_tail: None,
1296 add_selections_state: None,
1297 select_next_state: None,
1298 select_prev_state: None,
1299 selection_history: Default::default(),
1300 autoclose_regions: Default::default(),
1301 snippet_stack: Default::default(),
1302 select_larger_syntax_node_stack: Vec::new(),
1303 ime_transaction: Default::default(),
1304 active_diagnostics: None,
1305 soft_wrap_mode_override,
1306 completion_provider: project.clone().map(|project| Box::new(project) as _),
1307 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1308 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1309 project,
1310 blink_manager: blink_manager.clone(),
1311 show_local_selections: true,
1312 show_scrollbars: true,
1313 mode,
1314 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1315 show_gutter: mode == EditorMode::Full,
1316 show_line_numbers: None,
1317 use_relative_line_numbers: None,
1318 show_git_diff_gutter: None,
1319 show_code_actions: None,
1320 show_runnables: None,
1321 show_wrap_guides: None,
1322 show_indent_guides,
1323 placeholder_text: None,
1324 highlight_order: 0,
1325 highlighted_rows: HashMap::default(),
1326 background_highlights: Default::default(),
1327 gutter_highlights: TreeMap::default(),
1328 scrollbar_marker_state: ScrollbarMarkerState::default(),
1329 active_indent_guides_state: ActiveIndentGuidesState::default(),
1330 nav_history: None,
1331 context_menu: RefCell::new(None),
1332 mouse_context_menu: None,
1333 completion_tasks: Default::default(),
1334 signature_help_state: SignatureHelpState::default(),
1335 auto_signature_help: None,
1336 find_all_references_task_sources: Vec::new(),
1337 next_completion_id: 0,
1338 next_inlay_id: 0,
1339 code_action_providers,
1340 available_code_actions: Default::default(),
1341 code_actions_task: Default::default(),
1342 selection_highlight_task: Default::default(),
1343 document_highlights_task: Default::default(),
1344 linked_editing_range_task: Default::default(),
1345 pending_rename: Default::default(),
1346 searchable: true,
1347 cursor_shape: EditorSettings::get_global(cx)
1348 .cursor_shape
1349 .unwrap_or_default(),
1350 current_line_highlight: None,
1351 autoindent_mode: Some(AutoindentMode::EachLine),
1352 collapse_matches: false,
1353 workspace: None,
1354 input_enabled: true,
1355 use_modal_editing: mode == EditorMode::Full,
1356 read_only: false,
1357 use_autoclose: true,
1358 use_auto_surround: true,
1359 auto_replace_emoji_shortcode: false,
1360 leader_peer_id: None,
1361 remote_id: None,
1362 hover_state: Default::default(),
1363 pending_mouse_down: None,
1364 hovered_link_state: Default::default(),
1365 edit_prediction_provider: None,
1366 active_inline_completion: None,
1367 stale_inline_completion_in_menu: None,
1368 edit_prediction_preview: EditPredictionPreview::Inactive,
1369 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1370
1371 gutter_hovered: false,
1372 pixel_position_of_newest_cursor: None,
1373 last_bounds: None,
1374 last_position_map: None,
1375 expect_bounds_change: None,
1376 gutter_dimensions: GutterDimensions::default(),
1377 style: None,
1378 show_cursor_names: false,
1379 hovered_cursors: Default::default(),
1380 next_editor_action_id: EditorActionId::default(),
1381 editor_actions: Rc::default(),
1382 inline_completions_hidden_for_vim_mode: false,
1383 show_inline_completions_override: None,
1384 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1385 edit_prediction_settings: EditPredictionSettings::Disabled,
1386 edit_prediction_cursor_on_leading_whitespace: false,
1387 edit_prediction_requires_modifier_in_leading_space: true,
1388 custom_context_menu: None,
1389 show_git_blame_gutter: false,
1390 show_git_blame_inline: false,
1391 distinguish_unstaged_diff_hunks: false,
1392 show_selection_menu: None,
1393 show_git_blame_inline_delay_task: None,
1394 git_blame_inline_tooltip: None,
1395 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1396 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1397 .session
1398 .restore_unsaved_buffers,
1399 blame: None,
1400 blame_subscription: None,
1401 tasks: Default::default(),
1402 _subscriptions: vec![
1403 cx.observe(&buffer, Self::on_buffer_changed),
1404 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1405 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1406 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1407 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1408 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1409 cx.observe_window_activation(window, |editor, window, cx| {
1410 let active = window.is_window_active();
1411 editor.blink_manager.update(cx, |blink_manager, cx| {
1412 if active {
1413 blink_manager.enable(cx);
1414 } else {
1415 blink_manager.disable(cx);
1416 }
1417 });
1418 }),
1419 ],
1420 tasks_update_task: None,
1421 linked_edit_ranges: Default::default(),
1422 in_project_search: false,
1423 previous_search_ranges: None,
1424 breadcrumb_header: None,
1425 focused_block: None,
1426 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1427 addons: HashMap::default(),
1428 registered_buffers: HashMap::default(),
1429 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1430 selection_mark_mode: false,
1431 toggle_fold_multiple_buffers: Task::ready(()),
1432 serialize_selections: Task::ready(()),
1433 text_style_refinement: None,
1434 load_diff_task: load_uncommitted_diff,
1435 };
1436 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1437 this._subscriptions.extend(project_subscriptions);
1438
1439 this.end_selection(window, cx);
1440 this.scroll_manager.show_scrollbar(window, cx);
1441
1442 if mode == EditorMode::Full {
1443 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1444 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1445
1446 if this.git_blame_inline_enabled {
1447 this.git_blame_inline_enabled = true;
1448 this.start_git_blame_inline(false, window, cx);
1449 }
1450
1451 if let Some(buffer) = buffer.read(cx).as_singleton() {
1452 if let Some(project) = this.project.as_ref() {
1453 let handle = project.update(cx, |project, cx| {
1454 project.register_buffer_with_language_servers(&buffer, cx)
1455 });
1456 this.registered_buffers
1457 .insert(buffer.read(cx).remote_id(), handle);
1458 }
1459 }
1460 }
1461
1462 this.report_editor_event("Editor Opened", None, cx);
1463 this
1464 }
1465
1466 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1467 self.mouse_context_menu
1468 .as_ref()
1469 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1470 }
1471
1472 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1473 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1474 }
1475
1476 fn key_context_internal(
1477 &self,
1478 has_active_edit_prediction: bool,
1479 window: &Window,
1480 cx: &App,
1481 ) -> KeyContext {
1482 let mut key_context = KeyContext::new_with_defaults();
1483 key_context.add("Editor");
1484 let mode = match self.mode {
1485 EditorMode::SingleLine { .. } => "single_line",
1486 EditorMode::AutoHeight { .. } => "auto_height",
1487 EditorMode::Full => "full",
1488 };
1489
1490 if EditorSettings::jupyter_enabled(cx) {
1491 key_context.add("jupyter");
1492 }
1493
1494 key_context.set("mode", mode);
1495 if self.pending_rename.is_some() {
1496 key_context.add("renaming");
1497 }
1498
1499 match self.context_menu.borrow().as_ref() {
1500 Some(CodeContextMenu::Completions(_)) => {
1501 key_context.add("menu");
1502 key_context.add("showing_completions");
1503 }
1504 Some(CodeContextMenu::CodeActions(_)) => {
1505 key_context.add("menu");
1506 key_context.add("showing_code_actions")
1507 }
1508 None => {}
1509 }
1510
1511 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1512 if !self.focus_handle(cx).contains_focused(window, cx)
1513 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1514 {
1515 for addon in self.addons.values() {
1516 addon.extend_key_context(&mut key_context, cx)
1517 }
1518 }
1519
1520 if let Some(extension) = self
1521 .buffer
1522 .read(cx)
1523 .as_singleton()
1524 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1525 {
1526 key_context.set("extension", extension.to_string());
1527 }
1528
1529 if has_active_edit_prediction {
1530 if self.edit_prediction_in_conflict() {
1531 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1532 } else {
1533 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1534 key_context.add("copilot_suggestion");
1535 }
1536 }
1537
1538 if self.selection_mark_mode {
1539 key_context.add("selection_mode");
1540 }
1541
1542 key_context
1543 }
1544
1545 pub fn edit_prediction_in_conflict(&self) -> bool {
1546 if !self.show_edit_predictions_in_menu() {
1547 return false;
1548 }
1549
1550 let showing_completions = self
1551 .context_menu
1552 .borrow()
1553 .as_ref()
1554 .map_or(false, |context| {
1555 matches!(context, CodeContextMenu::Completions(_))
1556 });
1557
1558 showing_completions
1559 || self.edit_prediction_requires_modifier()
1560 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1561 // bindings to insert tab characters.
1562 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1563 }
1564
1565 pub fn accept_edit_prediction_keybind(
1566 &self,
1567 window: &Window,
1568 cx: &App,
1569 ) -> AcceptEditPredictionBinding {
1570 let key_context = self.key_context_internal(true, window, cx);
1571 let in_conflict = self.edit_prediction_in_conflict();
1572
1573 AcceptEditPredictionBinding(
1574 window
1575 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1576 .into_iter()
1577 .filter(|binding| {
1578 !in_conflict
1579 || binding
1580 .keystrokes()
1581 .first()
1582 .map_or(false, |keystroke| keystroke.modifiers.modified())
1583 })
1584 .rev()
1585 .min_by_key(|binding| {
1586 binding
1587 .keystrokes()
1588 .first()
1589 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1590 }),
1591 )
1592 }
1593
1594 pub fn new_file(
1595 workspace: &mut Workspace,
1596 _: &workspace::NewFile,
1597 window: &mut Window,
1598 cx: &mut Context<Workspace>,
1599 ) {
1600 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1601 "Failed to create buffer",
1602 window,
1603 cx,
1604 |e, _, _| match e.error_code() {
1605 ErrorCode::RemoteUpgradeRequired => Some(format!(
1606 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1607 e.error_tag("required").unwrap_or("the latest version")
1608 )),
1609 _ => None,
1610 },
1611 );
1612 }
1613
1614 pub fn new_in_workspace(
1615 workspace: &mut Workspace,
1616 window: &mut Window,
1617 cx: &mut Context<Workspace>,
1618 ) -> Task<Result<Entity<Editor>>> {
1619 let project = workspace.project().clone();
1620 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1621
1622 cx.spawn_in(window, |workspace, mut cx| async move {
1623 let buffer = create.await?;
1624 workspace.update_in(&mut cx, |workspace, window, cx| {
1625 let editor =
1626 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1627 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1628 editor
1629 })
1630 })
1631 }
1632
1633 fn new_file_vertical(
1634 workspace: &mut Workspace,
1635 _: &workspace::NewFileSplitVertical,
1636 window: &mut Window,
1637 cx: &mut Context<Workspace>,
1638 ) {
1639 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1640 }
1641
1642 fn new_file_horizontal(
1643 workspace: &mut Workspace,
1644 _: &workspace::NewFileSplitHorizontal,
1645 window: &mut Window,
1646 cx: &mut Context<Workspace>,
1647 ) {
1648 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1649 }
1650
1651 fn new_file_in_direction(
1652 workspace: &mut Workspace,
1653 direction: SplitDirection,
1654 window: &mut Window,
1655 cx: &mut Context<Workspace>,
1656 ) {
1657 let project = workspace.project().clone();
1658 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1659
1660 cx.spawn_in(window, |workspace, mut cx| async move {
1661 let buffer = create.await?;
1662 workspace.update_in(&mut cx, move |workspace, window, cx| {
1663 workspace.split_item(
1664 direction,
1665 Box::new(
1666 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1667 ),
1668 window,
1669 cx,
1670 )
1671 })?;
1672 anyhow::Ok(())
1673 })
1674 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1675 match e.error_code() {
1676 ErrorCode::RemoteUpgradeRequired => Some(format!(
1677 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1678 e.error_tag("required").unwrap_or("the latest version")
1679 )),
1680 _ => None,
1681 }
1682 });
1683 }
1684
1685 pub fn leader_peer_id(&self) -> Option<PeerId> {
1686 self.leader_peer_id
1687 }
1688
1689 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1690 &self.buffer
1691 }
1692
1693 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1694 self.workspace.as_ref()?.0.upgrade()
1695 }
1696
1697 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1698 self.buffer().read(cx).title(cx)
1699 }
1700
1701 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1702 let git_blame_gutter_max_author_length = self
1703 .render_git_blame_gutter(cx)
1704 .then(|| {
1705 if let Some(blame) = self.blame.as_ref() {
1706 let max_author_length =
1707 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1708 Some(max_author_length)
1709 } else {
1710 None
1711 }
1712 })
1713 .flatten();
1714
1715 EditorSnapshot {
1716 mode: self.mode,
1717 show_gutter: self.show_gutter,
1718 show_line_numbers: self.show_line_numbers,
1719 show_git_diff_gutter: self.show_git_diff_gutter,
1720 show_code_actions: self.show_code_actions,
1721 show_runnables: self.show_runnables,
1722 git_blame_gutter_max_author_length,
1723 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1724 scroll_anchor: self.scroll_manager.anchor(),
1725 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1726 placeholder_text: self.placeholder_text.clone(),
1727 is_focused: self.focus_handle.is_focused(window),
1728 current_line_highlight: self
1729 .current_line_highlight
1730 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1731 gutter_hovered: self.gutter_hovered,
1732 }
1733 }
1734
1735 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1736 self.buffer.read(cx).language_at(point, cx)
1737 }
1738
1739 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1740 self.buffer.read(cx).read(cx).file_at(point).cloned()
1741 }
1742
1743 pub fn active_excerpt(
1744 &self,
1745 cx: &App,
1746 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1747 self.buffer
1748 .read(cx)
1749 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1750 }
1751
1752 pub fn mode(&self) -> EditorMode {
1753 self.mode
1754 }
1755
1756 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1757 self.collaboration_hub.as_deref()
1758 }
1759
1760 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1761 self.collaboration_hub = Some(hub);
1762 }
1763
1764 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1765 self.in_project_search = in_project_search;
1766 }
1767
1768 pub fn set_custom_context_menu(
1769 &mut self,
1770 f: impl 'static
1771 + Fn(
1772 &mut Self,
1773 DisplayPoint,
1774 &mut Window,
1775 &mut Context<Self>,
1776 ) -> Option<Entity<ui::ContextMenu>>,
1777 ) {
1778 self.custom_context_menu = Some(Box::new(f))
1779 }
1780
1781 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1782 self.completion_provider = provider;
1783 }
1784
1785 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1786 self.semantics_provider.clone()
1787 }
1788
1789 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1790 self.semantics_provider = provider;
1791 }
1792
1793 pub fn set_edit_prediction_provider<T>(
1794 &mut self,
1795 provider: Option<Entity<T>>,
1796 window: &mut Window,
1797 cx: &mut Context<Self>,
1798 ) where
1799 T: EditPredictionProvider,
1800 {
1801 self.edit_prediction_provider =
1802 provider.map(|provider| RegisteredInlineCompletionProvider {
1803 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1804 if this.focus_handle.is_focused(window) {
1805 this.update_visible_inline_completion(window, cx);
1806 }
1807 }),
1808 provider: Arc::new(provider),
1809 });
1810 self.refresh_inline_completion(false, false, window, cx);
1811 }
1812
1813 pub fn placeholder_text(&self) -> Option<&str> {
1814 self.placeholder_text.as_deref()
1815 }
1816
1817 pub fn set_placeholder_text(
1818 &mut self,
1819 placeholder_text: impl Into<Arc<str>>,
1820 cx: &mut Context<Self>,
1821 ) {
1822 let placeholder_text = Some(placeholder_text.into());
1823 if self.placeholder_text != placeholder_text {
1824 self.placeholder_text = placeholder_text;
1825 cx.notify();
1826 }
1827 }
1828
1829 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1830 self.cursor_shape = cursor_shape;
1831
1832 // Disrupt blink for immediate user feedback that the cursor shape has changed
1833 self.blink_manager.update(cx, BlinkManager::show_cursor);
1834
1835 cx.notify();
1836 }
1837
1838 pub fn set_current_line_highlight(
1839 &mut self,
1840 current_line_highlight: Option<CurrentLineHighlight>,
1841 ) {
1842 self.current_line_highlight = current_line_highlight;
1843 }
1844
1845 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1846 self.collapse_matches = collapse_matches;
1847 }
1848
1849 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1850 let buffers = self.buffer.read(cx).all_buffers();
1851 let Some(project) = self.project.as_ref() else {
1852 return;
1853 };
1854 project.update(cx, |project, cx| {
1855 for buffer in buffers {
1856 self.registered_buffers
1857 .entry(buffer.read(cx).remote_id())
1858 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1859 }
1860 })
1861 }
1862
1863 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1864 if self.collapse_matches {
1865 return range.start..range.start;
1866 }
1867 range.clone()
1868 }
1869
1870 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1871 if self.display_map.read(cx).clip_at_line_ends != clip {
1872 self.display_map
1873 .update(cx, |map, _| map.clip_at_line_ends = clip);
1874 }
1875 }
1876
1877 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1878 self.input_enabled = input_enabled;
1879 }
1880
1881 pub fn set_inline_completions_hidden_for_vim_mode(
1882 &mut self,
1883 hidden: bool,
1884 window: &mut Window,
1885 cx: &mut Context<Self>,
1886 ) {
1887 if hidden != self.inline_completions_hidden_for_vim_mode {
1888 self.inline_completions_hidden_for_vim_mode = hidden;
1889 if hidden {
1890 self.update_visible_inline_completion(window, cx);
1891 } else {
1892 self.refresh_inline_completion(true, false, window, cx);
1893 }
1894 }
1895 }
1896
1897 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1898 self.menu_inline_completions_policy = value;
1899 }
1900
1901 pub fn set_autoindent(&mut self, autoindent: bool) {
1902 if autoindent {
1903 self.autoindent_mode = Some(AutoindentMode::EachLine);
1904 } else {
1905 self.autoindent_mode = None;
1906 }
1907 }
1908
1909 pub fn read_only(&self, cx: &App) -> bool {
1910 self.read_only || self.buffer.read(cx).read_only()
1911 }
1912
1913 pub fn set_read_only(&mut self, read_only: bool) {
1914 self.read_only = read_only;
1915 }
1916
1917 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1918 self.use_autoclose = autoclose;
1919 }
1920
1921 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1922 self.use_auto_surround = auto_surround;
1923 }
1924
1925 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1926 self.auto_replace_emoji_shortcode = auto_replace;
1927 }
1928
1929 pub fn toggle_inline_completions(
1930 &mut self,
1931 _: &ToggleEditPrediction,
1932 window: &mut Window,
1933 cx: &mut Context<Self>,
1934 ) {
1935 if self.show_inline_completions_override.is_some() {
1936 self.set_show_edit_predictions(None, window, cx);
1937 } else {
1938 let show_edit_predictions = !self.edit_predictions_enabled();
1939 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1940 }
1941 }
1942
1943 pub fn set_show_edit_predictions(
1944 &mut self,
1945 show_edit_predictions: Option<bool>,
1946 window: &mut Window,
1947 cx: &mut Context<Self>,
1948 ) {
1949 self.show_inline_completions_override = show_edit_predictions;
1950 self.refresh_inline_completion(false, true, window, cx);
1951 }
1952
1953 fn inline_completions_disabled_in_scope(
1954 &self,
1955 buffer: &Entity<Buffer>,
1956 buffer_position: language::Anchor,
1957 cx: &App,
1958 ) -> bool {
1959 let snapshot = buffer.read(cx).snapshot();
1960 let settings = snapshot.settings_at(buffer_position, cx);
1961
1962 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1963 return false;
1964 };
1965
1966 scope.override_name().map_or(false, |scope_name| {
1967 settings
1968 .edit_predictions_disabled_in
1969 .iter()
1970 .any(|s| s == scope_name)
1971 })
1972 }
1973
1974 pub fn set_use_modal_editing(&mut self, to: bool) {
1975 self.use_modal_editing = to;
1976 }
1977
1978 pub fn use_modal_editing(&self) -> bool {
1979 self.use_modal_editing
1980 }
1981
1982 fn selections_did_change(
1983 &mut self,
1984 local: bool,
1985 old_cursor_position: &Anchor,
1986 show_completions: bool,
1987 window: &mut Window,
1988 cx: &mut Context<Self>,
1989 ) {
1990 window.invalidate_character_coordinates();
1991
1992 // Copy selections to primary selection buffer
1993 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1994 if local {
1995 let selections = self.selections.all::<usize>(cx);
1996 let buffer_handle = self.buffer.read(cx).read(cx);
1997
1998 let mut text = String::new();
1999 for (index, selection) in selections.iter().enumerate() {
2000 let text_for_selection = buffer_handle
2001 .text_for_range(selection.start..selection.end)
2002 .collect::<String>();
2003
2004 text.push_str(&text_for_selection);
2005 if index != selections.len() - 1 {
2006 text.push('\n');
2007 }
2008 }
2009
2010 if !text.is_empty() {
2011 cx.write_to_primary(ClipboardItem::new_string(text));
2012 }
2013 }
2014
2015 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2016 self.buffer.update(cx, |buffer, cx| {
2017 buffer.set_active_selections(
2018 &self.selections.disjoint_anchors(),
2019 self.selections.line_mode,
2020 self.cursor_shape,
2021 cx,
2022 )
2023 });
2024 }
2025 let display_map = self
2026 .display_map
2027 .update(cx, |display_map, cx| display_map.snapshot(cx));
2028 let buffer = &display_map.buffer_snapshot;
2029 self.add_selections_state = None;
2030 self.select_next_state = None;
2031 self.select_prev_state = None;
2032 self.select_larger_syntax_node_stack.clear();
2033 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2034 self.snippet_stack
2035 .invalidate(&self.selections.disjoint_anchors(), buffer);
2036 self.take_rename(false, window, cx);
2037
2038 let new_cursor_position = self.selections.newest_anchor().head();
2039
2040 self.push_to_nav_history(
2041 *old_cursor_position,
2042 Some(new_cursor_position.to_point(buffer)),
2043 cx,
2044 );
2045
2046 if local {
2047 let new_cursor_position = self.selections.newest_anchor().head();
2048 let mut context_menu = self.context_menu.borrow_mut();
2049 let completion_menu = match context_menu.as_ref() {
2050 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2051 _ => {
2052 *context_menu = None;
2053 None
2054 }
2055 };
2056 if let Some(buffer_id) = new_cursor_position.buffer_id {
2057 if !self.registered_buffers.contains_key(&buffer_id) {
2058 if let Some(project) = self.project.as_ref() {
2059 project.update(cx, |project, cx| {
2060 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2061 return;
2062 };
2063 self.registered_buffers.insert(
2064 buffer_id,
2065 project.register_buffer_with_language_servers(&buffer, cx),
2066 );
2067 })
2068 }
2069 }
2070 }
2071
2072 if let Some(completion_menu) = completion_menu {
2073 let cursor_position = new_cursor_position.to_offset(buffer);
2074 let (word_range, kind) =
2075 buffer.surrounding_word(completion_menu.initial_position, true);
2076 if kind == Some(CharKind::Word)
2077 && word_range.to_inclusive().contains(&cursor_position)
2078 {
2079 let mut completion_menu = completion_menu.clone();
2080 drop(context_menu);
2081
2082 let query = Self::completion_query(buffer, cursor_position);
2083 cx.spawn(move |this, mut cx| async move {
2084 completion_menu
2085 .filter(query.as_deref(), cx.background_executor().clone())
2086 .await;
2087
2088 this.update(&mut cx, |this, cx| {
2089 let mut context_menu = this.context_menu.borrow_mut();
2090 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2091 else {
2092 return;
2093 };
2094
2095 if menu.id > completion_menu.id {
2096 return;
2097 }
2098
2099 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2100 drop(context_menu);
2101 cx.notify();
2102 })
2103 })
2104 .detach();
2105
2106 if show_completions {
2107 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2108 }
2109 } else {
2110 drop(context_menu);
2111 self.hide_context_menu(window, cx);
2112 }
2113 } else {
2114 drop(context_menu);
2115 }
2116
2117 hide_hover(self, cx);
2118
2119 if old_cursor_position.to_display_point(&display_map).row()
2120 != new_cursor_position.to_display_point(&display_map).row()
2121 {
2122 self.available_code_actions.take();
2123 }
2124 self.refresh_code_actions(window, cx);
2125 self.refresh_document_highlights(cx);
2126 self.refresh_selected_text_highlights(window, cx);
2127 refresh_matching_bracket_highlights(self, window, cx);
2128 self.update_visible_inline_completion(window, cx);
2129 self.edit_prediction_requires_modifier_in_leading_space = true;
2130 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2131 if self.git_blame_inline_enabled {
2132 self.start_inline_blame_timer(window, cx);
2133 }
2134 }
2135
2136 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2137 cx.emit(EditorEvent::SelectionsChanged { local });
2138
2139 let selections = &self.selections.disjoint;
2140 if selections.len() == 1 {
2141 cx.emit(SearchEvent::ActiveMatchChanged)
2142 }
2143 if local
2144 && self.is_singleton(cx)
2145 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2146 {
2147 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2148 let background_executor = cx.background_executor().clone();
2149 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2150 let snapshot = self.buffer().read(cx).snapshot(cx);
2151 let selections = selections.clone();
2152 self.serialize_selections = cx.background_spawn(async move {
2153 background_executor.timer(Duration::from_millis(100)).await;
2154 let selections = selections
2155 .iter()
2156 .map(|selection| {
2157 (
2158 selection.start.to_offset(&snapshot),
2159 selection.end.to_offset(&snapshot),
2160 )
2161 })
2162 .collect();
2163 DB.save_editor_selections(editor_id, workspace_id, selections)
2164 .await
2165 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2166 .log_err();
2167 });
2168 }
2169 }
2170
2171 cx.notify();
2172 }
2173
2174 pub fn change_selections<R>(
2175 &mut self,
2176 autoscroll: Option<Autoscroll>,
2177 window: &mut Window,
2178 cx: &mut Context<Self>,
2179 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2180 ) -> R {
2181 self.change_selections_inner(autoscroll, true, window, cx, change)
2182 }
2183
2184 fn change_selections_inner<R>(
2185 &mut self,
2186 autoscroll: Option<Autoscroll>,
2187 request_completions: bool,
2188 window: &mut Window,
2189 cx: &mut Context<Self>,
2190 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2191 ) -> R {
2192 let old_cursor_position = self.selections.newest_anchor().head();
2193 self.push_to_selection_history();
2194
2195 let (changed, result) = self.selections.change_with(cx, change);
2196
2197 if changed {
2198 if let Some(autoscroll) = autoscroll {
2199 self.request_autoscroll(autoscroll, cx);
2200 }
2201 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2202
2203 if self.should_open_signature_help_automatically(
2204 &old_cursor_position,
2205 self.signature_help_state.backspace_pressed(),
2206 cx,
2207 ) {
2208 self.show_signature_help(&ShowSignatureHelp, window, cx);
2209 }
2210 self.signature_help_state.set_backspace_pressed(false);
2211 }
2212
2213 result
2214 }
2215
2216 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2217 where
2218 I: IntoIterator<Item = (Range<S>, T)>,
2219 S: ToOffset,
2220 T: Into<Arc<str>>,
2221 {
2222 if self.read_only(cx) {
2223 return;
2224 }
2225
2226 self.buffer
2227 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2228 }
2229
2230 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2231 where
2232 I: IntoIterator<Item = (Range<S>, T)>,
2233 S: ToOffset,
2234 T: Into<Arc<str>>,
2235 {
2236 if self.read_only(cx) {
2237 return;
2238 }
2239
2240 self.buffer.update(cx, |buffer, cx| {
2241 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2242 });
2243 }
2244
2245 pub fn edit_with_block_indent<I, S, T>(
2246 &mut self,
2247 edits: I,
2248 original_indent_columns: Vec<u32>,
2249 cx: &mut Context<Self>,
2250 ) where
2251 I: IntoIterator<Item = (Range<S>, T)>,
2252 S: ToOffset,
2253 T: Into<Arc<str>>,
2254 {
2255 if self.read_only(cx) {
2256 return;
2257 }
2258
2259 self.buffer.update(cx, |buffer, cx| {
2260 buffer.edit(
2261 edits,
2262 Some(AutoindentMode::Block {
2263 original_indent_columns,
2264 }),
2265 cx,
2266 )
2267 });
2268 }
2269
2270 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2271 self.hide_context_menu(window, cx);
2272
2273 match phase {
2274 SelectPhase::Begin {
2275 position,
2276 add,
2277 click_count,
2278 } => self.begin_selection(position, add, click_count, window, cx),
2279 SelectPhase::BeginColumnar {
2280 position,
2281 goal_column,
2282 reset,
2283 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2284 SelectPhase::Extend {
2285 position,
2286 click_count,
2287 } => self.extend_selection(position, click_count, window, cx),
2288 SelectPhase::Update {
2289 position,
2290 goal_column,
2291 scroll_delta,
2292 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2293 SelectPhase::End => self.end_selection(window, cx),
2294 }
2295 }
2296
2297 fn extend_selection(
2298 &mut self,
2299 position: DisplayPoint,
2300 click_count: usize,
2301 window: &mut Window,
2302 cx: &mut Context<Self>,
2303 ) {
2304 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2305 let tail = self.selections.newest::<usize>(cx).tail();
2306 self.begin_selection(position, false, click_count, window, cx);
2307
2308 let position = position.to_offset(&display_map, Bias::Left);
2309 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2310
2311 let mut pending_selection = self
2312 .selections
2313 .pending_anchor()
2314 .expect("extend_selection not called with pending selection");
2315 if position >= tail {
2316 pending_selection.start = tail_anchor;
2317 } else {
2318 pending_selection.end = tail_anchor;
2319 pending_selection.reversed = true;
2320 }
2321
2322 let mut pending_mode = self.selections.pending_mode().unwrap();
2323 match &mut pending_mode {
2324 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2325 _ => {}
2326 }
2327
2328 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2329 s.set_pending(pending_selection, pending_mode)
2330 });
2331 }
2332
2333 fn begin_selection(
2334 &mut self,
2335 position: DisplayPoint,
2336 add: bool,
2337 click_count: usize,
2338 window: &mut Window,
2339 cx: &mut Context<Self>,
2340 ) {
2341 if !self.focus_handle.is_focused(window) {
2342 self.last_focused_descendant = None;
2343 window.focus(&self.focus_handle);
2344 }
2345
2346 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2347 let buffer = &display_map.buffer_snapshot;
2348 let newest_selection = self.selections.newest_anchor().clone();
2349 let position = display_map.clip_point(position, Bias::Left);
2350
2351 let start;
2352 let end;
2353 let mode;
2354 let mut auto_scroll;
2355 match click_count {
2356 1 => {
2357 start = buffer.anchor_before(position.to_point(&display_map));
2358 end = start;
2359 mode = SelectMode::Character;
2360 auto_scroll = true;
2361 }
2362 2 => {
2363 let range = movement::surrounding_word(&display_map, position);
2364 start = buffer.anchor_before(range.start.to_point(&display_map));
2365 end = buffer.anchor_before(range.end.to_point(&display_map));
2366 mode = SelectMode::Word(start..end);
2367 auto_scroll = true;
2368 }
2369 3 => {
2370 let position = display_map
2371 .clip_point(position, Bias::Left)
2372 .to_point(&display_map);
2373 let line_start = display_map.prev_line_boundary(position).0;
2374 let next_line_start = buffer.clip_point(
2375 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2376 Bias::Left,
2377 );
2378 start = buffer.anchor_before(line_start);
2379 end = buffer.anchor_before(next_line_start);
2380 mode = SelectMode::Line(start..end);
2381 auto_scroll = true;
2382 }
2383 _ => {
2384 start = buffer.anchor_before(0);
2385 end = buffer.anchor_before(buffer.len());
2386 mode = SelectMode::All;
2387 auto_scroll = false;
2388 }
2389 }
2390 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2391
2392 let point_to_delete: Option<usize> = {
2393 let selected_points: Vec<Selection<Point>> =
2394 self.selections.disjoint_in_range(start..end, cx);
2395
2396 if !add || click_count > 1 {
2397 None
2398 } else if !selected_points.is_empty() {
2399 Some(selected_points[0].id)
2400 } else {
2401 let clicked_point_already_selected =
2402 self.selections.disjoint.iter().find(|selection| {
2403 selection.start.to_point(buffer) == start.to_point(buffer)
2404 || selection.end.to_point(buffer) == end.to_point(buffer)
2405 });
2406
2407 clicked_point_already_selected.map(|selection| selection.id)
2408 }
2409 };
2410
2411 let selections_count = self.selections.count();
2412
2413 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2414 if let Some(point_to_delete) = point_to_delete {
2415 s.delete(point_to_delete);
2416
2417 if selections_count == 1 {
2418 s.set_pending_anchor_range(start..end, mode);
2419 }
2420 } else {
2421 if !add {
2422 s.clear_disjoint();
2423 } else if click_count > 1 {
2424 s.delete(newest_selection.id)
2425 }
2426
2427 s.set_pending_anchor_range(start..end, mode);
2428 }
2429 });
2430 }
2431
2432 fn begin_columnar_selection(
2433 &mut self,
2434 position: DisplayPoint,
2435 goal_column: u32,
2436 reset: bool,
2437 window: &mut Window,
2438 cx: &mut Context<Self>,
2439 ) {
2440 if !self.focus_handle.is_focused(window) {
2441 self.last_focused_descendant = None;
2442 window.focus(&self.focus_handle);
2443 }
2444
2445 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2446
2447 if reset {
2448 let pointer_position = display_map
2449 .buffer_snapshot
2450 .anchor_before(position.to_point(&display_map));
2451
2452 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2453 s.clear_disjoint();
2454 s.set_pending_anchor_range(
2455 pointer_position..pointer_position,
2456 SelectMode::Character,
2457 );
2458 });
2459 }
2460
2461 let tail = self.selections.newest::<Point>(cx).tail();
2462 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2463
2464 if !reset {
2465 self.select_columns(
2466 tail.to_display_point(&display_map),
2467 position,
2468 goal_column,
2469 &display_map,
2470 window,
2471 cx,
2472 );
2473 }
2474 }
2475
2476 fn update_selection(
2477 &mut self,
2478 position: DisplayPoint,
2479 goal_column: u32,
2480 scroll_delta: gpui::Point<f32>,
2481 window: &mut Window,
2482 cx: &mut Context<Self>,
2483 ) {
2484 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2485
2486 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2487 let tail = tail.to_display_point(&display_map);
2488 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2489 } else if let Some(mut pending) = self.selections.pending_anchor() {
2490 let buffer = self.buffer.read(cx).snapshot(cx);
2491 let head;
2492 let tail;
2493 let mode = self.selections.pending_mode().unwrap();
2494 match &mode {
2495 SelectMode::Character => {
2496 head = position.to_point(&display_map);
2497 tail = pending.tail().to_point(&buffer);
2498 }
2499 SelectMode::Word(original_range) => {
2500 let original_display_range = original_range.start.to_display_point(&display_map)
2501 ..original_range.end.to_display_point(&display_map);
2502 let original_buffer_range = original_display_range.start.to_point(&display_map)
2503 ..original_display_range.end.to_point(&display_map);
2504 if movement::is_inside_word(&display_map, position)
2505 || original_display_range.contains(&position)
2506 {
2507 let word_range = movement::surrounding_word(&display_map, position);
2508 if word_range.start < original_display_range.start {
2509 head = word_range.start.to_point(&display_map);
2510 } else {
2511 head = word_range.end.to_point(&display_map);
2512 }
2513 } else {
2514 head = position.to_point(&display_map);
2515 }
2516
2517 if head <= original_buffer_range.start {
2518 tail = original_buffer_range.end;
2519 } else {
2520 tail = original_buffer_range.start;
2521 }
2522 }
2523 SelectMode::Line(original_range) => {
2524 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2525
2526 let position = display_map
2527 .clip_point(position, Bias::Left)
2528 .to_point(&display_map);
2529 let line_start = display_map.prev_line_boundary(position).0;
2530 let next_line_start = buffer.clip_point(
2531 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2532 Bias::Left,
2533 );
2534
2535 if line_start < original_range.start {
2536 head = line_start
2537 } else {
2538 head = next_line_start
2539 }
2540
2541 if head <= original_range.start {
2542 tail = original_range.end;
2543 } else {
2544 tail = original_range.start;
2545 }
2546 }
2547 SelectMode::All => {
2548 return;
2549 }
2550 };
2551
2552 if head < tail {
2553 pending.start = buffer.anchor_before(head);
2554 pending.end = buffer.anchor_before(tail);
2555 pending.reversed = true;
2556 } else {
2557 pending.start = buffer.anchor_before(tail);
2558 pending.end = buffer.anchor_before(head);
2559 pending.reversed = false;
2560 }
2561
2562 self.change_selections(None, window, cx, |s| {
2563 s.set_pending(pending, mode);
2564 });
2565 } else {
2566 log::error!("update_selection dispatched with no pending selection");
2567 return;
2568 }
2569
2570 self.apply_scroll_delta(scroll_delta, window, cx);
2571 cx.notify();
2572 }
2573
2574 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2575 self.columnar_selection_tail.take();
2576 if self.selections.pending_anchor().is_some() {
2577 let selections = self.selections.all::<usize>(cx);
2578 self.change_selections(None, window, cx, |s| {
2579 s.select(selections);
2580 s.clear_pending();
2581 });
2582 }
2583 }
2584
2585 fn select_columns(
2586 &mut self,
2587 tail: DisplayPoint,
2588 head: DisplayPoint,
2589 goal_column: u32,
2590 display_map: &DisplaySnapshot,
2591 window: &mut Window,
2592 cx: &mut Context<Self>,
2593 ) {
2594 let start_row = cmp::min(tail.row(), head.row());
2595 let end_row = cmp::max(tail.row(), head.row());
2596 let start_column = cmp::min(tail.column(), goal_column);
2597 let end_column = cmp::max(tail.column(), goal_column);
2598 let reversed = start_column < tail.column();
2599
2600 let selection_ranges = (start_row.0..=end_row.0)
2601 .map(DisplayRow)
2602 .filter_map(|row| {
2603 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2604 let start = display_map
2605 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2606 .to_point(display_map);
2607 let end = display_map
2608 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2609 .to_point(display_map);
2610 if reversed {
2611 Some(end..start)
2612 } else {
2613 Some(start..end)
2614 }
2615 } else {
2616 None
2617 }
2618 })
2619 .collect::<Vec<_>>();
2620
2621 self.change_selections(None, window, cx, |s| {
2622 s.select_ranges(selection_ranges);
2623 });
2624 cx.notify();
2625 }
2626
2627 pub fn has_pending_nonempty_selection(&self) -> bool {
2628 let pending_nonempty_selection = match self.selections.pending_anchor() {
2629 Some(Selection { start, end, .. }) => start != end,
2630 None => false,
2631 };
2632
2633 pending_nonempty_selection
2634 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2635 }
2636
2637 pub fn has_pending_selection(&self) -> bool {
2638 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2639 }
2640
2641 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2642 self.selection_mark_mode = false;
2643
2644 if self.clear_expanded_diff_hunks(cx) {
2645 cx.notify();
2646 return;
2647 }
2648 if self.dismiss_menus_and_popups(true, window, cx) {
2649 return;
2650 }
2651
2652 if self.mode == EditorMode::Full
2653 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2654 {
2655 return;
2656 }
2657
2658 cx.propagate();
2659 }
2660
2661 pub fn dismiss_menus_and_popups(
2662 &mut self,
2663 is_user_requested: bool,
2664 window: &mut Window,
2665 cx: &mut Context<Self>,
2666 ) -> bool {
2667 if self.take_rename(false, window, cx).is_some() {
2668 return true;
2669 }
2670
2671 if hide_hover(self, cx) {
2672 return true;
2673 }
2674
2675 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2676 return true;
2677 }
2678
2679 if self.hide_context_menu(window, cx).is_some() {
2680 return true;
2681 }
2682
2683 if self.mouse_context_menu.take().is_some() {
2684 return true;
2685 }
2686
2687 if is_user_requested && self.discard_inline_completion(true, cx) {
2688 return true;
2689 }
2690
2691 if self.snippet_stack.pop().is_some() {
2692 return true;
2693 }
2694
2695 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2696 self.dismiss_diagnostics(cx);
2697 return true;
2698 }
2699
2700 false
2701 }
2702
2703 fn linked_editing_ranges_for(
2704 &self,
2705 selection: Range<text::Anchor>,
2706 cx: &App,
2707 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2708 if self.linked_edit_ranges.is_empty() {
2709 return None;
2710 }
2711 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2712 selection.end.buffer_id.and_then(|end_buffer_id| {
2713 if selection.start.buffer_id != Some(end_buffer_id) {
2714 return None;
2715 }
2716 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2717 let snapshot = buffer.read(cx).snapshot();
2718 self.linked_edit_ranges
2719 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2720 .map(|ranges| (ranges, snapshot, buffer))
2721 })?;
2722 use text::ToOffset as TO;
2723 // find offset from the start of current range to current cursor position
2724 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2725
2726 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2727 let start_difference = start_offset - start_byte_offset;
2728 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2729 let end_difference = end_offset - start_byte_offset;
2730 // Current range has associated linked ranges.
2731 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2732 for range in linked_ranges.iter() {
2733 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2734 let end_offset = start_offset + end_difference;
2735 let start_offset = start_offset + start_difference;
2736 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2737 continue;
2738 }
2739 if self.selections.disjoint_anchor_ranges().any(|s| {
2740 if s.start.buffer_id != selection.start.buffer_id
2741 || s.end.buffer_id != selection.end.buffer_id
2742 {
2743 return false;
2744 }
2745 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2746 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2747 }) {
2748 continue;
2749 }
2750 let start = buffer_snapshot.anchor_after(start_offset);
2751 let end = buffer_snapshot.anchor_after(end_offset);
2752 linked_edits
2753 .entry(buffer.clone())
2754 .or_default()
2755 .push(start..end);
2756 }
2757 Some(linked_edits)
2758 }
2759
2760 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2761 let text: Arc<str> = text.into();
2762
2763 if self.read_only(cx) {
2764 return;
2765 }
2766
2767 let selections = self.selections.all_adjusted(cx);
2768 let mut bracket_inserted = false;
2769 let mut edits = Vec::new();
2770 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2771 let mut new_selections = Vec::with_capacity(selections.len());
2772 let mut new_autoclose_regions = Vec::new();
2773 let snapshot = self.buffer.read(cx).read(cx);
2774
2775 for (selection, autoclose_region) in
2776 self.selections_with_autoclose_regions(selections, &snapshot)
2777 {
2778 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2779 // Determine if the inserted text matches the opening or closing
2780 // bracket of any of this language's bracket pairs.
2781 let mut bracket_pair = None;
2782 let mut is_bracket_pair_start = false;
2783 let mut is_bracket_pair_end = false;
2784 if !text.is_empty() {
2785 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2786 // and they are removing the character that triggered IME popup.
2787 for (pair, enabled) in scope.brackets() {
2788 if !pair.close && !pair.surround {
2789 continue;
2790 }
2791
2792 if enabled && pair.start.ends_with(text.as_ref()) {
2793 let prefix_len = pair.start.len() - text.len();
2794 let preceding_text_matches_prefix = prefix_len == 0
2795 || (selection.start.column >= (prefix_len as u32)
2796 && snapshot.contains_str_at(
2797 Point::new(
2798 selection.start.row,
2799 selection.start.column - (prefix_len as u32),
2800 ),
2801 &pair.start[..prefix_len],
2802 ));
2803 if preceding_text_matches_prefix {
2804 bracket_pair = Some(pair.clone());
2805 is_bracket_pair_start = true;
2806 break;
2807 }
2808 }
2809 if pair.end.as_str() == text.as_ref() {
2810 bracket_pair = Some(pair.clone());
2811 is_bracket_pair_end = true;
2812 break;
2813 }
2814 }
2815 }
2816
2817 if let Some(bracket_pair) = bracket_pair {
2818 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2819 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2820 let auto_surround =
2821 self.use_auto_surround && snapshot_settings.use_auto_surround;
2822 if selection.is_empty() {
2823 if is_bracket_pair_start {
2824 // If the inserted text is a suffix of an opening bracket and the
2825 // selection is preceded by the rest of the opening bracket, then
2826 // insert the closing bracket.
2827 let following_text_allows_autoclose = snapshot
2828 .chars_at(selection.start)
2829 .next()
2830 .map_or(true, |c| scope.should_autoclose_before(c));
2831
2832 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2833 && bracket_pair.start.len() == 1
2834 {
2835 let target = bracket_pair.start.chars().next().unwrap();
2836 let current_line_count = snapshot
2837 .reversed_chars_at(selection.start)
2838 .take_while(|&c| c != '\n')
2839 .filter(|&c| c == target)
2840 .count();
2841 current_line_count % 2 == 1
2842 } else {
2843 false
2844 };
2845
2846 if autoclose
2847 && bracket_pair.close
2848 && following_text_allows_autoclose
2849 && !is_closing_quote
2850 {
2851 let anchor = snapshot.anchor_before(selection.end);
2852 new_selections.push((selection.map(|_| anchor), text.len()));
2853 new_autoclose_regions.push((
2854 anchor,
2855 text.len(),
2856 selection.id,
2857 bracket_pair.clone(),
2858 ));
2859 edits.push((
2860 selection.range(),
2861 format!("{}{}", text, bracket_pair.end).into(),
2862 ));
2863 bracket_inserted = true;
2864 continue;
2865 }
2866 }
2867
2868 if let Some(region) = autoclose_region {
2869 // If the selection is followed by an auto-inserted closing bracket,
2870 // then don't insert that closing bracket again; just move the selection
2871 // past the closing bracket.
2872 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2873 && text.as_ref() == region.pair.end.as_str();
2874 if should_skip {
2875 let anchor = snapshot.anchor_after(selection.end);
2876 new_selections
2877 .push((selection.map(|_| anchor), region.pair.end.len()));
2878 continue;
2879 }
2880 }
2881
2882 let always_treat_brackets_as_autoclosed = snapshot
2883 .settings_at(selection.start, cx)
2884 .always_treat_brackets_as_autoclosed;
2885 if always_treat_brackets_as_autoclosed
2886 && is_bracket_pair_end
2887 && snapshot.contains_str_at(selection.end, text.as_ref())
2888 {
2889 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2890 // and the inserted text is a closing bracket and the selection is followed
2891 // by the closing bracket then move the selection past the closing bracket.
2892 let anchor = snapshot.anchor_after(selection.end);
2893 new_selections.push((selection.map(|_| anchor), text.len()));
2894 continue;
2895 }
2896 }
2897 // If an opening bracket is 1 character long and is typed while
2898 // text is selected, then surround that text with the bracket pair.
2899 else if auto_surround
2900 && bracket_pair.surround
2901 && is_bracket_pair_start
2902 && bracket_pair.start.chars().count() == 1
2903 {
2904 edits.push((selection.start..selection.start, text.clone()));
2905 edits.push((
2906 selection.end..selection.end,
2907 bracket_pair.end.as_str().into(),
2908 ));
2909 bracket_inserted = true;
2910 new_selections.push((
2911 Selection {
2912 id: selection.id,
2913 start: snapshot.anchor_after(selection.start),
2914 end: snapshot.anchor_before(selection.end),
2915 reversed: selection.reversed,
2916 goal: selection.goal,
2917 },
2918 0,
2919 ));
2920 continue;
2921 }
2922 }
2923 }
2924
2925 if self.auto_replace_emoji_shortcode
2926 && selection.is_empty()
2927 && text.as_ref().ends_with(':')
2928 {
2929 if let Some(possible_emoji_short_code) =
2930 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2931 {
2932 if !possible_emoji_short_code.is_empty() {
2933 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2934 let emoji_shortcode_start = Point::new(
2935 selection.start.row,
2936 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2937 );
2938
2939 // Remove shortcode from buffer
2940 edits.push((
2941 emoji_shortcode_start..selection.start,
2942 "".to_string().into(),
2943 ));
2944 new_selections.push((
2945 Selection {
2946 id: selection.id,
2947 start: snapshot.anchor_after(emoji_shortcode_start),
2948 end: snapshot.anchor_before(selection.start),
2949 reversed: selection.reversed,
2950 goal: selection.goal,
2951 },
2952 0,
2953 ));
2954
2955 // Insert emoji
2956 let selection_start_anchor = snapshot.anchor_after(selection.start);
2957 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2958 edits.push((selection.start..selection.end, emoji.to_string().into()));
2959
2960 continue;
2961 }
2962 }
2963 }
2964 }
2965
2966 // If not handling any auto-close operation, then just replace the selected
2967 // text with the given input and move the selection to the end of the
2968 // newly inserted text.
2969 let anchor = snapshot.anchor_after(selection.end);
2970 if !self.linked_edit_ranges.is_empty() {
2971 let start_anchor = snapshot.anchor_before(selection.start);
2972
2973 let is_word_char = text.chars().next().map_or(true, |char| {
2974 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2975 classifier.is_word(char)
2976 });
2977
2978 if is_word_char {
2979 if let Some(ranges) = self
2980 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2981 {
2982 for (buffer, edits) in ranges {
2983 linked_edits
2984 .entry(buffer.clone())
2985 .or_default()
2986 .extend(edits.into_iter().map(|range| (range, text.clone())));
2987 }
2988 }
2989 }
2990 }
2991
2992 new_selections.push((selection.map(|_| anchor), 0));
2993 edits.push((selection.start..selection.end, text.clone()));
2994 }
2995
2996 drop(snapshot);
2997
2998 self.transact(window, cx, |this, window, cx| {
2999 this.buffer.update(cx, |buffer, cx| {
3000 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3001 });
3002 for (buffer, edits) in linked_edits {
3003 buffer.update(cx, |buffer, cx| {
3004 let snapshot = buffer.snapshot();
3005 let edits = edits
3006 .into_iter()
3007 .map(|(range, text)| {
3008 use text::ToPoint as TP;
3009 let end_point = TP::to_point(&range.end, &snapshot);
3010 let start_point = TP::to_point(&range.start, &snapshot);
3011 (start_point..end_point, text)
3012 })
3013 .sorted_by_key(|(range, _)| range.start)
3014 .collect::<Vec<_>>();
3015 buffer.edit(edits, None, cx);
3016 })
3017 }
3018 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3019 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3020 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3021 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3022 .zip(new_selection_deltas)
3023 .map(|(selection, delta)| Selection {
3024 id: selection.id,
3025 start: selection.start + delta,
3026 end: selection.end + delta,
3027 reversed: selection.reversed,
3028 goal: SelectionGoal::None,
3029 })
3030 .collect::<Vec<_>>();
3031
3032 let mut i = 0;
3033 for (position, delta, selection_id, pair) in new_autoclose_regions {
3034 let position = position.to_offset(&map.buffer_snapshot) + delta;
3035 let start = map.buffer_snapshot.anchor_before(position);
3036 let end = map.buffer_snapshot.anchor_after(position);
3037 while let Some(existing_state) = this.autoclose_regions.get(i) {
3038 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3039 Ordering::Less => i += 1,
3040 Ordering::Greater => break,
3041 Ordering::Equal => {
3042 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3043 Ordering::Less => i += 1,
3044 Ordering::Equal => break,
3045 Ordering::Greater => break,
3046 }
3047 }
3048 }
3049 }
3050 this.autoclose_regions.insert(
3051 i,
3052 AutocloseRegion {
3053 selection_id,
3054 range: start..end,
3055 pair,
3056 },
3057 );
3058 }
3059
3060 let had_active_inline_completion = this.has_active_inline_completion();
3061 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3062 s.select(new_selections)
3063 });
3064
3065 if !bracket_inserted {
3066 if let Some(on_type_format_task) =
3067 this.trigger_on_type_formatting(text.to_string(), window, cx)
3068 {
3069 on_type_format_task.detach_and_log_err(cx);
3070 }
3071 }
3072
3073 let editor_settings = EditorSettings::get_global(cx);
3074 if bracket_inserted
3075 && (editor_settings.auto_signature_help
3076 || editor_settings.show_signature_help_after_edits)
3077 {
3078 this.show_signature_help(&ShowSignatureHelp, window, cx);
3079 }
3080
3081 let trigger_in_words =
3082 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3083 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3084 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3085 this.refresh_inline_completion(true, false, window, cx);
3086 });
3087 }
3088
3089 fn find_possible_emoji_shortcode_at_position(
3090 snapshot: &MultiBufferSnapshot,
3091 position: Point,
3092 ) -> Option<String> {
3093 let mut chars = Vec::new();
3094 let mut found_colon = false;
3095 for char in snapshot.reversed_chars_at(position).take(100) {
3096 // Found a possible emoji shortcode in the middle of the buffer
3097 if found_colon {
3098 if char.is_whitespace() {
3099 chars.reverse();
3100 return Some(chars.iter().collect());
3101 }
3102 // If the previous character is not a whitespace, we are in the middle of a word
3103 // and we only want to complete the shortcode if the word is made up of other emojis
3104 let mut containing_word = String::new();
3105 for ch in snapshot
3106 .reversed_chars_at(position)
3107 .skip(chars.len() + 1)
3108 .take(100)
3109 {
3110 if ch.is_whitespace() {
3111 break;
3112 }
3113 containing_word.push(ch);
3114 }
3115 let containing_word = containing_word.chars().rev().collect::<String>();
3116 if util::word_consists_of_emojis(containing_word.as_str()) {
3117 chars.reverse();
3118 return Some(chars.iter().collect());
3119 }
3120 }
3121
3122 if char.is_whitespace() || !char.is_ascii() {
3123 return None;
3124 }
3125 if char == ':' {
3126 found_colon = true;
3127 } else {
3128 chars.push(char);
3129 }
3130 }
3131 // Found a possible emoji shortcode at the beginning of the buffer
3132 chars.reverse();
3133 Some(chars.iter().collect())
3134 }
3135
3136 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3137 self.transact(window, cx, |this, window, cx| {
3138 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3139 let selections = this.selections.all::<usize>(cx);
3140 let multi_buffer = this.buffer.read(cx);
3141 let buffer = multi_buffer.snapshot(cx);
3142 selections
3143 .iter()
3144 .map(|selection| {
3145 let start_point = selection.start.to_point(&buffer);
3146 let mut indent =
3147 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3148 indent.len = cmp::min(indent.len, start_point.column);
3149 let start = selection.start;
3150 let end = selection.end;
3151 let selection_is_empty = start == end;
3152 let language_scope = buffer.language_scope_at(start);
3153 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3154 &language_scope
3155 {
3156 let leading_whitespace_len = buffer
3157 .reversed_chars_at(start)
3158 .take_while(|c| c.is_whitespace() && *c != '\n')
3159 .map(|c| c.len_utf8())
3160 .sum::<usize>();
3161
3162 let trailing_whitespace_len = buffer
3163 .chars_at(end)
3164 .take_while(|c| c.is_whitespace() && *c != '\n')
3165 .map(|c| c.len_utf8())
3166 .sum::<usize>();
3167
3168 let insert_extra_newline =
3169 language.brackets().any(|(pair, enabled)| {
3170 let pair_start = pair.start.trim_end();
3171 let pair_end = pair.end.trim_start();
3172
3173 enabled
3174 && pair.newline
3175 && buffer.contains_str_at(
3176 end + trailing_whitespace_len,
3177 pair_end,
3178 )
3179 && buffer.contains_str_at(
3180 (start - leading_whitespace_len)
3181 .saturating_sub(pair_start.len()),
3182 pair_start,
3183 )
3184 });
3185
3186 // Comment extension on newline is allowed only for cursor selections
3187 let comment_delimiter = maybe!({
3188 if !selection_is_empty {
3189 return None;
3190 }
3191
3192 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3193 return None;
3194 }
3195
3196 let delimiters = language.line_comment_prefixes();
3197 let max_len_of_delimiter =
3198 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3199 let (snapshot, range) =
3200 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3201
3202 let mut index_of_first_non_whitespace = 0;
3203 let comment_candidate = snapshot
3204 .chars_for_range(range)
3205 .skip_while(|c| {
3206 let should_skip = c.is_whitespace();
3207 if should_skip {
3208 index_of_first_non_whitespace += 1;
3209 }
3210 should_skip
3211 })
3212 .take(max_len_of_delimiter)
3213 .collect::<String>();
3214 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3215 comment_candidate.starts_with(comment_prefix.as_ref())
3216 })?;
3217 let cursor_is_placed_after_comment_marker =
3218 index_of_first_non_whitespace + comment_prefix.len()
3219 <= start_point.column as usize;
3220 if cursor_is_placed_after_comment_marker {
3221 Some(comment_prefix.clone())
3222 } else {
3223 None
3224 }
3225 });
3226 (comment_delimiter, insert_extra_newline)
3227 } else {
3228 (None, false)
3229 };
3230
3231 let capacity_for_delimiter = comment_delimiter
3232 .as_deref()
3233 .map(str::len)
3234 .unwrap_or_default();
3235 let mut new_text =
3236 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3237 new_text.push('\n');
3238 new_text.extend(indent.chars());
3239 if let Some(delimiter) = &comment_delimiter {
3240 new_text.push_str(delimiter);
3241 }
3242 if insert_extra_newline {
3243 new_text = new_text.repeat(2);
3244 }
3245
3246 let anchor = buffer.anchor_after(end);
3247 let new_selection = selection.map(|_| anchor);
3248 (
3249 (start..end, new_text),
3250 (insert_extra_newline, new_selection),
3251 )
3252 })
3253 .unzip()
3254 };
3255
3256 this.edit_with_autoindent(edits, cx);
3257 let buffer = this.buffer.read(cx).snapshot(cx);
3258 let new_selections = selection_fixup_info
3259 .into_iter()
3260 .map(|(extra_newline_inserted, new_selection)| {
3261 let mut cursor = new_selection.end.to_point(&buffer);
3262 if extra_newline_inserted {
3263 cursor.row -= 1;
3264 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3265 }
3266 new_selection.map(|_| cursor)
3267 })
3268 .collect();
3269
3270 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3271 s.select(new_selections)
3272 });
3273 this.refresh_inline_completion(true, false, window, cx);
3274 });
3275 }
3276
3277 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3278 let buffer = self.buffer.read(cx);
3279 let snapshot = buffer.snapshot(cx);
3280
3281 let mut edits = Vec::new();
3282 let mut rows = Vec::new();
3283
3284 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3285 let cursor = selection.head();
3286 let row = cursor.row;
3287
3288 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3289
3290 let newline = "\n".to_string();
3291 edits.push((start_of_line..start_of_line, newline));
3292
3293 rows.push(row + rows_inserted as u32);
3294 }
3295
3296 self.transact(window, cx, |editor, window, cx| {
3297 editor.edit(edits, cx);
3298
3299 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3300 let mut index = 0;
3301 s.move_cursors_with(|map, _, _| {
3302 let row = rows[index];
3303 index += 1;
3304
3305 let point = Point::new(row, 0);
3306 let boundary = map.next_line_boundary(point).1;
3307 let clipped = map.clip_point(boundary, Bias::Left);
3308
3309 (clipped, SelectionGoal::None)
3310 });
3311 });
3312
3313 let mut indent_edits = Vec::new();
3314 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3315 for row in rows {
3316 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3317 for (row, indent) in indents {
3318 if indent.len == 0 {
3319 continue;
3320 }
3321
3322 let text = match indent.kind {
3323 IndentKind::Space => " ".repeat(indent.len as usize),
3324 IndentKind::Tab => "\t".repeat(indent.len as usize),
3325 };
3326 let point = Point::new(row.0, 0);
3327 indent_edits.push((point..point, text));
3328 }
3329 }
3330 editor.edit(indent_edits, cx);
3331 });
3332 }
3333
3334 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3335 let buffer = self.buffer.read(cx);
3336 let snapshot = buffer.snapshot(cx);
3337
3338 let mut edits = Vec::new();
3339 let mut rows = Vec::new();
3340 let mut rows_inserted = 0;
3341
3342 for selection in self.selections.all_adjusted(cx) {
3343 let cursor = selection.head();
3344 let row = cursor.row;
3345
3346 let point = Point::new(row + 1, 0);
3347 let start_of_line = snapshot.clip_point(point, Bias::Left);
3348
3349 let newline = "\n".to_string();
3350 edits.push((start_of_line..start_of_line, newline));
3351
3352 rows_inserted += 1;
3353 rows.push(row + rows_inserted);
3354 }
3355
3356 self.transact(window, cx, |editor, window, cx| {
3357 editor.edit(edits, cx);
3358
3359 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3360 let mut index = 0;
3361 s.move_cursors_with(|map, _, _| {
3362 let row = rows[index];
3363 index += 1;
3364
3365 let point = Point::new(row, 0);
3366 let boundary = map.next_line_boundary(point).1;
3367 let clipped = map.clip_point(boundary, Bias::Left);
3368
3369 (clipped, SelectionGoal::None)
3370 });
3371 });
3372
3373 let mut indent_edits = Vec::new();
3374 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3375 for row in rows {
3376 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3377 for (row, indent) in indents {
3378 if indent.len == 0 {
3379 continue;
3380 }
3381
3382 let text = match indent.kind {
3383 IndentKind::Space => " ".repeat(indent.len as usize),
3384 IndentKind::Tab => "\t".repeat(indent.len as usize),
3385 };
3386 let point = Point::new(row.0, 0);
3387 indent_edits.push((point..point, text));
3388 }
3389 }
3390 editor.edit(indent_edits, cx);
3391 });
3392 }
3393
3394 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3395 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3396 original_indent_columns: Vec::new(),
3397 });
3398 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3399 }
3400
3401 fn insert_with_autoindent_mode(
3402 &mut self,
3403 text: &str,
3404 autoindent_mode: Option<AutoindentMode>,
3405 window: &mut Window,
3406 cx: &mut Context<Self>,
3407 ) {
3408 if self.read_only(cx) {
3409 return;
3410 }
3411
3412 let text: Arc<str> = text.into();
3413 self.transact(window, cx, |this, window, cx| {
3414 let old_selections = this.selections.all_adjusted(cx);
3415 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3416 let anchors = {
3417 let snapshot = buffer.read(cx);
3418 old_selections
3419 .iter()
3420 .map(|s| {
3421 let anchor = snapshot.anchor_after(s.head());
3422 s.map(|_| anchor)
3423 })
3424 .collect::<Vec<_>>()
3425 };
3426 buffer.edit(
3427 old_selections
3428 .iter()
3429 .map(|s| (s.start..s.end, text.clone())),
3430 autoindent_mode,
3431 cx,
3432 );
3433 anchors
3434 });
3435
3436 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3437 s.select_anchors(selection_anchors);
3438 });
3439
3440 cx.notify();
3441 });
3442 }
3443
3444 fn trigger_completion_on_input(
3445 &mut self,
3446 text: &str,
3447 trigger_in_words: bool,
3448 window: &mut Window,
3449 cx: &mut Context<Self>,
3450 ) {
3451 if self.is_completion_trigger(text, trigger_in_words, cx) {
3452 self.show_completions(
3453 &ShowCompletions {
3454 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3455 },
3456 window,
3457 cx,
3458 );
3459 } else {
3460 self.hide_context_menu(window, cx);
3461 }
3462 }
3463
3464 fn is_completion_trigger(
3465 &self,
3466 text: &str,
3467 trigger_in_words: bool,
3468 cx: &mut Context<Self>,
3469 ) -> bool {
3470 let position = self.selections.newest_anchor().head();
3471 let multibuffer = self.buffer.read(cx);
3472 let Some(buffer) = position
3473 .buffer_id
3474 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3475 else {
3476 return false;
3477 };
3478
3479 if let Some(completion_provider) = &self.completion_provider {
3480 completion_provider.is_completion_trigger(
3481 &buffer,
3482 position.text_anchor,
3483 text,
3484 trigger_in_words,
3485 cx,
3486 )
3487 } else {
3488 false
3489 }
3490 }
3491
3492 /// If any empty selections is touching the start of its innermost containing autoclose
3493 /// region, expand it to select the brackets.
3494 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3495 let selections = self.selections.all::<usize>(cx);
3496 let buffer = self.buffer.read(cx).read(cx);
3497 let new_selections = self
3498 .selections_with_autoclose_regions(selections, &buffer)
3499 .map(|(mut selection, region)| {
3500 if !selection.is_empty() {
3501 return selection;
3502 }
3503
3504 if let Some(region) = region {
3505 let mut range = region.range.to_offset(&buffer);
3506 if selection.start == range.start && range.start >= region.pair.start.len() {
3507 range.start -= region.pair.start.len();
3508 if buffer.contains_str_at(range.start, ®ion.pair.start)
3509 && buffer.contains_str_at(range.end, ®ion.pair.end)
3510 {
3511 range.end += region.pair.end.len();
3512 selection.start = range.start;
3513 selection.end = range.end;
3514
3515 return selection;
3516 }
3517 }
3518 }
3519
3520 let always_treat_brackets_as_autoclosed = buffer
3521 .settings_at(selection.start, cx)
3522 .always_treat_brackets_as_autoclosed;
3523
3524 if !always_treat_brackets_as_autoclosed {
3525 return selection;
3526 }
3527
3528 if let Some(scope) = buffer.language_scope_at(selection.start) {
3529 for (pair, enabled) in scope.brackets() {
3530 if !enabled || !pair.close {
3531 continue;
3532 }
3533
3534 if buffer.contains_str_at(selection.start, &pair.end) {
3535 let pair_start_len = pair.start.len();
3536 if buffer.contains_str_at(
3537 selection.start.saturating_sub(pair_start_len),
3538 &pair.start,
3539 ) {
3540 selection.start -= pair_start_len;
3541 selection.end += pair.end.len();
3542
3543 return selection;
3544 }
3545 }
3546 }
3547 }
3548
3549 selection
3550 })
3551 .collect();
3552
3553 drop(buffer);
3554 self.change_selections(None, window, cx, |selections| {
3555 selections.select(new_selections)
3556 });
3557 }
3558
3559 /// Iterate the given selections, and for each one, find the smallest surrounding
3560 /// autoclose region. This uses the ordering of the selections and the autoclose
3561 /// regions to avoid repeated comparisons.
3562 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3563 &'a self,
3564 selections: impl IntoIterator<Item = Selection<D>>,
3565 buffer: &'a MultiBufferSnapshot,
3566 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3567 let mut i = 0;
3568 let mut regions = self.autoclose_regions.as_slice();
3569 selections.into_iter().map(move |selection| {
3570 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3571
3572 let mut enclosing = None;
3573 while let Some(pair_state) = regions.get(i) {
3574 if pair_state.range.end.to_offset(buffer) < range.start {
3575 regions = ®ions[i + 1..];
3576 i = 0;
3577 } else if pair_state.range.start.to_offset(buffer) > range.end {
3578 break;
3579 } else {
3580 if pair_state.selection_id == selection.id {
3581 enclosing = Some(pair_state);
3582 }
3583 i += 1;
3584 }
3585 }
3586
3587 (selection, enclosing)
3588 })
3589 }
3590
3591 /// Remove any autoclose regions that no longer contain their selection.
3592 fn invalidate_autoclose_regions(
3593 &mut self,
3594 mut selections: &[Selection<Anchor>],
3595 buffer: &MultiBufferSnapshot,
3596 ) {
3597 self.autoclose_regions.retain(|state| {
3598 let mut i = 0;
3599 while let Some(selection) = selections.get(i) {
3600 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3601 selections = &selections[1..];
3602 continue;
3603 }
3604 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3605 break;
3606 }
3607 if selection.id == state.selection_id {
3608 return true;
3609 } else {
3610 i += 1;
3611 }
3612 }
3613 false
3614 });
3615 }
3616
3617 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3618 let offset = position.to_offset(buffer);
3619 let (word_range, kind) = buffer.surrounding_word(offset, true);
3620 if offset > word_range.start && kind == Some(CharKind::Word) {
3621 Some(
3622 buffer
3623 .text_for_range(word_range.start..offset)
3624 .collect::<String>(),
3625 )
3626 } else {
3627 None
3628 }
3629 }
3630
3631 pub fn toggle_inlay_hints(
3632 &mut self,
3633 _: &ToggleInlayHints,
3634 _: &mut Window,
3635 cx: &mut Context<Self>,
3636 ) {
3637 self.refresh_inlay_hints(
3638 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3639 cx,
3640 );
3641 }
3642
3643 pub fn inlay_hints_enabled(&self) -> bool {
3644 self.inlay_hint_cache.enabled
3645 }
3646
3647 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3648 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3649 return;
3650 }
3651
3652 let reason_description = reason.description();
3653 let ignore_debounce = matches!(
3654 reason,
3655 InlayHintRefreshReason::SettingsChange(_)
3656 | InlayHintRefreshReason::Toggle(_)
3657 | InlayHintRefreshReason::ExcerptsRemoved(_)
3658 );
3659 let (invalidate_cache, required_languages) = match reason {
3660 InlayHintRefreshReason::Toggle(enabled) => {
3661 self.inlay_hint_cache.enabled = enabled;
3662 if enabled {
3663 (InvalidationStrategy::RefreshRequested, None)
3664 } else {
3665 self.inlay_hint_cache.clear();
3666 self.splice_inlays(
3667 &self
3668 .visible_inlay_hints(cx)
3669 .iter()
3670 .map(|inlay| inlay.id)
3671 .collect::<Vec<InlayId>>(),
3672 Vec::new(),
3673 cx,
3674 );
3675 return;
3676 }
3677 }
3678 InlayHintRefreshReason::SettingsChange(new_settings) => {
3679 match self.inlay_hint_cache.update_settings(
3680 &self.buffer,
3681 new_settings,
3682 self.visible_inlay_hints(cx),
3683 cx,
3684 ) {
3685 ControlFlow::Break(Some(InlaySplice {
3686 to_remove,
3687 to_insert,
3688 })) => {
3689 self.splice_inlays(&to_remove, to_insert, cx);
3690 return;
3691 }
3692 ControlFlow::Break(None) => return,
3693 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3694 }
3695 }
3696 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3697 if let Some(InlaySplice {
3698 to_remove,
3699 to_insert,
3700 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3701 {
3702 self.splice_inlays(&to_remove, to_insert, cx);
3703 }
3704 return;
3705 }
3706 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3707 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3708 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3709 }
3710 InlayHintRefreshReason::RefreshRequested => {
3711 (InvalidationStrategy::RefreshRequested, None)
3712 }
3713 };
3714
3715 if let Some(InlaySplice {
3716 to_remove,
3717 to_insert,
3718 }) = self.inlay_hint_cache.spawn_hint_refresh(
3719 reason_description,
3720 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3721 invalidate_cache,
3722 ignore_debounce,
3723 cx,
3724 ) {
3725 self.splice_inlays(&to_remove, to_insert, cx);
3726 }
3727 }
3728
3729 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3730 self.display_map
3731 .read(cx)
3732 .current_inlays()
3733 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3734 .cloned()
3735 .collect()
3736 }
3737
3738 pub fn excerpts_for_inlay_hints_query(
3739 &self,
3740 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3741 cx: &mut Context<Editor>,
3742 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3743 let Some(project) = self.project.as_ref() else {
3744 return HashMap::default();
3745 };
3746 let project = project.read(cx);
3747 let multi_buffer = self.buffer().read(cx);
3748 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3749 let multi_buffer_visible_start = self
3750 .scroll_manager
3751 .anchor()
3752 .anchor
3753 .to_point(&multi_buffer_snapshot);
3754 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3755 multi_buffer_visible_start
3756 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3757 Bias::Left,
3758 );
3759 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3760 multi_buffer_snapshot
3761 .range_to_buffer_ranges(multi_buffer_visible_range)
3762 .into_iter()
3763 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3764 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3765 let buffer_file = project::File::from_dyn(buffer.file())?;
3766 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3767 let worktree_entry = buffer_worktree
3768 .read(cx)
3769 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3770 if worktree_entry.is_ignored {
3771 return None;
3772 }
3773
3774 let language = buffer.language()?;
3775 if let Some(restrict_to_languages) = restrict_to_languages {
3776 if !restrict_to_languages.contains(language) {
3777 return None;
3778 }
3779 }
3780 Some((
3781 excerpt_id,
3782 (
3783 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3784 buffer.version().clone(),
3785 excerpt_visible_range,
3786 ),
3787 ))
3788 })
3789 .collect()
3790 }
3791
3792 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3793 TextLayoutDetails {
3794 text_system: window.text_system().clone(),
3795 editor_style: self.style.clone().unwrap(),
3796 rem_size: window.rem_size(),
3797 scroll_anchor: self.scroll_manager.anchor(),
3798 visible_rows: self.visible_line_count(),
3799 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3800 }
3801 }
3802
3803 pub fn splice_inlays(
3804 &self,
3805 to_remove: &[InlayId],
3806 to_insert: Vec<Inlay>,
3807 cx: &mut Context<Self>,
3808 ) {
3809 self.display_map.update(cx, |display_map, cx| {
3810 display_map.splice_inlays(to_remove, to_insert, cx)
3811 });
3812 cx.notify();
3813 }
3814
3815 fn trigger_on_type_formatting(
3816 &self,
3817 input: String,
3818 window: &mut Window,
3819 cx: &mut Context<Self>,
3820 ) -> Option<Task<Result<()>>> {
3821 if input.len() != 1 {
3822 return None;
3823 }
3824
3825 let project = self.project.as_ref()?;
3826 let position = self.selections.newest_anchor().head();
3827 let (buffer, buffer_position) = self
3828 .buffer
3829 .read(cx)
3830 .text_anchor_for_position(position, cx)?;
3831
3832 let settings = language_settings::language_settings(
3833 buffer
3834 .read(cx)
3835 .language_at(buffer_position)
3836 .map(|l| l.name()),
3837 buffer.read(cx).file(),
3838 cx,
3839 );
3840 if !settings.use_on_type_format {
3841 return None;
3842 }
3843
3844 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3845 // hence we do LSP request & edit on host side only — add formats to host's history.
3846 let push_to_lsp_host_history = true;
3847 // If this is not the host, append its history with new edits.
3848 let push_to_client_history = project.read(cx).is_via_collab();
3849
3850 let on_type_formatting = project.update(cx, |project, cx| {
3851 project.on_type_format(
3852 buffer.clone(),
3853 buffer_position,
3854 input,
3855 push_to_lsp_host_history,
3856 cx,
3857 )
3858 });
3859 Some(cx.spawn_in(window, |editor, mut cx| async move {
3860 if let Some(transaction) = on_type_formatting.await? {
3861 if push_to_client_history {
3862 buffer
3863 .update(&mut cx, |buffer, _| {
3864 buffer.push_transaction(transaction, Instant::now());
3865 })
3866 .ok();
3867 }
3868 editor.update(&mut cx, |editor, cx| {
3869 editor.refresh_document_highlights(cx);
3870 })?;
3871 }
3872 Ok(())
3873 }))
3874 }
3875
3876 pub fn show_completions(
3877 &mut self,
3878 options: &ShowCompletions,
3879 window: &mut Window,
3880 cx: &mut Context<Self>,
3881 ) {
3882 if self.pending_rename.is_some() {
3883 return;
3884 }
3885
3886 let Some(provider) = self.completion_provider.as_ref() else {
3887 return;
3888 };
3889
3890 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3891 return;
3892 }
3893
3894 let position = self.selections.newest_anchor().head();
3895 if position.diff_base_anchor.is_some() {
3896 return;
3897 }
3898 let (buffer, buffer_position) =
3899 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3900 output
3901 } else {
3902 return;
3903 };
3904 let show_completion_documentation = buffer
3905 .read(cx)
3906 .snapshot()
3907 .settings_at(buffer_position, cx)
3908 .show_completion_documentation;
3909
3910 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3911
3912 let trigger_kind = match &options.trigger {
3913 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3914 CompletionTriggerKind::TRIGGER_CHARACTER
3915 }
3916 _ => CompletionTriggerKind::INVOKED,
3917 };
3918 let completion_context = CompletionContext {
3919 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3920 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3921 Some(String::from(trigger))
3922 } else {
3923 None
3924 }
3925 }),
3926 trigger_kind,
3927 };
3928 let completions =
3929 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3930 let sort_completions = provider.sort_completions();
3931
3932 let id = post_inc(&mut self.next_completion_id);
3933 let task = cx.spawn_in(window, |editor, mut cx| {
3934 async move {
3935 editor.update(&mut cx, |this, _| {
3936 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3937 })?;
3938 let completions = completions.await.log_err();
3939 let menu = if let Some(completions) = completions {
3940 let mut menu = CompletionsMenu::new(
3941 id,
3942 sort_completions,
3943 show_completion_documentation,
3944 position,
3945 buffer.clone(),
3946 completions.into(),
3947 );
3948
3949 menu.filter(query.as_deref(), cx.background_executor().clone())
3950 .await;
3951
3952 menu.visible().then_some(menu)
3953 } else {
3954 None
3955 };
3956
3957 editor.update_in(&mut cx, |editor, window, cx| {
3958 match editor.context_menu.borrow().as_ref() {
3959 None => {}
3960 Some(CodeContextMenu::Completions(prev_menu)) => {
3961 if prev_menu.id > id {
3962 return;
3963 }
3964 }
3965 _ => return,
3966 }
3967
3968 if editor.focus_handle.is_focused(window) && menu.is_some() {
3969 let mut menu = menu.unwrap();
3970 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3971
3972 *editor.context_menu.borrow_mut() =
3973 Some(CodeContextMenu::Completions(menu));
3974
3975 if editor.show_edit_predictions_in_menu() {
3976 editor.update_visible_inline_completion(window, cx);
3977 } else {
3978 editor.discard_inline_completion(false, cx);
3979 }
3980
3981 cx.notify();
3982 } else if editor.completion_tasks.len() <= 1 {
3983 // If there are no more completion tasks and the last menu was
3984 // empty, we should hide it.
3985 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3986 // If it was already hidden and we don't show inline
3987 // completions in the menu, we should also show the
3988 // inline-completion when available.
3989 if was_hidden && editor.show_edit_predictions_in_menu() {
3990 editor.update_visible_inline_completion(window, cx);
3991 }
3992 }
3993 })?;
3994
3995 Ok::<_, anyhow::Error>(())
3996 }
3997 .log_err()
3998 });
3999
4000 self.completion_tasks.push((id, task));
4001 }
4002
4003 pub fn confirm_completion(
4004 &mut self,
4005 action: &ConfirmCompletion,
4006 window: &mut Window,
4007 cx: &mut Context<Self>,
4008 ) -> Option<Task<Result<()>>> {
4009 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4010 }
4011
4012 pub fn compose_completion(
4013 &mut self,
4014 action: &ComposeCompletion,
4015 window: &mut Window,
4016 cx: &mut Context<Self>,
4017 ) -> Option<Task<Result<()>>> {
4018 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4019 }
4020
4021 fn do_completion(
4022 &mut self,
4023 item_ix: Option<usize>,
4024 intent: CompletionIntent,
4025 window: &mut Window,
4026 cx: &mut Context<Editor>,
4027 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4028 use language::ToOffset as _;
4029
4030 let completions_menu =
4031 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4032 menu
4033 } else {
4034 return None;
4035 };
4036
4037 let entries = completions_menu.entries.borrow();
4038 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4039 if self.show_edit_predictions_in_menu() {
4040 self.discard_inline_completion(true, cx);
4041 }
4042 let candidate_id = mat.candidate_id;
4043 drop(entries);
4044
4045 let buffer_handle = completions_menu.buffer;
4046 let completion = completions_menu
4047 .completions
4048 .borrow()
4049 .get(candidate_id)?
4050 .clone();
4051 cx.stop_propagation();
4052
4053 let snippet;
4054 let text;
4055
4056 if completion.is_snippet() {
4057 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4058 text = snippet.as_ref().unwrap().text.clone();
4059 } else {
4060 snippet = None;
4061 text = completion.new_text.clone();
4062 };
4063 let selections = self.selections.all::<usize>(cx);
4064 let buffer = buffer_handle.read(cx);
4065 let old_range = completion.old_range.to_offset(buffer);
4066 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4067
4068 let newest_selection = self.selections.newest_anchor();
4069 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4070 return None;
4071 }
4072
4073 let lookbehind = newest_selection
4074 .start
4075 .text_anchor
4076 .to_offset(buffer)
4077 .saturating_sub(old_range.start);
4078 let lookahead = old_range
4079 .end
4080 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4081 let mut common_prefix_len = old_text
4082 .bytes()
4083 .zip(text.bytes())
4084 .take_while(|(a, b)| a == b)
4085 .count();
4086
4087 let snapshot = self.buffer.read(cx).snapshot(cx);
4088 let mut range_to_replace: Option<Range<isize>> = None;
4089 let mut ranges = Vec::new();
4090 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4091 for selection in &selections {
4092 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4093 let start = selection.start.saturating_sub(lookbehind);
4094 let end = selection.end + lookahead;
4095 if selection.id == newest_selection.id {
4096 range_to_replace = Some(
4097 ((start + common_prefix_len) as isize - selection.start as isize)
4098 ..(end as isize - selection.start as isize),
4099 );
4100 }
4101 ranges.push(start + common_prefix_len..end);
4102 } else {
4103 common_prefix_len = 0;
4104 ranges.clear();
4105 ranges.extend(selections.iter().map(|s| {
4106 if s.id == newest_selection.id {
4107 range_to_replace = Some(
4108 old_range.start.to_offset_utf16(&snapshot).0 as isize
4109 - selection.start as isize
4110 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4111 - selection.start as isize,
4112 );
4113 old_range.clone()
4114 } else {
4115 s.start..s.end
4116 }
4117 }));
4118 break;
4119 }
4120 if !self.linked_edit_ranges.is_empty() {
4121 let start_anchor = snapshot.anchor_before(selection.head());
4122 let end_anchor = snapshot.anchor_after(selection.tail());
4123 if let Some(ranges) = self
4124 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4125 {
4126 for (buffer, edits) in ranges {
4127 linked_edits.entry(buffer.clone()).or_default().extend(
4128 edits
4129 .into_iter()
4130 .map(|range| (range, text[common_prefix_len..].to_owned())),
4131 );
4132 }
4133 }
4134 }
4135 }
4136 let text = &text[common_prefix_len..];
4137
4138 cx.emit(EditorEvent::InputHandled {
4139 utf16_range_to_replace: range_to_replace,
4140 text: text.into(),
4141 });
4142
4143 self.transact(window, cx, |this, window, cx| {
4144 if let Some(mut snippet) = snippet {
4145 snippet.text = text.to_string();
4146 for tabstop in snippet
4147 .tabstops
4148 .iter_mut()
4149 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4150 {
4151 tabstop.start -= common_prefix_len as isize;
4152 tabstop.end -= common_prefix_len as isize;
4153 }
4154
4155 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4156 } else {
4157 this.buffer.update(cx, |buffer, cx| {
4158 buffer.edit(
4159 ranges.iter().map(|range| (range.clone(), text)),
4160 this.autoindent_mode.clone(),
4161 cx,
4162 );
4163 });
4164 }
4165 for (buffer, edits) in linked_edits {
4166 buffer.update(cx, |buffer, cx| {
4167 let snapshot = buffer.snapshot();
4168 let edits = edits
4169 .into_iter()
4170 .map(|(range, text)| {
4171 use text::ToPoint as TP;
4172 let end_point = TP::to_point(&range.end, &snapshot);
4173 let start_point = TP::to_point(&range.start, &snapshot);
4174 (start_point..end_point, text)
4175 })
4176 .sorted_by_key(|(range, _)| range.start)
4177 .collect::<Vec<_>>();
4178 buffer.edit(edits, None, cx);
4179 })
4180 }
4181
4182 this.refresh_inline_completion(true, false, window, cx);
4183 });
4184
4185 let show_new_completions_on_confirm = completion
4186 .confirm
4187 .as_ref()
4188 .map_or(false, |confirm| confirm(intent, window, cx));
4189 if show_new_completions_on_confirm {
4190 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4191 }
4192
4193 let provider = self.completion_provider.as_ref()?;
4194 drop(completion);
4195 let apply_edits = provider.apply_additional_edits_for_completion(
4196 buffer_handle,
4197 completions_menu.completions.clone(),
4198 candidate_id,
4199 true,
4200 cx,
4201 );
4202
4203 let editor_settings = EditorSettings::get_global(cx);
4204 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4205 // After the code completion is finished, users often want to know what signatures are needed.
4206 // so we should automatically call signature_help
4207 self.show_signature_help(&ShowSignatureHelp, window, cx);
4208 }
4209
4210 Some(cx.foreground_executor().spawn(async move {
4211 apply_edits.await?;
4212 Ok(())
4213 }))
4214 }
4215
4216 pub fn toggle_code_actions(
4217 &mut self,
4218 action: &ToggleCodeActions,
4219 window: &mut Window,
4220 cx: &mut Context<Self>,
4221 ) {
4222 let mut context_menu = self.context_menu.borrow_mut();
4223 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4224 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4225 // Toggle if we're selecting the same one
4226 *context_menu = None;
4227 cx.notify();
4228 return;
4229 } else {
4230 // Otherwise, clear it and start a new one
4231 *context_menu = None;
4232 cx.notify();
4233 }
4234 }
4235 drop(context_menu);
4236 let snapshot = self.snapshot(window, cx);
4237 let deployed_from_indicator = action.deployed_from_indicator;
4238 let mut task = self.code_actions_task.take();
4239 let action = action.clone();
4240 cx.spawn_in(window, |editor, mut cx| async move {
4241 while let Some(prev_task) = task {
4242 prev_task.await.log_err();
4243 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4244 }
4245
4246 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4247 if editor.focus_handle.is_focused(window) {
4248 let multibuffer_point = action
4249 .deployed_from_indicator
4250 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4251 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4252 let (buffer, buffer_row) = snapshot
4253 .buffer_snapshot
4254 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4255 .and_then(|(buffer_snapshot, range)| {
4256 editor
4257 .buffer
4258 .read(cx)
4259 .buffer(buffer_snapshot.remote_id())
4260 .map(|buffer| (buffer, range.start.row))
4261 })?;
4262 let (_, code_actions) = editor
4263 .available_code_actions
4264 .clone()
4265 .and_then(|(location, code_actions)| {
4266 let snapshot = location.buffer.read(cx).snapshot();
4267 let point_range = location.range.to_point(&snapshot);
4268 let point_range = point_range.start.row..=point_range.end.row;
4269 if point_range.contains(&buffer_row) {
4270 Some((location, code_actions))
4271 } else {
4272 None
4273 }
4274 })
4275 .unzip();
4276 let buffer_id = buffer.read(cx).remote_id();
4277 let tasks = editor
4278 .tasks
4279 .get(&(buffer_id, buffer_row))
4280 .map(|t| Arc::new(t.to_owned()));
4281 if tasks.is_none() && code_actions.is_none() {
4282 return None;
4283 }
4284
4285 editor.completion_tasks.clear();
4286 editor.discard_inline_completion(false, cx);
4287 let task_context =
4288 tasks
4289 .as_ref()
4290 .zip(editor.project.clone())
4291 .map(|(tasks, project)| {
4292 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4293 });
4294
4295 Some(cx.spawn_in(window, |editor, mut cx| async move {
4296 let task_context = match task_context {
4297 Some(task_context) => task_context.await,
4298 None => None,
4299 };
4300 let resolved_tasks =
4301 tasks.zip(task_context).map(|(tasks, task_context)| {
4302 Rc::new(ResolvedTasks {
4303 templates: tasks.resolve(&task_context).collect(),
4304 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4305 multibuffer_point.row,
4306 tasks.column,
4307 )),
4308 })
4309 });
4310 let spawn_straight_away = resolved_tasks
4311 .as_ref()
4312 .map_or(false, |tasks| tasks.templates.len() == 1)
4313 && code_actions
4314 .as_ref()
4315 .map_or(true, |actions| actions.is_empty());
4316 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4317 *editor.context_menu.borrow_mut() =
4318 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4319 buffer,
4320 actions: CodeActionContents {
4321 tasks: resolved_tasks,
4322 actions: code_actions,
4323 },
4324 selected_item: Default::default(),
4325 scroll_handle: UniformListScrollHandle::default(),
4326 deployed_from_indicator,
4327 }));
4328 if spawn_straight_away {
4329 if let Some(task) = editor.confirm_code_action(
4330 &ConfirmCodeAction { item_ix: Some(0) },
4331 window,
4332 cx,
4333 ) {
4334 cx.notify();
4335 return task;
4336 }
4337 }
4338 cx.notify();
4339 Task::ready(Ok(()))
4340 }) {
4341 task.await
4342 } else {
4343 Ok(())
4344 }
4345 }))
4346 } else {
4347 Some(Task::ready(Ok(())))
4348 }
4349 })?;
4350 if let Some(task) = spawned_test_task {
4351 task.await?;
4352 }
4353
4354 Ok::<_, anyhow::Error>(())
4355 })
4356 .detach_and_log_err(cx);
4357 }
4358
4359 pub fn confirm_code_action(
4360 &mut self,
4361 action: &ConfirmCodeAction,
4362 window: &mut Window,
4363 cx: &mut Context<Self>,
4364 ) -> Option<Task<Result<()>>> {
4365 let actions_menu =
4366 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4367 menu
4368 } else {
4369 return None;
4370 };
4371 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4372 let action = actions_menu.actions.get(action_ix)?;
4373 let title = action.label();
4374 let buffer = actions_menu.buffer;
4375 let workspace = self.workspace()?;
4376
4377 match action {
4378 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4379 workspace.update(cx, |workspace, cx| {
4380 workspace::tasks::schedule_resolved_task(
4381 workspace,
4382 task_source_kind,
4383 resolved_task,
4384 false,
4385 cx,
4386 );
4387
4388 Some(Task::ready(Ok(())))
4389 })
4390 }
4391 CodeActionsItem::CodeAction {
4392 excerpt_id,
4393 action,
4394 provider,
4395 } => {
4396 let apply_code_action =
4397 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4398 let workspace = workspace.downgrade();
4399 Some(cx.spawn_in(window, |editor, cx| async move {
4400 let project_transaction = apply_code_action.await?;
4401 Self::open_project_transaction(
4402 &editor,
4403 workspace,
4404 project_transaction,
4405 title,
4406 cx,
4407 )
4408 .await
4409 }))
4410 }
4411 }
4412 }
4413
4414 pub async fn open_project_transaction(
4415 this: &WeakEntity<Editor>,
4416 workspace: WeakEntity<Workspace>,
4417 transaction: ProjectTransaction,
4418 title: String,
4419 mut cx: AsyncWindowContext,
4420 ) -> Result<()> {
4421 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4422 cx.update(|_, cx| {
4423 entries.sort_unstable_by_key(|(buffer, _)| {
4424 buffer.read(cx).file().map(|f| f.path().clone())
4425 });
4426 })?;
4427
4428 // If the project transaction's edits are all contained within this editor, then
4429 // avoid opening a new editor to display them.
4430
4431 if let Some((buffer, transaction)) = entries.first() {
4432 if entries.len() == 1 {
4433 let excerpt = this.update(&mut cx, |editor, cx| {
4434 editor
4435 .buffer()
4436 .read(cx)
4437 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4438 })?;
4439 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4440 if excerpted_buffer == *buffer {
4441 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4442 let excerpt_range = excerpt_range.to_offset(buffer);
4443 buffer
4444 .edited_ranges_for_transaction::<usize>(transaction)
4445 .all(|range| {
4446 excerpt_range.start <= range.start
4447 && excerpt_range.end >= range.end
4448 })
4449 })?;
4450
4451 if all_edits_within_excerpt {
4452 return Ok(());
4453 }
4454 }
4455 }
4456 }
4457 } else {
4458 return Ok(());
4459 }
4460
4461 let mut ranges_to_highlight = Vec::new();
4462 let excerpt_buffer = cx.new(|cx| {
4463 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4464 for (buffer_handle, transaction) in &entries {
4465 let buffer = buffer_handle.read(cx);
4466 ranges_to_highlight.extend(
4467 multibuffer.push_excerpts_with_context_lines(
4468 buffer_handle.clone(),
4469 buffer
4470 .edited_ranges_for_transaction::<usize>(transaction)
4471 .collect(),
4472 DEFAULT_MULTIBUFFER_CONTEXT,
4473 cx,
4474 ),
4475 );
4476 }
4477 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4478 multibuffer
4479 })?;
4480
4481 workspace.update_in(&mut cx, |workspace, window, cx| {
4482 let project = workspace.project().clone();
4483 let editor = cx
4484 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4485 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4486 editor.update(cx, |editor, cx| {
4487 editor.highlight_background::<Self>(
4488 &ranges_to_highlight,
4489 |theme| theme.editor_highlighted_line_background,
4490 cx,
4491 );
4492 });
4493 })?;
4494
4495 Ok(())
4496 }
4497
4498 pub fn clear_code_action_providers(&mut self) {
4499 self.code_action_providers.clear();
4500 self.available_code_actions.take();
4501 }
4502
4503 pub fn add_code_action_provider(
4504 &mut self,
4505 provider: Rc<dyn CodeActionProvider>,
4506 window: &mut Window,
4507 cx: &mut Context<Self>,
4508 ) {
4509 if self
4510 .code_action_providers
4511 .iter()
4512 .any(|existing_provider| existing_provider.id() == provider.id())
4513 {
4514 return;
4515 }
4516
4517 self.code_action_providers.push(provider);
4518 self.refresh_code_actions(window, cx);
4519 }
4520
4521 pub fn remove_code_action_provider(
4522 &mut self,
4523 id: Arc<str>,
4524 window: &mut Window,
4525 cx: &mut Context<Self>,
4526 ) {
4527 self.code_action_providers
4528 .retain(|provider| provider.id() != id);
4529 self.refresh_code_actions(window, cx);
4530 }
4531
4532 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4533 let buffer = self.buffer.read(cx);
4534 let newest_selection = self.selections.newest_anchor().clone();
4535 if newest_selection.head().diff_base_anchor.is_some() {
4536 return None;
4537 }
4538 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4539 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4540 if start_buffer != end_buffer {
4541 return None;
4542 }
4543
4544 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4545 cx.background_executor()
4546 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4547 .await;
4548
4549 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4550 let providers = this.code_action_providers.clone();
4551 let tasks = this
4552 .code_action_providers
4553 .iter()
4554 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4555 .collect::<Vec<_>>();
4556 (providers, tasks)
4557 })?;
4558
4559 let mut actions = Vec::new();
4560 for (provider, provider_actions) in
4561 providers.into_iter().zip(future::join_all(tasks).await)
4562 {
4563 if let Some(provider_actions) = provider_actions.log_err() {
4564 actions.extend(provider_actions.into_iter().map(|action| {
4565 AvailableCodeAction {
4566 excerpt_id: newest_selection.start.excerpt_id,
4567 action,
4568 provider: provider.clone(),
4569 }
4570 }));
4571 }
4572 }
4573
4574 this.update(&mut cx, |this, cx| {
4575 this.available_code_actions = if actions.is_empty() {
4576 None
4577 } else {
4578 Some((
4579 Location {
4580 buffer: start_buffer,
4581 range: start..end,
4582 },
4583 actions.into(),
4584 ))
4585 };
4586 cx.notify();
4587 })
4588 }));
4589 None
4590 }
4591
4592 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4593 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4594 self.show_git_blame_inline = false;
4595
4596 self.show_git_blame_inline_delay_task =
4597 Some(cx.spawn_in(window, |this, mut cx| async move {
4598 cx.background_executor().timer(delay).await;
4599
4600 this.update(&mut cx, |this, cx| {
4601 this.show_git_blame_inline = true;
4602 cx.notify();
4603 })
4604 .log_err();
4605 }));
4606 }
4607 }
4608
4609 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4610 if self.pending_rename.is_some() {
4611 return None;
4612 }
4613
4614 let provider = self.semantics_provider.clone()?;
4615 let buffer = self.buffer.read(cx);
4616 let newest_selection = self.selections.newest_anchor().clone();
4617 let cursor_position = newest_selection.head();
4618 let (cursor_buffer, cursor_buffer_position) =
4619 buffer.text_anchor_for_position(cursor_position, cx)?;
4620 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4621 if cursor_buffer != tail_buffer {
4622 return None;
4623 }
4624 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4625 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4626 cx.background_executor()
4627 .timer(Duration::from_millis(debounce))
4628 .await;
4629
4630 let highlights = if let Some(highlights) = cx
4631 .update(|cx| {
4632 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4633 })
4634 .ok()
4635 .flatten()
4636 {
4637 highlights.await.log_err()
4638 } else {
4639 None
4640 };
4641
4642 if let Some(highlights) = highlights {
4643 this.update(&mut cx, |this, cx| {
4644 if this.pending_rename.is_some() {
4645 return;
4646 }
4647
4648 let buffer_id = cursor_position.buffer_id;
4649 let buffer = this.buffer.read(cx);
4650 if !buffer
4651 .text_anchor_for_position(cursor_position, cx)
4652 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4653 {
4654 return;
4655 }
4656
4657 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4658 let mut write_ranges = Vec::new();
4659 let mut read_ranges = Vec::new();
4660 for highlight in highlights {
4661 for (excerpt_id, excerpt_range) in
4662 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4663 {
4664 let start = highlight
4665 .range
4666 .start
4667 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4668 let end = highlight
4669 .range
4670 .end
4671 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4672 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4673 continue;
4674 }
4675
4676 let range = Anchor {
4677 buffer_id,
4678 excerpt_id,
4679 text_anchor: start,
4680 diff_base_anchor: None,
4681 }..Anchor {
4682 buffer_id,
4683 excerpt_id,
4684 text_anchor: end,
4685 diff_base_anchor: None,
4686 };
4687 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4688 write_ranges.push(range);
4689 } else {
4690 read_ranges.push(range);
4691 }
4692 }
4693 }
4694
4695 this.highlight_background::<DocumentHighlightRead>(
4696 &read_ranges,
4697 |theme| theme.editor_document_highlight_read_background,
4698 cx,
4699 );
4700 this.highlight_background::<DocumentHighlightWrite>(
4701 &write_ranges,
4702 |theme| theme.editor_document_highlight_write_background,
4703 cx,
4704 );
4705 cx.notify();
4706 })
4707 .log_err();
4708 }
4709 }));
4710 None
4711 }
4712
4713 pub fn refresh_selected_text_highlights(
4714 &mut self,
4715 window: &mut Window,
4716 cx: &mut Context<Editor>,
4717 ) {
4718 self.selection_highlight_task.take();
4719 if !EditorSettings::get_global(cx).selection_highlight {
4720 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4721 return;
4722 }
4723 if self.selections.count() != 1 || self.selections.line_mode {
4724 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4725 return;
4726 }
4727 let selection = self.selections.newest::<Point>(cx);
4728 if selection.is_empty() || selection.start.row != selection.end.row {
4729 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4730 return;
4731 }
4732 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4733 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4734 cx.background_executor()
4735 .timer(Duration::from_millis(debounce))
4736 .await;
4737 let Some(Some(matches_task)) = editor
4738 .update_in(&mut cx, |editor, _, cx| {
4739 if editor.selections.count() != 1 || editor.selections.line_mode {
4740 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4741 return None;
4742 }
4743 let selection = editor.selections.newest::<Point>(cx);
4744 if selection.is_empty() || selection.start.row != selection.end.row {
4745 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4746 return None;
4747 }
4748 let buffer = editor.buffer().read(cx).snapshot(cx);
4749 Some(cx.background_spawn(async move {
4750 let mut ranges = Vec::new();
4751 let query = buffer.text_for_range(selection.range()).collect::<String>();
4752 let selection_anchors = selection.range().to_anchors(&buffer);
4753 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4754 for (search_buffer, search_range, excerpt_id) in
4755 buffer.range_to_buffer_ranges(range)
4756 {
4757 ranges.extend(
4758 project::search::SearchQuery::text(
4759 query.clone(),
4760 false,
4761 false,
4762 false,
4763 Default::default(),
4764 Default::default(),
4765 None,
4766 )
4767 .unwrap()
4768 .search(search_buffer, Some(search_range.clone()))
4769 .await
4770 .into_iter()
4771 .filter_map(
4772 |match_range| {
4773 let start = search_buffer.anchor_after(
4774 search_range.start + match_range.start,
4775 );
4776 let end = search_buffer.anchor_before(
4777 search_range.start + match_range.end,
4778 );
4779 let range = Anchor::range_in_buffer(
4780 excerpt_id,
4781 search_buffer.remote_id(),
4782 start..end,
4783 );
4784 (range != selection_anchors).then_some(range)
4785 },
4786 ),
4787 );
4788 }
4789 }
4790 ranges
4791 }))
4792 })
4793 .log_err()
4794 else {
4795 return;
4796 };
4797 let matches = matches_task.await;
4798 editor
4799 .update_in(&mut cx, |editor, _, cx| {
4800 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4801 if !matches.is_empty() {
4802 editor.highlight_background::<SelectedTextHighlight>(
4803 &matches,
4804 |theme| theme.editor_document_highlight_bracket_background,
4805 cx,
4806 )
4807 }
4808 })
4809 .log_err();
4810 }));
4811 }
4812
4813 pub fn refresh_inline_completion(
4814 &mut self,
4815 debounce: bool,
4816 user_requested: bool,
4817 window: &mut Window,
4818 cx: &mut Context<Self>,
4819 ) -> Option<()> {
4820 let provider = self.edit_prediction_provider()?;
4821 let cursor = self.selections.newest_anchor().head();
4822 let (buffer, cursor_buffer_position) =
4823 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4824
4825 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4826 self.discard_inline_completion(false, cx);
4827 return None;
4828 }
4829
4830 if !user_requested
4831 && (!self.should_show_edit_predictions()
4832 || !self.is_focused(window)
4833 || buffer.read(cx).is_empty())
4834 {
4835 self.discard_inline_completion(false, cx);
4836 return None;
4837 }
4838
4839 self.update_visible_inline_completion(window, cx);
4840 provider.refresh(
4841 self.project.clone(),
4842 buffer,
4843 cursor_buffer_position,
4844 debounce,
4845 cx,
4846 );
4847 Some(())
4848 }
4849
4850 fn show_edit_predictions_in_menu(&self) -> bool {
4851 match self.edit_prediction_settings {
4852 EditPredictionSettings::Disabled => false,
4853 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4854 }
4855 }
4856
4857 pub fn edit_predictions_enabled(&self) -> bool {
4858 match self.edit_prediction_settings {
4859 EditPredictionSettings::Disabled => false,
4860 EditPredictionSettings::Enabled { .. } => true,
4861 }
4862 }
4863
4864 fn edit_prediction_requires_modifier(&self) -> bool {
4865 match self.edit_prediction_settings {
4866 EditPredictionSettings::Disabled => false,
4867 EditPredictionSettings::Enabled {
4868 preview_requires_modifier,
4869 ..
4870 } => preview_requires_modifier,
4871 }
4872 }
4873
4874 fn edit_prediction_settings_at_position(
4875 &self,
4876 buffer: &Entity<Buffer>,
4877 buffer_position: language::Anchor,
4878 cx: &App,
4879 ) -> EditPredictionSettings {
4880 if self.mode != EditorMode::Full
4881 || !self.show_inline_completions_override.unwrap_or(true)
4882 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4883 {
4884 return EditPredictionSettings::Disabled;
4885 }
4886
4887 let buffer = buffer.read(cx);
4888
4889 let file = buffer.file();
4890
4891 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4892 return EditPredictionSettings::Disabled;
4893 };
4894
4895 let by_provider = matches!(
4896 self.menu_inline_completions_policy,
4897 MenuInlineCompletionsPolicy::ByProvider
4898 );
4899
4900 let show_in_menu = by_provider
4901 && self
4902 .edit_prediction_provider
4903 .as_ref()
4904 .map_or(false, |provider| {
4905 provider.provider.show_completions_in_menu()
4906 });
4907
4908 let preview_requires_modifier =
4909 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4910
4911 EditPredictionSettings::Enabled {
4912 show_in_menu,
4913 preview_requires_modifier,
4914 }
4915 }
4916
4917 fn should_show_edit_predictions(&self) -> bool {
4918 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4919 }
4920
4921 pub fn edit_prediction_preview_is_active(&self) -> bool {
4922 matches!(
4923 self.edit_prediction_preview,
4924 EditPredictionPreview::Active { .. }
4925 )
4926 }
4927
4928 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4929 let cursor = self.selections.newest_anchor().head();
4930 if let Some((buffer, cursor_position)) =
4931 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4932 {
4933 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4934 } else {
4935 false
4936 }
4937 }
4938
4939 fn inline_completions_enabled_in_buffer(
4940 &self,
4941 buffer: &Entity<Buffer>,
4942 buffer_position: language::Anchor,
4943 cx: &App,
4944 ) -> bool {
4945 maybe!({
4946 let provider = self.edit_prediction_provider()?;
4947 if !provider.is_enabled(&buffer, buffer_position, cx) {
4948 return Some(false);
4949 }
4950 let buffer = buffer.read(cx);
4951 let Some(file) = buffer.file() else {
4952 return Some(true);
4953 };
4954 let settings = all_language_settings(Some(file), cx);
4955 Some(settings.inline_completions_enabled_for_path(file.path()))
4956 })
4957 .unwrap_or(false)
4958 }
4959
4960 fn cycle_inline_completion(
4961 &mut self,
4962 direction: Direction,
4963 window: &mut Window,
4964 cx: &mut Context<Self>,
4965 ) -> Option<()> {
4966 let provider = self.edit_prediction_provider()?;
4967 let cursor = self.selections.newest_anchor().head();
4968 let (buffer, cursor_buffer_position) =
4969 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4970 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4971 return None;
4972 }
4973
4974 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4975 self.update_visible_inline_completion(window, cx);
4976
4977 Some(())
4978 }
4979
4980 pub fn show_inline_completion(
4981 &mut self,
4982 _: &ShowEditPrediction,
4983 window: &mut Window,
4984 cx: &mut Context<Self>,
4985 ) {
4986 if !self.has_active_inline_completion() {
4987 self.refresh_inline_completion(false, true, window, cx);
4988 return;
4989 }
4990
4991 self.update_visible_inline_completion(window, cx);
4992 }
4993
4994 pub fn display_cursor_names(
4995 &mut self,
4996 _: &DisplayCursorNames,
4997 window: &mut Window,
4998 cx: &mut Context<Self>,
4999 ) {
5000 self.show_cursor_names(window, cx);
5001 }
5002
5003 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5004 self.show_cursor_names = true;
5005 cx.notify();
5006 cx.spawn_in(window, |this, mut cx| async move {
5007 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5008 this.update(&mut cx, |this, cx| {
5009 this.show_cursor_names = false;
5010 cx.notify()
5011 })
5012 .ok()
5013 })
5014 .detach();
5015 }
5016
5017 pub fn next_edit_prediction(
5018 &mut self,
5019 _: &NextEditPrediction,
5020 window: &mut Window,
5021 cx: &mut Context<Self>,
5022 ) {
5023 if self.has_active_inline_completion() {
5024 self.cycle_inline_completion(Direction::Next, window, cx);
5025 } else {
5026 let is_copilot_disabled = self
5027 .refresh_inline_completion(false, true, window, cx)
5028 .is_none();
5029 if is_copilot_disabled {
5030 cx.propagate();
5031 }
5032 }
5033 }
5034
5035 pub fn previous_edit_prediction(
5036 &mut self,
5037 _: &PreviousEditPrediction,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 if self.has_active_inline_completion() {
5042 self.cycle_inline_completion(Direction::Prev, 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 accept_edit_prediction(
5054 &mut self,
5055 _: &AcceptEditPrediction,
5056 window: &mut Window,
5057 cx: &mut Context<Self>,
5058 ) {
5059 if self.show_edit_predictions_in_menu() {
5060 self.hide_context_menu(window, cx);
5061 }
5062
5063 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5064 return;
5065 };
5066
5067 self.report_inline_completion_event(
5068 active_inline_completion.completion_id.clone(),
5069 true,
5070 cx,
5071 );
5072
5073 match &active_inline_completion.completion {
5074 InlineCompletion::Move { target, .. } => {
5075 let target = *target;
5076
5077 if let Some(position_map) = &self.last_position_map {
5078 if position_map
5079 .visible_row_range
5080 .contains(&target.to_display_point(&position_map.snapshot).row())
5081 || !self.edit_prediction_requires_modifier()
5082 {
5083 self.unfold_ranges(&[target..target], true, false, cx);
5084 // Note that this is also done in vim's handler of the Tab action.
5085 self.change_selections(
5086 Some(Autoscroll::newest()),
5087 window,
5088 cx,
5089 |selections| {
5090 selections.select_anchor_ranges([target..target]);
5091 },
5092 );
5093 self.clear_row_highlights::<EditPredictionPreview>();
5094
5095 self.edit_prediction_preview = EditPredictionPreview::Active {
5096 previous_scroll_position: None,
5097 };
5098 } else {
5099 self.edit_prediction_preview = EditPredictionPreview::Active {
5100 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5101 };
5102 self.highlight_rows::<EditPredictionPreview>(
5103 target..target,
5104 cx.theme().colors().editor_highlighted_line_background,
5105 true,
5106 cx,
5107 );
5108 self.request_autoscroll(Autoscroll::fit(), cx);
5109 }
5110 }
5111 }
5112 InlineCompletion::Edit { edits, .. } => {
5113 if let Some(provider) = self.edit_prediction_provider() {
5114 provider.accept(cx);
5115 }
5116
5117 let snapshot = self.buffer.read(cx).snapshot(cx);
5118 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5119
5120 self.buffer.update(cx, |buffer, cx| {
5121 buffer.edit(edits.iter().cloned(), None, cx)
5122 });
5123
5124 self.change_selections(None, window, cx, |s| {
5125 s.select_anchor_ranges([last_edit_end..last_edit_end])
5126 });
5127
5128 self.update_visible_inline_completion(window, cx);
5129 if self.active_inline_completion.is_none() {
5130 self.refresh_inline_completion(true, true, window, cx);
5131 }
5132
5133 cx.notify();
5134 }
5135 }
5136
5137 self.edit_prediction_requires_modifier_in_leading_space = false;
5138 }
5139
5140 pub fn accept_partial_inline_completion(
5141 &mut self,
5142 _: &AcceptPartialEditPrediction,
5143 window: &mut Window,
5144 cx: &mut Context<Self>,
5145 ) {
5146 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5147 return;
5148 };
5149 if self.selections.count() != 1 {
5150 return;
5151 }
5152
5153 self.report_inline_completion_event(
5154 active_inline_completion.completion_id.clone(),
5155 true,
5156 cx,
5157 );
5158
5159 match &active_inline_completion.completion {
5160 InlineCompletion::Move { target, .. } => {
5161 let target = *target;
5162 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5163 selections.select_anchor_ranges([target..target]);
5164 });
5165 }
5166 InlineCompletion::Edit { edits, .. } => {
5167 // Find an insertion that starts at the cursor position.
5168 let snapshot = self.buffer.read(cx).snapshot(cx);
5169 let cursor_offset = self.selections.newest::<usize>(cx).head();
5170 let insertion = edits.iter().find_map(|(range, text)| {
5171 let range = range.to_offset(&snapshot);
5172 if range.is_empty() && range.start == cursor_offset {
5173 Some(text)
5174 } else {
5175 None
5176 }
5177 });
5178
5179 if let Some(text) = insertion {
5180 let mut partial_completion = text
5181 .chars()
5182 .by_ref()
5183 .take_while(|c| c.is_alphabetic())
5184 .collect::<String>();
5185 if partial_completion.is_empty() {
5186 partial_completion = text
5187 .chars()
5188 .by_ref()
5189 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5190 .collect::<String>();
5191 }
5192
5193 cx.emit(EditorEvent::InputHandled {
5194 utf16_range_to_replace: None,
5195 text: partial_completion.clone().into(),
5196 });
5197
5198 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5199
5200 self.refresh_inline_completion(true, true, window, cx);
5201 cx.notify();
5202 } else {
5203 self.accept_edit_prediction(&Default::default(), window, cx);
5204 }
5205 }
5206 }
5207 }
5208
5209 fn discard_inline_completion(
5210 &mut self,
5211 should_report_inline_completion_event: bool,
5212 cx: &mut Context<Self>,
5213 ) -> bool {
5214 if should_report_inline_completion_event {
5215 let completion_id = self
5216 .active_inline_completion
5217 .as_ref()
5218 .and_then(|active_completion| active_completion.completion_id.clone());
5219
5220 self.report_inline_completion_event(completion_id, false, cx);
5221 }
5222
5223 if let Some(provider) = self.edit_prediction_provider() {
5224 provider.discard(cx);
5225 }
5226
5227 self.take_active_inline_completion(cx)
5228 }
5229
5230 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5231 let Some(provider) = self.edit_prediction_provider() else {
5232 return;
5233 };
5234
5235 let Some((_, buffer, _)) = self
5236 .buffer
5237 .read(cx)
5238 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5239 else {
5240 return;
5241 };
5242
5243 let extension = buffer
5244 .read(cx)
5245 .file()
5246 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5247
5248 let event_type = match accepted {
5249 true => "Edit Prediction Accepted",
5250 false => "Edit Prediction Discarded",
5251 };
5252 telemetry::event!(
5253 event_type,
5254 provider = provider.name(),
5255 prediction_id = id,
5256 suggestion_accepted = accepted,
5257 file_extension = extension,
5258 );
5259 }
5260
5261 pub fn has_active_inline_completion(&self) -> bool {
5262 self.active_inline_completion.is_some()
5263 }
5264
5265 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5266 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5267 return false;
5268 };
5269
5270 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5271 self.clear_highlights::<InlineCompletionHighlight>(cx);
5272 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5273 true
5274 }
5275
5276 /// Returns true when we're displaying the edit prediction popover below the cursor
5277 /// like we are not previewing and the LSP autocomplete menu is visible
5278 /// or we are in `when_holding_modifier` mode.
5279 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5280 if self.edit_prediction_preview_is_active()
5281 || !self.show_edit_predictions_in_menu()
5282 || !self.edit_predictions_enabled()
5283 {
5284 return false;
5285 }
5286
5287 if self.has_visible_completions_menu() {
5288 return true;
5289 }
5290
5291 has_completion && self.edit_prediction_requires_modifier()
5292 }
5293
5294 fn handle_modifiers_changed(
5295 &mut self,
5296 modifiers: Modifiers,
5297 position_map: &PositionMap,
5298 window: &mut Window,
5299 cx: &mut Context<Self>,
5300 ) {
5301 if self.show_edit_predictions_in_menu() {
5302 self.update_edit_prediction_preview(&modifiers, window, cx);
5303 }
5304
5305 self.update_selection_mode(&modifiers, position_map, window, cx);
5306
5307 let mouse_position = window.mouse_position();
5308 if !position_map.text_hitbox.is_hovered(window) {
5309 return;
5310 }
5311
5312 self.update_hovered_link(
5313 position_map.point_for_position(mouse_position),
5314 &position_map.snapshot,
5315 modifiers,
5316 window,
5317 cx,
5318 )
5319 }
5320
5321 fn update_selection_mode(
5322 &mut self,
5323 modifiers: &Modifiers,
5324 position_map: &PositionMap,
5325 window: &mut Window,
5326 cx: &mut Context<Self>,
5327 ) {
5328 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5329 return;
5330 }
5331
5332 let mouse_position = window.mouse_position();
5333 let point_for_position = position_map.point_for_position(mouse_position);
5334 let position = point_for_position.previous_valid;
5335
5336 self.select(
5337 SelectPhase::BeginColumnar {
5338 position,
5339 reset: false,
5340 goal_column: point_for_position.exact_unclipped.column(),
5341 },
5342 window,
5343 cx,
5344 );
5345 }
5346
5347 fn update_edit_prediction_preview(
5348 &mut self,
5349 modifiers: &Modifiers,
5350 window: &mut Window,
5351 cx: &mut Context<Self>,
5352 ) {
5353 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5354 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5355 return;
5356 };
5357
5358 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5359 if matches!(
5360 self.edit_prediction_preview,
5361 EditPredictionPreview::Inactive
5362 ) {
5363 self.edit_prediction_preview = EditPredictionPreview::Active {
5364 previous_scroll_position: None,
5365 };
5366
5367 self.update_visible_inline_completion(window, cx);
5368 cx.notify();
5369 }
5370 } else if let EditPredictionPreview::Active {
5371 previous_scroll_position,
5372 } = self.edit_prediction_preview
5373 {
5374 if let (Some(previous_scroll_position), Some(position_map)) =
5375 (previous_scroll_position, self.last_position_map.as_ref())
5376 {
5377 self.set_scroll_position(
5378 previous_scroll_position
5379 .scroll_position(&position_map.snapshot.display_snapshot),
5380 window,
5381 cx,
5382 );
5383 }
5384
5385 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5386 self.clear_row_highlights::<EditPredictionPreview>();
5387 self.update_visible_inline_completion(window, cx);
5388 cx.notify();
5389 }
5390 }
5391
5392 fn update_visible_inline_completion(
5393 &mut self,
5394 _window: &mut Window,
5395 cx: &mut Context<Self>,
5396 ) -> Option<()> {
5397 let selection = self.selections.newest_anchor();
5398 let cursor = selection.head();
5399 let multibuffer = self.buffer.read(cx).snapshot(cx);
5400 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5401 let excerpt_id = cursor.excerpt_id;
5402
5403 let show_in_menu = self.show_edit_predictions_in_menu();
5404 let completions_menu_has_precedence = !show_in_menu
5405 && (self.context_menu.borrow().is_some()
5406 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5407
5408 if completions_menu_has_precedence
5409 || !offset_selection.is_empty()
5410 || self
5411 .active_inline_completion
5412 .as_ref()
5413 .map_or(false, |completion| {
5414 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5415 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5416 !invalidation_range.contains(&offset_selection.head())
5417 })
5418 {
5419 self.discard_inline_completion(false, cx);
5420 return None;
5421 }
5422
5423 self.take_active_inline_completion(cx);
5424 let Some(provider) = self.edit_prediction_provider() else {
5425 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5426 return None;
5427 };
5428
5429 let (buffer, cursor_buffer_position) =
5430 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5431
5432 self.edit_prediction_settings =
5433 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5434
5435 self.edit_prediction_cursor_on_leading_whitespace =
5436 multibuffer.is_line_whitespace_upto(cursor);
5437
5438 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5439 let edits = inline_completion
5440 .edits
5441 .into_iter()
5442 .flat_map(|(range, new_text)| {
5443 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5444 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5445 Some((start..end, new_text))
5446 })
5447 .collect::<Vec<_>>();
5448 if edits.is_empty() {
5449 return None;
5450 }
5451
5452 let first_edit_start = edits.first().unwrap().0.start;
5453 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5454 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5455
5456 let last_edit_end = edits.last().unwrap().0.end;
5457 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5458 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5459
5460 let cursor_row = cursor.to_point(&multibuffer).row;
5461
5462 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5463
5464 let mut inlay_ids = Vec::new();
5465 let invalidation_row_range;
5466 let move_invalidation_row_range = if cursor_row < edit_start_row {
5467 Some(cursor_row..edit_end_row)
5468 } else if cursor_row > edit_end_row {
5469 Some(edit_start_row..cursor_row)
5470 } else {
5471 None
5472 };
5473 let is_move =
5474 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5475 let completion = if is_move {
5476 invalidation_row_range =
5477 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5478 let target = first_edit_start;
5479 InlineCompletion::Move { target, snapshot }
5480 } else {
5481 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5482 && !self.inline_completions_hidden_for_vim_mode;
5483
5484 if show_completions_in_buffer {
5485 if edits
5486 .iter()
5487 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5488 {
5489 let mut inlays = Vec::new();
5490 for (range, new_text) in &edits {
5491 let inlay = Inlay::inline_completion(
5492 post_inc(&mut self.next_inlay_id),
5493 range.start,
5494 new_text.as_str(),
5495 );
5496 inlay_ids.push(inlay.id);
5497 inlays.push(inlay);
5498 }
5499
5500 self.splice_inlays(&[], inlays, cx);
5501 } else {
5502 let background_color = cx.theme().status().deleted_background;
5503 self.highlight_text::<InlineCompletionHighlight>(
5504 edits.iter().map(|(range, _)| range.clone()).collect(),
5505 HighlightStyle {
5506 background_color: Some(background_color),
5507 ..Default::default()
5508 },
5509 cx,
5510 );
5511 }
5512 }
5513
5514 invalidation_row_range = edit_start_row..edit_end_row;
5515
5516 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5517 if provider.show_tab_accept_marker() {
5518 EditDisplayMode::TabAccept
5519 } else {
5520 EditDisplayMode::Inline
5521 }
5522 } else {
5523 EditDisplayMode::DiffPopover
5524 };
5525
5526 InlineCompletion::Edit {
5527 edits,
5528 edit_preview: inline_completion.edit_preview,
5529 display_mode,
5530 snapshot,
5531 }
5532 };
5533
5534 let invalidation_range = multibuffer
5535 .anchor_before(Point::new(invalidation_row_range.start, 0))
5536 ..multibuffer.anchor_after(Point::new(
5537 invalidation_row_range.end,
5538 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5539 ));
5540
5541 self.stale_inline_completion_in_menu = None;
5542 self.active_inline_completion = Some(InlineCompletionState {
5543 inlay_ids,
5544 completion,
5545 completion_id: inline_completion.id,
5546 invalidation_range,
5547 });
5548
5549 cx.notify();
5550
5551 Some(())
5552 }
5553
5554 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5555 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5556 }
5557
5558 fn render_code_actions_indicator(
5559 &self,
5560 _style: &EditorStyle,
5561 row: DisplayRow,
5562 is_active: bool,
5563 cx: &mut Context<Self>,
5564 ) -> Option<IconButton> {
5565 if self.available_code_actions.is_some() {
5566 Some(
5567 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5568 .shape(ui::IconButtonShape::Square)
5569 .icon_size(IconSize::XSmall)
5570 .icon_color(Color::Muted)
5571 .toggle_state(is_active)
5572 .tooltip({
5573 let focus_handle = self.focus_handle.clone();
5574 move |window, cx| {
5575 Tooltip::for_action_in(
5576 "Toggle Code Actions",
5577 &ToggleCodeActions {
5578 deployed_from_indicator: None,
5579 },
5580 &focus_handle,
5581 window,
5582 cx,
5583 )
5584 }
5585 })
5586 .on_click(cx.listener(move |editor, _e, window, cx| {
5587 window.focus(&editor.focus_handle(cx));
5588 editor.toggle_code_actions(
5589 &ToggleCodeActions {
5590 deployed_from_indicator: Some(row),
5591 },
5592 window,
5593 cx,
5594 );
5595 })),
5596 )
5597 } else {
5598 None
5599 }
5600 }
5601
5602 fn clear_tasks(&mut self) {
5603 self.tasks.clear()
5604 }
5605
5606 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5607 if self.tasks.insert(key, value).is_some() {
5608 // This case should hopefully be rare, but just in case...
5609 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5610 }
5611 }
5612
5613 fn build_tasks_context(
5614 project: &Entity<Project>,
5615 buffer: &Entity<Buffer>,
5616 buffer_row: u32,
5617 tasks: &Arc<RunnableTasks>,
5618 cx: &mut Context<Self>,
5619 ) -> Task<Option<task::TaskContext>> {
5620 let position = Point::new(buffer_row, tasks.column);
5621 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5622 let location = Location {
5623 buffer: buffer.clone(),
5624 range: range_start..range_start,
5625 };
5626 // Fill in the environmental variables from the tree-sitter captures
5627 let mut captured_task_variables = TaskVariables::default();
5628 for (capture_name, value) in tasks.extra_variables.clone() {
5629 captured_task_variables.insert(
5630 task::VariableName::Custom(capture_name.into()),
5631 value.clone(),
5632 );
5633 }
5634 project.update(cx, |project, cx| {
5635 project.task_store().update(cx, |task_store, cx| {
5636 task_store.task_context_for_location(captured_task_variables, location, cx)
5637 })
5638 })
5639 }
5640
5641 pub fn spawn_nearest_task(
5642 &mut self,
5643 action: &SpawnNearestTask,
5644 window: &mut Window,
5645 cx: &mut Context<Self>,
5646 ) {
5647 let Some((workspace, _)) = self.workspace.clone() else {
5648 return;
5649 };
5650 let Some(project) = self.project.clone() else {
5651 return;
5652 };
5653
5654 // Try to find a closest, enclosing node using tree-sitter that has a
5655 // task
5656 let Some((buffer, buffer_row, tasks)) = self
5657 .find_enclosing_node_task(cx)
5658 // Or find the task that's closest in row-distance.
5659 .or_else(|| self.find_closest_task(cx))
5660 else {
5661 return;
5662 };
5663
5664 let reveal_strategy = action.reveal;
5665 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5666 cx.spawn_in(window, |_, mut cx| async move {
5667 let context = task_context.await?;
5668 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5669
5670 let resolved = resolved_task.resolved.as_mut()?;
5671 resolved.reveal = reveal_strategy;
5672
5673 workspace
5674 .update(&mut cx, |workspace, cx| {
5675 workspace::tasks::schedule_resolved_task(
5676 workspace,
5677 task_source_kind,
5678 resolved_task,
5679 false,
5680 cx,
5681 );
5682 })
5683 .ok()
5684 })
5685 .detach();
5686 }
5687
5688 fn find_closest_task(
5689 &mut self,
5690 cx: &mut Context<Self>,
5691 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5692 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5693
5694 let ((buffer_id, row), tasks) = self
5695 .tasks
5696 .iter()
5697 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5698
5699 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5700 let tasks = Arc::new(tasks.to_owned());
5701 Some((buffer, *row, tasks))
5702 }
5703
5704 fn find_enclosing_node_task(
5705 &mut self,
5706 cx: &mut Context<Self>,
5707 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5708 let snapshot = self.buffer.read(cx).snapshot(cx);
5709 let offset = self.selections.newest::<usize>(cx).head();
5710 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5711 let buffer_id = excerpt.buffer().remote_id();
5712
5713 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5714 let mut cursor = layer.node().walk();
5715
5716 while cursor.goto_first_child_for_byte(offset).is_some() {
5717 if cursor.node().end_byte() == offset {
5718 cursor.goto_next_sibling();
5719 }
5720 }
5721
5722 // Ascend to the smallest ancestor that contains the range and has a task.
5723 loop {
5724 let node = cursor.node();
5725 let node_range = node.byte_range();
5726 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5727
5728 // Check if this node contains our offset
5729 if node_range.start <= offset && node_range.end >= offset {
5730 // If it contains offset, check for task
5731 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5732 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5733 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5734 }
5735 }
5736
5737 if !cursor.goto_parent() {
5738 break;
5739 }
5740 }
5741 None
5742 }
5743
5744 fn render_run_indicator(
5745 &self,
5746 _style: &EditorStyle,
5747 is_active: bool,
5748 row: DisplayRow,
5749 cx: &mut Context<Self>,
5750 ) -> IconButton {
5751 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5752 .shape(ui::IconButtonShape::Square)
5753 .icon_size(IconSize::XSmall)
5754 .icon_color(Color::Muted)
5755 .toggle_state(is_active)
5756 .on_click(cx.listener(move |editor, _e, window, cx| {
5757 window.focus(&editor.focus_handle(cx));
5758 editor.toggle_code_actions(
5759 &ToggleCodeActions {
5760 deployed_from_indicator: Some(row),
5761 },
5762 window,
5763 cx,
5764 );
5765 }))
5766 }
5767
5768 pub fn context_menu_visible(&self) -> bool {
5769 !self.edit_prediction_preview_is_active()
5770 && self
5771 .context_menu
5772 .borrow()
5773 .as_ref()
5774 .map_or(false, |menu| menu.visible())
5775 }
5776
5777 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5778 self.context_menu
5779 .borrow()
5780 .as_ref()
5781 .map(|menu| menu.origin())
5782 }
5783
5784 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5785 px(30.)
5786 }
5787
5788 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5789 if self.read_only(cx) {
5790 cx.theme().players().read_only()
5791 } else {
5792 self.style.as_ref().unwrap().local_player
5793 }
5794 }
5795
5796 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5797 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5798 let accept_keystroke = accept_binding.keystroke()?;
5799
5800 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5801
5802 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5803 Color::Accent
5804 } else {
5805 Color::Muted
5806 };
5807
5808 h_flex()
5809 .px_0p5()
5810 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5811 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5812 .text_size(TextSize::XSmall.rems(cx))
5813 .child(h_flex().children(ui::render_modifiers(
5814 &accept_keystroke.modifiers,
5815 PlatformStyle::platform(),
5816 Some(modifiers_color),
5817 Some(IconSize::XSmall.rems().into()),
5818 true,
5819 )))
5820 .when(is_platform_style_mac, |parent| {
5821 parent.child(accept_keystroke.key.clone())
5822 })
5823 .when(!is_platform_style_mac, |parent| {
5824 parent.child(
5825 Key::new(
5826 util::capitalize(&accept_keystroke.key),
5827 Some(Color::Default),
5828 )
5829 .size(Some(IconSize::XSmall.rems().into())),
5830 )
5831 })
5832 .into()
5833 }
5834
5835 fn render_edit_prediction_line_popover(
5836 &self,
5837 label: impl Into<SharedString>,
5838 icon: Option<IconName>,
5839 window: &mut Window,
5840 cx: &App,
5841 ) -> Option<Div> {
5842 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5843
5844 let result = h_flex()
5845 .py_0p5()
5846 .pl_1()
5847 .pr(padding_right)
5848 .gap_1()
5849 .rounded(px(6.))
5850 .border_1()
5851 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5852 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5853 .shadow_sm()
5854 .children(self.render_edit_prediction_accept_keybind(window, cx))
5855 .child(Label::new(label).size(LabelSize::Small))
5856 .when_some(icon, |element, icon| {
5857 element.child(
5858 div()
5859 .mt(px(1.5))
5860 .child(Icon::new(icon).size(IconSize::Small)),
5861 )
5862 });
5863
5864 Some(result)
5865 }
5866
5867 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5868 let accent_color = cx.theme().colors().text_accent;
5869 let editor_bg_color = cx.theme().colors().editor_background;
5870 editor_bg_color.blend(accent_color.opacity(0.1))
5871 }
5872
5873 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5874 let accent_color = cx.theme().colors().text_accent;
5875 let editor_bg_color = cx.theme().colors().editor_background;
5876 editor_bg_color.blend(accent_color.opacity(0.6))
5877 }
5878
5879 #[allow(clippy::too_many_arguments)]
5880 fn render_edit_prediction_cursor_popover(
5881 &self,
5882 min_width: Pixels,
5883 max_width: Pixels,
5884 cursor_point: Point,
5885 style: &EditorStyle,
5886 accept_keystroke: Option<&gpui::Keystroke>,
5887 _window: &Window,
5888 cx: &mut Context<Editor>,
5889 ) -> Option<AnyElement> {
5890 let provider = self.edit_prediction_provider.as_ref()?;
5891
5892 if provider.provider.needs_terms_acceptance(cx) {
5893 return Some(
5894 h_flex()
5895 .min_w(min_width)
5896 .flex_1()
5897 .px_2()
5898 .py_1()
5899 .gap_3()
5900 .elevation_2(cx)
5901 .hover(|style| style.bg(cx.theme().colors().element_hover))
5902 .id("accept-terms")
5903 .cursor_pointer()
5904 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5905 .on_click(cx.listener(|this, _event, window, cx| {
5906 cx.stop_propagation();
5907 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5908 window.dispatch_action(
5909 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5910 cx,
5911 );
5912 }))
5913 .child(
5914 h_flex()
5915 .flex_1()
5916 .gap_2()
5917 .child(Icon::new(IconName::ZedPredict))
5918 .child(Label::new("Accept Terms of Service"))
5919 .child(div().w_full())
5920 .child(
5921 Icon::new(IconName::ArrowUpRight)
5922 .color(Color::Muted)
5923 .size(IconSize::Small),
5924 )
5925 .into_any_element(),
5926 )
5927 .into_any(),
5928 );
5929 }
5930
5931 let is_refreshing = provider.provider.is_refreshing(cx);
5932
5933 fn pending_completion_container() -> Div {
5934 h_flex()
5935 .h_full()
5936 .flex_1()
5937 .gap_2()
5938 .child(Icon::new(IconName::ZedPredict))
5939 }
5940
5941 let completion = match &self.active_inline_completion {
5942 Some(completion) => match &completion.completion {
5943 InlineCompletion::Move {
5944 target, snapshot, ..
5945 } if !self.has_visible_completions_menu() => {
5946 use text::ToPoint as _;
5947
5948 return Some(
5949 h_flex()
5950 .px_2()
5951 .py_1()
5952 .gap_2()
5953 .elevation_2(cx)
5954 .border_color(cx.theme().colors().border)
5955 .rounded(px(6.))
5956 .rounded_tl(px(0.))
5957 .child(
5958 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5959 Icon::new(IconName::ZedPredictDown)
5960 } else {
5961 Icon::new(IconName::ZedPredictUp)
5962 },
5963 )
5964 .child(Label::new("Hold").size(LabelSize::Small))
5965 .child(h_flex().children(ui::render_modifiers(
5966 &accept_keystroke?.modifiers,
5967 PlatformStyle::platform(),
5968 Some(Color::Default),
5969 Some(IconSize::Small.rems().into()),
5970 false,
5971 )))
5972 .into_any(),
5973 );
5974 }
5975 _ => self.render_edit_prediction_cursor_popover_preview(
5976 completion,
5977 cursor_point,
5978 style,
5979 cx,
5980 )?,
5981 },
5982
5983 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5984 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5985 stale_completion,
5986 cursor_point,
5987 style,
5988 cx,
5989 )?,
5990
5991 None => {
5992 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5993 }
5994 },
5995
5996 None => pending_completion_container().child(Label::new("No Prediction")),
5997 };
5998
5999 let completion = if is_refreshing {
6000 completion
6001 .with_animation(
6002 "loading-completion",
6003 Animation::new(Duration::from_secs(2))
6004 .repeat()
6005 .with_easing(pulsating_between(0.4, 0.8)),
6006 |label, delta| label.opacity(delta),
6007 )
6008 .into_any_element()
6009 } else {
6010 completion.into_any_element()
6011 };
6012
6013 let has_completion = self.active_inline_completion.is_some();
6014
6015 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6016 Some(
6017 h_flex()
6018 .min_w(min_width)
6019 .max_w(max_width)
6020 .flex_1()
6021 .elevation_2(cx)
6022 .border_color(cx.theme().colors().border)
6023 .child(
6024 div()
6025 .flex_1()
6026 .py_1()
6027 .px_2()
6028 .overflow_hidden()
6029 .child(completion),
6030 )
6031 .when_some(accept_keystroke, |el, accept_keystroke| {
6032 if !accept_keystroke.modifiers.modified() {
6033 return el;
6034 }
6035
6036 el.child(
6037 h_flex()
6038 .h_full()
6039 .border_l_1()
6040 .rounded_r_lg()
6041 .border_color(cx.theme().colors().border)
6042 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6043 .gap_1()
6044 .py_1()
6045 .px_2()
6046 .child(
6047 h_flex()
6048 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6049 .when(is_platform_style_mac, |parent| parent.gap_1())
6050 .child(h_flex().children(ui::render_modifiers(
6051 &accept_keystroke.modifiers,
6052 PlatformStyle::platform(),
6053 Some(if !has_completion {
6054 Color::Muted
6055 } else {
6056 Color::Default
6057 }),
6058 None,
6059 false,
6060 ))),
6061 )
6062 .child(Label::new("Preview").into_any_element())
6063 .opacity(if has_completion { 1.0 } else { 0.4 }),
6064 )
6065 })
6066 .into_any(),
6067 )
6068 }
6069
6070 fn render_edit_prediction_cursor_popover_preview(
6071 &self,
6072 completion: &InlineCompletionState,
6073 cursor_point: Point,
6074 style: &EditorStyle,
6075 cx: &mut Context<Editor>,
6076 ) -> Option<Div> {
6077 use text::ToPoint as _;
6078
6079 fn render_relative_row_jump(
6080 prefix: impl Into<String>,
6081 current_row: u32,
6082 target_row: u32,
6083 ) -> Div {
6084 let (row_diff, arrow) = if target_row < current_row {
6085 (current_row - target_row, IconName::ArrowUp)
6086 } else {
6087 (target_row - current_row, IconName::ArrowDown)
6088 };
6089
6090 h_flex()
6091 .child(
6092 Label::new(format!("{}{}", prefix.into(), row_diff))
6093 .color(Color::Muted)
6094 .size(LabelSize::Small),
6095 )
6096 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6097 }
6098
6099 match &completion.completion {
6100 InlineCompletion::Move {
6101 target, snapshot, ..
6102 } => Some(
6103 h_flex()
6104 .px_2()
6105 .gap_2()
6106 .flex_1()
6107 .child(
6108 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6109 Icon::new(IconName::ZedPredictDown)
6110 } else {
6111 Icon::new(IconName::ZedPredictUp)
6112 },
6113 )
6114 .child(Label::new("Jump to Edit")),
6115 ),
6116
6117 InlineCompletion::Edit {
6118 edits,
6119 edit_preview,
6120 snapshot,
6121 display_mode: _,
6122 } => {
6123 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6124
6125 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6126 &snapshot,
6127 &edits,
6128 edit_preview.as_ref()?,
6129 true,
6130 cx,
6131 )
6132 .first_line_preview();
6133
6134 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6135 .with_highlights(&style.text, highlighted_edits.highlights);
6136
6137 let preview = h_flex()
6138 .gap_1()
6139 .min_w_16()
6140 .child(styled_text)
6141 .when(has_more_lines, |parent| parent.child("…"));
6142
6143 let left = if first_edit_row != cursor_point.row {
6144 render_relative_row_jump("", cursor_point.row, first_edit_row)
6145 .into_any_element()
6146 } else {
6147 Icon::new(IconName::ZedPredict).into_any_element()
6148 };
6149
6150 Some(
6151 h_flex()
6152 .h_full()
6153 .flex_1()
6154 .gap_2()
6155 .pr_1()
6156 .overflow_x_hidden()
6157 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6158 .child(left)
6159 .child(preview),
6160 )
6161 }
6162 }
6163 }
6164
6165 fn render_context_menu(
6166 &self,
6167 style: &EditorStyle,
6168 max_height_in_lines: u32,
6169 y_flipped: bool,
6170 window: &mut Window,
6171 cx: &mut Context<Editor>,
6172 ) -> Option<AnyElement> {
6173 let menu = self.context_menu.borrow();
6174 let menu = menu.as_ref()?;
6175 if !menu.visible() {
6176 return None;
6177 };
6178 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6179 }
6180
6181 fn render_context_menu_aside(
6182 &mut self,
6183 max_size: Size<Pixels>,
6184 window: &mut Window,
6185 cx: &mut Context<Editor>,
6186 ) -> Option<AnyElement> {
6187 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6188 if menu.visible() {
6189 menu.render_aside(self, max_size, window, cx)
6190 } else {
6191 None
6192 }
6193 })
6194 }
6195
6196 fn hide_context_menu(
6197 &mut self,
6198 window: &mut Window,
6199 cx: &mut Context<Self>,
6200 ) -> Option<CodeContextMenu> {
6201 cx.notify();
6202 self.completion_tasks.clear();
6203 let context_menu = self.context_menu.borrow_mut().take();
6204 self.stale_inline_completion_in_menu.take();
6205 self.update_visible_inline_completion(window, cx);
6206 context_menu
6207 }
6208
6209 fn show_snippet_choices(
6210 &mut self,
6211 choices: &Vec<String>,
6212 selection: Range<Anchor>,
6213 cx: &mut Context<Self>,
6214 ) {
6215 if selection.start.buffer_id.is_none() {
6216 return;
6217 }
6218 let buffer_id = selection.start.buffer_id.unwrap();
6219 let buffer = self.buffer().read(cx).buffer(buffer_id);
6220 let id = post_inc(&mut self.next_completion_id);
6221
6222 if let Some(buffer) = buffer {
6223 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6224 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6225 ));
6226 }
6227 }
6228
6229 pub fn insert_snippet(
6230 &mut self,
6231 insertion_ranges: &[Range<usize>],
6232 snippet: Snippet,
6233 window: &mut Window,
6234 cx: &mut Context<Self>,
6235 ) -> Result<()> {
6236 struct Tabstop<T> {
6237 is_end_tabstop: bool,
6238 ranges: Vec<Range<T>>,
6239 choices: Option<Vec<String>>,
6240 }
6241
6242 let tabstops = self.buffer.update(cx, |buffer, cx| {
6243 let snippet_text: Arc<str> = snippet.text.clone().into();
6244 buffer.edit(
6245 insertion_ranges
6246 .iter()
6247 .cloned()
6248 .map(|range| (range, snippet_text.clone())),
6249 Some(AutoindentMode::EachLine),
6250 cx,
6251 );
6252
6253 let snapshot = &*buffer.read(cx);
6254 let snippet = &snippet;
6255 snippet
6256 .tabstops
6257 .iter()
6258 .map(|tabstop| {
6259 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6260 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6261 });
6262 let mut tabstop_ranges = tabstop
6263 .ranges
6264 .iter()
6265 .flat_map(|tabstop_range| {
6266 let mut delta = 0_isize;
6267 insertion_ranges.iter().map(move |insertion_range| {
6268 let insertion_start = insertion_range.start as isize + delta;
6269 delta +=
6270 snippet.text.len() as isize - insertion_range.len() as isize;
6271
6272 let start = ((insertion_start + tabstop_range.start) as usize)
6273 .min(snapshot.len());
6274 let end = ((insertion_start + tabstop_range.end) as usize)
6275 .min(snapshot.len());
6276 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6277 })
6278 })
6279 .collect::<Vec<_>>();
6280 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6281
6282 Tabstop {
6283 is_end_tabstop,
6284 ranges: tabstop_ranges,
6285 choices: tabstop.choices.clone(),
6286 }
6287 })
6288 .collect::<Vec<_>>()
6289 });
6290 if let Some(tabstop) = tabstops.first() {
6291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6292 s.select_ranges(tabstop.ranges.iter().cloned());
6293 });
6294
6295 if let Some(choices) = &tabstop.choices {
6296 if let Some(selection) = tabstop.ranges.first() {
6297 self.show_snippet_choices(choices, selection.clone(), cx)
6298 }
6299 }
6300
6301 // If we're already at the last tabstop and it's at the end of the snippet,
6302 // we're done, we don't need to keep the state around.
6303 if !tabstop.is_end_tabstop {
6304 let choices = tabstops
6305 .iter()
6306 .map(|tabstop| tabstop.choices.clone())
6307 .collect();
6308
6309 let ranges = tabstops
6310 .into_iter()
6311 .map(|tabstop| tabstop.ranges)
6312 .collect::<Vec<_>>();
6313
6314 self.snippet_stack.push(SnippetState {
6315 active_index: 0,
6316 ranges,
6317 choices,
6318 });
6319 }
6320
6321 // Check whether the just-entered snippet ends with an auto-closable bracket.
6322 if self.autoclose_regions.is_empty() {
6323 let snapshot = self.buffer.read(cx).snapshot(cx);
6324 for selection in &mut self.selections.all::<Point>(cx) {
6325 let selection_head = selection.head();
6326 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6327 continue;
6328 };
6329
6330 let mut bracket_pair = None;
6331 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6332 let prev_chars = snapshot
6333 .reversed_chars_at(selection_head)
6334 .collect::<String>();
6335 for (pair, enabled) in scope.brackets() {
6336 if enabled
6337 && pair.close
6338 && prev_chars.starts_with(pair.start.as_str())
6339 && next_chars.starts_with(pair.end.as_str())
6340 {
6341 bracket_pair = Some(pair.clone());
6342 break;
6343 }
6344 }
6345 if let Some(pair) = bracket_pair {
6346 let start = snapshot.anchor_after(selection_head);
6347 let end = snapshot.anchor_after(selection_head);
6348 self.autoclose_regions.push(AutocloseRegion {
6349 selection_id: selection.id,
6350 range: start..end,
6351 pair,
6352 });
6353 }
6354 }
6355 }
6356 }
6357 Ok(())
6358 }
6359
6360 pub fn move_to_next_snippet_tabstop(
6361 &mut self,
6362 window: &mut Window,
6363 cx: &mut Context<Self>,
6364 ) -> bool {
6365 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6366 }
6367
6368 pub fn move_to_prev_snippet_tabstop(
6369 &mut self,
6370 window: &mut Window,
6371 cx: &mut Context<Self>,
6372 ) -> bool {
6373 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6374 }
6375
6376 pub fn move_to_snippet_tabstop(
6377 &mut self,
6378 bias: Bias,
6379 window: &mut Window,
6380 cx: &mut Context<Self>,
6381 ) -> bool {
6382 if let Some(mut snippet) = self.snippet_stack.pop() {
6383 match bias {
6384 Bias::Left => {
6385 if snippet.active_index > 0 {
6386 snippet.active_index -= 1;
6387 } else {
6388 self.snippet_stack.push(snippet);
6389 return false;
6390 }
6391 }
6392 Bias::Right => {
6393 if snippet.active_index + 1 < snippet.ranges.len() {
6394 snippet.active_index += 1;
6395 } else {
6396 self.snippet_stack.push(snippet);
6397 return false;
6398 }
6399 }
6400 }
6401 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6402 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6403 s.select_anchor_ranges(current_ranges.iter().cloned())
6404 });
6405
6406 if let Some(choices) = &snippet.choices[snippet.active_index] {
6407 if let Some(selection) = current_ranges.first() {
6408 self.show_snippet_choices(&choices, selection.clone(), cx);
6409 }
6410 }
6411
6412 // If snippet state is not at the last tabstop, push it back on the stack
6413 if snippet.active_index + 1 < snippet.ranges.len() {
6414 self.snippet_stack.push(snippet);
6415 }
6416 return true;
6417 }
6418 }
6419
6420 false
6421 }
6422
6423 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6424 self.transact(window, cx, |this, window, cx| {
6425 this.select_all(&SelectAll, window, cx);
6426 this.insert("", window, cx);
6427 });
6428 }
6429
6430 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6431 self.transact(window, cx, |this, window, cx| {
6432 this.select_autoclose_pair(window, cx);
6433 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6434 if !this.linked_edit_ranges.is_empty() {
6435 let selections = this.selections.all::<MultiBufferPoint>(cx);
6436 let snapshot = this.buffer.read(cx).snapshot(cx);
6437
6438 for selection in selections.iter() {
6439 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6440 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6441 if selection_start.buffer_id != selection_end.buffer_id {
6442 continue;
6443 }
6444 if let Some(ranges) =
6445 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6446 {
6447 for (buffer, entries) in ranges {
6448 linked_ranges.entry(buffer).or_default().extend(entries);
6449 }
6450 }
6451 }
6452 }
6453
6454 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6455 if !this.selections.line_mode {
6456 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6457 for selection in &mut selections {
6458 if selection.is_empty() {
6459 let old_head = selection.head();
6460 let mut new_head =
6461 movement::left(&display_map, old_head.to_display_point(&display_map))
6462 .to_point(&display_map);
6463 if let Some((buffer, line_buffer_range)) = display_map
6464 .buffer_snapshot
6465 .buffer_line_for_row(MultiBufferRow(old_head.row))
6466 {
6467 let indent_size =
6468 buffer.indent_size_for_line(line_buffer_range.start.row);
6469 let indent_len = match indent_size.kind {
6470 IndentKind::Space => {
6471 buffer.settings_at(line_buffer_range.start, cx).tab_size
6472 }
6473 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6474 };
6475 if old_head.column <= indent_size.len && old_head.column > 0 {
6476 let indent_len = indent_len.get();
6477 new_head = cmp::min(
6478 new_head,
6479 MultiBufferPoint::new(
6480 old_head.row,
6481 ((old_head.column - 1) / indent_len) * indent_len,
6482 ),
6483 );
6484 }
6485 }
6486
6487 selection.set_head(new_head, SelectionGoal::None);
6488 }
6489 }
6490 }
6491
6492 this.signature_help_state.set_backspace_pressed(true);
6493 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6494 s.select(selections)
6495 });
6496 this.insert("", window, cx);
6497 let empty_str: Arc<str> = Arc::from("");
6498 for (buffer, edits) in linked_ranges {
6499 let snapshot = buffer.read(cx).snapshot();
6500 use text::ToPoint as TP;
6501
6502 let edits = edits
6503 .into_iter()
6504 .map(|range| {
6505 let end_point = TP::to_point(&range.end, &snapshot);
6506 let mut start_point = TP::to_point(&range.start, &snapshot);
6507
6508 if end_point == start_point {
6509 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6510 .saturating_sub(1);
6511 start_point =
6512 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6513 };
6514
6515 (start_point..end_point, empty_str.clone())
6516 })
6517 .sorted_by_key(|(range, _)| range.start)
6518 .collect::<Vec<_>>();
6519 buffer.update(cx, |this, cx| {
6520 this.edit(edits, None, cx);
6521 })
6522 }
6523 this.refresh_inline_completion(true, false, window, cx);
6524 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6525 });
6526 }
6527
6528 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6529 self.transact(window, cx, |this, window, cx| {
6530 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6531 let line_mode = s.line_mode;
6532 s.move_with(|map, selection| {
6533 if selection.is_empty() && !line_mode {
6534 let cursor = movement::right(map, selection.head());
6535 selection.end = cursor;
6536 selection.reversed = true;
6537 selection.goal = SelectionGoal::None;
6538 }
6539 })
6540 });
6541 this.insert("", window, cx);
6542 this.refresh_inline_completion(true, false, window, cx);
6543 });
6544 }
6545
6546 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6547 if self.move_to_prev_snippet_tabstop(window, cx) {
6548 return;
6549 }
6550
6551 self.outdent(&Outdent, window, cx);
6552 }
6553
6554 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6555 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6556 return;
6557 }
6558
6559 let mut selections = self.selections.all_adjusted(cx);
6560 let buffer = self.buffer.read(cx);
6561 let snapshot = buffer.snapshot(cx);
6562 let rows_iter = selections.iter().map(|s| s.head().row);
6563 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6564
6565 let mut edits = Vec::new();
6566 let mut prev_edited_row = 0;
6567 let mut row_delta = 0;
6568 for selection in &mut selections {
6569 if selection.start.row != prev_edited_row {
6570 row_delta = 0;
6571 }
6572 prev_edited_row = selection.end.row;
6573
6574 // If the selection is non-empty, then increase the indentation of the selected lines.
6575 if !selection.is_empty() {
6576 row_delta =
6577 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6578 continue;
6579 }
6580
6581 // If the selection is empty and the cursor is in the leading whitespace before the
6582 // suggested indentation, then auto-indent the line.
6583 let cursor = selection.head();
6584 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6585 if let Some(suggested_indent) =
6586 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6587 {
6588 if cursor.column < suggested_indent.len
6589 && cursor.column <= current_indent.len
6590 && current_indent.len <= suggested_indent.len
6591 {
6592 selection.start = Point::new(cursor.row, suggested_indent.len);
6593 selection.end = selection.start;
6594 if row_delta == 0 {
6595 edits.extend(Buffer::edit_for_indent_size_adjustment(
6596 cursor.row,
6597 current_indent,
6598 suggested_indent,
6599 ));
6600 row_delta = suggested_indent.len - current_indent.len;
6601 }
6602 continue;
6603 }
6604 }
6605
6606 // Otherwise, insert a hard or soft tab.
6607 let settings = buffer.settings_at(cursor, cx);
6608 let tab_size = if settings.hard_tabs {
6609 IndentSize::tab()
6610 } else {
6611 let tab_size = settings.tab_size.get();
6612 let char_column = snapshot
6613 .text_for_range(Point::new(cursor.row, 0)..cursor)
6614 .flat_map(str::chars)
6615 .count()
6616 + row_delta as usize;
6617 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6618 IndentSize::spaces(chars_to_next_tab_stop)
6619 };
6620 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6621 selection.end = selection.start;
6622 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6623 row_delta += tab_size.len;
6624 }
6625
6626 self.transact(window, cx, |this, window, cx| {
6627 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6628 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6629 s.select(selections)
6630 });
6631 this.refresh_inline_completion(true, false, window, cx);
6632 });
6633 }
6634
6635 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6636 if self.read_only(cx) {
6637 return;
6638 }
6639 let mut selections = self.selections.all::<Point>(cx);
6640 let mut prev_edited_row = 0;
6641 let mut row_delta = 0;
6642 let mut edits = Vec::new();
6643 let buffer = self.buffer.read(cx);
6644 let snapshot = buffer.snapshot(cx);
6645 for selection in &mut selections {
6646 if selection.start.row != prev_edited_row {
6647 row_delta = 0;
6648 }
6649 prev_edited_row = selection.end.row;
6650
6651 row_delta =
6652 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6653 }
6654
6655 self.transact(window, cx, |this, window, cx| {
6656 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6657 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6658 s.select(selections)
6659 });
6660 });
6661 }
6662
6663 fn indent_selection(
6664 buffer: &MultiBuffer,
6665 snapshot: &MultiBufferSnapshot,
6666 selection: &mut Selection<Point>,
6667 edits: &mut Vec<(Range<Point>, String)>,
6668 delta_for_start_row: u32,
6669 cx: &App,
6670 ) -> u32 {
6671 let settings = buffer.settings_at(selection.start, cx);
6672 let tab_size = settings.tab_size.get();
6673 let indent_kind = if settings.hard_tabs {
6674 IndentKind::Tab
6675 } else {
6676 IndentKind::Space
6677 };
6678 let mut start_row = selection.start.row;
6679 let mut end_row = selection.end.row + 1;
6680
6681 // If a selection ends at the beginning of a line, don't indent
6682 // that last line.
6683 if selection.end.column == 0 && selection.end.row > selection.start.row {
6684 end_row -= 1;
6685 }
6686
6687 // Avoid re-indenting a row that has already been indented by a
6688 // previous selection, but still update this selection's column
6689 // to reflect that indentation.
6690 if delta_for_start_row > 0 {
6691 start_row += 1;
6692 selection.start.column += delta_for_start_row;
6693 if selection.end.row == selection.start.row {
6694 selection.end.column += delta_for_start_row;
6695 }
6696 }
6697
6698 let mut delta_for_end_row = 0;
6699 let has_multiple_rows = start_row + 1 != end_row;
6700 for row in start_row..end_row {
6701 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6702 let indent_delta = match (current_indent.kind, indent_kind) {
6703 (IndentKind::Space, IndentKind::Space) => {
6704 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6705 IndentSize::spaces(columns_to_next_tab_stop)
6706 }
6707 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6708 (_, IndentKind::Tab) => IndentSize::tab(),
6709 };
6710
6711 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6712 0
6713 } else {
6714 selection.start.column
6715 };
6716 let row_start = Point::new(row, start);
6717 edits.push((
6718 row_start..row_start,
6719 indent_delta.chars().collect::<String>(),
6720 ));
6721
6722 // Update this selection's endpoints to reflect the indentation.
6723 if row == selection.start.row {
6724 selection.start.column += indent_delta.len;
6725 }
6726 if row == selection.end.row {
6727 selection.end.column += indent_delta.len;
6728 delta_for_end_row = indent_delta.len;
6729 }
6730 }
6731
6732 if selection.start.row == selection.end.row {
6733 delta_for_start_row + delta_for_end_row
6734 } else {
6735 delta_for_end_row
6736 }
6737 }
6738
6739 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6740 if self.read_only(cx) {
6741 return;
6742 }
6743 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6744 let selections = self.selections.all::<Point>(cx);
6745 let mut deletion_ranges = Vec::new();
6746 let mut last_outdent = None;
6747 {
6748 let buffer = self.buffer.read(cx);
6749 let snapshot = buffer.snapshot(cx);
6750 for selection in &selections {
6751 let settings = buffer.settings_at(selection.start, cx);
6752 let tab_size = settings.tab_size.get();
6753 let mut rows = selection.spanned_rows(false, &display_map);
6754
6755 // Avoid re-outdenting a row that has already been outdented by a
6756 // previous selection.
6757 if let Some(last_row) = last_outdent {
6758 if last_row == rows.start {
6759 rows.start = rows.start.next_row();
6760 }
6761 }
6762 let has_multiple_rows = rows.len() > 1;
6763 for row in rows.iter_rows() {
6764 let indent_size = snapshot.indent_size_for_line(row);
6765 if indent_size.len > 0 {
6766 let deletion_len = match indent_size.kind {
6767 IndentKind::Space => {
6768 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6769 if columns_to_prev_tab_stop == 0 {
6770 tab_size
6771 } else {
6772 columns_to_prev_tab_stop
6773 }
6774 }
6775 IndentKind::Tab => 1,
6776 };
6777 let start = if has_multiple_rows
6778 || deletion_len > selection.start.column
6779 || indent_size.len < selection.start.column
6780 {
6781 0
6782 } else {
6783 selection.start.column - deletion_len
6784 };
6785 deletion_ranges.push(
6786 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6787 );
6788 last_outdent = Some(row);
6789 }
6790 }
6791 }
6792 }
6793
6794 self.transact(window, cx, |this, window, cx| {
6795 this.buffer.update(cx, |buffer, cx| {
6796 let empty_str: Arc<str> = Arc::default();
6797 buffer.edit(
6798 deletion_ranges
6799 .into_iter()
6800 .map(|range| (range, empty_str.clone())),
6801 None,
6802 cx,
6803 );
6804 });
6805 let selections = this.selections.all::<usize>(cx);
6806 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6807 s.select(selections)
6808 });
6809 });
6810 }
6811
6812 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6813 if self.read_only(cx) {
6814 return;
6815 }
6816 let selections = self
6817 .selections
6818 .all::<usize>(cx)
6819 .into_iter()
6820 .map(|s| s.range());
6821
6822 self.transact(window, cx, |this, window, cx| {
6823 this.buffer.update(cx, |buffer, cx| {
6824 buffer.autoindent_ranges(selections, cx);
6825 });
6826 let selections = this.selections.all::<usize>(cx);
6827 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6828 s.select(selections)
6829 });
6830 });
6831 }
6832
6833 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6834 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6835 let selections = self.selections.all::<Point>(cx);
6836
6837 let mut new_cursors = Vec::new();
6838 let mut edit_ranges = Vec::new();
6839 let mut selections = selections.iter().peekable();
6840 while let Some(selection) = selections.next() {
6841 let mut rows = selection.spanned_rows(false, &display_map);
6842 let goal_display_column = selection.head().to_display_point(&display_map).column();
6843
6844 // Accumulate contiguous regions of rows that we want to delete.
6845 while let Some(next_selection) = selections.peek() {
6846 let next_rows = next_selection.spanned_rows(false, &display_map);
6847 if next_rows.start <= rows.end {
6848 rows.end = next_rows.end;
6849 selections.next().unwrap();
6850 } else {
6851 break;
6852 }
6853 }
6854
6855 let buffer = &display_map.buffer_snapshot;
6856 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6857 let edit_end;
6858 let cursor_buffer_row;
6859 if buffer.max_point().row >= rows.end.0 {
6860 // If there's a line after the range, delete the \n from the end of the row range
6861 // and position the cursor on the next line.
6862 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6863 cursor_buffer_row = rows.end;
6864 } else {
6865 // If there isn't a line after the range, delete the \n from the line before the
6866 // start of the row range and position the cursor there.
6867 edit_start = edit_start.saturating_sub(1);
6868 edit_end = buffer.len();
6869 cursor_buffer_row = rows.start.previous_row();
6870 }
6871
6872 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6873 *cursor.column_mut() =
6874 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6875
6876 new_cursors.push((
6877 selection.id,
6878 buffer.anchor_after(cursor.to_point(&display_map)),
6879 ));
6880 edit_ranges.push(edit_start..edit_end);
6881 }
6882
6883 self.transact(window, cx, |this, window, cx| {
6884 let buffer = this.buffer.update(cx, |buffer, cx| {
6885 let empty_str: Arc<str> = Arc::default();
6886 buffer.edit(
6887 edit_ranges
6888 .into_iter()
6889 .map(|range| (range, empty_str.clone())),
6890 None,
6891 cx,
6892 );
6893 buffer.snapshot(cx)
6894 });
6895 let new_selections = new_cursors
6896 .into_iter()
6897 .map(|(id, cursor)| {
6898 let cursor = cursor.to_point(&buffer);
6899 Selection {
6900 id,
6901 start: cursor,
6902 end: cursor,
6903 reversed: false,
6904 goal: SelectionGoal::None,
6905 }
6906 })
6907 .collect();
6908
6909 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6910 s.select(new_selections);
6911 });
6912 });
6913 }
6914
6915 pub fn join_lines_impl(
6916 &mut self,
6917 insert_whitespace: bool,
6918 window: &mut Window,
6919 cx: &mut Context<Self>,
6920 ) {
6921 if self.read_only(cx) {
6922 return;
6923 }
6924 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6925 for selection in self.selections.all::<Point>(cx) {
6926 let start = MultiBufferRow(selection.start.row);
6927 // Treat single line selections as if they include the next line. Otherwise this action
6928 // would do nothing for single line selections individual cursors.
6929 let end = if selection.start.row == selection.end.row {
6930 MultiBufferRow(selection.start.row + 1)
6931 } else {
6932 MultiBufferRow(selection.end.row)
6933 };
6934
6935 if let Some(last_row_range) = row_ranges.last_mut() {
6936 if start <= last_row_range.end {
6937 last_row_range.end = end;
6938 continue;
6939 }
6940 }
6941 row_ranges.push(start..end);
6942 }
6943
6944 let snapshot = self.buffer.read(cx).snapshot(cx);
6945 let mut cursor_positions = Vec::new();
6946 for row_range in &row_ranges {
6947 let anchor = snapshot.anchor_before(Point::new(
6948 row_range.end.previous_row().0,
6949 snapshot.line_len(row_range.end.previous_row()),
6950 ));
6951 cursor_positions.push(anchor..anchor);
6952 }
6953
6954 self.transact(window, cx, |this, window, cx| {
6955 for row_range in row_ranges.into_iter().rev() {
6956 for row in row_range.iter_rows().rev() {
6957 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6958 let next_line_row = row.next_row();
6959 let indent = snapshot.indent_size_for_line(next_line_row);
6960 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6961
6962 let replace =
6963 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6964 " "
6965 } else {
6966 ""
6967 };
6968
6969 this.buffer.update(cx, |buffer, cx| {
6970 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6971 });
6972 }
6973 }
6974
6975 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6976 s.select_anchor_ranges(cursor_positions)
6977 });
6978 });
6979 }
6980
6981 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6982 self.join_lines_impl(true, window, cx);
6983 }
6984
6985 pub fn sort_lines_case_sensitive(
6986 &mut self,
6987 _: &SortLinesCaseSensitive,
6988 window: &mut Window,
6989 cx: &mut Context<Self>,
6990 ) {
6991 self.manipulate_lines(window, cx, |lines| lines.sort())
6992 }
6993
6994 pub fn sort_lines_case_insensitive(
6995 &mut self,
6996 _: &SortLinesCaseInsensitive,
6997 window: &mut Window,
6998 cx: &mut Context<Self>,
6999 ) {
7000 self.manipulate_lines(window, cx, |lines| {
7001 lines.sort_by_key(|line| line.to_lowercase())
7002 })
7003 }
7004
7005 pub fn unique_lines_case_insensitive(
7006 &mut self,
7007 _: &UniqueLinesCaseInsensitive,
7008 window: &mut Window,
7009 cx: &mut Context<Self>,
7010 ) {
7011 self.manipulate_lines(window, cx, |lines| {
7012 let mut seen = HashSet::default();
7013 lines.retain(|line| seen.insert(line.to_lowercase()));
7014 })
7015 }
7016
7017 pub fn unique_lines_case_sensitive(
7018 &mut self,
7019 _: &UniqueLinesCaseSensitive,
7020 window: &mut Window,
7021 cx: &mut Context<Self>,
7022 ) {
7023 self.manipulate_lines(window, cx, |lines| {
7024 let mut seen = HashSet::default();
7025 lines.retain(|line| seen.insert(*line));
7026 })
7027 }
7028
7029 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7030 let mut revert_changes = HashMap::default();
7031 let snapshot = self.snapshot(window, cx);
7032 for hunk in snapshot
7033 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7034 {
7035 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7036 }
7037 if !revert_changes.is_empty() {
7038 self.transact(window, cx, |editor, window, cx| {
7039 editor.revert(revert_changes, window, cx);
7040 });
7041 }
7042 }
7043
7044 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7045 let Some(project) = self.project.clone() else {
7046 return;
7047 };
7048 self.reload(project, window, cx)
7049 .detach_and_notify_err(window, cx);
7050 }
7051
7052 pub fn revert_selected_hunks(
7053 &mut self,
7054 _: &RevertSelectedHunks,
7055 window: &mut Window,
7056 cx: &mut Context<Self>,
7057 ) {
7058 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7059 self.revert_hunks_in_ranges(selections, window, cx);
7060 }
7061
7062 fn revert_hunks_in_ranges(
7063 &mut self,
7064 ranges: impl Iterator<Item = Range<Point>>,
7065 window: &mut Window,
7066 cx: &mut Context<Editor>,
7067 ) {
7068 let mut revert_changes = HashMap::default();
7069 let snapshot = self.snapshot(window, cx);
7070 for hunk in &snapshot.hunks_for_ranges(ranges) {
7071 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7072 }
7073 if !revert_changes.is_empty() {
7074 self.transact(window, cx, |editor, window, cx| {
7075 editor.revert(revert_changes, window, cx);
7076 });
7077 }
7078 }
7079
7080 pub fn open_active_item_in_terminal(
7081 &mut self,
7082 _: &OpenInTerminal,
7083 window: &mut Window,
7084 cx: &mut Context<Self>,
7085 ) {
7086 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7087 let project_path = buffer.read(cx).project_path(cx)?;
7088 let project = self.project.as_ref()?.read(cx);
7089 let entry = project.entry_for_path(&project_path, cx)?;
7090 let parent = match &entry.canonical_path {
7091 Some(canonical_path) => canonical_path.to_path_buf(),
7092 None => project.absolute_path(&project_path, cx)?,
7093 }
7094 .parent()?
7095 .to_path_buf();
7096 Some(parent)
7097 }) {
7098 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7099 }
7100 }
7101
7102 pub fn prepare_revert_change(
7103 &self,
7104 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7105 hunk: &MultiBufferDiffHunk,
7106 cx: &mut App,
7107 ) -> Option<()> {
7108 let buffer = self.buffer.read(cx);
7109 let diff = buffer.diff_for(hunk.buffer_id)?;
7110 let buffer = buffer.buffer(hunk.buffer_id)?;
7111 let buffer = buffer.read(cx);
7112 let original_text = diff
7113 .read(cx)
7114 .base_text()
7115 .as_ref()?
7116 .as_rope()
7117 .slice(hunk.diff_base_byte_range.clone());
7118 let buffer_snapshot = buffer.snapshot();
7119 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7120 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7121 probe
7122 .0
7123 .start
7124 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7125 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7126 }) {
7127 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7128 Some(())
7129 } else {
7130 None
7131 }
7132 }
7133
7134 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7135 self.manipulate_lines(window, cx, |lines| lines.reverse())
7136 }
7137
7138 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7139 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7140 }
7141
7142 fn manipulate_lines<Fn>(
7143 &mut self,
7144 window: &mut Window,
7145 cx: &mut Context<Self>,
7146 mut callback: Fn,
7147 ) where
7148 Fn: FnMut(&mut Vec<&str>),
7149 {
7150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7151 let buffer = self.buffer.read(cx).snapshot(cx);
7152
7153 let mut edits = Vec::new();
7154
7155 let selections = self.selections.all::<Point>(cx);
7156 let mut selections = selections.iter().peekable();
7157 let mut contiguous_row_selections = Vec::new();
7158 let mut new_selections = Vec::new();
7159 let mut added_lines = 0;
7160 let mut removed_lines = 0;
7161
7162 while let Some(selection) = selections.next() {
7163 let (start_row, end_row) = consume_contiguous_rows(
7164 &mut contiguous_row_selections,
7165 selection,
7166 &display_map,
7167 &mut selections,
7168 );
7169
7170 let start_point = Point::new(start_row.0, 0);
7171 let end_point = Point::new(
7172 end_row.previous_row().0,
7173 buffer.line_len(end_row.previous_row()),
7174 );
7175 let text = buffer
7176 .text_for_range(start_point..end_point)
7177 .collect::<String>();
7178
7179 let mut lines = text.split('\n').collect_vec();
7180
7181 let lines_before = lines.len();
7182 callback(&mut lines);
7183 let lines_after = lines.len();
7184
7185 edits.push((start_point..end_point, lines.join("\n")));
7186
7187 // Selections must change based on added and removed line count
7188 let start_row =
7189 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7190 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7191 new_selections.push(Selection {
7192 id: selection.id,
7193 start: start_row,
7194 end: end_row,
7195 goal: SelectionGoal::None,
7196 reversed: selection.reversed,
7197 });
7198
7199 if lines_after > lines_before {
7200 added_lines += lines_after - lines_before;
7201 } else if lines_before > lines_after {
7202 removed_lines += lines_before - lines_after;
7203 }
7204 }
7205
7206 self.transact(window, cx, |this, window, cx| {
7207 let buffer = this.buffer.update(cx, |buffer, cx| {
7208 buffer.edit(edits, None, cx);
7209 buffer.snapshot(cx)
7210 });
7211
7212 // Recalculate offsets on newly edited buffer
7213 let new_selections = new_selections
7214 .iter()
7215 .map(|s| {
7216 let start_point = Point::new(s.start.0, 0);
7217 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7218 Selection {
7219 id: s.id,
7220 start: buffer.point_to_offset(start_point),
7221 end: buffer.point_to_offset(end_point),
7222 goal: s.goal,
7223 reversed: s.reversed,
7224 }
7225 })
7226 .collect();
7227
7228 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7229 s.select(new_selections);
7230 });
7231
7232 this.request_autoscroll(Autoscroll::fit(), cx);
7233 });
7234 }
7235
7236 pub fn convert_to_upper_case(
7237 &mut self,
7238 _: &ConvertToUpperCase,
7239 window: &mut Window,
7240 cx: &mut Context<Self>,
7241 ) {
7242 self.manipulate_text(window, cx, |text| text.to_uppercase())
7243 }
7244
7245 pub fn convert_to_lower_case(
7246 &mut self,
7247 _: &ConvertToLowerCase,
7248 window: &mut Window,
7249 cx: &mut Context<Self>,
7250 ) {
7251 self.manipulate_text(window, cx, |text| text.to_lowercase())
7252 }
7253
7254 pub fn convert_to_title_case(
7255 &mut self,
7256 _: &ConvertToTitleCase,
7257 window: &mut Window,
7258 cx: &mut Context<Self>,
7259 ) {
7260 self.manipulate_text(window, cx, |text| {
7261 text.split('\n')
7262 .map(|line| line.to_case(Case::Title))
7263 .join("\n")
7264 })
7265 }
7266
7267 pub fn convert_to_snake_case(
7268 &mut self,
7269 _: &ConvertToSnakeCase,
7270 window: &mut Window,
7271 cx: &mut Context<Self>,
7272 ) {
7273 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7274 }
7275
7276 pub fn convert_to_kebab_case(
7277 &mut self,
7278 _: &ConvertToKebabCase,
7279 window: &mut Window,
7280 cx: &mut Context<Self>,
7281 ) {
7282 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7283 }
7284
7285 pub fn convert_to_upper_camel_case(
7286 &mut self,
7287 _: &ConvertToUpperCamelCase,
7288 window: &mut Window,
7289 cx: &mut Context<Self>,
7290 ) {
7291 self.manipulate_text(window, cx, |text| {
7292 text.split('\n')
7293 .map(|line| line.to_case(Case::UpperCamel))
7294 .join("\n")
7295 })
7296 }
7297
7298 pub fn convert_to_lower_camel_case(
7299 &mut self,
7300 _: &ConvertToLowerCamelCase,
7301 window: &mut Window,
7302 cx: &mut Context<Self>,
7303 ) {
7304 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7305 }
7306
7307 pub fn convert_to_opposite_case(
7308 &mut self,
7309 _: &ConvertToOppositeCase,
7310 window: &mut Window,
7311 cx: &mut Context<Self>,
7312 ) {
7313 self.manipulate_text(window, cx, |text| {
7314 text.chars()
7315 .fold(String::with_capacity(text.len()), |mut t, c| {
7316 if c.is_uppercase() {
7317 t.extend(c.to_lowercase());
7318 } else {
7319 t.extend(c.to_uppercase());
7320 }
7321 t
7322 })
7323 })
7324 }
7325
7326 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7327 where
7328 Fn: FnMut(&str) -> String,
7329 {
7330 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7331 let buffer = self.buffer.read(cx).snapshot(cx);
7332
7333 let mut new_selections = Vec::new();
7334 let mut edits = Vec::new();
7335 let mut selection_adjustment = 0i32;
7336
7337 for selection in self.selections.all::<usize>(cx) {
7338 let selection_is_empty = selection.is_empty();
7339
7340 let (start, end) = if selection_is_empty {
7341 let word_range = movement::surrounding_word(
7342 &display_map,
7343 selection.start.to_display_point(&display_map),
7344 );
7345 let start = word_range.start.to_offset(&display_map, Bias::Left);
7346 let end = word_range.end.to_offset(&display_map, Bias::Left);
7347 (start, end)
7348 } else {
7349 (selection.start, selection.end)
7350 };
7351
7352 let text = buffer.text_for_range(start..end).collect::<String>();
7353 let old_length = text.len() as i32;
7354 let text = callback(&text);
7355
7356 new_selections.push(Selection {
7357 start: (start as i32 - selection_adjustment) as usize,
7358 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7359 goal: SelectionGoal::None,
7360 ..selection
7361 });
7362
7363 selection_adjustment += old_length - text.len() as i32;
7364
7365 edits.push((start..end, text));
7366 }
7367
7368 self.transact(window, cx, |this, window, cx| {
7369 this.buffer.update(cx, |buffer, cx| {
7370 buffer.edit(edits, None, cx);
7371 });
7372
7373 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7374 s.select(new_selections);
7375 });
7376
7377 this.request_autoscroll(Autoscroll::fit(), cx);
7378 });
7379 }
7380
7381 pub fn duplicate(
7382 &mut self,
7383 upwards: bool,
7384 whole_lines: bool,
7385 window: &mut Window,
7386 cx: &mut Context<Self>,
7387 ) {
7388 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7389 let buffer = &display_map.buffer_snapshot;
7390 let selections = self.selections.all::<Point>(cx);
7391
7392 let mut edits = Vec::new();
7393 let mut selections_iter = selections.iter().peekable();
7394 while let Some(selection) = selections_iter.next() {
7395 let mut rows = selection.spanned_rows(false, &display_map);
7396 // duplicate line-wise
7397 if whole_lines || selection.start == selection.end {
7398 // Avoid duplicating the same lines twice.
7399 while let Some(next_selection) = selections_iter.peek() {
7400 let next_rows = next_selection.spanned_rows(false, &display_map);
7401 if next_rows.start < rows.end {
7402 rows.end = next_rows.end;
7403 selections_iter.next().unwrap();
7404 } else {
7405 break;
7406 }
7407 }
7408
7409 // Copy the text from the selected row region and splice it either at the start
7410 // or end of the region.
7411 let start = Point::new(rows.start.0, 0);
7412 let end = Point::new(
7413 rows.end.previous_row().0,
7414 buffer.line_len(rows.end.previous_row()),
7415 );
7416 let text = buffer
7417 .text_for_range(start..end)
7418 .chain(Some("\n"))
7419 .collect::<String>();
7420 let insert_location = if upwards {
7421 Point::new(rows.end.0, 0)
7422 } else {
7423 start
7424 };
7425 edits.push((insert_location..insert_location, text));
7426 } else {
7427 // duplicate character-wise
7428 let start = selection.start;
7429 let end = selection.end;
7430 let text = buffer.text_for_range(start..end).collect::<String>();
7431 edits.push((selection.end..selection.end, text));
7432 }
7433 }
7434
7435 self.transact(window, cx, |this, _, cx| {
7436 this.buffer.update(cx, |buffer, cx| {
7437 buffer.edit(edits, None, cx);
7438 });
7439
7440 this.request_autoscroll(Autoscroll::fit(), cx);
7441 });
7442 }
7443
7444 pub fn duplicate_line_up(
7445 &mut self,
7446 _: &DuplicateLineUp,
7447 window: &mut Window,
7448 cx: &mut Context<Self>,
7449 ) {
7450 self.duplicate(true, true, window, cx);
7451 }
7452
7453 pub fn duplicate_line_down(
7454 &mut self,
7455 _: &DuplicateLineDown,
7456 window: &mut Window,
7457 cx: &mut Context<Self>,
7458 ) {
7459 self.duplicate(false, true, window, cx);
7460 }
7461
7462 pub fn duplicate_selection(
7463 &mut self,
7464 _: &DuplicateSelection,
7465 window: &mut Window,
7466 cx: &mut Context<Self>,
7467 ) {
7468 self.duplicate(false, false, window, cx);
7469 }
7470
7471 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7472 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7473 let buffer = self.buffer.read(cx).snapshot(cx);
7474
7475 let mut edits = Vec::new();
7476 let mut unfold_ranges = Vec::new();
7477 let mut refold_creases = Vec::new();
7478
7479 let selections = self.selections.all::<Point>(cx);
7480 let mut selections = selections.iter().peekable();
7481 let mut contiguous_row_selections = Vec::new();
7482 let mut new_selections = Vec::new();
7483
7484 while let Some(selection) = selections.next() {
7485 // Find all the selections that span a contiguous row range
7486 let (start_row, end_row) = consume_contiguous_rows(
7487 &mut contiguous_row_selections,
7488 selection,
7489 &display_map,
7490 &mut selections,
7491 );
7492
7493 // Move the text spanned by the row range to be before the line preceding the row range
7494 if start_row.0 > 0 {
7495 let range_to_move = Point::new(
7496 start_row.previous_row().0,
7497 buffer.line_len(start_row.previous_row()),
7498 )
7499 ..Point::new(
7500 end_row.previous_row().0,
7501 buffer.line_len(end_row.previous_row()),
7502 );
7503 let insertion_point = display_map
7504 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7505 .0;
7506
7507 // Don't move lines across excerpts
7508 if buffer
7509 .excerpt_containing(insertion_point..range_to_move.end)
7510 .is_some()
7511 {
7512 let text = buffer
7513 .text_for_range(range_to_move.clone())
7514 .flat_map(|s| s.chars())
7515 .skip(1)
7516 .chain(['\n'])
7517 .collect::<String>();
7518
7519 edits.push((
7520 buffer.anchor_after(range_to_move.start)
7521 ..buffer.anchor_before(range_to_move.end),
7522 String::new(),
7523 ));
7524 let insertion_anchor = buffer.anchor_after(insertion_point);
7525 edits.push((insertion_anchor..insertion_anchor, text));
7526
7527 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7528
7529 // Move selections up
7530 new_selections.extend(contiguous_row_selections.drain(..).map(
7531 |mut selection| {
7532 selection.start.row -= row_delta;
7533 selection.end.row -= row_delta;
7534 selection
7535 },
7536 ));
7537
7538 // Move folds up
7539 unfold_ranges.push(range_to_move.clone());
7540 for fold in display_map.folds_in_range(
7541 buffer.anchor_before(range_to_move.start)
7542 ..buffer.anchor_after(range_to_move.end),
7543 ) {
7544 let mut start = fold.range.start.to_point(&buffer);
7545 let mut end = fold.range.end.to_point(&buffer);
7546 start.row -= row_delta;
7547 end.row -= row_delta;
7548 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7549 }
7550 }
7551 }
7552
7553 // If we didn't move line(s), preserve the existing selections
7554 new_selections.append(&mut contiguous_row_selections);
7555 }
7556
7557 self.transact(window, cx, |this, window, cx| {
7558 this.unfold_ranges(&unfold_ranges, true, true, cx);
7559 this.buffer.update(cx, |buffer, cx| {
7560 for (range, text) in edits {
7561 buffer.edit([(range, text)], None, cx);
7562 }
7563 });
7564 this.fold_creases(refold_creases, true, window, cx);
7565 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7566 s.select(new_selections);
7567 })
7568 });
7569 }
7570
7571 pub fn move_line_down(
7572 &mut self,
7573 _: &MoveLineDown,
7574 window: &mut Window,
7575 cx: &mut Context<Self>,
7576 ) {
7577 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7578 let buffer = self.buffer.read(cx).snapshot(cx);
7579
7580 let mut edits = Vec::new();
7581 let mut unfold_ranges = Vec::new();
7582 let mut refold_creases = Vec::new();
7583
7584 let selections = self.selections.all::<Point>(cx);
7585 let mut selections = selections.iter().peekable();
7586 let mut contiguous_row_selections = Vec::new();
7587 let mut new_selections = Vec::new();
7588
7589 while let Some(selection) = selections.next() {
7590 // Find all the selections that span a contiguous row range
7591 let (start_row, end_row) = consume_contiguous_rows(
7592 &mut contiguous_row_selections,
7593 selection,
7594 &display_map,
7595 &mut selections,
7596 );
7597
7598 // Move the text spanned by the row range to be after the last line of the row range
7599 if end_row.0 <= buffer.max_point().row {
7600 let range_to_move =
7601 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7602 let insertion_point = display_map
7603 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7604 .0;
7605
7606 // Don't move lines across excerpt boundaries
7607 if buffer
7608 .excerpt_containing(range_to_move.start..insertion_point)
7609 .is_some()
7610 {
7611 let mut text = String::from("\n");
7612 text.extend(buffer.text_for_range(range_to_move.clone()));
7613 text.pop(); // Drop trailing newline
7614 edits.push((
7615 buffer.anchor_after(range_to_move.start)
7616 ..buffer.anchor_before(range_to_move.end),
7617 String::new(),
7618 ));
7619 let insertion_anchor = buffer.anchor_after(insertion_point);
7620 edits.push((insertion_anchor..insertion_anchor, text));
7621
7622 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7623
7624 // Move selections down
7625 new_selections.extend(contiguous_row_selections.drain(..).map(
7626 |mut selection| {
7627 selection.start.row += row_delta;
7628 selection.end.row += row_delta;
7629 selection
7630 },
7631 ));
7632
7633 // Move folds down
7634 unfold_ranges.push(range_to_move.clone());
7635 for fold in display_map.folds_in_range(
7636 buffer.anchor_before(range_to_move.start)
7637 ..buffer.anchor_after(range_to_move.end),
7638 ) {
7639 let mut start = fold.range.start.to_point(&buffer);
7640 let mut end = fold.range.end.to_point(&buffer);
7641 start.row += row_delta;
7642 end.row += row_delta;
7643 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7644 }
7645 }
7646 }
7647
7648 // If we didn't move line(s), preserve the existing selections
7649 new_selections.append(&mut contiguous_row_selections);
7650 }
7651
7652 self.transact(window, cx, |this, window, cx| {
7653 this.unfold_ranges(&unfold_ranges, true, true, cx);
7654 this.buffer.update(cx, |buffer, cx| {
7655 for (range, text) in edits {
7656 buffer.edit([(range, text)], None, cx);
7657 }
7658 });
7659 this.fold_creases(refold_creases, true, window, cx);
7660 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7661 s.select(new_selections)
7662 });
7663 });
7664 }
7665
7666 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7667 let text_layout_details = &self.text_layout_details(window);
7668 self.transact(window, cx, |this, window, cx| {
7669 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7670 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7671 let line_mode = s.line_mode;
7672 s.move_with(|display_map, selection| {
7673 if !selection.is_empty() || line_mode {
7674 return;
7675 }
7676
7677 let mut head = selection.head();
7678 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7679 if head.column() == display_map.line_len(head.row()) {
7680 transpose_offset = display_map
7681 .buffer_snapshot
7682 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7683 }
7684
7685 if transpose_offset == 0 {
7686 return;
7687 }
7688
7689 *head.column_mut() += 1;
7690 head = display_map.clip_point(head, Bias::Right);
7691 let goal = SelectionGoal::HorizontalPosition(
7692 display_map
7693 .x_for_display_point(head, text_layout_details)
7694 .into(),
7695 );
7696 selection.collapse_to(head, goal);
7697
7698 let transpose_start = display_map
7699 .buffer_snapshot
7700 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7701 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7702 let transpose_end = display_map
7703 .buffer_snapshot
7704 .clip_offset(transpose_offset + 1, Bias::Right);
7705 if let Some(ch) =
7706 display_map.buffer_snapshot.chars_at(transpose_start).next()
7707 {
7708 edits.push((transpose_start..transpose_offset, String::new()));
7709 edits.push((transpose_end..transpose_end, ch.to_string()));
7710 }
7711 }
7712 });
7713 edits
7714 });
7715 this.buffer
7716 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7717 let selections = this.selections.all::<usize>(cx);
7718 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7719 s.select(selections);
7720 });
7721 });
7722 }
7723
7724 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7725 self.rewrap_impl(IsVimMode::No, cx)
7726 }
7727
7728 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7729 let buffer = self.buffer.read(cx).snapshot(cx);
7730 let selections = self.selections.all::<Point>(cx);
7731 let mut selections = selections.iter().peekable();
7732
7733 let mut edits = Vec::new();
7734 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7735
7736 while let Some(selection) = selections.next() {
7737 let mut start_row = selection.start.row;
7738 let mut end_row = selection.end.row;
7739
7740 // Skip selections that overlap with a range that has already been rewrapped.
7741 let selection_range = start_row..end_row;
7742 if rewrapped_row_ranges
7743 .iter()
7744 .any(|range| range.overlaps(&selection_range))
7745 {
7746 continue;
7747 }
7748
7749 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7750
7751 // Since not all lines in the selection may be at the same indent
7752 // level, choose the indent size that is the most common between all
7753 // of the lines.
7754 //
7755 // If there is a tie, we use the deepest indent.
7756 let (indent_size, indent_end) = {
7757 let mut indent_size_occurrences = HashMap::default();
7758 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7759
7760 for row in start_row..=end_row {
7761 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7762 rows_by_indent_size.entry(indent).or_default().push(row);
7763 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7764 }
7765
7766 let indent_size = indent_size_occurrences
7767 .into_iter()
7768 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7769 .map(|(indent, _)| indent)
7770 .unwrap_or_default();
7771 let row = rows_by_indent_size[&indent_size][0];
7772 let indent_end = Point::new(row, indent_size.len);
7773
7774 (indent_size, indent_end)
7775 };
7776
7777 let mut line_prefix = indent_size.chars().collect::<String>();
7778
7779 let mut inside_comment = false;
7780 if let Some(comment_prefix) =
7781 buffer
7782 .language_scope_at(selection.head())
7783 .and_then(|language| {
7784 language
7785 .line_comment_prefixes()
7786 .iter()
7787 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7788 .cloned()
7789 })
7790 {
7791 line_prefix.push_str(&comment_prefix);
7792 inside_comment = true;
7793 }
7794
7795 let language_settings = buffer.settings_at(selection.head(), cx);
7796 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
7797 RewrapBehavior::InComments => inside_comment,
7798 RewrapBehavior::InSelections => !selection.is_empty(),
7799 RewrapBehavior::Anywhere => true,
7800 };
7801
7802 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
7803 if !should_rewrap {
7804 continue;
7805 }
7806
7807 if selection.is_empty() {
7808 'expand_upwards: while start_row > 0 {
7809 let prev_row = start_row - 1;
7810 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7811 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7812 {
7813 start_row = prev_row;
7814 } else {
7815 break 'expand_upwards;
7816 }
7817 }
7818
7819 'expand_downwards: while end_row < buffer.max_point().row {
7820 let next_row = end_row + 1;
7821 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7822 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7823 {
7824 end_row = next_row;
7825 } else {
7826 break 'expand_downwards;
7827 }
7828 }
7829 }
7830
7831 let start = Point::new(start_row, 0);
7832 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7833 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7834 let Some(lines_without_prefixes) = selection_text
7835 .lines()
7836 .map(|line| {
7837 line.strip_prefix(&line_prefix)
7838 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7839 .ok_or_else(|| {
7840 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7841 })
7842 })
7843 .collect::<Result<Vec<_>, _>>()
7844 .log_err()
7845 else {
7846 continue;
7847 };
7848
7849 let wrap_column = buffer
7850 .settings_at(Point::new(start_row, 0), cx)
7851 .preferred_line_length as usize;
7852 let wrapped_text = wrap_with_prefix(
7853 line_prefix,
7854 lines_without_prefixes.join(" "),
7855 wrap_column,
7856 tab_size,
7857 );
7858
7859 // TODO: should always use char-based diff while still supporting cursor behavior that
7860 // matches vim.
7861 let diff = match is_vim_mode {
7862 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7863 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7864 };
7865 let mut offset = start.to_offset(&buffer);
7866 let mut moved_since_edit = true;
7867
7868 for change in diff.iter_all_changes() {
7869 let value = change.value();
7870 match change.tag() {
7871 ChangeTag::Equal => {
7872 offset += value.len();
7873 moved_since_edit = true;
7874 }
7875 ChangeTag::Delete => {
7876 let start = buffer.anchor_after(offset);
7877 let end = buffer.anchor_before(offset + value.len());
7878
7879 if moved_since_edit {
7880 edits.push((start..end, String::new()));
7881 } else {
7882 edits.last_mut().unwrap().0.end = end;
7883 }
7884
7885 offset += value.len();
7886 moved_since_edit = false;
7887 }
7888 ChangeTag::Insert => {
7889 if moved_since_edit {
7890 let anchor = buffer.anchor_after(offset);
7891 edits.push((anchor..anchor, value.to_string()));
7892 } else {
7893 edits.last_mut().unwrap().1.push_str(value);
7894 }
7895
7896 moved_since_edit = false;
7897 }
7898 }
7899 }
7900
7901 rewrapped_row_ranges.push(start_row..=end_row);
7902 }
7903
7904 self.buffer
7905 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7906 }
7907
7908 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7909 let mut text = String::new();
7910 let buffer = self.buffer.read(cx).snapshot(cx);
7911 let mut selections = self.selections.all::<Point>(cx);
7912 let mut clipboard_selections = Vec::with_capacity(selections.len());
7913 {
7914 let max_point = buffer.max_point();
7915 let mut is_first = true;
7916 for selection in &mut selections {
7917 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7918 if is_entire_line {
7919 selection.start = Point::new(selection.start.row, 0);
7920 if !selection.is_empty() && selection.end.column == 0 {
7921 selection.end = cmp::min(max_point, selection.end);
7922 } else {
7923 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7924 }
7925 selection.goal = SelectionGoal::None;
7926 }
7927 if is_first {
7928 is_first = false;
7929 } else {
7930 text += "\n";
7931 }
7932 let mut len = 0;
7933 for chunk in buffer.text_for_range(selection.start..selection.end) {
7934 text.push_str(chunk);
7935 len += chunk.len();
7936 }
7937 clipboard_selections.push(ClipboardSelection {
7938 len,
7939 is_entire_line,
7940 first_line_indent: buffer
7941 .indent_size_for_line(MultiBufferRow(selection.start.row))
7942 .len,
7943 });
7944 }
7945 }
7946
7947 self.transact(window, cx, |this, window, cx| {
7948 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7949 s.select(selections);
7950 });
7951 this.insert("", window, cx);
7952 });
7953 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7954 }
7955
7956 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7957 let item = self.cut_common(window, cx);
7958 cx.write_to_clipboard(item);
7959 }
7960
7961 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7962 self.change_selections(None, window, cx, |s| {
7963 s.move_with(|snapshot, sel| {
7964 if sel.is_empty() {
7965 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7966 }
7967 });
7968 });
7969 let item = self.cut_common(window, cx);
7970 cx.set_global(KillRing(item))
7971 }
7972
7973 pub fn kill_ring_yank(
7974 &mut self,
7975 _: &KillRingYank,
7976 window: &mut Window,
7977 cx: &mut Context<Self>,
7978 ) {
7979 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7980 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7981 (kill_ring.text().to_string(), kill_ring.metadata_json())
7982 } else {
7983 return;
7984 }
7985 } else {
7986 return;
7987 };
7988 self.do_paste(&text, metadata, false, window, cx);
7989 }
7990
7991 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7992 let selections = self.selections.all::<Point>(cx);
7993 let buffer = self.buffer.read(cx).read(cx);
7994 let mut text = String::new();
7995
7996 let mut clipboard_selections = Vec::with_capacity(selections.len());
7997 {
7998 let max_point = buffer.max_point();
7999 let mut is_first = true;
8000 for selection in selections.iter() {
8001 let mut start = selection.start;
8002 let mut end = selection.end;
8003 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8004 if is_entire_line {
8005 start = Point::new(start.row, 0);
8006 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8007 }
8008 if is_first {
8009 is_first = false;
8010 } else {
8011 text += "\n";
8012 }
8013 let mut len = 0;
8014 for chunk in buffer.text_for_range(start..end) {
8015 text.push_str(chunk);
8016 len += chunk.len();
8017 }
8018 clipboard_selections.push(ClipboardSelection {
8019 len,
8020 is_entire_line,
8021 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8022 });
8023 }
8024 }
8025
8026 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8027 text,
8028 clipboard_selections,
8029 ));
8030 }
8031
8032 pub fn do_paste(
8033 &mut self,
8034 text: &String,
8035 clipboard_selections: Option<Vec<ClipboardSelection>>,
8036 handle_entire_lines: bool,
8037 window: &mut Window,
8038 cx: &mut Context<Self>,
8039 ) {
8040 if self.read_only(cx) {
8041 return;
8042 }
8043
8044 let clipboard_text = Cow::Borrowed(text);
8045
8046 self.transact(window, cx, |this, window, cx| {
8047 if let Some(mut clipboard_selections) = clipboard_selections {
8048 let old_selections = this.selections.all::<usize>(cx);
8049 let all_selections_were_entire_line =
8050 clipboard_selections.iter().all(|s| s.is_entire_line);
8051 let first_selection_indent_column =
8052 clipboard_selections.first().map(|s| s.first_line_indent);
8053 if clipboard_selections.len() != old_selections.len() {
8054 clipboard_selections.drain(..);
8055 }
8056 let cursor_offset = this.selections.last::<usize>(cx).head();
8057 let mut auto_indent_on_paste = true;
8058
8059 this.buffer.update(cx, |buffer, cx| {
8060 let snapshot = buffer.read(cx);
8061 auto_indent_on_paste =
8062 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8063
8064 let mut start_offset = 0;
8065 let mut edits = Vec::new();
8066 let mut original_indent_columns = Vec::new();
8067 for (ix, selection) in old_selections.iter().enumerate() {
8068 let to_insert;
8069 let entire_line;
8070 let original_indent_column;
8071 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8072 let end_offset = start_offset + clipboard_selection.len;
8073 to_insert = &clipboard_text[start_offset..end_offset];
8074 entire_line = clipboard_selection.is_entire_line;
8075 start_offset = end_offset + 1;
8076 original_indent_column = Some(clipboard_selection.first_line_indent);
8077 } else {
8078 to_insert = clipboard_text.as_str();
8079 entire_line = all_selections_were_entire_line;
8080 original_indent_column = first_selection_indent_column
8081 }
8082
8083 // If the corresponding selection was empty when this slice of the
8084 // clipboard text was written, then the entire line containing the
8085 // selection was copied. If this selection is also currently empty,
8086 // then paste the line before the current line of the buffer.
8087 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8088 let column = selection.start.to_point(&snapshot).column as usize;
8089 let line_start = selection.start - column;
8090 line_start..line_start
8091 } else {
8092 selection.range()
8093 };
8094
8095 edits.push((range, to_insert));
8096 original_indent_columns.extend(original_indent_column);
8097 }
8098 drop(snapshot);
8099
8100 buffer.edit(
8101 edits,
8102 if auto_indent_on_paste {
8103 Some(AutoindentMode::Block {
8104 original_indent_columns,
8105 })
8106 } else {
8107 None
8108 },
8109 cx,
8110 );
8111 });
8112
8113 let selections = this.selections.all::<usize>(cx);
8114 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8115 s.select(selections)
8116 });
8117 } else {
8118 this.insert(&clipboard_text, window, cx);
8119 }
8120 });
8121 }
8122
8123 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8124 if let Some(item) = cx.read_from_clipboard() {
8125 let entries = item.entries();
8126
8127 match entries.first() {
8128 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8129 // of all the pasted entries.
8130 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8131 .do_paste(
8132 clipboard_string.text(),
8133 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8134 true,
8135 window,
8136 cx,
8137 ),
8138 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8139 }
8140 }
8141 }
8142
8143 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8144 if self.read_only(cx) {
8145 return;
8146 }
8147
8148 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8149 if let Some((selections, _)) =
8150 self.selection_history.transaction(transaction_id).cloned()
8151 {
8152 self.change_selections(None, window, cx, |s| {
8153 s.select_anchors(selections.to_vec());
8154 });
8155 }
8156 self.request_autoscroll(Autoscroll::fit(), cx);
8157 self.unmark_text(window, cx);
8158 self.refresh_inline_completion(true, false, window, cx);
8159 cx.emit(EditorEvent::Edited { transaction_id });
8160 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8161 }
8162 }
8163
8164 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8165 if self.read_only(cx) {
8166 return;
8167 }
8168
8169 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8170 if let Some((_, Some(selections))) =
8171 self.selection_history.transaction(transaction_id).cloned()
8172 {
8173 self.change_selections(None, window, cx, |s| {
8174 s.select_anchors(selections.to_vec());
8175 });
8176 }
8177 self.request_autoscroll(Autoscroll::fit(), cx);
8178 self.unmark_text(window, cx);
8179 self.refresh_inline_completion(true, false, window, cx);
8180 cx.emit(EditorEvent::Edited { transaction_id });
8181 }
8182 }
8183
8184 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8185 self.buffer
8186 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8187 }
8188
8189 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8190 self.buffer
8191 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8192 }
8193
8194 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8195 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8196 let line_mode = s.line_mode;
8197 s.move_with(|map, selection| {
8198 let cursor = if selection.is_empty() && !line_mode {
8199 movement::left(map, selection.start)
8200 } else {
8201 selection.start
8202 };
8203 selection.collapse_to(cursor, SelectionGoal::None);
8204 });
8205 })
8206 }
8207
8208 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8209 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8210 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8211 })
8212 }
8213
8214 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8215 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8216 let line_mode = s.line_mode;
8217 s.move_with(|map, selection| {
8218 let cursor = if selection.is_empty() && !line_mode {
8219 movement::right(map, selection.end)
8220 } else {
8221 selection.end
8222 };
8223 selection.collapse_to(cursor, SelectionGoal::None)
8224 });
8225 })
8226 }
8227
8228 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8229 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8230 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8231 })
8232 }
8233
8234 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8235 if self.take_rename(true, window, cx).is_some() {
8236 return;
8237 }
8238
8239 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8240 cx.propagate();
8241 return;
8242 }
8243
8244 let text_layout_details = &self.text_layout_details(window);
8245 let selection_count = self.selections.count();
8246 let first_selection = self.selections.first_anchor();
8247
8248 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8249 let line_mode = s.line_mode;
8250 s.move_with(|map, selection| {
8251 if !selection.is_empty() && !line_mode {
8252 selection.goal = SelectionGoal::None;
8253 }
8254 let (cursor, goal) = movement::up(
8255 map,
8256 selection.start,
8257 selection.goal,
8258 false,
8259 text_layout_details,
8260 );
8261 selection.collapse_to(cursor, goal);
8262 });
8263 });
8264
8265 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8266 {
8267 cx.propagate();
8268 }
8269 }
8270
8271 pub fn move_up_by_lines(
8272 &mut self,
8273 action: &MoveUpByLines,
8274 window: &mut Window,
8275 cx: &mut Context<Self>,
8276 ) {
8277 if self.take_rename(true, window, cx).is_some() {
8278 return;
8279 }
8280
8281 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8282 cx.propagate();
8283 return;
8284 }
8285
8286 let text_layout_details = &self.text_layout_details(window);
8287
8288 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8289 let line_mode = s.line_mode;
8290 s.move_with(|map, selection| {
8291 if !selection.is_empty() && !line_mode {
8292 selection.goal = SelectionGoal::None;
8293 }
8294 let (cursor, goal) = movement::up_by_rows(
8295 map,
8296 selection.start,
8297 action.lines,
8298 selection.goal,
8299 false,
8300 text_layout_details,
8301 );
8302 selection.collapse_to(cursor, goal);
8303 });
8304 })
8305 }
8306
8307 pub fn move_down_by_lines(
8308 &mut self,
8309 action: &MoveDownByLines,
8310 window: &mut Window,
8311 cx: &mut Context<Self>,
8312 ) {
8313 if self.take_rename(true, window, cx).is_some() {
8314 return;
8315 }
8316
8317 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8318 cx.propagate();
8319 return;
8320 }
8321
8322 let text_layout_details = &self.text_layout_details(window);
8323
8324 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8325 let line_mode = s.line_mode;
8326 s.move_with(|map, selection| {
8327 if !selection.is_empty() && !line_mode {
8328 selection.goal = SelectionGoal::None;
8329 }
8330 let (cursor, goal) = movement::down_by_rows(
8331 map,
8332 selection.start,
8333 action.lines,
8334 selection.goal,
8335 false,
8336 text_layout_details,
8337 );
8338 selection.collapse_to(cursor, goal);
8339 });
8340 })
8341 }
8342
8343 pub fn select_down_by_lines(
8344 &mut self,
8345 action: &SelectDownByLines,
8346 window: &mut Window,
8347 cx: &mut Context<Self>,
8348 ) {
8349 let text_layout_details = &self.text_layout_details(window);
8350 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8351 s.move_heads_with(|map, head, goal| {
8352 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8353 })
8354 })
8355 }
8356
8357 pub fn select_up_by_lines(
8358 &mut self,
8359 action: &SelectUpByLines,
8360 window: &mut Window,
8361 cx: &mut Context<Self>,
8362 ) {
8363 let text_layout_details = &self.text_layout_details(window);
8364 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8365 s.move_heads_with(|map, head, goal| {
8366 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8367 })
8368 })
8369 }
8370
8371 pub fn select_page_up(
8372 &mut self,
8373 _: &SelectPageUp,
8374 window: &mut Window,
8375 cx: &mut Context<Self>,
8376 ) {
8377 let Some(row_count) = self.visible_row_count() else {
8378 return;
8379 };
8380
8381 let text_layout_details = &self.text_layout_details(window);
8382
8383 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8384 s.move_heads_with(|map, head, goal| {
8385 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8386 })
8387 })
8388 }
8389
8390 pub fn move_page_up(
8391 &mut self,
8392 action: &MovePageUp,
8393 window: &mut Window,
8394 cx: &mut Context<Self>,
8395 ) {
8396 if self.take_rename(true, window, cx).is_some() {
8397 return;
8398 }
8399
8400 if self
8401 .context_menu
8402 .borrow_mut()
8403 .as_mut()
8404 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8405 .unwrap_or(false)
8406 {
8407 return;
8408 }
8409
8410 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8411 cx.propagate();
8412 return;
8413 }
8414
8415 let Some(row_count) = self.visible_row_count() else {
8416 return;
8417 };
8418
8419 let autoscroll = if action.center_cursor {
8420 Autoscroll::center()
8421 } else {
8422 Autoscroll::fit()
8423 };
8424
8425 let text_layout_details = &self.text_layout_details(window);
8426
8427 self.change_selections(Some(autoscroll), window, cx, |s| {
8428 let line_mode = s.line_mode;
8429 s.move_with(|map, selection| {
8430 if !selection.is_empty() && !line_mode {
8431 selection.goal = SelectionGoal::None;
8432 }
8433 let (cursor, goal) = movement::up_by_rows(
8434 map,
8435 selection.end,
8436 row_count,
8437 selection.goal,
8438 false,
8439 text_layout_details,
8440 );
8441 selection.collapse_to(cursor, goal);
8442 });
8443 });
8444 }
8445
8446 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8447 let text_layout_details = &self.text_layout_details(window);
8448 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8449 s.move_heads_with(|map, head, goal| {
8450 movement::up(map, head, goal, false, text_layout_details)
8451 })
8452 })
8453 }
8454
8455 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8456 self.take_rename(true, window, cx);
8457
8458 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8459 cx.propagate();
8460 return;
8461 }
8462
8463 let text_layout_details = &self.text_layout_details(window);
8464 let selection_count = self.selections.count();
8465 let first_selection = self.selections.first_anchor();
8466
8467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8468 let line_mode = s.line_mode;
8469 s.move_with(|map, selection| {
8470 if !selection.is_empty() && !line_mode {
8471 selection.goal = SelectionGoal::None;
8472 }
8473 let (cursor, goal) = movement::down(
8474 map,
8475 selection.end,
8476 selection.goal,
8477 false,
8478 text_layout_details,
8479 );
8480 selection.collapse_to(cursor, goal);
8481 });
8482 });
8483
8484 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8485 {
8486 cx.propagate();
8487 }
8488 }
8489
8490 pub fn select_page_down(
8491 &mut self,
8492 _: &SelectPageDown,
8493 window: &mut Window,
8494 cx: &mut Context<Self>,
8495 ) {
8496 let Some(row_count) = self.visible_row_count() else {
8497 return;
8498 };
8499
8500 let text_layout_details = &self.text_layout_details(window);
8501
8502 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8503 s.move_heads_with(|map, head, goal| {
8504 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8505 })
8506 })
8507 }
8508
8509 pub fn move_page_down(
8510 &mut self,
8511 action: &MovePageDown,
8512 window: &mut Window,
8513 cx: &mut Context<Self>,
8514 ) {
8515 if self.take_rename(true, window, cx).is_some() {
8516 return;
8517 }
8518
8519 if self
8520 .context_menu
8521 .borrow_mut()
8522 .as_mut()
8523 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8524 .unwrap_or(false)
8525 {
8526 return;
8527 }
8528
8529 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8530 cx.propagate();
8531 return;
8532 }
8533
8534 let Some(row_count) = self.visible_row_count() else {
8535 return;
8536 };
8537
8538 let autoscroll = if action.center_cursor {
8539 Autoscroll::center()
8540 } else {
8541 Autoscroll::fit()
8542 };
8543
8544 let text_layout_details = &self.text_layout_details(window);
8545 self.change_selections(Some(autoscroll), window, cx, |s| {
8546 let line_mode = s.line_mode;
8547 s.move_with(|map, selection| {
8548 if !selection.is_empty() && !line_mode {
8549 selection.goal = SelectionGoal::None;
8550 }
8551 let (cursor, goal) = movement::down_by_rows(
8552 map,
8553 selection.end,
8554 row_count,
8555 selection.goal,
8556 false,
8557 text_layout_details,
8558 );
8559 selection.collapse_to(cursor, goal);
8560 });
8561 });
8562 }
8563
8564 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8565 let text_layout_details = &self.text_layout_details(window);
8566 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8567 s.move_heads_with(|map, head, goal| {
8568 movement::down(map, head, goal, false, text_layout_details)
8569 })
8570 });
8571 }
8572
8573 pub fn context_menu_first(
8574 &mut self,
8575 _: &ContextMenuFirst,
8576 _window: &mut Window,
8577 cx: &mut Context<Self>,
8578 ) {
8579 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8580 context_menu.select_first(self.completion_provider.as_deref(), cx);
8581 }
8582 }
8583
8584 pub fn context_menu_prev(
8585 &mut self,
8586 _: &ContextMenuPrev,
8587 _window: &mut Window,
8588 cx: &mut Context<Self>,
8589 ) {
8590 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8591 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8592 }
8593 }
8594
8595 pub fn context_menu_next(
8596 &mut self,
8597 _: &ContextMenuNext,
8598 _window: &mut Window,
8599 cx: &mut Context<Self>,
8600 ) {
8601 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8602 context_menu.select_next(self.completion_provider.as_deref(), cx);
8603 }
8604 }
8605
8606 pub fn context_menu_last(
8607 &mut self,
8608 _: &ContextMenuLast,
8609 _window: &mut Window,
8610 cx: &mut Context<Self>,
8611 ) {
8612 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8613 context_menu.select_last(self.completion_provider.as_deref(), cx);
8614 }
8615 }
8616
8617 pub fn move_to_previous_word_start(
8618 &mut self,
8619 _: &MoveToPreviousWordStart,
8620 window: &mut Window,
8621 cx: &mut Context<Self>,
8622 ) {
8623 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8624 s.move_cursors_with(|map, head, _| {
8625 (
8626 movement::previous_word_start(map, head),
8627 SelectionGoal::None,
8628 )
8629 });
8630 })
8631 }
8632
8633 pub fn move_to_previous_subword_start(
8634 &mut self,
8635 _: &MoveToPreviousSubwordStart,
8636 window: &mut Window,
8637 cx: &mut Context<Self>,
8638 ) {
8639 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8640 s.move_cursors_with(|map, head, _| {
8641 (
8642 movement::previous_subword_start(map, head),
8643 SelectionGoal::None,
8644 )
8645 });
8646 })
8647 }
8648
8649 pub fn select_to_previous_word_start(
8650 &mut self,
8651 _: &SelectToPreviousWordStart,
8652 window: &mut Window,
8653 cx: &mut Context<Self>,
8654 ) {
8655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8656 s.move_heads_with(|map, head, _| {
8657 (
8658 movement::previous_word_start(map, head),
8659 SelectionGoal::None,
8660 )
8661 });
8662 })
8663 }
8664
8665 pub fn select_to_previous_subword_start(
8666 &mut self,
8667 _: &SelectToPreviousSubwordStart,
8668 window: &mut Window,
8669 cx: &mut Context<Self>,
8670 ) {
8671 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8672 s.move_heads_with(|map, head, _| {
8673 (
8674 movement::previous_subword_start(map, head),
8675 SelectionGoal::None,
8676 )
8677 });
8678 })
8679 }
8680
8681 pub fn delete_to_previous_word_start(
8682 &mut self,
8683 action: &DeleteToPreviousWordStart,
8684 window: &mut Window,
8685 cx: &mut Context<Self>,
8686 ) {
8687 self.transact(window, cx, |this, window, cx| {
8688 this.select_autoclose_pair(window, cx);
8689 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8690 let line_mode = s.line_mode;
8691 s.move_with(|map, selection| {
8692 if selection.is_empty() && !line_mode {
8693 let cursor = if action.ignore_newlines {
8694 movement::previous_word_start(map, selection.head())
8695 } else {
8696 movement::previous_word_start_or_newline(map, selection.head())
8697 };
8698 selection.set_head(cursor, SelectionGoal::None);
8699 }
8700 });
8701 });
8702 this.insert("", window, cx);
8703 });
8704 }
8705
8706 pub fn delete_to_previous_subword_start(
8707 &mut self,
8708 _: &DeleteToPreviousSubwordStart,
8709 window: &mut Window,
8710 cx: &mut Context<Self>,
8711 ) {
8712 self.transact(window, cx, |this, window, cx| {
8713 this.select_autoclose_pair(window, cx);
8714 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8715 let line_mode = s.line_mode;
8716 s.move_with(|map, selection| {
8717 if selection.is_empty() && !line_mode {
8718 let cursor = movement::previous_subword_start(map, selection.head());
8719 selection.set_head(cursor, SelectionGoal::None);
8720 }
8721 });
8722 });
8723 this.insert("", window, cx);
8724 });
8725 }
8726
8727 pub fn move_to_next_word_end(
8728 &mut self,
8729 _: &MoveToNextWordEnd,
8730 window: &mut Window,
8731 cx: &mut Context<Self>,
8732 ) {
8733 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8734 s.move_cursors_with(|map, head, _| {
8735 (movement::next_word_end(map, head), SelectionGoal::None)
8736 });
8737 })
8738 }
8739
8740 pub fn move_to_next_subword_end(
8741 &mut self,
8742 _: &MoveToNextSubwordEnd,
8743 window: &mut Window,
8744 cx: &mut Context<Self>,
8745 ) {
8746 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8747 s.move_cursors_with(|map, head, _| {
8748 (movement::next_subword_end(map, head), SelectionGoal::None)
8749 });
8750 })
8751 }
8752
8753 pub fn select_to_next_word_end(
8754 &mut self,
8755 _: &SelectToNextWordEnd,
8756 window: &mut Window,
8757 cx: &mut Context<Self>,
8758 ) {
8759 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8760 s.move_heads_with(|map, head, _| {
8761 (movement::next_word_end(map, head), SelectionGoal::None)
8762 });
8763 })
8764 }
8765
8766 pub fn select_to_next_subword_end(
8767 &mut self,
8768 _: &SelectToNextSubwordEnd,
8769 window: &mut Window,
8770 cx: &mut Context<Self>,
8771 ) {
8772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.move_heads_with(|map, head, _| {
8774 (movement::next_subword_end(map, head), SelectionGoal::None)
8775 });
8776 })
8777 }
8778
8779 pub fn delete_to_next_word_end(
8780 &mut self,
8781 action: &DeleteToNextWordEnd,
8782 window: &mut Window,
8783 cx: &mut Context<Self>,
8784 ) {
8785 self.transact(window, cx, |this, window, cx| {
8786 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8787 let line_mode = s.line_mode;
8788 s.move_with(|map, selection| {
8789 if selection.is_empty() && !line_mode {
8790 let cursor = if action.ignore_newlines {
8791 movement::next_word_end(map, selection.head())
8792 } else {
8793 movement::next_word_end_or_newline(map, selection.head())
8794 };
8795 selection.set_head(cursor, SelectionGoal::None);
8796 }
8797 });
8798 });
8799 this.insert("", window, cx);
8800 });
8801 }
8802
8803 pub fn delete_to_next_subword_end(
8804 &mut self,
8805 _: &DeleteToNextSubwordEnd,
8806 window: &mut Window,
8807 cx: &mut Context<Self>,
8808 ) {
8809 self.transact(window, cx, |this, window, cx| {
8810 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8811 s.move_with(|map, selection| {
8812 if selection.is_empty() {
8813 let cursor = movement::next_subword_end(map, selection.head());
8814 selection.set_head(cursor, SelectionGoal::None);
8815 }
8816 });
8817 });
8818 this.insert("", window, cx);
8819 });
8820 }
8821
8822 pub fn move_to_beginning_of_line(
8823 &mut self,
8824 action: &MoveToBeginningOfLine,
8825 window: &mut Window,
8826 cx: &mut Context<Self>,
8827 ) {
8828 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8829 s.move_cursors_with(|map, head, _| {
8830 (
8831 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8832 SelectionGoal::None,
8833 )
8834 });
8835 })
8836 }
8837
8838 pub fn select_to_beginning_of_line(
8839 &mut self,
8840 action: &SelectToBeginningOfLine,
8841 window: &mut Window,
8842 cx: &mut Context<Self>,
8843 ) {
8844 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8845 s.move_heads_with(|map, head, _| {
8846 (
8847 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8848 SelectionGoal::None,
8849 )
8850 });
8851 });
8852 }
8853
8854 pub fn delete_to_beginning_of_line(
8855 &mut self,
8856 _: &DeleteToBeginningOfLine,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) {
8860 self.transact(window, cx, |this, window, cx| {
8861 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8862 s.move_with(|_, selection| {
8863 selection.reversed = true;
8864 });
8865 });
8866
8867 this.select_to_beginning_of_line(
8868 &SelectToBeginningOfLine {
8869 stop_at_soft_wraps: false,
8870 },
8871 window,
8872 cx,
8873 );
8874 this.backspace(&Backspace, window, cx);
8875 });
8876 }
8877
8878 pub fn move_to_end_of_line(
8879 &mut self,
8880 action: &MoveToEndOfLine,
8881 window: &mut Window,
8882 cx: &mut Context<Self>,
8883 ) {
8884 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8885 s.move_cursors_with(|map, head, _| {
8886 (
8887 movement::line_end(map, head, action.stop_at_soft_wraps),
8888 SelectionGoal::None,
8889 )
8890 });
8891 })
8892 }
8893
8894 pub fn select_to_end_of_line(
8895 &mut self,
8896 action: &SelectToEndOfLine,
8897 window: &mut Window,
8898 cx: &mut Context<Self>,
8899 ) {
8900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8901 s.move_heads_with(|map, head, _| {
8902 (
8903 movement::line_end(map, head, action.stop_at_soft_wraps),
8904 SelectionGoal::None,
8905 )
8906 });
8907 })
8908 }
8909
8910 pub fn delete_to_end_of_line(
8911 &mut self,
8912 _: &DeleteToEndOfLine,
8913 window: &mut Window,
8914 cx: &mut Context<Self>,
8915 ) {
8916 self.transact(window, cx, |this, window, cx| {
8917 this.select_to_end_of_line(
8918 &SelectToEndOfLine {
8919 stop_at_soft_wraps: false,
8920 },
8921 window,
8922 cx,
8923 );
8924 this.delete(&Delete, window, cx);
8925 });
8926 }
8927
8928 pub fn cut_to_end_of_line(
8929 &mut self,
8930 _: &CutToEndOfLine,
8931 window: &mut Window,
8932 cx: &mut Context<Self>,
8933 ) {
8934 self.transact(window, cx, |this, window, cx| {
8935 this.select_to_end_of_line(
8936 &SelectToEndOfLine {
8937 stop_at_soft_wraps: false,
8938 },
8939 window,
8940 cx,
8941 );
8942 this.cut(&Cut, window, cx);
8943 });
8944 }
8945
8946 pub fn move_to_start_of_paragraph(
8947 &mut self,
8948 _: &MoveToStartOfParagraph,
8949 window: &mut Window,
8950 cx: &mut Context<Self>,
8951 ) {
8952 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8953 cx.propagate();
8954 return;
8955 }
8956
8957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8958 s.move_with(|map, selection| {
8959 selection.collapse_to(
8960 movement::start_of_paragraph(map, selection.head(), 1),
8961 SelectionGoal::None,
8962 )
8963 });
8964 })
8965 }
8966
8967 pub fn move_to_end_of_paragraph(
8968 &mut self,
8969 _: &MoveToEndOfParagraph,
8970 window: &mut Window,
8971 cx: &mut Context<Self>,
8972 ) {
8973 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8974 cx.propagate();
8975 return;
8976 }
8977
8978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8979 s.move_with(|map, selection| {
8980 selection.collapse_to(
8981 movement::end_of_paragraph(map, selection.head(), 1),
8982 SelectionGoal::None,
8983 )
8984 });
8985 })
8986 }
8987
8988 pub fn select_to_start_of_paragraph(
8989 &mut self,
8990 _: &SelectToStartOfParagraph,
8991 window: &mut Window,
8992 cx: &mut Context<Self>,
8993 ) {
8994 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8995 cx.propagate();
8996 return;
8997 }
8998
8999 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9000 s.move_heads_with(|map, head, _| {
9001 (
9002 movement::start_of_paragraph(map, head, 1),
9003 SelectionGoal::None,
9004 )
9005 });
9006 })
9007 }
9008
9009 pub fn select_to_end_of_paragraph(
9010 &mut self,
9011 _: &SelectToEndOfParagraph,
9012 window: &mut Window,
9013 cx: &mut Context<Self>,
9014 ) {
9015 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9016 cx.propagate();
9017 return;
9018 }
9019
9020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9021 s.move_heads_with(|map, head, _| {
9022 (
9023 movement::end_of_paragraph(map, head, 1),
9024 SelectionGoal::None,
9025 )
9026 });
9027 })
9028 }
9029
9030 pub fn move_to_beginning(
9031 &mut self,
9032 _: &MoveToBeginning,
9033 window: &mut Window,
9034 cx: &mut Context<Self>,
9035 ) {
9036 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9037 cx.propagate();
9038 return;
9039 }
9040
9041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9042 s.select_ranges(vec![0..0]);
9043 });
9044 }
9045
9046 pub fn select_to_beginning(
9047 &mut self,
9048 _: &SelectToBeginning,
9049 window: &mut Window,
9050 cx: &mut Context<Self>,
9051 ) {
9052 let mut selection = self.selections.last::<Point>(cx);
9053 selection.set_head(Point::zero(), SelectionGoal::None);
9054
9055 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9056 s.select(vec![selection]);
9057 });
9058 }
9059
9060 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9061 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9062 cx.propagate();
9063 return;
9064 }
9065
9066 let cursor = self.buffer.read(cx).read(cx).len();
9067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9068 s.select_ranges(vec![cursor..cursor])
9069 });
9070 }
9071
9072 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9073 self.nav_history = nav_history;
9074 }
9075
9076 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9077 self.nav_history.as_ref()
9078 }
9079
9080 fn push_to_nav_history(
9081 &mut self,
9082 cursor_anchor: Anchor,
9083 new_position: Option<Point>,
9084 cx: &mut Context<Self>,
9085 ) {
9086 if let Some(nav_history) = self.nav_history.as_mut() {
9087 let buffer = self.buffer.read(cx).read(cx);
9088 let cursor_position = cursor_anchor.to_point(&buffer);
9089 let scroll_state = self.scroll_manager.anchor();
9090 let scroll_top_row = scroll_state.top_row(&buffer);
9091 drop(buffer);
9092
9093 if let Some(new_position) = new_position {
9094 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9095 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9096 return;
9097 }
9098 }
9099
9100 nav_history.push(
9101 Some(NavigationData {
9102 cursor_anchor,
9103 cursor_position,
9104 scroll_anchor: scroll_state,
9105 scroll_top_row,
9106 }),
9107 cx,
9108 );
9109 }
9110 }
9111
9112 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9113 let buffer = self.buffer.read(cx).snapshot(cx);
9114 let mut selection = self.selections.first::<usize>(cx);
9115 selection.set_head(buffer.len(), SelectionGoal::None);
9116 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9117 s.select(vec![selection]);
9118 });
9119 }
9120
9121 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9122 let end = self.buffer.read(cx).read(cx).len();
9123 self.change_selections(None, window, cx, |s| {
9124 s.select_ranges(vec![0..end]);
9125 });
9126 }
9127
9128 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9129 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9130 let mut selections = self.selections.all::<Point>(cx);
9131 let max_point = display_map.buffer_snapshot.max_point();
9132 for selection in &mut selections {
9133 let rows = selection.spanned_rows(true, &display_map);
9134 selection.start = Point::new(rows.start.0, 0);
9135 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9136 selection.reversed = false;
9137 }
9138 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9139 s.select(selections);
9140 });
9141 }
9142
9143 pub fn split_selection_into_lines(
9144 &mut self,
9145 _: &SplitSelectionIntoLines,
9146 window: &mut Window,
9147 cx: &mut Context<Self>,
9148 ) {
9149 let selections = self
9150 .selections
9151 .all::<Point>(cx)
9152 .into_iter()
9153 .map(|selection| selection.start..selection.end)
9154 .collect::<Vec<_>>();
9155 self.unfold_ranges(&selections, true, true, cx);
9156
9157 let mut new_selection_ranges = Vec::new();
9158 {
9159 let buffer = self.buffer.read(cx).read(cx);
9160 for selection in selections {
9161 for row in selection.start.row..selection.end.row {
9162 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9163 new_selection_ranges.push(cursor..cursor);
9164 }
9165
9166 let is_multiline_selection = selection.start.row != selection.end.row;
9167 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9168 // so this action feels more ergonomic when paired with other selection operations
9169 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9170 if !should_skip_last {
9171 new_selection_ranges.push(selection.end..selection.end);
9172 }
9173 }
9174 }
9175 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9176 s.select_ranges(new_selection_ranges);
9177 });
9178 }
9179
9180 pub fn add_selection_above(
9181 &mut self,
9182 _: &AddSelectionAbove,
9183 window: &mut Window,
9184 cx: &mut Context<Self>,
9185 ) {
9186 self.add_selection(true, window, cx);
9187 }
9188
9189 pub fn add_selection_below(
9190 &mut self,
9191 _: &AddSelectionBelow,
9192 window: &mut Window,
9193 cx: &mut Context<Self>,
9194 ) {
9195 self.add_selection(false, window, cx);
9196 }
9197
9198 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9200 let mut selections = self.selections.all::<Point>(cx);
9201 let text_layout_details = self.text_layout_details(window);
9202 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9203 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9204 let range = oldest_selection.display_range(&display_map).sorted();
9205
9206 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9207 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9208 let positions = start_x.min(end_x)..start_x.max(end_x);
9209
9210 selections.clear();
9211 let mut stack = Vec::new();
9212 for row in range.start.row().0..=range.end.row().0 {
9213 if let Some(selection) = self.selections.build_columnar_selection(
9214 &display_map,
9215 DisplayRow(row),
9216 &positions,
9217 oldest_selection.reversed,
9218 &text_layout_details,
9219 ) {
9220 stack.push(selection.id);
9221 selections.push(selection);
9222 }
9223 }
9224
9225 if above {
9226 stack.reverse();
9227 }
9228
9229 AddSelectionsState { above, stack }
9230 });
9231
9232 let last_added_selection = *state.stack.last().unwrap();
9233 let mut new_selections = Vec::new();
9234 if above == state.above {
9235 let end_row = if above {
9236 DisplayRow(0)
9237 } else {
9238 display_map.max_point().row()
9239 };
9240
9241 'outer: for selection in selections {
9242 if selection.id == last_added_selection {
9243 let range = selection.display_range(&display_map).sorted();
9244 debug_assert_eq!(range.start.row(), range.end.row());
9245 let mut row = range.start.row();
9246 let positions =
9247 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9248 px(start)..px(end)
9249 } else {
9250 let start_x =
9251 display_map.x_for_display_point(range.start, &text_layout_details);
9252 let end_x =
9253 display_map.x_for_display_point(range.end, &text_layout_details);
9254 start_x.min(end_x)..start_x.max(end_x)
9255 };
9256
9257 while row != end_row {
9258 if above {
9259 row.0 -= 1;
9260 } else {
9261 row.0 += 1;
9262 }
9263
9264 if let Some(new_selection) = self.selections.build_columnar_selection(
9265 &display_map,
9266 row,
9267 &positions,
9268 selection.reversed,
9269 &text_layout_details,
9270 ) {
9271 state.stack.push(new_selection.id);
9272 if above {
9273 new_selections.push(new_selection);
9274 new_selections.push(selection);
9275 } else {
9276 new_selections.push(selection);
9277 new_selections.push(new_selection);
9278 }
9279
9280 continue 'outer;
9281 }
9282 }
9283 }
9284
9285 new_selections.push(selection);
9286 }
9287 } else {
9288 new_selections = selections;
9289 new_selections.retain(|s| s.id != last_added_selection);
9290 state.stack.pop();
9291 }
9292
9293 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9294 s.select(new_selections);
9295 });
9296 if state.stack.len() > 1 {
9297 self.add_selections_state = Some(state);
9298 }
9299 }
9300
9301 pub fn select_next_match_internal(
9302 &mut self,
9303 display_map: &DisplaySnapshot,
9304 replace_newest: bool,
9305 autoscroll: Option<Autoscroll>,
9306 window: &mut Window,
9307 cx: &mut Context<Self>,
9308 ) -> Result<()> {
9309 fn select_next_match_ranges(
9310 this: &mut Editor,
9311 range: Range<usize>,
9312 replace_newest: bool,
9313 auto_scroll: Option<Autoscroll>,
9314 window: &mut Window,
9315 cx: &mut Context<Editor>,
9316 ) {
9317 this.unfold_ranges(&[range.clone()], false, true, cx);
9318 this.change_selections(auto_scroll, window, cx, |s| {
9319 if replace_newest {
9320 s.delete(s.newest_anchor().id);
9321 }
9322 s.insert_range(range.clone());
9323 });
9324 }
9325
9326 let buffer = &display_map.buffer_snapshot;
9327 let mut selections = self.selections.all::<usize>(cx);
9328 if let Some(mut select_next_state) = self.select_next_state.take() {
9329 let query = &select_next_state.query;
9330 if !select_next_state.done {
9331 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9332 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9333 let mut next_selected_range = None;
9334
9335 let bytes_after_last_selection =
9336 buffer.bytes_in_range(last_selection.end..buffer.len());
9337 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9338 let query_matches = query
9339 .stream_find_iter(bytes_after_last_selection)
9340 .map(|result| (last_selection.end, result))
9341 .chain(
9342 query
9343 .stream_find_iter(bytes_before_first_selection)
9344 .map(|result| (0, result)),
9345 );
9346
9347 for (start_offset, query_match) in query_matches {
9348 let query_match = query_match.unwrap(); // can only fail due to I/O
9349 let offset_range =
9350 start_offset + query_match.start()..start_offset + query_match.end();
9351 let display_range = offset_range.start.to_display_point(display_map)
9352 ..offset_range.end.to_display_point(display_map);
9353
9354 if !select_next_state.wordwise
9355 || (!movement::is_inside_word(display_map, display_range.start)
9356 && !movement::is_inside_word(display_map, display_range.end))
9357 {
9358 // TODO: This is n^2, because we might check all the selections
9359 if !selections
9360 .iter()
9361 .any(|selection| selection.range().overlaps(&offset_range))
9362 {
9363 next_selected_range = Some(offset_range);
9364 break;
9365 }
9366 }
9367 }
9368
9369 if let Some(next_selected_range) = next_selected_range {
9370 select_next_match_ranges(
9371 self,
9372 next_selected_range,
9373 replace_newest,
9374 autoscroll,
9375 window,
9376 cx,
9377 );
9378 } else {
9379 select_next_state.done = true;
9380 }
9381 }
9382
9383 self.select_next_state = Some(select_next_state);
9384 } else {
9385 let mut only_carets = true;
9386 let mut same_text_selected = true;
9387 let mut selected_text = None;
9388
9389 let mut selections_iter = selections.iter().peekable();
9390 while let Some(selection) = selections_iter.next() {
9391 if selection.start != selection.end {
9392 only_carets = false;
9393 }
9394
9395 if same_text_selected {
9396 if selected_text.is_none() {
9397 selected_text =
9398 Some(buffer.text_for_range(selection.range()).collect::<String>());
9399 }
9400
9401 if let Some(next_selection) = selections_iter.peek() {
9402 if next_selection.range().len() == selection.range().len() {
9403 let next_selected_text = buffer
9404 .text_for_range(next_selection.range())
9405 .collect::<String>();
9406 if Some(next_selected_text) != selected_text {
9407 same_text_selected = false;
9408 selected_text = None;
9409 }
9410 } else {
9411 same_text_selected = false;
9412 selected_text = None;
9413 }
9414 }
9415 }
9416 }
9417
9418 if only_carets {
9419 for selection in &mut selections {
9420 let word_range = movement::surrounding_word(
9421 display_map,
9422 selection.start.to_display_point(display_map),
9423 );
9424 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9425 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9426 selection.goal = SelectionGoal::None;
9427 selection.reversed = false;
9428 select_next_match_ranges(
9429 self,
9430 selection.start..selection.end,
9431 replace_newest,
9432 autoscroll,
9433 window,
9434 cx,
9435 );
9436 }
9437
9438 if selections.len() == 1 {
9439 let selection = selections
9440 .last()
9441 .expect("ensured that there's only one selection");
9442 let query = buffer
9443 .text_for_range(selection.start..selection.end)
9444 .collect::<String>();
9445 let is_empty = query.is_empty();
9446 let select_state = SelectNextState {
9447 query: AhoCorasick::new(&[query])?,
9448 wordwise: true,
9449 done: is_empty,
9450 };
9451 self.select_next_state = Some(select_state);
9452 } else {
9453 self.select_next_state = None;
9454 }
9455 } else if let Some(selected_text) = selected_text {
9456 self.select_next_state = Some(SelectNextState {
9457 query: AhoCorasick::new(&[selected_text])?,
9458 wordwise: false,
9459 done: false,
9460 });
9461 self.select_next_match_internal(
9462 display_map,
9463 replace_newest,
9464 autoscroll,
9465 window,
9466 cx,
9467 )?;
9468 }
9469 }
9470 Ok(())
9471 }
9472
9473 pub fn select_all_matches(
9474 &mut self,
9475 _action: &SelectAllMatches,
9476 window: &mut Window,
9477 cx: &mut Context<Self>,
9478 ) -> Result<()> {
9479 self.push_to_selection_history();
9480 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9481
9482 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9483 let Some(select_next_state) = self.select_next_state.as_mut() else {
9484 return Ok(());
9485 };
9486 if select_next_state.done {
9487 return Ok(());
9488 }
9489
9490 let mut new_selections = self.selections.all::<usize>(cx);
9491
9492 let buffer = &display_map.buffer_snapshot;
9493 let query_matches = select_next_state
9494 .query
9495 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9496
9497 for query_match in query_matches {
9498 let query_match = query_match.unwrap(); // can only fail due to I/O
9499 let offset_range = query_match.start()..query_match.end();
9500 let display_range = offset_range.start.to_display_point(&display_map)
9501 ..offset_range.end.to_display_point(&display_map);
9502
9503 if !select_next_state.wordwise
9504 || (!movement::is_inside_word(&display_map, display_range.start)
9505 && !movement::is_inside_word(&display_map, display_range.end))
9506 {
9507 self.selections.change_with(cx, |selections| {
9508 new_selections.push(Selection {
9509 id: selections.new_selection_id(),
9510 start: offset_range.start,
9511 end: offset_range.end,
9512 reversed: false,
9513 goal: SelectionGoal::None,
9514 });
9515 });
9516 }
9517 }
9518
9519 new_selections.sort_by_key(|selection| selection.start);
9520 let mut ix = 0;
9521 while ix + 1 < new_selections.len() {
9522 let current_selection = &new_selections[ix];
9523 let next_selection = &new_selections[ix + 1];
9524 if current_selection.range().overlaps(&next_selection.range()) {
9525 if current_selection.id < next_selection.id {
9526 new_selections.remove(ix + 1);
9527 } else {
9528 new_selections.remove(ix);
9529 }
9530 } else {
9531 ix += 1;
9532 }
9533 }
9534
9535 let reversed = self.selections.oldest::<usize>(cx).reversed;
9536
9537 for selection in new_selections.iter_mut() {
9538 selection.reversed = reversed;
9539 }
9540
9541 select_next_state.done = true;
9542 self.unfold_ranges(
9543 &new_selections
9544 .iter()
9545 .map(|selection| selection.range())
9546 .collect::<Vec<_>>(),
9547 false,
9548 false,
9549 cx,
9550 );
9551 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9552 selections.select(new_selections)
9553 });
9554
9555 Ok(())
9556 }
9557
9558 pub fn select_next(
9559 &mut self,
9560 action: &SelectNext,
9561 window: &mut Window,
9562 cx: &mut Context<Self>,
9563 ) -> Result<()> {
9564 self.push_to_selection_history();
9565 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9566 self.select_next_match_internal(
9567 &display_map,
9568 action.replace_newest,
9569 Some(Autoscroll::newest()),
9570 window,
9571 cx,
9572 )?;
9573 Ok(())
9574 }
9575
9576 pub fn select_previous(
9577 &mut self,
9578 action: &SelectPrevious,
9579 window: &mut Window,
9580 cx: &mut Context<Self>,
9581 ) -> Result<()> {
9582 self.push_to_selection_history();
9583 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9584 let buffer = &display_map.buffer_snapshot;
9585 let mut selections = self.selections.all::<usize>(cx);
9586 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9587 let query = &select_prev_state.query;
9588 if !select_prev_state.done {
9589 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9590 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9591 let mut next_selected_range = None;
9592 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9593 let bytes_before_last_selection =
9594 buffer.reversed_bytes_in_range(0..last_selection.start);
9595 let bytes_after_first_selection =
9596 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9597 let query_matches = query
9598 .stream_find_iter(bytes_before_last_selection)
9599 .map(|result| (last_selection.start, result))
9600 .chain(
9601 query
9602 .stream_find_iter(bytes_after_first_selection)
9603 .map(|result| (buffer.len(), result)),
9604 );
9605 for (end_offset, query_match) in query_matches {
9606 let query_match = query_match.unwrap(); // can only fail due to I/O
9607 let offset_range =
9608 end_offset - query_match.end()..end_offset - query_match.start();
9609 let display_range = offset_range.start.to_display_point(&display_map)
9610 ..offset_range.end.to_display_point(&display_map);
9611
9612 if !select_prev_state.wordwise
9613 || (!movement::is_inside_word(&display_map, display_range.start)
9614 && !movement::is_inside_word(&display_map, display_range.end))
9615 {
9616 next_selected_range = Some(offset_range);
9617 break;
9618 }
9619 }
9620
9621 if let Some(next_selected_range) = next_selected_range {
9622 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9623 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9624 if action.replace_newest {
9625 s.delete(s.newest_anchor().id);
9626 }
9627 s.insert_range(next_selected_range);
9628 });
9629 } else {
9630 select_prev_state.done = true;
9631 }
9632 }
9633
9634 self.select_prev_state = Some(select_prev_state);
9635 } else {
9636 let mut only_carets = true;
9637 let mut same_text_selected = true;
9638 let mut selected_text = None;
9639
9640 let mut selections_iter = selections.iter().peekable();
9641 while let Some(selection) = selections_iter.next() {
9642 if selection.start != selection.end {
9643 only_carets = false;
9644 }
9645
9646 if same_text_selected {
9647 if selected_text.is_none() {
9648 selected_text =
9649 Some(buffer.text_for_range(selection.range()).collect::<String>());
9650 }
9651
9652 if let Some(next_selection) = selections_iter.peek() {
9653 if next_selection.range().len() == selection.range().len() {
9654 let next_selected_text = buffer
9655 .text_for_range(next_selection.range())
9656 .collect::<String>();
9657 if Some(next_selected_text) != selected_text {
9658 same_text_selected = false;
9659 selected_text = None;
9660 }
9661 } else {
9662 same_text_selected = false;
9663 selected_text = None;
9664 }
9665 }
9666 }
9667 }
9668
9669 if only_carets {
9670 for selection in &mut selections {
9671 let word_range = movement::surrounding_word(
9672 &display_map,
9673 selection.start.to_display_point(&display_map),
9674 );
9675 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9676 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9677 selection.goal = SelectionGoal::None;
9678 selection.reversed = false;
9679 }
9680 if selections.len() == 1 {
9681 let selection = selections
9682 .last()
9683 .expect("ensured that there's only one selection");
9684 let query = buffer
9685 .text_for_range(selection.start..selection.end)
9686 .collect::<String>();
9687 let is_empty = query.is_empty();
9688 let select_state = SelectNextState {
9689 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9690 wordwise: true,
9691 done: is_empty,
9692 };
9693 self.select_prev_state = Some(select_state);
9694 } else {
9695 self.select_prev_state = None;
9696 }
9697
9698 self.unfold_ranges(
9699 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9700 false,
9701 true,
9702 cx,
9703 );
9704 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9705 s.select(selections);
9706 });
9707 } else if let Some(selected_text) = selected_text {
9708 self.select_prev_state = Some(SelectNextState {
9709 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9710 wordwise: false,
9711 done: false,
9712 });
9713 self.select_previous(action, window, cx)?;
9714 }
9715 }
9716 Ok(())
9717 }
9718
9719 pub fn toggle_comments(
9720 &mut self,
9721 action: &ToggleComments,
9722 window: &mut Window,
9723 cx: &mut Context<Self>,
9724 ) {
9725 if self.read_only(cx) {
9726 return;
9727 }
9728 let text_layout_details = &self.text_layout_details(window);
9729 self.transact(window, cx, |this, window, cx| {
9730 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9731 let mut edits = Vec::new();
9732 let mut selection_edit_ranges = Vec::new();
9733 let mut last_toggled_row = None;
9734 let snapshot = this.buffer.read(cx).read(cx);
9735 let empty_str: Arc<str> = Arc::default();
9736 let mut suffixes_inserted = Vec::new();
9737 let ignore_indent = action.ignore_indent;
9738
9739 fn comment_prefix_range(
9740 snapshot: &MultiBufferSnapshot,
9741 row: MultiBufferRow,
9742 comment_prefix: &str,
9743 comment_prefix_whitespace: &str,
9744 ignore_indent: bool,
9745 ) -> Range<Point> {
9746 let indent_size = if ignore_indent {
9747 0
9748 } else {
9749 snapshot.indent_size_for_line(row).len
9750 };
9751
9752 let start = Point::new(row.0, indent_size);
9753
9754 let mut line_bytes = snapshot
9755 .bytes_in_range(start..snapshot.max_point())
9756 .flatten()
9757 .copied();
9758
9759 // If this line currently begins with the line comment prefix, then record
9760 // the range containing the prefix.
9761 if line_bytes
9762 .by_ref()
9763 .take(comment_prefix.len())
9764 .eq(comment_prefix.bytes())
9765 {
9766 // Include any whitespace that matches the comment prefix.
9767 let matching_whitespace_len = line_bytes
9768 .zip(comment_prefix_whitespace.bytes())
9769 .take_while(|(a, b)| a == b)
9770 .count() as u32;
9771 let end = Point::new(
9772 start.row,
9773 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9774 );
9775 start..end
9776 } else {
9777 start..start
9778 }
9779 }
9780
9781 fn comment_suffix_range(
9782 snapshot: &MultiBufferSnapshot,
9783 row: MultiBufferRow,
9784 comment_suffix: &str,
9785 comment_suffix_has_leading_space: bool,
9786 ) -> Range<Point> {
9787 let end = Point::new(row.0, snapshot.line_len(row));
9788 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9789
9790 let mut line_end_bytes = snapshot
9791 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9792 .flatten()
9793 .copied();
9794
9795 let leading_space_len = if suffix_start_column > 0
9796 && line_end_bytes.next() == Some(b' ')
9797 && comment_suffix_has_leading_space
9798 {
9799 1
9800 } else {
9801 0
9802 };
9803
9804 // If this line currently begins with the line comment prefix, then record
9805 // the range containing the prefix.
9806 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9807 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9808 start..end
9809 } else {
9810 end..end
9811 }
9812 }
9813
9814 // TODO: Handle selections that cross excerpts
9815 for selection in &mut selections {
9816 let start_column = snapshot
9817 .indent_size_for_line(MultiBufferRow(selection.start.row))
9818 .len;
9819 let language = if let Some(language) =
9820 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9821 {
9822 language
9823 } else {
9824 continue;
9825 };
9826
9827 selection_edit_ranges.clear();
9828
9829 // If multiple selections contain a given row, avoid processing that
9830 // row more than once.
9831 let mut start_row = MultiBufferRow(selection.start.row);
9832 if last_toggled_row == Some(start_row) {
9833 start_row = start_row.next_row();
9834 }
9835 let end_row =
9836 if selection.end.row > selection.start.row && selection.end.column == 0 {
9837 MultiBufferRow(selection.end.row - 1)
9838 } else {
9839 MultiBufferRow(selection.end.row)
9840 };
9841 last_toggled_row = Some(end_row);
9842
9843 if start_row > end_row {
9844 continue;
9845 }
9846
9847 // If the language has line comments, toggle those.
9848 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9849
9850 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9851 if ignore_indent {
9852 full_comment_prefixes = full_comment_prefixes
9853 .into_iter()
9854 .map(|s| Arc::from(s.trim_end()))
9855 .collect();
9856 }
9857
9858 if !full_comment_prefixes.is_empty() {
9859 let first_prefix = full_comment_prefixes
9860 .first()
9861 .expect("prefixes is non-empty");
9862 let prefix_trimmed_lengths = full_comment_prefixes
9863 .iter()
9864 .map(|p| p.trim_end_matches(' ').len())
9865 .collect::<SmallVec<[usize; 4]>>();
9866
9867 let mut all_selection_lines_are_comments = true;
9868
9869 for row in start_row.0..=end_row.0 {
9870 let row = MultiBufferRow(row);
9871 if start_row < end_row && snapshot.is_line_blank(row) {
9872 continue;
9873 }
9874
9875 let prefix_range = full_comment_prefixes
9876 .iter()
9877 .zip(prefix_trimmed_lengths.iter().copied())
9878 .map(|(prefix, trimmed_prefix_len)| {
9879 comment_prefix_range(
9880 snapshot.deref(),
9881 row,
9882 &prefix[..trimmed_prefix_len],
9883 &prefix[trimmed_prefix_len..],
9884 ignore_indent,
9885 )
9886 })
9887 .max_by_key(|range| range.end.column - range.start.column)
9888 .expect("prefixes is non-empty");
9889
9890 if prefix_range.is_empty() {
9891 all_selection_lines_are_comments = false;
9892 }
9893
9894 selection_edit_ranges.push(prefix_range);
9895 }
9896
9897 if all_selection_lines_are_comments {
9898 edits.extend(
9899 selection_edit_ranges
9900 .iter()
9901 .cloned()
9902 .map(|range| (range, empty_str.clone())),
9903 );
9904 } else {
9905 let min_column = selection_edit_ranges
9906 .iter()
9907 .map(|range| range.start.column)
9908 .min()
9909 .unwrap_or(0);
9910 edits.extend(selection_edit_ranges.iter().map(|range| {
9911 let position = Point::new(range.start.row, min_column);
9912 (position..position, first_prefix.clone())
9913 }));
9914 }
9915 } else if let Some((full_comment_prefix, comment_suffix)) =
9916 language.block_comment_delimiters()
9917 {
9918 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9919 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9920 let prefix_range = comment_prefix_range(
9921 snapshot.deref(),
9922 start_row,
9923 comment_prefix,
9924 comment_prefix_whitespace,
9925 ignore_indent,
9926 );
9927 let suffix_range = comment_suffix_range(
9928 snapshot.deref(),
9929 end_row,
9930 comment_suffix.trim_start_matches(' '),
9931 comment_suffix.starts_with(' '),
9932 );
9933
9934 if prefix_range.is_empty() || suffix_range.is_empty() {
9935 edits.push((
9936 prefix_range.start..prefix_range.start,
9937 full_comment_prefix.clone(),
9938 ));
9939 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9940 suffixes_inserted.push((end_row, comment_suffix.len()));
9941 } else {
9942 edits.push((prefix_range, empty_str.clone()));
9943 edits.push((suffix_range, empty_str.clone()));
9944 }
9945 } else {
9946 continue;
9947 }
9948 }
9949
9950 drop(snapshot);
9951 this.buffer.update(cx, |buffer, cx| {
9952 buffer.edit(edits, None, cx);
9953 });
9954
9955 // Adjust selections so that they end before any comment suffixes that
9956 // were inserted.
9957 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9958 let mut selections = this.selections.all::<Point>(cx);
9959 let snapshot = this.buffer.read(cx).read(cx);
9960 for selection in &mut selections {
9961 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9962 match row.cmp(&MultiBufferRow(selection.end.row)) {
9963 Ordering::Less => {
9964 suffixes_inserted.next();
9965 continue;
9966 }
9967 Ordering::Greater => break,
9968 Ordering::Equal => {
9969 if selection.end.column == snapshot.line_len(row) {
9970 if selection.is_empty() {
9971 selection.start.column -= suffix_len as u32;
9972 }
9973 selection.end.column -= suffix_len as u32;
9974 }
9975 break;
9976 }
9977 }
9978 }
9979 }
9980
9981 drop(snapshot);
9982 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9983 s.select(selections)
9984 });
9985
9986 let selections = this.selections.all::<Point>(cx);
9987 let selections_on_single_row = selections.windows(2).all(|selections| {
9988 selections[0].start.row == selections[1].start.row
9989 && selections[0].end.row == selections[1].end.row
9990 && selections[0].start.row == selections[0].end.row
9991 });
9992 let selections_selecting = selections
9993 .iter()
9994 .any(|selection| selection.start != selection.end);
9995 let advance_downwards = action.advance_downwards
9996 && selections_on_single_row
9997 && !selections_selecting
9998 && !matches!(this.mode, EditorMode::SingleLine { .. });
9999
10000 if advance_downwards {
10001 let snapshot = this.buffer.read(cx).snapshot(cx);
10002
10003 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10004 s.move_cursors_with(|display_snapshot, display_point, _| {
10005 let mut point = display_point.to_point(display_snapshot);
10006 point.row += 1;
10007 point = snapshot.clip_point(point, Bias::Left);
10008 let display_point = point.to_display_point(display_snapshot);
10009 let goal = SelectionGoal::HorizontalPosition(
10010 display_snapshot
10011 .x_for_display_point(display_point, text_layout_details)
10012 .into(),
10013 );
10014 (display_point, goal)
10015 })
10016 });
10017 }
10018 });
10019 }
10020
10021 pub fn select_enclosing_symbol(
10022 &mut self,
10023 _: &SelectEnclosingSymbol,
10024 window: &mut Window,
10025 cx: &mut Context<Self>,
10026 ) {
10027 let buffer = self.buffer.read(cx).snapshot(cx);
10028 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10029
10030 fn update_selection(
10031 selection: &Selection<usize>,
10032 buffer_snap: &MultiBufferSnapshot,
10033 ) -> Option<Selection<usize>> {
10034 let cursor = selection.head();
10035 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10036 for symbol in symbols.iter().rev() {
10037 let start = symbol.range.start.to_offset(buffer_snap);
10038 let end = symbol.range.end.to_offset(buffer_snap);
10039 let new_range = start..end;
10040 if start < selection.start || end > selection.end {
10041 return Some(Selection {
10042 id: selection.id,
10043 start: new_range.start,
10044 end: new_range.end,
10045 goal: SelectionGoal::None,
10046 reversed: selection.reversed,
10047 });
10048 }
10049 }
10050 None
10051 }
10052
10053 let mut selected_larger_symbol = false;
10054 let new_selections = old_selections
10055 .iter()
10056 .map(|selection| match update_selection(selection, &buffer) {
10057 Some(new_selection) => {
10058 if new_selection.range() != selection.range() {
10059 selected_larger_symbol = true;
10060 }
10061 new_selection
10062 }
10063 None => selection.clone(),
10064 })
10065 .collect::<Vec<_>>();
10066
10067 if selected_larger_symbol {
10068 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10069 s.select(new_selections);
10070 });
10071 }
10072 }
10073
10074 pub fn select_larger_syntax_node(
10075 &mut self,
10076 _: &SelectLargerSyntaxNode,
10077 window: &mut Window,
10078 cx: &mut Context<Self>,
10079 ) {
10080 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10081 let buffer = self.buffer.read(cx).snapshot(cx);
10082 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10083
10084 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10085 let mut selected_larger_node = false;
10086 let new_selections = old_selections
10087 .iter()
10088 .map(|selection| {
10089 let old_range = selection.start..selection.end;
10090 let mut new_range = old_range.clone();
10091 let mut new_node = None;
10092 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10093 {
10094 new_node = Some(node);
10095 new_range = containing_range;
10096 if !display_map.intersects_fold(new_range.start)
10097 && !display_map.intersects_fold(new_range.end)
10098 {
10099 break;
10100 }
10101 }
10102
10103 if let Some(node) = new_node {
10104 // Log the ancestor, to support using this action as a way to explore TreeSitter
10105 // nodes. Parent and grandparent are also logged because this operation will not
10106 // visit nodes that have the same range as their parent.
10107 log::info!("Node: {node:?}");
10108 let parent = node.parent();
10109 log::info!("Parent: {parent:?}");
10110 let grandparent = parent.and_then(|x| x.parent());
10111 log::info!("Grandparent: {grandparent:?}");
10112 }
10113
10114 selected_larger_node |= new_range != old_range;
10115 Selection {
10116 id: selection.id,
10117 start: new_range.start,
10118 end: new_range.end,
10119 goal: SelectionGoal::None,
10120 reversed: selection.reversed,
10121 }
10122 })
10123 .collect::<Vec<_>>();
10124
10125 if selected_larger_node {
10126 stack.push(old_selections);
10127 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10128 s.select(new_selections);
10129 });
10130 }
10131 self.select_larger_syntax_node_stack = stack;
10132 }
10133
10134 pub fn select_smaller_syntax_node(
10135 &mut self,
10136 _: &SelectSmallerSyntaxNode,
10137 window: &mut Window,
10138 cx: &mut Context<Self>,
10139 ) {
10140 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10141 if let Some(selections) = stack.pop() {
10142 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10143 s.select(selections.to_vec());
10144 });
10145 }
10146 self.select_larger_syntax_node_stack = stack;
10147 }
10148
10149 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10150 if !EditorSettings::get_global(cx).gutter.runnables {
10151 self.clear_tasks();
10152 return Task::ready(());
10153 }
10154 let project = self.project.as_ref().map(Entity::downgrade);
10155 cx.spawn_in(window, |this, mut cx| async move {
10156 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10157 let Some(project) = project.and_then(|p| p.upgrade()) else {
10158 return;
10159 };
10160 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10161 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10162 }) else {
10163 return;
10164 };
10165
10166 let hide_runnables = project
10167 .update(&mut cx, |project, cx| {
10168 // Do not display any test indicators in non-dev server remote projects.
10169 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10170 })
10171 .unwrap_or(true);
10172 if hide_runnables {
10173 return;
10174 }
10175 let new_rows =
10176 cx.background_spawn({
10177 let snapshot = display_snapshot.clone();
10178 async move {
10179 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10180 }
10181 })
10182 .await;
10183
10184 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10185 this.update(&mut cx, |this, _| {
10186 this.clear_tasks();
10187 for (key, value) in rows {
10188 this.insert_tasks(key, value);
10189 }
10190 })
10191 .ok();
10192 })
10193 }
10194 fn fetch_runnable_ranges(
10195 snapshot: &DisplaySnapshot,
10196 range: Range<Anchor>,
10197 ) -> Vec<language::RunnableRange> {
10198 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10199 }
10200
10201 fn runnable_rows(
10202 project: Entity<Project>,
10203 snapshot: DisplaySnapshot,
10204 runnable_ranges: Vec<RunnableRange>,
10205 mut cx: AsyncWindowContext,
10206 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10207 runnable_ranges
10208 .into_iter()
10209 .filter_map(|mut runnable| {
10210 let tasks = cx
10211 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10212 .ok()?;
10213 if tasks.is_empty() {
10214 return None;
10215 }
10216
10217 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10218
10219 let row = snapshot
10220 .buffer_snapshot
10221 .buffer_line_for_row(MultiBufferRow(point.row))?
10222 .1
10223 .start
10224 .row;
10225
10226 let context_range =
10227 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10228 Some((
10229 (runnable.buffer_id, row),
10230 RunnableTasks {
10231 templates: tasks,
10232 offset: MultiBufferOffset(runnable.run_range.start),
10233 context_range,
10234 column: point.column,
10235 extra_variables: runnable.extra_captures,
10236 },
10237 ))
10238 })
10239 .collect()
10240 }
10241
10242 fn templates_with_tags(
10243 project: &Entity<Project>,
10244 runnable: &mut Runnable,
10245 cx: &mut App,
10246 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10247 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10248 let (worktree_id, file) = project
10249 .buffer_for_id(runnable.buffer, cx)
10250 .and_then(|buffer| buffer.read(cx).file())
10251 .map(|file| (file.worktree_id(cx), file.clone()))
10252 .unzip();
10253
10254 (
10255 project.task_store().read(cx).task_inventory().cloned(),
10256 worktree_id,
10257 file,
10258 )
10259 });
10260
10261 let tags = mem::take(&mut runnable.tags);
10262 let mut tags: Vec<_> = tags
10263 .into_iter()
10264 .flat_map(|tag| {
10265 let tag = tag.0.clone();
10266 inventory
10267 .as_ref()
10268 .into_iter()
10269 .flat_map(|inventory| {
10270 inventory.read(cx).list_tasks(
10271 file.clone(),
10272 Some(runnable.language.clone()),
10273 worktree_id,
10274 cx,
10275 )
10276 })
10277 .filter(move |(_, template)| {
10278 template.tags.iter().any(|source_tag| source_tag == &tag)
10279 })
10280 })
10281 .sorted_by_key(|(kind, _)| kind.to_owned())
10282 .collect();
10283 if let Some((leading_tag_source, _)) = tags.first() {
10284 // Strongest source wins; if we have worktree tag binding, prefer that to
10285 // global and language bindings;
10286 // if we have a global binding, prefer that to language binding.
10287 let first_mismatch = tags
10288 .iter()
10289 .position(|(tag_source, _)| tag_source != leading_tag_source);
10290 if let Some(index) = first_mismatch {
10291 tags.truncate(index);
10292 }
10293 }
10294
10295 tags
10296 }
10297
10298 pub fn move_to_enclosing_bracket(
10299 &mut self,
10300 _: &MoveToEnclosingBracket,
10301 window: &mut Window,
10302 cx: &mut Context<Self>,
10303 ) {
10304 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10305 s.move_offsets_with(|snapshot, selection| {
10306 let Some(enclosing_bracket_ranges) =
10307 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10308 else {
10309 return;
10310 };
10311
10312 let mut best_length = usize::MAX;
10313 let mut best_inside = false;
10314 let mut best_in_bracket_range = false;
10315 let mut best_destination = None;
10316 for (open, close) in enclosing_bracket_ranges {
10317 let close = close.to_inclusive();
10318 let length = close.end() - open.start;
10319 let inside = selection.start >= open.end && selection.end <= *close.start();
10320 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10321 || close.contains(&selection.head());
10322
10323 // If best is next to a bracket and current isn't, skip
10324 if !in_bracket_range && best_in_bracket_range {
10325 continue;
10326 }
10327
10328 // Prefer smaller lengths unless best is inside and current isn't
10329 if length > best_length && (best_inside || !inside) {
10330 continue;
10331 }
10332
10333 best_length = length;
10334 best_inside = inside;
10335 best_in_bracket_range = in_bracket_range;
10336 best_destination = Some(
10337 if close.contains(&selection.start) && close.contains(&selection.end) {
10338 if inside {
10339 open.end
10340 } else {
10341 open.start
10342 }
10343 } else if inside {
10344 *close.start()
10345 } else {
10346 *close.end()
10347 },
10348 );
10349 }
10350
10351 if let Some(destination) = best_destination {
10352 selection.collapse_to(destination, SelectionGoal::None);
10353 }
10354 })
10355 });
10356 }
10357
10358 pub fn undo_selection(
10359 &mut self,
10360 _: &UndoSelection,
10361 window: &mut Window,
10362 cx: &mut Context<Self>,
10363 ) {
10364 self.end_selection(window, cx);
10365 self.selection_history.mode = SelectionHistoryMode::Undoing;
10366 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10367 self.change_selections(None, window, cx, |s| {
10368 s.select_anchors(entry.selections.to_vec())
10369 });
10370 self.select_next_state = entry.select_next_state;
10371 self.select_prev_state = entry.select_prev_state;
10372 self.add_selections_state = entry.add_selections_state;
10373 self.request_autoscroll(Autoscroll::newest(), cx);
10374 }
10375 self.selection_history.mode = SelectionHistoryMode::Normal;
10376 }
10377
10378 pub fn redo_selection(
10379 &mut self,
10380 _: &RedoSelection,
10381 window: &mut Window,
10382 cx: &mut Context<Self>,
10383 ) {
10384 self.end_selection(window, cx);
10385 self.selection_history.mode = SelectionHistoryMode::Redoing;
10386 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10387 self.change_selections(None, window, cx, |s| {
10388 s.select_anchors(entry.selections.to_vec())
10389 });
10390 self.select_next_state = entry.select_next_state;
10391 self.select_prev_state = entry.select_prev_state;
10392 self.add_selections_state = entry.add_selections_state;
10393 self.request_autoscroll(Autoscroll::newest(), cx);
10394 }
10395 self.selection_history.mode = SelectionHistoryMode::Normal;
10396 }
10397
10398 pub fn expand_excerpts(
10399 &mut self,
10400 action: &ExpandExcerpts,
10401 _: &mut Window,
10402 cx: &mut Context<Self>,
10403 ) {
10404 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10405 }
10406
10407 pub fn expand_excerpts_down(
10408 &mut self,
10409 action: &ExpandExcerptsDown,
10410 _: &mut Window,
10411 cx: &mut Context<Self>,
10412 ) {
10413 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10414 }
10415
10416 pub fn expand_excerpts_up(
10417 &mut self,
10418 action: &ExpandExcerptsUp,
10419 _: &mut Window,
10420 cx: &mut Context<Self>,
10421 ) {
10422 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10423 }
10424
10425 pub fn expand_excerpts_for_direction(
10426 &mut self,
10427 lines: u32,
10428 direction: ExpandExcerptDirection,
10429
10430 cx: &mut Context<Self>,
10431 ) {
10432 let selections = self.selections.disjoint_anchors();
10433
10434 let lines = if lines == 0 {
10435 EditorSettings::get_global(cx).expand_excerpt_lines
10436 } else {
10437 lines
10438 };
10439
10440 self.buffer.update(cx, |buffer, cx| {
10441 let snapshot = buffer.snapshot(cx);
10442 let mut excerpt_ids = selections
10443 .iter()
10444 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10445 .collect::<Vec<_>>();
10446 excerpt_ids.sort();
10447 excerpt_ids.dedup();
10448 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10449 })
10450 }
10451
10452 pub fn expand_excerpt(
10453 &mut self,
10454 excerpt: ExcerptId,
10455 direction: ExpandExcerptDirection,
10456 cx: &mut Context<Self>,
10457 ) {
10458 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10459 self.buffer.update(cx, |buffer, cx| {
10460 buffer.expand_excerpts([excerpt], lines, direction, cx)
10461 })
10462 }
10463
10464 pub fn go_to_singleton_buffer_point(
10465 &mut self,
10466 point: Point,
10467 window: &mut Window,
10468 cx: &mut Context<Self>,
10469 ) {
10470 self.go_to_singleton_buffer_range(point..point, window, cx);
10471 }
10472
10473 pub fn go_to_singleton_buffer_range(
10474 &mut self,
10475 range: Range<Point>,
10476 window: &mut Window,
10477 cx: &mut Context<Self>,
10478 ) {
10479 let multibuffer = self.buffer().read(cx);
10480 let Some(buffer) = multibuffer.as_singleton() else {
10481 return;
10482 };
10483 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10484 return;
10485 };
10486 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10487 return;
10488 };
10489 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10490 s.select_anchor_ranges([start..end])
10491 });
10492 }
10493
10494 fn go_to_diagnostic(
10495 &mut self,
10496 _: &GoToDiagnostic,
10497 window: &mut Window,
10498 cx: &mut Context<Self>,
10499 ) {
10500 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10501 }
10502
10503 fn go_to_prev_diagnostic(
10504 &mut self,
10505 _: &GoToPrevDiagnostic,
10506 window: &mut Window,
10507 cx: &mut Context<Self>,
10508 ) {
10509 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10510 }
10511
10512 pub fn go_to_diagnostic_impl(
10513 &mut self,
10514 direction: Direction,
10515 window: &mut Window,
10516 cx: &mut Context<Self>,
10517 ) {
10518 let buffer = self.buffer.read(cx).snapshot(cx);
10519 let selection = self.selections.newest::<usize>(cx);
10520
10521 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10522 if direction == Direction::Next {
10523 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10524 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10525 return;
10526 };
10527 self.activate_diagnostics(
10528 buffer_id,
10529 popover.local_diagnostic.diagnostic.group_id,
10530 window,
10531 cx,
10532 );
10533 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10534 let primary_range_start = active_diagnostics.primary_range.start;
10535 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10536 let mut new_selection = s.newest_anchor().clone();
10537 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10538 s.select_anchors(vec![new_selection.clone()]);
10539 });
10540 self.refresh_inline_completion(false, true, window, cx);
10541 }
10542 return;
10543 }
10544 }
10545
10546 let active_group_id = self
10547 .active_diagnostics
10548 .as_ref()
10549 .map(|active_group| active_group.group_id);
10550 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10551 active_diagnostics
10552 .primary_range
10553 .to_offset(&buffer)
10554 .to_inclusive()
10555 });
10556 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10557 if active_primary_range.contains(&selection.head()) {
10558 *active_primary_range.start()
10559 } else {
10560 selection.head()
10561 }
10562 } else {
10563 selection.head()
10564 };
10565
10566 let snapshot = self.snapshot(window, cx);
10567 let primary_diagnostics_before = buffer
10568 .diagnostics_in_range::<usize>(0..search_start)
10569 .filter(|entry| entry.diagnostic.is_primary)
10570 .filter(|entry| entry.range.start != entry.range.end)
10571 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10572 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10573 .collect::<Vec<_>>();
10574 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10575 primary_diagnostics_before
10576 .iter()
10577 .position(|entry| entry.diagnostic.group_id == active_group_id)
10578 });
10579
10580 let primary_diagnostics_after = buffer
10581 .diagnostics_in_range::<usize>(search_start..buffer.len())
10582 .filter(|entry| entry.diagnostic.is_primary)
10583 .filter(|entry| entry.range.start != entry.range.end)
10584 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10585 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10586 .collect::<Vec<_>>();
10587 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10588 primary_diagnostics_after
10589 .iter()
10590 .enumerate()
10591 .rev()
10592 .find_map(|(i, entry)| {
10593 if entry.diagnostic.group_id == active_group_id {
10594 Some(i)
10595 } else {
10596 None
10597 }
10598 })
10599 });
10600
10601 let next_primary_diagnostic = match direction {
10602 Direction::Prev => primary_diagnostics_before
10603 .iter()
10604 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10605 .rev()
10606 .next(),
10607 Direction::Next => primary_diagnostics_after
10608 .iter()
10609 .skip(
10610 last_same_group_diagnostic_after
10611 .map(|index| index + 1)
10612 .unwrap_or(0),
10613 )
10614 .next(),
10615 };
10616
10617 // Cycle around to the start of the buffer, potentially moving back to the start of
10618 // the currently active diagnostic.
10619 let cycle_around = || match direction {
10620 Direction::Prev => primary_diagnostics_after
10621 .iter()
10622 .rev()
10623 .chain(primary_diagnostics_before.iter().rev())
10624 .next(),
10625 Direction::Next => primary_diagnostics_before
10626 .iter()
10627 .chain(primary_diagnostics_after.iter())
10628 .next(),
10629 };
10630
10631 if let Some((primary_range, group_id)) = next_primary_diagnostic
10632 .or_else(cycle_around)
10633 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10634 {
10635 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10636 return;
10637 };
10638 self.activate_diagnostics(buffer_id, group_id, window, cx);
10639 if self.active_diagnostics.is_some() {
10640 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10641 s.select(vec![Selection {
10642 id: selection.id,
10643 start: primary_range.start,
10644 end: primary_range.start,
10645 reversed: false,
10646 goal: SelectionGoal::None,
10647 }]);
10648 });
10649 self.refresh_inline_completion(false, true, window, cx);
10650 }
10651 }
10652 }
10653
10654 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10655 let snapshot = self.snapshot(window, cx);
10656 let selection = self.selections.newest::<Point>(cx);
10657 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10658 }
10659
10660 fn go_to_hunk_after_position(
10661 &mut self,
10662 snapshot: &EditorSnapshot,
10663 position: Point,
10664 window: &mut Window,
10665 cx: &mut Context<Editor>,
10666 ) -> Option<MultiBufferDiffHunk> {
10667 let mut hunk = snapshot
10668 .buffer_snapshot
10669 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10670 .find(|hunk| hunk.row_range.start.0 > position.row);
10671 if hunk.is_none() {
10672 hunk = snapshot
10673 .buffer_snapshot
10674 .diff_hunks_in_range(Point::zero()..position)
10675 .find(|hunk| hunk.row_range.end.0 < position.row)
10676 }
10677 if let Some(hunk) = &hunk {
10678 let destination = Point::new(hunk.row_range.start.0, 0);
10679 self.unfold_ranges(&[destination..destination], false, false, cx);
10680 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681 s.select_ranges(vec![destination..destination]);
10682 });
10683 }
10684
10685 hunk
10686 }
10687
10688 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10689 let snapshot = self.snapshot(window, cx);
10690 let selection = self.selections.newest::<Point>(cx);
10691 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10692 }
10693
10694 fn go_to_hunk_before_position(
10695 &mut self,
10696 snapshot: &EditorSnapshot,
10697 position: Point,
10698 window: &mut Window,
10699 cx: &mut Context<Editor>,
10700 ) -> Option<MultiBufferDiffHunk> {
10701 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10702 if hunk.is_none() {
10703 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10704 }
10705 if let Some(hunk) = &hunk {
10706 let destination = Point::new(hunk.row_range.start.0, 0);
10707 self.unfold_ranges(&[destination..destination], false, false, cx);
10708 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10709 s.select_ranges(vec![destination..destination]);
10710 });
10711 }
10712
10713 hunk
10714 }
10715
10716 pub fn go_to_definition(
10717 &mut self,
10718 _: &GoToDefinition,
10719 window: &mut Window,
10720 cx: &mut Context<Self>,
10721 ) -> Task<Result<Navigated>> {
10722 let definition =
10723 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10724 cx.spawn_in(window, |editor, mut cx| async move {
10725 if definition.await? == Navigated::Yes {
10726 return Ok(Navigated::Yes);
10727 }
10728 match editor.update_in(&mut cx, |editor, window, cx| {
10729 editor.find_all_references(&FindAllReferences, window, cx)
10730 })? {
10731 Some(references) => references.await,
10732 None => Ok(Navigated::No),
10733 }
10734 })
10735 }
10736
10737 pub fn go_to_declaration(
10738 &mut self,
10739 _: &GoToDeclaration,
10740 window: &mut Window,
10741 cx: &mut Context<Self>,
10742 ) -> Task<Result<Navigated>> {
10743 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10744 }
10745
10746 pub fn go_to_declaration_split(
10747 &mut self,
10748 _: &GoToDeclaration,
10749 window: &mut Window,
10750 cx: &mut Context<Self>,
10751 ) -> Task<Result<Navigated>> {
10752 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10753 }
10754
10755 pub fn go_to_implementation(
10756 &mut self,
10757 _: &GoToImplementation,
10758 window: &mut Window,
10759 cx: &mut Context<Self>,
10760 ) -> Task<Result<Navigated>> {
10761 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10762 }
10763
10764 pub fn go_to_implementation_split(
10765 &mut self,
10766 _: &GoToImplementationSplit,
10767 window: &mut Window,
10768 cx: &mut Context<Self>,
10769 ) -> Task<Result<Navigated>> {
10770 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10771 }
10772
10773 pub fn go_to_type_definition(
10774 &mut self,
10775 _: &GoToTypeDefinition,
10776 window: &mut Window,
10777 cx: &mut Context<Self>,
10778 ) -> Task<Result<Navigated>> {
10779 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10780 }
10781
10782 pub fn go_to_definition_split(
10783 &mut self,
10784 _: &GoToDefinitionSplit,
10785 window: &mut Window,
10786 cx: &mut Context<Self>,
10787 ) -> Task<Result<Navigated>> {
10788 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10789 }
10790
10791 pub fn go_to_type_definition_split(
10792 &mut self,
10793 _: &GoToTypeDefinitionSplit,
10794 window: &mut Window,
10795 cx: &mut Context<Self>,
10796 ) -> Task<Result<Navigated>> {
10797 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10798 }
10799
10800 fn go_to_definition_of_kind(
10801 &mut self,
10802 kind: GotoDefinitionKind,
10803 split: bool,
10804 window: &mut Window,
10805 cx: &mut Context<Self>,
10806 ) -> Task<Result<Navigated>> {
10807 let Some(provider) = self.semantics_provider.clone() else {
10808 return Task::ready(Ok(Navigated::No));
10809 };
10810 let head = self.selections.newest::<usize>(cx).head();
10811 let buffer = self.buffer.read(cx);
10812 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10813 text_anchor
10814 } else {
10815 return Task::ready(Ok(Navigated::No));
10816 };
10817
10818 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10819 return Task::ready(Ok(Navigated::No));
10820 };
10821
10822 cx.spawn_in(window, |editor, mut cx| async move {
10823 let definitions = definitions.await?;
10824 let navigated = editor
10825 .update_in(&mut cx, |editor, window, cx| {
10826 editor.navigate_to_hover_links(
10827 Some(kind),
10828 definitions
10829 .into_iter()
10830 .filter(|location| {
10831 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10832 })
10833 .map(HoverLink::Text)
10834 .collect::<Vec<_>>(),
10835 split,
10836 window,
10837 cx,
10838 )
10839 })?
10840 .await?;
10841 anyhow::Ok(navigated)
10842 })
10843 }
10844
10845 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10846 let selection = self.selections.newest_anchor();
10847 let head = selection.head();
10848 let tail = selection.tail();
10849
10850 let Some((buffer, start_position)) =
10851 self.buffer.read(cx).text_anchor_for_position(head, cx)
10852 else {
10853 return;
10854 };
10855
10856 let end_position = if head != tail {
10857 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10858 return;
10859 };
10860 Some(pos)
10861 } else {
10862 None
10863 };
10864
10865 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10866 let url = if let Some(end_pos) = end_position {
10867 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10868 } else {
10869 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10870 };
10871
10872 if let Some(url) = url {
10873 editor.update(&mut cx, |_, cx| {
10874 cx.open_url(&url);
10875 })
10876 } else {
10877 Ok(())
10878 }
10879 });
10880
10881 url_finder.detach();
10882 }
10883
10884 pub fn open_selected_filename(
10885 &mut self,
10886 _: &OpenSelectedFilename,
10887 window: &mut Window,
10888 cx: &mut Context<Self>,
10889 ) {
10890 let Some(workspace) = self.workspace() else {
10891 return;
10892 };
10893
10894 let position = self.selections.newest_anchor().head();
10895
10896 let Some((buffer, buffer_position)) =
10897 self.buffer.read(cx).text_anchor_for_position(position, cx)
10898 else {
10899 return;
10900 };
10901
10902 let project = self.project.clone();
10903
10904 cx.spawn_in(window, |_, mut cx| async move {
10905 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10906
10907 if let Some((_, path)) = result {
10908 workspace
10909 .update_in(&mut cx, |workspace, window, cx| {
10910 workspace.open_resolved_path(path, window, cx)
10911 })?
10912 .await?;
10913 }
10914 anyhow::Ok(())
10915 })
10916 .detach();
10917 }
10918
10919 pub(crate) fn navigate_to_hover_links(
10920 &mut self,
10921 kind: Option<GotoDefinitionKind>,
10922 mut definitions: Vec<HoverLink>,
10923 split: bool,
10924 window: &mut Window,
10925 cx: &mut Context<Editor>,
10926 ) -> Task<Result<Navigated>> {
10927 // If there is one definition, just open it directly
10928 if definitions.len() == 1 {
10929 let definition = definitions.pop().unwrap();
10930
10931 enum TargetTaskResult {
10932 Location(Option<Location>),
10933 AlreadyNavigated,
10934 }
10935
10936 let target_task = match definition {
10937 HoverLink::Text(link) => {
10938 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10939 }
10940 HoverLink::InlayHint(lsp_location, server_id) => {
10941 let computation =
10942 self.compute_target_location(lsp_location, server_id, window, cx);
10943 cx.background_spawn(async move {
10944 let location = computation.await?;
10945 Ok(TargetTaskResult::Location(location))
10946 })
10947 }
10948 HoverLink::Url(url) => {
10949 cx.open_url(&url);
10950 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10951 }
10952 HoverLink::File(path) => {
10953 if let Some(workspace) = self.workspace() {
10954 cx.spawn_in(window, |_, mut cx| async move {
10955 workspace
10956 .update_in(&mut cx, |workspace, window, cx| {
10957 workspace.open_resolved_path(path, window, cx)
10958 })?
10959 .await
10960 .map(|_| TargetTaskResult::AlreadyNavigated)
10961 })
10962 } else {
10963 Task::ready(Ok(TargetTaskResult::Location(None)))
10964 }
10965 }
10966 };
10967 cx.spawn_in(window, |editor, mut cx| async move {
10968 let target = match target_task.await.context("target resolution task")? {
10969 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10970 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10971 TargetTaskResult::Location(Some(target)) => target,
10972 };
10973
10974 editor.update_in(&mut cx, |editor, window, cx| {
10975 let Some(workspace) = editor.workspace() else {
10976 return Navigated::No;
10977 };
10978 let pane = workspace.read(cx).active_pane().clone();
10979
10980 let range = target.range.to_point(target.buffer.read(cx));
10981 let range = editor.range_for_match(&range);
10982 let range = collapse_multiline_range(range);
10983
10984 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10985 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10986 } else {
10987 window.defer(cx, move |window, cx| {
10988 let target_editor: Entity<Self> =
10989 workspace.update(cx, |workspace, cx| {
10990 let pane = if split {
10991 workspace.adjacent_pane(window, cx)
10992 } else {
10993 workspace.active_pane().clone()
10994 };
10995
10996 workspace.open_project_item(
10997 pane,
10998 target.buffer.clone(),
10999 true,
11000 true,
11001 window,
11002 cx,
11003 )
11004 });
11005 target_editor.update(cx, |target_editor, cx| {
11006 // When selecting a definition in a different buffer, disable the nav history
11007 // to avoid creating a history entry at the previous cursor location.
11008 pane.update(cx, |pane, _| pane.disable_history());
11009 target_editor.go_to_singleton_buffer_range(range, window, cx);
11010 pane.update(cx, |pane, _| pane.enable_history());
11011 });
11012 });
11013 }
11014 Navigated::Yes
11015 })
11016 })
11017 } else if !definitions.is_empty() {
11018 cx.spawn_in(window, |editor, mut cx| async move {
11019 let (title, location_tasks, workspace) = editor
11020 .update_in(&mut cx, |editor, window, cx| {
11021 let tab_kind = match kind {
11022 Some(GotoDefinitionKind::Implementation) => "Implementations",
11023 _ => "Definitions",
11024 };
11025 let title = definitions
11026 .iter()
11027 .find_map(|definition| match definition {
11028 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11029 let buffer = origin.buffer.read(cx);
11030 format!(
11031 "{} for {}",
11032 tab_kind,
11033 buffer
11034 .text_for_range(origin.range.clone())
11035 .collect::<String>()
11036 )
11037 }),
11038 HoverLink::InlayHint(_, _) => None,
11039 HoverLink::Url(_) => None,
11040 HoverLink::File(_) => None,
11041 })
11042 .unwrap_or(tab_kind.to_string());
11043 let location_tasks = definitions
11044 .into_iter()
11045 .map(|definition| match definition {
11046 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11047 HoverLink::InlayHint(lsp_location, server_id) => editor
11048 .compute_target_location(lsp_location, server_id, window, cx),
11049 HoverLink::Url(_) => Task::ready(Ok(None)),
11050 HoverLink::File(_) => Task::ready(Ok(None)),
11051 })
11052 .collect::<Vec<_>>();
11053 (title, location_tasks, editor.workspace().clone())
11054 })
11055 .context("location tasks preparation")?;
11056
11057 let locations = future::join_all(location_tasks)
11058 .await
11059 .into_iter()
11060 .filter_map(|location| location.transpose())
11061 .collect::<Result<_>>()
11062 .context("location tasks")?;
11063
11064 let Some(workspace) = workspace else {
11065 return Ok(Navigated::No);
11066 };
11067 let opened = workspace
11068 .update_in(&mut cx, |workspace, window, cx| {
11069 Self::open_locations_in_multibuffer(
11070 workspace,
11071 locations,
11072 title,
11073 split,
11074 MultibufferSelectionMode::First,
11075 window,
11076 cx,
11077 )
11078 })
11079 .ok();
11080
11081 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11082 })
11083 } else {
11084 Task::ready(Ok(Navigated::No))
11085 }
11086 }
11087
11088 fn compute_target_location(
11089 &self,
11090 lsp_location: lsp::Location,
11091 server_id: LanguageServerId,
11092 window: &mut Window,
11093 cx: &mut Context<Self>,
11094 ) -> Task<anyhow::Result<Option<Location>>> {
11095 let Some(project) = self.project.clone() else {
11096 return Task::ready(Ok(None));
11097 };
11098
11099 cx.spawn_in(window, move |editor, mut cx| async move {
11100 let location_task = editor.update(&mut cx, |_, cx| {
11101 project.update(cx, |project, cx| {
11102 let language_server_name = project
11103 .language_server_statuses(cx)
11104 .find(|(id, _)| server_id == *id)
11105 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11106 language_server_name.map(|language_server_name| {
11107 project.open_local_buffer_via_lsp(
11108 lsp_location.uri.clone(),
11109 server_id,
11110 language_server_name,
11111 cx,
11112 )
11113 })
11114 })
11115 })?;
11116 let location = match location_task {
11117 Some(task) => Some({
11118 let target_buffer_handle = task.await.context("open local buffer")?;
11119 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11120 let target_start = target_buffer
11121 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11122 let target_end = target_buffer
11123 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11124 target_buffer.anchor_after(target_start)
11125 ..target_buffer.anchor_before(target_end)
11126 })?;
11127 Location {
11128 buffer: target_buffer_handle,
11129 range,
11130 }
11131 }),
11132 None => None,
11133 };
11134 Ok(location)
11135 })
11136 }
11137
11138 pub fn find_all_references(
11139 &mut self,
11140 _: &FindAllReferences,
11141 window: &mut Window,
11142 cx: &mut Context<Self>,
11143 ) -> Option<Task<Result<Navigated>>> {
11144 let selection = self.selections.newest::<usize>(cx);
11145 let multi_buffer = self.buffer.read(cx);
11146 let head = selection.head();
11147
11148 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11149 let head_anchor = multi_buffer_snapshot.anchor_at(
11150 head,
11151 if head < selection.tail() {
11152 Bias::Right
11153 } else {
11154 Bias::Left
11155 },
11156 );
11157
11158 match self
11159 .find_all_references_task_sources
11160 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11161 {
11162 Ok(_) => {
11163 log::info!(
11164 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11165 );
11166 return None;
11167 }
11168 Err(i) => {
11169 self.find_all_references_task_sources.insert(i, head_anchor);
11170 }
11171 }
11172
11173 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11174 let workspace = self.workspace()?;
11175 let project = workspace.read(cx).project().clone();
11176 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11177 Some(cx.spawn_in(window, |editor, mut cx| async move {
11178 let _cleanup = defer({
11179 let mut cx = cx.clone();
11180 move || {
11181 let _ = editor.update(&mut cx, |editor, _| {
11182 if let Ok(i) =
11183 editor
11184 .find_all_references_task_sources
11185 .binary_search_by(|anchor| {
11186 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11187 })
11188 {
11189 editor.find_all_references_task_sources.remove(i);
11190 }
11191 });
11192 }
11193 });
11194
11195 let locations = references.await?;
11196 if locations.is_empty() {
11197 return anyhow::Ok(Navigated::No);
11198 }
11199
11200 workspace.update_in(&mut cx, |workspace, window, cx| {
11201 let title = locations
11202 .first()
11203 .as_ref()
11204 .map(|location| {
11205 let buffer = location.buffer.read(cx);
11206 format!(
11207 "References to `{}`",
11208 buffer
11209 .text_for_range(location.range.clone())
11210 .collect::<String>()
11211 )
11212 })
11213 .unwrap();
11214 Self::open_locations_in_multibuffer(
11215 workspace,
11216 locations,
11217 title,
11218 false,
11219 MultibufferSelectionMode::First,
11220 window,
11221 cx,
11222 );
11223 Navigated::Yes
11224 })
11225 }))
11226 }
11227
11228 /// Opens a multibuffer with the given project locations in it
11229 pub fn open_locations_in_multibuffer(
11230 workspace: &mut Workspace,
11231 mut locations: Vec<Location>,
11232 title: String,
11233 split: bool,
11234 multibuffer_selection_mode: MultibufferSelectionMode,
11235 window: &mut Window,
11236 cx: &mut Context<Workspace>,
11237 ) {
11238 // If there are multiple definitions, open them in a multibuffer
11239 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11240 let mut locations = locations.into_iter().peekable();
11241 let mut ranges = Vec::new();
11242 let capability = workspace.project().read(cx).capability();
11243
11244 let excerpt_buffer = cx.new(|cx| {
11245 let mut multibuffer = MultiBuffer::new(capability);
11246 while let Some(location) = locations.next() {
11247 let buffer = location.buffer.read(cx);
11248 let mut ranges_for_buffer = Vec::new();
11249 let range = location.range.to_offset(buffer);
11250 ranges_for_buffer.push(range.clone());
11251
11252 while let Some(next_location) = locations.peek() {
11253 if next_location.buffer == location.buffer {
11254 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11255 locations.next();
11256 } else {
11257 break;
11258 }
11259 }
11260
11261 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11262 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11263 location.buffer.clone(),
11264 ranges_for_buffer,
11265 DEFAULT_MULTIBUFFER_CONTEXT,
11266 cx,
11267 ))
11268 }
11269
11270 multibuffer.with_title(title)
11271 });
11272
11273 let editor = cx.new(|cx| {
11274 Editor::for_multibuffer(
11275 excerpt_buffer,
11276 Some(workspace.project().clone()),
11277 true,
11278 window,
11279 cx,
11280 )
11281 });
11282 editor.update(cx, |editor, cx| {
11283 match multibuffer_selection_mode {
11284 MultibufferSelectionMode::First => {
11285 if let Some(first_range) = ranges.first() {
11286 editor.change_selections(None, window, cx, |selections| {
11287 selections.clear_disjoint();
11288 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11289 });
11290 }
11291 editor.highlight_background::<Self>(
11292 &ranges,
11293 |theme| theme.editor_highlighted_line_background,
11294 cx,
11295 );
11296 }
11297 MultibufferSelectionMode::All => {
11298 editor.change_selections(None, window, cx, |selections| {
11299 selections.clear_disjoint();
11300 selections.select_anchor_ranges(ranges);
11301 });
11302 }
11303 }
11304 editor.register_buffers_with_language_servers(cx);
11305 });
11306
11307 let item = Box::new(editor);
11308 let item_id = item.item_id();
11309
11310 if split {
11311 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11312 } else {
11313 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11314 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11315 pane.close_current_preview_item(window, cx)
11316 } else {
11317 None
11318 }
11319 });
11320 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11321 }
11322 workspace.active_pane().update(cx, |pane, cx| {
11323 pane.set_preview_item_id(Some(item_id), cx);
11324 });
11325 }
11326
11327 pub fn rename(
11328 &mut self,
11329 _: &Rename,
11330 window: &mut Window,
11331 cx: &mut Context<Self>,
11332 ) -> Option<Task<Result<()>>> {
11333 use language::ToOffset as _;
11334
11335 let provider = self.semantics_provider.clone()?;
11336 let selection = self.selections.newest_anchor().clone();
11337 let (cursor_buffer, cursor_buffer_position) = self
11338 .buffer
11339 .read(cx)
11340 .text_anchor_for_position(selection.head(), cx)?;
11341 let (tail_buffer, cursor_buffer_position_end) = self
11342 .buffer
11343 .read(cx)
11344 .text_anchor_for_position(selection.tail(), cx)?;
11345 if tail_buffer != cursor_buffer {
11346 return None;
11347 }
11348
11349 let snapshot = cursor_buffer.read(cx).snapshot();
11350 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11351 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11352 let prepare_rename = provider
11353 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11354 .unwrap_or_else(|| Task::ready(Ok(None)));
11355 drop(snapshot);
11356
11357 Some(cx.spawn_in(window, |this, mut cx| async move {
11358 let rename_range = if let Some(range) = prepare_rename.await? {
11359 Some(range)
11360 } else {
11361 this.update(&mut cx, |this, cx| {
11362 let buffer = this.buffer.read(cx).snapshot(cx);
11363 let mut buffer_highlights = this
11364 .document_highlights_for_position(selection.head(), &buffer)
11365 .filter(|highlight| {
11366 highlight.start.excerpt_id == selection.head().excerpt_id
11367 && highlight.end.excerpt_id == selection.head().excerpt_id
11368 });
11369 buffer_highlights
11370 .next()
11371 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11372 })?
11373 };
11374 if let Some(rename_range) = rename_range {
11375 this.update_in(&mut cx, |this, window, cx| {
11376 let snapshot = cursor_buffer.read(cx).snapshot();
11377 let rename_buffer_range = rename_range.to_offset(&snapshot);
11378 let cursor_offset_in_rename_range =
11379 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11380 let cursor_offset_in_rename_range_end =
11381 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11382
11383 this.take_rename(false, window, cx);
11384 let buffer = this.buffer.read(cx).read(cx);
11385 let cursor_offset = selection.head().to_offset(&buffer);
11386 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11387 let rename_end = rename_start + rename_buffer_range.len();
11388 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11389 let mut old_highlight_id = None;
11390 let old_name: Arc<str> = buffer
11391 .chunks(rename_start..rename_end, true)
11392 .map(|chunk| {
11393 if old_highlight_id.is_none() {
11394 old_highlight_id = chunk.syntax_highlight_id;
11395 }
11396 chunk.text
11397 })
11398 .collect::<String>()
11399 .into();
11400
11401 drop(buffer);
11402
11403 // Position the selection in the rename editor so that it matches the current selection.
11404 this.show_local_selections = false;
11405 let rename_editor = cx.new(|cx| {
11406 let mut editor = Editor::single_line(window, cx);
11407 editor.buffer.update(cx, |buffer, cx| {
11408 buffer.edit([(0..0, old_name.clone())], None, cx)
11409 });
11410 let rename_selection_range = match cursor_offset_in_rename_range
11411 .cmp(&cursor_offset_in_rename_range_end)
11412 {
11413 Ordering::Equal => {
11414 editor.select_all(&SelectAll, window, cx);
11415 return editor;
11416 }
11417 Ordering::Less => {
11418 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11419 }
11420 Ordering::Greater => {
11421 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11422 }
11423 };
11424 if rename_selection_range.end > old_name.len() {
11425 editor.select_all(&SelectAll, window, cx);
11426 } else {
11427 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11428 s.select_ranges([rename_selection_range]);
11429 });
11430 }
11431 editor
11432 });
11433 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11434 if e == &EditorEvent::Focused {
11435 cx.emit(EditorEvent::FocusedIn)
11436 }
11437 })
11438 .detach();
11439
11440 let write_highlights =
11441 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11442 let read_highlights =
11443 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11444 let ranges = write_highlights
11445 .iter()
11446 .flat_map(|(_, ranges)| ranges.iter())
11447 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11448 .cloned()
11449 .collect();
11450
11451 this.highlight_text::<Rename>(
11452 ranges,
11453 HighlightStyle {
11454 fade_out: Some(0.6),
11455 ..Default::default()
11456 },
11457 cx,
11458 );
11459 let rename_focus_handle = rename_editor.focus_handle(cx);
11460 window.focus(&rename_focus_handle);
11461 let block_id = this.insert_blocks(
11462 [BlockProperties {
11463 style: BlockStyle::Flex,
11464 placement: BlockPlacement::Below(range.start),
11465 height: 1,
11466 render: Arc::new({
11467 let rename_editor = rename_editor.clone();
11468 move |cx: &mut BlockContext| {
11469 let mut text_style = cx.editor_style.text.clone();
11470 if let Some(highlight_style) = old_highlight_id
11471 .and_then(|h| h.style(&cx.editor_style.syntax))
11472 {
11473 text_style = text_style.highlight(highlight_style);
11474 }
11475 div()
11476 .block_mouse_down()
11477 .pl(cx.anchor_x)
11478 .child(EditorElement::new(
11479 &rename_editor,
11480 EditorStyle {
11481 background: cx.theme().system().transparent,
11482 local_player: cx.editor_style.local_player,
11483 text: text_style,
11484 scrollbar_width: cx.editor_style.scrollbar_width,
11485 syntax: cx.editor_style.syntax.clone(),
11486 status: cx.editor_style.status.clone(),
11487 inlay_hints_style: HighlightStyle {
11488 font_weight: Some(FontWeight::BOLD),
11489 ..make_inlay_hints_style(cx.app)
11490 },
11491 inline_completion_styles: make_suggestion_styles(
11492 cx.app,
11493 ),
11494 ..EditorStyle::default()
11495 },
11496 ))
11497 .into_any_element()
11498 }
11499 }),
11500 priority: 0,
11501 }],
11502 Some(Autoscroll::fit()),
11503 cx,
11504 )[0];
11505 this.pending_rename = Some(RenameState {
11506 range,
11507 old_name,
11508 editor: rename_editor,
11509 block_id,
11510 });
11511 })?;
11512 }
11513
11514 Ok(())
11515 }))
11516 }
11517
11518 pub fn confirm_rename(
11519 &mut self,
11520 _: &ConfirmRename,
11521 window: &mut Window,
11522 cx: &mut Context<Self>,
11523 ) -> Option<Task<Result<()>>> {
11524 let rename = self.take_rename(false, window, cx)?;
11525 let workspace = self.workspace()?.downgrade();
11526 let (buffer, start) = self
11527 .buffer
11528 .read(cx)
11529 .text_anchor_for_position(rename.range.start, cx)?;
11530 let (end_buffer, _) = self
11531 .buffer
11532 .read(cx)
11533 .text_anchor_for_position(rename.range.end, cx)?;
11534 if buffer != end_buffer {
11535 return None;
11536 }
11537
11538 let old_name = rename.old_name;
11539 let new_name = rename.editor.read(cx).text(cx);
11540
11541 let rename = self.semantics_provider.as_ref()?.perform_rename(
11542 &buffer,
11543 start,
11544 new_name.clone(),
11545 cx,
11546 )?;
11547
11548 Some(cx.spawn_in(window, |editor, mut cx| async move {
11549 let project_transaction = rename.await?;
11550 Self::open_project_transaction(
11551 &editor,
11552 workspace,
11553 project_transaction,
11554 format!("Rename: {} → {}", old_name, new_name),
11555 cx.clone(),
11556 )
11557 .await?;
11558
11559 editor.update(&mut cx, |editor, cx| {
11560 editor.refresh_document_highlights(cx);
11561 })?;
11562 Ok(())
11563 }))
11564 }
11565
11566 fn take_rename(
11567 &mut self,
11568 moving_cursor: bool,
11569 window: &mut Window,
11570 cx: &mut Context<Self>,
11571 ) -> Option<RenameState> {
11572 let rename = self.pending_rename.take()?;
11573 if rename.editor.focus_handle(cx).is_focused(window) {
11574 window.focus(&self.focus_handle);
11575 }
11576
11577 self.remove_blocks(
11578 [rename.block_id].into_iter().collect(),
11579 Some(Autoscroll::fit()),
11580 cx,
11581 );
11582 self.clear_highlights::<Rename>(cx);
11583 self.show_local_selections = true;
11584
11585 if moving_cursor {
11586 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11587 editor.selections.newest::<usize>(cx).head()
11588 });
11589
11590 // Update the selection to match the position of the selection inside
11591 // the rename editor.
11592 let snapshot = self.buffer.read(cx).read(cx);
11593 let rename_range = rename.range.to_offset(&snapshot);
11594 let cursor_in_editor = snapshot
11595 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11596 .min(rename_range.end);
11597 drop(snapshot);
11598
11599 self.change_selections(None, window, cx, |s| {
11600 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11601 });
11602 } else {
11603 self.refresh_document_highlights(cx);
11604 }
11605
11606 Some(rename)
11607 }
11608
11609 pub fn pending_rename(&self) -> Option<&RenameState> {
11610 self.pending_rename.as_ref()
11611 }
11612
11613 fn format(
11614 &mut self,
11615 _: &Format,
11616 window: &mut Window,
11617 cx: &mut Context<Self>,
11618 ) -> Option<Task<Result<()>>> {
11619 let project = match &self.project {
11620 Some(project) => project.clone(),
11621 None => return None,
11622 };
11623
11624 Some(self.perform_format(
11625 project,
11626 FormatTrigger::Manual,
11627 FormatTarget::Buffers,
11628 window,
11629 cx,
11630 ))
11631 }
11632
11633 fn format_selections(
11634 &mut self,
11635 _: &FormatSelections,
11636 window: &mut Window,
11637 cx: &mut Context<Self>,
11638 ) -> Option<Task<Result<()>>> {
11639 let project = match &self.project {
11640 Some(project) => project.clone(),
11641 None => return None,
11642 };
11643
11644 let ranges = self
11645 .selections
11646 .all_adjusted(cx)
11647 .into_iter()
11648 .map(|selection| selection.range())
11649 .collect_vec();
11650
11651 Some(self.perform_format(
11652 project,
11653 FormatTrigger::Manual,
11654 FormatTarget::Ranges(ranges),
11655 window,
11656 cx,
11657 ))
11658 }
11659
11660 fn perform_format(
11661 &mut self,
11662 project: Entity<Project>,
11663 trigger: FormatTrigger,
11664 target: FormatTarget,
11665 window: &mut Window,
11666 cx: &mut Context<Self>,
11667 ) -> Task<Result<()>> {
11668 let buffer = self.buffer.clone();
11669 let (buffers, target) = match target {
11670 FormatTarget::Buffers => {
11671 let mut buffers = buffer.read(cx).all_buffers();
11672 if trigger == FormatTrigger::Save {
11673 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11674 }
11675 (buffers, LspFormatTarget::Buffers)
11676 }
11677 FormatTarget::Ranges(selection_ranges) => {
11678 let multi_buffer = buffer.read(cx);
11679 let snapshot = multi_buffer.read(cx);
11680 let mut buffers = HashSet::default();
11681 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11682 BTreeMap::new();
11683 for selection_range in selection_ranges {
11684 for (buffer, buffer_range, _) in
11685 snapshot.range_to_buffer_ranges(selection_range)
11686 {
11687 let buffer_id = buffer.remote_id();
11688 let start = buffer.anchor_before(buffer_range.start);
11689 let end = buffer.anchor_after(buffer_range.end);
11690 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11691 buffer_id_to_ranges
11692 .entry(buffer_id)
11693 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11694 .or_insert_with(|| vec![start..end]);
11695 }
11696 }
11697 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11698 }
11699 };
11700
11701 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11702 let format = project.update(cx, |project, cx| {
11703 project.format(buffers, target, true, trigger, cx)
11704 });
11705
11706 cx.spawn_in(window, |_, mut cx| async move {
11707 let transaction = futures::select_biased! {
11708 () = timeout => {
11709 log::warn!("timed out waiting for formatting");
11710 None
11711 }
11712 transaction = format.log_err().fuse() => transaction,
11713 };
11714
11715 buffer
11716 .update(&mut cx, |buffer, cx| {
11717 if let Some(transaction) = transaction {
11718 if !buffer.is_singleton() {
11719 buffer.push_transaction(&transaction.0, cx);
11720 }
11721 }
11722
11723 cx.notify();
11724 })
11725 .ok();
11726
11727 Ok(())
11728 })
11729 }
11730
11731 fn restart_language_server(
11732 &mut self,
11733 _: &RestartLanguageServer,
11734 _: &mut Window,
11735 cx: &mut Context<Self>,
11736 ) {
11737 if let Some(project) = self.project.clone() {
11738 self.buffer.update(cx, |multi_buffer, cx| {
11739 project.update(cx, |project, cx| {
11740 project.restart_language_servers_for_buffers(
11741 multi_buffer.all_buffers().into_iter().collect(),
11742 cx,
11743 );
11744 });
11745 })
11746 }
11747 }
11748
11749 fn cancel_language_server_work(
11750 workspace: &mut Workspace,
11751 _: &actions::CancelLanguageServerWork,
11752 _: &mut Window,
11753 cx: &mut Context<Workspace>,
11754 ) {
11755 let project = workspace.project();
11756 let buffers = workspace
11757 .active_item(cx)
11758 .and_then(|item| item.act_as::<Editor>(cx))
11759 .map_or(HashSet::default(), |editor| {
11760 editor.read(cx).buffer.read(cx).all_buffers()
11761 });
11762 project.update(cx, |project, cx| {
11763 project.cancel_language_server_work_for_buffers(buffers, cx);
11764 });
11765 }
11766
11767 fn show_character_palette(
11768 &mut self,
11769 _: &ShowCharacterPalette,
11770 window: &mut Window,
11771 _: &mut Context<Self>,
11772 ) {
11773 window.show_character_palette();
11774 }
11775
11776 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11777 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11778 let buffer = self.buffer.read(cx).snapshot(cx);
11779 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11780 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11781 let is_valid = buffer
11782 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11783 .any(|entry| {
11784 entry.diagnostic.is_primary
11785 && !entry.range.is_empty()
11786 && entry.range.start == primary_range_start
11787 && entry.diagnostic.message == active_diagnostics.primary_message
11788 });
11789
11790 if is_valid != active_diagnostics.is_valid {
11791 active_diagnostics.is_valid = is_valid;
11792 let mut new_styles = HashMap::default();
11793 for (block_id, diagnostic) in &active_diagnostics.blocks {
11794 new_styles.insert(
11795 *block_id,
11796 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11797 );
11798 }
11799 self.display_map.update(cx, |display_map, _cx| {
11800 display_map.replace_blocks(new_styles)
11801 });
11802 }
11803 }
11804 }
11805
11806 fn activate_diagnostics(
11807 &mut self,
11808 buffer_id: BufferId,
11809 group_id: usize,
11810 window: &mut Window,
11811 cx: &mut Context<Self>,
11812 ) {
11813 self.dismiss_diagnostics(cx);
11814 let snapshot = self.snapshot(window, cx);
11815 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11816 let buffer = self.buffer.read(cx).snapshot(cx);
11817
11818 let mut primary_range = None;
11819 let mut primary_message = None;
11820 let diagnostic_group = buffer
11821 .diagnostic_group(buffer_id, group_id)
11822 .filter_map(|entry| {
11823 let start = entry.range.start;
11824 let end = entry.range.end;
11825 if snapshot.is_line_folded(MultiBufferRow(start.row))
11826 && (start.row == end.row
11827 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11828 {
11829 return None;
11830 }
11831 if entry.diagnostic.is_primary {
11832 primary_range = Some(entry.range.clone());
11833 primary_message = Some(entry.diagnostic.message.clone());
11834 }
11835 Some(entry)
11836 })
11837 .collect::<Vec<_>>();
11838 let primary_range = primary_range?;
11839 let primary_message = primary_message?;
11840
11841 let blocks = display_map
11842 .insert_blocks(
11843 diagnostic_group.iter().map(|entry| {
11844 let diagnostic = entry.diagnostic.clone();
11845 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11846 BlockProperties {
11847 style: BlockStyle::Fixed,
11848 placement: BlockPlacement::Below(
11849 buffer.anchor_after(entry.range.start),
11850 ),
11851 height: message_height,
11852 render: diagnostic_block_renderer(diagnostic, None, true, true),
11853 priority: 0,
11854 }
11855 }),
11856 cx,
11857 )
11858 .into_iter()
11859 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11860 .collect();
11861
11862 Some(ActiveDiagnosticGroup {
11863 primary_range: buffer.anchor_before(primary_range.start)
11864 ..buffer.anchor_after(primary_range.end),
11865 primary_message,
11866 group_id,
11867 blocks,
11868 is_valid: true,
11869 })
11870 });
11871 }
11872
11873 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11874 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11875 self.display_map.update(cx, |display_map, cx| {
11876 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11877 });
11878 cx.notify();
11879 }
11880 }
11881
11882 pub fn set_selections_from_remote(
11883 &mut self,
11884 selections: Vec<Selection<Anchor>>,
11885 pending_selection: Option<Selection<Anchor>>,
11886 window: &mut Window,
11887 cx: &mut Context<Self>,
11888 ) {
11889 let old_cursor_position = self.selections.newest_anchor().head();
11890 self.selections.change_with(cx, |s| {
11891 s.select_anchors(selections);
11892 if let Some(pending_selection) = pending_selection {
11893 s.set_pending(pending_selection, SelectMode::Character);
11894 } else {
11895 s.clear_pending();
11896 }
11897 });
11898 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11899 }
11900
11901 fn push_to_selection_history(&mut self) {
11902 self.selection_history.push(SelectionHistoryEntry {
11903 selections: self.selections.disjoint_anchors(),
11904 select_next_state: self.select_next_state.clone(),
11905 select_prev_state: self.select_prev_state.clone(),
11906 add_selections_state: self.add_selections_state.clone(),
11907 });
11908 }
11909
11910 pub fn transact(
11911 &mut self,
11912 window: &mut Window,
11913 cx: &mut Context<Self>,
11914 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11915 ) -> Option<TransactionId> {
11916 self.start_transaction_at(Instant::now(), window, cx);
11917 update(self, window, cx);
11918 self.end_transaction_at(Instant::now(), cx)
11919 }
11920
11921 pub fn start_transaction_at(
11922 &mut self,
11923 now: Instant,
11924 window: &mut Window,
11925 cx: &mut Context<Self>,
11926 ) {
11927 self.end_selection(window, cx);
11928 if let Some(tx_id) = self
11929 .buffer
11930 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11931 {
11932 self.selection_history
11933 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11934 cx.emit(EditorEvent::TransactionBegun {
11935 transaction_id: tx_id,
11936 })
11937 }
11938 }
11939
11940 pub fn end_transaction_at(
11941 &mut self,
11942 now: Instant,
11943 cx: &mut Context<Self>,
11944 ) -> Option<TransactionId> {
11945 if let Some(transaction_id) = self
11946 .buffer
11947 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11948 {
11949 if let Some((_, end_selections)) =
11950 self.selection_history.transaction_mut(transaction_id)
11951 {
11952 *end_selections = Some(self.selections.disjoint_anchors());
11953 } else {
11954 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11955 }
11956
11957 cx.emit(EditorEvent::Edited { transaction_id });
11958 Some(transaction_id)
11959 } else {
11960 None
11961 }
11962 }
11963
11964 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11965 if self.selection_mark_mode {
11966 self.change_selections(None, window, cx, |s| {
11967 s.move_with(|_, sel| {
11968 sel.collapse_to(sel.head(), SelectionGoal::None);
11969 });
11970 })
11971 }
11972 self.selection_mark_mode = true;
11973 cx.notify();
11974 }
11975
11976 pub fn swap_selection_ends(
11977 &mut self,
11978 _: &actions::SwapSelectionEnds,
11979 window: &mut Window,
11980 cx: &mut Context<Self>,
11981 ) {
11982 self.change_selections(None, window, cx, |s| {
11983 s.move_with(|_, sel| {
11984 if sel.start != sel.end {
11985 sel.reversed = !sel.reversed
11986 }
11987 });
11988 });
11989 self.request_autoscroll(Autoscroll::newest(), cx);
11990 cx.notify();
11991 }
11992
11993 pub fn toggle_fold(
11994 &mut self,
11995 _: &actions::ToggleFold,
11996 window: &mut Window,
11997 cx: &mut Context<Self>,
11998 ) {
11999 if self.is_singleton(cx) {
12000 let selection = self.selections.newest::<Point>(cx);
12001
12002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12003 let range = if selection.is_empty() {
12004 let point = selection.head().to_display_point(&display_map);
12005 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12006 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12007 .to_point(&display_map);
12008 start..end
12009 } else {
12010 selection.range()
12011 };
12012 if display_map.folds_in_range(range).next().is_some() {
12013 self.unfold_lines(&Default::default(), window, cx)
12014 } else {
12015 self.fold(&Default::default(), window, cx)
12016 }
12017 } else {
12018 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12019 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12020 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12021 .map(|(snapshot, _, _)| snapshot.remote_id())
12022 .collect();
12023
12024 for buffer_id in buffer_ids {
12025 if self.is_buffer_folded(buffer_id, cx) {
12026 self.unfold_buffer(buffer_id, cx);
12027 } else {
12028 self.fold_buffer(buffer_id, cx);
12029 }
12030 }
12031 }
12032 }
12033
12034 pub fn toggle_fold_recursive(
12035 &mut self,
12036 _: &actions::ToggleFoldRecursive,
12037 window: &mut Window,
12038 cx: &mut Context<Self>,
12039 ) {
12040 let selection = self.selections.newest::<Point>(cx);
12041
12042 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12043 let range = if selection.is_empty() {
12044 let point = selection.head().to_display_point(&display_map);
12045 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12046 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12047 .to_point(&display_map);
12048 start..end
12049 } else {
12050 selection.range()
12051 };
12052 if display_map.folds_in_range(range).next().is_some() {
12053 self.unfold_recursive(&Default::default(), window, cx)
12054 } else {
12055 self.fold_recursive(&Default::default(), window, cx)
12056 }
12057 }
12058
12059 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12060 if self.is_singleton(cx) {
12061 let mut to_fold = Vec::new();
12062 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12063 let selections = self.selections.all_adjusted(cx);
12064
12065 for selection in selections {
12066 let range = selection.range().sorted();
12067 let buffer_start_row = range.start.row;
12068
12069 if range.start.row != range.end.row {
12070 let mut found = false;
12071 let mut row = range.start.row;
12072 while row <= range.end.row {
12073 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12074 {
12075 found = true;
12076 row = crease.range().end.row + 1;
12077 to_fold.push(crease);
12078 } else {
12079 row += 1
12080 }
12081 }
12082 if found {
12083 continue;
12084 }
12085 }
12086
12087 for row in (0..=range.start.row).rev() {
12088 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12089 if crease.range().end.row >= buffer_start_row {
12090 to_fold.push(crease);
12091 if row <= range.start.row {
12092 break;
12093 }
12094 }
12095 }
12096 }
12097 }
12098
12099 self.fold_creases(to_fold, true, window, cx);
12100 } else {
12101 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12102
12103 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12104 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12105 .map(|(snapshot, _, _)| snapshot.remote_id())
12106 .collect();
12107 for buffer_id in buffer_ids {
12108 self.fold_buffer(buffer_id, cx);
12109 }
12110 }
12111 }
12112
12113 fn fold_at_level(
12114 &mut self,
12115 fold_at: &FoldAtLevel,
12116 window: &mut Window,
12117 cx: &mut Context<Self>,
12118 ) {
12119 if !self.buffer.read(cx).is_singleton() {
12120 return;
12121 }
12122
12123 let fold_at_level = fold_at.0;
12124 let snapshot = self.buffer.read(cx).snapshot(cx);
12125 let mut to_fold = Vec::new();
12126 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12127
12128 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12129 while start_row < end_row {
12130 match self
12131 .snapshot(window, cx)
12132 .crease_for_buffer_row(MultiBufferRow(start_row))
12133 {
12134 Some(crease) => {
12135 let nested_start_row = crease.range().start.row + 1;
12136 let nested_end_row = crease.range().end.row;
12137
12138 if current_level < fold_at_level {
12139 stack.push((nested_start_row, nested_end_row, current_level + 1));
12140 } else if current_level == fold_at_level {
12141 to_fold.push(crease);
12142 }
12143
12144 start_row = nested_end_row + 1;
12145 }
12146 None => start_row += 1,
12147 }
12148 }
12149 }
12150
12151 self.fold_creases(to_fold, true, window, cx);
12152 }
12153
12154 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12155 if self.buffer.read(cx).is_singleton() {
12156 let mut fold_ranges = Vec::new();
12157 let snapshot = self.buffer.read(cx).snapshot(cx);
12158
12159 for row in 0..snapshot.max_row().0 {
12160 if let Some(foldable_range) = self
12161 .snapshot(window, cx)
12162 .crease_for_buffer_row(MultiBufferRow(row))
12163 {
12164 fold_ranges.push(foldable_range);
12165 }
12166 }
12167
12168 self.fold_creases(fold_ranges, true, window, cx);
12169 } else {
12170 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12171 editor
12172 .update_in(&mut cx, |editor, _, cx| {
12173 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12174 editor.fold_buffer(buffer_id, cx);
12175 }
12176 })
12177 .ok();
12178 });
12179 }
12180 }
12181
12182 pub fn fold_function_bodies(
12183 &mut self,
12184 _: &actions::FoldFunctionBodies,
12185 window: &mut Window,
12186 cx: &mut Context<Self>,
12187 ) {
12188 let snapshot = self.buffer.read(cx).snapshot(cx);
12189
12190 let ranges = snapshot
12191 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12192 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12193 .collect::<Vec<_>>();
12194
12195 let creases = ranges
12196 .into_iter()
12197 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12198 .collect();
12199
12200 self.fold_creases(creases, true, window, cx);
12201 }
12202
12203 pub fn fold_recursive(
12204 &mut self,
12205 _: &actions::FoldRecursive,
12206 window: &mut Window,
12207 cx: &mut Context<Self>,
12208 ) {
12209 let mut to_fold = Vec::new();
12210 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12211 let selections = self.selections.all_adjusted(cx);
12212
12213 for selection in selections {
12214 let range = selection.range().sorted();
12215 let buffer_start_row = range.start.row;
12216
12217 if range.start.row != range.end.row {
12218 let mut found = false;
12219 for row in range.start.row..=range.end.row {
12220 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12221 found = true;
12222 to_fold.push(crease);
12223 }
12224 }
12225 if found {
12226 continue;
12227 }
12228 }
12229
12230 for row in (0..=range.start.row).rev() {
12231 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12232 if crease.range().end.row >= buffer_start_row {
12233 to_fold.push(crease);
12234 } else {
12235 break;
12236 }
12237 }
12238 }
12239 }
12240
12241 self.fold_creases(to_fold, true, window, cx);
12242 }
12243
12244 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12245 let buffer_row = fold_at.buffer_row;
12246 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12247
12248 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12249 let autoscroll = self
12250 .selections
12251 .all::<Point>(cx)
12252 .iter()
12253 .any(|selection| crease.range().overlaps(&selection.range()));
12254
12255 self.fold_creases(vec![crease], autoscroll, window, cx);
12256 }
12257 }
12258
12259 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12260 if self.is_singleton(cx) {
12261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12262 let buffer = &display_map.buffer_snapshot;
12263 let selections = self.selections.all::<Point>(cx);
12264 let ranges = selections
12265 .iter()
12266 .map(|s| {
12267 let range = s.display_range(&display_map).sorted();
12268 let mut start = range.start.to_point(&display_map);
12269 let mut end = range.end.to_point(&display_map);
12270 start.column = 0;
12271 end.column = buffer.line_len(MultiBufferRow(end.row));
12272 start..end
12273 })
12274 .collect::<Vec<_>>();
12275
12276 self.unfold_ranges(&ranges, true, true, cx);
12277 } else {
12278 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12279 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12280 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12281 .map(|(snapshot, _, _)| snapshot.remote_id())
12282 .collect();
12283 for buffer_id in buffer_ids {
12284 self.unfold_buffer(buffer_id, cx);
12285 }
12286 }
12287 }
12288
12289 pub fn unfold_recursive(
12290 &mut self,
12291 _: &UnfoldRecursive,
12292 _window: &mut Window,
12293 cx: &mut Context<Self>,
12294 ) {
12295 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12296 let selections = self.selections.all::<Point>(cx);
12297 let ranges = selections
12298 .iter()
12299 .map(|s| {
12300 let mut range = s.display_range(&display_map).sorted();
12301 *range.start.column_mut() = 0;
12302 *range.end.column_mut() = display_map.line_len(range.end.row());
12303 let start = range.start.to_point(&display_map);
12304 let end = range.end.to_point(&display_map);
12305 start..end
12306 })
12307 .collect::<Vec<_>>();
12308
12309 self.unfold_ranges(&ranges, true, true, cx);
12310 }
12311
12312 pub fn unfold_at(
12313 &mut self,
12314 unfold_at: &UnfoldAt,
12315 _window: &mut Window,
12316 cx: &mut Context<Self>,
12317 ) {
12318 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12319
12320 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12321 ..Point::new(
12322 unfold_at.buffer_row.0,
12323 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12324 );
12325
12326 let autoscroll = self
12327 .selections
12328 .all::<Point>(cx)
12329 .iter()
12330 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12331
12332 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12333 }
12334
12335 pub fn unfold_all(
12336 &mut self,
12337 _: &actions::UnfoldAll,
12338 _window: &mut Window,
12339 cx: &mut Context<Self>,
12340 ) {
12341 if self.buffer.read(cx).is_singleton() {
12342 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12343 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12344 } else {
12345 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12346 editor
12347 .update(&mut cx, |editor, cx| {
12348 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12349 editor.unfold_buffer(buffer_id, cx);
12350 }
12351 })
12352 .ok();
12353 });
12354 }
12355 }
12356
12357 pub fn fold_selected_ranges(
12358 &mut self,
12359 _: &FoldSelectedRanges,
12360 window: &mut Window,
12361 cx: &mut Context<Self>,
12362 ) {
12363 let selections = self.selections.all::<Point>(cx);
12364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12365 let line_mode = self.selections.line_mode;
12366 let ranges = selections
12367 .into_iter()
12368 .map(|s| {
12369 if line_mode {
12370 let start = Point::new(s.start.row, 0);
12371 let end = Point::new(
12372 s.end.row,
12373 display_map
12374 .buffer_snapshot
12375 .line_len(MultiBufferRow(s.end.row)),
12376 );
12377 Crease::simple(start..end, display_map.fold_placeholder.clone())
12378 } else {
12379 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12380 }
12381 })
12382 .collect::<Vec<_>>();
12383 self.fold_creases(ranges, true, window, cx);
12384 }
12385
12386 pub fn fold_ranges<T: ToOffset + Clone>(
12387 &mut self,
12388 ranges: Vec<Range<T>>,
12389 auto_scroll: bool,
12390 window: &mut Window,
12391 cx: &mut Context<Self>,
12392 ) {
12393 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12394 let ranges = ranges
12395 .into_iter()
12396 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12397 .collect::<Vec<_>>();
12398 self.fold_creases(ranges, auto_scroll, window, cx);
12399 }
12400
12401 pub fn fold_creases<T: ToOffset + Clone>(
12402 &mut self,
12403 creases: Vec<Crease<T>>,
12404 auto_scroll: bool,
12405 window: &mut Window,
12406 cx: &mut Context<Self>,
12407 ) {
12408 if creases.is_empty() {
12409 return;
12410 }
12411
12412 let mut buffers_affected = HashSet::default();
12413 let multi_buffer = self.buffer().read(cx);
12414 for crease in &creases {
12415 if let Some((_, buffer, _)) =
12416 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12417 {
12418 buffers_affected.insert(buffer.read(cx).remote_id());
12419 };
12420 }
12421
12422 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12423
12424 if auto_scroll {
12425 self.request_autoscroll(Autoscroll::fit(), cx);
12426 }
12427
12428 cx.notify();
12429
12430 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12431 // Clear diagnostics block when folding a range that contains it.
12432 let snapshot = self.snapshot(window, cx);
12433 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12434 drop(snapshot);
12435 self.active_diagnostics = Some(active_diagnostics);
12436 self.dismiss_diagnostics(cx);
12437 } else {
12438 self.active_diagnostics = Some(active_diagnostics);
12439 }
12440 }
12441
12442 self.scrollbar_marker_state.dirty = true;
12443 }
12444
12445 /// Removes any folds whose ranges intersect any of the given ranges.
12446 pub fn unfold_ranges<T: ToOffset + Clone>(
12447 &mut self,
12448 ranges: &[Range<T>],
12449 inclusive: bool,
12450 auto_scroll: bool,
12451 cx: &mut Context<Self>,
12452 ) {
12453 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12454 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12455 });
12456 }
12457
12458 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12459 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12460 return;
12461 }
12462 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12463 self.display_map
12464 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12465 cx.emit(EditorEvent::BufferFoldToggled {
12466 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12467 folded: true,
12468 });
12469 cx.notify();
12470 }
12471
12472 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12473 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12474 return;
12475 }
12476 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12477 self.display_map.update(cx, |display_map, cx| {
12478 display_map.unfold_buffer(buffer_id, cx);
12479 });
12480 cx.emit(EditorEvent::BufferFoldToggled {
12481 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12482 folded: false,
12483 });
12484 cx.notify();
12485 }
12486
12487 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12488 self.display_map.read(cx).is_buffer_folded(buffer)
12489 }
12490
12491 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12492 self.display_map.read(cx).folded_buffers()
12493 }
12494
12495 /// Removes any folds with the given ranges.
12496 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12497 &mut self,
12498 ranges: &[Range<T>],
12499 type_id: TypeId,
12500 auto_scroll: bool,
12501 cx: &mut Context<Self>,
12502 ) {
12503 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12504 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12505 });
12506 }
12507
12508 fn remove_folds_with<T: ToOffset + Clone>(
12509 &mut self,
12510 ranges: &[Range<T>],
12511 auto_scroll: bool,
12512 cx: &mut Context<Self>,
12513 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12514 ) {
12515 if ranges.is_empty() {
12516 return;
12517 }
12518
12519 let mut buffers_affected = HashSet::default();
12520 let multi_buffer = self.buffer().read(cx);
12521 for range in ranges {
12522 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12523 buffers_affected.insert(buffer.read(cx).remote_id());
12524 };
12525 }
12526
12527 self.display_map.update(cx, update);
12528
12529 if auto_scroll {
12530 self.request_autoscroll(Autoscroll::fit(), cx);
12531 }
12532
12533 cx.notify();
12534 self.scrollbar_marker_state.dirty = true;
12535 self.active_indent_guides_state.dirty = true;
12536 }
12537
12538 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12539 self.display_map.read(cx).fold_placeholder.clone()
12540 }
12541
12542 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12543 self.buffer.update(cx, |buffer, cx| {
12544 buffer.set_all_diff_hunks_expanded(cx);
12545 });
12546 }
12547
12548 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12549 self.distinguish_unstaged_diff_hunks = true;
12550 }
12551
12552 pub fn expand_all_diff_hunks(
12553 &mut self,
12554 _: &ExpandAllHunkDiffs,
12555 _window: &mut Window,
12556 cx: &mut Context<Self>,
12557 ) {
12558 self.buffer.update(cx, |buffer, cx| {
12559 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12560 });
12561 }
12562
12563 pub fn toggle_selected_diff_hunks(
12564 &mut self,
12565 _: &ToggleSelectedDiffHunks,
12566 _window: &mut Window,
12567 cx: &mut Context<Self>,
12568 ) {
12569 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12570 self.toggle_diff_hunks_in_ranges(ranges, cx);
12571 }
12572
12573 fn diff_hunks_in_ranges<'a>(
12574 &'a self,
12575 ranges: &'a [Range<Anchor>],
12576 buffer: &'a MultiBufferSnapshot,
12577 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12578 ranges.iter().flat_map(move |range| {
12579 let end_excerpt_id = range.end.excerpt_id;
12580 let range = range.to_point(buffer);
12581 let mut peek_end = range.end;
12582 if range.end.row < buffer.max_row().0 {
12583 peek_end = Point::new(range.end.row + 1, 0);
12584 }
12585 buffer
12586 .diff_hunks_in_range(range.start..peek_end)
12587 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12588 })
12589 }
12590
12591 pub fn has_stageable_diff_hunks_in_ranges(
12592 &self,
12593 ranges: &[Range<Anchor>],
12594 snapshot: &MultiBufferSnapshot,
12595 ) -> bool {
12596 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12597 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12598 }
12599
12600 pub fn toggle_staged_selected_diff_hunks(
12601 &mut self,
12602 _: &ToggleStagedSelectedDiffHunks,
12603 _window: &mut Window,
12604 cx: &mut Context<Self>,
12605 ) {
12606 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12607 self.stage_or_unstage_diff_hunks(&ranges, cx);
12608 }
12609
12610 pub fn stage_or_unstage_diff_hunks(
12611 &mut self,
12612 ranges: &[Range<Anchor>],
12613 cx: &mut Context<Self>,
12614 ) {
12615 let Some(project) = &self.project else {
12616 return;
12617 };
12618 let snapshot = self.buffer.read(cx).snapshot(cx);
12619 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12620
12621 let chunk_by = self
12622 .diff_hunks_in_ranges(&ranges, &snapshot)
12623 .chunk_by(|hunk| hunk.buffer_id);
12624 for (buffer_id, hunks) in &chunk_by {
12625 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12626 log::debug!("no buffer for id");
12627 continue;
12628 };
12629 let buffer = buffer.read(cx).snapshot();
12630 let Some((repo, path)) = project
12631 .read(cx)
12632 .repository_and_path_for_buffer_id(buffer_id, cx)
12633 else {
12634 log::debug!("no git repo for buffer id");
12635 continue;
12636 };
12637 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12638 log::debug!("no diff for buffer id");
12639 continue;
12640 };
12641 let Some(secondary_diff) = diff.secondary_diff() else {
12642 log::debug!("no secondary diff for buffer id");
12643 continue;
12644 };
12645
12646 let edits = diff.secondary_edits_for_stage_or_unstage(
12647 stage,
12648 hunks.map(|hunk| {
12649 (
12650 hunk.diff_base_byte_range.clone(),
12651 hunk.secondary_diff_base_byte_range.clone(),
12652 hunk.buffer_range.clone(),
12653 )
12654 }),
12655 &buffer,
12656 );
12657
12658 let index_base = secondary_diff.base_text().map_or_else(
12659 || Rope::from(""),
12660 |snapshot| snapshot.text.as_rope().clone(),
12661 );
12662 let index_buffer = cx.new(|cx| {
12663 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12664 });
12665 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12666 index_buffer.edit(edits, None, cx);
12667 index_buffer.snapshot().as_rope().to_string()
12668 });
12669 let new_index_text = if new_index_text.is_empty()
12670 && (diff.is_single_insertion
12671 || buffer
12672 .file()
12673 .map_or(false, |file| file.disk_state() == DiskState::New))
12674 {
12675 log::debug!("removing from index");
12676 None
12677 } else {
12678 Some(new_index_text)
12679 };
12680
12681 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12682 }
12683 }
12684
12685 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12686 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12687 self.buffer
12688 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12689 }
12690
12691 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12692 self.buffer.update(cx, |buffer, cx| {
12693 let ranges = vec![Anchor::min()..Anchor::max()];
12694 if !buffer.all_diff_hunks_expanded()
12695 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12696 {
12697 buffer.collapse_diff_hunks(ranges, cx);
12698 true
12699 } else {
12700 false
12701 }
12702 })
12703 }
12704
12705 fn toggle_diff_hunks_in_ranges(
12706 &mut self,
12707 ranges: Vec<Range<Anchor>>,
12708 cx: &mut Context<'_, Editor>,
12709 ) {
12710 self.buffer.update(cx, |buffer, cx| {
12711 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12712 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12713 })
12714 }
12715
12716 fn toggle_diff_hunks_in_ranges_narrow(
12717 &mut self,
12718 ranges: Vec<Range<Anchor>>,
12719 cx: &mut Context<'_, Editor>,
12720 ) {
12721 self.buffer.update(cx, |buffer, cx| {
12722 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12723 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12724 })
12725 }
12726
12727 pub(crate) fn apply_all_diff_hunks(
12728 &mut self,
12729 _: &ApplyAllDiffHunks,
12730 window: &mut Window,
12731 cx: &mut Context<Self>,
12732 ) {
12733 let buffers = self.buffer.read(cx).all_buffers();
12734 for branch_buffer in buffers {
12735 branch_buffer.update(cx, |branch_buffer, cx| {
12736 branch_buffer.merge_into_base(Vec::new(), cx);
12737 });
12738 }
12739
12740 if let Some(project) = self.project.clone() {
12741 self.save(true, project, window, cx).detach_and_log_err(cx);
12742 }
12743 }
12744
12745 pub(crate) fn apply_selected_diff_hunks(
12746 &mut self,
12747 _: &ApplyDiffHunk,
12748 window: &mut Window,
12749 cx: &mut Context<Self>,
12750 ) {
12751 let snapshot = self.snapshot(window, cx);
12752 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12753 let mut ranges_by_buffer = HashMap::default();
12754 self.transact(window, cx, |editor, _window, cx| {
12755 for hunk in hunks {
12756 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12757 ranges_by_buffer
12758 .entry(buffer.clone())
12759 .or_insert_with(Vec::new)
12760 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12761 }
12762 }
12763
12764 for (buffer, ranges) in ranges_by_buffer {
12765 buffer.update(cx, |buffer, cx| {
12766 buffer.merge_into_base(ranges, cx);
12767 });
12768 }
12769 });
12770
12771 if let Some(project) = self.project.clone() {
12772 self.save(true, project, window, cx).detach_and_log_err(cx);
12773 }
12774 }
12775
12776 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12777 if hovered != self.gutter_hovered {
12778 self.gutter_hovered = hovered;
12779 cx.notify();
12780 }
12781 }
12782
12783 pub fn insert_blocks(
12784 &mut self,
12785 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12786 autoscroll: Option<Autoscroll>,
12787 cx: &mut Context<Self>,
12788 ) -> Vec<CustomBlockId> {
12789 let blocks = self
12790 .display_map
12791 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12792 if let Some(autoscroll) = autoscroll {
12793 self.request_autoscroll(autoscroll, cx);
12794 }
12795 cx.notify();
12796 blocks
12797 }
12798
12799 pub fn resize_blocks(
12800 &mut self,
12801 heights: HashMap<CustomBlockId, u32>,
12802 autoscroll: Option<Autoscroll>,
12803 cx: &mut Context<Self>,
12804 ) {
12805 self.display_map
12806 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12807 if let Some(autoscroll) = autoscroll {
12808 self.request_autoscroll(autoscroll, cx);
12809 }
12810 cx.notify();
12811 }
12812
12813 pub fn replace_blocks(
12814 &mut self,
12815 renderers: HashMap<CustomBlockId, RenderBlock>,
12816 autoscroll: Option<Autoscroll>,
12817 cx: &mut Context<Self>,
12818 ) {
12819 self.display_map
12820 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12821 if let Some(autoscroll) = autoscroll {
12822 self.request_autoscroll(autoscroll, cx);
12823 }
12824 cx.notify();
12825 }
12826
12827 pub fn remove_blocks(
12828 &mut self,
12829 block_ids: HashSet<CustomBlockId>,
12830 autoscroll: Option<Autoscroll>,
12831 cx: &mut Context<Self>,
12832 ) {
12833 self.display_map.update(cx, |display_map, cx| {
12834 display_map.remove_blocks(block_ids, cx)
12835 });
12836 if let Some(autoscroll) = autoscroll {
12837 self.request_autoscroll(autoscroll, cx);
12838 }
12839 cx.notify();
12840 }
12841
12842 pub fn row_for_block(
12843 &self,
12844 block_id: CustomBlockId,
12845 cx: &mut Context<Self>,
12846 ) -> Option<DisplayRow> {
12847 self.display_map
12848 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12849 }
12850
12851 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12852 self.focused_block = Some(focused_block);
12853 }
12854
12855 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12856 self.focused_block.take()
12857 }
12858
12859 pub fn insert_creases(
12860 &mut self,
12861 creases: impl IntoIterator<Item = Crease<Anchor>>,
12862 cx: &mut Context<Self>,
12863 ) -> Vec<CreaseId> {
12864 self.display_map
12865 .update(cx, |map, cx| map.insert_creases(creases, cx))
12866 }
12867
12868 pub fn remove_creases(
12869 &mut self,
12870 ids: impl IntoIterator<Item = CreaseId>,
12871 cx: &mut Context<Self>,
12872 ) {
12873 self.display_map
12874 .update(cx, |map, cx| map.remove_creases(ids, cx));
12875 }
12876
12877 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12878 self.display_map
12879 .update(cx, |map, cx| map.snapshot(cx))
12880 .longest_row()
12881 }
12882
12883 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12884 self.display_map
12885 .update(cx, |map, cx| map.snapshot(cx))
12886 .max_point()
12887 }
12888
12889 pub fn text(&self, cx: &App) -> String {
12890 self.buffer.read(cx).read(cx).text()
12891 }
12892
12893 pub fn is_empty(&self, cx: &App) -> bool {
12894 self.buffer.read(cx).read(cx).is_empty()
12895 }
12896
12897 pub fn text_option(&self, cx: &App) -> Option<String> {
12898 let text = self.text(cx);
12899 let text = text.trim();
12900
12901 if text.is_empty() {
12902 return None;
12903 }
12904
12905 Some(text.to_string())
12906 }
12907
12908 pub fn set_text(
12909 &mut self,
12910 text: impl Into<Arc<str>>,
12911 window: &mut Window,
12912 cx: &mut Context<Self>,
12913 ) {
12914 self.transact(window, cx, |this, _, cx| {
12915 this.buffer
12916 .read(cx)
12917 .as_singleton()
12918 .expect("you can only call set_text on editors for singleton buffers")
12919 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12920 });
12921 }
12922
12923 pub fn display_text(&self, cx: &mut App) -> String {
12924 self.display_map
12925 .update(cx, |map, cx| map.snapshot(cx))
12926 .text()
12927 }
12928
12929 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12930 let mut wrap_guides = smallvec::smallvec![];
12931
12932 if self.show_wrap_guides == Some(false) {
12933 return wrap_guides;
12934 }
12935
12936 let settings = self.buffer.read(cx).settings_at(0, cx);
12937 if settings.show_wrap_guides {
12938 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12939 wrap_guides.push((soft_wrap as usize, true));
12940 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12941 wrap_guides.push((soft_wrap as usize, true));
12942 }
12943 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12944 }
12945
12946 wrap_guides
12947 }
12948
12949 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12950 let settings = self.buffer.read(cx).settings_at(0, cx);
12951 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12952 match mode {
12953 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12954 SoftWrap::None
12955 }
12956 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12957 language_settings::SoftWrap::PreferredLineLength => {
12958 SoftWrap::Column(settings.preferred_line_length)
12959 }
12960 language_settings::SoftWrap::Bounded => {
12961 SoftWrap::Bounded(settings.preferred_line_length)
12962 }
12963 }
12964 }
12965
12966 pub fn set_soft_wrap_mode(
12967 &mut self,
12968 mode: language_settings::SoftWrap,
12969
12970 cx: &mut Context<Self>,
12971 ) {
12972 self.soft_wrap_mode_override = Some(mode);
12973 cx.notify();
12974 }
12975
12976 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12977 self.text_style_refinement = Some(style);
12978 }
12979
12980 /// called by the Element so we know what style we were most recently rendered with.
12981 pub(crate) fn set_style(
12982 &mut self,
12983 style: EditorStyle,
12984 window: &mut Window,
12985 cx: &mut Context<Self>,
12986 ) {
12987 let rem_size = window.rem_size();
12988 self.display_map.update(cx, |map, cx| {
12989 map.set_font(
12990 style.text.font(),
12991 style.text.font_size.to_pixels(rem_size),
12992 cx,
12993 )
12994 });
12995 self.style = Some(style);
12996 }
12997
12998 pub fn style(&self) -> Option<&EditorStyle> {
12999 self.style.as_ref()
13000 }
13001
13002 // Called by the element. This method is not designed to be called outside of the editor
13003 // element's layout code because it does not notify when rewrapping is computed synchronously.
13004 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13005 self.display_map
13006 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13007 }
13008
13009 pub fn set_soft_wrap(&mut self) {
13010 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13011 }
13012
13013 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13014 if self.soft_wrap_mode_override.is_some() {
13015 self.soft_wrap_mode_override.take();
13016 } else {
13017 let soft_wrap = match self.soft_wrap_mode(cx) {
13018 SoftWrap::GitDiff => return,
13019 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13020 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13021 language_settings::SoftWrap::None
13022 }
13023 };
13024 self.soft_wrap_mode_override = Some(soft_wrap);
13025 }
13026 cx.notify();
13027 }
13028
13029 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13030 let Some(workspace) = self.workspace() else {
13031 return;
13032 };
13033 let fs = workspace.read(cx).app_state().fs.clone();
13034 let current_show = TabBarSettings::get_global(cx).show;
13035 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13036 setting.show = Some(!current_show);
13037 });
13038 }
13039
13040 pub fn toggle_indent_guides(
13041 &mut self,
13042 _: &ToggleIndentGuides,
13043 _: &mut Window,
13044 cx: &mut Context<Self>,
13045 ) {
13046 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13047 self.buffer
13048 .read(cx)
13049 .settings_at(0, cx)
13050 .indent_guides
13051 .enabled
13052 });
13053 self.show_indent_guides = Some(!currently_enabled);
13054 cx.notify();
13055 }
13056
13057 fn should_show_indent_guides(&self) -> Option<bool> {
13058 self.show_indent_guides
13059 }
13060
13061 pub fn toggle_line_numbers(
13062 &mut self,
13063 _: &ToggleLineNumbers,
13064 _: &mut Window,
13065 cx: &mut Context<Self>,
13066 ) {
13067 let mut editor_settings = EditorSettings::get_global(cx).clone();
13068 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13069 EditorSettings::override_global(editor_settings, cx);
13070 }
13071
13072 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13073 self.use_relative_line_numbers
13074 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13075 }
13076
13077 pub fn toggle_relative_line_numbers(
13078 &mut self,
13079 _: &ToggleRelativeLineNumbers,
13080 _: &mut Window,
13081 cx: &mut Context<Self>,
13082 ) {
13083 let is_relative = self.should_use_relative_line_numbers(cx);
13084 self.set_relative_line_number(Some(!is_relative), cx)
13085 }
13086
13087 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13088 self.use_relative_line_numbers = is_relative;
13089 cx.notify();
13090 }
13091
13092 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13093 self.show_gutter = show_gutter;
13094 cx.notify();
13095 }
13096
13097 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13098 self.show_scrollbars = show_scrollbars;
13099 cx.notify();
13100 }
13101
13102 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13103 self.show_line_numbers = Some(show_line_numbers);
13104 cx.notify();
13105 }
13106
13107 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13108 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13109 cx.notify();
13110 }
13111
13112 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13113 self.show_code_actions = Some(show_code_actions);
13114 cx.notify();
13115 }
13116
13117 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13118 self.show_runnables = Some(show_runnables);
13119 cx.notify();
13120 }
13121
13122 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13123 if self.display_map.read(cx).masked != masked {
13124 self.display_map.update(cx, |map, _| map.masked = masked);
13125 }
13126 cx.notify()
13127 }
13128
13129 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13130 self.show_wrap_guides = Some(show_wrap_guides);
13131 cx.notify();
13132 }
13133
13134 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13135 self.show_indent_guides = Some(show_indent_guides);
13136 cx.notify();
13137 }
13138
13139 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13140 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13141 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13142 if let Some(dir) = file.abs_path(cx).parent() {
13143 return Some(dir.to_owned());
13144 }
13145 }
13146
13147 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13148 return Some(project_path.path.to_path_buf());
13149 }
13150 }
13151
13152 None
13153 }
13154
13155 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13156 self.active_excerpt(cx)?
13157 .1
13158 .read(cx)
13159 .file()
13160 .and_then(|f| f.as_local())
13161 }
13162
13163 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13164 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13165 let buffer = buffer.read(cx);
13166 if let Some(project_path) = buffer.project_path(cx) {
13167 let project = self.project.as_ref()?.read(cx);
13168 project.absolute_path(&project_path, cx)
13169 } else {
13170 buffer
13171 .file()
13172 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13173 }
13174 })
13175 }
13176
13177 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13178 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13179 let project_path = buffer.read(cx).project_path(cx)?;
13180 let project = self.project.as_ref()?.read(cx);
13181 let entry = project.entry_for_path(&project_path, cx)?;
13182 let path = entry.path.to_path_buf();
13183 Some(path)
13184 })
13185 }
13186
13187 pub fn reveal_in_finder(
13188 &mut self,
13189 _: &RevealInFileManager,
13190 _window: &mut Window,
13191 cx: &mut Context<Self>,
13192 ) {
13193 if let Some(target) = self.target_file(cx) {
13194 cx.reveal_path(&target.abs_path(cx));
13195 }
13196 }
13197
13198 pub fn copy_path(
13199 &mut self,
13200 _: &zed_actions::workspace::CopyPath,
13201 _window: &mut Window,
13202 cx: &mut Context<Self>,
13203 ) {
13204 if let Some(path) = self.target_file_abs_path(cx) {
13205 if let Some(path) = path.to_str() {
13206 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13207 }
13208 }
13209 }
13210
13211 pub fn copy_relative_path(
13212 &mut self,
13213 _: &zed_actions::workspace::CopyRelativePath,
13214 _window: &mut Window,
13215 cx: &mut Context<Self>,
13216 ) {
13217 if let Some(path) = self.target_file_path(cx) {
13218 if let Some(path) = path.to_str() {
13219 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13220 }
13221 }
13222 }
13223
13224 pub fn copy_file_name_without_extension(
13225 &mut self,
13226 _: &CopyFileNameWithoutExtension,
13227 _: &mut Window,
13228 cx: &mut Context<Self>,
13229 ) {
13230 if let Some(file) = self.target_file(cx) {
13231 if let Some(file_stem) = file.path().file_stem() {
13232 if let Some(name) = file_stem.to_str() {
13233 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13234 }
13235 }
13236 }
13237 }
13238
13239 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13240 if let Some(file) = self.target_file(cx) {
13241 if let Some(file_name) = file.path().file_name() {
13242 if let Some(name) = file_name.to_str() {
13243 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13244 }
13245 }
13246 }
13247 }
13248
13249 pub fn toggle_git_blame(
13250 &mut self,
13251 _: &ToggleGitBlame,
13252 window: &mut Window,
13253 cx: &mut Context<Self>,
13254 ) {
13255 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13256
13257 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13258 self.start_git_blame(true, window, cx);
13259 }
13260
13261 cx.notify();
13262 }
13263
13264 pub fn toggle_git_blame_inline(
13265 &mut self,
13266 _: &ToggleGitBlameInline,
13267 window: &mut Window,
13268 cx: &mut Context<Self>,
13269 ) {
13270 self.toggle_git_blame_inline_internal(true, window, cx);
13271 cx.notify();
13272 }
13273
13274 pub fn git_blame_inline_enabled(&self) -> bool {
13275 self.git_blame_inline_enabled
13276 }
13277
13278 pub fn toggle_selection_menu(
13279 &mut self,
13280 _: &ToggleSelectionMenu,
13281 _: &mut Window,
13282 cx: &mut Context<Self>,
13283 ) {
13284 self.show_selection_menu = self
13285 .show_selection_menu
13286 .map(|show_selections_menu| !show_selections_menu)
13287 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13288
13289 cx.notify();
13290 }
13291
13292 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13293 self.show_selection_menu
13294 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13295 }
13296
13297 fn start_git_blame(
13298 &mut self,
13299 user_triggered: bool,
13300 window: &mut Window,
13301 cx: &mut Context<Self>,
13302 ) {
13303 if let Some(project) = self.project.as_ref() {
13304 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13305 return;
13306 };
13307
13308 if buffer.read(cx).file().is_none() {
13309 return;
13310 }
13311
13312 let focused = self.focus_handle(cx).contains_focused(window, cx);
13313
13314 let project = project.clone();
13315 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13316 self.blame_subscription =
13317 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13318 self.blame = Some(blame);
13319 }
13320 }
13321
13322 fn toggle_git_blame_inline_internal(
13323 &mut self,
13324 user_triggered: bool,
13325 window: &mut Window,
13326 cx: &mut Context<Self>,
13327 ) {
13328 if self.git_blame_inline_enabled {
13329 self.git_blame_inline_enabled = false;
13330 self.show_git_blame_inline = false;
13331 self.show_git_blame_inline_delay_task.take();
13332 } else {
13333 self.git_blame_inline_enabled = true;
13334 self.start_git_blame_inline(user_triggered, window, cx);
13335 }
13336
13337 cx.notify();
13338 }
13339
13340 fn start_git_blame_inline(
13341 &mut self,
13342 user_triggered: bool,
13343 window: &mut Window,
13344 cx: &mut Context<Self>,
13345 ) {
13346 self.start_git_blame(user_triggered, window, cx);
13347
13348 if ProjectSettings::get_global(cx)
13349 .git
13350 .inline_blame_delay()
13351 .is_some()
13352 {
13353 self.start_inline_blame_timer(window, cx);
13354 } else {
13355 self.show_git_blame_inline = true
13356 }
13357 }
13358
13359 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13360 self.blame.as_ref()
13361 }
13362
13363 pub fn show_git_blame_gutter(&self) -> bool {
13364 self.show_git_blame_gutter
13365 }
13366
13367 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13368 self.show_git_blame_gutter && self.has_blame_entries(cx)
13369 }
13370
13371 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13372 self.show_git_blame_inline
13373 && (self.focus_handle.is_focused(window)
13374 || self
13375 .git_blame_inline_tooltip
13376 .as_ref()
13377 .and_then(|t| t.upgrade())
13378 .is_some())
13379 && !self.newest_selection_head_on_empty_line(cx)
13380 && self.has_blame_entries(cx)
13381 }
13382
13383 fn has_blame_entries(&self, cx: &App) -> bool {
13384 self.blame()
13385 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13386 }
13387
13388 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13389 let cursor_anchor = self.selections.newest_anchor().head();
13390
13391 let snapshot = self.buffer.read(cx).snapshot(cx);
13392 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13393
13394 snapshot.line_len(buffer_row) == 0
13395 }
13396
13397 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13398 let buffer_and_selection = maybe!({
13399 let selection = self.selections.newest::<Point>(cx);
13400 let selection_range = selection.range();
13401
13402 let multi_buffer = self.buffer().read(cx);
13403 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13404 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13405
13406 let (buffer, range, _) = if selection.reversed {
13407 buffer_ranges.first()
13408 } else {
13409 buffer_ranges.last()
13410 }?;
13411
13412 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13413 ..text::ToPoint::to_point(&range.end, &buffer).row;
13414 Some((
13415 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13416 selection,
13417 ))
13418 });
13419
13420 let Some((buffer, selection)) = buffer_and_selection else {
13421 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13422 };
13423
13424 let Some(project) = self.project.as_ref() else {
13425 return Task::ready(Err(anyhow!("editor does not have project")));
13426 };
13427
13428 project.update(cx, |project, cx| {
13429 project.get_permalink_to_line(&buffer, selection, cx)
13430 })
13431 }
13432
13433 pub fn copy_permalink_to_line(
13434 &mut self,
13435 _: &CopyPermalinkToLine,
13436 window: &mut Window,
13437 cx: &mut Context<Self>,
13438 ) {
13439 let permalink_task = self.get_permalink_to_line(cx);
13440 let workspace = self.workspace();
13441
13442 cx.spawn_in(window, |_, mut cx| async move {
13443 match permalink_task.await {
13444 Ok(permalink) => {
13445 cx.update(|_, cx| {
13446 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13447 })
13448 .ok();
13449 }
13450 Err(err) => {
13451 let message = format!("Failed to copy permalink: {err}");
13452
13453 Err::<(), anyhow::Error>(err).log_err();
13454
13455 if let Some(workspace) = workspace {
13456 workspace
13457 .update_in(&mut cx, |workspace, _, cx| {
13458 struct CopyPermalinkToLine;
13459
13460 workspace.show_toast(
13461 Toast::new(
13462 NotificationId::unique::<CopyPermalinkToLine>(),
13463 message,
13464 ),
13465 cx,
13466 )
13467 })
13468 .ok();
13469 }
13470 }
13471 }
13472 })
13473 .detach();
13474 }
13475
13476 pub fn copy_file_location(
13477 &mut self,
13478 _: &CopyFileLocation,
13479 _: &mut Window,
13480 cx: &mut Context<Self>,
13481 ) {
13482 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13483 if let Some(file) = self.target_file(cx) {
13484 if let Some(path) = file.path().to_str() {
13485 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13486 }
13487 }
13488 }
13489
13490 pub fn open_permalink_to_line(
13491 &mut self,
13492 _: &OpenPermalinkToLine,
13493 window: &mut Window,
13494 cx: &mut Context<Self>,
13495 ) {
13496 let permalink_task = self.get_permalink_to_line(cx);
13497 let workspace = self.workspace();
13498
13499 cx.spawn_in(window, |_, mut cx| async move {
13500 match permalink_task.await {
13501 Ok(permalink) => {
13502 cx.update(|_, cx| {
13503 cx.open_url(permalink.as_ref());
13504 })
13505 .ok();
13506 }
13507 Err(err) => {
13508 let message = format!("Failed to open permalink: {err}");
13509
13510 Err::<(), anyhow::Error>(err).log_err();
13511
13512 if let Some(workspace) = workspace {
13513 workspace
13514 .update(&mut cx, |workspace, cx| {
13515 struct OpenPermalinkToLine;
13516
13517 workspace.show_toast(
13518 Toast::new(
13519 NotificationId::unique::<OpenPermalinkToLine>(),
13520 message,
13521 ),
13522 cx,
13523 )
13524 })
13525 .ok();
13526 }
13527 }
13528 }
13529 })
13530 .detach();
13531 }
13532
13533 pub fn insert_uuid_v4(
13534 &mut self,
13535 _: &InsertUuidV4,
13536 window: &mut Window,
13537 cx: &mut Context<Self>,
13538 ) {
13539 self.insert_uuid(UuidVersion::V4, window, cx);
13540 }
13541
13542 pub fn insert_uuid_v7(
13543 &mut self,
13544 _: &InsertUuidV7,
13545 window: &mut Window,
13546 cx: &mut Context<Self>,
13547 ) {
13548 self.insert_uuid(UuidVersion::V7, window, cx);
13549 }
13550
13551 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13552 self.transact(window, cx, |this, window, cx| {
13553 let edits = this
13554 .selections
13555 .all::<Point>(cx)
13556 .into_iter()
13557 .map(|selection| {
13558 let uuid = match version {
13559 UuidVersion::V4 => uuid::Uuid::new_v4(),
13560 UuidVersion::V7 => uuid::Uuid::now_v7(),
13561 };
13562
13563 (selection.range(), uuid.to_string())
13564 });
13565 this.edit(edits, cx);
13566 this.refresh_inline_completion(true, false, window, cx);
13567 });
13568 }
13569
13570 pub fn open_selections_in_multibuffer(
13571 &mut self,
13572 _: &OpenSelectionsInMultibuffer,
13573 window: &mut Window,
13574 cx: &mut Context<Self>,
13575 ) {
13576 let multibuffer = self.buffer.read(cx);
13577
13578 let Some(buffer) = multibuffer.as_singleton() else {
13579 return;
13580 };
13581
13582 let Some(workspace) = self.workspace() else {
13583 return;
13584 };
13585
13586 let locations = self
13587 .selections
13588 .disjoint_anchors()
13589 .iter()
13590 .map(|range| Location {
13591 buffer: buffer.clone(),
13592 range: range.start.text_anchor..range.end.text_anchor,
13593 })
13594 .collect::<Vec<_>>();
13595
13596 let title = multibuffer.title(cx).to_string();
13597
13598 cx.spawn_in(window, |_, mut cx| async move {
13599 workspace.update_in(&mut cx, |workspace, window, cx| {
13600 Self::open_locations_in_multibuffer(
13601 workspace,
13602 locations,
13603 format!("Selections for '{title}'"),
13604 false,
13605 MultibufferSelectionMode::All,
13606 window,
13607 cx,
13608 );
13609 })
13610 })
13611 .detach();
13612 }
13613
13614 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13615 /// last highlight added will be used.
13616 ///
13617 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13618 pub fn highlight_rows<T: 'static>(
13619 &mut self,
13620 range: Range<Anchor>,
13621 color: Hsla,
13622 should_autoscroll: bool,
13623 cx: &mut Context<Self>,
13624 ) {
13625 let snapshot = self.buffer().read(cx).snapshot(cx);
13626 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13627 let ix = row_highlights.binary_search_by(|highlight| {
13628 Ordering::Equal
13629 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13630 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13631 });
13632
13633 if let Err(mut ix) = ix {
13634 let index = post_inc(&mut self.highlight_order);
13635
13636 // If this range intersects with the preceding highlight, then merge it with
13637 // the preceding highlight. Otherwise insert a new highlight.
13638 let mut merged = false;
13639 if ix > 0 {
13640 let prev_highlight = &mut row_highlights[ix - 1];
13641 if prev_highlight
13642 .range
13643 .end
13644 .cmp(&range.start, &snapshot)
13645 .is_ge()
13646 {
13647 ix -= 1;
13648 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13649 prev_highlight.range.end = range.end;
13650 }
13651 merged = true;
13652 prev_highlight.index = index;
13653 prev_highlight.color = color;
13654 prev_highlight.should_autoscroll = should_autoscroll;
13655 }
13656 }
13657
13658 if !merged {
13659 row_highlights.insert(
13660 ix,
13661 RowHighlight {
13662 range: range.clone(),
13663 index,
13664 color,
13665 should_autoscroll,
13666 },
13667 );
13668 }
13669
13670 // If any of the following highlights intersect with this one, merge them.
13671 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13672 let highlight = &row_highlights[ix];
13673 if next_highlight
13674 .range
13675 .start
13676 .cmp(&highlight.range.end, &snapshot)
13677 .is_le()
13678 {
13679 if next_highlight
13680 .range
13681 .end
13682 .cmp(&highlight.range.end, &snapshot)
13683 .is_gt()
13684 {
13685 row_highlights[ix].range.end = next_highlight.range.end;
13686 }
13687 row_highlights.remove(ix + 1);
13688 } else {
13689 break;
13690 }
13691 }
13692 }
13693 }
13694
13695 /// Remove any highlighted row ranges of the given type that intersect the
13696 /// given ranges.
13697 pub fn remove_highlighted_rows<T: 'static>(
13698 &mut self,
13699 ranges_to_remove: Vec<Range<Anchor>>,
13700 cx: &mut Context<Self>,
13701 ) {
13702 let snapshot = self.buffer().read(cx).snapshot(cx);
13703 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13704 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13705 row_highlights.retain(|highlight| {
13706 while let Some(range_to_remove) = ranges_to_remove.peek() {
13707 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13708 Ordering::Less | Ordering::Equal => {
13709 ranges_to_remove.next();
13710 }
13711 Ordering::Greater => {
13712 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13713 Ordering::Less | Ordering::Equal => {
13714 return false;
13715 }
13716 Ordering::Greater => break,
13717 }
13718 }
13719 }
13720 }
13721
13722 true
13723 })
13724 }
13725
13726 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13727 pub fn clear_row_highlights<T: 'static>(&mut self) {
13728 self.highlighted_rows.remove(&TypeId::of::<T>());
13729 }
13730
13731 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13732 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13733 self.highlighted_rows
13734 .get(&TypeId::of::<T>())
13735 .map_or(&[] as &[_], |vec| vec.as_slice())
13736 .iter()
13737 .map(|highlight| (highlight.range.clone(), highlight.color))
13738 }
13739
13740 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13741 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13742 /// Allows to ignore certain kinds of highlights.
13743 pub fn highlighted_display_rows(
13744 &self,
13745 window: &mut Window,
13746 cx: &mut App,
13747 ) -> BTreeMap<DisplayRow, Background> {
13748 let snapshot = self.snapshot(window, cx);
13749 let mut used_highlight_orders = HashMap::default();
13750 self.highlighted_rows
13751 .iter()
13752 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13753 .fold(
13754 BTreeMap::<DisplayRow, Background>::new(),
13755 |mut unique_rows, highlight| {
13756 let start = highlight.range.start.to_display_point(&snapshot);
13757 let end = highlight.range.end.to_display_point(&snapshot);
13758 let start_row = start.row().0;
13759 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13760 && end.column() == 0
13761 {
13762 end.row().0.saturating_sub(1)
13763 } else {
13764 end.row().0
13765 };
13766 for row in start_row..=end_row {
13767 let used_index =
13768 used_highlight_orders.entry(row).or_insert(highlight.index);
13769 if highlight.index >= *used_index {
13770 *used_index = highlight.index;
13771 unique_rows.insert(DisplayRow(row), highlight.color.into());
13772 }
13773 }
13774 unique_rows
13775 },
13776 )
13777 }
13778
13779 pub fn highlighted_display_row_for_autoscroll(
13780 &self,
13781 snapshot: &DisplaySnapshot,
13782 ) -> Option<DisplayRow> {
13783 self.highlighted_rows
13784 .values()
13785 .flat_map(|highlighted_rows| highlighted_rows.iter())
13786 .filter_map(|highlight| {
13787 if highlight.should_autoscroll {
13788 Some(highlight.range.start.to_display_point(snapshot).row())
13789 } else {
13790 None
13791 }
13792 })
13793 .min()
13794 }
13795
13796 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13797 self.highlight_background::<SearchWithinRange>(
13798 ranges,
13799 |colors| colors.editor_document_highlight_read_background,
13800 cx,
13801 )
13802 }
13803
13804 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13805 self.breadcrumb_header = Some(new_header);
13806 }
13807
13808 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13809 self.clear_background_highlights::<SearchWithinRange>(cx);
13810 }
13811
13812 pub fn highlight_background<T: 'static>(
13813 &mut self,
13814 ranges: &[Range<Anchor>],
13815 color_fetcher: fn(&ThemeColors) -> Hsla,
13816 cx: &mut Context<Self>,
13817 ) {
13818 self.background_highlights
13819 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13820 self.scrollbar_marker_state.dirty = true;
13821 cx.notify();
13822 }
13823
13824 pub fn clear_background_highlights<T: 'static>(
13825 &mut self,
13826 cx: &mut Context<Self>,
13827 ) -> Option<BackgroundHighlight> {
13828 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13829 if !text_highlights.1.is_empty() {
13830 self.scrollbar_marker_state.dirty = true;
13831 cx.notify();
13832 }
13833 Some(text_highlights)
13834 }
13835
13836 pub fn highlight_gutter<T: 'static>(
13837 &mut self,
13838 ranges: &[Range<Anchor>],
13839 color_fetcher: fn(&App) -> Hsla,
13840 cx: &mut Context<Self>,
13841 ) {
13842 self.gutter_highlights
13843 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13844 cx.notify();
13845 }
13846
13847 pub fn clear_gutter_highlights<T: 'static>(
13848 &mut self,
13849 cx: &mut Context<Self>,
13850 ) -> Option<GutterHighlight> {
13851 cx.notify();
13852 self.gutter_highlights.remove(&TypeId::of::<T>())
13853 }
13854
13855 #[cfg(feature = "test-support")]
13856 pub fn all_text_background_highlights(
13857 &self,
13858 window: &mut Window,
13859 cx: &mut Context<Self>,
13860 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13861 let snapshot = self.snapshot(window, cx);
13862 let buffer = &snapshot.buffer_snapshot;
13863 let start = buffer.anchor_before(0);
13864 let end = buffer.anchor_after(buffer.len());
13865 let theme = cx.theme().colors();
13866 self.background_highlights_in_range(start..end, &snapshot, theme)
13867 }
13868
13869 #[cfg(feature = "test-support")]
13870 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13871 let snapshot = self.buffer().read(cx).snapshot(cx);
13872
13873 let highlights = self
13874 .background_highlights
13875 .get(&TypeId::of::<items::BufferSearchHighlights>());
13876
13877 if let Some((_color, ranges)) = highlights {
13878 ranges
13879 .iter()
13880 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13881 .collect_vec()
13882 } else {
13883 vec![]
13884 }
13885 }
13886
13887 fn document_highlights_for_position<'a>(
13888 &'a self,
13889 position: Anchor,
13890 buffer: &'a MultiBufferSnapshot,
13891 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13892 let read_highlights = self
13893 .background_highlights
13894 .get(&TypeId::of::<DocumentHighlightRead>())
13895 .map(|h| &h.1);
13896 let write_highlights = self
13897 .background_highlights
13898 .get(&TypeId::of::<DocumentHighlightWrite>())
13899 .map(|h| &h.1);
13900 let left_position = position.bias_left(buffer);
13901 let right_position = position.bias_right(buffer);
13902 read_highlights
13903 .into_iter()
13904 .chain(write_highlights)
13905 .flat_map(move |ranges| {
13906 let start_ix = match ranges.binary_search_by(|probe| {
13907 let cmp = probe.end.cmp(&left_position, buffer);
13908 if cmp.is_ge() {
13909 Ordering::Greater
13910 } else {
13911 Ordering::Less
13912 }
13913 }) {
13914 Ok(i) | Err(i) => i,
13915 };
13916
13917 ranges[start_ix..]
13918 .iter()
13919 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13920 })
13921 }
13922
13923 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13924 self.background_highlights
13925 .get(&TypeId::of::<T>())
13926 .map_or(false, |(_, highlights)| !highlights.is_empty())
13927 }
13928
13929 pub fn background_highlights_in_range(
13930 &self,
13931 search_range: Range<Anchor>,
13932 display_snapshot: &DisplaySnapshot,
13933 theme: &ThemeColors,
13934 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13935 let mut results = Vec::new();
13936 for (color_fetcher, ranges) in self.background_highlights.values() {
13937 let color = color_fetcher(theme);
13938 let start_ix = match ranges.binary_search_by(|probe| {
13939 let cmp = probe
13940 .end
13941 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13942 if cmp.is_gt() {
13943 Ordering::Greater
13944 } else {
13945 Ordering::Less
13946 }
13947 }) {
13948 Ok(i) | Err(i) => i,
13949 };
13950 for range in &ranges[start_ix..] {
13951 if range
13952 .start
13953 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13954 .is_ge()
13955 {
13956 break;
13957 }
13958
13959 let start = range.start.to_display_point(display_snapshot);
13960 let end = range.end.to_display_point(display_snapshot);
13961 results.push((start..end, color))
13962 }
13963 }
13964 results
13965 }
13966
13967 pub fn background_highlight_row_ranges<T: 'static>(
13968 &self,
13969 search_range: Range<Anchor>,
13970 display_snapshot: &DisplaySnapshot,
13971 count: usize,
13972 ) -> Vec<RangeInclusive<DisplayPoint>> {
13973 let mut results = Vec::new();
13974 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13975 return vec![];
13976 };
13977
13978 let start_ix = match ranges.binary_search_by(|probe| {
13979 let cmp = probe
13980 .end
13981 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13982 if cmp.is_gt() {
13983 Ordering::Greater
13984 } else {
13985 Ordering::Less
13986 }
13987 }) {
13988 Ok(i) | Err(i) => i,
13989 };
13990 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13991 if let (Some(start_display), Some(end_display)) = (start, end) {
13992 results.push(
13993 start_display.to_display_point(display_snapshot)
13994 ..=end_display.to_display_point(display_snapshot),
13995 );
13996 }
13997 };
13998 let mut start_row: Option<Point> = None;
13999 let mut end_row: Option<Point> = None;
14000 if ranges.len() > count {
14001 return Vec::new();
14002 }
14003 for range in &ranges[start_ix..] {
14004 if range
14005 .start
14006 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14007 .is_ge()
14008 {
14009 break;
14010 }
14011 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14012 if let Some(current_row) = &end_row {
14013 if end.row == current_row.row {
14014 continue;
14015 }
14016 }
14017 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14018 if start_row.is_none() {
14019 assert_eq!(end_row, None);
14020 start_row = Some(start);
14021 end_row = Some(end);
14022 continue;
14023 }
14024 if let Some(current_end) = end_row.as_mut() {
14025 if start.row > current_end.row + 1 {
14026 push_region(start_row, end_row);
14027 start_row = Some(start);
14028 end_row = Some(end);
14029 } else {
14030 // Merge two hunks.
14031 *current_end = end;
14032 }
14033 } else {
14034 unreachable!();
14035 }
14036 }
14037 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14038 push_region(start_row, end_row);
14039 results
14040 }
14041
14042 pub fn gutter_highlights_in_range(
14043 &self,
14044 search_range: Range<Anchor>,
14045 display_snapshot: &DisplaySnapshot,
14046 cx: &App,
14047 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14048 let mut results = Vec::new();
14049 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14050 let color = color_fetcher(cx);
14051 let start_ix = match ranges.binary_search_by(|probe| {
14052 let cmp = probe
14053 .end
14054 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14055 if cmp.is_gt() {
14056 Ordering::Greater
14057 } else {
14058 Ordering::Less
14059 }
14060 }) {
14061 Ok(i) | Err(i) => i,
14062 };
14063 for range in &ranges[start_ix..] {
14064 if range
14065 .start
14066 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14067 .is_ge()
14068 {
14069 break;
14070 }
14071
14072 let start = range.start.to_display_point(display_snapshot);
14073 let end = range.end.to_display_point(display_snapshot);
14074 results.push((start..end, color))
14075 }
14076 }
14077 results
14078 }
14079
14080 /// Get the text ranges corresponding to the redaction query
14081 pub fn redacted_ranges(
14082 &self,
14083 search_range: Range<Anchor>,
14084 display_snapshot: &DisplaySnapshot,
14085 cx: &App,
14086 ) -> Vec<Range<DisplayPoint>> {
14087 display_snapshot
14088 .buffer_snapshot
14089 .redacted_ranges(search_range, |file| {
14090 if let Some(file) = file {
14091 file.is_private()
14092 && EditorSettings::get(
14093 Some(SettingsLocation {
14094 worktree_id: file.worktree_id(cx),
14095 path: file.path().as_ref(),
14096 }),
14097 cx,
14098 )
14099 .redact_private_values
14100 } else {
14101 false
14102 }
14103 })
14104 .map(|range| {
14105 range.start.to_display_point(display_snapshot)
14106 ..range.end.to_display_point(display_snapshot)
14107 })
14108 .collect()
14109 }
14110
14111 pub fn highlight_text<T: 'static>(
14112 &mut self,
14113 ranges: Vec<Range<Anchor>>,
14114 style: HighlightStyle,
14115 cx: &mut Context<Self>,
14116 ) {
14117 self.display_map.update(cx, |map, _| {
14118 map.highlight_text(TypeId::of::<T>(), ranges, style)
14119 });
14120 cx.notify();
14121 }
14122
14123 pub(crate) fn highlight_inlays<T: 'static>(
14124 &mut self,
14125 highlights: Vec<InlayHighlight>,
14126 style: HighlightStyle,
14127 cx: &mut Context<Self>,
14128 ) {
14129 self.display_map.update(cx, |map, _| {
14130 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14131 });
14132 cx.notify();
14133 }
14134
14135 pub fn text_highlights<'a, T: 'static>(
14136 &'a self,
14137 cx: &'a App,
14138 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14139 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14140 }
14141
14142 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14143 let cleared = self
14144 .display_map
14145 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14146 if cleared {
14147 cx.notify();
14148 }
14149 }
14150
14151 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14152 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14153 && self.focus_handle.is_focused(window)
14154 }
14155
14156 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14157 self.show_cursor_when_unfocused = is_enabled;
14158 cx.notify();
14159 }
14160
14161 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14162 cx.notify();
14163 }
14164
14165 fn on_buffer_event(
14166 &mut self,
14167 multibuffer: &Entity<MultiBuffer>,
14168 event: &multi_buffer::Event,
14169 window: &mut Window,
14170 cx: &mut Context<Self>,
14171 ) {
14172 match event {
14173 multi_buffer::Event::Edited {
14174 singleton_buffer_edited,
14175 edited_buffer: buffer_edited,
14176 } => {
14177 self.scrollbar_marker_state.dirty = true;
14178 self.active_indent_guides_state.dirty = true;
14179 self.refresh_active_diagnostics(cx);
14180 self.refresh_code_actions(window, cx);
14181 if self.has_active_inline_completion() {
14182 self.update_visible_inline_completion(window, cx);
14183 }
14184 if let Some(buffer) = buffer_edited {
14185 let buffer_id = buffer.read(cx).remote_id();
14186 if !self.registered_buffers.contains_key(&buffer_id) {
14187 if let Some(project) = self.project.as_ref() {
14188 project.update(cx, |project, cx| {
14189 self.registered_buffers.insert(
14190 buffer_id,
14191 project.register_buffer_with_language_servers(&buffer, cx),
14192 );
14193 })
14194 }
14195 }
14196 }
14197 cx.emit(EditorEvent::BufferEdited);
14198 cx.emit(SearchEvent::MatchesInvalidated);
14199 if *singleton_buffer_edited {
14200 if let Some(project) = &self.project {
14201 #[allow(clippy::mutable_key_type)]
14202 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14203 multibuffer
14204 .all_buffers()
14205 .into_iter()
14206 .filter_map(|buffer| {
14207 buffer.update(cx, |buffer, cx| {
14208 let language = buffer.language()?;
14209 let should_discard = project.update(cx, |project, cx| {
14210 project.is_local()
14211 && !project.has_language_servers_for(buffer, cx)
14212 });
14213 should_discard.not().then_some(language.clone())
14214 })
14215 })
14216 .collect::<HashSet<_>>()
14217 });
14218 if !languages_affected.is_empty() {
14219 self.refresh_inlay_hints(
14220 InlayHintRefreshReason::BufferEdited(languages_affected),
14221 cx,
14222 );
14223 }
14224 }
14225 }
14226
14227 let Some(project) = &self.project else { return };
14228 let (telemetry, is_via_ssh) = {
14229 let project = project.read(cx);
14230 let telemetry = project.client().telemetry().clone();
14231 let is_via_ssh = project.is_via_ssh();
14232 (telemetry, is_via_ssh)
14233 };
14234 refresh_linked_ranges(self, window, cx);
14235 telemetry.log_edit_event("editor", is_via_ssh);
14236 }
14237 multi_buffer::Event::ExcerptsAdded {
14238 buffer,
14239 predecessor,
14240 excerpts,
14241 } => {
14242 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14243 let buffer_id = buffer.read(cx).remote_id();
14244 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14245 if let Some(project) = &self.project {
14246 get_uncommitted_diff_for_buffer(
14247 project,
14248 [buffer.clone()],
14249 self.buffer.clone(),
14250 cx,
14251 )
14252 .detach();
14253 }
14254 }
14255 cx.emit(EditorEvent::ExcerptsAdded {
14256 buffer: buffer.clone(),
14257 predecessor: *predecessor,
14258 excerpts: excerpts.clone(),
14259 });
14260 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14261 }
14262 multi_buffer::Event::ExcerptsRemoved { ids } => {
14263 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14264 let buffer = self.buffer.read(cx);
14265 self.registered_buffers
14266 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14267 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14268 }
14269 multi_buffer::Event::ExcerptsEdited { ids } => {
14270 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14271 }
14272 multi_buffer::Event::ExcerptsExpanded { ids } => {
14273 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14274 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14275 }
14276 multi_buffer::Event::Reparsed(buffer_id) => {
14277 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14278
14279 cx.emit(EditorEvent::Reparsed(*buffer_id));
14280 }
14281 multi_buffer::Event::DiffHunksToggled => {
14282 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14283 }
14284 multi_buffer::Event::LanguageChanged(buffer_id) => {
14285 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14286 cx.emit(EditorEvent::Reparsed(*buffer_id));
14287 cx.notify();
14288 }
14289 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14290 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14291 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14292 cx.emit(EditorEvent::TitleChanged)
14293 }
14294 // multi_buffer::Event::DiffBaseChanged => {
14295 // self.scrollbar_marker_state.dirty = true;
14296 // cx.emit(EditorEvent::DiffBaseChanged);
14297 // cx.notify();
14298 // }
14299 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14300 multi_buffer::Event::DiagnosticsUpdated => {
14301 self.refresh_active_diagnostics(cx);
14302 self.scrollbar_marker_state.dirty = true;
14303 cx.notify();
14304 }
14305 _ => {}
14306 };
14307 }
14308
14309 fn on_display_map_changed(
14310 &mut self,
14311 _: Entity<DisplayMap>,
14312 _: &mut Window,
14313 cx: &mut Context<Self>,
14314 ) {
14315 cx.notify();
14316 }
14317
14318 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14319 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14320 self.refresh_inline_completion(true, false, window, cx);
14321 self.refresh_inlay_hints(
14322 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14323 self.selections.newest_anchor().head(),
14324 &self.buffer.read(cx).snapshot(cx),
14325 cx,
14326 )),
14327 cx,
14328 );
14329
14330 let old_cursor_shape = self.cursor_shape;
14331
14332 {
14333 let editor_settings = EditorSettings::get_global(cx);
14334 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14335 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14336 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14337 }
14338
14339 if old_cursor_shape != self.cursor_shape {
14340 cx.emit(EditorEvent::CursorShapeChanged);
14341 }
14342
14343 let project_settings = ProjectSettings::get_global(cx);
14344 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14345
14346 if self.mode == EditorMode::Full {
14347 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14348 if self.git_blame_inline_enabled != inline_blame_enabled {
14349 self.toggle_git_blame_inline_internal(false, window, cx);
14350 }
14351 }
14352
14353 cx.notify();
14354 }
14355
14356 pub fn set_searchable(&mut self, searchable: bool) {
14357 self.searchable = searchable;
14358 }
14359
14360 pub fn searchable(&self) -> bool {
14361 self.searchable
14362 }
14363
14364 fn open_proposed_changes_editor(
14365 &mut self,
14366 _: &OpenProposedChangesEditor,
14367 window: &mut Window,
14368 cx: &mut Context<Self>,
14369 ) {
14370 let Some(workspace) = self.workspace() else {
14371 cx.propagate();
14372 return;
14373 };
14374
14375 let selections = self.selections.all::<usize>(cx);
14376 let multi_buffer = self.buffer.read(cx);
14377 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14378 let mut new_selections_by_buffer = HashMap::default();
14379 for selection in selections {
14380 for (buffer, range, _) in
14381 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14382 {
14383 let mut range = range.to_point(buffer);
14384 range.start.column = 0;
14385 range.end.column = buffer.line_len(range.end.row);
14386 new_selections_by_buffer
14387 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14388 .or_insert(Vec::new())
14389 .push(range)
14390 }
14391 }
14392
14393 let proposed_changes_buffers = new_selections_by_buffer
14394 .into_iter()
14395 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14396 .collect::<Vec<_>>();
14397 let proposed_changes_editor = cx.new(|cx| {
14398 ProposedChangesEditor::new(
14399 "Proposed changes",
14400 proposed_changes_buffers,
14401 self.project.clone(),
14402 window,
14403 cx,
14404 )
14405 });
14406
14407 window.defer(cx, move |window, cx| {
14408 workspace.update(cx, |workspace, cx| {
14409 workspace.active_pane().update(cx, |pane, cx| {
14410 pane.add_item(
14411 Box::new(proposed_changes_editor),
14412 true,
14413 true,
14414 None,
14415 window,
14416 cx,
14417 );
14418 });
14419 });
14420 });
14421 }
14422
14423 pub fn open_excerpts_in_split(
14424 &mut self,
14425 _: &OpenExcerptsSplit,
14426 window: &mut Window,
14427 cx: &mut Context<Self>,
14428 ) {
14429 self.open_excerpts_common(None, true, window, cx)
14430 }
14431
14432 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14433 self.open_excerpts_common(None, false, window, cx)
14434 }
14435
14436 fn open_excerpts_common(
14437 &mut self,
14438 jump_data: Option<JumpData>,
14439 split: bool,
14440 window: &mut Window,
14441 cx: &mut Context<Self>,
14442 ) {
14443 let Some(workspace) = self.workspace() else {
14444 cx.propagate();
14445 return;
14446 };
14447
14448 if self.buffer.read(cx).is_singleton() {
14449 cx.propagate();
14450 return;
14451 }
14452
14453 let mut new_selections_by_buffer = HashMap::default();
14454 match &jump_data {
14455 Some(JumpData::MultiBufferPoint {
14456 excerpt_id,
14457 position,
14458 anchor,
14459 line_offset_from_top,
14460 }) => {
14461 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14462 if let Some(buffer) = multi_buffer_snapshot
14463 .buffer_id_for_excerpt(*excerpt_id)
14464 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14465 {
14466 let buffer_snapshot = buffer.read(cx).snapshot();
14467 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14468 language::ToPoint::to_point(anchor, &buffer_snapshot)
14469 } else {
14470 buffer_snapshot.clip_point(*position, Bias::Left)
14471 };
14472 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14473 new_selections_by_buffer.insert(
14474 buffer,
14475 (
14476 vec![jump_to_offset..jump_to_offset],
14477 Some(*line_offset_from_top),
14478 ),
14479 );
14480 }
14481 }
14482 Some(JumpData::MultiBufferRow {
14483 row,
14484 line_offset_from_top,
14485 }) => {
14486 let point = MultiBufferPoint::new(row.0, 0);
14487 if let Some((buffer, buffer_point, _)) =
14488 self.buffer.read(cx).point_to_buffer_point(point, cx)
14489 {
14490 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14491 new_selections_by_buffer
14492 .entry(buffer)
14493 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14494 .0
14495 .push(buffer_offset..buffer_offset)
14496 }
14497 }
14498 None => {
14499 let selections = self.selections.all::<usize>(cx);
14500 let multi_buffer = self.buffer.read(cx);
14501 for selection in selections {
14502 for (buffer, mut range, _) in multi_buffer
14503 .snapshot(cx)
14504 .range_to_buffer_ranges(selection.range())
14505 {
14506 // When editing branch buffers, jump to the corresponding location
14507 // in their base buffer.
14508 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14509 let buffer = buffer_handle.read(cx);
14510 if let Some(base_buffer) = buffer.base_buffer() {
14511 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14512 buffer_handle = base_buffer;
14513 }
14514
14515 if selection.reversed {
14516 mem::swap(&mut range.start, &mut range.end);
14517 }
14518 new_selections_by_buffer
14519 .entry(buffer_handle)
14520 .or_insert((Vec::new(), None))
14521 .0
14522 .push(range)
14523 }
14524 }
14525 }
14526 }
14527
14528 if new_selections_by_buffer.is_empty() {
14529 return;
14530 }
14531
14532 // We defer the pane interaction because we ourselves are a workspace item
14533 // and activating a new item causes the pane to call a method on us reentrantly,
14534 // which panics if we're on the stack.
14535 window.defer(cx, move |window, cx| {
14536 workspace.update(cx, |workspace, cx| {
14537 let pane = if split {
14538 workspace.adjacent_pane(window, cx)
14539 } else {
14540 workspace.active_pane().clone()
14541 };
14542
14543 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14544 let editor = buffer
14545 .read(cx)
14546 .file()
14547 .is_none()
14548 .then(|| {
14549 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14550 // so `workspace.open_project_item` will never find them, always opening a new editor.
14551 // Instead, we try to activate the existing editor in the pane first.
14552 let (editor, pane_item_index) =
14553 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14554 let editor = item.downcast::<Editor>()?;
14555 let singleton_buffer =
14556 editor.read(cx).buffer().read(cx).as_singleton()?;
14557 if singleton_buffer == buffer {
14558 Some((editor, i))
14559 } else {
14560 None
14561 }
14562 })?;
14563 pane.update(cx, |pane, cx| {
14564 pane.activate_item(pane_item_index, true, true, window, cx)
14565 });
14566 Some(editor)
14567 })
14568 .flatten()
14569 .unwrap_or_else(|| {
14570 workspace.open_project_item::<Self>(
14571 pane.clone(),
14572 buffer,
14573 true,
14574 true,
14575 window,
14576 cx,
14577 )
14578 });
14579
14580 editor.update(cx, |editor, cx| {
14581 let autoscroll = match scroll_offset {
14582 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14583 None => Autoscroll::newest(),
14584 };
14585 let nav_history = editor.nav_history.take();
14586 editor.change_selections(Some(autoscroll), window, cx, |s| {
14587 s.select_ranges(ranges);
14588 });
14589 editor.nav_history = nav_history;
14590 });
14591 }
14592 })
14593 });
14594 }
14595
14596 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14597 let snapshot = self.buffer.read(cx).read(cx);
14598 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14599 Some(
14600 ranges
14601 .iter()
14602 .map(move |range| {
14603 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14604 })
14605 .collect(),
14606 )
14607 }
14608
14609 fn selection_replacement_ranges(
14610 &self,
14611 range: Range<OffsetUtf16>,
14612 cx: &mut App,
14613 ) -> Vec<Range<OffsetUtf16>> {
14614 let selections = self.selections.all::<OffsetUtf16>(cx);
14615 let newest_selection = selections
14616 .iter()
14617 .max_by_key(|selection| selection.id)
14618 .unwrap();
14619 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14620 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14621 let snapshot = self.buffer.read(cx).read(cx);
14622 selections
14623 .into_iter()
14624 .map(|mut selection| {
14625 selection.start.0 =
14626 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14627 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14628 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14629 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14630 })
14631 .collect()
14632 }
14633
14634 fn report_editor_event(
14635 &self,
14636 event_type: &'static str,
14637 file_extension: Option<String>,
14638 cx: &App,
14639 ) {
14640 if cfg!(any(test, feature = "test-support")) {
14641 return;
14642 }
14643
14644 let Some(project) = &self.project else { return };
14645
14646 // If None, we are in a file without an extension
14647 let file = self
14648 .buffer
14649 .read(cx)
14650 .as_singleton()
14651 .and_then(|b| b.read(cx).file());
14652 let file_extension = file_extension.or(file
14653 .as_ref()
14654 .and_then(|file| Path::new(file.file_name(cx)).extension())
14655 .and_then(|e| e.to_str())
14656 .map(|a| a.to_string()));
14657
14658 let vim_mode = cx
14659 .global::<SettingsStore>()
14660 .raw_user_settings()
14661 .get("vim_mode")
14662 == Some(&serde_json::Value::Bool(true));
14663
14664 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14665 let copilot_enabled = edit_predictions_provider
14666 == language::language_settings::EditPredictionProvider::Copilot;
14667 let copilot_enabled_for_language = self
14668 .buffer
14669 .read(cx)
14670 .settings_at(0, cx)
14671 .show_edit_predictions;
14672
14673 let project = project.read(cx);
14674 telemetry::event!(
14675 event_type,
14676 file_extension,
14677 vim_mode,
14678 copilot_enabled,
14679 copilot_enabled_for_language,
14680 edit_predictions_provider,
14681 is_via_ssh = project.is_via_ssh(),
14682 );
14683 }
14684
14685 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14686 /// with each line being an array of {text, highlight} objects.
14687 fn copy_highlight_json(
14688 &mut self,
14689 _: &CopyHighlightJson,
14690 window: &mut Window,
14691 cx: &mut Context<Self>,
14692 ) {
14693 #[derive(Serialize)]
14694 struct Chunk<'a> {
14695 text: String,
14696 highlight: Option<&'a str>,
14697 }
14698
14699 let snapshot = self.buffer.read(cx).snapshot(cx);
14700 let range = self
14701 .selected_text_range(false, window, cx)
14702 .and_then(|selection| {
14703 if selection.range.is_empty() {
14704 None
14705 } else {
14706 Some(selection.range)
14707 }
14708 })
14709 .unwrap_or_else(|| 0..snapshot.len());
14710
14711 let chunks = snapshot.chunks(range, true);
14712 let mut lines = Vec::new();
14713 let mut line: VecDeque<Chunk> = VecDeque::new();
14714
14715 let Some(style) = self.style.as_ref() else {
14716 return;
14717 };
14718
14719 for chunk in chunks {
14720 let highlight = chunk
14721 .syntax_highlight_id
14722 .and_then(|id| id.name(&style.syntax));
14723 let mut chunk_lines = chunk.text.split('\n').peekable();
14724 while let Some(text) = chunk_lines.next() {
14725 let mut merged_with_last_token = false;
14726 if let Some(last_token) = line.back_mut() {
14727 if last_token.highlight == highlight {
14728 last_token.text.push_str(text);
14729 merged_with_last_token = true;
14730 }
14731 }
14732
14733 if !merged_with_last_token {
14734 line.push_back(Chunk {
14735 text: text.into(),
14736 highlight,
14737 });
14738 }
14739
14740 if chunk_lines.peek().is_some() {
14741 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14742 line.pop_front();
14743 }
14744 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14745 line.pop_back();
14746 }
14747
14748 lines.push(mem::take(&mut line));
14749 }
14750 }
14751 }
14752
14753 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14754 return;
14755 };
14756 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14757 }
14758
14759 pub fn open_context_menu(
14760 &mut self,
14761 _: &OpenContextMenu,
14762 window: &mut Window,
14763 cx: &mut Context<Self>,
14764 ) {
14765 self.request_autoscroll(Autoscroll::newest(), cx);
14766 let position = self.selections.newest_display(cx).start;
14767 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14768 }
14769
14770 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14771 &self.inlay_hint_cache
14772 }
14773
14774 pub fn replay_insert_event(
14775 &mut self,
14776 text: &str,
14777 relative_utf16_range: Option<Range<isize>>,
14778 window: &mut Window,
14779 cx: &mut Context<Self>,
14780 ) {
14781 if !self.input_enabled {
14782 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14783 return;
14784 }
14785 if let Some(relative_utf16_range) = relative_utf16_range {
14786 let selections = self.selections.all::<OffsetUtf16>(cx);
14787 self.change_selections(None, window, cx, |s| {
14788 let new_ranges = selections.into_iter().map(|range| {
14789 let start = OffsetUtf16(
14790 range
14791 .head()
14792 .0
14793 .saturating_add_signed(relative_utf16_range.start),
14794 );
14795 let end = OffsetUtf16(
14796 range
14797 .head()
14798 .0
14799 .saturating_add_signed(relative_utf16_range.end),
14800 );
14801 start..end
14802 });
14803 s.select_ranges(new_ranges);
14804 });
14805 }
14806
14807 self.handle_input(text, window, cx);
14808 }
14809
14810 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14811 let Some(provider) = self.semantics_provider.as_ref() else {
14812 return false;
14813 };
14814
14815 let mut supports = false;
14816 self.buffer().update(cx, |this, cx| {
14817 this.for_each_buffer(|buffer| {
14818 supports |= provider.supports_inlay_hints(buffer, cx);
14819 });
14820 });
14821
14822 supports
14823 }
14824
14825 pub fn is_focused(&self, window: &Window) -> bool {
14826 self.focus_handle.is_focused(window)
14827 }
14828
14829 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14830 cx.emit(EditorEvent::Focused);
14831
14832 if let Some(descendant) = self
14833 .last_focused_descendant
14834 .take()
14835 .and_then(|descendant| descendant.upgrade())
14836 {
14837 window.focus(&descendant);
14838 } else {
14839 if let Some(blame) = self.blame.as_ref() {
14840 blame.update(cx, GitBlame::focus)
14841 }
14842
14843 self.blink_manager.update(cx, BlinkManager::enable);
14844 self.show_cursor_names(window, cx);
14845 self.buffer.update(cx, |buffer, cx| {
14846 buffer.finalize_last_transaction(cx);
14847 if self.leader_peer_id.is_none() {
14848 buffer.set_active_selections(
14849 &self.selections.disjoint_anchors(),
14850 self.selections.line_mode,
14851 self.cursor_shape,
14852 cx,
14853 );
14854 }
14855 });
14856 }
14857 }
14858
14859 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14860 cx.emit(EditorEvent::FocusedIn)
14861 }
14862
14863 fn handle_focus_out(
14864 &mut self,
14865 event: FocusOutEvent,
14866 _window: &mut Window,
14867 _cx: &mut Context<Self>,
14868 ) {
14869 if event.blurred != self.focus_handle {
14870 self.last_focused_descendant = Some(event.blurred);
14871 }
14872 }
14873
14874 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14875 self.blink_manager.update(cx, BlinkManager::disable);
14876 self.buffer
14877 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14878
14879 if let Some(blame) = self.blame.as_ref() {
14880 blame.update(cx, GitBlame::blur)
14881 }
14882 if !self.hover_state.focused(window, cx) {
14883 hide_hover(self, cx);
14884 }
14885 if !self
14886 .context_menu
14887 .borrow()
14888 .as_ref()
14889 .is_some_and(|context_menu| context_menu.focused(window, cx))
14890 {
14891 self.hide_context_menu(window, cx);
14892 }
14893 self.discard_inline_completion(false, cx);
14894 cx.emit(EditorEvent::Blurred);
14895 cx.notify();
14896 }
14897
14898 pub fn register_action<A: Action>(
14899 &mut self,
14900 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14901 ) -> Subscription {
14902 let id = self.next_editor_action_id.post_inc();
14903 let listener = Arc::new(listener);
14904 self.editor_actions.borrow_mut().insert(
14905 id,
14906 Box::new(move |window, _| {
14907 let listener = listener.clone();
14908 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14909 let action = action.downcast_ref().unwrap();
14910 if phase == DispatchPhase::Bubble {
14911 listener(action, window, cx)
14912 }
14913 })
14914 }),
14915 );
14916
14917 let editor_actions = self.editor_actions.clone();
14918 Subscription::new(move || {
14919 editor_actions.borrow_mut().remove(&id);
14920 })
14921 }
14922
14923 pub fn file_header_size(&self) -> u32 {
14924 FILE_HEADER_HEIGHT
14925 }
14926
14927 pub fn revert(
14928 &mut self,
14929 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14930 window: &mut Window,
14931 cx: &mut Context<Self>,
14932 ) {
14933 self.buffer().update(cx, |multi_buffer, cx| {
14934 for (buffer_id, changes) in revert_changes {
14935 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14936 buffer.update(cx, |buffer, cx| {
14937 buffer.edit(
14938 changes.into_iter().map(|(range, text)| {
14939 (range, text.to_string().map(Arc::<str>::from))
14940 }),
14941 None,
14942 cx,
14943 );
14944 });
14945 }
14946 }
14947 });
14948 self.change_selections(None, window, cx, |selections| selections.refresh());
14949 }
14950
14951 pub fn to_pixel_point(
14952 &self,
14953 source: multi_buffer::Anchor,
14954 editor_snapshot: &EditorSnapshot,
14955 window: &mut Window,
14956 ) -> Option<gpui::Point<Pixels>> {
14957 let source_point = source.to_display_point(editor_snapshot);
14958 self.display_to_pixel_point(source_point, editor_snapshot, window)
14959 }
14960
14961 pub fn display_to_pixel_point(
14962 &self,
14963 source: DisplayPoint,
14964 editor_snapshot: &EditorSnapshot,
14965 window: &mut Window,
14966 ) -> Option<gpui::Point<Pixels>> {
14967 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14968 let text_layout_details = self.text_layout_details(window);
14969 let scroll_top = text_layout_details
14970 .scroll_anchor
14971 .scroll_position(editor_snapshot)
14972 .y;
14973
14974 if source.row().as_f32() < scroll_top.floor() {
14975 return None;
14976 }
14977 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14978 let source_y = line_height * (source.row().as_f32() - scroll_top);
14979 Some(gpui::Point::new(source_x, source_y))
14980 }
14981
14982 pub fn has_visible_completions_menu(&self) -> bool {
14983 !self.edit_prediction_preview_is_active()
14984 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14985 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14986 })
14987 }
14988
14989 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14990 self.addons
14991 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14992 }
14993
14994 pub fn unregister_addon<T: Addon>(&mut self) {
14995 self.addons.remove(&std::any::TypeId::of::<T>());
14996 }
14997
14998 pub fn addon<T: Addon>(&self) -> Option<&T> {
14999 let type_id = std::any::TypeId::of::<T>();
15000 self.addons
15001 .get(&type_id)
15002 .and_then(|item| item.to_any().downcast_ref::<T>())
15003 }
15004
15005 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15006 let text_layout_details = self.text_layout_details(window);
15007 let style = &text_layout_details.editor_style;
15008 let font_id = window.text_system().resolve_font(&style.text.font());
15009 let font_size = style.text.font_size.to_pixels(window.rem_size());
15010 let line_height = style.text.line_height_in_pixels(window.rem_size());
15011 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15012
15013 gpui::Size::new(em_width, line_height)
15014 }
15015
15016 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15017 self.load_diff_task.clone()
15018 }
15019
15020 fn read_selections_from_db(
15021 &mut self,
15022 item_id: u64,
15023 workspace_id: WorkspaceId,
15024 window: &mut Window,
15025 cx: &mut Context<Editor>,
15026 ) {
15027 if !self.is_singleton(cx)
15028 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15029 {
15030 return;
15031 }
15032 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15033 return;
15034 };
15035 if selections.is_empty() {
15036 return;
15037 }
15038
15039 let snapshot = self.buffer.read(cx).snapshot(cx);
15040 self.change_selections(None, window, cx, |s| {
15041 s.select_ranges(selections.into_iter().map(|(start, end)| {
15042 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15043 }));
15044 });
15045 }
15046}
15047
15048fn get_uncommitted_diff_for_buffer(
15049 project: &Entity<Project>,
15050 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15051 buffer: Entity<MultiBuffer>,
15052 cx: &mut App,
15053) -> Task<()> {
15054 let mut tasks = Vec::new();
15055 project.update(cx, |project, cx| {
15056 for buffer in buffers {
15057 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15058 }
15059 });
15060 cx.spawn(|mut cx| async move {
15061 let diffs = futures::future::join_all(tasks).await;
15062 buffer
15063 .update(&mut cx, |buffer, cx| {
15064 for diff in diffs.into_iter().flatten() {
15065 buffer.add_diff(diff, cx);
15066 }
15067 })
15068 .ok();
15069 })
15070}
15071
15072fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15073 let tab_size = tab_size.get() as usize;
15074 let mut width = offset;
15075
15076 for ch in text.chars() {
15077 width += if ch == '\t' {
15078 tab_size - (width % tab_size)
15079 } else {
15080 1
15081 };
15082 }
15083
15084 width - offset
15085}
15086
15087#[cfg(test)]
15088mod tests {
15089 use super::*;
15090
15091 #[test]
15092 fn test_string_size_with_expanded_tabs() {
15093 let nz = |val| NonZeroU32::new(val).unwrap();
15094 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15095 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15096 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15097 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15098 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15099 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15100 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15101 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15102 }
15103}
15104
15105/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15106struct WordBreakingTokenizer<'a> {
15107 input: &'a str,
15108}
15109
15110impl<'a> WordBreakingTokenizer<'a> {
15111 fn new(input: &'a str) -> Self {
15112 Self { input }
15113 }
15114}
15115
15116fn is_char_ideographic(ch: char) -> bool {
15117 use unicode_script::Script::*;
15118 use unicode_script::UnicodeScript;
15119 matches!(ch.script(), Han | Tangut | Yi)
15120}
15121
15122fn is_grapheme_ideographic(text: &str) -> bool {
15123 text.chars().any(is_char_ideographic)
15124}
15125
15126fn is_grapheme_whitespace(text: &str) -> bool {
15127 text.chars().any(|x| x.is_whitespace())
15128}
15129
15130fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15131 text.chars().next().map_or(false, |ch| {
15132 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15133 })
15134}
15135
15136#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15137struct WordBreakToken<'a> {
15138 token: &'a str,
15139 grapheme_len: usize,
15140 is_whitespace: bool,
15141}
15142
15143impl<'a> Iterator for WordBreakingTokenizer<'a> {
15144 /// Yields a span, the count of graphemes in the token, and whether it was
15145 /// whitespace. Note that it also breaks at word boundaries.
15146 type Item = WordBreakToken<'a>;
15147
15148 fn next(&mut self) -> Option<Self::Item> {
15149 use unicode_segmentation::UnicodeSegmentation;
15150 if self.input.is_empty() {
15151 return None;
15152 }
15153
15154 let mut iter = self.input.graphemes(true).peekable();
15155 let mut offset = 0;
15156 let mut graphemes = 0;
15157 if let Some(first_grapheme) = iter.next() {
15158 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15159 offset += first_grapheme.len();
15160 graphemes += 1;
15161 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15162 if let Some(grapheme) = iter.peek().copied() {
15163 if should_stay_with_preceding_ideograph(grapheme) {
15164 offset += grapheme.len();
15165 graphemes += 1;
15166 }
15167 }
15168 } else {
15169 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15170 let mut next_word_bound = words.peek().copied();
15171 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15172 next_word_bound = words.next();
15173 }
15174 while let Some(grapheme) = iter.peek().copied() {
15175 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15176 break;
15177 };
15178 if is_grapheme_whitespace(grapheme) != is_whitespace {
15179 break;
15180 };
15181 offset += grapheme.len();
15182 graphemes += 1;
15183 iter.next();
15184 }
15185 }
15186 let token = &self.input[..offset];
15187 self.input = &self.input[offset..];
15188 if is_whitespace {
15189 Some(WordBreakToken {
15190 token: " ",
15191 grapheme_len: 1,
15192 is_whitespace: true,
15193 })
15194 } else {
15195 Some(WordBreakToken {
15196 token,
15197 grapheme_len: graphemes,
15198 is_whitespace: false,
15199 })
15200 }
15201 } else {
15202 None
15203 }
15204 }
15205}
15206
15207#[test]
15208fn test_word_breaking_tokenizer() {
15209 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15210 ("", &[]),
15211 (" ", &[(" ", 1, true)]),
15212 ("Ʒ", &[("Ʒ", 1, false)]),
15213 ("Ǽ", &[("Ǽ", 1, false)]),
15214 ("⋑", &[("⋑", 1, false)]),
15215 ("⋑⋑", &[("⋑⋑", 2, false)]),
15216 (
15217 "原理,进而",
15218 &[
15219 ("原", 1, false),
15220 ("理,", 2, false),
15221 ("进", 1, false),
15222 ("而", 1, false),
15223 ],
15224 ),
15225 (
15226 "hello world",
15227 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15228 ),
15229 (
15230 "hello, world",
15231 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15232 ),
15233 (
15234 " hello world",
15235 &[
15236 (" ", 1, true),
15237 ("hello", 5, false),
15238 (" ", 1, true),
15239 ("world", 5, false),
15240 ],
15241 ),
15242 (
15243 "这是什么 \n 钢笔",
15244 &[
15245 ("这", 1, false),
15246 ("是", 1, false),
15247 ("什", 1, false),
15248 ("么", 1, false),
15249 (" ", 1, true),
15250 ("钢", 1, false),
15251 ("笔", 1, false),
15252 ],
15253 ),
15254 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15255 ];
15256
15257 for (input, result) in tests {
15258 assert_eq!(
15259 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15260 result
15261 .iter()
15262 .copied()
15263 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15264 token,
15265 grapheme_len,
15266 is_whitespace,
15267 })
15268 .collect::<Vec<_>>()
15269 );
15270 }
15271}
15272
15273fn wrap_with_prefix(
15274 line_prefix: String,
15275 unwrapped_text: String,
15276 wrap_column: usize,
15277 tab_size: NonZeroU32,
15278) -> String {
15279 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15280 let mut wrapped_text = String::new();
15281 let mut current_line = line_prefix.clone();
15282
15283 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15284 let mut current_line_len = line_prefix_len;
15285 for WordBreakToken {
15286 token,
15287 grapheme_len,
15288 is_whitespace,
15289 } in tokenizer
15290 {
15291 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15292 wrapped_text.push_str(current_line.trim_end());
15293 wrapped_text.push('\n');
15294 current_line.truncate(line_prefix.len());
15295 current_line_len = line_prefix_len;
15296 if !is_whitespace {
15297 current_line.push_str(token);
15298 current_line_len += grapheme_len;
15299 }
15300 } else if !is_whitespace {
15301 current_line.push_str(token);
15302 current_line_len += grapheme_len;
15303 } else if current_line_len != line_prefix_len {
15304 current_line.push(' ');
15305 current_line_len += 1;
15306 }
15307 }
15308
15309 if !current_line.is_empty() {
15310 wrapped_text.push_str(¤t_line);
15311 }
15312 wrapped_text
15313}
15314
15315#[test]
15316fn test_wrap_with_prefix() {
15317 assert_eq!(
15318 wrap_with_prefix(
15319 "# ".to_string(),
15320 "abcdefg".to_string(),
15321 4,
15322 NonZeroU32::new(4).unwrap()
15323 ),
15324 "# abcdefg"
15325 );
15326 assert_eq!(
15327 wrap_with_prefix(
15328 "".to_string(),
15329 "\thello world".to_string(),
15330 8,
15331 NonZeroU32::new(4).unwrap()
15332 ),
15333 "hello\nworld"
15334 );
15335 assert_eq!(
15336 wrap_with_prefix(
15337 "// ".to_string(),
15338 "xx \nyy zz aa bb cc".to_string(),
15339 12,
15340 NonZeroU32::new(4).unwrap()
15341 ),
15342 "// xx yy zz\n// aa bb cc"
15343 );
15344 assert_eq!(
15345 wrap_with_prefix(
15346 String::new(),
15347 "这是什么 \n 钢笔".to_string(),
15348 3,
15349 NonZeroU32::new(4).unwrap()
15350 ),
15351 "这是什\n么 钢\n笔"
15352 );
15353}
15354
15355pub trait CollaborationHub {
15356 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15357 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15358 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15359}
15360
15361impl CollaborationHub for Entity<Project> {
15362 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15363 self.read(cx).collaborators()
15364 }
15365
15366 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15367 self.read(cx).user_store().read(cx).participant_indices()
15368 }
15369
15370 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15371 let this = self.read(cx);
15372 let user_ids = this.collaborators().values().map(|c| c.user_id);
15373 this.user_store().read_with(cx, |user_store, cx| {
15374 user_store.participant_names(user_ids, cx)
15375 })
15376 }
15377}
15378
15379pub trait SemanticsProvider {
15380 fn hover(
15381 &self,
15382 buffer: &Entity<Buffer>,
15383 position: text::Anchor,
15384 cx: &mut App,
15385 ) -> Option<Task<Vec<project::Hover>>>;
15386
15387 fn inlay_hints(
15388 &self,
15389 buffer_handle: Entity<Buffer>,
15390 range: Range<text::Anchor>,
15391 cx: &mut App,
15392 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15393
15394 fn resolve_inlay_hint(
15395 &self,
15396 hint: InlayHint,
15397 buffer_handle: Entity<Buffer>,
15398 server_id: LanguageServerId,
15399 cx: &mut App,
15400 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15401
15402 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15403
15404 fn document_highlights(
15405 &self,
15406 buffer: &Entity<Buffer>,
15407 position: text::Anchor,
15408 cx: &mut App,
15409 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15410
15411 fn definitions(
15412 &self,
15413 buffer: &Entity<Buffer>,
15414 position: text::Anchor,
15415 kind: GotoDefinitionKind,
15416 cx: &mut App,
15417 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15418
15419 fn range_for_rename(
15420 &self,
15421 buffer: &Entity<Buffer>,
15422 position: text::Anchor,
15423 cx: &mut App,
15424 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15425
15426 fn perform_rename(
15427 &self,
15428 buffer: &Entity<Buffer>,
15429 position: text::Anchor,
15430 new_name: String,
15431 cx: &mut App,
15432 ) -> Option<Task<Result<ProjectTransaction>>>;
15433}
15434
15435pub trait CompletionProvider {
15436 fn completions(
15437 &self,
15438 buffer: &Entity<Buffer>,
15439 buffer_position: text::Anchor,
15440 trigger: CompletionContext,
15441 window: &mut Window,
15442 cx: &mut Context<Editor>,
15443 ) -> Task<Result<Vec<Completion>>>;
15444
15445 fn resolve_completions(
15446 &self,
15447 buffer: Entity<Buffer>,
15448 completion_indices: Vec<usize>,
15449 completions: Rc<RefCell<Box<[Completion]>>>,
15450 cx: &mut Context<Editor>,
15451 ) -> Task<Result<bool>>;
15452
15453 fn apply_additional_edits_for_completion(
15454 &self,
15455 _buffer: Entity<Buffer>,
15456 _completions: Rc<RefCell<Box<[Completion]>>>,
15457 _completion_index: usize,
15458 _push_to_history: bool,
15459 _cx: &mut Context<Editor>,
15460 ) -> Task<Result<Option<language::Transaction>>> {
15461 Task::ready(Ok(None))
15462 }
15463
15464 fn is_completion_trigger(
15465 &self,
15466 buffer: &Entity<Buffer>,
15467 position: language::Anchor,
15468 text: &str,
15469 trigger_in_words: bool,
15470 cx: &mut Context<Editor>,
15471 ) -> bool;
15472
15473 fn sort_completions(&self) -> bool {
15474 true
15475 }
15476}
15477
15478pub trait CodeActionProvider {
15479 fn id(&self) -> Arc<str>;
15480
15481 fn code_actions(
15482 &self,
15483 buffer: &Entity<Buffer>,
15484 range: Range<text::Anchor>,
15485 window: &mut Window,
15486 cx: &mut App,
15487 ) -> Task<Result<Vec<CodeAction>>>;
15488
15489 fn apply_code_action(
15490 &self,
15491 buffer_handle: Entity<Buffer>,
15492 action: CodeAction,
15493 excerpt_id: ExcerptId,
15494 push_to_history: bool,
15495 window: &mut Window,
15496 cx: &mut App,
15497 ) -> Task<Result<ProjectTransaction>>;
15498}
15499
15500impl CodeActionProvider for Entity<Project> {
15501 fn id(&self) -> Arc<str> {
15502 "project".into()
15503 }
15504
15505 fn code_actions(
15506 &self,
15507 buffer: &Entity<Buffer>,
15508 range: Range<text::Anchor>,
15509 _window: &mut Window,
15510 cx: &mut App,
15511 ) -> Task<Result<Vec<CodeAction>>> {
15512 self.update(cx, |project, cx| {
15513 project.code_actions(buffer, range, None, cx)
15514 })
15515 }
15516
15517 fn apply_code_action(
15518 &self,
15519 buffer_handle: Entity<Buffer>,
15520 action: CodeAction,
15521 _excerpt_id: ExcerptId,
15522 push_to_history: bool,
15523 _window: &mut Window,
15524 cx: &mut App,
15525 ) -> Task<Result<ProjectTransaction>> {
15526 self.update(cx, |project, cx| {
15527 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15528 })
15529 }
15530}
15531
15532fn snippet_completions(
15533 project: &Project,
15534 buffer: &Entity<Buffer>,
15535 buffer_position: text::Anchor,
15536 cx: &mut App,
15537) -> Task<Result<Vec<Completion>>> {
15538 let language = buffer.read(cx).language_at(buffer_position);
15539 let language_name = language.as_ref().map(|language| language.lsp_id());
15540 let snippet_store = project.snippets().read(cx);
15541 let snippets = snippet_store.snippets_for(language_name, cx);
15542
15543 if snippets.is_empty() {
15544 return Task::ready(Ok(vec![]));
15545 }
15546 let snapshot = buffer.read(cx).text_snapshot();
15547 let chars: String = snapshot
15548 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15549 .collect();
15550
15551 let scope = language.map(|language| language.default_scope());
15552 let executor = cx.background_executor().clone();
15553
15554 cx.background_spawn(async move {
15555 let classifier = CharClassifier::new(scope).for_completion(true);
15556 let mut last_word = chars
15557 .chars()
15558 .take_while(|c| classifier.is_word(*c))
15559 .collect::<String>();
15560 last_word = last_word.chars().rev().collect();
15561
15562 if last_word.is_empty() {
15563 return Ok(vec![]);
15564 }
15565
15566 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15567 let to_lsp = |point: &text::Anchor| {
15568 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15569 point_to_lsp(end)
15570 };
15571 let lsp_end = to_lsp(&buffer_position);
15572
15573 let candidates = snippets
15574 .iter()
15575 .enumerate()
15576 .flat_map(|(ix, snippet)| {
15577 snippet
15578 .prefix
15579 .iter()
15580 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15581 })
15582 .collect::<Vec<StringMatchCandidate>>();
15583
15584 let mut matches = fuzzy::match_strings(
15585 &candidates,
15586 &last_word,
15587 last_word.chars().any(|c| c.is_uppercase()),
15588 100,
15589 &Default::default(),
15590 executor,
15591 )
15592 .await;
15593
15594 // Remove all candidates where the query's start does not match the start of any word in the candidate
15595 if let Some(query_start) = last_word.chars().next() {
15596 matches.retain(|string_match| {
15597 split_words(&string_match.string).any(|word| {
15598 // Check that the first codepoint of the word as lowercase matches the first
15599 // codepoint of the query as lowercase
15600 word.chars()
15601 .flat_map(|codepoint| codepoint.to_lowercase())
15602 .zip(query_start.to_lowercase())
15603 .all(|(word_cp, query_cp)| word_cp == query_cp)
15604 })
15605 });
15606 }
15607
15608 let matched_strings = matches
15609 .into_iter()
15610 .map(|m| m.string)
15611 .collect::<HashSet<_>>();
15612
15613 let result: Vec<Completion> = snippets
15614 .into_iter()
15615 .filter_map(|snippet| {
15616 let matching_prefix = snippet
15617 .prefix
15618 .iter()
15619 .find(|prefix| matched_strings.contains(*prefix))?;
15620 let start = as_offset - last_word.len();
15621 let start = snapshot.anchor_before(start);
15622 let range = start..buffer_position;
15623 let lsp_start = to_lsp(&start);
15624 let lsp_range = lsp::Range {
15625 start: lsp_start,
15626 end: lsp_end,
15627 };
15628 Some(Completion {
15629 old_range: range,
15630 new_text: snippet.body.clone(),
15631 resolved: false,
15632 label: CodeLabel {
15633 text: matching_prefix.clone(),
15634 runs: vec![],
15635 filter_range: 0..matching_prefix.len(),
15636 },
15637 server_id: LanguageServerId(usize::MAX),
15638 documentation: snippet
15639 .description
15640 .clone()
15641 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15642 lsp_completion: lsp::CompletionItem {
15643 label: snippet.prefix.first().unwrap().clone(),
15644 kind: Some(CompletionItemKind::SNIPPET),
15645 label_details: snippet.description.as_ref().map(|description| {
15646 lsp::CompletionItemLabelDetails {
15647 detail: Some(description.clone()),
15648 description: None,
15649 }
15650 }),
15651 insert_text_format: Some(InsertTextFormat::SNIPPET),
15652 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15653 lsp::InsertReplaceEdit {
15654 new_text: snippet.body.clone(),
15655 insert: lsp_range,
15656 replace: lsp_range,
15657 },
15658 )),
15659 filter_text: Some(snippet.body.clone()),
15660 sort_text: Some(char::MAX.to_string()),
15661 ..Default::default()
15662 },
15663 confirm: None,
15664 })
15665 })
15666 .collect();
15667
15668 Ok(result)
15669 })
15670}
15671
15672impl CompletionProvider for Entity<Project> {
15673 fn completions(
15674 &self,
15675 buffer: &Entity<Buffer>,
15676 buffer_position: text::Anchor,
15677 options: CompletionContext,
15678 _window: &mut Window,
15679 cx: &mut Context<Editor>,
15680 ) -> Task<Result<Vec<Completion>>> {
15681 self.update(cx, |project, cx| {
15682 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15683 let project_completions = project.completions(buffer, buffer_position, options, cx);
15684 cx.background_spawn(async move {
15685 let mut completions = project_completions.await?;
15686 let snippets_completions = snippets.await?;
15687 completions.extend(snippets_completions);
15688 Ok(completions)
15689 })
15690 })
15691 }
15692
15693 fn resolve_completions(
15694 &self,
15695 buffer: Entity<Buffer>,
15696 completion_indices: Vec<usize>,
15697 completions: Rc<RefCell<Box<[Completion]>>>,
15698 cx: &mut Context<Editor>,
15699 ) -> Task<Result<bool>> {
15700 self.update(cx, |project, cx| {
15701 project.lsp_store().update(cx, |lsp_store, cx| {
15702 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15703 })
15704 })
15705 }
15706
15707 fn apply_additional_edits_for_completion(
15708 &self,
15709 buffer: Entity<Buffer>,
15710 completions: Rc<RefCell<Box<[Completion]>>>,
15711 completion_index: usize,
15712 push_to_history: bool,
15713 cx: &mut Context<Editor>,
15714 ) -> Task<Result<Option<language::Transaction>>> {
15715 self.update(cx, |project, cx| {
15716 project.lsp_store().update(cx, |lsp_store, cx| {
15717 lsp_store.apply_additional_edits_for_completion(
15718 buffer,
15719 completions,
15720 completion_index,
15721 push_to_history,
15722 cx,
15723 )
15724 })
15725 })
15726 }
15727
15728 fn is_completion_trigger(
15729 &self,
15730 buffer: &Entity<Buffer>,
15731 position: language::Anchor,
15732 text: &str,
15733 trigger_in_words: bool,
15734 cx: &mut Context<Editor>,
15735 ) -> bool {
15736 let mut chars = text.chars();
15737 let char = if let Some(char) = chars.next() {
15738 char
15739 } else {
15740 return false;
15741 };
15742 if chars.next().is_some() {
15743 return false;
15744 }
15745
15746 let buffer = buffer.read(cx);
15747 let snapshot = buffer.snapshot();
15748 if !snapshot.settings_at(position, cx).show_completions_on_input {
15749 return false;
15750 }
15751 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15752 if trigger_in_words && classifier.is_word(char) {
15753 return true;
15754 }
15755
15756 buffer.completion_triggers().contains(text)
15757 }
15758}
15759
15760impl SemanticsProvider for Entity<Project> {
15761 fn hover(
15762 &self,
15763 buffer: &Entity<Buffer>,
15764 position: text::Anchor,
15765 cx: &mut App,
15766 ) -> Option<Task<Vec<project::Hover>>> {
15767 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15768 }
15769
15770 fn document_highlights(
15771 &self,
15772 buffer: &Entity<Buffer>,
15773 position: text::Anchor,
15774 cx: &mut App,
15775 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15776 Some(self.update(cx, |project, cx| {
15777 project.document_highlights(buffer, position, cx)
15778 }))
15779 }
15780
15781 fn definitions(
15782 &self,
15783 buffer: &Entity<Buffer>,
15784 position: text::Anchor,
15785 kind: GotoDefinitionKind,
15786 cx: &mut App,
15787 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15788 Some(self.update(cx, |project, cx| match kind {
15789 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15790 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15791 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15792 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15793 }))
15794 }
15795
15796 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15797 // TODO: make this work for remote projects
15798 self.update(cx, |this, cx| {
15799 buffer.update(cx, |buffer, cx| {
15800 this.any_language_server_supports_inlay_hints(buffer, cx)
15801 })
15802 })
15803 }
15804
15805 fn inlay_hints(
15806 &self,
15807 buffer_handle: Entity<Buffer>,
15808 range: Range<text::Anchor>,
15809 cx: &mut App,
15810 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15811 Some(self.update(cx, |project, cx| {
15812 project.inlay_hints(buffer_handle, range, cx)
15813 }))
15814 }
15815
15816 fn resolve_inlay_hint(
15817 &self,
15818 hint: InlayHint,
15819 buffer_handle: Entity<Buffer>,
15820 server_id: LanguageServerId,
15821 cx: &mut App,
15822 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15823 Some(self.update(cx, |project, cx| {
15824 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15825 }))
15826 }
15827
15828 fn range_for_rename(
15829 &self,
15830 buffer: &Entity<Buffer>,
15831 position: text::Anchor,
15832 cx: &mut App,
15833 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15834 Some(self.update(cx, |project, cx| {
15835 let buffer = buffer.clone();
15836 let task = project.prepare_rename(buffer.clone(), position, cx);
15837 cx.spawn(|_, mut cx| async move {
15838 Ok(match task.await? {
15839 PrepareRenameResponse::Success(range) => Some(range),
15840 PrepareRenameResponse::InvalidPosition => None,
15841 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15842 // Fallback on using TreeSitter info to determine identifier range
15843 buffer.update(&mut cx, |buffer, _| {
15844 let snapshot = buffer.snapshot();
15845 let (range, kind) = snapshot.surrounding_word(position);
15846 if kind != Some(CharKind::Word) {
15847 return None;
15848 }
15849 Some(
15850 snapshot.anchor_before(range.start)
15851 ..snapshot.anchor_after(range.end),
15852 )
15853 })?
15854 }
15855 })
15856 })
15857 }))
15858 }
15859
15860 fn perform_rename(
15861 &self,
15862 buffer: &Entity<Buffer>,
15863 position: text::Anchor,
15864 new_name: String,
15865 cx: &mut App,
15866 ) -> Option<Task<Result<ProjectTransaction>>> {
15867 Some(self.update(cx, |project, cx| {
15868 project.perform_rename(buffer.clone(), position, new_name, cx)
15869 }))
15870 }
15871}
15872
15873fn inlay_hint_settings(
15874 location: Anchor,
15875 snapshot: &MultiBufferSnapshot,
15876 cx: &mut Context<Editor>,
15877) -> InlayHintSettings {
15878 let file = snapshot.file_at(location);
15879 let language = snapshot.language_at(location).map(|l| l.name());
15880 language_settings(language, file, cx).inlay_hints
15881}
15882
15883fn consume_contiguous_rows(
15884 contiguous_row_selections: &mut Vec<Selection<Point>>,
15885 selection: &Selection<Point>,
15886 display_map: &DisplaySnapshot,
15887 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15888) -> (MultiBufferRow, MultiBufferRow) {
15889 contiguous_row_selections.push(selection.clone());
15890 let start_row = MultiBufferRow(selection.start.row);
15891 let mut end_row = ending_row(selection, display_map);
15892
15893 while let Some(next_selection) = selections.peek() {
15894 if next_selection.start.row <= end_row.0 {
15895 end_row = ending_row(next_selection, display_map);
15896 contiguous_row_selections.push(selections.next().unwrap().clone());
15897 } else {
15898 break;
15899 }
15900 }
15901 (start_row, end_row)
15902}
15903
15904fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15905 if next_selection.end.column > 0 || next_selection.is_empty() {
15906 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15907 } else {
15908 MultiBufferRow(next_selection.end.row)
15909 }
15910}
15911
15912impl EditorSnapshot {
15913 pub fn remote_selections_in_range<'a>(
15914 &'a self,
15915 range: &'a Range<Anchor>,
15916 collaboration_hub: &dyn CollaborationHub,
15917 cx: &'a App,
15918 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15919 let participant_names = collaboration_hub.user_names(cx);
15920 let participant_indices = collaboration_hub.user_participant_indices(cx);
15921 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15922 let collaborators_by_replica_id = collaborators_by_peer_id
15923 .iter()
15924 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15925 .collect::<HashMap<_, _>>();
15926 self.buffer_snapshot
15927 .selections_in_range(range, false)
15928 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15929 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15930 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15931 let user_name = participant_names.get(&collaborator.user_id).cloned();
15932 Some(RemoteSelection {
15933 replica_id,
15934 selection,
15935 cursor_shape,
15936 line_mode,
15937 participant_index,
15938 peer_id: collaborator.peer_id,
15939 user_name,
15940 })
15941 })
15942 }
15943
15944 pub fn hunks_for_ranges(
15945 &self,
15946 ranges: impl Iterator<Item = Range<Point>>,
15947 ) -> Vec<MultiBufferDiffHunk> {
15948 let mut hunks = Vec::new();
15949 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15950 HashMap::default();
15951 for query_range in ranges {
15952 let query_rows =
15953 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15954 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15955 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15956 ) {
15957 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15958 // when the caret is just above or just below the deleted hunk.
15959 let allow_adjacent = hunk.status().is_deleted();
15960 let related_to_selection = if allow_adjacent {
15961 hunk.row_range.overlaps(&query_rows)
15962 || hunk.row_range.start == query_rows.end
15963 || hunk.row_range.end == query_rows.start
15964 } else {
15965 hunk.row_range.overlaps(&query_rows)
15966 };
15967 if related_to_selection {
15968 if !processed_buffer_rows
15969 .entry(hunk.buffer_id)
15970 .or_default()
15971 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15972 {
15973 continue;
15974 }
15975 hunks.push(hunk);
15976 }
15977 }
15978 }
15979
15980 hunks
15981 }
15982
15983 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15984 self.display_snapshot.buffer_snapshot.language_at(position)
15985 }
15986
15987 pub fn is_focused(&self) -> bool {
15988 self.is_focused
15989 }
15990
15991 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15992 self.placeholder_text.as_ref()
15993 }
15994
15995 pub fn scroll_position(&self) -> gpui::Point<f32> {
15996 self.scroll_anchor.scroll_position(&self.display_snapshot)
15997 }
15998
15999 fn gutter_dimensions(
16000 &self,
16001 font_id: FontId,
16002 font_size: Pixels,
16003 max_line_number_width: Pixels,
16004 cx: &App,
16005 ) -> Option<GutterDimensions> {
16006 if !self.show_gutter {
16007 return None;
16008 }
16009
16010 let descent = cx.text_system().descent(font_id, font_size);
16011 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16012 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16013
16014 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16015 matches!(
16016 ProjectSettings::get_global(cx).git.git_gutter,
16017 Some(GitGutterSetting::TrackedFiles)
16018 )
16019 });
16020 let gutter_settings = EditorSettings::get_global(cx).gutter;
16021 let show_line_numbers = self
16022 .show_line_numbers
16023 .unwrap_or(gutter_settings.line_numbers);
16024 let line_gutter_width = if show_line_numbers {
16025 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16026 let min_width_for_number_on_gutter = em_advance * 4.0;
16027 max_line_number_width.max(min_width_for_number_on_gutter)
16028 } else {
16029 0.0.into()
16030 };
16031
16032 let show_code_actions = self
16033 .show_code_actions
16034 .unwrap_or(gutter_settings.code_actions);
16035
16036 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16037
16038 let git_blame_entries_width =
16039 self.git_blame_gutter_max_author_length
16040 .map(|max_author_length| {
16041 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16042
16043 /// The number of characters to dedicate to gaps and margins.
16044 const SPACING_WIDTH: usize = 4;
16045
16046 let max_char_count = max_author_length
16047 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16048 + ::git::SHORT_SHA_LENGTH
16049 + MAX_RELATIVE_TIMESTAMP.len()
16050 + SPACING_WIDTH;
16051
16052 em_advance * max_char_count
16053 });
16054
16055 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16056 left_padding += if show_code_actions || show_runnables {
16057 em_width * 3.0
16058 } else if show_git_gutter && show_line_numbers {
16059 em_width * 2.0
16060 } else if show_git_gutter || show_line_numbers {
16061 em_width
16062 } else {
16063 px(0.)
16064 };
16065
16066 let right_padding = if gutter_settings.folds && show_line_numbers {
16067 em_width * 4.0
16068 } else if gutter_settings.folds {
16069 em_width * 3.0
16070 } else if show_line_numbers {
16071 em_width
16072 } else {
16073 px(0.)
16074 };
16075
16076 Some(GutterDimensions {
16077 left_padding,
16078 right_padding,
16079 width: line_gutter_width + left_padding + right_padding,
16080 margin: -descent,
16081 git_blame_entries_width,
16082 })
16083 }
16084
16085 pub fn render_crease_toggle(
16086 &self,
16087 buffer_row: MultiBufferRow,
16088 row_contains_cursor: bool,
16089 editor: Entity<Editor>,
16090 window: &mut Window,
16091 cx: &mut App,
16092 ) -> Option<AnyElement> {
16093 let folded = self.is_line_folded(buffer_row);
16094 let mut is_foldable = false;
16095
16096 if let Some(crease) = self
16097 .crease_snapshot
16098 .query_row(buffer_row, &self.buffer_snapshot)
16099 {
16100 is_foldable = true;
16101 match crease {
16102 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16103 if let Some(render_toggle) = render_toggle {
16104 let toggle_callback =
16105 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16106 if folded {
16107 editor.update(cx, |editor, cx| {
16108 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16109 });
16110 } else {
16111 editor.update(cx, |editor, cx| {
16112 editor.unfold_at(
16113 &crate::UnfoldAt { buffer_row },
16114 window,
16115 cx,
16116 )
16117 });
16118 }
16119 });
16120 return Some((render_toggle)(
16121 buffer_row,
16122 folded,
16123 toggle_callback,
16124 window,
16125 cx,
16126 ));
16127 }
16128 }
16129 }
16130 }
16131
16132 is_foldable |= self.starts_indent(buffer_row);
16133
16134 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16135 Some(
16136 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16137 .toggle_state(folded)
16138 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16139 if folded {
16140 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16141 } else {
16142 this.fold_at(&FoldAt { buffer_row }, window, cx);
16143 }
16144 }))
16145 .into_any_element(),
16146 )
16147 } else {
16148 None
16149 }
16150 }
16151
16152 pub fn render_crease_trailer(
16153 &self,
16154 buffer_row: MultiBufferRow,
16155 window: &mut Window,
16156 cx: &mut App,
16157 ) -> Option<AnyElement> {
16158 let folded = self.is_line_folded(buffer_row);
16159 if let Crease::Inline { render_trailer, .. } = self
16160 .crease_snapshot
16161 .query_row(buffer_row, &self.buffer_snapshot)?
16162 {
16163 let render_trailer = render_trailer.as_ref()?;
16164 Some(render_trailer(buffer_row, folded, window, cx))
16165 } else {
16166 None
16167 }
16168 }
16169}
16170
16171impl Deref for EditorSnapshot {
16172 type Target = DisplaySnapshot;
16173
16174 fn deref(&self) -> &Self::Target {
16175 &self.display_snapshot
16176 }
16177}
16178
16179#[derive(Clone, Debug, PartialEq, Eq)]
16180pub enum EditorEvent {
16181 InputIgnored {
16182 text: Arc<str>,
16183 },
16184 InputHandled {
16185 utf16_range_to_replace: Option<Range<isize>>,
16186 text: Arc<str>,
16187 },
16188 ExcerptsAdded {
16189 buffer: Entity<Buffer>,
16190 predecessor: ExcerptId,
16191 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16192 },
16193 ExcerptsRemoved {
16194 ids: Vec<ExcerptId>,
16195 },
16196 BufferFoldToggled {
16197 ids: Vec<ExcerptId>,
16198 folded: bool,
16199 },
16200 ExcerptsEdited {
16201 ids: Vec<ExcerptId>,
16202 },
16203 ExcerptsExpanded {
16204 ids: Vec<ExcerptId>,
16205 },
16206 BufferEdited,
16207 Edited {
16208 transaction_id: clock::Lamport,
16209 },
16210 Reparsed(BufferId),
16211 Focused,
16212 FocusedIn,
16213 Blurred,
16214 DirtyChanged,
16215 Saved,
16216 TitleChanged,
16217 DiffBaseChanged,
16218 SelectionsChanged {
16219 local: bool,
16220 },
16221 ScrollPositionChanged {
16222 local: bool,
16223 autoscroll: bool,
16224 },
16225 Closed,
16226 TransactionUndone {
16227 transaction_id: clock::Lamport,
16228 },
16229 TransactionBegun {
16230 transaction_id: clock::Lamport,
16231 },
16232 Reloaded,
16233 CursorShapeChanged,
16234}
16235
16236impl EventEmitter<EditorEvent> for Editor {}
16237
16238impl Focusable for Editor {
16239 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16240 self.focus_handle.clone()
16241 }
16242}
16243
16244impl Render for Editor {
16245 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16246 let settings = ThemeSettings::get_global(cx);
16247
16248 let mut text_style = match self.mode {
16249 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16250 color: cx.theme().colors().editor_foreground,
16251 font_family: settings.ui_font.family.clone(),
16252 font_features: settings.ui_font.features.clone(),
16253 font_fallbacks: settings.ui_font.fallbacks.clone(),
16254 font_size: rems(0.875).into(),
16255 font_weight: settings.ui_font.weight,
16256 line_height: relative(settings.buffer_line_height.value()),
16257 ..Default::default()
16258 },
16259 EditorMode::Full => TextStyle {
16260 color: cx.theme().colors().editor_foreground,
16261 font_family: settings.buffer_font.family.clone(),
16262 font_features: settings.buffer_font.features.clone(),
16263 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16264 font_size: settings.buffer_font_size(cx).into(),
16265 font_weight: settings.buffer_font.weight,
16266 line_height: relative(settings.buffer_line_height.value()),
16267 ..Default::default()
16268 },
16269 };
16270 if let Some(text_style_refinement) = &self.text_style_refinement {
16271 text_style.refine(text_style_refinement)
16272 }
16273
16274 let background = match self.mode {
16275 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16276 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16277 EditorMode::Full => cx.theme().colors().editor_background,
16278 };
16279
16280 EditorElement::new(
16281 &cx.entity(),
16282 EditorStyle {
16283 background,
16284 local_player: cx.theme().players().local(),
16285 text: text_style,
16286 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16287 syntax: cx.theme().syntax().clone(),
16288 status: cx.theme().status().clone(),
16289 inlay_hints_style: make_inlay_hints_style(cx),
16290 inline_completion_styles: make_suggestion_styles(cx),
16291 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16292 },
16293 )
16294 }
16295}
16296
16297impl EntityInputHandler for Editor {
16298 fn text_for_range(
16299 &mut self,
16300 range_utf16: Range<usize>,
16301 adjusted_range: &mut Option<Range<usize>>,
16302 _: &mut Window,
16303 cx: &mut Context<Self>,
16304 ) -> Option<String> {
16305 let snapshot = self.buffer.read(cx).read(cx);
16306 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16307 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16308 if (start.0..end.0) != range_utf16 {
16309 adjusted_range.replace(start.0..end.0);
16310 }
16311 Some(snapshot.text_for_range(start..end).collect())
16312 }
16313
16314 fn selected_text_range(
16315 &mut self,
16316 ignore_disabled_input: bool,
16317 _: &mut Window,
16318 cx: &mut Context<Self>,
16319 ) -> Option<UTF16Selection> {
16320 // Prevent the IME menu from appearing when holding down an alphabetic key
16321 // while input is disabled.
16322 if !ignore_disabled_input && !self.input_enabled {
16323 return None;
16324 }
16325
16326 let selection = self.selections.newest::<OffsetUtf16>(cx);
16327 let range = selection.range();
16328
16329 Some(UTF16Selection {
16330 range: range.start.0..range.end.0,
16331 reversed: selection.reversed,
16332 })
16333 }
16334
16335 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16336 let snapshot = self.buffer.read(cx).read(cx);
16337 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16338 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16339 }
16340
16341 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16342 self.clear_highlights::<InputComposition>(cx);
16343 self.ime_transaction.take();
16344 }
16345
16346 fn replace_text_in_range(
16347 &mut self,
16348 range_utf16: Option<Range<usize>>,
16349 text: &str,
16350 window: &mut Window,
16351 cx: &mut Context<Self>,
16352 ) {
16353 if !self.input_enabled {
16354 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16355 return;
16356 }
16357
16358 self.transact(window, cx, |this, window, cx| {
16359 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16360 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16361 Some(this.selection_replacement_ranges(range_utf16, cx))
16362 } else {
16363 this.marked_text_ranges(cx)
16364 };
16365
16366 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16367 let newest_selection_id = this.selections.newest_anchor().id;
16368 this.selections
16369 .all::<OffsetUtf16>(cx)
16370 .iter()
16371 .zip(ranges_to_replace.iter())
16372 .find_map(|(selection, range)| {
16373 if selection.id == newest_selection_id {
16374 Some(
16375 (range.start.0 as isize - selection.head().0 as isize)
16376 ..(range.end.0 as isize - selection.head().0 as isize),
16377 )
16378 } else {
16379 None
16380 }
16381 })
16382 });
16383
16384 cx.emit(EditorEvent::InputHandled {
16385 utf16_range_to_replace: range_to_replace,
16386 text: text.into(),
16387 });
16388
16389 if let Some(new_selected_ranges) = new_selected_ranges {
16390 this.change_selections(None, window, cx, |selections| {
16391 selections.select_ranges(new_selected_ranges)
16392 });
16393 this.backspace(&Default::default(), window, cx);
16394 }
16395
16396 this.handle_input(text, window, cx);
16397 });
16398
16399 if let Some(transaction) = self.ime_transaction {
16400 self.buffer.update(cx, |buffer, cx| {
16401 buffer.group_until_transaction(transaction, cx);
16402 });
16403 }
16404
16405 self.unmark_text(window, cx);
16406 }
16407
16408 fn replace_and_mark_text_in_range(
16409 &mut self,
16410 range_utf16: Option<Range<usize>>,
16411 text: &str,
16412 new_selected_range_utf16: Option<Range<usize>>,
16413 window: &mut Window,
16414 cx: &mut Context<Self>,
16415 ) {
16416 if !self.input_enabled {
16417 return;
16418 }
16419
16420 let transaction = self.transact(window, cx, |this, window, cx| {
16421 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16422 let snapshot = this.buffer.read(cx).read(cx);
16423 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16424 for marked_range in &mut marked_ranges {
16425 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16426 marked_range.start.0 += relative_range_utf16.start;
16427 marked_range.start =
16428 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16429 marked_range.end =
16430 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16431 }
16432 }
16433 Some(marked_ranges)
16434 } else if let Some(range_utf16) = range_utf16 {
16435 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16436 Some(this.selection_replacement_ranges(range_utf16, cx))
16437 } else {
16438 None
16439 };
16440
16441 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16442 let newest_selection_id = this.selections.newest_anchor().id;
16443 this.selections
16444 .all::<OffsetUtf16>(cx)
16445 .iter()
16446 .zip(ranges_to_replace.iter())
16447 .find_map(|(selection, range)| {
16448 if selection.id == newest_selection_id {
16449 Some(
16450 (range.start.0 as isize - selection.head().0 as isize)
16451 ..(range.end.0 as isize - selection.head().0 as isize),
16452 )
16453 } else {
16454 None
16455 }
16456 })
16457 });
16458
16459 cx.emit(EditorEvent::InputHandled {
16460 utf16_range_to_replace: range_to_replace,
16461 text: text.into(),
16462 });
16463
16464 if let Some(ranges) = ranges_to_replace {
16465 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16466 }
16467
16468 let marked_ranges = {
16469 let snapshot = this.buffer.read(cx).read(cx);
16470 this.selections
16471 .disjoint_anchors()
16472 .iter()
16473 .map(|selection| {
16474 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16475 })
16476 .collect::<Vec<_>>()
16477 };
16478
16479 if text.is_empty() {
16480 this.unmark_text(window, cx);
16481 } else {
16482 this.highlight_text::<InputComposition>(
16483 marked_ranges.clone(),
16484 HighlightStyle {
16485 underline: Some(UnderlineStyle {
16486 thickness: px(1.),
16487 color: None,
16488 wavy: false,
16489 }),
16490 ..Default::default()
16491 },
16492 cx,
16493 );
16494 }
16495
16496 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16497 let use_autoclose = this.use_autoclose;
16498 let use_auto_surround = this.use_auto_surround;
16499 this.set_use_autoclose(false);
16500 this.set_use_auto_surround(false);
16501 this.handle_input(text, window, cx);
16502 this.set_use_autoclose(use_autoclose);
16503 this.set_use_auto_surround(use_auto_surround);
16504
16505 if let Some(new_selected_range) = new_selected_range_utf16 {
16506 let snapshot = this.buffer.read(cx).read(cx);
16507 let new_selected_ranges = marked_ranges
16508 .into_iter()
16509 .map(|marked_range| {
16510 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16511 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16512 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16513 snapshot.clip_offset_utf16(new_start, Bias::Left)
16514 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16515 })
16516 .collect::<Vec<_>>();
16517
16518 drop(snapshot);
16519 this.change_selections(None, window, cx, |selections| {
16520 selections.select_ranges(new_selected_ranges)
16521 });
16522 }
16523 });
16524
16525 self.ime_transaction = self.ime_transaction.or(transaction);
16526 if let Some(transaction) = self.ime_transaction {
16527 self.buffer.update(cx, |buffer, cx| {
16528 buffer.group_until_transaction(transaction, cx);
16529 });
16530 }
16531
16532 if self.text_highlights::<InputComposition>(cx).is_none() {
16533 self.ime_transaction.take();
16534 }
16535 }
16536
16537 fn bounds_for_range(
16538 &mut self,
16539 range_utf16: Range<usize>,
16540 element_bounds: gpui::Bounds<Pixels>,
16541 window: &mut Window,
16542 cx: &mut Context<Self>,
16543 ) -> Option<gpui::Bounds<Pixels>> {
16544 let text_layout_details = self.text_layout_details(window);
16545 let gpui::Size {
16546 width: em_width,
16547 height: line_height,
16548 } = self.character_size(window);
16549
16550 let snapshot = self.snapshot(window, cx);
16551 let scroll_position = snapshot.scroll_position();
16552 let scroll_left = scroll_position.x * em_width;
16553
16554 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16555 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16556 + self.gutter_dimensions.width
16557 + self.gutter_dimensions.margin;
16558 let y = line_height * (start.row().as_f32() - scroll_position.y);
16559
16560 Some(Bounds {
16561 origin: element_bounds.origin + point(x, y),
16562 size: size(em_width, line_height),
16563 })
16564 }
16565
16566 fn character_index_for_point(
16567 &mut self,
16568 point: gpui::Point<Pixels>,
16569 _window: &mut Window,
16570 _cx: &mut Context<Self>,
16571 ) -> Option<usize> {
16572 let position_map = self.last_position_map.as_ref()?;
16573 if !position_map.text_hitbox.contains(&point) {
16574 return None;
16575 }
16576 let display_point = position_map.point_for_position(point).previous_valid;
16577 let anchor = position_map
16578 .snapshot
16579 .display_point_to_anchor(display_point, Bias::Left);
16580 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16581 Some(utf16_offset.0)
16582 }
16583}
16584
16585trait SelectionExt {
16586 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16587 fn spanned_rows(
16588 &self,
16589 include_end_if_at_line_start: bool,
16590 map: &DisplaySnapshot,
16591 ) -> Range<MultiBufferRow>;
16592}
16593
16594impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16595 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16596 let start = self
16597 .start
16598 .to_point(&map.buffer_snapshot)
16599 .to_display_point(map);
16600 let end = self
16601 .end
16602 .to_point(&map.buffer_snapshot)
16603 .to_display_point(map);
16604 if self.reversed {
16605 end..start
16606 } else {
16607 start..end
16608 }
16609 }
16610
16611 fn spanned_rows(
16612 &self,
16613 include_end_if_at_line_start: bool,
16614 map: &DisplaySnapshot,
16615 ) -> Range<MultiBufferRow> {
16616 let start = self.start.to_point(&map.buffer_snapshot);
16617 let mut end = self.end.to_point(&map.buffer_snapshot);
16618 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16619 end.row -= 1;
16620 }
16621
16622 let buffer_start = map.prev_line_boundary(start).0;
16623 let buffer_end = map.next_line_boundary(end).0;
16624 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16625 }
16626}
16627
16628impl<T: InvalidationRegion> InvalidationStack<T> {
16629 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16630 where
16631 S: Clone + ToOffset,
16632 {
16633 while let Some(region) = self.last() {
16634 let all_selections_inside_invalidation_ranges =
16635 if selections.len() == region.ranges().len() {
16636 selections
16637 .iter()
16638 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16639 .all(|(selection, invalidation_range)| {
16640 let head = selection.head().to_offset(buffer);
16641 invalidation_range.start <= head && invalidation_range.end >= head
16642 })
16643 } else {
16644 false
16645 };
16646
16647 if all_selections_inside_invalidation_ranges {
16648 break;
16649 } else {
16650 self.pop();
16651 }
16652 }
16653 }
16654}
16655
16656impl<T> Default for InvalidationStack<T> {
16657 fn default() -> Self {
16658 Self(Default::default())
16659 }
16660}
16661
16662impl<T> Deref for InvalidationStack<T> {
16663 type Target = Vec<T>;
16664
16665 fn deref(&self) -> &Self::Target {
16666 &self.0
16667 }
16668}
16669
16670impl<T> DerefMut for InvalidationStack<T> {
16671 fn deref_mut(&mut self) -> &mut Self::Target {
16672 &mut self.0
16673 }
16674}
16675
16676impl InvalidationRegion for SnippetState {
16677 fn ranges(&self) -> &[Range<Anchor>] {
16678 &self.ranges[self.active_index]
16679 }
16680}
16681
16682pub fn diagnostic_block_renderer(
16683 diagnostic: Diagnostic,
16684 max_message_rows: Option<u8>,
16685 allow_closing: bool,
16686 _is_valid: bool,
16687) -> RenderBlock {
16688 let (text_without_backticks, code_ranges) =
16689 highlight_diagnostic_message(&diagnostic, max_message_rows);
16690
16691 Arc::new(move |cx: &mut BlockContext| {
16692 let group_id: SharedString = cx.block_id.to_string().into();
16693
16694 let mut text_style = cx.window.text_style().clone();
16695 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16696 let theme_settings = ThemeSettings::get_global(cx);
16697 text_style.font_family = theme_settings.buffer_font.family.clone();
16698 text_style.font_style = theme_settings.buffer_font.style;
16699 text_style.font_features = theme_settings.buffer_font.features.clone();
16700 text_style.font_weight = theme_settings.buffer_font.weight;
16701
16702 let multi_line_diagnostic = diagnostic.message.contains('\n');
16703
16704 let buttons = |diagnostic: &Diagnostic| {
16705 if multi_line_diagnostic {
16706 v_flex()
16707 } else {
16708 h_flex()
16709 }
16710 .when(allow_closing, |div| {
16711 div.children(diagnostic.is_primary.then(|| {
16712 IconButton::new("close-block", IconName::XCircle)
16713 .icon_color(Color::Muted)
16714 .size(ButtonSize::Compact)
16715 .style(ButtonStyle::Transparent)
16716 .visible_on_hover(group_id.clone())
16717 .on_click(move |_click, window, cx| {
16718 window.dispatch_action(Box::new(Cancel), cx)
16719 })
16720 .tooltip(|window, cx| {
16721 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16722 })
16723 }))
16724 })
16725 .child(
16726 IconButton::new("copy-block", IconName::Copy)
16727 .icon_color(Color::Muted)
16728 .size(ButtonSize::Compact)
16729 .style(ButtonStyle::Transparent)
16730 .visible_on_hover(group_id.clone())
16731 .on_click({
16732 let message = diagnostic.message.clone();
16733 move |_click, _, cx| {
16734 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16735 }
16736 })
16737 .tooltip(Tooltip::text("Copy diagnostic message")),
16738 )
16739 };
16740
16741 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16742 AvailableSpace::min_size(),
16743 cx.window,
16744 cx.app,
16745 );
16746
16747 h_flex()
16748 .id(cx.block_id)
16749 .group(group_id.clone())
16750 .relative()
16751 .size_full()
16752 .block_mouse_down()
16753 .pl(cx.gutter_dimensions.width)
16754 .w(cx.max_width - cx.gutter_dimensions.full_width())
16755 .child(
16756 div()
16757 .flex()
16758 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16759 .flex_shrink(),
16760 )
16761 .child(buttons(&diagnostic))
16762 .child(div().flex().flex_shrink_0().child(
16763 StyledText::new(text_without_backticks.clone()).with_highlights(
16764 &text_style,
16765 code_ranges.iter().map(|range| {
16766 (
16767 range.clone(),
16768 HighlightStyle {
16769 font_weight: Some(FontWeight::BOLD),
16770 ..Default::default()
16771 },
16772 )
16773 }),
16774 ),
16775 ))
16776 .into_any_element()
16777 })
16778}
16779
16780fn inline_completion_edit_text(
16781 current_snapshot: &BufferSnapshot,
16782 edits: &[(Range<Anchor>, String)],
16783 edit_preview: &EditPreview,
16784 include_deletions: bool,
16785 cx: &App,
16786) -> HighlightedText {
16787 let edits = edits
16788 .iter()
16789 .map(|(anchor, text)| {
16790 (
16791 anchor.start.text_anchor..anchor.end.text_anchor,
16792 text.clone(),
16793 )
16794 })
16795 .collect::<Vec<_>>();
16796
16797 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16798}
16799
16800pub fn highlight_diagnostic_message(
16801 diagnostic: &Diagnostic,
16802 mut max_message_rows: Option<u8>,
16803) -> (SharedString, Vec<Range<usize>>) {
16804 let mut text_without_backticks = String::new();
16805 let mut code_ranges = Vec::new();
16806
16807 if let Some(source) = &diagnostic.source {
16808 text_without_backticks.push_str(source);
16809 code_ranges.push(0..source.len());
16810 text_without_backticks.push_str(": ");
16811 }
16812
16813 let mut prev_offset = 0;
16814 let mut in_code_block = false;
16815 let has_row_limit = max_message_rows.is_some();
16816 let mut newline_indices = diagnostic
16817 .message
16818 .match_indices('\n')
16819 .filter(|_| has_row_limit)
16820 .map(|(ix, _)| ix)
16821 .fuse()
16822 .peekable();
16823
16824 for (quote_ix, _) in diagnostic
16825 .message
16826 .match_indices('`')
16827 .chain([(diagnostic.message.len(), "")])
16828 {
16829 let mut first_newline_ix = None;
16830 let mut last_newline_ix = None;
16831 while let Some(newline_ix) = newline_indices.peek() {
16832 if *newline_ix < quote_ix {
16833 if first_newline_ix.is_none() {
16834 first_newline_ix = Some(*newline_ix);
16835 }
16836 last_newline_ix = Some(*newline_ix);
16837
16838 if let Some(rows_left) = &mut max_message_rows {
16839 if *rows_left == 0 {
16840 break;
16841 } else {
16842 *rows_left -= 1;
16843 }
16844 }
16845 let _ = newline_indices.next();
16846 } else {
16847 break;
16848 }
16849 }
16850 let prev_len = text_without_backticks.len();
16851 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16852 text_without_backticks.push_str(new_text);
16853 if in_code_block {
16854 code_ranges.push(prev_len..text_without_backticks.len());
16855 }
16856 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16857 in_code_block = !in_code_block;
16858 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16859 text_without_backticks.push_str("...");
16860 break;
16861 }
16862 }
16863
16864 (text_without_backticks.into(), code_ranges)
16865}
16866
16867fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16868 match severity {
16869 DiagnosticSeverity::ERROR => colors.error,
16870 DiagnosticSeverity::WARNING => colors.warning,
16871 DiagnosticSeverity::INFORMATION => colors.info,
16872 DiagnosticSeverity::HINT => colors.info,
16873 _ => colors.ignored,
16874 }
16875}
16876
16877pub fn styled_runs_for_code_label<'a>(
16878 label: &'a CodeLabel,
16879 syntax_theme: &'a theme::SyntaxTheme,
16880) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16881 let fade_out = HighlightStyle {
16882 fade_out: Some(0.35),
16883 ..Default::default()
16884 };
16885
16886 let mut prev_end = label.filter_range.end;
16887 label
16888 .runs
16889 .iter()
16890 .enumerate()
16891 .flat_map(move |(ix, (range, highlight_id))| {
16892 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16893 style
16894 } else {
16895 return Default::default();
16896 };
16897 let mut muted_style = style;
16898 muted_style.highlight(fade_out);
16899
16900 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16901 if range.start >= label.filter_range.end {
16902 if range.start > prev_end {
16903 runs.push((prev_end..range.start, fade_out));
16904 }
16905 runs.push((range.clone(), muted_style));
16906 } else if range.end <= label.filter_range.end {
16907 runs.push((range.clone(), style));
16908 } else {
16909 runs.push((range.start..label.filter_range.end, style));
16910 runs.push((label.filter_range.end..range.end, muted_style));
16911 }
16912 prev_end = cmp::max(prev_end, range.end);
16913
16914 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16915 runs.push((prev_end..label.text.len(), fade_out));
16916 }
16917
16918 runs
16919 })
16920}
16921
16922pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16923 let mut prev_index = 0;
16924 let mut prev_codepoint: Option<char> = None;
16925 text.char_indices()
16926 .chain([(text.len(), '\0')])
16927 .filter_map(move |(index, codepoint)| {
16928 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16929 let is_boundary = index == text.len()
16930 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16931 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16932 if is_boundary {
16933 let chunk = &text[prev_index..index];
16934 prev_index = index;
16935 Some(chunk)
16936 } else {
16937 None
16938 }
16939 })
16940}
16941
16942pub trait RangeToAnchorExt: Sized {
16943 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16944
16945 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16946 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16947 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16948 }
16949}
16950
16951impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16952 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16953 let start_offset = self.start.to_offset(snapshot);
16954 let end_offset = self.end.to_offset(snapshot);
16955 if start_offset == end_offset {
16956 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16957 } else {
16958 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16959 }
16960 }
16961}
16962
16963pub trait RowExt {
16964 fn as_f32(&self) -> f32;
16965
16966 fn next_row(&self) -> Self;
16967
16968 fn previous_row(&self) -> Self;
16969
16970 fn minus(&self, other: Self) -> u32;
16971}
16972
16973impl RowExt for DisplayRow {
16974 fn as_f32(&self) -> f32 {
16975 self.0 as f32
16976 }
16977
16978 fn next_row(&self) -> Self {
16979 Self(self.0 + 1)
16980 }
16981
16982 fn previous_row(&self) -> Self {
16983 Self(self.0.saturating_sub(1))
16984 }
16985
16986 fn minus(&self, other: Self) -> u32 {
16987 self.0 - other.0
16988 }
16989}
16990
16991impl RowExt for MultiBufferRow {
16992 fn as_f32(&self) -> f32 {
16993 self.0 as f32
16994 }
16995
16996 fn next_row(&self) -> Self {
16997 Self(self.0 + 1)
16998 }
16999
17000 fn previous_row(&self) -> Self {
17001 Self(self.0.saturating_sub(1))
17002 }
17003
17004 fn minus(&self, other: Self) -> u32 {
17005 self.0 - other.0
17006 }
17007}
17008
17009trait RowRangeExt {
17010 type Row;
17011
17012 fn len(&self) -> usize;
17013
17014 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17015}
17016
17017impl RowRangeExt for Range<MultiBufferRow> {
17018 type Row = MultiBufferRow;
17019
17020 fn len(&self) -> usize {
17021 (self.end.0 - self.start.0) as usize
17022 }
17023
17024 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17025 (self.start.0..self.end.0).map(MultiBufferRow)
17026 }
17027}
17028
17029impl RowRangeExt for Range<DisplayRow> {
17030 type Row = DisplayRow;
17031
17032 fn len(&self) -> usize {
17033 (self.end.0 - self.start.0) as usize
17034 }
17035
17036 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17037 (self.start.0..self.end.0).map(DisplayRow)
17038 }
17039}
17040
17041/// If select range has more than one line, we
17042/// just point the cursor to range.start.
17043fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17044 if range.start.row == range.end.row {
17045 range
17046 } else {
17047 range.start..range.start
17048 }
17049}
17050pub struct KillRing(ClipboardItem);
17051impl Global for KillRing {}
17052
17053const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17054
17055fn all_edits_insertions_or_deletions(
17056 edits: &Vec<(Range<Anchor>, String)>,
17057 snapshot: &MultiBufferSnapshot,
17058) -> bool {
17059 let mut all_insertions = true;
17060 let mut all_deletions = true;
17061
17062 for (range, new_text) in edits.iter() {
17063 let range_is_empty = range.to_offset(&snapshot).is_empty();
17064 let text_is_empty = new_text.is_empty();
17065
17066 if range_is_empty != text_is_empty {
17067 if range_is_empty {
17068 all_deletions = false;
17069 } else {
17070 all_insertions = false;
17071 }
17072 } else {
17073 return false;
17074 }
17075
17076 if !all_insertions && !all_deletions {
17077 return false;
17078 }
17079 }
17080 all_insertions || all_deletions
17081}