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::{self, all_language_settings, language_settings, InlayHintSettings},
101 point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
103 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
104 TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109use persistence::DB;
110pub use proposed_changes_editor::{
111 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
112};
113use similar::{ChangeTag, TextDiff};
114use std::iter::Peekable;
115use task::{ResolvedTask, TaskTemplate, TaskVariables};
116
117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
118pub use lsp::CompletionContext;
119use lsp::{
120 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
121 LanguageServerId, LanguageServerName,
122};
123
124use language::BufferSnapshot;
125use movement::TextLayoutDetails;
126pub use multi_buffer::{
127 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
128 ToOffset, ToPoint,
129};
130use multi_buffer::{
131 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
132 ToOffsetUtf16,
133};
134use project::{
135 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
136 project_settings::{GitGutterSetting, ProjectSettings},
137 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
138 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
139};
140use rand::prelude::*;
141use rpc::{proto::*, ErrorExt};
142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
143use selections_collection::{
144 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
145};
146use serde::{Deserialize, Serialize};
147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
148use smallvec::SmallVec;
149use snippet::Snippet;
150use std::{
151 any::TypeId,
152 borrow::Cow,
153 cell::RefCell,
154 cmp::{self, Ordering, Reverse},
155 mem,
156 num::NonZeroU32,
157 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
158 path::{Path, PathBuf},
159 rc::Rc,
160 sync::Arc,
161 time::{Duration, Instant},
162};
163pub use sum_tree::Bias;
164use sum_tree::TreeMap;
165use text::{BufferId, OffsetUtf16, Rope};
166use theme::{
167 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
168 ThemeColors, ThemeSettings,
169};
170use ui::{
171 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
172 Tooltip,
173};
174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
175use workspace::{
176 item::{ItemHandle, PreviewTabsSettings},
177 ItemId, RestoreOnStartupBehavior,
178};
179use workspace::{
180 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
181 WorkspaceSettings,
182};
183use workspace::{
184 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
185};
186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
187
188use crate::hover_links::{find_url, find_url_from_range};
189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
190
191pub const FILE_HEADER_HEIGHT: u32 = 2;
192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
196const MAX_LINE_LEN: usize = 1024;
197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
200#[doc(hidden)]
201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
202
203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
205
206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
208
209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
210 alt: true,
211 shift: true,
212 control: false,
213 platform: false,
214 function: false,
215};
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
218pub enum InlayId {
219 InlineCompletion(usize),
220 Hint(usize),
221}
222
223impl InlayId {
224 fn id(&self) -> usize {
225 match self {
226 Self::InlineCompletion(id) => *id,
227 Self::Hint(id) => *id,
228 }
229 }
230}
231
232enum DocumentHighlightRead {}
233enum DocumentHighlightWrite {}
234enum InputComposition {}
235enum SelectedTextHighlight {}
236
237#[derive(Debug, Copy, Clone, PartialEq, Eq)]
238pub enum Navigated {
239 Yes,
240 No,
241}
242
243impl Navigated {
244 pub fn from_bool(yes: bool) -> Navigated {
245 if yes {
246 Navigated::Yes
247 } else {
248 Navigated::No
249 }
250 }
251}
252
253pub fn init_settings(cx: &mut App) {
254 EditorSettings::register(cx);
255}
256
257pub fn init(cx: &mut App) {
258 init_settings(cx);
259
260 workspace::register_project_item::<Editor>(cx);
261 workspace::FollowableViewRegistry::register::<Editor>(cx);
262 workspace::register_serializable_item::<Editor>(cx);
263
264 cx.observe_new(
265 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
266 workspace.register_action(Editor::new_file);
267 workspace.register_action(Editor::new_file_vertical);
268 workspace.register_action(Editor::new_file_horizontal);
269 workspace.register_action(Editor::cancel_language_server_work);
270 },
271 )
272 .detach();
273
274 cx.on_action(move |_: &workspace::NewFile, cx| {
275 let app_state = workspace::AppState::global(cx);
276 if let Some(app_state) = app_state.upgrade() {
277 workspace::open_new(
278 Default::default(),
279 app_state,
280 cx,
281 |workspace, window, cx| {
282 Editor::new_file(workspace, &Default::default(), window, cx)
283 },
284 )
285 .detach();
286 }
287 });
288 cx.on_action(move |_: &workspace::NewWindow, cx| {
289 let app_state = workspace::AppState::global(cx);
290 if let Some(app_state) = app_state.upgrade() {
291 workspace::open_new(
292 Default::default(),
293 app_state,
294 cx,
295 |workspace, window, cx| {
296 cx.activate(true);
297 Editor::new_file(workspace, &Default::default(), window, cx)
298 },
299 )
300 .detach();
301 }
302 });
303}
304
305pub struct SearchWithinRange;
306
307trait InvalidationRegion {
308 fn ranges(&self) -> &[Range<Anchor>];
309}
310
311#[derive(Clone, Debug, PartialEq)]
312pub enum SelectPhase {
313 Begin {
314 position: DisplayPoint,
315 add: bool,
316 click_count: usize,
317 },
318 BeginColumnar {
319 position: DisplayPoint,
320 reset: bool,
321 goal_column: u32,
322 },
323 Extend {
324 position: DisplayPoint,
325 click_count: usize,
326 },
327 Update {
328 position: DisplayPoint,
329 goal_column: u32,
330 scroll_delta: gpui::Point<f32>,
331 },
332 End,
333}
334
335#[derive(Clone, Debug)]
336pub enum SelectMode {
337 Character,
338 Word(Range<Anchor>),
339 Line(Range<Anchor>),
340 All,
341}
342
343#[derive(Copy, Clone, PartialEq, Eq, Debug)]
344pub enum EditorMode {
345 SingleLine { auto_width: bool },
346 AutoHeight { max_lines: usize },
347 Full,
348}
349
350#[derive(Copy, Clone, Debug)]
351pub enum SoftWrap {
352 /// Prefer not to wrap at all.
353 ///
354 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
355 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
356 GitDiff,
357 /// Prefer a single line generally, unless an overly long line is encountered.
358 None,
359 /// Soft wrap lines that exceed the editor width.
360 EditorWidth,
361 /// Soft wrap lines at the preferred line length.
362 Column(u32),
363 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
364 Bounded(u32),
365}
366
367#[derive(Clone)]
368pub struct EditorStyle {
369 pub background: Hsla,
370 pub local_player: PlayerColor,
371 pub text: TextStyle,
372 pub scrollbar_width: Pixels,
373 pub syntax: Arc<SyntaxTheme>,
374 pub status: StatusColors,
375 pub inlay_hints_style: HighlightStyle,
376 pub inline_completion_styles: InlineCompletionStyles,
377 pub unnecessary_code_fade: f32,
378}
379
380impl Default for EditorStyle {
381 fn default() -> Self {
382 Self {
383 background: Hsla::default(),
384 local_player: PlayerColor::default(),
385 text: TextStyle::default(),
386 scrollbar_width: Pixels::default(),
387 syntax: Default::default(),
388 // HACK: Status colors don't have a real default.
389 // We should look into removing the status colors from the editor
390 // style and retrieve them directly from the theme.
391 status: StatusColors::dark(),
392 inlay_hints_style: HighlightStyle::default(),
393 inline_completion_styles: InlineCompletionStyles {
394 insertion: HighlightStyle::default(),
395 whitespace: HighlightStyle::default(),
396 },
397 unnecessary_code_fade: Default::default(),
398 }
399 }
400}
401
402pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
403 let show_background = language_settings::language_settings(None, None, cx)
404 .inlay_hints
405 .show_background;
406
407 HighlightStyle {
408 color: Some(cx.theme().status().hint),
409 background_color: show_background.then(|| cx.theme().status().hint_background),
410 ..HighlightStyle::default()
411 }
412}
413
414pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
415 InlineCompletionStyles {
416 insertion: HighlightStyle {
417 color: Some(cx.theme().status().predictive),
418 ..HighlightStyle::default()
419 },
420 whitespace: HighlightStyle {
421 background_color: Some(cx.theme().status().created_background),
422 ..HighlightStyle::default()
423 },
424 }
425}
426
427type CompletionId = usize;
428
429pub(crate) enum EditDisplayMode {
430 TabAccept,
431 DiffPopover,
432 Inline,
433}
434
435enum InlineCompletion {
436 Edit {
437 edits: Vec<(Range<Anchor>, String)>,
438 edit_preview: Option<EditPreview>,
439 display_mode: EditDisplayMode,
440 snapshot: BufferSnapshot,
441 },
442 Move {
443 target: Anchor,
444 snapshot: BufferSnapshot,
445 },
446}
447
448struct InlineCompletionState {
449 inlay_ids: Vec<InlayId>,
450 completion: InlineCompletion,
451 completion_id: Option<SharedString>,
452 invalidation_range: Range<Anchor>,
453}
454
455enum EditPredictionSettings {
456 Disabled,
457 Enabled {
458 show_in_menu: bool,
459 preview_requires_modifier: bool,
460 },
461}
462
463enum InlineCompletionHighlight {}
464
465pub enum MenuInlineCompletionsPolicy {
466 Never,
467 ByProvider,
468}
469
470pub enum EditPredictionPreview {
471 /// Modifier is not pressed
472 Inactive,
473 /// Modifier pressed
474 Active {
475 previous_scroll_position: Option<ScrollAnchor>,
476 },
477}
478
479#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
480struct EditorActionId(usize);
481
482impl EditorActionId {
483 pub fn post_inc(&mut self) -> Self {
484 let answer = self.0;
485
486 *self = Self(answer + 1);
487
488 Self(answer)
489 }
490}
491
492// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
493// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
494
495type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
496type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
497
498#[derive(Default)]
499struct ScrollbarMarkerState {
500 scrollbar_size: Size<Pixels>,
501 dirty: bool,
502 markers: Arc<[PaintQuad]>,
503 pending_refresh: Option<Task<Result<()>>>,
504}
505
506impl ScrollbarMarkerState {
507 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
508 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
509 }
510}
511
512#[derive(Clone, Debug)]
513struct RunnableTasks {
514 templates: Vec<(TaskSourceKind, TaskTemplate)>,
515 offset: MultiBufferOffset,
516 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
517 column: u32,
518 // Values of all named captures, including those starting with '_'
519 extra_variables: HashMap<String, String>,
520 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
521 context_range: Range<BufferOffset>,
522}
523
524impl RunnableTasks {
525 fn resolve<'a>(
526 &'a self,
527 cx: &'a task::TaskContext,
528 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
529 self.templates.iter().filter_map(|(kind, template)| {
530 template
531 .resolve_task(&kind.to_id_base(), cx)
532 .map(|task| (kind.clone(), task))
533 })
534 }
535}
536
537#[derive(Clone)]
538struct ResolvedTasks {
539 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
540 position: Anchor,
541}
542#[derive(Copy, Clone, Debug)]
543struct MultiBufferOffset(usize);
544#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
545struct BufferOffset(usize);
546
547// Addons allow storing per-editor state in other crates (e.g. Vim)
548pub trait Addon: 'static {
549 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
550
551 fn render_buffer_header_controls(
552 &self,
553 _: &ExcerptInfo,
554 _: &Window,
555 _: &App,
556 ) -> Option<AnyElement> {
557 None
558 }
559
560 fn to_any(&self) -> &dyn std::any::Any;
561}
562
563#[derive(Debug, Copy, Clone, PartialEq, Eq)]
564pub enum IsVimMode {
565 Yes,
566 No,
567}
568
569/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
570///
571/// See the [module level documentation](self) for more information.
572pub struct Editor {
573 focus_handle: FocusHandle,
574 last_focused_descendant: Option<WeakFocusHandle>,
575 /// The text buffer being edited
576 buffer: Entity<MultiBuffer>,
577 /// Map of how text in the buffer should be displayed.
578 /// Handles soft wraps, folds, fake inlay text insertions, etc.
579 pub display_map: Entity<DisplayMap>,
580 pub selections: SelectionsCollection,
581 pub scroll_manager: ScrollManager,
582 /// When inline assist editors are linked, they all render cursors because
583 /// typing enters text into each of them, even the ones that aren't focused.
584 pub(crate) show_cursor_when_unfocused: bool,
585 columnar_selection_tail: Option<Anchor>,
586 add_selections_state: Option<AddSelectionsState>,
587 select_next_state: Option<SelectNextState>,
588 select_prev_state: Option<SelectNextState>,
589 selection_history: SelectionHistory,
590 autoclose_regions: Vec<AutocloseRegion>,
591 snippet_stack: InvalidationStack<SnippetState>,
592 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
593 ime_transaction: Option<TransactionId>,
594 active_diagnostics: Option<ActiveDiagnosticGroup>,
595 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
596
597 // TODO: make this a access method
598 pub project: Option<Entity<Project>>,
599 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
600 completion_provider: Option<Box<dyn CompletionProvider>>,
601 collaboration_hub: Option<Box<dyn CollaborationHub>>,
602 blink_manager: Entity<BlinkManager>,
603 show_cursor_names: bool,
604 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
605 pub show_local_selections: bool,
606 mode: EditorMode,
607 show_breadcrumbs: bool,
608 show_gutter: bool,
609 show_scrollbars: bool,
610 show_line_numbers: Option<bool>,
611 use_relative_line_numbers: Option<bool>,
612 show_git_diff_gutter: Option<bool>,
613 show_code_actions: Option<bool>,
614 show_runnables: Option<bool>,
615 show_wrap_guides: Option<bool>,
616 show_indent_guides: Option<bool>,
617 placeholder_text: Option<Arc<str>>,
618 highlight_order: usize,
619 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
620 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
621 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
622 scrollbar_marker_state: ScrollbarMarkerState,
623 active_indent_guides_state: ActiveIndentGuidesState,
624 nav_history: Option<ItemNavHistory>,
625 context_menu: RefCell<Option<CodeContextMenu>>,
626 mouse_context_menu: Option<MouseContextMenu>,
627 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
628 signature_help_state: SignatureHelpState,
629 auto_signature_help: Option<bool>,
630 find_all_references_task_sources: Vec<Anchor>,
631 next_completion_id: CompletionId,
632 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
633 code_actions_task: Option<Task<Result<()>>>,
634 selection_highlight_task: Option<Task<()>>,
635 document_highlights_task: Option<Task<()>>,
636 linked_editing_range_task: Option<Task<Option<()>>>,
637 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
638 pending_rename: Option<RenameState>,
639 searchable: bool,
640 cursor_shape: CursorShape,
641 current_line_highlight: Option<CurrentLineHighlight>,
642 collapse_matches: bool,
643 autoindent_mode: Option<AutoindentMode>,
644 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
645 input_enabled: bool,
646 use_modal_editing: bool,
647 read_only: bool,
648 leader_peer_id: Option<PeerId>,
649 remote_id: Option<ViewId>,
650 hover_state: HoverState,
651 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
652 gutter_hovered: bool,
653 hovered_link_state: Option<HoveredLinkState>,
654 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
655 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
656 active_inline_completion: Option<InlineCompletionState>,
657 /// Used to prevent flickering as the user types while the menu is open
658 stale_inline_completion_in_menu: Option<InlineCompletionState>,
659 edit_prediction_settings: EditPredictionSettings,
660 inline_completions_hidden_for_vim_mode: bool,
661 show_inline_completions_override: Option<bool>,
662 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
663 edit_prediction_preview: EditPredictionPreview,
664 edit_prediction_cursor_on_leading_whitespace: bool,
665 edit_prediction_requires_modifier_in_leading_space: bool,
666 inlay_hint_cache: InlayHintCache,
667 next_inlay_id: usize,
668 _subscriptions: Vec<Subscription>,
669 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
670 gutter_dimensions: GutterDimensions,
671 style: Option<EditorStyle>,
672 text_style_refinement: Option<TextStyleRefinement>,
673 next_editor_action_id: EditorActionId,
674 editor_actions:
675 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
676 use_autoclose: bool,
677 use_auto_surround: bool,
678 auto_replace_emoji_shortcode: bool,
679 show_git_blame_gutter: bool,
680 show_git_blame_inline: bool,
681 show_git_blame_inline_delay_task: Option<Task<()>>,
682 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
683 distinguish_unstaged_diff_hunks: bool,
684 git_blame_inline_enabled: bool,
685 serialize_dirty_buffers: bool,
686 show_selection_menu: Option<bool>,
687 blame: Option<Entity<GitBlame>>,
688 blame_subscription: Option<Subscription>,
689 custom_context_menu: Option<
690 Box<
691 dyn 'static
692 + Fn(
693 &mut Self,
694 DisplayPoint,
695 &mut Window,
696 &mut Context<Self>,
697 ) -> Option<Entity<ui::ContextMenu>>,
698 >,
699 >,
700 last_bounds: Option<Bounds<Pixels>>,
701 last_position_map: Option<Rc<PositionMap>>,
702 expect_bounds_change: Option<Bounds<Pixels>>,
703 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
704 tasks_update_task: Option<Task<()>>,
705 in_project_search: bool,
706 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
707 breadcrumb_header: Option<String>,
708 focused_block: Option<FocusedBlock>,
709 next_scroll_position: NextScrollCursorCenterTopBottom,
710 addons: HashMap<TypeId, Box<dyn Addon>>,
711 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
712 load_diff_task: Option<Shared<Task<()>>>,
713 selection_mark_mode: bool,
714 toggle_fold_multiple_buffers: Task<()>,
715 _scroll_cursor_center_top_bottom_task: Task<()>,
716 serialize_selections: Task<()>,
717}
718
719#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
720enum NextScrollCursorCenterTopBottom {
721 #[default]
722 Center,
723 Top,
724 Bottom,
725}
726
727impl NextScrollCursorCenterTopBottom {
728 fn next(&self) -> Self {
729 match self {
730 Self::Center => Self::Top,
731 Self::Top => Self::Bottom,
732 Self::Bottom => Self::Center,
733 }
734 }
735}
736
737#[derive(Clone)]
738pub struct EditorSnapshot {
739 pub mode: EditorMode,
740 show_gutter: bool,
741 show_line_numbers: Option<bool>,
742 show_git_diff_gutter: Option<bool>,
743 show_code_actions: Option<bool>,
744 show_runnables: Option<bool>,
745 git_blame_gutter_max_author_length: Option<usize>,
746 pub display_snapshot: DisplaySnapshot,
747 pub placeholder_text: Option<Arc<str>>,
748 is_focused: bool,
749 scroll_anchor: ScrollAnchor,
750 ongoing_scroll: OngoingScroll,
751 current_line_highlight: CurrentLineHighlight,
752 gutter_hovered: bool,
753}
754
755const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
756
757#[derive(Default, Debug, Clone, Copy)]
758pub struct GutterDimensions {
759 pub left_padding: Pixels,
760 pub right_padding: Pixels,
761 pub width: Pixels,
762 pub margin: Pixels,
763 pub git_blame_entries_width: Option<Pixels>,
764}
765
766impl GutterDimensions {
767 /// The full width of the space taken up by the gutter.
768 pub fn full_width(&self) -> Pixels {
769 self.margin + self.width
770 }
771
772 /// The width of the space reserved for the fold indicators,
773 /// use alongside 'justify_end' and `gutter_width` to
774 /// right align content with the line numbers
775 pub fn fold_area_width(&self) -> Pixels {
776 self.margin + self.right_padding
777 }
778}
779
780#[derive(Debug)]
781pub struct RemoteSelection {
782 pub replica_id: ReplicaId,
783 pub selection: Selection<Anchor>,
784 pub cursor_shape: CursorShape,
785 pub peer_id: PeerId,
786 pub line_mode: bool,
787 pub participant_index: Option<ParticipantIndex>,
788 pub user_name: Option<SharedString>,
789}
790
791#[derive(Clone, Debug)]
792struct SelectionHistoryEntry {
793 selections: Arc<[Selection<Anchor>]>,
794 select_next_state: Option<SelectNextState>,
795 select_prev_state: Option<SelectNextState>,
796 add_selections_state: Option<AddSelectionsState>,
797}
798
799enum SelectionHistoryMode {
800 Normal,
801 Undoing,
802 Redoing,
803}
804
805#[derive(Clone, PartialEq, Eq, Hash)]
806struct HoveredCursor {
807 replica_id: u16,
808 selection_id: usize,
809}
810
811impl Default for SelectionHistoryMode {
812 fn default() -> Self {
813 Self::Normal
814 }
815}
816
817#[derive(Default)]
818struct SelectionHistory {
819 #[allow(clippy::type_complexity)]
820 selections_by_transaction:
821 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
822 mode: SelectionHistoryMode,
823 undo_stack: VecDeque<SelectionHistoryEntry>,
824 redo_stack: VecDeque<SelectionHistoryEntry>,
825}
826
827impl SelectionHistory {
828 fn insert_transaction(
829 &mut self,
830 transaction_id: TransactionId,
831 selections: Arc<[Selection<Anchor>]>,
832 ) {
833 self.selections_by_transaction
834 .insert(transaction_id, (selections, None));
835 }
836
837 #[allow(clippy::type_complexity)]
838 fn transaction(
839 &self,
840 transaction_id: TransactionId,
841 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
842 self.selections_by_transaction.get(&transaction_id)
843 }
844
845 #[allow(clippy::type_complexity)]
846 fn transaction_mut(
847 &mut self,
848 transaction_id: TransactionId,
849 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
850 self.selections_by_transaction.get_mut(&transaction_id)
851 }
852
853 fn push(&mut self, entry: SelectionHistoryEntry) {
854 if !entry.selections.is_empty() {
855 match self.mode {
856 SelectionHistoryMode::Normal => {
857 self.push_undo(entry);
858 self.redo_stack.clear();
859 }
860 SelectionHistoryMode::Undoing => self.push_redo(entry),
861 SelectionHistoryMode::Redoing => self.push_undo(entry),
862 }
863 }
864 }
865
866 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
867 if self
868 .undo_stack
869 .back()
870 .map_or(true, |e| e.selections != entry.selections)
871 {
872 self.undo_stack.push_back(entry);
873 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
874 self.undo_stack.pop_front();
875 }
876 }
877 }
878
879 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
880 if self
881 .redo_stack
882 .back()
883 .map_or(true, |e| e.selections != entry.selections)
884 {
885 self.redo_stack.push_back(entry);
886 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
887 self.redo_stack.pop_front();
888 }
889 }
890 }
891}
892
893struct RowHighlight {
894 index: usize,
895 range: Range<Anchor>,
896 color: Hsla,
897 should_autoscroll: bool,
898}
899
900#[derive(Clone, Debug)]
901struct AddSelectionsState {
902 above: bool,
903 stack: Vec<usize>,
904}
905
906#[derive(Clone)]
907struct SelectNextState {
908 query: AhoCorasick,
909 wordwise: bool,
910 done: bool,
911}
912
913impl std::fmt::Debug for SelectNextState {
914 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
915 f.debug_struct(std::any::type_name::<Self>())
916 .field("wordwise", &self.wordwise)
917 .field("done", &self.done)
918 .finish()
919 }
920}
921
922#[derive(Debug)]
923struct AutocloseRegion {
924 selection_id: usize,
925 range: Range<Anchor>,
926 pair: BracketPair,
927}
928
929#[derive(Debug)]
930struct SnippetState {
931 ranges: Vec<Vec<Range<Anchor>>>,
932 active_index: usize,
933 choices: Vec<Option<Vec<String>>>,
934}
935
936#[doc(hidden)]
937pub struct RenameState {
938 pub range: Range<Anchor>,
939 pub old_name: Arc<str>,
940 pub editor: Entity<Editor>,
941 block_id: CustomBlockId,
942}
943
944struct InvalidationStack<T>(Vec<T>);
945
946struct RegisteredInlineCompletionProvider {
947 provider: Arc<dyn InlineCompletionProviderHandle>,
948 _subscription: Subscription,
949}
950
951#[derive(Debug)]
952struct ActiveDiagnosticGroup {
953 primary_range: Range<Anchor>,
954 primary_message: String,
955 group_id: usize,
956 blocks: HashMap<CustomBlockId, Diagnostic>,
957 is_valid: bool,
958}
959
960#[derive(Serialize, Deserialize, Clone, Debug)]
961pub struct ClipboardSelection {
962 pub len: usize,
963 pub is_entire_line: bool,
964 pub first_line_indent: u32,
965}
966
967#[derive(Debug)]
968pub(crate) struct NavigationData {
969 cursor_anchor: Anchor,
970 cursor_position: Point,
971 scroll_anchor: ScrollAnchor,
972 scroll_top_row: u32,
973}
974
975#[derive(Debug, Clone, Copy, PartialEq, Eq)]
976pub enum GotoDefinitionKind {
977 Symbol,
978 Declaration,
979 Type,
980 Implementation,
981}
982
983#[derive(Debug, Clone)]
984enum InlayHintRefreshReason {
985 Toggle(bool),
986 SettingsChange(InlayHintSettings),
987 NewLinesShown,
988 BufferEdited(HashSet<Arc<Language>>),
989 RefreshRequested,
990 ExcerptsRemoved(Vec<ExcerptId>),
991}
992
993impl InlayHintRefreshReason {
994 fn description(&self) -> &'static str {
995 match self {
996 Self::Toggle(_) => "toggle",
997 Self::SettingsChange(_) => "settings change",
998 Self::NewLinesShown => "new lines shown",
999 Self::BufferEdited(_) => "buffer edited",
1000 Self::RefreshRequested => "refresh requested",
1001 Self::ExcerptsRemoved(_) => "excerpts removed",
1002 }
1003 }
1004}
1005
1006pub enum FormatTarget {
1007 Buffers,
1008 Ranges(Vec<Range<MultiBufferPoint>>),
1009}
1010
1011pub(crate) struct FocusedBlock {
1012 id: BlockId,
1013 focus_handle: WeakFocusHandle,
1014}
1015
1016#[derive(Clone)]
1017enum JumpData {
1018 MultiBufferRow {
1019 row: MultiBufferRow,
1020 line_offset_from_top: u32,
1021 },
1022 MultiBufferPoint {
1023 excerpt_id: ExcerptId,
1024 position: Point,
1025 anchor: text::Anchor,
1026 line_offset_from_top: u32,
1027 },
1028}
1029
1030pub enum MultibufferSelectionMode {
1031 First,
1032 All,
1033}
1034
1035impl Editor {
1036 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1037 let buffer = cx.new(|cx| Buffer::local("", cx));
1038 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1039 Self::new(
1040 EditorMode::SingleLine { auto_width: false },
1041 buffer,
1042 None,
1043 false,
1044 window,
1045 cx,
1046 )
1047 }
1048
1049 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1050 let buffer = cx.new(|cx| Buffer::local("", cx));
1051 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1052 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1053 }
1054
1055 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1056 let buffer = cx.new(|cx| Buffer::local("", cx));
1057 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1058 Self::new(
1059 EditorMode::SingleLine { auto_width: true },
1060 buffer,
1061 None,
1062 false,
1063 window,
1064 cx,
1065 )
1066 }
1067
1068 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1069 let buffer = cx.new(|cx| Buffer::local("", cx));
1070 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1071 Self::new(
1072 EditorMode::AutoHeight { max_lines },
1073 buffer,
1074 None,
1075 false,
1076 window,
1077 cx,
1078 )
1079 }
1080
1081 pub fn for_buffer(
1082 buffer: Entity<Buffer>,
1083 project: Option<Entity<Project>>,
1084 window: &mut Window,
1085 cx: &mut Context<Self>,
1086 ) -> Self {
1087 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1088 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1089 }
1090
1091 pub fn for_multibuffer(
1092 buffer: Entity<MultiBuffer>,
1093 project: Option<Entity<Project>>,
1094 show_excerpt_controls: bool,
1095 window: &mut Window,
1096 cx: &mut Context<Self>,
1097 ) -> Self {
1098 Self::new(
1099 EditorMode::Full,
1100 buffer,
1101 project,
1102 show_excerpt_controls,
1103 window,
1104 cx,
1105 )
1106 }
1107
1108 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1109 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1110 let mut clone = Self::new(
1111 self.mode,
1112 self.buffer.clone(),
1113 self.project.clone(),
1114 show_excerpt_controls,
1115 window,
1116 cx,
1117 );
1118 self.display_map.update(cx, |display_map, cx| {
1119 let snapshot = display_map.snapshot(cx);
1120 clone.display_map.update(cx, |display_map, cx| {
1121 display_map.set_state(&snapshot, cx);
1122 });
1123 });
1124 clone.selections.clone_state(&self.selections);
1125 clone.scroll_manager.clone_state(&self.scroll_manager);
1126 clone.searchable = self.searchable;
1127 clone
1128 }
1129
1130 pub fn new(
1131 mode: EditorMode,
1132 buffer: Entity<MultiBuffer>,
1133 project: Option<Entity<Project>>,
1134 show_excerpt_controls: bool,
1135 window: &mut Window,
1136 cx: &mut Context<Self>,
1137 ) -> Self {
1138 let style = window.text_style();
1139 let font_size = style.font_size.to_pixels(window.rem_size());
1140 let editor = cx.entity().downgrade();
1141 let fold_placeholder = FoldPlaceholder {
1142 constrain_width: true,
1143 render: Arc::new(move |fold_id, fold_range, _, cx| {
1144 let editor = editor.clone();
1145 div()
1146 .id(fold_id)
1147 .bg(cx.theme().colors().ghost_element_background)
1148 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1149 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1150 .rounded_sm()
1151 .size_full()
1152 .cursor_pointer()
1153 .child("⋯")
1154 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1155 .on_click(move |_, _window, cx| {
1156 editor
1157 .update(cx, |editor, cx| {
1158 editor.unfold_ranges(
1159 &[fold_range.start..fold_range.end],
1160 true,
1161 false,
1162 cx,
1163 );
1164 cx.stop_propagation();
1165 })
1166 .ok();
1167 })
1168 .into_any()
1169 }),
1170 merge_adjacent: true,
1171 ..Default::default()
1172 };
1173 let display_map = cx.new(|cx| {
1174 DisplayMap::new(
1175 buffer.clone(),
1176 style.font(),
1177 font_size,
1178 None,
1179 show_excerpt_controls,
1180 FILE_HEADER_HEIGHT,
1181 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1182 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1183 fold_placeholder,
1184 cx,
1185 )
1186 });
1187
1188 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1189
1190 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1191
1192 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1193 .then(|| language_settings::SoftWrap::None);
1194
1195 let mut project_subscriptions = Vec::new();
1196 if mode == EditorMode::Full {
1197 if let Some(project) = project.as_ref() {
1198 if buffer.read(cx).is_singleton() {
1199 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1200 cx.emit(EditorEvent::TitleChanged);
1201 }));
1202 }
1203 project_subscriptions.push(cx.subscribe_in(
1204 project,
1205 window,
1206 |editor, _, event, window, cx| {
1207 if let project::Event::RefreshInlayHints = event {
1208 editor
1209 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1210 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1211 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1212 let focus_handle = editor.focus_handle(cx);
1213 if focus_handle.is_focused(window) {
1214 let snapshot = buffer.read(cx).snapshot();
1215 for (range, snippet) in snippet_edits {
1216 let editor_range =
1217 language::range_from_lsp(*range).to_offset(&snapshot);
1218 editor
1219 .insert_snippet(
1220 &[editor_range],
1221 snippet.clone(),
1222 window,
1223 cx,
1224 )
1225 .ok();
1226 }
1227 }
1228 }
1229 }
1230 },
1231 ));
1232 if let Some(task_inventory) = project
1233 .read(cx)
1234 .task_store()
1235 .read(cx)
1236 .task_inventory()
1237 .cloned()
1238 {
1239 project_subscriptions.push(cx.observe_in(
1240 &task_inventory,
1241 window,
1242 |editor, _, window, cx| {
1243 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1244 },
1245 ));
1246 }
1247 }
1248 }
1249
1250 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1251
1252 let inlay_hint_settings =
1253 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1254 let focus_handle = cx.focus_handle();
1255 cx.on_focus(&focus_handle, window, Self::handle_focus)
1256 .detach();
1257 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1258 .detach();
1259 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1260 .detach();
1261 cx.on_blur(&focus_handle, window, Self::handle_blur)
1262 .detach();
1263
1264 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1265 Some(false)
1266 } else {
1267 None
1268 };
1269
1270 let mut code_action_providers = Vec::new();
1271 let mut load_uncommitted_diff = None;
1272 if let Some(project) = project.clone() {
1273 load_uncommitted_diff = Some(
1274 get_uncommitted_diff_for_buffer(
1275 &project,
1276 buffer.read(cx).all_buffers(),
1277 buffer.clone(),
1278 cx,
1279 )
1280 .shared(),
1281 );
1282 code_action_providers.push(Rc::new(project) as Rc<_>);
1283 }
1284
1285 let mut this = Self {
1286 focus_handle,
1287 show_cursor_when_unfocused: false,
1288 last_focused_descendant: None,
1289 buffer: buffer.clone(),
1290 display_map: display_map.clone(),
1291 selections,
1292 scroll_manager: ScrollManager::new(cx),
1293 columnar_selection_tail: None,
1294 add_selections_state: None,
1295 select_next_state: None,
1296 select_prev_state: None,
1297 selection_history: Default::default(),
1298 autoclose_regions: Default::default(),
1299 snippet_stack: Default::default(),
1300 select_larger_syntax_node_stack: Vec::new(),
1301 ime_transaction: Default::default(),
1302 active_diagnostics: None,
1303 soft_wrap_mode_override,
1304 completion_provider: project.clone().map(|project| Box::new(project) as _),
1305 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1306 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1307 project,
1308 blink_manager: blink_manager.clone(),
1309 show_local_selections: true,
1310 show_scrollbars: true,
1311 mode,
1312 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1313 show_gutter: mode == EditorMode::Full,
1314 show_line_numbers: None,
1315 use_relative_line_numbers: None,
1316 show_git_diff_gutter: None,
1317 show_code_actions: None,
1318 show_runnables: None,
1319 show_wrap_guides: None,
1320 show_indent_guides,
1321 placeholder_text: None,
1322 highlight_order: 0,
1323 highlighted_rows: HashMap::default(),
1324 background_highlights: Default::default(),
1325 gutter_highlights: TreeMap::default(),
1326 scrollbar_marker_state: ScrollbarMarkerState::default(),
1327 active_indent_guides_state: ActiveIndentGuidesState::default(),
1328 nav_history: None,
1329 context_menu: RefCell::new(None),
1330 mouse_context_menu: None,
1331 completion_tasks: Default::default(),
1332 signature_help_state: SignatureHelpState::default(),
1333 auto_signature_help: None,
1334 find_all_references_task_sources: Vec::new(),
1335 next_completion_id: 0,
1336 next_inlay_id: 0,
1337 code_action_providers,
1338 available_code_actions: Default::default(),
1339 code_actions_task: Default::default(),
1340 selection_highlight_task: Default::default(),
1341 document_highlights_task: Default::default(),
1342 linked_editing_range_task: Default::default(),
1343 pending_rename: Default::default(),
1344 searchable: true,
1345 cursor_shape: EditorSettings::get_global(cx)
1346 .cursor_shape
1347 .unwrap_or_default(),
1348 current_line_highlight: None,
1349 autoindent_mode: Some(AutoindentMode::EachLine),
1350 collapse_matches: false,
1351 workspace: None,
1352 input_enabled: true,
1353 use_modal_editing: mode == EditorMode::Full,
1354 read_only: false,
1355 use_autoclose: true,
1356 use_auto_surround: true,
1357 auto_replace_emoji_shortcode: false,
1358 leader_peer_id: None,
1359 remote_id: None,
1360 hover_state: Default::default(),
1361 pending_mouse_down: None,
1362 hovered_link_state: Default::default(),
1363 edit_prediction_provider: None,
1364 active_inline_completion: None,
1365 stale_inline_completion_in_menu: None,
1366 edit_prediction_preview: EditPredictionPreview::Inactive,
1367 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1368
1369 gutter_hovered: false,
1370 pixel_position_of_newest_cursor: None,
1371 last_bounds: None,
1372 last_position_map: None,
1373 expect_bounds_change: None,
1374 gutter_dimensions: GutterDimensions::default(),
1375 style: None,
1376 show_cursor_names: false,
1377 hovered_cursors: Default::default(),
1378 next_editor_action_id: EditorActionId::default(),
1379 editor_actions: Rc::default(),
1380 inline_completions_hidden_for_vim_mode: false,
1381 show_inline_completions_override: None,
1382 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1383 edit_prediction_settings: EditPredictionSettings::Disabled,
1384 edit_prediction_cursor_on_leading_whitespace: false,
1385 edit_prediction_requires_modifier_in_leading_space: true,
1386 custom_context_menu: None,
1387 show_git_blame_gutter: false,
1388 show_git_blame_inline: false,
1389 distinguish_unstaged_diff_hunks: false,
1390 show_selection_menu: None,
1391 show_git_blame_inline_delay_task: None,
1392 git_blame_inline_tooltip: None,
1393 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1394 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1395 .session
1396 .restore_unsaved_buffers,
1397 blame: None,
1398 blame_subscription: None,
1399 tasks: Default::default(),
1400 _subscriptions: vec![
1401 cx.observe(&buffer, Self::on_buffer_changed),
1402 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1403 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1404 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1405 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1406 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1407 cx.observe_window_activation(window, |editor, window, cx| {
1408 let active = window.is_window_active();
1409 editor.blink_manager.update(cx, |blink_manager, cx| {
1410 if active {
1411 blink_manager.enable(cx);
1412 } else {
1413 blink_manager.disable(cx);
1414 }
1415 });
1416 }),
1417 ],
1418 tasks_update_task: None,
1419 linked_edit_ranges: Default::default(),
1420 in_project_search: false,
1421 previous_search_ranges: None,
1422 breadcrumb_header: None,
1423 focused_block: None,
1424 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1425 addons: HashMap::default(),
1426 registered_buffers: HashMap::default(),
1427 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1428 selection_mark_mode: false,
1429 toggle_fold_multiple_buffers: Task::ready(()),
1430 serialize_selections: Task::ready(()),
1431 text_style_refinement: None,
1432 load_diff_task: load_uncommitted_diff,
1433 };
1434 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1435 this._subscriptions.extend(project_subscriptions);
1436
1437 this.end_selection(window, cx);
1438 this.scroll_manager.show_scrollbar(window, cx);
1439
1440 if mode == EditorMode::Full {
1441 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1442 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1443
1444 if this.git_blame_inline_enabled {
1445 this.git_blame_inline_enabled = true;
1446 this.start_git_blame_inline(false, window, cx);
1447 }
1448
1449 if let Some(buffer) = buffer.read(cx).as_singleton() {
1450 if let Some(project) = this.project.as_ref() {
1451 let handle = project.update(cx, |project, cx| {
1452 project.register_buffer_with_language_servers(&buffer, cx)
1453 });
1454 this.registered_buffers
1455 .insert(buffer.read(cx).remote_id(), handle);
1456 }
1457 }
1458 }
1459
1460 this.report_editor_event("Editor Opened", None, cx);
1461 this
1462 }
1463
1464 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1465 self.mouse_context_menu
1466 .as_ref()
1467 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1468 }
1469
1470 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1471 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1472 }
1473
1474 fn key_context_internal(
1475 &self,
1476 has_active_edit_prediction: bool,
1477 window: &Window,
1478 cx: &App,
1479 ) -> KeyContext {
1480 let mut key_context = KeyContext::new_with_defaults();
1481 key_context.add("Editor");
1482 let mode = match self.mode {
1483 EditorMode::SingleLine { .. } => "single_line",
1484 EditorMode::AutoHeight { .. } => "auto_height",
1485 EditorMode::Full => "full",
1486 };
1487
1488 if EditorSettings::jupyter_enabled(cx) {
1489 key_context.add("jupyter");
1490 }
1491
1492 key_context.set("mode", mode);
1493 if self.pending_rename.is_some() {
1494 key_context.add("renaming");
1495 }
1496
1497 match self.context_menu.borrow().as_ref() {
1498 Some(CodeContextMenu::Completions(_)) => {
1499 key_context.add("menu");
1500 key_context.add("showing_completions");
1501 }
1502 Some(CodeContextMenu::CodeActions(_)) => {
1503 key_context.add("menu");
1504 key_context.add("showing_code_actions")
1505 }
1506 None => {}
1507 }
1508
1509 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1510 if !self.focus_handle(cx).contains_focused(window, cx)
1511 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1512 {
1513 for addon in self.addons.values() {
1514 addon.extend_key_context(&mut key_context, cx)
1515 }
1516 }
1517
1518 if let Some(extension) = self
1519 .buffer
1520 .read(cx)
1521 .as_singleton()
1522 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1523 {
1524 key_context.set("extension", extension.to_string());
1525 }
1526
1527 if has_active_edit_prediction {
1528 if self.edit_prediction_in_conflict() {
1529 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1530 } else {
1531 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1532 key_context.add("copilot_suggestion");
1533 }
1534 }
1535
1536 if self.selection_mark_mode {
1537 key_context.add("selection_mode");
1538 }
1539
1540 key_context
1541 }
1542
1543 pub fn edit_prediction_in_conflict(&self) -> bool {
1544 if !self.show_edit_predictions_in_menu() {
1545 return false;
1546 }
1547
1548 let showing_completions = self
1549 .context_menu
1550 .borrow()
1551 .as_ref()
1552 .map_or(false, |context| {
1553 matches!(context, CodeContextMenu::Completions(_))
1554 });
1555
1556 showing_completions
1557 || self.edit_prediction_requires_modifier()
1558 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1559 // bindings to insert tab characters.
1560 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1561 }
1562
1563 pub fn accept_edit_prediction_keybind(
1564 &self,
1565 window: &Window,
1566 cx: &App,
1567 ) -> AcceptEditPredictionBinding {
1568 let key_context = self.key_context_internal(true, window, cx);
1569 let in_conflict = self.edit_prediction_in_conflict();
1570
1571 AcceptEditPredictionBinding(
1572 window
1573 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1574 .into_iter()
1575 .filter(|binding| {
1576 !in_conflict
1577 || binding
1578 .keystrokes()
1579 .first()
1580 .map_or(false, |keystroke| keystroke.modifiers.modified())
1581 })
1582 .rev()
1583 .min_by_key(|binding| {
1584 binding
1585 .keystrokes()
1586 .first()
1587 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1588 }),
1589 )
1590 }
1591
1592 pub fn new_file(
1593 workspace: &mut Workspace,
1594 _: &workspace::NewFile,
1595 window: &mut Window,
1596 cx: &mut Context<Workspace>,
1597 ) {
1598 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1599 "Failed to create buffer",
1600 window,
1601 cx,
1602 |e, _, _| match e.error_code() {
1603 ErrorCode::RemoteUpgradeRequired => Some(format!(
1604 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1605 e.error_tag("required").unwrap_or("the latest version")
1606 )),
1607 _ => None,
1608 },
1609 );
1610 }
1611
1612 pub fn new_in_workspace(
1613 workspace: &mut Workspace,
1614 window: &mut Window,
1615 cx: &mut Context<Workspace>,
1616 ) -> Task<Result<Entity<Editor>>> {
1617 let project = workspace.project().clone();
1618 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1619
1620 cx.spawn_in(window, |workspace, mut cx| async move {
1621 let buffer = create.await?;
1622 workspace.update_in(&mut cx, |workspace, window, cx| {
1623 let editor =
1624 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1625 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1626 editor
1627 })
1628 })
1629 }
1630
1631 fn new_file_vertical(
1632 workspace: &mut Workspace,
1633 _: &workspace::NewFileSplitVertical,
1634 window: &mut Window,
1635 cx: &mut Context<Workspace>,
1636 ) {
1637 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1638 }
1639
1640 fn new_file_horizontal(
1641 workspace: &mut Workspace,
1642 _: &workspace::NewFileSplitHorizontal,
1643 window: &mut Window,
1644 cx: &mut Context<Workspace>,
1645 ) {
1646 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1647 }
1648
1649 fn new_file_in_direction(
1650 workspace: &mut Workspace,
1651 direction: SplitDirection,
1652 window: &mut Window,
1653 cx: &mut Context<Workspace>,
1654 ) {
1655 let project = workspace.project().clone();
1656 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1657
1658 cx.spawn_in(window, |workspace, mut cx| async move {
1659 let buffer = create.await?;
1660 workspace.update_in(&mut cx, move |workspace, window, cx| {
1661 workspace.split_item(
1662 direction,
1663 Box::new(
1664 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1665 ),
1666 window,
1667 cx,
1668 )
1669 })?;
1670 anyhow::Ok(())
1671 })
1672 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1673 match e.error_code() {
1674 ErrorCode::RemoteUpgradeRequired => Some(format!(
1675 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1676 e.error_tag("required").unwrap_or("the latest version")
1677 )),
1678 _ => None,
1679 }
1680 });
1681 }
1682
1683 pub fn leader_peer_id(&self) -> Option<PeerId> {
1684 self.leader_peer_id
1685 }
1686
1687 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1688 &self.buffer
1689 }
1690
1691 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1692 self.workspace.as_ref()?.0.upgrade()
1693 }
1694
1695 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1696 self.buffer().read(cx).title(cx)
1697 }
1698
1699 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1700 let git_blame_gutter_max_author_length = self
1701 .render_git_blame_gutter(cx)
1702 .then(|| {
1703 if let Some(blame) = self.blame.as_ref() {
1704 let max_author_length =
1705 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1706 Some(max_author_length)
1707 } else {
1708 None
1709 }
1710 })
1711 .flatten();
1712
1713 EditorSnapshot {
1714 mode: self.mode,
1715 show_gutter: self.show_gutter,
1716 show_line_numbers: self.show_line_numbers,
1717 show_git_diff_gutter: self.show_git_diff_gutter,
1718 show_code_actions: self.show_code_actions,
1719 show_runnables: self.show_runnables,
1720 git_blame_gutter_max_author_length,
1721 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1722 scroll_anchor: self.scroll_manager.anchor(),
1723 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1724 placeholder_text: self.placeholder_text.clone(),
1725 is_focused: self.focus_handle.is_focused(window),
1726 current_line_highlight: self
1727 .current_line_highlight
1728 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1729 gutter_hovered: self.gutter_hovered,
1730 }
1731 }
1732
1733 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1734 self.buffer.read(cx).language_at(point, cx)
1735 }
1736
1737 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1738 self.buffer.read(cx).read(cx).file_at(point).cloned()
1739 }
1740
1741 pub fn active_excerpt(
1742 &self,
1743 cx: &App,
1744 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1745 self.buffer
1746 .read(cx)
1747 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1748 }
1749
1750 pub fn mode(&self) -> EditorMode {
1751 self.mode
1752 }
1753
1754 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1755 self.collaboration_hub.as_deref()
1756 }
1757
1758 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1759 self.collaboration_hub = Some(hub);
1760 }
1761
1762 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1763 self.in_project_search = in_project_search;
1764 }
1765
1766 pub fn set_custom_context_menu(
1767 &mut self,
1768 f: impl 'static
1769 + Fn(
1770 &mut Self,
1771 DisplayPoint,
1772 &mut Window,
1773 &mut Context<Self>,
1774 ) -> Option<Entity<ui::ContextMenu>>,
1775 ) {
1776 self.custom_context_menu = Some(Box::new(f))
1777 }
1778
1779 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1780 self.completion_provider = provider;
1781 }
1782
1783 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1784 self.semantics_provider.clone()
1785 }
1786
1787 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1788 self.semantics_provider = provider;
1789 }
1790
1791 pub fn set_edit_prediction_provider<T>(
1792 &mut self,
1793 provider: Option<Entity<T>>,
1794 window: &mut Window,
1795 cx: &mut Context<Self>,
1796 ) where
1797 T: EditPredictionProvider,
1798 {
1799 self.edit_prediction_provider =
1800 provider.map(|provider| RegisteredInlineCompletionProvider {
1801 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1802 if this.focus_handle.is_focused(window) {
1803 this.update_visible_inline_completion(window, cx);
1804 }
1805 }),
1806 provider: Arc::new(provider),
1807 });
1808 self.refresh_inline_completion(false, false, window, cx);
1809 }
1810
1811 pub fn placeholder_text(&self) -> Option<&str> {
1812 self.placeholder_text.as_deref()
1813 }
1814
1815 pub fn set_placeholder_text(
1816 &mut self,
1817 placeholder_text: impl Into<Arc<str>>,
1818 cx: &mut Context<Self>,
1819 ) {
1820 let placeholder_text = Some(placeholder_text.into());
1821 if self.placeholder_text != placeholder_text {
1822 self.placeholder_text = placeholder_text;
1823 cx.notify();
1824 }
1825 }
1826
1827 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1828 self.cursor_shape = cursor_shape;
1829
1830 // Disrupt blink for immediate user feedback that the cursor shape has changed
1831 self.blink_manager.update(cx, BlinkManager::show_cursor);
1832
1833 cx.notify();
1834 }
1835
1836 pub fn set_current_line_highlight(
1837 &mut self,
1838 current_line_highlight: Option<CurrentLineHighlight>,
1839 ) {
1840 self.current_line_highlight = current_line_highlight;
1841 }
1842
1843 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1844 self.collapse_matches = collapse_matches;
1845 }
1846
1847 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1848 let buffers = self.buffer.read(cx).all_buffers();
1849 let Some(project) = self.project.as_ref() else {
1850 return;
1851 };
1852 project.update(cx, |project, cx| {
1853 for buffer in buffers {
1854 self.registered_buffers
1855 .entry(buffer.read(cx).remote_id())
1856 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1857 }
1858 })
1859 }
1860
1861 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1862 if self.collapse_matches {
1863 return range.start..range.start;
1864 }
1865 range.clone()
1866 }
1867
1868 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1869 if self.display_map.read(cx).clip_at_line_ends != clip {
1870 self.display_map
1871 .update(cx, |map, _| map.clip_at_line_ends = clip);
1872 }
1873 }
1874
1875 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1876 self.input_enabled = input_enabled;
1877 }
1878
1879 pub fn set_inline_completions_hidden_for_vim_mode(
1880 &mut self,
1881 hidden: bool,
1882 window: &mut Window,
1883 cx: &mut Context<Self>,
1884 ) {
1885 if hidden != self.inline_completions_hidden_for_vim_mode {
1886 self.inline_completions_hidden_for_vim_mode = hidden;
1887 if hidden {
1888 self.update_visible_inline_completion(window, cx);
1889 } else {
1890 self.refresh_inline_completion(true, false, window, cx);
1891 }
1892 }
1893 }
1894
1895 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1896 self.menu_inline_completions_policy = value;
1897 }
1898
1899 pub fn set_autoindent(&mut self, autoindent: bool) {
1900 if autoindent {
1901 self.autoindent_mode = Some(AutoindentMode::EachLine);
1902 } else {
1903 self.autoindent_mode = None;
1904 }
1905 }
1906
1907 pub fn read_only(&self, cx: &App) -> bool {
1908 self.read_only || self.buffer.read(cx).read_only()
1909 }
1910
1911 pub fn set_read_only(&mut self, read_only: bool) {
1912 self.read_only = read_only;
1913 }
1914
1915 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1916 self.use_autoclose = autoclose;
1917 }
1918
1919 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1920 self.use_auto_surround = auto_surround;
1921 }
1922
1923 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1924 self.auto_replace_emoji_shortcode = auto_replace;
1925 }
1926
1927 pub fn toggle_inline_completions(
1928 &mut self,
1929 _: &ToggleEditPrediction,
1930 window: &mut Window,
1931 cx: &mut Context<Self>,
1932 ) {
1933 if self.show_inline_completions_override.is_some() {
1934 self.set_show_edit_predictions(None, window, cx);
1935 } else {
1936 let show_edit_predictions = !self.edit_predictions_enabled();
1937 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1938 }
1939 }
1940
1941 pub fn set_show_edit_predictions(
1942 &mut self,
1943 show_edit_predictions: Option<bool>,
1944 window: &mut Window,
1945 cx: &mut Context<Self>,
1946 ) {
1947 self.show_inline_completions_override = show_edit_predictions;
1948 self.refresh_inline_completion(false, true, window, cx);
1949 }
1950
1951 fn inline_completions_disabled_in_scope(
1952 &self,
1953 buffer: &Entity<Buffer>,
1954 buffer_position: language::Anchor,
1955 cx: &App,
1956 ) -> bool {
1957 let snapshot = buffer.read(cx).snapshot();
1958 let settings = snapshot.settings_at(buffer_position, cx);
1959
1960 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1961 return false;
1962 };
1963
1964 scope.override_name().map_or(false, |scope_name| {
1965 settings
1966 .edit_predictions_disabled_in
1967 .iter()
1968 .any(|s| s == scope_name)
1969 })
1970 }
1971
1972 pub fn set_use_modal_editing(&mut self, to: bool) {
1973 self.use_modal_editing = to;
1974 }
1975
1976 pub fn use_modal_editing(&self) -> bool {
1977 self.use_modal_editing
1978 }
1979
1980 fn selections_did_change(
1981 &mut self,
1982 local: bool,
1983 old_cursor_position: &Anchor,
1984 show_completions: bool,
1985 window: &mut Window,
1986 cx: &mut Context<Self>,
1987 ) {
1988 window.invalidate_character_coordinates();
1989
1990 // Copy selections to primary selection buffer
1991 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1992 if local {
1993 let selections = self.selections.all::<usize>(cx);
1994 let buffer_handle = self.buffer.read(cx).read(cx);
1995
1996 let mut text = String::new();
1997 for (index, selection) in selections.iter().enumerate() {
1998 let text_for_selection = buffer_handle
1999 .text_for_range(selection.start..selection.end)
2000 .collect::<String>();
2001
2002 text.push_str(&text_for_selection);
2003 if index != selections.len() - 1 {
2004 text.push('\n');
2005 }
2006 }
2007
2008 if !text.is_empty() {
2009 cx.write_to_primary(ClipboardItem::new_string(text));
2010 }
2011 }
2012
2013 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2014 self.buffer.update(cx, |buffer, cx| {
2015 buffer.set_active_selections(
2016 &self.selections.disjoint_anchors(),
2017 self.selections.line_mode,
2018 self.cursor_shape,
2019 cx,
2020 )
2021 });
2022 }
2023 let display_map = self
2024 .display_map
2025 .update(cx, |display_map, cx| display_map.snapshot(cx));
2026 let buffer = &display_map.buffer_snapshot;
2027 self.add_selections_state = None;
2028 self.select_next_state = None;
2029 self.select_prev_state = None;
2030 self.select_larger_syntax_node_stack.clear();
2031 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2032 self.snippet_stack
2033 .invalidate(&self.selections.disjoint_anchors(), buffer);
2034 self.take_rename(false, window, cx);
2035
2036 let new_cursor_position = self.selections.newest_anchor().head();
2037
2038 self.push_to_nav_history(
2039 *old_cursor_position,
2040 Some(new_cursor_position.to_point(buffer)),
2041 cx,
2042 );
2043
2044 if local {
2045 let new_cursor_position = self.selections.newest_anchor().head();
2046 let mut context_menu = self.context_menu.borrow_mut();
2047 let completion_menu = match context_menu.as_ref() {
2048 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2049 _ => {
2050 *context_menu = None;
2051 None
2052 }
2053 };
2054 if let Some(buffer_id) = new_cursor_position.buffer_id {
2055 if !self.registered_buffers.contains_key(&buffer_id) {
2056 if let Some(project) = self.project.as_ref() {
2057 project.update(cx, |project, cx| {
2058 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2059 return;
2060 };
2061 self.registered_buffers.insert(
2062 buffer_id,
2063 project.register_buffer_with_language_servers(&buffer, cx),
2064 );
2065 })
2066 }
2067 }
2068 }
2069
2070 if let Some(completion_menu) = completion_menu {
2071 let cursor_position = new_cursor_position.to_offset(buffer);
2072 let (word_range, kind) =
2073 buffer.surrounding_word(completion_menu.initial_position, true);
2074 if kind == Some(CharKind::Word)
2075 && word_range.to_inclusive().contains(&cursor_position)
2076 {
2077 let mut completion_menu = completion_menu.clone();
2078 drop(context_menu);
2079
2080 let query = Self::completion_query(buffer, cursor_position);
2081 cx.spawn(move |this, mut cx| async move {
2082 completion_menu
2083 .filter(query.as_deref(), cx.background_executor().clone())
2084 .await;
2085
2086 this.update(&mut cx, |this, cx| {
2087 let mut context_menu = this.context_menu.borrow_mut();
2088 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2089 else {
2090 return;
2091 };
2092
2093 if menu.id > completion_menu.id {
2094 return;
2095 }
2096
2097 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2098 drop(context_menu);
2099 cx.notify();
2100 })
2101 })
2102 .detach();
2103
2104 if show_completions {
2105 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2106 }
2107 } else {
2108 drop(context_menu);
2109 self.hide_context_menu(window, cx);
2110 }
2111 } else {
2112 drop(context_menu);
2113 }
2114
2115 hide_hover(self, cx);
2116
2117 if old_cursor_position.to_display_point(&display_map).row()
2118 != new_cursor_position.to_display_point(&display_map).row()
2119 {
2120 self.available_code_actions.take();
2121 }
2122 self.refresh_code_actions(window, cx);
2123 self.refresh_document_highlights(cx);
2124 self.refresh_selected_text_highlights(window, cx);
2125 refresh_matching_bracket_highlights(self, window, cx);
2126 self.update_visible_inline_completion(window, cx);
2127 self.edit_prediction_requires_modifier_in_leading_space = true;
2128 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2129 if self.git_blame_inline_enabled {
2130 self.start_inline_blame_timer(window, cx);
2131 }
2132 }
2133
2134 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2135 cx.emit(EditorEvent::SelectionsChanged { local });
2136
2137 let selections = &self.selections.disjoint;
2138 if selections.len() == 1 {
2139 cx.emit(SearchEvent::ActiveMatchChanged)
2140 }
2141 if local
2142 && self.is_singleton(cx)
2143 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2144 {
2145 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2146 let background_executor = cx.background_executor().clone();
2147 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2148 let snapshot = self.buffer().read(cx).snapshot(cx);
2149 let selections = selections.clone();
2150 self.serialize_selections = cx.background_spawn(async move {
2151 background_executor.timer(Duration::from_millis(100)).await;
2152 let selections = selections
2153 .iter()
2154 .map(|selection| {
2155 (
2156 selection.start.to_offset(&snapshot),
2157 selection.end.to_offset(&snapshot),
2158 )
2159 })
2160 .collect();
2161 DB.save_editor_selections(editor_id, workspace_id, selections)
2162 .await
2163 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2164 .log_err();
2165 });
2166 }
2167 }
2168
2169 cx.notify();
2170 }
2171
2172 pub fn change_selections<R>(
2173 &mut self,
2174 autoscroll: Option<Autoscroll>,
2175 window: &mut Window,
2176 cx: &mut Context<Self>,
2177 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2178 ) -> R {
2179 self.change_selections_inner(autoscroll, true, window, cx, change)
2180 }
2181
2182 fn change_selections_inner<R>(
2183 &mut self,
2184 autoscroll: Option<Autoscroll>,
2185 request_completions: bool,
2186 window: &mut Window,
2187 cx: &mut Context<Self>,
2188 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2189 ) -> R {
2190 let old_cursor_position = self.selections.newest_anchor().head();
2191 self.push_to_selection_history();
2192
2193 let (changed, result) = self.selections.change_with(cx, change);
2194
2195 if changed {
2196 if let Some(autoscroll) = autoscroll {
2197 self.request_autoscroll(autoscroll, cx);
2198 }
2199 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2200
2201 if self.should_open_signature_help_automatically(
2202 &old_cursor_position,
2203 self.signature_help_state.backspace_pressed(),
2204 cx,
2205 ) {
2206 self.show_signature_help(&ShowSignatureHelp, window, cx);
2207 }
2208 self.signature_help_state.set_backspace_pressed(false);
2209 }
2210
2211 result
2212 }
2213
2214 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2215 where
2216 I: IntoIterator<Item = (Range<S>, T)>,
2217 S: ToOffset,
2218 T: Into<Arc<str>>,
2219 {
2220 if self.read_only(cx) {
2221 return;
2222 }
2223
2224 self.buffer
2225 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2226 }
2227
2228 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2229 where
2230 I: IntoIterator<Item = (Range<S>, T)>,
2231 S: ToOffset,
2232 T: Into<Arc<str>>,
2233 {
2234 if self.read_only(cx) {
2235 return;
2236 }
2237
2238 self.buffer.update(cx, |buffer, cx| {
2239 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2240 });
2241 }
2242
2243 pub fn edit_with_block_indent<I, S, T>(
2244 &mut self,
2245 edits: I,
2246 original_indent_columns: Vec<u32>,
2247 cx: &mut Context<Self>,
2248 ) where
2249 I: IntoIterator<Item = (Range<S>, T)>,
2250 S: ToOffset,
2251 T: Into<Arc<str>>,
2252 {
2253 if self.read_only(cx) {
2254 return;
2255 }
2256
2257 self.buffer.update(cx, |buffer, cx| {
2258 buffer.edit(
2259 edits,
2260 Some(AutoindentMode::Block {
2261 original_indent_columns,
2262 }),
2263 cx,
2264 )
2265 });
2266 }
2267
2268 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2269 self.hide_context_menu(window, cx);
2270
2271 match phase {
2272 SelectPhase::Begin {
2273 position,
2274 add,
2275 click_count,
2276 } => self.begin_selection(position, add, click_count, window, cx),
2277 SelectPhase::BeginColumnar {
2278 position,
2279 goal_column,
2280 reset,
2281 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2282 SelectPhase::Extend {
2283 position,
2284 click_count,
2285 } => self.extend_selection(position, click_count, window, cx),
2286 SelectPhase::Update {
2287 position,
2288 goal_column,
2289 scroll_delta,
2290 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2291 SelectPhase::End => self.end_selection(window, cx),
2292 }
2293 }
2294
2295 fn extend_selection(
2296 &mut self,
2297 position: DisplayPoint,
2298 click_count: usize,
2299 window: &mut Window,
2300 cx: &mut Context<Self>,
2301 ) {
2302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2303 let tail = self.selections.newest::<usize>(cx).tail();
2304 self.begin_selection(position, false, click_count, window, cx);
2305
2306 let position = position.to_offset(&display_map, Bias::Left);
2307 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2308
2309 let mut pending_selection = self
2310 .selections
2311 .pending_anchor()
2312 .expect("extend_selection not called with pending selection");
2313 if position >= tail {
2314 pending_selection.start = tail_anchor;
2315 } else {
2316 pending_selection.end = tail_anchor;
2317 pending_selection.reversed = true;
2318 }
2319
2320 let mut pending_mode = self.selections.pending_mode().unwrap();
2321 match &mut pending_mode {
2322 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2323 _ => {}
2324 }
2325
2326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2327 s.set_pending(pending_selection, pending_mode)
2328 });
2329 }
2330
2331 fn begin_selection(
2332 &mut self,
2333 position: DisplayPoint,
2334 add: bool,
2335 click_count: usize,
2336 window: &mut Window,
2337 cx: &mut Context<Self>,
2338 ) {
2339 if !self.focus_handle.is_focused(window) {
2340 self.last_focused_descendant = None;
2341 window.focus(&self.focus_handle);
2342 }
2343
2344 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2345 let buffer = &display_map.buffer_snapshot;
2346 let newest_selection = self.selections.newest_anchor().clone();
2347 let position = display_map.clip_point(position, Bias::Left);
2348
2349 let start;
2350 let end;
2351 let mode;
2352 let mut auto_scroll;
2353 match click_count {
2354 1 => {
2355 start = buffer.anchor_before(position.to_point(&display_map));
2356 end = start;
2357 mode = SelectMode::Character;
2358 auto_scroll = true;
2359 }
2360 2 => {
2361 let range = movement::surrounding_word(&display_map, position);
2362 start = buffer.anchor_before(range.start.to_point(&display_map));
2363 end = buffer.anchor_before(range.end.to_point(&display_map));
2364 mode = SelectMode::Word(start..end);
2365 auto_scroll = true;
2366 }
2367 3 => {
2368 let position = display_map
2369 .clip_point(position, Bias::Left)
2370 .to_point(&display_map);
2371 let line_start = display_map.prev_line_boundary(position).0;
2372 let next_line_start = buffer.clip_point(
2373 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2374 Bias::Left,
2375 );
2376 start = buffer.anchor_before(line_start);
2377 end = buffer.anchor_before(next_line_start);
2378 mode = SelectMode::Line(start..end);
2379 auto_scroll = true;
2380 }
2381 _ => {
2382 start = buffer.anchor_before(0);
2383 end = buffer.anchor_before(buffer.len());
2384 mode = SelectMode::All;
2385 auto_scroll = false;
2386 }
2387 }
2388 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2389
2390 let point_to_delete: Option<usize> = {
2391 let selected_points: Vec<Selection<Point>> =
2392 self.selections.disjoint_in_range(start..end, cx);
2393
2394 if !add || click_count > 1 {
2395 None
2396 } else if !selected_points.is_empty() {
2397 Some(selected_points[0].id)
2398 } else {
2399 let clicked_point_already_selected =
2400 self.selections.disjoint.iter().find(|selection| {
2401 selection.start.to_point(buffer) == start.to_point(buffer)
2402 || selection.end.to_point(buffer) == end.to_point(buffer)
2403 });
2404
2405 clicked_point_already_selected.map(|selection| selection.id)
2406 }
2407 };
2408
2409 let selections_count = self.selections.count();
2410
2411 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2412 if let Some(point_to_delete) = point_to_delete {
2413 s.delete(point_to_delete);
2414
2415 if selections_count == 1 {
2416 s.set_pending_anchor_range(start..end, mode);
2417 }
2418 } else {
2419 if !add {
2420 s.clear_disjoint();
2421 } else if click_count > 1 {
2422 s.delete(newest_selection.id)
2423 }
2424
2425 s.set_pending_anchor_range(start..end, mode);
2426 }
2427 });
2428 }
2429
2430 fn begin_columnar_selection(
2431 &mut self,
2432 position: DisplayPoint,
2433 goal_column: u32,
2434 reset: bool,
2435 window: &mut Window,
2436 cx: &mut Context<Self>,
2437 ) {
2438 if !self.focus_handle.is_focused(window) {
2439 self.last_focused_descendant = None;
2440 window.focus(&self.focus_handle);
2441 }
2442
2443 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2444
2445 if reset {
2446 let pointer_position = display_map
2447 .buffer_snapshot
2448 .anchor_before(position.to_point(&display_map));
2449
2450 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2451 s.clear_disjoint();
2452 s.set_pending_anchor_range(
2453 pointer_position..pointer_position,
2454 SelectMode::Character,
2455 );
2456 });
2457 }
2458
2459 let tail = self.selections.newest::<Point>(cx).tail();
2460 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2461
2462 if !reset {
2463 self.select_columns(
2464 tail.to_display_point(&display_map),
2465 position,
2466 goal_column,
2467 &display_map,
2468 window,
2469 cx,
2470 );
2471 }
2472 }
2473
2474 fn update_selection(
2475 &mut self,
2476 position: DisplayPoint,
2477 goal_column: u32,
2478 scroll_delta: gpui::Point<f32>,
2479 window: &mut Window,
2480 cx: &mut Context<Self>,
2481 ) {
2482 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2483
2484 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2485 let tail = tail.to_display_point(&display_map);
2486 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2487 } else if let Some(mut pending) = self.selections.pending_anchor() {
2488 let buffer = self.buffer.read(cx).snapshot(cx);
2489 let head;
2490 let tail;
2491 let mode = self.selections.pending_mode().unwrap();
2492 match &mode {
2493 SelectMode::Character => {
2494 head = position.to_point(&display_map);
2495 tail = pending.tail().to_point(&buffer);
2496 }
2497 SelectMode::Word(original_range) => {
2498 let original_display_range = original_range.start.to_display_point(&display_map)
2499 ..original_range.end.to_display_point(&display_map);
2500 let original_buffer_range = original_display_range.start.to_point(&display_map)
2501 ..original_display_range.end.to_point(&display_map);
2502 if movement::is_inside_word(&display_map, position)
2503 || original_display_range.contains(&position)
2504 {
2505 let word_range = movement::surrounding_word(&display_map, position);
2506 if word_range.start < original_display_range.start {
2507 head = word_range.start.to_point(&display_map);
2508 } else {
2509 head = word_range.end.to_point(&display_map);
2510 }
2511 } else {
2512 head = position.to_point(&display_map);
2513 }
2514
2515 if head <= original_buffer_range.start {
2516 tail = original_buffer_range.end;
2517 } else {
2518 tail = original_buffer_range.start;
2519 }
2520 }
2521 SelectMode::Line(original_range) => {
2522 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2523
2524 let position = display_map
2525 .clip_point(position, Bias::Left)
2526 .to_point(&display_map);
2527 let line_start = display_map.prev_line_boundary(position).0;
2528 let next_line_start = buffer.clip_point(
2529 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2530 Bias::Left,
2531 );
2532
2533 if line_start < original_range.start {
2534 head = line_start
2535 } else {
2536 head = next_line_start
2537 }
2538
2539 if head <= original_range.start {
2540 tail = original_range.end;
2541 } else {
2542 tail = original_range.start;
2543 }
2544 }
2545 SelectMode::All => {
2546 return;
2547 }
2548 };
2549
2550 if head < tail {
2551 pending.start = buffer.anchor_before(head);
2552 pending.end = buffer.anchor_before(tail);
2553 pending.reversed = true;
2554 } else {
2555 pending.start = buffer.anchor_before(tail);
2556 pending.end = buffer.anchor_before(head);
2557 pending.reversed = false;
2558 }
2559
2560 self.change_selections(None, window, cx, |s| {
2561 s.set_pending(pending, mode);
2562 });
2563 } else {
2564 log::error!("update_selection dispatched with no pending selection");
2565 return;
2566 }
2567
2568 self.apply_scroll_delta(scroll_delta, window, cx);
2569 cx.notify();
2570 }
2571
2572 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2573 self.columnar_selection_tail.take();
2574 if self.selections.pending_anchor().is_some() {
2575 let selections = self.selections.all::<usize>(cx);
2576 self.change_selections(None, window, cx, |s| {
2577 s.select(selections);
2578 s.clear_pending();
2579 });
2580 }
2581 }
2582
2583 fn select_columns(
2584 &mut self,
2585 tail: DisplayPoint,
2586 head: DisplayPoint,
2587 goal_column: u32,
2588 display_map: &DisplaySnapshot,
2589 window: &mut Window,
2590 cx: &mut Context<Self>,
2591 ) {
2592 let start_row = cmp::min(tail.row(), head.row());
2593 let end_row = cmp::max(tail.row(), head.row());
2594 let start_column = cmp::min(tail.column(), goal_column);
2595 let end_column = cmp::max(tail.column(), goal_column);
2596 let reversed = start_column < tail.column();
2597
2598 let selection_ranges = (start_row.0..=end_row.0)
2599 .map(DisplayRow)
2600 .filter_map(|row| {
2601 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2602 let start = display_map
2603 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2604 .to_point(display_map);
2605 let end = display_map
2606 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2607 .to_point(display_map);
2608 if reversed {
2609 Some(end..start)
2610 } else {
2611 Some(start..end)
2612 }
2613 } else {
2614 None
2615 }
2616 })
2617 .collect::<Vec<_>>();
2618
2619 self.change_selections(None, window, cx, |s| {
2620 s.select_ranges(selection_ranges);
2621 });
2622 cx.notify();
2623 }
2624
2625 pub fn has_pending_nonempty_selection(&self) -> bool {
2626 let pending_nonempty_selection = match self.selections.pending_anchor() {
2627 Some(Selection { start, end, .. }) => start != end,
2628 None => false,
2629 };
2630
2631 pending_nonempty_selection
2632 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2633 }
2634
2635 pub fn has_pending_selection(&self) -> bool {
2636 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2637 }
2638
2639 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2640 self.selection_mark_mode = false;
2641
2642 if self.clear_expanded_diff_hunks(cx) {
2643 cx.notify();
2644 return;
2645 }
2646 if self.dismiss_menus_and_popups(true, window, cx) {
2647 return;
2648 }
2649
2650 if self.mode == EditorMode::Full
2651 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2652 {
2653 return;
2654 }
2655
2656 cx.propagate();
2657 }
2658
2659 pub fn dismiss_menus_and_popups(
2660 &mut self,
2661 is_user_requested: bool,
2662 window: &mut Window,
2663 cx: &mut Context<Self>,
2664 ) -> bool {
2665 if self.take_rename(false, window, cx).is_some() {
2666 return true;
2667 }
2668
2669 if hide_hover(self, cx) {
2670 return true;
2671 }
2672
2673 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2674 return true;
2675 }
2676
2677 if self.hide_context_menu(window, cx).is_some() {
2678 return true;
2679 }
2680
2681 if self.mouse_context_menu.take().is_some() {
2682 return true;
2683 }
2684
2685 if is_user_requested && self.discard_inline_completion(true, cx) {
2686 return true;
2687 }
2688
2689 if self.snippet_stack.pop().is_some() {
2690 return true;
2691 }
2692
2693 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2694 self.dismiss_diagnostics(cx);
2695 return true;
2696 }
2697
2698 false
2699 }
2700
2701 fn linked_editing_ranges_for(
2702 &self,
2703 selection: Range<text::Anchor>,
2704 cx: &App,
2705 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2706 if self.linked_edit_ranges.is_empty() {
2707 return None;
2708 }
2709 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2710 selection.end.buffer_id.and_then(|end_buffer_id| {
2711 if selection.start.buffer_id != Some(end_buffer_id) {
2712 return None;
2713 }
2714 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2715 let snapshot = buffer.read(cx).snapshot();
2716 self.linked_edit_ranges
2717 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2718 .map(|ranges| (ranges, snapshot, buffer))
2719 })?;
2720 use text::ToOffset as TO;
2721 // find offset from the start of current range to current cursor position
2722 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2723
2724 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2725 let start_difference = start_offset - start_byte_offset;
2726 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2727 let end_difference = end_offset - start_byte_offset;
2728 // Current range has associated linked ranges.
2729 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2730 for range in linked_ranges.iter() {
2731 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2732 let end_offset = start_offset + end_difference;
2733 let start_offset = start_offset + start_difference;
2734 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2735 continue;
2736 }
2737 if self.selections.disjoint_anchor_ranges().any(|s| {
2738 if s.start.buffer_id != selection.start.buffer_id
2739 || s.end.buffer_id != selection.end.buffer_id
2740 {
2741 return false;
2742 }
2743 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2744 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2745 }) {
2746 continue;
2747 }
2748 let start = buffer_snapshot.anchor_after(start_offset);
2749 let end = buffer_snapshot.anchor_after(end_offset);
2750 linked_edits
2751 .entry(buffer.clone())
2752 .or_default()
2753 .push(start..end);
2754 }
2755 Some(linked_edits)
2756 }
2757
2758 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2759 let text: Arc<str> = text.into();
2760
2761 if self.read_only(cx) {
2762 return;
2763 }
2764
2765 let selections = self.selections.all_adjusted(cx);
2766 let mut bracket_inserted = false;
2767 let mut edits = Vec::new();
2768 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2769 let mut new_selections = Vec::with_capacity(selections.len());
2770 let mut new_autoclose_regions = Vec::new();
2771 let snapshot = self.buffer.read(cx).read(cx);
2772
2773 for (selection, autoclose_region) in
2774 self.selections_with_autoclose_regions(selections, &snapshot)
2775 {
2776 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2777 // Determine if the inserted text matches the opening or closing
2778 // bracket of any of this language's bracket pairs.
2779 let mut bracket_pair = None;
2780 let mut is_bracket_pair_start = false;
2781 let mut is_bracket_pair_end = false;
2782 if !text.is_empty() {
2783 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2784 // and they are removing the character that triggered IME popup.
2785 for (pair, enabled) in scope.brackets() {
2786 if !pair.close && !pair.surround {
2787 continue;
2788 }
2789
2790 if enabled && pair.start.ends_with(text.as_ref()) {
2791 let prefix_len = pair.start.len() - text.len();
2792 let preceding_text_matches_prefix = prefix_len == 0
2793 || (selection.start.column >= (prefix_len as u32)
2794 && snapshot.contains_str_at(
2795 Point::new(
2796 selection.start.row,
2797 selection.start.column - (prefix_len as u32),
2798 ),
2799 &pair.start[..prefix_len],
2800 ));
2801 if preceding_text_matches_prefix {
2802 bracket_pair = Some(pair.clone());
2803 is_bracket_pair_start = true;
2804 break;
2805 }
2806 }
2807 if pair.end.as_str() == text.as_ref() {
2808 bracket_pair = Some(pair.clone());
2809 is_bracket_pair_end = true;
2810 break;
2811 }
2812 }
2813 }
2814
2815 if let Some(bracket_pair) = bracket_pair {
2816 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2817 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2818 let auto_surround =
2819 self.use_auto_surround && snapshot_settings.use_auto_surround;
2820 if selection.is_empty() {
2821 if is_bracket_pair_start {
2822 // If the inserted text is a suffix of an opening bracket and the
2823 // selection is preceded by the rest of the opening bracket, then
2824 // insert the closing bracket.
2825 let following_text_allows_autoclose = snapshot
2826 .chars_at(selection.start)
2827 .next()
2828 .map_or(true, |c| scope.should_autoclose_before(c));
2829
2830 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2831 && bracket_pair.start.len() == 1
2832 {
2833 let target = bracket_pair.start.chars().next().unwrap();
2834 let current_line_count = snapshot
2835 .reversed_chars_at(selection.start)
2836 .take_while(|&c| c != '\n')
2837 .filter(|&c| c == target)
2838 .count();
2839 current_line_count % 2 == 1
2840 } else {
2841 false
2842 };
2843
2844 if autoclose
2845 && bracket_pair.close
2846 && following_text_allows_autoclose
2847 && !is_closing_quote
2848 {
2849 let anchor = snapshot.anchor_before(selection.end);
2850 new_selections.push((selection.map(|_| anchor), text.len()));
2851 new_autoclose_regions.push((
2852 anchor,
2853 text.len(),
2854 selection.id,
2855 bracket_pair.clone(),
2856 ));
2857 edits.push((
2858 selection.range(),
2859 format!("{}{}", text, bracket_pair.end).into(),
2860 ));
2861 bracket_inserted = true;
2862 continue;
2863 }
2864 }
2865
2866 if let Some(region) = autoclose_region {
2867 // If the selection is followed by an auto-inserted closing bracket,
2868 // then don't insert that closing bracket again; just move the selection
2869 // past the closing bracket.
2870 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2871 && text.as_ref() == region.pair.end.as_str();
2872 if should_skip {
2873 let anchor = snapshot.anchor_after(selection.end);
2874 new_selections
2875 .push((selection.map(|_| anchor), region.pair.end.len()));
2876 continue;
2877 }
2878 }
2879
2880 let always_treat_brackets_as_autoclosed = snapshot
2881 .settings_at(selection.start, cx)
2882 .always_treat_brackets_as_autoclosed;
2883 if always_treat_brackets_as_autoclosed
2884 && is_bracket_pair_end
2885 && snapshot.contains_str_at(selection.end, text.as_ref())
2886 {
2887 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2888 // and the inserted text is a closing bracket and the selection is followed
2889 // by the closing bracket then move the selection past the closing bracket.
2890 let anchor = snapshot.anchor_after(selection.end);
2891 new_selections.push((selection.map(|_| anchor), text.len()));
2892 continue;
2893 }
2894 }
2895 // If an opening bracket is 1 character long and is typed while
2896 // text is selected, then surround that text with the bracket pair.
2897 else if auto_surround
2898 && bracket_pair.surround
2899 && is_bracket_pair_start
2900 && bracket_pair.start.chars().count() == 1
2901 {
2902 edits.push((selection.start..selection.start, text.clone()));
2903 edits.push((
2904 selection.end..selection.end,
2905 bracket_pair.end.as_str().into(),
2906 ));
2907 bracket_inserted = true;
2908 new_selections.push((
2909 Selection {
2910 id: selection.id,
2911 start: snapshot.anchor_after(selection.start),
2912 end: snapshot.anchor_before(selection.end),
2913 reversed: selection.reversed,
2914 goal: selection.goal,
2915 },
2916 0,
2917 ));
2918 continue;
2919 }
2920 }
2921 }
2922
2923 if self.auto_replace_emoji_shortcode
2924 && selection.is_empty()
2925 && text.as_ref().ends_with(':')
2926 {
2927 if let Some(possible_emoji_short_code) =
2928 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2929 {
2930 if !possible_emoji_short_code.is_empty() {
2931 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2932 let emoji_shortcode_start = Point::new(
2933 selection.start.row,
2934 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2935 );
2936
2937 // Remove shortcode from buffer
2938 edits.push((
2939 emoji_shortcode_start..selection.start,
2940 "".to_string().into(),
2941 ));
2942 new_selections.push((
2943 Selection {
2944 id: selection.id,
2945 start: snapshot.anchor_after(emoji_shortcode_start),
2946 end: snapshot.anchor_before(selection.start),
2947 reversed: selection.reversed,
2948 goal: selection.goal,
2949 },
2950 0,
2951 ));
2952
2953 // Insert emoji
2954 let selection_start_anchor = snapshot.anchor_after(selection.start);
2955 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2956 edits.push((selection.start..selection.end, emoji.to_string().into()));
2957
2958 continue;
2959 }
2960 }
2961 }
2962 }
2963
2964 // If not handling any auto-close operation, then just replace the selected
2965 // text with the given input and move the selection to the end of the
2966 // newly inserted text.
2967 let anchor = snapshot.anchor_after(selection.end);
2968 if !self.linked_edit_ranges.is_empty() {
2969 let start_anchor = snapshot.anchor_before(selection.start);
2970
2971 let is_word_char = text.chars().next().map_or(true, |char| {
2972 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2973 classifier.is_word(char)
2974 });
2975
2976 if is_word_char {
2977 if let Some(ranges) = self
2978 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2979 {
2980 for (buffer, edits) in ranges {
2981 linked_edits
2982 .entry(buffer.clone())
2983 .or_default()
2984 .extend(edits.into_iter().map(|range| (range, text.clone())));
2985 }
2986 }
2987 }
2988 }
2989
2990 new_selections.push((selection.map(|_| anchor), 0));
2991 edits.push((selection.start..selection.end, text.clone()));
2992 }
2993
2994 drop(snapshot);
2995
2996 self.transact(window, cx, |this, window, cx| {
2997 this.buffer.update(cx, |buffer, cx| {
2998 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2999 });
3000 for (buffer, edits) in linked_edits {
3001 buffer.update(cx, |buffer, cx| {
3002 let snapshot = buffer.snapshot();
3003 let edits = edits
3004 .into_iter()
3005 .map(|(range, text)| {
3006 use text::ToPoint as TP;
3007 let end_point = TP::to_point(&range.end, &snapshot);
3008 let start_point = TP::to_point(&range.start, &snapshot);
3009 (start_point..end_point, text)
3010 })
3011 .sorted_by_key(|(range, _)| range.start)
3012 .collect::<Vec<_>>();
3013 buffer.edit(edits, None, cx);
3014 })
3015 }
3016 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3017 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3018 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3019 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3020 .zip(new_selection_deltas)
3021 .map(|(selection, delta)| Selection {
3022 id: selection.id,
3023 start: selection.start + delta,
3024 end: selection.end + delta,
3025 reversed: selection.reversed,
3026 goal: SelectionGoal::None,
3027 })
3028 .collect::<Vec<_>>();
3029
3030 let mut i = 0;
3031 for (position, delta, selection_id, pair) in new_autoclose_regions {
3032 let position = position.to_offset(&map.buffer_snapshot) + delta;
3033 let start = map.buffer_snapshot.anchor_before(position);
3034 let end = map.buffer_snapshot.anchor_after(position);
3035 while let Some(existing_state) = this.autoclose_regions.get(i) {
3036 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3037 Ordering::Less => i += 1,
3038 Ordering::Greater => break,
3039 Ordering::Equal => {
3040 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3041 Ordering::Less => i += 1,
3042 Ordering::Equal => break,
3043 Ordering::Greater => break,
3044 }
3045 }
3046 }
3047 }
3048 this.autoclose_regions.insert(
3049 i,
3050 AutocloseRegion {
3051 selection_id,
3052 range: start..end,
3053 pair,
3054 },
3055 );
3056 }
3057
3058 let had_active_inline_completion = this.has_active_inline_completion();
3059 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3060 s.select(new_selections)
3061 });
3062
3063 if !bracket_inserted {
3064 if let Some(on_type_format_task) =
3065 this.trigger_on_type_formatting(text.to_string(), window, cx)
3066 {
3067 on_type_format_task.detach_and_log_err(cx);
3068 }
3069 }
3070
3071 let editor_settings = EditorSettings::get_global(cx);
3072 if bracket_inserted
3073 && (editor_settings.auto_signature_help
3074 || editor_settings.show_signature_help_after_edits)
3075 {
3076 this.show_signature_help(&ShowSignatureHelp, window, cx);
3077 }
3078
3079 let trigger_in_words =
3080 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3081 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3082 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3083 this.refresh_inline_completion(true, false, window, cx);
3084 });
3085 }
3086
3087 fn find_possible_emoji_shortcode_at_position(
3088 snapshot: &MultiBufferSnapshot,
3089 position: Point,
3090 ) -> Option<String> {
3091 let mut chars = Vec::new();
3092 let mut found_colon = false;
3093 for char in snapshot.reversed_chars_at(position).take(100) {
3094 // Found a possible emoji shortcode in the middle of the buffer
3095 if found_colon {
3096 if char.is_whitespace() {
3097 chars.reverse();
3098 return Some(chars.iter().collect());
3099 }
3100 // If the previous character is not a whitespace, we are in the middle of a word
3101 // and we only want to complete the shortcode if the word is made up of other emojis
3102 let mut containing_word = String::new();
3103 for ch in snapshot
3104 .reversed_chars_at(position)
3105 .skip(chars.len() + 1)
3106 .take(100)
3107 {
3108 if ch.is_whitespace() {
3109 break;
3110 }
3111 containing_word.push(ch);
3112 }
3113 let containing_word = containing_word.chars().rev().collect::<String>();
3114 if util::word_consists_of_emojis(containing_word.as_str()) {
3115 chars.reverse();
3116 return Some(chars.iter().collect());
3117 }
3118 }
3119
3120 if char.is_whitespace() || !char.is_ascii() {
3121 return None;
3122 }
3123 if char == ':' {
3124 found_colon = true;
3125 } else {
3126 chars.push(char);
3127 }
3128 }
3129 // Found a possible emoji shortcode at the beginning of the buffer
3130 chars.reverse();
3131 Some(chars.iter().collect())
3132 }
3133
3134 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3135 self.transact(window, cx, |this, window, cx| {
3136 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3137 let selections = this.selections.all::<usize>(cx);
3138 let multi_buffer = this.buffer.read(cx);
3139 let buffer = multi_buffer.snapshot(cx);
3140 selections
3141 .iter()
3142 .map(|selection| {
3143 let start_point = selection.start.to_point(&buffer);
3144 let mut indent =
3145 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3146 indent.len = cmp::min(indent.len, start_point.column);
3147 let start = selection.start;
3148 let end = selection.end;
3149 let selection_is_empty = start == end;
3150 let language_scope = buffer.language_scope_at(start);
3151 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3152 &language_scope
3153 {
3154 let leading_whitespace_len = buffer
3155 .reversed_chars_at(start)
3156 .take_while(|c| c.is_whitespace() && *c != '\n')
3157 .map(|c| c.len_utf8())
3158 .sum::<usize>();
3159
3160 let trailing_whitespace_len = buffer
3161 .chars_at(end)
3162 .take_while(|c| c.is_whitespace() && *c != '\n')
3163 .map(|c| c.len_utf8())
3164 .sum::<usize>();
3165
3166 let insert_extra_newline =
3167 language.brackets().any(|(pair, enabled)| {
3168 let pair_start = pair.start.trim_end();
3169 let pair_end = pair.end.trim_start();
3170
3171 enabled
3172 && pair.newline
3173 && buffer.contains_str_at(
3174 end + trailing_whitespace_len,
3175 pair_end,
3176 )
3177 && buffer.contains_str_at(
3178 (start - leading_whitespace_len)
3179 .saturating_sub(pair_start.len()),
3180 pair_start,
3181 )
3182 });
3183
3184 // Comment extension on newline is allowed only for cursor selections
3185 let comment_delimiter = maybe!({
3186 if !selection_is_empty {
3187 return None;
3188 }
3189
3190 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3191 return None;
3192 }
3193
3194 let delimiters = language.line_comment_prefixes();
3195 let max_len_of_delimiter =
3196 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3197 let (snapshot, range) =
3198 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3199
3200 let mut index_of_first_non_whitespace = 0;
3201 let comment_candidate = snapshot
3202 .chars_for_range(range)
3203 .skip_while(|c| {
3204 let should_skip = c.is_whitespace();
3205 if should_skip {
3206 index_of_first_non_whitespace += 1;
3207 }
3208 should_skip
3209 })
3210 .take(max_len_of_delimiter)
3211 .collect::<String>();
3212 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3213 comment_candidate.starts_with(comment_prefix.as_ref())
3214 })?;
3215 let cursor_is_placed_after_comment_marker =
3216 index_of_first_non_whitespace + comment_prefix.len()
3217 <= start_point.column as usize;
3218 if cursor_is_placed_after_comment_marker {
3219 Some(comment_prefix.clone())
3220 } else {
3221 None
3222 }
3223 });
3224 (comment_delimiter, insert_extra_newline)
3225 } else {
3226 (None, false)
3227 };
3228
3229 let capacity_for_delimiter = comment_delimiter
3230 .as_deref()
3231 .map(str::len)
3232 .unwrap_or_default();
3233 let mut new_text =
3234 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3235 new_text.push('\n');
3236 new_text.extend(indent.chars());
3237 if let Some(delimiter) = &comment_delimiter {
3238 new_text.push_str(delimiter);
3239 }
3240 if insert_extra_newline {
3241 new_text = new_text.repeat(2);
3242 }
3243
3244 let anchor = buffer.anchor_after(end);
3245 let new_selection = selection.map(|_| anchor);
3246 (
3247 (start..end, new_text),
3248 (insert_extra_newline, new_selection),
3249 )
3250 })
3251 .unzip()
3252 };
3253
3254 this.edit_with_autoindent(edits, cx);
3255 let buffer = this.buffer.read(cx).snapshot(cx);
3256 let new_selections = selection_fixup_info
3257 .into_iter()
3258 .map(|(extra_newline_inserted, new_selection)| {
3259 let mut cursor = new_selection.end.to_point(&buffer);
3260 if extra_newline_inserted {
3261 cursor.row -= 1;
3262 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3263 }
3264 new_selection.map(|_| cursor)
3265 })
3266 .collect();
3267
3268 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3269 s.select(new_selections)
3270 });
3271 this.refresh_inline_completion(true, false, window, cx);
3272 });
3273 }
3274
3275 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3276 let buffer = self.buffer.read(cx);
3277 let snapshot = buffer.snapshot(cx);
3278
3279 let mut edits = Vec::new();
3280 let mut rows = Vec::new();
3281
3282 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3283 let cursor = selection.head();
3284 let row = cursor.row;
3285
3286 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3287
3288 let newline = "\n".to_string();
3289 edits.push((start_of_line..start_of_line, newline));
3290
3291 rows.push(row + rows_inserted as u32);
3292 }
3293
3294 self.transact(window, cx, |editor, window, cx| {
3295 editor.edit(edits, cx);
3296
3297 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3298 let mut index = 0;
3299 s.move_cursors_with(|map, _, _| {
3300 let row = rows[index];
3301 index += 1;
3302
3303 let point = Point::new(row, 0);
3304 let boundary = map.next_line_boundary(point).1;
3305 let clipped = map.clip_point(boundary, Bias::Left);
3306
3307 (clipped, SelectionGoal::None)
3308 });
3309 });
3310
3311 let mut indent_edits = Vec::new();
3312 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3313 for row in rows {
3314 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3315 for (row, indent) in indents {
3316 if indent.len == 0 {
3317 continue;
3318 }
3319
3320 let text = match indent.kind {
3321 IndentKind::Space => " ".repeat(indent.len as usize),
3322 IndentKind::Tab => "\t".repeat(indent.len as usize),
3323 };
3324 let point = Point::new(row.0, 0);
3325 indent_edits.push((point..point, text));
3326 }
3327 }
3328 editor.edit(indent_edits, cx);
3329 });
3330 }
3331
3332 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3333 let buffer = self.buffer.read(cx);
3334 let snapshot = buffer.snapshot(cx);
3335
3336 let mut edits = Vec::new();
3337 let mut rows = Vec::new();
3338 let mut rows_inserted = 0;
3339
3340 for selection in self.selections.all_adjusted(cx) {
3341 let cursor = selection.head();
3342 let row = cursor.row;
3343
3344 let point = Point::new(row + 1, 0);
3345 let start_of_line = snapshot.clip_point(point, Bias::Left);
3346
3347 let newline = "\n".to_string();
3348 edits.push((start_of_line..start_of_line, newline));
3349
3350 rows_inserted += 1;
3351 rows.push(row + rows_inserted);
3352 }
3353
3354 self.transact(window, cx, |editor, window, cx| {
3355 editor.edit(edits, cx);
3356
3357 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3358 let mut index = 0;
3359 s.move_cursors_with(|map, _, _| {
3360 let row = rows[index];
3361 index += 1;
3362
3363 let point = Point::new(row, 0);
3364 let boundary = map.next_line_boundary(point).1;
3365 let clipped = map.clip_point(boundary, Bias::Left);
3366
3367 (clipped, SelectionGoal::None)
3368 });
3369 });
3370
3371 let mut indent_edits = Vec::new();
3372 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3373 for row in rows {
3374 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3375 for (row, indent) in indents {
3376 if indent.len == 0 {
3377 continue;
3378 }
3379
3380 let text = match indent.kind {
3381 IndentKind::Space => " ".repeat(indent.len as usize),
3382 IndentKind::Tab => "\t".repeat(indent.len as usize),
3383 };
3384 let point = Point::new(row.0, 0);
3385 indent_edits.push((point..point, text));
3386 }
3387 }
3388 editor.edit(indent_edits, cx);
3389 });
3390 }
3391
3392 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3393 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3394 original_indent_columns: Vec::new(),
3395 });
3396 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3397 }
3398
3399 fn insert_with_autoindent_mode(
3400 &mut self,
3401 text: &str,
3402 autoindent_mode: Option<AutoindentMode>,
3403 window: &mut Window,
3404 cx: &mut Context<Self>,
3405 ) {
3406 if self.read_only(cx) {
3407 return;
3408 }
3409
3410 let text: Arc<str> = text.into();
3411 self.transact(window, cx, |this, window, cx| {
3412 let old_selections = this.selections.all_adjusted(cx);
3413 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3414 let anchors = {
3415 let snapshot = buffer.read(cx);
3416 old_selections
3417 .iter()
3418 .map(|s| {
3419 let anchor = snapshot.anchor_after(s.head());
3420 s.map(|_| anchor)
3421 })
3422 .collect::<Vec<_>>()
3423 };
3424 buffer.edit(
3425 old_selections
3426 .iter()
3427 .map(|s| (s.start..s.end, text.clone())),
3428 autoindent_mode,
3429 cx,
3430 );
3431 anchors
3432 });
3433
3434 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3435 s.select_anchors(selection_anchors);
3436 });
3437
3438 cx.notify();
3439 });
3440 }
3441
3442 fn trigger_completion_on_input(
3443 &mut self,
3444 text: &str,
3445 trigger_in_words: bool,
3446 window: &mut Window,
3447 cx: &mut Context<Self>,
3448 ) {
3449 if self.is_completion_trigger(text, trigger_in_words, cx) {
3450 self.show_completions(
3451 &ShowCompletions {
3452 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3453 },
3454 window,
3455 cx,
3456 );
3457 } else {
3458 self.hide_context_menu(window, cx);
3459 }
3460 }
3461
3462 fn is_completion_trigger(
3463 &self,
3464 text: &str,
3465 trigger_in_words: bool,
3466 cx: &mut Context<Self>,
3467 ) -> bool {
3468 let position = self.selections.newest_anchor().head();
3469 let multibuffer = self.buffer.read(cx);
3470 let Some(buffer) = position
3471 .buffer_id
3472 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3473 else {
3474 return false;
3475 };
3476
3477 if let Some(completion_provider) = &self.completion_provider {
3478 completion_provider.is_completion_trigger(
3479 &buffer,
3480 position.text_anchor,
3481 text,
3482 trigger_in_words,
3483 cx,
3484 )
3485 } else {
3486 false
3487 }
3488 }
3489
3490 /// If any empty selections is touching the start of its innermost containing autoclose
3491 /// region, expand it to select the brackets.
3492 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3493 let selections = self.selections.all::<usize>(cx);
3494 let buffer = self.buffer.read(cx).read(cx);
3495 let new_selections = self
3496 .selections_with_autoclose_regions(selections, &buffer)
3497 .map(|(mut selection, region)| {
3498 if !selection.is_empty() {
3499 return selection;
3500 }
3501
3502 if let Some(region) = region {
3503 let mut range = region.range.to_offset(&buffer);
3504 if selection.start == range.start && range.start >= region.pair.start.len() {
3505 range.start -= region.pair.start.len();
3506 if buffer.contains_str_at(range.start, ®ion.pair.start)
3507 && buffer.contains_str_at(range.end, ®ion.pair.end)
3508 {
3509 range.end += region.pair.end.len();
3510 selection.start = range.start;
3511 selection.end = range.end;
3512
3513 return selection;
3514 }
3515 }
3516 }
3517
3518 let always_treat_brackets_as_autoclosed = buffer
3519 .settings_at(selection.start, cx)
3520 .always_treat_brackets_as_autoclosed;
3521
3522 if !always_treat_brackets_as_autoclosed {
3523 return selection;
3524 }
3525
3526 if let Some(scope) = buffer.language_scope_at(selection.start) {
3527 for (pair, enabled) in scope.brackets() {
3528 if !enabled || !pair.close {
3529 continue;
3530 }
3531
3532 if buffer.contains_str_at(selection.start, &pair.end) {
3533 let pair_start_len = pair.start.len();
3534 if buffer.contains_str_at(
3535 selection.start.saturating_sub(pair_start_len),
3536 &pair.start,
3537 ) {
3538 selection.start -= pair_start_len;
3539 selection.end += pair.end.len();
3540
3541 return selection;
3542 }
3543 }
3544 }
3545 }
3546
3547 selection
3548 })
3549 .collect();
3550
3551 drop(buffer);
3552 self.change_selections(None, window, cx, |selections| {
3553 selections.select(new_selections)
3554 });
3555 }
3556
3557 /// Iterate the given selections, and for each one, find the smallest surrounding
3558 /// autoclose region. This uses the ordering of the selections and the autoclose
3559 /// regions to avoid repeated comparisons.
3560 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3561 &'a self,
3562 selections: impl IntoIterator<Item = Selection<D>>,
3563 buffer: &'a MultiBufferSnapshot,
3564 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3565 let mut i = 0;
3566 let mut regions = self.autoclose_regions.as_slice();
3567 selections.into_iter().map(move |selection| {
3568 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3569
3570 let mut enclosing = None;
3571 while let Some(pair_state) = regions.get(i) {
3572 if pair_state.range.end.to_offset(buffer) < range.start {
3573 regions = ®ions[i + 1..];
3574 i = 0;
3575 } else if pair_state.range.start.to_offset(buffer) > range.end {
3576 break;
3577 } else {
3578 if pair_state.selection_id == selection.id {
3579 enclosing = Some(pair_state);
3580 }
3581 i += 1;
3582 }
3583 }
3584
3585 (selection, enclosing)
3586 })
3587 }
3588
3589 /// Remove any autoclose regions that no longer contain their selection.
3590 fn invalidate_autoclose_regions(
3591 &mut self,
3592 mut selections: &[Selection<Anchor>],
3593 buffer: &MultiBufferSnapshot,
3594 ) {
3595 self.autoclose_regions.retain(|state| {
3596 let mut i = 0;
3597 while let Some(selection) = selections.get(i) {
3598 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3599 selections = &selections[1..];
3600 continue;
3601 }
3602 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3603 break;
3604 }
3605 if selection.id == state.selection_id {
3606 return true;
3607 } else {
3608 i += 1;
3609 }
3610 }
3611 false
3612 });
3613 }
3614
3615 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3616 let offset = position.to_offset(buffer);
3617 let (word_range, kind) = buffer.surrounding_word(offset, true);
3618 if offset > word_range.start && kind == Some(CharKind::Word) {
3619 Some(
3620 buffer
3621 .text_for_range(word_range.start..offset)
3622 .collect::<String>(),
3623 )
3624 } else {
3625 None
3626 }
3627 }
3628
3629 pub fn toggle_inlay_hints(
3630 &mut self,
3631 _: &ToggleInlayHints,
3632 _: &mut Window,
3633 cx: &mut Context<Self>,
3634 ) {
3635 self.refresh_inlay_hints(
3636 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3637 cx,
3638 );
3639 }
3640
3641 pub fn inlay_hints_enabled(&self) -> bool {
3642 self.inlay_hint_cache.enabled
3643 }
3644
3645 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3646 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3647 return;
3648 }
3649
3650 let reason_description = reason.description();
3651 let ignore_debounce = matches!(
3652 reason,
3653 InlayHintRefreshReason::SettingsChange(_)
3654 | InlayHintRefreshReason::Toggle(_)
3655 | InlayHintRefreshReason::ExcerptsRemoved(_)
3656 );
3657 let (invalidate_cache, required_languages) = match reason {
3658 InlayHintRefreshReason::Toggle(enabled) => {
3659 self.inlay_hint_cache.enabled = enabled;
3660 if enabled {
3661 (InvalidationStrategy::RefreshRequested, None)
3662 } else {
3663 self.inlay_hint_cache.clear();
3664 self.splice_inlays(
3665 &self
3666 .visible_inlay_hints(cx)
3667 .iter()
3668 .map(|inlay| inlay.id)
3669 .collect::<Vec<InlayId>>(),
3670 Vec::new(),
3671 cx,
3672 );
3673 return;
3674 }
3675 }
3676 InlayHintRefreshReason::SettingsChange(new_settings) => {
3677 match self.inlay_hint_cache.update_settings(
3678 &self.buffer,
3679 new_settings,
3680 self.visible_inlay_hints(cx),
3681 cx,
3682 ) {
3683 ControlFlow::Break(Some(InlaySplice {
3684 to_remove,
3685 to_insert,
3686 })) => {
3687 self.splice_inlays(&to_remove, to_insert, cx);
3688 return;
3689 }
3690 ControlFlow::Break(None) => return,
3691 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3692 }
3693 }
3694 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3695 if let Some(InlaySplice {
3696 to_remove,
3697 to_insert,
3698 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3699 {
3700 self.splice_inlays(&to_remove, to_insert, cx);
3701 }
3702 return;
3703 }
3704 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3705 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3706 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3707 }
3708 InlayHintRefreshReason::RefreshRequested => {
3709 (InvalidationStrategy::RefreshRequested, None)
3710 }
3711 };
3712
3713 if let Some(InlaySplice {
3714 to_remove,
3715 to_insert,
3716 }) = self.inlay_hint_cache.spawn_hint_refresh(
3717 reason_description,
3718 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3719 invalidate_cache,
3720 ignore_debounce,
3721 cx,
3722 ) {
3723 self.splice_inlays(&to_remove, to_insert, cx);
3724 }
3725 }
3726
3727 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3728 self.display_map
3729 .read(cx)
3730 .current_inlays()
3731 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3732 .cloned()
3733 .collect()
3734 }
3735
3736 pub fn excerpts_for_inlay_hints_query(
3737 &self,
3738 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3739 cx: &mut Context<Editor>,
3740 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3741 let Some(project) = self.project.as_ref() else {
3742 return HashMap::default();
3743 };
3744 let project = project.read(cx);
3745 let multi_buffer = self.buffer().read(cx);
3746 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3747 let multi_buffer_visible_start = self
3748 .scroll_manager
3749 .anchor()
3750 .anchor
3751 .to_point(&multi_buffer_snapshot);
3752 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3753 multi_buffer_visible_start
3754 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3755 Bias::Left,
3756 );
3757 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3758 multi_buffer_snapshot
3759 .range_to_buffer_ranges(multi_buffer_visible_range)
3760 .into_iter()
3761 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3762 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3763 let buffer_file = project::File::from_dyn(buffer.file())?;
3764 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3765 let worktree_entry = buffer_worktree
3766 .read(cx)
3767 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3768 if worktree_entry.is_ignored {
3769 return None;
3770 }
3771
3772 let language = buffer.language()?;
3773 if let Some(restrict_to_languages) = restrict_to_languages {
3774 if !restrict_to_languages.contains(language) {
3775 return None;
3776 }
3777 }
3778 Some((
3779 excerpt_id,
3780 (
3781 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3782 buffer.version().clone(),
3783 excerpt_visible_range,
3784 ),
3785 ))
3786 })
3787 .collect()
3788 }
3789
3790 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3791 TextLayoutDetails {
3792 text_system: window.text_system().clone(),
3793 editor_style: self.style.clone().unwrap(),
3794 rem_size: window.rem_size(),
3795 scroll_anchor: self.scroll_manager.anchor(),
3796 visible_rows: self.visible_line_count(),
3797 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3798 }
3799 }
3800
3801 pub fn splice_inlays(
3802 &self,
3803 to_remove: &[InlayId],
3804 to_insert: Vec<Inlay>,
3805 cx: &mut Context<Self>,
3806 ) {
3807 self.display_map.update(cx, |display_map, cx| {
3808 display_map.splice_inlays(to_remove, to_insert, cx)
3809 });
3810 cx.notify();
3811 }
3812
3813 fn trigger_on_type_formatting(
3814 &self,
3815 input: String,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) -> Option<Task<Result<()>>> {
3819 if input.len() != 1 {
3820 return None;
3821 }
3822
3823 let project = self.project.as_ref()?;
3824 let position = self.selections.newest_anchor().head();
3825 let (buffer, buffer_position) = self
3826 .buffer
3827 .read(cx)
3828 .text_anchor_for_position(position, cx)?;
3829
3830 let settings = language_settings::language_settings(
3831 buffer
3832 .read(cx)
3833 .language_at(buffer_position)
3834 .map(|l| l.name()),
3835 buffer.read(cx).file(),
3836 cx,
3837 );
3838 if !settings.use_on_type_format {
3839 return None;
3840 }
3841
3842 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3843 // hence we do LSP request & edit on host side only — add formats to host's history.
3844 let push_to_lsp_host_history = true;
3845 // If this is not the host, append its history with new edits.
3846 let push_to_client_history = project.read(cx).is_via_collab();
3847
3848 let on_type_formatting = project.update(cx, |project, cx| {
3849 project.on_type_format(
3850 buffer.clone(),
3851 buffer_position,
3852 input,
3853 push_to_lsp_host_history,
3854 cx,
3855 )
3856 });
3857 Some(cx.spawn_in(window, |editor, mut cx| async move {
3858 if let Some(transaction) = on_type_formatting.await? {
3859 if push_to_client_history {
3860 buffer
3861 .update(&mut cx, |buffer, _| {
3862 buffer.push_transaction(transaction, Instant::now());
3863 })
3864 .ok();
3865 }
3866 editor.update(&mut cx, |editor, cx| {
3867 editor.refresh_document_highlights(cx);
3868 })?;
3869 }
3870 Ok(())
3871 }))
3872 }
3873
3874 pub fn show_completions(
3875 &mut self,
3876 options: &ShowCompletions,
3877 window: &mut Window,
3878 cx: &mut Context<Self>,
3879 ) {
3880 if self.pending_rename.is_some() {
3881 return;
3882 }
3883
3884 let Some(provider) = self.completion_provider.as_ref() else {
3885 return;
3886 };
3887
3888 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3889 return;
3890 }
3891
3892 let position = self.selections.newest_anchor().head();
3893 if position.diff_base_anchor.is_some() {
3894 return;
3895 }
3896 let (buffer, buffer_position) =
3897 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3898 output
3899 } else {
3900 return;
3901 };
3902 let show_completion_documentation = buffer
3903 .read(cx)
3904 .snapshot()
3905 .settings_at(buffer_position, cx)
3906 .show_completion_documentation;
3907
3908 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3909
3910 let trigger_kind = match &options.trigger {
3911 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3912 CompletionTriggerKind::TRIGGER_CHARACTER
3913 }
3914 _ => CompletionTriggerKind::INVOKED,
3915 };
3916 let completion_context = CompletionContext {
3917 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3918 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3919 Some(String::from(trigger))
3920 } else {
3921 None
3922 }
3923 }),
3924 trigger_kind,
3925 };
3926 let completions =
3927 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3928 let sort_completions = provider.sort_completions();
3929
3930 let id = post_inc(&mut self.next_completion_id);
3931 let task = cx.spawn_in(window, |editor, mut cx| {
3932 async move {
3933 editor.update(&mut cx, |this, _| {
3934 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3935 })?;
3936 let completions = completions.await.log_err();
3937 let menu = if let Some(completions) = completions {
3938 let mut menu = CompletionsMenu::new(
3939 id,
3940 sort_completions,
3941 show_completion_documentation,
3942 position,
3943 buffer.clone(),
3944 completions.into(),
3945 );
3946
3947 menu.filter(query.as_deref(), cx.background_executor().clone())
3948 .await;
3949
3950 menu.visible().then_some(menu)
3951 } else {
3952 None
3953 };
3954
3955 editor.update_in(&mut cx, |editor, window, cx| {
3956 match editor.context_menu.borrow().as_ref() {
3957 None => {}
3958 Some(CodeContextMenu::Completions(prev_menu)) => {
3959 if prev_menu.id > id {
3960 return;
3961 }
3962 }
3963 _ => return,
3964 }
3965
3966 if editor.focus_handle.is_focused(window) && menu.is_some() {
3967 let mut menu = menu.unwrap();
3968 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3969
3970 *editor.context_menu.borrow_mut() =
3971 Some(CodeContextMenu::Completions(menu));
3972
3973 if editor.show_edit_predictions_in_menu() {
3974 editor.update_visible_inline_completion(window, cx);
3975 } else {
3976 editor.discard_inline_completion(false, cx);
3977 }
3978
3979 cx.notify();
3980 } else if editor.completion_tasks.len() <= 1 {
3981 // If there are no more completion tasks and the last menu was
3982 // empty, we should hide it.
3983 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3984 // If it was already hidden and we don't show inline
3985 // completions in the menu, we should also show the
3986 // inline-completion when available.
3987 if was_hidden && editor.show_edit_predictions_in_menu() {
3988 editor.update_visible_inline_completion(window, cx);
3989 }
3990 }
3991 })?;
3992
3993 Ok::<_, anyhow::Error>(())
3994 }
3995 .log_err()
3996 });
3997
3998 self.completion_tasks.push((id, task));
3999 }
4000
4001 pub fn confirm_completion(
4002 &mut self,
4003 action: &ConfirmCompletion,
4004 window: &mut Window,
4005 cx: &mut Context<Self>,
4006 ) -> Option<Task<Result<()>>> {
4007 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4008 }
4009
4010 pub fn compose_completion(
4011 &mut self,
4012 action: &ComposeCompletion,
4013 window: &mut Window,
4014 cx: &mut Context<Self>,
4015 ) -> Option<Task<Result<()>>> {
4016 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4017 }
4018
4019 fn do_completion(
4020 &mut self,
4021 item_ix: Option<usize>,
4022 intent: CompletionIntent,
4023 window: &mut Window,
4024 cx: &mut Context<Editor>,
4025 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4026 use language::ToOffset as _;
4027
4028 let completions_menu =
4029 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4030 menu
4031 } else {
4032 return None;
4033 };
4034
4035 let entries = completions_menu.entries.borrow();
4036 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4037 if self.show_edit_predictions_in_menu() {
4038 self.discard_inline_completion(true, cx);
4039 }
4040 let candidate_id = mat.candidate_id;
4041 drop(entries);
4042
4043 let buffer_handle = completions_menu.buffer;
4044 let completion = completions_menu
4045 .completions
4046 .borrow()
4047 .get(candidate_id)?
4048 .clone();
4049 cx.stop_propagation();
4050
4051 let snippet;
4052 let text;
4053
4054 if completion.is_snippet() {
4055 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4056 text = snippet.as_ref().unwrap().text.clone();
4057 } else {
4058 snippet = None;
4059 text = completion.new_text.clone();
4060 };
4061 let selections = self.selections.all::<usize>(cx);
4062 let buffer = buffer_handle.read(cx);
4063 let old_range = completion.old_range.to_offset(buffer);
4064 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4065
4066 let newest_selection = self.selections.newest_anchor();
4067 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4068 return None;
4069 }
4070
4071 let lookbehind = newest_selection
4072 .start
4073 .text_anchor
4074 .to_offset(buffer)
4075 .saturating_sub(old_range.start);
4076 let lookahead = old_range
4077 .end
4078 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4079 let mut common_prefix_len = old_text
4080 .bytes()
4081 .zip(text.bytes())
4082 .take_while(|(a, b)| a == b)
4083 .count();
4084
4085 let snapshot = self.buffer.read(cx).snapshot(cx);
4086 let mut range_to_replace: Option<Range<isize>> = None;
4087 let mut ranges = Vec::new();
4088 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4089 for selection in &selections {
4090 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4091 let start = selection.start.saturating_sub(lookbehind);
4092 let end = selection.end + lookahead;
4093 if selection.id == newest_selection.id {
4094 range_to_replace = Some(
4095 ((start + common_prefix_len) as isize - selection.start as isize)
4096 ..(end as isize - selection.start as isize),
4097 );
4098 }
4099 ranges.push(start + common_prefix_len..end);
4100 } else {
4101 common_prefix_len = 0;
4102 ranges.clear();
4103 ranges.extend(selections.iter().map(|s| {
4104 if s.id == newest_selection.id {
4105 range_to_replace = Some(
4106 old_range.start.to_offset_utf16(&snapshot).0 as isize
4107 - selection.start as isize
4108 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4109 - selection.start as isize,
4110 );
4111 old_range.clone()
4112 } else {
4113 s.start..s.end
4114 }
4115 }));
4116 break;
4117 }
4118 if !self.linked_edit_ranges.is_empty() {
4119 let start_anchor = snapshot.anchor_before(selection.head());
4120 let end_anchor = snapshot.anchor_after(selection.tail());
4121 if let Some(ranges) = self
4122 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4123 {
4124 for (buffer, edits) in ranges {
4125 linked_edits.entry(buffer.clone()).or_default().extend(
4126 edits
4127 .into_iter()
4128 .map(|range| (range, text[common_prefix_len..].to_owned())),
4129 );
4130 }
4131 }
4132 }
4133 }
4134 let text = &text[common_prefix_len..];
4135
4136 cx.emit(EditorEvent::InputHandled {
4137 utf16_range_to_replace: range_to_replace,
4138 text: text.into(),
4139 });
4140
4141 self.transact(window, cx, |this, window, cx| {
4142 if let Some(mut snippet) = snippet {
4143 snippet.text = text.to_string();
4144 for tabstop in snippet
4145 .tabstops
4146 .iter_mut()
4147 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4148 {
4149 tabstop.start -= common_prefix_len as isize;
4150 tabstop.end -= common_prefix_len as isize;
4151 }
4152
4153 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4154 } else {
4155 this.buffer.update(cx, |buffer, cx| {
4156 buffer.edit(
4157 ranges.iter().map(|range| (range.clone(), text)),
4158 this.autoindent_mode.clone(),
4159 cx,
4160 );
4161 });
4162 }
4163 for (buffer, edits) in linked_edits {
4164 buffer.update(cx, |buffer, cx| {
4165 let snapshot = buffer.snapshot();
4166 let edits = edits
4167 .into_iter()
4168 .map(|(range, text)| {
4169 use text::ToPoint as TP;
4170 let end_point = TP::to_point(&range.end, &snapshot);
4171 let start_point = TP::to_point(&range.start, &snapshot);
4172 (start_point..end_point, text)
4173 })
4174 .sorted_by_key(|(range, _)| range.start)
4175 .collect::<Vec<_>>();
4176 buffer.edit(edits, None, cx);
4177 })
4178 }
4179
4180 this.refresh_inline_completion(true, false, window, cx);
4181 });
4182
4183 let show_new_completions_on_confirm = completion
4184 .confirm
4185 .as_ref()
4186 .map_or(false, |confirm| confirm(intent, window, cx));
4187 if show_new_completions_on_confirm {
4188 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4189 }
4190
4191 let provider = self.completion_provider.as_ref()?;
4192 drop(completion);
4193 let apply_edits = provider.apply_additional_edits_for_completion(
4194 buffer_handle,
4195 completions_menu.completions.clone(),
4196 candidate_id,
4197 true,
4198 cx,
4199 );
4200
4201 let editor_settings = EditorSettings::get_global(cx);
4202 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4203 // After the code completion is finished, users often want to know what signatures are needed.
4204 // so we should automatically call signature_help
4205 self.show_signature_help(&ShowSignatureHelp, window, cx);
4206 }
4207
4208 Some(cx.foreground_executor().spawn(async move {
4209 apply_edits.await?;
4210 Ok(())
4211 }))
4212 }
4213
4214 pub fn toggle_code_actions(
4215 &mut self,
4216 action: &ToggleCodeActions,
4217 window: &mut Window,
4218 cx: &mut Context<Self>,
4219 ) {
4220 let mut context_menu = self.context_menu.borrow_mut();
4221 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4222 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4223 // Toggle if we're selecting the same one
4224 *context_menu = None;
4225 cx.notify();
4226 return;
4227 } else {
4228 // Otherwise, clear it and start a new one
4229 *context_menu = None;
4230 cx.notify();
4231 }
4232 }
4233 drop(context_menu);
4234 let snapshot = self.snapshot(window, cx);
4235 let deployed_from_indicator = action.deployed_from_indicator;
4236 let mut task = self.code_actions_task.take();
4237 let action = action.clone();
4238 cx.spawn_in(window, |editor, mut cx| async move {
4239 while let Some(prev_task) = task {
4240 prev_task.await.log_err();
4241 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4242 }
4243
4244 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4245 if editor.focus_handle.is_focused(window) {
4246 let multibuffer_point = action
4247 .deployed_from_indicator
4248 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4249 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4250 let (buffer, buffer_row) = snapshot
4251 .buffer_snapshot
4252 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4253 .and_then(|(buffer_snapshot, range)| {
4254 editor
4255 .buffer
4256 .read(cx)
4257 .buffer(buffer_snapshot.remote_id())
4258 .map(|buffer| (buffer, range.start.row))
4259 })?;
4260 let (_, code_actions) = editor
4261 .available_code_actions
4262 .clone()
4263 .and_then(|(location, code_actions)| {
4264 let snapshot = location.buffer.read(cx).snapshot();
4265 let point_range = location.range.to_point(&snapshot);
4266 let point_range = point_range.start.row..=point_range.end.row;
4267 if point_range.contains(&buffer_row) {
4268 Some((location, code_actions))
4269 } else {
4270 None
4271 }
4272 })
4273 .unzip();
4274 let buffer_id = buffer.read(cx).remote_id();
4275 let tasks = editor
4276 .tasks
4277 .get(&(buffer_id, buffer_row))
4278 .map(|t| Arc::new(t.to_owned()));
4279 if tasks.is_none() && code_actions.is_none() {
4280 return None;
4281 }
4282
4283 editor.completion_tasks.clear();
4284 editor.discard_inline_completion(false, cx);
4285 let task_context =
4286 tasks
4287 .as_ref()
4288 .zip(editor.project.clone())
4289 .map(|(tasks, project)| {
4290 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4291 });
4292
4293 Some(cx.spawn_in(window, |editor, mut cx| async move {
4294 let task_context = match task_context {
4295 Some(task_context) => task_context.await,
4296 None => None,
4297 };
4298 let resolved_tasks =
4299 tasks.zip(task_context).map(|(tasks, task_context)| {
4300 Rc::new(ResolvedTasks {
4301 templates: tasks.resolve(&task_context).collect(),
4302 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4303 multibuffer_point.row,
4304 tasks.column,
4305 )),
4306 })
4307 });
4308 let spawn_straight_away = resolved_tasks
4309 .as_ref()
4310 .map_or(false, |tasks| tasks.templates.len() == 1)
4311 && code_actions
4312 .as_ref()
4313 .map_or(true, |actions| actions.is_empty());
4314 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4315 *editor.context_menu.borrow_mut() =
4316 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4317 buffer,
4318 actions: CodeActionContents {
4319 tasks: resolved_tasks,
4320 actions: code_actions,
4321 },
4322 selected_item: Default::default(),
4323 scroll_handle: UniformListScrollHandle::default(),
4324 deployed_from_indicator,
4325 }));
4326 if spawn_straight_away {
4327 if let Some(task) = editor.confirm_code_action(
4328 &ConfirmCodeAction { item_ix: Some(0) },
4329 window,
4330 cx,
4331 ) {
4332 cx.notify();
4333 return task;
4334 }
4335 }
4336 cx.notify();
4337 Task::ready(Ok(()))
4338 }) {
4339 task.await
4340 } else {
4341 Ok(())
4342 }
4343 }))
4344 } else {
4345 Some(Task::ready(Ok(())))
4346 }
4347 })?;
4348 if let Some(task) = spawned_test_task {
4349 task.await?;
4350 }
4351
4352 Ok::<_, anyhow::Error>(())
4353 })
4354 .detach_and_log_err(cx);
4355 }
4356
4357 pub fn confirm_code_action(
4358 &mut self,
4359 action: &ConfirmCodeAction,
4360 window: &mut Window,
4361 cx: &mut Context<Self>,
4362 ) -> Option<Task<Result<()>>> {
4363 let actions_menu =
4364 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4365 menu
4366 } else {
4367 return None;
4368 };
4369 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4370 let action = actions_menu.actions.get(action_ix)?;
4371 let title = action.label();
4372 let buffer = actions_menu.buffer;
4373 let workspace = self.workspace()?;
4374
4375 match action {
4376 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4377 workspace.update(cx, |workspace, cx| {
4378 workspace::tasks::schedule_resolved_task(
4379 workspace,
4380 task_source_kind,
4381 resolved_task,
4382 false,
4383 cx,
4384 );
4385
4386 Some(Task::ready(Ok(())))
4387 })
4388 }
4389 CodeActionsItem::CodeAction {
4390 excerpt_id,
4391 action,
4392 provider,
4393 } => {
4394 let apply_code_action =
4395 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4396 let workspace = workspace.downgrade();
4397 Some(cx.spawn_in(window, |editor, cx| async move {
4398 let project_transaction = apply_code_action.await?;
4399 Self::open_project_transaction(
4400 &editor,
4401 workspace,
4402 project_transaction,
4403 title,
4404 cx,
4405 )
4406 .await
4407 }))
4408 }
4409 }
4410 }
4411
4412 pub async fn open_project_transaction(
4413 this: &WeakEntity<Editor>,
4414 workspace: WeakEntity<Workspace>,
4415 transaction: ProjectTransaction,
4416 title: String,
4417 mut cx: AsyncWindowContext,
4418 ) -> Result<()> {
4419 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4420 cx.update(|_, cx| {
4421 entries.sort_unstable_by_key(|(buffer, _)| {
4422 buffer.read(cx).file().map(|f| f.path().clone())
4423 });
4424 })?;
4425
4426 // If the project transaction's edits are all contained within this editor, then
4427 // avoid opening a new editor to display them.
4428
4429 if let Some((buffer, transaction)) = entries.first() {
4430 if entries.len() == 1 {
4431 let excerpt = this.update(&mut cx, |editor, cx| {
4432 editor
4433 .buffer()
4434 .read(cx)
4435 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4436 })?;
4437 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4438 if excerpted_buffer == *buffer {
4439 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4440 let excerpt_range = excerpt_range.to_offset(buffer);
4441 buffer
4442 .edited_ranges_for_transaction::<usize>(transaction)
4443 .all(|range| {
4444 excerpt_range.start <= range.start
4445 && excerpt_range.end >= range.end
4446 })
4447 })?;
4448
4449 if all_edits_within_excerpt {
4450 return Ok(());
4451 }
4452 }
4453 }
4454 }
4455 } else {
4456 return Ok(());
4457 }
4458
4459 let mut ranges_to_highlight = Vec::new();
4460 let excerpt_buffer = cx.new(|cx| {
4461 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4462 for (buffer_handle, transaction) in &entries {
4463 let buffer = buffer_handle.read(cx);
4464 ranges_to_highlight.extend(
4465 multibuffer.push_excerpts_with_context_lines(
4466 buffer_handle.clone(),
4467 buffer
4468 .edited_ranges_for_transaction::<usize>(transaction)
4469 .collect(),
4470 DEFAULT_MULTIBUFFER_CONTEXT,
4471 cx,
4472 ),
4473 );
4474 }
4475 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4476 multibuffer
4477 })?;
4478
4479 workspace.update_in(&mut cx, |workspace, window, cx| {
4480 let project = workspace.project().clone();
4481 let editor = cx
4482 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4483 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4484 editor.update(cx, |editor, cx| {
4485 editor.highlight_background::<Self>(
4486 &ranges_to_highlight,
4487 |theme| theme.editor_highlighted_line_background,
4488 cx,
4489 );
4490 });
4491 })?;
4492
4493 Ok(())
4494 }
4495
4496 pub fn clear_code_action_providers(&mut self) {
4497 self.code_action_providers.clear();
4498 self.available_code_actions.take();
4499 }
4500
4501 pub fn add_code_action_provider(
4502 &mut self,
4503 provider: Rc<dyn CodeActionProvider>,
4504 window: &mut Window,
4505 cx: &mut Context<Self>,
4506 ) {
4507 if self
4508 .code_action_providers
4509 .iter()
4510 .any(|existing_provider| existing_provider.id() == provider.id())
4511 {
4512 return;
4513 }
4514
4515 self.code_action_providers.push(provider);
4516 self.refresh_code_actions(window, cx);
4517 }
4518
4519 pub fn remove_code_action_provider(
4520 &mut self,
4521 id: Arc<str>,
4522 window: &mut Window,
4523 cx: &mut Context<Self>,
4524 ) {
4525 self.code_action_providers
4526 .retain(|provider| provider.id() != id);
4527 self.refresh_code_actions(window, cx);
4528 }
4529
4530 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4531 let buffer = self.buffer.read(cx);
4532 let newest_selection = self.selections.newest_anchor().clone();
4533 if newest_selection.head().diff_base_anchor.is_some() {
4534 return None;
4535 }
4536 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4537 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4538 if start_buffer != end_buffer {
4539 return None;
4540 }
4541
4542 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4543 cx.background_executor()
4544 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4545 .await;
4546
4547 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4548 let providers = this.code_action_providers.clone();
4549 let tasks = this
4550 .code_action_providers
4551 .iter()
4552 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4553 .collect::<Vec<_>>();
4554 (providers, tasks)
4555 })?;
4556
4557 let mut actions = Vec::new();
4558 for (provider, provider_actions) in
4559 providers.into_iter().zip(future::join_all(tasks).await)
4560 {
4561 if let Some(provider_actions) = provider_actions.log_err() {
4562 actions.extend(provider_actions.into_iter().map(|action| {
4563 AvailableCodeAction {
4564 excerpt_id: newest_selection.start.excerpt_id,
4565 action,
4566 provider: provider.clone(),
4567 }
4568 }));
4569 }
4570 }
4571
4572 this.update(&mut cx, |this, cx| {
4573 this.available_code_actions = if actions.is_empty() {
4574 None
4575 } else {
4576 Some((
4577 Location {
4578 buffer: start_buffer,
4579 range: start..end,
4580 },
4581 actions.into(),
4582 ))
4583 };
4584 cx.notify();
4585 })
4586 }));
4587 None
4588 }
4589
4590 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4591 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4592 self.show_git_blame_inline = false;
4593
4594 self.show_git_blame_inline_delay_task =
4595 Some(cx.spawn_in(window, |this, mut cx| async move {
4596 cx.background_executor().timer(delay).await;
4597
4598 this.update(&mut cx, |this, cx| {
4599 this.show_git_blame_inline = true;
4600 cx.notify();
4601 })
4602 .log_err();
4603 }));
4604 }
4605 }
4606
4607 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4608 if self.pending_rename.is_some() {
4609 return None;
4610 }
4611
4612 let provider = self.semantics_provider.clone()?;
4613 let buffer = self.buffer.read(cx);
4614 let newest_selection = self.selections.newest_anchor().clone();
4615 let cursor_position = newest_selection.head();
4616 let (cursor_buffer, cursor_buffer_position) =
4617 buffer.text_anchor_for_position(cursor_position, cx)?;
4618 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4619 if cursor_buffer != tail_buffer {
4620 return None;
4621 }
4622 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4623 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4624 cx.background_executor()
4625 .timer(Duration::from_millis(debounce))
4626 .await;
4627
4628 let highlights = if let Some(highlights) = cx
4629 .update(|cx| {
4630 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4631 })
4632 .ok()
4633 .flatten()
4634 {
4635 highlights.await.log_err()
4636 } else {
4637 None
4638 };
4639
4640 if let Some(highlights) = highlights {
4641 this.update(&mut cx, |this, cx| {
4642 if this.pending_rename.is_some() {
4643 return;
4644 }
4645
4646 let buffer_id = cursor_position.buffer_id;
4647 let buffer = this.buffer.read(cx);
4648 if !buffer
4649 .text_anchor_for_position(cursor_position, cx)
4650 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4651 {
4652 return;
4653 }
4654
4655 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4656 let mut write_ranges = Vec::new();
4657 let mut read_ranges = Vec::new();
4658 for highlight in highlights {
4659 for (excerpt_id, excerpt_range) in
4660 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4661 {
4662 let start = highlight
4663 .range
4664 .start
4665 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4666 let end = highlight
4667 .range
4668 .end
4669 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4670 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4671 continue;
4672 }
4673
4674 let range = Anchor {
4675 buffer_id,
4676 excerpt_id,
4677 text_anchor: start,
4678 diff_base_anchor: None,
4679 }..Anchor {
4680 buffer_id,
4681 excerpt_id,
4682 text_anchor: end,
4683 diff_base_anchor: None,
4684 };
4685 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4686 write_ranges.push(range);
4687 } else {
4688 read_ranges.push(range);
4689 }
4690 }
4691 }
4692
4693 this.highlight_background::<DocumentHighlightRead>(
4694 &read_ranges,
4695 |theme| theme.editor_document_highlight_read_background,
4696 cx,
4697 );
4698 this.highlight_background::<DocumentHighlightWrite>(
4699 &write_ranges,
4700 |theme| theme.editor_document_highlight_write_background,
4701 cx,
4702 );
4703 cx.notify();
4704 })
4705 .log_err();
4706 }
4707 }));
4708 None
4709 }
4710
4711 pub fn refresh_selected_text_highlights(
4712 &mut self,
4713 window: &mut Window,
4714 cx: &mut Context<Editor>,
4715 ) {
4716 self.selection_highlight_task.take();
4717 if !EditorSettings::get_global(cx).selection_highlight {
4718 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4719 return;
4720 }
4721 if self.selections.count() != 1 || self.selections.line_mode {
4722 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4723 return;
4724 }
4725 let selection = self.selections.newest::<Point>(cx);
4726 if selection.is_empty() || selection.start.row != selection.end.row {
4727 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4728 return;
4729 }
4730 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4731 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4732 cx.background_executor()
4733 .timer(Duration::from_millis(debounce))
4734 .await;
4735 let Some(Some(matches_task)) = editor
4736 .update_in(&mut cx, |editor, _, cx| {
4737 if editor.selections.count() != 1 || editor.selections.line_mode {
4738 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4739 return None;
4740 }
4741 let selection = editor.selections.newest::<Point>(cx);
4742 if selection.is_empty() || selection.start.row != selection.end.row {
4743 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4744 return None;
4745 }
4746 let buffer = editor.buffer().read(cx).snapshot(cx);
4747 Some(cx.background_spawn(async move {
4748 let mut ranges = Vec::new();
4749 let query = buffer.text_for_range(selection.range()).collect::<String>();
4750 let selection_anchors = selection.range().to_anchors(&buffer);
4751 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4752 for (search_buffer, search_range, excerpt_id) in
4753 buffer.range_to_buffer_ranges(range)
4754 {
4755 ranges.extend(
4756 project::search::SearchQuery::text(
4757 query.clone(),
4758 false,
4759 false,
4760 false,
4761 Default::default(),
4762 Default::default(),
4763 None,
4764 )
4765 .unwrap()
4766 .search(search_buffer, Some(search_range.clone()))
4767 .await
4768 .into_iter()
4769 .filter_map(
4770 |match_range| {
4771 let start = search_buffer.anchor_after(
4772 search_range.start + match_range.start,
4773 );
4774 let end = search_buffer.anchor_before(
4775 search_range.start + match_range.end,
4776 );
4777 let range = Anchor::range_in_buffer(
4778 excerpt_id,
4779 search_buffer.remote_id(),
4780 start..end,
4781 );
4782 (range != selection_anchors).then_some(range)
4783 },
4784 ),
4785 );
4786 }
4787 }
4788 ranges
4789 }))
4790 })
4791 .log_err()
4792 else {
4793 return;
4794 };
4795 let matches = matches_task.await;
4796 editor
4797 .update_in(&mut cx, |editor, _, cx| {
4798 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4799 if !matches.is_empty() {
4800 editor.highlight_background::<SelectedTextHighlight>(
4801 &matches,
4802 |theme| theme.editor_document_highlight_bracket_background,
4803 cx,
4804 )
4805 }
4806 })
4807 .log_err();
4808 }));
4809 }
4810
4811 pub fn refresh_inline_completion(
4812 &mut self,
4813 debounce: bool,
4814 user_requested: bool,
4815 window: &mut Window,
4816 cx: &mut Context<Self>,
4817 ) -> Option<()> {
4818 let provider = self.edit_prediction_provider()?;
4819 let cursor = self.selections.newest_anchor().head();
4820 let (buffer, cursor_buffer_position) =
4821 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4822
4823 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4824 self.discard_inline_completion(false, cx);
4825 return None;
4826 }
4827
4828 if !user_requested
4829 && (!self.should_show_edit_predictions()
4830 || !self.is_focused(window)
4831 || buffer.read(cx).is_empty())
4832 {
4833 self.discard_inline_completion(false, cx);
4834 return None;
4835 }
4836
4837 self.update_visible_inline_completion(window, cx);
4838 provider.refresh(
4839 self.project.clone(),
4840 buffer,
4841 cursor_buffer_position,
4842 debounce,
4843 cx,
4844 );
4845 Some(())
4846 }
4847
4848 fn show_edit_predictions_in_menu(&self) -> bool {
4849 match self.edit_prediction_settings {
4850 EditPredictionSettings::Disabled => false,
4851 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4852 }
4853 }
4854
4855 pub fn edit_predictions_enabled(&self) -> bool {
4856 match self.edit_prediction_settings {
4857 EditPredictionSettings::Disabled => false,
4858 EditPredictionSettings::Enabled { .. } => true,
4859 }
4860 }
4861
4862 fn edit_prediction_requires_modifier(&self) -> bool {
4863 match self.edit_prediction_settings {
4864 EditPredictionSettings::Disabled => false,
4865 EditPredictionSettings::Enabled {
4866 preview_requires_modifier,
4867 ..
4868 } => preview_requires_modifier,
4869 }
4870 }
4871
4872 fn edit_prediction_settings_at_position(
4873 &self,
4874 buffer: &Entity<Buffer>,
4875 buffer_position: language::Anchor,
4876 cx: &App,
4877 ) -> EditPredictionSettings {
4878 if self.mode != EditorMode::Full
4879 || !self.show_inline_completions_override.unwrap_or(true)
4880 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4881 {
4882 return EditPredictionSettings::Disabled;
4883 }
4884
4885 let buffer = buffer.read(cx);
4886
4887 let file = buffer.file();
4888
4889 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4890 return EditPredictionSettings::Disabled;
4891 };
4892
4893 let by_provider = matches!(
4894 self.menu_inline_completions_policy,
4895 MenuInlineCompletionsPolicy::ByProvider
4896 );
4897
4898 let show_in_menu = by_provider
4899 && self
4900 .edit_prediction_provider
4901 .as_ref()
4902 .map_or(false, |provider| {
4903 provider.provider.show_completions_in_menu()
4904 });
4905
4906 let preview_requires_modifier =
4907 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4908
4909 EditPredictionSettings::Enabled {
4910 show_in_menu,
4911 preview_requires_modifier,
4912 }
4913 }
4914
4915 fn should_show_edit_predictions(&self) -> bool {
4916 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4917 }
4918
4919 pub fn edit_prediction_preview_is_active(&self) -> bool {
4920 matches!(
4921 self.edit_prediction_preview,
4922 EditPredictionPreview::Active { .. }
4923 )
4924 }
4925
4926 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4927 let cursor = self.selections.newest_anchor().head();
4928 if let Some((buffer, cursor_position)) =
4929 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4930 {
4931 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4932 } else {
4933 false
4934 }
4935 }
4936
4937 fn inline_completions_enabled_in_buffer(
4938 &self,
4939 buffer: &Entity<Buffer>,
4940 buffer_position: language::Anchor,
4941 cx: &App,
4942 ) -> bool {
4943 maybe!({
4944 let provider = self.edit_prediction_provider()?;
4945 if !provider.is_enabled(&buffer, buffer_position, cx) {
4946 return Some(false);
4947 }
4948 let buffer = buffer.read(cx);
4949 let Some(file) = buffer.file() else {
4950 return Some(true);
4951 };
4952 let settings = all_language_settings(Some(file), cx);
4953 Some(settings.inline_completions_enabled_for_path(file.path()))
4954 })
4955 .unwrap_or(false)
4956 }
4957
4958 fn cycle_inline_completion(
4959 &mut self,
4960 direction: Direction,
4961 window: &mut Window,
4962 cx: &mut Context<Self>,
4963 ) -> Option<()> {
4964 let provider = self.edit_prediction_provider()?;
4965 let cursor = self.selections.newest_anchor().head();
4966 let (buffer, cursor_buffer_position) =
4967 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4968 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4969 return None;
4970 }
4971
4972 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4973 self.update_visible_inline_completion(window, cx);
4974
4975 Some(())
4976 }
4977
4978 pub fn show_inline_completion(
4979 &mut self,
4980 _: &ShowEditPrediction,
4981 window: &mut Window,
4982 cx: &mut Context<Self>,
4983 ) {
4984 if !self.has_active_inline_completion() {
4985 self.refresh_inline_completion(false, true, window, cx);
4986 return;
4987 }
4988
4989 self.update_visible_inline_completion(window, cx);
4990 }
4991
4992 pub fn display_cursor_names(
4993 &mut self,
4994 _: &DisplayCursorNames,
4995 window: &mut Window,
4996 cx: &mut Context<Self>,
4997 ) {
4998 self.show_cursor_names(window, cx);
4999 }
5000
5001 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5002 self.show_cursor_names = true;
5003 cx.notify();
5004 cx.spawn_in(window, |this, mut cx| async move {
5005 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5006 this.update(&mut cx, |this, cx| {
5007 this.show_cursor_names = false;
5008 cx.notify()
5009 })
5010 .ok()
5011 })
5012 .detach();
5013 }
5014
5015 pub fn next_edit_prediction(
5016 &mut self,
5017 _: &NextEditPrediction,
5018 window: &mut Window,
5019 cx: &mut Context<Self>,
5020 ) {
5021 if self.has_active_inline_completion() {
5022 self.cycle_inline_completion(Direction::Next, window, cx);
5023 } else {
5024 let is_copilot_disabled = self
5025 .refresh_inline_completion(false, true, window, cx)
5026 .is_none();
5027 if is_copilot_disabled {
5028 cx.propagate();
5029 }
5030 }
5031 }
5032
5033 pub fn previous_edit_prediction(
5034 &mut self,
5035 _: &PreviousEditPrediction,
5036 window: &mut Window,
5037 cx: &mut Context<Self>,
5038 ) {
5039 if self.has_active_inline_completion() {
5040 self.cycle_inline_completion(Direction::Prev, window, cx);
5041 } else {
5042 let is_copilot_disabled = self
5043 .refresh_inline_completion(false, true, window, cx)
5044 .is_none();
5045 if is_copilot_disabled {
5046 cx.propagate();
5047 }
5048 }
5049 }
5050
5051 pub fn accept_edit_prediction(
5052 &mut self,
5053 _: &AcceptEditPrediction,
5054 window: &mut Window,
5055 cx: &mut Context<Self>,
5056 ) {
5057 if self.show_edit_predictions_in_menu() {
5058 self.hide_context_menu(window, cx);
5059 }
5060
5061 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5062 return;
5063 };
5064
5065 self.report_inline_completion_event(
5066 active_inline_completion.completion_id.clone(),
5067 true,
5068 cx,
5069 );
5070
5071 match &active_inline_completion.completion {
5072 InlineCompletion::Move { target, .. } => {
5073 let target = *target;
5074
5075 if let Some(position_map) = &self.last_position_map {
5076 if position_map
5077 .visible_row_range
5078 .contains(&target.to_display_point(&position_map.snapshot).row())
5079 || !self.edit_prediction_requires_modifier()
5080 {
5081 self.unfold_ranges(&[target..target], true, false, cx);
5082 // Note that this is also done in vim's handler of the Tab action.
5083 self.change_selections(
5084 Some(Autoscroll::newest()),
5085 window,
5086 cx,
5087 |selections| {
5088 selections.select_anchor_ranges([target..target]);
5089 },
5090 );
5091 self.clear_row_highlights::<EditPredictionPreview>();
5092
5093 self.edit_prediction_preview = EditPredictionPreview::Active {
5094 previous_scroll_position: None,
5095 };
5096 } else {
5097 self.edit_prediction_preview = EditPredictionPreview::Active {
5098 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5099 };
5100 self.highlight_rows::<EditPredictionPreview>(
5101 target..target,
5102 cx.theme().colors().editor_highlighted_line_background,
5103 true,
5104 cx,
5105 );
5106 self.request_autoscroll(Autoscroll::fit(), cx);
5107 }
5108 }
5109 }
5110 InlineCompletion::Edit { edits, .. } => {
5111 if let Some(provider) = self.edit_prediction_provider() {
5112 provider.accept(cx);
5113 }
5114
5115 let snapshot = self.buffer.read(cx).snapshot(cx);
5116 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5117
5118 self.buffer.update(cx, |buffer, cx| {
5119 buffer.edit(edits.iter().cloned(), None, cx)
5120 });
5121
5122 self.change_selections(None, window, cx, |s| {
5123 s.select_anchor_ranges([last_edit_end..last_edit_end])
5124 });
5125
5126 self.update_visible_inline_completion(window, cx);
5127 if self.active_inline_completion.is_none() {
5128 self.refresh_inline_completion(true, true, window, cx);
5129 }
5130
5131 cx.notify();
5132 }
5133 }
5134
5135 self.edit_prediction_requires_modifier_in_leading_space = false;
5136 }
5137
5138 pub fn accept_partial_inline_completion(
5139 &mut self,
5140 _: &AcceptPartialEditPrediction,
5141 window: &mut Window,
5142 cx: &mut Context<Self>,
5143 ) {
5144 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5145 return;
5146 };
5147 if self.selections.count() != 1 {
5148 return;
5149 }
5150
5151 self.report_inline_completion_event(
5152 active_inline_completion.completion_id.clone(),
5153 true,
5154 cx,
5155 );
5156
5157 match &active_inline_completion.completion {
5158 InlineCompletion::Move { target, .. } => {
5159 let target = *target;
5160 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5161 selections.select_anchor_ranges([target..target]);
5162 });
5163 }
5164 InlineCompletion::Edit { edits, .. } => {
5165 // Find an insertion that starts at the cursor position.
5166 let snapshot = self.buffer.read(cx).snapshot(cx);
5167 let cursor_offset = self.selections.newest::<usize>(cx).head();
5168 let insertion = edits.iter().find_map(|(range, text)| {
5169 let range = range.to_offset(&snapshot);
5170 if range.is_empty() && range.start == cursor_offset {
5171 Some(text)
5172 } else {
5173 None
5174 }
5175 });
5176
5177 if let Some(text) = insertion {
5178 let mut partial_completion = text
5179 .chars()
5180 .by_ref()
5181 .take_while(|c| c.is_alphabetic())
5182 .collect::<String>();
5183 if partial_completion.is_empty() {
5184 partial_completion = text
5185 .chars()
5186 .by_ref()
5187 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5188 .collect::<String>();
5189 }
5190
5191 cx.emit(EditorEvent::InputHandled {
5192 utf16_range_to_replace: None,
5193 text: partial_completion.clone().into(),
5194 });
5195
5196 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5197
5198 self.refresh_inline_completion(true, true, window, cx);
5199 cx.notify();
5200 } else {
5201 self.accept_edit_prediction(&Default::default(), window, cx);
5202 }
5203 }
5204 }
5205 }
5206
5207 fn discard_inline_completion(
5208 &mut self,
5209 should_report_inline_completion_event: bool,
5210 cx: &mut Context<Self>,
5211 ) -> bool {
5212 if should_report_inline_completion_event {
5213 let completion_id = self
5214 .active_inline_completion
5215 .as_ref()
5216 .and_then(|active_completion| active_completion.completion_id.clone());
5217
5218 self.report_inline_completion_event(completion_id, false, cx);
5219 }
5220
5221 if let Some(provider) = self.edit_prediction_provider() {
5222 provider.discard(cx);
5223 }
5224
5225 self.take_active_inline_completion(cx)
5226 }
5227
5228 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5229 let Some(provider) = self.edit_prediction_provider() else {
5230 return;
5231 };
5232
5233 let Some((_, buffer, _)) = self
5234 .buffer
5235 .read(cx)
5236 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5237 else {
5238 return;
5239 };
5240
5241 let extension = buffer
5242 .read(cx)
5243 .file()
5244 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5245
5246 let event_type = match accepted {
5247 true => "Edit Prediction Accepted",
5248 false => "Edit Prediction Discarded",
5249 };
5250 telemetry::event!(
5251 event_type,
5252 provider = provider.name(),
5253 prediction_id = id,
5254 suggestion_accepted = accepted,
5255 file_extension = extension,
5256 );
5257 }
5258
5259 pub fn has_active_inline_completion(&self) -> bool {
5260 self.active_inline_completion.is_some()
5261 }
5262
5263 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5264 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5265 return false;
5266 };
5267
5268 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5269 self.clear_highlights::<InlineCompletionHighlight>(cx);
5270 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5271 true
5272 }
5273
5274 /// Returns true when we're displaying the edit prediction popover below the cursor
5275 /// like we are not previewing and the LSP autocomplete menu is visible
5276 /// or we are in `when_holding_modifier` mode.
5277 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5278 if self.edit_prediction_preview_is_active()
5279 || !self.show_edit_predictions_in_menu()
5280 || !self.edit_predictions_enabled()
5281 {
5282 return false;
5283 }
5284
5285 if self.has_visible_completions_menu() {
5286 return true;
5287 }
5288
5289 has_completion && self.edit_prediction_requires_modifier()
5290 }
5291
5292 fn handle_modifiers_changed(
5293 &mut self,
5294 modifiers: Modifiers,
5295 position_map: &PositionMap,
5296 window: &mut Window,
5297 cx: &mut Context<Self>,
5298 ) {
5299 if self.show_edit_predictions_in_menu() {
5300 self.update_edit_prediction_preview(&modifiers, window, cx);
5301 }
5302
5303 self.update_selection_mode(&modifiers, position_map, window, cx);
5304
5305 let mouse_position = window.mouse_position();
5306 if !position_map.text_hitbox.is_hovered(window) {
5307 return;
5308 }
5309
5310 self.update_hovered_link(
5311 position_map.point_for_position(mouse_position),
5312 &position_map.snapshot,
5313 modifiers,
5314 window,
5315 cx,
5316 )
5317 }
5318
5319 fn update_selection_mode(
5320 &mut self,
5321 modifiers: &Modifiers,
5322 position_map: &PositionMap,
5323 window: &mut Window,
5324 cx: &mut Context<Self>,
5325 ) {
5326 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5327 return;
5328 }
5329
5330 let mouse_position = window.mouse_position();
5331 let point_for_position = position_map.point_for_position(mouse_position);
5332 let position = point_for_position.previous_valid;
5333
5334 self.select(
5335 SelectPhase::BeginColumnar {
5336 position,
5337 reset: false,
5338 goal_column: point_for_position.exact_unclipped.column(),
5339 },
5340 window,
5341 cx,
5342 );
5343 }
5344
5345 fn update_edit_prediction_preview(
5346 &mut self,
5347 modifiers: &Modifiers,
5348 window: &mut Window,
5349 cx: &mut Context<Self>,
5350 ) {
5351 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5352 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5353 return;
5354 };
5355
5356 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5357 if matches!(
5358 self.edit_prediction_preview,
5359 EditPredictionPreview::Inactive
5360 ) {
5361 self.edit_prediction_preview = EditPredictionPreview::Active {
5362 previous_scroll_position: None,
5363 };
5364
5365 self.update_visible_inline_completion(window, cx);
5366 cx.notify();
5367 }
5368 } else if let EditPredictionPreview::Active {
5369 previous_scroll_position,
5370 } = self.edit_prediction_preview
5371 {
5372 if let (Some(previous_scroll_position), Some(position_map)) =
5373 (previous_scroll_position, self.last_position_map.as_ref())
5374 {
5375 self.set_scroll_position(
5376 previous_scroll_position
5377 .scroll_position(&position_map.snapshot.display_snapshot),
5378 window,
5379 cx,
5380 );
5381 }
5382
5383 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5384 self.clear_row_highlights::<EditPredictionPreview>();
5385 self.update_visible_inline_completion(window, cx);
5386 cx.notify();
5387 }
5388 }
5389
5390 fn update_visible_inline_completion(
5391 &mut self,
5392 _window: &mut Window,
5393 cx: &mut Context<Self>,
5394 ) -> Option<()> {
5395 let selection = self.selections.newest_anchor();
5396 let cursor = selection.head();
5397 let multibuffer = self.buffer.read(cx).snapshot(cx);
5398 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5399 let excerpt_id = cursor.excerpt_id;
5400
5401 let show_in_menu = self.show_edit_predictions_in_menu();
5402 let completions_menu_has_precedence = !show_in_menu
5403 && (self.context_menu.borrow().is_some()
5404 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5405
5406 if completions_menu_has_precedence
5407 || !offset_selection.is_empty()
5408 || self
5409 .active_inline_completion
5410 .as_ref()
5411 .map_or(false, |completion| {
5412 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5413 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5414 !invalidation_range.contains(&offset_selection.head())
5415 })
5416 {
5417 self.discard_inline_completion(false, cx);
5418 return None;
5419 }
5420
5421 self.take_active_inline_completion(cx);
5422 let Some(provider) = self.edit_prediction_provider() else {
5423 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5424 return None;
5425 };
5426
5427 let (buffer, cursor_buffer_position) =
5428 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5429
5430 self.edit_prediction_settings =
5431 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5432
5433 self.edit_prediction_cursor_on_leading_whitespace =
5434 multibuffer.is_line_whitespace_upto(cursor);
5435
5436 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5437 let edits = inline_completion
5438 .edits
5439 .into_iter()
5440 .flat_map(|(range, new_text)| {
5441 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5442 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5443 Some((start..end, new_text))
5444 })
5445 .collect::<Vec<_>>();
5446 if edits.is_empty() {
5447 return None;
5448 }
5449
5450 let first_edit_start = edits.first().unwrap().0.start;
5451 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5452 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5453
5454 let last_edit_end = edits.last().unwrap().0.end;
5455 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5456 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5457
5458 let cursor_row = cursor.to_point(&multibuffer).row;
5459
5460 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5461
5462 let mut inlay_ids = Vec::new();
5463 let invalidation_row_range;
5464 let move_invalidation_row_range = if cursor_row < edit_start_row {
5465 Some(cursor_row..edit_end_row)
5466 } else if cursor_row > edit_end_row {
5467 Some(edit_start_row..cursor_row)
5468 } else {
5469 None
5470 };
5471 let is_move =
5472 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5473 let completion = if is_move {
5474 invalidation_row_range =
5475 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5476 let target = first_edit_start;
5477 InlineCompletion::Move { target, snapshot }
5478 } else {
5479 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5480 && !self.inline_completions_hidden_for_vim_mode;
5481
5482 if show_completions_in_buffer {
5483 if edits
5484 .iter()
5485 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5486 {
5487 let mut inlays = Vec::new();
5488 for (range, new_text) in &edits {
5489 let inlay = Inlay::inline_completion(
5490 post_inc(&mut self.next_inlay_id),
5491 range.start,
5492 new_text.as_str(),
5493 );
5494 inlay_ids.push(inlay.id);
5495 inlays.push(inlay);
5496 }
5497
5498 self.splice_inlays(&[], inlays, cx);
5499 } else {
5500 let background_color = cx.theme().status().deleted_background;
5501 self.highlight_text::<InlineCompletionHighlight>(
5502 edits.iter().map(|(range, _)| range.clone()).collect(),
5503 HighlightStyle {
5504 background_color: Some(background_color),
5505 ..Default::default()
5506 },
5507 cx,
5508 );
5509 }
5510 }
5511
5512 invalidation_row_range = edit_start_row..edit_end_row;
5513
5514 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5515 if provider.show_tab_accept_marker() {
5516 EditDisplayMode::TabAccept
5517 } else {
5518 EditDisplayMode::Inline
5519 }
5520 } else {
5521 EditDisplayMode::DiffPopover
5522 };
5523
5524 InlineCompletion::Edit {
5525 edits,
5526 edit_preview: inline_completion.edit_preview,
5527 display_mode,
5528 snapshot,
5529 }
5530 };
5531
5532 let invalidation_range = multibuffer
5533 .anchor_before(Point::new(invalidation_row_range.start, 0))
5534 ..multibuffer.anchor_after(Point::new(
5535 invalidation_row_range.end,
5536 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5537 ));
5538
5539 self.stale_inline_completion_in_menu = None;
5540 self.active_inline_completion = Some(InlineCompletionState {
5541 inlay_ids,
5542 completion,
5543 completion_id: inline_completion.id,
5544 invalidation_range,
5545 });
5546
5547 cx.notify();
5548
5549 Some(())
5550 }
5551
5552 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5553 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5554 }
5555
5556 fn render_code_actions_indicator(
5557 &self,
5558 _style: &EditorStyle,
5559 row: DisplayRow,
5560 is_active: bool,
5561 cx: &mut Context<Self>,
5562 ) -> Option<IconButton> {
5563 if self.available_code_actions.is_some() {
5564 Some(
5565 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5566 .shape(ui::IconButtonShape::Square)
5567 .icon_size(IconSize::XSmall)
5568 .icon_color(Color::Muted)
5569 .toggle_state(is_active)
5570 .tooltip({
5571 let focus_handle = self.focus_handle.clone();
5572 move |window, cx| {
5573 Tooltip::for_action_in(
5574 "Toggle Code Actions",
5575 &ToggleCodeActions {
5576 deployed_from_indicator: None,
5577 },
5578 &focus_handle,
5579 window,
5580 cx,
5581 )
5582 }
5583 })
5584 .on_click(cx.listener(move |editor, _e, window, cx| {
5585 window.focus(&editor.focus_handle(cx));
5586 editor.toggle_code_actions(
5587 &ToggleCodeActions {
5588 deployed_from_indicator: Some(row),
5589 },
5590 window,
5591 cx,
5592 );
5593 })),
5594 )
5595 } else {
5596 None
5597 }
5598 }
5599
5600 fn clear_tasks(&mut self) {
5601 self.tasks.clear()
5602 }
5603
5604 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5605 if self.tasks.insert(key, value).is_some() {
5606 // This case should hopefully be rare, but just in case...
5607 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5608 }
5609 }
5610
5611 fn build_tasks_context(
5612 project: &Entity<Project>,
5613 buffer: &Entity<Buffer>,
5614 buffer_row: u32,
5615 tasks: &Arc<RunnableTasks>,
5616 cx: &mut Context<Self>,
5617 ) -> Task<Option<task::TaskContext>> {
5618 let position = Point::new(buffer_row, tasks.column);
5619 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5620 let location = Location {
5621 buffer: buffer.clone(),
5622 range: range_start..range_start,
5623 };
5624 // Fill in the environmental variables from the tree-sitter captures
5625 let mut captured_task_variables = TaskVariables::default();
5626 for (capture_name, value) in tasks.extra_variables.clone() {
5627 captured_task_variables.insert(
5628 task::VariableName::Custom(capture_name.into()),
5629 value.clone(),
5630 );
5631 }
5632 project.update(cx, |project, cx| {
5633 project.task_store().update(cx, |task_store, cx| {
5634 task_store.task_context_for_location(captured_task_variables, location, cx)
5635 })
5636 })
5637 }
5638
5639 pub fn spawn_nearest_task(
5640 &mut self,
5641 action: &SpawnNearestTask,
5642 window: &mut Window,
5643 cx: &mut Context<Self>,
5644 ) {
5645 let Some((workspace, _)) = self.workspace.clone() else {
5646 return;
5647 };
5648 let Some(project) = self.project.clone() else {
5649 return;
5650 };
5651
5652 // Try to find a closest, enclosing node using tree-sitter that has a
5653 // task
5654 let Some((buffer, buffer_row, tasks)) = self
5655 .find_enclosing_node_task(cx)
5656 // Or find the task that's closest in row-distance.
5657 .or_else(|| self.find_closest_task(cx))
5658 else {
5659 return;
5660 };
5661
5662 let reveal_strategy = action.reveal;
5663 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5664 cx.spawn_in(window, |_, mut cx| async move {
5665 let context = task_context.await?;
5666 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5667
5668 let resolved = resolved_task.resolved.as_mut()?;
5669 resolved.reveal = reveal_strategy;
5670
5671 workspace
5672 .update(&mut cx, |workspace, cx| {
5673 workspace::tasks::schedule_resolved_task(
5674 workspace,
5675 task_source_kind,
5676 resolved_task,
5677 false,
5678 cx,
5679 );
5680 })
5681 .ok()
5682 })
5683 .detach();
5684 }
5685
5686 fn find_closest_task(
5687 &mut self,
5688 cx: &mut Context<Self>,
5689 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5690 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5691
5692 let ((buffer_id, row), tasks) = self
5693 .tasks
5694 .iter()
5695 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5696
5697 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5698 let tasks = Arc::new(tasks.to_owned());
5699 Some((buffer, *row, tasks))
5700 }
5701
5702 fn find_enclosing_node_task(
5703 &mut self,
5704 cx: &mut Context<Self>,
5705 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5706 let snapshot = self.buffer.read(cx).snapshot(cx);
5707 let offset = self.selections.newest::<usize>(cx).head();
5708 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5709 let buffer_id = excerpt.buffer().remote_id();
5710
5711 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5712 let mut cursor = layer.node().walk();
5713
5714 while cursor.goto_first_child_for_byte(offset).is_some() {
5715 if cursor.node().end_byte() == offset {
5716 cursor.goto_next_sibling();
5717 }
5718 }
5719
5720 // Ascend to the smallest ancestor that contains the range and has a task.
5721 loop {
5722 let node = cursor.node();
5723 let node_range = node.byte_range();
5724 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5725
5726 // Check if this node contains our offset
5727 if node_range.start <= offset && node_range.end >= offset {
5728 // If it contains offset, check for task
5729 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5730 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5731 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5732 }
5733 }
5734
5735 if !cursor.goto_parent() {
5736 break;
5737 }
5738 }
5739 None
5740 }
5741
5742 fn render_run_indicator(
5743 &self,
5744 _style: &EditorStyle,
5745 is_active: bool,
5746 row: DisplayRow,
5747 cx: &mut Context<Self>,
5748 ) -> IconButton {
5749 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5750 .shape(ui::IconButtonShape::Square)
5751 .icon_size(IconSize::XSmall)
5752 .icon_color(Color::Muted)
5753 .toggle_state(is_active)
5754 .on_click(cx.listener(move |editor, _e, window, cx| {
5755 window.focus(&editor.focus_handle(cx));
5756 editor.toggle_code_actions(
5757 &ToggleCodeActions {
5758 deployed_from_indicator: Some(row),
5759 },
5760 window,
5761 cx,
5762 );
5763 }))
5764 }
5765
5766 pub fn context_menu_visible(&self) -> bool {
5767 !self.edit_prediction_preview_is_active()
5768 && self
5769 .context_menu
5770 .borrow()
5771 .as_ref()
5772 .map_or(false, |menu| menu.visible())
5773 }
5774
5775 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5776 self.context_menu
5777 .borrow()
5778 .as_ref()
5779 .map(|menu| menu.origin())
5780 }
5781
5782 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5783 px(30.)
5784 }
5785
5786 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5787 if self.read_only(cx) {
5788 cx.theme().players().read_only()
5789 } else {
5790 self.style.as_ref().unwrap().local_player
5791 }
5792 }
5793
5794 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5795 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5796 let accept_keystroke = accept_binding.keystroke()?;
5797
5798 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5799
5800 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5801 Color::Accent
5802 } else {
5803 Color::Muted
5804 };
5805
5806 h_flex()
5807 .px_0p5()
5808 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5809 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5810 .text_size(TextSize::XSmall.rems(cx))
5811 .child(h_flex().children(ui::render_modifiers(
5812 &accept_keystroke.modifiers,
5813 PlatformStyle::platform(),
5814 Some(modifiers_color),
5815 Some(IconSize::XSmall.rems().into()),
5816 true,
5817 )))
5818 .when(is_platform_style_mac, |parent| {
5819 parent.child(accept_keystroke.key.clone())
5820 })
5821 .when(!is_platform_style_mac, |parent| {
5822 parent.child(
5823 Key::new(
5824 util::capitalize(&accept_keystroke.key),
5825 Some(Color::Default),
5826 )
5827 .size(Some(IconSize::XSmall.rems().into())),
5828 )
5829 })
5830 .into()
5831 }
5832
5833 fn render_edit_prediction_line_popover(
5834 &self,
5835 label: impl Into<SharedString>,
5836 icon: Option<IconName>,
5837 window: &mut Window,
5838 cx: &App,
5839 ) -> Option<Div> {
5840 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5841
5842 let result = h_flex()
5843 .py_0p5()
5844 .pl_1()
5845 .pr(padding_right)
5846 .gap_1()
5847 .rounded(px(6.))
5848 .border_1()
5849 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5850 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5851 .shadow_sm()
5852 .children(self.render_edit_prediction_accept_keybind(window, cx))
5853 .child(Label::new(label).size(LabelSize::Small))
5854 .when_some(icon, |element, icon| {
5855 element.child(
5856 div()
5857 .mt(px(1.5))
5858 .child(Icon::new(icon).size(IconSize::Small)),
5859 )
5860 });
5861
5862 Some(result)
5863 }
5864
5865 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5866 let accent_color = cx.theme().colors().text_accent;
5867 let editor_bg_color = cx.theme().colors().editor_background;
5868 editor_bg_color.blend(accent_color.opacity(0.1))
5869 }
5870
5871 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5872 let accent_color = cx.theme().colors().text_accent;
5873 let editor_bg_color = cx.theme().colors().editor_background;
5874 editor_bg_color.blend(accent_color.opacity(0.6))
5875 }
5876
5877 #[allow(clippy::too_many_arguments)]
5878 fn render_edit_prediction_cursor_popover(
5879 &self,
5880 min_width: Pixels,
5881 max_width: Pixels,
5882 cursor_point: Point,
5883 style: &EditorStyle,
5884 accept_keystroke: Option<&gpui::Keystroke>,
5885 _window: &Window,
5886 cx: &mut Context<Editor>,
5887 ) -> Option<AnyElement> {
5888 let provider = self.edit_prediction_provider.as_ref()?;
5889
5890 if provider.provider.needs_terms_acceptance(cx) {
5891 return Some(
5892 h_flex()
5893 .min_w(min_width)
5894 .flex_1()
5895 .px_2()
5896 .py_1()
5897 .gap_3()
5898 .elevation_2(cx)
5899 .hover(|style| style.bg(cx.theme().colors().element_hover))
5900 .id("accept-terms")
5901 .cursor_pointer()
5902 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5903 .on_click(cx.listener(|this, _event, window, cx| {
5904 cx.stop_propagation();
5905 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5906 window.dispatch_action(
5907 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5908 cx,
5909 );
5910 }))
5911 .child(
5912 h_flex()
5913 .flex_1()
5914 .gap_2()
5915 .child(Icon::new(IconName::ZedPredict))
5916 .child(Label::new("Accept Terms of Service"))
5917 .child(div().w_full())
5918 .child(
5919 Icon::new(IconName::ArrowUpRight)
5920 .color(Color::Muted)
5921 .size(IconSize::Small),
5922 )
5923 .into_any_element(),
5924 )
5925 .into_any(),
5926 );
5927 }
5928
5929 let is_refreshing = provider.provider.is_refreshing(cx);
5930
5931 fn pending_completion_container() -> Div {
5932 h_flex()
5933 .h_full()
5934 .flex_1()
5935 .gap_2()
5936 .child(Icon::new(IconName::ZedPredict))
5937 }
5938
5939 let completion = match &self.active_inline_completion {
5940 Some(completion) => match &completion.completion {
5941 InlineCompletion::Move {
5942 target, snapshot, ..
5943 } if !self.has_visible_completions_menu() => {
5944 use text::ToPoint as _;
5945
5946 return Some(
5947 h_flex()
5948 .px_2()
5949 .py_1()
5950 .gap_2()
5951 .elevation_2(cx)
5952 .border_color(cx.theme().colors().border)
5953 .rounded(px(6.))
5954 .rounded_tl(px(0.))
5955 .child(
5956 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5957 Icon::new(IconName::ZedPredictDown)
5958 } else {
5959 Icon::new(IconName::ZedPredictUp)
5960 },
5961 )
5962 .child(Label::new("Hold").size(LabelSize::Small))
5963 .child(h_flex().children(ui::render_modifiers(
5964 &accept_keystroke?.modifiers,
5965 PlatformStyle::platform(),
5966 Some(Color::Default),
5967 Some(IconSize::Small.rems().into()),
5968 false,
5969 )))
5970 .into_any(),
5971 );
5972 }
5973 _ => self.render_edit_prediction_cursor_popover_preview(
5974 completion,
5975 cursor_point,
5976 style,
5977 cx,
5978 )?,
5979 },
5980
5981 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5982 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5983 stale_completion,
5984 cursor_point,
5985 style,
5986 cx,
5987 )?,
5988
5989 None => {
5990 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5991 }
5992 },
5993
5994 None => pending_completion_container().child(Label::new("No Prediction")),
5995 };
5996
5997 let completion = if is_refreshing {
5998 completion
5999 .with_animation(
6000 "loading-completion",
6001 Animation::new(Duration::from_secs(2))
6002 .repeat()
6003 .with_easing(pulsating_between(0.4, 0.8)),
6004 |label, delta| label.opacity(delta),
6005 )
6006 .into_any_element()
6007 } else {
6008 completion.into_any_element()
6009 };
6010
6011 let has_completion = self.active_inline_completion.is_some();
6012
6013 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6014 Some(
6015 h_flex()
6016 .min_w(min_width)
6017 .max_w(max_width)
6018 .flex_1()
6019 .elevation_2(cx)
6020 .border_color(cx.theme().colors().border)
6021 .child(
6022 div()
6023 .flex_1()
6024 .py_1()
6025 .px_2()
6026 .overflow_hidden()
6027 .child(completion),
6028 )
6029 .when_some(accept_keystroke, |el, accept_keystroke| {
6030 if !accept_keystroke.modifiers.modified() {
6031 return el;
6032 }
6033
6034 el.child(
6035 h_flex()
6036 .h_full()
6037 .border_l_1()
6038 .rounded_r_lg()
6039 .border_color(cx.theme().colors().border)
6040 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6041 .gap_1()
6042 .py_1()
6043 .px_2()
6044 .child(
6045 h_flex()
6046 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6047 .when(is_platform_style_mac, |parent| parent.gap_1())
6048 .child(h_flex().children(ui::render_modifiers(
6049 &accept_keystroke.modifiers,
6050 PlatformStyle::platform(),
6051 Some(if !has_completion {
6052 Color::Muted
6053 } else {
6054 Color::Default
6055 }),
6056 None,
6057 false,
6058 ))),
6059 )
6060 .child(Label::new("Preview").into_any_element())
6061 .opacity(if has_completion { 1.0 } else { 0.4 }),
6062 )
6063 })
6064 .into_any(),
6065 )
6066 }
6067
6068 fn render_edit_prediction_cursor_popover_preview(
6069 &self,
6070 completion: &InlineCompletionState,
6071 cursor_point: Point,
6072 style: &EditorStyle,
6073 cx: &mut Context<Editor>,
6074 ) -> Option<Div> {
6075 use text::ToPoint as _;
6076
6077 fn render_relative_row_jump(
6078 prefix: impl Into<String>,
6079 current_row: u32,
6080 target_row: u32,
6081 ) -> Div {
6082 let (row_diff, arrow) = if target_row < current_row {
6083 (current_row - target_row, IconName::ArrowUp)
6084 } else {
6085 (target_row - current_row, IconName::ArrowDown)
6086 };
6087
6088 h_flex()
6089 .child(
6090 Label::new(format!("{}{}", prefix.into(), row_diff))
6091 .color(Color::Muted)
6092 .size(LabelSize::Small),
6093 )
6094 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6095 }
6096
6097 match &completion.completion {
6098 InlineCompletion::Move {
6099 target, snapshot, ..
6100 } => Some(
6101 h_flex()
6102 .px_2()
6103 .gap_2()
6104 .flex_1()
6105 .child(
6106 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6107 Icon::new(IconName::ZedPredictDown)
6108 } else {
6109 Icon::new(IconName::ZedPredictUp)
6110 },
6111 )
6112 .child(Label::new("Jump to Edit")),
6113 ),
6114
6115 InlineCompletion::Edit {
6116 edits,
6117 edit_preview,
6118 snapshot,
6119 display_mode: _,
6120 } => {
6121 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6122
6123 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6124 &snapshot,
6125 &edits,
6126 edit_preview.as_ref()?,
6127 true,
6128 cx,
6129 )
6130 .first_line_preview();
6131
6132 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6133 .with_highlights(&style.text, highlighted_edits.highlights);
6134
6135 let preview = h_flex()
6136 .gap_1()
6137 .min_w_16()
6138 .child(styled_text)
6139 .when(has_more_lines, |parent| parent.child("…"));
6140
6141 let left = if first_edit_row != cursor_point.row {
6142 render_relative_row_jump("", cursor_point.row, first_edit_row)
6143 .into_any_element()
6144 } else {
6145 Icon::new(IconName::ZedPredict).into_any_element()
6146 };
6147
6148 Some(
6149 h_flex()
6150 .h_full()
6151 .flex_1()
6152 .gap_2()
6153 .pr_1()
6154 .overflow_x_hidden()
6155 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6156 .child(left)
6157 .child(preview),
6158 )
6159 }
6160 }
6161 }
6162
6163 fn render_context_menu(
6164 &self,
6165 style: &EditorStyle,
6166 max_height_in_lines: u32,
6167 y_flipped: bool,
6168 window: &mut Window,
6169 cx: &mut Context<Editor>,
6170 ) -> Option<AnyElement> {
6171 let menu = self.context_menu.borrow();
6172 let menu = menu.as_ref()?;
6173 if !menu.visible() {
6174 return None;
6175 };
6176 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6177 }
6178
6179 fn render_context_menu_aside(
6180 &mut self,
6181 max_size: Size<Pixels>,
6182 window: &mut Window,
6183 cx: &mut Context<Editor>,
6184 ) -> Option<AnyElement> {
6185 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6186 if menu.visible() {
6187 menu.render_aside(self, max_size, window, cx)
6188 } else {
6189 None
6190 }
6191 })
6192 }
6193
6194 fn hide_context_menu(
6195 &mut self,
6196 window: &mut Window,
6197 cx: &mut Context<Self>,
6198 ) -> Option<CodeContextMenu> {
6199 cx.notify();
6200 self.completion_tasks.clear();
6201 let context_menu = self.context_menu.borrow_mut().take();
6202 self.stale_inline_completion_in_menu.take();
6203 self.update_visible_inline_completion(window, cx);
6204 context_menu
6205 }
6206
6207 fn show_snippet_choices(
6208 &mut self,
6209 choices: &Vec<String>,
6210 selection: Range<Anchor>,
6211 cx: &mut Context<Self>,
6212 ) {
6213 if selection.start.buffer_id.is_none() {
6214 return;
6215 }
6216 let buffer_id = selection.start.buffer_id.unwrap();
6217 let buffer = self.buffer().read(cx).buffer(buffer_id);
6218 let id = post_inc(&mut self.next_completion_id);
6219
6220 if let Some(buffer) = buffer {
6221 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6222 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6223 ));
6224 }
6225 }
6226
6227 pub fn insert_snippet(
6228 &mut self,
6229 insertion_ranges: &[Range<usize>],
6230 snippet: Snippet,
6231 window: &mut Window,
6232 cx: &mut Context<Self>,
6233 ) -> Result<()> {
6234 struct Tabstop<T> {
6235 is_end_tabstop: bool,
6236 ranges: Vec<Range<T>>,
6237 choices: Option<Vec<String>>,
6238 }
6239
6240 let tabstops = self.buffer.update(cx, |buffer, cx| {
6241 let snippet_text: Arc<str> = snippet.text.clone().into();
6242 buffer.edit(
6243 insertion_ranges
6244 .iter()
6245 .cloned()
6246 .map(|range| (range, snippet_text.clone())),
6247 Some(AutoindentMode::EachLine),
6248 cx,
6249 );
6250
6251 let snapshot = &*buffer.read(cx);
6252 let snippet = &snippet;
6253 snippet
6254 .tabstops
6255 .iter()
6256 .map(|tabstop| {
6257 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6258 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6259 });
6260 let mut tabstop_ranges = tabstop
6261 .ranges
6262 .iter()
6263 .flat_map(|tabstop_range| {
6264 let mut delta = 0_isize;
6265 insertion_ranges.iter().map(move |insertion_range| {
6266 let insertion_start = insertion_range.start as isize + delta;
6267 delta +=
6268 snippet.text.len() as isize - insertion_range.len() as isize;
6269
6270 let start = ((insertion_start + tabstop_range.start) as usize)
6271 .min(snapshot.len());
6272 let end = ((insertion_start + tabstop_range.end) as usize)
6273 .min(snapshot.len());
6274 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6275 })
6276 })
6277 .collect::<Vec<_>>();
6278 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6279
6280 Tabstop {
6281 is_end_tabstop,
6282 ranges: tabstop_ranges,
6283 choices: tabstop.choices.clone(),
6284 }
6285 })
6286 .collect::<Vec<_>>()
6287 });
6288 if let Some(tabstop) = tabstops.first() {
6289 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6290 s.select_ranges(tabstop.ranges.iter().cloned());
6291 });
6292
6293 if let Some(choices) = &tabstop.choices {
6294 if let Some(selection) = tabstop.ranges.first() {
6295 self.show_snippet_choices(choices, selection.clone(), cx)
6296 }
6297 }
6298
6299 // If we're already at the last tabstop and it's at the end of the snippet,
6300 // we're done, we don't need to keep the state around.
6301 if !tabstop.is_end_tabstop {
6302 let choices = tabstops
6303 .iter()
6304 .map(|tabstop| tabstop.choices.clone())
6305 .collect();
6306
6307 let ranges = tabstops
6308 .into_iter()
6309 .map(|tabstop| tabstop.ranges)
6310 .collect::<Vec<_>>();
6311
6312 self.snippet_stack.push(SnippetState {
6313 active_index: 0,
6314 ranges,
6315 choices,
6316 });
6317 }
6318
6319 // Check whether the just-entered snippet ends with an auto-closable bracket.
6320 if self.autoclose_regions.is_empty() {
6321 let snapshot = self.buffer.read(cx).snapshot(cx);
6322 for selection in &mut self.selections.all::<Point>(cx) {
6323 let selection_head = selection.head();
6324 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6325 continue;
6326 };
6327
6328 let mut bracket_pair = None;
6329 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6330 let prev_chars = snapshot
6331 .reversed_chars_at(selection_head)
6332 .collect::<String>();
6333 for (pair, enabled) in scope.brackets() {
6334 if enabled
6335 && pair.close
6336 && prev_chars.starts_with(pair.start.as_str())
6337 && next_chars.starts_with(pair.end.as_str())
6338 {
6339 bracket_pair = Some(pair.clone());
6340 break;
6341 }
6342 }
6343 if let Some(pair) = bracket_pair {
6344 let start = snapshot.anchor_after(selection_head);
6345 let end = snapshot.anchor_after(selection_head);
6346 self.autoclose_regions.push(AutocloseRegion {
6347 selection_id: selection.id,
6348 range: start..end,
6349 pair,
6350 });
6351 }
6352 }
6353 }
6354 }
6355 Ok(())
6356 }
6357
6358 pub fn move_to_next_snippet_tabstop(
6359 &mut self,
6360 window: &mut Window,
6361 cx: &mut Context<Self>,
6362 ) -> bool {
6363 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6364 }
6365
6366 pub fn move_to_prev_snippet_tabstop(
6367 &mut self,
6368 window: &mut Window,
6369 cx: &mut Context<Self>,
6370 ) -> bool {
6371 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6372 }
6373
6374 pub fn move_to_snippet_tabstop(
6375 &mut self,
6376 bias: Bias,
6377 window: &mut Window,
6378 cx: &mut Context<Self>,
6379 ) -> bool {
6380 if let Some(mut snippet) = self.snippet_stack.pop() {
6381 match bias {
6382 Bias::Left => {
6383 if snippet.active_index > 0 {
6384 snippet.active_index -= 1;
6385 } else {
6386 self.snippet_stack.push(snippet);
6387 return false;
6388 }
6389 }
6390 Bias::Right => {
6391 if snippet.active_index + 1 < snippet.ranges.len() {
6392 snippet.active_index += 1;
6393 } else {
6394 self.snippet_stack.push(snippet);
6395 return false;
6396 }
6397 }
6398 }
6399 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6400 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6401 s.select_anchor_ranges(current_ranges.iter().cloned())
6402 });
6403
6404 if let Some(choices) = &snippet.choices[snippet.active_index] {
6405 if let Some(selection) = current_ranges.first() {
6406 self.show_snippet_choices(&choices, selection.clone(), cx);
6407 }
6408 }
6409
6410 // If snippet state is not at the last tabstop, push it back on the stack
6411 if snippet.active_index + 1 < snippet.ranges.len() {
6412 self.snippet_stack.push(snippet);
6413 }
6414 return true;
6415 }
6416 }
6417
6418 false
6419 }
6420
6421 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6422 self.transact(window, cx, |this, window, cx| {
6423 this.select_all(&SelectAll, window, cx);
6424 this.insert("", window, cx);
6425 });
6426 }
6427
6428 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6429 self.transact(window, cx, |this, window, cx| {
6430 this.select_autoclose_pair(window, cx);
6431 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6432 if !this.linked_edit_ranges.is_empty() {
6433 let selections = this.selections.all::<MultiBufferPoint>(cx);
6434 let snapshot = this.buffer.read(cx).snapshot(cx);
6435
6436 for selection in selections.iter() {
6437 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6438 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6439 if selection_start.buffer_id != selection_end.buffer_id {
6440 continue;
6441 }
6442 if let Some(ranges) =
6443 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6444 {
6445 for (buffer, entries) in ranges {
6446 linked_ranges.entry(buffer).or_default().extend(entries);
6447 }
6448 }
6449 }
6450 }
6451
6452 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6453 if !this.selections.line_mode {
6454 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6455 for selection in &mut selections {
6456 if selection.is_empty() {
6457 let old_head = selection.head();
6458 let mut new_head =
6459 movement::left(&display_map, old_head.to_display_point(&display_map))
6460 .to_point(&display_map);
6461 if let Some((buffer, line_buffer_range)) = display_map
6462 .buffer_snapshot
6463 .buffer_line_for_row(MultiBufferRow(old_head.row))
6464 {
6465 let indent_size =
6466 buffer.indent_size_for_line(line_buffer_range.start.row);
6467 let indent_len = match indent_size.kind {
6468 IndentKind::Space => {
6469 buffer.settings_at(line_buffer_range.start, cx).tab_size
6470 }
6471 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6472 };
6473 if old_head.column <= indent_size.len && old_head.column > 0 {
6474 let indent_len = indent_len.get();
6475 new_head = cmp::min(
6476 new_head,
6477 MultiBufferPoint::new(
6478 old_head.row,
6479 ((old_head.column - 1) / indent_len) * indent_len,
6480 ),
6481 );
6482 }
6483 }
6484
6485 selection.set_head(new_head, SelectionGoal::None);
6486 }
6487 }
6488 }
6489
6490 this.signature_help_state.set_backspace_pressed(true);
6491 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6492 s.select(selections)
6493 });
6494 this.insert("", window, cx);
6495 let empty_str: Arc<str> = Arc::from("");
6496 for (buffer, edits) in linked_ranges {
6497 let snapshot = buffer.read(cx).snapshot();
6498 use text::ToPoint as TP;
6499
6500 let edits = edits
6501 .into_iter()
6502 .map(|range| {
6503 let end_point = TP::to_point(&range.end, &snapshot);
6504 let mut start_point = TP::to_point(&range.start, &snapshot);
6505
6506 if end_point == start_point {
6507 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6508 .saturating_sub(1);
6509 start_point =
6510 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6511 };
6512
6513 (start_point..end_point, empty_str.clone())
6514 })
6515 .sorted_by_key(|(range, _)| range.start)
6516 .collect::<Vec<_>>();
6517 buffer.update(cx, |this, cx| {
6518 this.edit(edits, None, cx);
6519 })
6520 }
6521 this.refresh_inline_completion(true, false, window, cx);
6522 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6523 });
6524 }
6525
6526 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6527 self.transact(window, cx, |this, window, cx| {
6528 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6529 let line_mode = s.line_mode;
6530 s.move_with(|map, selection| {
6531 if selection.is_empty() && !line_mode {
6532 let cursor = movement::right(map, selection.head());
6533 selection.end = cursor;
6534 selection.reversed = true;
6535 selection.goal = SelectionGoal::None;
6536 }
6537 })
6538 });
6539 this.insert("", window, cx);
6540 this.refresh_inline_completion(true, false, window, cx);
6541 });
6542 }
6543
6544 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6545 if self.move_to_prev_snippet_tabstop(window, cx) {
6546 return;
6547 }
6548
6549 self.outdent(&Outdent, window, cx);
6550 }
6551
6552 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6553 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6554 return;
6555 }
6556
6557 let mut selections = self.selections.all_adjusted(cx);
6558 let buffer = self.buffer.read(cx);
6559 let snapshot = buffer.snapshot(cx);
6560 let rows_iter = selections.iter().map(|s| s.head().row);
6561 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6562
6563 let mut edits = Vec::new();
6564 let mut prev_edited_row = 0;
6565 let mut row_delta = 0;
6566 for selection in &mut selections {
6567 if selection.start.row != prev_edited_row {
6568 row_delta = 0;
6569 }
6570 prev_edited_row = selection.end.row;
6571
6572 // If the selection is non-empty, then increase the indentation of the selected lines.
6573 if !selection.is_empty() {
6574 row_delta =
6575 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6576 continue;
6577 }
6578
6579 // If the selection is empty and the cursor is in the leading whitespace before the
6580 // suggested indentation, then auto-indent the line.
6581 let cursor = selection.head();
6582 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6583 if let Some(suggested_indent) =
6584 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6585 {
6586 if cursor.column < suggested_indent.len
6587 && cursor.column <= current_indent.len
6588 && current_indent.len <= suggested_indent.len
6589 {
6590 selection.start = Point::new(cursor.row, suggested_indent.len);
6591 selection.end = selection.start;
6592 if row_delta == 0 {
6593 edits.extend(Buffer::edit_for_indent_size_adjustment(
6594 cursor.row,
6595 current_indent,
6596 suggested_indent,
6597 ));
6598 row_delta = suggested_indent.len - current_indent.len;
6599 }
6600 continue;
6601 }
6602 }
6603
6604 // Otherwise, insert a hard or soft tab.
6605 let settings = buffer.settings_at(cursor, cx);
6606 let tab_size = if settings.hard_tabs {
6607 IndentSize::tab()
6608 } else {
6609 let tab_size = settings.tab_size.get();
6610 let char_column = snapshot
6611 .text_for_range(Point::new(cursor.row, 0)..cursor)
6612 .flat_map(str::chars)
6613 .count()
6614 + row_delta as usize;
6615 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6616 IndentSize::spaces(chars_to_next_tab_stop)
6617 };
6618 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6619 selection.end = selection.start;
6620 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6621 row_delta += tab_size.len;
6622 }
6623
6624 self.transact(window, cx, |this, window, cx| {
6625 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6626 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6627 s.select(selections)
6628 });
6629 this.refresh_inline_completion(true, false, window, cx);
6630 });
6631 }
6632
6633 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6634 if self.read_only(cx) {
6635 return;
6636 }
6637 let mut selections = self.selections.all::<Point>(cx);
6638 let mut prev_edited_row = 0;
6639 let mut row_delta = 0;
6640 let mut edits = Vec::new();
6641 let buffer = self.buffer.read(cx);
6642 let snapshot = buffer.snapshot(cx);
6643 for selection in &mut selections {
6644 if selection.start.row != prev_edited_row {
6645 row_delta = 0;
6646 }
6647 prev_edited_row = selection.end.row;
6648
6649 row_delta =
6650 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6651 }
6652
6653 self.transact(window, cx, |this, window, cx| {
6654 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6655 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6656 s.select(selections)
6657 });
6658 });
6659 }
6660
6661 fn indent_selection(
6662 buffer: &MultiBuffer,
6663 snapshot: &MultiBufferSnapshot,
6664 selection: &mut Selection<Point>,
6665 edits: &mut Vec<(Range<Point>, String)>,
6666 delta_for_start_row: u32,
6667 cx: &App,
6668 ) -> u32 {
6669 let settings = buffer.settings_at(selection.start, cx);
6670 let tab_size = settings.tab_size.get();
6671 let indent_kind = if settings.hard_tabs {
6672 IndentKind::Tab
6673 } else {
6674 IndentKind::Space
6675 };
6676 let mut start_row = selection.start.row;
6677 let mut end_row = selection.end.row + 1;
6678
6679 // If a selection ends at the beginning of a line, don't indent
6680 // that last line.
6681 if selection.end.column == 0 && selection.end.row > selection.start.row {
6682 end_row -= 1;
6683 }
6684
6685 // Avoid re-indenting a row that has already been indented by a
6686 // previous selection, but still update this selection's column
6687 // to reflect that indentation.
6688 if delta_for_start_row > 0 {
6689 start_row += 1;
6690 selection.start.column += delta_for_start_row;
6691 if selection.end.row == selection.start.row {
6692 selection.end.column += delta_for_start_row;
6693 }
6694 }
6695
6696 let mut delta_for_end_row = 0;
6697 let has_multiple_rows = start_row + 1 != end_row;
6698 for row in start_row..end_row {
6699 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6700 let indent_delta = match (current_indent.kind, indent_kind) {
6701 (IndentKind::Space, IndentKind::Space) => {
6702 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6703 IndentSize::spaces(columns_to_next_tab_stop)
6704 }
6705 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6706 (_, IndentKind::Tab) => IndentSize::tab(),
6707 };
6708
6709 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6710 0
6711 } else {
6712 selection.start.column
6713 };
6714 let row_start = Point::new(row, start);
6715 edits.push((
6716 row_start..row_start,
6717 indent_delta.chars().collect::<String>(),
6718 ));
6719
6720 // Update this selection's endpoints to reflect the indentation.
6721 if row == selection.start.row {
6722 selection.start.column += indent_delta.len;
6723 }
6724 if row == selection.end.row {
6725 selection.end.column += indent_delta.len;
6726 delta_for_end_row = indent_delta.len;
6727 }
6728 }
6729
6730 if selection.start.row == selection.end.row {
6731 delta_for_start_row + delta_for_end_row
6732 } else {
6733 delta_for_end_row
6734 }
6735 }
6736
6737 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6738 if self.read_only(cx) {
6739 return;
6740 }
6741 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6742 let selections = self.selections.all::<Point>(cx);
6743 let mut deletion_ranges = Vec::new();
6744 let mut last_outdent = None;
6745 {
6746 let buffer = self.buffer.read(cx);
6747 let snapshot = buffer.snapshot(cx);
6748 for selection in &selections {
6749 let settings = buffer.settings_at(selection.start, cx);
6750 let tab_size = settings.tab_size.get();
6751 let mut rows = selection.spanned_rows(false, &display_map);
6752
6753 // Avoid re-outdenting a row that has already been outdented by a
6754 // previous selection.
6755 if let Some(last_row) = last_outdent {
6756 if last_row == rows.start {
6757 rows.start = rows.start.next_row();
6758 }
6759 }
6760 let has_multiple_rows = rows.len() > 1;
6761 for row in rows.iter_rows() {
6762 let indent_size = snapshot.indent_size_for_line(row);
6763 if indent_size.len > 0 {
6764 let deletion_len = match indent_size.kind {
6765 IndentKind::Space => {
6766 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6767 if columns_to_prev_tab_stop == 0 {
6768 tab_size
6769 } else {
6770 columns_to_prev_tab_stop
6771 }
6772 }
6773 IndentKind::Tab => 1,
6774 };
6775 let start = if has_multiple_rows
6776 || deletion_len > selection.start.column
6777 || indent_size.len < selection.start.column
6778 {
6779 0
6780 } else {
6781 selection.start.column - deletion_len
6782 };
6783 deletion_ranges.push(
6784 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6785 );
6786 last_outdent = Some(row);
6787 }
6788 }
6789 }
6790 }
6791
6792 self.transact(window, cx, |this, window, cx| {
6793 this.buffer.update(cx, |buffer, cx| {
6794 let empty_str: Arc<str> = Arc::default();
6795 buffer.edit(
6796 deletion_ranges
6797 .into_iter()
6798 .map(|range| (range, empty_str.clone())),
6799 None,
6800 cx,
6801 );
6802 });
6803 let selections = this.selections.all::<usize>(cx);
6804 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6805 s.select(selections)
6806 });
6807 });
6808 }
6809
6810 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6811 if self.read_only(cx) {
6812 return;
6813 }
6814 let selections = self
6815 .selections
6816 .all::<usize>(cx)
6817 .into_iter()
6818 .map(|s| s.range());
6819
6820 self.transact(window, cx, |this, window, cx| {
6821 this.buffer.update(cx, |buffer, cx| {
6822 buffer.autoindent_ranges(selections, cx);
6823 });
6824 let selections = this.selections.all::<usize>(cx);
6825 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6826 s.select(selections)
6827 });
6828 });
6829 }
6830
6831 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6832 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6833 let selections = self.selections.all::<Point>(cx);
6834
6835 let mut new_cursors = Vec::new();
6836 let mut edit_ranges = Vec::new();
6837 let mut selections = selections.iter().peekable();
6838 while let Some(selection) = selections.next() {
6839 let mut rows = selection.spanned_rows(false, &display_map);
6840 let goal_display_column = selection.head().to_display_point(&display_map).column();
6841
6842 // Accumulate contiguous regions of rows that we want to delete.
6843 while let Some(next_selection) = selections.peek() {
6844 let next_rows = next_selection.spanned_rows(false, &display_map);
6845 if next_rows.start <= rows.end {
6846 rows.end = next_rows.end;
6847 selections.next().unwrap();
6848 } else {
6849 break;
6850 }
6851 }
6852
6853 let buffer = &display_map.buffer_snapshot;
6854 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6855 let edit_end;
6856 let cursor_buffer_row;
6857 if buffer.max_point().row >= rows.end.0 {
6858 // If there's a line after the range, delete the \n from the end of the row range
6859 // and position the cursor on the next line.
6860 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6861 cursor_buffer_row = rows.end;
6862 } else {
6863 // If there isn't a line after the range, delete the \n from the line before the
6864 // start of the row range and position the cursor there.
6865 edit_start = edit_start.saturating_sub(1);
6866 edit_end = buffer.len();
6867 cursor_buffer_row = rows.start.previous_row();
6868 }
6869
6870 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6871 *cursor.column_mut() =
6872 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6873
6874 new_cursors.push((
6875 selection.id,
6876 buffer.anchor_after(cursor.to_point(&display_map)),
6877 ));
6878 edit_ranges.push(edit_start..edit_end);
6879 }
6880
6881 self.transact(window, cx, |this, window, cx| {
6882 let buffer = this.buffer.update(cx, |buffer, cx| {
6883 let empty_str: Arc<str> = Arc::default();
6884 buffer.edit(
6885 edit_ranges
6886 .into_iter()
6887 .map(|range| (range, empty_str.clone())),
6888 None,
6889 cx,
6890 );
6891 buffer.snapshot(cx)
6892 });
6893 let new_selections = new_cursors
6894 .into_iter()
6895 .map(|(id, cursor)| {
6896 let cursor = cursor.to_point(&buffer);
6897 Selection {
6898 id,
6899 start: cursor,
6900 end: cursor,
6901 reversed: false,
6902 goal: SelectionGoal::None,
6903 }
6904 })
6905 .collect();
6906
6907 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6908 s.select(new_selections);
6909 });
6910 });
6911 }
6912
6913 pub fn join_lines_impl(
6914 &mut self,
6915 insert_whitespace: bool,
6916 window: &mut Window,
6917 cx: &mut Context<Self>,
6918 ) {
6919 if self.read_only(cx) {
6920 return;
6921 }
6922 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6923 for selection in self.selections.all::<Point>(cx) {
6924 let start = MultiBufferRow(selection.start.row);
6925 // Treat single line selections as if they include the next line. Otherwise this action
6926 // would do nothing for single line selections individual cursors.
6927 let end = if selection.start.row == selection.end.row {
6928 MultiBufferRow(selection.start.row + 1)
6929 } else {
6930 MultiBufferRow(selection.end.row)
6931 };
6932
6933 if let Some(last_row_range) = row_ranges.last_mut() {
6934 if start <= last_row_range.end {
6935 last_row_range.end = end;
6936 continue;
6937 }
6938 }
6939 row_ranges.push(start..end);
6940 }
6941
6942 let snapshot = self.buffer.read(cx).snapshot(cx);
6943 let mut cursor_positions = Vec::new();
6944 for row_range in &row_ranges {
6945 let anchor = snapshot.anchor_before(Point::new(
6946 row_range.end.previous_row().0,
6947 snapshot.line_len(row_range.end.previous_row()),
6948 ));
6949 cursor_positions.push(anchor..anchor);
6950 }
6951
6952 self.transact(window, cx, |this, window, cx| {
6953 for row_range in row_ranges.into_iter().rev() {
6954 for row in row_range.iter_rows().rev() {
6955 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6956 let next_line_row = row.next_row();
6957 let indent = snapshot.indent_size_for_line(next_line_row);
6958 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6959
6960 let replace =
6961 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6962 " "
6963 } else {
6964 ""
6965 };
6966
6967 this.buffer.update(cx, |buffer, cx| {
6968 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6969 });
6970 }
6971 }
6972
6973 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6974 s.select_anchor_ranges(cursor_positions)
6975 });
6976 });
6977 }
6978
6979 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6980 self.join_lines_impl(true, window, cx);
6981 }
6982
6983 pub fn sort_lines_case_sensitive(
6984 &mut self,
6985 _: &SortLinesCaseSensitive,
6986 window: &mut Window,
6987 cx: &mut Context<Self>,
6988 ) {
6989 self.manipulate_lines(window, cx, |lines| lines.sort())
6990 }
6991
6992 pub fn sort_lines_case_insensitive(
6993 &mut self,
6994 _: &SortLinesCaseInsensitive,
6995 window: &mut Window,
6996 cx: &mut Context<Self>,
6997 ) {
6998 self.manipulate_lines(window, cx, |lines| {
6999 lines.sort_by_key(|line| line.to_lowercase())
7000 })
7001 }
7002
7003 pub fn unique_lines_case_insensitive(
7004 &mut self,
7005 _: &UniqueLinesCaseInsensitive,
7006 window: &mut Window,
7007 cx: &mut Context<Self>,
7008 ) {
7009 self.manipulate_lines(window, cx, |lines| {
7010 let mut seen = HashSet::default();
7011 lines.retain(|line| seen.insert(line.to_lowercase()));
7012 })
7013 }
7014
7015 pub fn unique_lines_case_sensitive(
7016 &mut self,
7017 _: &UniqueLinesCaseSensitive,
7018 window: &mut Window,
7019 cx: &mut Context<Self>,
7020 ) {
7021 self.manipulate_lines(window, cx, |lines| {
7022 let mut seen = HashSet::default();
7023 lines.retain(|line| seen.insert(*line));
7024 })
7025 }
7026
7027 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7028 let mut revert_changes = HashMap::default();
7029 let snapshot = self.snapshot(window, cx);
7030 for hunk in snapshot
7031 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7032 {
7033 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7034 }
7035 if !revert_changes.is_empty() {
7036 self.transact(window, cx, |editor, window, cx| {
7037 editor.revert(revert_changes, window, cx);
7038 });
7039 }
7040 }
7041
7042 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7043 let Some(project) = self.project.clone() else {
7044 return;
7045 };
7046 self.reload(project, window, cx)
7047 .detach_and_notify_err(window, cx);
7048 }
7049
7050 pub fn revert_selected_hunks(
7051 &mut self,
7052 _: &RevertSelectedHunks,
7053 window: &mut Window,
7054 cx: &mut Context<Self>,
7055 ) {
7056 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7057 self.discard_hunks_in_ranges(selections, window, cx);
7058 }
7059
7060 fn discard_hunks_in_ranges(
7061 &mut self,
7062 ranges: impl Iterator<Item = Range<Point>>,
7063 window: &mut Window,
7064 cx: &mut Context<Editor>,
7065 ) {
7066 let mut revert_changes = HashMap::default();
7067 let snapshot = self.snapshot(window, cx);
7068 for hunk in &snapshot.hunks_for_ranges(ranges) {
7069 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7070 }
7071 if !revert_changes.is_empty() {
7072 self.transact(window, cx, |editor, window, cx| {
7073 editor.revert(revert_changes, window, cx);
7074 });
7075 }
7076 }
7077
7078 pub fn open_active_item_in_terminal(
7079 &mut self,
7080 _: &OpenInTerminal,
7081 window: &mut Window,
7082 cx: &mut Context<Self>,
7083 ) {
7084 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7085 let project_path = buffer.read(cx).project_path(cx)?;
7086 let project = self.project.as_ref()?.read(cx);
7087 let entry = project.entry_for_path(&project_path, cx)?;
7088 let parent = match &entry.canonical_path {
7089 Some(canonical_path) => canonical_path.to_path_buf(),
7090 None => project.absolute_path(&project_path, cx)?,
7091 }
7092 .parent()?
7093 .to_path_buf();
7094 Some(parent)
7095 }) {
7096 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7097 }
7098 }
7099
7100 pub fn prepare_revert_change(
7101 &self,
7102 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7103 hunk: &MultiBufferDiffHunk,
7104 cx: &mut App,
7105 ) -> Option<()> {
7106 let buffer = self.buffer.read(cx);
7107 let diff = buffer.diff_for(hunk.buffer_id)?;
7108 let buffer = buffer.buffer(hunk.buffer_id)?;
7109 let buffer = buffer.read(cx);
7110 let original_text = diff
7111 .read(cx)
7112 .base_text()
7113 .as_ref()?
7114 .as_rope()
7115 .slice(hunk.diff_base_byte_range.clone());
7116 let buffer_snapshot = buffer.snapshot();
7117 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7118 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7119 probe
7120 .0
7121 .start
7122 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7123 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7124 }) {
7125 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7126 Some(())
7127 } else {
7128 None
7129 }
7130 }
7131
7132 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7133 self.manipulate_lines(window, cx, |lines| lines.reverse())
7134 }
7135
7136 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7137 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7138 }
7139
7140 fn manipulate_lines<Fn>(
7141 &mut self,
7142 window: &mut Window,
7143 cx: &mut Context<Self>,
7144 mut callback: Fn,
7145 ) where
7146 Fn: FnMut(&mut Vec<&str>),
7147 {
7148 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7149 let buffer = self.buffer.read(cx).snapshot(cx);
7150
7151 let mut edits = Vec::new();
7152
7153 let selections = self.selections.all::<Point>(cx);
7154 let mut selections = selections.iter().peekable();
7155 let mut contiguous_row_selections = Vec::new();
7156 let mut new_selections = Vec::new();
7157 let mut added_lines = 0;
7158 let mut removed_lines = 0;
7159
7160 while let Some(selection) = selections.next() {
7161 let (start_row, end_row) = consume_contiguous_rows(
7162 &mut contiguous_row_selections,
7163 selection,
7164 &display_map,
7165 &mut selections,
7166 );
7167
7168 let start_point = Point::new(start_row.0, 0);
7169 let end_point = Point::new(
7170 end_row.previous_row().0,
7171 buffer.line_len(end_row.previous_row()),
7172 );
7173 let text = buffer
7174 .text_for_range(start_point..end_point)
7175 .collect::<String>();
7176
7177 let mut lines = text.split('\n').collect_vec();
7178
7179 let lines_before = lines.len();
7180 callback(&mut lines);
7181 let lines_after = lines.len();
7182
7183 edits.push((start_point..end_point, lines.join("\n")));
7184
7185 // Selections must change based on added and removed line count
7186 let start_row =
7187 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7188 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7189 new_selections.push(Selection {
7190 id: selection.id,
7191 start: start_row,
7192 end: end_row,
7193 goal: SelectionGoal::None,
7194 reversed: selection.reversed,
7195 });
7196
7197 if lines_after > lines_before {
7198 added_lines += lines_after - lines_before;
7199 } else if lines_before > lines_after {
7200 removed_lines += lines_before - lines_after;
7201 }
7202 }
7203
7204 self.transact(window, cx, |this, window, cx| {
7205 let buffer = this.buffer.update(cx, |buffer, cx| {
7206 buffer.edit(edits, None, cx);
7207 buffer.snapshot(cx)
7208 });
7209
7210 // Recalculate offsets on newly edited buffer
7211 let new_selections = new_selections
7212 .iter()
7213 .map(|s| {
7214 let start_point = Point::new(s.start.0, 0);
7215 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7216 Selection {
7217 id: s.id,
7218 start: buffer.point_to_offset(start_point),
7219 end: buffer.point_to_offset(end_point),
7220 goal: s.goal,
7221 reversed: s.reversed,
7222 }
7223 })
7224 .collect();
7225
7226 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7227 s.select(new_selections);
7228 });
7229
7230 this.request_autoscroll(Autoscroll::fit(), cx);
7231 });
7232 }
7233
7234 pub fn convert_to_upper_case(
7235 &mut self,
7236 _: &ConvertToUpperCase,
7237 window: &mut Window,
7238 cx: &mut Context<Self>,
7239 ) {
7240 self.manipulate_text(window, cx, |text| text.to_uppercase())
7241 }
7242
7243 pub fn convert_to_lower_case(
7244 &mut self,
7245 _: &ConvertToLowerCase,
7246 window: &mut Window,
7247 cx: &mut Context<Self>,
7248 ) {
7249 self.manipulate_text(window, cx, |text| text.to_lowercase())
7250 }
7251
7252 pub fn convert_to_title_case(
7253 &mut self,
7254 _: &ConvertToTitleCase,
7255 window: &mut Window,
7256 cx: &mut Context<Self>,
7257 ) {
7258 self.manipulate_text(window, cx, |text| {
7259 text.split('\n')
7260 .map(|line| line.to_case(Case::Title))
7261 .join("\n")
7262 })
7263 }
7264
7265 pub fn convert_to_snake_case(
7266 &mut self,
7267 _: &ConvertToSnakeCase,
7268 window: &mut Window,
7269 cx: &mut Context<Self>,
7270 ) {
7271 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7272 }
7273
7274 pub fn convert_to_kebab_case(
7275 &mut self,
7276 _: &ConvertToKebabCase,
7277 window: &mut Window,
7278 cx: &mut Context<Self>,
7279 ) {
7280 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7281 }
7282
7283 pub fn convert_to_upper_camel_case(
7284 &mut self,
7285 _: &ConvertToUpperCamelCase,
7286 window: &mut Window,
7287 cx: &mut Context<Self>,
7288 ) {
7289 self.manipulate_text(window, cx, |text| {
7290 text.split('\n')
7291 .map(|line| line.to_case(Case::UpperCamel))
7292 .join("\n")
7293 })
7294 }
7295
7296 pub fn convert_to_lower_camel_case(
7297 &mut self,
7298 _: &ConvertToLowerCamelCase,
7299 window: &mut Window,
7300 cx: &mut Context<Self>,
7301 ) {
7302 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7303 }
7304
7305 pub fn convert_to_opposite_case(
7306 &mut self,
7307 _: &ConvertToOppositeCase,
7308 window: &mut Window,
7309 cx: &mut Context<Self>,
7310 ) {
7311 self.manipulate_text(window, cx, |text| {
7312 text.chars()
7313 .fold(String::with_capacity(text.len()), |mut t, c| {
7314 if c.is_uppercase() {
7315 t.extend(c.to_lowercase());
7316 } else {
7317 t.extend(c.to_uppercase());
7318 }
7319 t
7320 })
7321 })
7322 }
7323
7324 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7325 where
7326 Fn: FnMut(&str) -> String,
7327 {
7328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7329 let buffer = self.buffer.read(cx).snapshot(cx);
7330
7331 let mut new_selections = Vec::new();
7332 let mut edits = Vec::new();
7333 let mut selection_adjustment = 0i32;
7334
7335 for selection in self.selections.all::<usize>(cx) {
7336 let selection_is_empty = selection.is_empty();
7337
7338 let (start, end) = if selection_is_empty {
7339 let word_range = movement::surrounding_word(
7340 &display_map,
7341 selection.start.to_display_point(&display_map),
7342 );
7343 let start = word_range.start.to_offset(&display_map, Bias::Left);
7344 let end = word_range.end.to_offset(&display_map, Bias::Left);
7345 (start, end)
7346 } else {
7347 (selection.start, selection.end)
7348 };
7349
7350 let text = buffer.text_for_range(start..end).collect::<String>();
7351 let old_length = text.len() as i32;
7352 let text = callback(&text);
7353
7354 new_selections.push(Selection {
7355 start: (start as i32 - selection_adjustment) as usize,
7356 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7357 goal: SelectionGoal::None,
7358 ..selection
7359 });
7360
7361 selection_adjustment += old_length - text.len() as i32;
7362
7363 edits.push((start..end, text));
7364 }
7365
7366 self.transact(window, cx, |this, window, cx| {
7367 this.buffer.update(cx, |buffer, cx| {
7368 buffer.edit(edits, None, cx);
7369 });
7370
7371 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7372 s.select(new_selections);
7373 });
7374
7375 this.request_autoscroll(Autoscroll::fit(), cx);
7376 });
7377 }
7378
7379 pub fn duplicate(
7380 &mut self,
7381 upwards: bool,
7382 whole_lines: bool,
7383 window: &mut Window,
7384 cx: &mut Context<Self>,
7385 ) {
7386 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7387 let buffer = &display_map.buffer_snapshot;
7388 let selections = self.selections.all::<Point>(cx);
7389
7390 let mut edits = Vec::new();
7391 let mut selections_iter = selections.iter().peekable();
7392 while let Some(selection) = selections_iter.next() {
7393 let mut rows = selection.spanned_rows(false, &display_map);
7394 // duplicate line-wise
7395 if whole_lines || selection.start == selection.end {
7396 // Avoid duplicating the same lines twice.
7397 while let Some(next_selection) = selections_iter.peek() {
7398 let next_rows = next_selection.spanned_rows(false, &display_map);
7399 if next_rows.start < rows.end {
7400 rows.end = next_rows.end;
7401 selections_iter.next().unwrap();
7402 } else {
7403 break;
7404 }
7405 }
7406
7407 // Copy the text from the selected row region and splice it either at the start
7408 // or end of the region.
7409 let start = Point::new(rows.start.0, 0);
7410 let end = Point::new(
7411 rows.end.previous_row().0,
7412 buffer.line_len(rows.end.previous_row()),
7413 );
7414 let text = buffer
7415 .text_for_range(start..end)
7416 .chain(Some("\n"))
7417 .collect::<String>();
7418 let insert_location = if upwards {
7419 Point::new(rows.end.0, 0)
7420 } else {
7421 start
7422 };
7423 edits.push((insert_location..insert_location, text));
7424 } else {
7425 // duplicate character-wise
7426 let start = selection.start;
7427 let end = selection.end;
7428 let text = buffer.text_for_range(start..end).collect::<String>();
7429 edits.push((selection.end..selection.end, text));
7430 }
7431 }
7432
7433 self.transact(window, cx, |this, _, cx| {
7434 this.buffer.update(cx, |buffer, cx| {
7435 buffer.edit(edits, None, cx);
7436 });
7437
7438 this.request_autoscroll(Autoscroll::fit(), cx);
7439 });
7440 }
7441
7442 pub fn duplicate_line_up(
7443 &mut self,
7444 _: &DuplicateLineUp,
7445 window: &mut Window,
7446 cx: &mut Context<Self>,
7447 ) {
7448 self.duplicate(true, true, window, cx);
7449 }
7450
7451 pub fn duplicate_line_down(
7452 &mut self,
7453 _: &DuplicateLineDown,
7454 window: &mut Window,
7455 cx: &mut Context<Self>,
7456 ) {
7457 self.duplicate(false, true, window, cx);
7458 }
7459
7460 pub fn duplicate_selection(
7461 &mut self,
7462 _: &DuplicateSelection,
7463 window: &mut Window,
7464 cx: &mut Context<Self>,
7465 ) {
7466 self.duplicate(false, false, window, cx);
7467 }
7468
7469 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7471 let buffer = self.buffer.read(cx).snapshot(cx);
7472
7473 let mut edits = Vec::new();
7474 let mut unfold_ranges = Vec::new();
7475 let mut refold_creases = Vec::new();
7476
7477 let selections = self.selections.all::<Point>(cx);
7478 let mut selections = selections.iter().peekable();
7479 let mut contiguous_row_selections = Vec::new();
7480 let mut new_selections = Vec::new();
7481
7482 while let Some(selection) = selections.next() {
7483 // Find all the selections that span a contiguous row range
7484 let (start_row, end_row) = consume_contiguous_rows(
7485 &mut contiguous_row_selections,
7486 selection,
7487 &display_map,
7488 &mut selections,
7489 );
7490
7491 // Move the text spanned by the row range to be before the line preceding the row range
7492 if start_row.0 > 0 {
7493 let range_to_move = Point::new(
7494 start_row.previous_row().0,
7495 buffer.line_len(start_row.previous_row()),
7496 )
7497 ..Point::new(
7498 end_row.previous_row().0,
7499 buffer.line_len(end_row.previous_row()),
7500 );
7501 let insertion_point = display_map
7502 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7503 .0;
7504
7505 // Don't move lines across excerpts
7506 if buffer
7507 .excerpt_containing(insertion_point..range_to_move.end)
7508 .is_some()
7509 {
7510 let text = buffer
7511 .text_for_range(range_to_move.clone())
7512 .flat_map(|s| s.chars())
7513 .skip(1)
7514 .chain(['\n'])
7515 .collect::<String>();
7516
7517 edits.push((
7518 buffer.anchor_after(range_to_move.start)
7519 ..buffer.anchor_before(range_to_move.end),
7520 String::new(),
7521 ));
7522 let insertion_anchor = buffer.anchor_after(insertion_point);
7523 edits.push((insertion_anchor..insertion_anchor, text));
7524
7525 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7526
7527 // Move selections up
7528 new_selections.extend(contiguous_row_selections.drain(..).map(
7529 |mut selection| {
7530 selection.start.row -= row_delta;
7531 selection.end.row -= row_delta;
7532 selection
7533 },
7534 ));
7535
7536 // Move folds up
7537 unfold_ranges.push(range_to_move.clone());
7538 for fold in display_map.folds_in_range(
7539 buffer.anchor_before(range_to_move.start)
7540 ..buffer.anchor_after(range_to_move.end),
7541 ) {
7542 let mut start = fold.range.start.to_point(&buffer);
7543 let mut end = fold.range.end.to_point(&buffer);
7544 start.row -= row_delta;
7545 end.row -= row_delta;
7546 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7547 }
7548 }
7549 }
7550
7551 // If we didn't move line(s), preserve the existing selections
7552 new_selections.append(&mut contiguous_row_selections);
7553 }
7554
7555 self.transact(window, cx, |this, window, cx| {
7556 this.unfold_ranges(&unfold_ranges, true, true, cx);
7557 this.buffer.update(cx, |buffer, cx| {
7558 for (range, text) in edits {
7559 buffer.edit([(range, text)], None, cx);
7560 }
7561 });
7562 this.fold_creases(refold_creases, true, window, cx);
7563 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7564 s.select(new_selections);
7565 })
7566 });
7567 }
7568
7569 pub fn move_line_down(
7570 &mut self,
7571 _: &MoveLineDown,
7572 window: &mut Window,
7573 cx: &mut Context<Self>,
7574 ) {
7575 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7576 let buffer = self.buffer.read(cx).snapshot(cx);
7577
7578 let mut edits = Vec::new();
7579 let mut unfold_ranges = Vec::new();
7580 let mut refold_creases = Vec::new();
7581
7582 let selections = self.selections.all::<Point>(cx);
7583 let mut selections = selections.iter().peekable();
7584 let mut contiguous_row_selections = Vec::new();
7585 let mut new_selections = Vec::new();
7586
7587 while let Some(selection) = selections.next() {
7588 // Find all the selections that span a contiguous row range
7589 let (start_row, end_row) = consume_contiguous_rows(
7590 &mut contiguous_row_selections,
7591 selection,
7592 &display_map,
7593 &mut selections,
7594 );
7595
7596 // Move the text spanned by the row range to be after the last line of the row range
7597 if end_row.0 <= buffer.max_point().row {
7598 let range_to_move =
7599 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7600 let insertion_point = display_map
7601 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7602 .0;
7603
7604 // Don't move lines across excerpt boundaries
7605 if buffer
7606 .excerpt_containing(range_to_move.start..insertion_point)
7607 .is_some()
7608 {
7609 let mut text = String::from("\n");
7610 text.extend(buffer.text_for_range(range_to_move.clone()));
7611 text.pop(); // Drop trailing newline
7612 edits.push((
7613 buffer.anchor_after(range_to_move.start)
7614 ..buffer.anchor_before(range_to_move.end),
7615 String::new(),
7616 ));
7617 let insertion_anchor = buffer.anchor_after(insertion_point);
7618 edits.push((insertion_anchor..insertion_anchor, text));
7619
7620 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7621
7622 // Move selections down
7623 new_selections.extend(contiguous_row_selections.drain(..).map(
7624 |mut selection| {
7625 selection.start.row += row_delta;
7626 selection.end.row += row_delta;
7627 selection
7628 },
7629 ));
7630
7631 // Move folds down
7632 unfold_ranges.push(range_to_move.clone());
7633 for fold in display_map.folds_in_range(
7634 buffer.anchor_before(range_to_move.start)
7635 ..buffer.anchor_after(range_to_move.end),
7636 ) {
7637 let mut start = fold.range.start.to_point(&buffer);
7638 let mut end = fold.range.end.to_point(&buffer);
7639 start.row += row_delta;
7640 end.row += row_delta;
7641 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7642 }
7643 }
7644 }
7645
7646 // If we didn't move line(s), preserve the existing selections
7647 new_selections.append(&mut contiguous_row_selections);
7648 }
7649
7650 self.transact(window, cx, |this, window, cx| {
7651 this.unfold_ranges(&unfold_ranges, true, true, cx);
7652 this.buffer.update(cx, |buffer, cx| {
7653 for (range, text) in edits {
7654 buffer.edit([(range, text)], None, cx);
7655 }
7656 });
7657 this.fold_creases(refold_creases, true, window, cx);
7658 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7659 s.select(new_selections)
7660 });
7661 });
7662 }
7663
7664 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7665 let text_layout_details = &self.text_layout_details(window);
7666 self.transact(window, cx, |this, window, cx| {
7667 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7668 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7669 let line_mode = s.line_mode;
7670 s.move_with(|display_map, selection| {
7671 if !selection.is_empty() || line_mode {
7672 return;
7673 }
7674
7675 let mut head = selection.head();
7676 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7677 if head.column() == display_map.line_len(head.row()) {
7678 transpose_offset = display_map
7679 .buffer_snapshot
7680 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7681 }
7682
7683 if transpose_offset == 0 {
7684 return;
7685 }
7686
7687 *head.column_mut() += 1;
7688 head = display_map.clip_point(head, Bias::Right);
7689 let goal = SelectionGoal::HorizontalPosition(
7690 display_map
7691 .x_for_display_point(head, text_layout_details)
7692 .into(),
7693 );
7694 selection.collapse_to(head, goal);
7695
7696 let transpose_start = display_map
7697 .buffer_snapshot
7698 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7699 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7700 let transpose_end = display_map
7701 .buffer_snapshot
7702 .clip_offset(transpose_offset + 1, Bias::Right);
7703 if let Some(ch) =
7704 display_map.buffer_snapshot.chars_at(transpose_start).next()
7705 {
7706 edits.push((transpose_start..transpose_offset, String::new()));
7707 edits.push((transpose_end..transpose_end, ch.to_string()));
7708 }
7709 }
7710 });
7711 edits
7712 });
7713 this.buffer
7714 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7715 let selections = this.selections.all::<usize>(cx);
7716 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7717 s.select(selections);
7718 });
7719 });
7720 }
7721
7722 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7723 self.rewrap_impl(IsVimMode::No, cx)
7724 }
7725
7726 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7727 let buffer = self.buffer.read(cx).snapshot(cx);
7728 let selections = self.selections.all::<Point>(cx);
7729 let mut selections = selections.iter().peekable();
7730
7731 let mut edits = Vec::new();
7732 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7733
7734 while let Some(selection) = selections.next() {
7735 let mut start_row = selection.start.row;
7736 let mut end_row = selection.end.row;
7737
7738 // Skip selections that overlap with a range that has already been rewrapped.
7739 let selection_range = start_row..end_row;
7740 if rewrapped_row_ranges
7741 .iter()
7742 .any(|range| range.overlaps(&selection_range))
7743 {
7744 continue;
7745 }
7746
7747 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7748
7749 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7750 match language_scope.language_name().as_ref() {
7751 "Markdown" | "Plain Text" => {
7752 should_rewrap = true;
7753 }
7754 _ => {}
7755 }
7756 }
7757
7758 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7759
7760 // Since not all lines in the selection may be at the same indent
7761 // level, choose the indent size that is the most common between all
7762 // of the lines.
7763 //
7764 // If there is a tie, we use the deepest indent.
7765 let (indent_size, indent_end) = {
7766 let mut indent_size_occurrences = HashMap::default();
7767 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7768
7769 for row in start_row..=end_row {
7770 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7771 rows_by_indent_size.entry(indent).or_default().push(row);
7772 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7773 }
7774
7775 let indent_size = indent_size_occurrences
7776 .into_iter()
7777 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7778 .map(|(indent, _)| indent)
7779 .unwrap_or_default();
7780 let row = rows_by_indent_size[&indent_size][0];
7781 let indent_end = Point::new(row, indent_size.len);
7782
7783 (indent_size, indent_end)
7784 };
7785
7786 let mut line_prefix = indent_size.chars().collect::<String>();
7787
7788 if let Some(comment_prefix) =
7789 buffer
7790 .language_scope_at(selection.head())
7791 .and_then(|language| {
7792 language
7793 .line_comment_prefixes()
7794 .iter()
7795 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7796 .cloned()
7797 })
7798 {
7799 line_prefix.push_str(&comment_prefix);
7800 should_rewrap = true;
7801 }
7802
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_removed();
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}