1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
84 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Entity, EntityInputHandler,
85 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
86 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
87 ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
88 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
89 WeakEntity, WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{
101 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
102 },
103 point_from_lsp, text_diff_with_options, AutoindentMode, BracketPair, Buffer, Capability,
104 CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState, EditPredictionsMode,
105 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
106 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
107};
108use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
109use linked_editing_ranges::refresh_linked_ranges;
110use mouse_context_menu::MouseContextMenu;
111use persistence::DB;
112pub use proposed_changes_editor::{
113 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
114};
115use std::iter::Peekable;
116use task::{ResolvedTask, TaskTemplate, TaskVariables};
117
118use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
119pub use lsp::CompletionContext;
120use lsp::{
121 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
122 LanguageServerId, LanguageServerName,
123};
124
125use language::BufferSnapshot;
126use movement::TextLayoutDetails;
127pub use multi_buffer::{
128 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
129 ToOffset, ToPoint,
130};
131use multi_buffer::{
132 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
133 ToOffsetUtf16,
134};
135use project::{
136 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
137 project_settings::{GitGutterSetting, ProjectSettings},
138 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
139 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
140};
141use rand::prelude::*;
142use rpc::{proto::*, ErrorExt};
143use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
144use selections_collection::{
145 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
146};
147use serde::{Deserialize, Serialize};
148use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
149use smallvec::SmallVec;
150use snippet::Snippet;
151use std::{
152 any::TypeId,
153 borrow::Cow,
154 cell::RefCell,
155 cmp::{self, Ordering, Reverse},
156 mem,
157 num::NonZeroU32,
158 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
159 path::{Path, PathBuf},
160 rc::Rc,
161 sync::Arc,
162 time::{Duration, Instant},
163};
164pub use sum_tree::Bias;
165use sum_tree::TreeMap;
166use text::{BufferId, OffsetUtf16, Rope};
167use theme::{
168 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
169 ThemeColors, ThemeSettings,
170};
171use ui::{
172 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
173 Tooltip,
174};
175use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
176use workspace::{
177 item::{ItemHandle, PreviewTabsSettings},
178 ItemId, RestoreOnStartupBehavior,
179};
180use workspace::{
181 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
182 WorkspaceSettings,
183};
184use workspace::{
185 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
186};
187use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
188
189use crate::hover_links::{find_url, find_url_from_range};
190use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
191
192pub const FILE_HEADER_HEIGHT: u32 = 2;
193pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
194pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
195pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
196const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
197const MAX_LINE_LEN: usize = 1024;
198const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
199const MAX_SELECTION_HISTORY_LEN: usize = 1024;
200pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
201#[doc(hidden)]
202pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
203
204pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
205pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
206
207pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
208pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
209
210const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
211 alt: true,
212 shift: true,
213 control: false,
214 platform: false,
215 function: false,
216};
217
218#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
219pub enum InlayId {
220 InlineCompletion(usize),
221 Hint(usize),
222}
223
224impl InlayId {
225 fn id(&self) -> usize {
226 match self {
227 Self::InlineCompletion(id) => *id,
228 Self::Hint(id) => *id,
229 }
230 }
231}
232
233enum DocumentHighlightRead {}
234enum DocumentHighlightWrite {}
235enum InputComposition {}
236enum SelectedTextHighlight {}
237
238#[derive(Debug, Copy, Clone, PartialEq, Eq)]
239pub enum Navigated {
240 Yes,
241 No,
242}
243
244impl Navigated {
245 pub fn from_bool(yes: bool) -> Navigated {
246 if yes {
247 Navigated::Yes
248 } else {
249 Navigated::No
250 }
251 }
252}
253
254pub fn init_settings(cx: &mut App) {
255 EditorSettings::register(cx);
256}
257
258pub fn init(cx: &mut App) {
259 init_settings(cx);
260
261 workspace::register_project_item::<Editor>(cx);
262 workspace::FollowableViewRegistry::register::<Editor>(cx);
263 workspace::register_serializable_item::<Editor>(cx);
264
265 cx.observe_new(
266 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
267 workspace.register_action(Editor::new_file);
268 workspace.register_action(Editor::new_file_vertical);
269 workspace.register_action(Editor::new_file_horizontal);
270 workspace.register_action(Editor::cancel_language_server_work);
271 },
272 )
273 .detach();
274
275 cx.on_action(move |_: &workspace::NewFile, cx| {
276 let app_state = workspace::AppState::global(cx);
277 if let Some(app_state) = app_state.upgrade() {
278 workspace::open_new(
279 Default::default(),
280 app_state,
281 cx,
282 |workspace, window, cx| {
283 Editor::new_file(workspace, &Default::default(), window, cx)
284 },
285 )
286 .detach();
287 }
288 });
289 cx.on_action(move |_: &workspace::NewWindow, cx| {
290 let app_state = workspace::AppState::global(cx);
291 if let Some(app_state) = app_state.upgrade() {
292 workspace::open_new(
293 Default::default(),
294 app_state,
295 cx,
296 |workspace, window, cx| {
297 cx.activate(true);
298 Editor::new_file(workspace, &Default::default(), window, cx)
299 },
300 )
301 .detach();
302 }
303 });
304}
305
306pub struct SearchWithinRange;
307
308trait InvalidationRegion {
309 fn ranges(&self) -> &[Range<Anchor>];
310}
311
312#[derive(Clone, Debug, PartialEq)]
313pub enum SelectPhase {
314 Begin {
315 position: DisplayPoint,
316 add: bool,
317 click_count: usize,
318 },
319 BeginColumnar {
320 position: DisplayPoint,
321 reset: bool,
322 goal_column: u32,
323 },
324 Extend {
325 position: DisplayPoint,
326 click_count: usize,
327 },
328 Update {
329 position: DisplayPoint,
330 goal_column: u32,
331 scroll_delta: gpui::Point<f32>,
332 },
333 End,
334}
335
336#[derive(Clone, Debug)]
337pub enum SelectMode {
338 Character,
339 Word(Range<Anchor>),
340 Line(Range<Anchor>),
341 All,
342}
343
344#[derive(Copy, Clone, PartialEq, Eq, Debug)]
345pub enum EditorMode {
346 SingleLine { auto_width: bool },
347 AutoHeight { max_lines: usize },
348 Full,
349}
350
351#[derive(Copy, Clone, Debug)]
352pub enum SoftWrap {
353 /// Prefer not to wrap at all.
354 ///
355 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
356 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
357 GitDiff,
358 /// Prefer a single line generally, unless an overly long line is encountered.
359 None,
360 /// Soft wrap lines that exceed the editor width.
361 EditorWidth,
362 /// Soft wrap lines at the preferred line length.
363 Column(u32),
364 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
365 Bounded(u32),
366}
367
368#[derive(Clone)]
369pub struct EditorStyle {
370 pub background: Hsla,
371 pub local_player: PlayerColor,
372 pub text: TextStyle,
373 pub scrollbar_width: Pixels,
374 pub syntax: Arc<SyntaxTheme>,
375 pub status: StatusColors,
376 pub inlay_hints_style: HighlightStyle,
377 pub inline_completion_styles: InlineCompletionStyles,
378 pub unnecessary_code_fade: f32,
379}
380
381impl Default for EditorStyle {
382 fn default() -> Self {
383 Self {
384 background: Hsla::default(),
385 local_player: PlayerColor::default(),
386 text: TextStyle::default(),
387 scrollbar_width: Pixels::default(),
388 syntax: Default::default(),
389 // HACK: Status colors don't have a real default.
390 // We should look into removing the status colors from the editor
391 // style and retrieve them directly from the theme.
392 status: StatusColors::dark(),
393 inlay_hints_style: HighlightStyle::default(),
394 inline_completion_styles: InlineCompletionStyles {
395 insertion: HighlightStyle::default(),
396 whitespace: HighlightStyle::default(),
397 },
398 unnecessary_code_fade: Default::default(),
399 }
400 }
401}
402
403pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
404 let show_background = language_settings::language_settings(None, None, cx)
405 .inlay_hints
406 .show_background;
407
408 HighlightStyle {
409 color: Some(cx.theme().status().hint),
410 background_color: show_background.then(|| cx.theme().status().hint_background),
411 ..HighlightStyle::default()
412 }
413}
414
415pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
416 InlineCompletionStyles {
417 insertion: HighlightStyle {
418 color: Some(cx.theme().status().predictive),
419 ..HighlightStyle::default()
420 },
421 whitespace: HighlightStyle {
422 background_color: Some(cx.theme().status().created_background),
423 ..HighlightStyle::default()
424 },
425 }
426}
427
428type CompletionId = usize;
429
430pub(crate) enum EditDisplayMode {
431 TabAccept,
432 DiffPopover,
433 Inline,
434}
435
436enum InlineCompletion {
437 Edit {
438 edits: Vec<(Range<Anchor>, String)>,
439 edit_preview: Option<EditPreview>,
440 display_mode: EditDisplayMode,
441 snapshot: BufferSnapshot,
442 },
443 Move {
444 target: Anchor,
445 snapshot: BufferSnapshot,
446 },
447}
448
449struct InlineCompletionState {
450 inlay_ids: Vec<InlayId>,
451 completion: InlineCompletion,
452 completion_id: Option<SharedString>,
453 invalidation_range: Range<Anchor>,
454}
455
456enum EditPredictionSettings {
457 Disabled,
458 Enabled {
459 show_in_menu: bool,
460 preview_requires_modifier: bool,
461 },
462}
463
464enum InlineCompletionHighlight {}
465
466pub enum MenuInlineCompletionsPolicy {
467 Never,
468 ByProvider,
469}
470
471pub enum EditPredictionPreview {
472 /// Modifier is not pressed
473 Inactive,
474 /// Modifier pressed
475 Active {
476 previous_scroll_position: Option<ScrollAnchor>,
477 },
478}
479
480#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
481struct EditorActionId(usize);
482
483impl EditorActionId {
484 pub fn post_inc(&mut self) -> Self {
485 let answer = self.0;
486
487 *self = Self(answer + 1);
488
489 Self(answer)
490 }
491}
492
493// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
494// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
495
496type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
497type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
498
499#[derive(Default)]
500struct ScrollbarMarkerState {
501 scrollbar_size: Size<Pixels>,
502 dirty: bool,
503 markers: Arc<[PaintQuad]>,
504 pending_refresh: Option<Task<Result<()>>>,
505}
506
507impl ScrollbarMarkerState {
508 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
509 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
510 }
511}
512
513#[derive(Clone, Debug)]
514struct RunnableTasks {
515 templates: Vec<(TaskSourceKind, TaskTemplate)>,
516 offset: MultiBufferOffset,
517 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
518 column: u32,
519 // Values of all named captures, including those starting with '_'
520 extra_variables: HashMap<String, String>,
521 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
522 context_range: Range<BufferOffset>,
523}
524
525impl RunnableTasks {
526 fn resolve<'a>(
527 &'a self,
528 cx: &'a task::TaskContext,
529 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
530 self.templates.iter().filter_map(|(kind, template)| {
531 template
532 .resolve_task(&kind.to_id_base(), cx)
533 .map(|task| (kind.clone(), task))
534 })
535 }
536}
537
538#[derive(Clone)]
539struct ResolvedTasks {
540 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
541 position: Anchor,
542}
543#[derive(Copy, Clone, Debug)]
544struct MultiBufferOffset(usize);
545#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
546struct BufferOffset(usize);
547
548// Addons allow storing per-editor state in other crates (e.g. Vim)
549pub trait Addon: 'static {
550 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
551
552 fn render_buffer_header_controls(
553 &self,
554 _: &ExcerptInfo,
555 _: &Window,
556 _: &App,
557 ) -> Option<AnyElement> {
558 None
559 }
560
561 fn to_any(&self) -> &dyn std::any::Any;
562}
563
564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
565pub enum IsVimMode {
566 Yes,
567 No,
568}
569
570/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
571///
572/// See the [module level documentation](self) for more information.
573pub struct Editor {
574 focus_handle: FocusHandle,
575 last_focused_descendant: Option<WeakFocusHandle>,
576 /// The text buffer being edited
577 buffer: Entity<MultiBuffer>,
578 /// Map of how text in the buffer should be displayed.
579 /// Handles soft wraps, folds, fake inlay text insertions, etc.
580 pub display_map: Entity<DisplayMap>,
581 pub selections: SelectionsCollection,
582 pub scroll_manager: ScrollManager,
583 /// When inline assist editors are linked, they all render cursors because
584 /// typing enters text into each of them, even the ones that aren't focused.
585 pub(crate) show_cursor_when_unfocused: bool,
586 columnar_selection_tail: Option<Anchor>,
587 add_selections_state: Option<AddSelectionsState>,
588 select_next_state: Option<SelectNextState>,
589 select_prev_state: Option<SelectNextState>,
590 selection_history: SelectionHistory,
591 autoclose_regions: Vec<AutocloseRegion>,
592 snippet_stack: InvalidationStack<SnippetState>,
593 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
594 ime_transaction: Option<TransactionId>,
595 active_diagnostics: Option<ActiveDiagnosticGroup>,
596 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
597
598 // TODO: make this a access method
599 pub project: Option<Entity<Project>>,
600 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
601 completion_provider: Option<Box<dyn CompletionProvider>>,
602 collaboration_hub: Option<Box<dyn CollaborationHub>>,
603 blink_manager: Entity<BlinkManager>,
604 show_cursor_names: bool,
605 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
606 pub show_local_selections: bool,
607 mode: EditorMode,
608 show_breadcrumbs: bool,
609 show_gutter: bool,
610 show_scrollbars: bool,
611 show_line_numbers: Option<bool>,
612 use_relative_line_numbers: Option<bool>,
613 show_git_diff_gutter: Option<bool>,
614 show_code_actions: Option<bool>,
615 show_runnables: Option<bool>,
616 show_wrap_guides: Option<bool>,
617 show_indent_guides: Option<bool>,
618 placeholder_text: Option<Arc<str>>,
619 highlight_order: usize,
620 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
621 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
622 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
623 scrollbar_marker_state: ScrollbarMarkerState,
624 active_indent_guides_state: ActiveIndentGuidesState,
625 nav_history: Option<ItemNavHistory>,
626 context_menu: RefCell<Option<CodeContextMenu>>,
627 mouse_context_menu: Option<MouseContextMenu>,
628 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
629 signature_help_state: SignatureHelpState,
630 auto_signature_help: Option<bool>,
631 find_all_references_task_sources: Vec<Anchor>,
632 next_completion_id: CompletionId,
633 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
634 code_actions_task: Option<Task<Result<()>>>,
635 selection_highlight_task: Option<Task<()>>,
636 document_highlights_task: Option<Task<()>>,
637 linked_editing_range_task: Option<Task<Option<()>>>,
638 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
639 pending_rename: Option<RenameState>,
640 searchable: bool,
641 cursor_shape: CursorShape,
642 current_line_highlight: Option<CurrentLineHighlight>,
643 collapse_matches: bool,
644 autoindent_mode: Option<AutoindentMode>,
645 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
646 input_enabled: bool,
647 use_modal_editing: bool,
648 read_only: bool,
649 leader_peer_id: Option<PeerId>,
650 remote_id: Option<ViewId>,
651 hover_state: HoverState,
652 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
653 gutter_hovered: bool,
654 hovered_link_state: Option<HoveredLinkState>,
655 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
656 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
657 active_inline_completion: Option<InlineCompletionState>,
658 /// Used to prevent flickering as the user types while the menu is open
659 stale_inline_completion_in_menu: Option<InlineCompletionState>,
660 edit_prediction_settings: EditPredictionSettings,
661 inline_completions_hidden_for_vim_mode: bool,
662 show_inline_completions_override: Option<bool>,
663 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
664 edit_prediction_preview: EditPredictionPreview,
665 edit_prediction_cursor_on_leading_whitespace: bool,
666 edit_prediction_requires_modifier_in_leading_space: bool,
667 inlay_hint_cache: InlayHintCache,
668 next_inlay_id: usize,
669 _subscriptions: Vec<Subscription>,
670 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
671 gutter_dimensions: GutterDimensions,
672 style: Option<EditorStyle>,
673 text_style_refinement: Option<TextStyleRefinement>,
674 next_editor_action_id: EditorActionId,
675 editor_actions:
676 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
677 use_autoclose: bool,
678 use_auto_surround: bool,
679 auto_replace_emoji_shortcode: bool,
680 show_git_blame_gutter: bool,
681 show_git_blame_inline: bool,
682 show_git_blame_inline_delay_task: Option<Task<()>>,
683 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
684 distinguish_unstaged_diff_hunks: bool,
685 git_blame_inline_enabled: bool,
686 serialize_dirty_buffers: bool,
687 show_selection_menu: Option<bool>,
688 blame: Option<Entity<GitBlame>>,
689 blame_subscription: Option<Subscription>,
690 custom_context_menu: Option<
691 Box<
692 dyn 'static
693 + Fn(
694 &mut Self,
695 DisplayPoint,
696 &mut Window,
697 &mut Context<Self>,
698 ) -> Option<Entity<ui::ContextMenu>>,
699 >,
700 >,
701 last_bounds: Option<Bounds<Pixels>>,
702 last_position_map: Option<Rc<PositionMap>>,
703 expect_bounds_change: Option<Bounds<Pixels>>,
704 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
705 tasks_update_task: Option<Task<()>>,
706 in_project_search: bool,
707 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
708 breadcrumb_header: Option<String>,
709 focused_block: Option<FocusedBlock>,
710 next_scroll_position: NextScrollCursorCenterTopBottom,
711 addons: HashMap<TypeId, Box<dyn Addon>>,
712 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
713 load_diff_task: Option<Shared<Task<()>>>,
714 selection_mark_mode: bool,
715 toggle_fold_multiple_buffers: Task<()>,
716 _scroll_cursor_center_top_bottom_task: Task<()>,
717 serialize_selections: Task<()>,
718}
719
720#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
721enum NextScrollCursorCenterTopBottom {
722 #[default]
723 Center,
724 Top,
725 Bottom,
726}
727
728impl NextScrollCursorCenterTopBottom {
729 fn next(&self) -> Self {
730 match self {
731 Self::Center => Self::Top,
732 Self::Top => Self::Bottom,
733 Self::Bottom => Self::Center,
734 }
735 }
736}
737
738#[derive(Clone)]
739pub struct EditorSnapshot {
740 pub mode: EditorMode,
741 show_gutter: bool,
742 show_line_numbers: Option<bool>,
743 show_git_diff_gutter: Option<bool>,
744 show_code_actions: Option<bool>,
745 show_runnables: Option<bool>,
746 git_blame_gutter_max_author_length: Option<usize>,
747 pub display_snapshot: DisplaySnapshot,
748 pub placeholder_text: Option<Arc<str>>,
749 is_focused: bool,
750 scroll_anchor: ScrollAnchor,
751 ongoing_scroll: OngoingScroll,
752 current_line_highlight: CurrentLineHighlight,
753 gutter_hovered: bool,
754}
755
756const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
757
758#[derive(Default, Debug, Clone, Copy)]
759pub struct GutterDimensions {
760 pub left_padding: Pixels,
761 pub right_padding: Pixels,
762 pub width: Pixels,
763 pub margin: Pixels,
764 pub git_blame_entries_width: Option<Pixels>,
765}
766
767impl GutterDimensions {
768 /// The full width of the space taken up by the gutter.
769 pub fn full_width(&self) -> Pixels {
770 self.margin + self.width
771 }
772
773 /// The width of the space reserved for the fold indicators,
774 /// use alongside 'justify_end' and `gutter_width` to
775 /// right align content with the line numbers
776 pub fn fold_area_width(&self) -> Pixels {
777 self.margin + self.right_padding
778 }
779}
780
781#[derive(Debug)]
782pub struct RemoteSelection {
783 pub replica_id: ReplicaId,
784 pub selection: Selection<Anchor>,
785 pub cursor_shape: CursorShape,
786 pub peer_id: PeerId,
787 pub line_mode: bool,
788 pub participant_index: Option<ParticipantIndex>,
789 pub user_name: Option<SharedString>,
790}
791
792#[derive(Clone, Debug)]
793struct SelectionHistoryEntry {
794 selections: Arc<[Selection<Anchor>]>,
795 select_next_state: Option<SelectNextState>,
796 select_prev_state: Option<SelectNextState>,
797 add_selections_state: Option<AddSelectionsState>,
798}
799
800enum SelectionHistoryMode {
801 Normal,
802 Undoing,
803 Redoing,
804}
805
806#[derive(Clone, PartialEq, Eq, Hash)]
807struct HoveredCursor {
808 replica_id: u16,
809 selection_id: usize,
810}
811
812impl Default for SelectionHistoryMode {
813 fn default() -> Self {
814 Self::Normal
815 }
816}
817
818#[derive(Default)]
819struct SelectionHistory {
820 #[allow(clippy::type_complexity)]
821 selections_by_transaction:
822 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
823 mode: SelectionHistoryMode,
824 undo_stack: VecDeque<SelectionHistoryEntry>,
825 redo_stack: VecDeque<SelectionHistoryEntry>,
826}
827
828impl SelectionHistory {
829 fn insert_transaction(
830 &mut self,
831 transaction_id: TransactionId,
832 selections: Arc<[Selection<Anchor>]>,
833 ) {
834 self.selections_by_transaction
835 .insert(transaction_id, (selections, None));
836 }
837
838 #[allow(clippy::type_complexity)]
839 fn transaction(
840 &self,
841 transaction_id: TransactionId,
842 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
843 self.selections_by_transaction.get(&transaction_id)
844 }
845
846 #[allow(clippy::type_complexity)]
847 fn transaction_mut(
848 &mut self,
849 transaction_id: TransactionId,
850 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
851 self.selections_by_transaction.get_mut(&transaction_id)
852 }
853
854 fn push(&mut self, entry: SelectionHistoryEntry) {
855 if !entry.selections.is_empty() {
856 match self.mode {
857 SelectionHistoryMode::Normal => {
858 self.push_undo(entry);
859 self.redo_stack.clear();
860 }
861 SelectionHistoryMode::Undoing => self.push_redo(entry),
862 SelectionHistoryMode::Redoing => self.push_undo(entry),
863 }
864 }
865 }
866
867 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
868 if self
869 .undo_stack
870 .back()
871 .map_or(true, |e| e.selections != entry.selections)
872 {
873 self.undo_stack.push_back(entry);
874 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
875 self.undo_stack.pop_front();
876 }
877 }
878 }
879
880 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
881 if self
882 .redo_stack
883 .back()
884 .map_or(true, |e| e.selections != entry.selections)
885 {
886 self.redo_stack.push_back(entry);
887 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
888 self.redo_stack.pop_front();
889 }
890 }
891 }
892}
893
894struct RowHighlight {
895 index: usize,
896 range: Range<Anchor>,
897 color: Hsla,
898 should_autoscroll: bool,
899}
900
901#[derive(Clone, Debug)]
902struct AddSelectionsState {
903 above: bool,
904 stack: Vec<usize>,
905}
906
907#[derive(Clone)]
908struct SelectNextState {
909 query: AhoCorasick,
910 wordwise: bool,
911 done: bool,
912}
913
914impl std::fmt::Debug for SelectNextState {
915 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
916 f.debug_struct(std::any::type_name::<Self>())
917 .field("wordwise", &self.wordwise)
918 .field("done", &self.done)
919 .finish()
920 }
921}
922
923#[derive(Debug)]
924struct AutocloseRegion {
925 selection_id: usize,
926 range: Range<Anchor>,
927 pair: BracketPair,
928}
929
930#[derive(Debug)]
931struct SnippetState {
932 ranges: Vec<Vec<Range<Anchor>>>,
933 active_index: usize,
934 choices: Vec<Option<Vec<String>>>,
935}
936
937#[doc(hidden)]
938pub struct RenameState {
939 pub range: Range<Anchor>,
940 pub old_name: Arc<str>,
941 pub editor: Entity<Editor>,
942 block_id: CustomBlockId,
943}
944
945struct InvalidationStack<T>(Vec<T>);
946
947struct RegisteredInlineCompletionProvider {
948 provider: Arc<dyn InlineCompletionProviderHandle>,
949 _subscription: Subscription,
950}
951
952#[derive(Debug)]
953struct ActiveDiagnosticGroup {
954 primary_range: Range<Anchor>,
955 primary_message: String,
956 group_id: usize,
957 blocks: HashMap<CustomBlockId, Diagnostic>,
958 is_valid: bool,
959}
960
961#[derive(Serialize, Deserialize, Clone, Debug)]
962pub struct ClipboardSelection {
963 pub len: usize,
964 pub is_entire_line: bool,
965 pub first_line_indent: u32,
966}
967
968#[derive(Debug)]
969pub(crate) struct NavigationData {
970 cursor_anchor: Anchor,
971 cursor_position: Point,
972 scroll_anchor: ScrollAnchor,
973 scroll_top_row: u32,
974}
975
976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
977pub enum GotoDefinitionKind {
978 Symbol,
979 Declaration,
980 Type,
981 Implementation,
982}
983
984#[derive(Debug, Clone)]
985enum InlayHintRefreshReason {
986 Toggle(bool),
987 SettingsChange(InlayHintSettings),
988 NewLinesShown,
989 BufferEdited(HashSet<Arc<Language>>),
990 RefreshRequested,
991 ExcerptsRemoved(Vec<ExcerptId>),
992}
993
994impl InlayHintRefreshReason {
995 fn description(&self) -> &'static str {
996 match self {
997 Self::Toggle(_) => "toggle",
998 Self::SettingsChange(_) => "settings change",
999 Self::NewLinesShown => "new lines shown",
1000 Self::BufferEdited(_) => "buffer edited",
1001 Self::RefreshRequested => "refresh requested",
1002 Self::ExcerptsRemoved(_) => "excerpts removed",
1003 }
1004 }
1005}
1006
1007pub enum FormatTarget {
1008 Buffers,
1009 Ranges(Vec<Range<MultiBufferPoint>>),
1010}
1011
1012pub(crate) struct FocusedBlock {
1013 id: BlockId,
1014 focus_handle: WeakFocusHandle,
1015}
1016
1017#[derive(Clone)]
1018enum JumpData {
1019 MultiBufferRow {
1020 row: MultiBufferRow,
1021 line_offset_from_top: u32,
1022 },
1023 MultiBufferPoint {
1024 excerpt_id: ExcerptId,
1025 position: Point,
1026 anchor: text::Anchor,
1027 line_offset_from_top: u32,
1028 },
1029}
1030
1031pub enum MultibufferSelectionMode {
1032 First,
1033 All,
1034}
1035
1036impl Editor {
1037 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1038 let buffer = cx.new(|cx| Buffer::local("", cx));
1039 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1040 Self::new(
1041 EditorMode::SingleLine { auto_width: false },
1042 buffer,
1043 None,
1044 false,
1045 window,
1046 cx,
1047 )
1048 }
1049
1050 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1051 let buffer = cx.new(|cx| Buffer::local("", cx));
1052 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1053 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1054 }
1055
1056 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1057 let buffer = cx.new(|cx| Buffer::local("", cx));
1058 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1059 Self::new(
1060 EditorMode::SingleLine { auto_width: true },
1061 buffer,
1062 None,
1063 false,
1064 window,
1065 cx,
1066 )
1067 }
1068
1069 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1070 let buffer = cx.new(|cx| Buffer::local("", cx));
1071 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1072 Self::new(
1073 EditorMode::AutoHeight { max_lines },
1074 buffer,
1075 None,
1076 false,
1077 window,
1078 cx,
1079 )
1080 }
1081
1082 pub fn for_buffer(
1083 buffer: Entity<Buffer>,
1084 project: Option<Entity<Project>>,
1085 window: &mut Window,
1086 cx: &mut Context<Self>,
1087 ) -> Self {
1088 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1089 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1090 }
1091
1092 pub fn for_multibuffer(
1093 buffer: Entity<MultiBuffer>,
1094 project: Option<Entity<Project>>,
1095 show_excerpt_controls: bool,
1096 window: &mut Window,
1097 cx: &mut Context<Self>,
1098 ) -> Self {
1099 Self::new(
1100 EditorMode::Full,
1101 buffer,
1102 project,
1103 show_excerpt_controls,
1104 window,
1105 cx,
1106 )
1107 }
1108
1109 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1110 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1111 let mut clone = Self::new(
1112 self.mode,
1113 self.buffer.clone(),
1114 self.project.clone(),
1115 show_excerpt_controls,
1116 window,
1117 cx,
1118 );
1119 self.display_map.update(cx, |display_map, cx| {
1120 let snapshot = display_map.snapshot(cx);
1121 clone.display_map.update(cx, |display_map, cx| {
1122 display_map.set_state(&snapshot, cx);
1123 });
1124 });
1125 clone.selections.clone_state(&self.selections);
1126 clone.scroll_manager.clone_state(&self.scroll_manager);
1127 clone.searchable = self.searchable;
1128 clone
1129 }
1130
1131 pub fn new(
1132 mode: EditorMode,
1133 buffer: Entity<MultiBuffer>,
1134 project: Option<Entity<Project>>,
1135 show_excerpt_controls: bool,
1136 window: &mut Window,
1137 cx: &mut Context<Self>,
1138 ) -> Self {
1139 let style = window.text_style();
1140 let font_size = style.font_size.to_pixels(window.rem_size());
1141 let editor = cx.entity().downgrade();
1142 let fold_placeholder = FoldPlaceholder {
1143 constrain_width: true,
1144 render: Arc::new(move |fold_id, fold_range, _, cx| {
1145 let editor = editor.clone();
1146 div()
1147 .id(fold_id)
1148 .bg(cx.theme().colors().ghost_element_background)
1149 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1150 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1151 .rounded_sm()
1152 .size_full()
1153 .cursor_pointer()
1154 .child("⋯")
1155 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1156 .on_click(move |_, _window, cx| {
1157 editor
1158 .update(cx, |editor, cx| {
1159 editor.unfold_ranges(
1160 &[fold_range.start..fold_range.end],
1161 true,
1162 false,
1163 cx,
1164 );
1165 cx.stop_propagation();
1166 })
1167 .ok();
1168 })
1169 .into_any()
1170 }),
1171 merge_adjacent: true,
1172 ..Default::default()
1173 };
1174 let display_map = cx.new(|cx| {
1175 DisplayMap::new(
1176 buffer.clone(),
1177 style.font(),
1178 font_size,
1179 None,
1180 show_excerpt_controls,
1181 FILE_HEADER_HEIGHT,
1182 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1183 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1184 fold_placeholder,
1185 cx,
1186 )
1187 });
1188
1189 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1190
1191 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1192
1193 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1194 .then(|| language_settings::SoftWrap::None);
1195
1196 let mut project_subscriptions = Vec::new();
1197 if mode == EditorMode::Full {
1198 if let Some(project) = project.as_ref() {
1199 if buffer.read(cx).is_singleton() {
1200 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1201 cx.emit(EditorEvent::TitleChanged);
1202 }));
1203 }
1204 project_subscriptions.push(cx.subscribe_in(
1205 project,
1206 window,
1207 |editor, _, event, window, cx| {
1208 if let project::Event::RefreshInlayHints = event {
1209 editor
1210 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1211 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1212 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1213 let focus_handle = editor.focus_handle(cx);
1214 if focus_handle.is_focused(window) {
1215 let snapshot = buffer.read(cx).snapshot();
1216 for (range, snippet) in snippet_edits {
1217 let editor_range =
1218 language::range_from_lsp(*range).to_offset(&snapshot);
1219 editor
1220 .insert_snippet(
1221 &[editor_range],
1222 snippet.clone(),
1223 window,
1224 cx,
1225 )
1226 .ok();
1227 }
1228 }
1229 }
1230 }
1231 },
1232 ));
1233 if let Some(task_inventory) = project
1234 .read(cx)
1235 .task_store()
1236 .read(cx)
1237 .task_inventory()
1238 .cloned()
1239 {
1240 project_subscriptions.push(cx.observe_in(
1241 &task_inventory,
1242 window,
1243 |editor, _, window, cx| {
1244 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1245 },
1246 ));
1247 }
1248 }
1249 }
1250
1251 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1252
1253 let inlay_hint_settings =
1254 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1255 let focus_handle = cx.focus_handle();
1256 cx.on_focus(&focus_handle, window, Self::handle_focus)
1257 .detach();
1258 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1259 .detach();
1260 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1261 .detach();
1262 cx.on_blur(&focus_handle, window, Self::handle_blur)
1263 .detach();
1264
1265 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1266 Some(false)
1267 } else {
1268 None
1269 };
1270
1271 let mut code_action_providers = Vec::new();
1272 let mut load_uncommitted_diff = None;
1273 if let Some(project) = project.clone() {
1274 load_uncommitted_diff = Some(
1275 get_uncommitted_diff_for_buffer(
1276 &project,
1277 buffer.read(cx).all_buffers(),
1278 buffer.clone(),
1279 cx,
1280 )
1281 .shared(),
1282 );
1283 code_action_providers.push(Rc::new(project) as Rc<_>);
1284 }
1285
1286 let mut this = Self {
1287 focus_handle,
1288 show_cursor_when_unfocused: false,
1289 last_focused_descendant: None,
1290 buffer: buffer.clone(),
1291 display_map: display_map.clone(),
1292 selections,
1293 scroll_manager: ScrollManager::new(cx),
1294 columnar_selection_tail: None,
1295 add_selections_state: None,
1296 select_next_state: None,
1297 select_prev_state: None,
1298 selection_history: Default::default(),
1299 autoclose_regions: Default::default(),
1300 snippet_stack: Default::default(),
1301 select_larger_syntax_node_stack: Vec::new(),
1302 ime_transaction: Default::default(),
1303 active_diagnostics: None,
1304 soft_wrap_mode_override,
1305 completion_provider: project.clone().map(|project| Box::new(project) as _),
1306 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1307 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1308 project,
1309 blink_manager: blink_manager.clone(),
1310 show_local_selections: true,
1311 show_scrollbars: true,
1312 mode,
1313 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1314 show_gutter: mode == EditorMode::Full,
1315 show_line_numbers: None,
1316 use_relative_line_numbers: None,
1317 show_git_diff_gutter: None,
1318 show_code_actions: None,
1319 show_runnables: None,
1320 show_wrap_guides: None,
1321 show_indent_guides,
1322 placeholder_text: None,
1323 highlight_order: 0,
1324 highlighted_rows: HashMap::default(),
1325 background_highlights: Default::default(),
1326 gutter_highlights: TreeMap::default(),
1327 scrollbar_marker_state: ScrollbarMarkerState::default(),
1328 active_indent_guides_state: ActiveIndentGuidesState::default(),
1329 nav_history: None,
1330 context_menu: RefCell::new(None),
1331 mouse_context_menu: None,
1332 completion_tasks: Default::default(),
1333 signature_help_state: SignatureHelpState::default(),
1334 auto_signature_help: None,
1335 find_all_references_task_sources: Vec::new(),
1336 next_completion_id: 0,
1337 next_inlay_id: 0,
1338 code_action_providers,
1339 available_code_actions: Default::default(),
1340 code_actions_task: Default::default(),
1341 selection_highlight_task: Default::default(),
1342 document_highlights_task: Default::default(),
1343 linked_editing_range_task: Default::default(),
1344 pending_rename: Default::default(),
1345 searchable: true,
1346 cursor_shape: EditorSettings::get_global(cx)
1347 .cursor_shape
1348 .unwrap_or_default(),
1349 current_line_highlight: None,
1350 autoindent_mode: Some(AutoindentMode::EachLine),
1351 collapse_matches: false,
1352 workspace: None,
1353 input_enabled: true,
1354 use_modal_editing: mode == EditorMode::Full,
1355 read_only: false,
1356 use_autoclose: true,
1357 use_auto_surround: true,
1358 auto_replace_emoji_shortcode: false,
1359 leader_peer_id: None,
1360 remote_id: None,
1361 hover_state: Default::default(),
1362 pending_mouse_down: None,
1363 hovered_link_state: Default::default(),
1364 edit_prediction_provider: None,
1365 active_inline_completion: None,
1366 stale_inline_completion_in_menu: None,
1367 edit_prediction_preview: EditPredictionPreview::Inactive,
1368 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1369
1370 gutter_hovered: false,
1371 pixel_position_of_newest_cursor: None,
1372 last_bounds: None,
1373 last_position_map: None,
1374 expect_bounds_change: None,
1375 gutter_dimensions: GutterDimensions::default(),
1376 style: None,
1377 show_cursor_names: false,
1378 hovered_cursors: Default::default(),
1379 next_editor_action_id: EditorActionId::default(),
1380 editor_actions: Rc::default(),
1381 inline_completions_hidden_for_vim_mode: false,
1382 show_inline_completions_override: None,
1383 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1384 edit_prediction_settings: EditPredictionSettings::Disabled,
1385 edit_prediction_cursor_on_leading_whitespace: false,
1386 edit_prediction_requires_modifier_in_leading_space: true,
1387 custom_context_menu: None,
1388 show_git_blame_gutter: false,
1389 show_git_blame_inline: false,
1390 distinguish_unstaged_diff_hunks: false,
1391 show_selection_menu: None,
1392 show_git_blame_inline_delay_task: None,
1393 git_blame_inline_tooltip: None,
1394 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1395 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1396 .session
1397 .restore_unsaved_buffers,
1398 blame: None,
1399 blame_subscription: None,
1400 tasks: Default::default(),
1401 _subscriptions: vec![
1402 cx.observe(&buffer, Self::on_buffer_changed),
1403 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1404 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1405 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1406 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1407 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1408 cx.observe_window_activation(window, |editor, window, cx| {
1409 let active = window.is_window_active();
1410 editor.blink_manager.update(cx, |blink_manager, cx| {
1411 if active {
1412 blink_manager.enable(cx);
1413 } else {
1414 blink_manager.disable(cx);
1415 }
1416 });
1417 }),
1418 ],
1419 tasks_update_task: None,
1420 linked_edit_ranges: Default::default(),
1421 in_project_search: false,
1422 previous_search_ranges: None,
1423 breadcrumb_header: None,
1424 focused_block: None,
1425 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1426 addons: HashMap::default(),
1427 registered_buffers: HashMap::default(),
1428 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1429 selection_mark_mode: false,
1430 toggle_fold_multiple_buffers: Task::ready(()),
1431 serialize_selections: Task::ready(()),
1432 text_style_refinement: None,
1433 load_diff_task: load_uncommitted_diff,
1434 };
1435 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1436 this._subscriptions.extend(project_subscriptions);
1437
1438 this.end_selection(window, cx);
1439 this.scroll_manager.show_scrollbar(window, cx);
1440
1441 if mode == EditorMode::Full {
1442 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1443 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1444
1445 if this.git_blame_inline_enabled {
1446 this.git_blame_inline_enabled = true;
1447 this.start_git_blame_inline(false, window, cx);
1448 }
1449
1450 if let Some(buffer) = buffer.read(cx).as_singleton() {
1451 if let Some(project) = this.project.as_ref() {
1452 let handle = project.update(cx, |project, cx| {
1453 project.register_buffer_with_language_servers(&buffer, cx)
1454 });
1455 this.registered_buffers
1456 .insert(buffer.read(cx).remote_id(), handle);
1457 }
1458 }
1459 }
1460
1461 this.report_editor_event("Editor Opened", None, cx);
1462 this
1463 }
1464
1465 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1466 self.mouse_context_menu
1467 .as_ref()
1468 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1469 }
1470
1471 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1472 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1473 }
1474
1475 fn key_context_internal(
1476 &self,
1477 has_active_edit_prediction: bool,
1478 window: &Window,
1479 cx: &App,
1480 ) -> KeyContext {
1481 let mut key_context = KeyContext::new_with_defaults();
1482 key_context.add("Editor");
1483 let mode = match self.mode {
1484 EditorMode::SingleLine { .. } => "single_line",
1485 EditorMode::AutoHeight { .. } => "auto_height",
1486 EditorMode::Full => "full",
1487 };
1488
1489 if EditorSettings::jupyter_enabled(cx) {
1490 key_context.add("jupyter");
1491 }
1492
1493 key_context.set("mode", mode);
1494 if self.pending_rename.is_some() {
1495 key_context.add("renaming");
1496 }
1497
1498 match self.context_menu.borrow().as_ref() {
1499 Some(CodeContextMenu::Completions(_)) => {
1500 key_context.add("menu");
1501 key_context.add("showing_completions");
1502 }
1503 Some(CodeContextMenu::CodeActions(_)) => {
1504 key_context.add("menu");
1505 key_context.add("showing_code_actions")
1506 }
1507 None => {}
1508 }
1509
1510 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1511 if !self.focus_handle(cx).contains_focused(window, cx)
1512 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1513 {
1514 for addon in self.addons.values() {
1515 addon.extend_key_context(&mut key_context, cx)
1516 }
1517 }
1518
1519 if let Some(extension) = self
1520 .buffer
1521 .read(cx)
1522 .as_singleton()
1523 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1524 {
1525 key_context.set("extension", extension.to_string());
1526 }
1527
1528 if has_active_edit_prediction {
1529 if self.edit_prediction_in_conflict() {
1530 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1531 } else {
1532 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1533 key_context.add("copilot_suggestion");
1534 }
1535 }
1536
1537 if self.selection_mark_mode {
1538 key_context.add("selection_mode");
1539 }
1540
1541 key_context
1542 }
1543
1544 pub fn edit_prediction_in_conflict(&self) -> bool {
1545 if !self.show_edit_predictions_in_menu() {
1546 return false;
1547 }
1548
1549 let showing_completions = self
1550 .context_menu
1551 .borrow()
1552 .as_ref()
1553 .map_or(false, |context| {
1554 matches!(context, CodeContextMenu::Completions(_))
1555 });
1556
1557 showing_completions
1558 || self.edit_prediction_requires_modifier()
1559 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1560 // bindings to insert tab characters.
1561 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1562 }
1563
1564 pub fn accept_edit_prediction_keybind(
1565 &self,
1566 window: &Window,
1567 cx: &App,
1568 ) -> AcceptEditPredictionBinding {
1569 let key_context = self.key_context_internal(true, window, cx);
1570 let in_conflict = self.edit_prediction_in_conflict();
1571
1572 AcceptEditPredictionBinding(
1573 window
1574 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1575 .into_iter()
1576 .filter(|binding| {
1577 !in_conflict
1578 || binding
1579 .keystrokes()
1580 .first()
1581 .map_or(false, |keystroke| keystroke.modifiers.modified())
1582 })
1583 .rev()
1584 .min_by_key(|binding| {
1585 binding
1586 .keystrokes()
1587 .first()
1588 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1589 }),
1590 )
1591 }
1592
1593 pub fn new_file(
1594 workspace: &mut Workspace,
1595 _: &workspace::NewFile,
1596 window: &mut Window,
1597 cx: &mut Context<Workspace>,
1598 ) {
1599 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1600 "Failed to create buffer",
1601 window,
1602 cx,
1603 |e, _, _| match e.error_code() {
1604 ErrorCode::RemoteUpgradeRequired => Some(format!(
1605 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1606 e.error_tag("required").unwrap_or("the latest version")
1607 )),
1608 _ => None,
1609 },
1610 );
1611 }
1612
1613 pub fn new_in_workspace(
1614 workspace: &mut Workspace,
1615 window: &mut Window,
1616 cx: &mut Context<Workspace>,
1617 ) -> Task<Result<Entity<Editor>>> {
1618 let project = workspace.project().clone();
1619 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1620
1621 cx.spawn_in(window, |workspace, mut cx| async move {
1622 let buffer = create.await?;
1623 workspace.update_in(&mut cx, |workspace, window, cx| {
1624 let editor =
1625 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1626 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1627 editor
1628 })
1629 })
1630 }
1631
1632 fn new_file_vertical(
1633 workspace: &mut Workspace,
1634 _: &workspace::NewFileSplitVertical,
1635 window: &mut Window,
1636 cx: &mut Context<Workspace>,
1637 ) {
1638 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1639 }
1640
1641 fn new_file_horizontal(
1642 workspace: &mut Workspace,
1643 _: &workspace::NewFileSplitHorizontal,
1644 window: &mut Window,
1645 cx: &mut Context<Workspace>,
1646 ) {
1647 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1648 }
1649
1650 fn new_file_in_direction(
1651 workspace: &mut Workspace,
1652 direction: SplitDirection,
1653 window: &mut Window,
1654 cx: &mut Context<Workspace>,
1655 ) {
1656 let project = workspace.project().clone();
1657 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1658
1659 cx.spawn_in(window, |workspace, mut cx| async move {
1660 let buffer = create.await?;
1661 workspace.update_in(&mut cx, move |workspace, window, cx| {
1662 workspace.split_item(
1663 direction,
1664 Box::new(
1665 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1666 ),
1667 window,
1668 cx,
1669 )
1670 })?;
1671 anyhow::Ok(())
1672 })
1673 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1674 match e.error_code() {
1675 ErrorCode::RemoteUpgradeRequired => Some(format!(
1676 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1677 e.error_tag("required").unwrap_or("the latest version")
1678 )),
1679 _ => None,
1680 }
1681 });
1682 }
1683
1684 pub fn leader_peer_id(&self) -> Option<PeerId> {
1685 self.leader_peer_id
1686 }
1687
1688 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1689 &self.buffer
1690 }
1691
1692 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1693 self.workspace.as_ref()?.0.upgrade()
1694 }
1695
1696 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1697 self.buffer().read(cx).title(cx)
1698 }
1699
1700 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1701 let git_blame_gutter_max_author_length = self
1702 .render_git_blame_gutter(cx)
1703 .then(|| {
1704 if let Some(blame) = self.blame.as_ref() {
1705 let max_author_length =
1706 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1707 Some(max_author_length)
1708 } else {
1709 None
1710 }
1711 })
1712 .flatten();
1713
1714 EditorSnapshot {
1715 mode: self.mode,
1716 show_gutter: self.show_gutter,
1717 show_line_numbers: self.show_line_numbers,
1718 show_git_diff_gutter: self.show_git_diff_gutter,
1719 show_code_actions: self.show_code_actions,
1720 show_runnables: self.show_runnables,
1721 git_blame_gutter_max_author_length,
1722 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1723 scroll_anchor: self.scroll_manager.anchor(),
1724 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1725 placeholder_text: self.placeholder_text.clone(),
1726 is_focused: self.focus_handle.is_focused(window),
1727 current_line_highlight: self
1728 .current_line_highlight
1729 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1730 gutter_hovered: self.gutter_hovered,
1731 }
1732 }
1733
1734 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1735 self.buffer.read(cx).language_at(point, cx)
1736 }
1737
1738 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1739 self.buffer.read(cx).read(cx).file_at(point).cloned()
1740 }
1741
1742 pub fn active_excerpt(
1743 &self,
1744 cx: &App,
1745 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1746 self.buffer
1747 .read(cx)
1748 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1749 }
1750
1751 pub fn mode(&self) -> EditorMode {
1752 self.mode
1753 }
1754
1755 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1756 self.collaboration_hub.as_deref()
1757 }
1758
1759 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1760 self.collaboration_hub = Some(hub);
1761 }
1762
1763 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1764 self.in_project_search = in_project_search;
1765 }
1766
1767 pub fn set_custom_context_menu(
1768 &mut self,
1769 f: impl 'static
1770 + Fn(
1771 &mut Self,
1772 DisplayPoint,
1773 &mut Window,
1774 &mut Context<Self>,
1775 ) -> Option<Entity<ui::ContextMenu>>,
1776 ) {
1777 self.custom_context_menu = Some(Box::new(f))
1778 }
1779
1780 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1781 self.completion_provider = provider;
1782 }
1783
1784 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1785 self.semantics_provider.clone()
1786 }
1787
1788 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1789 self.semantics_provider = provider;
1790 }
1791
1792 pub fn set_edit_prediction_provider<T>(
1793 &mut self,
1794 provider: Option<Entity<T>>,
1795 window: &mut Window,
1796 cx: &mut Context<Self>,
1797 ) where
1798 T: EditPredictionProvider,
1799 {
1800 self.edit_prediction_provider =
1801 provider.map(|provider| RegisteredInlineCompletionProvider {
1802 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1803 if this.focus_handle.is_focused(window) {
1804 this.update_visible_inline_completion(window, cx);
1805 }
1806 }),
1807 provider: Arc::new(provider),
1808 });
1809 self.refresh_inline_completion(false, false, window, cx);
1810 }
1811
1812 pub fn placeholder_text(&self) -> Option<&str> {
1813 self.placeholder_text.as_deref()
1814 }
1815
1816 pub fn set_placeholder_text(
1817 &mut self,
1818 placeholder_text: impl Into<Arc<str>>,
1819 cx: &mut Context<Self>,
1820 ) {
1821 let placeholder_text = Some(placeholder_text.into());
1822 if self.placeholder_text != placeholder_text {
1823 self.placeholder_text = placeholder_text;
1824 cx.notify();
1825 }
1826 }
1827
1828 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1829 self.cursor_shape = cursor_shape;
1830
1831 // Disrupt blink for immediate user feedback that the cursor shape has changed
1832 self.blink_manager.update(cx, BlinkManager::show_cursor);
1833
1834 cx.notify();
1835 }
1836
1837 pub fn set_current_line_highlight(
1838 &mut self,
1839 current_line_highlight: Option<CurrentLineHighlight>,
1840 ) {
1841 self.current_line_highlight = current_line_highlight;
1842 }
1843
1844 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1845 self.collapse_matches = collapse_matches;
1846 }
1847
1848 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1849 let buffers = self.buffer.read(cx).all_buffers();
1850 let Some(project) = self.project.as_ref() else {
1851 return;
1852 };
1853 project.update(cx, |project, cx| {
1854 for buffer in buffers {
1855 self.registered_buffers
1856 .entry(buffer.read(cx).remote_id())
1857 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1858 }
1859 })
1860 }
1861
1862 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1863 if self.collapse_matches {
1864 return range.start..range.start;
1865 }
1866 range.clone()
1867 }
1868
1869 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1870 if self.display_map.read(cx).clip_at_line_ends != clip {
1871 self.display_map
1872 .update(cx, |map, _| map.clip_at_line_ends = clip);
1873 }
1874 }
1875
1876 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1877 self.input_enabled = input_enabled;
1878 }
1879
1880 pub fn set_inline_completions_hidden_for_vim_mode(
1881 &mut self,
1882 hidden: bool,
1883 window: &mut Window,
1884 cx: &mut Context<Self>,
1885 ) {
1886 if hidden != self.inline_completions_hidden_for_vim_mode {
1887 self.inline_completions_hidden_for_vim_mode = hidden;
1888 if hidden {
1889 self.update_visible_inline_completion(window, cx);
1890 } else {
1891 self.refresh_inline_completion(true, false, window, cx);
1892 }
1893 }
1894 }
1895
1896 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1897 self.menu_inline_completions_policy = value;
1898 }
1899
1900 pub fn set_autoindent(&mut self, autoindent: bool) {
1901 if autoindent {
1902 self.autoindent_mode = Some(AutoindentMode::EachLine);
1903 } else {
1904 self.autoindent_mode = None;
1905 }
1906 }
1907
1908 pub fn read_only(&self, cx: &App) -> bool {
1909 self.read_only || self.buffer.read(cx).read_only()
1910 }
1911
1912 pub fn set_read_only(&mut self, read_only: bool) {
1913 self.read_only = read_only;
1914 }
1915
1916 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1917 self.use_autoclose = autoclose;
1918 }
1919
1920 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1921 self.use_auto_surround = auto_surround;
1922 }
1923
1924 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1925 self.auto_replace_emoji_shortcode = auto_replace;
1926 }
1927
1928 pub fn toggle_inline_completions(
1929 &mut self,
1930 _: &ToggleEditPrediction,
1931 window: &mut Window,
1932 cx: &mut Context<Self>,
1933 ) {
1934 if self.show_inline_completions_override.is_some() {
1935 self.set_show_edit_predictions(None, window, cx);
1936 } else {
1937 let show_edit_predictions = !self.edit_predictions_enabled();
1938 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1939 }
1940 }
1941
1942 pub fn set_show_edit_predictions(
1943 &mut self,
1944 show_edit_predictions: Option<bool>,
1945 window: &mut Window,
1946 cx: &mut Context<Self>,
1947 ) {
1948 self.show_inline_completions_override = show_edit_predictions;
1949 self.refresh_inline_completion(false, true, window, cx);
1950 }
1951
1952 fn inline_completions_disabled_in_scope(
1953 &self,
1954 buffer: &Entity<Buffer>,
1955 buffer_position: language::Anchor,
1956 cx: &App,
1957 ) -> bool {
1958 let snapshot = buffer.read(cx).snapshot();
1959 let settings = snapshot.settings_at(buffer_position, cx);
1960
1961 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1962 return false;
1963 };
1964
1965 scope.override_name().map_or(false, |scope_name| {
1966 settings
1967 .edit_predictions_disabled_in
1968 .iter()
1969 .any(|s| s == scope_name)
1970 })
1971 }
1972
1973 pub fn set_use_modal_editing(&mut self, to: bool) {
1974 self.use_modal_editing = to;
1975 }
1976
1977 pub fn use_modal_editing(&self) -> bool {
1978 self.use_modal_editing
1979 }
1980
1981 fn selections_did_change(
1982 &mut self,
1983 local: bool,
1984 old_cursor_position: &Anchor,
1985 show_completions: bool,
1986 window: &mut Window,
1987 cx: &mut Context<Self>,
1988 ) {
1989 window.invalidate_character_coordinates();
1990
1991 // Copy selections to primary selection buffer
1992 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1993 if local {
1994 let selections = self.selections.all::<usize>(cx);
1995 let buffer_handle = self.buffer.read(cx).read(cx);
1996
1997 let mut text = String::new();
1998 for (index, selection) in selections.iter().enumerate() {
1999 let text_for_selection = buffer_handle
2000 .text_for_range(selection.start..selection.end)
2001 .collect::<String>();
2002
2003 text.push_str(&text_for_selection);
2004 if index != selections.len() - 1 {
2005 text.push('\n');
2006 }
2007 }
2008
2009 if !text.is_empty() {
2010 cx.write_to_primary(ClipboardItem::new_string(text));
2011 }
2012 }
2013
2014 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2015 self.buffer.update(cx, |buffer, cx| {
2016 buffer.set_active_selections(
2017 &self.selections.disjoint_anchors(),
2018 self.selections.line_mode,
2019 self.cursor_shape,
2020 cx,
2021 )
2022 });
2023 }
2024 let display_map = self
2025 .display_map
2026 .update(cx, |display_map, cx| display_map.snapshot(cx));
2027 let buffer = &display_map.buffer_snapshot;
2028 self.add_selections_state = None;
2029 self.select_next_state = None;
2030 self.select_prev_state = None;
2031 self.select_larger_syntax_node_stack.clear();
2032 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2033 self.snippet_stack
2034 .invalidate(&self.selections.disjoint_anchors(), buffer);
2035 self.take_rename(false, window, cx);
2036
2037 let new_cursor_position = self.selections.newest_anchor().head();
2038
2039 self.push_to_nav_history(
2040 *old_cursor_position,
2041 Some(new_cursor_position.to_point(buffer)),
2042 cx,
2043 );
2044
2045 if local {
2046 let new_cursor_position = self.selections.newest_anchor().head();
2047 let mut context_menu = self.context_menu.borrow_mut();
2048 let completion_menu = match context_menu.as_ref() {
2049 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2050 _ => {
2051 *context_menu = None;
2052 None
2053 }
2054 };
2055 if let Some(buffer_id) = new_cursor_position.buffer_id {
2056 if !self.registered_buffers.contains_key(&buffer_id) {
2057 if let Some(project) = self.project.as_ref() {
2058 project.update(cx, |project, cx| {
2059 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2060 return;
2061 };
2062 self.registered_buffers.insert(
2063 buffer_id,
2064 project.register_buffer_with_language_servers(&buffer, cx),
2065 );
2066 })
2067 }
2068 }
2069 }
2070
2071 if let Some(completion_menu) = completion_menu {
2072 let cursor_position = new_cursor_position.to_offset(buffer);
2073 let (word_range, kind) =
2074 buffer.surrounding_word(completion_menu.initial_position, true);
2075 if kind == Some(CharKind::Word)
2076 && word_range.to_inclusive().contains(&cursor_position)
2077 {
2078 let mut completion_menu = completion_menu.clone();
2079 drop(context_menu);
2080
2081 let query = Self::completion_query(buffer, cursor_position);
2082 cx.spawn(move |this, mut cx| async move {
2083 completion_menu
2084 .filter(query.as_deref(), cx.background_executor().clone())
2085 .await;
2086
2087 this.update(&mut cx, |this, cx| {
2088 let mut context_menu = this.context_menu.borrow_mut();
2089 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2090 else {
2091 return;
2092 };
2093
2094 if menu.id > completion_menu.id {
2095 return;
2096 }
2097
2098 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2099 drop(context_menu);
2100 cx.notify();
2101 })
2102 })
2103 .detach();
2104
2105 if show_completions {
2106 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2107 }
2108 } else {
2109 drop(context_menu);
2110 self.hide_context_menu(window, cx);
2111 }
2112 } else {
2113 drop(context_menu);
2114 }
2115
2116 hide_hover(self, cx);
2117
2118 if old_cursor_position.to_display_point(&display_map).row()
2119 != new_cursor_position.to_display_point(&display_map).row()
2120 {
2121 self.available_code_actions.take();
2122 }
2123 self.refresh_code_actions(window, cx);
2124 self.refresh_document_highlights(cx);
2125 self.refresh_selected_text_highlights(window, cx);
2126 refresh_matching_bracket_highlights(self, window, cx);
2127 self.update_visible_inline_completion(window, cx);
2128 self.edit_prediction_requires_modifier_in_leading_space = true;
2129 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2130 if self.git_blame_inline_enabled {
2131 self.start_inline_blame_timer(window, cx);
2132 }
2133 }
2134
2135 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2136 cx.emit(EditorEvent::SelectionsChanged { local });
2137
2138 let selections = &self.selections.disjoint;
2139 if selections.len() == 1 {
2140 cx.emit(SearchEvent::ActiveMatchChanged)
2141 }
2142 if local
2143 && self.is_singleton(cx)
2144 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2145 {
2146 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2147 let background_executor = cx.background_executor().clone();
2148 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2149 let snapshot = self.buffer().read(cx).snapshot(cx);
2150 let selections = selections.clone();
2151 self.serialize_selections = cx.background_spawn(async move {
2152 background_executor.timer(Duration::from_millis(100)).await;
2153 let selections = selections
2154 .iter()
2155 .map(|selection| {
2156 (
2157 selection.start.to_offset(&snapshot),
2158 selection.end.to_offset(&snapshot),
2159 )
2160 })
2161 .collect();
2162 DB.save_editor_selections(editor_id, workspace_id, selections)
2163 .await
2164 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2165 .log_err();
2166 });
2167 }
2168 }
2169
2170 cx.notify();
2171 }
2172
2173 pub fn change_selections<R>(
2174 &mut self,
2175 autoscroll: Option<Autoscroll>,
2176 window: &mut Window,
2177 cx: &mut Context<Self>,
2178 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2179 ) -> R {
2180 self.change_selections_inner(autoscroll, true, window, cx, change)
2181 }
2182
2183 fn change_selections_inner<R>(
2184 &mut self,
2185 autoscroll: Option<Autoscroll>,
2186 request_completions: bool,
2187 window: &mut Window,
2188 cx: &mut Context<Self>,
2189 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2190 ) -> R {
2191 let old_cursor_position = self.selections.newest_anchor().head();
2192 self.push_to_selection_history();
2193
2194 let (changed, result) = self.selections.change_with(cx, change);
2195
2196 if changed {
2197 if let Some(autoscroll) = autoscroll {
2198 self.request_autoscroll(autoscroll, cx);
2199 }
2200 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2201
2202 if self.should_open_signature_help_automatically(
2203 &old_cursor_position,
2204 self.signature_help_state.backspace_pressed(),
2205 cx,
2206 ) {
2207 self.show_signature_help(&ShowSignatureHelp, window, cx);
2208 }
2209 self.signature_help_state.set_backspace_pressed(false);
2210 }
2211
2212 result
2213 }
2214
2215 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2216 where
2217 I: IntoIterator<Item = (Range<S>, T)>,
2218 S: ToOffset,
2219 T: Into<Arc<str>>,
2220 {
2221 if self.read_only(cx) {
2222 return;
2223 }
2224
2225 self.buffer
2226 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2227 }
2228
2229 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2230 where
2231 I: IntoIterator<Item = (Range<S>, T)>,
2232 S: ToOffset,
2233 T: Into<Arc<str>>,
2234 {
2235 if self.read_only(cx) {
2236 return;
2237 }
2238
2239 self.buffer.update(cx, |buffer, cx| {
2240 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2241 });
2242 }
2243
2244 pub fn edit_with_block_indent<I, S, T>(
2245 &mut self,
2246 edits: I,
2247 original_indent_columns: Vec<u32>,
2248 cx: &mut Context<Self>,
2249 ) where
2250 I: IntoIterator<Item = (Range<S>, T)>,
2251 S: ToOffset,
2252 T: Into<Arc<str>>,
2253 {
2254 if self.read_only(cx) {
2255 return;
2256 }
2257
2258 self.buffer.update(cx, |buffer, cx| {
2259 buffer.edit(
2260 edits,
2261 Some(AutoindentMode::Block {
2262 original_indent_columns,
2263 }),
2264 cx,
2265 )
2266 });
2267 }
2268
2269 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2270 self.hide_context_menu(window, cx);
2271
2272 match phase {
2273 SelectPhase::Begin {
2274 position,
2275 add,
2276 click_count,
2277 } => self.begin_selection(position, add, click_count, window, cx),
2278 SelectPhase::BeginColumnar {
2279 position,
2280 goal_column,
2281 reset,
2282 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2283 SelectPhase::Extend {
2284 position,
2285 click_count,
2286 } => self.extend_selection(position, click_count, window, cx),
2287 SelectPhase::Update {
2288 position,
2289 goal_column,
2290 scroll_delta,
2291 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2292 SelectPhase::End => self.end_selection(window, cx),
2293 }
2294 }
2295
2296 fn extend_selection(
2297 &mut self,
2298 position: DisplayPoint,
2299 click_count: usize,
2300 window: &mut Window,
2301 cx: &mut Context<Self>,
2302 ) {
2303 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2304 let tail = self.selections.newest::<usize>(cx).tail();
2305 self.begin_selection(position, false, click_count, window, cx);
2306
2307 let position = position.to_offset(&display_map, Bias::Left);
2308 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2309
2310 let mut pending_selection = self
2311 .selections
2312 .pending_anchor()
2313 .expect("extend_selection not called with pending selection");
2314 if position >= tail {
2315 pending_selection.start = tail_anchor;
2316 } else {
2317 pending_selection.end = tail_anchor;
2318 pending_selection.reversed = true;
2319 }
2320
2321 let mut pending_mode = self.selections.pending_mode().unwrap();
2322 match &mut pending_mode {
2323 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2324 _ => {}
2325 }
2326
2327 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2328 s.set_pending(pending_selection, pending_mode)
2329 });
2330 }
2331
2332 fn begin_selection(
2333 &mut self,
2334 position: DisplayPoint,
2335 add: bool,
2336 click_count: usize,
2337 window: &mut Window,
2338 cx: &mut Context<Self>,
2339 ) {
2340 if !self.focus_handle.is_focused(window) {
2341 self.last_focused_descendant = None;
2342 window.focus(&self.focus_handle);
2343 }
2344
2345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2346 let buffer = &display_map.buffer_snapshot;
2347 let newest_selection = self.selections.newest_anchor().clone();
2348 let position = display_map.clip_point(position, Bias::Left);
2349
2350 let start;
2351 let end;
2352 let mode;
2353 let mut auto_scroll;
2354 match click_count {
2355 1 => {
2356 start = buffer.anchor_before(position.to_point(&display_map));
2357 end = start;
2358 mode = SelectMode::Character;
2359 auto_scroll = true;
2360 }
2361 2 => {
2362 let range = movement::surrounding_word(&display_map, position);
2363 start = buffer.anchor_before(range.start.to_point(&display_map));
2364 end = buffer.anchor_before(range.end.to_point(&display_map));
2365 mode = SelectMode::Word(start..end);
2366 auto_scroll = true;
2367 }
2368 3 => {
2369 let position = display_map
2370 .clip_point(position, Bias::Left)
2371 .to_point(&display_map);
2372 let line_start = display_map.prev_line_boundary(position).0;
2373 let next_line_start = buffer.clip_point(
2374 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2375 Bias::Left,
2376 );
2377 start = buffer.anchor_before(line_start);
2378 end = buffer.anchor_before(next_line_start);
2379 mode = SelectMode::Line(start..end);
2380 auto_scroll = true;
2381 }
2382 _ => {
2383 start = buffer.anchor_before(0);
2384 end = buffer.anchor_before(buffer.len());
2385 mode = SelectMode::All;
2386 auto_scroll = false;
2387 }
2388 }
2389 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2390
2391 let point_to_delete: Option<usize> = {
2392 let selected_points: Vec<Selection<Point>> =
2393 self.selections.disjoint_in_range(start..end, cx);
2394
2395 if !add || click_count > 1 {
2396 None
2397 } else if !selected_points.is_empty() {
2398 Some(selected_points[0].id)
2399 } else {
2400 let clicked_point_already_selected =
2401 self.selections.disjoint.iter().find(|selection| {
2402 selection.start.to_point(buffer) == start.to_point(buffer)
2403 || selection.end.to_point(buffer) == end.to_point(buffer)
2404 });
2405
2406 clicked_point_already_selected.map(|selection| selection.id)
2407 }
2408 };
2409
2410 let selections_count = self.selections.count();
2411
2412 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2413 if let Some(point_to_delete) = point_to_delete {
2414 s.delete(point_to_delete);
2415
2416 if selections_count == 1 {
2417 s.set_pending_anchor_range(start..end, mode);
2418 }
2419 } else {
2420 if !add {
2421 s.clear_disjoint();
2422 } else if click_count > 1 {
2423 s.delete(newest_selection.id)
2424 }
2425
2426 s.set_pending_anchor_range(start..end, mode);
2427 }
2428 });
2429 }
2430
2431 fn begin_columnar_selection(
2432 &mut self,
2433 position: DisplayPoint,
2434 goal_column: u32,
2435 reset: bool,
2436 window: &mut Window,
2437 cx: &mut Context<Self>,
2438 ) {
2439 if !self.focus_handle.is_focused(window) {
2440 self.last_focused_descendant = None;
2441 window.focus(&self.focus_handle);
2442 }
2443
2444 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2445
2446 if reset {
2447 let pointer_position = display_map
2448 .buffer_snapshot
2449 .anchor_before(position.to_point(&display_map));
2450
2451 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2452 s.clear_disjoint();
2453 s.set_pending_anchor_range(
2454 pointer_position..pointer_position,
2455 SelectMode::Character,
2456 );
2457 });
2458 }
2459
2460 let tail = self.selections.newest::<Point>(cx).tail();
2461 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2462
2463 if !reset {
2464 self.select_columns(
2465 tail.to_display_point(&display_map),
2466 position,
2467 goal_column,
2468 &display_map,
2469 window,
2470 cx,
2471 );
2472 }
2473 }
2474
2475 fn update_selection(
2476 &mut self,
2477 position: DisplayPoint,
2478 goal_column: u32,
2479 scroll_delta: gpui::Point<f32>,
2480 window: &mut Window,
2481 cx: &mut Context<Self>,
2482 ) {
2483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2484
2485 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2486 let tail = tail.to_display_point(&display_map);
2487 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2488 } else if let Some(mut pending) = self.selections.pending_anchor() {
2489 let buffer = self.buffer.read(cx).snapshot(cx);
2490 let head;
2491 let tail;
2492 let mode = self.selections.pending_mode().unwrap();
2493 match &mode {
2494 SelectMode::Character => {
2495 head = position.to_point(&display_map);
2496 tail = pending.tail().to_point(&buffer);
2497 }
2498 SelectMode::Word(original_range) => {
2499 let original_display_range = original_range.start.to_display_point(&display_map)
2500 ..original_range.end.to_display_point(&display_map);
2501 let original_buffer_range = original_display_range.start.to_point(&display_map)
2502 ..original_display_range.end.to_point(&display_map);
2503 if movement::is_inside_word(&display_map, position)
2504 || original_display_range.contains(&position)
2505 {
2506 let word_range = movement::surrounding_word(&display_map, position);
2507 if word_range.start < original_display_range.start {
2508 head = word_range.start.to_point(&display_map);
2509 } else {
2510 head = word_range.end.to_point(&display_map);
2511 }
2512 } else {
2513 head = position.to_point(&display_map);
2514 }
2515
2516 if head <= original_buffer_range.start {
2517 tail = original_buffer_range.end;
2518 } else {
2519 tail = original_buffer_range.start;
2520 }
2521 }
2522 SelectMode::Line(original_range) => {
2523 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2524
2525 let position = display_map
2526 .clip_point(position, Bias::Left)
2527 .to_point(&display_map);
2528 let line_start = display_map.prev_line_boundary(position).0;
2529 let next_line_start = buffer.clip_point(
2530 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2531 Bias::Left,
2532 );
2533
2534 if line_start < original_range.start {
2535 head = line_start
2536 } else {
2537 head = next_line_start
2538 }
2539
2540 if head <= original_range.start {
2541 tail = original_range.end;
2542 } else {
2543 tail = original_range.start;
2544 }
2545 }
2546 SelectMode::All => {
2547 return;
2548 }
2549 };
2550
2551 if head < tail {
2552 pending.start = buffer.anchor_before(head);
2553 pending.end = buffer.anchor_before(tail);
2554 pending.reversed = true;
2555 } else {
2556 pending.start = buffer.anchor_before(tail);
2557 pending.end = buffer.anchor_before(head);
2558 pending.reversed = false;
2559 }
2560
2561 self.change_selections(None, window, cx, |s| {
2562 s.set_pending(pending, mode);
2563 });
2564 } else {
2565 log::error!("update_selection dispatched with no pending selection");
2566 return;
2567 }
2568
2569 self.apply_scroll_delta(scroll_delta, window, cx);
2570 cx.notify();
2571 }
2572
2573 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2574 self.columnar_selection_tail.take();
2575 if self.selections.pending_anchor().is_some() {
2576 let selections = self.selections.all::<usize>(cx);
2577 self.change_selections(None, window, cx, |s| {
2578 s.select(selections);
2579 s.clear_pending();
2580 });
2581 }
2582 }
2583
2584 fn select_columns(
2585 &mut self,
2586 tail: DisplayPoint,
2587 head: DisplayPoint,
2588 goal_column: u32,
2589 display_map: &DisplaySnapshot,
2590 window: &mut Window,
2591 cx: &mut Context<Self>,
2592 ) {
2593 let start_row = cmp::min(tail.row(), head.row());
2594 let end_row = cmp::max(tail.row(), head.row());
2595 let start_column = cmp::min(tail.column(), goal_column);
2596 let end_column = cmp::max(tail.column(), goal_column);
2597 let reversed = start_column < tail.column();
2598
2599 let selection_ranges = (start_row.0..=end_row.0)
2600 .map(DisplayRow)
2601 .filter_map(|row| {
2602 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2603 let start = display_map
2604 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2605 .to_point(display_map);
2606 let end = display_map
2607 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2608 .to_point(display_map);
2609 if reversed {
2610 Some(end..start)
2611 } else {
2612 Some(start..end)
2613 }
2614 } else {
2615 None
2616 }
2617 })
2618 .collect::<Vec<_>>();
2619
2620 self.change_selections(None, window, cx, |s| {
2621 s.select_ranges(selection_ranges);
2622 });
2623 cx.notify();
2624 }
2625
2626 pub fn has_pending_nonempty_selection(&self) -> bool {
2627 let pending_nonempty_selection = match self.selections.pending_anchor() {
2628 Some(Selection { start, end, .. }) => start != end,
2629 None => false,
2630 };
2631
2632 pending_nonempty_selection
2633 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2634 }
2635
2636 pub fn has_pending_selection(&self) -> bool {
2637 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2638 }
2639
2640 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2641 self.selection_mark_mode = false;
2642
2643 if self.clear_expanded_diff_hunks(cx) {
2644 cx.notify();
2645 return;
2646 }
2647 if self.dismiss_menus_and_popups(true, window, cx) {
2648 return;
2649 }
2650
2651 if self.mode == EditorMode::Full
2652 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2653 {
2654 return;
2655 }
2656
2657 cx.propagate();
2658 }
2659
2660 pub fn dismiss_menus_and_popups(
2661 &mut self,
2662 is_user_requested: bool,
2663 window: &mut Window,
2664 cx: &mut Context<Self>,
2665 ) -> bool {
2666 if self.take_rename(false, window, cx).is_some() {
2667 return true;
2668 }
2669
2670 if hide_hover(self, cx) {
2671 return true;
2672 }
2673
2674 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2675 return true;
2676 }
2677
2678 if self.hide_context_menu(window, cx).is_some() {
2679 return true;
2680 }
2681
2682 if self.mouse_context_menu.take().is_some() {
2683 return true;
2684 }
2685
2686 if is_user_requested && self.discard_inline_completion(true, cx) {
2687 return true;
2688 }
2689
2690 if self.snippet_stack.pop().is_some() {
2691 return true;
2692 }
2693
2694 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2695 self.dismiss_diagnostics(cx);
2696 return true;
2697 }
2698
2699 false
2700 }
2701
2702 fn linked_editing_ranges_for(
2703 &self,
2704 selection: Range<text::Anchor>,
2705 cx: &App,
2706 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2707 if self.linked_edit_ranges.is_empty() {
2708 return None;
2709 }
2710 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2711 selection.end.buffer_id.and_then(|end_buffer_id| {
2712 if selection.start.buffer_id != Some(end_buffer_id) {
2713 return None;
2714 }
2715 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2716 let snapshot = buffer.read(cx).snapshot();
2717 self.linked_edit_ranges
2718 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2719 .map(|ranges| (ranges, snapshot, buffer))
2720 })?;
2721 use text::ToOffset as TO;
2722 // find offset from the start of current range to current cursor position
2723 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2724
2725 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2726 let start_difference = start_offset - start_byte_offset;
2727 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2728 let end_difference = end_offset - start_byte_offset;
2729 // Current range has associated linked ranges.
2730 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2731 for range in linked_ranges.iter() {
2732 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2733 let end_offset = start_offset + end_difference;
2734 let start_offset = start_offset + start_difference;
2735 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2736 continue;
2737 }
2738 if self.selections.disjoint_anchor_ranges().any(|s| {
2739 if s.start.buffer_id != selection.start.buffer_id
2740 || s.end.buffer_id != selection.end.buffer_id
2741 {
2742 return false;
2743 }
2744 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2745 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2746 }) {
2747 continue;
2748 }
2749 let start = buffer_snapshot.anchor_after(start_offset);
2750 let end = buffer_snapshot.anchor_after(end_offset);
2751 linked_edits
2752 .entry(buffer.clone())
2753 .or_default()
2754 .push(start..end);
2755 }
2756 Some(linked_edits)
2757 }
2758
2759 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2760 let text: Arc<str> = text.into();
2761
2762 if self.read_only(cx) {
2763 return;
2764 }
2765
2766 let selections = self.selections.all_adjusted(cx);
2767 let mut bracket_inserted = false;
2768 let mut edits = Vec::new();
2769 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2770 let mut new_selections = Vec::with_capacity(selections.len());
2771 let mut new_autoclose_regions = Vec::new();
2772 let snapshot = self.buffer.read(cx).read(cx);
2773
2774 for (selection, autoclose_region) in
2775 self.selections_with_autoclose_regions(selections, &snapshot)
2776 {
2777 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2778 // Determine if the inserted text matches the opening or closing
2779 // bracket of any of this language's bracket pairs.
2780 let mut bracket_pair = None;
2781 let mut is_bracket_pair_start = false;
2782 let mut is_bracket_pair_end = false;
2783 if !text.is_empty() {
2784 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2785 // and they are removing the character that triggered IME popup.
2786 for (pair, enabled) in scope.brackets() {
2787 if !pair.close && !pair.surround {
2788 continue;
2789 }
2790
2791 if enabled && pair.start.ends_with(text.as_ref()) {
2792 let prefix_len = pair.start.len() - text.len();
2793 let preceding_text_matches_prefix = prefix_len == 0
2794 || (selection.start.column >= (prefix_len as u32)
2795 && snapshot.contains_str_at(
2796 Point::new(
2797 selection.start.row,
2798 selection.start.column - (prefix_len as u32),
2799 ),
2800 &pair.start[..prefix_len],
2801 ));
2802 if preceding_text_matches_prefix {
2803 bracket_pair = Some(pair.clone());
2804 is_bracket_pair_start = true;
2805 break;
2806 }
2807 }
2808 if pair.end.as_str() == text.as_ref() {
2809 bracket_pair = Some(pair.clone());
2810 is_bracket_pair_end = true;
2811 break;
2812 }
2813 }
2814 }
2815
2816 if let Some(bracket_pair) = bracket_pair {
2817 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2818 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2819 let auto_surround =
2820 self.use_auto_surround && snapshot_settings.use_auto_surround;
2821 if selection.is_empty() {
2822 if is_bracket_pair_start {
2823 // If the inserted text is a suffix of an opening bracket and the
2824 // selection is preceded by the rest of the opening bracket, then
2825 // insert the closing bracket.
2826 let following_text_allows_autoclose = snapshot
2827 .chars_at(selection.start)
2828 .next()
2829 .map_or(true, |c| scope.should_autoclose_before(c));
2830
2831 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2832 && bracket_pair.start.len() == 1
2833 {
2834 let target = bracket_pair.start.chars().next().unwrap();
2835 let current_line_count = snapshot
2836 .reversed_chars_at(selection.start)
2837 .take_while(|&c| c != '\n')
2838 .filter(|&c| c == target)
2839 .count();
2840 current_line_count % 2 == 1
2841 } else {
2842 false
2843 };
2844
2845 if autoclose
2846 && bracket_pair.close
2847 && following_text_allows_autoclose
2848 && !is_closing_quote
2849 {
2850 let anchor = snapshot.anchor_before(selection.end);
2851 new_selections.push((selection.map(|_| anchor), text.len()));
2852 new_autoclose_regions.push((
2853 anchor,
2854 text.len(),
2855 selection.id,
2856 bracket_pair.clone(),
2857 ));
2858 edits.push((
2859 selection.range(),
2860 format!("{}{}", text, bracket_pair.end).into(),
2861 ));
2862 bracket_inserted = true;
2863 continue;
2864 }
2865 }
2866
2867 if let Some(region) = autoclose_region {
2868 // If the selection is followed by an auto-inserted closing bracket,
2869 // then don't insert that closing bracket again; just move the selection
2870 // past the closing bracket.
2871 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2872 && text.as_ref() == region.pair.end.as_str();
2873 if should_skip {
2874 let anchor = snapshot.anchor_after(selection.end);
2875 new_selections
2876 .push((selection.map(|_| anchor), region.pair.end.len()));
2877 continue;
2878 }
2879 }
2880
2881 let always_treat_brackets_as_autoclosed = snapshot
2882 .settings_at(selection.start, cx)
2883 .always_treat_brackets_as_autoclosed;
2884 if always_treat_brackets_as_autoclosed
2885 && is_bracket_pair_end
2886 && snapshot.contains_str_at(selection.end, text.as_ref())
2887 {
2888 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2889 // and the inserted text is a closing bracket and the selection is followed
2890 // by the closing bracket then move the selection past the closing bracket.
2891 let anchor = snapshot.anchor_after(selection.end);
2892 new_selections.push((selection.map(|_| anchor), text.len()));
2893 continue;
2894 }
2895 }
2896 // If an opening bracket is 1 character long and is typed while
2897 // text is selected, then surround that text with the bracket pair.
2898 else if auto_surround
2899 && bracket_pair.surround
2900 && is_bracket_pair_start
2901 && bracket_pair.start.chars().count() == 1
2902 {
2903 edits.push((selection.start..selection.start, text.clone()));
2904 edits.push((
2905 selection.end..selection.end,
2906 bracket_pair.end.as_str().into(),
2907 ));
2908 bracket_inserted = true;
2909 new_selections.push((
2910 Selection {
2911 id: selection.id,
2912 start: snapshot.anchor_after(selection.start),
2913 end: snapshot.anchor_before(selection.end),
2914 reversed: selection.reversed,
2915 goal: selection.goal,
2916 },
2917 0,
2918 ));
2919 continue;
2920 }
2921 }
2922 }
2923
2924 if self.auto_replace_emoji_shortcode
2925 && selection.is_empty()
2926 && text.as_ref().ends_with(':')
2927 {
2928 if let Some(possible_emoji_short_code) =
2929 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2930 {
2931 if !possible_emoji_short_code.is_empty() {
2932 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2933 let emoji_shortcode_start = Point::new(
2934 selection.start.row,
2935 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2936 );
2937
2938 // Remove shortcode from buffer
2939 edits.push((
2940 emoji_shortcode_start..selection.start,
2941 "".to_string().into(),
2942 ));
2943 new_selections.push((
2944 Selection {
2945 id: selection.id,
2946 start: snapshot.anchor_after(emoji_shortcode_start),
2947 end: snapshot.anchor_before(selection.start),
2948 reversed: selection.reversed,
2949 goal: selection.goal,
2950 },
2951 0,
2952 ));
2953
2954 // Insert emoji
2955 let selection_start_anchor = snapshot.anchor_after(selection.start);
2956 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2957 edits.push((selection.start..selection.end, emoji.to_string().into()));
2958
2959 continue;
2960 }
2961 }
2962 }
2963 }
2964
2965 // If not handling any auto-close operation, then just replace the selected
2966 // text with the given input and move the selection to the end of the
2967 // newly inserted text.
2968 let anchor = snapshot.anchor_after(selection.end);
2969 if !self.linked_edit_ranges.is_empty() {
2970 let start_anchor = snapshot.anchor_before(selection.start);
2971
2972 let is_word_char = text.chars().next().map_or(true, |char| {
2973 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2974 classifier.is_word(char)
2975 });
2976
2977 if is_word_char {
2978 if let Some(ranges) = self
2979 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2980 {
2981 for (buffer, edits) in ranges {
2982 linked_edits
2983 .entry(buffer.clone())
2984 .or_default()
2985 .extend(edits.into_iter().map(|range| (range, text.clone())));
2986 }
2987 }
2988 }
2989 }
2990
2991 new_selections.push((selection.map(|_| anchor), 0));
2992 edits.push((selection.start..selection.end, text.clone()));
2993 }
2994
2995 drop(snapshot);
2996
2997 self.transact(window, cx, |this, window, cx| {
2998 this.buffer.update(cx, |buffer, cx| {
2999 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3000 });
3001 for (buffer, edits) in linked_edits {
3002 buffer.update(cx, |buffer, cx| {
3003 let snapshot = buffer.snapshot();
3004 let edits = edits
3005 .into_iter()
3006 .map(|(range, text)| {
3007 use text::ToPoint as TP;
3008 let end_point = TP::to_point(&range.end, &snapshot);
3009 let start_point = TP::to_point(&range.start, &snapshot);
3010 (start_point..end_point, text)
3011 })
3012 .sorted_by_key(|(range, _)| range.start)
3013 .collect::<Vec<_>>();
3014 buffer.edit(edits, None, cx);
3015 })
3016 }
3017 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3018 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3019 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3020 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3021 .zip(new_selection_deltas)
3022 .map(|(selection, delta)| Selection {
3023 id: selection.id,
3024 start: selection.start + delta,
3025 end: selection.end + delta,
3026 reversed: selection.reversed,
3027 goal: SelectionGoal::None,
3028 })
3029 .collect::<Vec<_>>();
3030
3031 let mut i = 0;
3032 for (position, delta, selection_id, pair) in new_autoclose_regions {
3033 let position = position.to_offset(&map.buffer_snapshot) + delta;
3034 let start = map.buffer_snapshot.anchor_before(position);
3035 let end = map.buffer_snapshot.anchor_after(position);
3036 while let Some(existing_state) = this.autoclose_regions.get(i) {
3037 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3038 Ordering::Less => i += 1,
3039 Ordering::Greater => break,
3040 Ordering::Equal => {
3041 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3042 Ordering::Less => i += 1,
3043 Ordering::Equal => break,
3044 Ordering::Greater => break,
3045 }
3046 }
3047 }
3048 }
3049 this.autoclose_regions.insert(
3050 i,
3051 AutocloseRegion {
3052 selection_id,
3053 range: start..end,
3054 pair,
3055 },
3056 );
3057 }
3058
3059 let had_active_inline_completion = this.has_active_inline_completion();
3060 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3061 s.select(new_selections)
3062 });
3063
3064 if !bracket_inserted {
3065 if let Some(on_type_format_task) =
3066 this.trigger_on_type_formatting(text.to_string(), window, cx)
3067 {
3068 on_type_format_task.detach_and_log_err(cx);
3069 }
3070 }
3071
3072 let editor_settings = EditorSettings::get_global(cx);
3073 if bracket_inserted
3074 && (editor_settings.auto_signature_help
3075 || editor_settings.show_signature_help_after_edits)
3076 {
3077 this.show_signature_help(&ShowSignatureHelp, window, cx);
3078 }
3079
3080 let trigger_in_words =
3081 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3082 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3083 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3084 this.refresh_inline_completion(true, false, window, cx);
3085 });
3086 }
3087
3088 fn find_possible_emoji_shortcode_at_position(
3089 snapshot: &MultiBufferSnapshot,
3090 position: Point,
3091 ) -> Option<String> {
3092 let mut chars = Vec::new();
3093 let mut found_colon = false;
3094 for char in snapshot.reversed_chars_at(position).take(100) {
3095 // Found a possible emoji shortcode in the middle of the buffer
3096 if found_colon {
3097 if char.is_whitespace() {
3098 chars.reverse();
3099 return Some(chars.iter().collect());
3100 }
3101 // If the previous character is not a whitespace, we are in the middle of a word
3102 // and we only want to complete the shortcode if the word is made up of other emojis
3103 let mut containing_word = String::new();
3104 for ch in snapshot
3105 .reversed_chars_at(position)
3106 .skip(chars.len() + 1)
3107 .take(100)
3108 {
3109 if ch.is_whitespace() {
3110 break;
3111 }
3112 containing_word.push(ch);
3113 }
3114 let containing_word = containing_word.chars().rev().collect::<String>();
3115 if util::word_consists_of_emojis(containing_word.as_str()) {
3116 chars.reverse();
3117 return Some(chars.iter().collect());
3118 }
3119 }
3120
3121 if char.is_whitespace() || !char.is_ascii() {
3122 return None;
3123 }
3124 if char == ':' {
3125 found_colon = true;
3126 } else {
3127 chars.push(char);
3128 }
3129 }
3130 // Found a possible emoji shortcode at the beginning of the buffer
3131 chars.reverse();
3132 Some(chars.iter().collect())
3133 }
3134
3135 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3136 self.transact(window, cx, |this, window, cx| {
3137 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3138 let selections = this.selections.all::<usize>(cx);
3139 let multi_buffer = this.buffer.read(cx);
3140 let buffer = multi_buffer.snapshot(cx);
3141 selections
3142 .iter()
3143 .map(|selection| {
3144 let start_point = selection.start.to_point(&buffer);
3145 let mut indent =
3146 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3147 indent.len = cmp::min(indent.len, start_point.column);
3148 let start = selection.start;
3149 let end = selection.end;
3150 let selection_is_empty = start == end;
3151 let language_scope = buffer.language_scope_at(start);
3152 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3153 &language_scope
3154 {
3155 let leading_whitespace_len = buffer
3156 .reversed_chars_at(start)
3157 .take_while(|c| c.is_whitespace() && *c != '\n')
3158 .map(|c| c.len_utf8())
3159 .sum::<usize>();
3160
3161 let trailing_whitespace_len = buffer
3162 .chars_at(end)
3163 .take_while(|c| c.is_whitespace() && *c != '\n')
3164 .map(|c| c.len_utf8())
3165 .sum::<usize>();
3166
3167 let insert_extra_newline =
3168 language.brackets().any(|(pair, enabled)| {
3169 let pair_start = pair.start.trim_end();
3170 let pair_end = pair.end.trim_start();
3171
3172 enabled
3173 && pair.newline
3174 && buffer.contains_str_at(
3175 end + trailing_whitespace_len,
3176 pair_end,
3177 )
3178 && buffer.contains_str_at(
3179 (start - leading_whitespace_len)
3180 .saturating_sub(pair_start.len()),
3181 pair_start,
3182 )
3183 });
3184
3185 // Comment extension on newline is allowed only for cursor selections
3186 let comment_delimiter = maybe!({
3187 if !selection_is_empty {
3188 return None;
3189 }
3190
3191 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3192 return None;
3193 }
3194
3195 let delimiters = language.line_comment_prefixes();
3196 let max_len_of_delimiter =
3197 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3198 let (snapshot, range) =
3199 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3200
3201 let mut index_of_first_non_whitespace = 0;
3202 let comment_candidate = snapshot
3203 .chars_for_range(range)
3204 .skip_while(|c| {
3205 let should_skip = c.is_whitespace();
3206 if should_skip {
3207 index_of_first_non_whitespace += 1;
3208 }
3209 should_skip
3210 })
3211 .take(max_len_of_delimiter)
3212 .collect::<String>();
3213 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3214 comment_candidate.starts_with(comment_prefix.as_ref())
3215 })?;
3216 let cursor_is_placed_after_comment_marker =
3217 index_of_first_non_whitespace + comment_prefix.len()
3218 <= start_point.column as usize;
3219 if cursor_is_placed_after_comment_marker {
3220 Some(comment_prefix.clone())
3221 } else {
3222 None
3223 }
3224 });
3225 (comment_delimiter, insert_extra_newline)
3226 } else {
3227 (None, false)
3228 };
3229
3230 let capacity_for_delimiter = comment_delimiter
3231 .as_deref()
3232 .map(str::len)
3233 .unwrap_or_default();
3234 let mut new_text =
3235 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3236 new_text.push('\n');
3237 new_text.extend(indent.chars());
3238 if let Some(delimiter) = &comment_delimiter {
3239 new_text.push_str(delimiter);
3240 }
3241 if insert_extra_newline {
3242 new_text = new_text.repeat(2);
3243 }
3244
3245 let anchor = buffer.anchor_after(end);
3246 let new_selection = selection.map(|_| anchor);
3247 (
3248 (start..end, new_text),
3249 (insert_extra_newline, new_selection),
3250 )
3251 })
3252 .unzip()
3253 };
3254
3255 this.edit_with_autoindent(edits, cx);
3256 let buffer = this.buffer.read(cx).snapshot(cx);
3257 let new_selections = selection_fixup_info
3258 .into_iter()
3259 .map(|(extra_newline_inserted, new_selection)| {
3260 let mut cursor = new_selection.end.to_point(&buffer);
3261 if extra_newline_inserted {
3262 cursor.row -= 1;
3263 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3264 }
3265 new_selection.map(|_| cursor)
3266 })
3267 .collect();
3268
3269 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3270 s.select(new_selections)
3271 });
3272 this.refresh_inline_completion(true, false, window, cx);
3273 });
3274 }
3275
3276 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3277 let buffer = self.buffer.read(cx);
3278 let snapshot = buffer.snapshot(cx);
3279
3280 let mut edits = Vec::new();
3281 let mut rows = Vec::new();
3282
3283 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3284 let cursor = selection.head();
3285 let row = cursor.row;
3286
3287 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3288
3289 let newline = "\n".to_string();
3290 edits.push((start_of_line..start_of_line, newline));
3291
3292 rows.push(row + rows_inserted as u32);
3293 }
3294
3295 self.transact(window, cx, |editor, window, cx| {
3296 editor.edit(edits, cx);
3297
3298 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3299 let mut index = 0;
3300 s.move_cursors_with(|map, _, _| {
3301 let row = rows[index];
3302 index += 1;
3303
3304 let point = Point::new(row, 0);
3305 let boundary = map.next_line_boundary(point).1;
3306 let clipped = map.clip_point(boundary, Bias::Left);
3307
3308 (clipped, SelectionGoal::None)
3309 });
3310 });
3311
3312 let mut indent_edits = Vec::new();
3313 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3314 for row in rows {
3315 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3316 for (row, indent) in indents {
3317 if indent.len == 0 {
3318 continue;
3319 }
3320
3321 let text = match indent.kind {
3322 IndentKind::Space => " ".repeat(indent.len as usize),
3323 IndentKind::Tab => "\t".repeat(indent.len as usize),
3324 };
3325 let point = Point::new(row.0, 0);
3326 indent_edits.push((point..point, text));
3327 }
3328 }
3329 editor.edit(indent_edits, cx);
3330 });
3331 }
3332
3333 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3334 let buffer = self.buffer.read(cx);
3335 let snapshot = buffer.snapshot(cx);
3336
3337 let mut edits = Vec::new();
3338 let mut rows = Vec::new();
3339 let mut rows_inserted = 0;
3340
3341 for selection in self.selections.all_adjusted(cx) {
3342 let cursor = selection.head();
3343 let row = cursor.row;
3344
3345 let point = Point::new(row + 1, 0);
3346 let start_of_line = snapshot.clip_point(point, Bias::Left);
3347
3348 let newline = "\n".to_string();
3349 edits.push((start_of_line..start_of_line, newline));
3350
3351 rows_inserted += 1;
3352 rows.push(row + rows_inserted);
3353 }
3354
3355 self.transact(window, cx, |editor, window, cx| {
3356 editor.edit(edits, cx);
3357
3358 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3359 let mut index = 0;
3360 s.move_cursors_with(|map, _, _| {
3361 let row = rows[index];
3362 index += 1;
3363
3364 let point = Point::new(row, 0);
3365 let boundary = map.next_line_boundary(point).1;
3366 let clipped = map.clip_point(boundary, Bias::Left);
3367
3368 (clipped, SelectionGoal::None)
3369 });
3370 });
3371
3372 let mut indent_edits = Vec::new();
3373 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3374 for row in rows {
3375 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3376 for (row, indent) in indents {
3377 if indent.len == 0 {
3378 continue;
3379 }
3380
3381 let text = match indent.kind {
3382 IndentKind::Space => " ".repeat(indent.len as usize),
3383 IndentKind::Tab => "\t".repeat(indent.len as usize),
3384 };
3385 let point = Point::new(row.0, 0);
3386 indent_edits.push((point..point, text));
3387 }
3388 }
3389 editor.edit(indent_edits, cx);
3390 });
3391 }
3392
3393 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3394 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3395 original_indent_columns: Vec::new(),
3396 });
3397 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3398 }
3399
3400 fn insert_with_autoindent_mode(
3401 &mut self,
3402 text: &str,
3403 autoindent_mode: Option<AutoindentMode>,
3404 window: &mut Window,
3405 cx: &mut Context<Self>,
3406 ) {
3407 if self.read_only(cx) {
3408 return;
3409 }
3410
3411 let text: Arc<str> = text.into();
3412 self.transact(window, cx, |this, window, cx| {
3413 let old_selections = this.selections.all_adjusted(cx);
3414 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3415 let anchors = {
3416 let snapshot = buffer.read(cx);
3417 old_selections
3418 .iter()
3419 .map(|s| {
3420 let anchor = snapshot.anchor_after(s.head());
3421 s.map(|_| anchor)
3422 })
3423 .collect::<Vec<_>>()
3424 };
3425 buffer.edit(
3426 old_selections
3427 .iter()
3428 .map(|s| (s.start..s.end, text.clone())),
3429 autoindent_mode,
3430 cx,
3431 );
3432 anchors
3433 });
3434
3435 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3436 s.select_anchors(selection_anchors);
3437 });
3438
3439 cx.notify();
3440 });
3441 }
3442
3443 fn trigger_completion_on_input(
3444 &mut self,
3445 text: &str,
3446 trigger_in_words: bool,
3447 window: &mut Window,
3448 cx: &mut Context<Self>,
3449 ) {
3450 if self.is_completion_trigger(text, trigger_in_words, cx) {
3451 self.show_completions(
3452 &ShowCompletions {
3453 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3454 },
3455 window,
3456 cx,
3457 );
3458 } else {
3459 self.hide_context_menu(window, cx);
3460 }
3461 }
3462
3463 fn is_completion_trigger(
3464 &self,
3465 text: &str,
3466 trigger_in_words: bool,
3467 cx: &mut Context<Self>,
3468 ) -> bool {
3469 let position = self.selections.newest_anchor().head();
3470 let multibuffer = self.buffer.read(cx);
3471 let Some(buffer) = position
3472 .buffer_id
3473 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3474 else {
3475 return false;
3476 };
3477
3478 if let Some(completion_provider) = &self.completion_provider {
3479 completion_provider.is_completion_trigger(
3480 &buffer,
3481 position.text_anchor,
3482 text,
3483 trigger_in_words,
3484 cx,
3485 )
3486 } else {
3487 false
3488 }
3489 }
3490
3491 /// If any empty selections is touching the start of its innermost containing autoclose
3492 /// region, expand it to select the brackets.
3493 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3494 let selections = self.selections.all::<usize>(cx);
3495 let buffer = self.buffer.read(cx).read(cx);
3496 let new_selections = self
3497 .selections_with_autoclose_regions(selections, &buffer)
3498 .map(|(mut selection, region)| {
3499 if !selection.is_empty() {
3500 return selection;
3501 }
3502
3503 if let Some(region) = region {
3504 let mut range = region.range.to_offset(&buffer);
3505 if selection.start == range.start && range.start >= region.pair.start.len() {
3506 range.start -= region.pair.start.len();
3507 if buffer.contains_str_at(range.start, ®ion.pair.start)
3508 && buffer.contains_str_at(range.end, ®ion.pair.end)
3509 {
3510 range.end += region.pair.end.len();
3511 selection.start = range.start;
3512 selection.end = range.end;
3513
3514 return selection;
3515 }
3516 }
3517 }
3518
3519 let always_treat_brackets_as_autoclosed = buffer
3520 .settings_at(selection.start, cx)
3521 .always_treat_brackets_as_autoclosed;
3522
3523 if !always_treat_brackets_as_autoclosed {
3524 return selection;
3525 }
3526
3527 if let Some(scope) = buffer.language_scope_at(selection.start) {
3528 for (pair, enabled) in scope.brackets() {
3529 if !enabled || !pair.close {
3530 continue;
3531 }
3532
3533 if buffer.contains_str_at(selection.start, &pair.end) {
3534 let pair_start_len = pair.start.len();
3535 if buffer.contains_str_at(
3536 selection.start.saturating_sub(pair_start_len),
3537 &pair.start,
3538 ) {
3539 selection.start -= pair_start_len;
3540 selection.end += pair.end.len();
3541
3542 return selection;
3543 }
3544 }
3545 }
3546 }
3547
3548 selection
3549 })
3550 .collect();
3551
3552 drop(buffer);
3553 self.change_selections(None, window, cx, |selections| {
3554 selections.select(new_selections)
3555 });
3556 }
3557
3558 /// Iterate the given selections, and for each one, find the smallest surrounding
3559 /// autoclose region. This uses the ordering of the selections and the autoclose
3560 /// regions to avoid repeated comparisons.
3561 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3562 &'a self,
3563 selections: impl IntoIterator<Item = Selection<D>>,
3564 buffer: &'a MultiBufferSnapshot,
3565 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3566 let mut i = 0;
3567 let mut regions = self.autoclose_regions.as_slice();
3568 selections.into_iter().map(move |selection| {
3569 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3570
3571 let mut enclosing = None;
3572 while let Some(pair_state) = regions.get(i) {
3573 if pair_state.range.end.to_offset(buffer) < range.start {
3574 regions = ®ions[i + 1..];
3575 i = 0;
3576 } else if pair_state.range.start.to_offset(buffer) > range.end {
3577 break;
3578 } else {
3579 if pair_state.selection_id == selection.id {
3580 enclosing = Some(pair_state);
3581 }
3582 i += 1;
3583 }
3584 }
3585
3586 (selection, enclosing)
3587 })
3588 }
3589
3590 /// Remove any autoclose regions that no longer contain their selection.
3591 fn invalidate_autoclose_regions(
3592 &mut self,
3593 mut selections: &[Selection<Anchor>],
3594 buffer: &MultiBufferSnapshot,
3595 ) {
3596 self.autoclose_regions.retain(|state| {
3597 let mut i = 0;
3598 while let Some(selection) = selections.get(i) {
3599 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3600 selections = &selections[1..];
3601 continue;
3602 }
3603 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3604 break;
3605 }
3606 if selection.id == state.selection_id {
3607 return true;
3608 } else {
3609 i += 1;
3610 }
3611 }
3612 false
3613 });
3614 }
3615
3616 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3617 let offset = position.to_offset(buffer);
3618 let (word_range, kind) = buffer.surrounding_word(offset, true);
3619 if offset > word_range.start && kind == Some(CharKind::Word) {
3620 Some(
3621 buffer
3622 .text_for_range(word_range.start..offset)
3623 .collect::<String>(),
3624 )
3625 } else {
3626 None
3627 }
3628 }
3629
3630 pub fn toggle_inlay_hints(
3631 &mut self,
3632 _: &ToggleInlayHints,
3633 _: &mut Window,
3634 cx: &mut Context<Self>,
3635 ) {
3636 self.refresh_inlay_hints(
3637 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3638 cx,
3639 );
3640 }
3641
3642 pub fn inlay_hints_enabled(&self) -> bool {
3643 self.inlay_hint_cache.enabled
3644 }
3645
3646 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3647 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3648 return;
3649 }
3650
3651 let reason_description = reason.description();
3652 let ignore_debounce = matches!(
3653 reason,
3654 InlayHintRefreshReason::SettingsChange(_)
3655 | InlayHintRefreshReason::Toggle(_)
3656 | InlayHintRefreshReason::ExcerptsRemoved(_)
3657 );
3658 let (invalidate_cache, required_languages) = match reason {
3659 InlayHintRefreshReason::Toggle(enabled) => {
3660 self.inlay_hint_cache.enabled = enabled;
3661 if enabled {
3662 (InvalidationStrategy::RefreshRequested, None)
3663 } else {
3664 self.inlay_hint_cache.clear();
3665 self.splice_inlays(
3666 &self
3667 .visible_inlay_hints(cx)
3668 .iter()
3669 .map(|inlay| inlay.id)
3670 .collect::<Vec<InlayId>>(),
3671 Vec::new(),
3672 cx,
3673 );
3674 return;
3675 }
3676 }
3677 InlayHintRefreshReason::SettingsChange(new_settings) => {
3678 match self.inlay_hint_cache.update_settings(
3679 &self.buffer,
3680 new_settings,
3681 self.visible_inlay_hints(cx),
3682 cx,
3683 ) {
3684 ControlFlow::Break(Some(InlaySplice {
3685 to_remove,
3686 to_insert,
3687 })) => {
3688 self.splice_inlays(&to_remove, to_insert, cx);
3689 return;
3690 }
3691 ControlFlow::Break(None) => return,
3692 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3693 }
3694 }
3695 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3696 if let Some(InlaySplice {
3697 to_remove,
3698 to_insert,
3699 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3700 {
3701 self.splice_inlays(&to_remove, to_insert, cx);
3702 }
3703 return;
3704 }
3705 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3706 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3707 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3708 }
3709 InlayHintRefreshReason::RefreshRequested => {
3710 (InvalidationStrategy::RefreshRequested, None)
3711 }
3712 };
3713
3714 if let Some(InlaySplice {
3715 to_remove,
3716 to_insert,
3717 }) = self.inlay_hint_cache.spawn_hint_refresh(
3718 reason_description,
3719 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3720 invalidate_cache,
3721 ignore_debounce,
3722 cx,
3723 ) {
3724 self.splice_inlays(&to_remove, to_insert, cx);
3725 }
3726 }
3727
3728 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3729 self.display_map
3730 .read(cx)
3731 .current_inlays()
3732 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3733 .cloned()
3734 .collect()
3735 }
3736
3737 pub fn excerpts_for_inlay_hints_query(
3738 &self,
3739 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3740 cx: &mut Context<Editor>,
3741 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3742 let Some(project) = self.project.as_ref() else {
3743 return HashMap::default();
3744 };
3745 let project = project.read(cx);
3746 let multi_buffer = self.buffer().read(cx);
3747 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3748 let multi_buffer_visible_start = self
3749 .scroll_manager
3750 .anchor()
3751 .anchor
3752 .to_point(&multi_buffer_snapshot);
3753 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3754 multi_buffer_visible_start
3755 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3756 Bias::Left,
3757 );
3758 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3759 multi_buffer_snapshot
3760 .range_to_buffer_ranges(multi_buffer_visible_range)
3761 .into_iter()
3762 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3763 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3764 let buffer_file = project::File::from_dyn(buffer.file())?;
3765 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3766 let worktree_entry = buffer_worktree
3767 .read(cx)
3768 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3769 if worktree_entry.is_ignored {
3770 return None;
3771 }
3772
3773 let language = buffer.language()?;
3774 if let Some(restrict_to_languages) = restrict_to_languages {
3775 if !restrict_to_languages.contains(language) {
3776 return None;
3777 }
3778 }
3779 Some((
3780 excerpt_id,
3781 (
3782 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3783 buffer.version().clone(),
3784 excerpt_visible_range,
3785 ),
3786 ))
3787 })
3788 .collect()
3789 }
3790
3791 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3792 TextLayoutDetails {
3793 text_system: window.text_system().clone(),
3794 editor_style: self.style.clone().unwrap(),
3795 rem_size: window.rem_size(),
3796 scroll_anchor: self.scroll_manager.anchor(),
3797 visible_rows: self.visible_line_count(),
3798 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3799 }
3800 }
3801
3802 pub fn splice_inlays(
3803 &self,
3804 to_remove: &[InlayId],
3805 to_insert: Vec<Inlay>,
3806 cx: &mut Context<Self>,
3807 ) {
3808 self.display_map.update(cx, |display_map, cx| {
3809 display_map.splice_inlays(to_remove, to_insert, cx)
3810 });
3811 cx.notify();
3812 }
3813
3814 fn trigger_on_type_formatting(
3815 &self,
3816 input: String,
3817 window: &mut Window,
3818 cx: &mut Context<Self>,
3819 ) -> Option<Task<Result<()>>> {
3820 if input.len() != 1 {
3821 return None;
3822 }
3823
3824 let project = self.project.as_ref()?;
3825 let position = self.selections.newest_anchor().head();
3826 let (buffer, buffer_position) = self
3827 .buffer
3828 .read(cx)
3829 .text_anchor_for_position(position, cx)?;
3830
3831 let settings = language_settings::language_settings(
3832 buffer
3833 .read(cx)
3834 .language_at(buffer_position)
3835 .map(|l| l.name()),
3836 buffer.read(cx).file(),
3837 cx,
3838 );
3839 if !settings.use_on_type_format {
3840 return None;
3841 }
3842
3843 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3844 // hence we do LSP request & edit on host side only — add formats to host's history.
3845 let push_to_lsp_host_history = true;
3846 // If this is not the host, append its history with new edits.
3847 let push_to_client_history = project.read(cx).is_via_collab();
3848
3849 let on_type_formatting = project.update(cx, |project, cx| {
3850 project.on_type_format(
3851 buffer.clone(),
3852 buffer_position,
3853 input,
3854 push_to_lsp_host_history,
3855 cx,
3856 )
3857 });
3858 Some(cx.spawn_in(window, |editor, mut cx| async move {
3859 if let Some(transaction) = on_type_formatting.await? {
3860 if push_to_client_history {
3861 buffer
3862 .update(&mut cx, |buffer, _| {
3863 buffer.push_transaction(transaction, Instant::now());
3864 })
3865 .ok();
3866 }
3867 editor.update(&mut cx, |editor, cx| {
3868 editor.refresh_document_highlights(cx);
3869 })?;
3870 }
3871 Ok(())
3872 }))
3873 }
3874
3875 pub fn show_completions(
3876 &mut self,
3877 options: &ShowCompletions,
3878 window: &mut Window,
3879 cx: &mut Context<Self>,
3880 ) {
3881 if self.pending_rename.is_some() {
3882 return;
3883 }
3884
3885 let Some(provider) = self.completion_provider.as_ref() else {
3886 return;
3887 };
3888
3889 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3890 return;
3891 }
3892
3893 let position = self.selections.newest_anchor().head();
3894 if position.diff_base_anchor.is_some() {
3895 return;
3896 }
3897 let (buffer, buffer_position) =
3898 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3899 output
3900 } else {
3901 return;
3902 };
3903 let show_completion_documentation = buffer
3904 .read(cx)
3905 .snapshot()
3906 .settings_at(buffer_position, cx)
3907 .show_completion_documentation;
3908
3909 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3910
3911 let trigger_kind = match &options.trigger {
3912 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3913 CompletionTriggerKind::TRIGGER_CHARACTER
3914 }
3915 _ => CompletionTriggerKind::INVOKED,
3916 };
3917 let completion_context = CompletionContext {
3918 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3919 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3920 Some(String::from(trigger))
3921 } else {
3922 None
3923 }
3924 }),
3925 trigger_kind,
3926 };
3927 let completions =
3928 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3929 let sort_completions = provider.sort_completions();
3930
3931 let id = post_inc(&mut self.next_completion_id);
3932 let task = cx.spawn_in(window, |editor, mut cx| {
3933 async move {
3934 editor.update(&mut cx, |this, _| {
3935 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3936 })?;
3937 let completions = completions.await.log_err();
3938 let menu = if let Some(completions) = completions {
3939 let mut menu = CompletionsMenu::new(
3940 id,
3941 sort_completions,
3942 show_completion_documentation,
3943 position,
3944 buffer.clone(),
3945 completions.into(),
3946 );
3947
3948 menu.filter(query.as_deref(), cx.background_executor().clone())
3949 .await;
3950
3951 menu.visible().then_some(menu)
3952 } else {
3953 None
3954 };
3955
3956 editor.update_in(&mut cx, |editor, window, cx| {
3957 match editor.context_menu.borrow().as_ref() {
3958 None => {}
3959 Some(CodeContextMenu::Completions(prev_menu)) => {
3960 if prev_menu.id > id {
3961 return;
3962 }
3963 }
3964 _ => return,
3965 }
3966
3967 if editor.focus_handle.is_focused(window) && menu.is_some() {
3968 let mut menu = menu.unwrap();
3969 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3970
3971 *editor.context_menu.borrow_mut() =
3972 Some(CodeContextMenu::Completions(menu));
3973
3974 if editor.show_edit_predictions_in_menu() {
3975 editor.update_visible_inline_completion(window, cx);
3976 } else {
3977 editor.discard_inline_completion(false, cx);
3978 }
3979
3980 cx.notify();
3981 } else if editor.completion_tasks.len() <= 1 {
3982 // If there are no more completion tasks and the last menu was
3983 // empty, we should hide it.
3984 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3985 // If it was already hidden and we don't show inline
3986 // completions in the menu, we should also show the
3987 // inline-completion when available.
3988 if was_hidden && editor.show_edit_predictions_in_menu() {
3989 editor.update_visible_inline_completion(window, cx);
3990 }
3991 }
3992 })?;
3993
3994 Ok::<_, anyhow::Error>(())
3995 }
3996 .log_err()
3997 });
3998
3999 self.completion_tasks.push((id, task));
4000 }
4001
4002 pub fn confirm_completion(
4003 &mut self,
4004 action: &ConfirmCompletion,
4005 window: &mut Window,
4006 cx: &mut Context<Self>,
4007 ) -> Option<Task<Result<()>>> {
4008 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4009 }
4010
4011 pub fn compose_completion(
4012 &mut self,
4013 action: &ComposeCompletion,
4014 window: &mut Window,
4015 cx: &mut Context<Self>,
4016 ) -> Option<Task<Result<()>>> {
4017 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4018 }
4019
4020 fn do_completion(
4021 &mut self,
4022 item_ix: Option<usize>,
4023 intent: CompletionIntent,
4024 window: &mut Window,
4025 cx: &mut Context<Editor>,
4026 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4027 use language::ToOffset as _;
4028
4029 let completions_menu =
4030 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4031 menu
4032 } else {
4033 return None;
4034 };
4035
4036 let entries = completions_menu.entries.borrow();
4037 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4038 if self.show_edit_predictions_in_menu() {
4039 self.discard_inline_completion(true, cx);
4040 }
4041 let candidate_id = mat.candidate_id;
4042 drop(entries);
4043
4044 let buffer_handle = completions_menu.buffer;
4045 let completion = completions_menu
4046 .completions
4047 .borrow()
4048 .get(candidate_id)?
4049 .clone();
4050 cx.stop_propagation();
4051
4052 let snippet;
4053 let text;
4054
4055 if completion.is_snippet() {
4056 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4057 text = snippet.as_ref().unwrap().text.clone();
4058 } else {
4059 snippet = None;
4060 text = completion.new_text.clone();
4061 };
4062 let selections = self.selections.all::<usize>(cx);
4063 let buffer = buffer_handle.read(cx);
4064 let old_range = completion.old_range.to_offset(buffer);
4065 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4066
4067 let newest_selection = self.selections.newest_anchor();
4068 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4069 return None;
4070 }
4071
4072 let lookbehind = newest_selection
4073 .start
4074 .text_anchor
4075 .to_offset(buffer)
4076 .saturating_sub(old_range.start);
4077 let lookahead = old_range
4078 .end
4079 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4080 let mut common_prefix_len = old_text
4081 .bytes()
4082 .zip(text.bytes())
4083 .take_while(|(a, b)| a == b)
4084 .count();
4085
4086 let snapshot = self.buffer.read(cx).snapshot(cx);
4087 let mut range_to_replace: Option<Range<isize>> = None;
4088 let mut ranges = Vec::new();
4089 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4090 for selection in &selections {
4091 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4092 let start = selection.start.saturating_sub(lookbehind);
4093 let end = selection.end + lookahead;
4094 if selection.id == newest_selection.id {
4095 range_to_replace = Some(
4096 ((start + common_prefix_len) as isize - selection.start as isize)
4097 ..(end as isize - selection.start as isize),
4098 );
4099 }
4100 ranges.push(start + common_prefix_len..end);
4101 } else {
4102 common_prefix_len = 0;
4103 ranges.clear();
4104 ranges.extend(selections.iter().map(|s| {
4105 if s.id == newest_selection.id {
4106 range_to_replace = Some(
4107 old_range.start.to_offset_utf16(&snapshot).0 as isize
4108 - selection.start as isize
4109 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4110 - selection.start as isize,
4111 );
4112 old_range.clone()
4113 } else {
4114 s.start..s.end
4115 }
4116 }));
4117 break;
4118 }
4119 if !self.linked_edit_ranges.is_empty() {
4120 let start_anchor = snapshot.anchor_before(selection.head());
4121 let end_anchor = snapshot.anchor_after(selection.tail());
4122 if let Some(ranges) = self
4123 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4124 {
4125 for (buffer, edits) in ranges {
4126 linked_edits.entry(buffer.clone()).or_default().extend(
4127 edits
4128 .into_iter()
4129 .map(|range| (range, text[common_prefix_len..].to_owned())),
4130 );
4131 }
4132 }
4133 }
4134 }
4135 let text = &text[common_prefix_len..];
4136
4137 cx.emit(EditorEvent::InputHandled {
4138 utf16_range_to_replace: range_to_replace,
4139 text: text.into(),
4140 });
4141
4142 self.transact(window, cx, |this, window, cx| {
4143 if let Some(mut snippet) = snippet {
4144 snippet.text = text.to_string();
4145 for tabstop in snippet
4146 .tabstops
4147 .iter_mut()
4148 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4149 {
4150 tabstop.start -= common_prefix_len as isize;
4151 tabstop.end -= common_prefix_len as isize;
4152 }
4153
4154 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4155 } else {
4156 this.buffer.update(cx, |buffer, cx| {
4157 buffer.edit(
4158 ranges.iter().map(|range| (range.clone(), text)),
4159 this.autoindent_mode.clone(),
4160 cx,
4161 );
4162 });
4163 }
4164 for (buffer, edits) in linked_edits {
4165 buffer.update(cx, |buffer, cx| {
4166 let snapshot = buffer.snapshot();
4167 let edits = edits
4168 .into_iter()
4169 .map(|(range, text)| {
4170 use text::ToPoint as TP;
4171 let end_point = TP::to_point(&range.end, &snapshot);
4172 let start_point = TP::to_point(&range.start, &snapshot);
4173 (start_point..end_point, text)
4174 })
4175 .sorted_by_key(|(range, _)| range.start)
4176 .collect::<Vec<_>>();
4177 buffer.edit(edits, None, cx);
4178 })
4179 }
4180
4181 this.refresh_inline_completion(true, false, window, cx);
4182 });
4183
4184 let show_new_completions_on_confirm = completion
4185 .confirm
4186 .as_ref()
4187 .map_or(false, |confirm| confirm(intent, window, cx));
4188 if show_new_completions_on_confirm {
4189 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4190 }
4191
4192 let provider = self.completion_provider.as_ref()?;
4193 drop(completion);
4194 let apply_edits = provider.apply_additional_edits_for_completion(
4195 buffer_handle,
4196 completions_menu.completions.clone(),
4197 candidate_id,
4198 true,
4199 cx,
4200 );
4201
4202 let editor_settings = EditorSettings::get_global(cx);
4203 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4204 // After the code completion is finished, users often want to know what signatures are needed.
4205 // so we should automatically call signature_help
4206 self.show_signature_help(&ShowSignatureHelp, window, cx);
4207 }
4208
4209 Some(cx.foreground_executor().spawn(async move {
4210 apply_edits.await?;
4211 Ok(())
4212 }))
4213 }
4214
4215 pub fn toggle_code_actions(
4216 &mut self,
4217 action: &ToggleCodeActions,
4218 window: &mut Window,
4219 cx: &mut Context<Self>,
4220 ) {
4221 let mut context_menu = self.context_menu.borrow_mut();
4222 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4223 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4224 // Toggle if we're selecting the same one
4225 *context_menu = None;
4226 cx.notify();
4227 return;
4228 } else {
4229 // Otherwise, clear it and start a new one
4230 *context_menu = None;
4231 cx.notify();
4232 }
4233 }
4234 drop(context_menu);
4235 let snapshot = self.snapshot(window, cx);
4236 let deployed_from_indicator = action.deployed_from_indicator;
4237 let mut task = self.code_actions_task.take();
4238 let action = action.clone();
4239 cx.spawn_in(window, |editor, mut cx| async move {
4240 while let Some(prev_task) = task {
4241 prev_task.await.log_err();
4242 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4243 }
4244
4245 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4246 if editor.focus_handle.is_focused(window) {
4247 let multibuffer_point = action
4248 .deployed_from_indicator
4249 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4250 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4251 let (buffer, buffer_row) = snapshot
4252 .buffer_snapshot
4253 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4254 .and_then(|(buffer_snapshot, range)| {
4255 editor
4256 .buffer
4257 .read(cx)
4258 .buffer(buffer_snapshot.remote_id())
4259 .map(|buffer| (buffer, range.start.row))
4260 })?;
4261 let (_, code_actions) = editor
4262 .available_code_actions
4263 .clone()
4264 .and_then(|(location, code_actions)| {
4265 let snapshot = location.buffer.read(cx).snapshot();
4266 let point_range = location.range.to_point(&snapshot);
4267 let point_range = point_range.start.row..=point_range.end.row;
4268 if point_range.contains(&buffer_row) {
4269 Some((location, code_actions))
4270 } else {
4271 None
4272 }
4273 })
4274 .unzip();
4275 let buffer_id = buffer.read(cx).remote_id();
4276 let tasks = editor
4277 .tasks
4278 .get(&(buffer_id, buffer_row))
4279 .map(|t| Arc::new(t.to_owned()));
4280 if tasks.is_none() && code_actions.is_none() {
4281 return None;
4282 }
4283
4284 editor.completion_tasks.clear();
4285 editor.discard_inline_completion(false, cx);
4286 let task_context =
4287 tasks
4288 .as_ref()
4289 .zip(editor.project.clone())
4290 .map(|(tasks, project)| {
4291 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4292 });
4293
4294 Some(cx.spawn_in(window, |editor, mut cx| async move {
4295 let task_context = match task_context {
4296 Some(task_context) => task_context.await,
4297 None => None,
4298 };
4299 let resolved_tasks =
4300 tasks.zip(task_context).map(|(tasks, task_context)| {
4301 Rc::new(ResolvedTasks {
4302 templates: tasks.resolve(&task_context).collect(),
4303 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4304 multibuffer_point.row,
4305 tasks.column,
4306 )),
4307 })
4308 });
4309 let spawn_straight_away = resolved_tasks
4310 .as_ref()
4311 .map_or(false, |tasks| tasks.templates.len() == 1)
4312 && code_actions
4313 .as_ref()
4314 .map_or(true, |actions| actions.is_empty());
4315 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4316 *editor.context_menu.borrow_mut() =
4317 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4318 buffer,
4319 actions: CodeActionContents {
4320 tasks: resolved_tasks,
4321 actions: code_actions,
4322 },
4323 selected_item: Default::default(),
4324 scroll_handle: UniformListScrollHandle::default(),
4325 deployed_from_indicator,
4326 }));
4327 if spawn_straight_away {
4328 if let Some(task) = editor.confirm_code_action(
4329 &ConfirmCodeAction { item_ix: Some(0) },
4330 window,
4331 cx,
4332 ) {
4333 cx.notify();
4334 return task;
4335 }
4336 }
4337 cx.notify();
4338 Task::ready(Ok(()))
4339 }) {
4340 task.await
4341 } else {
4342 Ok(())
4343 }
4344 }))
4345 } else {
4346 Some(Task::ready(Ok(())))
4347 }
4348 })?;
4349 if let Some(task) = spawned_test_task {
4350 task.await?;
4351 }
4352
4353 Ok::<_, anyhow::Error>(())
4354 })
4355 .detach_and_log_err(cx);
4356 }
4357
4358 pub fn confirm_code_action(
4359 &mut self,
4360 action: &ConfirmCodeAction,
4361 window: &mut Window,
4362 cx: &mut Context<Self>,
4363 ) -> Option<Task<Result<()>>> {
4364 let actions_menu =
4365 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4366 menu
4367 } else {
4368 return None;
4369 };
4370 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4371 let action = actions_menu.actions.get(action_ix)?;
4372 let title = action.label();
4373 let buffer = actions_menu.buffer;
4374 let workspace = self.workspace()?;
4375
4376 match action {
4377 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4378 workspace.update(cx, |workspace, cx| {
4379 workspace::tasks::schedule_resolved_task(
4380 workspace,
4381 task_source_kind,
4382 resolved_task,
4383 false,
4384 cx,
4385 );
4386
4387 Some(Task::ready(Ok(())))
4388 })
4389 }
4390 CodeActionsItem::CodeAction {
4391 excerpt_id,
4392 action,
4393 provider,
4394 } => {
4395 let apply_code_action =
4396 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4397 let workspace = workspace.downgrade();
4398 Some(cx.spawn_in(window, |editor, cx| async move {
4399 let project_transaction = apply_code_action.await?;
4400 Self::open_project_transaction(
4401 &editor,
4402 workspace,
4403 project_transaction,
4404 title,
4405 cx,
4406 )
4407 .await
4408 }))
4409 }
4410 }
4411 }
4412
4413 pub async fn open_project_transaction(
4414 this: &WeakEntity<Editor>,
4415 workspace: WeakEntity<Workspace>,
4416 transaction: ProjectTransaction,
4417 title: String,
4418 mut cx: AsyncWindowContext,
4419 ) -> Result<()> {
4420 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4421 cx.update(|_, cx| {
4422 entries.sort_unstable_by_key(|(buffer, _)| {
4423 buffer.read(cx).file().map(|f| f.path().clone())
4424 });
4425 })?;
4426
4427 // If the project transaction's edits are all contained within this editor, then
4428 // avoid opening a new editor to display them.
4429
4430 if let Some((buffer, transaction)) = entries.first() {
4431 if entries.len() == 1 {
4432 let excerpt = this.update(&mut cx, |editor, cx| {
4433 editor
4434 .buffer()
4435 .read(cx)
4436 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4437 })?;
4438 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4439 if excerpted_buffer == *buffer {
4440 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4441 let excerpt_range = excerpt_range.to_offset(buffer);
4442 buffer
4443 .edited_ranges_for_transaction::<usize>(transaction)
4444 .all(|range| {
4445 excerpt_range.start <= range.start
4446 && excerpt_range.end >= range.end
4447 })
4448 })?;
4449
4450 if all_edits_within_excerpt {
4451 return Ok(());
4452 }
4453 }
4454 }
4455 }
4456 } else {
4457 return Ok(());
4458 }
4459
4460 let mut ranges_to_highlight = Vec::new();
4461 let excerpt_buffer = cx.new(|cx| {
4462 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4463 for (buffer_handle, transaction) in &entries {
4464 let buffer = buffer_handle.read(cx);
4465 ranges_to_highlight.extend(
4466 multibuffer.push_excerpts_with_context_lines(
4467 buffer_handle.clone(),
4468 buffer
4469 .edited_ranges_for_transaction::<usize>(transaction)
4470 .collect(),
4471 DEFAULT_MULTIBUFFER_CONTEXT,
4472 cx,
4473 ),
4474 );
4475 }
4476 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4477 multibuffer
4478 })?;
4479
4480 workspace.update_in(&mut cx, |workspace, window, cx| {
4481 let project = workspace.project().clone();
4482 let editor = cx
4483 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4484 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4485 editor.update(cx, |editor, cx| {
4486 editor.highlight_background::<Self>(
4487 &ranges_to_highlight,
4488 |theme| theme.editor_highlighted_line_background,
4489 cx,
4490 );
4491 });
4492 })?;
4493
4494 Ok(())
4495 }
4496
4497 pub fn clear_code_action_providers(&mut self) {
4498 self.code_action_providers.clear();
4499 self.available_code_actions.take();
4500 }
4501
4502 pub fn add_code_action_provider(
4503 &mut self,
4504 provider: Rc<dyn CodeActionProvider>,
4505 window: &mut Window,
4506 cx: &mut Context<Self>,
4507 ) {
4508 if self
4509 .code_action_providers
4510 .iter()
4511 .any(|existing_provider| existing_provider.id() == provider.id())
4512 {
4513 return;
4514 }
4515
4516 self.code_action_providers.push(provider);
4517 self.refresh_code_actions(window, cx);
4518 }
4519
4520 pub fn remove_code_action_provider(
4521 &mut self,
4522 id: Arc<str>,
4523 window: &mut Window,
4524 cx: &mut Context<Self>,
4525 ) {
4526 self.code_action_providers
4527 .retain(|provider| provider.id() != id);
4528 self.refresh_code_actions(window, cx);
4529 }
4530
4531 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4532 let buffer = self.buffer.read(cx);
4533 let newest_selection = self.selections.newest_anchor().clone();
4534 if newest_selection.head().diff_base_anchor.is_some() {
4535 return None;
4536 }
4537 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4538 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4539 if start_buffer != end_buffer {
4540 return None;
4541 }
4542
4543 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4544 cx.background_executor()
4545 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4546 .await;
4547
4548 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4549 let providers = this.code_action_providers.clone();
4550 let tasks = this
4551 .code_action_providers
4552 .iter()
4553 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4554 .collect::<Vec<_>>();
4555 (providers, tasks)
4556 })?;
4557
4558 let mut actions = Vec::new();
4559 for (provider, provider_actions) in
4560 providers.into_iter().zip(future::join_all(tasks).await)
4561 {
4562 if let Some(provider_actions) = provider_actions.log_err() {
4563 actions.extend(provider_actions.into_iter().map(|action| {
4564 AvailableCodeAction {
4565 excerpt_id: newest_selection.start.excerpt_id,
4566 action,
4567 provider: provider.clone(),
4568 }
4569 }));
4570 }
4571 }
4572
4573 this.update(&mut cx, |this, cx| {
4574 this.available_code_actions = if actions.is_empty() {
4575 None
4576 } else {
4577 Some((
4578 Location {
4579 buffer: start_buffer,
4580 range: start..end,
4581 },
4582 actions.into(),
4583 ))
4584 };
4585 cx.notify();
4586 })
4587 }));
4588 None
4589 }
4590
4591 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4592 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4593 self.show_git_blame_inline = false;
4594
4595 self.show_git_blame_inline_delay_task =
4596 Some(cx.spawn_in(window, |this, mut cx| async move {
4597 cx.background_executor().timer(delay).await;
4598
4599 this.update(&mut cx, |this, cx| {
4600 this.show_git_blame_inline = true;
4601 cx.notify();
4602 })
4603 .log_err();
4604 }));
4605 }
4606 }
4607
4608 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4609 if self.pending_rename.is_some() {
4610 return None;
4611 }
4612
4613 let provider = self.semantics_provider.clone()?;
4614 let buffer = self.buffer.read(cx);
4615 let newest_selection = self.selections.newest_anchor().clone();
4616 let cursor_position = newest_selection.head();
4617 let (cursor_buffer, cursor_buffer_position) =
4618 buffer.text_anchor_for_position(cursor_position, cx)?;
4619 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4620 if cursor_buffer != tail_buffer {
4621 return None;
4622 }
4623 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4624 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4625 cx.background_executor()
4626 .timer(Duration::from_millis(debounce))
4627 .await;
4628
4629 let highlights = if let Some(highlights) = cx
4630 .update(|cx| {
4631 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4632 })
4633 .ok()
4634 .flatten()
4635 {
4636 highlights.await.log_err()
4637 } else {
4638 None
4639 };
4640
4641 if let Some(highlights) = highlights {
4642 this.update(&mut cx, |this, cx| {
4643 if this.pending_rename.is_some() {
4644 return;
4645 }
4646
4647 let buffer_id = cursor_position.buffer_id;
4648 let buffer = this.buffer.read(cx);
4649 if !buffer
4650 .text_anchor_for_position(cursor_position, cx)
4651 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4652 {
4653 return;
4654 }
4655
4656 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4657 let mut write_ranges = Vec::new();
4658 let mut read_ranges = Vec::new();
4659 for highlight in highlights {
4660 for (excerpt_id, excerpt_range) in
4661 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4662 {
4663 let start = highlight
4664 .range
4665 .start
4666 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4667 let end = highlight
4668 .range
4669 .end
4670 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4671 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4672 continue;
4673 }
4674
4675 let range = Anchor {
4676 buffer_id,
4677 excerpt_id,
4678 text_anchor: start,
4679 diff_base_anchor: None,
4680 }..Anchor {
4681 buffer_id,
4682 excerpt_id,
4683 text_anchor: end,
4684 diff_base_anchor: None,
4685 };
4686 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4687 write_ranges.push(range);
4688 } else {
4689 read_ranges.push(range);
4690 }
4691 }
4692 }
4693
4694 this.highlight_background::<DocumentHighlightRead>(
4695 &read_ranges,
4696 |theme| theme.editor_document_highlight_read_background,
4697 cx,
4698 );
4699 this.highlight_background::<DocumentHighlightWrite>(
4700 &write_ranges,
4701 |theme| theme.editor_document_highlight_write_background,
4702 cx,
4703 );
4704 cx.notify();
4705 })
4706 .log_err();
4707 }
4708 }));
4709 None
4710 }
4711
4712 pub fn refresh_selected_text_highlights(
4713 &mut self,
4714 window: &mut Window,
4715 cx: &mut Context<Editor>,
4716 ) {
4717 self.selection_highlight_task.take();
4718 if !EditorSettings::get_global(cx).selection_highlight {
4719 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4720 return;
4721 }
4722 if self.selections.count() != 1 || self.selections.line_mode {
4723 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4724 return;
4725 }
4726 let selection = self.selections.newest::<Point>(cx);
4727 if selection.is_empty() || selection.start.row != selection.end.row {
4728 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4729 return;
4730 }
4731 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4732 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4733 cx.background_executor()
4734 .timer(Duration::from_millis(debounce))
4735 .await;
4736 let Some(Some(matches_task)) = editor
4737 .update_in(&mut cx, |editor, _, cx| {
4738 if editor.selections.count() != 1 || editor.selections.line_mode {
4739 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4740 return None;
4741 }
4742 let selection = editor.selections.newest::<Point>(cx);
4743 if selection.is_empty() || selection.start.row != selection.end.row {
4744 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4745 return None;
4746 }
4747 let buffer = editor.buffer().read(cx).snapshot(cx);
4748 Some(cx.background_spawn(async move {
4749 let mut ranges = Vec::new();
4750 let query = buffer.text_for_range(selection.range()).collect::<String>();
4751 let selection_anchors = selection.range().to_anchors(&buffer);
4752 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4753 for (search_buffer, search_range, excerpt_id) in
4754 buffer.range_to_buffer_ranges(range)
4755 {
4756 ranges.extend(
4757 project::search::SearchQuery::text(
4758 query.clone(),
4759 false,
4760 false,
4761 false,
4762 Default::default(),
4763 Default::default(),
4764 None,
4765 )
4766 .unwrap()
4767 .search(search_buffer, Some(search_range.clone()))
4768 .await
4769 .into_iter()
4770 .filter_map(
4771 |match_range| {
4772 let start = search_buffer.anchor_after(
4773 search_range.start + match_range.start,
4774 );
4775 let end = search_buffer.anchor_before(
4776 search_range.start + match_range.end,
4777 );
4778 let range = Anchor::range_in_buffer(
4779 excerpt_id,
4780 search_buffer.remote_id(),
4781 start..end,
4782 );
4783 (range != selection_anchors).then_some(range)
4784 },
4785 ),
4786 );
4787 }
4788 }
4789 ranges
4790 }))
4791 })
4792 .log_err()
4793 else {
4794 return;
4795 };
4796 let matches = matches_task.await;
4797 editor
4798 .update_in(&mut cx, |editor, _, cx| {
4799 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4800 if !matches.is_empty() {
4801 editor.highlight_background::<SelectedTextHighlight>(
4802 &matches,
4803 |theme| theme.editor_document_highlight_bracket_background,
4804 cx,
4805 )
4806 }
4807 })
4808 .log_err();
4809 }));
4810 }
4811
4812 pub fn refresh_inline_completion(
4813 &mut self,
4814 debounce: bool,
4815 user_requested: bool,
4816 window: &mut Window,
4817 cx: &mut Context<Self>,
4818 ) -> Option<()> {
4819 let provider = self.edit_prediction_provider()?;
4820 let cursor = self.selections.newest_anchor().head();
4821 let (buffer, cursor_buffer_position) =
4822 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4823
4824 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4825 self.discard_inline_completion(false, cx);
4826 return None;
4827 }
4828
4829 if !user_requested
4830 && (!self.should_show_edit_predictions()
4831 || !self.is_focused(window)
4832 || buffer.read(cx).is_empty())
4833 {
4834 self.discard_inline_completion(false, cx);
4835 return None;
4836 }
4837
4838 self.update_visible_inline_completion(window, cx);
4839 provider.refresh(
4840 self.project.clone(),
4841 buffer,
4842 cursor_buffer_position,
4843 debounce,
4844 cx,
4845 );
4846 Some(())
4847 }
4848
4849 fn show_edit_predictions_in_menu(&self) -> bool {
4850 match self.edit_prediction_settings {
4851 EditPredictionSettings::Disabled => false,
4852 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4853 }
4854 }
4855
4856 pub fn edit_predictions_enabled(&self) -> bool {
4857 match self.edit_prediction_settings {
4858 EditPredictionSettings::Disabled => false,
4859 EditPredictionSettings::Enabled { .. } => true,
4860 }
4861 }
4862
4863 fn edit_prediction_requires_modifier(&self) -> bool {
4864 match self.edit_prediction_settings {
4865 EditPredictionSettings::Disabled => false,
4866 EditPredictionSettings::Enabled {
4867 preview_requires_modifier,
4868 ..
4869 } => preview_requires_modifier,
4870 }
4871 }
4872
4873 fn edit_prediction_settings_at_position(
4874 &self,
4875 buffer: &Entity<Buffer>,
4876 buffer_position: language::Anchor,
4877 cx: &App,
4878 ) -> EditPredictionSettings {
4879 if self.mode != EditorMode::Full
4880 || !self.show_inline_completions_override.unwrap_or(true)
4881 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4882 {
4883 return EditPredictionSettings::Disabled;
4884 }
4885
4886 let buffer = buffer.read(cx);
4887
4888 let file = buffer.file();
4889
4890 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4891 return EditPredictionSettings::Disabled;
4892 };
4893
4894 let by_provider = matches!(
4895 self.menu_inline_completions_policy,
4896 MenuInlineCompletionsPolicy::ByProvider
4897 );
4898
4899 let show_in_menu = by_provider
4900 && self
4901 .edit_prediction_provider
4902 .as_ref()
4903 .map_or(false, |provider| {
4904 provider.provider.show_completions_in_menu()
4905 });
4906
4907 let preview_requires_modifier =
4908 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4909
4910 EditPredictionSettings::Enabled {
4911 show_in_menu,
4912 preview_requires_modifier,
4913 }
4914 }
4915
4916 fn should_show_edit_predictions(&self) -> bool {
4917 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4918 }
4919
4920 pub fn edit_prediction_preview_is_active(&self) -> bool {
4921 matches!(
4922 self.edit_prediction_preview,
4923 EditPredictionPreview::Active { .. }
4924 )
4925 }
4926
4927 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4928 let cursor = self.selections.newest_anchor().head();
4929 if let Some((buffer, cursor_position)) =
4930 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4931 {
4932 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4933 } else {
4934 false
4935 }
4936 }
4937
4938 fn inline_completions_enabled_in_buffer(
4939 &self,
4940 buffer: &Entity<Buffer>,
4941 buffer_position: language::Anchor,
4942 cx: &App,
4943 ) -> bool {
4944 maybe!({
4945 let provider = self.edit_prediction_provider()?;
4946 if !provider.is_enabled(&buffer, buffer_position, cx) {
4947 return Some(false);
4948 }
4949 let buffer = buffer.read(cx);
4950 let Some(file) = buffer.file() else {
4951 return Some(true);
4952 };
4953 let settings = all_language_settings(Some(file), cx);
4954 Some(settings.inline_completions_enabled_for_path(file.path()))
4955 })
4956 .unwrap_or(false)
4957 }
4958
4959 fn cycle_inline_completion(
4960 &mut self,
4961 direction: Direction,
4962 window: &mut Window,
4963 cx: &mut Context<Self>,
4964 ) -> Option<()> {
4965 let provider = self.edit_prediction_provider()?;
4966 let cursor = self.selections.newest_anchor().head();
4967 let (buffer, cursor_buffer_position) =
4968 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4969 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4970 return None;
4971 }
4972
4973 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4974 self.update_visible_inline_completion(window, cx);
4975
4976 Some(())
4977 }
4978
4979 pub fn show_inline_completion(
4980 &mut self,
4981 _: &ShowEditPrediction,
4982 window: &mut Window,
4983 cx: &mut Context<Self>,
4984 ) {
4985 if !self.has_active_inline_completion() {
4986 self.refresh_inline_completion(false, true, window, cx);
4987 return;
4988 }
4989
4990 self.update_visible_inline_completion(window, cx);
4991 }
4992
4993 pub fn display_cursor_names(
4994 &mut self,
4995 _: &DisplayCursorNames,
4996 window: &mut Window,
4997 cx: &mut Context<Self>,
4998 ) {
4999 self.show_cursor_names(window, cx);
5000 }
5001
5002 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5003 self.show_cursor_names = true;
5004 cx.notify();
5005 cx.spawn_in(window, |this, mut cx| async move {
5006 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5007 this.update(&mut cx, |this, cx| {
5008 this.show_cursor_names = false;
5009 cx.notify()
5010 })
5011 .ok()
5012 })
5013 .detach();
5014 }
5015
5016 pub fn next_edit_prediction(
5017 &mut self,
5018 _: &NextEditPrediction,
5019 window: &mut Window,
5020 cx: &mut Context<Self>,
5021 ) {
5022 if self.has_active_inline_completion() {
5023 self.cycle_inline_completion(Direction::Next, window, cx);
5024 } else {
5025 let is_copilot_disabled = self
5026 .refresh_inline_completion(false, true, window, cx)
5027 .is_none();
5028 if is_copilot_disabled {
5029 cx.propagate();
5030 }
5031 }
5032 }
5033
5034 pub fn previous_edit_prediction(
5035 &mut self,
5036 _: &PreviousEditPrediction,
5037 window: &mut Window,
5038 cx: &mut Context<Self>,
5039 ) {
5040 if self.has_active_inline_completion() {
5041 self.cycle_inline_completion(Direction::Prev, window, cx);
5042 } else {
5043 let is_copilot_disabled = self
5044 .refresh_inline_completion(false, true, window, cx)
5045 .is_none();
5046 if is_copilot_disabled {
5047 cx.propagate();
5048 }
5049 }
5050 }
5051
5052 pub fn accept_edit_prediction(
5053 &mut self,
5054 _: &AcceptEditPrediction,
5055 window: &mut Window,
5056 cx: &mut Context<Self>,
5057 ) {
5058 if self.show_edit_predictions_in_menu() {
5059 self.hide_context_menu(window, cx);
5060 }
5061
5062 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5063 return;
5064 };
5065
5066 self.report_inline_completion_event(
5067 active_inline_completion.completion_id.clone(),
5068 true,
5069 cx,
5070 );
5071
5072 match &active_inline_completion.completion {
5073 InlineCompletion::Move { target, .. } => {
5074 let target = *target;
5075
5076 if let Some(position_map) = &self.last_position_map {
5077 if position_map
5078 .visible_row_range
5079 .contains(&target.to_display_point(&position_map.snapshot).row())
5080 || !self.edit_prediction_requires_modifier()
5081 {
5082 self.unfold_ranges(&[target..target], true, false, cx);
5083 // Note that this is also done in vim's handler of the Tab action.
5084 self.change_selections(
5085 Some(Autoscroll::newest()),
5086 window,
5087 cx,
5088 |selections| {
5089 selections.select_anchor_ranges([target..target]);
5090 },
5091 );
5092 self.clear_row_highlights::<EditPredictionPreview>();
5093
5094 self.edit_prediction_preview = EditPredictionPreview::Active {
5095 previous_scroll_position: None,
5096 };
5097 } else {
5098 self.edit_prediction_preview = EditPredictionPreview::Active {
5099 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5100 };
5101 self.highlight_rows::<EditPredictionPreview>(
5102 target..target,
5103 cx.theme().colors().editor_highlighted_line_background,
5104 true,
5105 cx,
5106 );
5107 self.request_autoscroll(Autoscroll::fit(), cx);
5108 }
5109 }
5110 }
5111 InlineCompletion::Edit { edits, .. } => {
5112 if let Some(provider) = self.edit_prediction_provider() {
5113 provider.accept(cx);
5114 }
5115
5116 let snapshot = self.buffer.read(cx).snapshot(cx);
5117 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5118
5119 self.buffer.update(cx, |buffer, cx| {
5120 buffer.edit(edits.iter().cloned(), None, cx)
5121 });
5122
5123 self.change_selections(None, window, cx, |s| {
5124 s.select_anchor_ranges([last_edit_end..last_edit_end])
5125 });
5126
5127 self.update_visible_inline_completion(window, cx);
5128 if self.active_inline_completion.is_none() {
5129 self.refresh_inline_completion(true, true, window, cx);
5130 }
5131
5132 cx.notify();
5133 }
5134 }
5135
5136 self.edit_prediction_requires_modifier_in_leading_space = false;
5137 }
5138
5139 pub fn accept_partial_inline_completion(
5140 &mut self,
5141 _: &AcceptPartialEditPrediction,
5142 window: &mut Window,
5143 cx: &mut Context<Self>,
5144 ) {
5145 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5146 return;
5147 };
5148 if self.selections.count() != 1 {
5149 return;
5150 }
5151
5152 self.report_inline_completion_event(
5153 active_inline_completion.completion_id.clone(),
5154 true,
5155 cx,
5156 );
5157
5158 match &active_inline_completion.completion {
5159 InlineCompletion::Move { target, .. } => {
5160 let target = *target;
5161 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5162 selections.select_anchor_ranges([target..target]);
5163 });
5164 }
5165 InlineCompletion::Edit { edits, .. } => {
5166 // Find an insertion that starts at the cursor position.
5167 let snapshot = self.buffer.read(cx).snapshot(cx);
5168 let cursor_offset = self.selections.newest::<usize>(cx).head();
5169 let insertion = edits.iter().find_map(|(range, text)| {
5170 let range = range.to_offset(&snapshot);
5171 if range.is_empty() && range.start == cursor_offset {
5172 Some(text)
5173 } else {
5174 None
5175 }
5176 });
5177
5178 if let Some(text) = insertion {
5179 let mut partial_completion = text
5180 .chars()
5181 .by_ref()
5182 .take_while(|c| c.is_alphabetic())
5183 .collect::<String>();
5184 if partial_completion.is_empty() {
5185 partial_completion = text
5186 .chars()
5187 .by_ref()
5188 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5189 .collect::<String>();
5190 }
5191
5192 cx.emit(EditorEvent::InputHandled {
5193 utf16_range_to_replace: None,
5194 text: partial_completion.clone().into(),
5195 });
5196
5197 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5198
5199 self.refresh_inline_completion(true, true, window, cx);
5200 cx.notify();
5201 } else {
5202 self.accept_edit_prediction(&Default::default(), window, cx);
5203 }
5204 }
5205 }
5206 }
5207
5208 fn discard_inline_completion(
5209 &mut self,
5210 should_report_inline_completion_event: bool,
5211 cx: &mut Context<Self>,
5212 ) -> bool {
5213 if should_report_inline_completion_event {
5214 let completion_id = self
5215 .active_inline_completion
5216 .as_ref()
5217 .and_then(|active_completion| active_completion.completion_id.clone());
5218
5219 self.report_inline_completion_event(completion_id, false, cx);
5220 }
5221
5222 if let Some(provider) = self.edit_prediction_provider() {
5223 provider.discard(cx);
5224 }
5225
5226 self.take_active_inline_completion(cx)
5227 }
5228
5229 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5230 let Some(provider) = self.edit_prediction_provider() else {
5231 return;
5232 };
5233
5234 let Some((_, buffer, _)) = self
5235 .buffer
5236 .read(cx)
5237 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5238 else {
5239 return;
5240 };
5241
5242 let extension = buffer
5243 .read(cx)
5244 .file()
5245 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5246
5247 let event_type = match accepted {
5248 true => "Edit Prediction Accepted",
5249 false => "Edit Prediction Discarded",
5250 };
5251 telemetry::event!(
5252 event_type,
5253 provider = provider.name(),
5254 prediction_id = id,
5255 suggestion_accepted = accepted,
5256 file_extension = extension,
5257 );
5258 }
5259
5260 pub fn has_active_inline_completion(&self) -> bool {
5261 self.active_inline_completion.is_some()
5262 }
5263
5264 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5265 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5266 return false;
5267 };
5268
5269 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5270 self.clear_highlights::<InlineCompletionHighlight>(cx);
5271 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5272 true
5273 }
5274
5275 /// Returns true when we're displaying the edit prediction popover below the cursor
5276 /// like we are not previewing and the LSP autocomplete menu is visible
5277 /// or we are in `when_holding_modifier` mode.
5278 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5279 if self.edit_prediction_preview_is_active()
5280 || !self.show_edit_predictions_in_menu()
5281 || !self.edit_predictions_enabled()
5282 {
5283 return false;
5284 }
5285
5286 if self.has_visible_completions_menu() {
5287 return true;
5288 }
5289
5290 has_completion && self.edit_prediction_requires_modifier()
5291 }
5292
5293 fn handle_modifiers_changed(
5294 &mut self,
5295 modifiers: Modifiers,
5296 position_map: &PositionMap,
5297 window: &mut Window,
5298 cx: &mut Context<Self>,
5299 ) {
5300 if self.show_edit_predictions_in_menu() {
5301 self.update_edit_prediction_preview(&modifiers, window, cx);
5302 }
5303
5304 self.update_selection_mode(&modifiers, position_map, window, cx);
5305
5306 let mouse_position = window.mouse_position();
5307 if !position_map.text_hitbox.is_hovered(window) {
5308 return;
5309 }
5310
5311 self.update_hovered_link(
5312 position_map.point_for_position(mouse_position),
5313 &position_map.snapshot,
5314 modifiers,
5315 window,
5316 cx,
5317 )
5318 }
5319
5320 fn update_selection_mode(
5321 &mut self,
5322 modifiers: &Modifiers,
5323 position_map: &PositionMap,
5324 window: &mut Window,
5325 cx: &mut Context<Self>,
5326 ) {
5327 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5328 return;
5329 }
5330
5331 let mouse_position = window.mouse_position();
5332 let point_for_position = position_map.point_for_position(mouse_position);
5333 let position = point_for_position.previous_valid;
5334
5335 self.select(
5336 SelectPhase::BeginColumnar {
5337 position,
5338 reset: false,
5339 goal_column: point_for_position.exact_unclipped.column(),
5340 },
5341 window,
5342 cx,
5343 );
5344 }
5345
5346 fn update_edit_prediction_preview(
5347 &mut self,
5348 modifiers: &Modifiers,
5349 window: &mut Window,
5350 cx: &mut Context<Self>,
5351 ) {
5352 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5353 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5354 return;
5355 };
5356
5357 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5358 if matches!(
5359 self.edit_prediction_preview,
5360 EditPredictionPreview::Inactive
5361 ) {
5362 self.edit_prediction_preview = EditPredictionPreview::Active {
5363 previous_scroll_position: None,
5364 };
5365
5366 self.update_visible_inline_completion(window, cx);
5367 cx.notify();
5368 }
5369 } else if let EditPredictionPreview::Active {
5370 previous_scroll_position,
5371 } = self.edit_prediction_preview
5372 {
5373 if let (Some(previous_scroll_position), Some(position_map)) =
5374 (previous_scroll_position, self.last_position_map.as_ref())
5375 {
5376 self.set_scroll_position(
5377 previous_scroll_position
5378 .scroll_position(&position_map.snapshot.display_snapshot),
5379 window,
5380 cx,
5381 );
5382 }
5383
5384 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5385 self.clear_row_highlights::<EditPredictionPreview>();
5386 self.update_visible_inline_completion(window, cx);
5387 cx.notify();
5388 }
5389 }
5390
5391 fn update_visible_inline_completion(
5392 &mut self,
5393 _window: &mut Window,
5394 cx: &mut Context<Self>,
5395 ) -> Option<()> {
5396 let selection = self.selections.newest_anchor();
5397 let cursor = selection.head();
5398 let multibuffer = self.buffer.read(cx).snapshot(cx);
5399 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5400 let excerpt_id = cursor.excerpt_id;
5401
5402 let show_in_menu = self.show_edit_predictions_in_menu();
5403 let completions_menu_has_precedence = !show_in_menu
5404 && (self.context_menu.borrow().is_some()
5405 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5406
5407 if completions_menu_has_precedence
5408 || !offset_selection.is_empty()
5409 || self
5410 .active_inline_completion
5411 .as_ref()
5412 .map_or(false, |completion| {
5413 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5414 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5415 !invalidation_range.contains(&offset_selection.head())
5416 })
5417 {
5418 self.discard_inline_completion(false, cx);
5419 return None;
5420 }
5421
5422 self.take_active_inline_completion(cx);
5423 let Some(provider) = self.edit_prediction_provider() else {
5424 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5425 return None;
5426 };
5427
5428 let (buffer, cursor_buffer_position) =
5429 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5430
5431 self.edit_prediction_settings =
5432 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5433
5434 self.edit_prediction_cursor_on_leading_whitespace =
5435 multibuffer.is_line_whitespace_upto(cursor);
5436
5437 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5438 let edits = inline_completion
5439 .edits
5440 .into_iter()
5441 .flat_map(|(range, new_text)| {
5442 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5443 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5444 Some((start..end, new_text))
5445 })
5446 .collect::<Vec<_>>();
5447 if edits.is_empty() {
5448 return None;
5449 }
5450
5451 let first_edit_start = edits.first().unwrap().0.start;
5452 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5453 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5454
5455 let last_edit_end = edits.last().unwrap().0.end;
5456 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5457 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5458
5459 let cursor_row = cursor.to_point(&multibuffer).row;
5460
5461 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5462
5463 let mut inlay_ids = Vec::new();
5464 let invalidation_row_range;
5465 let move_invalidation_row_range = if cursor_row < edit_start_row {
5466 Some(cursor_row..edit_end_row)
5467 } else if cursor_row > edit_end_row {
5468 Some(edit_start_row..cursor_row)
5469 } else {
5470 None
5471 };
5472 let is_move =
5473 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5474 let completion = if is_move {
5475 invalidation_row_range =
5476 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5477 let target = first_edit_start;
5478 InlineCompletion::Move { target, snapshot }
5479 } else {
5480 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5481 && !self.inline_completions_hidden_for_vim_mode;
5482
5483 if show_completions_in_buffer {
5484 if edits
5485 .iter()
5486 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5487 {
5488 let mut inlays = Vec::new();
5489 for (range, new_text) in &edits {
5490 let inlay = Inlay::inline_completion(
5491 post_inc(&mut self.next_inlay_id),
5492 range.start,
5493 new_text.as_str(),
5494 );
5495 inlay_ids.push(inlay.id);
5496 inlays.push(inlay);
5497 }
5498
5499 self.splice_inlays(&[], inlays, cx);
5500 } else {
5501 let background_color = cx.theme().status().deleted_background;
5502 self.highlight_text::<InlineCompletionHighlight>(
5503 edits.iter().map(|(range, _)| range.clone()).collect(),
5504 HighlightStyle {
5505 background_color: Some(background_color),
5506 ..Default::default()
5507 },
5508 cx,
5509 );
5510 }
5511 }
5512
5513 invalidation_row_range = edit_start_row..edit_end_row;
5514
5515 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5516 if provider.show_tab_accept_marker() {
5517 EditDisplayMode::TabAccept
5518 } else {
5519 EditDisplayMode::Inline
5520 }
5521 } else {
5522 EditDisplayMode::DiffPopover
5523 };
5524
5525 InlineCompletion::Edit {
5526 edits,
5527 edit_preview: inline_completion.edit_preview,
5528 display_mode,
5529 snapshot,
5530 }
5531 };
5532
5533 let invalidation_range = multibuffer
5534 .anchor_before(Point::new(invalidation_row_range.start, 0))
5535 ..multibuffer.anchor_after(Point::new(
5536 invalidation_row_range.end,
5537 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5538 ));
5539
5540 self.stale_inline_completion_in_menu = None;
5541 self.active_inline_completion = Some(InlineCompletionState {
5542 inlay_ids,
5543 completion,
5544 completion_id: inline_completion.id,
5545 invalidation_range,
5546 });
5547
5548 cx.notify();
5549
5550 Some(())
5551 }
5552
5553 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5554 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5555 }
5556
5557 fn render_code_actions_indicator(
5558 &self,
5559 _style: &EditorStyle,
5560 row: DisplayRow,
5561 is_active: bool,
5562 cx: &mut Context<Self>,
5563 ) -> Option<IconButton> {
5564 if self.available_code_actions.is_some() {
5565 Some(
5566 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5567 .shape(ui::IconButtonShape::Square)
5568 .icon_size(IconSize::XSmall)
5569 .icon_color(Color::Muted)
5570 .toggle_state(is_active)
5571 .tooltip({
5572 let focus_handle = self.focus_handle.clone();
5573 move |window, cx| {
5574 Tooltip::for_action_in(
5575 "Toggle Code Actions",
5576 &ToggleCodeActions {
5577 deployed_from_indicator: None,
5578 },
5579 &focus_handle,
5580 window,
5581 cx,
5582 )
5583 }
5584 })
5585 .on_click(cx.listener(move |editor, _e, window, cx| {
5586 window.focus(&editor.focus_handle(cx));
5587 editor.toggle_code_actions(
5588 &ToggleCodeActions {
5589 deployed_from_indicator: Some(row),
5590 },
5591 window,
5592 cx,
5593 );
5594 })),
5595 )
5596 } else {
5597 None
5598 }
5599 }
5600
5601 fn clear_tasks(&mut self) {
5602 self.tasks.clear()
5603 }
5604
5605 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5606 if self.tasks.insert(key, value).is_some() {
5607 // This case should hopefully be rare, but just in case...
5608 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5609 }
5610 }
5611
5612 fn build_tasks_context(
5613 project: &Entity<Project>,
5614 buffer: &Entity<Buffer>,
5615 buffer_row: u32,
5616 tasks: &Arc<RunnableTasks>,
5617 cx: &mut Context<Self>,
5618 ) -> Task<Option<task::TaskContext>> {
5619 let position = Point::new(buffer_row, tasks.column);
5620 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5621 let location = Location {
5622 buffer: buffer.clone(),
5623 range: range_start..range_start,
5624 };
5625 // Fill in the environmental variables from the tree-sitter captures
5626 let mut captured_task_variables = TaskVariables::default();
5627 for (capture_name, value) in tasks.extra_variables.clone() {
5628 captured_task_variables.insert(
5629 task::VariableName::Custom(capture_name.into()),
5630 value.clone(),
5631 );
5632 }
5633 project.update(cx, |project, cx| {
5634 project.task_store().update(cx, |task_store, cx| {
5635 task_store.task_context_for_location(captured_task_variables, location, cx)
5636 })
5637 })
5638 }
5639
5640 pub fn spawn_nearest_task(
5641 &mut self,
5642 action: &SpawnNearestTask,
5643 window: &mut Window,
5644 cx: &mut Context<Self>,
5645 ) {
5646 let Some((workspace, _)) = self.workspace.clone() else {
5647 return;
5648 };
5649 let Some(project) = self.project.clone() else {
5650 return;
5651 };
5652
5653 // Try to find a closest, enclosing node using tree-sitter that has a
5654 // task
5655 let Some((buffer, buffer_row, tasks)) = self
5656 .find_enclosing_node_task(cx)
5657 // Or find the task that's closest in row-distance.
5658 .or_else(|| self.find_closest_task(cx))
5659 else {
5660 return;
5661 };
5662
5663 let reveal_strategy = action.reveal;
5664 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5665 cx.spawn_in(window, |_, mut cx| async move {
5666 let context = task_context.await?;
5667 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5668
5669 let resolved = resolved_task.resolved.as_mut()?;
5670 resolved.reveal = reveal_strategy;
5671
5672 workspace
5673 .update(&mut cx, |workspace, cx| {
5674 workspace::tasks::schedule_resolved_task(
5675 workspace,
5676 task_source_kind,
5677 resolved_task,
5678 false,
5679 cx,
5680 );
5681 })
5682 .ok()
5683 })
5684 .detach();
5685 }
5686
5687 fn find_closest_task(
5688 &mut self,
5689 cx: &mut Context<Self>,
5690 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5691 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5692
5693 let ((buffer_id, row), tasks) = self
5694 .tasks
5695 .iter()
5696 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5697
5698 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5699 let tasks = Arc::new(tasks.to_owned());
5700 Some((buffer, *row, tasks))
5701 }
5702
5703 fn find_enclosing_node_task(
5704 &mut self,
5705 cx: &mut Context<Self>,
5706 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5707 let snapshot = self.buffer.read(cx).snapshot(cx);
5708 let offset = self.selections.newest::<usize>(cx).head();
5709 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5710 let buffer_id = excerpt.buffer().remote_id();
5711
5712 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5713 let mut cursor = layer.node().walk();
5714
5715 while cursor.goto_first_child_for_byte(offset).is_some() {
5716 if cursor.node().end_byte() == offset {
5717 cursor.goto_next_sibling();
5718 }
5719 }
5720
5721 // Ascend to the smallest ancestor that contains the range and has a task.
5722 loop {
5723 let node = cursor.node();
5724 let node_range = node.byte_range();
5725 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5726
5727 // Check if this node contains our offset
5728 if node_range.start <= offset && node_range.end >= offset {
5729 // If it contains offset, check for task
5730 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5731 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5732 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5733 }
5734 }
5735
5736 if !cursor.goto_parent() {
5737 break;
5738 }
5739 }
5740 None
5741 }
5742
5743 fn render_run_indicator(
5744 &self,
5745 _style: &EditorStyle,
5746 is_active: bool,
5747 row: DisplayRow,
5748 cx: &mut Context<Self>,
5749 ) -> IconButton {
5750 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5751 .shape(ui::IconButtonShape::Square)
5752 .icon_size(IconSize::XSmall)
5753 .icon_color(Color::Muted)
5754 .toggle_state(is_active)
5755 .on_click(cx.listener(move |editor, _e, window, cx| {
5756 window.focus(&editor.focus_handle(cx));
5757 editor.toggle_code_actions(
5758 &ToggleCodeActions {
5759 deployed_from_indicator: Some(row),
5760 },
5761 window,
5762 cx,
5763 );
5764 }))
5765 }
5766
5767 pub fn context_menu_visible(&self) -> bool {
5768 !self.edit_prediction_preview_is_active()
5769 && self
5770 .context_menu
5771 .borrow()
5772 .as_ref()
5773 .map_or(false, |menu| menu.visible())
5774 }
5775
5776 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5777 self.context_menu
5778 .borrow()
5779 .as_ref()
5780 .map(|menu| menu.origin())
5781 }
5782
5783 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5784 px(30.)
5785 }
5786
5787 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5788 if self.read_only(cx) {
5789 cx.theme().players().read_only()
5790 } else {
5791 self.style.as_ref().unwrap().local_player
5792 }
5793 }
5794
5795 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5796 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5797 let accept_keystroke = accept_binding.keystroke()?;
5798
5799 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5800
5801 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5802 Color::Accent
5803 } else {
5804 Color::Muted
5805 };
5806
5807 h_flex()
5808 .px_0p5()
5809 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5810 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5811 .text_size(TextSize::XSmall.rems(cx))
5812 .child(h_flex().children(ui::render_modifiers(
5813 &accept_keystroke.modifiers,
5814 PlatformStyle::platform(),
5815 Some(modifiers_color),
5816 Some(IconSize::XSmall.rems().into()),
5817 true,
5818 )))
5819 .when(is_platform_style_mac, |parent| {
5820 parent.child(accept_keystroke.key.clone())
5821 })
5822 .when(!is_platform_style_mac, |parent| {
5823 parent.child(
5824 Key::new(
5825 util::capitalize(&accept_keystroke.key),
5826 Some(Color::Default),
5827 )
5828 .size(Some(IconSize::XSmall.rems().into())),
5829 )
5830 })
5831 .into()
5832 }
5833
5834 fn render_edit_prediction_line_popover(
5835 &self,
5836 label: impl Into<SharedString>,
5837 icon: Option<IconName>,
5838 window: &mut Window,
5839 cx: &App,
5840 ) -> Option<Div> {
5841 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5842
5843 let result = h_flex()
5844 .py_0p5()
5845 .pl_1()
5846 .pr(padding_right)
5847 .gap_1()
5848 .rounded(px(6.))
5849 .border_1()
5850 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5851 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5852 .shadow_sm()
5853 .children(self.render_edit_prediction_accept_keybind(window, cx))
5854 .child(Label::new(label).size(LabelSize::Small))
5855 .when_some(icon, |element, icon| {
5856 element.child(
5857 div()
5858 .mt(px(1.5))
5859 .child(Icon::new(icon).size(IconSize::Small)),
5860 )
5861 });
5862
5863 Some(result)
5864 }
5865
5866 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5867 let accent_color = cx.theme().colors().text_accent;
5868 let editor_bg_color = cx.theme().colors().editor_background;
5869 editor_bg_color.blend(accent_color.opacity(0.1))
5870 }
5871
5872 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5873 let accent_color = cx.theme().colors().text_accent;
5874 let editor_bg_color = cx.theme().colors().editor_background;
5875 editor_bg_color.blend(accent_color.opacity(0.6))
5876 }
5877
5878 #[allow(clippy::too_many_arguments)]
5879 fn render_edit_prediction_cursor_popover(
5880 &self,
5881 min_width: Pixels,
5882 max_width: Pixels,
5883 cursor_point: Point,
5884 style: &EditorStyle,
5885 accept_keystroke: Option<&gpui::Keystroke>,
5886 _window: &Window,
5887 cx: &mut Context<Editor>,
5888 ) -> Option<AnyElement> {
5889 let provider = self.edit_prediction_provider.as_ref()?;
5890
5891 if provider.provider.needs_terms_acceptance(cx) {
5892 return Some(
5893 h_flex()
5894 .min_w(min_width)
5895 .flex_1()
5896 .px_2()
5897 .py_1()
5898 .gap_3()
5899 .elevation_2(cx)
5900 .hover(|style| style.bg(cx.theme().colors().element_hover))
5901 .id("accept-terms")
5902 .cursor_pointer()
5903 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5904 .on_click(cx.listener(|this, _event, window, cx| {
5905 cx.stop_propagation();
5906 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5907 window.dispatch_action(
5908 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5909 cx,
5910 );
5911 }))
5912 .child(
5913 h_flex()
5914 .flex_1()
5915 .gap_2()
5916 .child(Icon::new(IconName::ZedPredict))
5917 .child(Label::new("Accept Terms of Service"))
5918 .child(div().w_full())
5919 .child(
5920 Icon::new(IconName::ArrowUpRight)
5921 .color(Color::Muted)
5922 .size(IconSize::Small),
5923 )
5924 .into_any_element(),
5925 )
5926 .into_any(),
5927 );
5928 }
5929
5930 let is_refreshing = provider.provider.is_refreshing(cx);
5931
5932 fn pending_completion_container() -> Div {
5933 h_flex()
5934 .h_full()
5935 .flex_1()
5936 .gap_2()
5937 .child(Icon::new(IconName::ZedPredict))
5938 }
5939
5940 let completion = match &self.active_inline_completion {
5941 Some(completion) => match &completion.completion {
5942 InlineCompletion::Move {
5943 target, snapshot, ..
5944 } if !self.has_visible_completions_menu() => {
5945 use text::ToPoint as _;
5946
5947 return Some(
5948 h_flex()
5949 .px_2()
5950 .py_1()
5951 .gap_2()
5952 .elevation_2(cx)
5953 .border_color(cx.theme().colors().border)
5954 .rounded(px(6.))
5955 .rounded_tl(px(0.))
5956 .child(
5957 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5958 Icon::new(IconName::ZedPredictDown)
5959 } else {
5960 Icon::new(IconName::ZedPredictUp)
5961 },
5962 )
5963 .child(Label::new("Hold").size(LabelSize::Small))
5964 .child(h_flex().children(ui::render_modifiers(
5965 &accept_keystroke?.modifiers,
5966 PlatformStyle::platform(),
5967 Some(Color::Default),
5968 Some(IconSize::Small.rems().into()),
5969 false,
5970 )))
5971 .into_any(),
5972 );
5973 }
5974 _ => self.render_edit_prediction_cursor_popover_preview(
5975 completion,
5976 cursor_point,
5977 style,
5978 cx,
5979 )?,
5980 },
5981
5982 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5983 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5984 stale_completion,
5985 cursor_point,
5986 style,
5987 cx,
5988 )?,
5989
5990 None => {
5991 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5992 }
5993 },
5994
5995 None => pending_completion_container().child(Label::new("No Prediction")),
5996 };
5997
5998 let completion = if is_refreshing {
5999 completion
6000 .with_animation(
6001 "loading-completion",
6002 Animation::new(Duration::from_secs(2))
6003 .repeat()
6004 .with_easing(pulsating_between(0.4, 0.8)),
6005 |label, delta| label.opacity(delta),
6006 )
6007 .into_any_element()
6008 } else {
6009 completion.into_any_element()
6010 };
6011
6012 let has_completion = self.active_inline_completion.is_some();
6013
6014 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6015 Some(
6016 h_flex()
6017 .min_w(min_width)
6018 .max_w(max_width)
6019 .flex_1()
6020 .elevation_2(cx)
6021 .border_color(cx.theme().colors().border)
6022 .child(
6023 div()
6024 .flex_1()
6025 .py_1()
6026 .px_2()
6027 .overflow_hidden()
6028 .child(completion),
6029 )
6030 .when_some(accept_keystroke, |el, accept_keystroke| {
6031 if !accept_keystroke.modifiers.modified() {
6032 return el;
6033 }
6034
6035 el.child(
6036 h_flex()
6037 .h_full()
6038 .border_l_1()
6039 .rounded_r_lg()
6040 .border_color(cx.theme().colors().border)
6041 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6042 .gap_1()
6043 .py_1()
6044 .px_2()
6045 .child(
6046 h_flex()
6047 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6048 .when(is_platform_style_mac, |parent| parent.gap_1())
6049 .child(h_flex().children(ui::render_modifiers(
6050 &accept_keystroke.modifiers,
6051 PlatformStyle::platform(),
6052 Some(if !has_completion {
6053 Color::Muted
6054 } else {
6055 Color::Default
6056 }),
6057 None,
6058 false,
6059 ))),
6060 )
6061 .child(Label::new("Preview").into_any_element())
6062 .opacity(if has_completion { 1.0 } else { 0.4 }),
6063 )
6064 })
6065 .into_any(),
6066 )
6067 }
6068
6069 fn render_edit_prediction_cursor_popover_preview(
6070 &self,
6071 completion: &InlineCompletionState,
6072 cursor_point: Point,
6073 style: &EditorStyle,
6074 cx: &mut Context<Editor>,
6075 ) -> Option<Div> {
6076 use text::ToPoint as _;
6077
6078 fn render_relative_row_jump(
6079 prefix: impl Into<String>,
6080 current_row: u32,
6081 target_row: u32,
6082 ) -> Div {
6083 let (row_diff, arrow) = if target_row < current_row {
6084 (current_row - target_row, IconName::ArrowUp)
6085 } else {
6086 (target_row - current_row, IconName::ArrowDown)
6087 };
6088
6089 h_flex()
6090 .child(
6091 Label::new(format!("{}{}", prefix.into(), row_diff))
6092 .color(Color::Muted)
6093 .size(LabelSize::Small),
6094 )
6095 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6096 }
6097
6098 match &completion.completion {
6099 InlineCompletion::Move {
6100 target, snapshot, ..
6101 } => Some(
6102 h_flex()
6103 .px_2()
6104 .gap_2()
6105 .flex_1()
6106 .child(
6107 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6108 Icon::new(IconName::ZedPredictDown)
6109 } else {
6110 Icon::new(IconName::ZedPredictUp)
6111 },
6112 )
6113 .child(Label::new("Jump to Edit")),
6114 ),
6115
6116 InlineCompletion::Edit {
6117 edits,
6118 edit_preview,
6119 snapshot,
6120 display_mode: _,
6121 } => {
6122 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6123
6124 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6125 &snapshot,
6126 &edits,
6127 edit_preview.as_ref()?,
6128 true,
6129 cx,
6130 )
6131 .first_line_preview();
6132
6133 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6134 .with_highlights(&style.text, highlighted_edits.highlights);
6135
6136 let preview = h_flex()
6137 .gap_1()
6138 .min_w_16()
6139 .child(styled_text)
6140 .when(has_more_lines, |parent| parent.child("…"));
6141
6142 let left = if first_edit_row != cursor_point.row {
6143 render_relative_row_jump("", cursor_point.row, first_edit_row)
6144 .into_any_element()
6145 } else {
6146 Icon::new(IconName::ZedPredict).into_any_element()
6147 };
6148
6149 Some(
6150 h_flex()
6151 .h_full()
6152 .flex_1()
6153 .gap_2()
6154 .pr_1()
6155 .overflow_x_hidden()
6156 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6157 .child(left)
6158 .child(preview),
6159 )
6160 }
6161 }
6162 }
6163
6164 fn render_context_menu(
6165 &self,
6166 style: &EditorStyle,
6167 max_height_in_lines: u32,
6168 y_flipped: bool,
6169 window: &mut Window,
6170 cx: &mut Context<Editor>,
6171 ) -> Option<AnyElement> {
6172 let menu = self.context_menu.borrow();
6173 let menu = menu.as_ref()?;
6174 if !menu.visible() {
6175 return None;
6176 };
6177 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6178 }
6179
6180 fn render_context_menu_aside(
6181 &mut self,
6182 max_size: Size<Pixels>,
6183 window: &mut Window,
6184 cx: &mut Context<Editor>,
6185 ) -> Option<AnyElement> {
6186 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6187 if menu.visible() {
6188 menu.render_aside(self, max_size, window, cx)
6189 } else {
6190 None
6191 }
6192 })
6193 }
6194
6195 fn hide_context_menu(
6196 &mut self,
6197 window: &mut Window,
6198 cx: &mut Context<Self>,
6199 ) -> Option<CodeContextMenu> {
6200 cx.notify();
6201 self.completion_tasks.clear();
6202 let context_menu = self.context_menu.borrow_mut().take();
6203 self.stale_inline_completion_in_menu.take();
6204 self.update_visible_inline_completion(window, cx);
6205 context_menu
6206 }
6207
6208 fn show_snippet_choices(
6209 &mut self,
6210 choices: &Vec<String>,
6211 selection: Range<Anchor>,
6212 cx: &mut Context<Self>,
6213 ) {
6214 if selection.start.buffer_id.is_none() {
6215 return;
6216 }
6217 let buffer_id = selection.start.buffer_id.unwrap();
6218 let buffer = self.buffer().read(cx).buffer(buffer_id);
6219 let id = post_inc(&mut self.next_completion_id);
6220
6221 if let Some(buffer) = buffer {
6222 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6223 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6224 ));
6225 }
6226 }
6227
6228 pub fn insert_snippet(
6229 &mut self,
6230 insertion_ranges: &[Range<usize>],
6231 snippet: Snippet,
6232 window: &mut Window,
6233 cx: &mut Context<Self>,
6234 ) -> Result<()> {
6235 struct Tabstop<T> {
6236 is_end_tabstop: bool,
6237 ranges: Vec<Range<T>>,
6238 choices: Option<Vec<String>>,
6239 }
6240
6241 let tabstops = self.buffer.update(cx, |buffer, cx| {
6242 let snippet_text: Arc<str> = snippet.text.clone().into();
6243 buffer.edit(
6244 insertion_ranges
6245 .iter()
6246 .cloned()
6247 .map(|range| (range, snippet_text.clone())),
6248 Some(AutoindentMode::EachLine),
6249 cx,
6250 );
6251
6252 let snapshot = &*buffer.read(cx);
6253 let snippet = &snippet;
6254 snippet
6255 .tabstops
6256 .iter()
6257 .map(|tabstop| {
6258 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6259 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6260 });
6261 let mut tabstop_ranges = tabstop
6262 .ranges
6263 .iter()
6264 .flat_map(|tabstop_range| {
6265 let mut delta = 0_isize;
6266 insertion_ranges.iter().map(move |insertion_range| {
6267 let insertion_start = insertion_range.start as isize + delta;
6268 delta +=
6269 snippet.text.len() as isize - insertion_range.len() as isize;
6270
6271 let start = ((insertion_start + tabstop_range.start) as usize)
6272 .min(snapshot.len());
6273 let end = ((insertion_start + tabstop_range.end) as usize)
6274 .min(snapshot.len());
6275 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6276 })
6277 })
6278 .collect::<Vec<_>>();
6279 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6280
6281 Tabstop {
6282 is_end_tabstop,
6283 ranges: tabstop_ranges,
6284 choices: tabstop.choices.clone(),
6285 }
6286 })
6287 .collect::<Vec<_>>()
6288 });
6289 if let Some(tabstop) = tabstops.first() {
6290 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6291 s.select_ranges(tabstop.ranges.iter().cloned());
6292 });
6293
6294 if let Some(choices) = &tabstop.choices {
6295 if let Some(selection) = tabstop.ranges.first() {
6296 self.show_snippet_choices(choices, selection.clone(), cx)
6297 }
6298 }
6299
6300 // If we're already at the last tabstop and it's at the end of the snippet,
6301 // we're done, we don't need to keep the state around.
6302 if !tabstop.is_end_tabstop {
6303 let choices = tabstops
6304 .iter()
6305 .map(|tabstop| tabstop.choices.clone())
6306 .collect();
6307
6308 let ranges = tabstops
6309 .into_iter()
6310 .map(|tabstop| tabstop.ranges)
6311 .collect::<Vec<_>>();
6312
6313 self.snippet_stack.push(SnippetState {
6314 active_index: 0,
6315 ranges,
6316 choices,
6317 });
6318 }
6319
6320 // Check whether the just-entered snippet ends with an auto-closable bracket.
6321 if self.autoclose_regions.is_empty() {
6322 let snapshot = self.buffer.read(cx).snapshot(cx);
6323 for selection in &mut self.selections.all::<Point>(cx) {
6324 let selection_head = selection.head();
6325 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6326 continue;
6327 };
6328
6329 let mut bracket_pair = None;
6330 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6331 let prev_chars = snapshot
6332 .reversed_chars_at(selection_head)
6333 .collect::<String>();
6334 for (pair, enabled) in scope.brackets() {
6335 if enabled
6336 && pair.close
6337 && prev_chars.starts_with(pair.start.as_str())
6338 && next_chars.starts_with(pair.end.as_str())
6339 {
6340 bracket_pair = Some(pair.clone());
6341 break;
6342 }
6343 }
6344 if let Some(pair) = bracket_pair {
6345 let start = snapshot.anchor_after(selection_head);
6346 let end = snapshot.anchor_after(selection_head);
6347 self.autoclose_regions.push(AutocloseRegion {
6348 selection_id: selection.id,
6349 range: start..end,
6350 pair,
6351 });
6352 }
6353 }
6354 }
6355 }
6356 Ok(())
6357 }
6358
6359 pub fn move_to_next_snippet_tabstop(
6360 &mut self,
6361 window: &mut Window,
6362 cx: &mut Context<Self>,
6363 ) -> bool {
6364 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6365 }
6366
6367 pub fn move_to_prev_snippet_tabstop(
6368 &mut self,
6369 window: &mut Window,
6370 cx: &mut Context<Self>,
6371 ) -> bool {
6372 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6373 }
6374
6375 pub fn move_to_snippet_tabstop(
6376 &mut self,
6377 bias: Bias,
6378 window: &mut Window,
6379 cx: &mut Context<Self>,
6380 ) -> bool {
6381 if let Some(mut snippet) = self.snippet_stack.pop() {
6382 match bias {
6383 Bias::Left => {
6384 if snippet.active_index > 0 {
6385 snippet.active_index -= 1;
6386 } else {
6387 self.snippet_stack.push(snippet);
6388 return false;
6389 }
6390 }
6391 Bias::Right => {
6392 if snippet.active_index + 1 < snippet.ranges.len() {
6393 snippet.active_index += 1;
6394 } else {
6395 self.snippet_stack.push(snippet);
6396 return false;
6397 }
6398 }
6399 }
6400 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6401 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6402 s.select_anchor_ranges(current_ranges.iter().cloned())
6403 });
6404
6405 if let Some(choices) = &snippet.choices[snippet.active_index] {
6406 if let Some(selection) = current_ranges.first() {
6407 self.show_snippet_choices(&choices, selection.clone(), cx);
6408 }
6409 }
6410
6411 // If snippet state is not at the last tabstop, push it back on the stack
6412 if snippet.active_index + 1 < snippet.ranges.len() {
6413 self.snippet_stack.push(snippet);
6414 }
6415 return true;
6416 }
6417 }
6418
6419 false
6420 }
6421
6422 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6423 self.transact(window, cx, |this, window, cx| {
6424 this.select_all(&SelectAll, window, cx);
6425 this.insert("", window, cx);
6426 });
6427 }
6428
6429 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6430 self.transact(window, cx, |this, window, cx| {
6431 this.select_autoclose_pair(window, cx);
6432 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6433 if !this.linked_edit_ranges.is_empty() {
6434 let selections = this.selections.all::<MultiBufferPoint>(cx);
6435 let snapshot = this.buffer.read(cx).snapshot(cx);
6436
6437 for selection in selections.iter() {
6438 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6439 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6440 if selection_start.buffer_id != selection_end.buffer_id {
6441 continue;
6442 }
6443 if let Some(ranges) =
6444 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6445 {
6446 for (buffer, entries) in ranges {
6447 linked_ranges.entry(buffer).or_default().extend(entries);
6448 }
6449 }
6450 }
6451 }
6452
6453 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6454 if !this.selections.line_mode {
6455 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6456 for selection in &mut selections {
6457 if selection.is_empty() {
6458 let old_head = selection.head();
6459 let mut new_head =
6460 movement::left(&display_map, old_head.to_display_point(&display_map))
6461 .to_point(&display_map);
6462 if let Some((buffer, line_buffer_range)) = display_map
6463 .buffer_snapshot
6464 .buffer_line_for_row(MultiBufferRow(old_head.row))
6465 {
6466 let indent_size =
6467 buffer.indent_size_for_line(line_buffer_range.start.row);
6468 let indent_len = match indent_size.kind {
6469 IndentKind::Space => {
6470 buffer.settings_at(line_buffer_range.start, cx).tab_size
6471 }
6472 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6473 };
6474 if old_head.column <= indent_size.len && old_head.column > 0 {
6475 let indent_len = indent_len.get();
6476 new_head = cmp::min(
6477 new_head,
6478 MultiBufferPoint::new(
6479 old_head.row,
6480 ((old_head.column - 1) / indent_len) * indent_len,
6481 ),
6482 );
6483 }
6484 }
6485
6486 selection.set_head(new_head, SelectionGoal::None);
6487 }
6488 }
6489 }
6490
6491 this.signature_help_state.set_backspace_pressed(true);
6492 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6493 s.select(selections)
6494 });
6495 this.insert("", window, cx);
6496 let empty_str: Arc<str> = Arc::from("");
6497 for (buffer, edits) in linked_ranges {
6498 let snapshot = buffer.read(cx).snapshot();
6499 use text::ToPoint as TP;
6500
6501 let edits = edits
6502 .into_iter()
6503 .map(|range| {
6504 let end_point = TP::to_point(&range.end, &snapshot);
6505 let mut start_point = TP::to_point(&range.start, &snapshot);
6506
6507 if end_point == start_point {
6508 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6509 .saturating_sub(1);
6510 start_point =
6511 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6512 };
6513
6514 (start_point..end_point, empty_str.clone())
6515 })
6516 .sorted_by_key(|(range, _)| range.start)
6517 .collect::<Vec<_>>();
6518 buffer.update(cx, |this, cx| {
6519 this.edit(edits, None, cx);
6520 })
6521 }
6522 this.refresh_inline_completion(true, false, window, cx);
6523 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6524 });
6525 }
6526
6527 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6528 self.transact(window, cx, |this, window, cx| {
6529 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6530 let line_mode = s.line_mode;
6531 s.move_with(|map, selection| {
6532 if selection.is_empty() && !line_mode {
6533 let cursor = movement::right(map, selection.head());
6534 selection.end = cursor;
6535 selection.reversed = true;
6536 selection.goal = SelectionGoal::None;
6537 }
6538 })
6539 });
6540 this.insert("", window, cx);
6541 this.refresh_inline_completion(true, false, window, cx);
6542 });
6543 }
6544
6545 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6546 if self.move_to_prev_snippet_tabstop(window, cx) {
6547 return;
6548 }
6549
6550 self.outdent(&Outdent, window, cx);
6551 }
6552
6553 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6554 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6555 return;
6556 }
6557
6558 let mut selections = self.selections.all_adjusted(cx);
6559 let buffer = self.buffer.read(cx);
6560 let snapshot = buffer.snapshot(cx);
6561 let rows_iter = selections.iter().map(|s| s.head().row);
6562 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6563
6564 let mut edits = Vec::new();
6565 let mut prev_edited_row = 0;
6566 let mut row_delta = 0;
6567 for selection in &mut selections {
6568 if selection.start.row != prev_edited_row {
6569 row_delta = 0;
6570 }
6571 prev_edited_row = selection.end.row;
6572
6573 // If the selection is non-empty, then increase the indentation of the selected lines.
6574 if !selection.is_empty() {
6575 row_delta =
6576 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6577 continue;
6578 }
6579
6580 // If the selection is empty and the cursor is in the leading whitespace before the
6581 // suggested indentation, then auto-indent the line.
6582 let cursor = selection.head();
6583 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6584 if let Some(suggested_indent) =
6585 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6586 {
6587 if cursor.column < suggested_indent.len
6588 && cursor.column <= current_indent.len
6589 && current_indent.len <= suggested_indent.len
6590 {
6591 selection.start = Point::new(cursor.row, suggested_indent.len);
6592 selection.end = selection.start;
6593 if row_delta == 0 {
6594 edits.extend(Buffer::edit_for_indent_size_adjustment(
6595 cursor.row,
6596 current_indent,
6597 suggested_indent,
6598 ));
6599 row_delta = suggested_indent.len - current_indent.len;
6600 }
6601 continue;
6602 }
6603 }
6604
6605 // Otherwise, insert a hard or soft tab.
6606 let settings = buffer.settings_at(cursor, cx);
6607 let tab_size = if settings.hard_tabs {
6608 IndentSize::tab()
6609 } else {
6610 let tab_size = settings.tab_size.get();
6611 let char_column = snapshot
6612 .text_for_range(Point::new(cursor.row, 0)..cursor)
6613 .flat_map(str::chars)
6614 .count()
6615 + row_delta as usize;
6616 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6617 IndentSize::spaces(chars_to_next_tab_stop)
6618 };
6619 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6620 selection.end = selection.start;
6621 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6622 row_delta += tab_size.len;
6623 }
6624
6625 self.transact(window, cx, |this, window, cx| {
6626 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6627 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6628 s.select(selections)
6629 });
6630 this.refresh_inline_completion(true, false, window, cx);
6631 });
6632 }
6633
6634 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6635 if self.read_only(cx) {
6636 return;
6637 }
6638 let mut selections = self.selections.all::<Point>(cx);
6639 let mut prev_edited_row = 0;
6640 let mut row_delta = 0;
6641 let mut edits = Vec::new();
6642 let buffer = self.buffer.read(cx);
6643 let snapshot = buffer.snapshot(cx);
6644 for selection in &mut selections {
6645 if selection.start.row != prev_edited_row {
6646 row_delta = 0;
6647 }
6648 prev_edited_row = selection.end.row;
6649
6650 row_delta =
6651 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6652 }
6653
6654 self.transact(window, cx, |this, window, cx| {
6655 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6656 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6657 s.select(selections)
6658 });
6659 });
6660 }
6661
6662 fn indent_selection(
6663 buffer: &MultiBuffer,
6664 snapshot: &MultiBufferSnapshot,
6665 selection: &mut Selection<Point>,
6666 edits: &mut Vec<(Range<Point>, String)>,
6667 delta_for_start_row: u32,
6668 cx: &App,
6669 ) -> u32 {
6670 let settings = buffer.settings_at(selection.start, cx);
6671 let tab_size = settings.tab_size.get();
6672 let indent_kind = if settings.hard_tabs {
6673 IndentKind::Tab
6674 } else {
6675 IndentKind::Space
6676 };
6677 let mut start_row = selection.start.row;
6678 let mut end_row = selection.end.row + 1;
6679
6680 // If a selection ends at the beginning of a line, don't indent
6681 // that last line.
6682 if selection.end.column == 0 && selection.end.row > selection.start.row {
6683 end_row -= 1;
6684 }
6685
6686 // Avoid re-indenting a row that has already been indented by a
6687 // previous selection, but still update this selection's column
6688 // to reflect that indentation.
6689 if delta_for_start_row > 0 {
6690 start_row += 1;
6691 selection.start.column += delta_for_start_row;
6692 if selection.end.row == selection.start.row {
6693 selection.end.column += delta_for_start_row;
6694 }
6695 }
6696
6697 let mut delta_for_end_row = 0;
6698 let has_multiple_rows = start_row + 1 != end_row;
6699 for row in start_row..end_row {
6700 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6701 let indent_delta = match (current_indent.kind, indent_kind) {
6702 (IndentKind::Space, IndentKind::Space) => {
6703 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6704 IndentSize::spaces(columns_to_next_tab_stop)
6705 }
6706 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6707 (_, IndentKind::Tab) => IndentSize::tab(),
6708 };
6709
6710 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6711 0
6712 } else {
6713 selection.start.column
6714 };
6715 let row_start = Point::new(row, start);
6716 edits.push((
6717 row_start..row_start,
6718 indent_delta.chars().collect::<String>(),
6719 ));
6720
6721 // Update this selection's endpoints to reflect the indentation.
6722 if row == selection.start.row {
6723 selection.start.column += indent_delta.len;
6724 }
6725 if row == selection.end.row {
6726 selection.end.column += indent_delta.len;
6727 delta_for_end_row = indent_delta.len;
6728 }
6729 }
6730
6731 if selection.start.row == selection.end.row {
6732 delta_for_start_row + delta_for_end_row
6733 } else {
6734 delta_for_end_row
6735 }
6736 }
6737
6738 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6739 if self.read_only(cx) {
6740 return;
6741 }
6742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6743 let selections = self.selections.all::<Point>(cx);
6744 let mut deletion_ranges = Vec::new();
6745 let mut last_outdent = None;
6746 {
6747 let buffer = self.buffer.read(cx);
6748 let snapshot = buffer.snapshot(cx);
6749 for selection in &selections {
6750 let settings = buffer.settings_at(selection.start, cx);
6751 let tab_size = settings.tab_size.get();
6752 let mut rows = selection.spanned_rows(false, &display_map);
6753
6754 // Avoid re-outdenting a row that has already been outdented by a
6755 // previous selection.
6756 if let Some(last_row) = last_outdent {
6757 if last_row == rows.start {
6758 rows.start = rows.start.next_row();
6759 }
6760 }
6761 let has_multiple_rows = rows.len() > 1;
6762 for row in rows.iter_rows() {
6763 let indent_size = snapshot.indent_size_for_line(row);
6764 if indent_size.len > 0 {
6765 let deletion_len = match indent_size.kind {
6766 IndentKind::Space => {
6767 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6768 if columns_to_prev_tab_stop == 0 {
6769 tab_size
6770 } else {
6771 columns_to_prev_tab_stop
6772 }
6773 }
6774 IndentKind::Tab => 1,
6775 };
6776 let start = if has_multiple_rows
6777 || deletion_len > selection.start.column
6778 || indent_size.len < selection.start.column
6779 {
6780 0
6781 } else {
6782 selection.start.column - deletion_len
6783 };
6784 deletion_ranges.push(
6785 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6786 );
6787 last_outdent = Some(row);
6788 }
6789 }
6790 }
6791 }
6792
6793 self.transact(window, cx, |this, window, cx| {
6794 this.buffer.update(cx, |buffer, cx| {
6795 let empty_str: Arc<str> = Arc::default();
6796 buffer.edit(
6797 deletion_ranges
6798 .into_iter()
6799 .map(|range| (range, empty_str.clone())),
6800 None,
6801 cx,
6802 );
6803 });
6804 let selections = this.selections.all::<usize>(cx);
6805 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6806 s.select(selections)
6807 });
6808 });
6809 }
6810
6811 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6812 if self.read_only(cx) {
6813 return;
6814 }
6815 let selections = self
6816 .selections
6817 .all::<usize>(cx)
6818 .into_iter()
6819 .map(|s| s.range());
6820
6821 self.transact(window, cx, |this, window, cx| {
6822 this.buffer.update(cx, |buffer, cx| {
6823 buffer.autoindent_ranges(selections, cx);
6824 });
6825 let selections = this.selections.all::<usize>(cx);
6826 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6827 s.select(selections)
6828 });
6829 });
6830 }
6831
6832 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6833 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6834 let selections = self.selections.all::<Point>(cx);
6835
6836 let mut new_cursors = Vec::new();
6837 let mut edit_ranges = Vec::new();
6838 let mut selections = selections.iter().peekable();
6839 while let Some(selection) = selections.next() {
6840 let mut rows = selection.spanned_rows(false, &display_map);
6841 let goal_display_column = selection.head().to_display_point(&display_map).column();
6842
6843 // Accumulate contiguous regions of rows that we want to delete.
6844 while let Some(next_selection) = selections.peek() {
6845 let next_rows = next_selection.spanned_rows(false, &display_map);
6846 if next_rows.start <= rows.end {
6847 rows.end = next_rows.end;
6848 selections.next().unwrap();
6849 } else {
6850 break;
6851 }
6852 }
6853
6854 let buffer = &display_map.buffer_snapshot;
6855 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6856 let edit_end;
6857 let cursor_buffer_row;
6858 if buffer.max_point().row >= rows.end.0 {
6859 // If there's a line after the range, delete the \n from the end of the row range
6860 // and position the cursor on the next line.
6861 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6862 cursor_buffer_row = rows.end;
6863 } else {
6864 // If there isn't a line after the range, delete the \n from the line before the
6865 // start of the row range and position the cursor there.
6866 edit_start = edit_start.saturating_sub(1);
6867 edit_end = buffer.len();
6868 cursor_buffer_row = rows.start.previous_row();
6869 }
6870
6871 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6872 *cursor.column_mut() =
6873 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6874
6875 new_cursors.push((
6876 selection.id,
6877 buffer.anchor_after(cursor.to_point(&display_map)),
6878 ));
6879 edit_ranges.push(edit_start..edit_end);
6880 }
6881
6882 self.transact(window, cx, |this, window, cx| {
6883 let buffer = this.buffer.update(cx, |buffer, cx| {
6884 let empty_str: Arc<str> = Arc::default();
6885 buffer.edit(
6886 edit_ranges
6887 .into_iter()
6888 .map(|range| (range, empty_str.clone())),
6889 None,
6890 cx,
6891 );
6892 buffer.snapshot(cx)
6893 });
6894 let new_selections = new_cursors
6895 .into_iter()
6896 .map(|(id, cursor)| {
6897 let cursor = cursor.to_point(&buffer);
6898 Selection {
6899 id,
6900 start: cursor,
6901 end: cursor,
6902 reversed: false,
6903 goal: SelectionGoal::None,
6904 }
6905 })
6906 .collect();
6907
6908 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6909 s.select(new_selections);
6910 });
6911 });
6912 }
6913
6914 pub fn join_lines_impl(
6915 &mut self,
6916 insert_whitespace: bool,
6917 window: &mut Window,
6918 cx: &mut Context<Self>,
6919 ) {
6920 if self.read_only(cx) {
6921 return;
6922 }
6923 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6924 for selection in self.selections.all::<Point>(cx) {
6925 let start = MultiBufferRow(selection.start.row);
6926 // Treat single line selections as if they include the next line. Otherwise this action
6927 // would do nothing for single line selections individual cursors.
6928 let end = if selection.start.row == selection.end.row {
6929 MultiBufferRow(selection.start.row + 1)
6930 } else {
6931 MultiBufferRow(selection.end.row)
6932 };
6933
6934 if let Some(last_row_range) = row_ranges.last_mut() {
6935 if start <= last_row_range.end {
6936 last_row_range.end = end;
6937 continue;
6938 }
6939 }
6940 row_ranges.push(start..end);
6941 }
6942
6943 let snapshot = self.buffer.read(cx).snapshot(cx);
6944 let mut cursor_positions = Vec::new();
6945 for row_range in &row_ranges {
6946 let anchor = snapshot.anchor_before(Point::new(
6947 row_range.end.previous_row().0,
6948 snapshot.line_len(row_range.end.previous_row()),
6949 ));
6950 cursor_positions.push(anchor..anchor);
6951 }
6952
6953 self.transact(window, cx, |this, window, cx| {
6954 for row_range in row_ranges.into_iter().rev() {
6955 for row in row_range.iter_rows().rev() {
6956 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6957 let next_line_row = row.next_row();
6958 let indent = snapshot.indent_size_for_line(next_line_row);
6959 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6960
6961 let replace =
6962 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6963 " "
6964 } else {
6965 ""
6966 };
6967
6968 this.buffer.update(cx, |buffer, cx| {
6969 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6970 });
6971 }
6972 }
6973
6974 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6975 s.select_anchor_ranges(cursor_positions)
6976 });
6977 });
6978 }
6979
6980 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6981 self.join_lines_impl(true, window, cx);
6982 }
6983
6984 pub fn sort_lines_case_sensitive(
6985 &mut self,
6986 _: &SortLinesCaseSensitive,
6987 window: &mut Window,
6988 cx: &mut Context<Self>,
6989 ) {
6990 self.manipulate_lines(window, cx, |lines| lines.sort())
6991 }
6992
6993 pub fn sort_lines_case_insensitive(
6994 &mut self,
6995 _: &SortLinesCaseInsensitive,
6996 window: &mut Window,
6997 cx: &mut Context<Self>,
6998 ) {
6999 self.manipulate_lines(window, cx, |lines| {
7000 lines.sort_by_key(|line| line.to_lowercase())
7001 })
7002 }
7003
7004 pub fn unique_lines_case_insensitive(
7005 &mut self,
7006 _: &UniqueLinesCaseInsensitive,
7007 window: &mut Window,
7008 cx: &mut Context<Self>,
7009 ) {
7010 self.manipulate_lines(window, cx, |lines| {
7011 let mut seen = HashSet::default();
7012 lines.retain(|line| seen.insert(line.to_lowercase()));
7013 })
7014 }
7015
7016 pub fn unique_lines_case_sensitive(
7017 &mut self,
7018 _: &UniqueLinesCaseSensitive,
7019 window: &mut Window,
7020 cx: &mut Context<Self>,
7021 ) {
7022 self.manipulate_lines(window, cx, |lines| {
7023 let mut seen = HashSet::default();
7024 lines.retain(|line| seen.insert(*line));
7025 })
7026 }
7027
7028 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7029 let mut revert_changes = HashMap::default();
7030 let snapshot = self.snapshot(window, cx);
7031 for hunk in snapshot
7032 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7033 {
7034 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7035 }
7036 if !revert_changes.is_empty() {
7037 self.transact(window, cx, |editor, window, cx| {
7038 editor.revert(revert_changes, window, cx);
7039 });
7040 }
7041 }
7042
7043 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7044 let Some(project) = self.project.clone() else {
7045 return;
7046 };
7047 self.reload(project, window, cx)
7048 .detach_and_notify_err(window, cx);
7049 }
7050
7051 pub fn revert_selected_hunks(
7052 &mut self,
7053 _: &RevertSelectedHunks,
7054 window: &mut Window,
7055 cx: &mut Context<Self>,
7056 ) {
7057 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7058 self.revert_hunks_in_ranges(selections, window, cx);
7059 }
7060
7061 fn revert_hunks_in_ranges(
7062 &mut self,
7063 ranges: impl Iterator<Item = Range<Point>>,
7064 window: &mut Window,
7065 cx: &mut Context<Editor>,
7066 ) {
7067 let mut revert_changes = HashMap::default();
7068 let snapshot = self.snapshot(window, cx);
7069 for hunk in &snapshot.hunks_for_ranges(ranges) {
7070 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7071 }
7072 if !revert_changes.is_empty() {
7073 self.transact(window, cx, |editor, window, cx| {
7074 editor.revert(revert_changes, window, cx);
7075 });
7076 }
7077 }
7078
7079 pub fn open_active_item_in_terminal(
7080 &mut self,
7081 _: &OpenInTerminal,
7082 window: &mut Window,
7083 cx: &mut Context<Self>,
7084 ) {
7085 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7086 let project_path = buffer.read(cx).project_path(cx)?;
7087 let project = self.project.as_ref()?.read(cx);
7088 let entry = project.entry_for_path(&project_path, cx)?;
7089 let parent = match &entry.canonical_path {
7090 Some(canonical_path) => canonical_path.to_path_buf(),
7091 None => project.absolute_path(&project_path, cx)?,
7092 }
7093 .parent()?
7094 .to_path_buf();
7095 Some(parent)
7096 }) {
7097 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7098 }
7099 }
7100
7101 pub fn prepare_revert_change(
7102 &self,
7103 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7104 hunk: &MultiBufferDiffHunk,
7105 cx: &mut App,
7106 ) -> Option<()> {
7107 let buffer = self.buffer.read(cx);
7108 let diff = buffer.diff_for(hunk.buffer_id)?;
7109 let buffer = buffer.buffer(hunk.buffer_id)?;
7110 let buffer = buffer.read(cx);
7111 let original_text = diff
7112 .read(cx)
7113 .base_text()
7114 .as_ref()?
7115 .as_rope()
7116 .slice(hunk.diff_base_byte_range.clone());
7117 let buffer_snapshot = buffer.snapshot();
7118 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7119 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7120 probe
7121 .0
7122 .start
7123 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7124 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7125 }) {
7126 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7127 Some(())
7128 } else {
7129 None
7130 }
7131 }
7132
7133 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7134 self.manipulate_lines(window, cx, |lines| lines.reverse())
7135 }
7136
7137 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7138 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7139 }
7140
7141 fn manipulate_lines<Fn>(
7142 &mut self,
7143 window: &mut Window,
7144 cx: &mut Context<Self>,
7145 mut callback: Fn,
7146 ) where
7147 Fn: FnMut(&mut Vec<&str>),
7148 {
7149 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7150 let buffer = self.buffer.read(cx).snapshot(cx);
7151
7152 let mut edits = Vec::new();
7153
7154 let selections = self.selections.all::<Point>(cx);
7155 let mut selections = selections.iter().peekable();
7156 let mut contiguous_row_selections = Vec::new();
7157 let mut new_selections = Vec::new();
7158 let mut added_lines = 0;
7159 let mut removed_lines = 0;
7160
7161 while let Some(selection) = selections.next() {
7162 let (start_row, end_row) = consume_contiguous_rows(
7163 &mut contiguous_row_selections,
7164 selection,
7165 &display_map,
7166 &mut selections,
7167 );
7168
7169 let start_point = Point::new(start_row.0, 0);
7170 let end_point = Point::new(
7171 end_row.previous_row().0,
7172 buffer.line_len(end_row.previous_row()),
7173 );
7174 let text = buffer
7175 .text_for_range(start_point..end_point)
7176 .collect::<String>();
7177
7178 let mut lines = text.split('\n').collect_vec();
7179
7180 let lines_before = lines.len();
7181 callback(&mut lines);
7182 let lines_after = lines.len();
7183
7184 edits.push((start_point..end_point, lines.join("\n")));
7185
7186 // Selections must change based on added and removed line count
7187 let start_row =
7188 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7189 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7190 new_selections.push(Selection {
7191 id: selection.id,
7192 start: start_row,
7193 end: end_row,
7194 goal: SelectionGoal::None,
7195 reversed: selection.reversed,
7196 });
7197
7198 if lines_after > lines_before {
7199 added_lines += lines_after - lines_before;
7200 } else if lines_before > lines_after {
7201 removed_lines += lines_before - lines_after;
7202 }
7203 }
7204
7205 self.transact(window, cx, |this, window, cx| {
7206 let buffer = this.buffer.update(cx, |buffer, cx| {
7207 buffer.edit(edits, None, cx);
7208 buffer.snapshot(cx)
7209 });
7210
7211 // Recalculate offsets on newly edited buffer
7212 let new_selections = new_selections
7213 .iter()
7214 .map(|s| {
7215 let start_point = Point::new(s.start.0, 0);
7216 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7217 Selection {
7218 id: s.id,
7219 start: buffer.point_to_offset(start_point),
7220 end: buffer.point_to_offset(end_point),
7221 goal: s.goal,
7222 reversed: s.reversed,
7223 }
7224 })
7225 .collect();
7226
7227 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7228 s.select(new_selections);
7229 });
7230
7231 this.request_autoscroll(Autoscroll::fit(), cx);
7232 });
7233 }
7234
7235 pub fn convert_to_upper_case(
7236 &mut self,
7237 _: &ConvertToUpperCase,
7238 window: &mut Window,
7239 cx: &mut Context<Self>,
7240 ) {
7241 self.manipulate_text(window, cx, |text| text.to_uppercase())
7242 }
7243
7244 pub fn convert_to_lower_case(
7245 &mut self,
7246 _: &ConvertToLowerCase,
7247 window: &mut Window,
7248 cx: &mut Context<Self>,
7249 ) {
7250 self.manipulate_text(window, cx, |text| text.to_lowercase())
7251 }
7252
7253 pub fn convert_to_title_case(
7254 &mut self,
7255 _: &ConvertToTitleCase,
7256 window: &mut Window,
7257 cx: &mut Context<Self>,
7258 ) {
7259 self.manipulate_text(window, cx, |text| {
7260 text.split('\n')
7261 .map(|line| line.to_case(Case::Title))
7262 .join("\n")
7263 })
7264 }
7265
7266 pub fn convert_to_snake_case(
7267 &mut self,
7268 _: &ConvertToSnakeCase,
7269 window: &mut Window,
7270 cx: &mut Context<Self>,
7271 ) {
7272 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7273 }
7274
7275 pub fn convert_to_kebab_case(
7276 &mut self,
7277 _: &ConvertToKebabCase,
7278 window: &mut Window,
7279 cx: &mut Context<Self>,
7280 ) {
7281 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7282 }
7283
7284 pub fn convert_to_upper_camel_case(
7285 &mut self,
7286 _: &ConvertToUpperCamelCase,
7287 window: &mut Window,
7288 cx: &mut Context<Self>,
7289 ) {
7290 self.manipulate_text(window, cx, |text| {
7291 text.split('\n')
7292 .map(|line| line.to_case(Case::UpperCamel))
7293 .join("\n")
7294 })
7295 }
7296
7297 pub fn convert_to_lower_camel_case(
7298 &mut self,
7299 _: &ConvertToLowerCamelCase,
7300 window: &mut Window,
7301 cx: &mut Context<Self>,
7302 ) {
7303 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7304 }
7305
7306 pub fn convert_to_opposite_case(
7307 &mut self,
7308 _: &ConvertToOppositeCase,
7309 window: &mut Window,
7310 cx: &mut Context<Self>,
7311 ) {
7312 self.manipulate_text(window, cx, |text| {
7313 text.chars()
7314 .fold(String::with_capacity(text.len()), |mut t, c| {
7315 if c.is_uppercase() {
7316 t.extend(c.to_lowercase());
7317 } else {
7318 t.extend(c.to_uppercase());
7319 }
7320 t
7321 })
7322 })
7323 }
7324
7325 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7326 where
7327 Fn: FnMut(&str) -> String,
7328 {
7329 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7330 let buffer = self.buffer.read(cx).snapshot(cx);
7331
7332 let mut new_selections = Vec::new();
7333 let mut edits = Vec::new();
7334 let mut selection_adjustment = 0i32;
7335
7336 for selection in self.selections.all::<usize>(cx) {
7337 let selection_is_empty = selection.is_empty();
7338
7339 let (start, end) = if selection_is_empty {
7340 let word_range = movement::surrounding_word(
7341 &display_map,
7342 selection.start.to_display_point(&display_map),
7343 );
7344 let start = word_range.start.to_offset(&display_map, Bias::Left);
7345 let end = word_range.end.to_offset(&display_map, Bias::Left);
7346 (start, end)
7347 } else {
7348 (selection.start, selection.end)
7349 };
7350
7351 let text = buffer.text_for_range(start..end).collect::<String>();
7352 let old_length = text.len() as i32;
7353 let text = callback(&text);
7354
7355 new_selections.push(Selection {
7356 start: (start as i32 - selection_adjustment) as usize,
7357 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7358 goal: SelectionGoal::None,
7359 ..selection
7360 });
7361
7362 selection_adjustment += old_length - text.len() as i32;
7363
7364 edits.push((start..end, text));
7365 }
7366
7367 self.transact(window, cx, |this, window, cx| {
7368 this.buffer.update(cx, |buffer, cx| {
7369 buffer.edit(edits, None, cx);
7370 });
7371
7372 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7373 s.select(new_selections);
7374 });
7375
7376 this.request_autoscroll(Autoscroll::fit(), cx);
7377 });
7378 }
7379
7380 pub fn duplicate(
7381 &mut self,
7382 upwards: bool,
7383 whole_lines: bool,
7384 window: &mut Window,
7385 cx: &mut Context<Self>,
7386 ) {
7387 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7388 let buffer = &display_map.buffer_snapshot;
7389 let selections = self.selections.all::<Point>(cx);
7390
7391 let mut edits = Vec::new();
7392 let mut selections_iter = selections.iter().peekable();
7393 while let Some(selection) = selections_iter.next() {
7394 let mut rows = selection.spanned_rows(false, &display_map);
7395 // duplicate line-wise
7396 if whole_lines || selection.start == selection.end {
7397 // Avoid duplicating the same lines twice.
7398 while let Some(next_selection) = selections_iter.peek() {
7399 let next_rows = next_selection.spanned_rows(false, &display_map);
7400 if next_rows.start < rows.end {
7401 rows.end = next_rows.end;
7402 selections_iter.next().unwrap();
7403 } else {
7404 break;
7405 }
7406 }
7407
7408 // Copy the text from the selected row region and splice it either at the start
7409 // or end of the region.
7410 let start = Point::new(rows.start.0, 0);
7411 let end = Point::new(
7412 rows.end.previous_row().0,
7413 buffer.line_len(rows.end.previous_row()),
7414 );
7415 let text = buffer
7416 .text_for_range(start..end)
7417 .chain(Some("\n"))
7418 .collect::<String>();
7419 let insert_location = if upwards {
7420 Point::new(rows.end.0, 0)
7421 } else {
7422 start
7423 };
7424 edits.push((insert_location..insert_location, text));
7425 } else {
7426 // duplicate character-wise
7427 let start = selection.start;
7428 let end = selection.end;
7429 let text = buffer.text_for_range(start..end).collect::<String>();
7430 edits.push((selection.end..selection.end, text));
7431 }
7432 }
7433
7434 self.transact(window, cx, |this, _, cx| {
7435 this.buffer.update(cx, |buffer, cx| {
7436 buffer.edit(edits, None, cx);
7437 });
7438
7439 this.request_autoscroll(Autoscroll::fit(), cx);
7440 });
7441 }
7442
7443 pub fn duplicate_line_up(
7444 &mut self,
7445 _: &DuplicateLineUp,
7446 window: &mut Window,
7447 cx: &mut Context<Self>,
7448 ) {
7449 self.duplicate(true, true, window, cx);
7450 }
7451
7452 pub fn duplicate_line_down(
7453 &mut self,
7454 _: &DuplicateLineDown,
7455 window: &mut Window,
7456 cx: &mut Context<Self>,
7457 ) {
7458 self.duplicate(false, true, window, cx);
7459 }
7460
7461 pub fn duplicate_selection(
7462 &mut self,
7463 _: &DuplicateSelection,
7464 window: &mut Window,
7465 cx: &mut Context<Self>,
7466 ) {
7467 self.duplicate(false, false, window, cx);
7468 }
7469
7470 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7471 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7472 let buffer = self.buffer.read(cx).snapshot(cx);
7473
7474 let mut edits = Vec::new();
7475 let mut unfold_ranges = Vec::new();
7476 let mut refold_creases = Vec::new();
7477
7478 let selections = self.selections.all::<Point>(cx);
7479 let mut selections = selections.iter().peekable();
7480 let mut contiguous_row_selections = Vec::new();
7481 let mut new_selections = Vec::new();
7482
7483 while let Some(selection) = selections.next() {
7484 // Find all the selections that span a contiguous row range
7485 let (start_row, end_row) = consume_contiguous_rows(
7486 &mut contiguous_row_selections,
7487 selection,
7488 &display_map,
7489 &mut selections,
7490 );
7491
7492 // Move the text spanned by the row range to be before the line preceding the row range
7493 if start_row.0 > 0 {
7494 let range_to_move = Point::new(
7495 start_row.previous_row().0,
7496 buffer.line_len(start_row.previous_row()),
7497 )
7498 ..Point::new(
7499 end_row.previous_row().0,
7500 buffer.line_len(end_row.previous_row()),
7501 );
7502 let insertion_point = display_map
7503 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7504 .0;
7505
7506 // Don't move lines across excerpts
7507 if buffer
7508 .excerpt_containing(insertion_point..range_to_move.end)
7509 .is_some()
7510 {
7511 let text = buffer
7512 .text_for_range(range_to_move.clone())
7513 .flat_map(|s| s.chars())
7514 .skip(1)
7515 .chain(['\n'])
7516 .collect::<String>();
7517
7518 edits.push((
7519 buffer.anchor_after(range_to_move.start)
7520 ..buffer.anchor_before(range_to_move.end),
7521 String::new(),
7522 ));
7523 let insertion_anchor = buffer.anchor_after(insertion_point);
7524 edits.push((insertion_anchor..insertion_anchor, text));
7525
7526 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7527
7528 // Move selections up
7529 new_selections.extend(contiguous_row_selections.drain(..).map(
7530 |mut selection| {
7531 selection.start.row -= row_delta;
7532 selection.end.row -= row_delta;
7533 selection
7534 },
7535 ));
7536
7537 // Move folds up
7538 unfold_ranges.push(range_to_move.clone());
7539 for fold in display_map.folds_in_range(
7540 buffer.anchor_before(range_to_move.start)
7541 ..buffer.anchor_after(range_to_move.end),
7542 ) {
7543 let mut start = fold.range.start.to_point(&buffer);
7544 let mut end = fold.range.end.to_point(&buffer);
7545 start.row -= row_delta;
7546 end.row -= row_delta;
7547 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7548 }
7549 }
7550 }
7551
7552 // If we didn't move line(s), preserve the existing selections
7553 new_selections.append(&mut contiguous_row_selections);
7554 }
7555
7556 self.transact(window, cx, |this, window, cx| {
7557 this.unfold_ranges(&unfold_ranges, true, true, cx);
7558 this.buffer.update(cx, |buffer, cx| {
7559 for (range, text) in edits {
7560 buffer.edit([(range, text)], None, cx);
7561 }
7562 });
7563 this.fold_creases(refold_creases, true, window, cx);
7564 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7565 s.select(new_selections);
7566 })
7567 });
7568 }
7569
7570 pub fn move_line_down(
7571 &mut self,
7572 _: &MoveLineDown,
7573 window: &mut Window,
7574 cx: &mut Context<Self>,
7575 ) {
7576 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7577 let buffer = self.buffer.read(cx).snapshot(cx);
7578
7579 let mut edits = Vec::new();
7580 let mut unfold_ranges = Vec::new();
7581 let mut refold_creases = Vec::new();
7582
7583 let selections = self.selections.all::<Point>(cx);
7584 let mut selections = selections.iter().peekable();
7585 let mut contiguous_row_selections = Vec::new();
7586 let mut new_selections = Vec::new();
7587
7588 while let Some(selection) = selections.next() {
7589 // Find all the selections that span a contiguous row range
7590 let (start_row, end_row) = consume_contiguous_rows(
7591 &mut contiguous_row_selections,
7592 selection,
7593 &display_map,
7594 &mut selections,
7595 );
7596
7597 // Move the text spanned by the row range to be after the last line of the row range
7598 if end_row.0 <= buffer.max_point().row {
7599 let range_to_move =
7600 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7601 let insertion_point = display_map
7602 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7603 .0;
7604
7605 // Don't move lines across excerpt boundaries
7606 if buffer
7607 .excerpt_containing(range_to_move.start..insertion_point)
7608 .is_some()
7609 {
7610 let mut text = String::from("\n");
7611 text.extend(buffer.text_for_range(range_to_move.clone()));
7612 text.pop(); // Drop trailing newline
7613 edits.push((
7614 buffer.anchor_after(range_to_move.start)
7615 ..buffer.anchor_before(range_to_move.end),
7616 String::new(),
7617 ));
7618 let insertion_anchor = buffer.anchor_after(insertion_point);
7619 edits.push((insertion_anchor..insertion_anchor, text));
7620
7621 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7622
7623 // Move selections down
7624 new_selections.extend(contiguous_row_selections.drain(..).map(
7625 |mut selection| {
7626 selection.start.row += row_delta;
7627 selection.end.row += row_delta;
7628 selection
7629 },
7630 ));
7631
7632 // Move folds down
7633 unfold_ranges.push(range_to_move.clone());
7634 for fold in display_map.folds_in_range(
7635 buffer.anchor_before(range_to_move.start)
7636 ..buffer.anchor_after(range_to_move.end),
7637 ) {
7638 let mut start = fold.range.start.to_point(&buffer);
7639 let mut end = fold.range.end.to_point(&buffer);
7640 start.row += row_delta;
7641 end.row += row_delta;
7642 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7643 }
7644 }
7645 }
7646
7647 // If we didn't move line(s), preserve the existing selections
7648 new_selections.append(&mut contiguous_row_selections);
7649 }
7650
7651 self.transact(window, cx, |this, window, cx| {
7652 this.unfold_ranges(&unfold_ranges, true, true, cx);
7653 this.buffer.update(cx, |buffer, cx| {
7654 for (range, text) in edits {
7655 buffer.edit([(range, text)], None, cx);
7656 }
7657 });
7658 this.fold_creases(refold_creases, true, window, cx);
7659 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7660 s.select(new_selections)
7661 });
7662 });
7663 }
7664
7665 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7666 let text_layout_details = &self.text_layout_details(window);
7667 self.transact(window, cx, |this, window, cx| {
7668 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7669 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7670 let line_mode = s.line_mode;
7671 s.move_with(|display_map, selection| {
7672 if !selection.is_empty() || line_mode {
7673 return;
7674 }
7675
7676 let mut head = selection.head();
7677 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7678 if head.column() == display_map.line_len(head.row()) {
7679 transpose_offset = display_map
7680 .buffer_snapshot
7681 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7682 }
7683
7684 if transpose_offset == 0 {
7685 return;
7686 }
7687
7688 *head.column_mut() += 1;
7689 head = display_map.clip_point(head, Bias::Right);
7690 let goal = SelectionGoal::HorizontalPosition(
7691 display_map
7692 .x_for_display_point(head, text_layout_details)
7693 .into(),
7694 );
7695 selection.collapse_to(head, goal);
7696
7697 let transpose_start = display_map
7698 .buffer_snapshot
7699 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7700 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7701 let transpose_end = display_map
7702 .buffer_snapshot
7703 .clip_offset(transpose_offset + 1, Bias::Right);
7704 if let Some(ch) =
7705 display_map.buffer_snapshot.chars_at(transpose_start).next()
7706 {
7707 edits.push((transpose_start..transpose_offset, String::new()));
7708 edits.push((transpose_end..transpose_end, ch.to_string()));
7709 }
7710 }
7711 });
7712 edits
7713 });
7714 this.buffer
7715 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7716 let selections = this.selections.all::<usize>(cx);
7717 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7718 s.select(selections);
7719 });
7720 });
7721 }
7722
7723 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7724 self.rewrap_impl(IsVimMode::No, cx)
7725 }
7726
7727 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7728 let buffer = self.buffer.read(cx).snapshot(cx);
7729 let selections = self.selections.all::<Point>(cx);
7730 let mut selections = selections.iter().peekable();
7731
7732 let mut edits = Vec::new();
7733 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7734
7735 while let Some(selection) = selections.next() {
7736 let mut start_row = selection.start.row;
7737 let mut end_row = selection.end.row;
7738
7739 // Skip selections that overlap with a range that has already been rewrapped.
7740 let selection_range = start_row..end_row;
7741 if rewrapped_row_ranges
7742 .iter()
7743 .any(|range| range.overlaps(&selection_range))
7744 {
7745 continue;
7746 }
7747
7748 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7749
7750 // Since not all lines in the selection may be at the same indent
7751 // level, choose the indent size that is the most common between all
7752 // of the lines.
7753 //
7754 // If there is a tie, we use the deepest indent.
7755 let (indent_size, indent_end) = {
7756 let mut indent_size_occurrences = HashMap::default();
7757 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7758
7759 for row in start_row..=end_row {
7760 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7761 rows_by_indent_size.entry(indent).or_default().push(row);
7762 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7763 }
7764
7765 let indent_size = indent_size_occurrences
7766 .into_iter()
7767 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7768 .map(|(indent, _)| indent)
7769 .unwrap_or_default();
7770 let row = rows_by_indent_size[&indent_size][0];
7771 let indent_end = Point::new(row, indent_size.len);
7772
7773 (indent_size, indent_end)
7774 };
7775
7776 let mut line_prefix = indent_size.chars().collect::<String>();
7777
7778 let mut inside_comment = false;
7779 if let Some(comment_prefix) =
7780 buffer
7781 .language_scope_at(selection.head())
7782 .and_then(|language| {
7783 language
7784 .line_comment_prefixes()
7785 .iter()
7786 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7787 .cloned()
7788 })
7789 {
7790 line_prefix.push_str(&comment_prefix);
7791 inside_comment = true;
7792 }
7793
7794 let language_settings = buffer.settings_at(selection.head(), cx);
7795 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
7796 RewrapBehavior::InComments => inside_comment,
7797 RewrapBehavior::InSelections => !selection.is_empty(),
7798 RewrapBehavior::Anywhere => true,
7799 };
7800
7801 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
7802 if !should_rewrap {
7803 continue;
7804 }
7805
7806 if selection.is_empty() {
7807 'expand_upwards: while start_row > 0 {
7808 let prev_row = start_row - 1;
7809 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7810 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7811 {
7812 start_row = prev_row;
7813 } else {
7814 break 'expand_upwards;
7815 }
7816 }
7817
7818 'expand_downwards: while end_row < buffer.max_point().row {
7819 let next_row = end_row + 1;
7820 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7821 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7822 {
7823 end_row = next_row;
7824 } else {
7825 break 'expand_downwards;
7826 }
7827 }
7828 }
7829
7830 let start = Point::new(start_row, 0);
7831 let start_offset = start.to_offset(&buffer);
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 mut diff_options = DiffOptions::default();
7862 if is_vim_mode == IsVimMode::Yes {
7863 diff_options.max_word_diff_len = 0;
7864 diff_options.max_word_diff_line_count = 0;
7865 } else {
7866 diff_options.max_word_diff_len = usize::MAX;
7867 diff_options.max_word_diff_line_count = usize::MAX;
7868 }
7869
7870 for (old_range, new_text) in
7871 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
7872 {
7873 let edit_start = buffer.anchor_after(start_offset + old_range.start);
7874 let edit_end = buffer.anchor_after(start_offset + old_range.end);
7875 edits.push((edit_start..edit_end, new_text));
7876 }
7877
7878 rewrapped_row_ranges.push(start_row..=end_row);
7879 }
7880
7881 self.buffer
7882 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7883 }
7884
7885 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7886 let mut text = String::new();
7887 let buffer = self.buffer.read(cx).snapshot(cx);
7888 let mut selections = self.selections.all::<Point>(cx);
7889 let mut clipboard_selections = Vec::with_capacity(selections.len());
7890 {
7891 let max_point = buffer.max_point();
7892 let mut is_first = true;
7893 for selection in &mut selections {
7894 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7895 if is_entire_line {
7896 selection.start = Point::new(selection.start.row, 0);
7897 if !selection.is_empty() && selection.end.column == 0 {
7898 selection.end = cmp::min(max_point, selection.end);
7899 } else {
7900 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7901 }
7902 selection.goal = SelectionGoal::None;
7903 }
7904 if is_first {
7905 is_first = false;
7906 } else {
7907 text += "\n";
7908 }
7909 let mut len = 0;
7910 for chunk in buffer.text_for_range(selection.start..selection.end) {
7911 text.push_str(chunk);
7912 len += chunk.len();
7913 }
7914 clipboard_selections.push(ClipboardSelection {
7915 len,
7916 is_entire_line,
7917 first_line_indent: buffer
7918 .indent_size_for_line(MultiBufferRow(selection.start.row))
7919 .len,
7920 });
7921 }
7922 }
7923
7924 self.transact(window, cx, |this, window, cx| {
7925 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7926 s.select(selections);
7927 });
7928 this.insert("", window, cx);
7929 });
7930 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7931 }
7932
7933 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7934 let item = self.cut_common(window, cx);
7935 cx.write_to_clipboard(item);
7936 }
7937
7938 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7939 self.change_selections(None, window, cx, |s| {
7940 s.move_with(|snapshot, sel| {
7941 if sel.is_empty() {
7942 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7943 }
7944 });
7945 });
7946 let item = self.cut_common(window, cx);
7947 cx.set_global(KillRing(item))
7948 }
7949
7950 pub fn kill_ring_yank(
7951 &mut self,
7952 _: &KillRingYank,
7953 window: &mut Window,
7954 cx: &mut Context<Self>,
7955 ) {
7956 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7957 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7958 (kill_ring.text().to_string(), kill_ring.metadata_json())
7959 } else {
7960 return;
7961 }
7962 } else {
7963 return;
7964 };
7965 self.do_paste(&text, metadata, false, window, cx);
7966 }
7967
7968 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7969 let selections = self.selections.all::<Point>(cx);
7970 let buffer = self.buffer.read(cx).read(cx);
7971 let mut text = String::new();
7972
7973 let mut clipboard_selections = Vec::with_capacity(selections.len());
7974 {
7975 let max_point = buffer.max_point();
7976 let mut is_first = true;
7977 for selection in selections.iter() {
7978 let mut start = selection.start;
7979 let mut end = selection.end;
7980 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7981 if is_entire_line {
7982 start = Point::new(start.row, 0);
7983 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7984 }
7985 if is_first {
7986 is_first = false;
7987 } else {
7988 text += "\n";
7989 }
7990 let mut len = 0;
7991 for chunk in buffer.text_for_range(start..end) {
7992 text.push_str(chunk);
7993 len += chunk.len();
7994 }
7995 clipboard_selections.push(ClipboardSelection {
7996 len,
7997 is_entire_line,
7998 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7999 });
8000 }
8001 }
8002
8003 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8004 text,
8005 clipboard_selections,
8006 ));
8007 }
8008
8009 pub fn do_paste(
8010 &mut self,
8011 text: &String,
8012 clipboard_selections: Option<Vec<ClipboardSelection>>,
8013 handle_entire_lines: bool,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 if self.read_only(cx) {
8018 return;
8019 }
8020
8021 let clipboard_text = Cow::Borrowed(text);
8022
8023 self.transact(window, cx, |this, window, cx| {
8024 if let Some(mut clipboard_selections) = clipboard_selections {
8025 let old_selections = this.selections.all::<usize>(cx);
8026 let all_selections_were_entire_line =
8027 clipboard_selections.iter().all(|s| s.is_entire_line);
8028 let first_selection_indent_column =
8029 clipboard_selections.first().map(|s| s.first_line_indent);
8030 if clipboard_selections.len() != old_selections.len() {
8031 clipboard_selections.drain(..);
8032 }
8033 let cursor_offset = this.selections.last::<usize>(cx).head();
8034 let mut auto_indent_on_paste = true;
8035
8036 this.buffer.update(cx, |buffer, cx| {
8037 let snapshot = buffer.read(cx);
8038 auto_indent_on_paste =
8039 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8040
8041 let mut start_offset = 0;
8042 let mut edits = Vec::new();
8043 let mut original_indent_columns = Vec::new();
8044 for (ix, selection) in old_selections.iter().enumerate() {
8045 let to_insert;
8046 let entire_line;
8047 let original_indent_column;
8048 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8049 let end_offset = start_offset + clipboard_selection.len;
8050 to_insert = &clipboard_text[start_offset..end_offset];
8051 entire_line = clipboard_selection.is_entire_line;
8052 start_offset = end_offset + 1;
8053 original_indent_column = Some(clipboard_selection.first_line_indent);
8054 } else {
8055 to_insert = clipboard_text.as_str();
8056 entire_line = all_selections_were_entire_line;
8057 original_indent_column = first_selection_indent_column
8058 }
8059
8060 // If the corresponding selection was empty when this slice of the
8061 // clipboard text was written, then the entire line containing the
8062 // selection was copied. If this selection is also currently empty,
8063 // then paste the line before the current line of the buffer.
8064 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8065 let column = selection.start.to_point(&snapshot).column as usize;
8066 let line_start = selection.start - column;
8067 line_start..line_start
8068 } else {
8069 selection.range()
8070 };
8071
8072 edits.push((range, to_insert));
8073 original_indent_columns.extend(original_indent_column);
8074 }
8075 drop(snapshot);
8076
8077 buffer.edit(
8078 edits,
8079 if auto_indent_on_paste {
8080 Some(AutoindentMode::Block {
8081 original_indent_columns,
8082 })
8083 } else {
8084 None
8085 },
8086 cx,
8087 );
8088 });
8089
8090 let selections = this.selections.all::<usize>(cx);
8091 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8092 s.select(selections)
8093 });
8094 } else {
8095 this.insert(&clipboard_text, window, cx);
8096 }
8097 });
8098 }
8099
8100 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8101 if let Some(item) = cx.read_from_clipboard() {
8102 let entries = item.entries();
8103
8104 match entries.first() {
8105 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8106 // of all the pasted entries.
8107 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8108 .do_paste(
8109 clipboard_string.text(),
8110 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8111 true,
8112 window,
8113 cx,
8114 ),
8115 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8116 }
8117 }
8118 }
8119
8120 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8121 if self.read_only(cx) {
8122 return;
8123 }
8124
8125 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8126 if let Some((selections, _)) =
8127 self.selection_history.transaction(transaction_id).cloned()
8128 {
8129 self.change_selections(None, window, cx, |s| {
8130 s.select_anchors(selections.to_vec());
8131 });
8132 }
8133 self.request_autoscroll(Autoscroll::fit(), cx);
8134 self.unmark_text(window, cx);
8135 self.refresh_inline_completion(true, false, window, cx);
8136 cx.emit(EditorEvent::Edited { transaction_id });
8137 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8138 }
8139 }
8140
8141 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8142 if self.read_only(cx) {
8143 return;
8144 }
8145
8146 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8147 if let Some((_, Some(selections))) =
8148 self.selection_history.transaction(transaction_id).cloned()
8149 {
8150 self.change_selections(None, window, cx, |s| {
8151 s.select_anchors(selections.to_vec());
8152 });
8153 }
8154 self.request_autoscroll(Autoscroll::fit(), cx);
8155 self.unmark_text(window, cx);
8156 self.refresh_inline_completion(true, false, window, cx);
8157 cx.emit(EditorEvent::Edited { transaction_id });
8158 }
8159 }
8160
8161 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8162 self.buffer
8163 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8164 }
8165
8166 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8167 self.buffer
8168 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8169 }
8170
8171 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8172 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8173 let line_mode = s.line_mode;
8174 s.move_with(|map, selection| {
8175 let cursor = if selection.is_empty() && !line_mode {
8176 movement::left(map, selection.start)
8177 } else {
8178 selection.start
8179 };
8180 selection.collapse_to(cursor, SelectionGoal::None);
8181 });
8182 })
8183 }
8184
8185 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8187 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8188 })
8189 }
8190
8191 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8192 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8193 let line_mode = s.line_mode;
8194 s.move_with(|map, selection| {
8195 let cursor = if selection.is_empty() && !line_mode {
8196 movement::right(map, selection.end)
8197 } else {
8198 selection.end
8199 };
8200 selection.collapse_to(cursor, SelectionGoal::None)
8201 });
8202 })
8203 }
8204
8205 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8207 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8208 })
8209 }
8210
8211 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8212 if self.take_rename(true, window, cx).is_some() {
8213 return;
8214 }
8215
8216 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8217 cx.propagate();
8218 return;
8219 }
8220
8221 let text_layout_details = &self.text_layout_details(window);
8222 let selection_count = self.selections.count();
8223 let first_selection = self.selections.first_anchor();
8224
8225 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8226 let line_mode = s.line_mode;
8227 s.move_with(|map, selection| {
8228 if !selection.is_empty() && !line_mode {
8229 selection.goal = SelectionGoal::None;
8230 }
8231 let (cursor, goal) = movement::up(
8232 map,
8233 selection.start,
8234 selection.goal,
8235 false,
8236 text_layout_details,
8237 );
8238 selection.collapse_to(cursor, goal);
8239 });
8240 });
8241
8242 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8243 {
8244 cx.propagate();
8245 }
8246 }
8247
8248 pub fn move_up_by_lines(
8249 &mut self,
8250 action: &MoveUpByLines,
8251 window: &mut Window,
8252 cx: &mut Context<Self>,
8253 ) {
8254 if self.take_rename(true, window, cx).is_some() {
8255 return;
8256 }
8257
8258 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8259 cx.propagate();
8260 return;
8261 }
8262
8263 let text_layout_details = &self.text_layout_details(window);
8264
8265 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8266 let line_mode = s.line_mode;
8267 s.move_with(|map, selection| {
8268 if !selection.is_empty() && !line_mode {
8269 selection.goal = SelectionGoal::None;
8270 }
8271 let (cursor, goal) = movement::up_by_rows(
8272 map,
8273 selection.start,
8274 action.lines,
8275 selection.goal,
8276 false,
8277 text_layout_details,
8278 );
8279 selection.collapse_to(cursor, goal);
8280 });
8281 })
8282 }
8283
8284 pub fn move_down_by_lines(
8285 &mut self,
8286 action: &MoveDownByLines,
8287 window: &mut Window,
8288 cx: &mut Context<Self>,
8289 ) {
8290 if self.take_rename(true, window, cx).is_some() {
8291 return;
8292 }
8293
8294 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8295 cx.propagate();
8296 return;
8297 }
8298
8299 let text_layout_details = &self.text_layout_details(window);
8300
8301 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8302 let line_mode = s.line_mode;
8303 s.move_with(|map, selection| {
8304 if !selection.is_empty() && !line_mode {
8305 selection.goal = SelectionGoal::None;
8306 }
8307 let (cursor, goal) = movement::down_by_rows(
8308 map,
8309 selection.start,
8310 action.lines,
8311 selection.goal,
8312 false,
8313 text_layout_details,
8314 );
8315 selection.collapse_to(cursor, goal);
8316 });
8317 })
8318 }
8319
8320 pub fn select_down_by_lines(
8321 &mut self,
8322 action: &SelectDownByLines,
8323 window: &mut Window,
8324 cx: &mut Context<Self>,
8325 ) {
8326 let text_layout_details = &self.text_layout_details(window);
8327 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8328 s.move_heads_with(|map, head, goal| {
8329 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8330 })
8331 })
8332 }
8333
8334 pub fn select_up_by_lines(
8335 &mut self,
8336 action: &SelectUpByLines,
8337 window: &mut Window,
8338 cx: &mut Context<Self>,
8339 ) {
8340 let text_layout_details = &self.text_layout_details(window);
8341 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8342 s.move_heads_with(|map, head, goal| {
8343 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8344 })
8345 })
8346 }
8347
8348 pub fn select_page_up(
8349 &mut self,
8350 _: &SelectPageUp,
8351 window: &mut Window,
8352 cx: &mut Context<Self>,
8353 ) {
8354 let Some(row_count) = self.visible_row_count() else {
8355 return;
8356 };
8357
8358 let text_layout_details = &self.text_layout_details(window);
8359
8360 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8361 s.move_heads_with(|map, head, goal| {
8362 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8363 })
8364 })
8365 }
8366
8367 pub fn move_page_up(
8368 &mut self,
8369 action: &MovePageUp,
8370 window: &mut Window,
8371 cx: &mut Context<Self>,
8372 ) {
8373 if self.take_rename(true, window, cx).is_some() {
8374 return;
8375 }
8376
8377 if self
8378 .context_menu
8379 .borrow_mut()
8380 .as_mut()
8381 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8382 .unwrap_or(false)
8383 {
8384 return;
8385 }
8386
8387 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8388 cx.propagate();
8389 return;
8390 }
8391
8392 let Some(row_count) = self.visible_row_count() else {
8393 return;
8394 };
8395
8396 let autoscroll = if action.center_cursor {
8397 Autoscroll::center()
8398 } else {
8399 Autoscroll::fit()
8400 };
8401
8402 let text_layout_details = &self.text_layout_details(window);
8403
8404 self.change_selections(Some(autoscroll), window, cx, |s| {
8405 let line_mode = s.line_mode;
8406 s.move_with(|map, selection| {
8407 if !selection.is_empty() && !line_mode {
8408 selection.goal = SelectionGoal::None;
8409 }
8410 let (cursor, goal) = movement::up_by_rows(
8411 map,
8412 selection.end,
8413 row_count,
8414 selection.goal,
8415 false,
8416 text_layout_details,
8417 );
8418 selection.collapse_to(cursor, goal);
8419 });
8420 });
8421 }
8422
8423 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8424 let text_layout_details = &self.text_layout_details(window);
8425 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8426 s.move_heads_with(|map, head, goal| {
8427 movement::up(map, head, goal, false, text_layout_details)
8428 })
8429 })
8430 }
8431
8432 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8433 self.take_rename(true, window, cx);
8434
8435 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8436 cx.propagate();
8437 return;
8438 }
8439
8440 let text_layout_details = &self.text_layout_details(window);
8441 let selection_count = self.selections.count();
8442 let first_selection = self.selections.first_anchor();
8443
8444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8445 let line_mode = s.line_mode;
8446 s.move_with(|map, selection| {
8447 if !selection.is_empty() && !line_mode {
8448 selection.goal = SelectionGoal::None;
8449 }
8450 let (cursor, goal) = movement::down(
8451 map,
8452 selection.end,
8453 selection.goal,
8454 false,
8455 text_layout_details,
8456 );
8457 selection.collapse_to(cursor, goal);
8458 });
8459 });
8460
8461 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8462 {
8463 cx.propagate();
8464 }
8465 }
8466
8467 pub fn select_page_down(
8468 &mut self,
8469 _: &SelectPageDown,
8470 window: &mut Window,
8471 cx: &mut Context<Self>,
8472 ) {
8473 let Some(row_count) = self.visible_row_count() else {
8474 return;
8475 };
8476
8477 let text_layout_details = &self.text_layout_details(window);
8478
8479 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8480 s.move_heads_with(|map, head, goal| {
8481 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8482 })
8483 })
8484 }
8485
8486 pub fn move_page_down(
8487 &mut self,
8488 action: &MovePageDown,
8489 window: &mut Window,
8490 cx: &mut Context<Self>,
8491 ) {
8492 if self.take_rename(true, window, cx).is_some() {
8493 return;
8494 }
8495
8496 if self
8497 .context_menu
8498 .borrow_mut()
8499 .as_mut()
8500 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8501 .unwrap_or(false)
8502 {
8503 return;
8504 }
8505
8506 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8507 cx.propagate();
8508 return;
8509 }
8510
8511 let Some(row_count) = self.visible_row_count() else {
8512 return;
8513 };
8514
8515 let autoscroll = if action.center_cursor {
8516 Autoscroll::center()
8517 } else {
8518 Autoscroll::fit()
8519 };
8520
8521 let text_layout_details = &self.text_layout_details(window);
8522 self.change_selections(Some(autoscroll), window, cx, |s| {
8523 let line_mode = s.line_mode;
8524 s.move_with(|map, selection| {
8525 if !selection.is_empty() && !line_mode {
8526 selection.goal = SelectionGoal::None;
8527 }
8528 let (cursor, goal) = movement::down_by_rows(
8529 map,
8530 selection.end,
8531 row_count,
8532 selection.goal,
8533 false,
8534 text_layout_details,
8535 );
8536 selection.collapse_to(cursor, goal);
8537 });
8538 });
8539 }
8540
8541 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8542 let text_layout_details = &self.text_layout_details(window);
8543 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8544 s.move_heads_with(|map, head, goal| {
8545 movement::down(map, head, goal, false, text_layout_details)
8546 })
8547 });
8548 }
8549
8550 pub fn context_menu_first(
8551 &mut self,
8552 _: &ContextMenuFirst,
8553 _window: &mut Window,
8554 cx: &mut Context<Self>,
8555 ) {
8556 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8557 context_menu.select_first(self.completion_provider.as_deref(), cx);
8558 }
8559 }
8560
8561 pub fn context_menu_prev(
8562 &mut self,
8563 _: &ContextMenuPrev,
8564 _window: &mut Window,
8565 cx: &mut Context<Self>,
8566 ) {
8567 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8568 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8569 }
8570 }
8571
8572 pub fn context_menu_next(
8573 &mut self,
8574 _: &ContextMenuNext,
8575 _window: &mut Window,
8576 cx: &mut Context<Self>,
8577 ) {
8578 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8579 context_menu.select_next(self.completion_provider.as_deref(), cx);
8580 }
8581 }
8582
8583 pub fn context_menu_last(
8584 &mut self,
8585 _: &ContextMenuLast,
8586 _window: &mut Window,
8587 cx: &mut Context<Self>,
8588 ) {
8589 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8590 context_menu.select_last(self.completion_provider.as_deref(), cx);
8591 }
8592 }
8593
8594 pub fn move_to_previous_word_start(
8595 &mut self,
8596 _: &MoveToPreviousWordStart,
8597 window: &mut Window,
8598 cx: &mut Context<Self>,
8599 ) {
8600 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8601 s.move_cursors_with(|map, head, _| {
8602 (
8603 movement::previous_word_start(map, head),
8604 SelectionGoal::None,
8605 )
8606 });
8607 })
8608 }
8609
8610 pub fn move_to_previous_subword_start(
8611 &mut self,
8612 _: &MoveToPreviousSubwordStart,
8613 window: &mut Window,
8614 cx: &mut Context<Self>,
8615 ) {
8616 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8617 s.move_cursors_with(|map, head, _| {
8618 (
8619 movement::previous_subword_start(map, head),
8620 SelectionGoal::None,
8621 )
8622 });
8623 })
8624 }
8625
8626 pub fn select_to_previous_word_start(
8627 &mut self,
8628 _: &SelectToPreviousWordStart,
8629 window: &mut Window,
8630 cx: &mut Context<Self>,
8631 ) {
8632 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8633 s.move_heads_with(|map, head, _| {
8634 (
8635 movement::previous_word_start(map, head),
8636 SelectionGoal::None,
8637 )
8638 });
8639 })
8640 }
8641
8642 pub fn select_to_previous_subword_start(
8643 &mut self,
8644 _: &SelectToPreviousSubwordStart,
8645 window: &mut Window,
8646 cx: &mut Context<Self>,
8647 ) {
8648 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8649 s.move_heads_with(|map, head, _| {
8650 (
8651 movement::previous_subword_start(map, head),
8652 SelectionGoal::None,
8653 )
8654 });
8655 })
8656 }
8657
8658 pub fn delete_to_previous_word_start(
8659 &mut self,
8660 action: &DeleteToPreviousWordStart,
8661 window: &mut Window,
8662 cx: &mut Context<Self>,
8663 ) {
8664 self.transact(window, cx, |this, window, cx| {
8665 this.select_autoclose_pair(window, cx);
8666 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8667 let line_mode = s.line_mode;
8668 s.move_with(|map, selection| {
8669 if selection.is_empty() && !line_mode {
8670 let cursor = if action.ignore_newlines {
8671 movement::previous_word_start(map, selection.head())
8672 } else {
8673 movement::previous_word_start_or_newline(map, selection.head())
8674 };
8675 selection.set_head(cursor, SelectionGoal::None);
8676 }
8677 });
8678 });
8679 this.insert("", window, cx);
8680 });
8681 }
8682
8683 pub fn delete_to_previous_subword_start(
8684 &mut self,
8685 _: &DeleteToPreviousSubwordStart,
8686 window: &mut Window,
8687 cx: &mut Context<Self>,
8688 ) {
8689 self.transact(window, cx, |this, window, cx| {
8690 this.select_autoclose_pair(window, cx);
8691 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8692 let line_mode = s.line_mode;
8693 s.move_with(|map, selection| {
8694 if selection.is_empty() && !line_mode {
8695 let cursor = movement::previous_subword_start(map, selection.head());
8696 selection.set_head(cursor, SelectionGoal::None);
8697 }
8698 });
8699 });
8700 this.insert("", window, cx);
8701 });
8702 }
8703
8704 pub fn move_to_next_word_end(
8705 &mut self,
8706 _: &MoveToNextWordEnd,
8707 window: &mut Window,
8708 cx: &mut Context<Self>,
8709 ) {
8710 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8711 s.move_cursors_with(|map, head, _| {
8712 (movement::next_word_end(map, head), SelectionGoal::None)
8713 });
8714 })
8715 }
8716
8717 pub fn move_to_next_subword_end(
8718 &mut self,
8719 _: &MoveToNextSubwordEnd,
8720 window: &mut Window,
8721 cx: &mut Context<Self>,
8722 ) {
8723 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8724 s.move_cursors_with(|map, head, _| {
8725 (movement::next_subword_end(map, head), SelectionGoal::None)
8726 });
8727 })
8728 }
8729
8730 pub fn select_to_next_word_end(
8731 &mut self,
8732 _: &SelectToNextWordEnd,
8733 window: &mut Window,
8734 cx: &mut Context<Self>,
8735 ) {
8736 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8737 s.move_heads_with(|map, head, _| {
8738 (movement::next_word_end(map, head), SelectionGoal::None)
8739 });
8740 })
8741 }
8742
8743 pub fn select_to_next_subword_end(
8744 &mut self,
8745 _: &SelectToNextSubwordEnd,
8746 window: &mut Window,
8747 cx: &mut Context<Self>,
8748 ) {
8749 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8750 s.move_heads_with(|map, head, _| {
8751 (movement::next_subword_end(map, head), SelectionGoal::None)
8752 });
8753 })
8754 }
8755
8756 pub fn delete_to_next_word_end(
8757 &mut self,
8758 action: &DeleteToNextWordEnd,
8759 window: &mut Window,
8760 cx: &mut Context<Self>,
8761 ) {
8762 self.transact(window, cx, |this, window, cx| {
8763 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8764 let line_mode = s.line_mode;
8765 s.move_with(|map, selection| {
8766 if selection.is_empty() && !line_mode {
8767 let cursor = if action.ignore_newlines {
8768 movement::next_word_end(map, selection.head())
8769 } else {
8770 movement::next_word_end_or_newline(map, selection.head())
8771 };
8772 selection.set_head(cursor, SelectionGoal::None);
8773 }
8774 });
8775 });
8776 this.insert("", window, cx);
8777 });
8778 }
8779
8780 pub fn delete_to_next_subword_end(
8781 &mut self,
8782 _: &DeleteToNextSubwordEnd,
8783 window: &mut Window,
8784 cx: &mut Context<Self>,
8785 ) {
8786 self.transact(window, cx, |this, window, cx| {
8787 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8788 s.move_with(|map, selection| {
8789 if selection.is_empty() {
8790 let cursor = movement::next_subword_end(map, selection.head());
8791 selection.set_head(cursor, SelectionGoal::None);
8792 }
8793 });
8794 });
8795 this.insert("", window, cx);
8796 });
8797 }
8798
8799 pub fn move_to_beginning_of_line(
8800 &mut self,
8801 action: &MoveToBeginningOfLine,
8802 window: &mut Window,
8803 cx: &mut Context<Self>,
8804 ) {
8805 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8806 s.move_cursors_with(|map, head, _| {
8807 (
8808 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8809 SelectionGoal::None,
8810 )
8811 });
8812 })
8813 }
8814
8815 pub fn select_to_beginning_of_line(
8816 &mut self,
8817 action: &SelectToBeginningOfLine,
8818 window: &mut Window,
8819 cx: &mut Context<Self>,
8820 ) {
8821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8822 s.move_heads_with(|map, head, _| {
8823 (
8824 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8825 SelectionGoal::None,
8826 )
8827 });
8828 });
8829 }
8830
8831 pub fn delete_to_beginning_of_line(
8832 &mut self,
8833 _: &DeleteToBeginningOfLine,
8834 window: &mut Window,
8835 cx: &mut Context<Self>,
8836 ) {
8837 self.transact(window, cx, |this, window, cx| {
8838 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8839 s.move_with(|_, selection| {
8840 selection.reversed = true;
8841 });
8842 });
8843
8844 this.select_to_beginning_of_line(
8845 &SelectToBeginningOfLine {
8846 stop_at_soft_wraps: false,
8847 },
8848 window,
8849 cx,
8850 );
8851 this.backspace(&Backspace, window, cx);
8852 });
8853 }
8854
8855 pub fn move_to_end_of_line(
8856 &mut self,
8857 action: &MoveToEndOfLine,
8858 window: &mut Window,
8859 cx: &mut Context<Self>,
8860 ) {
8861 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8862 s.move_cursors_with(|map, head, _| {
8863 (
8864 movement::line_end(map, head, action.stop_at_soft_wraps),
8865 SelectionGoal::None,
8866 )
8867 });
8868 })
8869 }
8870
8871 pub fn select_to_end_of_line(
8872 &mut self,
8873 action: &SelectToEndOfLine,
8874 window: &mut Window,
8875 cx: &mut Context<Self>,
8876 ) {
8877 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8878 s.move_heads_with(|map, head, _| {
8879 (
8880 movement::line_end(map, head, action.stop_at_soft_wraps),
8881 SelectionGoal::None,
8882 )
8883 });
8884 })
8885 }
8886
8887 pub fn delete_to_end_of_line(
8888 &mut self,
8889 _: &DeleteToEndOfLine,
8890 window: &mut Window,
8891 cx: &mut Context<Self>,
8892 ) {
8893 self.transact(window, cx, |this, window, cx| {
8894 this.select_to_end_of_line(
8895 &SelectToEndOfLine {
8896 stop_at_soft_wraps: false,
8897 },
8898 window,
8899 cx,
8900 );
8901 this.delete(&Delete, window, cx);
8902 });
8903 }
8904
8905 pub fn cut_to_end_of_line(
8906 &mut self,
8907 _: &CutToEndOfLine,
8908 window: &mut Window,
8909 cx: &mut Context<Self>,
8910 ) {
8911 self.transact(window, cx, |this, window, cx| {
8912 this.select_to_end_of_line(
8913 &SelectToEndOfLine {
8914 stop_at_soft_wraps: false,
8915 },
8916 window,
8917 cx,
8918 );
8919 this.cut(&Cut, window, cx);
8920 });
8921 }
8922
8923 pub fn move_to_start_of_paragraph(
8924 &mut self,
8925 _: &MoveToStartOfParagraph,
8926 window: &mut Window,
8927 cx: &mut Context<Self>,
8928 ) {
8929 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8930 cx.propagate();
8931 return;
8932 }
8933
8934 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8935 s.move_with(|map, selection| {
8936 selection.collapse_to(
8937 movement::start_of_paragraph(map, selection.head(), 1),
8938 SelectionGoal::None,
8939 )
8940 });
8941 })
8942 }
8943
8944 pub fn move_to_end_of_paragraph(
8945 &mut self,
8946 _: &MoveToEndOfParagraph,
8947 window: &mut Window,
8948 cx: &mut Context<Self>,
8949 ) {
8950 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8951 cx.propagate();
8952 return;
8953 }
8954
8955 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8956 s.move_with(|map, selection| {
8957 selection.collapse_to(
8958 movement::end_of_paragraph(map, selection.head(), 1),
8959 SelectionGoal::None,
8960 )
8961 });
8962 })
8963 }
8964
8965 pub fn select_to_start_of_paragraph(
8966 &mut self,
8967 _: &SelectToStartOfParagraph,
8968 window: &mut Window,
8969 cx: &mut Context<Self>,
8970 ) {
8971 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8972 cx.propagate();
8973 return;
8974 }
8975
8976 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8977 s.move_heads_with(|map, head, _| {
8978 (
8979 movement::start_of_paragraph(map, head, 1),
8980 SelectionGoal::None,
8981 )
8982 });
8983 })
8984 }
8985
8986 pub fn select_to_end_of_paragraph(
8987 &mut self,
8988 _: &SelectToEndOfParagraph,
8989 window: &mut Window,
8990 cx: &mut Context<Self>,
8991 ) {
8992 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8993 cx.propagate();
8994 return;
8995 }
8996
8997 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8998 s.move_heads_with(|map, head, _| {
8999 (
9000 movement::end_of_paragraph(map, head, 1),
9001 SelectionGoal::None,
9002 )
9003 });
9004 })
9005 }
9006
9007 pub fn move_to_beginning(
9008 &mut self,
9009 _: &MoveToBeginning,
9010 window: &mut Window,
9011 cx: &mut Context<Self>,
9012 ) {
9013 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9014 cx.propagate();
9015 return;
9016 }
9017
9018 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9019 s.select_ranges(vec![0..0]);
9020 });
9021 }
9022
9023 pub fn select_to_beginning(
9024 &mut self,
9025 _: &SelectToBeginning,
9026 window: &mut Window,
9027 cx: &mut Context<Self>,
9028 ) {
9029 let mut selection = self.selections.last::<Point>(cx);
9030 selection.set_head(Point::zero(), SelectionGoal::None);
9031
9032 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9033 s.select(vec![selection]);
9034 });
9035 }
9036
9037 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9038 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9039 cx.propagate();
9040 return;
9041 }
9042
9043 let cursor = self.buffer.read(cx).read(cx).len();
9044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9045 s.select_ranges(vec![cursor..cursor])
9046 });
9047 }
9048
9049 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9050 self.nav_history = nav_history;
9051 }
9052
9053 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9054 self.nav_history.as_ref()
9055 }
9056
9057 fn push_to_nav_history(
9058 &mut self,
9059 cursor_anchor: Anchor,
9060 new_position: Option<Point>,
9061 cx: &mut Context<Self>,
9062 ) {
9063 if let Some(nav_history) = self.nav_history.as_mut() {
9064 let buffer = self.buffer.read(cx).read(cx);
9065 let cursor_position = cursor_anchor.to_point(&buffer);
9066 let scroll_state = self.scroll_manager.anchor();
9067 let scroll_top_row = scroll_state.top_row(&buffer);
9068 drop(buffer);
9069
9070 if let Some(new_position) = new_position {
9071 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9072 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9073 return;
9074 }
9075 }
9076
9077 nav_history.push(
9078 Some(NavigationData {
9079 cursor_anchor,
9080 cursor_position,
9081 scroll_anchor: scroll_state,
9082 scroll_top_row,
9083 }),
9084 cx,
9085 );
9086 }
9087 }
9088
9089 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9090 let buffer = self.buffer.read(cx).snapshot(cx);
9091 let mut selection = self.selections.first::<usize>(cx);
9092 selection.set_head(buffer.len(), SelectionGoal::None);
9093 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9094 s.select(vec![selection]);
9095 });
9096 }
9097
9098 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9099 let end = self.buffer.read(cx).read(cx).len();
9100 self.change_selections(None, window, cx, |s| {
9101 s.select_ranges(vec![0..end]);
9102 });
9103 }
9104
9105 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9106 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9107 let mut selections = self.selections.all::<Point>(cx);
9108 let max_point = display_map.buffer_snapshot.max_point();
9109 for selection in &mut selections {
9110 let rows = selection.spanned_rows(true, &display_map);
9111 selection.start = Point::new(rows.start.0, 0);
9112 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9113 selection.reversed = false;
9114 }
9115 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9116 s.select(selections);
9117 });
9118 }
9119
9120 pub fn split_selection_into_lines(
9121 &mut self,
9122 _: &SplitSelectionIntoLines,
9123 window: &mut Window,
9124 cx: &mut Context<Self>,
9125 ) {
9126 let selections = self
9127 .selections
9128 .all::<Point>(cx)
9129 .into_iter()
9130 .map(|selection| selection.start..selection.end)
9131 .collect::<Vec<_>>();
9132 self.unfold_ranges(&selections, true, true, cx);
9133
9134 let mut new_selection_ranges = Vec::new();
9135 {
9136 let buffer = self.buffer.read(cx).read(cx);
9137 for selection in selections {
9138 for row in selection.start.row..selection.end.row {
9139 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9140 new_selection_ranges.push(cursor..cursor);
9141 }
9142
9143 let is_multiline_selection = selection.start.row != selection.end.row;
9144 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9145 // so this action feels more ergonomic when paired with other selection operations
9146 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9147 if !should_skip_last {
9148 new_selection_ranges.push(selection.end..selection.end);
9149 }
9150 }
9151 }
9152 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9153 s.select_ranges(new_selection_ranges);
9154 });
9155 }
9156
9157 pub fn add_selection_above(
9158 &mut self,
9159 _: &AddSelectionAbove,
9160 window: &mut Window,
9161 cx: &mut Context<Self>,
9162 ) {
9163 self.add_selection(true, window, cx);
9164 }
9165
9166 pub fn add_selection_below(
9167 &mut self,
9168 _: &AddSelectionBelow,
9169 window: &mut Window,
9170 cx: &mut Context<Self>,
9171 ) {
9172 self.add_selection(false, window, cx);
9173 }
9174
9175 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9176 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9177 let mut selections = self.selections.all::<Point>(cx);
9178 let text_layout_details = self.text_layout_details(window);
9179 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9180 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9181 let range = oldest_selection.display_range(&display_map).sorted();
9182
9183 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9184 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9185 let positions = start_x.min(end_x)..start_x.max(end_x);
9186
9187 selections.clear();
9188 let mut stack = Vec::new();
9189 for row in range.start.row().0..=range.end.row().0 {
9190 if let Some(selection) = self.selections.build_columnar_selection(
9191 &display_map,
9192 DisplayRow(row),
9193 &positions,
9194 oldest_selection.reversed,
9195 &text_layout_details,
9196 ) {
9197 stack.push(selection.id);
9198 selections.push(selection);
9199 }
9200 }
9201
9202 if above {
9203 stack.reverse();
9204 }
9205
9206 AddSelectionsState { above, stack }
9207 });
9208
9209 let last_added_selection = *state.stack.last().unwrap();
9210 let mut new_selections = Vec::new();
9211 if above == state.above {
9212 let end_row = if above {
9213 DisplayRow(0)
9214 } else {
9215 display_map.max_point().row()
9216 };
9217
9218 'outer: for selection in selections {
9219 if selection.id == last_added_selection {
9220 let range = selection.display_range(&display_map).sorted();
9221 debug_assert_eq!(range.start.row(), range.end.row());
9222 let mut row = range.start.row();
9223 let positions =
9224 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9225 px(start)..px(end)
9226 } else {
9227 let start_x =
9228 display_map.x_for_display_point(range.start, &text_layout_details);
9229 let end_x =
9230 display_map.x_for_display_point(range.end, &text_layout_details);
9231 start_x.min(end_x)..start_x.max(end_x)
9232 };
9233
9234 while row != end_row {
9235 if above {
9236 row.0 -= 1;
9237 } else {
9238 row.0 += 1;
9239 }
9240
9241 if let Some(new_selection) = self.selections.build_columnar_selection(
9242 &display_map,
9243 row,
9244 &positions,
9245 selection.reversed,
9246 &text_layout_details,
9247 ) {
9248 state.stack.push(new_selection.id);
9249 if above {
9250 new_selections.push(new_selection);
9251 new_selections.push(selection);
9252 } else {
9253 new_selections.push(selection);
9254 new_selections.push(new_selection);
9255 }
9256
9257 continue 'outer;
9258 }
9259 }
9260 }
9261
9262 new_selections.push(selection);
9263 }
9264 } else {
9265 new_selections = selections;
9266 new_selections.retain(|s| s.id != last_added_selection);
9267 state.stack.pop();
9268 }
9269
9270 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9271 s.select(new_selections);
9272 });
9273 if state.stack.len() > 1 {
9274 self.add_selections_state = Some(state);
9275 }
9276 }
9277
9278 pub fn select_next_match_internal(
9279 &mut self,
9280 display_map: &DisplaySnapshot,
9281 replace_newest: bool,
9282 autoscroll: Option<Autoscroll>,
9283 window: &mut Window,
9284 cx: &mut Context<Self>,
9285 ) -> Result<()> {
9286 fn select_next_match_ranges(
9287 this: &mut Editor,
9288 range: Range<usize>,
9289 replace_newest: bool,
9290 auto_scroll: Option<Autoscroll>,
9291 window: &mut Window,
9292 cx: &mut Context<Editor>,
9293 ) {
9294 this.unfold_ranges(&[range.clone()], false, true, cx);
9295 this.change_selections(auto_scroll, window, cx, |s| {
9296 if replace_newest {
9297 s.delete(s.newest_anchor().id);
9298 }
9299 s.insert_range(range.clone());
9300 });
9301 }
9302
9303 let buffer = &display_map.buffer_snapshot;
9304 let mut selections = self.selections.all::<usize>(cx);
9305 if let Some(mut select_next_state) = self.select_next_state.take() {
9306 let query = &select_next_state.query;
9307 if !select_next_state.done {
9308 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9309 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9310 let mut next_selected_range = None;
9311
9312 let bytes_after_last_selection =
9313 buffer.bytes_in_range(last_selection.end..buffer.len());
9314 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9315 let query_matches = query
9316 .stream_find_iter(bytes_after_last_selection)
9317 .map(|result| (last_selection.end, result))
9318 .chain(
9319 query
9320 .stream_find_iter(bytes_before_first_selection)
9321 .map(|result| (0, result)),
9322 );
9323
9324 for (start_offset, query_match) in query_matches {
9325 let query_match = query_match.unwrap(); // can only fail due to I/O
9326 let offset_range =
9327 start_offset + query_match.start()..start_offset + query_match.end();
9328 let display_range = offset_range.start.to_display_point(display_map)
9329 ..offset_range.end.to_display_point(display_map);
9330
9331 if !select_next_state.wordwise
9332 || (!movement::is_inside_word(display_map, display_range.start)
9333 && !movement::is_inside_word(display_map, display_range.end))
9334 {
9335 // TODO: This is n^2, because we might check all the selections
9336 if !selections
9337 .iter()
9338 .any(|selection| selection.range().overlaps(&offset_range))
9339 {
9340 next_selected_range = Some(offset_range);
9341 break;
9342 }
9343 }
9344 }
9345
9346 if let Some(next_selected_range) = next_selected_range {
9347 select_next_match_ranges(
9348 self,
9349 next_selected_range,
9350 replace_newest,
9351 autoscroll,
9352 window,
9353 cx,
9354 );
9355 } else {
9356 select_next_state.done = true;
9357 }
9358 }
9359
9360 self.select_next_state = Some(select_next_state);
9361 } else {
9362 let mut only_carets = true;
9363 let mut same_text_selected = true;
9364 let mut selected_text = None;
9365
9366 let mut selections_iter = selections.iter().peekable();
9367 while let Some(selection) = selections_iter.next() {
9368 if selection.start != selection.end {
9369 only_carets = false;
9370 }
9371
9372 if same_text_selected {
9373 if selected_text.is_none() {
9374 selected_text =
9375 Some(buffer.text_for_range(selection.range()).collect::<String>());
9376 }
9377
9378 if let Some(next_selection) = selections_iter.peek() {
9379 if next_selection.range().len() == selection.range().len() {
9380 let next_selected_text = buffer
9381 .text_for_range(next_selection.range())
9382 .collect::<String>();
9383 if Some(next_selected_text) != selected_text {
9384 same_text_selected = false;
9385 selected_text = None;
9386 }
9387 } else {
9388 same_text_selected = false;
9389 selected_text = None;
9390 }
9391 }
9392 }
9393 }
9394
9395 if only_carets {
9396 for selection in &mut selections {
9397 let word_range = movement::surrounding_word(
9398 display_map,
9399 selection.start.to_display_point(display_map),
9400 );
9401 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9402 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9403 selection.goal = SelectionGoal::None;
9404 selection.reversed = false;
9405 select_next_match_ranges(
9406 self,
9407 selection.start..selection.end,
9408 replace_newest,
9409 autoscroll,
9410 window,
9411 cx,
9412 );
9413 }
9414
9415 if selections.len() == 1 {
9416 let selection = selections
9417 .last()
9418 .expect("ensured that there's only one selection");
9419 let query = buffer
9420 .text_for_range(selection.start..selection.end)
9421 .collect::<String>();
9422 let is_empty = query.is_empty();
9423 let select_state = SelectNextState {
9424 query: AhoCorasick::new(&[query])?,
9425 wordwise: true,
9426 done: is_empty,
9427 };
9428 self.select_next_state = Some(select_state);
9429 } else {
9430 self.select_next_state = None;
9431 }
9432 } else if let Some(selected_text) = selected_text {
9433 self.select_next_state = Some(SelectNextState {
9434 query: AhoCorasick::new(&[selected_text])?,
9435 wordwise: false,
9436 done: false,
9437 });
9438 self.select_next_match_internal(
9439 display_map,
9440 replace_newest,
9441 autoscroll,
9442 window,
9443 cx,
9444 )?;
9445 }
9446 }
9447 Ok(())
9448 }
9449
9450 pub fn select_all_matches(
9451 &mut self,
9452 _action: &SelectAllMatches,
9453 window: &mut Window,
9454 cx: &mut Context<Self>,
9455 ) -> Result<()> {
9456 self.push_to_selection_history();
9457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9458
9459 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9460 let Some(select_next_state) = self.select_next_state.as_mut() else {
9461 return Ok(());
9462 };
9463 if select_next_state.done {
9464 return Ok(());
9465 }
9466
9467 let mut new_selections = self.selections.all::<usize>(cx);
9468
9469 let buffer = &display_map.buffer_snapshot;
9470 let query_matches = select_next_state
9471 .query
9472 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9473
9474 for query_match in query_matches {
9475 let query_match = query_match.unwrap(); // can only fail due to I/O
9476 let offset_range = query_match.start()..query_match.end();
9477 let display_range = offset_range.start.to_display_point(&display_map)
9478 ..offset_range.end.to_display_point(&display_map);
9479
9480 if !select_next_state.wordwise
9481 || (!movement::is_inside_word(&display_map, display_range.start)
9482 && !movement::is_inside_word(&display_map, display_range.end))
9483 {
9484 self.selections.change_with(cx, |selections| {
9485 new_selections.push(Selection {
9486 id: selections.new_selection_id(),
9487 start: offset_range.start,
9488 end: offset_range.end,
9489 reversed: false,
9490 goal: SelectionGoal::None,
9491 });
9492 });
9493 }
9494 }
9495
9496 new_selections.sort_by_key(|selection| selection.start);
9497 let mut ix = 0;
9498 while ix + 1 < new_selections.len() {
9499 let current_selection = &new_selections[ix];
9500 let next_selection = &new_selections[ix + 1];
9501 if current_selection.range().overlaps(&next_selection.range()) {
9502 if current_selection.id < next_selection.id {
9503 new_selections.remove(ix + 1);
9504 } else {
9505 new_selections.remove(ix);
9506 }
9507 } else {
9508 ix += 1;
9509 }
9510 }
9511
9512 let reversed = self.selections.oldest::<usize>(cx).reversed;
9513
9514 for selection in new_selections.iter_mut() {
9515 selection.reversed = reversed;
9516 }
9517
9518 select_next_state.done = true;
9519 self.unfold_ranges(
9520 &new_selections
9521 .iter()
9522 .map(|selection| selection.range())
9523 .collect::<Vec<_>>(),
9524 false,
9525 false,
9526 cx,
9527 );
9528 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9529 selections.select(new_selections)
9530 });
9531
9532 Ok(())
9533 }
9534
9535 pub fn select_next(
9536 &mut self,
9537 action: &SelectNext,
9538 window: &mut Window,
9539 cx: &mut Context<Self>,
9540 ) -> Result<()> {
9541 self.push_to_selection_history();
9542 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9543 self.select_next_match_internal(
9544 &display_map,
9545 action.replace_newest,
9546 Some(Autoscroll::newest()),
9547 window,
9548 cx,
9549 )?;
9550 Ok(())
9551 }
9552
9553 pub fn select_previous(
9554 &mut self,
9555 action: &SelectPrevious,
9556 window: &mut Window,
9557 cx: &mut Context<Self>,
9558 ) -> Result<()> {
9559 self.push_to_selection_history();
9560 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9561 let buffer = &display_map.buffer_snapshot;
9562 let mut selections = self.selections.all::<usize>(cx);
9563 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9564 let query = &select_prev_state.query;
9565 if !select_prev_state.done {
9566 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9567 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9568 let mut next_selected_range = None;
9569 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9570 let bytes_before_last_selection =
9571 buffer.reversed_bytes_in_range(0..last_selection.start);
9572 let bytes_after_first_selection =
9573 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9574 let query_matches = query
9575 .stream_find_iter(bytes_before_last_selection)
9576 .map(|result| (last_selection.start, result))
9577 .chain(
9578 query
9579 .stream_find_iter(bytes_after_first_selection)
9580 .map(|result| (buffer.len(), result)),
9581 );
9582 for (end_offset, query_match) in query_matches {
9583 let query_match = query_match.unwrap(); // can only fail due to I/O
9584 let offset_range =
9585 end_offset - query_match.end()..end_offset - query_match.start();
9586 let display_range = offset_range.start.to_display_point(&display_map)
9587 ..offset_range.end.to_display_point(&display_map);
9588
9589 if !select_prev_state.wordwise
9590 || (!movement::is_inside_word(&display_map, display_range.start)
9591 && !movement::is_inside_word(&display_map, display_range.end))
9592 {
9593 next_selected_range = Some(offset_range);
9594 break;
9595 }
9596 }
9597
9598 if let Some(next_selected_range) = next_selected_range {
9599 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9600 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9601 if action.replace_newest {
9602 s.delete(s.newest_anchor().id);
9603 }
9604 s.insert_range(next_selected_range);
9605 });
9606 } else {
9607 select_prev_state.done = true;
9608 }
9609 }
9610
9611 self.select_prev_state = Some(select_prev_state);
9612 } else {
9613 let mut only_carets = true;
9614 let mut same_text_selected = true;
9615 let mut selected_text = None;
9616
9617 let mut selections_iter = selections.iter().peekable();
9618 while let Some(selection) = selections_iter.next() {
9619 if selection.start != selection.end {
9620 only_carets = false;
9621 }
9622
9623 if same_text_selected {
9624 if selected_text.is_none() {
9625 selected_text =
9626 Some(buffer.text_for_range(selection.range()).collect::<String>());
9627 }
9628
9629 if let Some(next_selection) = selections_iter.peek() {
9630 if next_selection.range().len() == selection.range().len() {
9631 let next_selected_text = buffer
9632 .text_for_range(next_selection.range())
9633 .collect::<String>();
9634 if Some(next_selected_text) != selected_text {
9635 same_text_selected = false;
9636 selected_text = None;
9637 }
9638 } else {
9639 same_text_selected = false;
9640 selected_text = None;
9641 }
9642 }
9643 }
9644 }
9645
9646 if only_carets {
9647 for selection in &mut selections {
9648 let word_range = movement::surrounding_word(
9649 &display_map,
9650 selection.start.to_display_point(&display_map),
9651 );
9652 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9653 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9654 selection.goal = SelectionGoal::None;
9655 selection.reversed = false;
9656 }
9657 if selections.len() == 1 {
9658 let selection = selections
9659 .last()
9660 .expect("ensured that there's only one selection");
9661 let query = buffer
9662 .text_for_range(selection.start..selection.end)
9663 .collect::<String>();
9664 let is_empty = query.is_empty();
9665 let select_state = SelectNextState {
9666 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9667 wordwise: true,
9668 done: is_empty,
9669 };
9670 self.select_prev_state = Some(select_state);
9671 } else {
9672 self.select_prev_state = None;
9673 }
9674
9675 self.unfold_ranges(
9676 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9677 false,
9678 true,
9679 cx,
9680 );
9681 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9682 s.select(selections);
9683 });
9684 } else if let Some(selected_text) = selected_text {
9685 self.select_prev_state = Some(SelectNextState {
9686 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9687 wordwise: false,
9688 done: false,
9689 });
9690 self.select_previous(action, window, cx)?;
9691 }
9692 }
9693 Ok(())
9694 }
9695
9696 pub fn toggle_comments(
9697 &mut self,
9698 action: &ToggleComments,
9699 window: &mut Window,
9700 cx: &mut Context<Self>,
9701 ) {
9702 if self.read_only(cx) {
9703 return;
9704 }
9705 let text_layout_details = &self.text_layout_details(window);
9706 self.transact(window, cx, |this, window, cx| {
9707 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9708 let mut edits = Vec::new();
9709 let mut selection_edit_ranges = Vec::new();
9710 let mut last_toggled_row = None;
9711 let snapshot = this.buffer.read(cx).read(cx);
9712 let empty_str: Arc<str> = Arc::default();
9713 let mut suffixes_inserted = Vec::new();
9714 let ignore_indent = action.ignore_indent;
9715
9716 fn comment_prefix_range(
9717 snapshot: &MultiBufferSnapshot,
9718 row: MultiBufferRow,
9719 comment_prefix: &str,
9720 comment_prefix_whitespace: &str,
9721 ignore_indent: bool,
9722 ) -> Range<Point> {
9723 let indent_size = if ignore_indent {
9724 0
9725 } else {
9726 snapshot.indent_size_for_line(row).len
9727 };
9728
9729 let start = Point::new(row.0, indent_size);
9730
9731 let mut line_bytes = snapshot
9732 .bytes_in_range(start..snapshot.max_point())
9733 .flatten()
9734 .copied();
9735
9736 // If this line currently begins with the line comment prefix, then record
9737 // the range containing the prefix.
9738 if line_bytes
9739 .by_ref()
9740 .take(comment_prefix.len())
9741 .eq(comment_prefix.bytes())
9742 {
9743 // Include any whitespace that matches the comment prefix.
9744 let matching_whitespace_len = line_bytes
9745 .zip(comment_prefix_whitespace.bytes())
9746 .take_while(|(a, b)| a == b)
9747 .count() as u32;
9748 let end = Point::new(
9749 start.row,
9750 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9751 );
9752 start..end
9753 } else {
9754 start..start
9755 }
9756 }
9757
9758 fn comment_suffix_range(
9759 snapshot: &MultiBufferSnapshot,
9760 row: MultiBufferRow,
9761 comment_suffix: &str,
9762 comment_suffix_has_leading_space: bool,
9763 ) -> Range<Point> {
9764 let end = Point::new(row.0, snapshot.line_len(row));
9765 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9766
9767 let mut line_end_bytes = snapshot
9768 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9769 .flatten()
9770 .copied();
9771
9772 let leading_space_len = if suffix_start_column > 0
9773 && line_end_bytes.next() == Some(b' ')
9774 && comment_suffix_has_leading_space
9775 {
9776 1
9777 } else {
9778 0
9779 };
9780
9781 // If this line currently begins with the line comment prefix, then record
9782 // the range containing the prefix.
9783 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9784 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9785 start..end
9786 } else {
9787 end..end
9788 }
9789 }
9790
9791 // TODO: Handle selections that cross excerpts
9792 for selection in &mut selections {
9793 let start_column = snapshot
9794 .indent_size_for_line(MultiBufferRow(selection.start.row))
9795 .len;
9796 let language = if let Some(language) =
9797 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9798 {
9799 language
9800 } else {
9801 continue;
9802 };
9803
9804 selection_edit_ranges.clear();
9805
9806 // If multiple selections contain a given row, avoid processing that
9807 // row more than once.
9808 let mut start_row = MultiBufferRow(selection.start.row);
9809 if last_toggled_row == Some(start_row) {
9810 start_row = start_row.next_row();
9811 }
9812 let end_row =
9813 if selection.end.row > selection.start.row && selection.end.column == 0 {
9814 MultiBufferRow(selection.end.row - 1)
9815 } else {
9816 MultiBufferRow(selection.end.row)
9817 };
9818 last_toggled_row = Some(end_row);
9819
9820 if start_row > end_row {
9821 continue;
9822 }
9823
9824 // If the language has line comments, toggle those.
9825 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9826
9827 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9828 if ignore_indent {
9829 full_comment_prefixes = full_comment_prefixes
9830 .into_iter()
9831 .map(|s| Arc::from(s.trim_end()))
9832 .collect();
9833 }
9834
9835 if !full_comment_prefixes.is_empty() {
9836 let first_prefix = full_comment_prefixes
9837 .first()
9838 .expect("prefixes is non-empty");
9839 let prefix_trimmed_lengths = full_comment_prefixes
9840 .iter()
9841 .map(|p| p.trim_end_matches(' ').len())
9842 .collect::<SmallVec<[usize; 4]>>();
9843
9844 let mut all_selection_lines_are_comments = true;
9845
9846 for row in start_row.0..=end_row.0 {
9847 let row = MultiBufferRow(row);
9848 if start_row < end_row && snapshot.is_line_blank(row) {
9849 continue;
9850 }
9851
9852 let prefix_range = full_comment_prefixes
9853 .iter()
9854 .zip(prefix_trimmed_lengths.iter().copied())
9855 .map(|(prefix, trimmed_prefix_len)| {
9856 comment_prefix_range(
9857 snapshot.deref(),
9858 row,
9859 &prefix[..trimmed_prefix_len],
9860 &prefix[trimmed_prefix_len..],
9861 ignore_indent,
9862 )
9863 })
9864 .max_by_key(|range| range.end.column - range.start.column)
9865 .expect("prefixes is non-empty");
9866
9867 if prefix_range.is_empty() {
9868 all_selection_lines_are_comments = false;
9869 }
9870
9871 selection_edit_ranges.push(prefix_range);
9872 }
9873
9874 if all_selection_lines_are_comments {
9875 edits.extend(
9876 selection_edit_ranges
9877 .iter()
9878 .cloned()
9879 .map(|range| (range, empty_str.clone())),
9880 );
9881 } else {
9882 let min_column = selection_edit_ranges
9883 .iter()
9884 .map(|range| range.start.column)
9885 .min()
9886 .unwrap_or(0);
9887 edits.extend(selection_edit_ranges.iter().map(|range| {
9888 let position = Point::new(range.start.row, min_column);
9889 (position..position, first_prefix.clone())
9890 }));
9891 }
9892 } else if let Some((full_comment_prefix, comment_suffix)) =
9893 language.block_comment_delimiters()
9894 {
9895 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9896 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9897 let prefix_range = comment_prefix_range(
9898 snapshot.deref(),
9899 start_row,
9900 comment_prefix,
9901 comment_prefix_whitespace,
9902 ignore_indent,
9903 );
9904 let suffix_range = comment_suffix_range(
9905 snapshot.deref(),
9906 end_row,
9907 comment_suffix.trim_start_matches(' '),
9908 comment_suffix.starts_with(' '),
9909 );
9910
9911 if prefix_range.is_empty() || suffix_range.is_empty() {
9912 edits.push((
9913 prefix_range.start..prefix_range.start,
9914 full_comment_prefix.clone(),
9915 ));
9916 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9917 suffixes_inserted.push((end_row, comment_suffix.len()));
9918 } else {
9919 edits.push((prefix_range, empty_str.clone()));
9920 edits.push((suffix_range, empty_str.clone()));
9921 }
9922 } else {
9923 continue;
9924 }
9925 }
9926
9927 drop(snapshot);
9928 this.buffer.update(cx, |buffer, cx| {
9929 buffer.edit(edits, None, cx);
9930 });
9931
9932 // Adjust selections so that they end before any comment suffixes that
9933 // were inserted.
9934 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9935 let mut selections = this.selections.all::<Point>(cx);
9936 let snapshot = this.buffer.read(cx).read(cx);
9937 for selection in &mut selections {
9938 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9939 match row.cmp(&MultiBufferRow(selection.end.row)) {
9940 Ordering::Less => {
9941 suffixes_inserted.next();
9942 continue;
9943 }
9944 Ordering::Greater => break,
9945 Ordering::Equal => {
9946 if selection.end.column == snapshot.line_len(row) {
9947 if selection.is_empty() {
9948 selection.start.column -= suffix_len as u32;
9949 }
9950 selection.end.column -= suffix_len as u32;
9951 }
9952 break;
9953 }
9954 }
9955 }
9956 }
9957
9958 drop(snapshot);
9959 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9960 s.select(selections)
9961 });
9962
9963 let selections = this.selections.all::<Point>(cx);
9964 let selections_on_single_row = selections.windows(2).all(|selections| {
9965 selections[0].start.row == selections[1].start.row
9966 && selections[0].end.row == selections[1].end.row
9967 && selections[0].start.row == selections[0].end.row
9968 });
9969 let selections_selecting = selections
9970 .iter()
9971 .any(|selection| selection.start != selection.end);
9972 let advance_downwards = action.advance_downwards
9973 && selections_on_single_row
9974 && !selections_selecting
9975 && !matches!(this.mode, EditorMode::SingleLine { .. });
9976
9977 if advance_downwards {
9978 let snapshot = this.buffer.read(cx).snapshot(cx);
9979
9980 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9981 s.move_cursors_with(|display_snapshot, display_point, _| {
9982 let mut point = display_point.to_point(display_snapshot);
9983 point.row += 1;
9984 point = snapshot.clip_point(point, Bias::Left);
9985 let display_point = point.to_display_point(display_snapshot);
9986 let goal = SelectionGoal::HorizontalPosition(
9987 display_snapshot
9988 .x_for_display_point(display_point, text_layout_details)
9989 .into(),
9990 );
9991 (display_point, goal)
9992 })
9993 });
9994 }
9995 });
9996 }
9997
9998 pub fn select_enclosing_symbol(
9999 &mut self,
10000 _: &SelectEnclosingSymbol,
10001 window: &mut Window,
10002 cx: &mut Context<Self>,
10003 ) {
10004 let buffer = self.buffer.read(cx).snapshot(cx);
10005 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10006
10007 fn update_selection(
10008 selection: &Selection<usize>,
10009 buffer_snap: &MultiBufferSnapshot,
10010 ) -> Option<Selection<usize>> {
10011 let cursor = selection.head();
10012 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10013 for symbol in symbols.iter().rev() {
10014 let start = symbol.range.start.to_offset(buffer_snap);
10015 let end = symbol.range.end.to_offset(buffer_snap);
10016 let new_range = start..end;
10017 if start < selection.start || end > selection.end {
10018 return Some(Selection {
10019 id: selection.id,
10020 start: new_range.start,
10021 end: new_range.end,
10022 goal: SelectionGoal::None,
10023 reversed: selection.reversed,
10024 });
10025 }
10026 }
10027 None
10028 }
10029
10030 let mut selected_larger_symbol = false;
10031 let new_selections = old_selections
10032 .iter()
10033 .map(|selection| match update_selection(selection, &buffer) {
10034 Some(new_selection) => {
10035 if new_selection.range() != selection.range() {
10036 selected_larger_symbol = true;
10037 }
10038 new_selection
10039 }
10040 None => selection.clone(),
10041 })
10042 .collect::<Vec<_>>();
10043
10044 if selected_larger_symbol {
10045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10046 s.select(new_selections);
10047 });
10048 }
10049 }
10050
10051 pub fn select_larger_syntax_node(
10052 &mut self,
10053 _: &SelectLargerSyntaxNode,
10054 window: &mut Window,
10055 cx: &mut Context<Self>,
10056 ) {
10057 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10058 let buffer = self.buffer.read(cx).snapshot(cx);
10059 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10060
10061 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10062 let mut selected_larger_node = false;
10063 let new_selections = old_selections
10064 .iter()
10065 .map(|selection| {
10066 let old_range = selection.start..selection.end;
10067 let mut new_range = old_range.clone();
10068 let mut new_node = None;
10069 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10070 {
10071 new_node = Some(node);
10072 new_range = containing_range;
10073 if !display_map.intersects_fold(new_range.start)
10074 && !display_map.intersects_fold(new_range.end)
10075 {
10076 break;
10077 }
10078 }
10079
10080 if let Some(node) = new_node {
10081 // Log the ancestor, to support using this action as a way to explore TreeSitter
10082 // nodes. Parent and grandparent are also logged because this operation will not
10083 // visit nodes that have the same range as their parent.
10084 log::info!("Node: {node:?}");
10085 let parent = node.parent();
10086 log::info!("Parent: {parent:?}");
10087 let grandparent = parent.and_then(|x| x.parent());
10088 log::info!("Grandparent: {grandparent:?}");
10089 }
10090
10091 selected_larger_node |= new_range != old_range;
10092 Selection {
10093 id: selection.id,
10094 start: new_range.start,
10095 end: new_range.end,
10096 goal: SelectionGoal::None,
10097 reversed: selection.reversed,
10098 }
10099 })
10100 .collect::<Vec<_>>();
10101
10102 if selected_larger_node {
10103 stack.push(old_selections);
10104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10105 s.select(new_selections);
10106 });
10107 }
10108 self.select_larger_syntax_node_stack = stack;
10109 }
10110
10111 pub fn select_smaller_syntax_node(
10112 &mut self,
10113 _: &SelectSmallerSyntaxNode,
10114 window: &mut Window,
10115 cx: &mut Context<Self>,
10116 ) {
10117 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10118 if let Some(selections) = stack.pop() {
10119 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10120 s.select(selections.to_vec());
10121 });
10122 }
10123 self.select_larger_syntax_node_stack = stack;
10124 }
10125
10126 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10127 if !EditorSettings::get_global(cx).gutter.runnables {
10128 self.clear_tasks();
10129 return Task::ready(());
10130 }
10131 let project = self.project.as_ref().map(Entity::downgrade);
10132 cx.spawn_in(window, |this, mut cx| async move {
10133 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10134 let Some(project) = project.and_then(|p| p.upgrade()) else {
10135 return;
10136 };
10137 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10138 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10139 }) else {
10140 return;
10141 };
10142
10143 let hide_runnables = project
10144 .update(&mut cx, |project, cx| {
10145 // Do not display any test indicators in non-dev server remote projects.
10146 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10147 })
10148 .unwrap_or(true);
10149 if hide_runnables {
10150 return;
10151 }
10152 let new_rows =
10153 cx.background_spawn({
10154 let snapshot = display_snapshot.clone();
10155 async move {
10156 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10157 }
10158 })
10159 .await;
10160
10161 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10162 this.update(&mut cx, |this, _| {
10163 this.clear_tasks();
10164 for (key, value) in rows {
10165 this.insert_tasks(key, value);
10166 }
10167 })
10168 .ok();
10169 })
10170 }
10171 fn fetch_runnable_ranges(
10172 snapshot: &DisplaySnapshot,
10173 range: Range<Anchor>,
10174 ) -> Vec<language::RunnableRange> {
10175 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10176 }
10177
10178 fn runnable_rows(
10179 project: Entity<Project>,
10180 snapshot: DisplaySnapshot,
10181 runnable_ranges: Vec<RunnableRange>,
10182 mut cx: AsyncWindowContext,
10183 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10184 runnable_ranges
10185 .into_iter()
10186 .filter_map(|mut runnable| {
10187 let tasks = cx
10188 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10189 .ok()?;
10190 if tasks.is_empty() {
10191 return None;
10192 }
10193
10194 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10195
10196 let row = snapshot
10197 .buffer_snapshot
10198 .buffer_line_for_row(MultiBufferRow(point.row))?
10199 .1
10200 .start
10201 .row;
10202
10203 let context_range =
10204 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10205 Some((
10206 (runnable.buffer_id, row),
10207 RunnableTasks {
10208 templates: tasks,
10209 offset: MultiBufferOffset(runnable.run_range.start),
10210 context_range,
10211 column: point.column,
10212 extra_variables: runnable.extra_captures,
10213 },
10214 ))
10215 })
10216 .collect()
10217 }
10218
10219 fn templates_with_tags(
10220 project: &Entity<Project>,
10221 runnable: &mut Runnable,
10222 cx: &mut App,
10223 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10224 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10225 let (worktree_id, file) = project
10226 .buffer_for_id(runnable.buffer, cx)
10227 .and_then(|buffer| buffer.read(cx).file())
10228 .map(|file| (file.worktree_id(cx), file.clone()))
10229 .unzip();
10230
10231 (
10232 project.task_store().read(cx).task_inventory().cloned(),
10233 worktree_id,
10234 file,
10235 )
10236 });
10237
10238 let tags = mem::take(&mut runnable.tags);
10239 let mut tags: Vec<_> = tags
10240 .into_iter()
10241 .flat_map(|tag| {
10242 let tag = tag.0.clone();
10243 inventory
10244 .as_ref()
10245 .into_iter()
10246 .flat_map(|inventory| {
10247 inventory.read(cx).list_tasks(
10248 file.clone(),
10249 Some(runnable.language.clone()),
10250 worktree_id,
10251 cx,
10252 )
10253 })
10254 .filter(move |(_, template)| {
10255 template.tags.iter().any(|source_tag| source_tag == &tag)
10256 })
10257 })
10258 .sorted_by_key(|(kind, _)| kind.to_owned())
10259 .collect();
10260 if let Some((leading_tag_source, _)) = tags.first() {
10261 // Strongest source wins; if we have worktree tag binding, prefer that to
10262 // global and language bindings;
10263 // if we have a global binding, prefer that to language binding.
10264 let first_mismatch = tags
10265 .iter()
10266 .position(|(tag_source, _)| tag_source != leading_tag_source);
10267 if let Some(index) = first_mismatch {
10268 tags.truncate(index);
10269 }
10270 }
10271
10272 tags
10273 }
10274
10275 pub fn move_to_enclosing_bracket(
10276 &mut self,
10277 _: &MoveToEnclosingBracket,
10278 window: &mut Window,
10279 cx: &mut Context<Self>,
10280 ) {
10281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10282 s.move_offsets_with(|snapshot, selection| {
10283 let Some(enclosing_bracket_ranges) =
10284 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10285 else {
10286 return;
10287 };
10288
10289 let mut best_length = usize::MAX;
10290 let mut best_inside = false;
10291 let mut best_in_bracket_range = false;
10292 let mut best_destination = None;
10293 for (open, close) in enclosing_bracket_ranges {
10294 let close = close.to_inclusive();
10295 let length = close.end() - open.start;
10296 let inside = selection.start >= open.end && selection.end <= *close.start();
10297 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10298 || close.contains(&selection.head());
10299
10300 // If best is next to a bracket and current isn't, skip
10301 if !in_bracket_range && best_in_bracket_range {
10302 continue;
10303 }
10304
10305 // Prefer smaller lengths unless best is inside and current isn't
10306 if length > best_length && (best_inside || !inside) {
10307 continue;
10308 }
10309
10310 best_length = length;
10311 best_inside = inside;
10312 best_in_bracket_range = in_bracket_range;
10313 best_destination = Some(
10314 if close.contains(&selection.start) && close.contains(&selection.end) {
10315 if inside {
10316 open.end
10317 } else {
10318 open.start
10319 }
10320 } else if inside {
10321 *close.start()
10322 } else {
10323 *close.end()
10324 },
10325 );
10326 }
10327
10328 if let Some(destination) = best_destination {
10329 selection.collapse_to(destination, SelectionGoal::None);
10330 }
10331 })
10332 });
10333 }
10334
10335 pub fn undo_selection(
10336 &mut self,
10337 _: &UndoSelection,
10338 window: &mut Window,
10339 cx: &mut Context<Self>,
10340 ) {
10341 self.end_selection(window, cx);
10342 self.selection_history.mode = SelectionHistoryMode::Undoing;
10343 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10344 self.change_selections(None, window, cx, |s| {
10345 s.select_anchors(entry.selections.to_vec())
10346 });
10347 self.select_next_state = entry.select_next_state;
10348 self.select_prev_state = entry.select_prev_state;
10349 self.add_selections_state = entry.add_selections_state;
10350 self.request_autoscroll(Autoscroll::newest(), cx);
10351 }
10352 self.selection_history.mode = SelectionHistoryMode::Normal;
10353 }
10354
10355 pub fn redo_selection(
10356 &mut self,
10357 _: &RedoSelection,
10358 window: &mut Window,
10359 cx: &mut Context<Self>,
10360 ) {
10361 self.end_selection(window, cx);
10362 self.selection_history.mode = SelectionHistoryMode::Redoing;
10363 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10364 self.change_selections(None, window, cx, |s| {
10365 s.select_anchors(entry.selections.to_vec())
10366 });
10367 self.select_next_state = entry.select_next_state;
10368 self.select_prev_state = entry.select_prev_state;
10369 self.add_selections_state = entry.add_selections_state;
10370 self.request_autoscroll(Autoscroll::newest(), cx);
10371 }
10372 self.selection_history.mode = SelectionHistoryMode::Normal;
10373 }
10374
10375 pub fn expand_excerpts(
10376 &mut self,
10377 action: &ExpandExcerpts,
10378 _: &mut Window,
10379 cx: &mut Context<Self>,
10380 ) {
10381 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10382 }
10383
10384 pub fn expand_excerpts_down(
10385 &mut self,
10386 action: &ExpandExcerptsDown,
10387 _: &mut Window,
10388 cx: &mut Context<Self>,
10389 ) {
10390 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10391 }
10392
10393 pub fn expand_excerpts_up(
10394 &mut self,
10395 action: &ExpandExcerptsUp,
10396 _: &mut Window,
10397 cx: &mut Context<Self>,
10398 ) {
10399 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10400 }
10401
10402 pub fn expand_excerpts_for_direction(
10403 &mut self,
10404 lines: u32,
10405 direction: ExpandExcerptDirection,
10406
10407 cx: &mut Context<Self>,
10408 ) {
10409 let selections = self.selections.disjoint_anchors();
10410
10411 let lines = if lines == 0 {
10412 EditorSettings::get_global(cx).expand_excerpt_lines
10413 } else {
10414 lines
10415 };
10416
10417 self.buffer.update(cx, |buffer, cx| {
10418 let snapshot = buffer.snapshot(cx);
10419 let mut excerpt_ids = selections
10420 .iter()
10421 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10422 .collect::<Vec<_>>();
10423 excerpt_ids.sort();
10424 excerpt_ids.dedup();
10425 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10426 })
10427 }
10428
10429 pub fn expand_excerpt(
10430 &mut self,
10431 excerpt: ExcerptId,
10432 direction: ExpandExcerptDirection,
10433 cx: &mut Context<Self>,
10434 ) {
10435 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10436 self.buffer.update(cx, |buffer, cx| {
10437 buffer.expand_excerpts([excerpt], lines, direction, cx)
10438 })
10439 }
10440
10441 pub fn go_to_singleton_buffer_point(
10442 &mut self,
10443 point: Point,
10444 window: &mut Window,
10445 cx: &mut Context<Self>,
10446 ) {
10447 self.go_to_singleton_buffer_range(point..point, window, cx);
10448 }
10449
10450 pub fn go_to_singleton_buffer_range(
10451 &mut self,
10452 range: Range<Point>,
10453 window: &mut Window,
10454 cx: &mut Context<Self>,
10455 ) {
10456 let multibuffer = self.buffer().read(cx);
10457 let Some(buffer) = multibuffer.as_singleton() else {
10458 return;
10459 };
10460 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10461 return;
10462 };
10463 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10464 return;
10465 };
10466 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10467 s.select_anchor_ranges([start..end])
10468 });
10469 }
10470
10471 fn go_to_diagnostic(
10472 &mut self,
10473 _: &GoToDiagnostic,
10474 window: &mut Window,
10475 cx: &mut Context<Self>,
10476 ) {
10477 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10478 }
10479
10480 fn go_to_prev_diagnostic(
10481 &mut self,
10482 _: &GoToPrevDiagnostic,
10483 window: &mut Window,
10484 cx: &mut Context<Self>,
10485 ) {
10486 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10487 }
10488
10489 pub fn go_to_diagnostic_impl(
10490 &mut self,
10491 direction: Direction,
10492 window: &mut Window,
10493 cx: &mut Context<Self>,
10494 ) {
10495 let buffer = self.buffer.read(cx).snapshot(cx);
10496 let selection = self.selections.newest::<usize>(cx);
10497
10498 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10499 if direction == Direction::Next {
10500 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10501 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10502 return;
10503 };
10504 self.activate_diagnostics(
10505 buffer_id,
10506 popover.local_diagnostic.diagnostic.group_id,
10507 window,
10508 cx,
10509 );
10510 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10511 let primary_range_start = active_diagnostics.primary_range.start;
10512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10513 let mut new_selection = s.newest_anchor().clone();
10514 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10515 s.select_anchors(vec![new_selection.clone()]);
10516 });
10517 self.refresh_inline_completion(false, true, window, cx);
10518 }
10519 return;
10520 }
10521 }
10522
10523 let active_group_id = self
10524 .active_diagnostics
10525 .as_ref()
10526 .map(|active_group| active_group.group_id);
10527 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10528 active_diagnostics
10529 .primary_range
10530 .to_offset(&buffer)
10531 .to_inclusive()
10532 });
10533 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10534 if active_primary_range.contains(&selection.head()) {
10535 *active_primary_range.start()
10536 } else {
10537 selection.head()
10538 }
10539 } else {
10540 selection.head()
10541 };
10542
10543 let snapshot = self.snapshot(window, cx);
10544 let primary_diagnostics_before = buffer
10545 .diagnostics_in_range::<usize>(0..search_start)
10546 .filter(|entry| entry.diagnostic.is_primary)
10547 .filter(|entry| entry.range.start != entry.range.end)
10548 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10549 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10550 .collect::<Vec<_>>();
10551 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10552 primary_diagnostics_before
10553 .iter()
10554 .position(|entry| entry.diagnostic.group_id == active_group_id)
10555 });
10556
10557 let primary_diagnostics_after = buffer
10558 .diagnostics_in_range::<usize>(search_start..buffer.len())
10559 .filter(|entry| entry.diagnostic.is_primary)
10560 .filter(|entry| entry.range.start != entry.range.end)
10561 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10562 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10563 .collect::<Vec<_>>();
10564 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10565 primary_diagnostics_after
10566 .iter()
10567 .enumerate()
10568 .rev()
10569 .find_map(|(i, entry)| {
10570 if entry.diagnostic.group_id == active_group_id {
10571 Some(i)
10572 } else {
10573 None
10574 }
10575 })
10576 });
10577
10578 let next_primary_diagnostic = match direction {
10579 Direction::Prev => primary_diagnostics_before
10580 .iter()
10581 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10582 .rev()
10583 .next(),
10584 Direction::Next => primary_diagnostics_after
10585 .iter()
10586 .skip(
10587 last_same_group_diagnostic_after
10588 .map(|index| index + 1)
10589 .unwrap_or(0),
10590 )
10591 .next(),
10592 };
10593
10594 // Cycle around to the start of the buffer, potentially moving back to the start of
10595 // the currently active diagnostic.
10596 let cycle_around = || match direction {
10597 Direction::Prev => primary_diagnostics_after
10598 .iter()
10599 .rev()
10600 .chain(primary_diagnostics_before.iter().rev())
10601 .next(),
10602 Direction::Next => primary_diagnostics_before
10603 .iter()
10604 .chain(primary_diagnostics_after.iter())
10605 .next(),
10606 };
10607
10608 if let Some((primary_range, group_id)) = next_primary_diagnostic
10609 .or_else(cycle_around)
10610 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10611 {
10612 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10613 return;
10614 };
10615 self.activate_diagnostics(buffer_id, group_id, window, cx);
10616 if self.active_diagnostics.is_some() {
10617 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618 s.select(vec![Selection {
10619 id: selection.id,
10620 start: primary_range.start,
10621 end: primary_range.start,
10622 reversed: false,
10623 goal: SelectionGoal::None,
10624 }]);
10625 });
10626 self.refresh_inline_completion(false, true, window, cx);
10627 }
10628 }
10629 }
10630
10631 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10632 let snapshot = self.snapshot(window, cx);
10633 let selection = self.selections.newest::<Point>(cx);
10634 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10635 }
10636
10637 fn go_to_hunk_after_position(
10638 &mut self,
10639 snapshot: &EditorSnapshot,
10640 position: Point,
10641 window: &mut Window,
10642 cx: &mut Context<Editor>,
10643 ) -> Option<MultiBufferDiffHunk> {
10644 let mut hunk = snapshot
10645 .buffer_snapshot
10646 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10647 .find(|hunk| hunk.row_range.start.0 > position.row);
10648 if hunk.is_none() {
10649 hunk = snapshot
10650 .buffer_snapshot
10651 .diff_hunks_in_range(Point::zero()..position)
10652 .find(|hunk| hunk.row_range.end.0 < position.row)
10653 }
10654 if let Some(hunk) = &hunk {
10655 let destination = Point::new(hunk.row_range.start.0, 0);
10656 self.unfold_ranges(&[destination..destination], false, false, cx);
10657 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10658 s.select_ranges(vec![destination..destination]);
10659 });
10660 }
10661
10662 hunk
10663 }
10664
10665 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10666 let snapshot = self.snapshot(window, cx);
10667 let selection = self.selections.newest::<Point>(cx);
10668 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10669 }
10670
10671 fn go_to_hunk_before_position(
10672 &mut self,
10673 snapshot: &EditorSnapshot,
10674 position: Point,
10675 window: &mut Window,
10676 cx: &mut Context<Editor>,
10677 ) -> Option<MultiBufferDiffHunk> {
10678 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10679 if hunk.is_none() {
10680 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10681 }
10682 if let Some(hunk) = &hunk {
10683 let destination = Point::new(hunk.row_range.start.0, 0);
10684 self.unfold_ranges(&[destination..destination], false, false, cx);
10685 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686 s.select_ranges(vec![destination..destination]);
10687 });
10688 }
10689
10690 hunk
10691 }
10692
10693 pub fn go_to_definition(
10694 &mut self,
10695 _: &GoToDefinition,
10696 window: &mut Window,
10697 cx: &mut Context<Self>,
10698 ) -> Task<Result<Navigated>> {
10699 let definition =
10700 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10701 cx.spawn_in(window, |editor, mut cx| async move {
10702 if definition.await? == Navigated::Yes {
10703 return Ok(Navigated::Yes);
10704 }
10705 match editor.update_in(&mut cx, |editor, window, cx| {
10706 editor.find_all_references(&FindAllReferences, window, cx)
10707 })? {
10708 Some(references) => references.await,
10709 None => Ok(Navigated::No),
10710 }
10711 })
10712 }
10713
10714 pub fn go_to_declaration(
10715 &mut self,
10716 _: &GoToDeclaration,
10717 window: &mut Window,
10718 cx: &mut Context<Self>,
10719 ) -> Task<Result<Navigated>> {
10720 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10721 }
10722
10723 pub fn go_to_declaration_split(
10724 &mut self,
10725 _: &GoToDeclaration,
10726 window: &mut Window,
10727 cx: &mut Context<Self>,
10728 ) -> Task<Result<Navigated>> {
10729 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10730 }
10731
10732 pub fn go_to_implementation(
10733 &mut self,
10734 _: &GoToImplementation,
10735 window: &mut Window,
10736 cx: &mut Context<Self>,
10737 ) -> Task<Result<Navigated>> {
10738 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10739 }
10740
10741 pub fn go_to_implementation_split(
10742 &mut self,
10743 _: &GoToImplementationSplit,
10744 window: &mut Window,
10745 cx: &mut Context<Self>,
10746 ) -> Task<Result<Navigated>> {
10747 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10748 }
10749
10750 pub fn go_to_type_definition(
10751 &mut self,
10752 _: &GoToTypeDefinition,
10753 window: &mut Window,
10754 cx: &mut Context<Self>,
10755 ) -> Task<Result<Navigated>> {
10756 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10757 }
10758
10759 pub fn go_to_definition_split(
10760 &mut self,
10761 _: &GoToDefinitionSplit,
10762 window: &mut Window,
10763 cx: &mut Context<Self>,
10764 ) -> Task<Result<Navigated>> {
10765 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10766 }
10767
10768 pub fn go_to_type_definition_split(
10769 &mut self,
10770 _: &GoToTypeDefinitionSplit,
10771 window: &mut Window,
10772 cx: &mut Context<Self>,
10773 ) -> Task<Result<Navigated>> {
10774 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10775 }
10776
10777 fn go_to_definition_of_kind(
10778 &mut self,
10779 kind: GotoDefinitionKind,
10780 split: bool,
10781 window: &mut Window,
10782 cx: &mut Context<Self>,
10783 ) -> Task<Result<Navigated>> {
10784 let Some(provider) = self.semantics_provider.clone() else {
10785 return Task::ready(Ok(Navigated::No));
10786 };
10787 let head = self.selections.newest::<usize>(cx).head();
10788 let buffer = self.buffer.read(cx);
10789 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10790 text_anchor
10791 } else {
10792 return Task::ready(Ok(Navigated::No));
10793 };
10794
10795 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10796 return Task::ready(Ok(Navigated::No));
10797 };
10798
10799 cx.spawn_in(window, |editor, mut cx| async move {
10800 let definitions = definitions.await?;
10801 let navigated = editor
10802 .update_in(&mut cx, |editor, window, cx| {
10803 editor.navigate_to_hover_links(
10804 Some(kind),
10805 definitions
10806 .into_iter()
10807 .filter(|location| {
10808 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10809 })
10810 .map(HoverLink::Text)
10811 .collect::<Vec<_>>(),
10812 split,
10813 window,
10814 cx,
10815 )
10816 })?
10817 .await?;
10818 anyhow::Ok(navigated)
10819 })
10820 }
10821
10822 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10823 let selection = self.selections.newest_anchor();
10824 let head = selection.head();
10825 let tail = selection.tail();
10826
10827 let Some((buffer, start_position)) =
10828 self.buffer.read(cx).text_anchor_for_position(head, cx)
10829 else {
10830 return;
10831 };
10832
10833 let end_position = if head != tail {
10834 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10835 return;
10836 };
10837 Some(pos)
10838 } else {
10839 None
10840 };
10841
10842 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10843 let url = if let Some(end_pos) = end_position {
10844 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10845 } else {
10846 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10847 };
10848
10849 if let Some(url) = url {
10850 editor.update(&mut cx, |_, cx| {
10851 cx.open_url(&url);
10852 })
10853 } else {
10854 Ok(())
10855 }
10856 });
10857
10858 url_finder.detach();
10859 }
10860
10861 pub fn open_selected_filename(
10862 &mut self,
10863 _: &OpenSelectedFilename,
10864 window: &mut Window,
10865 cx: &mut Context<Self>,
10866 ) {
10867 let Some(workspace) = self.workspace() else {
10868 return;
10869 };
10870
10871 let position = self.selections.newest_anchor().head();
10872
10873 let Some((buffer, buffer_position)) =
10874 self.buffer.read(cx).text_anchor_for_position(position, cx)
10875 else {
10876 return;
10877 };
10878
10879 let project = self.project.clone();
10880
10881 cx.spawn_in(window, |_, mut cx| async move {
10882 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10883
10884 if let Some((_, path)) = result {
10885 workspace
10886 .update_in(&mut cx, |workspace, window, cx| {
10887 workspace.open_resolved_path(path, window, cx)
10888 })?
10889 .await?;
10890 }
10891 anyhow::Ok(())
10892 })
10893 .detach();
10894 }
10895
10896 pub(crate) fn navigate_to_hover_links(
10897 &mut self,
10898 kind: Option<GotoDefinitionKind>,
10899 mut definitions: Vec<HoverLink>,
10900 split: bool,
10901 window: &mut Window,
10902 cx: &mut Context<Editor>,
10903 ) -> Task<Result<Navigated>> {
10904 // If there is one definition, just open it directly
10905 if definitions.len() == 1 {
10906 let definition = definitions.pop().unwrap();
10907
10908 enum TargetTaskResult {
10909 Location(Option<Location>),
10910 AlreadyNavigated,
10911 }
10912
10913 let target_task = match definition {
10914 HoverLink::Text(link) => {
10915 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10916 }
10917 HoverLink::InlayHint(lsp_location, server_id) => {
10918 let computation =
10919 self.compute_target_location(lsp_location, server_id, window, cx);
10920 cx.background_spawn(async move {
10921 let location = computation.await?;
10922 Ok(TargetTaskResult::Location(location))
10923 })
10924 }
10925 HoverLink::Url(url) => {
10926 cx.open_url(&url);
10927 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10928 }
10929 HoverLink::File(path) => {
10930 if let Some(workspace) = self.workspace() {
10931 cx.spawn_in(window, |_, mut cx| async move {
10932 workspace
10933 .update_in(&mut cx, |workspace, window, cx| {
10934 workspace.open_resolved_path(path, window, cx)
10935 })?
10936 .await
10937 .map(|_| TargetTaskResult::AlreadyNavigated)
10938 })
10939 } else {
10940 Task::ready(Ok(TargetTaskResult::Location(None)))
10941 }
10942 }
10943 };
10944 cx.spawn_in(window, |editor, mut cx| async move {
10945 let target = match target_task.await.context("target resolution task")? {
10946 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10947 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10948 TargetTaskResult::Location(Some(target)) => target,
10949 };
10950
10951 editor.update_in(&mut cx, |editor, window, cx| {
10952 let Some(workspace) = editor.workspace() else {
10953 return Navigated::No;
10954 };
10955 let pane = workspace.read(cx).active_pane().clone();
10956
10957 let range = target.range.to_point(target.buffer.read(cx));
10958 let range = editor.range_for_match(&range);
10959 let range = collapse_multiline_range(range);
10960
10961 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10962 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10963 } else {
10964 window.defer(cx, move |window, cx| {
10965 let target_editor: Entity<Self> =
10966 workspace.update(cx, |workspace, cx| {
10967 let pane = if split {
10968 workspace.adjacent_pane(window, cx)
10969 } else {
10970 workspace.active_pane().clone()
10971 };
10972
10973 workspace.open_project_item(
10974 pane,
10975 target.buffer.clone(),
10976 true,
10977 true,
10978 window,
10979 cx,
10980 )
10981 });
10982 target_editor.update(cx, |target_editor, cx| {
10983 // When selecting a definition in a different buffer, disable the nav history
10984 // to avoid creating a history entry at the previous cursor location.
10985 pane.update(cx, |pane, _| pane.disable_history());
10986 target_editor.go_to_singleton_buffer_range(range, window, cx);
10987 pane.update(cx, |pane, _| pane.enable_history());
10988 });
10989 });
10990 }
10991 Navigated::Yes
10992 })
10993 })
10994 } else if !definitions.is_empty() {
10995 cx.spawn_in(window, |editor, mut cx| async move {
10996 let (title, location_tasks, workspace) = editor
10997 .update_in(&mut cx, |editor, window, cx| {
10998 let tab_kind = match kind {
10999 Some(GotoDefinitionKind::Implementation) => "Implementations",
11000 _ => "Definitions",
11001 };
11002 let title = definitions
11003 .iter()
11004 .find_map(|definition| match definition {
11005 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11006 let buffer = origin.buffer.read(cx);
11007 format!(
11008 "{} for {}",
11009 tab_kind,
11010 buffer
11011 .text_for_range(origin.range.clone())
11012 .collect::<String>()
11013 )
11014 }),
11015 HoverLink::InlayHint(_, _) => None,
11016 HoverLink::Url(_) => None,
11017 HoverLink::File(_) => None,
11018 })
11019 .unwrap_or(tab_kind.to_string());
11020 let location_tasks = definitions
11021 .into_iter()
11022 .map(|definition| match definition {
11023 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11024 HoverLink::InlayHint(lsp_location, server_id) => editor
11025 .compute_target_location(lsp_location, server_id, window, cx),
11026 HoverLink::Url(_) => Task::ready(Ok(None)),
11027 HoverLink::File(_) => Task::ready(Ok(None)),
11028 })
11029 .collect::<Vec<_>>();
11030 (title, location_tasks, editor.workspace().clone())
11031 })
11032 .context("location tasks preparation")?;
11033
11034 let locations = future::join_all(location_tasks)
11035 .await
11036 .into_iter()
11037 .filter_map(|location| location.transpose())
11038 .collect::<Result<_>>()
11039 .context("location tasks")?;
11040
11041 let Some(workspace) = workspace else {
11042 return Ok(Navigated::No);
11043 };
11044 let opened = workspace
11045 .update_in(&mut cx, |workspace, window, cx| {
11046 Self::open_locations_in_multibuffer(
11047 workspace,
11048 locations,
11049 title,
11050 split,
11051 MultibufferSelectionMode::First,
11052 window,
11053 cx,
11054 )
11055 })
11056 .ok();
11057
11058 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11059 })
11060 } else {
11061 Task::ready(Ok(Navigated::No))
11062 }
11063 }
11064
11065 fn compute_target_location(
11066 &self,
11067 lsp_location: lsp::Location,
11068 server_id: LanguageServerId,
11069 window: &mut Window,
11070 cx: &mut Context<Self>,
11071 ) -> Task<anyhow::Result<Option<Location>>> {
11072 let Some(project) = self.project.clone() else {
11073 return Task::ready(Ok(None));
11074 };
11075
11076 cx.spawn_in(window, move |editor, mut cx| async move {
11077 let location_task = editor.update(&mut cx, |_, cx| {
11078 project.update(cx, |project, cx| {
11079 let language_server_name = project
11080 .language_server_statuses(cx)
11081 .find(|(id, _)| server_id == *id)
11082 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11083 language_server_name.map(|language_server_name| {
11084 project.open_local_buffer_via_lsp(
11085 lsp_location.uri.clone(),
11086 server_id,
11087 language_server_name,
11088 cx,
11089 )
11090 })
11091 })
11092 })?;
11093 let location = match location_task {
11094 Some(task) => Some({
11095 let target_buffer_handle = task.await.context("open local buffer")?;
11096 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11097 let target_start = target_buffer
11098 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11099 let target_end = target_buffer
11100 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11101 target_buffer.anchor_after(target_start)
11102 ..target_buffer.anchor_before(target_end)
11103 })?;
11104 Location {
11105 buffer: target_buffer_handle,
11106 range,
11107 }
11108 }),
11109 None => None,
11110 };
11111 Ok(location)
11112 })
11113 }
11114
11115 pub fn find_all_references(
11116 &mut self,
11117 _: &FindAllReferences,
11118 window: &mut Window,
11119 cx: &mut Context<Self>,
11120 ) -> Option<Task<Result<Navigated>>> {
11121 let selection = self.selections.newest::<usize>(cx);
11122 let multi_buffer = self.buffer.read(cx);
11123 let head = selection.head();
11124
11125 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11126 let head_anchor = multi_buffer_snapshot.anchor_at(
11127 head,
11128 if head < selection.tail() {
11129 Bias::Right
11130 } else {
11131 Bias::Left
11132 },
11133 );
11134
11135 match self
11136 .find_all_references_task_sources
11137 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11138 {
11139 Ok(_) => {
11140 log::info!(
11141 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11142 );
11143 return None;
11144 }
11145 Err(i) => {
11146 self.find_all_references_task_sources.insert(i, head_anchor);
11147 }
11148 }
11149
11150 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11151 let workspace = self.workspace()?;
11152 let project = workspace.read(cx).project().clone();
11153 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11154 Some(cx.spawn_in(window, |editor, mut cx| async move {
11155 let _cleanup = defer({
11156 let mut cx = cx.clone();
11157 move || {
11158 let _ = editor.update(&mut cx, |editor, _| {
11159 if let Ok(i) =
11160 editor
11161 .find_all_references_task_sources
11162 .binary_search_by(|anchor| {
11163 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11164 })
11165 {
11166 editor.find_all_references_task_sources.remove(i);
11167 }
11168 });
11169 }
11170 });
11171
11172 let locations = references.await?;
11173 if locations.is_empty() {
11174 return anyhow::Ok(Navigated::No);
11175 }
11176
11177 workspace.update_in(&mut cx, |workspace, window, cx| {
11178 let title = locations
11179 .first()
11180 .as_ref()
11181 .map(|location| {
11182 let buffer = location.buffer.read(cx);
11183 format!(
11184 "References to `{}`",
11185 buffer
11186 .text_for_range(location.range.clone())
11187 .collect::<String>()
11188 )
11189 })
11190 .unwrap();
11191 Self::open_locations_in_multibuffer(
11192 workspace,
11193 locations,
11194 title,
11195 false,
11196 MultibufferSelectionMode::First,
11197 window,
11198 cx,
11199 );
11200 Navigated::Yes
11201 })
11202 }))
11203 }
11204
11205 /// Opens a multibuffer with the given project locations in it
11206 pub fn open_locations_in_multibuffer(
11207 workspace: &mut Workspace,
11208 mut locations: Vec<Location>,
11209 title: String,
11210 split: bool,
11211 multibuffer_selection_mode: MultibufferSelectionMode,
11212 window: &mut Window,
11213 cx: &mut Context<Workspace>,
11214 ) {
11215 // If there are multiple definitions, open them in a multibuffer
11216 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11217 let mut locations = locations.into_iter().peekable();
11218 let mut ranges = Vec::new();
11219 let capability = workspace.project().read(cx).capability();
11220
11221 let excerpt_buffer = cx.new(|cx| {
11222 let mut multibuffer = MultiBuffer::new(capability);
11223 while let Some(location) = locations.next() {
11224 let buffer = location.buffer.read(cx);
11225 let mut ranges_for_buffer = Vec::new();
11226 let range = location.range.to_offset(buffer);
11227 ranges_for_buffer.push(range.clone());
11228
11229 while let Some(next_location) = locations.peek() {
11230 if next_location.buffer == location.buffer {
11231 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11232 locations.next();
11233 } else {
11234 break;
11235 }
11236 }
11237
11238 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11239 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11240 location.buffer.clone(),
11241 ranges_for_buffer,
11242 DEFAULT_MULTIBUFFER_CONTEXT,
11243 cx,
11244 ))
11245 }
11246
11247 multibuffer.with_title(title)
11248 });
11249
11250 let editor = cx.new(|cx| {
11251 Editor::for_multibuffer(
11252 excerpt_buffer,
11253 Some(workspace.project().clone()),
11254 true,
11255 window,
11256 cx,
11257 )
11258 });
11259 editor.update(cx, |editor, cx| {
11260 match multibuffer_selection_mode {
11261 MultibufferSelectionMode::First => {
11262 if let Some(first_range) = ranges.first() {
11263 editor.change_selections(None, window, cx, |selections| {
11264 selections.clear_disjoint();
11265 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11266 });
11267 }
11268 editor.highlight_background::<Self>(
11269 &ranges,
11270 |theme| theme.editor_highlighted_line_background,
11271 cx,
11272 );
11273 }
11274 MultibufferSelectionMode::All => {
11275 editor.change_selections(None, window, cx, |selections| {
11276 selections.clear_disjoint();
11277 selections.select_anchor_ranges(ranges);
11278 });
11279 }
11280 }
11281 editor.register_buffers_with_language_servers(cx);
11282 });
11283
11284 let item = Box::new(editor);
11285 let item_id = item.item_id();
11286
11287 if split {
11288 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11289 } else {
11290 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11291 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11292 pane.close_current_preview_item(window, cx)
11293 } else {
11294 None
11295 }
11296 });
11297 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11298 }
11299 workspace.active_pane().update(cx, |pane, cx| {
11300 pane.set_preview_item_id(Some(item_id), cx);
11301 });
11302 }
11303
11304 pub fn rename(
11305 &mut self,
11306 _: &Rename,
11307 window: &mut Window,
11308 cx: &mut Context<Self>,
11309 ) -> Option<Task<Result<()>>> {
11310 use language::ToOffset as _;
11311
11312 let provider = self.semantics_provider.clone()?;
11313 let selection = self.selections.newest_anchor().clone();
11314 let (cursor_buffer, cursor_buffer_position) = self
11315 .buffer
11316 .read(cx)
11317 .text_anchor_for_position(selection.head(), cx)?;
11318 let (tail_buffer, cursor_buffer_position_end) = self
11319 .buffer
11320 .read(cx)
11321 .text_anchor_for_position(selection.tail(), cx)?;
11322 if tail_buffer != cursor_buffer {
11323 return None;
11324 }
11325
11326 let snapshot = cursor_buffer.read(cx).snapshot();
11327 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11328 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11329 let prepare_rename = provider
11330 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11331 .unwrap_or_else(|| Task::ready(Ok(None)));
11332 drop(snapshot);
11333
11334 Some(cx.spawn_in(window, |this, mut cx| async move {
11335 let rename_range = if let Some(range) = prepare_rename.await? {
11336 Some(range)
11337 } else {
11338 this.update(&mut cx, |this, cx| {
11339 let buffer = this.buffer.read(cx).snapshot(cx);
11340 let mut buffer_highlights = this
11341 .document_highlights_for_position(selection.head(), &buffer)
11342 .filter(|highlight| {
11343 highlight.start.excerpt_id == selection.head().excerpt_id
11344 && highlight.end.excerpt_id == selection.head().excerpt_id
11345 });
11346 buffer_highlights
11347 .next()
11348 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11349 })?
11350 };
11351 if let Some(rename_range) = rename_range {
11352 this.update_in(&mut cx, |this, window, cx| {
11353 let snapshot = cursor_buffer.read(cx).snapshot();
11354 let rename_buffer_range = rename_range.to_offset(&snapshot);
11355 let cursor_offset_in_rename_range =
11356 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11357 let cursor_offset_in_rename_range_end =
11358 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11359
11360 this.take_rename(false, window, cx);
11361 let buffer = this.buffer.read(cx).read(cx);
11362 let cursor_offset = selection.head().to_offset(&buffer);
11363 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11364 let rename_end = rename_start + rename_buffer_range.len();
11365 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11366 let mut old_highlight_id = None;
11367 let old_name: Arc<str> = buffer
11368 .chunks(rename_start..rename_end, true)
11369 .map(|chunk| {
11370 if old_highlight_id.is_none() {
11371 old_highlight_id = chunk.syntax_highlight_id;
11372 }
11373 chunk.text
11374 })
11375 .collect::<String>()
11376 .into();
11377
11378 drop(buffer);
11379
11380 // Position the selection in the rename editor so that it matches the current selection.
11381 this.show_local_selections = false;
11382 let rename_editor = cx.new(|cx| {
11383 let mut editor = Editor::single_line(window, cx);
11384 editor.buffer.update(cx, |buffer, cx| {
11385 buffer.edit([(0..0, old_name.clone())], None, cx)
11386 });
11387 let rename_selection_range = match cursor_offset_in_rename_range
11388 .cmp(&cursor_offset_in_rename_range_end)
11389 {
11390 Ordering::Equal => {
11391 editor.select_all(&SelectAll, window, cx);
11392 return editor;
11393 }
11394 Ordering::Less => {
11395 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11396 }
11397 Ordering::Greater => {
11398 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11399 }
11400 };
11401 if rename_selection_range.end > old_name.len() {
11402 editor.select_all(&SelectAll, window, cx);
11403 } else {
11404 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11405 s.select_ranges([rename_selection_range]);
11406 });
11407 }
11408 editor
11409 });
11410 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11411 if e == &EditorEvent::Focused {
11412 cx.emit(EditorEvent::FocusedIn)
11413 }
11414 })
11415 .detach();
11416
11417 let write_highlights =
11418 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11419 let read_highlights =
11420 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11421 let ranges = write_highlights
11422 .iter()
11423 .flat_map(|(_, ranges)| ranges.iter())
11424 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11425 .cloned()
11426 .collect();
11427
11428 this.highlight_text::<Rename>(
11429 ranges,
11430 HighlightStyle {
11431 fade_out: Some(0.6),
11432 ..Default::default()
11433 },
11434 cx,
11435 );
11436 let rename_focus_handle = rename_editor.focus_handle(cx);
11437 window.focus(&rename_focus_handle);
11438 let block_id = this.insert_blocks(
11439 [BlockProperties {
11440 style: BlockStyle::Flex,
11441 placement: BlockPlacement::Below(range.start),
11442 height: 1,
11443 render: Arc::new({
11444 let rename_editor = rename_editor.clone();
11445 move |cx: &mut BlockContext| {
11446 let mut text_style = cx.editor_style.text.clone();
11447 if let Some(highlight_style) = old_highlight_id
11448 .and_then(|h| h.style(&cx.editor_style.syntax))
11449 {
11450 text_style = text_style.highlight(highlight_style);
11451 }
11452 div()
11453 .block_mouse_down()
11454 .pl(cx.anchor_x)
11455 .child(EditorElement::new(
11456 &rename_editor,
11457 EditorStyle {
11458 background: cx.theme().system().transparent,
11459 local_player: cx.editor_style.local_player,
11460 text: text_style,
11461 scrollbar_width: cx.editor_style.scrollbar_width,
11462 syntax: cx.editor_style.syntax.clone(),
11463 status: cx.editor_style.status.clone(),
11464 inlay_hints_style: HighlightStyle {
11465 font_weight: Some(FontWeight::BOLD),
11466 ..make_inlay_hints_style(cx.app)
11467 },
11468 inline_completion_styles: make_suggestion_styles(
11469 cx.app,
11470 ),
11471 ..EditorStyle::default()
11472 },
11473 ))
11474 .into_any_element()
11475 }
11476 }),
11477 priority: 0,
11478 }],
11479 Some(Autoscroll::fit()),
11480 cx,
11481 )[0];
11482 this.pending_rename = Some(RenameState {
11483 range,
11484 old_name,
11485 editor: rename_editor,
11486 block_id,
11487 });
11488 })?;
11489 }
11490
11491 Ok(())
11492 }))
11493 }
11494
11495 pub fn confirm_rename(
11496 &mut self,
11497 _: &ConfirmRename,
11498 window: &mut Window,
11499 cx: &mut Context<Self>,
11500 ) -> Option<Task<Result<()>>> {
11501 let rename = self.take_rename(false, window, cx)?;
11502 let workspace = self.workspace()?.downgrade();
11503 let (buffer, start) = self
11504 .buffer
11505 .read(cx)
11506 .text_anchor_for_position(rename.range.start, cx)?;
11507 let (end_buffer, _) = self
11508 .buffer
11509 .read(cx)
11510 .text_anchor_for_position(rename.range.end, cx)?;
11511 if buffer != end_buffer {
11512 return None;
11513 }
11514
11515 let old_name = rename.old_name;
11516 let new_name = rename.editor.read(cx).text(cx);
11517
11518 let rename = self.semantics_provider.as_ref()?.perform_rename(
11519 &buffer,
11520 start,
11521 new_name.clone(),
11522 cx,
11523 )?;
11524
11525 Some(cx.spawn_in(window, |editor, mut cx| async move {
11526 let project_transaction = rename.await?;
11527 Self::open_project_transaction(
11528 &editor,
11529 workspace,
11530 project_transaction,
11531 format!("Rename: {} → {}", old_name, new_name),
11532 cx.clone(),
11533 )
11534 .await?;
11535
11536 editor.update(&mut cx, |editor, cx| {
11537 editor.refresh_document_highlights(cx);
11538 })?;
11539 Ok(())
11540 }))
11541 }
11542
11543 fn take_rename(
11544 &mut self,
11545 moving_cursor: bool,
11546 window: &mut Window,
11547 cx: &mut Context<Self>,
11548 ) -> Option<RenameState> {
11549 let rename = self.pending_rename.take()?;
11550 if rename.editor.focus_handle(cx).is_focused(window) {
11551 window.focus(&self.focus_handle);
11552 }
11553
11554 self.remove_blocks(
11555 [rename.block_id].into_iter().collect(),
11556 Some(Autoscroll::fit()),
11557 cx,
11558 );
11559 self.clear_highlights::<Rename>(cx);
11560 self.show_local_selections = true;
11561
11562 if moving_cursor {
11563 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11564 editor.selections.newest::<usize>(cx).head()
11565 });
11566
11567 // Update the selection to match the position of the selection inside
11568 // the rename editor.
11569 let snapshot = self.buffer.read(cx).read(cx);
11570 let rename_range = rename.range.to_offset(&snapshot);
11571 let cursor_in_editor = snapshot
11572 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11573 .min(rename_range.end);
11574 drop(snapshot);
11575
11576 self.change_selections(None, window, cx, |s| {
11577 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11578 });
11579 } else {
11580 self.refresh_document_highlights(cx);
11581 }
11582
11583 Some(rename)
11584 }
11585
11586 pub fn pending_rename(&self) -> Option<&RenameState> {
11587 self.pending_rename.as_ref()
11588 }
11589
11590 fn format(
11591 &mut self,
11592 _: &Format,
11593 window: &mut Window,
11594 cx: &mut Context<Self>,
11595 ) -> Option<Task<Result<()>>> {
11596 let project = match &self.project {
11597 Some(project) => project.clone(),
11598 None => return None,
11599 };
11600
11601 Some(self.perform_format(
11602 project,
11603 FormatTrigger::Manual,
11604 FormatTarget::Buffers,
11605 window,
11606 cx,
11607 ))
11608 }
11609
11610 fn format_selections(
11611 &mut self,
11612 _: &FormatSelections,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) -> Option<Task<Result<()>>> {
11616 let project = match &self.project {
11617 Some(project) => project.clone(),
11618 None => return None,
11619 };
11620
11621 let ranges = self
11622 .selections
11623 .all_adjusted(cx)
11624 .into_iter()
11625 .map(|selection| selection.range())
11626 .collect_vec();
11627
11628 Some(self.perform_format(
11629 project,
11630 FormatTrigger::Manual,
11631 FormatTarget::Ranges(ranges),
11632 window,
11633 cx,
11634 ))
11635 }
11636
11637 fn perform_format(
11638 &mut self,
11639 project: Entity<Project>,
11640 trigger: FormatTrigger,
11641 target: FormatTarget,
11642 window: &mut Window,
11643 cx: &mut Context<Self>,
11644 ) -> Task<Result<()>> {
11645 let buffer = self.buffer.clone();
11646 let (buffers, target) = match target {
11647 FormatTarget::Buffers => {
11648 let mut buffers = buffer.read(cx).all_buffers();
11649 if trigger == FormatTrigger::Save {
11650 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11651 }
11652 (buffers, LspFormatTarget::Buffers)
11653 }
11654 FormatTarget::Ranges(selection_ranges) => {
11655 let multi_buffer = buffer.read(cx);
11656 let snapshot = multi_buffer.read(cx);
11657 let mut buffers = HashSet::default();
11658 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11659 BTreeMap::new();
11660 for selection_range in selection_ranges {
11661 for (buffer, buffer_range, _) in
11662 snapshot.range_to_buffer_ranges(selection_range)
11663 {
11664 let buffer_id = buffer.remote_id();
11665 let start = buffer.anchor_before(buffer_range.start);
11666 let end = buffer.anchor_after(buffer_range.end);
11667 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11668 buffer_id_to_ranges
11669 .entry(buffer_id)
11670 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11671 .or_insert_with(|| vec![start..end]);
11672 }
11673 }
11674 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11675 }
11676 };
11677
11678 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11679 let format = project.update(cx, |project, cx| {
11680 project.format(buffers, target, true, trigger, cx)
11681 });
11682
11683 cx.spawn_in(window, |_, mut cx| async move {
11684 let transaction = futures::select_biased! {
11685 () = timeout => {
11686 log::warn!("timed out waiting for formatting");
11687 None
11688 }
11689 transaction = format.log_err().fuse() => transaction,
11690 };
11691
11692 buffer
11693 .update(&mut cx, |buffer, cx| {
11694 if let Some(transaction) = transaction {
11695 if !buffer.is_singleton() {
11696 buffer.push_transaction(&transaction.0, cx);
11697 }
11698 }
11699
11700 cx.notify();
11701 })
11702 .ok();
11703
11704 Ok(())
11705 })
11706 }
11707
11708 fn restart_language_server(
11709 &mut self,
11710 _: &RestartLanguageServer,
11711 _: &mut Window,
11712 cx: &mut Context<Self>,
11713 ) {
11714 if let Some(project) = self.project.clone() {
11715 self.buffer.update(cx, |multi_buffer, cx| {
11716 project.update(cx, |project, cx| {
11717 project.restart_language_servers_for_buffers(
11718 multi_buffer.all_buffers().into_iter().collect(),
11719 cx,
11720 );
11721 });
11722 })
11723 }
11724 }
11725
11726 fn cancel_language_server_work(
11727 workspace: &mut Workspace,
11728 _: &actions::CancelLanguageServerWork,
11729 _: &mut Window,
11730 cx: &mut Context<Workspace>,
11731 ) {
11732 let project = workspace.project();
11733 let buffers = workspace
11734 .active_item(cx)
11735 .and_then(|item| item.act_as::<Editor>(cx))
11736 .map_or(HashSet::default(), |editor| {
11737 editor.read(cx).buffer.read(cx).all_buffers()
11738 });
11739 project.update(cx, |project, cx| {
11740 project.cancel_language_server_work_for_buffers(buffers, cx);
11741 });
11742 }
11743
11744 fn show_character_palette(
11745 &mut self,
11746 _: &ShowCharacterPalette,
11747 window: &mut Window,
11748 _: &mut Context<Self>,
11749 ) {
11750 window.show_character_palette();
11751 }
11752
11753 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11754 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11755 let buffer = self.buffer.read(cx).snapshot(cx);
11756 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11757 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11758 let is_valid = buffer
11759 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11760 .any(|entry| {
11761 entry.diagnostic.is_primary
11762 && !entry.range.is_empty()
11763 && entry.range.start == primary_range_start
11764 && entry.diagnostic.message == active_diagnostics.primary_message
11765 });
11766
11767 if is_valid != active_diagnostics.is_valid {
11768 active_diagnostics.is_valid = is_valid;
11769 let mut new_styles = HashMap::default();
11770 for (block_id, diagnostic) in &active_diagnostics.blocks {
11771 new_styles.insert(
11772 *block_id,
11773 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11774 );
11775 }
11776 self.display_map.update(cx, |display_map, _cx| {
11777 display_map.replace_blocks(new_styles)
11778 });
11779 }
11780 }
11781 }
11782
11783 fn activate_diagnostics(
11784 &mut self,
11785 buffer_id: BufferId,
11786 group_id: usize,
11787 window: &mut Window,
11788 cx: &mut Context<Self>,
11789 ) {
11790 self.dismiss_diagnostics(cx);
11791 let snapshot = self.snapshot(window, cx);
11792 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11793 let buffer = self.buffer.read(cx).snapshot(cx);
11794
11795 let mut primary_range = None;
11796 let mut primary_message = None;
11797 let diagnostic_group = buffer
11798 .diagnostic_group(buffer_id, group_id)
11799 .filter_map(|entry| {
11800 let start = entry.range.start;
11801 let end = entry.range.end;
11802 if snapshot.is_line_folded(MultiBufferRow(start.row))
11803 && (start.row == end.row
11804 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11805 {
11806 return None;
11807 }
11808 if entry.diagnostic.is_primary {
11809 primary_range = Some(entry.range.clone());
11810 primary_message = Some(entry.diagnostic.message.clone());
11811 }
11812 Some(entry)
11813 })
11814 .collect::<Vec<_>>();
11815 let primary_range = primary_range?;
11816 let primary_message = primary_message?;
11817
11818 let blocks = display_map
11819 .insert_blocks(
11820 diagnostic_group.iter().map(|entry| {
11821 let diagnostic = entry.diagnostic.clone();
11822 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11823 BlockProperties {
11824 style: BlockStyle::Fixed,
11825 placement: BlockPlacement::Below(
11826 buffer.anchor_after(entry.range.start),
11827 ),
11828 height: message_height,
11829 render: diagnostic_block_renderer(diagnostic, None, true, true),
11830 priority: 0,
11831 }
11832 }),
11833 cx,
11834 )
11835 .into_iter()
11836 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11837 .collect();
11838
11839 Some(ActiveDiagnosticGroup {
11840 primary_range: buffer.anchor_before(primary_range.start)
11841 ..buffer.anchor_after(primary_range.end),
11842 primary_message,
11843 group_id,
11844 blocks,
11845 is_valid: true,
11846 })
11847 });
11848 }
11849
11850 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11851 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11852 self.display_map.update(cx, |display_map, cx| {
11853 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11854 });
11855 cx.notify();
11856 }
11857 }
11858
11859 pub fn set_selections_from_remote(
11860 &mut self,
11861 selections: Vec<Selection<Anchor>>,
11862 pending_selection: Option<Selection<Anchor>>,
11863 window: &mut Window,
11864 cx: &mut Context<Self>,
11865 ) {
11866 let old_cursor_position = self.selections.newest_anchor().head();
11867 self.selections.change_with(cx, |s| {
11868 s.select_anchors(selections);
11869 if let Some(pending_selection) = pending_selection {
11870 s.set_pending(pending_selection, SelectMode::Character);
11871 } else {
11872 s.clear_pending();
11873 }
11874 });
11875 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11876 }
11877
11878 fn push_to_selection_history(&mut self) {
11879 self.selection_history.push(SelectionHistoryEntry {
11880 selections: self.selections.disjoint_anchors(),
11881 select_next_state: self.select_next_state.clone(),
11882 select_prev_state: self.select_prev_state.clone(),
11883 add_selections_state: self.add_selections_state.clone(),
11884 });
11885 }
11886
11887 pub fn transact(
11888 &mut self,
11889 window: &mut Window,
11890 cx: &mut Context<Self>,
11891 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11892 ) -> Option<TransactionId> {
11893 self.start_transaction_at(Instant::now(), window, cx);
11894 update(self, window, cx);
11895 self.end_transaction_at(Instant::now(), cx)
11896 }
11897
11898 pub fn start_transaction_at(
11899 &mut self,
11900 now: Instant,
11901 window: &mut Window,
11902 cx: &mut Context<Self>,
11903 ) {
11904 self.end_selection(window, cx);
11905 if let Some(tx_id) = self
11906 .buffer
11907 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11908 {
11909 self.selection_history
11910 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11911 cx.emit(EditorEvent::TransactionBegun {
11912 transaction_id: tx_id,
11913 })
11914 }
11915 }
11916
11917 pub fn end_transaction_at(
11918 &mut self,
11919 now: Instant,
11920 cx: &mut Context<Self>,
11921 ) -> Option<TransactionId> {
11922 if let Some(transaction_id) = self
11923 .buffer
11924 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11925 {
11926 if let Some((_, end_selections)) =
11927 self.selection_history.transaction_mut(transaction_id)
11928 {
11929 *end_selections = Some(self.selections.disjoint_anchors());
11930 } else {
11931 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11932 }
11933
11934 cx.emit(EditorEvent::Edited { transaction_id });
11935 Some(transaction_id)
11936 } else {
11937 None
11938 }
11939 }
11940
11941 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11942 if self.selection_mark_mode {
11943 self.change_selections(None, window, cx, |s| {
11944 s.move_with(|_, sel| {
11945 sel.collapse_to(sel.head(), SelectionGoal::None);
11946 });
11947 })
11948 }
11949 self.selection_mark_mode = true;
11950 cx.notify();
11951 }
11952
11953 pub fn swap_selection_ends(
11954 &mut self,
11955 _: &actions::SwapSelectionEnds,
11956 window: &mut Window,
11957 cx: &mut Context<Self>,
11958 ) {
11959 self.change_selections(None, window, cx, |s| {
11960 s.move_with(|_, sel| {
11961 if sel.start != sel.end {
11962 sel.reversed = !sel.reversed
11963 }
11964 });
11965 });
11966 self.request_autoscroll(Autoscroll::newest(), cx);
11967 cx.notify();
11968 }
11969
11970 pub fn toggle_fold(
11971 &mut self,
11972 _: &actions::ToggleFold,
11973 window: &mut Window,
11974 cx: &mut Context<Self>,
11975 ) {
11976 if self.is_singleton(cx) {
11977 let selection = self.selections.newest::<Point>(cx);
11978
11979 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11980 let range = if selection.is_empty() {
11981 let point = selection.head().to_display_point(&display_map);
11982 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11983 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11984 .to_point(&display_map);
11985 start..end
11986 } else {
11987 selection.range()
11988 };
11989 if display_map.folds_in_range(range).next().is_some() {
11990 self.unfold_lines(&Default::default(), window, cx)
11991 } else {
11992 self.fold(&Default::default(), window, cx)
11993 }
11994 } else {
11995 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11996 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11997 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11998 .map(|(snapshot, _, _)| snapshot.remote_id())
11999 .collect();
12000
12001 for buffer_id in buffer_ids {
12002 if self.is_buffer_folded(buffer_id, cx) {
12003 self.unfold_buffer(buffer_id, cx);
12004 } else {
12005 self.fold_buffer(buffer_id, cx);
12006 }
12007 }
12008 }
12009 }
12010
12011 pub fn toggle_fold_recursive(
12012 &mut self,
12013 _: &actions::ToggleFoldRecursive,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) {
12017 let selection = self.selections.newest::<Point>(cx);
12018
12019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12020 let range = if selection.is_empty() {
12021 let point = selection.head().to_display_point(&display_map);
12022 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12023 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12024 .to_point(&display_map);
12025 start..end
12026 } else {
12027 selection.range()
12028 };
12029 if display_map.folds_in_range(range).next().is_some() {
12030 self.unfold_recursive(&Default::default(), window, cx)
12031 } else {
12032 self.fold_recursive(&Default::default(), window, cx)
12033 }
12034 }
12035
12036 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12037 if self.is_singleton(cx) {
12038 let mut to_fold = Vec::new();
12039 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12040 let selections = self.selections.all_adjusted(cx);
12041
12042 for selection in selections {
12043 let range = selection.range().sorted();
12044 let buffer_start_row = range.start.row;
12045
12046 if range.start.row != range.end.row {
12047 let mut found = false;
12048 let mut row = range.start.row;
12049 while row <= range.end.row {
12050 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12051 {
12052 found = true;
12053 row = crease.range().end.row + 1;
12054 to_fold.push(crease);
12055 } else {
12056 row += 1
12057 }
12058 }
12059 if found {
12060 continue;
12061 }
12062 }
12063
12064 for row in (0..=range.start.row).rev() {
12065 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12066 if crease.range().end.row >= buffer_start_row {
12067 to_fold.push(crease);
12068 if row <= range.start.row {
12069 break;
12070 }
12071 }
12072 }
12073 }
12074 }
12075
12076 self.fold_creases(to_fold, true, window, cx);
12077 } else {
12078 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12079
12080 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12081 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12082 .map(|(snapshot, _, _)| snapshot.remote_id())
12083 .collect();
12084 for buffer_id in buffer_ids {
12085 self.fold_buffer(buffer_id, cx);
12086 }
12087 }
12088 }
12089
12090 fn fold_at_level(
12091 &mut self,
12092 fold_at: &FoldAtLevel,
12093 window: &mut Window,
12094 cx: &mut Context<Self>,
12095 ) {
12096 if !self.buffer.read(cx).is_singleton() {
12097 return;
12098 }
12099
12100 let fold_at_level = fold_at.0;
12101 let snapshot = self.buffer.read(cx).snapshot(cx);
12102 let mut to_fold = Vec::new();
12103 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12104
12105 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12106 while start_row < end_row {
12107 match self
12108 .snapshot(window, cx)
12109 .crease_for_buffer_row(MultiBufferRow(start_row))
12110 {
12111 Some(crease) => {
12112 let nested_start_row = crease.range().start.row + 1;
12113 let nested_end_row = crease.range().end.row;
12114
12115 if current_level < fold_at_level {
12116 stack.push((nested_start_row, nested_end_row, current_level + 1));
12117 } else if current_level == fold_at_level {
12118 to_fold.push(crease);
12119 }
12120
12121 start_row = nested_end_row + 1;
12122 }
12123 None => start_row += 1,
12124 }
12125 }
12126 }
12127
12128 self.fold_creases(to_fold, true, window, cx);
12129 }
12130
12131 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12132 if self.buffer.read(cx).is_singleton() {
12133 let mut fold_ranges = Vec::new();
12134 let snapshot = self.buffer.read(cx).snapshot(cx);
12135
12136 for row in 0..snapshot.max_row().0 {
12137 if let Some(foldable_range) = self
12138 .snapshot(window, cx)
12139 .crease_for_buffer_row(MultiBufferRow(row))
12140 {
12141 fold_ranges.push(foldable_range);
12142 }
12143 }
12144
12145 self.fold_creases(fold_ranges, true, window, cx);
12146 } else {
12147 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12148 editor
12149 .update_in(&mut cx, |editor, _, cx| {
12150 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12151 editor.fold_buffer(buffer_id, cx);
12152 }
12153 })
12154 .ok();
12155 });
12156 }
12157 }
12158
12159 pub fn fold_function_bodies(
12160 &mut self,
12161 _: &actions::FoldFunctionBodies,
12162 window: &mut Window,
12163 cx: &mut Context<Self>,
12164 ) {
12165 let snapshot = self.buffer.read(cx).snapshot(cx);
12166
12167 let ranges = snapshot
12168 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12169 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12170 .collect::<Vec<_>>();
12171
12172 let creases = ranges
12173 .into_iter()
12174 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12175 .collect();
12176
12177 self.fold_creases(creases, true, window, cx);
12178 }
12179
12180 pub fn fold_recursive(
12181 &mut self,
12182 _: &actions::FoldRecursive,
12183 window: &mut Window,
12184 cx: &mut Context<Self>,
12185 ) {
12186 let mut to_fold = Vec::new();
12187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12188 let selections = self.selections.all_adjusted(cx);
12189
12190 for selection in selections {
12191 let range = selection.range().sorted();
12192 let buffer_start_row = range.start.row;
12193
12194 if range.start.row != range.end.row {
12195 let mut found = false;
12196 for row in range.start.row..=range.end.row {
12197 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12198 found = true;
12199 to_fold.push(crease);
12200 }
12201 }
12202 if found {
12203 continue;
12204 }
12205 }
12206
12207 for row in (0..=range.start.row).rev() {
12208 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12209 if crease.range().end.row >= buffer_start_row {
12210 to_fold.push(crease);
12211 } else {
12212 break;
12213 }
12214 }
12215 }
12216 }
12217
12218 self.fold_creases(to_fold, true, window, cx);
12219 }
12220
12221 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12222 let buffer_row = fold_at.buffer_row;
12223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12224
12225 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12226 let autoscroll = self
12227 .selections
12228 .all::<Point>(cx)
12229 .iter()
12230 .any(|selection| crease.range().overlaps(&selection.range()));
12231
12232 self.fold_creases(vec![crease], autoscroll, window, cx);
12233 }
12234 }
12235
12236 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12237 if self.is_singleton(cx) {
12238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12239 let buffer = &display_map.buffer_snapshot;
12240 let selections = self.selections.all::<Point>(cx);
12241 let ranges = selections
12242 .iter()
12243 .map(|s| {
12244 let range = s.display_range(&display_map).sorted();
12245 let mut start = range.start.to_point(&display_map);
12246 let mut end = range.end.to_point(&display_map);
12247 start.column = 0;
12248 end.column = buffer.line_len(MultiBufferRow(end.row));
12249 start..end
12250 })
12251 .collect::<Vec<_>>();
12252
12253 self.unfold_ranges(&ranges, true, true, cx);
12254 } else {
12255 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12256 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12257 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12258 .map(|(snapshot, _, _)| snapshot.remote_id())
12259 .collect();
12260 for buffer_id in buffer_ids {
12261 self.unfold_buffer(buffer_id, cx);
12262 }
12263 }
12264 }
12265
12266 pub fn unfold_recursive(
12267 &mut self,
12268 _: &UnfoldRecursive,
12269 _window: &mut Window,
12270 cx: &mut Context<Self>,
12271 ) {
12272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12273 let selections = self.selections.all::<Point>(cx);
12274 let ranges = selections
12275 .iter()
12276 .map(|s| {
12277 let mut range = s.display_range(&display_map).sorted();
12278 *range.start.column_mut() = 0;
12279 *range.end.column_mut() = display_map.line_len(range.end.row());
12280 let start = range.start.to_point(&display_map);
12281 let end = range.end.to_point(&display_map);
12282 start..end
12283 })
12284 .collect::<Vec<_>>();
12285
12286 self.unfold_ranges(&ranges, true, true, cx);
12287 }
12288
12289 pub fn unfold_at(
12290 &mut self,
12291 unfold_at: &UnfoldAt,
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
12297 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12298 ..Point::new(
12299 unfold_at.buffer_row.0,
12300 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12301 );
12302
12303 let autoscroll = self
12304 .selections
12305 .all::<Point>(cx)
12306 .iter()
12307 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12308
12309 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12310 }
12311
12312 pub fn unfold_all(
12313 &mut self,
12314 _: &actions::UnfoldAll,
12315 _window: &mut Window,
12316 cx: &mut Context<Self>,
12317 ) {
12318 if self.buffer.read(cx).is_singleton() {
12319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12320 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12321 } else {
12322 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12323 editor
12324 .update(&mut cx, |editor, cx| {
12325 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12326 editor.unfold_buffer(buffer_id, cx);
12327 }
12328 })
12329 .ok();
12330 });
12331 }
12332 }
12333
12334 pub fn fold_selected_ranges(
12335 &mut self,
12336 _: &FoldSelectedRanges,
12337 window: &mut Window,
12338 cx: &mut Context<Self>,
12339 ) {
12340 let selections = self.selections.all::<Point>(cx);
12341 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12342 let line_mode = self.selections.line_mode;
12343 let ranges = selections
12344 .into_iter()
12345 .map(|s| {
12346 if line_mode {
12347 let start = Point::new(s.start.row, 0);
12348 let end = Point::new(
12349 s.end.row,
12350 display_map
12351 .buffer_snapshot
12352 .line_len(MultiBufferRow(s.end.row)),
12353 );
12354 Crease::simple(start..end, display_map.fold_placeholder.clone())
12355 } else {
12356 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12357 }
12358 })
12359 .collect::<Vec<_>>();
12360 self.fold_creases(ranges, true, window, cx);
12361 }
12362
12363 pub fn fold_ranges<T: ToOffset + Clone>(
12364 &mut self,
12365 ranges: Vec<Range<T>>,
12366 auto_scroll: bool,
12367 window: &mut Window,
12368 cx: &mut Context<Self>,
12369 ) {
12370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12371 let ranges = ranges
12372 .into_iter()
12373 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12374 .collect::<Vec<_>>();
12375 self.fold_creases(ranges, auto_scroll, window, cx);
12376 }
12377
12378 pub fn fold_creases<T: ToOffset + Clone>(
12379 &mut self,
12380 creases: Vec<Crease<T>>,
12381 auto_scroll: bool,
12382 window: &mut Window,
12383 cx: &mut Context<Self>,
12384 ) {
12385 if creases.is_empty() {
12386 return;
12387 }
12388
12389 let mut buffers_affected = HashSet::default();
12390 let multi_buffer = self.buffer().read(cx);
12391 for crease in &creases {
12392 if let Some((_, buffer, _)) =
12393 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12394 {
12395 buffers_affected.insert(buffer.read(cx).remote_id());
12396 };
12397 }
12398
12399 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12400
12401 if auto_scroll {
12402 self.request_autoscroll(Autoscroll::fit(), cx);
12403 }
12404
12405 cx.notify();
12406
12407 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12408 // Clear diagnostics block when folding a range that contains it.
12409 let snapshot = self.snapshot(window, cx);
12410 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12411 drop(snapshot);
12412 self.active_diagnostics = Some(active_diagnostics);
12413 self.dismiss_diagnostics(cx);
12414 } else {
12415 self.active_diagnostics = Some(active_diagnostics);
12416 }
12417 }
12418
12419 self.scrollbar_marker_state.dirty = true;
12420 }
12421
12422 /// Removes any folds whose ranges intersect any of the given ranges.
12423 pub fn unfold_ranges<T: ToOffset + Clone>(
12424 &mut self,
12425 ranges: &[Range<T>],
12426 inclusive: bool,
12427 auto_scroll: bool,
12428 cx: &mut Context<Self>,
12429 ) {
12430 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12431 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12432 });
12433 }
12434
12435 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12436 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12437 return;
12438 }
12439 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12440 self.display_map
12441 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12442 cx.emit(EditorEvent::BufferFoldToggled {
12443 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12444 folded: true,
12445 });
12446 cx.notify();
12447 }
12448
12449 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12450 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12451 return;
12452 }
12453 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12454 self.display_map.update(cx, |display_map, cx| {
12455 display_map.unfold_buffer(buffer_id, cx);
12456 });
12457 cx.emit(EditorEvent::BufferFoldToggled {
12458 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12459 folded: false,
12460 });
12461 cx.notify();
12462 }
12463
12464 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12465 self.display_map.read(cx).is_buffer_folded(buffer)
12466 }
12467
12468 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12469 self.display_map.read(cx).folded_buffers()
12470 }
12471
12472 /// Removes any folds with the given ranges.
12473 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12474 &mut self,
12475 ranges: &[Range<T>],
12476 type_id: TypeId,
12477 auto_scroll: bool,
12478 cx: &mut Context<Self>,
12479 ) {
12480 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12481 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12482 });
12483 }
12484
12485 fn remove_folds_with<T: ToOffset + Clone>(
12486 &mut self,
12487 ranges: &[Range<T>],
12488 auto_scroll: bool,
12489 cx: &mut Context<Self>,
12490 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12491 ) {
12492 if ranges.is_empty() {
12493 return;
12494 }
12495
12496 let mut buffers_affected = HashSet::default();
12497 let multi_buffer = self.buffer().read(cx);
12498 for range in ranges {
12499 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12500 buffers_affected.insert(buffer.read(cx).remote_id());
12501 };
12502 }
12503
12504 self.display_map.update(cx, update);
12505
12506 if auto_scroll {
12507 self.request_autoscroll(Autoscroll::fit(), cx);
12508 }
12509
12510 cx.notify();
12511 self.scrollbar_marker_state.dirty = true;
12512 self.active_indent_guides_state.dirty = true;
12513 }
12514
12515 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12516 self.display_map.read(cx).fold_placeholder.clone()
12517 }
12518
12519 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12520 self.buffer.update(cx, |buffer, cx| {
12521 buffer.set_all_diff_hunks_expanded(cx);
12522 });
12523 }
12524
12525 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12526 self.distinguish_unstaged_diff_hunks = true;
12527 }
12528
12529 pub fn expand_all_diff_hunks(
12530 &mut self,
12531 _: &ExpandAllHunkDiffs,
12532 _window: &mut Window,
12533 cx: &mut Context<Self>,
12534 ) {
12535 self.buffer.update(cx, |buffer, cx| {
12536 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12537 });
12538 }
12539
12540 pub fn toggle_selected_diff_hunks(
12541 &mut self,
12542 _: &ToggleSelectedDiffHunks,
12543 _window: &mut Window,
12544 cx: &mut Context<Self>,
12545 ) {
12546 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12547 self.toggle_diff_hunks_in_ranges(ranges, cx);
12548 }
12549
12550 fn diff_hunks_in_ranges<'a>(
12551 &'a self,
12552 ranges: &'a [Range<Anchor>],
12553 buffer: &'a MultiBufferSnapshot,
12554 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12555 ranges.iter().flat_map(move |range| {
12556 let end_excerpt_id = range.end.excerpt_id;
12557 let range = range.to_point(buffer);
12558 let mut peek_end = range.end;
12559 if range.end.row < buffer.max_row().0 {
12560 peek_end = Point::new(range.end.row + 1, 0);
12561 }
12562 buffer
12563 .diff_hunks_in_range(range.start..peek_end)
12564 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12565 })
12566 }
12567
12568 pub fn has_stageable_diff_hunks_in_ranges(
12569 &self,
12570 ranges: &[Range<Anchor>],
12571 snapshot: &MultiBufferSnapshot,
12572 ) -> bool {
12573 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12574 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12575 }
12576
12577 pub fn toggle_staged_selected_diff_hunks(
12578 &mut self,
12579 _: &ToggleStagedSelectedDiffHunks,
12580 _window: &mut Window,
12581 cx: &mut Context<Self>,
12582 ) {
12583 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12584 self.stage_or_unstage_diff_hunks(&ranges, cx);
12585 }
12586
12587 pub fn stage_or_unstage_diff_hunks(
12588 &mut self,
12589 ranges: &[Range<Anchor>],
12590 cx: &mut Context<Self>,
12591 ) {
12592 let Some(project) = &self.project else {
12593 return;
12594 };
12595 let snapshot = self.buffer.read(cx).snapshot(cx);
12596 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12597
12598 let chunk_by = self
12599 .diff_hunks_in_ranges(&ranges, &snapshot)
12600 .chunk_by(|hunk| hunk.buffer_id);
12601 for (buffer_id, hunks) in &chunk_by {
12602 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12603 log::debug!("no buffer for id");
12604 continue;
12605 };
12606 let buffer = buffer.read(cx).snapshot();
12607 let Some((repo, path)) = project
12608 .read(cx)
12609 .repository_and_path_for_buffer_id(buffer_id, cx)
12610 else {
12611 log::debug!("no git repo for buffer id");
12612 continue;
12613 };
12614 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12615 log::debug!("no diff for buffer id");
12616 continue;
12617 };
12618 let Some(secondary_diff) = diff.secondary_diff() else {
12619 log::debug!("no secondary diff for buffer id");
12620 continue;
12621 };
12622
12623 let edits = diff.secondary_edits_for_stage_or_unstage(
12624 stage,
12625 hunks.map(|hunk| {
12626 (
12627 hunk.diff_base_byte_range.clone(),
12628 hunk.secondary_diff_base_byte_range.clone(),
12629 hunk.buffer_range.clone(),
12630 )
12631 }),
12632 &buffer,
12633 );
12634
12635 let index_base = secondary_diff.base_text().map_or_else(
12636 || Rope::from(""),
12637 |snapshot| snapshot.text.as_rope().clone(),
12638 );
12639 let index_buffer = cx.new(|cx| {
12640 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12641 });
12642 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12643 index_buffer.edit(edits, None, cx);
12644 index_buffer.snapshot().as_rope().to_string()
12645 });
12646 let new_index_text = if new_index_text.is_empty()
12647 && (diff.is_single_insertion
12648 || buffer
12649 .file()
12650 .map_or(false, |file| file.disk_state() == DiskState::New))
12651 {
12652 log::debug!("removing from index");
12653 None
12654 } else {
12655 Some(new_index_text)
12656 };
12657
12658 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12659 }
12660 }
12661
12662 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12663 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12664 self.buffer
12665 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12666 }
12667
12668 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12669 self.buffer.update(cx, |buffer, cx| {
12670 let ranges = vec![Anchor::min()..Anchor::max()];
12671 if !buffer.all_diff_hunks_expanded()
12672 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12673 {
12674 buffer.collapse_diff_hunks(ranges, cx);
12675 true
12676 } else {
12677 false
12678 }
12679 })
12680 }
12681
12682 fn toggle_diff_hunks_in_ranges(
12683 &mut self,
12684 ranges: Vec<Range<Anchor>>,
12685 cx: &mut Context<'_, Editor>,
12686 ) {
12687 self.buffer.update(cx, |buffer, cx| {
12688 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12689 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12690 })
12691 }
12692
12693 fn toggle_diff_hunks_in_ranges_narrow(
12694 &mut self,
12695 ranges: Vec<Range<Anchor>>,
12696 cx: &mut Context<'_, Editor>,
12697 ) {
12698 self.buffer.update(cx, |buffer, cx| {
12699 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12700 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12701 })
12702 }
12703
12704 pub(crate) fn apply_all_diff_hunks(
12705 &mut self,
12706 _: &ApplyAllDiffHunks,
12707 window: &mut Window,
12708 cx: &mut Context<Self>,
12709 ) {
12710 let buffers = self.buffer.read(cx).all_buffers();
12711 for branch_buffer in buffers {
12712 branch_buffer.update(cx, |branch_buffer, cx| {
12713 branch_buffer.merge_into_base(Vec::new(), cx);
12714 });
12715 }
12716
12717 if let Some(project) = self.project.clone() {
12718 self.save(true, project, window, cx).detach_and_log_err(cx);
12719 }
12720 }
12721
12722 pub(crate) fn apply_selected_diff_hunks(
12723 &mut self,
12724 _: &ApplyDiffHunk,
12725 window: &mut Window,
12726 cx: &mut Context<Self>,
12727 ) {
12728 let snapshot = self.snapshot(window, cx);
12729 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12730 let mut ranges_by_buffer = HashMap::default();
12731 self.transact(window, cx, |editor, _window, cx| {
12732 for hunk in hunks {
12733 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12734 ranges_by_buffer
12735 .entry(buffer.clone())
12736 .or_insert_with(Vec::new)
12737 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12738 }
12739 }
12740
12741 for (buffer, ranges) in ranges_by_buffer {
12742 buffer.update(cx, |buffer, cx| {
12743 buffer.merge_into_base(ranges, cx);
12744 });
12745 }
12746 });
12747
12748 if let Some(project) = self.project.clone() {
12749 self.save(true, project, window, cx).detach_and_log_err(cx);
12750 }
12751 }
12752
12753 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12754 if hovered != self.gutter_hovered {
12755 self.gutter_hovered = hovered;
12756 cx.notify();
12757 }
12758 }
12759
12760 pub fn insert_blocks(
12761 &mut self,
12762 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12763 autoscroll: Option<Autoscroll>,
12764 cx: &mut Context<Self>,
12765 ) -> Vec<CustomBlockId> {
12766 let blocks = self
12767 .display_map
12768 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12769 if let Some(autoscroll) = autoscroll {
12770 self.request_autoscroll(autoscroll, cx);
12771 }
12772 cx.notify();
12773 blocks
12774 }
12775
12776 pub fn resize_blocks(
12777 &mut self,
12778 heights: HashMap<CustomBlockId, u32>,
12779 autoscroll: Option<Autoscroll>,
12780 cx: &mut Context<Self>,
12781 ) {
12782 self.display_map
12783 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12784 if let Some(autoscroll) = autoscroll {
12785 self.request_autoscroll(autoscroll, cx);
12786 }
12787 cx.notify();
12788 }
12789
12790 pub fn replace_blocks(
12791 &mut self,
12792 renderers: HashMap<CustomBlockId, RenderBlock>,
12793 autoscroll: Option<Autoscroll>,
12794 cx: &mut Context<Self>,
12795 ) {
12796 self.display_map
12797 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12798 if let Some(autoscroll) = autoscroll {
12799 self.request_autoscroll(autoscroll, cx);
12800 }
12801 cx.notify();
12802 }
12803
12804 pub fn remove_blocks(
12805 &mut self,
12806 block_ids: HashSet<CustomBlockId>,
12807 autoscroll: Option<Autoscroll>,
12808 cx: &mut Context<Self>,
12809 ) {
12810 self.display_map.update(cx, |display_map, cx| {
12811 display_map.remove_blocks(block_ids, cx)
12812 });
12813 if let Some(autoscroll) = autoscroll {
12814 self.request_autoscroll(autoscroll, cx);
12815 }
12816 cx.notify();
12817 }
12818
12819 pub fn row_for_block(
12820 &self,
12821 block_id: CustomBlockId,
12822 cx: &mut Context<Self>,
12823 ) -> Option<DisplayRow> {
12824 self.display_map
12825 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12826 }
12827
12828 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12829 self.focused_block = Some(focused_block);
12830 }
12831
12832 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12833 self.focused_block.take()
12834 }
12835
12836 pub fn insert_creases(
12837 &mut self,
12838 creases: impl IntoIterator<Item = Crease<Anchor>>,
12839 cx: &mut Context<Self>,
12840 ) -> Vec<CreaseId> {
12841 self.display_map
12842 .update(cx, |map, cx| map.insert_creases(creases, cx))
12843 }
12844
12845 pub fn remove_creases(
12846 &mut self,
12847 ids: impl IntoIterator<Item = CreaseId>,
12848 cx: &mut Context<Self>,
12849 ) {
12850 self.display_map
12851 .update(cx, |map, cx| map.remove_creases(ids, cx));
12852 }
12853
12854 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12855 self.display_map
12856 .update(cx, |map, cx| map.snapshot(cx))
12857 .longest_row()
12858 }
12859
12860 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12861 self.display_map
12862 .update(cx, |map, cx| map.snapshot(cx))
12863 .max_point()
12864 }
12865
12866 pub fn text(&self, cx: &App) -> String {
12867 self.buffer.read(cx).read(cx).text()
12868 }
12869
12870 pub fn is_empty(&self, cx: &App) -> bool {
12871 self.buffer.read(cx).read(cx).is_empty()
12872 }
12873
12874 pub fn text_option(&self, cx: &App) -> Option<String> {
12875 let text = self.text(cx);
12876 let text = text.trim();
12877
12878 if text.is_empty() {
12879 return None;
12880 }
12881
12882 Some(text.to_string())
12883 }
12884
12885 pub fn set_text(
12886 &mut self,
12887 text: impl Into<Arc<str>>,
12888 window: &mut Window,
12889 cx: &mut Context<Self>,
12890 ) {
12891 self.transact(window, cx, |this, _, cx| {
12892 this.buffer
12893 .read(cx)
12894 .as_singleton()
12895 .expect("you can only call set_text on editors for singleton buffers")
12896 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12897 });
12898 }
12899
12900 pub fn display_text(&self, cx: &mut App) -> String {
12901 self.display_map
12902 .update(cx, |map, cx| map.snapshot(cx))
12903 .text()
12904 }
12905
12906 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12907 let mut wrap_guides = smallvec::smallvec![];
12908
12909 if self.show_wrap_guides == Some(false) {
12910 return wrap_guides;
12911 }
12912
12913 let settings = self.buffer.read(cx).settings_at(0, cx);
12914 if settings.show_wrap_guides {
12915 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12916 wrap_guides.push((soft_wrap as usize, true));
12917 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12918 wrap_guides.push((soft_wrap as usize, true));
12919 }
12920 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12921 }
12922
12923 wrap_guides
12924 }
12925
12926 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12927 let settings = self.buffer.read(cx).settings_at(0, cx);
12928 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12929 match mode {
12930 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12931 SoftWrap::None
12932 }
12933 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12934 language_settings::SoftWrap::PreferredLineLength => {
12935 SoftWrap::Column(settings.preferred_line_length)
12936 }
12937 language_settings::SoftWrap::Bounded => {
12938 SoftWrap::Bounded(settings.preferred_line_length)
12939 }
12940 }
12941 }
12942
12943 pub fn set_soft_wrap_mode(
12944 &mut self,
12945 mode: language_settings::SoftWrap,
12946
12947 cx: &mut Context<Self>,
12948 ) {
12949 self.soft_wrap_mode_override = Some(mode);
12950 cx.notify();
12951 }
12952
12953 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12954 self.text_style_refinement = Some(style);
12955 }
12956
12957 /// called by the Element so we know what style we were most recently rendered with.
12958 pub(crate) fn set_style(
12959 &mut self,
12960 style: EditorStyle,
12961 window: &mut Window,
12962 cx: &mut Context<Self>,
12963 ) {
12964 let rem_size = window.rem_size();
12965 self.display_map.update(cx, |map, cx| {
12966 map.set_font(
12967 style.text.font(),
12968 style.text.font_size.to_pixels(rem_size),
12969 cx,
12970 )
12971 });
12972 self.style = Some(style);
12973 }
12974
12975 pub fn style(&self) -> Option<&EditorStyle> {
12976 self.style.as_ref()
12977 }
12978
12979 // Called by the element. This method is not designed to be called outside of the editor
12980 // element's layout code because it does not notify when rewrapping is computed synchronously.
12981 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12982 self.display_map
12983 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12984 }
12985
12986 pub fn set_soft_wrap(&mut self) {
12987 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12988 }
12989
12990 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12991 if self.soft_wrap_mode_override.is_some() {
12992 self.soft_wrap_mode_override.take();
12993 } else {
12994 let soft_wrap = match self.soft_wrap_mode(cx) {
12995 SoftWrap::GitDiff => return,
12996 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12997 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12998 language_settings::SoftWrap::None
12999 }
13000 };
13001 self.soft_wrap_mode_override = Some(soft_wrap);
13002 }
13003 cx.notify();
13004 }
13005
13006 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13007 let Some(workspace) = self.workspace() else {
13008 return;
13009 };
13010 let fs = workspace.read(cx).app_state().fs.clone();
13011 let current_show = TabBarSettings::get_global(cx).show;
13012 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13013 setting.show = Some(!current_show);
13014 });
13015 }
13016
13017 pub fn toggle_indent_guides(
13018 &mut self,
13019 _: &ToggleIndentGuides,
13020 _: &mut Window,
13021 cx: &mut Context<Self>,
13022 ) {
13023 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13024 self.buffer
13025 .read(cx)
13026 .settings_at(0, cx)
13027 .indent_guides
13028 .enabled
13029 });
13030 self.show_indent_guides = Some(!currently_enabled);
13031 cx.notify();
13032 }
13033
13034 fn should_show_indent_guides(&self) -> Option<bool> {
13035 self.show_indent_guides
13036 }
13037
13038 pub fn toggle_line_numbers(
13039 &mut self,
13040 _: &ToggleLineNumbers,
13041 _: &mut Window,
13042 cx: &mut Context<Self>,
13043 ) {
13044 let mut editor_settings = EditorSettings::get_global(cx).clone();
13045 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13046 EditorSettings::override_global(editor_settings, cx);
13047 }
13048
13049 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13050 self.use_relative_line_numbers
13051 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13052 }
13053
13054 pub fn toggle_relative_line_numbers(
13055 &mut self,
13056 _: &ToggleRelativeLineNumbers,
13057 _: &mut Window,
13058 cx: &mut Context<Self>,
13059 ) {
13060 let is_relative = self.should_use_relative_line_numbers(cx);
13061 self.set_relative_line_number(Some(!is_relative), cx)
13062 }
13063
13064 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13065 self.use_relative_line_numbers = is_relative;
13066 cx.notify();
13067 }
13068
13069 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13070 self.show_gutter = show_gutter;
13071 cx.notify();
13072 }
13073
13074 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13075 self.show_scrollbars = show_scrollbars;
13076 cx.notify();
13077 }
13078
13079 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13080 self.show_line_numbers = Some(show_line_numbers);
13081 cx.notify();
13082 }
13083
13084 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13085 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13086 cx.notify();
13087 }
13088
13089 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13090 self.show_code_actions = Some(show_code_actions);
13091 cx.notify();
13092 }
13093
13094 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13095 self.show_runnables = Some(show_runnables);
13096 cx.notify();
13097 }
13098
13099 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13100 if self.display_map.read(cx).masked != masked {
13101 self.display_map.update(cx, |map, _| map.masked = masked);
13102 }
13103 cx.notify()
13104 }
13105
13106 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13107 self.show_wrap_guides = Some(show_wrap_guides);
13108 cx.notify();
13109 }
13110
13111 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13112 self.show_indent_guides = Some(show_indent_guides);
13113 cx.notify();
13114 }
13115
13116 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13117 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13118 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13119 if let Some(dir) = file.abs_path(cx).parent() {
13120 return Some(dir.to_owned());
13121 }
13122 }
13123
13124 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13125 return Some(project_path.path.to_path_buf());
13126 }
13127 }
13128
13129 None
13130 }
13131
13132 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13133 self.active_excerpt(cx)?
13134 .1
13135 .read(cx)
13136 .file()
13137 .and_then(|f| f.as_local())
13138 }
13139
13140 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13141 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13142 let buffer = buffer.read(cx);
13143 if let Some(project_path) = buffer.project_path(cx) {
13144 let project = self.project.as_ref()?.read(cx);
13145 project.absolute_path(&project_path, cx)
13146 } else {
13147 buffer
13148 .file()
13149 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13150 }
13151 })
13152 }
13153
13154 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13155 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13156 let project_path = buffer.read(cx).project_path(cx)?;
13157 let project = self.project.as_ref()?.read(cx);
13158 let entry = project.entry_for_path(&project_path, cx)?;
13159 let path = entry.path.to_path_buf();
13160 Some(path)
13161 })
13162 }
13163
13164 pub fn reveal_in_finder(
13165 &mut self,
13166 _: &RevealInFileManager,
13167 _window: &mut Window,
13168 cx: &mut Context<Self>,
13169 ) {
13170 if let Some(target) = self.target_file(cx) {
13171 cx.reveal_path(&target.abs_path(cx));
13172 }
13173 }
13174
13175 pub fn copy_path(
13176 &mut self,
13177 _: &zed_actions::workspace::CopyPath,
13178 _window: &mut Window,
13179 cx: &mut Context<Self>,
13180 ) {
13181 if let Some(path) = self.target_file_abs_path(cx) {
13182 if let Some(path) = path.to_str() {
13183 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13184 }
13185 }
13186 }
13187
13188 pub fn copy_relative_path(
13189 &mut self,
13190 _: &zed_actions::workspace::CopyRelativePath,
13191 _window: &mut Window,
13192 cx: &mut Context<Self>,
13193 ) {
13194 if let Some(path) = self.target_file_path(cx) {
13195 if let Some(path) = path.to_str() {
13196 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13197 }
13198 }
13199 }
13200
13201 pub fn copy_file_name_without_extension(
13202 &mut self,
13203 _: &CopyFileNameWithoutExtension,
13204 _: &mut Window,
13205 cx: &mut Context<Self>,
13206 ) {
13207 if let Some(file) = self.target_file(cx) {
13208 if let Some(file_stem) = file.path().file_stem() {
13209 if let Some(name) = file_stem.to_str() {
13210 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13211 }
13212 }
13213 }
13214 }
13215
13216 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13217 if let Some(file) = self.target_file(cx) {
13218 if let Some(file_name) = file.path().file_name() {
13219 if let Some(name) = file_name.to_str() {
13220 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13221 }
13222 }
13223 }
13224 }
13225
13226 pub fn toggle_git_blame(
13227 &mut self,
13228 _: &ToggleGitBlame,
13229 window: &mut Window,
13230 cx: &mut Context<Self>,
13231 ) {
13232 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13233
13234 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13235 self.start_git_blame(true, window, cx);
13236 }
13237
13238 cx.notify();
13239 }
13240
13241 pub fn toggle_git_blame_inline(
13242 &mut self,
13243 _: &ToggleGitBlameInline,
13244 window: &mut Window,
13245 cx: &mut Context<Self>,
13246 ) {
13247 self.toggle_git_blame_inline_internal(true, window, cx);
13248 cx.notify();
13249 }
13250
13251 pub fn git_blame_inline_enabled(&self) -> bool {
13252 self.git_blame_inline_enabled
13253 }
13254
13255 pub fn toggle_selection_menu(
13256 &mut self,
13257 _: &ToggleSelectionMenu,
13258 _: &mut Window,
13259 cx: &mut Context<Self>,
13260 ) {
13261 self.show_selection_menu = self
13262 .show_selection_menu
13263 .map(|show_selections_menu| !show_selections_menu)
13264 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13265
13266 cx.notify();
13267 }
13268
13269 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13270 self.show_selection_menu
13271 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13272 }
13273
13274 fn start_git_blame(
13275 &mut self,
13276 user_triggered: bool,
13277 window: &mut Window,
13278 cx: &mut Context<Self>,
13279 ) {
13280 if let Some(project) = self.project.as_ref() {
13281 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13282 return;
13283 };
13284
13285 if buffer.read(cx).file().is_none() {
13286 return;
13287 }
13288
13289 let focused = self.focus_handle(cx).contains_focused(window, cx);
13290
13291 let project = project.clone();
13292 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13293 self.blame_subscription =
13294 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13295 self.blame = Some(blame);
13296 }
13297 }
13298
13299 fn toggle_git_blame_inline_internal(
13300 &mut self,
13301 user_triggered: bool,
13302 window: &mut Window,
13303 cx: &mut Context<Self>,
13304 ) {
13305 if self.git_blame_inline_enabled {
13306 self.git_blame_inline_enabled = false;
13307 self.show_git_blame_inline = false;
13308 self.show_git_blame_inline_delay_task.take();
13309 } else {
13310 self.git_blame_inline_enabled = true;
13311 self.start_git_blame_inline(user_triggered, window, cx);
13312 }
13313
13314 cx.notify();
13315 }
13316
13317 fn start_git_blame_inline(
13318 &mut self,
13319 user_triggered: bool,
13320 window: &mut Window,
13321 cx: &mut Context<Self>,
13322 ) {
13323 self.start_git_blame(user_triggered, window, cx);
13324
13325 if ProjectSettings::get_global(cx)
13326 .git
13327 .inline_blame_delay()
13328 .is_some()
13329 {
13330 self.start_inline_blame_timer(window, cx);
13331 } else {
13332 self.show_git_blame_inline = true
13333 }
13334 }
13335
13336 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13337 self.blame.as_ref()
13338 }
13339
13340 pub fn show_git_blame_gutter(&self) -> bool {
13341 self.show_git_blame_gutter
13342 }
13343
13344 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13345 self.show_git_blame_gutter && self.has_blame_entries(cx)
13346 }
13347
13348 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13349 self.show_git_blame_inline
13350 && (self.focus_handle.is_focused(window)
13351 || self
13352 .git_blame_inline_tooltip
13353 .as_ref()
13354 .and_then(|t| t.upgrade())
13355 .is_some())
13356 && !self.newest_selection_head_on_empty_line(cx)
13357 && self.has_blame_entries(cx)
13358 }
13359
13360 fn has_blame_entries(&self, cx: &App) -> bool {
13361 self.blame()
13362 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13363 }
13364
13365 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13366 let cursor_anchor = self.selections.newest_anchor().head();
13367
13368 let snapshot = self.buffer.read(cx).snapshot(cx);
13369 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13370
13371 snapshot.line_len(buffer_row) == 0
13372 }
13373
13374 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13375 let buffer_and_selection = maybe!({
13376 let selection = self.selections.newest::<Point>(cx);
13377 let selection_range = selection.range();
13378
13379 let multi_buffer = self.buffer().read(cx);
13380 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13381 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13382
13383 let (buffer, range, _) = if selection.reversed {
13384 buffer_ranges.first()
13385 } else {
13386 buffer_ranges.last()
13387 }?;
13388
13389 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13390 ..text::ToPoint::to_point(&range.end, &buffer).row;
13391 Some((
13392 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13393 selection,
13394 ))
13395 });
13396
13397 let Some((buffer, selection)) = buffer_and_selection else {
13398 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13399 };
13400
13401 let Some(project) = self.project.as_ref() else {
13402 return Task::ready(Err(anyhow!("editor does not have project")));
13403 };
13404
13405 project.update(cx, |project, cx| {
13406 project.get_permalink_to_line(&buffer, selection, cx)
13407 })
13408 }
13409
13410 pub fn copy_permalink_to_line(
13411 &mut self,
13412 _: &CopyPermalinkToLine,
13413 window: &mut Window,
13414 cx: &mut Context<Self>,
13415 ) {
13416 let permalink_task = self.get_permalink_to_line(cx);
13417 let workspace = self.workspace();
13418
13419 cx.spawn_in(window, |_, mut cx| async move {
13420 match permalink_task.await {
13421 Ok(permalink) => {
13422 cx.update(|_, cx| {
13423 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13424 })
13425 .ok();
13426 }
13427 Err(err) => {
13428 let message = format!("Failed to copy permalink: {err}");
13429
13430 Err::<(), anyhow::Error>(err).log_err();
13431
13432 if let Some(workspace) = workspace {
13433 workspace
13434 .update_in(&mut cx, |workspace, _, cx| {
13435 struct CopyPermalinkToLine;
13436
13437 workspace.show_toast(
13438 Toast::new(
13439 NotificationId::unique::<CopyPermalinkToLine>(),
13440 message,
13441 ),
13442 cx,
13443 )
13444 })
13445 .ok();
13446 }
13447 }
13448 }
13449 })
13450 .detach();
13451 }
13452
13453 pub fn copy_file_location(
13454 &mut self,
13455 _: &CopyFileLocation,
13456 _: &mut Window,
13457 cx: &mut Context<Self>,
13458 ) {
13459 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13460 if let Some(file) = self.target_file(cx) {
13461 if let Some(path) = file.path().to_str() {
13462 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13463 }
13464 }
13465 }
13466
13467 pub fn open_permalink_to_line(
13468 &mut self,
13469 _: &OpenPermalinkToLine,
13470 window: &mut Window,
13471 cx: &mut Context<Self>,
13472 ) {
13473 let permalink_task = self.get_permalink_to_line(cx);
13474 let workspace = self.workspace();
13475
13476 cx.spawn_in(window, |_, mut cx| async move {
13477 match permalink_task.await {
13478 Ok(permalink) => {
13479 cx.update(|_, cx| {
13480 cx.open_url(permalink.as_ref());
13481 })
13482 .ok();
13483 }
13484 Err(err) => {
13485 let message = format!("Failed to open permalink: {err}");
13486
13487 Err::<(), anyhow::Error>(err).log_err();
13488
13489 if let Some(workspace) = workspace {
13490 workspace
13491 .update(&mut cx, |workspace, cx| {
13492 struct OpenPermalinkToLine;
13493
13494 workspace.show_toast(
13495 Toast::new(
13496 NotificationId::unique::<OpenPermalinkToLine>(),
13497 message,
13498 ),
13499 cx,
13500 )
13501 })
13502 .ok();
13503 }
13504 }
13505 }
13506 })
13507 .detach();
13508 }
13509
13510 pub fn insert_uuid_v4(
13511 &mut self,
13512 _: &InsertUuidV4,
13513 window: &mut Window,
13514 cx: &mut Context<Self>,
13515 ) {
13516 self.insert_uuid(UuidVersion::V4, window, cx);
13517 }
13518
13519 pub fn insert_uuid_v7(
13520 &mut self,
13521 _: &InsertUuidV7,
13522 window: &mut Window,
13523 cx: &mut Context<Self>,
13524 ) {
13525 self.insert_uuid(UuidVersion::V7, window, cx);
13526 }
13527
13528 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13529 self.transact(window, cx, |this, window, cx| {
13530 let edits = this
13531 .selections
13532 .all::<Point>(cx)
13533 .into_iter()
13534 .map(|selection| {
13535 let uuid = match version {
13536 UuidVersion::V4 => uuid::Uuid::new_v4(),
13537 UuidVersion::V7 => uuid::Uuid::now_v7(),
13538 };
13539
13540 (selection.range(), uuid.to_string())
13541 });
13542 this.edit(edits, cx);
13543 this.refresh_inline_completion(true, false, window, cx);
13544 });
13545 }
13546
13547 pub fn open_selections_in_multibuffer(
13548 &mut self,
13549 _: &OpenSelectionsInMultibuffer,
13550 window: &mut Window,
13551 cx: &mut Context<Self>,
13552 ) {
13553 let multibuffer = self.buffer.read(cx);
13554
13555 let Some(buffer) = multibuffer.as_singleton() else {
13556 return;
13557 };
13558
13559 let Some(workspace) = self.workspace() else {
13560 return;
13561 };
13562
13563 let locations = self
13564 .selections
13565 .disjoint_anchors()
13566 .iter()
13567 .map(|range| Location {
13568 buffer: buffer.clone(),
13569 range: range.start.text_anchor..range.end.text_anchor,
13570 })
13571 .collect::<Vec<_>>();
13572
13573 let title = multibuffer.title(cx).to_string();
13574
13575 cx.spawn_in(window, |_, mut cx| async move {
13576 workspace.update_in(&mut cx, |workspace, window, cx| {
13577 Self::open_locations_in_multibuffer(
13578 workspace,
13579 locations,
13580 format!("Selections for '{title}'"),
13581 false,
13582 MultibufferSelectionMode::All,
13583 window,
13584 cx,
13585 );
13586 })
13587 })
13588 .detach();
13589 }
13590
13591 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13592 /// last highlight added will be used.
13593 ///
13594 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13595 pub fn highlight_rows<T: 'static>(
13596 &mut self,
13597 range: Range<Anchor>,
13598 color: Hsla,
13599 should_autoscroll: bool,
13600 cx: &mut Context<Self>,
13601 ) {
13602 let snapshot = self.buffer().read(cx).snapshot(cx);
13603 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13604 let ix = row_highlights.binary_search_by(|highlight| {
13605 Ordering::Equal
13606 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13607 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13608 });
13609
13610 if let Err(mut ix) = ix {
13611 let index = post_inc(&mut self.highlight_order);
13612
13613 // If this range intersects with the preceding highlight, then merge it with
13614 // the preceding highlight. Otherwise insert a new highlight.
13615 let mut merged = false;
13616 if ix > 0 {
13617 let prev_highlight = &mut row_highlights[ix - 1];
13618 if prev_highlight
13619 .range
13620 .end
13621 .cmp(&range.start, &snapshot)
13622 .is_ge()
13623 {
13624 ix -= 1;
13625 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13626 prev_highlight.range.end = range.end;
13627 }
13628 merged = true;
13629 prev_highlight.index = index;
13630 prev_highlight.color = color;
13631 prev_highlight.should_autoscroll = should_autoscroll;
13632 }
13633 }
13634
13635 if !merged {
13636 row_highlights.insert(
13637 ix,
13638 RowHighlight {
13639 range: range.clone(),
13640 index,
13641 color,
13642 should_autoscroll,
13643 },
13644 );
13645 }
13646
13647 // If any of the following highlights intersect with this one, merge them.
13648 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13649 let highlight = &row_highlights[ix];
13650 if next_highlight
13651 .range
13652 .start
13653 .cmp(&highlight.range.end, &snapshot)
13654 .is_le()
13655 {
13656 if next_highlight
13657 .range
13658 .end
13659 .cmp(&highlight.range.end, &snapshot)
13660 .is_gt()
13661 {
13662 row_highlights[ix].range.end = next_highlight.range.end;
13663 }
13664 row_highlights.remove(ix + 1);
13665 } else {
13666 break;
13667 }
13668 }
13669 }
13670 }
13671
13672 /// Remove any highlighted row ranges of the given type that intersect the
13673 /// given ranges.
13674 pub fn remove_highlighted_rows<T: 'static>(
13675 &mut self,
13676 ranges_to_remove: Vec<Range<Anchor>>,
13677 cx: &mut Context<Self>,
13678 ) {
13679 let snapshot = self.buffer().read(cx).snapshot(cx);
13680 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13681 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13682 row_highlights.retain(|highlight| {
13683 while let Some(range_to_remove) = ranges_to_remove.peek() {
13684 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13685 Ordering::Less | Ordering::Equal => {
13686 ranges_to_remove.next();
13687 }
13688 Ordering::Greater => {
13689 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13690 Ordering::Less | Ordering::Equal => {
13691 return false;
13692 }
13693 Ordering::Greater => break,
13694 }
13695 }
13696 }
13697 }
13698
13699 true
13700 })
13701 }
13702
13703 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13704 pub fn clear_row_highlights<T: 'static>(&mut self) {
13705 self.highlighted_rows.remove(&TypeId::of::<T>());
13706 }
13707
13708 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13709 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13710 self.highlighted_rows
13711 .get(&TypeId::of::<T>())
13712 .map_or(&[] as &[_], |vec| vec.as_slice())
13713 .iter()
13714 .map(|highlight| (highlight.range.clone(), highlight.color))
13715 }
13716
13717 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13718 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13719 /// Allows to ignore certain kinds of highlights.
13720 pub fn highlighted_display_rows(
13721 &self,
13722 window: &mut Window,
13723 cx: &mut App,
13724 ) -> BTreeMap<DisplayRow, Background> {
13725 let snapshot = self.snapshot(window, cx);
13726 let mut used_highlight_orders = HashMap::default();
13727 self.highlighted_rows
13728 .iter()
13729 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13730 .fold(
13731 BTreeMap::<DisplayRow, Background>::new(),
13732 |mut unique_rows, highlight| {
13733 let start = highlight.range.start.to_display_point(&snapshot);
13734 let end = highlight.range.end.to_display_point(&snapshot);
13735 let start_row = start.row().0;
13736 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13737 && end.column() == 0
13738 {
13739 end.row().0.saturating_sub(1)
13740 } else {
13741 end.row().0
13742 };
13743 for row in start_row..=end_row {
13744 let used_index =
13745 used_highlight_orders.entry(row).or_insert(highlight.index);
13746 if highlight.index >= *used_index {
13747 *used_index = highlight.index;
13748 unique_rows.insert(DisplayRow(row), highlight.color.into());
13749 }
13750 }
13751 unique_rows
13752 },
13753 )
13754 }
13755
13756 pub fn highlighted_display_row_for_autoscroll(
13757 &self,
13758 snapshot: &DisplaySnapshot,
13759 ) -> Option<DisplayRow> {
13760 self.highlighted_rows
13761 .values()
13762 .flat_map(|highlighted_rows| highlighted_rows.iter())
13763 .filter_map(|highlight| {
13764 if highlight.should_autoscroll {
13765 Some(highlight.range.start.to_display_point(snapshot).row())
13766 } else {
13767 None
13768 }
13769 })
13770 .min()
13771 }
13772
13773 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13774 self.highlight_background::<SearchWithinRange>(
13775 ranges,
13776 |colors| colors.editor_document_highlight_read_background,
13777 cx,
13778 )
13779 }
13780
13781 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13782 self.breadcrumb_header = Some(new_header);
13783 }
13784
13785 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13786 self.clear_background_highlights::<SearchWithinRange>(cx);
13787 }
13788
13789 pub fn highlight_background<T: 'static>(
13790 &mut self,
13791 ranges: &[Range<Anchor>],
13792 color_fetcher: fn(&ThemeColors) -> Hsla,
13793 cx: &mut Context<Self>,
13794 ) {
13795 self.background_highlights
13796 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13797 self.scrollbar_marker_state.dirty = true;
13798 cx.notify();
13799 }
13800
13801 pub fn clear_background_highlights<T: 'static>(
13802 &mut self,
13803 cx: &mut Context<Self>,
13804 ) -> Option<BackgroundHighlight> {
13805 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13806 if !text_highlights.1.is_empty() {
13807 self.scrollbar_marker_state.dirty = true;
13808 cx.notify();
13809 }
13810 Some(text_highlights)
13811 }
13812
13813 pub fn highlight_gutter<T: 'static>(
13814 &mut self,
13815 ranges: &[Range<Anchor>],
13816 color_fetcher: fn(&App) -> Hsla,
13817 cx: &mut Context<Self>,
13818 ) {
13819 self.gutter_highlights
13820 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13821 cx.notify();
13822 }
13823
13824 pub fn clear_gutter_highlights<T: 'static>(
13825 &mut self,
13826 cx: &mut Context<Self>,
13827 ) -> Option<GutterHighlight> {
13828 cx.notify();
13829 self.gutter_highlights.remove(&TypeId::of::<T>())
13830 }
13831
13832 #[cfg(feature = "test-support")]
13833 pub fn all_text_background_highlights(
13834 &self,
13835 window: &mut Window,
13836 cx: &mut Context<Self>,
13837 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13838 let snapshot = self.snapshot(window, cx);
13839 let buffer = &snapshot.buffer_snapshot;
13840 let start = buffer.anchor_before(0);
13841 let end = buffer.anchor_after(buffer.len());
13842 let theme = cx.theme().colors();
13843 self.background_highlights_in_range(start..end, &snapshot, theme)
13844 }
13845
13846 #[cfg(feature = "test-support")]
13847 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13848 let snapshot = self.buffer().read(cx).snapshot(cx);
13849
13850 let highlights = self
13851 .background_highlights
13852 .get(&TypeId::of::<items::BufferSearchHighlights>());
13853
13854 if let Some((_color, ranges)) = highlights {
13855 ranges
13856 .iter()
13857 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13858 .collect_vec()
13859 } else {
13860 vec![]
13861 }
13862 }
13863
13864 fn document_highlights_for_position<'a>(
13865 &'a self,
13866 position: Anchor,
13867 buffer: &'a MultiBufferSnapshot,
13868 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13869 let read_highlights = self
13870 .background_highlights
13871 .get(&TypeId::of::<DocumentHighlightRead>())
13872 .map(|h| &h.1);
13873 let write_highlights = self
13874 .background_highlights
13875 .get(&TypeId::of::<DocumentHighlightWrite>())
13876 .map(|h| &h.1);
13877 let left_position = position.bias_left(buffer);
13878 let right_position = position.bias_right(buffer);
13879 read_highlights
13880 .into_iter()
13881 .chain(write_highlights)
13882 .flat_map(move |ranges| {
13883 let start_ix = match ranges.binary_search_by(|probe| {
13884 let cmp = probe.end.cmp(&left_position, buffer);
13885 if cmp.is_ge() {
13886 Ordering::Greater
13887 } else {
13888 Ordering::Less
13889 }
13890 }) {
13891 Ok(i) | Err(i) => i,
13892 };
13893
13894 ranges[start_ix..]
13895 .iter()
13896 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13897 })
13898 }
13899
13900 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13901 self.background_highlights
13902 .get(&TypeId::of::<T>())
13903 .map_or(false, |(_, highlights)| !highlights.is_empty())
13904 }
13905
13906 pub fn background_highlights_in_range(
13907 &self,
13908 search_range: Range<Anchor>,
13909 display_snapshot: &DisplaySnapshot,
13910 theme: &ThemeColors,
13911 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13912 let mut results = Vec::new();
13913 for (color_fetcher, ranges) in self.background_highlights.values() {
13914 let color = color_fetcher(theme);
13915 let start_ix = match ranges.binary_search_by(|probe| {
13916 let cmp = probe
13917 .end
13918 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13919 if cmp.is_gt() {
13920 Ordering::Greater
13921 } else {
13922 Ordering::Less
13923 }
13924 }) {
13925 Ok(i) | Err(i) => i,
13926 };
13927 for range in &ranges[start_ix..] {
13928 if range
13929 .start
13930 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13931 .is_ge()
13932 {
13933 break;
13934 }
13935
13936 let start = range.start.to_display_point(display_snapshot);
13937 let end = range.end.to_display_point(display_snapshot);
13938 results.push((start..end, color))
13939 }
13940 }
13941 results
13942 }
13943
13944 pub fn background_highlight_row_ranges<T: 'static>(
13945 &self,
13946 search_range: Range<Anchor>,
13947 display_snapshot: &DisplaySnapshot,
13948 count: usize,
13949 ) -> Vec<RangeInclusive<DisplayPoint>> {
13950 let mut results = Vec::new();
13951 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13952 return vec![];
13953 };
13954
13955 let start_ix = match ranges.binary_search_by(|probe| {
13956 let cmp = probe
13957 .end
13958 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13959 if cmp.is_gt() {
13960 Ordering::Greater
13961 } else {
13962 Ordering::Less
13963 }
13964 }) {
13965 Ok(i) | Err(i) => i,
13966 };
13967 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13968 if let (Some(start_display), Some(end_display)) = (start, end) {
13969 results.push(
13970 start_display.to_display_point(display_snapshot)
13971 ..=end_display.to_display_point(display_snapshot),
13972 );
13973 }
13974 };
13975 let mut start_row: Option<Point> = None;
13976 let mut end_row: Option<Point> = None;
13977 if ranges.len() > count {
13978 return Vec::new();
13979 }
13980 for range in &ranges[start_ix..] {
13981 if range
13982 .start
13983 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13984 .is_ge()
13985 {
13986 break;
13987 }
13988 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13989 if let Some(current_row) = &end_row {
13990 if end.row == current_row.row {
13991 continue;
13992 }
13993 }
13994 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13995 if start_row.is_none() {
13996 assert_eq!(end_row, None);
13997 start_row = Some(start);
13998 end_row = Some(end);
13999 continue;
14000 }
14001 if let Some(current_end) = end_row.as_mut() {
14002 if start.row > current_end.row + 1 {
14003 push_region(start_row, end_row);
14004 start_row = Some(start);
14005 end_row = Some(end);
14006 } else {
14007 // Merge two hunks.
14008 *current_end = end;
14009 }
14010 } else {
14011 unreachable!();
14012 }
14013 }
14014 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14015 push_region(start_row, end_row);
14016 results
14017 }
14018
14019 pub fn gutter_highlights_in_range(
14020 &self,
14021 search_range: Range<Anchor>,
14022 display_snapshot: &DisplaySnapshot,
14023 cx: &App,
14024 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14025 let mut results = Vec::new();
14026 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14027 let color = color_fetcher(cx);
14028 let start_ix = match ranges.binary_search_by(|probe| {
14029 let cmp = probe
14030 .end
14031 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14032 if cmp.is_gt() {
14033 Ordering::Greater
14034 } else {
14035 Ordering::Less
14036 }
14037 }) {
14038 Ok(i) | Err(i) => i,
14039 };
14040 for range in &ranges[start_ix..] {
14041 if range
14042 .start
14043 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14044 .is_ge()
14045 {
14046 break;
14047 }
14048
14049 let start = range.start.to_display_point(display_snapshot);
14050 let end = range.end.to_display_point(display_snapshot);
14051 results.push((start..end, color))
14052 }
14053 }
14054 results
14055 }
14056
14057 /// Get the text ranges corresponding to the redaction query
14058 pub fn redacted_ranges(
14059 &self,
14060 search_range: Range<Anchor>,
14061 display_snapshot: &DisplaySnapshot,
14062 cx: &App,
14063 ) -> Vec<Range<DisplayPoint>> {
14064 display_snapshot
14065 .buffer_snapshot
14066 .redacted_ranges(search_range, |file| {
14067 if let Some(file) = file {
14068 file.is_private()
14069 && EditorSettings::get(
14070 Some(SettingsLocation {
14071 worktree_id: file.worktree_id(cx),
14072 path: file.path().as_ref(),
14073 }),
14074 cx,
14075 )
14076 .redact_private_values
14077 } else {
14078 false
14079 }
14080 })
14081 .map(|range| {
14082 range.start.to_display_point(display_snapshot)
14083 ..range.end.to_display_point(display_snapshot)
14084 })
14085 .collect()
14086 }
14087
14088 pub fn highlight_text<T: 'static>(
14089 &mut self,
14090 ranges: Vec<Range<Anchor>>,
14091 style: HighlightStyle,
14092 cx: &mut Context<Self>,
14093 ) {
14094 self.display_map.update(cx, |map, _| {
14095 map.highlight_text(TypeId::of::<T>(), ranges, style)
14096 });
14097 cx.notify();
14098 }
14099
14100 pub(crate) fn highlight_inlays<T: 'static>(
14101 &mut self,
14102 highlights: Vec<InlayHighlight>,
14103 style: HighlightStyle,
14104 cx: &mut Context<Self>,
14105 ) {
14106 self.display_map.update(cx, |map, _| {
14107 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14108 });
14109 cx.notify();
14110 }
14111
14112 pub fn text_highlights<'a, T: 'static>(
14113 &'a self,
14114 cx: &'a App,
14115 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14116 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14117 }
14118
14119 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14120 let cleared = self
14121 .display_map
14122 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14123 if cleared {
14124 cx.notify();
14125 }
14126 }
14127
14128 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14129 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14130 && self.focus_handle.is_focused(window)
14131 }
14132
14133 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14134 self.show_cursor_when_unfocused = is_enabled;
14135 cx.notify();
14136 }
14137
14138 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14139 cx.notify();
14140 }
14141
14142 fn on_buffer_event(
14143 &mut self,
14144 multibuffer: &Entity<MultiBuffer>,
14145 event: &multi_buffer::Event,
14146 window: &mut Window,
14147 cx: &mut Context<Self>,
14148 ) {
14149 match event {
14150 multi_buffer::Event::Edited {
14151 singleton_buffer_edited,
14152 edited_buffer: buffer_edited,
14153 } => {
14154 self.scrollbar_marker_state.dirty = true;
14155 self.active_indent_guides_state.dirty = true;
14156 self.refresh_active_diagnostics(cx);
14157 self.refresh_code_actions(window, cx);
14158 if self.has_active_inline_completion() {
14159 self.update_visible_inline_completion(window, cx);
14160 }
14161 if let Some(buffer) = buffer_edited {
14162 let buffer_id = buffer.read(cx).remote_id();
14163 if !self.registered_buffers.contains_key(&buffer_id) {
14164 if let Some(project) = self.project.as_ref() {
14165 project.update(cx, |project, cx| {
14166 self.registered_buffers.insert(
14167 buffer_id,
14168 project.register_buffer_with_language_servers(&buffer, cx),
14169 );
14170 })
14171 }
14172 }
14173 }
14174 cx.emit(EditorEvent::BufferEdited);
14175 cx.emit(SearchEvent::MatchesInvalidated);
14176 if *singleton_buffer_edited {
14177 if let Some(project) = &self.project {
14178 #[allow(clippy::mutable_key_type)]
14179 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14180 multibuffer
14181 .all_buffers()
14182 .into_iter()
14183 .filter_map(|buffer| {
14184 buffer.update(cx, |buffer, cx| {
14185 let language = buffer.language()?;
14186 let should_discard = project.update(cx, |project, cx| {
14187 project.is_local()
14188 && !project.has_language_servers_for(buffer, cx)
14189 });
14190 should_discard.not().then_some(language.clone())
14191 })
14192 })
14193 .collect::<HashSet<_>>()
14194 });
14195 if !languages_affected.is_empty() {
14196 self.refresh_inlay_hints(
14197 InlayHintRefreshReason::BufferEdited(languages_affected),
14198 cx,
14199 );
14200 }
14201 }
14202 }
14203
14204 let Some(project) = &self.project else { return };
14205 let (telemetry, is_via_ssh) = {
14206 let project = project.read(cx);
14207 let telemetry = project.client().telemetry().clone();
14208 let is_via_ssh = project.is_via_ssh();
14209 (telemetry, is_via_ssh)
14210 };
14211 refresh_linked_ranges(self, window, cx);
14212 telemetry.log_edit_event("editor", is_via_ssh);
14213 }
14214 multi_buffer::Event::ExcerptsAdded {
14215 buffer,
14216 predecessor,
14217 excerpts,
14218 } => {
14219 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14220 let buffer_id = buffer.read(cx).remote_id();
14221 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14222 if let Some(project) = &self.project {
14223 get_uncommitted_diff_for_buffer(
14224 project,
14225 [buffer.clone()],
14226 self.buffer.clone(),
14227 cx,
14228 )
14229 .detach();
14230 }
14231 }
14232 cx.emit(EditorEvent::ExcerptsAdded {
14233 buffer: buffer.clone(),
14234 predecessor: *predecessor,
14235 excerpts: excerpts.clone(),
14236 });
14237 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14238 }
14239 multi_buffer::Event::ExcerptsRemoved { ids } => {
14240 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14241 let buffer = self.buffer.read(cx);
14242 self.registered_buffers
14243 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14244 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14245 }
14246 multi_buffer::Event::ExcerptsEdited { ids } => {
14247 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14248 }
14249 multi_buffer::Event::ExcerptsExpanded { ids } => {
14250 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14251 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14252 }
14253 multi_buffer::Event::Reparsed(buffer_id) => {
14254 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14255
14256 cx.emit(EditorEvent::Reparsed(*buffer_id));
14257 }
14258 multi_buffer::Event::DiffHunksToggled => {
14259 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14260 }
14261 multi_buffer::Event::LanguageChanged(buffer_id) => {
14262 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14263 cx.emit(EditorEvent::Reparsed(*buffer_id));
14264 cx.notify();
14265 }
14266 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14267 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14268 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14269 cx.emit(EditorEvent::TitleChanged)
14270 }
14271 // multi_buffer::Event::DiffBaseChanged => {
14272 // self.scrollbar_marker_state.dirty = true;
14273 // cx.emit(EditorEvent::DiffBaseChanged);
14274 // cx.notify();
14275 // }
14276 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14277 multi_buffer::Event::DiagnosticsUpdated => {
14278 self.refresh_active_diagnostics(cx);
14279 self.scrollbar_marker_state.dirty = true;
14280 cx.notify();
14281 }
14282 _ => {}
14283 };
14284 }
14285
14286 fn on_display_map_changed(
14287 &mut self,
14288 _: Entity<DisplayMap>,
14289 _: &mut Window,
14290 cx: &mut Context<Self>,
14291 ) {
14292 cx.notify();
14293 }
14294
14295 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14296 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14297 self.refresh_inline_completion(true, false, window, cx);
14298 self.refresh_inlay_hints(
14299 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14300 self.selections.newest_anchor().head(),
14301 &self.buffer.read(cx).snapshot(cx),
14302 cx,
14303 )),
14304 cx,
14305 );
14306
14307 let old_cursor_shape = self.cursor_shape;
14308
14309 {
14310 let editor_settings = EditorSettings::get_global(cx);
14311 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14312 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14313 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14314 }
14315
14316 if old_cursor_shape != self.cursor_shape {
14317 cx.emit(EditorEvent::CursorShapeChanged);
14318 }
14319
14320 let project_settings = ProjectSettings::get_global(cx);
14321 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14322
14323 if self.mode == EditorMode::Full {
14324 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14325 if self.git_blame_inline_enabled != inline_blame_enabled {
14326 self.toggle_git_blame_inline_internal(false, window, cx);
14327 }
14328 }
14329
14330 cx.notify();
14331 }
14332
14333 pub fn set_searchable(&mut self, searchable: bool) {
14334 self.searchable = searchable;
14335 }
14336
14337 pub fn searchable(&self) -> bool {
14338 self.searchable
14339 }
14340
14341 fn open_proposed_changes_editor(
14342 &mut self,
14343 _: &OpenProposedChangesEditor,
14344 window: &mut Window,
14345 cx: &mut Context<Self>,
14346 ) {
14347 let Some(workspace) = self.workspace() else {
14348 cx.propagate();
14349 return;
14350 };
14351
14352 let selections = self.selections.all::<usize>(cx);
14353 let multi_buffer = self.buffer.read(cx);
14354 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14355 let mut new_selections_by_buffer = HashMap::default();
14356 for selection in selections {
14357 for (buffer, range, _) in
14358 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14359 {
14360 let mut range = range.to_point(buffer);
14361 range.start.column = 0;
14362 range.end.column = buffer.line_len(range.end.row);
14363 new_selections_by_buffer
14364 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14365 .or_insert(Vec::new())
14366 .push(range)
14367 }
14368 }
14369
14370 let proposed_changes_buffers = new_selections_by_buffer
14371 .into_iter()
14372 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14373 .collect::<Vec<_>>();
14374 let proposed_changes_editor = cx.new(|cx| {
14375 ProposedChangesEditor::new(
14376 "Proposed changes",
14377 proposed_changes_buffers,
14378 self.project.clone(),
14379 window,
14380 cx,
14381 )
14382 });
14383
14384 window.defer(cx, move |window, cx| {
14385 workspace.update(cx, |workspace, cx| {
14386 workspace.active_pane().update(cx, |pane, cx| {
14387 pane.add_item(
14388 Box::new(proposed_changes_editor),
14389 true,
14390 true,
14391 None,
14392 window,
14393 cx,
14394 );
14395 });
14396 });
14397 });
14398 }
14399
14400 pub fn open_excerpts_in_split(
14401 &mut self,
14402 _: &OpenExcerptsSplit,
14403 window: &mut Window,
14404 cx: &mut Context<Self>,
14405 ) {
14406 self.open_excerpts_common(None, true, window, cx)
14407 }
14408
14409 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14410 self.open_excerpts_common(None, false, window, cx)
14411 }
14412
14413 fn open_excerpts_common(
14414 &mut self,
14415 jump_data: Option<JumpData>,
14416 split: bool,
14417 window: &mut Window,
14418 cx: &mut Context<Self>,
14419 ) {
14420 let Some(workspace) = self.workspace() else {
14421 cx.propagate();
14422 return;
14423 };
14424
14425 if self.buffer.read(cx).is_singleton() {
14426 cx.propagate();
14427 return;
14428 }
14429
14430 let mut new_selections_by_buffer = HashMap::default();
14431 match &jump_data {
14432 Some(JumpData::MultiBufferPoint {
14433 excerpt_id,
14434 position,
14435 anchor,
14436 line_offset_from_top,
14437 }) => {
14438 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14439 if let Some(buffer) = multi_buffer_snapshot
14440 .buffer_id_for_excerpt(*excerpt_id)
14441 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14442 {
14443 let buffer_snapshot = buffer.read(cx).snapshot();
14444 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14445 language::ToPoint::to_point(anchor, &buffer_snapshot)
14446 } else {
14447 buffer_snapshot.clip_point(*position, Bias::Left)
14448 };
14449 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14450 new_selections_by_buffer.insert(
14451 buffer,
14452 (
14453 vec![jump_to_offset..jump_to_offset],
14454 Some(*line_offset_from_top),
14455 ),
14456 );
14457 }
14458 }
14459 Some(JumpData::MultiBufferRow {
14460 row,
14461 line_offset_from_top,
14462 }) => {
14463 let point = MultiBufferPoint::new(row.0, 0);
14464 if let Some((buffer, buffer_point, _)) =
14465 self.buffer.read(cx).point_to_buffer_point(point, cx)
14466 {
14467 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14468 new_selections_by_buffer
14469 .entry(buffer)
14470 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14471 .0
14472 .push(buffer_offset..buffer_offset)
14473 }
14474 }
14475 None => {
14476 let selections = self.selections.all::<usize>(cx);
14477 let multi_buffer = self.buffer.read(cx);
14478 for selection in selections {
14479 for (buffer, mut range, _) in multi_buffer
14480 .snapshot(cx)
14481 .range_to_buffer_ranges(selection.range())
14482 {
14483 // When editing branch buffers, jump to the corresponding location
14484 // in their base buffer.
14485 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14486 let buffer = buffer_handle.read(cx);
14487 if let Some(base_buffer) = buffer.base_buffer() {
14488 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14489 buffer_handle = base_buffer;
14490 }
14491
14492 if selection.reversed {
14493 mem::swap(&mut range.start, &mut range.end);
14494 }
14495 new_selections_by_buffer
14496 .entry(buffer_handle)
14497 .or_insert((Vec::new(), None))
14498 .0
14499 .push(range)
14500 }
14501 }
14502 }
14503 }
14504
14505 if new_selections_by_buffer.is_empty() {
14506 return;
14507 }
14508
14509 // We defer the pane interaction because we ourselves are a workspace item
14510 // and activating a new item causes the pane to call a method on us reentrantly,
14511 // which panics if we're on the stack.
14512 window.defer(cx, move |window, cx| {
14513 workspace.update(cx, |workspace, cx| {
14514 let pane = if split {
14515 workspace.adjacent_pane(window, cx)
14516 } else {
14517 workspace.active_pane().clone()
14518 };
14519
14520 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14521 let editor = buffer
14522 .read(cx)
14523 .file()
14524 .is_none()
14525 .then(|| {
14526 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14527 // so `workspace.open_project_item` will never find them, always opening a new editor.
14528 // Instead, we try to activate the existing editor in the pane first.
14529 let (editor, pane_item_index) =
14530 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14531 let editor = item.downcast::<Editor>()?;
14532 let singleton_buffer =
14533 editor.read(cx).buffer().read(cx).as_singleton()?;
14534 if singleton_buffer == buffer {
14535 Some((editor, i))
14536 } else {
14537 None
14538 }
14539 })?;
14540 pane.update(cx, |pane, cx| {
14541 pane.activate_item(pane_item_index, true, true, window, cx)
14542 });
14543 Some(editor)
14544 })
14545 .flatten()
14546 .unwrap_or_else(|| {
14547 workspace.open_project_item::<Self>(
14548 pane.clone(),
14549 buffer,
14550 true,
14551 true,
14552 window,
14553 cx,
14554 )
14555 });
14556
14557 editor.update(cx, |editor, cx| {
14558 let autoscroll = match scroll_offset {
14559 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14560 None => Autoscroll::newest(),
14561 };
14562 let nav_history = editor.nav_history.take();
14563 editor.change_selections(Some(autoscroll), window, cx, |s| {
14564 s.select_ranges(ranges);
14565 });
14566 editor.nav_history = nav_history;
14567 });
14568 }
14569 })
14570 });
14571 }
14572
14573 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14574 let snapshot = self.buffer.read(cx).read(cx);
14575 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14576 Some(
14577 ranges
14578 .iter()
14579 .map(move |range| {
14580 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14581 })
14582 .collect(),
14583 )
14584 }
14585
14586 fn selection_replacement_ranges(
14587 &self,
14588 range: Range<OffsetUtf16>,
14589 cx: &mut App,
14590 ) -> Vec<Range<OffsetUtf16>> {
14591 let selections = self.selections.all::<OffsetUtf16>(cx);
14592 let newest_selection = selections
14593 .iter()
14594 .max_by_key(|selection| selection.id)
14595 .unwrap();
14596 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14597 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14598 let snapshot = self.buffer.read(cx).read(cx);
14599 selections
14600 .into_iter()
14601 .map(|mut selection| {
14602 selection.start.0 =
14603 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14604 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14605 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14606 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14607 })
14608 .collect()
14609 }
14610
14611 fn report_editor_event(
14612 &self,
14613 event_type: &'static str,
14614 file_extension: Option<String>,
14615 cx: &App,
14616 ) {
14617 if cfg!(any(test, feature = "test-support")) {
14618 return;
14619 }
14620
14621 let Some(project) = &self.project else { return };
14622
14623 // If None, we are in a file without an extension
14624 let file = self
14625 .buffer
14626 .read(cx)
14627 .as_singleton()
14628 .and_then(|b| b.read(cx).file());
14629 let file_extension = file_extension.or(file
14630 .as_ref()
14631 .and_then(|file| Path::new(file.file_name(cx)).extension())
14632 .and_then(|e| e.to_str())
14633 .map(|a| a.to_string()));
14634
14635 let vim_mode = cx
14636 .global::<SettingsStore>()
14637 .raw_user_settings()
14638 .get("vim_mode")
14639 == Some(&serde_json::Value::Bool(true));
14640
14641 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14642 let copilot_enabled = edit_predictions_provider
14643 == language::language_settings::EditPredictionProvider::Copilot;
14644 let copilot_enabled_for_language = self
14645 .buffer
14646 .read(cx)
14647 .settings_at(0, cx)
14648 .show_edit_predictions;
14649
14650 let project = project.read(cx);
14651 telemetry::event!(
14652 event_type,
14653 file_extension,
14654 vim_mode,
14655 copilot_enabled,
14656 copilot_enabled_for_language,
14657 edit_predictions_provider,
14658 is_via_ssh = project.is_via_ssh(),
14659 );
14660 }
14661
14662 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14663 /// with each line being an array of {text, highlight} objects.
14664 fn copy_highlight_json(
14665 &mut self,
14666 _: &CopyHighlightJson,
14667 window: &mut Window,
14668 cx: &mut Context<Self>,
14669 ) {
14670 #[derive(Serialize)]
14671 struct Chunk<'a> {
14672 text: String,
14673 highlight: Option<&'a str>,
14674 }
14675
14676 let snapshot = self.buffer.read(cx).snapshot(cx);
14677 let range = self
14678 .selected_text_range(false, window, cx)
14679 .and_then(|selection| {
14680 if selection.range.is_empty() {
14681 None
14682 } else {
14683 Some(selection.range)
14684 }
14685 })
14686 .unwrap_or_else(|| 0..snapshot.len());
14687
14688 let chunks = snapshot.chunks(range, true);
14689 let mut lines = Vec::new();
14690 let mut line: VecDeque<Chunk> = VecDeque::new();
14691
14692 let Some(style) = self.style.as_ref() else {
14693 return;
14694 };
14695
14696 for chunk in chunks {
14697 let highlight = chunk
14698 .syntax_highlight_id
14699 .and_then(|id| id.name(&style.syntax));
14700 let mut chunk_lines = chunk.text.split('\n').peekable();
14701 while let Some(text) = chunk_lines.next() {
14702 let mut merged_with_last_token = false;
14703 if let Some(last_token) = line.back_mut() {
14704 if last_token.highlight == highlight {
14705 last_token.text.push_str(text);
14706 merged_with_last_token = true;
14707 }
14708 }
14709
14710 if !merged_with_last_token {
14711 line.push_back(Chunk {
14712 text: text.into(),
14713 highlight,
14714 });
14715 }
14716
14717 if chunk_lines.peek().is_some() {
14718 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14719 line.pop_front();
14720 }
14721 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14722 line.pop_back();
14723 }
14724
14725 lines.push(mem::take(&mut line));
14726 }
14727 }
14728 }
14729
14730 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14731 return;
14732 };
14733 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14734 }
14735
14736 pub fn open_context_menu(
14737 &mut self,
14738 _: &OpenContextMenu,
14739 window: &mut Window,
14740 cx: &mut Context<Self>,
14741 ) {
14742 self.request_autoscroll(Autoscroll::newest(), cx);
14743 let position = self.selections.newest_display(cx).start;
14744 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14745 }
14746
14747 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14748 &self.inlay_hint_cache
14749 }
14750
14751 pub fn replay_insert_event(
14752 &mut self,
14753 text: &str,
14754 relative_utf16_range: Option<Range<isize>>,
14755 window: &mut Window,
14756 cx: &mut Context<Self>,
14757 ) {
14758 if !self.input_enabled {
14759 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14760 return;
14761 }
14762 if let Some(relative_utf16_range) = relative_utf16_range {
14763 let selections = self.selections.all::<OffsetUtf16>(cx);
14764 self.change_selections(None, window, cx, |s| {
14765 let new_ranges = selections.into_iter().map(|range| {
14766 let start = OffsetUtf16(
14767 range
14768 .head()
14769 .0
14770 .saturating_add_signed(relative_utf16_range.start),
14771 );
14772 let end = OffsetUtf16(
14773 range
14774 .head()
14775 .0
14776 .saturating_add_signed(relative_utf16_range.end),
14777 );
14778 start..end
14779 });
14780 s.select_ranges(new_ranges);
14781 });
14782 }
14783
14784 self.handle_input(text, window, cx);
14785 }
14786
14787 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14788 let Some(provider) = self.semantics_provider.as_ref() else {
14789 return false;
14790 };
14791
14792 let mut supports = false;
14793 self.buffer().update(cx, |this, cx| {
14794 this.for_each_buffer(|buffer| {
14795 supports |= provider.supports_inlay_hints(buffer, cx);
14796 });
14797 });
14798
14799 supports
14800 }
14801
14802 pub fn is_focused(&self, window: &Window) -> bool {
14803 self.focus_handle.is_focused(window)
14804 }
14805
14806 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14807 cx.emit(EditorEvent::Focused);
14808
14809 if let Some(descendant) = self
14810 .last_focused_descendant
14811 .take()
14812 .and_then(|descendant| descendant.upgrade())
14813 {
14814 window.focus(&descendant);
14815 } else {
14816 if let Some(blame) = self.blame.as_ref() {
14817 blame.update(cx, GitBlame::focus)
14818 }
14819
14820 self.blink_manager.update(cx, BlinkManager::enable);
14821 self.show_cursor_names(window, cx);
14822 self.buffer.update(cx, |buffer, cx| {
14823 buffer.finalize_last_transaction(cx);
14824 if self.leader_peer_id.is_none() {
14825 buffer.set_active_selections(
14826 &self.selections.disjoint_anchors(),
14827 self.selections.line_mode,
14828 self.cursor_shape,
14829 cx,
14830 );
14831 }
14832 });
14833 }
14834 }
14835
14836 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14837 cx.emit(EditorEvent::FocusedIn)
14838 }
14839
14840 fn handle_focus_out(
14841 &mut self,
14842 event: FocusOutEvent,
14843 _window: &mut Window,
14844 _cx: &mut Context<Self>,
14845 ) {
14846 if event.blurred != self.focus_handle {
14847 self.last_focused_descendant = Some(event.blurred);
14848 }
14849 }
14850
14851 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14852 self.blink_manager.update(cx, BlinkManager::disable);
14853 self.buffer
14854 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14855
14856 if let Some(blame) = self.blame.as_ref() {
14857 blame.update(cx, GitBlame::blur)
14858 }
14859 if !self.hover_state.focused(window, cx) {
14860 hide_hover(self, cx);
14861 }
14862 if !self
14863 .context_menu
14864 .borrow()
14865 .as_ref()
14866 .is_some_and(|context_menu| context_menu.focused(window, cx))
14867 {
14868 self.hide_context_menu(window, cx);
14869 }
14870 self.discard_inline_completion(false, cx);
14871 cx.emit(EditorEvent::Blurred);
14872 cx.notify();
14873 }
14874
14875 pub fn register_action<A: Action>(
14876 &mut self,
14877 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14878 ) -> Subscription {
14879 let id = self.next_editor_action_id.post_inc();
14880 let listener = Arc::new(listener);
14881 self.editor_actions.borrow_mut().insert(
14882 id,
14883 Box::new(move |window, _| {
14884 let listener = listener.clone();
14885 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14886 let action = action.downcast_ref().unwrap();
14887 if phase == DispatchPhase::Bubble {
14888 listener(action, window, cx)
14889 }
14890 })
14891 }),
14892 );
14893
14894 let editor_actions = self.editor_actions.clone();
14895 Subscription::new(move || {
14896 editor_actions.borrow_mut().remove(&id);
14897 })
14898 }
14899
14900 pub fn file_header_size(&self) -> u32 {
14901 FILE_HEADER_HEIGHT
14902 }
14903
14904 pub fn revert(
14905 &mut self,
14906 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14907 window: &mut Window,
14908 cx: &mut Context<Self>,
14909 ) {
14910 self.buffer().update(cx, |multi_buffer, cx| {
14911 for (buffer_id, changes) in revert_changes {
14912 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14913 buffer.update(cx, |buffer, cx| {
14914 buffer.edit(
14915 changes.into_iter().map(|(range, text)| {
14916 (range, text.to_string().map(Arc::<str>::from))
14917 }),
14918 None,
14919 cx,
14920 );
14921 });
14922 }
14923 }
14924 });
14925 self.change_selections(None, window, cx, |selections| selections.refresh());
14926 }
14927
14928 pub fn to_pixel_point(
14929 &self,
14930 source: multi_buffer::Anchor,
14931 editor_snapshot: &EditorSnapshot,
14932 window: &mut Window,
14933 ) -> Option<gpui::Point<Pixels>> {
14934 let source_point = source.to_display_point(editor_snapshot);
14935 self.display_to_pixel_point(source_point, editor_snapshot, window)
14936 }
14937
14938 pub fn display_to_pixel_point(
14939 &self,
14940 source: DisplayPoint,
14941 editor_snapshot: &EditorSnapshot,
14942 window: &mut Window,
14943 ) -> Option<gpui::Point<Pixels>> {
14944 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14945 let text_layout_details = self.text_layout_details(window);
14946 let scroll_top = text_layout_details
14947 .scroll_anchor
14948 .scroll_position(editor_snapshot)
14949 .y;
14950
14951 if source.row().as_f32() < scroll_top.floor() {
14952 return None;
14953 }
14954 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14955 let source_y = line_height * (source.row().as_f32() - scroll_top);
14956 Some(gpui::Point::new(source_x, source_y))
14957 }
14958
14959 pub fn has_visible_completions_menu(&self) -> bool {
14960 !self.edit_prediction_preview_is_active()
14961 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14962 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14963 })
14964 }
14965
14966 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14967 self.addons
14968 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14969 }
14970
14971 pub fn unregister_addon<T: Addon>(&mut self) {
14972 self.addons.remove(&std::any::TypeId::of::<T>());
14973 }
14974
14975 pub fn addon<T: Addon>(&self) -> Option<&T> {
14976 let type_id = std::any::TypeId::of::<T>();
14977 self.addons
14978 .get(&type_id)
14979 .and_then(|item| item.to_any().downcast_ref::<T>())
14980 }
14981
14982 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14983 let text_layout_details = self.text_layout_details(window);
14984 let style = &text_layout_details.editor_style;
14985 let font_id = window.text_system().resolve_font(&style.text.font());
14986 let font_size = style.text.font_size.to_pixels(window.rem_size());
14987 let line_height = style.text.line_height_in_pixels(window.rem_size());
14988 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14989
14990 gpui::Size::new(em_width, line_height)
14991 }
14992
14993 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14994 self.load_diff_task.clone()
14995 }
14996
14997 fn read_selections_from_db(
14998 &mut self,
14999 item_id: u64,
15000 workspace_id: WorkspaceId,
15001 window: &mut Window,
15002 cx: &mut Context<Editor>,
15003 ) {
15004 if !self.is_singleton(cx)
15005 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15006 {
15007 return;
15008 }
15009 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15010 return;
15011 };
15012 if selections.is_empty() {
15013 return;
15014 }
15015
15016 let snapshot = self.buffer.read(cx).snapshot(cx);
15017 self.change_selections(None, window, cx, |s| {
15018 s.select_ranges(selections.into_iter().map(|(start, end)| {
15019 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15020 }));
15021 });
15022 }
15023}
15024
15025fn get_uncommitted_diff_for_buffer(
15026 project: &Entity<Project>,
15027 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15028 buffer: Entity<MultiBuffer>,
15029 cx: &mut App,
15030) -> Task<()> {
15031 let mut tasks = Vec::new();
15032 project.update(cx, |project, cx| {
15033 for buffer in buffers {
15034 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15035 }
15036 });
15037 cx.spawn(|mut cx| async move {
15038 let diffs = futures::future::join_all(tasks).await;
15039 buffer
15040 .update(&mut cx, |buffer, cx| {
15041 for diff in diffs.into_iter().flatten() {
15042 buffer.add_diff(diff, cx);
15043 }
15044 })
15045 .ok();
15046 })
15047}
15048
15049fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15050 let tab_size = tab_size.get() as usize;
15051 let mut width = offset;
15052
15053 for ch in text.chars() {
15054 width += if ch == '\t' {
15055 tab_size - (width % tab_size)
15056 } else {
15057 1
15058 };
15059 }
15060
15061 width - offset
15062}
15063
15064#[cfg(test)]
15065mod tests {
15066 use super::*;
15067
15068 #[test]
15069 fn test_string_size_with_expanded_tabs() {
15070 let nz = |val| NonZeroU32::new(val).unwrap();
15071 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15072 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15073 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15074 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15075 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15076 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15077 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15078 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15079 }
15080}
15081
15082/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15083struct WordBreakingTokenizer<'a> {
15084 input: &'a str,
15085}
15086
15087impl<'a> WordBreakingTokenizer<'a> {
15088 fn new(input: &'a str) -> Self {
15089 Self { input }
15090 }
15091}
15092
15093fn is_char_ideographic(ch: char) -> bool {
15094 use unicode_script::Script::*;
15095 use unicode_script::UnicodeScript;
15096 matches!(ch.script(), Han | Tangut | Yi)
15097}
15098
15099fn is_grapheme_ideographic(text: &str) -> bool {
15100 text.chars().any(is_char_ideographic)
15101}
15102
15103fn is_grapheme_whitespace(text: &str) -> bool {
15104 text.chars().any(|x| x.is_whitespace())
15105}
15106
15107fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15108 text.chars().next().map_or(false, |ch| {
15109 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15110 })
15111}
15112
15113#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15114struct WordBreakToken<'a> {
15115 token: &'a str,
15116 grapheme_len: usize,
15117 is_whitespace: bool,
15118}
15119
15120impl<'a> Iterator for WordBreakingTokenizer<'a> {
15121 /// Yields a span, the count of graphemes in the token, and whether it was
15122 /// whitespace. Note that it also breaks at word boundaries.
15123 type Item = WordBreakToken<'a>;
15124
15125 fn next(&mut self) -> Option<Self::Item> {
15126 use unicode_segmentation::UnicodeSegmentation;
15127 if self.input.is_empty() {
15128 return None;
15129 }
15130
15131 let mut iter = self.input.graphemes(true).peekable();
15132 let mut offset = 0;
15133 let mut graphemes = 0;
15134 if let Some(first_grapheme) = iter.next() {
15135 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15136 offset += first_grapheme.len();
15137 graphemes += 1;
15138 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15139 if let Some(grapheme) = iter.peek().copied() {
15140 if should_stay_with_preceding_ideograph(grapheme) {
15141 offset += grapheme.len();
15142 graphemes += 1;
15143 }
15144 }
15145 } else {
15146 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15147 let mut next_word_bound = words.peek().copied();
15148 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15149 next_word_bound = words.next();
15150 }
15151 while let Some(grapheme) = iter.peek().copied() {
15152 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15153 break;
15154 };
15155 if is_grapheme_whitespace(grapheme) != is_whitespace {
15156 break;
15157 };
15158 offset += grapheme.len();
15159 graphemes += 1;
15160 iter.next();
15161 }
15162 }
15163 let token = &self.input[..offset];
15164 self.input = &self.input[offset..];
15165 if is_whitespace {
15166 Some(WordBreakToken {
15167 token: " ",
15168 grapheme_len: 1,
15169 is_whitespace: true,
15170 })
15171 } else {
15172 Some(WordBreakToken {
15173 token,
15174 grapheme_len: graphemes,
15175 is_whitespace: false,
15176 })
15177 }
15178 } else {
15179 None
15180 }
15181 }
15182}
15183
15184#[test]
15185fn test_word_breaking_tokenizer() {
15186 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15187 ("", &[]),
15188 (" ", &[(" ", 1, true)]),
15189 ("Ʒ", &[("Ʒ", 1, false)]),
15190 ("Ǽ", &[("Ǽ", 1, false)]),
15191 ("⋑", &[("⋑", 1, false)]),
15192 ("⋑⋑", &[("⋑⋑", 2, false)]),
15193 (
15194 "原理,进而",
15195 &[
15196 ("原", 1, false),
15197 ("理,", 2, false),
15198 ("进", 1, false),
15199 ("而", 1, false),
15200 ],
15201 ),
15202 (
15203 "hello world",
15204 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15205 ),
15206 (
15207 "hello, world",
15208 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15209 ),
15210 (
15211 " hello world",
15212 &[
15213 (" ", 1, true),
15214 ("hello", 5, false),
15215 (" ", 1, true),
15216 ("world", 5, false),
15217 ],
15218 ),
15219 (
15220 "这是什么 \n 钢笔",
15221 &[
15222 ("这", 1, false),
15223 ("是", 1, false),
15224 ("什", 1, false),
15225 ("么", 1, false),
15226 (" ", 1, true),
15227 ("钢", 1, false),
15228 ("笔", 1, false),
15229 ],
15230 ),
15231 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15232 ];
15233
15234 for (input, result) in tests {
15235 assert_eq!(
15236 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15237 result
15238 .iter()
15239 .copied()
15240 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15241 token,
15242 grapheme_len,
15243 is_whitespace,
15244 })
15245 .collect::<Vec<_>>()
15246 );
15247 }
15248}
15249
15250fn wrap_with_prefix(
15251 line_prefix: String,
15252 unwrapped_text: String,
15253 wrap_column: usize,
15254 tab_size: NonZeroU32,
15255) -> String {
15256 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15257 let mut wrapped_text = String::new();
15258 let mut current_line = line_prefix.clone();
15259
15260 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15261 let mut current_line_len = line_prefix_len;
15262 for WordBreakToken {
15263 token,
15264 grapheme_len,
15265 is_whitespace,
15266 } in tokenizer
15267 {
15268 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15269 wrapped_text.push_str(current_line.trim_end());
15270 wrapped_text.push('\n');
15271 current_line.truncate(line_prefix.len());
15272 current_line_len = line_prefix_len;
15273 if !is_whitespace {
15274 current_line.push_str(token);
15275 current_line_len += grapheme_len;
15276 }
15277 } else if !is_whitespace {
15278 current_line.push_str(token);
15279 current_line_len += grapheme_len;
15280 } else if current_line_len != line_prefix_len {
15281 current_line.push(' ');
15282 current_line_len += 1;
15283 }
15284 }
15285
15286 if !current_line.is_empty() {
15287 wrapped_text.push_str(¤t_line);
15288 }
15289 wrapped_text
15290}
15291
15292#[test]
15293fn test_wrap_with_prefix() {
15294 assert_eq!(
15295 wrap_with_prefix(
15296 "# ".to_string(),
15297 "abcdefg".to_string(),
15298 4,
15299 NonZeroU32::new(4).unwrap()
15300 ),
15301 "# abcdefg"
15302 );
15303 assert_eq!(
15304 wrap_with_prefix(
15305 "".to_string(),
15306 "\thello world".to_string(),
15307 8,
15308 NonZeroU32::new(4).unwrap()
15309 ),
15310 "hello\nworld"
15311 );
15312 assert_eq!(
15313 wrap_with_prefix(
15314 "// ".to_string(),
15315 "xx \nyy zz aa bb cc".to_string(),
15316 12,
15317 NonZeroU32::new(4).unwrap()
15318 ),
15319 "// xx yy zz\n// aa bb cc"
15320 );
15321 assert_eq!(
15322 wrap_with_prefix(
15323 String::new(),
15324 "这是什么 \n 钢笔".to_string(),
15325 3,
15326 NonZeroU32::new(4).unwrap()
15327 ),
15328 "这是什\n么 钢\n笔"
15329 );
15330}
15331
15332pub trait CollaborationHub {
15333 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15334 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15335 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15336}
15337
15338impl CollaborationHub for Entity<Project> {
15339 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15340 self.read(cx).collaborators()
15341 }
15342
15343 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15344 self.read(cx).user_store().read(cx).participant_indices()
15345 }
15346
15347 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15348 let this = self.read(cx);
15349 let user_ids = this.collaborators().values().map(|c| c.user_id);
15350 this.user_store().read_with(cx, |user_store, cx| {
15351 user_store.participant_names(user_ids, cx)
15352 })
15353 }
15354}
15355
15356pub trait SemanticsProvider {
15357 fn hover(
15358 &self,
15359 buffer: &Entity<Buffer>,
15360 position: text::Anchor,
15361 cx: &mut App,
15362 ) -> Option<Task<Vec<project::Hover>>>;
15363
15364 fn inlay_hints(
15365 &self,
15366 buffer_handle: Entity<Buffer>,
15367 range: Range<text::Anchor>,
15368 cx: &mut App,
15369 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15370
15371 fn resolve_inlay_hint(
15372 &self,
15373 hint: InlayHint,
15374 buffer_handle: Entity<Buffer>,
15375 server_id: LanguageServerId,
15376 cx: &mut App,
15377 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15378
15379 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15380
15381 fn document_highlights(
15382 &self,
15383 buffer: &Entity<Buffer>,
15384 position: text::Anchor,
15385 cx: &mut App,
15386 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15387
15388 fn definitions(
15389 &self,
15390 buffer: &Entity<Buffer>,
15391 position: text::Anchor,
15392 kind: GotoDefinitionKind,
15393 cx: &mut App,
15394 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15395
15396 fn range_for_rename(
15397 &self,
15398 buffer: &Entity<Buffer>,
15399 position: text::Anchor,
15400 cx: &mut App,
15401 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15402
15403 fn perform_rename(
15404 &self,
15405 buffer: &Entity<Buffer>,
15406 position: text::Anchor,
15407 new_name: String,
15408 cx: &mut App,
15409 ) -> Option<Task<Result<ProjectTransaction>>>;
15410}
15411
15412pub trait CompletionProvider {
15413 fn completions(
15414 &self,
15415 buffer: &Entity<Buffer>,
15416 buffer_position: text::Anchor,
15417 trigger: CompletionContext,
15418 window: &mut Window,
15419 cx: &mut Context<Editor>,
15420 ) -> Task<Result<Vec<Completion>>>;
15421
15422 fn resolve_completions(
15423 &self,
15424 buffer: Entity<Buffer>,
15425 completion_indices: Vec<usize>,
15426 completions: Rc<RefCell<Box<[Completion]>>>,
15427 cx: &mut Context<Editor>,
15428 ) -> Task<Result<bool>>;
15429
15430 fn apply_additional_edits_for_completion(
15431 &self,
15432 _buffer: Entity<Buffer>,
15433 _completions: Rc<RefCell<Box<[Completion]>>>,
15434 _completion_index: usize,
15435 _push_to_history: bool,
15436 _cx: &mut Context<Editor>,
15437 ) -> Task<Result<Option<language::Transaction>>> {
15438 Task::ready(Ok(None))
15439 }
15440
15441 fn is_completion_trigger(
15442 &self,
15443 buffer: &Entity<Buffer>,
15444 position: language::Anchor,
15445 text: &str,
15446 trigger_in_words: bool,
15447 cx: &mut Context<Editor>,
15448 ) -> bool;
15449
15450 fn sort_completions(&self) -> bool {
15451 true
15452 }
15453}
15454
15455pub trait CodeActionProvider {
15456 fn id(&self) -> Arc<str>;
15457
15458 fn code_actions(
15459 &self,
15460 buffer: &Entity<Buffer>,
15461 range: Range<text::Anchor>,
15462 window: &mut Window,
15463 cx: &mut App,
15464 ) -> Task<Result<Vec<CodeAction>>>;
15465
15466 fn apply_code_action(
15467 &self,
15468 buffer_handle: Entity<Buffer>,
15469 action: CodeAction,
15470 excerpt_id: ExcerptId,
15471 push_to_history: bool,
15472 window: &mut Window,
15473 cx: &mut App,
15474 ) -> Task<Result<ProjectTransaction>>;
15475}
15476
15477impl CodeActionProvider for Entity<Project> {
15478 fn id(&self) -> Arc<str> {
15479 "project".into()
15480 }
15481
15482 fn code_actions(
15483 &self,
15484 buffer: &Entity<Buffer>,
15485 range: Range<text::Anchor>,
15486 _window: &mut Window,
15487 cx: &mut App,
15488 ) -> Task<Result<Vec<CodeAction>>> {
15489 self.update(cx, |project, cx| {
15490 project.code_actions(buffer, range, None, cx)
15491 })
15492 }
15493
15494 fn apply_code_action(
15495 &self,
15496 buffer_handle: Entity<Buffer>,
15497 action: CodeAction,
15498 _excerpt_id: ExcerptId,
15499 push_to_history: bool,
15500 _window: &mut Window,
15501 cx: &mut App,
15502 ) -> Task<Result<ProjectTransaction>> {
15503 self.update(cx, |project, cx| {
15504 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15505 })
15506 }
15507}
15508
15509fn snippet_completions(
15510 project: &Project,
15511 buffer: &Entity<Buffer>,
15512 buffer_position: text::Anchor,
15513 cx: &mut App,
15514) -> Task<Result<Vec<Completion>>> {
15515 let language = buffer.read(cx).language_at(buffer_position);
15516 let language_name = language.as_ref().map(|language| language.lsp_id());
15517 let snippet_store = project.snippets().read(cx);
15518 let snippets = snippet_store.snippets_for(language_name, cx);
15519
15520 if snippets.is_empty() {
15521 return Task::ready(Ok(vec![]));
15522 }
15523 let snapshot = buffer.read(cx).text_snapshot();
15524 let chars: String = snapshot
15525 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15526 .collect();
15527
15528 let scope = language.map(|language| language.default_scope());
15529 let executor = cx.background_executor().clone();
15530
15531 cx.background_spawn(async move {
15532 let classifier = CharClassifier::new(scope).for_completion(true);
15533 let mut last_word = chars
15534 .chars()
15535 .take_while(|c| classifier.is_word(*c))
15536 .collect::<String>();
15537 last_word = last_word.chars().rev().collect();
15538
15539 if last_word.is_empty() {
15540 return Ok(vec![]);
15541 }
15542
15543 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15544 let to_lsp = |point: &text::Anchor| {
15545 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15546 point_to_lsp(end)
15547 };
15548 let lsp_end = to_lsp(&buffer_position);
15549
15550 let candidates = snippets
15551 .iter()
15552 .enumerate()
15553 .flat_map(|(ix, snippet)| {
15554 snippet
15555 .prefix
15556 .iter()
15557 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15558 })
15559 .collect::<Vec<StringMatchCandidate>>();
15560
15561 let mut matches = fuzzy::match_strings(
15562 &candidates,
15563 &last_word,
15564 last_word.chars().any(|c| c.is_uppercase()),
15565 100,
15566 &Default::default(),
15567 executor,
15568 )
15569 .await;
15570
15571 // Remove all candidates where the query's start does not match the start of any word in the candidate
15572 if let Some(query_start) = last_word.chars().next() {
15573 matches.retain(|string_match| {
15574 split_words(&string_match.string).any(|word| {
15575 // Check that the first codepoint of the word as lowercase matches the first
15576 // codepoint of the query as lowercase
15577 word.chars()
15578 .flat_map(|codepoint| codepoint.to_lowercase())
15579 .zip(query_start.to_lowercase())
15580 .all(|(word_cp, query_cp)| word_cp == query_cp)
15581 })
15582 });
15583 }
15584
15585 let matched_strings = matches
15586 .into_iter()
15587 .map(|m| m.string)
15588 .collect::<HashSet<_>>();
15589
15590 let result: Vec<Completion> = snippets
15591 .into_iter()
15592 .filter_map(|snippet| {
15593 let matching_prefix = snippet
15594 .prefix
15595 .iter()
15596 .find(|prefix| matched_strings.contains(*prefix))?;
15597 let start = as_offset - last_word.len();
15598 let start = snapshot.anchor_before(start);
15599 let range = start..buffer_position;
15600 let lsp_start = to_lsp(&start);
15601 let lsp_range = lsp::Range {
15602 start: lsp_start,
15603 end: lsp_end,
15604 };
15605 Some(Completion {
15606 old_range: range,
15607 new_text: snippet.body.clone(),
15608 resolved: false,
15609 label: CodeLabel {
15610 text: matching_prefix.clone(),
15611 runs: vec![],
15612 filter_range: 0..matching_prefix.len(),
15613 },
15614 server_id: LanguageServerId(usize::MAX),
15615 documentation: snippet
15616 .description
15617 .clone()
15618 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15619 lsp_completion: lsp::CompletionItem {
15620 label: snippet.prefix.first().unwrap().clone(),
15621 kind: Some(CompletionItemKind::SNIPPET),
15622 label_details: snippet.description.as_ref().map(|description| {
15623 lsp::CompletionItemLabelDetails {
15624 detail: Some(description.clone()),
15625 description: None,
15626 }
15627 }),
15628 insert_text_format: Some(InsertTextFormat::SNIPPET),
15629 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15630 lsp::InsertReplaceEdit {
15631 new_text: snippet.body.clone(),
15632 insert: lsp_range,
15633 replace: lsp_range,
15634 },
15635 )),
15636 filter_text: Some(snippet.body.clone()),
15637 sort_text: Some(char::MAX.to_string()),
15638 ..Default::default()
15639 },
15640 confirm: None,
15641 })
15642 })
15643 .collect();
15644
15645 Ok(result)
15646 })
15647}
15648
15649impl CompletionProvider for Entity<Project> {
15650 fn completions(
15651 &self,
15652 buffer: &Entity<Buffer>,
15653 buffer_position: text::Anchor,
15654 options: CompletionContext,
15655 _window: &mut Window,
15656 cx: &mut Context<Editor>,
15657 ) -> Task<Result<Vec<Completion>>> {
15658 self.update(cx, |project, cx| {
15659 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15660 let project_completions = project.completions(buffer, buffer_position, options, cx);
15661 cx.background_spawn(async move {
15662 let mut completions = project_completions.await?;
15663 let snippets_completions = snippets.await?;
15664 completions.extend(snippets_completions);
15665 Ok(completions)
15666 })
15667 })
15668 }
15669
15670 fn resolve_completions(
15671 &self,
15672 buffer: Entity<Buffer>,
15673 completion_indices: Vec<usize>,
15674 completions: Rc<RefCell<Box<[Completion]>>>,
15675 cx: &mut Context<Editor>,
15676 ) -> Task<Result<bool>> {
15677 self.update(cx, |project, cx| {
15678 project.lsp_store().update(cx, |lsp_store, cx| {
15679 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15680 })
15681 })
15682 }
15683
15684 fn apply_additional_edits_for_completion(
15685 &self,
15686 buffer: Entity<Buffer>,
15687 completions: Rc<RefCell<Box<[Completion]>>>,
15688 completion_index: usize,
15689 push_to_history: bool,
15690 cx: &mut Context<Editor>,
15691 ) -> Task<Result<Option<language::Transaction>>> {
15692 self.update(cx, |project, cx| {
15693 project.lsp_store().update(cx, |lsp_store, cx| {
15694 lsp_store.apply_additional_edits_for_completion(
15695 buffer,
15696 completions,
15697 completion_index,
15698 push_to_history,
15699 cx,
15700 )
15701 })
15702 })
15703 }
15704
15705 fn is_completion_trigger(
15706 &self,
15707 buffer: &Entity<Buffer>,
15708 position: language::Anchor,
15709 text: &str,
15710 trigger_in_words: bool,
15711 cx: &mut Context<Editor>,
15712 ) -> bool {
15713 let mut chars = text.chars();
15714 let char = if let Some(char) = chars.next() {
15715 char
15716 } else {
15717 return false;
15718 };
15719 if chars.next().is_some() {
15720 return false;
15721 }
15722
15723 let buffer = buffer.read(cx);
15724 let snapshot = buffer.snapshot();
15725 if !snapshot.settings_at(position, cx).show_completions_on_input {
15726 return false;
15727 }
15728 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15729 if trigger_in_words && classifier.is_word(char) {
15730 return true;
15731 }
15732
15733 buffer.completion_triggers().contains(text)
15734 }
15735}
15736
15737impl SemanticsProvider for Entity<Project> {
15738 fn hover(
15739 &self,
15740 buffer: &Entity<Buffer>,
15741 position: text::Anchor,
15742 cx: &mut App,
15743 ) -> Option<Task<Vec<project::Hover>>> {
15744 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15745 }
15746
15747 fn document_highlights(
15748 &self,
15749 buffer: &Entity<Buffer>,
15750 position: text::Anchor,
15751 cx: &mut App,
15752 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15753 Some(self.update(cx, |project, cx| {
15754 project.document_highlights(buffer, position, cx)
15755 }))
15756 }
15757
15758 fn definitions(
15759 &self,
15760 buffer: &Entity<Buffer>,
15761 position: text::Anchor,
15762 kind: GotoDefinitionKind,
15763 cx: &mut App,
15764 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15765 Some(self.update(cx, |project, cx| match kind {
15766 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15767 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15768 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15769 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15770 }))
15771 }
15772
15773 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15774 // TODO: make this work for remote projects
15775 self.update(cx, |this, cx| {
15776 buffer.update(cx, |buffer, cx| {
15777 this.any_language_server_supports_inlay_hints(buffer, cx)
15778 })
15779 })
15780 }
15781
15782 fn inlay_hints(
15783 &self,
15784 buffer_handle: Entity<Buffer>,
15785 range: Range<text::Anchor>,
15786 cx: &mut App,
15787 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15788 Some(self.update(cx, |project, cx| {
15789 project.inlay_hints(buffer_handle, range, cx)
15790 }))
15791 }
15792
15793 fn resolve_inlay_hint(
15794 &self,
15795 hint: InlayHint,
15796 buffer_handle: Entity<Buffer>,
15797 server_id: LanguageServerId,
15798 cx: &mut App,
15799 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15800 Some(self.update(cx, |project, cx| {
15801 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15802 }))
15803 }
15804
15805 fn range_for_rename(
15806 &self,
15807 buffer: &Entity<Buffer>,
15808 position: text::Anchor,
15809 cx: &mut App,
15810 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15811 Some(self.update(cx, |project, cx| {
15812 let buffer = buffer.clone();
15813 let task = project.prepare_rename(buffer.clone(), position, cx);
15814 cx.spawn(|_, mut cx| async move {
15815 Ok(match task.await? {
15816 PrepareRenameResponse::Success(range) => Some(range),
15817 PrepareRenameResponse::InvalidPosition => None,
15818 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15819 // Fallback on using TreeSitter info to determine identifier range
15820 buffer.update(&mut cx, |buffer, _| {
15821 let snapshot = buffer.snapshot();
15822 let (range, kind) = snapshot.surrounding_word(position);
15823 if kind != Some(CharKind::Word) {
15824 return None;
15825 }
15826 Some(
15827 snapshot.anchor_before(range.start)
15828 ..snapshot.anchor_after(range.end),
15829 )
15830 })?
15831 }
15832 })
15833 })
15834 }))
15835 }
15836
15837 fn perform_rename(
15838 &self,
15839 buffer: &Entity<Buffer>,
15840 position: text::Anchor,
15841 new_name: String,
15842 cx: &mut App,
15843 ) -> Option<Task<Result<ProjectTransaction>>> {
15844 Some(self.update(cx, |project, cx| {
15845 project.perform_rename(buffer.clone(), position, new_name, cx)
15846 }))
15847 }
15848}
15849
15850fn inlay_hint_settings(
15851 location: Anchor,
15852 snapshot: &MultiBufferSnapshot,
15853 cx: &mut Context<Editor>,
15854) -> InlayHintSettings {
15855 let file = snapshot.file_at(location);
15856 let language = snapshot.language_at(location).map(|l| l.name());
15857 language_settings(language, file, cx).inlay_hints
15858}
15859
15860fn consume_contiguous_rows(
15861 contiguous_row_selections: &mut Vec<Selection<Point>>,
15862 selection: &Selection<Point>,
15863 display_map: &DisplaySnapshot,
15864 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15865) -> (MultiBufferRow, MultiBufferRow) {
15866 contiguous_row_selections.push(selection.clone());
15867 let start_row = MultiBufferRow(selection.start.row);
15868 let mut end_row = ending_row(selection, display_map);
15869
15870 while let Some(next_selection) = selections.peek() {
15871 if next_selection.start.row <= end_row.0 {
15872 end_row = ending_row(next_selection, display_map);
15873 contiguous_row_selections.push(selections.next().unwrap().clone());
15874 } else {
15875 break;
15876 }
15877 }
15878 (start_row, end_row)
15879}
15880
15881fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15882 if next_selection.end.column > 0 || next_selection.is_empty() {
15883 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15884 } else {
15885 MultiBufferRow(next_selection.end.row)
15886 }
15887}
15888
15889impl EditorSnapshot {
15890 pub fn remote_selections_in_range<'a>(
15891 &'a self,
15892 range: &'a Range<Anchor>,
15893 collaboration_hub: &dyn CollaborationHub,
15894 cx: &'a App,
15895 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15896 let participant_names = collaboration_hub.user_names(cx);
15897 let participant_indices = collaboration_hub.user_participant_indices(cx);
15898 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15899 let collaborators_by_replica_id = collaborators_by_peer_id
15900 .iter()
15901 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15902 .collect::<HashMap<_, _>>();
15903 self.buffer_snapshot
15904 .selections_in_range(range, false)
15905 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15906 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15907 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15908 let user_name = participant_names.get(&collaborator.user_id).cloned();
15909 Some(RemoteSelection {
15910 replica_id,
15911 selection,
15912 cursor_shape,
15913 line_mode,
15914 participant_index,
15915 peer_id: collaborator.peer_id,
15916 user_name,
15917 })
15918 })
15919 }
15920
15921 pub fn hunks_for_ranges(
15922 &self,
15923 ranges: impl Iterator<Item = Range<Point>>,
15924 ) -> Vec<MultiBufferDiffHunk> {
15925 let mut hunks = Vec::new();
15926 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15927 HashMap::default();
15928 for query_range in ranges {
15929 let query_rows =
15930 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15931 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15932 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15933 ) {
15934 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15935 // when the caret is just above or just below the deleted hunk.
15936 let allow_adjacent = hunk.status().is_deleted();
15937 let related_to_selection = if allow_adjacent {
15938 hunk.row_range.overlaps(&query_rows)
15939 || hunk.row_range.start == query_rows.end
15940 || hunk.row_range.end == query_rows.start
15941 } else {
15942 hunk.row_range.overlaps(&query_rows)
15943 };
15944 if related_to_selection {
15945 if !processed_buffer_rows
15946 .entry(hunk.buffer_id)
15947 .or_default()
15948 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15949 {
15950 continue;
15951 }
15952 hunks.push(hunk);
15953 }
15954 }
15955 }
15956
15957 hunks
15958 }
15959
15960 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15961 self.display_snapshot.buffer_snapshot.language_at(position)
15962 }
15963
15964 pub fn is_focused(&self) -> bool {
15965 self.is_focused
15966 }
15967
15968 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15969 self.placeholder_text.as_ref()
15970 }
15971
15972 pub fn scroll_position(&self) -> gpui::Point<f32> {
15973 self.scroll_anchor.scroll_position(&self.display_snapshot)
15974 }
15975
15976 fn gutter_dimensions(
15977 &self,
15978 font_id: FontId,
15979 font_size: Pixels,
15980 max_line_number_width: Pixels,
15981 cx: &App,
15982 ) -> Option<GutterDimensions> {
15983 if !self.show_gutter {
15984 return None;
15985 }
15986
15987 let descent = cx.text_system().descent(font_id, font_size);
15988 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15989 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15990
15991 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15992 matches!(
15993 ProjectSettings::get_global(cx).git.git_gutter,
15994 Some(GitGutterSetting::TrackedFiles)
15995 )
15996 });
15997 let gutter_settings = EditorSettings::get_global(cx).gutter;
15998 let show_line_numbers = self
15999 .show_line_numbers
16000 .unwrap_or(gutter_settings.line_numbers);
16001 let line_gutter_width = if show_line_numbers {
16002 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16003 let min_width_for_number_on_gutter = em_advance * 4.0;
16004 max_line_number_width.max(min_width_for_number_on_gutter)
16005 } else {
16006 0.0.into()
16007 };
16008
16009 let show_code_actions = self
16010 .show_code_actions
16011 .unwrap_or(gutter_settings.code_actions);
16012
16013 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16014
16015 let git_blame_entries_width =
16016 self.git_blame_gutter_max_author_length
16017 .map(|max_author_length| {
16018 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16019
16020 /// The number of characters to dedicate to gaps and margins.
16021 const SPACING_WIDTH: usize = 4;
16022
16023 let max_char_count = max_author_length
16024 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16025 + ::git::SHORT_SHA_LENGTH
16026 + MAX_RELATIVE_TIMESTAMP.len()
16027 + SPACING_WIDTH;
16028
16029 em_advance * max_char_count
16030 });
16031
16032 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16033 left_padding += if show_code_actions || show_runnables {
16034 em_width * 3.0
16035 } else if show_git_gutter && show_line_numbers {
16036 em_width * 2.0
16037 } else if show_git_gutter || show_line_numbers {
16038 em_width
16039 } else {
16040 px(0.)
16041 };
16042
16043 let right_padding = if gutter_settings.folds && show_line_numbers {
16044 em_width * 4.0
16045 } else if gutter_settings.folds {
16046 em_width * 3.0
16047 } else if show_line_numbers {
16048 em_width
16049 } else {
16050 px(0.)
16051 };
16052
16053 Some(GutterDimensions {
16054 left_padding,
16055 right_padding,
16056 width: line_gutter_width + left_padding + right_padding,
16057 margin: -descent,
16058 git_blame_entries_width,
16059 })
16060 }
16061
16062 pub fn render_crease_toggle(
16063 &self,
16064 buffer_row: MultiBufferRow,
16065 row_contains_cursor: bool,
16066 editor: Entity<Editor>,
16067 window: &mut Window,
16068 cx: &mut App,
16069 ) -> Option<AnyElement> {
16070 let folded = self.is_line_folded(buffer_row);
16071 let mut is_foldable = false;
16072
16073 if let Some(crease) = self
16074 .crease_snapshot
16075 .query_row(buffer_row, &self.buffer_snapshot)
16076 {
16077 is_foldable = true;
16078 match crease {
16079 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16080 if let Some(render_toggle) = render_toggle {
16081 let toggle_callback =
16082 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16083 if folded {
16084 editor.update(cx, |editor, cx| {
16085 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16086 });
16087 } else {
16088 editor.update(cx, |editor, cx| {
16089 editor.unfold_at(
16090 &crate::UnfoldAt { buffer_row },
16091 window,
16092 cx,
16093 )
16094 });
16095 }
16096 });
16097 return Some((render_toggle)(
16098 buffer_row,
16099 folded,
16100 toggle_callback,
16101 window,
16102 cx,
16103 ));
16104 }
16105 }
16106 }
16107 }
16108
16109 is_foldable |= self.starts_indent(buffer_row);
16110
16111 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16112 Some(
16113 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16114 .toggle_state(folded)
16115 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16116 if folded {
16117 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16118 } else {
16119 this.fold_at(&FoldAt { buffer_row }, window, cx);
16120 }
16121 }))
16122 .into_any_element(),
16123 )
16124 } else {
16125 None
16126 }
16127 }
16128
16129 pub fn render_crease_trailer(
16130 &self,
16131 buffer_row: MultiBufferRow,
16132 window: &mut Window,
16133 cx: &mut App,
16134 ) -> Option<AnyElement> {
16135 let folded = self.is_line_folded(buffer_row);
16136 if let Crease::Inline { render_trailer, .. } = self
16137 .crease_snapshot
16138 .query_row(buffer_row, &self.buffer_snapshot)?
16139 {
16140 let render_trailer = render_trailer.as_ref()?;
16141 Some(render_trailer(buffer_row, folded, window, cx))
16142 } else {
16143 None
16144 }
16145 }
16146}
16147
16148impl Deref for EditorSnapshot {
16149 type Target = DisplaySnapshot;
16150
16151 fn deref(&self) -> &Self::Target {
16152 &self.display_snapshot
16153 }
16154}
16155
16156#[derive(Clone, Debug, PartialEq, Eq)]
16157pub enum EditorEvent {
16158 InputIgnored {
16159 text: Arc<str>,
16160 },
16161 InputHandled {
16162 utf16_range_to_replace: Option<Range<isize>>,
16163 text: Arc<str>,
16164 },
16165 ExcerptsAdded {
16166 buffer: Entity<Buffer>,
16167 predecessor: ExcerptId,
16168 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16169 },
16170 ExcerptsRemoved {
16171 ids: Vec<ExcerptId>,
16172 },
16173 BufferFoldToggled {
16174 ids: Vec<ExcerptId>,
16175 folded: bool,
16176 },
16177 ExcerptsEdited {
16178 ids: Vec<ExcerptId>,
16179 },
16180 ExcerptsExpanded {
16181 ids: Vec<ExcerptId>,
16182 },
16183 BufferEdited,
16184 Edited {
16185 transaction_id: clock::Lamport,
16186 },
16187 Reparsed(BufferId),
16188 Focused,
16189 FocusedIn,
16190 Blurred,
16191 DirtyChanged,
16192 Saved,
16193 TitleChanged,
16194 DiffBaseChanged,
16195 SelectionsChanged {
16196 local: bool,
16197 },
16198 ScrollPositionChanged {
16199 local: bool,
16200 autoscroll: bool,
16201 },
16202 Closed,
16203 TransactionUndone {
16204 transaction_id: clock::Lamport,
16205 },
16206 TransactionBegun {
16207 transaction_id: clock::Lamport,
16208 },
16209 Reloaded,
16210 CursorShapeChanged,
16211}
16212
16213impl EventEmitter<EditorEvent> for Editor {}
16214
16215impl Focusable for Editor {
16216 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16217 self.focus_handle.clone()
16218 }
16219}
16220
16221impl Render for Editor {
16222 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16223 let settings = ThemeSettings::get_global(cx);
16224
16225 let mut text_style = match self.mode {
16226 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16227 color: cx.theme().colors().editor_foreground,
16228 font_family: settings.ui_font.family.clone(),
16229 font_features: settings.ui_font.features.clone(),
16230 font_fallbacks: settings.ui_font.fallbacks.clone(),
16231 font_size: rems(0.875).into(),
16232 font_weight: settings.ui_font.weight,
16233 line_height: relative(settings.buffer_line_height.value()),
16234 ..Default::default()
16235 },
16236 EditorMode::Full => TextStyle {
16237 color: cx.theme().colors().editor_foreground,
16238 font_family: settings.buffer_font.family.clone(),
16239 font_features: settings.buffer_font.features.clone(),
16240 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16241 font_size: settings.buffer_font_size(cx).into(),
16242 font_weight: settings.buffer_font.weight,
16243 line_height: relative(settings.buffer_line_height.value()),
16244 ..Default::default()
16245 },
16246 };
16247 if let Some(text_style_refinement) = &self.text_style_refinement {
16248 text_style.refine(text_style_refinement)
16249 }
16250
16251 let background = match self.mode {
16252 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16253 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16254 EditorMode::Full => cx.theme().colors().editor_background,
16255 };
16256
16257 EditorElement::new(
16258 &cx.entity(),
16259 EditorStyle {
16260 background,
16261 local_player: cx.theme().players().local(),
16262 text: text_style,
16263 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16264 syntax: cx.theme().syntax().clone(),
16265 status: cx.theme().status().clone(),
16266 inlay_hints_style: make_inlay_hints_style(cx),
16267 inline_completion_styles: make_suggestion_styles(cx),
16268 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16269 },
16270 )
16271 }
16272}
16273
16274impl EntityInputHandler for Editor {
16275 fn text_for_range(
16276 &mut self,
16277 range_utf16: Range<usize>,
16278 adjusted_range: &mut Option<Range<usize>>,
16279 _: &mut Window,
16280 cx: &mut Context<Self>,
16281 ) -> Option<String> {
16282 let snapshot = self.buffer.read(cx).read(cx);
16283 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16284 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16285 if (start.0..end.0) != range_utf16 {
16286 adjusted_range.replace(start.0..end.0);
16287 }
16288 Some(snapshot.text_for_range(start..end).collect())
16289 }
16290
16291 fn selected_text_range(
16292 &mut self,
16293 ignore_disabled_input: bool,
16294 _: &mut Window,
16295 cx: &mut Context<Self>,
16296 ) -> Option<UTF16Selection> {
16297 // Prevent the IME menu from appearing when holding down an alphabetic key
16298 // while input is disabled.
16299 if !ignore_disabled_input && !self.input_enabled {
16300 return None;
16301 }
16302
16303 let selection = self.selections.newest::<OffsetUtf16>(cx);
16304 let range = selection.range();
16305
16306 Some(UTF16Selection {
16307 range: range.start.0..range.end.0,
16308 reversed: selection.reversed,
16309 })
16310 }
16311
16312 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16313 let snapshot = self.buffer.read(cx).read(cx);
16314 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16315 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16316 }
16317
16318 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16319 self.clear_highlights::<InputComposition>(cx);
16320 self.ime_transaction.take();
16321 }
16322
16323 fn replace_text_in_range(
16324 &mut self,
16325 range_utf16: Option<Range<usize>>,
16326 text: &str,
16327 window: &mut Window,
16328 cx: &mut Context<Self>,
16329 ) {
16330 if !self.input_enabled {
16331 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16332 return;
16333 }
16334
16335 self.transact(window, cx, |this, window, cx| {
16336 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16337 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16338 Some(this.selection_replacement_ranges(range_utf16, cx))
16339 } else {
16340 this.marked_text_ranges(cx)
16341 };
16342
16343 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16344 let newest_selection_id = this.selections.newest_anchor().id;
16345 this.selections
16346 .all::<OffsetUtf16>(cx)
16347 .iter()
16348 .zip(ranges_to_replace.iter())
16349 .find_map(|(selection, range)| {
16350 if selection.id == newest_selection_id {
16351 Some(
16352 (range.start.0 as isize - selection.head().0 as isize)
16353 ..(range.end.0 as isize - selection.head().0 as isize),
16354 )
16355 } else {
16356 None
16357 }
16358 })
16359 });
16360
16361 cx.emit(EditorEvent::InputHandled {
16362 utf16_range_to_replace: range_to_replace,
16363 text: text.into(),
16364 });
16365
16366 if let Some(new_selected_ranges) = new_selected_ranges {
16367 this.change_selections(None, window, cx, |selections| {
16368 selections.select_ranges(new_selected_ranges)
16369 });
16370 this.backspace(&Default::default(), window, cx);
16371 }
16372
16373 this.handle_input(text, window, cx);
16374 });
16375
16376 if let Some(transaction) = self.ime_transaction {
16377 self.buffer.update(cx, |buffer, cx| {
16378 buffer.group_until_transaction(transaction, cx);
16379 });
16380 }
16381
16382 self.unmark_text(window, cx);
16383 }
16384
16385 fn replace_and_mark_text_in_range(
16386 &mut self,
16387 range_utf16: Option<Range<usize>>,
16388 text: &str,
16389 new_selected_range_utf16: Option<Range<usize>>,
16390 window: &mut Window,
16391 cx: &mut Context<Self>,
16392 ) {
16393 if !self.input_enabled {
16394 return;
16395 }
16396
16397 let transaction = self.transact(window, cx, |this, window, cx| {
16398 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16399 let snapshot = this.buffer.read(cx).read(cx);
16400 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16401 for marked_range in &mut marked_ranges {
16402 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16403 marked_range.start.0 += relative_range_utf16.start;
16404 marked_range.start =
16405 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16406 marked_range.end =
16407 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16408 }
16409 }
16410 Some(marked_ranges)
16411 } else if let Some(range_utf16) = range_utf16 {
16412 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16413 Some(this.selection_replacement_ranges(range_utf16, cx))
16414 } else {
16415 None
16416 };
16417
16418 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16419 let newest_selection_id = this.selections.newest_anchor().id;
16420 this.selections
16421 .all::<OffsetUtf16>(cx)
16422 .iter()
16423 .zip(ranges_to_replace.iter())
16424 .find_map(|(selection, range)| {
16425 if selection.id == newest_selection_id {
16426 Some(
16427 (range.start.0 as isize - selection.head().0 as isize)
16428 ..(range.end.0 as isize - selection.head().0 as isize),
16429 )
16430 } else {
16431 None
16432 }
16433 })
16434 });
16435
16436 cx.emit(EditorEvent::InputHandled {
16437 utf16_range_to_replace: range_to_replace,
16438 text: text.into(),
16439 });
16440
16441 if let Some(ranges) = ranges_to_replace {
16442 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16443 }
16444
16445 let marked_ranges = {
16446 let snapshot = this.buffer.read(cx).read(cx);
16447 this.selections
16448 .disjoint_anchors()
16449 .iter()
16450 .map(|selection| {
16451 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16452 })
16453 .collect::<Vec<_>>()
16454 };
16455
16456 if text.is_empty() {
16457 this.unmark_text(window, cx);
16458 } else {
16459 this.highlight_text::<InputComposition>(
16460 marked_ranges.clone(),
16461 HighlightStyle {
16462 underline: Some(UnderlineStyle {
16463 thickness: px(1.),
16464 color: None,
16465 wavy: false,
16466 }),
16467 ..Default::default()
16468 },
16469 cx,
16470 );
16471 }
16472
16473 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16474 let use_autoclose = this.use_autoclose;
16475 let use_auto_surround = this.use_auto_surround;
16476 this.set_use_autoclose(false);
16477 this.set_use_auto_surround(false);
16478 this.handle_input(text, window, cx);
16479 this.set_use_autoclose(use_autoclose);
16480 this.set_use_auto_surround(use_auto_surround);
16481
16482 if let Some(new_selected_range) = new_selected_range_utf16 {
16483 let snapshot = this.buffer.read(cx).read(cx);
16484 let new_selected_ranges = marked_ranges
16485 .into_iter()
16486 .map(|marked_range| {
16487 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16488 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16489 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16490 snapshot.clip_offset_utf16(new_start, Bias::Left)
16491 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16492 })
16493 .collect::<Vec<_>>();
16494
16495 drop(snapshot);
16496 this.change_selections(None, window, cx, |selections| {
16497 selections.select_ranges(new_selected_ranges)
16498 });
16499 }
16500 });
16501
16502 self.ime_transaction = self.ime_transaction.or(transaction);
16503 if let Some(transaction) = self.ime_transaction {
16504 self.buffer.update(cx, |buffer, cx| {
16505 buffer.group_until_transaction(transaction, cx);
16506 });
16507 }
16508
16509 if self.text_highlights::<InputComposition>(cx).is_none() {
16510 self.ime_transaction.take();
16511 }
16512 }
16513
16514 fn bounds_for_range(
16515 &mut self,
16516 range_utf16: Range<usize>,
16517 element_bounds: gpui::Bounds<Pixels>,
16518 window: &mut Window,
16519 cx: &mut Context<Self>,
16520 ) -> Option<gpui::Bounds<Pixels>> {
16521 let text_layout_details = self.text_layout_details(window);
16522 let gpui::Size {
16523 width: em_width,
16524 height: line_height,
16525 } = self.character_size(window);
16526
16527 let snapshot = self.snapshot(window, cx);
16528 let scroll_position = snapshot.scroll_position();
16529 let scroll_left = scroll_position.x * em_width;
16530
16531 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16532 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16533 + self.gutter_dimensions.width
16534 + self.gutter_dimensions.margin;
16535 let y = line_height * (start.row().as_f32() - scroll_position.y);
16536
16537 Some(Bounds {
16538 origin: element_bounds.origin + point(x, y),
16539 size: size(em_width, line_height),
16540 })
16541 }
16542
16543 fn character_index_for_point(
16544 &mut self,
16545 point: gpui::Point<Pixels>,
16546 _window: &mut Window,
16547 _cx: &mut Context<Self>,
16548 ) -> Option<usize> {
16549 let position_map = self.last_position_map.as_ref()?;
16550 if !position_map.text_hitbox.contains(&point) {
16551 return None;
16552 }
16553 let display_point = position_map.point_for_position(point).previous_valid;
16554 let anchor = position_map
16555 .snapshot
16556 .display_point_to_anchor(display_point, Bias::Left);
16557 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16558 Some(utf16_offset.0)
16559 }
16560}
16561
16562trait SelectionExt {
16563 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16564 fn spanned_rows(
16565 &self,
16566 include_end_if_at_line_start: bool,
16567 map: &DisplaySnapshot,
16568 ) -> Range<MultiBufferRow>;
16569}
16570
16571impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16572 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16573 let start = self
16574 .start
16575 .to_point(&map.buffer_snapshot)
16576 .to_display_point(map);
16577 let end = self
16578 .end
16579 .to_point(&map.buffer_snapshot)
16580 .to_display_point(map);
16581 if self.reversed {
16582 end..start
16583 } else {
16584 start..end
16585 }
16586 }
16587
16588 fn spanned_rows(
16589 &self,
16590 include_end_if_at_line_start: bool,
16591 map: &DisplaySnapshot,
16592 ) -> Range<MultiBufferRow> {
16593 let start = self.start.to_point(&map.buffer_snapshot);
16594 let mut end = self.end.to_point(&map.buffer_snapshot);
16595 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16596 end.row -= 1;
16597 }
16598
16599 let buffer_start = map.prev_line_boundary(start).0;
16600 let buffer_end = map.next_line_boundary(end).0;
16601 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16602 }
16603}
16604
16605impl<T: InvalidationRegion> InvalidationStack<T> {
16606 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16607 where
16608 S: Clone + ToOffset,
16609 {
16610 while let Some(region) = self.last() {
16611 let all_selections_inside_invalidation_ranges =
16612 if selections.len() == region.ranges().len() {
16613 selections
16614 .iter()
16615 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16616 .all(|(selection, invalidation_range)| {
16617 let head = selection.head().to_offset(buffer);
16618 invalidation_range.start <= head && invalidation_range.end >= head
16619 })
16620 } else {
16621 false
16622 };
16623
16624 if all_selections_inside_invalidation_ranges {
16625 break;
16626 } else {
16627 self.pop();
16628 }
16629 }
16630 }
16631}
16632
16633impl<T> Default for InvalidationStack<T> {
16634 fn default() -> Self {
16635 Self(Default::default())
16636 }
16637}
16638
16639impl<T> Deref for InvalidationStack<T> {
16640 type Target = Vec<T>;
16641
16642 fn deref(&self) -> &Self::Target {
16643 &self.0
16644 }
16645}
16646
16647impl<T> DerefMut for InvalidationStack<T> {
16648 fn deref_mut(&mut self) -> &mut Self::Target {
16649 &mut self.0
16650 }
16651}
16652
16653impl InvalidationRegion for SnippetState {
16654 fn ranges(&self) -> &[Range<Anchor>] {
16655 &self.ranges[self.active_index]
16656 }
16657}
16658
16659pub fn diagnostic_block_renderer(
16660 diagnostic: Diagnostic,
16661 max_message_rows: Option<u8>,
16662 allow_closing: bool,
16663 _is_valid: bool,
16664) -> RenderBlock {
16665 let (text_without_backticks, code_ranges) =
16666 highlight_diagnostic_message(&diagnostic, max_message_rows);
16667
16668 Arc::new(move |cx: &mut BlockContext| {
16669 let group_id: SharedString = cx.block_id.to_string().into();
16670
16671 let mut text_style = cx.window.text_style().clone();
16672 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16673 let theme_settings = ThemeSettings::get_global(cx);
16674 text_style.font_family = theme_settings.buffer_font.family.clone();
16675 text_style.font_style = theme_settings.buffer_font.style;
16676 text_style.font_features = theme_settings.buffer_font.features.clone();
16677 text_style.font_weight = theme_settings.buffer_font.weight;
16678
16679 let multi_line_diagnostic = diagnostic.message.contains('\n');
16680
16681 let buttons = |diagnostic: &Diagnostic| {
16682 if multi_line_diagnostic {
16683 v_flex()
16684 } else {
16685 h_flex()
16686 }
16687 .when(allow_closing, |div| {
16688 div.children(diagnostic.is_primary.then(|| {
16689 IconButton::new("close-block", IconName::XCircle)
16690 .icon_color(Color::Muted)
16691 .size(ButtonSize::Compact)
16692 .style(ButtonStyle::Transparent)
16693 .visible_on_hover(group_id.clone())
16694 .on_click(move |_click, window, cx| {
16695 window.dispatch_action(Box::new(Cancel), cx)
16696 })
16697 .tooltip(|window, cx| {
16698 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16699 })
16700 }))
16701 })
16702 .child(
16703 IconButton::new("copy-block", IconName::Copy)
16704 .icon_color(Color::Muted)
16705 .size(ButtonSize::Compact)
16706 .style(ButtonStyle::Transparent)
16707 .visible_on_hover(group_id.clone())
16708 .on_click({
16709 let message = diagnostic.message.clone();
16710 move |_click, _, cx| {
16711 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16712 }
16713 })
16714 .tooltip(Tooltip::text("Copy diagnostic message")),
16715 )
16716 };
16717
16718 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16719 AvailableSpace::min_size(),
16720 cx.window,
16721 cx.app,
16722 );
16723
16724 h_flex()
16725 .id(cx.block_id)
16726 .group(group_id.clone())
16727 .relative()
16728 .size_full()
16729 .block_mouse_down()
16730 .pl(cx.gutter_dimensions.width)
16731 .w(cx.max_width - cx.gutter_dimensions.full_width())
16732 .child(
16733 div()
16734 .flex()
16735 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16736 .flex_shrink(),
16737 )
16738 .child(buttons(&diagnostic))
16739 .child(div().flex().flex_shrink_0().child(
16740 StyledText::new(text_without_backticks.clone()).with_highlights(
16741 &text_style,
16742 code_ranges.iter().map(|range| {
16743 (
16744 range.clone(),
16745 HighlightStyle {
16746 font_weight: Some(FontWeight::BOLD),
16747 ..Default::default()
16748 },
16749 )
16750 }),
16751 ),
16752 ))
16753 .into_any_element()
16754 })
16755}
16756
16757fn inline_completion_edit_text(
16758 current_snapshot: &BufferSnapshot,
16759 edits: &[(Range<Anchor>, String)],
16760 edit_preview: &EditPreview,
16761 include_deletions: bool,
16762 cx: &App,
16763) -> HighlightedText {
16764 let edits = edits
16765 .iter()
16766 .map(|(anchor, text)| {
16767 (
16768 anchor.start.text_anchor..anchor.end.text_anchor,
16769 text.clone(),
16770 )
16771 })
16772 .collect::<Vec<_>>();
16773
16774 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16775}
16776
16777pub fn highlight_diagnostic_message(
16778 diagnostic: &Diagnostic,
16779 mut max_message_rows: Option<u8>,
16780) -> (SharedString, Vec<Range<usize>>) {
16781 let mut text_without_backticks = String::new();
16782 let mut code_ranges = Vec::new();
16783
16784 if let Some(source) = &diagnostic.source {
16785 text_without_backticks.push_str(source);
16786 code_ranges.push(0..source.len());
16787 text_without_backticks.push_str(": ");
16788 }
16789
16790 let mut prev_offset = 0;
16791 let mut in_code_block = false;
16792 let has_row_limit = max_message_rows.is_some();
16793 let mut newline_indices = diagnostic
16794 .message
16795 .match_indices('\n')
16796 .filter(|_| has_row_limit)
16797 .map(|(ix, _)| ix)
16798 .fuse()
16799 .peekable();
16800
16801 for (quote_ix, _) in diagnostic
16802 .message
16803 .match_indices('`')
16804 .chain([(diagnostic.message.len(), "")])
16805 {
16806 let mut first_newline_ix = None;
16807 let mut last_newline_ix = None;
16808 while let Some(newline_ix) = newline_indices.peek() {
16809 if *newline_ix < quote_ix {
16810 if first_newline_ix.is_none() {
16811 first_newline_ix = Some(*newline_ix);
16812 }
16813 last_newline_ix = Some(*newline_ix);
16814
16815 if let Some(rows_left) = &mut max_message_rows {
16816 if *rows_left == 0 {
16817 break;
16818 } else {
16819 *rows_left -= 1;
16820 }
16821 }
16822 let _ = newline_indices.next();
16823 } else {
16824 break;
16825 }
16826 }
16827 let prev_len = text_without_backticks.len();
16828 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16829 text_without_backticks.push_str(new_text);
16830 if in_code_block {
16831 code_ranges.push(prev_len..text_without_backticks.len());
16832 }
16833 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16834 in_code_block = !in_code_block;
16835 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16836 text_without_backticks.push_str("...");
16837 break;
16838 }
16839 }
16840
16841 (text_without_backticks.into(), code_ranges)
16842}
16843
16844fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16845 match severity {
16846 DiagnosticSeverity::ERROR => colors.error,
16847 DiagnosticSeverity::WARNING => colors.warning,
16848 DiagnosticSeverity::INFORMATION => colors.info,
16849 DiagnosticSeverity::HINT => colors.info,
16850 _ => colors.ignored,
16851 }
16852}
16853
16854pub fn styled_runs_for_code_label<'a>(
16855 label: &'a CodeLabel,
16856 syntax_theme: &'a theme::SyntaxTheme,
16857) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16858 let fade_out = HighlightStyle {
16859 fade_out: Some(0.35),
16860 ..Default::default()
16861 };
16862
16863 let mut prev_end = label.filter_range.end;
16864 label
16865 .runs
16866 .iter()
16867 .enumerate()
16868 .flat_map(move |(ix, (range, highlight_id))| {
16869 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16870 style
16871 } else {
16872 return Default::default();
16873 };
16874 let mut muted_style = style;
16875 muted_style.highlight(fade_out);
16876
16877 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16878 if range.start >= label.filter_range.end {
16879 if range.start > prev_end {
16880 runs.push((prev_end..range.start, fade_out));
16881 }
16882 runs.push((range.clone(), muted_style));
16883 } else if range.end <= label.filter_range.end {
16884 runs.push((range.clone(), style));
16885 } else {
16886 runs.push((range.start..label.filter_range.end, style));
16887 runs.push((label.filter_range.end..range.end, muted_style));
16888 }
16889 prev_end = cmp::max(prev_end, range.end);
16890
16891 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16892 runs.push((prev_end..label.text.len(), fade_out));
16893 }
16894
16895 runs
16896 })
16897}
16898
16899pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16900 let mut prev_index = 0;
16901 let mut prev_codepoint: Option<char> = None;
16902 text.char_indices()
16903 .chain([(text.len(), '\0')])
16904 .filter_map(move |(index, codepoint)| {
16905 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16906 let is_boundary = index == text.len()
16907 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16908 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16909 if is_boundary {
16910 let chunk = &text[prev_index..index];
16911 prev_index = index;
16912 Some(chunk)
16913 } else {
16914 None
16915 }
16916 })
16917}
16918
16919pub trait RangeToAnchorExt: Sized {
16920 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16921
16922 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16923 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16924 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16925 }
16926}
16927
16928impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16929 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16930 let start_offset = self.start.to_offset(snapshot);
16931 let end_offset = self.end.to_offset(snapshot);
16932 if start_offset == end_offset {
16933 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16934 } else {
16935 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16936 }
16937 }
16938}
16939
16940pub trait RowExt {
16941 fn as_f32(&self) -> f32;
16942
16943 fn next_row(&self) -> Self;
16944
16945 fn previous_row(&self) -> Self;
16946
16947 fn minus(&self, other: Self) -> u32;
16948}
16949
16950impl RowExt for DisplayRow {
16951 fn as_f32(&self) -> f32 {
16952 self.0 as f32
16953 }
16954
16955 fn next_row(&self) -> Self {
16956 Self(self.0 + 1)
16957 }
16958
16959 fn previous_row(&self) -> Self {
16960 Self(self.0.saturating_sub(1))
16961 }
16962
16963 fn minus(&self, other: Self) -> u32 {
16964 self.0 - other.0
16965 }
16966}
16967
16968impl RowExt for MultiBufferRow {
16969 fn as_f32(&self) -> f32 {
16970 self.0 as f32
16971 }
16972
16973 fn next_row(&self) -> Self {
16974 Self(self.0 + 1)
16975 }
16976
16977 fn previous_row(&self) -> Self {
16978 Self(self.0.saturating_sub(1))
16979 }
16980
16981 fn minus(&self, other: Self) -> u32 {
16982 self.0 - other.0
16983 }
16984}
16985
16986trait RowRangeExt {
16987 type Row;
16988
16989 fn len(&self) -> usize;
16990
16991 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16992}
16993
16994impl RowRangeExt for Range<MultiBufferRow> {
16995 type Row = MultiBufferRow;
16996
16997 fn len(&self) -> usize {
16998 (self.end.0 - self.start.0) as usize
16999 }
17000
17001 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17002 (self.start.0..self.end.0).map(MultiBufferRow)
17003 }
17004}
17005
17006impl RowRangeExt for Range<DisplayRow> {
17007 type Row = DisplayRow;
17008
17009 fn len(&self) -> usize {
17010 (self.end.0 - self.start.0) as usize
17011 }
17012
17013 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17014 (self.start.0..self.end.0).map(DisplayRow)
17015 }
17016}
17017
17018/// If select range has more than one line, we
17019/// just point the cursor to range.start.
17020fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17021 if range.start.row == range.end.row {
17022 range
17023 } else {
17024 range.start..range.start
17025 }
17026}
17027pub struct KillRing(ClipboardItem);
17028impl Global for KillRing {}
17029
17030const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17031
17032fn all_edits_insertions_or_deletions(
17033 edits: &Vec<(Range<Anchor>, String)>,
17034 snapshot: &MultiBufferSnapshot,
17035) -> bool {
17036 let mut all_insertions = true;
17037 let mut all_deletions = true;
17038
17039 for (range, new_text) in edits.iter() {
17040 let range_is_empty = range.to_offset(&snapshot).is_empty();
17041 let text_is_empty = new_text.is_empty();
17042
17043 if range_is_empty != text_is_empty {
17044 if range_is_empty {
17045 all_deletions = false;
17046 } else {
17047 all_insertions = false;
17048 }
17049 } else {
17050 return false;
17051 }
17052
17053 if !all_insertions && !all_deletions {
17054 return false;
17055 }
17056 }
17057 all_insertions || all_deletions
17058}