1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use ::git::{status::FileStatus, Restore};
77use code_context_menus::{
78 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
79 CompletionsMenu, ContextMenuOrigin,
80};
81use git::blame::GitBlame;
82use gpui::{
83 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
84 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
85 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
86 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
87 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
88 ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
89 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
90 WeakEntity, WeakFocusHandle, Window,
91};
92use highlight_matching_bracket::refresh_matching_bracket_highlights;
93use hover_popover::{hide_hover, HoverState};
94use indent_guides::ActiveIndentGuidesState;
95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
96pub use inline_completion::Direction;
97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
98pub use items::MAX_TAB_TITLE_LEN;
99use itertools::Itertools;
100use language::{
101 language_settings::{
102 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
103 },
104 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
105 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState,
106 EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
107 OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
108};
109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
110use linked_editing_ranges::refresh_linked_ranges;
111use mouse_context_menu::MouseContextMenu;
112use persistence::DB;
113pub use proposed_changes_editor::{
114 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
115};
116use smallvec::smallvec;
117use std::iter::Peekable;
118use task::{ResolvedTask, TaskTemplate, TaskVariables};
119
120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
121pub use lsp::CompletionContext;
122use lsp::{
123 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
124 LanguageServerId, LanguageServerName,
125};
126
127use language::BufferSnapshot;
128use movement::TextLayoutDetails;
129pub use multi_buffer::{
130 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
131 ToOffset, ToPoint,
132};
133use multi_buffer::{
134 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
135 ToOffsetUtf16,
136};
137use project::{
138 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
139 project_settings::{GitGutterSetting, ProjectSettings},
140 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
141 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
142};
143use rand::prelude::*;
144use rpc::{proto::*, ErrorExt};
145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
146use selections_collection::{
147 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
148};
149use serde::{Deserialize, Serialize};
150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
151use smallvec::SmallVec;
152use snippet::Snippet;
153use std::{
154 any::TypeId,
155 borrow::Cow,
156 cell::RefCell,
157 cmp::{self, Ordering, Reverse},
158 mem,
159 num::NonZeroU32,
160 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
161 path::{Path, PathBuf},
162 rc::Rc,
163 sync::Arc,
164 time::{Duration, Instant},
165};
166pub use sum_tree::Bias;
167use sum_tree::TreeMap;
168use text::{BufferId, OffsetUtf16, Rope};
169use theme::{
170 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
171 ThemeColors, ThemeSettings,
172};
173use ui::{
174 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
175 Tooltip,
176};
177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
178use workspace::{
179 item::{ItemHandle, PreviewTabsSettings},
180 ItemId, RestoreOnStartupBehavior,
181};
182use workspace::{
183 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
184 WorkspaceSettings,
185};
186use workspace::{
187 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
188};
189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
190
191use crate::hover_links::{find_url, find_url_from_range};
192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
193
194pub const FILE_HEADER_HEIGHT: u32 = 2;
195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
199const MAX_LINE_LEN: usize = 1024;
200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
203#[doc(hidden)]
204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
205
206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
208
209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
211
212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
213 alt: true,
214 shift: true,
215 control: false,
216 platform: false,
217 function: false,
218};
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum InlayId {
222 InlineCompletion(usize),
223 Hint(usize),
224}
225
226impl InlayId {
227 fn id(&self) -> usize {
228 match self {
229 Self::InlineCompletion(id) => *id,
230 Self::Hint(id) => *id,
231 }
232 }
233}
234
235enum DocumentHighlightRead {}
236enum DocumentHighlightWrite {}
237enum InputComposition {}
238enum SelectedTextHighlight {}
239
240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
241pub enum Navigated {
242 Yes,
243 No,
244}
245
246impl Navigated {
247 pub fn from_bool(yes: bool) -> Navigated {
248 if yes {
249 Navigated::Yes
250 } else {
251 Navigated::No
252 }
253 }
254}
255
256pub fn init_settings(cx: &mut App) {
257 EditorSettings::register(cx);
258}
259
260pub fn init(cx: &mut App) {
261 init_settings(cx);
262
263 workspace::register_project_item::<Editor>(cx);
264 workspace::FollowableViewRegistry::register::<Editor>(cx);
265 workspace::register_serializable_item::<Editor>(cx);
266
267 cx.observe_new(
268 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
269 workspace.register_action(Editor::new_file);
270 workspace.register_action(Editor::new_file_vertical);
271 workspace.register_action(Editor::new_file_horizontal);
272 workspace.register_action(Editor::cancel_language_server_work);
273 },
274 )
275 .detach();
276
277 cx.on_action(move |_: &workspace::NewFile, cx| {
278 let app_state = workspace::AppState::global(cx);
279 if let Some(app_state) = app_state.upgrade() {
280 workspace::open_new(
281 Default::default(),
282 app_state,
283 cx,
284 |workspace, window, cx| {
285 Editor::new_file(workspace, &Default::default(), window, cx)
286 },
287 )
288 .detach();
289 }
290 });
291 cx.on_action(move |_: &workspace::NewWindow, cx| {
292 let app_state = workspace::AppState::global(cx);
293 if let Some(app_state) = app_state.upgrade() {
294 workspace::open_new(
295 Default::default(),
296 app_state,
297 cx,
298 |workspace, window, cx| {
299 cx.activate(true);
300 Editor::new_file(workspace, &Default::default(), window, cx)
301 },
302 )
303 .detach();
304 }
305 });
306}
307
308pub struct SearchWithinRange;
309
310trait InvalidationRegion {
311 fn ranges(&self) -> &[Range<Anchor>];
312}
313
314#[derive(Clone, Debug, PartialEq)]
315pub enum SelectPhase {
316 Begin {
317 position: DisplayPoint,
318 add: bool,
319 click_count: usize,
320 },
321 BeginColumnar {
322 position: DisplayPoint,
323 reset: bool,
324 goal_column: u32,
325 },
326 Extend {
327 position: DisplayPoint,
328 click_count: usize,
329 },
330 Update {
331 position: DisplayPoint,
332 goal_column: u32,
333 scroll_delta: gpui::Point<f32>,
334 },
335 End,
336}
337
338#[derive(Clone, Debug)]
339pub enum SelectMode {
340 Character,
341 Word(Range<Anchor>),
342 Line(Range<Anchor>),
343 All,
344}
345
346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
347pub enum EditorMode {
348 SingleLine { auto_width: bool },
349 AutoHeight { max_lines: usize },
350 Full,
351}
352
353#[derive(Copy, Clone, Debug)]
354pub enum SoftWrap {
355 /// Prefer not to wrap at all.
356 ///
357 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
358 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
359 GitDiff,
360 /// Prefer a single line generally, unless an overly long line is encountered.
361 None,
362 /// Soft wrap lines that exceed the editor width.
363 EditorWidth,
364 /// Soft wrap lines at the preferred line length.
365 Column(u32),
366 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
367 Bounded(u32),
368}
369
370#[derive(Clone)]
371pub struct EditorStyle {
372 pub background: Hsla,
373 pub local_player: PlayerColor,
374 pub text: TextStyle,
375 pub scrollbar_width: Pixels,
376 pub syntax: Arc<SyntaxTheme>,
377 pub status: StatusColors,
378 pub inlay_hints_style: HighlightStyle,
379 pub inline_completion_styles: InlineCompletionStyles,
380 pub unnecessary_code_fade: f32,
381}
382
383impl Default for EditorStyle {
384 fn default() -> Self {
385 Self {
386 background: Hsla::default(),
387 local_player: PlayerColor::default(),
388 text: TextStyle::default(),
389 scrollbar_width: Pixels::default(),
390 syntax: Default::default(),
391 // HACK: Status colors don't have a real default.
392 // We should look into removing the status colors from the editor
393 // style and retrieve them directly from the theme.
394 status: StatusColors::dark(),
395 inlay_hints_style: HighlightStyle::default(),
396 inline_completion_styles: InlineCompletionStyles {
397 insertion: HighlightStyle::default(),
398 whitespace: HighlightStyle::default(),
399 },
400 unnecessary_code_fade: Default::default(),
401 }
402 }
403}
404
405pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
406 let show_background = language_settings::language_settings(None, None, cx)
407 .inlay_hints
408 .show_background;
409
410 HighlightStyle {
411 color: Some(cx.theme().status().hint),
412 background_color: show_background.then(|| cx.theme().status().hint_background),
413 ..HighlightStyle::default()
414 }
415}
416
417pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
418 InlineCompletionStyles {
419 insertion: HighlightStyle {
420 color: Some(cx.theme().status().predictive),
421 ..HighlightStyle::default()
422 },
423 whitespace: HighlightStyle {
424 background_color: Some(cx.theme().status().created_background),
425 ..HighlightStyle::default()
426 },
427 }
428}
429
430type CompletionId = usize;
431
432pub(crate) enum EditDisplayMode {
433 TabAccept,
434 DiffPopover,
435 Inline,
436}
437
438enum InlineCompletion {
439 Edit {
440 edits: Vec<(Range<Anchor>, String)>,
441 edit_preview: Option<EditPreview>,
442 display_mode: EditDisplayMode,
443 snapshot: BufferSnapshot,
444 },
445 Move {
446 target: Anchor,
447 snapshot: BufferSnapshot,
448 },
449}
450
451struct InlineCompletionState {
452 inlay_ids: Vec<InlayId>,
453 completion: InlineCompletion,
454 completion_id: Option<SharedString>,
455 invalidation_range: Range<Anchor>,
456}
457
458enum EditPredictionSettings {
459 Disabled,
460 Enabled {
461 show_in_menu: bool,
462 preview_requires_modifier: bool,
463 },
464}
465
466enum InlineCompletionHighlight {}
467
468#[derive(Debug, Clone)]
469struct InlineDiagnostic {
470 message: SharedString,
471 group_id: usize,
472 is_primary: bool,
473 start: Point,
474 severity: DiagnosticSeverity,
475}
476
477pub enum MenuInlineCompletionsPolicy {
478 Never,
479 ByProvider,
480}
481
482pub enum EditPredictionPreview {
483 /// Modifier is not pressed
484 Inactive,
485 /// Modifier pressed
486 Active {
487 previous_scroll_position: Option<ScrollAnchor>,
488 },
489}
490
491#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
492struct EditorActionId(usize);
493
494impl EditorActionId {
495 pub fn post_inc(&mut self) -> Self {
496 let answer = self.0;
497
498 *self = Self(answer + 1);
499
500 Self(answer)
501 }
502}
503
504// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
505// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
506
507type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
508type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
509
510#[derive(Default)]
511struct ScrollbarMarkerState {
512 scrollbar_size: Size<Pixels>,
513 dirty: bool,
514 markers: Arc<[PaintQuad]>,
515 pending_refresh: Option<Task<Result<()>>>,
516}
517
518impl ScrollbarMarkerState {
519 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
520 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
521 }
522}
523
524#[derive(Clone, Debug)]
525struct RunnableTasks {
526 templates: Vec<(TaskSourceKind, TaskTemplate)>,
527 offset: multi_buffer::Anchor,
528 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
529 column: u32,
530 // Values of all named captures, including those starting with '_'
531 extra_variables: HashMap<String, String>,
532 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
533 context_range: Range<BufferOffset>,
534}
535
536impl RunnableTasks {
537 fn resolve<'a>(
538 &'a self,
539 cx: &'a task::TaskContext,
540 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
541 self.templates.iter().filter_map(|(kind, template)| {
542 template
543 .resolve_task(&kind.to_id_base(), cx)
544 .map(|task| (kind.clone(), task))
545 })
546 }
547}
548
549#[derive(Clone)]
550struct ResolvedTasks {
551 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
552 position: Anchor,
553}
554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
555struct BufferOffset(usize);
556
557// Addons allow storing per-editor state in other crates (e.g. Vim)
558pub trait Addon: 'static {
559 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
560
561 fn render_buffer_header_controls(
562 &self,
563 _: &ExcerptInfo,
564 _: &Window,
565 _: &App,
566 ) -> Option<AnyElement> {
567 None
568 }
569
570 fn to_any(&self) -> &dyn std::any::Any;
571}
572
573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
574pub enum IsVimMode {
575 Yes,
576 No,
577}
578
579/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
580///
581/// See the [module level documentation](self) for more information.
582pub struct Editor {
583 focus_handle: FocusHandle,
584 last_focused_descendant: Option<WeakFocusHandle>,
585 /// The text buffer being edited
586 buffer: Entity<MultiBuffer>,
587 /// Map of how text in the buffer should be displayed.
588 /// Handles soft wraps, folds, fake inlay text insertions, etc.
589 pub display_map: Entity<DisplayMap>,
590 pub selections: SelectionsCollection,
591 pub scroll_manager: ScrollManager,
592 /// When inline assist editors are linked, they all render cursors because
593 /// typing enters text into each of them, even the ones that aren't focused.
594 pub(crate) show_cursor_when_unfocused: bool,
595 columnar_selection_tail: Option<Anchor>,
596 add_selections_state: Option<AddSelectionsState>,
597 select_next_state: Option<SelectNextState>,
598 select_prev_state: Option<SelectNextState>,
599 selection_history: SelectionHistory,
600 autoclose_regions: Vec<AutocloseRegion>,
601 snippet_stack: InvalidationStack<SnippetState>,
602 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
603 ime_transaction: Option<TransactionId>,
604 active_diagnostics: Option<ActiveDiagnosticGroup>,
605 show_inline_diagnostics: bool,
606 inline_diagnostics_update: Task<()>,
607 inline_diagnostics_enabled: bool,
608 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
609 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
610
611 // TODO: make this a access method
612 pub project: Option<Entity<Project>>,
613 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
614 completion_provider: Option<Box<dyn CompletionProvider>>,
615 collaboration_hub: Option<Box<dyn CollaborationHub>>,
616 blink_manager: Entity<BlinkManager>,
617 show_cursor_names: bool,
618 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
619 pub show_local_selections: bool,
620 mode: EditorMode,
621 show_breadcrumbs: bool,
622 show_gutter: bool,
623 show_scrollbars: bool,
624 show_line_numbers: Option<bool>,
625 use_relative_line_numbers: Option<bool>,
626 show_git_diff_gutter: Option<bool>,
627 show_code_actions: Option<bool>,
628 show_runnables: Option<bool>,
629 show_wrap_guides: Option<bool>,
630 show_indent_guides: Option<bool>,
631 placeholder_text: Option<Arc<str>>,
632 highlight_order: usize,
633 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
634 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
635 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
636 scrollbar_marker_state: ScrollbarMarkerState,
637 active_indent_guides_state: ActiveIndentGuidesState,
638 nav_history: Option<ItemNavHistory>,
639 context_menu: RefCell<Option<CodeContextMenu>>,
640 mouse_context_menu: Option<MouseContextMenu>,
641 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
642 signature_help_state: SignatureHelpState,
643 auto_signature_help: Option<bool>,
644 find_all_references_task_sources: Vec<Anchor>,
645 next_completion_id: CompletionId,
646 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
647 code_actions_task: Option<Task<Result<()>>>,
648 selection_highlight_task: Option<Task<()>>,
649 document_highlights_task: Option<Task<()>>,
650 linked_editing_range_task: Option<Task<Option<()>>>,
651 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
652 pending_rename: Option<RenameState>,
653 searchable: bool,
654 cursor_shape: CursorShape,
655 current_line_highlight: Option<CurrentLineHighlight>,
656 collapse_matches: bool,
657 autoindent_mode: Option<AutoindentMode>,
658 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
659 input_enabled: bool,
660 use_modal_editing: bool,
661 read_only: bool,
662 leader_peer_id: Option<PeerId>,
663 remote_id: Option<ViewId>,
664 hover_state: HoverState,
665 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
666 gutter_hovered: bool,
667 hovered_link_state: Option<HoveredLinkState>,
668 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
669 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
670 active_inline_completion: Option<InlineCompletionState>,
671 /// Used to prevent flickering as the user types while the menu is open
672 stale_inline_completion_in_menu: Option<InlineCompletionState>,
673 edit_prediction_settings: EditPredictionSettings,
674 inline_completions_hidden_for_vim_mode: bool,
675 show_inline_completions_override: Option<bool>,
676 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
677 edit_prediction_preview: EditPredictionPreview,
678 edit_prediction_indent_conflict: bool,
679 edit_prediction_requires_modifier_in_indent_conflict: bool,
680 inlay_hint_cache: InlayHintCache,
681 next_inlay_id: usize,
682 _subscriptions: Vec<Subscription>,
683 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
684 gutter_dimensions: GutterDimensions,
685 style: Option<EditorStyle>,
686 text_style_refinement: Option<TextStyleRefinement>,
687 next_editor_action_id: EditorActionId,
688 editor_actions:
689 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
690 use_autoclose: bool,
691 use_auto_surround: bool,
692 auto_replace_emoji_shortcode: bool,
693 show_git_blame_gutter: bool,
694 show_git_blame_inline: bool,
695 show_git_blame_inline_delay_task: Option<Task<()>>,
696 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
697 git_blame_inline_enabled: bool,
698 serialize_dirty_buffers: bool,
699 show_selection_menu: Option<bool>,
700 blame: Option<Entity<GitBlame>>,
701 blame_subscription: Option<Subscription>,
702 custom_context_menu: Option<
703 Box<
704 dyn 'static
705 + Fn(
706 &mut Self,
707 DisplayPoint,
708 &mut Window,
709 &mut Context<Self>,
710 ) -> Option<Entity<ui::ContextMenu>>,
711 >,
712 >,
713 last_bounds: Option<Bounds<Pixels>>,
714 last_position_map: Option<Rc<PositionMap>>,
715 expect_bounds_change: Option<Bounds<Pixels>>,
716 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
717 tasks_update_task: Option<Task<()>>,
718 in_project_search: bool,
719 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
720 breadcrumb_header: Option<String>,
721 focused_block: Option<FocusedBlock>,
722 next_scroll_position: NextScrollCursorCenterTopBottom,
723 addons: HashMap<TypeId, Box<dyn Addon>>,
724 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
725 load_diff_task: Option<Shared<Task<()>>>,
726 selection_mark_mode: bool,
727 toggle_fold_multiple_buffers: Task<()>,
728 _scroll_cursor_center_top_bottom_task: Task<()>,
729 serialize_selections: Task<()>,
730}
731
732#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
733enum NextScrollCursorCenterTopBottom {
734 #[default]
735 Center,
736 Top,
737 Bottom,
738}
739
740impl NextScrollCursorCenterTopBottom {
741 fn next(&self) -> Self {
742 match self {
743 Self::Center => Self::Top,
744 Self::Top => Self::Bottom,
745 Self::Bottom => Self::Center,
746 }
747 }
748}
749
750#[derive(Clone)]
751pub struct EditorSnapshot {
752 pub mode: EditorMode,
753 show_gutter: bool,
754 show_line_numbers: Option<bool>,
755 show_git_diff_gutter: Option<bool>,
756 show_code_actions: Option<bool>,
757 show_runnables: Option<bool>,
758 git_blame_gutter_max_author_length: Option<usize>,
759 pub display_snapshot: DisplaySnapshot,
760 pub placeholder_text: Option<Arc<str>>,
761 is_focused: bool,
762 scroll_anchor: ScrollAnchor,
763 ongoing_scroll: OngoingScroll,
764 current_line_highlight: CurrentLineHighlight,
765 gutter_hovered: bool,
766}
767
768const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
769
770#[derive(Default, Debug, Clone, Copy)]
771pub struct GutterDimensions {
772 pub left_padding: Pixels,
773 pub right_padding: Pixels,
774 pub width: Pixels,
775 pub margin: Pixels,
776 pub git_blame_entries_width: Option<Pixels>,
777}
778
779impl GutterDimensions {
780 /// The full width of the space taken up by the gutter.
781 pub fn full_width(&self) -> Pixels {
782 self.margin + self.width
783 }
784
785 /// The width of the space reserved for the fold indicators,
786 /// use alongside 'justify_end' and `gutter_width` to
787 /// right align content with the line numbers
788 pub fn fold_area_width(&self) -> Pixels {
789 self.margin + self.right_padding
790 }
791}
792
793#[derive(Debug)]
794pub struct RemoteSelection {
795 pub replica_id: ReplicaId,
796 pub selection: Selection<Anchor>,
797 pub cursor_shape: CursorShape,
798 pub peer_id: PeerId,
799 pub line_mode: bool,
800 pub participant_index: Option<ParticipantIndex>,
801 pub user_name: Option<SharedString>,
802}
803
804#[derive(Clone, Debug)]
805struct SelectionHistoryEntry {
806 selections: Arc<[Selection<Anchor>]>,
807 select_next_state: Option<SelectNextState>,
808 select_prev_state: Option<SelectNextState>,
809 add_selections_state: Option<AddSelectionsState>,
810}
811
812enum SelectionHistoryMode {
813 Normal,
814 Undoing,
815 Redoing,
816}
817
818#[derive(Clone, PartialEq, Eq, Hash)]
819struct HoveredCursor {
820 replica_id: u16,
821 selection_id: usize,
822}
823
824impl Default for SelectionHistoryMode {
825 fn default() -> Self {
826 Self::Normal
827 }
828}
829
830#[derive(Default)]
831struct SelectionHistory {
832 #[allow(clippy::type_complexity)]
833 selections_by_transaction:
834 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
835 mode: SelectionHistoryMode,
836 undo_stack: VecDeque<SelectionHistoryEntry>,
837 redo_stack: VecDeque<SelectionHistoryEntry>,
838}
839
840impl SelectionHistory {
841 fn insert_transaction(
842 &mut self,
843 transaction_id: TransactionId,
844 selections: Arc<[Selection<Anchor>]>,
845 ) {
846 self.selections_by_transaction
847 .insert(transaction_id, (selections, None));
848 }
849
850 #[allow(clippy::type_complexity)]
851 fn transaction(
852 &self,
853 transaction_id: TransactionId,
854 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
855 self.selections_by_transaction.get(&transaction_id)
856 }
857
858 #[allow(clippy::type_complexity)]
859 fn transaction_mut(
860 &mut self,
861 transaction_id: TransactionId,
862 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
863 self.selections_by_transaction.get_mut(&transaction_id)
864 }
865
866 fn push(&mut self, entry: SelectionHistoryEntry) {
867 if !entry.selections.is_empty() {
868 match self.mode {
869 SelectionHistoryMode::Normal => {
870 self.push_undo(entry);
871 self.redo_stack.clear();
872 }
873 SelectionHistoryMode::Undoing => self.push_redo(entry),
874 SelectionHistoryMode::Redoing => self.push_undo(entry),
875 }
876 }
877 }
878
879 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
880 if self
881 .undo_stack
882 .back()
883 .map_or(true, |e| e.selections != entry.selections)
884 {
885 self.undo_stack.push_back(entry);
886 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
887 self.undo_stack.pop_front();
888 }
889 }
890 }
891
892 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
893 if self
894 .redo_stack
895 .back()
896 .map_or(true, |e| e.selections != entry.selections)
897 {
898 self.redo_stack.push_back(entry);
899 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
900 self.redo_stack.pop_front();
901 }
902 }
903 }
904}
905
906struct RowHighlight {
907 index: usize,
908 range: Range<Anchor>,
909 color: Hsla,
910 should_autoscroll: bool,
911}
912
913#[derive(Clone, Debug)]
914struct AddSelectionsState {
915 above: bool,
916 stack: Vec<usize>,
917}
918
919#[derive(Clone)]
920struct SelectNextState {
921 query: AhoCorasick,
922 wordwise: bool,
923 done: bool,
924}
925
926impl std::fmt::Debug for SelectNextState {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 f.debug_struct(std::any::type_name::<Self>())
929 .field("wordwise", &self.wordwise)
930 .field("done", &self.done)
931 .finish()
932 }
933}
934
935#[derive(Debug)]
936struct AutocloseRegion {
937 selection_id: usize,
938 range: Range<Anchor>,
939 pair: BracketPair,
940}
941
942#[derive(Debug)]
943struct SnippetState {
944 ranges: Vec<Vec<Range<Anchor>>>,
945 active_index: usize,
946 choices: Vec<Option<Vec<String>>>,
947}
948
949#[doc(hidden)]
950pub struct RenameState {
951 pub range: Range<Anchor>,
952 pub old_name: Arc<str>,
953 pub editor: Entity<Editor>,
954 block_id: CustomBlockId,
955}
956
957struct InvalidationStack<T>(Vec<T>);
958
959struct RegisteredInlineCompletionProvider {
960 provider: Arc<dyn InlineCompletionProviderHandle>,
961 _subscription: Subscription,
962}
963
964#[derive(Debug)]
965struct ActiveDiagnosticGroup {
966 primary_range: Range<Anchor>,
967 primary_message: String,
968 group_id: usize,
969 blocks: HashMap<CustomBlockId, Diagnostic>,
970 is_valid: bool,
971}
972
973#[derive(Serialize, Deserialize, Clone, Debug)]
974pub struct ClipboardSelection {
975 /// The number of bytes in this selection.
976 pub len: usize,
977 /// Whether this was a full-line selection.
978 pub is_entire_line: bool,
979 /// The column where this selection originally started.
980 pub start_column: u32,
981}
982
983#[derive(Debug)]
984pub(crate) struct NavigationData {
985 cursor_anchor: Anchor,
986 cursor_position: Point,
987 scroll_anchor: ScrollAnchor,
988 scroll_top_row: u32,
989}
990
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum GotoDefinitionKind {
993 Symbol,
994 Declaration,
995 Type,
996 Implementation,
997}
998
999#[derive(Debug, Clone)]
1000enum InlayHintRefreshReason {
1001 Toggle(bool),
1002 SettingsChange(InlayHintSettings),
1003 NewLinesShown,
1004 BufferEdited(HashSet<Arc<Language>>),
1005 RefreshRequested,
1006 ExcerptsRemoved(Vec<ExcerptId>),
1007}
1008
1009impl InlayHintRefreshReason {
1010 fn description(&self) -> &'static str {
1011 match self {
1012 Self::Toggle(_) => "toggle",
1013 Self::SettingsChange(_) => "settings change",
1014 Self::NewLinesShown => "new lines shown",
1015 Self::BufferEdited(_) => "buffer edited",
1016 Self::RefreshRequested => "refresh requested",
1017 Self::ExcerptsRemoved(_) => "excerpts removed",
1018 }
1019 }
1020}
1021
1022pub enum FormatTarget {
1023 Buffers,
1024 Ranges(Vec<Range<MultiBufferPoint>>),
1025}
1026
1027pub(crate) struct FocusedBlock {
1028 id: BlockId,
1029 focus_handle: WeakFocusHandle,
1030}
1031
1032#[derive(Clone)]
1033enum JumpData {
1034 MultiBufferRow {
1035 row: MultiBufferRow,
1036 line_offset_from_top: u32,
1037 },
1038 MultiBufferPoint {
1039 excerpt_id: ExcerptId,
1040 position: Point,
1041 anchor: text::Anchor,
1042 line_offset_from_top: u32,
1043 },
1044}
1045
1046pub enum MultibufferSelectionMode {
1047 First,
1048 All,
1049}
1050
1051impl Editor {
1052 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1053 let buffer = cx.new(|cx| Buffer::local("", cx));
1054 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1055 Self::new(
1056 EditorMode::SingleLine { auto_width: false },
1057 buffer,
1058 None,
1059 false,
1060 window,
1061 cx,
1062 )
1063 }
1064
1065 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1066 let buffer = cx.new(|cx| Buffer::local("", cx));
1067 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1068 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1069 }
1070
1071 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1072 let buffer = cx.new(|cx| Buffer::local("", cx));
1073 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(
1075 EditorMode::SingleLine { auto_width: true },
1076 buffer,
1077 None,
1078 false,
1079 window,
1080 cx,
1081 )
1082 }
1083
1084 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1085 let buffer = cx.new(|cx| Buffer::local("", cx));
1086 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1087 Self::new(
1088 EditorMode::AutoHeight { max_lines },
1089 buffer,
1090 None,
1091 false,
1092 window,
1093 cx,
1094 )
1095 }
1096
1097 pub fn for_buffer(
1098 buffer: Entity<Buffer>,
1099 project: Option<Entity<Project>>,
1100 window: &mut Window,
1101 cx: &mut Context<Self>,
1102 ) -> Self {
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1105 }
1106
1107 pub fn for_multibuffer(
1108 buffer: Entity<MultiBuffer>,
1109 project: Option<Entity<Project>>,
1110 show_excerpt_controls: bool,
1111 window: &mut Window,
1112 cx: &mut Context<Self>,
1113 ) -> Self {
1114 Self::new(
1115 EditorMode::Full,
1116 buffer,
1117 project,
1118 show_excerpt_controls,
1119 window,
1120 cx,
1121 )
1122 }
1123
1124 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1125 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1126 let mut clone = Self::new(
1127 self.mode,
1128 self.buffer.clone(),
1129 self.project.clone(),
1130 show_excerpt_controls,
1131 window,
1132 cx,
1133 );
1134 self.display_map.update(cx, |display_map, cx| {
1135 let snapshot = display_map.snapshot(cx);
1136 clone.display_map.update(cx, |display_map, cx| {
1137 display_map.set_state(&snapshot, cx);
1138 });
1139 });
1140 clone.selections.clone_state(&self.selections);
1141 clone.scroll_manager.clone_state(&self.scroll_manager);
1142 clone.searchable = self.searchable;
1143 clone
1144 }
1145
1146 pub fn new(
1147 mode: EditorMode,
1148 buffer: Entity<MultiBuffer>,
1149 project: Option<Entity<Project>>,
1150 show_excerpt_controls: bool,
1151 window: &mut Window,
1152 cx: &mut Context<Self>,
1153 ) -> Self {
1154 let style = window.text_style();
1155 let font_size = style.font_size.to_pixels(window.rem_size());
1156 let editor = cx.entity().downgrade();
1157 let fold_placeholder = FoldPlaceholder {
1158 constrain_width: true,
1159 render: Arc::new(move |fold_id, fold_range, cx| {
1160 let editor = editor.clone();
1161 div()
1162 .id(fold_id)
1163 .bg(cx.theme().colors().ghost_element_background)
1164 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1165 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1166 .rounded_sm()
1167 .size_full()
1168 .cursor_pointer()
1169 .child("⋯")
1170 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1171 .on_click(move |_, _window, cx| {
1172 editor
1173 .update(cx, |editor, cx| {
1174 editor.unfold_ranges(
1175 &[fold_range.start..fold_range.end],
1176 true,
1177 false,
1178 cx,
1179 );
1180 cx.stop_propagation();
1181 })
1182 .ok();
1183 })
1184 .into_any()
1185 }),
1186 merge_adjacent: true,
1187 ..Default::default()
1188 };
1189 let display_map = cx.new(|cx| {
1190 DisplayMap::new(
1191 buffer.clone(),
1192 style.font(),
1193 font_size,
1194 None,
1195 show_excerpt_controls,
1196 FILE_HEADER_HEIGHT,
1197 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1198 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1199 fold_placeholder,
1200 cx,
1201 )
1202 });
1203
1204 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1205
1206 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1207
1208 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1209 .then(|| language_settings::SoftWrap::None);
1210
1211 let mut project_subscriptions = Vec::new();
1212 if mode == EditorMode::Full {
1213 if let Some(project) = project.as_ref() {
1214 if buffer.read(cx).is_singleton() {
1215 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1216 cx.emit(EditorEvent::TitleChanged);
1217 }));
1218 }
1219 project_subscriptions.push(cx.subscribe_in(
1220 project,
1221 window,
1222 |editor, _, event, window, cx| {
1223 if let project::Event::RefreshInlayHints = event {
1224 editor
1225 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1226 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1227 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1228 let focus_handle = editor.focus_handle(cx);
1229 if focus_handle.is_focused(window) {
1230 let snapshot = buffer.read(cx).snapshot();
1231 for (range, snippet) in snippet_edits {
1232 let editor_range =
1233 language::range_from_lsp(*range).to_offset(&snapshot);
1234 editor
1235 .insert_snippet(
1236 &[editor_range],
1237 snippet.clone(),
1238 window,
1239 cx,
1240 )
1241 .ok();
1242 }
1243 }
1244 }
1245 }
1246 },
1247 ));
1248 if let Some(task_inventory) = project
1249 .read(cx)
1250 .task_store()
1251 .read(cx)
1252 .task_inventory()
1253 .cloned()
1254 {
1255 project_subscriptions.push(cx.observe_in(
1256 &task_inventory,
1257 window,
1258 |editor, _, window, cx| {
1259 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1260 },
1261 ));
1262 }
1263 }
1264 }
1265
1266 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1267
1268 let inlay_hint_settings =
1269 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1270 let focus_handle = cx.focus_handle();
1271 cx.on_focus(&focus_handle, window, Self::handle_focus)
1272 .detach();
1273 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1274 .detach();
1275 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1276 .detach();
1277 cx.on_blur(&focus_handle, window, Self::handle_blur)
1278 .detach();
1279
1280 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1281 Some(false)
1282 } else {
1283 None
1284 };
1285
1286 let mut code_action_providers = Vec::new();
1287 let mut load_uncommitted_diff = None;
1288 if let Some(project) = project.clone() {
1289 load_uncommitted_diff = Some(
1290 get_uncommitted_diff_for_buffer(
1291 &project,
1292 buffer.read(cx).all_buffers(),
1293 buffer.clone(),
1294 cx,
1295 )
1296 .shared(),
1297 );
1298 code_action_providers.push(Rc::new(project) as Rc<_>);
1299 }
1300
1301 let mut this = Self {
1302 focus_handle,
1303 show_cursor_when_unfocused: false,
1304 last_focused_descendant: None,
1305 buffer: buffer.clone(),
1306 display_map: display_map.clone(),
1307 selections,
1308 scroll_manager: ScrollManager::new(cx),
1309 columnar_selection_tail: None,
1310 add_selections_state: None,
1311 select_next_state: None,
1312 select_prev_state: None,
1313 selection_history: Default::default(),
1314 autoclose_regions: Default::default(),
1315 snippet_stack: Default::default(),
1316 select_larger_syntax_node_stack: Vec::new(),
1317 ime_transaction: Default::default(),
1318 active_diagnostics: None,
1319 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1320 inline_diagnostics_update: Task::ready(()),
1321 inline_diagnostics: Vec::new(),
1322 soft_wrap_mode_override,
1323 completion_provider: project.clone().map(|project| Box::new(project) as _),
1324 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1325 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1326 project,
1327 blink_manager: blink_manager.clone(),
1328 show_local_selections: true,
1329 show_scrollbars: true,
1330 mode,
1331 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1332 show_gutter: mode == EditorMode::Full,
1333 show_line_numbers: None,
1334 use_relative_line_numbers: None,
1335 show_git_diff_gutter: None,
1336 show_code_actions: None,
1337 show_runnables: None,
1338 show_wrap_guides: None,
1339 show_indent_guides,
1340 placeholder_text: None,
1341 highlight_order: 0,
1342 highlighted_rows: HashMap::default(),
1343 background_highlights: Default::default(),
1344 gutter_highlights: TreeMap::default(),
1345 scrollbar_marker_state: ScrollbarMarkerState::default(),
1346 active_indent_guides_state: ActiveIndentGuidesState::default(),
1347 nav_history: None,
1348 context_menu: RefCell::new(None),
1349 mouse_context_menu: None,
1350 completion_tasks: Default::default(),
1351 signature_help_state: SignatureHelpState::default(),
1352 auto_signature_help: None,
1353 find_all_references_task_sources: Vec::new(),
1354 next_completion_id: 0,
1355 next_inlay_id: 0,
1356 code_action_providers,
1357 available_code_actions: Default::default(),
1358 code_actions_task: Default::default(),
1359 selection_highlight_task: Default::default(),
1360 document_highlights_task: Default::default(),
1361 linked_editing_range_task: Default::default(),
1362 pending_rename: Default::default(),
1363 searchable: true,
1364 cursor_shape: EditorSettings::get_global(cx)
1365 .cursor_shape
1366 .unwrap_or_default(),
1367 current_line_highlight: None,
1368 autoindent_mode: Some(AutoindentMode::EachLine),
1369 collapse_matches: false,
1370 workspace: None,
1371 input_enabled: true,
1372 use_modal_editing: mode == EditorMode::Full,
1373 read_only: false,
1374 use_autoclose: true,
1375 use_auto_surround: true,
1376 auto_replace_emoji_shortcode: false,
1377 leader_peer_id: None,
1378 remote_id: None,
1379 hover_state: Default::default(),
1380 pending_mouse_down: None,
1381 hovered_link_state: Default::default(),
1382 edit_prediction_provider: None,
1383 active_inline_completion: None,
1384 stale_inline_completion_in_menu: None,
1385 edit_prediction_preview: EditPredictionPreview::Inactive,
1386 inline_diagnostics_enabled: mode == EditorMode::Full,
1387 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1388
1389 gutter_hovered: false,
1390 pixel_position_of_newest_cursor: None,
1391 last_bounds: None,
1392 last_position_map: None,
1393 expect_bounds_change: None,
1394 gutter_dimensions: GutterDimensions::default(),
1395 style: None,
1396 show_cursor_names: false,
1397 hovered_cursors: Default::default(),
1398 next_editor_action_id: EditorActionId::default(),
1399 editor_actions: Rc::default(),
1400 inline_completions_hidden_for_vim_mode: false,
1401 show_inline_completions_override: None,
1402 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1403 edit_prediction_settings: EditPredictionSettings::Disabled,
1404 edit_prediction_indent_conflict: false,
1405 edit_prediction_requires_modifier_in_indent_conflict: true,
1406 custom_context_menu: None,
1407 show_git_blame_gutter: false,
1408 show_git_blame_inline: false,
1409 show_selection_menu: None,
1410 show_git_blame_inline_delay_task: None,
1411 git_blame_inline_tooltip: None,
1412 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1413 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1414 .session
1415 .restore_unsaved_buffers,
1416 blame: None,
1417 blame_subscription: None,
1418 tasks: Default::default(),
1419 _subscriptions: vec![
1420 cx.observe(&buffer, Self::on_buffer_changed),
1421 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1422 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1423 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1424 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1425 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1426 cx.observe_window_activation(window, |editor, window, cx| {
1427 let active = window.is_window_active();
1428 editor.blink_manager.update(cx, |blink_manager, cx| {
1429 if active {
1430 blink_manager.enable(cx);
1431 } else {
1432 blink_manager.disable(cx);
1433 }
1434 });
1435 }),
1436 ],
1437 tasks_update_task: None,
1438 linked_edit_ranges: Default::default(),
1439 in_project_search: false,
1440 previous_search_ranges: None,
1441 breadcrumb_header: None,
1442 focused_block: None,
1443 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1444 addons: HashMap::default(),
1445 registered_buffers: HashMap::default(),
1446 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1447 selection_mark_mode: false,
1448 toggle_fold_multiple_buffers: Task::ready(()),
1449 serialize_selections: Task::ready(()),
1450 text_style_refinement: None,
1451 load_diff_task: load_uncommitted_diff,
1452 };
1453 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1454 this._subscriptions.extend(project_subscriptions);
1455
1456 this.end_selection(window, cx);
1457 this.scroll_manager.show_scrollbar(window, cx);
1458
1459 if mode == EditorMode::Full {
1460 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1461 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1462
1463 if this.git_blame_inline_enabled {
1464 this.git_blame_inline_enabled = true;
1465 this.start_git_blame_inline(false, window, cx);
1466 }
1467
1468 if let Some(buffer) = buffer.read(cx).as_singleton() {
1469 if let Some(project) = this.project.as_ref() {
1470 let handle = project.update(cx, |project, cx| {
1471 project.register_buffer_with_language_servers(&buffer, cx)
1472 });
1473 this.registered_buffers
1474 .insert(buffer.read(cx).remote_id(), handle);
1475 }
1476 }
1477 }
1478
1479 this.report_editor_event("Editor Opened", None, cx);
1480 this
1481 }
1482
1483 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1484 self.mouse_context_menu
1485 .as_ref()
1486 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1487 }
1488
1489 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1490 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1491 }
1492
1493 fn key_context_internal(
1494 &self,
1495 has_active_edit_prediction: bool,
1496 window: &Window,
1497 cx: &App,
1498 ) -> KeyContext {
1499 let mut key_context = KeyContext::new_with_defaults();
1500 key_context.add("Editor");
1501 let mode = match self.mode {
1502 EditorMode::SingleLine { .. } => "single_line",
1503 EditorMode::AutoHeight { .. } => "auto_height",
1504 EditorMode::Full => "full",
1505 };
1506
1507 if EditorSettings::jupyter_enabled(cx) {
1508 key_context.add("jupyter");
1509 }
1510
1511 key_context.set("mode", mode);
1512 if self.pending_rename.is_some() {
1513 key_context.add("renaming");
1514 }
1515
1516 match self.context_menu.borrow().as_ref() {
1517 Some(CodeContextMenu::Completions(_)) => {
1518 key_context.add("menu");
1519 key_context.add("showing_completions");
1520 }
1521 Some(CodeContextMenu::CodeActions(_)) => {
1522 key_context.add("menu");
1523 key_context.add("showing_code_actions")
1524 }
1525 None => {}
1526 }
1527
1528 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1529 if !self.focus_handle(cx).contains_focused(window, cx)
1530 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1531 {
1532 for addon in self.addons.values() {
1533 addon.extend_key_context(&mut key_context, cx)
1534 }
1535 }
1536
1537 if let Some(extension) = self
1538 .buffer
1539 .read(cx)
1540 .as_singleton()
1541 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1542 {
1543 key_context.set("extension", extension.to_string());
1544 }
1545
1546 if has_active_edit_prediction {
1547 if self.edit_prediction_in_conflict() {
1548 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1549 } else {
1550 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1551 key_context.add("copilot_suggestion");
1552 }
1553 }
1554
1555 if self.selection_mark_mode {
1556 key_context.add("selection_mode");
1557 }
1558
1559 key_context
1560 }
1561
1562 pub fn edit_prediction_in_conflict(&self) -> bool {
1563 if !self.show_edit_predictions_in_menu() {
1564 return false;
1565 }
1566
1567 let showing_completions = self
1568 .context_menu
1569 .borrow()
1570 .as_ref()
1571 .map_or(false, |context| {
1572 matches!(context, CodeContextMenu::Completions(_))
1573 });
1574
1575 showing_completions
1576 || self.edit_prediction_requires_modifier()
1577 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1578 // bindings to insert tab characters.
1579 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1580 }
1581
1582 pub fn accept_edit_prediction_keybind(
1583 &self,
1584 window: &Window,
1585 cx: &App,
1586 ) -> AcceptEditPredictionBinding {
1587 let key_context = self.key_context_internal(true, window, cx);
1588 let in_conflict = self.edit_prediction_in_conflict();
1589
1590 AcceptEditPredictionBinding(
1591 window
1592 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1593 .into_iter()
1594 .filter(|binding| {
1595 !in_conflict
1596 || binding
1597 .keystrokes()
1598 .first()
1599 .map_or(false, |keystroke| keystroke.modifiers.modified())
1600 })
1601 .rev()
1602 .min_by_key(|binding| {
1603 binding
1604 .keystrokes()
1605 .first()
1606 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1607 }),
1608 )
1609 }
1610
1611 pub fn new_file(
1612 workspace: &mut Workspace,
1613 _: &workspace::NewFile,
1614 window: &mut Window,
1615 cx: &mut Context<Workspace>,
1616 ) {
1617 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1618 "Failed to create buffer",
1619 window,
1620 cx,
1621 |e, _, _| match e.error_code() {
1622 ErrorCode::RemoteUpgradeRequired => Some(format!(
1623 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1624 e.error_tag("required").unwrap_or("the latest version")
1625 )),
1626 _ => None,
1627 },
1628 );
1629 }
1630
1631 pub fn new_in_workspace(
1632 workspace: &mut Workspace,
1633 window: &mut Window,
1634 cx: &mut Context<Workspace>,
1635 ) -> Task<Result<Entity<Editor>>> {
1636 let project = workspace.project().clone();
1637 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1638
1639 cx.spawn_in(window, |workspace, mut cx| async move {
1640 let buffer = create.await?;
1641 workspace.update_in(&mut cx, |workspace, window, cx| {
1642 let editor =
1643 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1644 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1645 editor
1646 })
1647 })
1648 }
1649
1650 fn new_file_vertical(
1651 workspace: &mut Workspace,
1652 _: &workspace::NewFileSplitVertical,
1653 window: &mut Window,
1654 cx: &mut Context<Workspace>,
1655 ) {
1656 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1657 }
1658
1659 fn new_file_horizontal(
1660 workspace: &mut Workspace,
1661 _: &workspace::NewFileSplitHorizontal,
1662 window: &mut Window,
1663 cx: &mut Context<Workspace>,
1664 ) {
1665 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1666 }
1667
1668 fn new_file_in_direction(
1669 workspace: &mut Workspace,
1670 direction: SplitDirection,
1671 window: &mut Window,
1672 cx: &mut Context<Workspace>,
1673 ) {
1674 let project = workspace.project().clone();
1675 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1676
1677 cx.spawn_in(window, |workspace, mut cx| async move {
1678 let buffer = create.await?;
1679 workspace.update_in(&mut cx, move |workspace, window, cx| {
1680 workspace.split_item(
1681 direction,
1682 Box::new(
1683 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1684 ),
1685 window,
1686 cx,
1687 )
1688 })?;
1689 anyhow::Ok(())
1690 })
1691 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1692 match e.error_code() {
1693 ErrorCode::RemoteUpgradeRequired => Some(format!(
1694 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1695 e.error_tag("required").unwrap_or("the latest version")
1696 )),
1697 _ => None,
1698 }
1699 });
1700 }
1701
1702 pub fn leader_peer_id(&self) -> Option<PeerId> {
1703 self.leader_peer_id
1704 }
1705
1706 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1707 &self.buffer
1708 }
1709
1710 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1711 self.workspace.as_ref()?.0.upgrade()
1712 }
1713
1714 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1715 self.buffer().read(cx).title(cx)
1716 }
1717
1718 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1719 let git_blame_gutter_max_author_length = self
1720 .render_git_blame_gutter(cx)
1721 .then(|| {
1722 if let Some(blame) = self.blame.as_ref() {
1723 let max_author_length =
1724 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1725 Some(max_author_length)
1726 } else {
1727 None
1728 }
1729 })
1730 .flatten();
1731
1732 EditorSnapshot {
1733 mode: self.mode,
1734 show_gutter: self.show_gutter,
1735 show_line_numbers: self.show_line_numbers,
1736 show_git_diff_gutter: self.show_git_diff_gutter,
1737 show_code_actions: self.show_code_actions,
1738 show_runnables: self.show_runnables,
1739 git_blame_gutter_max_author_length,
1740 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1741 scroll_anchor: self.scroll_manager.anchor(),
1742 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1743 placeholder_text: self.placeholder_text.clone(),
1744 is_focused: self.focus_handle.is_focused(window),
1745 current_line_highlight: self
1746 .current_line_highlight
1747 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1748 gutter_hovered: self.gutter_hovered,
1749 }
1750 }
1751
1752 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1753 self.buffer.read(cx).language_at(point, cx)
1754 }
1755
1756 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1757 self.buffer.read(cx).read(cx).file_at(point).cloned()
1758 }
1759
1760 pub fn active_excerpt(
1761 &self,
1762 cx: &App,
1763 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1764 self.buffer
1765 .read(cx)
1766 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1767 }
1768
1769 pub fn mode(&self) -> EditorMode {
1770 self.mode
1771 }
1772
1773 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1774 self.collaboration_hub.as_deref()
1775 }
1776
1777 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1778 self.collaboration_hub = Some(hub);
1779 }
1780
1781 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1782 self.in_project_search = in_project_search;
1783 }
1784
1785 pub fn set_custom_context_menu(
1786 &mut self,
1787 f: impl 'static
1788 + Fn(
1789 &mut Self,
1790 DisplayPoint,
1791 &mut Window,
1792 &mut Context<Self>,
1793 ) -> Option<Entity<ui::ContextMenu>>,
1794 ) {
1795 self.custom_context_menu = Some(Box::new(f))
1796 }
1797
1798 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1799 self.completion_provider = provider;
1800 }
1801
1802 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1803 self.semantics_provider.clone()
1804 }
1805
1806 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1807 self.semantics_provider = provider;
1808 }
1809
1810 pub fn set_edit_prediction_provider<T>(
1811 &mut self,
1812 provider: Option<Entity<T>>,
1813 window: &mut Window,
1814 cx: &mut Context<Self>,
1815 ) where
1816 T: EditPredictionProvider,
1817 {
1818 self.edit_prediction_provider =
1819 provider.map(|provider| RegisteredInlineCompletionProvider {
1820 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1821 if this.focus_handle.is_focused(window) {
1822 this.update_visible_inline_completion(window, cx);
1823 }
1824 }),
1825 provider: Arc::new(provider),
1826 });
1827 self.refresh_inline_completion(false, false, window, cx);
1828 }
1829
1830 pub fn placeholder_text(&self) -> Option<&str> {
1831 self.placeholder_text.as_deref()
1832 }
1833
1834 pub fn set_placeholder_text(
1835 &mut self,
1836 placeholder_text: impl Into<Arc<str>>,
1837 cx: &mut Context<Self>,
1838 ) {
1839 let placeholder_text = Some(placeholder_text.into());
1840 if self.placeholder_text != placeholder_text {
1841 self.placeholder_text = placeholder_text;
1842 cx.notify();
1843 }
1844 }
1845
1846 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1847 self.cursor_shape = cursor_shape;
1848
1849 // Disrupt blink for immediate user feedback that the cursor shape has changed
1850 self.blink_manager.update(cx, BlinkManager::show_cursor);
1851
1852 cx.notify();
1853 }
1854
1855 pub fn set_current_line_highlight(
1856 &mut self,
1857 current_line_highlight: Option<CurrentLineHighlight>,
1858 ) {
1859 self.current_line_highlight = current_line_highlight;
1860 }
1861
1862 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1863 self.collapse_matches = collapse_matches;
1864 }
1865
1866 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1867 let buffers = self.buffer.read(cx).all_buffers();
1868 let Some(project) = self.project.as_ref() else {
1869 return;
1870 };
1871 project.update(cx, |project, cx| {
1872 for buffer in buffers {
1873 self.registered_buffers
1874 .entry(buffer.read(cx).remote_id())
1875 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1876 }
1877 })
1878 }
1879
1880 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1881 if self.collapse_matches {
1882 return range.start..range.start;
1883 }
1884 range.clone()
1885 }
1886
1887 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1888 if self.display_map.read(cx).clip_at_line_ends != clip {
1889 self.display_map
1890 .update(cx, |map, _| map.clip_at_line_ends = clip);
1891 }
1892 }
1893
1894 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1895 self.input_enabled = input_enabled;
1896 }
1897
1898 pub fn set_inline_completions_hidden_for_vim_mode(
1899 &mut self,
1900 hidden: bool,
1901 window: &mut Window,
1902 cx: &mut Context<Self>,
1903 ) {
1904 if hidden != self.inline_completions_hidden_for_vim_mode {
1905 self.inline_completions_hidden_for_vim_mode = hidden;
1906 if hidden {
1907 self.update_visible_inline_completion(window, cx);
1908 } else {
1909 self.refresh_inline_completion(true, false, window, cx);
1910 }
1911 }
1912 }
1913
1914 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1915 self.menu_inline_completions_policy = value;
1916 }
1917
1918 pub fn set_autoindent(&mut self, autoindent: bool) {
1919 if autoindent {
1920 self.autoindent_mode = Some(AutoindentMode::EachLine);
1921 } else {
1922 self.autoindent_mode = None;
1923 }
1924 }
1925
1926 pub fn read_only(&self, cx: &App) -> bool {
1927 self.read_only || self.buffer.read(cx).read_only()
1928 }
1929
1930 pub fn set_read_only(&mut self, read_only: bool) {
1931 self.read_only = read_only;
1932 }
1933
1934 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1935 self.use_autoclose = autoclose;
1936 }
1937
1938 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1939 self.use_auto_surround = auto_surround;
1940 }
1941
1942 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1943 self.auto_replace_emoji_shortcode = auto_replace;
1944 }
1945
1946 pub fn toggle_inline_completions(
1947 &mut self,
1948 _: &ToggleEditPrediction,
1949 window: &mut Window,
1950 cx: &mut Context<Self>,
1951 ) {
1952 if self.show_inline_completions_override.is_some() {
1953 self.set_show_edit_predictions(None, window, cx);
1954 } else {
1955 let show_edit_predictions = !self.edit_predictions_enabled();
1956 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1957 }
1958 }
1959
1960 pub fn set_show_edit_predictions(
1961 &mut self,
1962 show_edit_predictions: Option<bool>,
1963 window: &mut Window,
1964 cx: &mut Context<Self>,
1965 ) {
1966 self.show_inline_completions_override = show_edit_predictions;
1967
1968 if let Some(false) = show_edit_predictions {
1969 self.discard_inline_completion(false, cx);
1970 } else {
1971 self.refresh_inline_completion(false, true, window, cx);
1972 }
1973 }
1974
1975 fn inline_completions_disabled_in_scope(
1976 &self,
1977 buffer: &Entity<Buffer>,
1978 buffer_position: language::Anchor,
1979 cx: &App,
1980 ) -> bool {
1981 let snapshot = buffer.read(cx).snapshot();
1982 let settings = snapshot.settings_at(buffer_position, cx);
1983
1984 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1985 return false;
1986 };
1987
1988 scope.override_name().map_or(false, |scope_name| {
1989 settings
1990 .edit_predictions_disabled_in
1991 .iter()
1992 .any(|s| s == scope_name)
1993 })
1994 }
1995
1996 pub fn set_use_modal_editing(&mut self, to: bool) {
1997 self.use_modal_editing = to;
1998 }
1999
2000 pub fn use_modal_editing(&self) -> bool {
2001 self.use_modal_editing
2002 }
2003
2004 fn selections_did_change(
2005 &mut self,
2006 local: bool,
2007 old_cursor_position: &Anchor,
2008 show_completions: bool,
2009 window: &mut Window,
2010 cx: &mut Context<Self>,
2011 ) {
2012 window.invalidate_character_coordinates();
2013
2014 // Copy selections to primary selection buffer
2015 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2016 if local {
2017 let selections = self.selections.all::<usize>(cx);
2018 let buffer_handle = self.buffer.read(cx).read(cx);
2019
2020 let mut text = String::new();
2021 for (index, selection) in selections.iter().enumerate() {
2022 let text_for_selection = buffer_handle
2023 .text_for_range(selection.start..selection.end)
2024 .collect::<String>();
2025
2026 text.push_str(&text_for_selection);
2027 if index != selections.len() - 1 {
2028 text.push('\n');
2029 }
2030 }
2031
2032 if !text.is_empty() {
2033 cx.write_to_primary(ClipboardItem::new_string(text));
2034 }
2035 }
2036
2037 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2038 self.buffer.update(cx, |buffer, cx| {
2039 buffer.set_active_selections(
2040 &self.selections.disjoint_anchors(),
2041 self.selections.line_mode,
2042 self.cursor_shape,
2043 cx,
2044 )
2045 });
2046 }
2047 let display_map = self
2048 .display_map
2049 .update(cx, |display_map, cx| display_map.snapshot(cx));
2050 let buffer = &display_map.buffer_snapshot;
2051 self.add_selections_state = None;
2052 self.select_next_state = None;
2053 self.select_prev_state = None;
2054 self.select_larger_syntax_node_stack.clear();
2055 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2056 self.snippet_stack
2057 .invalidate(&self.selections.disjoint_anchors(), buffer);
2058 self.take_rename(false, window, cx);
2059
2060 let new_cursor_position = self.selections.newest_anchor().head();
2061
2062 self.push_to_nav_history(
2063 *old_cursor_position,
2064 Some(new_cursor_position.to_point(buffer)),
2065 cx,
2066 );
2067
2068 if local {
2069 let new_cursor_position = self.selections.newest_anchor().head();
2070 let mut context_menu = self.context_menu.borrow_mut();
2071 let completion_menu = match context_menu.as_ref() {
2072 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2073 _ => {
2074 *context_menu = None;
2075 None
2076 }
2077 };
2078 if let Some(buffer_id) = new_cursor_position.buffer_id {
2079 if !self.registered_buffers.contains_key(&buffer_id) {
2080 if let Some(project) = self.project.as_ref() {
2081 project.update(cx, |project, cx| {
2082 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2083 return;
2084 };
2085 self.registered_buffers.insert(
2086 buffer_id,
2087 project.register_buffer_with_language_servers(&buffer, cx),
2088 );
2089 })
2090 }
2091 }
2092 }
2093
2094 if let Some(completion_menu) = completion_menu {
2095 let cursor_position = new_cursor_position.to_offset(buffer);
2096 let (word_range, kind) =
2097 buffer.surrounding_word(completion_menu.initial_position, true);
2098 if kind == Some(CharKind::Word)
2099 && word_range.to_inclusive().contains(&cursor_position)
2100 {
2101 let mut completion_menu = completion_menu.clone();
2102 drop(context_menu);
2103
2104 let query = Self::completion_query(buffer, cursor_position);
2105 cx.spawn(move |this, mut cx| async move {
2106 completion_menu
2107 .filter(query.as_deref(), cx.background_executor().clone())
2108 .await;
2109
2110 this.update(&mut cx, |this, cx| {
2111 let mut context_menu = this.context_menu.borrow_mut();
2112 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2113 else {
2114 return;
2115 };
2116
2117 if menu.id > completion_menu.id {
2118 return;
2119 }
2120
2121 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2122 drop(context_menu);
2123 cx.notify();
2124 })
2125 })
2126 .detach();
2127
2128 if show_completions {
2129 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2130 }
2131 } else {
2132 drop(context_menu);
2133 self.hide_context_menu(window, cx);
2134 }
2135 } else {
2136 drop(context_menu);
2137 }
2138
2139 hide_hover(self, cx);
2140
2141 if old_cursor_position.to_display_point(&display_map).row()
2142 != new_cursor_position.to_display_point(&display_map).row()
2143 {
2144 self.available_code_actions.take();
2145 }
2146 self.refresh_code_actions(window, cx);
2147 self.refresh_document_highlights(cx);
2148 self.refresh_selected_text_highlights(window, cx);
2149 refresh_matching_bracket_highlights(self, window, cx);
2150 self.update_visible_inline_completion(window, cx);
2151 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2152 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2153 if self.git_blame_inline_enabled {
2154 self.start_inline_blame_timer(window, cx);
2155 }
2156 }
2157
2158 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2159 cx.emit(EditorEvent::SelectionsChanged { local });
2160
2161 let selections = &self.selections.disjoint;
2162 if selections.len() == 1 {
2163 cx.emit(SearchEvent::ActiveMatchChanged)
2164 }
2165 if local
2166 && self.is_singleton(cx)
2167 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2168 {
2169 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2170 let background_executor = cx.background_executor().clone();
2171 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2172 let snapshot = self.buffer().read(cx).snapshot(cx);
2173 let selections = selections.clone();
2174 self.serialize_selections = cx.background_spawn(async move {
2175 background_executor.timer(Duration::from_millis(100)).await;
2176 let selections = selections
2177 .iter()
2178 .map(|selection| {
2179 (
2180 selection.start.to_offset(&snapshot),
2181 selection.end.to_offset(&snapshot),
2182 )
2183 })
2184 .collect();
2185 DB.save_editor_selections(editor_id, workspace_id, selections)
2186 .await
2187 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2188 .log_err();
2189 });
2190 }
2191 }
2192
2193 cx.notify();
2194 }
2195
2196 pub fn change_selections<R>(
2197 &mut self,
2198 autoscroll: Option<Autoscroll>,
2199 window: &mut Window,
2200 cx: &mut Context<Self>,
2201 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2202 ) -> R {
2203 self.change_selections_inner(autoscroll, true, window, cx, change)
2204 }
2205
2206 fn change_selections_inner<R>(
2207 &mut self,
2208 autoscroll: Option<Autoscroll>,
2209 request_completions: bool,
2210 window: &mut Window,
2211 cx: &mut Context<Self>,
2212 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2213 ) -> R {
2214 let old_cursor_position = self.selections.newest_anchor().head();
2215 self.push_to_selection_history();
2216
2217 let (changed, result) = self.selections.change_with(cx, change);
2218
2219 if changed {
2220 if let Some(autoscroll) = autoscroll {
2221 self.request_autoscroll(autoscroll, cx);
2222 }
2223 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2224
2225 if self.should_open_signature_help_automatically(
2226 &old_cursor_position,
2227 self.signature_help_state.backspace_pressed(),
2228 cx,
2229 ) {
2230 self.show_signature_help(&ShowSignatureHelp, window, cx);
2231 }
2232 self.signature_help_state.set_backspace_pressed(false);
2233 }
2234
2235 result
2236 }
2237
2238 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2239 where
2240 I: IntoIterator<Item = (Range<S>, T)>,
2241 S: ToOffset,
2242 T: Into<Arc<str>>,
2243 {
2244 if self.read_only(cx) {
2245 return;
2246 }
2247
2248 self.buffer
2249 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2250 }
2251
2252 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2253 where
2254 I: IntoIterator<Item = (Range<S>, T)>,
2255 S: ToOffset,
2256 T: Into<Arc<str>>,
2257 {
2258 if self.read_only(cx) {
2259 return;
2260 }
2261
2262 self.buffer.update(cx, |buffer, cx| {
2263 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2264 });
2265 }
2266
2267 pub fn edit_with_block_indent<I, S, T>(
2268 &mut self,
2269 edits: I,
2270 original_start_columns: Vec<u32>,
2271 cx: &mut Context<Self>,
2272 ) where
2273 I: IntoIterator<Item = (Range<S>, T)>,
2274 S: ToOffset,
2275 T: Into<Arc<str>>,
2276 {
2277 if self.read_only(cx) {
2278 return;
2279 }
2280
2281 self.buffer.update(cx, |buffer, cx| {
2282 buffer.edit(
2283 edits,
2284 Some(AutoindentMode::Block {
2285 original_start_columns,
2286 }),
2287 cx,
2288 )
2289 });
2290 }
2291
2292 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2293 self.hide_context_menu(window, cx);
2294
2295 match phase {
2296 SelectPhase::Begin {
2297 position,
2298 add,
2299 click_count,
2300 } => self.begin_selection(position, add, click_count, window, cx),
2301 SelectPhase::BeginColumnar {
2302 position,
2303 goal_column,
2304 reset,
2305 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2306 SelectPhase::Extend {
2307 position,
2308 click_count,
2309 } => self.extend_selection(position, click_count, window, cx),
2310 SelectPhase::Update {
2311 position,
2312 goal_column,
2313 scroll_delta,
2314 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2315 SelectPhase::End => self.end_selection(window, cx),
2316 }
2317 }
2318
2319 fn extend_selection(
2320 &mut self,
2321 position: DisplayPoint,
2322 click_count: usize,
2323 window: &mut Window,
2324 cx: &mut Context<Self>,
2325 ) {
2326 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2327 let tail = self.selections.newest::<usize>(cx).tail();
2328 self.begin_selection(position, false, click_count, window, cx);
2329
2330 let position = position.to_offset(&display_map, Bias::Left);
2331 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2332
2333 let mut pending_selection = self
2334 .selections
2335 .pending_anchor()
2336 .expect("extend_selection not called with pending selection");
2337 if position >= tail {
2338 pending_selection.start = tail_anchor;
2339 } else {
2340 pending_selection.end = tail_anchor;
2341 pending_selection.reversed = true;
2342 }
2343
2344 let mut pending_mode = self.selections.pending_mode().unwrap();
2345 match &mut pending_mode {
2346 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2347 _ => {}
2348 }
2349
2350 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2351 s.set_pending(pending_selection, pending_mode)
2352 });
2353 }
2354
2355 fn begin_selection(
2356 &mut self,
2357 position: DisplayPoint,
2358 add: bool,
2359 click_count: usize,
2360 window: &mut Window,
2361 cx: &mut Context<Self>,
2362 ) {
2363 if !self.focus_handle.is_focused(window) {
2364 self.last_focused_descendant = None;
2365 window.focus(&self.focus_handle);
2366 }
2367
2368 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2369 let buffer = &display_map.buffer_snapshot;
2370 let newest_selection = self.selections.newest_anchor().clone();
2371 let position = display_map.clip_point(position, Bias::Left);
2372
2373 let start;
2374 let end;
2375 let mode;
2376 let mut auto_scroll;
2377 match click_count {
2378 1 => {
2379 start = buffer.anchor_before(position.to_point(&display_map));
2380 end = start;
2381 mode = SelectMode::Character;
2382 auto_scroll = true;
2383 }
2384 2 => {
2385 let range = movement::surrounding_word(&display_map, position);
2386 start = buffer.anchor_before(range.start.to_point(&display_map));
2387 end = buffer.anchor_before(range.end.to_point(&display_map));
2388 mode = SelectMode::Word(start..end);
2389 auto_scroll = true;
2390 }
2391 3 => {
2392 let position = display_map
2393 .clip_point(position, Bias::Left)
2394 .to_point(&display_map);
2395 let line_start = display_map.prev_line_boundary(position).0;
2396 let next_line_start = buffer.clip_point(
2397 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2398 Bias::Left,
2399 );
2400 start = buffer.anchor_before(line_start);
2401 end = buffer.anchor_before(next_line_start);
2402 mode = SelectMode::Line(start..end);
2403 auto_scroll = true;
2404 }
2405 _ => {
2406 start = buffer.anchor_before(0);
2407 end = buffer.anchor_before(buffer.len());
2408 mode = SelectMode::All;
2409 auto_scroll = false;
2410 }
2411 }
2412 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2413
2414 let point_to_delete: Option<usize> = {
2415 let selected_points: Vec<Selection<Point>> =
2416 self.selections.disjoint_in_range(start..end, cx);
2417
2418 if !add || click_count > 1 {
2419 None
2420 } else if !selected_points.is_empty() {
2421 Some(selected_points[0].id)
2422 } else {
2423 let clicked_point_already_selected =
2424 self.selections.disjoint.iter().find(|selection| {
2425 selection.start.to_point(buffer) == start.to_point(buffer)
2426 || selection.end.to_point(buffer) == end.to_point(buffer)
2427 });
2428
2429 clicked_point_already_selected.map(|selection| selection.id)
2430 }
2431 };
2432
2433 let selections_count = self.selections.count();
2434
2435 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2436 if let Some(point_to_delete) = point_to_delete {
2437 s.delete(point_to_delete);
2438
2439 if selections_count == 1 {
2440 s.set_pending_anchor_range(start..end, mode);
2441 }
2442 } else {
2443 if !add {
2444 s.clear_disjoint();
2445 } else if click_count > 1 {
2446 s.delete(newest_selection.id)
2447 }
2448
2449 s.set_pending_anchor_range(start..end, mode);
2450 }
2451 });
2452 }
2453
2454 fn begin_columnar_selection(
2455 &mut self,
2456 position: DisplayPoint,
2457 goal_column: u32,
2458 reset: bool,
2459 window: &mut Window,
2460 cx: &mut Context<Self>,
2461 ) {
2462 if !self.focus_handle.is_focused(window) {
2463 self.last_focused_descendant = None;
2464 window.focus(&self.focus_handle);
2465 }
2466
2467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2468
2469 if reset {
2470 let pointer_position = display_map
2471 .buffer_snapshot
2472 .anchor_before(position.to_point(&display_map));
2473
2474 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2475 s.clear_disjoint();
2476 s.set_pending_anchor_range(
2477 pointer_position..pointer_position,
2478 SelectMode::Character,
2479 );
2480 });
2481 }
2482
2483 let tail = self.selections.newest::<Point>(cx).tail();
2484 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2485
2486 if !reset {
2487 self.select_columns(
2488 tail.to_display_point(&display_map),
2489 position,
2490 goal_column,
2491 &display_map,
2492 window,
2493 cx,
2494 );
2495 }
2496 }
2497
2498 fn update_selection(
2499 &mut self,
2500 position: DisplayPoint,
2501 goal_column: u32,
2502 scroll_delta: gpui::Point<f32>,
2503 window: &mut Window,
2504 cx: &mut Context<Self>,
2505 ) {
2506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2507
2508 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2509 let tail = tail.to_display_point(&display_map);
2510 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2511 } else if let Some(mut pending) = self.selections.pending_anchor() {
2512 let buffer = self.buffer.read(cx).snapshot(cx);
2513 let head;
2514 let tail;
2515 let mode = self.selections.pending_mode().unwrap();
2516 match &mode {
2517 SelectMode::Character => {
2518 head = position.to_point(&display_map);
2519 tail = pending.tail().to_point(&buffer);
2520 }
2521 SelectMode::Word(original_range) => {
2522 let original_display_range = original_range.start.to_display_point(&display_map)
2523 ..original_range.end.to_display_point(&display_map);
2524 let original_buffer_range = original_display_range.start.to_point(&display_map)
2525 ..original_display_range.end.to_point(&display_map);
2526 if movement::is_inside_word(&display_map, position)
2527 || original_display_range.contains(&position)
2528 {
2529 let word_range = movement::surrounding_word(&display_map, position);
2530 if word_range.start < original_display_range.start {
2531 head = word_range.start.to_point(&display_map);
2532 } else {
2533 head = word_range.end.to_point(&display_map);
2534 }
2535 } else {
2536 head = position.to_point(&display_map);
2537 }
2538
2539 if head <= original_buffer_range.start {
2540 tail = original_buffer_range.end;
2541 } else {
2542 tail = original_buffer_range.start;
2543 }
2544 }
2545 SelectMode::Line(original_range) => {
2546 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2547
2548 let position = display_map
2549 .clip_point(position, Bias::Left)
2550 .to_point(&display_map);
2551 let line_start = display_map.prev_line_boundary(position).0;
2552 let next_line_start = buffer.clip_point(
2553 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2554 Bias::Left,
2555 );
2556
2557 if line_start < original_range.start {
2558 head = line_start
2559 } else {
2560 head = next_line_start
2561 }
2562
2563 if head <= original_range.start {
2564 tail = original_range.end;
2565 } else {
2566 tail = original_range.start;
2567 }
2568 }
2569 SelectMode::All => {
2570 return;
2571 }
2572 };
2573
2574 if head < tail {
2575 pending.start = buffer.anchor_before(head);
2576 pending.end = buffer.anchor_before(tail);
2577 pending.reversed = true;
2578 } else {
2579 pending.start = buffer.anchor_before(tail);
2580 pending.end = buffer.anchor_before(head);
2581 pending.reversed = false;
2582 }
2583
2584 self.change_selections(None, window, cx, |s| {
2585 s.set_pending(pending, mode);
2586 });
2587 } else {
2588 log::error!("update_selection dispatched with no pending selection");
2589 return;
2590 }
2591
2592 self.apply_scroll_delta(scroll_delta, window, cx);
2593 cx.notify();
2594 }
2595
2596 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2597 self.columnar_selection_tail.take();
2598 if self.selections.pending_anchor().is_some() {
2599 let selections = self.selections.all::<usize>(cx);
2600 self.change_selections(None, window, cx, |s| {
2601 s.select(selections);
2602 s.clear_pending();
2603 });
2604 }
2605 }
2606
2607 fn select_columns(
2608 &mut self,
2609 tail: DisplayPoint,
2610 head: DisplayPoint,
2611 goal_column: u32,
2612 display_map: &DisplaySnapshot,
2613 window: &mut Window,
2614 cx: &mut Context<Self>,
2615 ) {
2616 let start_row = cmp::min(tail.row(), head.row());
2617 let end_row = cmp::max(tail.row(), head.row());
2618 let start_column = cmp::min(tail.column(), goal_column);
2619 let end_column = cmp::max(tail.column(), goal_column);
2620 let reversed = start_column < tail.column();
2621
2622 let selection_ranges = (start_row.0..=end_row.0)
2623 .map(DisplayRow)
2624 .filter_map(|row| {
2625 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2626 let start = display_map
2627 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2628 .to_point(display_map);
2629 let end = display_map
2630 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2631 .to_point(display_map);
2632 if reversed {
2633 Some(end..start)
2634 } else {
2635 Some(start..end)
2636 }
2637 } else {
2638 None
2639 }
2640 })
2641 .collect::<Vec<_>>();
2642
2643 self.change_selections(None, window, cx, |s| {
2644 s.select_ranges(selection_ranges);
2645 });
2646 cx.notify();
2647 }
2648
2649 pub fn has_pending_nonempty_selection(&self) -> bool {
2650 let pending_nonempty_selection = match self.selections.pending_anchor() {
2651 Some(Selection { start, end, .. }) => start != end,
2652 None => false,
2653 };
2654
2655 pending_nonempty_selection
2656 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2657 }
2658
2659 pub fn has_pending_selection(&self) -> bool {
2660 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2661 }
2662
2663 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2664 self.selection_mark_mode = false;
2665
2666 if self.clear_expanded_diff_hunks(cx) {
2667 cx.notify();
2668 return;
2669 }
2670 if self.dismiss_menus_and_popups(true, window, cx) {
2671 return;
2672 }
2673
2674 if self.mode == EditorMode::Full
2675 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2676 {
2677 return;
2678 }
2679
2680 cx.propagate();
2681 }
2682
2683 pub fn dismiss_menus_and_popups(
2684 &mut self,
2685 is_user_requested: bool,
2686 window: &mut Window,
2687 cx: &mut Context<Self>,
2688 ) -> bool {
2689 if self.take_rename(false, window, cx).is_some() {
2690 return true;
2691 }
2692
2693 if hide_hover(self, cx) {
2694 return true;
2695 }
2696
2697 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2698 return true;
2699 }
2700
2701 if self.hide_context_menu(window, cx).is_some() {
2702 return true;
2703 }
2704
2705 if self.mouse_context_menu.take().is_some() {
2706 return true;
2707 }
2708
2709 if is_user_requested && self.discard_inline_completion(true, cx) {
2710 return true;
2711 }
2712
2713 if self.snippet_stack.pop().is_some() {
2714 return true;
2715 }
2716
2717 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2718 self.dismiss_diagnostics(cx);
2719 return true;
2720 }
2721
2722 false
2723 }
2724
2725 fn linked_editing_ranges_for(
2726 &self,
2727 selection: Range<text::Anchor>,
2728 cx: &App,
2729 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2730 if self.linked_edit_ranges.is_empty() {
2731 return None;
2732 }
2733 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2734 selection.end.buffer_id.and_then(|end_buffer_id| {
2735 if selection.start.buffer_id != Some(end_buffer_id) {
2736 return None;
2737 }
2738 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2739 let snapshot = buffer.read(cx).snapshot();
2740 self.linked_edit_ranges
2741 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2742 .map(|ranges| (ranges, snapshot, buffer))
2743 })?;
2744 use text::ToOffset as TO;
2745 // find offset from the start of current range to current cursor position
2746 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2747
2748 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2749 let start_difference = start_offset - start_byte_offset;
2750 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2751 let end_difference = end_offset - start_byte_offset;
2752 // Current range has associated linked ranges.
2753 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2754 for range in linked_ranges.iter() {
2755 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2756 let end_offset = start_offset + end_difference;
2757 let start_offset = start_offset + start_difference;
2758 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2759 continue;
2760 }
2761 if self.selections.disjoint_anchor_ranges().any(|s| {
2762 if s.start.buffer_id != selection.start.buffer_id
2763 || s.end.buffer_id != selection.end.buffer_id
2764 {
2765 return false;
2766 }
2767 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2768 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2769 }) {
2770 continue;
2771 }
2772 let start = buffer_snapshot.anchor_after(start_offset);
2773 let end = buffer_snapshot.anchor_after(end_offset);
2774 linked_edits
2775 .entry(buffer.clone())
2776 .or_default()
2777 .push(start..end);
2778 }
2779 Some(linked_edits)
2780 }
2781
2782 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2783 let text: Arc<str> = text.into();
2784
2785 if self.read_only(cx) {
2786 return;
2787 }
2788
2789 let selections = self.selections.all_adjusted(cx);
2790 let mut bracket_inserted = false;
2791 let mut edits = Vec::new();
2792 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2793 let mut new_selections = Vec::with_capacity(selections.len());
2794 let mut new_autoclose_regions = Vec::new();
2795 let snapshot = self.buffer.read(cx).read(cx);
2796
2797 for (selection, autoclose_region) in
2798 self.selections_with_autoclose_regions(selections, &snapshot)
2799 {
2800 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2801 // Determine if the inserted text matches the opening or closing
2802 // bracket of any of this language's bracket pairs.
2803 let mut bracket_pair = None;
2804 let mut is_bracket_pair_start = false;
2805 let mut is_bracket_pair_end = false;
2806 if !text.is_empty() {
2807 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2808 // and they are removing the character that triggered IME popup.
2809 for (pair, enabled) in scope.brackets() {
2810 if !pair.close && !pair.surround {
2811 continue;
2812 }
2813
2814 if enabled && pair.start.ends_with(text.as_ref()) {
2815 let prefix_len = pair.start.len() - text.len();
2816 let preceding_text_matches_prefix = prefix_len == 0
2817 || (selection.start.column >= (prefix_len as u32)
2818 && snapshot.contains_str_at(
2819 Point::new(
2820 selection.start.row,
2821 selection.start.column - (prefix_len as u32),
2822 ),
2823 &pair.start[..prefix_len],
2824 ));
2825 if preceding_text_matches_prefix {
2826 bracket_pair = Some(pair.clone());
2827 is_bracket_pair_start = true;
2828 break;
2829 }
2830 }
2831 if pair.end.as_str() == text.as_ref() {
2832 bracket_pair = Some(pair.clone());
2833 is_bracket_pair_end = true;
2834 break;
2835 }
2836 }
2837 }
2838
2839 if let Some(bracket_pair) = bracket_pair {
2840 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2841 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2842 let auto_surround =
2843 self.use_auto_surround && snapshot_settings.use_auto_surround;
2844 if selection.is_empty() {
2845 if is_bracket_pair_start {
2846 // If the inserted text is a suffix of an opening bracket and the
2847 // selection is preceded by the rest of the opening bracket, then
2848 // insert the closing bracket.
2849 let following_text_allows_autoclose = snapshot
2850 .chars_at(selection.start)
2851 .next()
2852 .map_or(true, |c| scope.should_autoclose_before(c));
2853
2854 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2855 && bracket_pair.start.len() == 1
2856 {
2857 let target = bracket_pair.start.chars().next().unwrap();
2858 let current_line_count = snapshot
2859 .reversed_chars_at(selection.start)
2860 .take_while(|&c| c != '\n')
2861 .filter(|&c| c == target)
2862 .count();
2863 current_line_count % 2 == 1
2864 } else {
2865 false
2866 };
2867
2868 if autoclose
2869 && bracket_pair.close
2870 && following_text_allows_autoclose
2871 && !is_closing_quote
2872 {
2873 let anchor = snapshot.anchor_before(selection.end);
2874 new_selections.push((selection.map(|_| anchor), text.len()));
2875 new_autoclose_regions.push((
2876 anchor,
2877 text.len(),
2878 selection.id,
2879 bracket_pair.clone(),
2880 ));
2881 edits.push((
2882 selection.range(),
2883 format!("{}{}", text, bracket_pair.end).into(),
2884 ));
2885 bracket_inserted = true;
2886 continue;
2887 }
2888 }
2889
2890 if let Some(region) = autoclose_region {
2891 // If the selection is followed by an auto-inserted closing bracket,
2892 // then don't insert that closing bracket again; just move the selection
2893 // past the closing bracket.
2894 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2895 && text.as_ref() == region.pair.end.as_str();
2896 if should_skip {
2897 let anchor = snapshot.anchor_after(selection.end);
2898 new_selections
2899 .push((selection.map(|_| anchor), region.pair.end.len()));
2900 continue;
2901 }
2902 }
2903
2904 let always_treat_brackets_as_autoclosed = snapshot
2905 .settings_at(selection.start, cx)
2906 .always_treat_brackets_as_autoclosed;
2907 if always_treat_brackets_as_autoclosed
2908 && is_bracket_pair_end
2909 && snapshot.contains_str_at(selection.end, text.as_ref())
2910 {
2911 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2912 // and the inserted text is a closing bracket and the selection is followed
2913 // by the closing bracket then move the selection past the closing bracket.
2914 let anchor = snapshot.anchor_after(selection.end);
2915 new_selections.push((selection.map(|_| anchor), text.len()));
2916 continue;
2917 }
2918 }
2919 // If an opening bracket is 1 character long and is typed while
2920 // text is selected, then surround that text with the bracket pair.
2921 else if auto_surround
2922 && bracket_pair.surround
2923 && is_bracket_pair_start
2924 && bracket_pair.start.chars().count() == 1
2925 {
2926 edits.push((selection.start..selection.start, text.clone()));
2927 edits.push((
2928 selection.end..selection.end,
2929 bracket_pair.end.as_str().into(),
2930 ));
2931 bracket_inserted = true;
2932 new_selections.push((
2933 Selection {
2934 id: selection.id,
2935 start: snapshot.anchor_after(selection.start),
2936 end: snapshot.anchor_before(selection.end),
2937 reversed: selection.reversed,
2938 goal: selection.goal,
2939 },
2940 0,
2941 ));
2942 continue;
2943 }
2944 }
2945 }
2946
2947 if self.auto_replace_emoji_shortcode
2948 && selection.is_empty()
2949 && text.as_ref().ends_with(':')
2950 {
2951 if let Some(possible_emoji_short_code) =
2952 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2953 {
2954 if !possible_emoji_short_code.is_empty() {
2955 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2956 let emoji_shortcode_start = Point::new(
2957 selection.start.row,
2958 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2959 );
2960
2961 // Remove shortcode from buffer
2962 edits.push((
2963 emoji_shortcode_start..selection.start,
2964 "".to_string().into(),
2965 ));
2966 new_selections.push((
2967 Selection {
2968 id: selection.id,
2969 start: snapshot.anchor_after(emoji_shortcode_start),
2970 end: snapshot.anchor_before(selection.start),
2971 reversed: selection.reversed,
2972 goal: selection.goal,
2973 },
2974 0,
2975 ));
2976
2977 // Insert emoji
2978 let selection_start_anchor = snapshot.anchor_after(selection.start);
2979 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2980 edits.push((selection.start..selection.end, emoji.to_string().into()));
2981
2982 continue;
2983 }
2984 }
2985 }
2986 }
2987
2988 // If not handling any auto-close operation, then just replace the selected
2989 // text with the given input and move the selection to the end of the
2990 // newly inserted text.
2991 let anchor = snapshot.anchor_after(selection.end);
2992 if !self.linked_edit_ranges.is_empty() {
2993 let start_anchor = snapshot.anchor_before(selection.start);
2994
2995 let is_word_char = text.chars().next().map_or(true, |char| {
2996 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2997 classifier.is_word(char)
2998 });
2999
3000 if is_word_char {
3001 if let Some(ranges) = self
3002 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3003 {
3004 for (buffer, edits) in ranges {
3005 linked_edits
3006 .entry(buffer.clone())
3007 .or_default()
3008 .extend(edits.into_iter().map(|range| (range, text.clone())));
3009 }
3010 }
3011 }
3012 }
3013
3014 new_selections.push((selection.map(|_| anchor), 0));
3015 edits.push((selection.start..selection.end, text.clone()));
3016 }
3017
3018 drop(snapshot);
3019
3020 self.transact(window, cx, |this, window, cx| {
3021 this.buffer.update(cx, |buffer, cx| {
3022 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3023 });
3024 for (buffer, edits) in linked_edits {
3025 buffer.update(cx, |buffer, cx| {
3026 let snapshot = buffer.snapshot();
3027 let edits = edits
3028 .into_iter()
3029 .map(|(range, text)| {
3030 use text::ToPoint as TP;
3031 let end_point = TP::to_point(&range.end, &snapshot);
3032 let start_point = TP::to_point(&range.start, &snapshot);
3033 (start_point..end_point, text)
3034 })
3035 .sorted_by_key(|(range, _)| range.start)
3036 .collect::<Vec<_>>();
3037 buffer.edit(edits, None, cx);
3038 })
3039 }
3040 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3041 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3042 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3043 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3044 .zip(new_selection_deltas)
3045 .map(|(selection, delta)| Selection {
3046 id: selection.id,
3047 start: selection.start + delta,
3048 end: selection.end + delta,
3049 reversed: selection.reversed,
3050 goal: SelectionGoal::None,
3051 })
3052 .collect::<Vec<_>>();
3053
3054 let mut i = 0;
3055 for (position, delta, selection_id, pair) in new_autoclose_regions {
3056 let position = position.to_offset(&map.buffer_snapshot) + delta;
3057 let start = map.buffer_snapshot.anchor_before(position);
3058 let end = map.buffer_snapshot.anchor_after(position);
3059 while let Some(existing_state) = this.autoclose_regions.get(i) {
3060 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3061 Ordering::Less => i += 1,
3062 Ordering::Greater => break,
3063 Ordering::Equal => {
3064 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3065 Ordering::Less => i += 1,
3066 Ordering::Equal => break,
3067 Ordering::Greater => break,
3068 }
3069 }
3070 }
3071 }
3072 this.autoclose_regions.insert(
3073 i,
3074 AutocloseRegion {
3075 selection_id,
3076 range: start..end,
3077 pair,
3078 },
3079 );
3080 }
3081
3082 let had_active_inline_completion = this.has_active_inline_completion();
3083 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3084 s.select(new_selections)
3085 });
3086
3087 if !bracket_inserted {
3088 if let Some(on_type_format_task) =
3089 this.trigger_on_type_formatting(text.to_string(), window, cx)
3090 {
3091 on_type_format_task.detach_and_log_err(cx);
3092 }
3093 }
3094
3095 let editor_settings = EditorSettings::get_global(cx);
3096 if bracket_inserted
3097 && (editor_settings.auto_signature_help
3098 || editor_settings.show_signature_help_after_edits)
3099 {
3100 this.show_signature_help(&ShowSignatureHelp, window, cx);
3101 }
3102
3103 let trigger_in_words =
3104 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3105 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3106 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3107 this.refresh_inline_completion(true, false, window, cx);
3108 });
3109 }
3110
3111 fn find_possible_emoji_shortcode_at_position(
3112 snapshot: &MultiBufferSnapshot,
3113 position: Point,
3114 ) -> Option<String> {
3115 let mut chars = Vec::new();
3116 let mut found_colon = false;
3117 for char in snapshot.reversed_chars_at(position).take(100) {
3118 // Found a possible emoji shortcode in the middle of the buffer
3119 if found_colon {
3120 if char.is_whitespace() {
3121 chars.reverse();
3122 return Some(chars.iter().collect());
3123 }
3124 // If the previous character is not a whitespace, we are in the middle of a word
3125 // and we only want to complete the shortcode if the word is made up of other emojis
3126 let mut containing_word = String::new();
3127 for ch in snapshot
3128 .reversed_chars_at(position)
3129 .skip(chars.len() + 1)
3130 .take(100)
3131 {
3132 if ch.is_whitespace() {
3133 break;
3134 }
3135 containing_word.push(ch);
3136 }
3137 let containing_word = containing_word.chars().rev().collect::<String>();
3138 if util::word_consists_of_emojis(containing_word.as_str()) {
3139 chars.reverse();
3140 return Some(chars.iter().collect());
3141 }
3142 }
3143
3144 if char.is_whitespace() || !char.is_ascii() {
3145 return None;
3146 }
3147 if char == ':' {
3148 found_colon = true;
3149 } else {
3150 chars.push(char);
3151 }
3152 }
3153 // Found a possible emoji shortcode at the beginning of the buffer
3154 chars.reverse();
3155 Some(chars.iter().collect())
3156 }
3157
3158 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3159 self.transact(window, cx, |this, window, cx| {
3160 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3161 let selections = this.selections.all::<usize>(cx);
3162 let multi_buffer = this.buffer.read(cx);
3163 let buffer = multi_buffer.snapshot(cx);
3164 selections
3165 .iter()
3166 .map(|selection| {
3167 let start_point = selection.start.to_point(&buffer);
3168 let mut indent =
3169 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3170 indent.len = cmp::min(indent.len, start_point.column);
3171 let start = selection.start;
3172 let end = selection.end;
3173 let selection_is_empty = start == end;
3174 let language_scope = buffer.language_scope_at(start);
3175 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3176 &language_scope
3177 {
3178 let insert_extra_newline =
3179 insert_extra_newline_brackets(&buffer, start..end, language)
3180 || insert_extra_newline_tree_sitter(&buffer, start..end);
3181
3182 // Comment extension on newline is allowed only for cursor selections
3183 let comment_delimiter = maybe!({
3184 if !selection_is_empty {
3185 return None;
3186 }
3187
3188 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3189 return None;
3190 }
3191
3192 let delimiters = language.line_comment_prefixes();
3193 let max_len_of_delimiter =
3194 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3195 let (snapshot, range) =
3196 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3197
3198 let mut index_of_first_non_whitespace = 0;
3199 let comment_candidate = snapshot
3200 .chars_for_range(range)
3201 .skip_while(|c| {
3202 let should_skip = c.is_whitespace();
3203 if should_skip {
3204 index_of_first_non_whitespace += 1;
3205 }
3206 should_skip
3207 })
3208 .take(max_len_of_delimiter)
3209 .collect::<String>();
3210 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3211 comment_candidate.starts_with(comment_prefix.as_ref())
3212 })?;
3213 let cursor_is_placed_after_comment_marker =
3214 index_of_first_non_whitespace + comment_prefix.len()
3215 <= start_point.column as usize;
3216 if cursor_is_placed_after_comment_marker {
3217 Some(comment_prefix.clone())
3218 } else {
3219 None
3220 }
3221 });
3222 (comment_delimiter, insert_extra_newline)
3223 } else {
3224 (None, false)
3225 };
3226
3227 let capacity_for_delimiter = comment_delimiter
3228 .as_deref()
3229 .map(str::len)
3230 .unwrap_or_default();
3231 let mut new_text =
3232 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3233 new_text.push('\n');
3234 new_text.extend(indent.chars());
3235 if let Some(delimiter) = &comment_delimiter {
3236 new_text.push_str(delimiter);
3237 }
3238 if insert_extra_newline {
3239 new_text = new_text.repeat(2);
3240 }
3241
3242 let anchor = buffer.anchor_after(end);
3243 let new_selection = selection.map(|_| anchor);
3244 (
3245 (start..end, new_text),
3246 (insert_extra_newline, new_selection),
3247 )
3248 })
3249 .unzip()
3250 };
3251
3252 this.edit_with_autoindent(edits, cx);
3253 let buffer = this.buffer.read(cx).snapshot(cx);
3254 let new_selections = selection_fixup_info
3255 .into_iter()
3256 .map(|(extra_newline_inserted, new_selection)| {
3257 let mut cursor = new_selection.end.to_point(&buffer);
3258 if extra_newline_inserted {
3259 cursor.row -= 1;
3260 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3261 }
3262 new_selection.map(|_| cursor)
3263 })
3264 .collect();
3265
3266 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3267 s.select(new_selections)
3268 });
3269 this.refresh_inline_completion(true, false, window, cx);
3270 });
3271 }
3272
3273 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3274 let buffer = self.buffer.read(cx);
3275 let snapshot = buffer.snapshot(cx);
3276
3277 let mut edits = Vec::new();
3278 let mut rows = Vec::new();
3279
3280 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3281 let cursor = selection.head();
3282 let row = cursor.row;
3283
3284 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3285
3286 let newline = "\n".to_string();
3287 edits.push((start_of_line..start_of_line, newline));
3288
3289 rows.push(row + rows_inserted as u32);
3290 }
3291
3292 self.transact(window, cx, |editor, window, cx| {
3293 editor.edit(edits, cx);
3294
3295 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3296 let mut index = 0;
3297 s.move_cursors_with(|map, _, _| {
3298 let row = rows[index];
3299 index += 1;
3300
3301 let point = Point::new(row, 0);
3302 let boundary = map.next_line_boundary(point).1;
3303 let clipped = map.clip_point(boundary, Bias::Left);
3304
3305 (clipped, SelectionGoal::None)
3306 });
3307 });
3308
3309 let mut indent_edits = Vec::new();
3310 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3311 for row in rows {
3312 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3313 for (row, indent) in indents {
3314 if indent.len == 0 {
3315 continue;
3316 }
3317
3318 let text = match indent.kind {
3319 IndentKind::Space => " ".repeat(indent.len as usize),
3320 IndentKind::Tab => "\t".repeat(indent.len as usize),
3321 };
3322 let point = Point::new(row.0, 0);
3323 indent_edits.push((point..point, text));
3324 }
3325 }
3326 editor.edit(indent_edits, cx);
3327 });
3328 }
3329
3330 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3331 let buffer = self.buffer.read(cx);
3332 let snapshot = buffer.snapshot(cx);
3333
3334 let mut edits = Vec::new();
3335 let mut rows = Vec::new();
3336 let mut rows_inserted = 0;
3337
3338 for selection in self.selections.all_adjusted(cx) {
3339 let cursor = selection.head();
3340 let row = cursor.row;
3341
3342 let point = Point::new(row + 1, 0);
3343 let start_of_line = snapshot.clip_point(point, Bias::Left);
3344
3345 let newline = "\n".to_string();
3346 edits.push((start_of_line..start_of_line, newline));
3347
3348 rows_inserted += 1;
3349 rows.push(row + rows_inserted);
3350 }
3351
3352 self.transact(window, cx, |editor, window, cx| {
3353 editor.edit(edits, cx);
3354
3355 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3356 let mut index = 0;
3357 s.move_cursors_with(|map, _, _| {
3358 let row = rows[index];
3359 index += 1;
3360
3361 let point = Point::new(row, 0);
3362 let boundary = map.next_line_boundary(point).1;
3363 let clipped = map.clip_point(boundary, Bias::Left);
3364
3365 (clipped, SelectionGoal::None)
3366 });
3367 });
3368
3369 let mut indent_edits = Vec::new();
3370 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3371 for row in rows {
3372 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3373 for (row, indent) in indents {
3374 if indent.len == 0 {
3375 continue;
3376 }
3377
3378 let text = match indent.kind {
3379 IndentKind::Space => " ".repeat(indent.len as usize),
3380 IndentKind::Tab => "\t".repeat(indent.len as usize),
3381 };
3382 let point = Point::new(row.0, 0);
3383 indent_edits.push((point..point, text));
3384 }
3385 }
3386 editor.edit(indent_edits, cx);
3387 });
3388 }
3389
3390 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3391 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3392 original_start_columns: Vec::new(),
3393 });
3394 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3395 }
3396
3397 fn insert_with_autoindent_mode(
3398 &mut self,
3399 text: &str,
3400 autoindent_mode: Option<AutoindentMode>,
3401 window: &mut Window,
3402 cx: &mut Context<Self>,
3403 ) {
3404 if self.read_only(cx) {
3405 return;
3406 }
3407
3408 let text: Arc<str> = text.into();
3409 self.transact(window, cx, |this, window, cx| {
3410 let old_selections = this.selections.all_adjusted(cx);
3411 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3412 let anchors = {
3413 let snapshot = buffer.read(cx);
3414 old_selections
3415 .iter()
3416 .map(|s| {
3417 let anchor = snapshot.anchor_after(s.head());
3418 s.map(|_| anchor)
3419 })
3420 .collect::<Vec<_>>()
3421 };
3422 buffer.edit(
3423 old_selections
3424 .iter()
3425 .map(|s| (s.start..s.end, text.clone())),
3426 autoindent_mode,
3427 cx,
3428 );
3429 anchors
3430 });
3431
3432 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3433 s.select_anchors(selection_anchors);
3434 });
3435
3436 cx.notify();
3437 });
3438 }
3439
3440 fn trigger_completion_on_input(
3441 &mut self,
3442 text: &str,
3443 trigger_in_words: bool,
3444 window: &mut Window,
3445 cx: &mut Context<Self>,
3446 ) {
3447 if self.is_completion_trigger(text, trigger_in_words, cx) {
3448 self.show_completions(
3449 &ShowCompletions {
3450 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3451 },
3452 window,
3453 cx,
3454 );
3455 } else {
3456 self.hide_context_menu(window, cx);
3457 }
3458 }
3459
3460 fn is_completion_trigger(
3461 &self,
3462 text: &str,
3463 trigger_in_words: bool,
3464 cx: &mut Context<Self>,
3465 ) -> bool {
3466 let position = self.selections.newest_anchor().head();
3467 let multibuffer = self.buffer.read(cx);
3468 let Some(buffer) = position
3469 .buffer_id
3470 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3471 else {
3472 return false;
3473 };
3474
3475 if let Some(completion_provider) = &self.completion_provider {
3476 completion_provider.is_completion_trigger(
3477 &buffer,
3478 position.text_anchor,
3479 text,
3480 trigger_in_words,
3481 cx,
3482 )
3483 } else {
3484 false
3485 }
3486 }
3487
3488 /// If any empty selections is touching the start of its innermost containing autoclose
3489 /// region, expand it to select the brackets.
3490 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3491 let selections = self.selections.all::<usize>(cx);
3492 let buffer = self.buffer.read(cx).read(cx);
3493 let new_selections = self
3494 .selections_with_autoclose_regions(selections, &buffer)
3495 .map(|(mut selection, region)| {
3496 if !selection.is_empty() {
3497 return selection;
3498 }
3499
3500 if let Some(region) = region {
3501 let mut range = region.range.to_offset(&buffer);
3502 if selection.start == range.start && range.start >= region.pair.start.len() {
3503 range.start -= region.pair.start.len();
3504 if buffer.contains_str_at(range.start, ®ion.pair.start)
3505 && buffer.contains_str_at(range.end, ®ion.pair.end)
3506 {
3507 range.end += region.pair.end.len();
3508 selection.start = range.start;
3509 selection.end = range.end;
3510
3511 return selection;
3512 }
3513 }
3514 }
3515
3516 let always_treat_brackets_as_autoclosed = buffer
3517 .settings_at(selection.start, cx)
3518 .always_treat_brackets_as_autoclosed;
3519
3520 if !always_treat_brackets_as_autoclosed {
3521 return selection;
3522 }
3523
3524 if let Some(scope) = buffer.language_scope_at(selection.start) {
3525 for (pair, enabled) in scope.brackets() {
3526 if !enabled || !pair.close {
3527 continue;
3528 }
3529
3530 if buffer.contains_str_at(selection.start, &pair.end) {
3531 let pair_start_len = pair.start.len();
3532 if buffer.contains_str_at(
3533 selection.start.saturating_sub(pair_start_len),
3534 &pair.start,
3535 ) {
3536 selection.start -= pair_start_len;
3537 selection.end += pair.end.len();
3538
3539 return selection;
3540 }
3541 }
3542 }
3543 }
3544
3545 selection
3546 })
3547 .collect();
3548
3549 drop(buffer);
3550 self.change_selections(None, window, cx, |selections| {
3551 selections.select(new_selections)
3552 });
3553 }
3554
3555 /// Iterate the given selections, and for each one, find the smallest surrounding
3556 /// autoclose region. This uses the ordering of the selections and the autoclose
3557 /// regions to avoid repeated comparisons.
3558 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3559 &'a self,
3560 selections: impl IntoIterator<Item = Selection<D>>,
3561 buffer: &'a MultiBufferSnapshot,
3562 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3563 let mut i = 0;
3564 let mut regions = self.autoclose_regions.as_slice();
3565 selections.into_iter().map(move |selection| {
3566 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3567
3568 let mut enclosing = None;
3569 while let Some(pair_state) = regions.get(i) {
3570 if pair_state.range.end.to_offset(buffer) < range.start {
3571 regions = ®ions[i + 1..];
3572 i = 0;
3573 } else if pair_state.range.start.to_offset(buffer) > range.end {
3574 break;
3575 } else {
3576 if pair_state.selection_id == selection.id {
3577 enclosing = Some(pair_state);
3578 }
3579 i += 1;
3580 }
3581 }
3582
3583 (selection, enclosing)
3584 })
3585 }
3586
3587 /// Remove any autoclose regions that no longer contain their selection.
3588 fn invalidate_autoclose_regions(
3589 &mut self,
3590 mut selections: &[Selection<Anchor>],
3591 buffer: &MultiBufferSnapshot,
3592 ) {
3593 self.autoclose_regions.retain(|state| {
3594 let mut i = 0;
3595 while let Some(selection) = selections.get(i) {
3596 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3597 selections = &selections[1..];
3598 continue;
3599 }
3600 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3601 break;
3602 }
3603 if selection.id == state.selection_id {
3604 return true;
3605 } else {
3606 i += 1;
3607 }
3608 }
3609 false
3610 });
3611 }
3612
3613 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3614 let offset = position.to_offset(buffer);
3615 let (word_range, kind) = buffer.surrounding_word(offset, true);
3616 if offset > word_range.start && kind == Some(CharKind::Word) {
3617 Some(
3618 buffer
3619 .text_for_range(word_range.start..offset)
3620 .collect::<String>(),
3621 )
3622 } else {
3623 None
3624 }
3625 }
3626
3627 pub fn toggle_inlay_hints(
3628 &mut self,
3629 _: &ToggleInlayHints,
3630 _: &mut Window,
3631 cx: &mut Context<Self>,
3632 ) {
3633 self.refresh_inlay_hints(
3634 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3635 cx,
3636 );
3637 }
3638
3639 pub fn inlay_hints_enabled(&self) -> bool {
3640 self.inlay_hint_cache.enabled
3641 }
3642
3643 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3644 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3645 return;
3646 }
3647
3648 let reason_description = reason.description();
3649 let ignore_debounce = matches!(
3650 reason,
3651 InlayHintRefreshReason::SettingsChange(_)
3652 | InlayHintRefreshReason::Toggle(_)
3653 | InlayHintRefreshReason::ExcerptsRemoved(_)
3654 );
3655 let (invalidate_cache, required_languages) = match reason {
3656 InlayHintRefreshReason::Toggle(enabled) => {
3657 self.inlay_hint_cache.enabled = enabled;
3658 if enabled {
3659 (InvalidationStrategy::RefreshRequested, None)
3660 } else {
3661 self.inlay_hint_cache.clear();
3662 self.splice_inlays(
3663 &self
3664 .visible_inlay_hints(cx)
3665 .iter()
3666 .map(|inlay| inlay.id)
3667 .collect::<Vec<InlayId>>(),
3668 Vec::new(),
3669 cx,
3670 );
3671 return;
3672 }
3673 }
3674 InlayHintRefreshReason::SettingsChange(new_settings) => {
3675 match self.inlay_hint_cache.update_settings(
3676 &self.buffer,
3677 new_settings,
3678 self.visible_inlay_hints(cx),
3679 cx,
3680 ) {
3681 ControlFlow::Break(Some(InlaySplice {
3682 to_remove,
3683 to_insert,
3684 })) => {
3685 self.splice_inlays(&to_remove, to_insert, cx);
3686 return;
3687 }
3688 ControlFlow::Break(None) => return,
3689 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3690 }
3691 }
3692 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3693 if let Some(InlaySplice {
3694 to_remove,
3695 to_insert,
3696 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3697 {
3698 self.splice_inlays(&to_remove, to_insert, cx);
3699 }
3700 return;
3701 }
3702 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3703 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3704 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3705 }
3706 InlayHintRefreshReason::RefreshRequested => {
3707 (InvalidationStrategy::RefreshRequested, None)
3708 }
3709 };
3710
3711 if let Some(InlaySplice {
3712 to_remove,
3713 to_insert,
3714 }) = self.inlay_hint_cache.spawn_hint_refresh(
3715 reason_description,
3716 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3717 invalidate_cache,
3718 ignore_debounce,
3719 cx,
3720 ) {
3721 self.splice_inlays(&to_remove, to_insert, cx);
3722 }
3723 }
3724
3725 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3726 self.display_map
3727 .read(cx)
3728 .current_inlays()
3729 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3730 .cloned()
3731 .collect()
3732 }
3733
3734 pub fn excerpts_for_inlay_hints_query(
3735 &self,
3736 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3737 cx: &mut Context<Editor>,
3738 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3739 let Some(project) = self.project.as_ref() else {
3740 return HashMap::default();
3741 };
3742 let project = project.read(cx);
3743 let multi_buffer = self.buffer().read(cx);
3744 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3745 let multi_buffer_visible_start = self
3746 .scroll_manager
3747 .anchor()
3748 .anchor
3749 .to_point(&multi_buffer_snapshot);
3750 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3751 multi_buffer_visible_start
3752 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3753 Bias::Left,
3754 );
3755 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3756 multi_buffer_snapshot
3757 .range_to_buffer_ranges(multi_buffer_visible_range)
3758 .into_iter()
3759 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3760 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3761 let buffer_file = project::File::from_dyn(buffer.file())?;
3762 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3763 let worktree_entry = buffer_worktree
3764 .read(cx)
3765 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3766 if worktree_entry.is_ignored {
3767 return None;
3768 }
3769
3770 let language = buffer.language()?;
3771 if let Some(restrict_to_languages) = restrict_to_languages {
3772 if !restrict_to_languages.contains(language) {
3773 return None;
3774 }
3775 }
3776 Some((
3777 excerpt_id,
3778 (
3779 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3780 buffer.version().clone(),
3781 excerpt_visible_range,
3782 ),
3783 ))
3784 })
3785 .collect()
3786 }
3787
3788 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3789 TextLayoutDetails {
3790 text_system: window.text_system().clone(),
3791 editor_style: self.style.clone().unwrap(),
3792 rem_size: window.rem_size(),
3793 scroll_anchor: self.scroll_manager.anchor(),
3794 visible_rows: self.visible_line_count(),
3795 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3796 }
3797 }
3798
3799 pub fn splice_inlays(
3800 &self,
3801 to_remove: &[InlayId],
3802 to_insert: Vec<Inlay>,
3803 cx: &mut Context<Self>,
3804 ) {
3805 self.display_map.update(cx, |display_map, cx| {
3806 display_map.splice_inlays(to_remove, to_insert, cx)
3807 });
3808 cx.notify();
3809 }
3810
3811 fn trigger_on_type_formatting(
3812 &self,
3813 input: String,
3814 window: &mut Window,
3815 cx: &mut Context<Self>,
3816 ) -> Option<Task<Result<()>>> {
3817 if input.len() != 1 {
3818 return None;
3819 }
3820
3821 let project = self.project.as_ref()?;
3822 let position = self.selections.newest_anchor().head();
3823 let (buffer, buffer_position) = self
3824 .buffer
3825 .read(cx)
3826 .text_anchor_for_position(position, cx)?;
3827
3828 let settings = language_settings::language_settings(
3829 buffer
3830 .read(cx)
3831 .language_at(buffer_position)
3832 .map(|l| l.name()),
3833 buffer.read(cx).file(),
3834 cx,
3835 );
3836 if !settings.use_on_type_format {
3837 return None;
3838 }
3839
3840 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3841 // hence we do LSP request & edit on host side only — add formats to host's history.
3842 let push_to_lsp_host_history = true;
3843 // If this is not the host, append its history with new edits.
3844 let push_to_client_history = project.read(cx).is_via_collab();
3845
3846 let on_type_formatting = project.update(cx, |project, cx| {
3847 project.on_type_format(
3848 buffer.clone(),
3849 buffer_position,
3850 input,
3851 push_to_lsp_host_history,
3852 cx,
3853 )
3854 });
3855 Some(cx.spawn_in(window, |editor, mut cx| async move {
3856 if let Some(transaction) = on_type_formatting.await? {
3857 if push_to_client_history {
3858 buffer
3859 .update(&mut cx, |buffer, _| {
3860 buffer.push_transaction(transaction, Instant::now());
3861 })
3862 .ok();
3863 }
3864 editor.update(&mut cx, |editor, cx| {
3865 editor.refresh_document_highlights(cx);
3866 })?;
3867 }
3868 Ok(())
3869 }))
3870 }
3871
3872 pub fn show_completions(
3873 &mut self,
3874 options: &ShowCompletions,
3875 window: &mut Window,
3876 cx: &mut Context<Self>,
3877 ) {
3878 if self.pending_rename.is_some() {
3879 return;
3880 }
3881
3882 let Some(provider) = self.completion_provider.as_ref() else {
3883 return;
3884 };
3885
3886 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3887 return;
3888 }
3889
3890 let position = self.selections.newest_anchor().head();
3891 if position.diff_base_anchor.is_some() {
3892 return;
3893 }
3894 let (buffer, buffer_position) =
3895 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3896 output
3897 } else {
3898 return;
3899 };
3900 let show_completion_documentation = buffer
3901 .read(cx)
3902 .snapshot()
3903 .settings_at(buffer_position, cx)
3904 .show_completion_documentation;
3905
3906 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3907
3908 let trigger_kind = match &options.trigger {
3909 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3910 CompletionTriggerKind::TRIGGER_CHARACTER
3911 }
3912 _ => CompletionTriggerKind::INVOKED,
3913 };
3914 let completion_context = CompletionContext {
3915 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3916 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3917 Some(String::from(trigger))
3918 } else {
3919 None
3920 }
3921 }),
3922 trigger_kind,
3923 };
3924 let completions =
3925 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3926 let sort_completions = provider.sort_completions();
3927
3928 let id = post_inc(&mut self.next_completion_id);
3929 let task = cx.spawn_in(window, |editor, mut cx| {
3930 async move {
3931 editor.update(&mut cx, |this, _| {
3932 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3933 })?;
3934 let completions = completions.await.log_err();
3935 let menu = if let Some(completions) = completions {
3936 let mut menu = CompletionsMenu::new(
3937 id,
3938 sort_completions,
3939 show_completion_documentation,
3940 position,
3941 buffer.clone(),
3942 completions.into(),
3943 );
3944
3945 menu.filter(query.as_deref(), cx.background_executor().clone())
3946 .await;
3947
3948 menu.visible().then_some(menu)
3949 } else {
3950 None
3951 };
3952
3953 editor.update_in(&mut cx, |editor, window, cx| {
3954 match editor.context_menu.borrow().as_ref() {
3955 None => {}
3956 Some(CodeContextMenu::Completions(prev_menu)) => {
3957 if prev_menu.id > id {
3958 return;
3959 }
3960 }
3961 _ => return,
3962 }
3963
3964 if editor.focus_handle.is_focused(window) && menu.is_some() {
3965 let mut menu = menu.unwrap();
3966 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3967
3968 *editor.context_menu.borrow_mut() =
3969 Some(CodeContextMenu::Completions(menu));
3970
3971 if editor.show_edit_predictions_in_menu() {
3972 editor.update_visible_inline_completion(window, cx);
3973 } else {
3974 editor.discard_inline_completion(false, cx);
3975 }
3976
3977 cx.notify();
3978 } else if editor.completion_tasks.len() <= 1 {
3979 // If there are no more completion tasks and the last menu was
3980 // empty, we should hide it.
3981 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3982 // If it was already hidden and we don't show inline
3983 // completions in the menu, we should also show the
3984 // inline-completion when available.
3985 if was_hidden && editor.show_edit_predictions_in_menu() {
3986 editor.update_visible_inline_completion(window, cx);
3987 }
3988 }
3989 })?;
3990
3991 Ok::<_, anyhow::Error>(())
3992 }
3993 .log_err()
3994 });
3995
3996 self.completion_tasks.push((id, task));
3997 }
3998
3999 pub fn confirm_completion(
4000 &mut self,
4001 action: &ConfirmCompletion,
4002 window: &mut Window,
4003 cx: &mut Context<Self>,
4004 ) -> Option<Task<Result<()>>> {
4005 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4006 }
4007
4008 pub fn compose_completion(
4009 &mut self,
4010 action: &ComposeCompletion,
4011 window: &mut Window,
4012 cx: &mut Context<Self>,
4013 ) -> Option<Task<Result<()>>> {
4014 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4015 }
4016
4017 fn do_completion(
4018 &mut self,
4019 item_ix: Option<usize>,
4020 intent: CompletionIntent,
4021 window: &mut Window,
4022 cx: &mut Context<Editor>,
4023 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4024 use language::ToOffset as _;
4025
4026 let completions_menu =
4027 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4028 menu
4029 } else {
4030 return None;
4031 };
4032
4033 let entries = completions_menu.entries.borrow();
4034 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4035 if self.show_edit_predictions_in_menu() {
4036 self.discard_inline_completion(true, cx);
4037 }
4038 let candidate_id = mat.candidate_id;
4039 drop(entries);
4040
4041 let buffer_handle = completions_menu.buffer;
4042 let completion = completions_menu
4043 .completions
4044 .borrow()
4045 .get(candidate_id)?
4046 .clone();
4047 cx.stop_propagation();
4048
4049 let snippet;
4050 let text;
4051
4052 if completion.is_snippet() {
4053 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4054 text = snippet.as_ref().unwrap().text.clone();
4055 } else {
4056 snippet = None;
4057 text = completion.new_text.clone();
4058 };
4059 let selections = self.selections.all::<usize>(cx);
4060 let buffer = buffer_handle.read(cx);
4061 let old_range = completion.old_range.to_offset(buffer);
4062 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4063
4064 let newest_selection = self.selections.newest_anchor();
4065 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4066 return None;
4067 }
4068
4069 let lookbehind = newest_selection
4070 .start
4071 .text_anchor
4072 .to_offset(buffer)
4073 .saturating_sub(old_range.start);
4074 let lookahead = old_range
4075 .end
4076 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4077 let mut common_prefix_len = old_text
4078 .bytes()
4079 .zip(text.bytes())
4080 .take_while(|(a, b)| a == b)
4081 .count();
4082
4083 let snapshot = self.buffer.read(cx).snapshot(cx);
4084 let mut range_to_replace: Option<Range<isize>> = None;
4085 let mut ranges = Vec::new();
4086 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4087 for selection in &selections {
4088 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4089 let start = selection.start.saturating_sub(lookbehind);
4090 let end = selection.end + lookahead;
4091 if selection.id == newest_selection.id {
4092 range_to_replace = Some(
4093 ((start + common_prefix_len) as isize - selection.start as isize)
4094 ..(end as isize - selection.start as isize),
4095 );
4096 }
4097 ranges.push(start + common_prefix_len..end);
4098 } else {
4099 common_prefix_len = 0;
4100 ranges.clear();
4101 ranges.extend(selections.iter().map(|s| {
4102 if s.id == newest_selection.id {
4103 range_to_replace = Some(
4104 old_range.start.to_offset_utf16(&snapshot).0 as isize
4105 - selection.start as isize
4106 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4107 - selection.start as isize,
4108 );
4109 old_range.clone()
4110 } else {
4111 s.start..s.end
4112 }
4113 }));
4114 break;
4115 }
4116 if !self.linked_edit_ranges.is_empty() {
4117 let start_anchor = snapshot.anchor_before(selection.head());
4118 let end_anchor = snapshot.anchor_after(selection.tail());
4119 if let Some(ranges) = self
4120 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4121 {
4122 for (buffer, edits) in ranges {
4123 linked_edits.entry(buffer.clone()).or_default().extend(
4124 edits
4125 .into_iter()
4126 .map(|range| (range, text[common_prefix_len..].to_owned())),
4127 );
4128 }
4129 }
4130 }
4131 }
4132 let text = &text[common_prefix_len..];
4133
4134 cx.emit(EditorEvent::InputHandled {
4135 utf16_range_to_replace: range_to_replace,
4136 text: text.into(),
4137 });
4138
4139 self.transact(window, cx, |this, window, cx| {
4140 if let Some(mut snippet) = snippet {
4141 snippet.text = text.to_string();
4142 for tabstop in snippet
4143 .tabstops
4144 .iter_mut()
4145 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4146 {
4147 tabstop.start -= common_prefix_len as isize;
4148 tabstop.end -= common_prefix_len as isize;
4149 }
4150
4151 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4152 } else {
4153 this.buffer.update(cx, |buffer, cx| {
4154 buffer.edit(
4155 ranges.iter().map(|range| (range.clone(), text)),
4156 this.autoindent_mode.clone(),
4157 cx,
4158 );
4159 });
4160 }
4161 for (buffer, edits) in linked_edits {
4162 buffer.update(cx, |buffer, cx| {
4163 let snapshot = buffer.snapshot();
4164 let edits = edits
4165 .into_iter()
4166 .map(|(range, text)| {
4167 use text::ToPoint as TP;
4168 let end_point = TP::to_point(&range.end, &snapshot);
4169 let start_point = TP::to_point(&range.start, &snapshot);
4170 (start_point..end_point, text)
4171 })
4172 .sorted_by_key(|(range, _)| range.start)
4173 .collect::<Vec<_>>();
4174 buffer.edit(edits, None, cx);
4175 })
4176 }
4177
4178 this.refresh_inline_completion(true, false, window, cx);
4179 });
4180
4181 let show_new_completions_on_confirm = completion
4182 .confirm
4183 .as_ref()
4184 .map_or(false, |confirm| confirm(intent, window, cx));
4185 if show_new_completions_on_confirm {
4186 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4187 }
4188
4189 let provider = self.completion_provider.as_ref()?;
4190 drop(completion);
4191 let apply_edits = provider.apply_additional_edits_for_completion(
4192 buffer_handle,
4193 completions_menu.completions.clone(),
4194 candidate_id,
4195 true,
4196 cx,
4197 );
4198
4199 let editor_settings = EditorSettings::get_global(cx);
4200 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4201 // After the code completion is finished, users often want to know what signatures are needed.
4202 // so we should automatically call signature_help
4203 self.show_signature_help(&ShowSignatureHelp, window, cx);
4204 }
4205
4206 Some(cx.foreground_executor().spawn(async move {
4207 apply_edits.await?;
4208 Ok(())
4209 }))
4210 }
4211
4212 pub fn toggle_code_actions(
4213 &mut self,
4214 action: &ToggleCodeActions,
4215 window: &mut Window,
4216 cx: &mut Context<Self>,
4217 ) {
4218 let mut context_menu = self.context_menu.borrow_mut();
4219 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4220 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4221 // Toggle if we're selecting the same one
4222 *context_menu = None;
4223 cx.notify();
4224 return;
4225 } else {
4226 // Otherwise, clear it and start a new one
4227 *context_menu = None;
4228 cx.notify();
4229 }
4230 }
4231 drop(context_menu);
4232 let snapshot = self.snapshot(window, cx);
4233 let deployed_from_indicator = action.deployed_from_indicator;
4234 let mut task = self.code_actions_task.take();
4235 let action = action.clone();
4236 cx.spawn_in(window, |editor, mut cx| async move {
4237 while let Some(prev_task) = task {
4238 prev_task.await.log_err();
4239 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4240 }
4241
4242 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4243 if editor.focus_handle.is_focused(window) {
4244 let multibuffer_point = action
4245 .deployed_from_indicator
4246 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4247 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4248 let (buffer, buffer_row) = snapshot
4249 .buffer_snapshot
4250 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4251 .and_then(|(buffer_snapshot, range)| {
4252 editor
4253 .buffer
4254 .read(cx)
4255 .buffer(buffer_snapshot.remote_id())
4256 .map(|buffer| (buffer, range.start.row))
4257 })?;
4258 let (_, code_actions) = editor
4259 .available_code_actions
4260 .clone()
4261 .and_then(|(location, code_actions)| {
4262 let snapshot = location.buffer.read(cx).snapshot();
4263 let point_range = location.range.to_point(&snapshot);
4264 let point_range = point_range.start.row..=point_range.end.row;
4265 if point_range.contains(&buffer_row) {
4266 Some((location, code_actions))
4267 } else {
4268 None
4269 }
4270 })
4271 .unzip();
4272 let buffer_id = buffer.read(cx).remote_id();
4273 let tasks = editor
4274 .tasks
4275 .get(&(buffer_id, buffer_row))
4276 .map(|t| Arc::new(t.to_owned()));
4277 if tasks.is_none() && code_actions.is_none() {
4278 return None;
4279 }
4280
4281 editor.completion_tasks.clear();
4282 editor.discard_inline_completion(false, cx);
4283 let task_context =
4284 tasks
4285 .as_ref()
4286 .zip(editor.project.clone())
4287 .map(|(tasks, project)| {
4288 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4289 });
4290
4291 Some(cx.spawn_in(window, |editor, mut cx| async move {
4292 let task_context = match task_context {
4293 Some(task_context) => task_context.await,
4294 None => None,
4295 };
4296 let resolved_tasks =
4297 tasks.zip(task_context).map(|(tasks, task_context)| {
4298 Rc::new(ResolvedTasks {
4299 templates: tasks.resolve(&task_context).collect(),
4300 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4301 multibuffer_point.row,
4302 tasks.column,
4303 )),
4304 })
4305 });
4306 let spawn_straight_away = resolved_tasks
4307 .as_ref()
4308 .map_or(false, |tasks| tasks.templates.len() == 1)
4309 && code_actions
4310 .as_ref()
4311 .map_or(true, |actions| actions.is_empty());
4312 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4313 *editor.context_menu.borrow_mut() =
4314 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4315 buffer,
4316 actions: CodeActionContents {
4317 tasks: resolved_tasks,
4318 actions: code_actions,
4319 },
4320 selected_item: Default::default(),
4321 scroll_handle: UniformListScrollHandle::default(),
4322 deployed_from_indicator,
4323 }));
4324 if spawn_straight_away {
4325 if let Some(task) = editor.confirm_code_action(
4326 &ConfirmCodeAction { item_ix: Some(0) },
4327 window,
4328 cx,
4329 ) {
4330 cx.notify();
4331 return task;
4332 }
4333 }
4334 cx.notify();
4335 Task::ready(Ok(()))
4336 }) {
4337 task.await
4338 } else {
4339 Ok(())
4340 }
4341 }))
4342 } else {
4343 Some(Task::ready(Ok(())))
4344 }
4345 })?;
4346 if let Some(task) = spawned_test_task {
4347 task.await?;
4348 }
4349
4350 Ok::<_, anyhow::Error>(())
4351 })
4352 .detach_and_log_err(cx);
4353 }
4354
4355 pub fn confirm_code_action(
4356 &mut self,
4357 action: &ConfirmCodeAction,
4358 window: &mut Window,
4359 cx: &mut Context<Self>,
4360 ) -> Option<Task<Result<()>>> {
4361 let actions_menu =
4362 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4363 menu
4364 } else {
4365 return None;
4366 };
4367 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4368 let action = actions_menu.actions.get(action_ix)?;
4369 let title = action.label();
4370 let buffer = actions_menu.buffer;
4371 let workspace = self.workspace()?;
4372
4373 match action {
4374 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4375 workspace.update(cx, |workspace, cx| {
4376 workspace::tasks::schedule_resolved_task(
4377 workspace,
4378 task_source_kind,
4379 resolved_task,
4380 false,
4381 cx,
4382 );
4383
4384 Some(Task::ready(Ok(())))
4385 })
4386 }
4387 CodeActionsItem::CodeAction {
4388 excerpt_id,
4389 action,
4390 provider,
4391 } => {
4392 let apply_code_action =
4393 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4394 let workspace = workspace.downgrade();
4395 Some(cx.spawn_in(window, |editor, cx| async move {
4396 let project_transaction = apply_code_action.await?;
4397 Self::open_project_transaction(
4398 &editor,
4399 workspace,
4400 project_transaction,
4401 title,
4402 cx,
4403 )
4404 .await
4405 }))
4406 }
4407 }
4408 }
4409
4410 pub async fn open_project_transaction(
4411 this: &WeakEntity<Editor>,
4412 workspace: WeakEntity<Workspace>,
4413 transaction: ProjectTransaction,
4414 title: String,
4415 mut cx: AsyncWindowContext,
4416 ) -> Result<()> {
4417 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4418 cx.update(|_, cx| {
4419 entries.sort_unstable_by_key(|(buffer, _)| {
4420 buffer.read(cx).file().map(|f| f.path().clone())
4421 });
4422 })?;
4423
4424 // If the project transaction's edits are all contained within this editor, then
4425 // avoid opening a new editor to display them.
4426
4427 if let Some((buffer, transaction)) = entries.first() {
4428 if entries.len() == 1 {
4429 let excerpt = this.update(&mut cx, |editor, cx| {
4430 editor
4431 .buffer()
4432 .read(cx)
4433 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4434 })?;
4435 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4436 if excerpted_buffer == *buffer {
4437 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4438 let excerpt_range = excerpt_range.to_offset(buffer);
4439 buffer
4440 .edited_ranges_for_transaction::<usize>(transaction)
4441 .all(|range| {
4442 excerpt_range.start <= range.start
4443 && excerpt_range.end >= range.end
4444 })
4445 })?;
4446
4447 if all_edits_within_excerpt {
4448 return Ok(());
4449 }
4450 }
4451 }
4452 }
4453 } else {
4454 return Ok(());
4455 }
4456
4457 let mut ranges_to_highlight = Vec::new();
4458 let excerpt_buffer = cx.new(|cx| {
4459 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4460 for (buffer_handle, transaction) in &entries {
4461 let buffer = buffer_handle.read(cx);
4462 ranges_to_highlight.extend(
4463 multibuffer.push_excerpts_with_context_lines(
4464 buffer_handle.clone(),
4465 buffer
4466 .edited_ranges_for_transaction::<usize>(transaction)
4467 .collect(),
4468 DEFAULT_MULTIBUFFER_CONTEXT,
4469 cx,
4470 ),
4471 );
4472 }
4473 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4474 multibuffer
4475 })?;
4476
4477 workspace.update_in(&mut cx, |workspace, window, cx| {
4478 let project = workspace.project().clone();
4479 let editor = cx
4480 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4481 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4482 editor.update(cx, |editor, cx| {
4483 editor.highlight_background::<Self>(
4484 &ranges_to_highlight,
4485 |theme| theme.editor_highlighted_line_background,
4486 cx,
4487 );
4488 });
4489 })?;
4490
4491 Ok(())
4492 }
4493
4494 pub fn clear_code_action_providers(&mut self) {
4495 self.code_action_providers.clear();
4496 self.available_code_actions.take();
4497 }
4498
4499 pub fn add_code_action_provider(
4500 &mut self,
4501 provider: Rc<dyn CodeActionProvider>,
4502 window: &mut Window,
4503 cx: &mut Context<Self>,
4504 ) {
4505 if self
4506 .code_action_providers
4507 .iter()
4508 .any(|existing_provider| existing_provider.id() == provider.id())
4509 {
4510 return;
4511 }
4512
4513 self.code_action_providers.push(provider);
4514 self.refresh_code_actions(window, cx);
4515 }
4516
4517 pub fn remove_code_action_provider(
4518 &mut self,
4519 id: Arc<str>,
4520 window: &mut Window,
4521 cx: &mut Context<Self>,
4522 ) {
4523 self.code_action_providers
4524 .retain(|provider| provider.id() != id);
4525 self.refresh_code_actions(window, cx);
4526 }
4527
4528 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4529 let buffer = self.buffer.read(cx);
4530 let newest_selection = self.selections.newest_anchor().clone();
4531 if newest_selection.head().diff_base_anchor.is_some() {
4532 return None;
4533 }
4534 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4535 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4536 if start_buffer != end_buffer {
4537 return None;
4538 }
4539
4540 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4541 cx.background_executor()
4542 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4543 .await;
4544
4545 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4546 let providers = this.code_action_providers.clone();
4547 let tasks = this
4548 .code_action_providers
4549 .iter()
4550 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4551 .collect::<Vec<_>>();
4552 (providers, tasks)
4553 })?;
4554
4555 let mut actions = Vec::new();
4556 for (provider, provider_actions) in
4557 providers.into_iter().zip(future::join_all(tasks).await)
4558 {
4559 if let Some(provider_actions) = provider_actions.log_err() {
4560 actions.extend(provider_actions.into_iter().map(|action| {
4561 AvailableCodeAction {
4562 excerpt_id: newest_selection.start.excerpt_id,
4563 action,
4564 provider: provider.clone(),
4565 }
4566 }));
4567 }
4568 }
4569
4570 this.update(&mut cx, |this, cx| {
4571 this.available_code_actions = if actions.is_empty() {
4572 None
4573 } else {
4574 Some((
4575 Location {
4576 buffer: start_buffer,
4577 range: start..end,
4578 },
4579 actions.into(),
4580 ))
4581 };
4582 cx.notify();
4583 })
4584 }));
4585 None
4586 }
4587
4588 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4589 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4590 self.show_git_blame_inline = false;
4591
4592 self.show_git_blame_inline_delay_task =
4593 Some(cx.spawn_in(window, |this, mut cx| async move {
4594 cx.background_executor().timer(delay).await;
4595
4596 this.update(&mut cx, |this, cx| {
4597 this.show_git_blame_inline = true;
4598 cx.notify();
4599 })
4600 .log_err();
4601 }));
4602 }
4603 }
4604
4605 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4606 if self.pending_rename.is_some() {
4607 return None;
4608 }
4609
4610 let provider = self.semantics_provider.clone()?;
4611 let buffer = self.buffer.read(cx);
4612 let newest_selection = self.selections.newest_anchor().clone();
4613 let cursor_position = newest_selection.head();
4614 let (cursor_buffer, cursor_buffer_position) =
4615 buffer.text_anchor_for_position(cursor_position, cx)?;
4616 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4617 if cursor_buffer != tail_buffer {
4618 return None;
4619 }
4620 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4621 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4622 cx.background_executor()
4623 .timer(Duration::from_millis(debounce))
4624 .await;
4625
4626 let highlights = if let Some(highlights) = cx
4627 .update(|cx| {
4628 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4629 })
4630 .ok()
4631 .flatten()
4632 {
4633 highlights.await.log_err()
4634 } else {
4635 None
4636 };
4637
4638 if let Some(highlights) = highlights {
4639 this.update(&mut cx, |this, cx| {
4640 if this.pending_rename.is_some() {
4641 return;
4642 }
4643
4644 let buffer_id = cursor_position.buffer_id;
4645 let buffer = this.buffer.read(cx);
4646 if !buffer
4647 .text_anchor_for_position(cursor_position, cx)
4648 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4649 {
4650 return;
4651 }
4652
4653 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4654 let mut write_ranges = Vec::new();
4655 let mut read_ranges = Vec::new();
4656 for highlight in highlights {
4657 for (excerpt_id, excerpt_range) in
4658 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4659 {
4660 let start = highlight
4661 .range
4662 .start
4663 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4664 let end = highlight
4665 .range
4666 .end
4667 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4668 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4669 continue;
4670 }
4671
4672 let range = Anchor {
4673 buffer_id,
4674 excerpt_id,
4675 text_anchor: start,
4676 diff_base_anchor: None,
4677 }..Anchor {
4678 buffer_id,
4679 excerpt_id,
4680 text_anchor: end,
4681 diff_base_anchor: None,
4682 };
4683 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4684 write_ranges.push(range);
4685 } else {
4686 read_ranges.push(range);
4687 }
4688 }
4689 }
4690
4691 this.highlight_background::<DocumentHighlightRead>(
4692 &read_ranges,
4693 |theme| theme.editor_document_highlight_read_background,
4694 cx,
4695 );
4696 this.highlight_background::<DocumentHighlightWrite>(
4697 &write_ranges,
4698 |theme| theme.editor_document_highlight_write_background,
4699 cx,
4700 );
4701 cx.notify();
4702 })
4703 .log_err();
4704 }
4705 }));
4706 None
4707 }
4708
4709 pub fn refresh_selected_text_highlights(
4710 &mut self,
4711 window: &mut Window,
4712 cx: &mut Context<Editor>,
4713 ) {
4714 self.selection_highlight_task.take();
4715 if !EditorSettings::get_global(cx).selection_highlight {
4716 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4717 return;
4718 }
4719 if self.selections.count() != 1 || self.selections.line_mode {
4720 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4721 return;
4722 }
4723 let selection = self.selections.newest::<Point>(cx);
4724 if selection.is_empty() || selection.start.row != selection.end.row {
4725 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4726 return;
4727 }
4728 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4729 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4730 cx.background_executor()
4731 .timer(Duration::from_millis(debounce))
4732 .await;
4733 let Some(Some(matches_task)) = editor
4734 .update_in(&mut cx, |editor, _, cx| {
4735 if editor.selections.count() != 1 || editor.selections.line_mode {
4736 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4737 return None;
4738 }
4739 let selection = editor.selections.newest::<Point>(cx);
4740 if selection.is_empty() || selection.start.row != selection.end.row {
4741 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4742 return None;
4743 }
4744 let buffer = editor.buffer().read(cx).snapshot(cx);
4745 let query = buffer.text_for_range(selection.range()).collect::<String>();
4746 if query.trim().is_empty() {
4747 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4748 return None;
4749 }
4750 Some(cx.background_spawn(async move {
4751 let mut ranges = Vec::new();
4752 let selection_anchors = selection.range().to_anchors(&buffer);
4753 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4754 for (search_buffer, search_range, excerpt_id) in
4755 buffer.range_to_buffer_ranges(range)
4756 {
4757 ranges.extend(
4758 project::search::SearchQuery::text(
4759 query.clone(),
4760 false,
4761 false,
4762 false,
4763 Default::default(),
4764 Default::default(),
4765 None,
4766 )
4767 .unwrap()
4768 .search(search_buffer, Some(search_range.clone()))
4769 .await
4770 .into_iter()
4771 .filter_map(
4772 |match_range| {
4773 let start = search_buffer.anchor_after(
4774 search_range.start + match_range.start,
4775 );
4776 let end = search_buffer.anchor_before(
4777 search_range.start + match_range.end,
4778 );
4779 let range = Anchor::range_in_buffer(
4780 excerpt_id,
4781 search_buffer.remote_id(),
4782 start..end,
4783 );
4784 (range != selection_anchors).then_some(range)
4785 },
4786 ),
4787 );
4788 }
4789 }
4790 ranges
4791 }))
4792 })
4793 .log_err()
4794 else {
4795 return;
4796 };
4797 let matches = matches_task.await;
4798 editor
4799 .update_in(&mut cx, |editor, _, cx| {
4800 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4801 if !matches.is_empty() {
4802 editor.highlight_background::<SelectedTextHighlight>(
4803 &matches,
4804 |theme| theme.editor_document_highlight_bracket_background,
4805 cx,
4806 )
4807 }
4808 })
4809 .log_err();
4810 }));
4811 }
4812
4813 pub fn refresh_inline_completion(
4814 &mut self,
4815 debounce: bool,
4816 user_requested: bool,
4817 window: &mut Window,
4818 cx: &mut Context<Self>,
4819 ) -> Option<()> {
4820 let provider = self.edit_prediction_provider()?;
4821 let cursor = self.selections.newest_anchor().head();
4822 let (buffer, cursor_buffer_position) =
4823 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4824
4825 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4826 self.discard_inline_completion(false, cx);
4827 return None;
4828 }
4829
4830 if !user_requested
4831 && (!self.should_show_edit_predictions()
4832 || !self.is_focused(window)
4833 || buffer.read(cx).is_empty())
4834 {
4835 self.discard_inline_completion(false, cx);
4836 return None;
4837 }
4838
4839 self.update_visible_inline_completion(window, cx);
4840 provider.refresh(
4841 self.project.clone(),
4842 buffer,
4843 cursor_buffer_position,
4844 debounce,
4845 cx,
4846 );
4847 Some(())
4848 }
4849
4850 fn show_edit_predictions_in_menu(&self) -> bool {
4851 match self.edit_prediction_settings {
4852 EditPredictionSettings::Disabled => false,
4853 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4854 }
4855 }
4856
4857 pub fn edit_predictions_enabled(&self) -> bool {
4858 match self.edit_prediction_settings {
4859 EditPredictionSettings::Disabled => false,
4860 EditPredictionSettings::Enabled { .. } => true,
4861 }
4862 }
4863
4864 fn edit_prediction_requires_modifier(&self) -> bool {
4865 match self.edit_prediction_settings {
4866 EditPredictionSettings::Disabled => false,
4867 EditPredictionSettings::Enabled {
4868 preview_requires_modifier,
4869 ..
4870 } => preview_requires_modifier,
4871 }
4872 }
4873
4874 fn edit_prediction_settings_at_position(
4875 &self,
4876 buffer: &Entity<Buffer>,
4877 buffer_position: language::Anchor,
4878 cx: &App,
4879 ) -> EditPredictionSettings {
4880 if self.mode != EditorMode::Full
4881 || !self.show_inline_completions_override.unwrap_or(true)
4882 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4883 {
4884 return EditPredictionSettings::Disabled;
4885 }
4886
4887 let buffer = buffer.read(cx);
4888
4889 let file = buffer.file();
4890
4891 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4892 return EditPredictionSettings::Disabled;
4893 };
4894
4895 let by_provider = matches!(
4896 self.menu_inline_completions_policy,
4897 MenuInlineCompletionsPolicy::ByProvider
4898 );
4899
4900 let show_in_menu = by_provider
4901 && self
4902 .edit_prediction_provider
4903 .as_ref()
4904 .map_or(false, |provider| {
4905 provider.provider.show_completions_in_menu()
4906 });
4907
4908 let preview_requires_modifier =
4909 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4910
4911 EditPredictionSettings::Enabled {
4912 show_in_menu,
4913 preview_requires_modifier,
4914 }
4915 }
4916
4917 fn should_show_edit_predictions(&self) -> bool {
4918 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4919 }
4920
4921 pub fn edit_prediction_preview_is_active(&self) -> bool {
4922 matches!(
4923 self.edit_prediction_preview,
4924 EditPredictionPreview::Active { .. }
4925 )
4926 }
4927
4928 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4929 let cursor = self.selections.newest_anchor().head();
4930 if let Some((buffer, cursor_position)) =
4931 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4932 {
4933 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4934 } else {
4935 false
4936 }
4937 }
4938
4939 fn inline_completions_enabled_in_buffer(
4940 &self,
4941 buffer: &Entity<Buffer>,
4942 buffer_position: language::Anchor,
4943 cx: &App,
4944 ) -> bool {
4945 maybe!({
4946 let provider = self.edit_prediction_provider()?;
4947 if !provider.is_enabled(&buffer, buffer_position, cx) {
4948 return Some(false);
4949 }
4950 let buffer = buffer.read(cx);
4951 let Some(file) = buffer.file() else {
4952 return Some(true);
4953 };
4954 let settings = all_language_settings(Some(file), cx);
4955 Some(settings.inline_completions_enabled_for_path(file.path()))
4956 })
4957 .unwrap_or(false)
4958 }
4959
4960 fn cycle_inline_completion(
4961 &mut self,
4962 direction: Direction,
4963 window: &mut Window,
4964 cx: &mut Context<Self>,
4965 ) -> Option<()> {
4966 let provider = self.edit_prediction_provider()?;
4967 let cursor = self.selections.newest_anchor().head();
4968 let (buffer, cursor_buffer_position) =
4969 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4970 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4971 return None;
4972 }
4973
4974 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4975 self.update_visible_inline_completion(window, cx);
4976
4977 Some(())
4978 }
4979
4980 pub fn show_inline_completion(
4981 &mut self,
4982 _: &ShowEditPrediction,
4983 window: &mut Window,
4984 cx: &mut Context<Self>,
4985 ) {
4986 if !self.has_active_inline_completion() {
4987 self.refresh_inline_completion(false, true, window, cx);
4988 return;
4989 }
4990
4991 self.update_visible_inline_completion(window, cx);
4992 }
4993
4994 pub fn display_cursor_names(
4995 &mut self,
4996 _: &DisplayCursorNames,
4997 window: &mut Window,
4998 cx: &mut Context<Self>,
4999 ) {
5000 self.show_cursor_names(window, cx);
5001 }
5002
5003 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5004 self.show_cursor_names = true;
5005 cx.notify();
5006 cx.spawn_in(window, |this, mut cx| async move {
5007 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5008 this.update(&mut cx, |this, cx| {
5009 this.show_cursor_names = false;
5010 cx.notify()
5011 })
5012 .ok()
5013 })
5014 .detach();
5015 }
5016
5017 pub fn next_edit_prediction(
5018 &mut self,
5019 _: &NextEditPrediction,
5020 window: &mut Window,
5021 cx: &mut Context<Self>,
5022 ) {
5023 if self.has_active_inline_completion() {
5024 self.cycle_inline_completion(Direction::Next, window, cx);
5025 } else {
5026 let is_copilot_disabled = self
5027 .refresh_inline_completion(false, true, window, cx)
5028 .is_none();
5029 if is_copilot_disabled {
5030 cx.propagate();
5031 }
5032 }
5033 }
5034
5035 pub fn previous_edit_prediction(
5036 &mut self,
5037 _: &PreviousEditPrediction,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 if self.has_active_inline_completion() {
5042 self.cycle_inline_completion(Direction::Prev, window, cx);
5043 } else {
5044 let is_copilot_disabled = self
5045 .refresh_inline_completion(false, true, window, cx)
5046 .is_none();
5047 if is_copilot_disabled {
5048 cx.propagate();
5049 }
5050 }
5051 }
5052
5053 pub fn accept_edit_prediction(
5054 &mut self,
5055 _: &AcceptEditPrediction,
5056 window: &mut Window,
5057 cx: &mut Context<Self>,
5058 ) {
5059 if self.show_edit_predictions_in_menu() {
5060 self.hide_context_menu(window, cx);
5061 }
5062
5063 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5064 return;
5065 };
5066
5067 self.report_inline_completion_event(
5068 active_inline_completion.completion_id.clone(),
5069 true,
5070 cx,
5071 );
5072
5073 match &active_inline_completion.completion {
5074 InlineCompletion::Move { target, .. } => {
5075 let target = *target;
5076
5077 if let Some(position_map) = &self.last_position_map {
5078 if position_map
5079 .visible_row_range
5080 .contains(&target.to_display_point(&position_map.snapshot).row())
5081 || !self.edit_prediction_requires_modifier()
5082 {
5083 self.unfold_ranges(&[target..target], true, false, cx);
5084 // Note that this is also done in vim's handler of the Tab action.
5085 self.change_selections(
5086 Some(Autoscroll::newest()),
5087 window,
5088 cx,
5089 |selections| {
5090 selections.select_anchor_ranges([target..target]);
5091 },
5092 );
5093 self.clear_row_highlights::<EditPredictionPreview>();
5094
5095 self.edit_prediction_preview = EditPredictionPreview::Active {
5096 previous_scroll_position: None,
5097 };
5098 } else {
5099 self.edit_prediction_preview = EditPredictionPreview::Active {
5100 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5101 };
5102 self.highlight_rows::<EditPredictionPreview>(
5103 target..target,
5104 cx.theme().colors().editor_highlighted_line_background,
5105 true,
5106 cx,
5107 );
5108 self.request_autoscroll(Autoscroll::fit(), cx);
5109 }
5110 }
5111 }
5112 InlineCompletion::Edit { edits, .. } => {
5113 if let Some(provider) = self.edit_prediction_provider() {
5114 provider.accept(cx);
5115 }
5116
5117 let snapshot = self.buffer.read(cx).snapshot(cx);
5118 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5119
5120 self.buffer.update(cx, |buffer, cx| {
5121 buffer.edit(edits.iter().cloned(), None, cx)
5122 });
5123
5124 self.change_selections(None, window, cx, |s| {
5125 s.select_anchor_ranges([last_edit_end..last_edit_end])
5126 });
5127
5128 self.update_visible_inline_completion(window, cx);
5129 if self.active_inline_completion.is_none() {
5130 self.refresh_inline_completion(true, true, window, cx);
5131 }
5132
5133 cx.notify();
5134 }
5135 }
5136
5137 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5138 }
5139
5140 pub fn accept_partial_inline_completion(
5141 &mut self,
5142 _: &AcceptPartialEditPrediction,
5143 window: &mut Window,
5144 cx: &mut Context<Self>,
5145 ) {
5146 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5147 return;
5148 };
5149 if self.selections.count() != 1 {
5150 return;
5151 }
5152
5153 self.report_inline_completion_event(
5154 active_inline_completion.completion_id.clone(),
5155 true,
5156 cx,
5157 );
5158
5159 match &active_inline_completion.completion {
5160 InlineCompletion::Move { target, .. } => {
5161 let target = *target;
5162 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5163 selections.select_anchor_ranges([target..target]);
5164 });
5165 }
5166 InlineCompletion::Edit { edits, .. } => {
5167 // Find an insertion that starts at the cursor position.
5168 let snapshot = self.buffer.read(cx).snapshot(cx);
5169 let cursor_offset = self.selections.newest::<usize>(cx).head();
5170 let insertion = edits.iter().find_map(|(range, text)| {
5171 let range = range.to_offset(&snapshot);
5172 if range.is_empty() && range.start == cursor_offset {
5173 Some(text)
5174 } else {
5175 None
5176 }
5177 });
5178
5179 if let Some(text) = insertion {
5180 let mut partial_completion = text
5181 .chars()
5182 .by_ref()
5183 .take_while(|c| c.is_alphabetic())
5184 .collect::<String>();
5185 if partial_completion.is_empty() {
5186 partial_completion = text
5187 .chars()
5188 .by_ref()
5189 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5190 .collect::<String>();
5191 }
5192
5193 cx.emit(EditorEvent::InputHandled {
5194 utf16_range_to_replace: None,
5195 text: partial_completion.clone().into(),
5196 });
5197
5198 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5199
5200 self.refresh_inline_completion(true, true, window, cx);
5201 cx.notify();
5202 } else {
5203 self.accept_edit_prediction(&Default::default(), window, cx);
5204 }
5205 }
5206 }
5207 }
5208
5209 fn discard_inline_completion(
5210 &mut self,
5211 should_report_inline_completion_event: bool,
5212 cx: &mut Context<Self>,
5213 ) -> bool {
5214 if should_report_inline_completion_event {
5215 let completion_id = self
5216 .active_inline_completion
5217 .as_ref()
5218 .and_then(|active_completion| active_completion.completion_id.clone());
5219
5220 self.report_inline_completion_event(completion_id, false, cx);
5221 }
5222
5223 if let Some(provider) = self.edit_prediction_provider() {
5224 provider.discard(cx);
5225 }
5226
5227 self.take_active_inline_completion(cx)
5228 }
5229
5230 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5231 let Some(provider) = self.edit_prediction_provider() else {
5232 return;
5233 };
5234
5235 let Some((_, buffer, _)) = self
5236 .buffer
5237 .read(cx)
5238 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5239 else {
5240 return;
5241 };
5242
5243 let extension = buffer
5244 .read(cx)
5245 .file()
5246 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5247
5248 let event_type = match accepted {
5249 true => "Edit Prediction Accepted",
5250 false => "Edit Prediction Discarded",
5251 };
5252 telemetry::event!(
5253 event_type,
5254 provider = provider.name(),
5255 prediction_id = id,
5256 suggestion_accepted = accepted,
5257 file_extension = extension,
5258 );
5259 }
5260
5261 pub fn has_active_inline_completion(&self) -> bool {
5262 self.active_inline_completion.is_some()
5263 }
5264
5265 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5266 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5267 return false;
5268 };
5269
5270 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5271 self.clear_highlights::<InlineCompletionHighlight>(cx);
5272 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5273 true
5274 }
5275
5276 /// Returns true when we're displaying the edit prediction popover below the cursor
5277 /// like we are not previewing and the LSP autocomplete menu is visible
5278 /// or we are in `when_holding_modifier` mode.
5279 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5280 if self.edit_prediction_preview_is_active()
5281 || !self.show_edit_predictions_in_menu()
5282 || !self.edit_predictions_enabled()
5283 {
5284 return false;
5285 }
5286
5287 if self.has_visible_completions_menu() {
5288 return true;
5289 }
5290
5291 has_completion && self.edit_prediction_requires_modifier()
5292 }
5293
5294 fn handle_modifiers_changed(
5295 &mut self,
5296 modifiers: Modifiers,
5297 position_map: &PositionMap,
5298 window: &mut Window,
5299 cx: &mut Context<Self>,
5300 ) {
5301 if self.show_edit_predictions_in_menu() {
5302 self.update_edit_prediction_preview(&modifiers, window, cx);
5303 }
5304
5305 self.update_selection_mode(&modifiers, position_map, window, cx);
5306
5307 let mouse_position = window.mouse_position();
5308 if !position_map.text_hitbox.is_hovered(window) {
5309 return;
5310 }
5311
5312 self.update_hovered_link(
5313 position_map.point_for_position(mouse_position),
5314 &position_map.snapshot,
5315 modifiers,
5316 window,
5317 cx,
5318 )
5319 }
5320
5321 fn update_selection_mode(
5322 &mut self,
5323 modifiers: &Modifiers,
5324 position_map: &PositionMap,
5325 window: &mut Window,
5326 cx: &mut Context<Self>,
5327 ) {
5328 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5329 return;
5330 }
5331
5332 let mouse_position = window.mouse_position();
5333 let point_for_position = position_map.point_for_position(mouse_position);
5334 let position = point_for_position.previous_valid;
5335
5336 self.select(
5337 SelectPhase::BeginColumnar {
5338 position,
5339 reset: false,
5340 goal_column: point_for_position.exact_unclipped.column(),
5341 },
5342 window,
5343 cx,
5344 );
5345 }
5346
5347 fn update_edit_prediction_preview(
5348 &mut self,
5349 modifiers: &Modifiers,
5350 window: &mut Window,
5351 cx: &mut Context<Self>,
5352 ) {
5353 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5354 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5355 return;
5356 };
5357
5358 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5359 if matches!(
5360 self.edit_prediction_preview,
5361 EditPredictionPreview::Inactive
5362 ) {
5363 self.edit_prediction_preview = EditPredictionPreview::Active {
5364 previous_scroll_position: None,
5365 };
5366
5367 self.update_visible_inline_completion(window, cx);
5368 cx.notify();
5369 }
5370 } else if let EditPredictionPreview::Active {
5371 previous_scroll_position,
5372 } = self.edit_prediction_preview
5373 {
5374 if let (Some(previous_scroll_position), Some(position_map)) =
5375 (previous_scroll_position, self.last_position_map.as_ref())
5376 {
5377 self.set_scroll_position(
5378 previous_scroll_position
5379 .scroll_position(&position_map.snapshot.display_snapshot),
5380 window,
5381 cx,
5382 );
5383 }
5384
5385 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5386 self.clear_row_highlights::<EditPredictionPreview>();
5387 self.update_visible_inline_completion(window, cx);
5388 cx.notify();
5389 }
5390 }
5391
5392 fn update_visible_inline_completion(
5393 &mut self,
5394 _window: &mut Window,
5395 cx: &mut Context<Self>,
5396 ) -> Option<()> {
5397 let selection = self.selections.newest_anchor();
5398 let cursor = selection.head();
5399 let multibuffer = self.buffer.read(cx).snapshot(cx);
5400 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5401 let excerpt_id = cursor.excerpt_id;
5402
5403 let show_in_menu = self.show_edit_predictions_in_menu();
5404 let completions_menu_has_precedence = !show_in_menu
5405 && (self.context_menu.borrow().is_some()
5406 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5407
5408 if completions_menu_has_precedence
5409 || !offset_selection.is_empty()
5410 || self
5411 .active_inline_completion
5412 .as_ref()
5413 .map_or(false, |completion| {
5414 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5415 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5416 !invalidation_range.contains(&offset_selection.head())
5417 })
5418 {
5419 self.discard_inline_completion(false, cx);
5420 return None;
5421 }
5422
5423 self.take_active_inline_completion(cx);
5424 let Some(provider) = self.edit_prediction_provider() else {
5425 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5426 return None;
5427 };
5428
5429 let (buffer, cursor_buffer_position) =
5430 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5431
5432 self.edit_prediction_settings =
5433 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5434
5435 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5436
5437 if self.edit_prediction_indent_conflict {
5438 let cursor_point = cursor.to_point(&multibuffer);
5439
5440 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5441
5442 if let Some((_, indent)) = indents.iter().next() {
5443 if indent.len == cursor_point.column {
5444 self.edit_prediction_indent_conflict = false;
5445 }
5446 }
5447 }
5448
5449 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5450 let edits = inline_completion
5451 .edits
5452 .into_iter()
5453 .flat_map(|(range, new_text)| {
5454 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5455 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5456 Some((start..end, new_text))
5457 })
5458 .collect::<Vec<_>>();
5459 if edits.is_empty() {
5460 return None;
5461 }
5462
5463 let first_edit_start = edits.first().unwrap().0.start;
5464 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5465 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5466
5467 let last_edit_end = edits.last().unwrap().0.end;
5468 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5469 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5470
5471 let cursor_row = cursor.to_point(&multibuffer).row;
5472
5473 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5474
5475 let mut inlay_ids = Vec::new();
5476 let invalidation_row_range;
5477 let move_invalidation_row_range = if cursor_row < edit_start_row {
5478 Some(cursor_row..edit_end_row)
5479 } else if cursor_row > edit_end_row {
5480 Some(edit_start_row..cursor_row)
5481 } else {
5482 None
5483 };
5484 let is_move =
5485 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5486 let completion = if is_move {
5487 invalidation_row_range =
5488 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5489 let target = first_edit_start;
5490 InlineCompletion::Move { target, snapshot }
5491 } else {
5492 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5493 && !self.inline_completions_hidden_for_vim_mode;
5494
5495 if show_completions_in_buffer {
5496 if edits
5497 .iter()
5498 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5499 {
5500 let mut inlays = Vec::new();
5501 for (range, new_text) in &edits {
5502 let inlay = Inlay::inline_completion(
5503 post_inc(&mut self.next_inlay_id),
5504 range.start,
5505 new_text.as_str(),
5506 );
5507 inlay_ids.push(inlay.id);
5508 inlays.push(inlay);
5509 }
5510
5511 self.splice_inlays(&[], inlays, cx);
5512 } else {
5513 let background_color = cx.theme().status().deleted_background;
5514 self.highlight_text::<InlineCompletionHighlight>(
5515 edits.iter().map(|(range, _)| range.clone()).collect(),
5516 HighlightStyle {
5517 background_color: Some(background_color),
5518 ..Default::default()
5519 },
5520 cx,
5521 );
5522 }
5523 }
5524
5525 invalidation_row_range = edit_start_row..edit_end_row;
5526
5527 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5528 if provider.show_tab_accept_marker() {
5529 EditDisplayMode::TabAccept
5530 } else {
5531 EditDisplayMode::Inline
5532 }
5533 } else {
5534 EditDisplayMode::DiffPopover
5535 };
5536
5537 InlineCompletion::Edit {
5538 edits,
5539 edit_preview: inline_completion.edit_preview,
5540 display_mode,
5541 snapshot,
5542 }
5543 };
5544
5545 let invalidation_range = multibuffer
5546 .anchor_before(Point::new(invalidation_row_range.start, 0))
5547 ..multibuffer.anchor_after(Point::new(
5548 invalidation_row_range.end,
5549 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5550 ));
5551
5552 self.stale_inline_completion_in_menu = None;
5553 self.active_inline_completion = Some(InlineCompletionState {
5554 inlay_ids,
5555 completion,
5556 completion_id: inline_completion.id,
5557 invalidation_range,
5558 });
5559
5560 cx.notify();
5561
5562 Some(())
5563 }
5564
5565 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5566 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5567 }
5568
5569 fn render_code_actions_indicator(
5570 &self,
5571 _style: &EditorStyle,
5572 row: DisplayRow,
5573 is_active: bool,
5574 cx: &mut Context<Self>,
5575 ) -> Option<IconButton> {
5576 if self.available_code_actions.is_some() {
5577 Some(
5578 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5579 .shape(ui::IconButtonShape::Square)
5580 .icon_size(IconSize::XSmall)
5581 .icon_color(Color::Muted)
5582 .toggle_state(is_active)
5583 .tooltip({
5584 let focus_handle = self.focus_handle.clone();
5585 move |window, cx| {
5586 Tooltip::for_action_in(
5587 "Toggle Code Actions",
5588 &ToggleCodeActions {
5589 deployed_from_indicator: None,
5590 },
5591 &focus_handle,
5592 window,
5593 cx,
5594 )
5595 }
5596 })
5597 .on_click(cx.listener(move |editor, _e, window, cx| {
5598 window.focus(&editor.focus_handle(cx));
5599 editor.toggle_code_actions(
5600 &ToggleCodeActions {
5601 deployed_from_indicator: Some(row),
5602 },
5603 window,
5604 cx,
5605 );
5606 })),
5607 )
5608 } else {
5609 None
5610 }
5611 }
5612
5613 fn clear_tasks(&mut self) {
5614 self.tasks.clear()
5615 }
5616
5617 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5618 if self.tasks.insert(key, value).is_some() {
5619 // This case should hopefully be rare, but just in case...
5620 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5621 }
5622 }
5623
5624 fn build_tasks_context(
5625 project: &Entity<Project>,
5626 buffer: &Entity<Buffer>,
5627 buffer_row: u32,
5628 tasks: &Arc<RunnableTasks>,
5629 cx: &mut Context<Self>,
5630 ) -> Task<Option<task::TaskContext>> {
5631 let position = Point::new(buffer_row, tasks.column);
5632 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5633 let location = Location {
5634 buffer: buffer.clone(),
5635 range: range_start..range_start,
5636 };
5637 // Fill in the environmental variables from the tree-sitter captures
5638 let mut captured_task_variables = TaskVariables::default();
5639 for (capture_name, value) in tasks.extra_variables.clone() {
5640 captured_task_variables.insert(
5641 task::VariableName::Custom(capture_name.into()),
5642 value.clone(),
5643 );
5644 }
5645 project.update(cx, |project, cx| {
5646 project.task_store().update(cx, |task_store, cx| {
5647 task_store.task_context_for_location(captured_task_variables, location, cx)
5648 })
5649 })
5650 }
5651
5652 pub fn spawn_nearest_task(
5653 &mut self,
5654 action: &SpawnNearestTask,
5655 window: &mut Window,
5656 cx: &mut Context<Self>,
5657 ) {
5658 let Some((workspace, _)) = self.workspace.clone() else {
5659 return;
5660 };
5661 let Some(project) = self.project.clone() else {
5662 return;
5663 };
5664
5665 // Try to find a closest, enclosing node using tree-sitter that has a
5666 // task
5667 let Some((buffer, buffer_row, tasks)) = self
5668 .find_enclosing_node_task(cx)
5669 // Or find the task that's closest in row-distance.
5670 .or_else(|| self.find_closest_task(cx))
5671 else {
5672 return;
5673 };
5674
5675 let reveal_strategy = action.reveal;
5676 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5677 cx.spawn_in(window, |_, mut cx| async move {
5678 let context = task_context.await?;
5679 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5680
5681 let resolved = resolved_task.resolved.as_mut()?;
5682 resolved.reveal = reveal_strategy;
5683
5684 workspace
5685 .update(&mut cx, |workspace, cx| {
5686 workspace::tasks::schedule_resolved_task(
5687 workspace,
5688 task_source_kind,
5689 resolved_task,
5690 false,
5691 cx,
5692 );
5693 })
5694 .ok()
5695 })
5696 .detach();
5697 }
5698
5699 fn find_closest_task(
5700 &mut self,
5701 cx: &mut Context<Self>,
5702 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5703 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5704
5705 let ((buffer_id, row), tasks) = self
5706 .tasks
5707 .iter()
5708 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5709
5710 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5711 let tasks = Arc::new(tasks.to_owned());
5712 Some((buffer, *row, tasks))
5713 }
5714
5715 fn find_enclosing_node_task(
5716 &mut self,
5717 cx: &mut Context<Self>,
5718 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5719 let snapshot = self.buffer.read(cx).snapshot(cx);
5720 let offset = self.selections.newest::<usize>(cx).head();
5721 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5722 let buffer_id = excerpt.buffer().remote_id();
5723
5724 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5725 let mut cursor = layer.node().walk();
5726
5727 while cursor.goto_first_child_for_byte(offset).is_some() {
5728 if cursor.node().end_byte() == offset {
5729 cursor.goto_next_sibling();
5730 }
5731 }
5732
5733 // Ascend to the smallest ancestor that contains the range and has a task.
5734 loop {
5735 let node = cursor.node();
5736 let node_range = node.byte_range();
5737 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5738
5739 // Check if this node contains our offset
5740 if node_range.start <= offset && node_range.end >= offset {
5741 // If it contains offset, check for task
5742 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5743 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5744 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5745 }
5746 }
5747
5748 if !cursor.goto_parent() {
5749 break;
5750 }
5751 }
5752 None
5753 }
5754
5755 fn render_run_indicator(
5756 &self,
5757 _style: &EditorStyle,
5758 is_active: bool,
5759 row: DisplayRow,
5760 cx: &mut Context<Self>,
5761 ) -> IconButton {
5762 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5763 .shape(ui::IconButtonShape::Square)
5764 .icon_size(IconSize::XSmall)
5765 .icon_color(Color::Muted)
5766 .toggle_state(is_active)
5767 .on_click(cx.listener(move |editor, _e, window, cx| {
5768 window.focus(&editor.focus_handle(cx));
5769 editor.toggle_code_actions(
5770 &ToggleCodeActions {
5771 deployed_from_indicator: Some(row),
5772 },
5773 window,
5774 cx,
5775 );
5776 }))
5777 }
5778
5779 pub fn context_menu_visible(&self) -> bool {
5780 !self.edit_prediction_preview_is_active()
5781 && self
5782 .context_menu
5783 .borrow()
5784 .as_ref()
5785 .map_or(false, |menu| menu.visible())
5786 }
5787
5788 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5789 self.context_menu
5790 .borrow()
5791 .as_ref()
5792 .map(|menu| menu.origin())
5793 }
5794
5795 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5796 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5797
5798 #[allow(clippy::too_many_arguments)]
5799 fn render_edit_prediction_popover(
5800 &mut self,
5801 text_bounds: &Bounds<Pixels>,
5802 content_origin: gpui::Point<Pixels>,
5803 editor_snapshot: &EditorSnapshot,
5804 visible_row_range: Range<DisplayRow>,
5805 scroll_top: f32,
5806 scroll_bottom: f32,
5807 line_layouts: &[LineWithInvisibles],
5808 line_height: Pixels,
5809 scroll_pixel_position: gpui::Point<Pixels>,
5810 newest_selection_head: Option<DisplayPoint>,
5811 editor_width: Pixels,
5812 style: &EditorStyle,
5813 window: &mut Window,
5814 cx: &mut App,
5815 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5816 let active_inline_completion = self.active_inline_completion.as_ref()?;
5817
5818 if self.edit_prediction_visible_in_cursor_popover(true) {
5819 return None;
5820 }
5821
5822 match &active_inline_completion.completion {
5823 InlineCompletion::Move { target, .. } => {
5824 let target_display_point = target.to_display_point(editor_snapshot);
5825
5826 if self.edit_prediction_requires_modifier() {
5827 if !self.edit_prediction_preview_is_active() {
5828 return None;
5829 }
5830
5831 self.render_edit_prediction_modifier_jump_popover(
5832 text_bounds,
5833 content_origin,
5834 visible_row_range,
5835 line_layouts,
5836 line_height,
5837 scroll_pixel_position,
5838 newest_selection_head,
5839 target_display_point,
5840 window,
5841 cx,
5842 )
5843 } else {
5844 self.render_edit_prediction_eager_jump_popover(
5845 text_bounds,
5846 content_origin,
5847 editor_snapshot,
5848 visible_row_range,
5849 scroll_top,
5850 scroll_bottom,
5851 line_height,
5852 scroll_pixel_position,
5853 target_display_point,
5854 editor_width,
5855 window,
5856 cx,
5857 )
5858 }
5859 }
5860 InlineCompletion::Edit {
5861 display_mode: EditDisplayMode::Inline,
5862 ..
5863 } => None,
5864 InlineCompletion::Edit {
5865 display_mode: EditDisplayMode::TabAccept,
5866 edits,
5867 ..
5868 } => {
5869 let range = &edits.first()?.0;
5870 let target_display_point = range.end.to_display_point(editor_snapshot);
5871
5872 self.render_edit_prediction_end_of_line_popover(
5873 "Accept",
5874 editor_snapshot,
5875 visible_row_range,
5876 target_display_point,
5877 line_height,
5878 scroll_pixel_position,
5879 content_origin,
5880 editor_width,
5881 window,
5882 cx,
5883 )
5884 }
5885 InlineCompletion::Edit {
5886 edits,
5887 edit_preview,
5888 display_mode: EditDisplayMode::DiffPopover,
5889 snapshot,
5890 } => self.render_edit_prediction_diff_popover(
5891 text_bounds,
5892 content_origin,
5893 editor_snapshot,
5894 visible_row_range,
5895 line_layouts,
5896 line_height,
5897 scroll_pixel_position,
5898 newest_selection_head,
5899 editor_width,
5900 style,
5901 edits,
5902 edit_preview,
5903 snapshot,
5904 window,
5905 cx,
5906 ),
5907 }
5908 }
5909
5910 #[allow(clippy::too_many_arguments)]
5911 fn render_edit_prediction_modifier_jump_popover(
5912 &mut self,
5913 text_bounds: &Bounds<Pixels>,
5914 content_origin: gpui::Point<Pixels>,
5915 visible_row_range: Range<DisplayRow>,
5916 line_layouts: &[LineWithInvisibles],
5917 line_height: Pixels,
5918 scroll_pixel_position: gpui::Point<Pixels>,
5919 newest_selection_head: Option<DisplayPoint>,
5920 target_display_point: DisplayPoint,
5921 window: &mut Window,
5922 cx: &mut App,
5923 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5924 let scrolled_content_origin =
5925 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
5926
5927 const SCROLL_PADDING_Y: Pixels = px(12.);
5928
5929 if target_display_point.row() < visible_row_range.start {
5930 return self.render_edit_prediction_scroll_popover(
5931 |_| SCROLL_PADDING_Y,
5932 IconName::ArrowUp,
5933 visible_row_range,
5934 line_layouts,
5935 newest_selection_head,
5936 scrolled_content_origin,
5937 window,
5938 cx,
5939 );
5940 } else if target_display_point.row() >= visible_row_range.end {
5941 return self.render_edit_prediction_scroll_popover(
5942 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
5943 IconName::ArrowDown,
5944 visible_row_range,
5945 line_layouts,
5946 newest_selection_head,
5947 scrolled_content_origin,
5948 window,
5949 cx,
5950 );
5951 }
5952
5953 const POLE_WIDTH: Pixels = px(2.);
5954
5955 let mut element = v_flex()
5956 .items_end()
5957 .child(
5958 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
5959 .rounded_br(px(0.))
5960 .rounded_tr(px(0.))
5961 .border_r_2(),
5962 )
5963 .child(
5964 div()
5965 .w(POLE_WIDTH)
5966 .bg(Editor::edit_prediction_callout_popover_border_color(cx))
5967 .h(line_height),
5968 )
5969 .into_any();
5970
5971 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
5972
5973 let line_layout =
5974 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
5975 let target_column = target_display_point.column() as usize;
5976
5977 let target_x = line_layout.x_for_index(target_column);
5978 let target_y =
5979 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
5980
5981 let mut origin = scrolled_content_origin + point(target_x, target_y)
5982 - point(size.width - POLE_WIDTH, size.height - line_height);
5983
5984 origin.x = origin.x.max(content_origin.x);
5985
5986 element.prepaint_at(origin, window, cx);
5987
5988 Some((element, origin))
5989 }
5990
5991 #[allow(clippy::too_many_arguments)]
5992 fn render_edit_prediction_scroll_popover(
5993 &mut self,
5994 to_y: impl Fn(Size<Pixels>) -> Pixels,
5995 scroll_icon: IconName,
5996 visible_row_range: Range<DisplayRow>,
5997 line_layouts: &[LineWithInvisibles],
5998 newest_selection_head: Option<DisplayPoint>,
5999 scrolled_content_origin: gpui::Point<Pixels>,
6000 window: &mut Window,
6001 cx: &mut App,
6002 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6003 let mut element = self
6004 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6005 .into_any();
6006
6007 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6008
6009 let cursor = newest_selection_head?;
6010 let cursor_row_layout =
6011 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6012 let cursor_column = cursor.column() as usize;
6013
6014 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6015
6016 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6017
6018 element.prepaint_at(origin, window, cx);
6019 Some((element, origin))
6020 }
6021
6022 #[allow(clippy::too_many_arguments)]
6023 fn render_edit_prediction_eager_jump_popover(
6024 &mut self,
6025 text_bounds: &Bounds<Pixels>,
6026 content_origin: gpui::Point<Pixels>,
6027 editor_snapshot: &EditorSnapshot,
6028 visible_row_range: Range<DisplayRow>,
6029 scroll_top: f32,
6030 scroll_bottom: f32,
6031 line_height: Pixels,
6032 scroll_pixel_position: gpui::Point<Pixels>,
6033 target_display_point: DisplayPoint,
6034 editor_width: Pixels,
6035 window: &mut Window,
6036 cx: &mut App,
6037 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6038 if target_display_point.row().as_f32() < scroll_top {
6039 let mut element = self
6040 .render_edit_prediction_line_popover(
6041 "Jump to Edit",
6042 Some(IconName::ArrowUp),
6043 window,
6044 cx,
6045 )?
6046 .into_any();
6047
6048 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6049 let offset = point(
6050 (text_bounds.size.width - size.width) / 2.,
6051 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6052 );
6053
6054 let origin = text_bounds.origin + offset;
6055 element.prepaint_at(origin, window, cx);
6056 Some((element, origin))
6057 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6058 let mut element = self
6059 .render_edit_prediction_line_popover(
6060 "Jump to Edit",
6061 Some(IconName::ArrowDown),
6062 window,
6063 cx,
6064 )?
6065 .into_any();
6066
6067 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6068 let offset = point(
6069 (text_bounds.size.width - size.width) / 2.,
6070 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6071 );
6072
6073 let origin = text_bounds.origin + offset;
6074 element.prepaint_at(origin, window, cx);
6075 Some((element, origin))
6076 } else {
6077 self.render_edit_prediction_end_of_line_popover(
6078 "Jump to Edit",
6079 editor_snapshot,
6080 visible_row_range,
6081 target_display_point,
6082 line_height,
6083 scroll_pixel_position,
6084 content_origin,
6085 editor_width,
6086 window,
6087 cx,
6088 )
6089 }
6090 }
6091
6092 #[allow(clippy::too_many_arguments)]
6093 fn render_edit_prediction_end_of_line_popover(
6094 self: &mut Editor,
6095 label: &'static str,
6096 editor_snapshot: &EditorSnapshot,
6097 visible_row_range: Range<DisplayRow>,
6098 target_display_point: DisplayPoint,
6099 line_height: Pixels,
6100 scroll_pixel_position: gpui::Point<Pixels>,
6101 content_origin: gpui::Point<Pixels>,
6102 editor_width: Pixels,
6103 window: &mut Window,
6104 cx: &mut App,
6105 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6106 let target_line_end = DisplayPoint::new(
6107 target_display_point.row(),
6108 editor_snapshot.line_len(target_display_point.row()),
6109 );
6110
6111 let mut element = self
6112 .render_edit_prediction_line_popover(label, None, window, cx)?
6113 .into_any();
6114
6115 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6116
6117 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6118
6119 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6120 let mut origin = start_point
6121 + line_origin
6122 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6123 origin.x = origin.x.max(content_origin.x);
6124
6125 let max_x = content_origin.x + editor_width - size.width;
6126
6127 if origin.x > max_x {
6128 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6129
6130 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6131 origin.y += offset;
6132 IconName::ArrowUp
6133 } else {
6134 origin.y -= offset;
6135 IconName::ArrowDown
6136 };
6137
6138 element = self
6139 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6140 .into_any();
6141
6142 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6143
6144 origin.x = content_origin.x + editor_width - size.width - px(2.);
6145 }
6146
6147 element.prepaint_at(origin, window, cx);
6148 Some((element, origin))
6149 }
6150
6151 #[allow(clippy::too_many_arguments)]
6152 fn render_edit_prediction_diff_popover(
6153 self: &Editor,
6154 text_bounds: &Bounds<Pixels>,
6155 content_origin: gpui::Point<Pixels>,
6156 editor_snapshot: &EditorSnapshot,
6157 visible_row_range: Range<DisplayRow>,
6158 line_layouts: &[LineWithInvisibles],
6159 line_height: Pixels,
6160 scroll_pixel_position: gpui::Point<Pixels>,
6161 newest_selection_head: Option<DisplayPoint>,
6162 editor_width: Pixels,
6163 style: &EditorStyle,
6164 edits: &Vec<(Range<Anchor>, String)>,
6165 edit_preview: &Option<language::EditPreview>,
6166 snapshot: &language::BufferSnapshot,
6167 window: &mut Window,
6168 cx: &mut App,
6169 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6170 let edit_start = edits
6171 .first()
6172 .unwrap()
6173 .0
6174 .start
6175 .to_display_point(editor_snapshot);
6176 let edit_end = edits
6177 .last()
6178 .unwrap()
6179 .0
6180 .end
6181 .to_display_point(editor_snapshot);
6182
6183 let is_visible = visible_row_range.contains(&edit_start.row())
6184 || visible_row_range.contains(&edit_end.row());
6185 if !is_visible {
6186 return None;
6187 }
6188
6189 let highlighted_edits =
6190 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6191
6192 let styled_text = highlighted_edits.to_styled_text(&style.text);
6193 let line_count = highlighted_edits.text.lines().count();
6194
6195 const BORDER_WIDTH: Pixels = px(1.);
6196
6197 let mut element = h_flex()
6198 .items_start()
6199 .child(
6200 h_flex()
6201 .bg(cx.theme().colors().editor_background)
6202 .border(BORDER_WIDTH)
6203 .shadow_sm()
6204 .border_color(cx.theme().colors().border)
6205 .rounded_l_lg()
6206 .when(line_count > 1, |el| el.rounded_br_lg())
6207 .pr_1()
6208 .child(styled_text),
6209 )
6210 .child(
6211 h_flex()
6212 .h(line_height + BORDER_WIDTH * px(2.))
6213 .px_1p5()
6214 .gap_1()
6215 // Workaround: For some reason, there's a gap if we don't do this
6216 .ml(-BORDER_WIDTH)
6217 .shadow(smallvec![gpui::BoxShadow {
6218 color: gpui::black().opacity(0.05),
6219 offset: point(px(1.), px(1.)),
6220 blur_radius: px(2.),
6221 spread_radius: px(0.),
6222 }])
6223 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6224 .border(BORDER_WIDTH)
6225 .border_color(cx.theme().colors().border)
6226 .rounded_r_lg()
6227 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6228 )
6229 .into_any();
6230
6231 let longest_row =
6232 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6233 let longest_line_width = if visible_row_range.contains(&longest_row) {
6234 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6235 } else {
6236 layout_line(
6237 longest_row,
6238 editor_snapshot,
6239 style,
6240 editor_width,
6241 |_| false,
6242 window,
6243 cx,
6244 )
6245 .width
6246 };
6247
6248 let viewport_bounds =
6249 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6250 right: -EditorElement::SCROLLBAR_WIDTH,
6251 ..Default::default()
6252 });
6253
6254 let x_after_longest =
6255 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6256 - scroll_pixel_position.x;
6257
6258 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6259
6260 // Fully visible if it can be displayed within the window (allow overlapping other
6261 // panes). However, this is only allowed if the popover starts within text_bounds.
6262 let can_position_to_the_right = x_after_longest < text_bounds.right()
6263 && x_after_longest + element_bounds.width < viewport_bounds.right();
6264
6265 let mut origin = if can_position_to_the_right {
6266 point(
6267 x_after_longest,
6268 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6269 - scroll_pixel_position.y,
6270 )
6271 } else {
6272 let cursor_row = newest_selection_head.map(|head| head.row());
6273 let above_edit = edit_start
6274 .row()
6275 .0
6276 .checked_sub(line_count as u32)
6277 .map(DisplayRow);
6278 let below_edit = Some(edit_end.row() + 1);
6279 let above_cursor =
6280 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6281 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6282
6283 // Place the edit popover adjacent to the edit if there is a location
6284 // available that is onscreen and does not obscure the cursor. Otherwise,
6285 // place it adjacent to the cursor.
6286 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6287 .into_iter()
6288 .flatten()
6289 .find(|&start_row| {
6290 let end_row = start_row + line_count as u32;
6291 visible_row_range.contains(&start_row)
6292 && visible_row_range.contains(&end_row)
6293 && cursor_row.map_or(true, |cursor_row| {
6294 !((start_row..end_row).contains(&cursor_row))
6295 })
6296 })?;
6297
6298 content_origin
6299 + point(
6300 -scroll_pixel_position.x,
6301 row_target.as_f32() * line_height - scroll_pixel_position.y,
6302 )
6303 };
6304
6305 origin.x -= BORDER_WIDTH;
6306
6307 window.defer_draw(element, origin, 1);
6308
6309 // Do not return an element, since it will already be drawn due to defer_draw.
6310 None
6311 }
6312
6313 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6314 px(30.)
6315 }
6316
6317 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6318 if self.read_only(cx) {
6319 cx.theme().players().read_only()
6320 } else {
6321 self.style.as_ref().unwrap().local_player
6322 }
6323 }
6324
6325 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6326 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6327 let accept_keystroke = accept_binding.keystroke()?;
6328
6329 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6330
6331 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6332 Color::Accent
6333 } else {
6334 Color::Muted
6335 };
6336
6337 h_flex()
6338 .px_0p5()
6339 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6340 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6341 .text_size(TextSize::XSmall.rems(cx))
6342 .child(h_flex().children(ui::render_modifiers(
6343 &accept_keystroke.modifiers,
6344 PlatformStyle::platform(),
6345 Some(modifiers_color),
6346 Some(IconSize::XSmall.rems().into()),
6347 true,
6348 )))
6349 .when(is_platform_style_mac, |parent| {
6350 parent.child(accept_keystroke.key.clone())
6351 })
6352 .when(!is_platform_style_mac, |parent| {
6353 parent.child(
6354 Key::new(
6355 util::capitalize(&accept_keystroke.key),
6356 Some(Color::Default),
6357 )
6358 .size(Some(IconSize::XSmall.rems().into())),
6359 )
6360 })
6361 .into()
6362 }
6363
6364 fn render_edit_prediction_line_popover(
6365 &self,
6366 label: impl Into<SharedString>,
6367 icon: Option<IconName>,
6368 window: &mut Window,
6369 cx: &App,
6370 ) -> Option<Div> {
6371 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6372
6373 let result = h_flex()
6374 .py_0p5()
6375 .pl_1()
6376 .pr(padding_right)
6377 .gap_1()
6378 .rounded(px(6.))
6379 .border_1()
6380 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6381 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6382 .shadow_sm()
6383 .children(self.render_edit_prediction_accept_keybind(window, cx))
6384 .child(Label::new(label).size(LabelSize::Small))
6385 .when_some(icon, |element, icon| {
6386 element.child(
6387 div()
6388 .mt(px(1.5))
6389 .child(Icon::new(icon).size(IconSize::Small)),
6390 )
6391 });
6392
6393 Some(result)
6394 }
6395
6396 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6397 let accent_color = cx.theme().colors().text_accent;
6398 let editor_bg_color = cx.theme().colors().editor_background;
6399 editor_bg_color.blend(accent_color.opacity(0.1))
6400 }
6401
6402 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6403 let accent_color = cx.theme().colors().text_accent;
6404 let editor_bg_color = cx.theme().colors().editor_background;
6405 editor_bg_color.blend(accent_color.opacity(0.6))
6406 }
6407
6408 #[allow(clippy::too_many_arguments)]
6409 fn render_edit_prediction_cursor_popover(
6410 &self,
6411 min_width: Pixels,
6412 max_width: Pixels,
6413 cursor_point: Point,
6414 style: &EditorStyle,
6415 accept_keystroke: Option<&gpui::Keystroke>,
6416 _window: &Window,
6417 cx: &mut Context<Editor>,
6418 ) -> Option<AnyElement> {
6419 let provider = self.edit_prediction_provider.as_ref()?;
6420
6421 if provider.provider.needs_terms_acceptance(cx) {
6422 return Some(
6423 h_flex()
6424 .min_w(min_width)
6425 .flex_1()
6426 .px_2()
6427 .py_1()
6428 .gap_3()
6429 .elevation_2(cx)
6430 .hover(|style| style.bg(cx.theme().colors().element_hover))
6431 .id("accept-terms")
6432 .cursor_pointer()
6433 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6434 .on_click(cx.listener(|this, _event, window, cx| {
6435 cx.stop_propagation();
6436 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6437 window.dispatch_action(
6438 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6439 cx,
6440 );
6441 }))
6442 .child(
6443 h_flex()
6444 .flex_1()
6445 .gap_2()
6446 .child(Icon::new(IconName::ZedPredict))
6447 .child(Label::new("Accept Terms of Service"))
6448 .child(div().w_full())
6449 .child(
6450 Icon::new(IconName::ArrowUpRight)
6451 .color(Color::Muted)
6452 .size(IconSize::Small),
6453 )
6454 .into_any_element(),
6455 )
6456 .into_any(),
6457 );
6458 }
6459
6460 let is_refreshing = provider.provider.is_refreshing(cx);
6461
6462 fn pending_completion_container() -> Div {
6463 h_flex()
6464 .h_full()
6465 .flex_1()
6466 .gap_2()
6467 .child(Icon::new(IconName::ZedPredict))
6468 }
6469
6470 let completion = match &self.active_inline_completion {
6471 Some(completion) => match &completion.completion {
6472 InlineCompletion::Move {
6473 target, snapshot, ..
6474 } if !self.has_visible_completions_menu() => {
6475 use text::ToPoint as _;
6476
6477 return Some(
6478 h_flex()
6479 .px_2()
6480 .py_1()
6481 .gap_2()
6482 .elevation_2(cx)
6483 .border_color(cx.theme().colors().border)
6484 .rounded(px(6.))
6485 .rounded_tl(px(0.))
6486 .child(
6487 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6488 Icon::new(IconName::ZedPredictDown)
6489 } else {
6490 Icon::new(IconName::ZedPredictUp)
6491 },
6492 )
6493 .child(Label::new("Hold").size(LabelSize::Small))
6494 .child(h_flex().children(ui::render_modifiers(
6495 &accept_keystroke?.modifiers,
6496 PlatformStyle::platform(),
6497 Some(Color::Default),
6498 Some(IconSize::Small.rems().into()),
6499 false,
6500 )))
6501 .into_any(),
6502 );
6503 }
6504 _ => self.render_edit_prediction_cursor_popover_preview(
6505 completion,
6506 cursor_point,
6507 style,
6508 cx,
6509 )?,
6510 },
6511
6512 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6513 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6514 stale_completion,
6515 cursor_point,
6516 style,
6517 cx,
6518 )?,
6519
6520 None => {
6521 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6522 }
6523 },
6524
6525 None => pending_completion_container().child(Label::new("No Prediction")),
6526 };
6527
6528 let completion = if is_refreshing {
6529 completion
6530 .with_animation(
6531 "loading-completion",
6532 Animation::new(Duration::from_secs(2))
6533 .repeat()
6534 .with_easing(pulsating_between(0.4, 0.8)),
6535 |label, delta| label.opacity(delta),
6536 )
6537 .into_any_element()
6538 } else {
6539 completion.into_any_element()
6540 };
6541
6542 let has_completion = self.active_inline_completion.is_some();
6543
6544 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6545 Some(
6546 h_flex()
6547 .min_w(min_width)
6548 .max_w(max_width)
6549 .flex_1()
6550 .elevation_2(cx)
6551 .border_color(cx.theme().colors().border)
6552 .child(
6553 div()
6554 .flex_1()
6555 .py_1()
6556 .px_2()
6557 .overflow_hidden()
6558 .child(completion),
6559 )
6560 .when_some(accept_keystroke, |el, accept_keystroke| {
6561 if !accept_keystroke.modifiers.modified() {
6562 return el;
6563 }
6564
6565 el.child(
6566 h_flex()
6567 .h_full()
6568 .border_l_1()
6569 .rounded_r_lg()
6570 .border_color(cx.theme().colors().border)
6571 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6572 .gap_1()
6573 .py_1()
6574 .px_2()
6575 .child(
6576 h_flex()
6577 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6578 .when(is_platform_style_mac, |parent| parent.gap_1())
6579 .child(h_flex().children(ui::render_modifiers(
6580 &accept_keystroke.modifiers,
6581 PlatformStyle::platform(),
6582 Some(if !has_completion {
6583 Color::Muted
6584 } else {
6585 Color::Default
6586 }),
6587 None,
6588 false,
6589 ))),
6590 )
6591 .child(Label::new("Preview").into_any_element())
6592 .opacity(if has_completion { 1.0 } else { 0.4 }),
6593 )
6594 })
6595 .into_any(),
6596 )
6597 }
6598
6599 fn render_edit_prediction_cursor_popover_preview(
6600 &self,
6601 completion: &InlineCompletionState,
6602 cursor_point: Point,
6603 style: &EditorStyle,
6604 cx: &mut Context<Editor>,
6605 ) -> Option<Div> {
6606 use text::ToPoint as _;
6607
6608 fn render_relative_row_jump(
6609 prefix: impl Into<String>,
6610 current_row: u32,
6611 target_row: u32,
6612 ) -> Div {
6613 let (row_diff, arrow) = if target_row < current_row {
6614 (current_row - target_row, IconName::ArrowUp)
6615 } else {
6616 (target_row - current_row, IconName::ArrowDown)
6617 };
6618
6619 h_flex()
6620 .child(
6621 Label::new(format!("{}{}", prefix.into(), row_diff))
6622 .color(Color::Muted)
6623 .size(LabelSize::Small),
6624 )
6625 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6626 }
6627
6628 match &completion.completion {
6629 InlineCompletion::Move {
6630 target, snapshot, ..
6631 } => Some(
6632 h_flex()
6633 .px_2()
6634 .gap_2()
6635 .flex_1()
6636 .child(
6637 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6638 Icon::new(IconName::ZedPredictDown)
6639 } else {
6640 Icon::new(IconName::ZedPredictUp)
6641 },
6642 )
6643 .child(Label::new("Jump to Edit")),
6644 ),
6645
6646 InlineCompletion::Edit {
6647 edits,
6648 edit_preview,
6649 snapshot,
6650 display_mode: _,
6651 } => {
6652 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6653
6654 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6655 &snapshot,
6656 &edits,
6657 edit_preview.as_ref()?,
6658 true,
6659 cx,
6660 )
6661 .first_line_preview();
6662
6663 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6664 .with_highlights(&style.text, highlighted_edits.highlights);
6665
6666 let preview = h_flex()
6667 .gap_1()
6668 .min_w_16()
6669 .child(styled_text)
6670 .when(has_more_lines, |parent| parent.child("…"));
6671
6672 let left = if first_edit_row != cursor_point.row {
6673 render_relative_row_jump("", cursor_point.row, first_edit_row)
6674 .into_any_element()
6675 } else {
6676 Icon::new(IconName::ZedPredict).into_any_element()
6677 };
6678
6679 Some(
6680 h_flex()
6681 .h_full()
6682 .flex_1()
6683 .gap_2()
6684 .pr_1()
6685 .overflow_x_hidden()
6686 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6687 .child(left)
6688 .child(preview),
6689 )
6690 }
6691 }
6692 }
6693
6694 fn render_context_menu(
6695 &self,
6696 style: &EditorStyle,
6697 max_height_in_lines: u32,
6698 y_flipped: bool,
6699 window: &mut Window,
6700 cx: &mut Context<Editor>,
6701 ) -> Option<AnyElement> {
6702 let menu = self.context_menu.borrow();
6703 let menu = menu.as_ref()?;
6704 if !menu.visible() {
6705 return None;
6706 };
6707 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6708 }
6709
6710 fn render_context_menu_aside(
6711 &mut self,
6712 max_size: Size<Pixels>,
6713 window: &mut Window,
6714 cx: &mut Context<Editor>,
6715 ) -> Option<AnyElement> {
6716 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6717 if menu.visible() {
6718 menu.render_aside(self, max_size, window, cx)
6719 } else {
6720 None
6721 }
6722 })
6723 }
6724
6725 fn hide_context_menu(
6726 &mut self,
6727 window: &mut Window,
6728 cx: &mut Context<Self>,
6729 ) -> Option<CodeContextMenu> {
6730 cx.notify();
6731 self.completion_tasks.clear();
6732 let context_menu = self.context_menu.borrow_mut().take();
6733 self.stale_inline_completion_in_menu.take();
6734 self.update_visible_inline_completion(window, cx);
6735 context_menu
6736 }
6737
6738 fn show_snippet_choices(
6739 &mut self,
6740 choices: &Vec<String>,
6741 selection: Range<Anchor>,
6742 cx: &mut Context<Self>,
6743 ) {
6744 if selection.start.buffer_id.is_none() {
6745 return;
6746 }
6747 let buffer_id = selection.start.buffer_id.unwrap();
6748 let buffer = self.buffer().read(cx).buffer(buffer_id);
6749 let id = post_inc(&mut self.next_completion_id);
6750
6751 if let Some(buffer) = buffer {
6752 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6753 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6754 ));
6755 }
6756 }
6757
6758 pub fn insert_snippet(
6759 &mut self,
6760 insertion_ranges: &[Range<usize>],
6761 snippet: Snippet,
6762 window: &mut Window,
6763 cx: &mut Context<Self>,
6764 ) -> Result<()> {
6765 struct Tabstop<T> {
6766 is_end_tabstop: bool,
6767 ranges: Vec<Range<T>>,
6768 choices: Option<Vec<String>>,
6769 }
6770
6771 let tabstops = self.buffer.update(cx, |buffer, cx| {
6772 let snippet_text: Arc<str> = snippet.text.clone().into();
6773 buffer.edit(
6774 insertion_ranges
6775 .iter()
6776 .cloned()
6777 .map(|range| (range, snippet_text.clone())),
6778 Some(AutoindentMode::EachLine),
6779 cx,
6780 );
6781
6782 let snapshot = &*buffer.read(cx);
6783 let snippet = &snippet;
6784 snippet
6785 .tabstops
6786 .iter()
6787 .map(|tabstop| {
6788 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6789 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6790 });
6791 let mut tabstop_ranges = tabstop
6792 .ranges
6793 .iter()
6794 .flat_map(|tabstop_range| {
6795 let mut delta = 0_isize;
6796 insertion_ranges.iter().map(move |insertion_range| {
6797 let insertion_start = insertion_range.start as isize + delta;
6798 delta +=
6799 snippet.text.len() as isize - insertion_range.len() as isize;
6800
6801 let start = ((insertion_start + tabstop_range.start) as usize)
6802 .min(snapshot.len());
6803 let end = ((insertion_start + tabstop_range.end) as usize)
6804 .min(snapshot.len());
6805 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6806 })
6807 })
6808 .collect::<Vec<_>>();
6809 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6810
6811 Tabstop {
6812 is_end_tabstop,
6813 ranges: tabstop_ranges,
6814 choices: tabstop.choices.clone(),
6815 }
6816 })
6817 .collect::<Vec<_>>()
6818 });
6819 if let Some(tabstop) = tabstops.first() {
6820 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6821 s.select_ranges(tabstop.ranges.iter().cloned());
6822 });
6823
6824 if let Some(choices) = &tabstop.choices {
6825 if let Some(selection) = tabstop.ranges.first() {
6826 self.show_snippet_choices(choices, selection.clone(), cx)
6827 }
6828 }
6829
6830 // If we're already at the last tabstop and it's at the end of the snippet,
6831 // we're done, we don't need to keep the state around.
6832 if !tabstop.is_end_tabstop {
6833 let choices = tabstops
6834 .iter()
6835 .map(|tabstop| tabstop.choices.clone())
6836 .collect();
6837
6838 let ranges = tabstops
6839 .into_iter()
6840 .map(|tabstop| tabstop.ranges)
6841 .collect::<Vec<_>>();
6842
6843 self.snippet_stack.push(SnippetState {
6844 active_index: 0,
6845 ranges,
6846 choices,
6847 });
6848 }
6849
6850 // Check whether the just-entered snippet ends with an auto-closable bracket.
6851 if self.autoclose_regions.is_empty() {
6852 let snapshot = self.buffer.read(cx).snapshot(cx);
6853 for selection in &mut self.selections.all::<Point>(cx) {
6854 let selection_head = selection.head();
6855 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6856 continue;
6857 };
6858
6859 let mut bracket_pair = None;
6860 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6861 let prev_chars = snapshot
6862 .reversed_chars_at(selection_head)
6863 .collect::<String>();
6864 for (pair, enabled) in scope.brackets() {
6865 if enabled
6866 && pair.close
6867 && prev_chars.starts_with(pair.start.as_str())
6868 && next_chars.starts_with(pair.end.as_str())
6869 {
6870 bracket_pair = Some(pair.clone());
6871 break;
6872 }
6873 }
6874 if let Some(pair) = bracket_pair {
6875 let start = snapshot.anchor_after(selection_head);
6876 let end = snapshot.anchor_after(selection_head);
6877 self.autoclose_regions.push(AutocloseRegion {
6878 selection_id: selection.id,
6879 range: start..end,
6880 pair,
6881 });
6882 }
6883 }
6884 }
6885 }
6886 Ok(())
6887 }
6888
6889 pub fn move_to_next_snippet_tabstop(
6890 &mut self,
6891 window: &mut Window,
6892 cx: &mut Context<Self>,
6893 ) -> bool {
6894 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6895 }
6896
6897 pub fn move_to_prev_snippet_tabstop(
6898 &mut self,
6899 window: &mut Window,
6900 cx: &mut Context<Self>,
6901 ) -> bool {
6902 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6903 }
6904
6905 pub fn move_to_snippet_tabstop(
6906 &mut self,
6907 bias: Bias,
6908 window: &mut Window,
6909 cx: &mut Context<Self>,
6910 ) -> bool {
6911 if let Some(mut snippet) = self.snippet_stack.pop() {
6912 match bias {
6913 Bias::Left => {
6914 if snippet.active_index > 0 {
6915 snippet.active_index -= 1;
6916 } else {
6917 self.snippet_stack.push(snippet);
6918 return false;
6919 }
6920 }
6921 Bias::Right => {
6922 if snippet.active_index + 1 < snippet.ranges.len() {
6923 snippet.active_index += 1;
6924 } else {
6925 self.snippet_stack.push(snippet);
6926 return false;
6927 }
6928 }
6929 }
6930 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6931 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6932 s.select_anchor_ranges(current_ranges.iter().cloned())
6933 });
6934
6935 if let Some(choices) = &snippet.choices[snippet.active_index] {
6936 if let Some(selection) = current_ranges.first() {
6937 self.show_snippet_choices(&choices, selection.clone(), cx);
6938 }
6939 }
6940
6941 // If snippet state is not at the last tabstop, push it back on the stack
6942 if snippet.active_index + 1 < snippet.ranges.len() {
6943 self.snippet_stack.push(snippet);
6944 }
6945 return true;
6946 }
6947 }
6948
6949 false
6950 }
6951
6952 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6953 self.transact(window, cx, |this, window, cx| {
6954 this.select_all(&SelectAll, window, cx);
6955 this.insert("", window, cx);
6956 });
6957 }
6958
6959 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6960 self.transact(window, cx, |this, window, cx| {
6961 this.select_autoclose_pair(window, cx);
6962 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6963 if !this.linked_edit_ranges.is_empty() {
6964 let selections = this.selections.all::<MultiBufferPoint>(cx);
6965 let snapshot = this.buffer.read(cx).snapshot(cx);
6966
6967 for selection in selections.iter() {
6968 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6969 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6970 if selection_start.buffer_id != selection_end.buffer_id {
6971 continue;
6972 }
6973 if let Some(ranges) =
6974 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6975 {
6976 for (buffer, entries) in ranges {
6977 linked_ranges.entry(buffer).or_default().extend(entries);
6978 }
6979 }
6980 }
6981 }
6982
6983 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6984 if !this.selections.line_mode {
6985 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6986 for selection in &mut selections {
6987 if selection.is_empty() {
6988 let old_head = selection.head();
6989 let mut new_head =
6990 movement::left(&display_map, old_head.to_display_point(&display_map))
6991 .to_point(&display_map);
6992 if let Some((buffer, line_buffer_range)) = display_map
6993 .buffer_snapshot
6994 .buffer_line_for_row(MultiBufferRow(old_head.row))
6995 {
6996 let indent_size =
6997 buffer.indent_size_for_line(line_buffer_range.start.row);
6998 let indent_len = match indent_size.kind {
6999 IndentKind::Space => {
7000 buffer.settings_at(line_buffer_range.start, cx).tab_size
7001 }
7002 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7003 };
7004 if old_head.column <= indent_size.len && old_head.column > 0 {
7005 let indent_len = indent_len.get();
7006 new_head = cmp::min(
7007 new_head,
7008 MultiBufferPoint::new(
7009 old_head.row,
7010 ((old_head.column - 1) / indent_len) * indent_len,
7011 ),
7012 );
7013 }
7014 }
7015
7016 selection.set_head(new_head, SelectionGoal::None);
7017 }
7018 }
7019 }
7020
7021 this.signature_help_state.set_backspace_pressed(true);
7022 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7023 s.select(selections)
7024 });
7025 this.insert("", window, cx);
7026 let empty_str: Arc<str> = Arc::from("");
7027 for (buffer, edits) in linked_ranges {
7028 let snapshot = buffer.read(cx).snapshot();
7029 use text::ToPoint as TP;
7030
7031 let edits = edits
7032 .into_iter()
7033 .map(|range| {
7034 let end_point = TP::to_point(&range.end, &snapshot);
7035 let mut start_point = TP::to_point(&range.start, &snapshot);
7036
7037 if end_point == start_point {
7038 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7039 .saturating_sub(1);
7040 start_point =
7041 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7042 };
7043
7044 (start_point..end_point, empty_str.clone())
7045 })
7046 .sorted_by_key(|(range, _)| range.start)
7047 .collect::<Vec<_>>();
7048 buffer.update(cx, |this, cx| {
7049 this.edit(edits, None, cx);
7050 })
7051 }
7052 this.refresh_inline_completion(true, false, window, cx);
7053 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7054 });
7055 }
7056
7057 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7058 self.transact(window, cx, |this, window, cx| {
7059 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7060 let line_mode = s.line_mode;
7061 s.move_with(|map, selection| {
7062 if selection.is_empty() && !line_mode {
7063 let cursor = movement::right(map, selection.head());
7064 selection.end = cursor;
7065 selection.reversed = true;
7066 selection.goal = SelectionGoal::None;
7067 }
7068 })
7069 });
7070 this.insert("", window, cx);
7071 this.refresh_inline_completion(true, false, window, cx);
7072 });
7073 }
7074
7075 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
7076 if self.move_to_prev_snippet_tabstop(window, cx) {
7077 return;
7078 }
7079
7080 self.outdent(&Outdent, window, cx);
7081 }
7082
7083 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7084 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7085 return;
7086 }
7087
7088 let mut selections = self.selections.all_adjusted(cx);
7089 let buffer = self.buffer.read(cx);
7090 let snapshot = buffer.snapshot(cx);
7091 let rows_iter = selections.iter().map(|s| s.head().row);
7092 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7093
7094 let mut edits = Vec::new();
7095 let mut prev_edited_row = 0;
7096 let mut row_delta = 0;
7097 for selection in &mut selections {
7098 if selection.start.row != prev_edited_row {
7099 row_delta = 0;
7100 }
7101 prev_edited_row = selection.end.row;
7102
7103 // If the selection is non-empty, then increase the indentation of the selected lines.
7104 if !selection.is_empty() {
7105 row_delta =
7106 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7107 continue;
7108 }
7109
7110 // If the selection is empty and the cursor is in the leading whitespace before the
7111 // suggested indentation, then auto-indent the line.
7112 let cursor = selection.head();
7113 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7114 if let Some(suggested_indent) =
7115 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7116 {
7117 if cursor.column < suggested_indent.len
7118 && cursor.column <= current_indent.len
7119 && current_indent.len <= suggested_indent.len
7120 {
7121 selection.start = Point::new(cursor.row, suggested_indent.len);
7122 selection.end = selection.start;
7123 if row_delta == 0 {
7124 edits.extend(Buffer::edit_for_indent_size_adjustment(
7125 cursor.row,
7126 current_indent,
7127 suggested_indent,
7128 ));
7129 row_delta = suggested_indent.len - current_indent.len;
7130 }
7131 continue;
7132 }
7133 }
7134
7135 // Otherwise, insert a hard or soft tab.
7136 let settings = buffer.settings_at(cursor, cx);
7137 let tab_size = if settings.hard_tabs {
7138 IndentSize::tab()
7139 } else {
7140 let tab_size = settings.tab_size.get();
7141 let char_column = snapshot
7142 .text_for_range(Point::new(cursor.row, 0)..cursor)
7143 .flat_map(str::chars)
7144 .count()
7145 + row_delta as usize;
7146 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7147 IndentSize::spaces(chars_to_next_tab_stop)
7148 };
7149 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7150 selection.end = selection.start;
7151 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7152 row_delta += tab_size.len;
7153 }
7154
7155 self.transact(window, cx, |this, window, cx| {
7156 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7157 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7158 s.select(selections)
7159 });
7160 this.refresh_inline_completion(true, false, window, cx);
7161 });
7162 }
7163
7164 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7165 if self.read_only(cx) {
7166 return;
7167 }
7168 let mut selections = self.selections.all::<Point>(cx);
7169 let mut prev_edited_row = 0;
7170 let mut row_delta = 0;
7171 let mut edits = Vec::new();
7172 let buffer = self.buffer.read(cx);
7173 let snapshot = buffer.snapshot(cx);
7174 for selection in &mut selections {
7175 if selection.start.row != prev_edited_row {
7176 row_delta = 0;
7177 }
7178 prev_edited_row = selection.end.row;
7179
7180 row_delta =
7181 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7182 }
7183
7184 self.transact(window, cx, |this, window, cx| {
7185 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7186 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7187 s.select(selections)
7188 });
7189 });
7190 }
7191
7192 fn indent_selection(
7193 buffer: &MultiBuffer,
7194 snapshot: &MultiBufferSnapshot,
7195 selection: &mut Selection<Point>,
7196 edits: &mut Vec<(Range<Point>, String)>,
7197 delta_for_start_row: u32,
7198 cx: &App,
7199 ) -> u32 {
7200 let settings = buffer.settings_at(selection.start, cx);
7201 let tab_size = settings.tab_size.get();
7202 let indent_kind = if settings.hard_tabs {
7203 IndentKind::Tab
7204 } else {
7205 IndentKind::Space
7206 };
7207 let mut start_row = selection.start.row;
7208 let mut end_row = selection.end.row + 1;
7209
7210 // If a selection ends at the beginning of a line, don't indent
7211 // that last line.
7212 if selection.end.column == 0 && selection.end.row > selection.start.row {
7213 end_row -= 1;
7214 }
7215
7216 // Avoid re-indenting a row that has already been indented by a
7217 // previous selection, but still update this selection's column
7218 // to reflect that indentation.
7219 if delta_for_start_row > 0 {
7220 start_row += 1;
7221 selection.start.column += delta_for_start_row;
7222 if selection.end.row == selection.start.row {
7223 selection.end.column += delta_for_start_row;
7224 }
7225 }
7226
7227 let mut delta_for_end_row = 0;
7228 let has_multiple_rows = start_row + 1 != end_row;
7229 for row in start_row..end_row {
7230 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7231 let indent_delta = match (current_indent.kind, indent_kind) {
7232 (IndentKind::Space, IndentKind::Space) => {
7233 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7234 IndentSize::spaces(columns_to_next_tab_stop)
7235 }
7236 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7237 (_, IndentKind::Tab) => IndentSize::tab(),
7238 };
7239
7240 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7241 0
7242 } else {
7243 selection.start.column
7244 };
7245 let row_start = Point::new(row, start);
7246 edits.push((
7247 row_start..row_start,
7248 indent_delta.chars().collect::<String>(),
7249 ));
7250
7251 // Update this selection's endpoints to reflect the indentation.
7252 if row == selection.start.row {
7253 selection.start.column += indent_delta.len;
7254 }
7255 if row == selection.end.row {
7256 selection.end.column += indent_delta.len;
7257 delta_for_end_row = indent_delta.len;
7258 }
7259 }
7260
7261 if selection.start.row == selection.end.row {
7262 delta_for_start_row + delta_for_end_row
7263 } else {
7264 delta_for_end_row
7265 }
7266 }
7267
7268 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7269 if self.read_only(cx) {
7270 return;
7271 }
7272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7273 let selections = self.selections.all::<Point>(cx);
7274 let mut deletion_ranges = Vec::new();
7275 let mut last_outdent = None;
7276 {
7277 let buffer = self.buffer.read(cx);
7278 let snapshot = buffer.snapshot(cx);
7279 for selection in &selections {
7280 let settings = buffer.settings_at(selection.start, cx);
7281 let tab_size = settings.tab_size.get();
7282 let mut rows = selection.spanned_rows(false, &display_map);
7283
7284 // Avoid re-outdenting a row that has already been outdented by a
7285 // previous selection.
7286 if let Some(last_row) = last_outdent {
7287 if last_row == rows.start {
7288 rows.start = rows.start.next_row();
7289 }
7290 }
7291 let has_multiple_rows = rows.len() > 1;
7292 for row in rows.iter_rows() {
7293 let indent_size = snapshot.indent_size_for_line(row);
7294 if indent_size.len > 0 {
7295 let deletion_len = match indent_size.kind {
7296 IndentKind::Space => {
7297 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7298 if columns_to_prev_tab_stop == 0 {
7299 tab_size
7300 } else {
7301 columns_to_prev_tab_stop
7302 }
7303 }
7304 IndentKind::Tab => 1,
7305 };
7306 let start = if has_multiple_rows
7307 || deletion_len > selection.start.column
7308 || indent_size.len < selection.start.column
7309 {
7310 0
7311 } else {
7312 selection.start.column - deletion_len
7313 };
7314 deletion_ranges.push(
7315 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7316 );
7317 last_outdent = Some(row);
7318 }
7319 }
7320 }
7321 }
7322
7323 self.transact(window, cx, |this, window, cx| {
7324 this.buffer.update(cx, |buffer, cx| {
7325 let empty_str: Arc<str> = Arc::default();
7326 buffer.edit(
7327 deletion_ranges
7328 .into_iter()
7329 .map(|range| (range, empty_str.clone())),
7330 None,
7331 cx,
7332 );
7333 });
7334 let selections = this.selections.all::<usize>(cx);
7335 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7336 s.select(selections)
7337 });
7338 });
7339 }
7340
7341 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7342 if self.read_only(cx) {
7343 return;
7344 }
7345 let selections = self
7346 .selections
7347 .all::<usize>(cx)
7348 .into_iter()
7349 .map(|s| s.range());
7350
7351 self.transact(window, cx, |this, window, cx| {
7352 this.buffer.update(cx, |buffer, cx| {
7353 buffer.autoindent_ranges(selections, cx);
7354 });
7355 let selections = this.selections.all::<usize>(cx);
7356 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7357 s.select(selections)
7358 });
7359 });
7360 }
7361
7362 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7363 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7364 let selections = self.selections.all::<Point>(cx);
7365
7366 let mut new_cursors = Vec::new();
7367 let mut edit_ranges = Vec::new();
7368 let mut selections = selections.iter().peekable();
7369 while let Some(selection) = selections.next() {
7370 let mut rows = selection.spanned_rows(false, &display_map);
7371 let goal_display_column = selection.head().to_display_point(&display_map).column();
7372
7373 // Accumulate contiguous regions of rows that we want to delete.
7374 while let Some(next_selection) = selections.peek() {
7375 let next_rows = next_selection.spanned_rows(false, &display_map);
7376 if next_rows.start <= rows.end {
7377 rows.end = next_rows.end;
7378 selections.next().unwrap();
7379 } else {
7380 break;
7381 }
7382 }
7383
7384 let buffer = &display_map.buffer_snapshot;
7385 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7386 let edit_end;
7387 let cursor_buffer_row;
7388 if buffer.max_point().row >= rows.end.0 {
7389 // If there's a line after the range, delete the \n from the end of the row range
7390 // and position the cursor on the next line.
7391 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7392 cursor_buffer_row = rows.end;
7393 } else {
7394 // If there isn't a line after the range, delete the \n from the line before the
7395 // start of the row range and position the cursor there.
7396 edit_start = edit_start.saturating_sub(1);
7397 edit_end = buffer.len();
7398 cursor_buffer_row = rows.start.previous_row();
7399 }
7400
7401 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7402 *cursor.column_mut() =
7403 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7404
7405 new_cursors.push((
7406 selection.id,
7407 buffer.anchor_after(cursor.to_point(&display_map)),
7408 ));
7409 edit_ranges.push(edit_start..edit_end);
7410 }
7411
7412 self.transact(window, cx, |this, window, cx| {
7413 let buffer = this.buffer.update(cx, |buffer, cx| {
7414 let empty_str: Arc<str> = Arc::default();
7415 buffer.edit(
7416 edit_ranges
7417 .into_iter()
7418 .map(|range| (range, empty_str.clone())),
7419 None,
7420 cx,
7421 );
7422 buffer.snapshot(cx)
7423 });
7424 let new_selections = new_cursors
7425 .into_iter()
7426 .map(|(id, cursor)| {
7427 let cursor = cursor.to_point(&buffer);
7428 Selection {
7429 id,
7430 start: cursor,
7431 end: cursor,
7432 reversed: false,
7433 goal: SelectionGoal::None,
7434 }
7435 })
7436 .collect();
7437
7438 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7439 s.select(new_selections);
7440 });
7441 });
7442 }
7443
7444 pub fn join_lines_impl(
7445 &mut self,
7446 insert_whitespace: bool,
7447 window: &mut Window,
7448 cx: &mut Context<Self>,
7449 ) {
7450 if self.read_only(cx) {
7451 return;
7452 }
7453 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7454 for selection in self.selections.all::<Point>(cx) {
7455 let start = MultiBufferRow(selection.start.row);
7456 // Treat single line selections as if they include the next line. Otherwise this action
7457 // would do nothing for single line selections individual cursors.
7458 let end = if selection.start.row == selection.end.row {
7459 MultiBufferRow(selection.start.row + 1)
7460 } else {
7461 MultiBufferRow(selection.end.row)
7462 };
7463
7464 if let Some(last_row_range) = row_ranges.last_mut() {
7465 if start <= last_row_range.end {
7466 last_row_range.end = end;
7467 continue;
7468 }
7469 }
7470 row_ranges.push(start..end);
7471 }
7472
7473 let snapshot = self.buffer.read(cx).snapshot(cx);
7474 let mut cursor_positions = Vec::new();
7475 for row_range in &row_ranges {
7476 let anchor = snapshot.anchor_before(Point::new(
7477 row_range.end.previous_row().0,
7478 snapshot.line_len(row_range.end.previous_row()),
7479 ));
7480 cursor_positions.push(anchor..anchor);
7481 }
7482
7483 self.transact(window, cx, |this, window, cx| {
7484 for row_range in row_ranges.into_iter().rev() {
7485 for row in row_range.iter_rows().rev() {
7486 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7487 let next_line_row = row.next_row();
7488 let indent = snapshot.indent_size_for_line(next_line_row);
7489 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7490
7491 let replace =
7492 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7493 " "
7494 } else {
7495 ""
7496 };
7497
7498 this.buffer.update(cx, |buffer, cx| {
7499 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7500 });
7501 }
7502 }
7503
7504 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7505 s.select_anchor_ranges(cursor_positions)
7506 });
7507 });
7508 }
7509
7510 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7511 self.join_lines_impl(true, window, cx);
7512 }
7513
7514 pub fn sort_lines_case_sensitive(
7515 &mut self,
7516 _: &SortLinesCaseSensitive,
7517 window: &mut Window,
7518 cx: &mut Context<Self>,
7519 ) {
7520 self.manipulate_lines(window, cx, |lines| lines.sort())
7521 }
7522
7523 pub fn sort_lines_case_insensitive(
7524 &mut self,
7525 _: &SortLinesCaseInsensitive,
7526 window: &mut Window,
7527 cx: &mut Context<Self>,
7528 ) {
7529 self.manipulate_lines(window, cx, |lines| {
7530 lines.sort_by_key(|line| line.to_lowercase())
7531 })
7532 }
7533
7534 pub fn unique_lines_case_insensitive(
7535 &mut self,
7536 _: &UniqueLinesCaseInsensitive,
7537 window: &mut Window,
7538 cx: &mut Context<Self>,
7539 ) {
7540 self.manipulate_lines(window, cx, |lines| {
7541 let mut seen = HashSet::default();
7542 lines.retain(|line| seen.insert(line.to_lowercase()));
7543 })
7544 }
7545
7546 pub fn unique_lines_case_sensitive(
7547 &mut self,
7548 _: &UniqueLinesCaseSensitive,
7549 window: &mut Window,
7550 cx: &mut Context<Self>,
7551 ) {
7552 self.manipulate_lines(window, cx, |lines| {
7553 let mut seen = HashSet::default();
7554 lines.retain(|line| seen.insert(*line));
7555 })
7556 }
7557
7558 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7559 let Some(project) = self.project.clone() else {
7560 return;
7561 };
7562 self.reload(project, window, cx)
7563 .detach_and_notify_err(window, cx);
7564 }
7565
7566 pub fn restore_file(
7567 &mut self,
7568 _: &::git::RestoreFile,
7569 window: &mut Window,
7570 cx: &mut Context<Self>,
7571 ) {
7572 let mut buffer_ids = HashSet::default();
7573 let snapshot = self.buffer().read(cx).snapshot(cx);
7574 for selection in self.selections.all::<usize>(cx) {
7575 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7576 }
7577
7578 let buffer = self.buffer().read(cx);
7579 let ranges = buffer_ids
7580 .into_iter()
7581 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7582 .collect::<Vec<_>>();
7583
7584 self.restore_hunks_in_ranges(ranges, window, cx);
7585 }
7586
7587 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7588 let selections = self
7589 .selections
7590 .all(cx)
7591 .into_iter()
7592 .map(|s| s.range())
7593 .collect();
7594 self.restore_hunks_in_ranges(selections, window, cx);
7595 }
7596
7597 fn restore_hunks_in_ranges(
7598 &mut self,
7599 ranges: Vec<Range<Point>>,
7600 window: &mut Window,
7601 cx: &mut Context<Editor>,
7602 ) {
7603 let mut revert_changes = HashMap::default();
7604 let snapshot = self.buffer.read(cx).snapshot(cx);
7605 let Some(project) = &self.project else {
7606 return;
7607 };
7608
7609 let chunk_by = self
7610 .snapshot(window, cx)
7611 .hunks_for_ranges(ranges.into_iter())
7612 .into_iter()
7613 .chunk_by(|hunk| hunk.buffer_id);
7614 for (buffer_id, hunks) in &chunk_by {
7615 let hunks = hunks.collect::<Vec<_>>();
7616 for hunk in &hunks {
7617 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7618 }
7619 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7620 }
7621 drop(chunk_by);
7622 if !revert_changes.is_empty() {
7623 self.transact(window, cx, |editor, window, cx| {
7624 editor.revert(revert_changes, window, cx);
7625 });
7626 }
7627 }
7628
7629 pub fn open_active_item_in_terminal(
7630 &mut self,
7631 _: &OpenInTerminal,
7632 window: &mut Window,
7633 cx: &mut Context<Self>,
7634 ) {
7635 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7636 let project_path = buffer.read(cx).project_path(cx)?;
7637 let project = self.project.as_ref()?.read(cx);
7638 let entry = project.entry_for_path(&project_path, cx)?;
7639 let parent = match &entry.canonical_path {
7640 Some(canonical_path) => canonical_path.to_path_buf(),
7641 None => project.absolute_path(&project_path, cx)?,
7642 }
7643 .parent()?
7644 .to_path_buf();
7645 Some(parent)
7646 }) {
7647 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7648 }
7649 }
7650
7651 pub fn prepare_restore_change(
7652 &self,
7653 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7654 hunk: &MultiBufferDiffHunk,
7655 cx: &mut App,
7656 ) -> Option<()> {
7657 let buffer = self.buffer.read(cx);
7658 let diff = buffer.diff_for(hunk.buffer_id)?;
7659 let buffer = buffer.buffer(hunk.buffer_id)?;
7660 let buffer = buffer.read(cx);
7661 let original_text = diff
7662 .read(cx)
7663 .base_text()
7664 .as_ref()?
7665 .as_rope()
7666 .slice(hunk.diff_base_byte_range.clone());
7667 let buffer_snapshot = buffer.snapshot();
7668 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7669 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7670 probe
7671 .0
7672 .start
7673 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7674 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7675 }) {
7676 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7677 Some(())
7678 } else {
7679 None
7680 }
7681 }
7682
7683 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7684 self.manipulate_lines(window, cx, |lines| lines.reverse())
7685 }
7686
7687 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7688 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7689 }
7690
7691 fn manipulate_lines<Fn>(
7692 &mut self,
7693 window: &mut Window,
7694 cx: &mut Context<Self>,
7695 mut callback: Fn,
7696 ) where
7697 Fn: FnMut(&mut Vec<&str>),
7698 {
7699 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7700 let buffer = self.buffer.read(cx).snapshot(cx);
7701
7702 let mut edits = Vec::new();
7703
7704 let selections = self.selections.all::<Point>(cx);
7705 let mut selections = selections.iter().peekable();
7706 let mut contiguous_row_selections = Vec::new();
7707 let mut new_selections = Vec::new();
7708 let mut added_lines = 0;
7709 let mut removed_lines = 0;
7710
7711 while let Some(selection) = selections.next() {
7712 let (start_row, end_row) = consume_contiguous_rows(
7713 &mut contiguous_row_selections,
7714 selection,
7715 &display_map,
7716 &mut selections,
7717 );
7718
7719 let start_point = Point::new(start_row.0, 0);
7720 let end_point = Point::new(
7721 end_row.previous_row().0,
7722 buffer.line_len(end_row.previous_row()),
7723 );
7724 let text = buffer
7725 .text_for_range(start_point..end_point)
7726 .collect::<String>();
7727
7728 let mut lines = text.split('\n').collect_vec();
7729
7730 let lines_before = lines.len();
7731 callback(&mut lines);
7732 let lines_after = lines.len();
7733
7734 edits.push((start_point..end_point, lines.join("\n")));
7735
7736 // Selections must change based on added and removed line count
7737 let start_row =
7738 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7739 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7740 new_selections.push(Selection {
7741 id: selection.id,
7742 start: start_row,
7743 end: end_row,
7744 goal: SelectionGoal::None,
7745 reversed: selection.reversed,
7746 });
7747
7748 if lines_after > lines_before {
7749 added_lines += lines_after - lines_before;
7750 } else if lines_before > lines_after {
7751 removed_lines += lines_before - lines_after;
7752 }
7753 }
7754
7755 self.transact(window, cx, |this, window, cx| {
7756 let buffer = this.buffer.update(cx, |buffer, cx| {
7757 buffer.edit(edits, None, cx);
7758 buffer.snapshot(cx)
7759 });
7760
7761 // Recalculate offsets on newly edited buffer
7762 let new_selections = new_selections
7763 .iter()
7764 .map(|s| {
7765 let start_point = Point::new(s.start.0, 0);
7766 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7767 Selection {
7768 id: s.id,
7769 start: buffer.point_to_offset(start_point),
7770 end: buffer.point_to_offset(end_point),
7771 goal: s.goal,
7772 reversed: s.reversed,
7773 }
7774 })
7775 .collect();
7776
7777 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7778 s.select(new_selections);
7779 });
7780
7781 this.request_autoscroll(Autoscroll::fit(), cx);
7782 });
7783 }
7784
7785 pub fn convert_to_upper_case(
7786 &mut self,
7787 _: &ConvertToUpperCase,
7788 window: &mut Window,
7789 cx: &mut Context<Self>,
7790 ) {
7791 self.manipulate_text(window, cx, |text| text.to_uppercase())
7792 }
7793
7794 pub fn convert_to_lower_case(
7795 &mut self,
7796 _: &ConvertToLowerCase,
7797 window: &mut Window,
7798 cx: &mut Context<Self>,
7799 ) {
7800 self.manipulate_text(window, cx, |text| text.to_lowercase())
7801 }
7802
7803 pub fn convert_to_title_case(
7804 &mut self,
7805 _: &ConvertToTitleCase,
7806 window: &mut Window,
7807 cx: &mut Context<Self>,
7808 ) {
7809 self.manipulate_text(window, cx, |text| {
7810 text.split('\n')
7811 .map(|line| line.to_case(Case::Title))
7812 .join("\n")
7813 })
7814 }
7815
7816 pub fn convert_to_snake_case(
7817 &mut self,
7818 _: &ConvertToSnakeCase,
7819 window: &mut Window,
7820 cx: &mut Context<Self>,
7821 ) {
7822 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7823 }
7824
7825 pub fn convert_to_kebab_case(
7826 &mut self,
7827 _: &ConvertToKebabCase,
7828 window: &mut Window,
7829 cx: &mut Context<Self>,
7830 ) {
7831 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7832 }
7833
7834 pub fn convert_to_upper_camel_case(
7835 &mut self,
7836 _: &ConvertToUpperCamelCase,
7837 window: &mut Window,
7838 cx: &mut Context<Self>,
7839 ) {
7840 self.manipulate_text(window, cx, |text| {
7841 text.split('\n')
7842 .map(|line| line.to_case(Case::UpperCamel))
7843 .join("\n")
7844 })
7845 }
7846
7847 pub fn convert_to_lower_camel_case(
7848 &mut self,
7849 _: &ConvertToLowerCamelCase,
7850 window: &mut Window,
7851 cx: &mut Context<Self>,
7852 ) {
7853 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7854 }
7855
7856 pub fn convert_to_opposite_case(
7857 &mut self,
7858 _: &ConvertToOppositeCase,
7859 window: &mut Window,
7860 cx: &mut Context<Self>,
7861 ) {
7862 self.manipulate_text(window, cx, |text| {
7863 text.chars()
7864 .fold(String::with_capacity(text.len()), |mut t, c| {
7865 if c.is_uppercase() {
7866 t.extend(c.to_lowercase());
7867 } else {
7868 t.extend(c.to_uppercase());
7869 }
7870 t
7871 })
7872 })
7873 }
7874
7875 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7876 where
7877 Fn: FnMut(&str) -> String,
7878 {
7879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7880 let buffer = self.buffer.read(cx).snapshot(cx);
7881
7882 let mut new_selections = Vec::new();
7883 let mut edits = Vec::new();
7884 let mut selection_adjustment = 0i32;
7885
7886 for selection in self.selections.all::<usize>(cx) {
7887 let selection_is_empty = selection.is_empty();
7888
7889 let (start, end) = if selection_is_empty {
7890 let word_range = movement::surrounding_word(
7891 &display_map,
7892 selection.start.to_display_point(&display_map),
7893 );
7894 let start = word_range.start.to_offset(&display_map, Bias::Left);
7895 let end = word_range.end.to_offset(&display_map, Bias::Left);
7896 (start, end)
7897 } else {
7898 (selection.start, selection.end)
7899 };
7900
7901 let text = buffer.text_for_range(start..end).collect::<String>();
7902 let old_length = text.len() as i32;
7903 let text = callback(&text);
7904
7905 new_selections.push(Selection {
7906 start: (start as i32 - selection_adjustment) as usize,
7907 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7908 goal: SelectionGoal::None,
7909 ..selection
7910 });
7911
7912 selection_adjustment += old_length - text.len() as i32;
7913
7914 edits.push((start..end, text));
7915 }
7916
7917 self.transact(window, cx, |this, window, cx| {
7918 this.buffer.update(cx, |buffer, cx| {
7919 buffer.edit(edits, None, cx);
7920 });
7921
7922 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7923 s.select(new_selections);
7924 });
7925
7926 this.request_autoscroll(Autoscroll::fit(), cx);
7927 });
7928 }
7929
7930 pub fn duplicate(
7931 &mut self,
7932 upwards: bool,
7933 whole_lines: bool,
7934 window: &mut Window,
7935 cx: &mut Context<Self>,
7936 ) {
7937 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7938 let buffer = &display_map.buffer_snapshot;
7939 let selections = self.selections.all::<Point>(cx);
7940
7941 let mut edits = Vec::new();
7942 let mut selections_iter = selections.iter().peekable();
7943 while let Some(selection) = selections_iter.next() {
7944 let mut rows = selection.spanned_rows(false, &display_map);
7945 // duplicate line-wise
7946 if whole_lines || selection.start == selection.end {
7947 // Avoid duplicating the same lines twice.
7948 while let Some(next_selection) = selections_iter.peek() {
7949 let next_rows = next_selection.spanned_rows(false, &display_map);
7950 if next_rows.start < rows.end {
7951 rows.end = next_rows.end;
7952 selections_iter.next().unwrap();
7953 } else {
7954 break;
7955 }
7956 }
7957
7958 // Copy the text from the selected row region and splice it either at the start
7959 // or end of the region.
7960 let start = Point::new(rows.start.0, 0);
7961 let end = Point::new(
7962 rows.end.previous_row().0,
7963 buffer.line_len(rows.end.previous_row()),
7964 );
7965 let text = buffer
7966 .text_for_range(start..end)
7967 .chain(Some("\n"))
7968 .collect::<String>();
7969 let insert_location = if upwards {
7970 Point::new(rows.end.0, 0)
7971 } else {
7972 start
7973 };
7974 edits.push((insert_location..insert_location, text));
7975 } else {
7976 // duplicate character-wise
7977 let start = selection.start;
7978 let end = selection.end;
7979 let text = buffer.text_for_range(start..end).collect::<String>();
7980 edits.push((selection.end..selection.end, text));
7981 }
7982 }
7983
7984 self.transact(window, cx, |this, _, cx| {
7985 this.buffer.update(cx, |buffer, cx| {
7986 buffer.edit(edits, None, cx);
7987 });
7988
7989 this.request_autoscroll(Autoscroll::fit(), cx);
7990 });
7991 }
7992
7993 pub fn duplicate_line_up(
7994 &mut self,
7995 _: &DuplicateLineUp,
7996 window: &mut Window,
7997 cx: &mut Context<Self>,
7998 ) {
7999 self.duplicate(true, true, window, cx);
8000 }
8001
8002 pub fn duplicate_line_down(
8003 &mut self,
8004 _: &DuplicateLineDown,
8005 window: &mut Window,
8006 cx: &mut Context<Self>,
8007 ) {
8008 self.duplicate(false, true, window, cx);
8009 }
8010
8011 pub fn duplicate_selection(
8012 &mut self,
8013 _: &DuplicateSelection,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 self.duplicate(false, false, window, cx);
8018 }
8019
8020 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8021 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8022 let buffer = self.buffer.read(cx).snapshot(cx);
8023
8024 let mut edits = Vec::new();
8025 let mut unfold_ranges = Vec::new();
8026 let mut refold_creases = Vec::new();
8027
8028 let selections = self.selections.all::<Point>(cx);
8029 let mut selections = selections.iter().peekable();
8030 let mut contiguous_row_selections = Vec::new();
8031 let mut new_selections = Vec::new();
8032
8033 while let Some(selection) = selections.next() {
8034 // Find all the selections that span a contiguous row range
8035 let (start_row, end_row) = consume_contiguous_rows(
8036 &mut contiguous_row_selections,
8037 selection,
8038 &display_map,
8039 &mut selections,
8040 );
8041
8042 // Move the text spanned by the row range to be before the line preceding the row range
8043 if start_row.0 > 0 {
8044 let range_to_move = Point::new(
8045 start_row.previous_row().0,
8046 buffer.line_len(start_row.previous_row()),
8047 )
8048 ..Point::new(
8049 end_row.previous_row().0,
8050 buffer.line_len(end_row.previous_row()),
8051 );
8052 let insertion_point = display_map
8053 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8054 .0;
8055
8056 // Don't move lines across excerpts
8057 if buffer
8058 .excerpt_containing(insertion_point..range_to_move.end)
8059 .is_some()
8060 {
8061 let text = buffer
8062 .text_for_range(range_to_move.clone())
8063 .flat_map(|s| s.chars())
8064 .skip(1)
8065 .chain(['\n'])
8066 .collect::<String>();
8067
8068 edits.push((
8069 buffer.anchor_after(range_to_move.start)
8070 ..buffer.anchor_before(range_to_move.end),
8071 String::new(),
8072 ));
8073 let insertion_anchor = buffer.anchor_after(insertion_point);
8074 edits.push((insertion_anchor..insertion_anchor, text));
8075
8076 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8077
8078 // Move selections up
8079 new_selections.extend(contiguous_row_selections.drain(..).map(
8080 |mut selection| {
8081 selection.start.row -= row_delta;
8082 selection.end.row -= row_delta;
8083 selection
8084 },
8085 ));
8086
8087 // Move folds up
8088 unfold_ranges.push(range_to_move.clone());
8089 for fold in display_map.folds_in_range(
8090 buffer.anchor_before(range_to_move.start)
8091 ..buffer.anchor_after(range_to_move.end),
8092 ) {
8093 let mut start = fold.range.start.to_point(&buffer);
8094 let mut end = fold.range.end.to_point(&buffer);
8095 start.row -= row_delta;
8096 end.row -= row_delta;
8097 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8098 }
8099 }
8100 }
8101
8102 // If we didn't move line(s), preserve the existing selections
8103 new_selections.append(&mut contiguous_row_selections);
8104 }
8105
8106 self.transact(window, cx, |this, window, cx| {
8107 this.unfold_ranges(&unfold_ranges, true, true, cx);
8108 this.buffer.update(cx, |buffer, cx| {
8109 for (range, text) in edits {
8110 buffer.edit([(range, text)], None, cx);
8111 }
8112 });
8113 this.fold_creases(refold_creases, true, window, cx);
8114 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8115 s.select(new_selections);
8116 })
8117 });
8118 }
8119
8120 pub fn move_line_down(
8121 &mut self,
8122 _: &MoveLineDown,
8123 window: &mut Window,
8124 cx: &mut Context<Self>,
8125 ) {
8126 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8127 let buffer = self.buffer.read(cx).snapshot(cx);
8128
8129 let mut edits = Vec::new();
8130 let mut unfold_ranges = Vec::new();
8131 let mut refold_creases = Vec::new();
8132
8133 let selections = self.selections.all::<Point>(cx);
8134 let mut selections = selections.iter().peekable();
8135 let mut contiguous_row_selections = Vec::new();
8136 let mut new_selections = Vec::new();
8137
8138 while let Some(selection) = selections.next() {
8139 // Find all the selections that span a contiguous row range
8140 let (start_row, end_row) = consume_contiguous_rows(
8141 &mut contiguous_row_selections,
8142 selection,
8143 &display_map,
8144 &mut selections,
8145 );
8146
8147 // Move the text spanned by the row range to be after the last line of the row range
8148 if end_row.0 <= buffer.max_point().row {
8149 let range_to_move =
8150 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8151 let insertion_point = display_map
8152 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8153 .0;
8154
8155 // Don't move lines across excerpt boundaries
8156 if buffer
8157 .excerpt_containing(range_to_move.start..insertion_point)
8158 .is_some()
8159 {
8160 let mut text = String::from("\n");
8161 text.extend(buffer.text_for_range(range_to_move.clone()));
8162 text.pop(); // Drop trailing newline
8163 edits.push((
8164 buffer.anchor_after(range_to_move.start)
8165 ..buffer.anchor_before(range_to_move.end),
8166 String::new(),
8167 ));
8168 let insertion_anchor = buffer.anchor_after(insertion_point);
8169 edits.push((insertion_anchor..insertion_anchor, text));
8170
8171 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8172
8173 // Move selections down
8174 new_selections.extend(contiguous_row_selections.drain(..).map(
8175 |mut selection| {
8176 selection.start.row += row_delta;
8177 selection.end.row += row_delta;
8178 selection
8179 },
8180 ));
8181
8182 // Move folds down
8183 unfold_ranges.push(range_to_move.clone());
8184 for fold in display_map.folds_in_range(
8185 buffer.anchor_before(range_to_move.start)
8186 ..buffer.anchor_after(range_to_move.end),
8187 ) {
8188 let mut start = fold.range.start.to_point(&buffer);
8189 let mut end = fold.range.end.to_point(&buffer);
8190 start.row += row_delta;
8191 end.row += row_delta;
8192 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8193 }
8194 }
8195 }
8196
8197 // If we didn't move line(s), preserve the existing selections
8198 new_selections.append(&mut contiguous_row_selections);
8199 }
8200
8201 self.transact(window, cx, |this, window, cx| {
8202 this.unfold_ranges(&unfold_ranges, true, true, cx);
8203 this.buffer.update(cx, |buffer, cx| {
8204 for (range, text) in edits {
8205 buffer.edit([(range, text)], None, cx);
8206 }
8207 });
8208 this.fold_creases(refold_creases, true, window, cx);
8209 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8210 s.select(new_selections)
8211 });
8212 });
8213 }
8214
8215 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8216 let text_layout_details = &self.text_layout_details(window);
8217 self.transact(window, cx, |this, window, cx| {
8218 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8219 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8220 let line_mode = s.line_mode;
8221 s.move_with(|display_map, selection| {
8222 if !selection.is_empty() || line_mode {
8223 return;
8224 }
8225
8226 let mut head = selection.head();
8227 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8228 if head.column() == display_map.line_len(head.row()) {
8229 transpose_offset = display_map
8230 .buffer_snapshot
8231 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8232 }
8233
8234 if transpose_offset == 0 {
8235 return;
8236 }
8237
8238 *head.column_mut() += 1;
8239 head = display_map.clip_point(head, Bias::Right);
8240 let goal = SelectionGoal::HorizontalPosition(
8241 display_map
8242 .x_for_display_point(head, text_layout_details)
8243 .into(),
8244 );
8245 selection.collapse_to(head, goal);
8246
8247 let transpose_start = display_map
8248 .buffer_snapshot
8249 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8250 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8251 let transpose_end = display_map
8252 .buffer_snapshot
8253 .clip_offset(transpose_offset + 1, Bias::Right);
8254 if let Some(ch) =
8255 display_map.buffer_snapshot.chars_at(transpose_start).next()
8256 {
8257 edits.push((transpose_start..transpose_offset, String::new()));
8258 edits.push((transpose_end..transpose_end, ch.to_string()));
8259 }
8260 }
8261 });
8262 edits
8263 });
8264 this.buffer
8265 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8266 let selections = this.selections.all::<usize>(cx);
8267 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8268 s.select(selections);
8269 });
8270 });
8271 }
8272
8273 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8274 self.rewrap_impl(IsVimMode::No, cx)
8275 }
8276
8277 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8278 let buffer = self.buffer.read(cx).snapshot(cx);
8279 let selections = self.selections.all::<Point>(cx);
8280 let mut selections = selections.iter().peekable();
8281
8282 let mut edits = Vec::new();
8283 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8284
8285 while let Some(selection) = selections.next() {
8286 let mut start_row = selection.start.row;
8287 let mut end_row = selection.end.row;
8288
8289 // Skip selections that overlap with a range that has already been rewrapped.
8290 let selection_range = start_row..end_row;
8291 if rewrapped_row_ranges
8292 .iter()
8293 .any(|range| range.overlaps(&selection_range))
8294 {
8295 continue;
8296 }
8297
8298 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8299
8300 // Since not all lines in the selection may be at the same indent
8301 // level, choose the indent size that is the most common between all
8302 // of the lines.
8303 //
8304 // If there is a tie, we use the deepest indent.
8305 let (indent_size, indent_end) = {
8306 let mut indent_size_occurrences = HashMap::default();
8307 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8308
8309 for row in start_row..=end_row {
8310 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8311 rows_by_indent_size.entry(indent).or_default().push(row);
8312 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8313 }
8314
8315 let indent_size = indent_size_occurrences
8316 .into_iter()
8317 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8318 .map(|(indent, _)| indent)
8319 .unwrap_or_default();
8320 let row = rows_by_indent_size[&indent_size][0];
8321 let indent_end = Point::new(row, indent_size.len);
8322
8323 (indent_size, indent_end)
8324 };
8325
8326 let mut line_prefix = indent_size.chars().collect::<String>();
8327
8328 let mut inside_comment = false;
8329 if let Some(comment_prefix) =
8330 buffer
8331 .language_scope_at(selection.head())
8332 .and_then(|language| {
8333 language
8334 .line_comment_prefixes()
8335 .iter()
8336 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8337 .cloned()
8338 })
8339 {
8340 line_prefix.push_str(&comment_prefix);
8341 inside_comment = true;
8342 }
8343
8344 let language_settings = buffer.settings_at(selection.head(), cx);
8345 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8346 RewrapBehavior::InComments => inside_comment,
8347 RewrapBehavior::InSelections => !selection.is_empty(),
8348 RewrapBehavior::Anywhere => true,
8349 };
8350
8351 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8352 if !should_rewrap {
8353 continue;
8354 }
8355
8356 if selection.is_empty() {
8357 'expand_upwards: while start_row > 0 {
8358 let prev_row = start_row - 1;
8359 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8360 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8361 {
8362 start_row = prev_row;
8363 } else {
8364 break 'expand_upwards;
8365 }
8366 }
8367
8368 'expand_downwards: while end_row < buffer.max_point().row {
8369 let next_row = end_row + 1;
8370 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8371 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8372 {
8373 end_row = next_row;
8374 } else {
8375 break 'expand_downwards;
8376 }
8377 }
8378 }
8379
8380 let start = Point::new(start_row, 0);
8381 let start_offset = start.to_offset(&buffer);
8382 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8383 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8384 let Some(lines_without_prefixes) = selection_text
8385 .lines()
8386 .map(|line| {
8387 line.strip_prefix(&line_prefix)
8388 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8389 .ok_or_else(|| {
8390 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8391 })
8392 })
8393 .collect::<Result<Vec<_>, _>>()
8394 .log_err()
8395 else {
8396 continue;
8397 };
8398
8399 let wrap_column = buffer
8400 .settings_at(Point::new(start_row, 0), cx)
8401 .preferred_line_length as usize;
8402 let wrapped_text = wrap_with_prefix(
8403 line_prefix,
8404 lines_without_prefixes.join(" "),
8405 wrap_column,
8406 tab_size,
8407 );
8408
8409 // TODO: should always use char-based diff while still supporting cursor behavior that
8410 // matches vim.
8411 let mut diff_options = DiffOptions::default();
8412 if is_vim_mode == IsVimMode::Yes {
8413 diff_options.max_word_diff_len = 0;
8414 diff_options.max_word_diff_line_count = 0;
8415 } else {
8416 diff_options.max_word_diff_len = usize::MAX;
8417 diff_options.max_word_diff_line_count = usize::MAX;
8418 }
8419
8420 for (old_range, new_text) in
8421 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8422 {
8423 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8424 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8425 edits.push((edit_start..edit_end, new_text));
8426 }
8427
8428 rewrapped_row_ranges.push(start_row..=end_row);
8429 }
8430
8431 self.buffer
8432 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8433 }
8434
8435 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8436 let mut text = String::new();
8437 let buffer = self.buffer.read(cx).snapshot(cx);
8438 let mut selections = self.selections.all::<Point>(cx);
8439 let mut clipboard_selections = Vec::with_capacity(selections.len());
8440 {
8441 let max_point = buffer.max_point();
8442 let mut is_first = true;
8443 for selection in &mut selections {
8444 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8445 if is_entire_line {
8446 selection.start = Point::new(selection.start.row, 0);
8447 if !selection.is_empty() && selection.end.column == 0 {
8448 selection.end = cmp::min(max_point, selection.end);
8449 } else {
8450 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8451 }
8452 selection.goal = SelectionGoal::None;
8453 }
8454 if is_first {
8455 is_first = false;
8456 } else {
8457 text += "\n";
8458 }
8459 let mut len = 0;
8460 for chunk in buffer.text_for_range(selection.start..selection.end) {
8461 text.push_str(chunk);
8462 len += chunk.len();
8463 }
8464 clipboard_selections.push(ClipboardSelection {
8465 len,
8466 is_entire_line,
8467 start_column: selection.start.column,
8468 });
8469 }
8470 }
8471
8472 self.transact(window, cx, |this, window, cx| {
8473 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8474 s.select(selections);
8475 });
8476 this.insert("", window, cx);
8477 });
8478 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8479 }
8480
8481 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8482 let item = self.cut_common(window, cx);
8483 cx.write_to_clipboard(item);
8484 }
8485
8486 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8487 self.change_selections(None, window, cx, |s| {
8488 s.move_with(|snapshot, sel| {
8489 if sel.is_empty() {
8490 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8491 }
8492 });
8493 });
8494 let item = self.cut_common(window, cx);
8495 cx.set_global(KillRing(item))
8496 }
8497
8498 pub fn kill_ring_yank(
8499 &mut self,
8500 _: &KillRingYank,
8501 window: &mut Window,
8502 cx: &mut Context<Self>,
8503 ) {
8504 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8505 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8506 (kill_ring.text().to_string(), kill_ring.metadata_json())
8507 } else {
8508 return;
8509 }
8510 } else {
8511 return;
8512 };
8513 self.do_paste(&text, metadata, false, window, cx);
8514 }
8515
8516 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8517 let selections = self.selections.all::<Point>(cx);
8518 let buffer = self.buffer.read(cx).read(cx);
8519 let mut text = String::new();
8520
8521 let mut clipboard_selections = Vec::with_capacity(selections.len());
8522 {
8523 let max_point = buffer.max_point();
8524 let mut is_first = true;
8525 for selection in selections.iter() {
8526 let mut start = selection.start;
8527 let mut end = selection.end;
8528 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8529 if is_entire_line {
8530 start = Point::new(start.row, 0);
8531 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8532 }
8533 if is_first {
8534 is_first = false;
8535 } else {
8536 text += "\n";
8537 }
8538 let mut len = 0;
8539 for chunk in buffer.text_for_range(start..end) {
8540 text.push_str(chunk);
8541 len += chunk.len();
8542 }
8543 clipboard_selections.push(ClipboardSelection {
8544 len,
8545 is_entire_line,
8546 start_column: start.column,
8547 });
8548 }
8549 }
8550
8551 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8552 text,
8553 clipboard_selections,
8554 ));
8555 }
8556
8557 pub fn do_paste(
8558 &mut self,
8559 text: &String,
8560 clipboard_selections: Option<Vec<ClipboardSelection>>,
8561 handle_entire_lines: bool,
8562 window: &mut Window,
8563 cx: &mut Context<Self>,
8564 ) {
8565 if self.read_only(cx) {
8566 return;
8567 }
8568
8569 let clipboard_text = Cow::Borrowed(text);
8570
8571 self.transact(window, cx, |this, window, cx| {
8572 if let Some(mut clipboard_selections) = clipboard_selections {
8573 let old_selections = this.selections.all::<usize>(cx);
8574 let all_selections_were_entire_line =
8575 clipboard_selections.iter().all(|s| s.is_entire_line);
8576 let first_selection_start_column =
8577 clipboard_selections.first().map(|s| s.start_column);
8578 if clipboard_selections.len() != old_selections.len() {
8579 clipboard_selections.drain(..);
8580 }
8581 let cursor_offset = this.selections.last::<usize>(cx).head();
8582 let mut auto_indent_on_paste = true;
8583
8584 this.buffer.update(cx, |buffer, cx| {
8585 let snapshot = buffer.read(cx);
8586 auto_indent_on_paste =
8587 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8588
8589 let mut start_offset = 0;
8590 let mut edits = Vec::new();
8591 let mut original_start_columns = Vec::new();
8592 for (ix, selection) in old_selections.iter().enumerate() {
8593 let to_insert;
8594 let entire_line;
8595 let original_start_column;
8596 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8597 let end_offset = start_offset + clipboard_selection.len;
8598 to_insert = &clipboard_text[start_offset..end_offset];
8599 entire_line = clipboard_selection.is_entire_line;
8600 start_offset = end_offset + 1;
8601 original_start_column = Some(clipboard_selection.start_column);
8602 } else {
8603 to_insert = clipboard_text.as_str();
8604 entire_line = all_selections_were_entire_line;
8605 original_start_column = first_selection_start_column
8606 }
8607
8608 // If the corresponding selection was empty when this slice of the
8609 // clipboard text was written, then the entire line containing the
8610 // selection was copied. If this selection is also currently empty,
8611 // then paste the line before the current line of the buffer.
8612 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8613 let column = selection.start.to_point(&snapshot).column as usize;
8614 let line_start = selection.start - column;
8615 line_start..line_start
8616 } else {
8617 selection.range()
8618 };
8619
8620 edits.push((range, to_insert));
8621 original_start_columns.extend(original_start_column);
8622 }
8623 drop(snapshot);
8624
8625 buffer.edit(
8626 edits,
8627 if auto_indent_on_paste {
8628 Some(AutoindentMode::Block {
8629 original_start_columns,
8630 })
8631 } else {
8632 None
8633 },
8634 cx,
8635 );
8636 });
8637
8638 let selections = this.selections.all::<usize>(cx);
8639 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8640 s.select(selections)
8641 });
8642 } else {
8643 this.insert(&clipboard_text, window, cx);
8644 }
8645 });
8646 }
8647
8648 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8649 if let Some(item) = cx.read_from_clipboard() {
8650 let entries = item.entries();
8651
8652 match entries.first() {
8653 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8654 // of all the pasted entries.
8655 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8656 .do_paste(
8657 clipboard_string.text(),
8658 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8659 true,
8660 window,
8661 cx,
8662 ),
8663 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8664 }
8665 }
8666 }
8667
8668 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8669 if self.read_only(cx) {
8670 return;
8671 }
8672
8673 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8674 if let Some((selections, _)) =
8675 self.selection_history.transaction(transaction_id).cloned()
8676 {
8677 self.change_selections(None, window, cx, |s| {
8678 s.select_anchors(selections.to_vec());
8679 });
8680 }
8681 self.request_autoscroll(Autoscroll::fit(), cx);
8682 self.unmark_text(window, cx);
8683 self.refresh_inline_completion(true, false, window, cx);
8684 cx.emit(EditorEvent::Edited { transaction_id });
8685 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8686 }
8687 }
8688
8689 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8690 if self.read_only(cx) {
8691 return;
8692 }
8693
8694 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8695 if let Some((_, Some(selections))) =
8696 self.selection_history.transaction(transaction_id).cloned()
8697 {
8698 self.change_selections(None, window, cx, |s| {
8699 s.select_anchors(selections.to_vec());
8700 });
8701 }
8702 self.request_autoscroll(Autoscroll::fit(), cx);
8703 self.unmark_text(window, cx);
8704 self.refresh_inline_completion(true, false, window, cx);
8705 cx.emit(EditorEvent::Edited { transaction_id });
8706 }
8707 }
8708
8709 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8710 self.buffer
8711 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8712 }
8713
8714 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8715 self.buffer
8716 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8717 }
8718
8719 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8720 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8721 let line_mode = s.line_mode;
8722 s.move_with(|map, selection| {
8723 let cursor = if selection.is_empty() && !line_mode {
8724 movement::left(map, selection.start)
8725 } else {
8726 selection.start
8727 };
8728 selection.collapse_to(cursor, SelectionGoal::None);
8729 });
8730 })
8731 }
8732
8733 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8734 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8735 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8736 })
8737 }
8738
8739 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8740 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8741 let line_mode = s.line_mode;
8742 s.move_with(|map, selection| {
8743 let cursor = if selection.is_empty() && !line_mode {
8744 movement::right(map, selection.end)
8745 } else {
8746 selection.end
8747 };
8748 selection.collapse_to(cursor, SelectionGoal::None)
8749 });
8750 })
8751 }
8752
8753 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8754 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8755 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8756 })
8757 }
8758
8759 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8760 if self.take_rename(true, window, cx).is_some() {
8761 return;
8762 }
8763
8764 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8765 cx.propagate();
8766 return;
8767 }
8768
8769 let text_layout_details = &self.text_layout_details(window);
8770 let selection_count = self.selections.count();
8771 let first_selection = self.selections.first_anchor();
8772
8773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8774 let line_mode = s.line_mode;
8775 s.move_with(|map, selection| {
8776 if !selection.is_empty() && !line_mode {
8777 selection.goal = SelectionGoal::None;
8778 }
8779 let (cursor, goal) = movement::up(
8780 map,
8781 selection.start,
8782 selection.goal,
8783 false,
8784 text_layout_details,
8785 );
8786 selection.collapse_to(cursor, goal);
8787 });
8788 });
8789
8790 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8791 {
8792 cx.propagate();
8793 }
8794 }
8795
8796 pub fn move_up_by_lines(
8797 &mut self,
8798 action: &MoveUpByLines,
8799 window: &mut Window,
8800 cx: &mut Context<Self>,
8801 ) {
8802 if self.take_rename(true, window, cx).is_some() {
8803 return;
8804 }
8805
8806 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8807 cx.propagate();
8808 return;
8809 }
8810
8811 let text_layout_details = &self.text_layout_details(window);
8812
8813 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8814 let line_mode = s.line_mode;
8815 s.move_with(|map, selection| {
8816 if !selection.is_empty() && !line_mode {
8817 selection.goal = SelectionGoal::None;
8818 }
8819 let (cursor, goal) = movement::up_by_rows(
8820 map,
8821 selection.start,
8822 action.lines,
8823 selection.goal,
8824 false,
8825 text_layout_details,
8826 );
8827 selection.collapse_to(cursor, goal);
8828 });
8829 })
8830 }
8831
8832 pub fn move_down_by_lines(
8833 &mut self,
8834 action: &MoveDownByLines,
8835 window: &mut Window,
8836 cx: &mut Context<Self>,
8837 ) {
8838 if self.take_rename(true, window, cx).is_some() {
8839 return;
8840 }
8841
8842 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8843 cx.propagate();
8844 return;
8845 }
8846
8847 let text_layout_details = &self.text_layout_details(window);
8848
8849 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8850 let line_mode = s.line_mode;
8851 s.move_with(|map, selection| {
8852 if !selection.is_empty() && !line_mode {
8853 selection.goal = SelectionGoal::None;
8854 }
8855 let (cursor, goal) = movement::down_by_rows(
8856 map,
8857 selection.start,
8858 action.lines,
8859 selection.goal,
8860 false,
8861 text_layout_details,
8862 );
8863 selection.collapse_to(cursor, goal);
8864 });
8865 })
8866 }
8867
8868 pub fn select_down_by_lines(
8869 &mut self,
8870 action: &SelectDownByLines,
8871 window: &mut Window,
8872 cx: &mut Context<Self>,
8873 ) {
8874 let text_layout_details = &self.text_layout_details(window);
8875 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8876 s.move_heads_with(|map, head, goal| {
8877 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8878 })
8879 })
8880 }
8881
8882 pub fn select_up_by_lines(
8883 &mut self,
8884 action: &SelectUpByLines,
8885 window: &mut Window,
8886 cx: &mut Context<Self>,
8887 ) {
8888 let text_layout_details = &self.text_layout_details(window);
8889 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8890 s.move_heads_with(|map, head, goal| {
8891 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8892 })
8893 })
8894 }
8895
8896 pub fn select_page_up(
8897 &mut self,
8898 _: &SelectPageUp,
8899 window: &mut Window,
8900 cx: &mut Context<Self>,
8901 ) {
8902 let Some(row_count) = self.visible_row_count() else {
8903 return;
8904 };
8905
8906 let text_layout_details = &self.text_layout_details(window);
8907
8908 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8909 s.move_heads_with(|map, head, goal| {
8910 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8911 })
8912 })
8913 }
8914
8915 pub fn move_page_up(
8916 &mut self,
8917 action: &MovePageUp,
8918 window: &mut Window,
8919 cx: &mut Context<Self>,
8920 ) {
8921 if self.take_rename(true, window, cx).is_some() {
8922 return;
8923 }
8924
8925 if self
8926 .context_menu
8927 .borrow_mut()
8928 .as_mut()
8929 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8930 .unwrap_or(false)
8931 {
8932 return;
8933 }
8934
8935 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8936 cx.propagate();
8937 return;
8938 }
8939
8940 let Some(row_count) = self.visible_row_count() else {
8941 return;
8942 };
8943
8944 let autoscroll = if action.center_cursor {
8945 Autoscroll::center()
8946 } else {
8947 Autoscroll::fit()
8948 };
8949
8950 let text_layout_details = &self.text_layout_details(window);
8951
8952 self.change_selections(Some(autoscroll), window, cx, |s| {
8953 let line_mode = s.line_mode;
8954 s.move_with(|map, selection| {
8955 if !selection.is_empty() && !line_mode {
8956 selection.goal = SelectionGoal::None;
8957 }
8958 let (cursor, goal) = movement::up_by_rows(
8959 map,
8960 selection.end,
8961 row_count,
8962 selection.goal,
8963 false,
8964 text_layout_details,
8965 );
8966 selection.collapse_to(cursor, goal);
8967 });
8968 });
8969 }
8970
8971 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8972 let text_layout_details = &self.text_layout_details(window);
8973 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8974 s.move_heads_with(|map, head, goal| {
8975 movement::up(map, head, goal, false, text_layout_details)
8976 })
8977 })
8978 }
8979
8980 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8981 self.take_rename(true, window, cx);
8982
8983 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8984 cx.propagate();
8985 return;
8986 }
8987
8988 let text_layout_details = &self.text_layout_details(window);
8989 let selection_count = self.selections.count();
8990 let first_selection = self.selections.first_anchor();
8991
8992 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8993 let line_mode = s.line_mode;
8994 s.move_with(|map, selection| {
8995 if !selection.is_empty() && !line_mode {
8996 selection.goal = SelectionGoal::None;
8997 }
8998 let (cursor, goal) = movement::down(
8999 map,
9000 selection.end,
9001 selection.goal,
9002 false,
9003 text_layout_details,
9004 );
9005 selection.collapse_to(cursor, goal);
9006 });
9007 });
9008
9009 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9010 {
9011 cx.propagate();
9012 }
9013 }
9014
9015 pub fn select_page_down(
9016 &mut self,
9017 _: &SelectPageDown,
9018 window: &mut Window,
9019 cx: &mut Context<Self>,
9020 ) {
9021 let Some(row_count) = self.visible_row_count() else {
9022 return;
9023 };
9024
9025 let text_layout_details = &self.text_layout_details(window);
9026
9027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9028 s.move_heads_with(|map, head, goal| {
9029 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9030 })
9031 })
9032 }
9033
9034 pub fn move_page_down(
9035 &mut self,
9036 action: &MovePageDown,
9037 window: &mut Window,
9038 cx: &mut Context<Self>,
9039 ) {
9040 if self.take_rename(true, window, cx).is_some() {
9041 return;
9042 }
9043
9044 if self
9045 .context_menu
9046 .borrow_mut()
9047 .as_mut()
9048 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9049 .unwrap_or(false)
9050 {
9051 return;
9052 }
9053
9054 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9055 cx.propagate();
9056 return;
9057 }
9058
9059 let Some(row_count) = self.visible_row_count() else {
9060 return;
9061 };
9062
9063 let autoscroll = if action.center_cursor {
9064 Autoscroll::center()
9065 } else {
9066 Autoscroll::fit()
9067 };
9068
9069 let text_layout_details = &self.text_layout_details(window);
9070 self.change_selections(Some(autoscroll), window, cx, |s| {
9071 let line_mode = s.line_mode;
9072 s.move_with(|map, selection| {
9073 if !selection.is_empty() && !line_mode {
9074 selection.goal = SelectionGoal::None;
9075 }
9076 let (cursor, goal) = movement::down_by_rows(
9077 map,
9078 selection.end,
9079 row_count,
9080 selection.goal,
9081 false,
9082 text_layout_details,
9083 );
9084 selection.collapse_to(cursor, goal);
9085 });
9086 });
9087 }
9088
9089 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9090 let text_layout_details = &self.text_layout_details(window);
9091 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9092 s.move_heads_with(|map, head, goal| {
9093 movement::down(map, head, goal, false, text_layout_details)
9094 })
9095 });
9096 }
9097
9098 pub fn context_menu_first(
9099 &mut self,
9100 _: &ContextMenuFirst,
9101 _window: &mut Window,
9102 cx: &mut Context<Self>,
9103 ) {
9104 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9105 context_menu.select_first(self.completion_provider.as_deref(), cx);
9106 }
9107 }
9108
9109 pub fn context_menu_prev(
9110 &mut self,
9111 _: &ContextMenuPrev,
9112 _window: &mut Window,
9113 cx: &mut Context<Self>,
9114 ) {
9115 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9116 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9117 }
9118 }
9119
9120 pub fn context_menu_next(
9121 &mut self,
9122 _: &ContextMenuNext,
9123 _window: &mut Window,
9124 cx: &mut Context<Self>,
9125 ) {
9126 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9127 context_menu.select_next(self.completion_provider.as_deref(), cx);
9128 }
9129 }
9130
9131 pub fn context_menu_last(
9132 &mut self,
9133 _: &ContextMenuLast,
9134 _window: &mut Window,
9135 cx: &mut Context<Self>,
9136 ) {
9137 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9138 context_menu.select_last(self.completion_provider.as_deref(), cx);
9139 }
9140 }
9141
9142 pub fn move_to_previous_word_start(
9143 &mut self,
9144 _: &MoveToPreviousWordStart,
9145 window: &mut Window,
9146 cx: &mut Context<Self>,
9147 ) {
9148 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9149 s.move_cursors_with(|map, head, _| {
9150 (
9151 movement::previous_word_start(map, head),
9152 SelectionGoal::None,
9153 )
9154 });
9155 })
9156 }
9157
9158 pub fn move_to_previous_subword_start(
9159 &mut self,
9160 _: &MoveToPreviousSubwordStart,
9161 window: &mut Window,
9162 cx: &mut Context<Self>,
9163 ) {
9164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9165 s.move_cursors_with(|map, head, _| {
9166 (
9167 movement::previous_subword_start(map, head),
9168 SelectionGoal::None,
9169 )
9170 });
9171 })
9172 }
9173
9174 pub fn select_to_previous_word_start(
9175 &mut self,
9176 _: &SelectToPreviousWordStart,
9177 window: &mut Window,
9178 cx: &mut Context<Self>,
9179 ) {
9180 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9181 s.move_heads_with(|map, head, _| {
9182 (
9183 movement::previous_word_start(map, head),
9184 SelectionGoal::None,
9185 )
9186 });
9187 })
9188 }
9189
9190 pub fn select_to_previous_subword_start(
9191 &mut self,
9192 _: &SelectToPreviousSubwordStart,
9193 window: &mut Window,
9194 cx: &mut Context<Self>,
9195 ) {
9196 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9197 s.move_heads_with(|map, head, _| {
9198 (
9199 movement::previous_subword_start(map, head),
9200 SelectionGoal::None,
9201 )
9202 });
9203 })
9204 }
9205
9206 pub fn delete_to_previous_word_start(
9207 &mut self,
9208 action: &DeleteToPreviousWordStart,
9209 window: &mut Window,
9210 cx: &mut Context<Self>,
9211 ) {
9212 self.transact(window, cx, |this, window, cx| {
9213 this.select_autoclose_pair(window, cx);
9214 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9215 let line_mode = s.line_mode;
9216 s.move_with(|map, selection| {
9217 if selection.is_empty() && !line_mode {
9218 let cursor = if action.ignore_newlines {
9219 movement::previous_word_start(map, selection.head())
9220 } else {
9221 movement::previous_word_start_or_newline(map, selection.head())
9222 };
9223 selection.set_head(cursor, SelectionGoal::None);
9224 }
9225 });
9226 });
9227 this.insert("", window, cx);
9228 });
9229 }
9230
9231 pub fn delete_to_previous_subword_start(
9232 &mut self,
9233 _: &DeleteToPreviousSubwordStart,
9234 window: &mut Window,
9235 cx: &mut Context<Self>,
9236 ) {
9237 self.transact(window, cx, |this, window, cx| {
9238 this.select_autoclose_pair(window, cx);
9239 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9240 let line_mode = s.line_mode;
9241 s.move_with(|map, selection| {
9242 if selection.is_empty() && !line_mode {
9243 let cursor = movement::previous_subword_start(map, selection.head());
9244 selection.set_head(cursor, SelectionGoal::None);
9245 }
9246 });
9247 });
9248 this.insert("", window, cx);
9249 });
9250 }
9251
9252 pub fn move_to_next_word_end(
9253 &mut self,
9254 _: &MoveToNextWordEnd,
9255 window: &mut Window,
9256 cx: &mut Context<Self>,
9257 ) {
9258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9259 s.move_cursors_with(|map, head, _| {
9260 (movement::next_word_end(map, head), SelectionGoal::None)
9261 });
9262 })
9263 }
9264
9265 pub fn move_to_next_subword_end(
9266 &mut self,
9267 _: &MoveToNextSubwordEnd,
9268 window: &mut Window,
9269 cx: &mut Context<Self>,
9270 ) {
9271 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9272 s.move_cursors_with(|map, head, _| {
9273 (movement::next_subword_end(map, head), SelectionGoal::None)
9274 });
9275 })
9276 }
9277
9278 pub fn select_to_next_word_end(
9279 &mut self,
9280 _: &SelectToNextWordEnd,
9281 window: &mut Window,
9282 cx: &mut Context<Self>,
9283 ) {
9284 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9285 s.move_heads_with(|map, head, _| {
9286 (movement::next_word_end(map, head), SelectionGoal::None)
9287 });
9288 })
9289 }
9290
9291 pub fn select_to_next_subword_end(
9292 &mut self,
9293 _: &SelectToNextSubwordEnd,
9294 window: &mut Window,
9295 cx: &mut Context<Self>,
9296 ) {
9297 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9298 s.move_heads_with(|map, head, _| {
9299 (movement::next_subword_end(map, head), SelectionGoal::None)
9300 });
9301 })
9302 }
9303
9304 pub fn delete_to_next_word_end(
9305 &mut self,
9306 action: &DeleteToNextWordEnd,
9307 window: &mut Window,
9308 cx: &mut Context<Self>,
9309 ) {
9310 self.transact(window, cx, |this, window, cx| {
9311 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9312 let line_mode = s.line_mode;
9313 s.move_with(|map, selection| {
9314 if selection.is_empty() && !line_mode {
9315 let cursor = if action.ignore_newlines {
9316 movement::next_word_end(map, selection.head())
9317 } else {
9318 movement::next_word_end_or_newline(map, selection.head())
9319 };
9320 selection.set_head(cursor, SelectionGoal::None);
9321 }
9322 });
9323 });
9324 this.insert("", window, cx);
9325 });
9326 }
9327
9328 pub fn delete_to_next_subword_end(
9329 &mut self,
9330 _: &DeleteToNextSubwordEnd,
9331 window: &mut Window,
9332 cx: &mut Context<Self>,
9333 ) {
9334 self.transact(window, cx, |this, window, cx| {
9335 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9336 s.move_with(|map, selection| {
9337 if selection.is_empty() {
9338 let cursor = movement::next_subword_end(map, selection.head());
9339 selection.set_head(cursor, SelectionGoal::None);
9340 }
9341 });
9342 });
9343 this.insert("", window, cx);
9344 });
9345 }
9346
9347 pub fn move_to_beginning_of_line(
9348 &mut self,
9349 action: &MoveToBeginningOfLine,
9350 window: &mut Window,
9351 cx: &mut Context<Self>,
9352 ) {
9353 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9354 s.move_cursors_with(|map, head, _| {
9355 (
9356 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
9357 SelectionGoal::None,
9358 )
9359 });
9360 })
9361 }
9362
9363 pub fn select_to_beginning_of_line(
9364 &mut self,
9365 action: &SelectToBeginningOfLine,
9366 window: &mut Window,
9367 cx: &mut Context<Self>,
9368 ) {
9369 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9370 s.move_heads_with(|map, head, _| {
9371 (
9372 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
9373 SelectionGoal::None,
9374 )
9375 });
9376 });
9377 }
9378
9379 pub fn delete_to_beginning_of_line(
9380 &mut self,
9381 _: &DeleteToBeginningOfLine,
9382 window: &mut Window,
9383 cx: &mut Context<Self>,
9384 ) {
9385 self.transact(window, cx, |this, window, cx| {
9386 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9387 s.move_with(|_, selection| {
9388 selection.reversed = true;
9389 });
9390 });
9391
9392 this.select_to_beginning_of_line(
9393 &SelectToBeginningOfLine {
9394 stop_at_soft_wraps: false,
9395 },
9396 window,
9397 cx,
9398 );
9399 this.backspace(&Backspace, window, cx);
9400 });
9401 }
9402
9403 pub fn move_to_end_of_line(
9404 &mut self,
9405 action: &MoveToEndOfLine,
9406 window: &mut Window,
9407 cx: &mut Context<Self>,
9408 ) {
9409 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9410 s.move_cursors_with(|map, head, _| {
9411 (
9412 movement::line_end(map, head, action.stop_at_soft_wraps),
9413 SelectionGoal::None,
9414 )
9415 });
9416 })
9417 }
9418
9419 pub fn select_to_end_of_line(
9420 &mut self,
9421 action: &SelectToEndOfLine,
9422 window: &mut Window,
9423 cx: &mut Context<Self>,
9424 ) {
9425 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9426 s.move_heads_with(|map, head, _| {
9427 (
9428 movement::line_end(map, head, action.stop_at_soft_wraps),
9429 SelectionGoal::None,
9430 )
9431 });
9432 })
9433 }
9434
9435 pub fn delete_to_end_of_line(
9436 &mut self,
9437 _: &DeleteToEndOfLine,
9438 window: &mut Window,
9439 cx: &mut Context<Self>,
9440 ) {
9441 self.transact(window, cx, |this, window, cx| {
9442 this.select_to_end_of_line(
9443 &SelectToEndOfLine {
9444 stop_at_soft_wraps: false,
9445 },
9446 window,
9447 cx,
9448 );
9449 this.delete(&Delete, window, cx);
9450 });
9451 }
9452
9453 pub fn cut_to_end_of_line(
9454 &mut self,
9455 _: &CutToEndOfLine,
9456 window: &mut Window,
9457 cx: &mut Context<Self>,
9458 ) {
9459 self.transact(window, cx, |this, window, cx| {
9460 this.select_to_end_of_line(
9461 &SelectToEndOfLine {
9462 stop_at_soft_wraps: false,
9463 },
9464 window,
9465 cx,
9466 );
9467 this.cut(&Cut, window, cx);
9468 });
9469 }
9470
9471 pub fn move_to_start_of_paragraph(
9472 &mut self,
9473 _: &MoveToStartOfParagraph,
9474 window: &mut Window,
9475 cx: &mut Context<Self>,
9476 ) {
9477 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9478 cx.propagate();
9479 return;
9480 }
9481
9482 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9483 s.move_with(|map, selection| {
9484 selection.collapse_to(
9485 movement::start_of_paragraph(map, selection.head(), 1),
9486 SelectionGoal::None,
9487 )
9488 });
9489 })
9490 }
9491
9492 pub fn move_to_end_of_paragraph(
9493 &mut self,
9494 _: &MoveToEndOfParagraph,
9495 window: &mut Window,
9496 cx: &mut Context<Self>,
9497 ) {
9498 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9499 cx.propagate();
9500 return;
9501 }
9502
9503 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9504 s.move_with(|map, selection| {
9505 selection.collapse_to(
9506 movement::end_of_paragraph(map, selection.head(), 1),
9507 SelectionGoal::None,
9508 )
9509 });
9510 })
9511 }
9512
9513 pub fn select_to_start_of_paragraph(
9514 &mut self,
9515 _: &SelectToStartOfParagraph,
9516 window: &mut Window,
9517 cx: &mut Context<Self>,
9518 ) {
9519 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9520 cx.propagate();
9521 return;
9522 }
9523
9524 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9525 s.move_heads_with(|map, head, _| {
9526 (
9527 movement::start_of_paragraph(map, head, 1),
9528 SelectionGoal::None,
9529 )
9530 });
9531 })
9532 }
9533
9534 pub fn select_to_end_of_paragraph(
9535 &mut self,
9536 _: &SelectToEndOfParagraph,
9537 window: &mut Window,
9538 cx: &mut Context<Self>,
9539 ) {
9540 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9541 cx.propagate();
9542 return;
9543 }
9544
9545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9546 s.move_heads_with(|map, head, _| {
9547 (
9548 movement::end_of_paragraph(map, head, 1),
9549 SelectionGoal::None,
9550 )
9551 });
9552 })
9553 }
9554
9555 pub fn move_to_start_of_excerpt(
9556 &mut self,
9557 _: &MoveToStartOfExcerpt,
9558 window: &mut Window,
9559 cx: &mut Context<Self>,
9560 ) {
9561 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9562 cx.propagate();
9563 return;
9564 }
9565
9566 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9567 s.move_with(|map, selection| {
9568 selection.collapse_to(
9569 movement::start_of_excerpt(
9570 map,
9571 selection.head(),
9572 workspace::searchable::Direction::Prev,
9573 ),
9574 SelectionGoal::None,
9575 )
9576 });
9577 })
9578 }
9579
9580 pub fn move_to_end_of_excerpt(
9581 &mut self,
9582 _: &MoveToEndOfExcerpt,
9583 window: &mut Window,
9584 cx: &mut Context<Self>,
9585 ) {
9586 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9587 cx.propagate();
9588 return;
9589 }
9590
9591 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9592 s.move_with(|map, selection| {
9593 selection.collapse_to(
9594 movement::end_of_excerpt(
9595 map,
9596 selection.head(),
9597 workspace::searchable::Direction::Next,
9598 ),
9599 SelectionGoal::None,
9600 )
9601 });
9602 })
9603 }
9604
9605 pub fn select_to_start_of_excerpt(
9606 &mut self,
9607 _: &SelectToStartOfExcerpt,
9608 window: &mut Window,
9609 cx: &mut Context<Self>,
9610 ) {
9611 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9612 cx.propagate();
9613 return;
9614 }
9615
9616 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9617 s.move_heads_with(|map, head, _| {
9618 (
9619 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9620 SelectionGoal::None,
9621 )
9622 });
9623 })
9624 }
9625
9626 pub fn select_to_end_of_excerpt(
9627 &mut self,
9628 _: &SelectToEndOfExcerpt,
9629 window: &mut Window,
9630 cx: &mut Context<Self>,
9631 ) {
9632 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9633 cx.propagate();
9634 return;
9635 }
9636
9637 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9638 s.move_heads_with(|map, head, _| {
9639 (
9640 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9641 SelectionGoal::None,
9642 )
9643 });
9644 })
9645 }
9646
9647 pub fn move_to_beginning(
9648 &mut self,
9649 _: &MoveToBeginning,
9650 window: &mut Window,
9651 cx: &mut Context<Self>,
9652 ) {
9653 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9654 cx.propagate();
9655 return;
9656 }
9657
9658 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9659 s.select_ranges(vec![0..0]);
9660 });
9661 }
9662
9663 pub fn select_to_beginning(
9664 &mut self,
9665 _: &SelectToBeginning,
9666 window: &mut Window,
9667 cx: &mut Context<Self>,
9668 ) {
9669 let mut selection = self.selections.last::<Point>(cx);
9670 selection.set_head(Point::zero(), SelectionGoal::None);
9671
9672 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9673 s.select(vec![selection]);
9674 });
9675 }
9676
9677 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9678 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9679 cx.propagate();
9680 return;
9681 }
9682
9683 let cursor = self.buffer.read(cx).read(cx).len();
9684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9685 s.select_ranges(vec![cursor..cursor])
9686 });
9687 }
9688
9689 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9690 self.nav_history = nav_history;
9691 }
9692
9693 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9694 self.nav_history.as_ref()
9695 }
9696
9697 fn push_to_nav_history(
9698 &mut self,
9699 cursor_anchor: Anchor,
9700 new_position: Option<Point>,
9701 cx: &mut Context<Self>,
9702 ) {
9703 if let Some(nav_history) = self.nav_history.as_mut() {
9704 let buffer = self.buffer.read(cx).read(cx);
9705 let cursor_position = cursor_anchor.to_point(&buffer);
9706 let scroll_state = self.scroll_manager.anchor();
9707 let scroll_top_row = scroll_state.top_row(&buffer);
9708 drop(buffer);
9709
9710 if let Some(new_position) = new_position {
9711 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9712 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9713 return;
9714 }
9715 }
9716
9717 nav_history.push(
9718 Some(NavigationData {
9719 cursor_anchor,
9720 cursor_position,
9721 scroll_anchor: scroll_state,
9722 scroll_top_row,
9723 }),
9724 cx,
9725 );
9726 }
9727 }
9728
9729 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9730 let buffer = self.buffer.read(cx).snapshot(cx);
9731 let mut selection = self.selections.first::<usize>(cx);
9732 selection.set_head(buffer.len(), SelectionGoal::None);
9733 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9734 s.select(vec![selection]);
9735 });
9736 }
9737
9738 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9739 let end = self.buffer.read(cx).read(cx).len();
9740 self.change_selections(None, window, cx, |s| {
9741 s.select_ranges(vec![0..end]);
9742 });
9743 }
9744
9745 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9747 let mut selections = self.selections.all::<Point>(cx);
9748 let max_point = display_map.buffer_snapshot.max_point();
9749 for selection in &mut selections {
9750 let rows = selection.spanned_rows(true, &display_map);
9751 selection.start = Point::new(rows.start.0, 0);
9752 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9753 selection.reversed = false;
9754 }
9755 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9756 s.select(selections);
9757 });
9758 }
9759
9760 pub fn split_selection_into_lines(
9761 &mut self,
9762 _: &SplitSelectionIntoLines,
9763 window: &mut Window,
9764 cx: &mut Context<Self>,
9765 ) {
9766 let selections = self
9767 .selections
9768 .all::<Point>(cx)
9769 .into_iter()
9770 .map(|selection| selection.start..selection.end)
9771 .collect::<Vec<_>>();
9772 self.unfold_ranges(&selections, true, true, cx);
9773
9774 let mut new_selection_ranges = Vec::new();
9775 {
9776 let buffer = self.buffer.read(cx).read(cx);
9777 for selection in selections {
9778 for row in selection.start.row..selection.end.row {
9779 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9780 new_selection_ranges.push(cursor..cursor);
9781 }
9782
9783 let is_multiline_selection = selection.start.row != selection.end.row;
9784 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9785 // so this action feels more ergonomic when paired with other selection operations
9786 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9787 if !should_skip_last {
9788 new_selection_ranges.push(selection.end..selection.end);
9789 }
9790 }
9791 }
9792 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9793 s.select_ranges(new_selection_ranges);
9794 });
9795 }
9796
9797 pub fn add_selection_above(
9798 &mut self,
9799 _: &AddSelectionAbove,
9800 window: &mut Window,
9801 cx: &mut Context<Self>,
9802 ) {
9803 self.add_selection(true, window, cx);
9804 }
9805
9806 pub fn add_selection_below(
9807 &mut self,
9808 _: &AddSelectionBelow,
9809 window: &mut Window,
9810 cx: &mut Context<Self>,
9811 ) {
9812 self.add_selection(false, window, cx);
9813 }
9814
9815 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9816 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9817 let mut selections = self.selections.all::<Point>(cx);
9818 let text_layout_details = self.text_layout_details(window);
9819 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9820 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9821 let range = oldest_selection.display_range(&display_map).sorted();
9822
9823 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9824 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9825 let positions = start_x.min(end_x)..start_x.max(end_x);
9826
9827 selections.clear();
9828 let mut stack = Vec::new();
9829 for row in range.start.row().0..=range.end.row().0 {
9830 if let Some(selection) = self.selections.build_columnar_selection(
9831 &display_map,
9832 DisplayRow(row),
9833 &positions,
9834 oldest_selection.reversed,
9835 &text_layout_details,
9836 ) {
9837 stack.push(selection.id);
9838 selections.push(selection);
9839 }
9840 }
9841
9842 if above {
9843 stack.reverse();
9844 }
9845
9846 AddSelectionsState { above, stack }
9847 });
9848
9849 let last_added_selection = *state.stack.last().unwrap();
9850 let mut new_selections = Vec::new();
9851 if above == state.above {
9852 let end_row = if above {
9853 DisplayRow(0)
9854 } else {
9855 display_map.max_point().row()
9856 };
9857
9858 'outer: for selection in selections {
9859 if selection.id == last_added_selection {
9860 let range = selection.display_range(&display_map).sorted();
9861 debug_assert_eq!(range.start.row(), range.end.row());
9862 let mut row = range.start.row();
9863 let positions =
9864 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9865 px(start)..px(end)
9866 } else {
9867 let start_x =
9868 display_map.x_for_display_point(range.start, &text_layout_details);
9869 let end_x =
9870 display_map.x_for_display_point(range.end, &text_layout_details);
9871 start_x.min(end_x)..start_x.max(end_x)
9872 };
9873
9874 while row != end_row {
9875 if above {
9876 row.0 -= 1;
9877 } else {
9878 row.0 += 1;
9879 }
9880
9881 if let Some(new_selection) = self.selections.build_columnar_selection(
9882 &display_map,
9883 row,
9884 &positions,
9885 selection.reversed,
9886 &text_layout_details,
9887 ) {
9888 state.stack.push(new_selection.id);
9889 if above {
9890 new_selections.push(new_selection);
9891 new_selections.push(selection);
9892 } else {
9893 new_selections.push(selection);
9894 new_selections.push(new_selection);
9895 }
9896
9897 continue 'outer;
9898 }
9899 }
9900 }
9901
9902 new_selections.push(selection);
9903 }
9904 } else {
9905 new_selections = selections;
9906 new_selections.retain(|s| s.id != last_added_selection);
9907 state.stack.pop();
9908 }
9909
9910 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9911 s.select(new_selections);
9912 });
9913 if state.stack.len() > 1 {
9914 self.add_selections_state = Some(state);
9915 }
9916 }
9917
9918 pub fn select_next_match_internal(
9919 &mut self,
9920 display_map: &DisplaySnapshot,
9921 replace_newest: bool,
9922 autoscroll: Option<Autoscroll>,
9923 window: &mut Window,
9924 cx: &mut Context<Self>,
9925 ) -> Result<()> {
9926 fn select_next_match_ranges(
9927 this: &mut Editor,
9928 range: Range<usize>,
9929 replace_newest: bool,
9930 auto_scroll: Option<Autoscroll>,
9931 window: &mut Window,
9932 cx: &mut Context<Editor>,
9933 ) {
9934 this.unfold_ranges(&[range.clone()], false, true, cx);
9935 this.change_selections(auto_scroll, window, cx, |s| {
9936 if replace_newest {
9937 s.delete(s.newest_anchor().id);
9938 }
9939 s.insert_range(range.clone());
9940 });
9941 }
9942
9943 let buffer = &display_map.buffer_snapshot;
9944 let mut selections = self.selections.all::<usize>(cx);
9945 if let Some(mut select_next_state) = self.select_next_state.take() {
9946 let query = &select_next_state.query;
9947 if !select_next_state.done {
9948 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9949 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9950 let mut next_selected_range = None;
9951
9952 let bytes_after_last_selection =
9953 buffer.bytes_in_range(last_selection.end..buffer.len());
9954 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9955 let query_matches = query
9956 .stream_find_iter(bytes_after_last_selection)
9957 .map(|result| (last_selection.end, result))
9958 .chain(
9959 query
9960 .stream_find_iter(bytes_before_first_selection)
9961 .map(|result| (0, result)),
9962 );
9963
9964 for (start_offset, query_match) in query_matches {
9965 let query_match = query_match.unwrap(); // can only fail due to I/O
9966 let offset_range =
9967 start_offset + query_match.start()..start_offset + query_match.end();
9968 let display_range = offset_range.start.to_display_point(display_map)
9969 ..offset_range.end.to_display_point(display_map);
9970
9971 if !select_next_state.wordwise
9972 || (!movement::is_inside_word(display_map, display_range.start)
9973 && !movement::is_inside_word(display_map, display_range.end))
9974 {
9975 // TODO: This is n^2, because we might check all the selections
9976 if !selections
9977 .iter()
9978 .any(|selection| selection.range().overlaps(&offset_range))
9979 {
9980 next_selected_range = Some(offset_range);
9981 break;
9982 }
9983 }
9984 }
9985
9986 if let Some(next_selected_range) = next_selected_range {
9987 select_next_match_ranges(
9988 self,
9989 next_selected_range,
9990 replace_newest,
9991 autoscroll,
9992 window,
9993 cx,
9994 );
9995 } else {
9996 select_next_state.done = true;
9997 }
9998 }
9999
10000 self.select_next_state = Some(select_next_state);
10001 } else {
10002 let mut only_carets = true;
10003 let mut same_text_selected = true;
10004 let mut selected_text = None;
10005
10006 let mut selections_iter = selections.iter().peekable();
10007 while let Some(selection) = selections_iter.next() {
10008 if selection.start != selection.end {
10009 only_carets = false;
10010 }
10011
10012 if same_text_selected {
10013 if selected_text.is_none() {
10014 selected_text =
10015 Some(buffer.text_for_range(selection.range()).collect::<String>());
10016 }
10017
10018 if let Some(next_selection) = selections_iter.peek() {
10019 if next_selection.range().len() == selection.range().len() {
10020 let next_selected_text = buffer
10021 .text_for_range(next_selection.range())
10022 .collect::<String>();
10023 if Some(next_selected_text) != selected_text {
10024 same_text_selected = false;
10025 selected_text = None;
10026 }
10027 } else {
10028 same_text_selected = false;
10029 selected_text = None;
10030 }
10031 }
10032 }
10033 }
10034
10035 if only_carets {
10036 for selection in &mut selections {
10037 let word_range = movement::surrounding_word(
10038 display_map,
10039 selection.start.to_display_point(display_map),
10040 );
10041 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10042 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10043 selection.goal = SelectionGoal::None;
10044 selection.reversed = false;
10045 select_next_match_ranges(
10046 self,
10047 selection.start..selection.end,
10048 replace_newest,
10049 autoscroll,
10050 window,
10051 cx,
10052 );
10053 }
10054
10055 if selections.len() == 1 {
10056 let selection = selections
10057 .last()
10058 .expect("ensured that there's only one selection");
10059 let query = buffer
10060 .text_for_range(selection.start..selection.end)
10061 .collect::<String>();
10062 let is_empty = query.is_empty();
10063 let select_state = SelectNextState {
10064 query: AhoCorasick::new(&[query])?,
10065 wordwise: true,
10066 done: is_empty,
10067 };
10068 self.select_next_state = Some(select_state);
10069 } else {
10070 self.select_next_state = None;
10071 }
10072 } else if let Some(selected_text) = selected_text {
10073 self.select_next_state = Some(SelectNextState {
10074 query: AhoCorasick::new(&[selected_text])?,
10075 wordwise: false,
10076 done: false,
10077 });
10078 self.select_next_match_internal(
10079 display_map,
10080 replace_newest,
10081 autoscroll,
10082 window,
10083 cx,
10084 )?;
10085 }
10086 }
10087 Ok(())
10088 }
10089
10090 pub fn select_all_matches(
10091 &mut self,
10092 _action: &SelectAllMatches,
10093 window: &mut Window,
10094 cx: &mut Context<Self>,
10095 ) -> Result<()> {
10096 self.push_to_selection_history();
10097 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10098
10099 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10100 let Some(select_next_state) = self.select_next_state.as_mut() else {
10101 return Ok(());
10102 };
10103 if select_next_state.done {
10104 return Ok(());
10105 }
10106
10107 let mut new_selections = self.selections.all::<usize>(cx);
10108
10109 let buffer = &display_map.buffer_snapshot;
10110 let query_matches = select_next_state
10111 .query
10112 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10113
10114 for query_match in query_matches {
10115 let query_match = query_match.unwrap(); // can only fail due to I/O
10116 let offset_range = query_match.start()..query_match.end();
10117 let display_range = offset_range.start.to_display_point(&display_map)
10118 ..offset_range.end.to_display_point(&display_map);
10119
10120 if !select_next_state.wordwise
10121 || (!movement::is_inside_word(&display_map, display_range.start)
10122 && !movement::is_inside_word(&display_map, display_range.end))
10123 {
10124 self.selections.change_with(cx, |selections| {
10125 new_selections.push(Selection {
10126 id: selections.new_selection_id(),
10127 start: offset_range.start,
10128 end: offset_range.end,
10129 reversed: false,
10130 goal: SelectionGoal::None,
10131 });
10132 });
10133 }
10134 }
10135
10136 new_selections.sort_by_key(|selection| selection.start);
10137 let mut ix = 0;
10138 while ix + 1 < new_selections.len() {
10139 let current_selection = &new_selections[ix];
10140 let next_selection = &new_selections[ix + 1];
10141 if current_selection.range().overlaps(&next_selection.range()) {
10142 if current_selection.id < next_selection.id {
10143 new_selections.remove(ix + 1);
10144 } else {
10145 new_selections.remove(ix);
10146 }
10147 } else {
10148 ix += 1;
10149 }
10150 }
10151
10152 let reversed = self.selections.oldest::<usize>(cx).reversed;
10153
10154 for selection in new_selections.iter_mut() {
10155 selection.reversed = reversed;
10156 }
10157
10158 select_next_state.done = true;
10159 self.unfold_ranges(
10160 &new_selections
10161 .iter()
10162 .map(|selection| selection.range())
10163 .collect::<Vec<_>>(),
10164 false,
10165 false,
10166 cx,
10167 );
10168 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10169 selections.select(new_selections)
10170 });
10171
10172 Ok(())
10173 }
10174
10175 pub fn select_next(
10176 &mut self,
10177 action: &SelectNext,
10178 window: &mut Window,
10179 cx: &mut Context<Self>,
10180 ) -> Result<()> {
10181 self.push_to_selection_history();
10182 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10183 self.select_next_match_internal(
10184 &display_map,
10185 action.replace_newest,
10186 Some(Autoscroll::newest()),
10187 window,
10188 cx,
10189 )?;
10190 Ok(())
10191 }
10192
10193 pub fn select_previous(
10194 &mut self,
10195 action: &SelectPrevious,
10196 window: &mut Window,
10197 cx: &mut Context<Self>,
10198 ) -> Result<()> {
10199 self.push_to_selection_history();
10200 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10201 let buffer = &display_map.buffer_snapshot;
10202 let mut selections = self.selections.all::<usize>(cx);
10203 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10204 let query = &select_prev_state.query;
10205 if !select_prev_state.done {
10206 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10207 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10208 let mut next_selected_range = None;
10209 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10210 let bytes_before_last_selection =
10211 buffer.reversed_bytes_in_range(0..last_selection.start);
10212 let bytes_after_first_selection =
10213 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10214 let query_matches = query
10215 .stream_find_iter(bytes_before_last_selection)
10216 .map(|result| (last_selection.start, result))
10217 .chain(
10218 query
10219 .stream_find_iter(bytes_after_first_selection)
10220 .map(|result| (buffer.len(), result)),
10221 );
10222 for (end_offset, query_match) in query_matches {
10223 let query_match = query_match.unwrap(); // can only fail due to I/O
10224 let offset_range =
10225 end_offset - query_match.end()..end_offset - query_match.start();
10226 let display_range = offset_range.start.to_display_point(&display_map)
10227 ..offset_range.end.to_display_point(&display_map);
10228
10229 if !select_prev_state.wordwise
10230 || (!movement::is_inside_word(&display_map, display_range.start)
10231 && !movement::is_inside_word(&display_map, display_range.end))
10232 {
10233 next_selected_range = Some(offset_range);
10234 break;
10235 }
10236 }
10237
10238 if let Some(next_selected_range) = next_selected_range {
10239 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10240 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10241 if action.replace_newest {
10242 s.delete(s.newest_anchor().id);
10243 }
10244 s.insert_range(next_selected_range);
10245 });
10246 } else {
10247 select_prev_state.done = true;
10248 }
10249 }
10250
10251 self.select_prev_state = Some(select_prev_state);
10252 } else {
10253 let mut only_carets = true;
10254 let mut same_text_selected = true;
10255 let mut selected_text = None;
10256
10257 let mut selections_iter = selections.iter().peekable();
10258 while let Some(selection) = selections_iter.next() {
10259 if selection.start != selection.end {
10260 only_carets = false;
10261 }
10262
10263 if same_text_selected {
10264 if selected_text.is_none() {
10265 selected_text =
10266 Some(buffer.text_for_range(selection.range()).collect::<String>());
10267 }
10268
10269 if let Some(next_selection) = selections_iter.peek() {
10270 if next_selection.range().len() == selection.range().len() {
10271 let next_selected_text = buffer
10272 .text_for_range(next_selection.range())
10273 .collect::<String>();
10274 if Some(next_selected_text) != selected_text {
10275 same_text_selected = false;
10276 selected_text = None;
10277 }
10278 } else {
10279 same_text_selected = false;
10280 selected_text = None;
10281 }
10282 }
10283 }
10284 }
10285
10286 if only_carets {
10287 for selection in &mut selections {
10288 let word_range = movement::surrounding_word(
10289 &display_map,
10290 selection.start.to_display_point(&display_map),
10291 );
10292 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10293 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10294 selection.goal = SelectionGoal::None;
10295 selection.reversed = false;
10296 }
10297 if selections.len() == 1 {
10298 let selection = selections
10299 .last()
10300 .expect("ensured that there's only one selection");
10301 let query = buffer
10302 .text_for_range(selection.start..selection.end)
10303 .collect::<String>();
10304 let is_empty = query.is_empty();
10305 let select_state = SelectNextState {
10306 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10307 wordwise: true,
10308 done: is_empty,
10309 };
10310 self.select_prev_state = Some(select_state);
10311 } else {
10312 self.select_prev_state = None;
10313 }
10314
10315 self.unfold_ranges(
10316 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10317 false,
10318 true,
10319 cx,
10320 );
10321 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10322 s.select(selections);
10323 });
10324 } else if let Some(selected_text) = selected_text {
10325 self.select_prev_state = Some(SelectNextState {
10326 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10327 wordwise: false,
10328 done: false,
10329 });
10330 self.select_previous(action, window, cx)?;
10331 }
10332 }
10333 Ok(())
10334 }
10335
10336 pub fn toggle_comments(
10337 &mut self,
10338 action: &ToggleComments,
10339 window: &mut Window,
10340 cx: &mut Context<Self>,
10341 ) {
10342 if self.read_only(cx) {
10343 return;
10344 }
10345 let text_layout_details = &self.text_layout_details(window);
10346 self.transact(window, cx, |this, window, cx| {
10347 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10348 let mut edits = Vec::new();
10349 let mut selection_edit_ranges = Vec::new();
10350 let mut last_toggled_row = None;
10351 let snapshot = this.buffer.read(cx).read(cx);
10352 let empty_str: Arc<str> = Arc::default();
10353 let mut suffixes_inserted = Vec::new();
10354 let ignore_indent = action.ignore_indent;
10355
10356 fn comment_prefix_range(
10357 snapshot: &MultiBufferSnapshot,
10358 row: MultiBufferRow,
10359 comment_prefix: &str,
10360 comment_prefix_whitespace: &str,
10361 ignore_indent: bool,
10362 ) -> Range<Point> {
10363 let indent_size = if ignore_indent {
10364 0
10365 } else {
10366 snapshot.indent_size_for_line(row).len
10367 };
10368
10369 let start = Point::new(row.0, indent_size);
10370
10371 let mut line_bytes = snapshot
10372 .bytes_in_range(start..snapshot.max_point())
10373 .flatten()
10374 .copied();
10375
10376 // If this line currently begins with the line comment prefix, then record
10377 // the range containing the prefix.
10378 if line_bytes
10379 .by_ref()
10380 .take(comment_prefix.len())
10381 .eq(comment_prefix.bytes())
10382 {
10383 // Include any whitespace that matches the comment prefix.
10384 let matching_whitespace_len = line_bytes
10385 .zip(comment_prefix_whitespace.bytes())
10386 .take_while(|(a, b)| a == b)
10387 .count() as u32;
10388 let end = Point::new(
10389 start.row,
10390 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10391 );
10392 start..end
10393 } else {
10394 start..start
10395 }
10396 }
10397
10398 fn comment_suffix_range(
10399 snapshot: &MultiBufferSnapshot,
10400 row: MultiBufferRow,
10401 comment_suffix: &str,
10402 comment_suffix_has_leading_space: bool,
10403 ) -> Range<Point> {
10404 let end = Point::new(row.0, snapshot.line_len(row));
10405 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10406
10407 let mut line_end_bytes = snapshot
10408 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10409 .flatten()
10410 .copied();
10411
10412 let leading_space_len = if suffix_start_column > 0
10413 && line_end_bytes.next() == Some(b' ')
10414 && comment_suffix_has_leading_space
10415 {
10416 1
10417 } else {
10418 0
10419 };
10420
10421 // If this line currently begins with the line comment prefix, then record
10422 // the range containing the prefix.
10423 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10424 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10425 start..end
10426 } else {
10427 end..end
10428 }
10429 }
10430
10431 // TODO: Handle selections that cross excerpts
10432 for selection in &mut selections {
10433 let start_column = snapshot
10434 .indent_size_for_line(MultiBufferRow(selection.start.row))
10435 .len;
10436 let language = if let Some(language) =
10437 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10438 {
10439 language
10440 } else {
10441 continue;
10442 };
10443
10444 selection_edit_ranges.clear();
10445
10446 // If multiple selections contain a given row, avoid processing that
10447 // row more than once.
10448 let mut start_row = MultiBufferRow(selection.start.row);
10449 if last_toggled_row == Some(start_row) {
10450 start_row = start_row.next_row();
10451 }
10452 let end_row =
10453 if selection.end.row > selection.start.row && selection.end.column == 0 {
10454 MultiBufferRow(selection.end.row - 1)
10455 } else {
10456 MultiBufferRow(selection.end.row)
10457 };
10458 last_toggled_row = Some(end_row);
10459
10460 if start_row > end_row {
10461 continue;
10462 }
10463
10464 // If the language has line comments, toggle those.
10465 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10466
10467 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10468 if ignore_indent {
10469 full_comment_prefixes = full_comment_prefixes
10470 .into_iter()
10471 .map(|s| Arc::from(s.trim_end()))
10472 .collect();
10473 }
10474
10475 if !full_comment_prefixes.is_empty() {
10476 let first_prefix = full_comment_prefixes
10477 .first()
10478 .expect("prefixes is non-empty");
10479 let prefix_trimmed_lengths = full_comment_prefixes
10480 .iter()
10481 .map(|p| p.trim_end_matches(' ').len())
10482 .collect::<SmallVec<[usize; 4]>>();
10483
10484 let mut all_selection_lines_are_comments = true;
10485
10486 for row in start_row.0..=end_row.0 {
10487 let row = MultiBufferRow(row);
10488 if start_row < end_row && snapshot.is_line_blank(row) {
10489 continue;
10490 }
10491
10492 let prefix_range = full_comment_prefixes
10493 .iter()
10494 .zip(prefix_trimmed_lengths.iter().copied())
10495 .map(|(prefix, trimmed_prefix_len)| {
10496 comment_prefix_range(
10497 snapshot.deref(),
10498 row,
10499 &prefix[..trimmed_prefix_len],
10500 &prefix[trimmed_prefix_len..],
10501 ignore_indent,
10502 )
10503 })
10504 .max_by_key(|range| range.end.column - range.start.column)
10505 .expect("prefixes is non-empty");
10506
10507 if prefix_range.is_empty() {
10508 all_selection_lines_are_comments = false;
10509 }
10510
10511 selection_edit_ranges.push(prefix_range);
10512 }
10513
10514 if all_selection_lines_are_comments {
10515 edits.extend(
10516 selection_edit_ranges
10517 .iter()
10518 .cloned()
10519 .map(|range| (range, empty_str.clone())),
10520 );
10521 } else {
10522 let min_column = selection_edit_ranges
10523 .iter()
10524 .map(|range| range.start.column)
10525 .min()
10526 .unwrap_or(0);
10527 edits.extend(selection_edit_ranges.iter().map(|range| {
10528 let position = Point::new(range.start.row, min_column);
10529 (position..position, first_prefix.clone())
10530 }));
10531 }
10532 } else if let Some((full_comment_prefix, comment_suffix)) =
10533 language.block_comment_delimiters()
10534 {
10535 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10536 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10537 let prefix_range = comment_prefix_range(
10538 snapshot.deref(),
10539 start_row,
10540 comment_prefix,
10541 comment_prefix_whitespace,
10542 ignore_indent,
10543 );
10544 let suffix_range = comment_suffix_range(
10545 snapshot.deref(),
10546 end_row,
10547 comment_suffix.trim_start_matches(' '),
10548 comment_suffix.starts_with(' '),
10549 );
10550
10551 if prefix_range.is_empty() || suffix_range.is_empty() {
10552 edits.push((
10553 prefix_range.start..prefix_range.start,
10554 full_comment_prefix.clone(),
10555 ));
10556 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10557 suffixes_inserted.push((end_row, comment_suffix.len()));
10558 } else {
10559 edits.push((prefix_range, empty_str.clone()));
10560 edits.push((suffix_range, empty_str.clone()));
10561 }
10562 } else {
10563 continue;
10564 }
10565 }
10566
10567 drop(snapshot);
10568 this.buffer.update(cx, |buffer, cx| {
10569 buffer.edit(edits, None, cx);
10570 });
10571
10572 // Adjust selections so that they end before any comment suffixes that
10573 // were inserted.
10574 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10575 let mut selections = this.selections.all::<Point>(cx);
10576 let snapshot = this.buffer.read(cx).read(cx);
10577 for selection in &mut selections {
10578 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10579 match row.cmp(&MultiBufferRow(selection.end.row)) {
10580 Ordering::Less => {
10581 suffixes_inserted.next();
10582 continue;
10583 }
10584 Ordering::Greater => break,
10585 Ordering::Equal => {
10586 if selection.end.column == snapshot.line_len(row) {
10587 if selection.is_empty() {
10588 selection.start.column -= suffix_len as u32;
10589 }
10590 selection.end.column -= suffix_len as u32;
10591 }
10592 break;
10593 }
10594 }
10595 }
10596 }
10597
10598 drop(snapshot);
10599 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10600 s.select(selections)
10601 });
10602
10603 let selections = this.selections.all::<Point>(cx);
10604 let selections_on_single_row = selections.windows(2).all(|selections| {
10605 selections[0].start.row == selections[1].start.row
10606 && selections[0].end.row == selections[1].end.row
10607 && selections[0].start.row == selections[0].end.row
10608 });
10609 let selections_selecting = selections
10610 .iter()
10611 .any(|selection| selection.start != selection.end);
10612 let advance_downwards = action.advance_downwards
10613 && selections_on_single_row
10614 && !selections_selecting
10615 && !matches!(this.mode, EditorMode::SingleLine { .. });
10616
10617 if advance_downwards {
10618 let snapshot = this.buffer.read(cx).snapshot(cx);
10619
10620 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10621 s.move_cursors_with(|display_snapshot, display_point, _| {
10622 let mut point = display_point.to_point(display_snapshot);
10623 point.row += 1;
10624 point = snapshot.clip_point(point, Bias::Left);
10625 let display_point = point.to_display_point(display_snapshot);
10626 let goal = SelectionGoal::HorizontalPosition(
10627 display_snapshot
10628 .x_for_display_point(display_point, text_layout_details)
10629 .into(),
10630 );
10631 (display_point, goal)
10632 })
10633 });
10634 }
10635 });
10636 }
10637
10638 pub fn select_enclosing_symbol(
10639 &mut self,
10640 _: &SelectEnclosingSymbol,
10641 window: &mut Window,
10642 cx: &mut Context<Self>,
10643 ) {
10644 let buffer = self.buffer.read(cx).snapshot(cx);
10645 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10646
10647 fn update_selection(
10648 selection: &Selection<usize>,
10649 buffer_snap: &MultiBufferSnapshot,
10650 ) -> Option<Selection<usize>> {
10651 let cursor = selection.head();
10652 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10653 for symbol in symbols.iter().rev() {
10654 let start = symbol.range.start.to_offset(buffer_snap);
10655 let end = symbol.range.end.to_offset(buffer_snap);
10656 let new_range = start..end;
10657 if start < selection.start || end > selection.end {
10658 return Some(Selection {
10659 id: selection.id,
10660 start: new_range.start,
10661 end: new_range.end,
10662 goal: SelectionGoal::None,
10663 reversed: selection.reversed,
10664 });
10665 }
10666 }
10667 None
10668 }
10669
10670 let mut selected_larger_symbol = false;
10671 let new_selections = old_selections
10672 .iter()
10673 .map(|selection| match update_selection(selection, &buffer) {
10674 Some(new_selection) => {
10675 if new_selection.range() != selection.range() {
10676 selected_larger_symbol = true;
10677 }
10678 new_selection
10679 }
10680 None => selection.clone(),
10681 })
10682 .collect::<Vec<_>>();
10683
10684 if selected_larger_symbol {
10685 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686 s.select(new_selections);
10687 });
10688 }
10689 }
10690
10691 pub fn select_larger_syntax_node(
10692 &mut self,
10693 _: &SelectLargerSyntaxNode,
10694 window: &mut Window,
10695 cx: &mut Context<Self>,
10696 ) {
10697 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10698 let buffer = self.buffer.read(cx).snapshot(cx);
10699 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10700
10701 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10702 let mut selected_larger_node = false;
10703 let new_selections = old_selections
10704 .iter()
10705 .map(|selection| {
10706 let old_range = selection.start..selection.end;
10707 let mut new_range = old_range.clone();
10708 let mut new_node = None;
10709 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10710 {
10711 new_node = Some(node);
10712 new_range = containing_range;
10713 if !display_map.intersects_fold(new_range.start)
10714 && !display_map.intersects_fold(new_range.end)
10715 {
10716 break;
10717 }
10718 }
10719
10720 if let Some(node) = new_node {
10721 // Log the ancestor, to support using this action as a way to explore TreeSitter
10722 // nodes. Parent and grandparent are also logged because this operation will not
10723 // visit nodes that have the same range as their parent.
10724 log::info!("Node: {node:?}");
10725 let parent = node.parent();
10726 log::info!("Parent: {parent:?}");
10727 let grandparent = parent.and_then(|x| x.parent());
10728 log::info!("Grandparent: {grandparent:?}");
10729 }
10730
10731 selected_larger_node |= new_range != old_range;
10732 Selection {
10733 id: selection.id,
10734 start: new_range.start,
10735 end: new_range.end,
10736 goal: SelectionGoal::None,
10737 reversed: selection.reversed,
10738 }
10739 })
10740 .collect::<Vec<_>>();
10741
10742 if selected_larger_node {
10743 stack.push(old_selections);
10744 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10745 s.select(new_selections);
10746 });
10747 }
10748 self.select_larger_syntax_node_stack = stack;
10749 }
10750
10751 pub fn select_smaller_syntax_node(
10752 &mut self,
10753 _: &SelectSmallerSyntaxNode,
10754 window: &mut Window,
10755 cx: &mut Context<Self>,
10756 ) {
10757 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10758 if let Some(selections) = stack.pop() {
10759 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10760 s.select(selections.to_vec());
10761 });
10762 }
10763 self.select_larger_syntax_node_stack = stack;
10764 }
10765
10766 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10767 if !EditorSettings::get_global(cx).gutter.runnables {
10768 self.clear_tasks();
10769 return Task::ready(());
10770 }
10771 let project = self.project.as_ref().map(Entity::downgrade);
10772 cx.spawn_in(window, |this, mut cx| async move {
10773 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10774 let Some(project) = project.and_then(|p| p.upgrade()) else {
10775 return;
10776 };
10777 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10778 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10779 }) else {
10780 return;
10781 };
10782
10783 let hide_runnables = project
10784 .update(&mut cx, |project, cx| {
10785 // Do not display any test indicators in non-dev server remote projects.
10786 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10787 })
10788 .unwrap_or(true);
10789 if hide_runnables {
10790 return;
10791 }
10792 let new_rows =
10793 cx.background_spawn({
10794 let snapshot = display_snapshot.clone();
10795 async move {
10796 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10797 }
10798 })
10799 .await;
10800
10801 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10802 this.update(&mut cx, |this, _| {
10803 this.clear_tasks();
10804 for (key, value) in rows {
10805 this.insert_tasks(key, value);
10806 }
10807 })
10808 .ok();
10809 })
10810 }
10811 fn fetch_runnable_ranges(
10812 snapshot: &DisplaySnapshot,
10813 range: Range<Anchor>,
10814 ) -> Vec<language::RunnableRange> {
10815 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10816 }
10817
10818 fn runnable_rows(
10819 project: Entity<Project>,
10820 snapshot: DisplaySnapshot,
10821 runnable_ranges: Vec<RunnableRange>,
10822 mut cx: AsyncWindowContext,
10823 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10824 runnable_ranges
10825 .into_iter()
10826 .filter_map(|mut runnable| {
10827 let tasks = cx
10828 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10829 .ok()?;
10830 if tasks.is_empty() {
10831 return None;
10832 }
10833
10834 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10835
10836 let row = snapshot
10837 .buffer_snapshot
10838 .buffer_line_for_row(MultiBufferRow(point.row))?
10839 .1
10840 .start
10841 .row;
10842
10843 let context_range =
10844 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10845 Some((
10846 (runnable.buffer_id, row),
10847 RunnableTasks {
10848 templates: tasks,
10849 offset: snapshot
10850 .buffer_snapshot
10851 .anchor_before(runnable.run_range.start),
10852 context_range,
10853 column: point.column,
10854 extra_variables: runnable.extra_captures,
10855 },
10856 ))
10857 })
10858 .collect()
10859 }
10860
10861 fn templates_with_tags(
10862 project: &Entity<Project>,
10863 runnable: &mut Runnable,
10864 cx: &mut App,
10865 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10866 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10867 let (worktree_id, file) = project
10868 .buffer_for_id(runnable.buffer, cx)
10869 .and_then(|buffer| buffer.read(cx).file())
10870 .map(|file| (file.worktree_id(cx), file.clone()))
10871 .unzip();
10872
10873 (
10874 project.task_store().read(cx).task_inventory().cloned(),
10875 worktree_id,
10876 file,
10877 )
10878 });
10879
10880 let tags = mem::take(&mut runnable.tags);
10881 let mut tags: Vec<_> = tags
10882 .into_iter()
10883 .flat_map(|tag| {
10884 let tag = tag.0.clone();
10885 inventory
10886 .as_ref()
10887 .into_iter()
10888 .flat_map(|inventory| {
10889 inventory.read(cx).list_tasks(
10890 file.clone(),
10891 Some(runnable.language.clone()),
10892 worktree_id,
10893 cx,
10894 )
10895 })
10896 .filter(move |(_, template)| {
10897 template.tags.iter().any(|source_tag| source_tag == &tag)
10898 })
10899 })
10900 .sorted_by_key(|(kind, _)| kind.to_owned())
10901 .collect();
10902 if let Some((leading_tag_source, _)) = tags.first() {
10903 // Strongest source wins; if we have worktree tag binding, prefer that to
10904 // global and language bindings;
10905 // if we have a global binding, prefer that to language binding.
10906 let first_mismatch = tags
10907 .iter()
10908 .position(|(tag_source, _)| tag_source != leading_tag_source);
10909 if let Some(index) = first_mismatch {
10910 tags.truncate(index);
10911 }
10912 }
10913
10914 tags
10915 }
10916
10917 pub fn move_to_enclosing_bracket(
10918 &mut self,
10919 _: &MoveToEnclosingBracket,
10920 window: &mut Window,
10921 cx: &mut Context<Self>,
10922 ) {
10923 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10924 s.move_offsets_with(|snapshot, selection| {
10925 let Some(enclosing_bracket_ranges) =
10926 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10927 else {
10928 return;
10929 };
10930
10931 let mut best_length = usize::MAX;
10932 let mut best_inside = false;
10933 let mut best_in_bracket_range = false;
10934 let mut best_destination = None;
10935 for (open, close) in enclosing_bracket_ranges {
10936 let close = close.to_inclusive();
10937 let length = close.end() - open.start;
10938 let inside = selection.start >= open.end && selection.end <= *close.start();
10939 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10940 || close.contains(&selection.head());
10941
10942 // If best is next to a bracket and current isn't, skip
10943 if !in_bracket_range && best_in_bracket_range {
10944 continue;
10945 }
10946
10947 // Prefer smaller lengths unless best is inside and current isn't
10948 if length > best_length && (best_inside || !inside) {
10949 continue;
10950 }
10951
10952 best_length = length;
10953 best_inside = inside;
10954 best_in_bracket_range = in_bracket_range;
10955 best_destination = Some(
10956 if close.contains(&selection.start) && close.contains(&selection.end) {
10957 if inside {
10958 open.end
10959 } else {
10960 open.start
10961 }
10962 } else if inside {
10963 *close.start()
10964 } else {
10965 *close.end()
10966 },
10967 );
10968 }
10969
10970 if let Some(destination) = best_destination {
10971 selection.collapse_to(destination, SelectionGoal::None);
10972 }
10973 })
10974 });
10975 }
10976
10977 pub fn undo_selection(
10978 &mut self,
10979 _: &UndoSelection,
10980 window: &mut Window,
10981 cx: &mut Context<Self>,
10982 ) {
10983 self.end_selection(window, cx);
10984 self.selection_history.mode = SelectionHistoryMode::Undoing;
10985 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10986 self.change_selections(None, window, cx, |s| {
10987 s.select_anchors(entry.selections.to_vec())
10988 });
10989 self.select_next_state = entry.select_next_state;
10990 self.select_prev_state = entry.select_prev_state;
10991 self.add_selections_state = entry.add_selections_state;
10992 self.request_autoscroll(Autoscroll::newest(), cx);
10993 }
10994 self.selection_history.mode = SelectionHistoryMode::Normal;
10995 }
10996
10997 pub fn redo_selection(
10998 &mut self,
10999 _: &RedoSelection,
11000 window: &mut Window,
11001 cx: &mut Context<Self>,
11002 ) {
11003 self.end_selection(window, cx);
11004 self.selection_history.mode = SelectionHistoryMode::Redoing;
11005 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11006 self.change_selections(None, window, cx, |s| {
11007 s.select_anchors(entry.selections.to_vec())
11008 });
11009 self.select_next_state = entry.select_next_state;
11010 self.select_prev_state = entry.select_prev_state;
11011 self.add_selections_state = entry.add_selections_state;
11012 self.request_autoscroll(Autoscroll::newest(), cx);
11013 }
11014 self.selection_history.mode = SelectionHistoryMode::Normal;
11015 }
11016
11017 pub fn expand_excerpts(
11018 &mut self,
11019 action: &ExpandExcerpts,
11020 _: &mut Window,
11021 cx: &mut Context<Self>,
11022 ) {
11023 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11024 }
11025
11026 pub fn expand_excerpts_down(
11027 &mut self,
11028 action: &ExpandExcerptsDown,
11029 _: &mut Window,
11030 cx: &mut Context<Self>,
11031 ) {
11032 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11033 }
11034
11035 pub fn expand_excerpts_up(
11036 &mut self,
11037 action: &ExpandExcerptsUp,
11038 _: &mut Window,
11039 cx: &mut Context<Self>,
11040 ) {
11041 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11042 }
11043
11044 pub fn expand_excerpts_for_direction(
11045 &mut self,
11046 lines: u32,
11047 direction: ExpandExcerptDirection,
11048
11049 cx: &mut Context<Self>,
11050 ) {
11051 let selections = self.selections.disjoint_anchors();
11052
11053 let lines = if lines == 0 {
11054 EditorSettings::get_global(cx).expand_excerpt_lines
11055 } else {
11056 lines
11057 };
11058
11059 self.buffer.update(cx, |buffer, cx| {
11060 let snapshot = buffer.snapshot(cx);
11061 let mut excerpt_ids = selections
11062 .iter()
11063 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11064 .collect::<Vec<_>>();
11065 excerpt_ids.sort();
11066 excerpt_ids.dedup();
11067 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11068 })
11069 }
11070
11071 pub fn expand_excerpt(
11072 &mut self,
11073 excerpt: ExcerptId,
11074 direction: ExpandExcerptDirection,
11075 cx: &mut Context<Self>,
11076 ) {
11077 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11078 self.buffer.update(cx, |buffer, cx| {
11079 buffer.expand_excerpts([excerpt], lines, direction, cx)
11080 })
11081 }
11082
11083 pub fn go_to_singleton_buffer_point(
11084 &mut self,
11085 point: Point,
11086 window: &mut Window,
11087 cx: &mut Context<Self>,
11088 ) {
11089 self.go_to_singleton_buffer_range(point..point, window, cx);
11090 }
11091
11092 pub fn go_to_singleton_buffer_range(
11093 &mut self,
11094 range: Range<Point>,
11095 window: &mut Window,
11096 cx: &mut Context<Self>,
11097 ) {
11098 let multibuffer = self.buffer().read(cx);
11099 let Some(buffer) = multibuffer.as_singleton() else {
11100 return;
11101 };
11102 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11103 return;
11104 };
11105 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11106 return;
11107 };
11108 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11109 s.select_anchor_ranges([start..end])
11110 });
11111 }
11112
11113 fn go_to_diagnostic(
11114 &mut self,
11115 _: &GoToDiagnostic,
11116 window: &mut Window,
11117 cx: &mut Context<Self>,
11118 ) {
11119 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11120 }
11121
11122 fn go_to_prev_diagnostic(
11123 &mut self,
11124 _: &GoToPrevDiagnostic,
11125 window: &mut Window,
11126 cx: &mut Context<Self>,
11127 ) {
11128 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11129 }
11130
11131 pub fn go_to_diagnostic_impl(
11132 &mut self,
11133 direction: Direction,
11134 window: &mut Window,
11135 cx: &mut Context<Self>,
11136 ) {
11137 let buffer = self.buffer.read(cx).snapshot(cx);
11138 let selection = self.selections.newest::<usize>(cx);
11139
11140 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11141 if direction == Direction::Next {
11142 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11143 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11144 return;
11145 };
11146 self.activate_diagnostics(
11147 buffer_id,
11148 popover.local_diagnostic.diagnostic.group_id,
11149 window,
11150 cx,
11151 );
11152 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11153 let primary_range_start = active_diagnostics.primary_range.start;
11154 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11155 let mut new_selection = s.newest_anchor().clone();
11156 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11157 s.select_anchors(vec![new_selection.clone()]);
11158 });
11159 self.refresh_inline_completion(false, true, window, cx);
11160 }
11161 return;
11162 }
11163 }
11164
11165 let active_group_id = self
11166 .active_diagnostics
11167 .as_ref()
11168 .map(|active_group| active_group.group_id);
11169 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11170 active_diagnostics
11171 .primary_range
11172 .to_offset(&buffer)
11173 .to_inclusive()
11174 });
11175 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11176 if active_primary_range.contains(&selection.head()) {
11177 *active_primary_range.start()
11178 } else {
11179 selection.head()
11180 }
11181 } else {
11182 selection.head()
11183 };
11184
11185 let snapshot = self.snapshot(window, cx);
11186 let primary_diagnostics_before = buffer
11187 .diagnostics_in_range::<usize>(0..search_start)
11188 .filter(|entry| entry.diagnostic.is_primary)
11189 .filter(|entry| entry.range.start != entry.range.end)
11190 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11191 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11192 .collect::<Vec<_>>();
11193 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11194 primary_diagnostics_before
11195 .iter()
11196 .position(|entry| entry.diagnostic.group_id == active_group_id)
11197 });
11198
11199 let primary_diagnostics_after = buffer
11200 .diagnostics_in_range::<usize>(search_start..buffer.len())
11201 .filter(|entry| entry.diagnostic.is_primary)
11202 .filter(|entry| entry.range.start != entry.range.end)
11203 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11204 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11205 .collect::<Vec<_>>();
11206 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11207 primary_diagnostics_after
11208 .iter()
11209 .enumerate()
11210 .rev()
11211 .find_map(|(i, entry)| {
11212 if entry.diagnostic.group_id == active_group_id {
11213 Some(i)
11214 } else {
11215 None
11216 }
11217 })
11218 });
11219
11220 let next_primary_diagnostic = match direction {
11221 Direction::Prev => primary_diagnostics_before
11222 .iter()
11223 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11224 .rev()
11225 .next(),
11226 Direction::Next => primary_diagnostics_after
11227 .iter()
11228 .skip(
11229 last_same_group_diagnostic_after
11230 .map(|index| index + 1)
11231 .unwrap_or(0),
11232 )
11233 .next(),
11234 };
11235
11236 // Cycle around to the start of the buffer, potentially moving back to the start of
11237 // the currently active diagnostic.
11238 let cycle_around = || match direction {
11239 Direction::Prev => primary_diagnostics_after
11240 .iter()
11241 .rev()
11242 .chain(primary_diagnostics_before.iter().rev())
11243 .next(),
11244 Direction::Next => primary_diagnostics_before
11245 .iter()
11246 .chain(primary_diagnostics_after.iter())
11247 .next(),
11248 };
11249
11250 if let Some((primary_range, group_id)) = next_primary_diagnostic
11251 .or_else(cycle_around)
11252 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11253 {
11254 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11255 return;
11256 };
11257 self.activate_diagnostics(buffer_id, group_id, window, cx);
11258 if self.active_diagnostics.is_some() {
11259 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11260 s.select(vec![Selection {
11261 id: selection.id,
11262 start: primary_range.start,
11263 end: primary_range.start,
11264 reversed: false,
11265 goal: SelectionGoal::None,
11266 }]);
11267 });
11268 self.refresh_inline_completion(false, true, window, cx);
11269 }
11270 }
11271 }
11272
11273 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11274 let snapshot = self.snapshot(window, cx);
11275 let selection = self.selections.newest::<Point>(cx);
11276 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11277 }
11278
11279 fn go_to_hunk_after_position(
11280 &mut self,
11281 snapshot: &EditorSnapshot,
11282 position: Point,
11283 window: &mut Window,
11284 cx: &mut Context<Editor>,
11285 ) -> Option<MultiBufferDiffHunk> {
11286 let mut hunk = snapshot
11287 .buffer_snapshot
11288 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11289 .find(|hunk| hunk.row_range.start.0 > position.row);
11290 if hunk.is_none() {
11291 hunk = snapshot
11292 .buffer_snapshot
11293 .diff_hunks_in_range(Point::zero()..position)
11294 .find(|hunk| hunk.row_range.end.0 < position.row)
11295 }
11296 if let Some(hunk) = &hunk {
11297 let destination = Point::new(hunk.row_range.start.0, 0);
11298 self.unfold_ranges(&[destination..destination], false, false, cx);
11299 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11300 s.select_ranges(vec![destination..destination]);
11301 });
11302 }
11303
11304 hunk
11305 }
11306
11307 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11308 let snapshot = self.snapshot(window, cx);
11309 let selection = self.selections.newest::<Point>(cx);
11310 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11311 }
11312
11313 fn go_to_hunk_before_position(
11314 &mut self,
11315 snapshot: &EditorSnapshot,
11316 position: Point,
11317 window: &mut Window,
11318 cx: &mut Context<Editor>,
11319 ) -> Option<MultiBufferDiffHunk> {
11320 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11321 if hunk.is_none() {
11322 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11323 }
11324 if let Some(hunk) = &hunk {
11325 let destination = Point::new(hunk.row_range.start.0, 0);
11326 self.unfold_ranges(&[destination..destination], false, false, cx);
11327 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11328 s.select_ranges(vec![destination..destination]);
11329 });
11330 }
11331
11332 hunk
11333 }
11334
11335 pub fn go_to_definition(
11336 &mut self,
11337 _: &GoToDefinition,
11338 window: &mut Window,
11339 cx: &mut Context<Self>,
11340 ) -> Task<Result<Navigated>> {
11341 let definition =
11342 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11343 cx.spawn_in(window, |editor, mut cx| async move {
11344 if definition.await? == Navigated::Yes {
11345 return Ok(Navigated::Yes);
11346 }
11347 match editor.update_in(&mut cx, |editor, window, cx| {
11348 editor.find_all_references(&FindAllReferences, window, cx)
11349 })? {
11350 Some(references) => references.await,
11351 None => Ok(Navigated::No),
11352 }
11353 })
11354 }
11355
11356 pub fn go_to_declaration(
11357 &mut self,
11358 _: &GoToDeclaration,
11359 window: &mut Window,
11360 cx: &mut Context<Self>,
11361 ) -> Task<Result<Navigated>> {
11362 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11363 }
11364
11365 pub fn go_to_declaration_split(
11366 &mut self,
11367 _: &GoToDeclaration,
11368 window: &mut Window,
11369 cx: &mut Context<Self>,
11370 ) -> Task<Result<Navigated>> {
11371 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11372 }
11373
11374 pub fn go_to_implementation(
11375 &mut self,
11376 _: &GoToImplementation,
11377 window: &mut Window,
11378 cx: &mut Context<Self>,
11379 ) -> Task<Result<Navigated>> {
11380 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11381 }
11382
11383 pub fn go_to_implementation_split(
11384 &mut self,
11385 _: &GoToImplementationSplit,
11386 window: &mut Window,
11387 cx: &mut Context<Self>,
11388 ) -> Task<Result<Navigated>> {
11389 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11390 }
11391
11392 pub fn go_to_type_definition(
11393 &mut self,
11394 _: &GoToTypeDefinition,
11395 window: &mut Window,
11396 cx: &mut Context<Self>,
11397 ) -> Task<Result<Navigated>> {
11398 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11399 }
11400
11401 pub fn go_to_definition_split(
11402 &mut self,
11403 _: &GoToDefinitionSplit,
11404 window: &mut Window,
11405 cx: &mut Context<Self>,
11406 ) -> Task<Result<Navigated>> {
11407 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11408 }
11409
11410 pub fn go_to_type_definition_split(
11411 &mut self,
11412 _: &GoToTypeDefinitionSplit,
11413 window: &mut Window,
11414 cx: &mut Context<Self>,
11415 ) -> Task<Result<Navigated>> {
11416 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11417 }
11418
11419 fn go_to_definition_of_kind(
11420 &mut self,
11421 kind: GotoDefinitionKind,
11422 split: bool,
11423 window: &mut Window,
11424 cx: &mut Context<Self>,
11425 ) -> Task<Result<Navigated>> {
11426 let Some(provider) = self.semantics_provider.clone() else {
11427 return Task::ready(Ok(Navigated::No));
11428 };
11429 let head = self.selections.newest::<usize>(cx).head();
11430 let buffer = self.buffer.read(cx);
11431 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11432 text_anchor
11433 } else {
11434 return Task::ready(Ok(Navigated::No));
11435 };
11436
11437 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11438 return Task::ready(Ok(Navigated::No));
11439 };
11440
11441 cx.spawn_in(window, |editor, mut cx| async move {
11442 let definitions = definitions.await?;
11443 let navigated = editor
11444 .update_in(&mut cx, |editor, window, cx| {
11445 editor.navigate_to_hover_links(
11446 Some(kind),
11447 definitions
11448 .into_iter()
11449 .filter(|location| {
11450 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11451 })
11452 .map(HoverLink::Text)
11453 .collect::<Vec<_>>(),
11454 split,
11455 window,
11456 cx,
11457 )
11458 })?
11459 .await?;
11460 anyhow::Ok(navigated)
11461 })
11462 }
11463
11464 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11465 let selection = self.selections.newest_anchor();
11466 let head = selection.head();
11467 let tail = selection.tail();
11468
11469 let Some((buffer, start_position)) =
11470 self.buffer.read(cx).text_anchor_for_position(head, cx)
11471 else {
11472 return;
11473 };
11474
11475 let end_position = if head != tail {
11476 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11477 return;
11478 };
11479 Some(pos)
11480 } else {
11481 None
11482 };
11483
11484 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11485 let url = if let Some(end_pos) = end_position {
11486 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11487 } else {
11488 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11489 };
11490
11491 if let Some(url) = url {
11492 editor.update(&mut cx, |_, cx| {
11493 cx.open_url(&url);
11494 })
11495 } else {
11496 Ok(())
11497 }
11498 });
11499
11500 url_finder.detach();
11501 }
11502
11503 pub fn open_selected_filename(
11504 &mut self,
11505 _: &OpenSelectedFilename,
11506 window: &mut Window,
11507 cx: &mut Context<Self>,
11508 ) {
11509 let Some(workspace) = self.workspace() else {
11510 return;
11511 };
11512
11513 let position = self.selections.newest_anchor().head();
11514
11515 let Some((buffer, buffer_position)) =
11516 self.buffer.read(cx).text_anchor_for_position(position, cx)
11517 else {
11518 return;
11519 };
11520
11521 let project = self.project.clone();
11522
11523 cx.spawn_in(window, |_, mut cx| async move {
11524 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11525
11526 if let Some((_, path)) = result {
11527 workspace
11528 .update_in(&mut cx, |workspace, window, cx| {
11529 workspace.open_resolved_path(path, window, cx)
11530 })?
11531 .await?;
11532 }
11533 anyhow::Ok(())
11534 })
11535 .detach();
11536 }
11537
11538 pub(crate) fn navigate_to_hover_links(
11539 &mut self,
11540 kind: Option<GotoDefinitionKind>,
11541 mut definitions: Vec<HoverLink>,
11542 split: bool,
11543 window: &mut Window,
11544 cx: &mut Context<Editor>,
11545 ) -> Task<Result<Navigated>> {
11546 // If there is one definition, just open it directly
11547 if definitions.len() == 1 {
11548 let definition = definitions.pop().unwrap();
11549
11550 enum TargetTaskResult {
11551 Location(Option<Location>),
11552 AlreadyNavigated,
11553 }
11554
11555 let target_task = match definition {
11556 HoverLink::Text(link) => {
11557 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11558 }
11559 HoverLink::InlayHint(lsp_location, server_id) => {
11560 let computation =
11561 self.compute_target_location(lsp_location, server_id, window, cx);
11562 cx.background_spawn(async move {
11563 let location = computation.await?;
11564 Ok(TargetTaskResult::Location(location))
11565 })
11566 }
11567 HoverLink::Url(url) => {
11568 cx.open_url(&url);
11569 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11570 }
11571 HoverLink::File(path) => {
11572 if let Some(workspace) = self.workspace() {
11573 cx.spawn_in(window, |_, mut cx| async move {
11574 workspace
11575 .update_in(&mut cx, |workspace, window, cx| {
11576 workspace.open_resolved_path(path, window, cx)
11577 })?
11578 .await
11579 .map(|_| TargetTaskResult::AlreadyNavigated)
11580 })
11581 } else {
11582 Task::ready(Ok(TargetTaskResult::Location(None)))
11583 }
11584 }
11585 };
11586 cx.spawn_in(window, |editor, mut cx| async move {
11587 let target = match target_task.await.context("target resolution task")? {
11588 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11589 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11590 TargetTaskResult::Location(Some(target)) => target,
11591 };
11592
11593 editor.update_in(&mut cx, |editor, window, cx| {
11594 let Some(workspace) = editor.workspace() else {
11595 return Navigated::No;
11596 };
11597 let pane = workspace.read(cx).active_pane().clone();
11598
11599 let range = target.range.to_point(target.buffer.read(cx));
11600 let range = editor.range_for_match(&range);
11601 let range = collapse_multiline_range(range);
11602
11603 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11604 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11605 } else {
11606 window.defer(cx, move |window, cx| {
11607 let target_editor: Entity<Self> =
11608 workspace.update(cx, |workspace, cx| {
11609 let pane = if split {
11610 workspace.adjacent_pane(window, cx)
11611 } else {
11612 workspace.active_pane().clone()
11613 };
11614
11615 workspace.open_project_item(
11616 pane,
11617 target.buffer.clone(),
11618 true,
11619 true,
11620 window,
11621 cx,
11622 )
11623 });
11624 target_editor.update(cx, |target_editor, cx| {
11625 // When selecting a definition in a different buffer, disable the nav history
11626 // to avoid creating a history entry at the previous cursor location.
11627 pane.update(cx, |pane, _| pane.disable_history());
11628 target_editor.go_to_singleton_buffer_range(range, window, cx);
11629 pane.update(cx, |pane, _| pane.enable_history());
11630 });
11631 });
11632 }
11633 Navigated::Yes
11634 })
11635 })
11636 } else if !definitions.is_empty() {
11637 cx.spawn_in(window, |editor, mut cx| async move {
11638 let (title, location_tasks, workspace) = editor
11639 .update_in(&mut cx, |editor, window, cx| {
11640 let tab_kind = match kind {
11641 Some(GotoDefinitionKind::Implementation) => "Implementations",
11642 _ => "Definitions",
11643 };
11644 let title = definitions
11645 .iter()
11646 .find_map(|definition| match definition {
11647 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11648 let buffer = origin.buffer.read(cx);
11649 format!(
11650 "{} for {}",
11651 tab_kind,
11652 buffer
11653 .text_for_range(origin.range.clone())
11654 .collect::<String>()
11655 )
11656 }),
11657 HoverLink::InlayHint(_, _) => None,
11658 HoverLink::Url(_) => None,
11659 HoverLink::File(_) => None,
11660 })
11661 .unwrap_or(tab_kind.to_string());
11662 let location_tasks = definitions
11663 .into_iter()
11664 .map(|definition| match definition {
11665 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11666 HoverLink::InlayHint(lsp_location, server_id) => editor
11667 .compute_target_location(lsp_location, server_id, window, cx),
11668 HoverLink::Url(_) => Task::ready(Ok(None)),
11669 HoverLink::File(_) => Task::ready(Ok(None)),
11670 })
11671 .collect::<Vec<_>>();
11672 (title, location_tasks, editor.workspace().clone())
11673 })
11674 .context("location tasks preparation")?;
11675
11676 let locations = future::join_all(location_tasks)
11677 .await
11678 .into_iter()
11679 .filter_map(|location| location.transpose())
11680 .collect::<Result<_>>()
11681 .context("location tasks")?;
11682
11683 let Some(workspace) = workspace else {
11684 return Ok(Navigated::No);
11685 };
11686 let opened = workspace
11687 .update_in(&mut cx, |workspace, window, cx| {
11688 Self::open_locations_in_multibuffer(
11689 workspace,
11690 locations,
11691 title,
11692 split,
11693 MultibufferSelectionMode::First,
11694 window,
11695 cx,
11696 )
11697 })
11698 .ok();
11699
11700 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11701 })
11702 } else {
11703 Task::ready(Ok(Navigated::No))
11704 }
11705 }
11706
11707 fn compute_target_location(
11708 &self,
11709 lsp_location: lsp::Location,
11710 server_id: LanguageServerId,
11711 window: &mut Window,
11712 cx: &mut Context<Self>,
11713 ) -> Task<anyhow::Result<Option<Location>>> {
11714 let Some(project) = self.project.clone() else {
11715 return Task::ready(Ok(None));
11716 };
11717
11718 cx.spawn_in(window, move |editor, mut cx| async move {
11719 let location_task = editor.update(&mut cx, |_, cx| {
11720 project.update(cx, |project, cx| {
11721 let language_server_name = project
11722 .language_server_statuses(cx)
11723 .find(|(id, _)| server_id == *id)
11724 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11725 language_server_name.map(|language_server_name| {
11726 project.open_local_buffer_via_lsp(
11727 lsp_location.uri.clone(),
11728 server_id,
11729 language_server_name,
11730 cx,
11731 )
11732 })
11733 })
11734 })?;
11735 let location = match location_task {
11736 Some(task) => Some({
11737 let target_buffer_handle = task.await.context("open local buffer")?;
11738 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11739 let target_start = target_buffer
11740 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11741 let target_end = target_buffer
11742 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11743 target_buffer.anchor_after(target_start)
11744 ..target_buffer.anchor_before(target_end)
11745 })?;
11746 Location {
11747 buffer: target_buffer_handle,
11748 range,
11749 }
11750 }),
11751 None => None,
11752 };
11753 Ok(location)
11754 })
11755 }
11756
11757 pub fn find_all_references(
11758 &mut self,
11759 _: &FindAllReferences,
11760 window: &mut Window,
11761 cx: &mut Context<Self>,
11762 ) -> Option<Task<Result<Navigated>>> {
11763 let selection = self.selections.newest::<usize>(cx);
11764 let multi_buffer = self.buffer.read(cx);
11765 let head = selection.head();
11766
11767 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11768 let head_anchor = multi_buffer_snapshot.anchor_at(
11769 head,
11770 if head < selection.tail() {
11771 Bias::Right
11772 } else {
11773 Bias::Left
11774 },
11775 );
11776
11777 match self
11778 .find_all_references_task_sources
11779 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11780 {
11781 Ok(_) => {
11782 log::info!(
11783 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11784 );
11785 return None;
11786 }
11787 Err(i) => {
11788 self.find_all_references_task_sources.insert(i, head_anchor);
11789 }
11790 }
11791
11792 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11793 let workspace = self.workspace()?;
11794 let project = workspace.read(cx).project().clone();
11795 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11796 Some(cx.spawn_in(window, |editor, mut cx| async move {
11797 let _cleanup = defer({
11798 let mut cx = cx.clone();
11799 move || {
11800 let _ = editor.update(&mut cx, |editor, _| {
11801 if let Ok(i) =
11802 editor
11803 .find_all_references_task_sources
11804 .binary_search_by(|anchor| {
11805 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11806 })
11807 {
11808 editor.find_all_references_task_sources.remove(i);
11809 }
11810 });
11811 }
11812 });
11813
11814 let locations = references.await?;
11815 if locations.is_empty() {
11816 return anyhow::Ok(Navigated::No);
11817 }
11818
11819 workspace.update_in(&mut cx, |workspace, window, cx| {
11820 let title = locations
11821 .first()
11822 .as_ref()
11823 .map(|location| {
11824 let buffer = location.buffer.read(cx);
11825 format!(
11826 "References to `{}`",
11827 buffer
11828 .text_for_range(location.range.clone())
11829 .collect::<String>()
11830 )
11831 })
11832 .unwrap();
11833 Self::open_locations_in_multibuffer(
11834 workspace,
11835 locations,
11836 title,
11837 false,
11838 MultibufferSelectionMode::First,
11839 window,
11840 cx,
11841 );
11842 Navigated::Yes
11843 })
11844 }))
11845 }
11846
11847 /// Opens a multibuffer with the given project locations in it
11848 pub fn open_locations_in_multibuffer(
11849 workspace: &mut Workspace,
11850 mut locations: Vec<Location>,
11851 title: String,
11852 split: bool,
11853 multibuffer_selection_mode: MultibufferSelectionMode,
11854 window: &mut Window,
11855 cx: &mut Context<Workspace>,
11856 ) {
11857 // If there are multiple definitions, open them in a multibuffer
11858 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11859 let mut locations = locations.into_iter().peekable();
11860 let mut ranges = Vec::new();
11861 let capability = workspace.project().read(cx).capability();
11862
11863 let excerpt_buffer = cx.new(|cx| {
11864 let mut multibuffer = MultiBuffer::new(capability);
11865 while let Some(location) = locations.next() {
11866 let buffer = location.buffer.read(cx);
11867 let mut ranges_for_buffer = Vec::new();
11868 let range = location.range.to_offset(buffer);
11869 ranges_for_buffer.push(range.clone());
11870
11871 while let Some(next_location) = locations.peek() {
11872 if next_location.buffer == location.buffer {
11873 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11874 locations.next();
11875 } else {
11876 break;
11877 }
11878 }
11879
11880 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11881 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11882 location.buffer.clone(),
11883 ranges_for_buffer,
11884 DEFAULT_MULTIBUFFER_CONTEXT,
11885 cx,
11886 ))
11887 }
11888
11889 multibuffer.with_title(title)
11890 });
11891
11892 let editor = cx.new(|cx| {
11893 Editor::for_multibuffer(
11894 excerpt_buffer,
11895 Some(workspace.project().clone()),
11896 true,
11897 window,
11898 cx,
11899 )
11900 });
11901 editor.update(cx, |editor, cx| {
11902 match multibuffer_selection_mode {
11903 MultibufferSelectionMode::First => {
11904 if let Some(first_range) = ranges.first() {
11905 editor.change_selections(None, window, cx, |selections| {
11906 selections.clear_disjoint();
11907 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11908 });
11909 }
11910 editor.highlight_background::<Self>(
11911 &ranges,
11912 |theme| theme.editor_highlighted_line_background,
11913 cx,
11914 );
11915 }
11916 MultibufferSelectionMode::All => {
11917 editor.change_selections(None, window, cx, |selections| {
11918 selections.clear_disjoint();
11919 selections.select_anchor_ranges(ranges);
11920 });
11921 }
11922 }
11923 editor.register_buffers_with_language_servers(cx);
11924 });
11925
11926 let item = Box::new(editor);
11927 let item_id = item.item_id();
11928
11929 if split {
11930 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11931 } else {
11932 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11933 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11934 pane.close_current_preview_item(window, cx)
11935 } else {
11936 None
11937 }
11938 });
11939 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11940 }
11941 workspace.active_pane().update(cx, |pane, cx| {
11942 pane.set_preview_item_id(Some(item_id), cx);
11943 });
11944 }
11945
11946 pub fn rename(
11947 &mut self,
11948 _: &Rename,
11949 window: &mut Window,
11950 cx: &mut Context<Self>,
11951 ) -> Option<Task<Result<()>>> {
11952 use language::ToOffset as _;
11953
11954 let provider = self.semantics_provider.clone()?;
11955 let selection = self.selections.newest_anchor().clone();
11956 let (cursor_buffer, cursor_buffer_position) = self
11957 .buffer
11958 .read(cx)
11959 .text_anchor_for_position(selection.head(), cx)?;
11960 let (tail_buffer, cursor_buffer_position_end) = self
11961 .buffer
11962 .read(cx)
11963 .text_anchor_for_position(selection.tail(), cx)?;
11964 if tail_buffer != cursor_buffer {
11965 return None;
11966 }
11967
11968 let snapshot = cursor_buffer.read(cx).snapshot();
11969 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11970 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11971 let prepare_rename = provider
11972 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11973 .unwrap_or_else(|| Task::ready(Ok(None)));
11974 drop(snapshot);
11975
11976 Some(cx.spawn_in(window, |this, mut cx| async move {
11977 let rename_range = if let Some(range) = prepare_rename.await? {
11978 Some(range)
11979 } else {
11980 this.update(&mut cx, |this, cx| {
11981 let buffer = this.buffer.read(cx).snapshot(cx);
11982 let mut buffer_highlights = this
11983 .document_highlights_for_position(selection.head(), &buffer)
11984 .filter(|highlight| {
11985 highlight.start.excerpt_id == selection.head().excerpt_id
11986 && highlight.end.excerpt_id == selection.head().excerpt_id
11987 });
11988 buffer_highlights
11989 .next()
11990 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11991 })?
11992 };
11993 if let Some(rename_range) = rename_range {
11994 this.update_in(&mut cx, |this, window, cx| {
11995 let snapshot = cursor_buffer.read(cx).snapshot();
11996 let rename_buffer_range = rename_range.to_offset(&snapshot);
11997 let cursor_offset_in_rename_range =
11998 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11999 let cursor_offset_in_rename_range_end =
12000 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12001
12002 this.take_rename(false, window, cx);
12003 let buffer = this.buffer.read(cx).read(cx);
12004 let cursor_offset = selection.head().to_offset(&buffer);
12005 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12006 let rename_end = rename_start + rename_buffer_range.len();
12007 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12008 let mut old_highlight_id = None;
12009 let old_name: Arc<str> = buffer
12010 .chunks(rename_start..rename_end, true)
12011 .map(|chunk| {
12012 if old_highlight_id.is_none() {
12013 old_highlight_id = chunk.syntax_highlight_id;
12014 }
12015 chunk.text
12016 })
12017 .collect::<String>()
12018 .into();
12019
12020 drop(buffer);
12021
12022 // Position the selection in the rename editor so that it matches the current selection.
12023 this.show_local_selections = false;
12024 let rename_editor = cx.new(|cx| {
12025 let mut editor = Editor::single_line(window, cx);
12026 editor.buffer.update(cx, |buffer, cx| {
12027 buffer.edit([(0..0, old_name.clone())], None, cx)
12028 });
12029 let rename_selection_range = match cursor_offset_in_rename_range
12030 .cmp(&cursor_offset_in_rename_range_end)
12031 {
12032 Ordering::Equal => {
12033 editor.select_all(&SelectAll, window, cx);
12034 return editor;
12035 }
12036 Ordering::Less => {
12037 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12038 }
12039 Ordering::Greater => {
12040 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12041 }
12042 };
12043 if rename_selection_range.end > old_name.len() {
12044 editor.select_all(&SelectAll, window, cx);
12045 } else {
12046 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12047 s.select_ranges([rename_selection_range]);
12048 });
12049 }
12050 editor
12051 });
12052 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12053 if e == &EditorEvent::Focused {
12054 cx.emit(EditorEvent::FocusedIn)
12055 }
12056 })
12057 .detach();
12058
12059 let write_highlights =
12060 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12061 let read_highlights =
12062 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12063 let ranges = write_highlights
12064 .iter()
12065 .flat_map(|(_, ranges)| ranges.iter())
12066 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12067 .cloned()
12068 .collect();
12069
12070 this.highlight_text::<Rename>(
12071 ranges,
12072 HighlightStyle {
12073 fade_out: Some(0.6),
12074 ..Default::default()
12075 },
12076 cx,
12077 );
12078 let rename_focus_handle = rename_editor.focus_handle(cx);
12079 window.focus(&rename_focus_handle);
12080 let block_id = this.insert_blocks(
12081 [BlockProperties {
12082 style: BlockStyle::Flex,
12083 placement: BlockPlacement::Below(range.start),
12084 height: 1,
12085 render: Arc::new({
12086 let rename_editor = rename_editor.clone();
12087 move |cx: &mut BlockContext| {
12088 let mut text_style = cx.editor_style.text.clone();
12089 if let Some(highlight_style) = old_highlight_id
12090 .and_then(|h| h.style(&cx.editor_style.syntax))
12091 {
12092 text_style = text_style.highlight(highlight_style);
12093 }
12094 div()
12095 .block_mouse_down()
12096 .pl(cx.anchor_x)
12097 .child(EditorElement::new(
12098 &rename_editor,
12099 EditorStyle {
12100 background: cx.theme().system().transparent,
12101 local_player: cx.editor_style.local_player,
12102 text: text_style,
12103 scrollbar_width: cx.editor_style.scrollbar_width,
12104 syntax: cx.editor_style.syntax.clone(),
12105 status: cx.editor_style.status.clone(),
12106 inlay_hints_style: HighlightStyle {
12107 font_weight: Some(FontWeight::BOLD),
12108 ..make_inlay_hints_style(cx.app)
12109 },
12110 inline_completion_styles: make_suggestion_styles(
12111 cx.app,
12112 ),
12113 ..EditorStyle::default()
12114 },
12115 ))
12116 .into_any_element()
12117 }
12118 }),
12119 priority: 0,
12120 }],
12121 Some(Autoscroll::fit()),
12122 cx,
12123 )[0];
12124 this.pending_rename = Some(RenameState {
12125 range,
12126 old_name,
12127 editor: rename_editor,
12128 block_id,
12129 });
12130 })?;
12131 }
12132
12133 Ok(())
12134 }))
12135 }
12136
12137 pub fn confirm_rename(
12138 &mut self,
12139 _: &ConfirmRename,
12140 window: &mut Window,
12141 cx: &mut Context<Self>,
12142 ) -> Option<Task<Result<()>>> {
12143 let rename = self.take_rename(false, window, cx)?;
12144 let workspace = self.workspace()?.downgrade();
12145 let (buffer, start) = self
12146 .buffer
12147 .read(cx)
12148 .text_anchor_for_position(rename.range.start, cx)?;
12149 let (end_buffer, _) = self
12150 .buffer
12151 .read(cx)
12152 .text_anchor_for_position(rename.range.end, cx)?;
12153 if buffer != end_buffer {
12154 return None;
12155 }
12156
12157 let old_name = rename.old_name;
12158 let new_name = rename.editor.read(cx).text(cx);
12159
12160 let rename = self.semantics_provider.as_ref()?.perform_rename(
12161 &buffer,
12162 start,
12163 new_name.clone(),
12164 cx,
12165 )?;
12166
12167 Some(cx.spawn_in(window, |editor, mut cx| async move {
12168 let project_transaction = rename.await?;
12169 Self::open_project_transaction(
12170 &editor,
12171 workspace,
12172 project_transaction,
12173 format!("Rename: {} → {}", old_name, new_name),
12174 cx.clone(),
12175 )
12176 .await?;
12177
12178 editor.update(&mut cx, |editor, cx| {
12179 editor.refresh_document_highlights(cx);
12180 })?;
12181 Ok(())
12182 }))
12183 }
12184
12185 fn take_rename(
12186 &mut self,
12187 moving_cursor: bool,
12188 window: &mut Window,
12189 cx: &mut Context<Self>,
12190 ) -> Option<RenameState> {
12191 let rename = self.pending_rename.take()?;
12192 if rename.editor.focus_handle(cx).is_focused(window) {
12193 window.focus(&self.focus_handle);
12194 }
12195
12196 self.remove_blocks(
12197 [rename.block_id].into_iter().collect(),
12198 Some(Autoscroll::fit()),
12199 cx,
12200 );
12201 self.clear_highlights::<Rename>(cx);
12202 self.show_local_selections = true;
12203
12204 if moving_cursor {
12205 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12206 editor.selections.newest::<usize>(cx).head()
12207 });
12208
12209 // Update the selection to match the position of the selection inside
12210 // the rename editor.
12211 let snapshot = self.buffer.read(cx).read(cx);
12212 let rename_range = rename.range.to_offset(&snapshot);
12213 let cursor_in_editor = snapshot
12214 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12215 .min(rename_range.end);
12216 drop(snapshot);
12217
12218 self.change_selections(None, window, cx, |s| {
12219 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12220 });
12221 } else {
12222 self.refresh_document_highlights(cx);
12223 }
12224
12225 Some(rename)
12226 }
12227
12228 pub fn pending_rename(&self) -> Option<&RenameState> {
12229 self.pending_rename.as_ref()
12230 }
12231
12232 fn format(
12233 &mut self,
12234 _: &Format,
12235 window: &mut Window,
12236 cx: &mut Context<Self>,
12237 ) -> Option<Task<Result<()>>> {
12238 let project = match &self.project {
12239 Some(project) => project.clone(),
12240 None => return None,
12241 };
12242
12243 Some(self.perform_format(
12244 project,
12245 FormatTrigger::Manual,
12246 FormatTarget::Buffers,
12247 window,
12248 cx,
12249 ))
12250 }
12251
12252 fn format_selections(
12253 &mut self,
12254 _: &FormatSelections,
12255 window: &mut Window,
12256 cx: &mut Context<Self>,
12257 ) -> Option<Task<Result<()>>> {
12258 let project = match &self.project {
12259 Some(project) => project.clone(),
12260 None => return None,
12261 };
12262
12263 let ranges = self
12264 .selections
12265 .all_adjusted(cx)
12266 .into_iter()
12267 .map(|selection| selection.range())
12268 .collect_vec();
12269
12270 Some(self.perform_format(
12271 project,
12272 FormatTrigger::Manual,
12273 FormatTarget::Ranges(ranges),
12274 window,
12275 cx,
12276 ))
12277 }
12278
12279 fn perform_format(
12280 &mut self,
12281 project: Entity<Project>,
12282 trigger: FormatTrigger,
12283 target: FormatTarget,
12284 window: &mut Window,
12285 cx: &mut Context<Self>,
12286 ) -> Task<Result<()>> {
12287 let buffer = self.buffer.clone();
12288 let (buffers, target) = match target {
12289 FormatTarget::Buffers => {
12290 let mut buffers = buffer.read(cx).all_buffers();
12291 if trigger == FormatTrigger::Save {
12292 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12293 }
12294 (buffers, LspFormatTarget::Buffers)
12295 }
12296 FormatTarget::Ranges(selection_ranges) => {
12297 let multi_buffer = buffer.read(cx);
12298 let snapshot = multi_buffer.read(cx);
12299 let mut buffers = HashSet::default();
12300 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12301 BTreeMap::new();
12302 for selection_range in selection_ranges {
12303 for (buffer, buffer_range, _) in
12304 snapshot.range_to_buffer_ranges(selection_range)
12305 {
12306 let buffer_id = buffer.remote_id();
12307 let start = buffer.anchor_before(buffer_range.start);
12308 let end = buffer.anchor_after(buffer_range.end);
12309 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12310 buffer_id_to_ranges
12311 .entry(buffer_id)
12312 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12313 .or_insert_with(|| vec![start..end]);
12314 }
12315 }
12316 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12317 }
12318 };
12319
12320 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12321 let format = project.update(cx, |project, cx| {
12322 project.format(buffers, target, true, trigger, cx)
12323 });
12324
12325 cx.spawn_in(window, |_, mut cx| async move {
12326 let transaction = futures::select_biased! {
12327 () = timeout => {
12328 log::warn!("timed out waiting for formatting");
12329 None
12330 }
12331 transaction = format.log_err().fuse() => transaction,
12332 };
12333
12334 buffer
12335 .update(&mut cx, |buffer, cx| {
12336 if let Some(transaction) = transaction {
12337 if !buffer.is_singleton() {
12338 buffer.push_transaction(&transaction.0, cx);
12339 }
12340 }
12341
12342 cx.notify();
12343 })
12344 .ok();
12345
12346 Ok(())
12347 })
12348 }
12349
12350 fn restart_language_server(
12351 &mut self,
12352 _: &RestartLanguageServer,
12353 _: &mut Window,
12354 cx: &mut Context<Self>,
12355 ) {
12356 if let Some(project) = self.project.clone() {
12357 self.buffer.update(cx, |multi_buffer, cx| {
12358 project.update(cx, |project, cx| {
12359 project.restart_language_servers_for_buffers(
12360 multi_buffer.all_buffers().into_iter().collect(),
12361 cx,
12362 );
12363 });
12364 })
12365 }
12366 }
12367
12368 fn cancel_language_server_work(
12369 workspace: &mut Workspace,
12370 _: &actions::CancelLanguageServerWork,
12371 _: &mut Window,
12372 cx: &mut Context<Workspace>,
12373 ) {
12374 let project = workspace.project();
12375 let buffers = workspace
12376 .active_item(cx)
12377 .and_then(|item| item.act_as::<Editor>(cx))
12378 .map_or(HashSet::default(), |editor| {
12379 editor.read(cx).buffer.read(cx).all_buffers()
12380 });
12381 project.update(cx, |project, cx| {
12382 project.cancel_language_server_work_for_buffers(buffers, cx);
12383 });
12384 }
12385
12386 fn show_character_palette(
12387 &mut self,
12388 _: &ShowCharacterPalette,
12389 window: &mut Window,
12390 _: &mut Context<Self>,
12391 ) {
12392 window.show_character_palette();
12393 }
12394
12395 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12396 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12397 let buffer = self.buffer.read(cx).snapshot(cx);
12398 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12399 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12400 let is_valid = buffer
12401 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12402 .any(|entry| {
12403 entry.diagnostic.is_primary
12404 && !entry.range.is_empty()
12405 && entry.range.start == primary_range_start
12406 && entry.diagnostic.message == active_diagnostics.primary_message
12407 });
12408
12409 if is_valid != active_diagnostics.is_valid {
12410 active_diagnostics.is_valid = is_valid;
12411 let mut new_styles = HashMap::default();
12412 for (block_id, diagnostic) in &active_diagnostics.blocks {
12413 new_styles.insert(
12414 *block_id,
12415 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12416 );
12417 }
12418 self.display_map.update(cx, |display_map, _cx| {
12419 display_map.replace_blocks(new_styles)
12420 });
12421 }
12422 }
12423 }
12424
12425 fn activate_diagnostics(
12426 &mut self,
12427 buffer_id: BufferId,
12428 group_id: usize,
12429 window: &mut Window,
12430 cx: &mut Context<Self>,
12431 ) {
12432 self.dismiss_diagnostics(cx);
12433 let snapshot = self.snapshot(window, cx);
12434 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12435 let buffer = self.buffer.read(cx).snapshot(cx);
12436
12437 let mut primary_range = None;
12438 let mut primary_message = None;
12439 let diagnostic_group = buffer
12440 .diagnostic_group(buffer_id, group_id)
12441 .filter_map(|entry| {
12442 let start = entry.range.start;
12443 let end = entry.range.end;
12444 if snapshot.is_line_folded(MultiBufferRow(start.row))
12445 && (start.row == end.row
12446 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12447 {
12448 return None;
12449 }
12450 if entry.diagnostic.is_primary {
12451 primary_range = Some(entry.range.clone());
12452 primary_message = Some(entry.diagnostic.message.clone());
12453 }
12454 Some(entry)
12455 })
12456 .collect::<Vec<_>>();
12457 let primary_range = primary_range?;
12458 let primary_message = primary_message?;
12459
12460 let blocks = display_map
12461 .insert_blocks(
12462 diagnostic_group.iter().map(|entry| {
12463 let diagnostic = entry.diagnostic.clone();
12464 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12465 BlockProperties {
12466 style: BlockStyle::Fixed,
12467 placement: BlockPlacement::Below(
12468 buffer.anchor_after(entry.range.start),
12469 ),
12470 height: message_height,
12471 render: diagnostic_block_renderer(diagnostic, None, true, true),
12472 priority: 0,
12473 }
12474 }),
12475 cx,
12476 )
12477 .into_iter()
12478 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12479 .collect();
12480
12481 Some(ActiveDiagnosticGroup {
12482 primary_range: buffer.anchor_before(primary_range.start)
12483 ..buffer.anchor_after(primary_range.end),
12484 primary_message,
12485 group_id,
12486 blocks,
12487 is_valid: true,
12488 })
12489 });
12490 }
12491
12492 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12493 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12494 self.display_map.update(cx, |display_map, cx| {
12495 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12496 });
12497 cx.notify();
12498 }
12499 }
12500
12501 /// Disable inline diagnostics rendering for this editor.
12502 pub fn disable_inline_diagnostics(&mut self) {
12503 self.inline_diagnostics_enabled = false;
12504 self.inline_diagnostics_update = Task::ready(());
12505 self.inline_diagnostics.clear();
12506 }
12507
12508 pub fn inline_diagnostics_enabled(&self) -> bool {
12509 self.inline_diagnostics_enabled
12510 }
12511
12512 pub fn show_inline_diagnostics(&self) -> bool {
12513 self.show_inline_diagnostics
12514 }
12515
12516 pub fn toggle_inline_diagnostics(
12517 &mut self,
12518 _: &ToggleInlineDiagnostics,
12519 window: &mut Window,
12520 cx: &mut Context<'_, Editor>,
12521 ) {
12522 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12523 self.refresh_inline_diagnostics(false, window, cx);
12524 }
12525
12526 fn refresh_inline_diagnostics(
12527 &mut self,
12528 debounce: bool,
12529 window: &mut Window,
12530 cx: &mut Context<Self>,
12531 ) {
12532 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12533 self.inline_diagnostics_update = Task::ready(());
12534 self.inline_diagnostics.clear();
12535 return;
12536 }
12537
12538 let debounce_ms = ProjectSettings::get_global(cx)
12539 .diagnostics
12540 .inline
12541 .update_debounce_ms;
12542 let debounce = if debounce && debounce_ms > 0 {
12543 Some(Duration::from_millis(debounce_ms))
12544 } else {
12545 None
12546 };
12547 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12548 if let Some(debounce) = debounce {
12549 cx.background_executor().timer(debounce).await;
12550 }
12551 let Some(snapshot) = editor
12552 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12553 .ok()
12554 else {
12555 return;
12556 };
12557
12558 let new_inline_diagnostics = cx
12559 .background_spawn(async move {
12560 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12561 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12562 let message = diagnostic_entry
12563 .diagnostic
12564 .message
12565 .split_once('\n')
12566 .map(|(line, _)| line)
12567 .map(SharedString::new)
12568 .unwrap_or_else(|| {
12569 SharedString::from(diagnostic_entry.diagnostic.message)
12570 });
12571 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12572 let (Ok(i) | Err(i)) = inline_diagnostics
12573 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12574 inline_diagnostics.insert(
12575 i,
12576 (
12577 start_anchor,
12578 InlineDiagnostic {
12579 message,
12580 group_id: diagnostic_entry.diagnostic.group_id,
12581 start: diagnostic_entry.range.start.to_point(&snapshot),
12582 is_primary: diagnostic_entry.diagnostic.is_primary,
12583 severity: diagnostic_entry.diagnostic.severity,
12584 },
12585 ),
12586 );
12587 }
12588 inline_diagnostics
12589 })
12590 .await;
12591
12592 editor
12593 .update(&mut cx, |editor, cx| {
12594 editor.inline_diagnostics = new_inline_diagnostics;
12595 cx.notify();
12596 })
12597 .ok();
12598 });
12599 }
12600
12601 pub fn set_selections_from_remote(
12602 &mut self,
12603 selections: Vec<Selection<Anchor>>,
12604 pending_selection: Option<Selection<Anchor>>,
12605 window: &mut Window,
12606 cx: &mut Context<Self>,
12607 ) {
12608 let old_cursor_position = self.selections.newest_anchor().head();
12609 self.selections.change_with(cx, |s| {
12610 s.select_anchors(selections);
12611 if let Some(pending_selection) = pending_selection {
12612 s.set_pending(pending_selection, SelectMode::Character);
12613 } else {
12614 s.clear_pending();
12615 }
12616 });
12617 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12618 }
12619
12620 fn push_to_selection_history(&mut self) {
12621 self.selection_history.push(SelectionHistoryEntry {
12622 selections: self.selections.disjoint_anchors(),
12623 select_next_state: self.select_next_state.clone(),
12624 select_prev_state: self.select_prev_state.clone(),
12625 add_selections_state: self.add_selections_state.clone(),
12626 });
12627 }
12628
12629 pub fn transact(
12630 &mut self,
12631 window: &mut Window,
12632 cx: &mut Context<Self>,
12633 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12634 ) -> Option<TransactionId> {
12635 self.start_transaction_at(Instant::now(), window, cx);
12636 update(self, window, cx);
12637 self.end_transaction_at(Instant::now(), cx)
12638 }
12639
12640 pub fn start_transaction_at(
12641 &mut self,
12642 now: Instant,
12643 window: &mut Window,
12644 cx: &mut Context<Self>,
12645 ) {
12646 self.end_selection(window, cx);
12647 if let Some(tx_id) = self
12648 .buffer
12649 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12650 {
12651 self.selection_history
12652 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12653 cx.emit(EditorEvent::TransactionBegun {
12654 transaction_id: tx_id,
12655 })
12656 }
12657 }
12658
12659 pub fn end_transaction_at(
12660 &mut self,
12661 now: Instant,
12662 cx: &mut Context<Self>,
12663 ) -> Option<TransactionId> {
12664 if let Some(transaction_id) = self
12665 .buffer
12666 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12667 {
12668 if let Some((_, end_selections)) =
12669 self.selection_history.transaction_mut(transaction_id)
12670 {
12671 *end_selections = Some(self.selections.disjoint_anchors());
12672 } else {
12673 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12674 }
12675
12676 cx.emit(EditorEvent::Edited { transaction_id });
12677 Some(transaction_id)
12678 } else {
12679 None
12680 }
12681 }
12682
12683 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12684 if self.selection_mark_mode {
12685 self.change_selections(None, window, cx, |s| {
12686 s.move_with(|_, sel| {
12687 sel.collapse_to(sel.head(), SelectionGoal::None);
12688 });
12689 })
12690 }
12691 self.selection_mark_mode = true;
12692 cx.notify();
12693 }
12694
12695 pub fn swap_selection_ends(
12696 &mut self,
12697 _: &actions::SwapSelectionEnds,
12698 window: &mut Window,
12699 cx: &mut Context<Self>,
12700 ) {
12701 self.change_selections(None, window, cx, |s| {
12702 s.move_with(|_, sel| {
12703 if sel.start != sel.end {
12704 sel.reversed = !sel.reversed
12705 }
12706 });
12707 });
12708 self.request_autoscroll(Autoscroll::newest(), cx);
12709 cx.notify();
12710 }
12711
12712 pub fn toggle_fold(
12713 &mut self,
12714 _: &actions::ToggleFold,
12715 window: &mut Window,
12716 cx: &mut Context<Self>,
12717 ) {
12718 if self.is_singleton(cx) {
12719 let selection = self.selections.newest::<Point>(cx);
12720
12721 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12722 let range = if selection.is_empty() {
12723 let point = selection.head().to_display_point(&display_map);
12724 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12725 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12726 .to_point(&display_map);
12727 start..end
12728 } else {
12729 selection.range()
12730 };
12731 if display_map.folds_in_range(range).next().is_some() {
12732 self.unfold_lines(&Default::default(), window, cx)
12733 } else {
12734 self.fold(&Default::default(), window, cx)
12735 }
12736 } else {
12737 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12738 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12739 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12740 .map(|(snapshot, _, _)| snapshot.remote_id())
12741 .collect();
12742
12743 for buffer_id in buffer_ids {
12744 if self.is_buffer_folded(buffer_id, cx) {
12745 self.unfold_buffer(buffer_id, cx);
12746 } else {
12747 self.fold_buffer(buffer_id, cx);
12748 }
12749 }
12750 }
12751 }
12752
12753 pub fn toggle_fold_recursive(
12754 &mut self,
12755 _: &actions::ToggleFoldRecursive,
12756 window: &mut Window,
12757 cx: &mut Context<Self>,
12758 ) {
12759 let selection = self.selections.newest::<Point>(cx);
12760
12761 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12762 let range = if selection.is_empty() {
12763 let point = selection.head().to_display_point(&display_map);
12764 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12765 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12766 .to_point(&display_map);
12767 start..end
12768 } else {
12769 selection.range()
12770 };
12771 if display_map.folds_in_range(range).next().is_some() {
12772 self.unfold_recursive(&Default::default(), window, cx)
12773 } else {
12774 self.fold_recursive(&Default::default(), window, cx)
12775 }
12776 }
12777
12778 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12779 if self.is_singleton(cx) {
12780 let mut to_fold = Vec::new();
12781 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12782 let selections = self.selections.all_adjusted(cx);
12783
12784 for selection in selections {
12785 let range = selection.range().sorted();
12786 let buffer_start_row = range.start.row;
12787
12788 if range.start.row != range.end.row {
12789 let mut found = false;
12790 let mut row = range.start.row;
12791 while row <= range.end.row {
12792 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12793 {
12794 found = true;
12795 row = crease.range().end.row + 1;
12796 to_fold.push(crease);
12797 } else {
12798 row += 1
12799 }
12800 }
12801 if found {
12802 continue;
12803 }
12804 }
12805
12806 for row in (0..=range.start.row).rev() {
12807 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12808 if crease.range().end.row >= buffer_start_row {
12809 to_fold.push(crease);
12810 if row <= range.start.row {
12811 break;
12812 }
12813 }
12814 }
12815 }
12816 }
12817
12818 self.fold_creases(to_fold, true, window, cx);
12819 } else {
12820 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12821
12822 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12823 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12824 .map(|(snapshot, _, _)| snapshot.remote_id())
12825 .collect();
12826 for buffer_id in buffer_ids {
12827 self.fold_buffer(buffer_id, cx);
12828 }
12829 }
12830 }
12831
12832 fn fold_at_level(
12833 &mut self,
12834 fold_at: &FoldAtLevel,
12835 window: &mut Window,
12836 cx: &mut Context<Self>,
12837 ) {
12838 if !self.buffer.read(cx).is_singleton() {
12839 return;
12840 }
12841
12842 let fold_at_level = fold_at.0;
12843 let snapshot = self.buffer.read(cx).snapshot(cx);
12844 let mut to_fold = Vec::new();
12845 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12846
12847 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12848 while start_row < end_row {
12849 match self
12850 .snapshot(window, cx)
12851 .crease_for_buffer_row(MultiBufferRow(start_row))
12852 {
12853 Some(crease) => {
12854 let nested_start_row = crease.range().start.row + 1;
12855 let nested_end_row = crease.range().end.row;
12856
12857 if current_level < fold_at_level {
12858 stack.push((nested_start_row, nested_end_row, current_level + 1));
12859 } else if current_level == fold_at_level {
12860 to_fold.push(crease);
12861 }
12862
12863 start_row = nested_end_row + 1;
12864 }
12865 None => start_row += 1,
12866 }
12867 }
12868 }
12869
12870 self.fold_creases(to_fold, true, window, cx);
12871 }
12872
12873 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12874 if self.buffer.read(cx).is_singleton() {
12875 let mut fold_ranges = Vec::new();
12876 let snapshot = self.buffer.read(cx).snapshot(cx);
12877
12878 for row in 0..snapshot.max_row().0 {
12879 if let Some(foldable_range) = self
12880 .snapshot(window, cx)
12881 .crease_for_buffer_row(MultiBufferRow(row))
12882 {
12883 fold_ranges.push(foldable_range);
12884 }
12885 }
12886
12887 self.fold_creases(fold_ranges, true, window, cx);
12888 } else {
12889 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12890 editor
12891 .update_in(&mut cx, |editor, _, cx| {
12892 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12893 editor.fold_buffer(buffer_id, cx);
12894 }
12895 })
12896 .ok();
12897 });
12898 }
12899 }
12900
12901 pub fn fold_function_bodies(
12902 &mut self,
12903 _: &actions::FoldFunctionBodies,
12904 window: &mut Window,
12905 cx: &mut Context<Self>,
12906 ) {
12907 let snapshot = self.buffer.read(cx).snapshot(cx);
12908
12909 let ranges = snapshot
12910 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12911 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12912 .collect::<Vec<_>>();
12913
12914 let creases = ranges
12915 .into_iter()
12916 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12917 .collect();
12918
12919 self.fold_creases(creases, true, window, cx);
12920 }
12921
12922 pub fn fold_recursive(
12923 &mut self,
12924 _: &actions::FoldRecursive,
12925 window: &mut Window,
12926 cx: &mut Context<Self>,
12927 ) {
12928 let mut to_fold = Vec::new();
12929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12930 let selections = self.selections.all_adjusted(cx);
12931
12932 for selection in selections {
12933 let range = selection.range().sorted();
12934 let buffer_start_row = range.start.row;
12935
12936 if range.start.row != range.end.row {
12937 let mut found = false;
12938 for row in range.start.row..=range.end.row {
12939 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12940 found = true;
12941 to_fold.push(crease);
12942 }
12943 }
12944 if found {
12945 continue;
12946 }
12947 }
12948
12949 for row in (0..=range.start.row).rev() {
12950 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12951 if crease.range().end.row >= buffer_start_row {
12952 to_fold.push(crease);
12953 } else {
12954 break;
12955 }
12956 }
12957 }
12958 }
12959
12960 self.fold_creases(to_fold, true, window, cx);
12961 }
12962
12963 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12964 let buffer_row = fold_at.buffer_row;
12965 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12966
12967 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12968 let autoscroll = self
12969 .selections
12970 .all::<Point>(cx)
12971 .iter()
12972 .any(|selection| crease.range().overlaps(&selection.range()));
12973
12974 self.fold_creases(vec![crease], autoscroll, window, cx);
12975 }
12976 }
12977
12978 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12979 if self.is_singleton(cx) {
12980 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12981 let buffer = &display_map.buffer_snapshot;
12982 let selections = self.selections.all::<Point>(cx);
12983 let ranges = selections
12984 .iter()
12985 .map(|s| {
12986 let range = s.display_range(&display_map).sorted();
12987 let mut start = range.start.to_point(&display_map);
12988 let mut end = range.end.to_point(&display_map);
12989 start.column = 0;
12990 end.column = buffer.line_len(MultiBufferRow(end.row));
12991 start..end
12992 })
12993 .collect::<Vec<_>>();
12994
12995 self.unfold_ranges(&ranges, true, true, cx);
12996 } else {
12997 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12998 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12999 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13000 .map(|(snapshot, _, _)| snapshot.remote_id())
13001 .collect();
13002 for buffer_id in buffer_ids {
13003 self.unfold_buffer(buffer_id, cx);
13004 }
13005 }
13006 }
13007
13008 pub fn unfold_recursive(
13009 &mut self,
13010 _: &UnfoldRecursive,
13011 _window: &mut Window,
13012 cx: &mut Context<Self>,
13013 ) {
13014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13015 let selections = self.selections.all::<Point>(cx);
13016 let ranges = selections
13017 .iter()
13018 .map(|s| {
13019 let mut range = s.display_range(&display_map).sorted();
13020 *range.start.column_mut() = 0;
13021 *range.end.column_mut() = display_map.line_len(range.end.row());
13022 let start = range.start.to_point(&display_map);
13023 let end = range.end.to_point(&display_map);
13024 start..end
13025 })
13026 .collect::<Vec<_>>();
13027
13028 self.unfold_ranges(&ranges, true, true, cx);
13029 }
13030
13031 pub fn unfold_at(
13032 &mut self,
13033 unfold_at: &UnfoldAt,
13034 _window: &mut Window,
13035 cx: &mut Context<Self>,
13036 ) {
13037 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13038
13039 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13040 ..Point::new(
13041 unfold_at.buffer_row.0,
13042 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13043 );
13044
13045 let autoscroll = self
13046 .selections
13047 .all::<Point>(cx)
13048 .iter()
13049 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13050
13051 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13052 }
13053
13054 pub fn unfold_all(
13055 &mut self,
13056 _: &actions::UnfoldAll,
13057 _window: &mut Window,
13058 cx: &mut Context<Self>,
13059 ) {
13060 if self.buffer.read(cx).is_singleton() {
13061 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13062 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13063 } else {
13064 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13065 editor
13066 .update(&mut cx, |editor, cx| {
13067 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13068 editor.unfold_buffer(buffer_id, cx);
13069 }
13070 })
13071 .ok();
13072 });
13073 }
13074 }
13075
13076 pub fn fold_selected_ranges(
13077 &mut self,
13078 _: &FoldSelectedRanges,
13079 window: &mut Window,
13080 cx: &mut Context<Self>,
13081 ) {
13082 let selections = self.selections.all::<Point>(cx);
13083 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13084 let line_mode = self.selections.line_mode;
13085 let ranges = selections
13086 .into_iter()
13087 .map(|s| {
13088 if line_mode {
13089 let start = Point::new(s.start.row, 0);
13090 let end = Point::new(
13091 s.end.row,
13092 display_map
13093 .buffer_snapshot
13094 .line_len(MultiBufferRow(s.end.row)),
13095 );
13096 Crease::simple(start..end, display_map.fold_placeholder.clone())
13097 } else {
13098 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13099 }
13100 })
13101 .collect::<Vec<_>>();
13102 self.fold_creases(ranges, true, window, cx);
13103 }
13104
13105 pub fn fold_ranges<T: ToOffset + Clone>(
13106 &mut self,
13107 ranges: Vec<Range<T>>,
13108 auto_scroll: bool,
13109 window: &mut Window,
13110 cx: &mut Context<Self>,
13111 ) {
13112 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13113 let ranges = ranges
13114 .into_iter()
13115 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13116 .collect::<Vec<_>>();
13117 self.fold_creases(ranges, auto_scroll, window, cx);
13118 }
13119
13120 pub fn fold_creases<T: ToOffset + Clone>(
13121 &mut self,
13122 creases: Vec<Crease<T>>,
13123 auto_scroll: bool,
13124 window: &mut Window,
13125 cx: &mut Context<Self>,
13126 ) {
13127 if creases.is_empty() {
13128 return;
13129 }
13130
13131 let mut buffers_affected = HashSet::default();
13132 let multi_buffer = self.buffer().read(cx);
13133 for crease in &creases {
13134 if let Some((_, buffer, _)) =
13135 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13136 {
13137 buffers_affected.insert(buffer.read(cx).remote_id());
13138 };
13139 }
13140
13141 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13142
13143 if auto_scroll {
13144 self.request_autoscroll(Autoscroll::fit(), cx);
13145 }
13146
13147 cx.notify();
13148
13149 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13150 // Clear diagnostics block when folding a range that contains it.
13151 let snapshot = self.snapshot(window, cx);
13152 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13153 drop(snapshot);
13154 self.active_diagnostics = Some(active_diagnostics);
13155 self.dismiss_diagnostics(cx);
13156 } else {
13157 self.active_diagnostics = Some(active_diagnostics);
13158 }
13159 }
13160
13161 self.scrollbar_marker_state.dirty = true;
13162 }
13163
13164 /// Removes any folds whose ranges intersect any of the given ranges.
13165 pub fn unfold_ranges<T: ToOffset + Clone>(
13166 &mut self,
13167 ranges: &[Range<T>],
13168 inclusive: bool,
13169 auto_scroll: bool,
13170 cx: &mut Context<Self>,
13171 ) {
13172 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13173 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13174 });
13175 }
13176
13177 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13178 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13179 return;
13180 }
13181 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13182 self.display_map
13183 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13184 cx.emit(EditorEvent::BufferFoldToggled {
13185 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13186 folded: true,
13187 });
13188 cx.notify();
13189 }
13190
13191 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13192 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13193 return;
13194 }
13195 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13196 self.display_map.update(cx, |display_map, cx| {
13197 display_map.unfold_buffer(buffer_id, cx);
13198 });
13199 cx.emit(EditorEvent::BufferFoldToggled {
13200 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13201 folded: false,
13202 });
13203 cx.notify();
13204 }
13205
13206 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13207 self.display_map.read(cx).is_buffer_folded(buffer)
13208 }
13209
13210 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13211 self.display_map.read(cx).folded_buffers()
13212 }
13213
13214 /// Removes any folds with the given ranges.
13215 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13216 &mut self,
13217 ranges: &[Range<T>],
13218 type_id: TypeId,
13219 auto_scroll: bool,
13220 cx: &mut Context<Self>,
13221 ) {
13222 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13223 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13224 });
13225 }
13226
13227 fn remove_folds_with<T: ToOffset + Clone>(
13228 &mut self,
13229 ranges: &[Range<T>],
13230 auto_scroll: bool,
13231 cx: &mut Context<Self>,
13232 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13233 ) {
13234 if ranges.is_empty() {
13235 return;
13236 }
13237
13238 let mut buffers_affected = HashSet::default();
13239 let multi_buffer = self.buffer().read(cx);
13240 for range in ranges {
13241 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13242 buffers_affected.insert(buffer.read(cx).remote_id());
13243 };
13244 }
13245
13246 self.display_map.update(cx, update);
13247
13248 if auto_scroll {
13249 self.request_autoscroll(Autoscroll::fit(), cx);
13250 }
13251
13252 cx.notify();
13253 self.scrollbar_marker_state.dirty = true;
13254 self.active_indent_guides_state.dirty = true;
13255 }
13256
13257 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13258 self.display_map.read(cx).fold_placeholder.clone()
13259 }
13260
13261 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13262 self.buffer.update(cx, |buffer, cx| {
13263 buffer.set_all_diff_hunks_expanded(cx);
13264 });
13265 }
13266
13267 pub fn expand_all_diff_hunks(
13268 &mut self,
13269 _: &ExpandAllDiffHunks,
13270 _window: &mut Window,
13271 cx: &mut Context<Self>,
13272 ) {
13273 self.buffer.update(cx, |buffer, cx| {
13274 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13275 });
13276 }
13277
13278 pub fn toggle_selected_diff_hunks(
13279 &mut self,
13280 _: &ToggleSelectedDiffHunks,
13281 _window: &mut Window,
13282 cx: &mut Context<Self>,
13283 ) {
13284 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13285 self.toggle_diff_hunks_in_ranges(ranges, cx);
13286 }
13287
13288 pub fn diff_hunks_in_ranges<'a>(
13289 &'a self,
13290 ranges: &'a [Range<Anchor>],
13291 buffer: &'a MultiBufferSnapshot,
13292 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13293 ranges.iter().flat_map(move |range| {
13294 let end_excerpt_id = range.end.excerpt_id;
13295 let range = range.to_point(buffer);
13296 let mut peek_end = range.end;
13297 if range.end.row < buffer.max_row().0 {
13298 peek_end = Point::new(range.end.row + 1, 0);
13299 }
13300 buffer
13301 .diff_hunks_in_range(range.start..peek_end)
13302 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13303 })
13304 }
13305
13306 pub fn has_stageable_diff_hunks_in_ranges(
13307 &self,
13308 ranges: &[Range<Anchor>],
13309 snapshot: &MultiBufferSnapshot,
13310 ) -> bool {
13311 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13312 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
13313 }
13314
13315 pub fn toggle_staged_selected_diff_hunks(
13316 &mut self,
13317 _: &::git::ToggleStaged,
13318 _window: &mut Window,
13319 cx: &mut Context<Self>,
13320 ) {
13321 let snapshot = self.buffer.read(cx).snapshot(cx);
13322 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13323 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13324 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13325 }
13326
13327 pub fn stage_and_next(
13328 &mut self,
13329 _: &::git::StageAndNext,
13330 window: &mut Window,
13331 cx: &mut Context<Self>,
13332 ) {
13333 self.do_stage_or_unstage_and_next(true, window, cx);
13334 }
13335
13336 pub fn unstage_and_next(
13337 &mut self,
13338 _: &::git::UnstageAndNext,
13339 window: &mut Window,
13340 cx: &mut Context<Self>,
13341 ) {
13342 self.do_stage_or_unstage_and_next(false, window, cx);
13343 }
13344
13345 pub fn stage_or_unstage_diff_hunks(
13346 &mut self,
13347 stage: bool,
13348 ranges: &[Range<Anchor>],
13349 cx: &mut Context<Self>,
13350 ) {
13351 let snapshot = self.buffer.read(cx).snapshot(cx);
13352 let Some(project) = &self.project else {
13353 return;
13354 };
13355
13356 let chunk_by = self
13357 .diff_hunks_in_ranges(&ranges, &snapshot)
13358 .chunk_by(|hunk| hunk.buffer_id);
13359 for (buffer_id, hunks) in &chunk_by {
13360 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13361 }
13362 }
13363
13364 fn do_stage_or_unstage_and_next(
13365 &mut self,
13366 stage: bool,
13367 window: &mut Window,
13368 cx: &mut Context<Self>,
13369 ) {
13370 let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13371 if ranges.iter().any(|range| range.start != range.end) {
13372 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13373 return;
13374 }
13375
13376 if !self.buffer().read(cx).is_singleton() {
13377 if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13378 if buffer.read(cx).is_empty() {
13379 let buffer = buffer.read(cx);
13380 let Some(file) = buffer.file() else {
13381 return;
13382 };
13383 let project_path = project::ProjectPath {
13384 worktree_id: file.worktree_id(cx),
13385 path: file.path().clone(),
13386 };
13387 let Some(project) = self.project.as_ref() else {
13388 return;
13389 };
13390 let project = project.read(cx);
13391
13392 let Some(repo) = project.git_store().read(cx).active_repository() else {
13393 return;
13394 };
13395
13396 repo.update(cx, |repo, cx| {
13397 let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13398 return;
13399 };
13400 let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13401 return;
13402 };
13403 if stage && status.status == FileStatus::Untracked {
13404 repo.stage_entries(vec![repo_path], cx)
13405 .detach_and_log_err(cx);
13406 return;
13407 }
13408 })
13409 }
13410 ranges = vec![multi_buffer::Anchor::range_in_buffer(
13411 excerpt_id,
13412 buffer.read(cx).remote_id(),
13413 range,
13414 )];
13415 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13416 let snapshot = self.buffer().read(cx).snapshot(cx);
13417 let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13418 if point.row < snapshot.max_row().0 {
13419 point.row += 1;
13420 point.column = 0;
13421 point = snapshot.clip_point(point, Bias::Right);
13422 self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13423 s.select_ranges([point..point]);
13424 })
13425 }
13426 return;
13427 }
13428 }
13429 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13430 self.go_to_next_hunk(&Default::default(), window, cx);
13431 }
13432
13433 fn do_stage_or_unstage(
13434 project: &Entity<Project>,
13435 stage: bool,
13436 buffer_id: BufferId,
13437 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13438 snapshot: &MultiBufferSnapshot,
13439 cx: &mut Context<Self>,
13440 ) {
13441 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13442 log::debug!("no buffer for id");
13443 return;
13444 };
13445 let buffer_snapshot = buffer.read(cx).snapshot();
13446 let Some((repo, path)) = project
13447 .read(cx)
13448 .repository_and_path_for_buffer_id(buffer_id, cx)
13449 else {
13450 log::debug!("no git repo for buffer id");
13451 return;
13452 };
13453 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13454 log::debug!("no diff for buffer id");
13455 return;
13456 };
13457 let Some(secondary_diff) = diff.secondary_diff() else {
13458 log::debug!("no secondary diff for buffer id");
13459 return;
13460 };
13461
13462 let edits = diff.secondary_edits_for_stage_or_unstage(
13463 stage,
13464 hunks.filter_map(|hunk| {
13465 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13466 return None;
13467 } else if !stage
13468 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13469 {
13470 return None;
13471 }
13472 Some((
13473 hunk.diff_base_byte_range.clone(),
13474 hunk.secondary_diff_base_byte_range.clone(),
13475 hunk.buffer_range.clone(),
13476 ))
13477 }),
13478 &buffer_snapshot,
13479 );
13480
13481 let Some(index_base) = secondary_diff
13482 .base_text()
13483 .map(|snapshot| snapshot.text.as_rope().clone())
13484 else {
13485 log::debug!("no index base");
13486 return;
13487 };
13488 let index_buffer = cx.new(|cx| {
13489 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
13490 });
13491 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
13492 index_buffer.edit(edits, None, cx);
13493 index_buffer.snapshot().as_rope().to_string()
13494 });
13495 let new_index_text = if new_index_text.is_empty()
13496 && !stage
13497 && (diff.is_single_insertion
13498 || buffer_snapshot
13499 .file()
13500 .map_or(false, |file| file.disk_state() == DiskState::New))
13501 {
13502 log::debug!("removing from index");
13503 None
13504 } else {
13505 Some(new_index_text)
13506 };
13507 let buffer_store = project.read(cx).buffer_store().clone();
13508 buffer_store
13509 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13510 .detach_and_log_err(cx);
13511
13512 cx.background_spawn(
13513 repo.read(cx)
13514 .set_index_text(&path, new_index_text)
13515 .log_err(),
13516 )
13517 .detach();
13518 }
13519
13520 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13521 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13522 self.buffer
13523 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13524 }
13525
13526 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13527 self.buffer.update(cx, |buffer, cx| {
13528 let ranges = vec![Anchor::min()..Anchor::max()];
13529 if !buffer.all_diff_hunks_expanded()
13530 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13531 {
13532 buffer.collapse_diff_hunks(ranges, cx);
13533 true
13534 } else {
13535 false
13536 }
13537 })
13538 }
13539
13540 fn toggle_diff_hunks_in_ranges(
13541 &mut self,
13542 ranges: Vec<Range<Anchor>>,
13543 cx: &mut Context<'_, Editor>,
13544 ) {
13545 self.buffer.update(cx, |buffer, cx| {
13546 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13547 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13548 })
13549 }
13550
13551 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13552 self.buffer.update(cx, |buffer, cx| {
13553 let snapshot = buffer.snapshot(cx);
13554 let excerpt_id = range.end.excerpt_id;
13555 let point_range = range.to_point(&snapshot);
13556 let expand = !buffer.single_hunk_is_expanded(range, cx);
13557 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13558 })
13559 }
13560
13561 pub(crate) fn apply_all_diff_hunks(
13562 &mut self,
13563 _: &ApplyAllDiffHunks,
13564 window: &mut Window,
13565 cx: &mut Context<Self>,
13566 ) {
13567 let buffers = self.buffer.read(cx).all_buffers();
13568 for branch_buffer in buffers {
13569 branch_buffer.update(cx, |branch_buffer, cx| {
13570 branch_buffer.merge_into_base(Vec::new(), cx);
13571 });
13572 }
13573
13574 if let Some(project) = self.project.clone() {
13575 self.save(true, project, window, cx).detach_and_log_err(cx);
13576 }
13577 }
13578
13579 pub(crate) fn apply_selected_diff_hunks(
13580 &mut self,
13581 _: &ApplyDiffHunk,
13582 window: &mut Window,
13583 cx: &mut Context<Self>,
13584 ) {
13585 let snapshot = self.snapshot(window, cx);
13586 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13587 let mut ranges_by_buffer = HashMap::default();
13588 self.transact(window, cx, |editor, _window, cx| {
13589 for hunk in hunks {
13590 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13591 ranges_by_buffer
13592 .entry(buffer.clone())
13593 .or_insert_with(Vec::new)
13594 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13595 }
13596 }
13597
13598 for (buffer, ranges) in ranges_by_buffer {
13599 buffer.update(cx, |buffer, cx| {
13600 buffer.merge_into_base(ranges, cx);
13601 });
13602 }
13603 });
13604
13605 if let Some(project) = self.project.clone() {
13606 self.save(true, project, window, cx).detach_and_log_err(cx);
13607 }
13608 }
13609
13610 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13611 if hovered != self.gutter_hovered {
13612 self.gutter_hovered = hovered;
13613 cx.notify();
13614 }
13615 }
13616
13617 pub fn insert_blocks(
13618 &mut self,
13619 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13620 autoscroll: Option<Autoscroll>,
13621 cx: &mut Context<Self>,
13622 ) -> Vec<CustomBlockId> {
13623 let blocks = self
13624 .display_map
13625 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13626 if let Some(autoscroll) = autoscroll {
13627 self.request_autoscroll(autoscroll, cx);
13628 }
13629 cx.notify();
13630 blocks
13631 }
13632
13633 pub fn resize_blocks(
13634 &mut self,
13635 heights: HashMap<CustomBlockId, u32>,
13636 autoscroll: Option<Autoscroll>,
13637 cx: &mut Context<Self>,
13638 ) {
13639 self.display_map
13640 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13641 if let Some(autoscroll) = autoscroll {
13642 self.request_autoscroll(autoscroll, cx);
13643 }
13644 cx.notify();
13645 }
13646
13647 pub fn replace_blocks(
13648 &mut self,
13649 renderers: HashMap<CustomBlockId, RenderBlock>,
13650 autoscroll: Option<Autoscroll>,
13651 cx: &mut Context<Self>,
13652 ) {
13653 self.display_map
13654 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13655 if let Some(autoscroll) = autoscroll {
13656 self.request_autoscroll(autoscroll, cx);
13657 }
13658 cx.notify();
13659 }
13660
13661 pub fn remove_blocks(
13662 &mut self,
13663 block_ids: HashSet<CustomBlockId>,
13664 autoscroll: Option<Autoscroll>,
13665 cx: &mut Context<Self>,
13666 ) {
13667 self.display_map.update(cx, |display_map, cx| {
13668 display_map.remove_blocks(block_ids, cx)
13669 });
13670 if let Some(autoscroll) = autoscroll {
13671 self.request_autoscroll(autoscroll, cx);
13672 }
13673 cx.notify();
13674 }
13675
13676 pub fn row_for_block(
13677 &self,
13678 block_id: CustomBlockId,
13679 cx: &mut Context<Self>,
13680 ) -> Option<DisplayRow> {
13681 self.display_map
13682 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13683 }
13684
13685 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13686 self.focused_block = Some(focused_block);
13687 }
13688
13689 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13690 self.focused_block.take()
13691 }
13692
13693 pub fn insert_creases(
13694 &mut self,
13695 creases: impl IntoIterator<Item = Crease<Anchor>>,
13696 cx: &mut Context<Self>,
13697 ) -> Vec<CreaseId> {
13698 self.display_map
13699 .update(cx, |map, cx| map.insert_creases(creases, cx))
13700 }
13701
13702 pub fn remove_creases(
13703 &mut self,
13704 ids: impl IntoIterator<Item = CreaseId>,
13705 cx: &mut Context<Self>,
13706 ) {
13707 self.display_map
13708 .update(cx, |map, cx| map.remove_creases(ids, cx));
13709 }
13710
13711 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13712 self.display_map
13713 .update(cx, |map, cx| map.snapshot(cx))
13714 .longest_row()
13715 }
13716
13717 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13718 self.display_map
13719 .update(cx, |map, cx| map.snapshot(cx))
13720 .max_point()
13721 }
13722
13723 pub fn text(&self, cx: &App) -> String {
13724 self.buffer.read(cx).read(cx).text()
13725 }
13726
13727 pub fn is_empty(&self, cx: &App) -> bool {
13728 self.buffer.read(cx).read(cx).is_empty()
13729 }
13730
13731 pub fn text_option(&self, cx: &App) -> Option<String> {
13732 let text = self.text(cx);
13733 let text = text.trim();
13734
13735 if text.is_empty() {
13736 return None;
13737 }
13738
13739 Some(text.to_string())
13740 }
13741
13742 pub fn set_text(
13743 &mut self,
13744 text: impl Into<Arc<str>>,
13745 window: &mut Window,
13746 cx: &mut Context<Self>,
13747 ) {
13748 self.transact(window, cx, |this, _, cx| {
13749 this.buffer
13750 .read(cx)
13751 .as_singleton()
13752 .expect("you can only call set_text on editors for singleton buffers")
13753 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13754 });
13755 }
13756
13757 pub fn display_text(&self, cx: &mut App) -> String {
13758 self.display_map
13759 .update(cx, |map, cx| map.snapshot(cx))
13760 .text()
13761 }
13762
13763 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13764 let mut wrap_guides = smallvec::smallvec![];
13765
13766 if self.show_wrap_guides == Some(false) {
13767 return wrap_guides;
13768 }
13769
13770 let settings = self.buffer.read(cx).settings_at(0, cx);
13771 if settings.show_wrap_guides {
13772 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13773 wrap_guides.push((soft_wrap as usize, true));
13774 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13775 wrap_guides.push((soft_wrap as usize, true));
13776 }
13777 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13778 }
13779
13780 wrap_guides
13781 }
13782
13783 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13784 let settings = self.buffer.read(cx).settings_at(0, cx);
13785 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13786 match mode {
13787 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13788 SoftWrap::None
13789 }
13790 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13791 language_settings::SoftWrap::PreferredLineLength => {
13792 SoftWrap::Column(settings.preferred_line_length)
13793 }
13794 language_settings::SoftWrap::Bounded => {
13795 SoftWrap::Bounded(settings.preferred_line_length)
13796 }
13797 }
13798 }
13799
13800 pub fn set_soft_wrap_mode(
13801 &mut self,
13802 mode: language_settings::SoftWrap,
13803
13804 cx: &mut Context<Self>,
13805 ) {
13806 self.soft_wrap_mode_override = Some(mode);
13807 cx.notify();
13808 }
13809
13810 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13811 self.text_style_refinement = Some(style);
13812 }
13813
13814 /// called by the Element so we know what style we were most recently rendered with.
13815 pub(crate) fn set_style(
13816 &mut self,
13817 style: EditorStyle,
13818 window: &mut Window,
13819 cx: &mut Context<Self>,
13820 ) {
13821 let rem_size = window.rem_size();
13822 self.display_map.update(cx, |map, cx| {
13823 map.set_font(
13824 style.text.font(),
13825 style.text.font_size.to_pixels(rem_size),
13826 cx,
13827 )
13828 });
13829 self.style = Some(style);
13830 }
13831
13832 pub fn style(&self) -> Option<&EditorStyle> {
13833 self.style.as_ref()
13834 }
13835
13836 // Called by the element. This method is not designed to be called outside of the editor
13837 // element's layout code because it does not notify when rewrapping is computed synchronously.
13838 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13839 self.display_map
13840 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13841 }
13842
13843 pub fn set_soft_wrap(&mut self) {
13844 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13845 }
13846
13847 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13848 if self.soft_wrap_mode_override.is_some() {
13849 self.soft_wrap_mode_override.take();
13850 } else {
13851 let soft_wrap = match self.soft_wrap_mode(cx) {
13852 SoftWrap::GitDiff => return,
13853 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13854 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13855 language_settings::SoftWrap::None
13856 }
13857 };
13858 self.soft_wrap_mode_override = Some(soft_wrap);
13859 }
13860 cx.notify();
13861 }
13862
13863 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13864 let Some(workspace) = self.workspace() else {
13865 return;
13866 };
13867 let fs = workspace.read(cx).app_state().fs.clone();
13868 let current_show = TabBarSettings::get_global(cx).show;
13869 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13870 setting.show = Some(!current_show);
13871 });
13872 }
13873
13874 pub fn toggle_indent_guides(
13875 &mut self,
13876 _: &ToggleIndentGuides,
13877 _: &mut Window,
13878 cx: &mut Context<Self>,
13879 ) {
13880 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13881 self.buffer
13882 .read(cx)
13883 .settings_at(0, cx)
13884 .indent_guides
13885 .enabled
13886 });
13887 self.show_indent_guides = Some(!currently_enabled);
13888 cx.notify();
13889 }
13890
13891 fn should_show_indent_guides(&self) -> Option<bool> {
13892 self.show_indent_guides
13893 }
13894
13895 pub fn toggle_line_numbers(
13896 &mut self,
13897 _: &ToggleLineNumbers,
13898 _: &mut Window,
13899 cx: &mut Context<Self>,
13900 ) {
13901 let mut editor_settings = EditorSettings::get_global(cx).clone();
13902 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13903 EditorSettings::override_global(editor_settings, cx);
13904 }
13905
13906 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13907 self.use_relative_line_numbers
13908 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13909 }
13910
13911 pub fn toggle_relative_line_numbers(
13912 &mut self,
13913 _: &ToggleRelativeLineNumbers,
13914 _: &mut Window,
13915 cx: &mut Context<Self>,
13916 ) {
13917 let is_relative = self.should_use_relative_line_numbers(cx);
13918 self.set_relative_line_number(Some(!is_relative), cx)
13919 }
13920
13921 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13922 self.use_relative_line_numbers = is_relative;
13923 cx.notify();
13924 }
13925
13926 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13927 self.show_gutter = show_gutter;
13928 cx.notify();
13929 }
13930
13931 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13932 self.show_scrollbars = show_scrollbars;
13933 cx.notify();
13934 }
13935
13936 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13937 self.show_line_numbers = Some(show_line_numbers);
13938 cx.notify();
13939 }
13940
13941 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13942 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13943 cx.notify();
13944 }
13945
13946 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13947 self.show_code_actions = Some(show_code_actions);
13948 cx.notify();
13949 }
13950
13951 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13952 self.show_runnables = Some(show_runnables);
13953 cx.notify();
13954 }
13955
13956 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13957 if self.display_map.read(cx).masked != masked {
13958 self.display_map.update(cx, |map, _| map.masked = masked);
13959 }
13960 cx.notify()
13961 }
13962
13963 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13964 self.show_wrap_guides = Some(show_wrap_guides);
13965 cx.notify();
13966 }
13967
13968 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13969 self.show_indent_guides = Some(show_indent_guides);
13970 cx.notify();
13971 }
13972
13973 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13974 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13975 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13976 if let Some(dir) = file.abs_path(cx).parent() {
13977 return Some(dir.to_owned());
13978 }
13979 }
13980
13981 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13982 return Some(project_path.path.to_path_buf());
13983 }
13984 }
13985
13986 None
13987 }
13988
13989 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13990 self.active_excerpt(cx)?
13991 .1
13992 .read(cx)
13993 .file()
13994 .and_then(|f| f.as_local())
13995 }
13996
13997 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13998 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13999 let buffer = buffer.read(cx);
14000 if let Some(project_path) = buffer.project_path(cx) {
14001 let project = self.project.as_ref()?.read(cx);
14002 project.absolute_path(&project_path, cx)
14003 } else {
14004 buffer
14005 .file()
14006 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14007 }
14008 })
14009 }
14010
14011 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14012 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14013 let project_path = buffer.read(cx).project_path(cx)?;
14014 let project = self.project.as_ref()?.read(cx);
14015 let entry = project.entry_for_path(&project_path, cx)?;
14016 let path = entry.path.to_path_buf();
14017 Some(path)
14018 })
14019 }
14020
14021 pub fn reveal_in_finder(
14022 &mut self,
14023 _: &RevealInFileManager,
14024 _window: &mut Window,
14025 cx: &mut Context<Self>,
14026 ) {
14027 if let Some(target) = self.target_file(cx) {
14028 cx.reveal_path(&target.abs_path(cx));
14029 }
14030 }
14031
14032 pub fn copy_path(
14033 &mut self,
14034 _: &zed_actions::workspace::CopyPath,
14035 _window: &mut Window,
14036 cx: &mut Context<Self>,
14037 ) {
14038 if let Some(path) = self.target_file_abs_path(cx) {
14039 if let Some(path) = path.to_str() {
14040 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14041 }
14042 }
14043 }
14044
14045 pub fn copy_relative_path(
14046 &mut self,
14047 _: &zed_actions::workspace::CopyRelativePath,
14048 _window: &mut Window,
14049 cx: &mut Context<Self>,
14050 ) {
14051 if let Some(path) = self.target_file_path(cx) {
14052 if let Some(path) = path.to_str() {
14053 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14054 }
14055 }
14056 }
14057
14058 pub fn copy_file_name_without_extension(
14059 &mut self,
14060 _: &CopyFileNameWithoutExtension,
14061 _: &mut Window,
14062 cx: &mut Context<Self>,
14063 ) {
14064 if let Some(file) = self.target_file(cx) {
14065 if let Some(file_stem) = file.path().file_stem() {
14066 if let Some(name) = file_stem.to_str() {
14067 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14068 }
14069 }
14070 }
14071 }
14072
14073 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14074 if let Some(file) = self.target_file(cx) {
14075 if let Some(file_name) = file.path().file_name() {
14076 if let Some(name) = file_name.to_str() {
14077 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14078 }
14079 }
14080 }
14081 }
14082
14083 pub fn toggle_git_blame(
14084 &mut self,
14085 _: &ToggleGitBlame,
14086 window: &mut Window,
14087 cx: &mut Context<Self>,
14088 ) {
14089 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14090
14091 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14092 self.start_git_blame(true, window, cx);
14093 }
14094
14095 cx.notify();
14096 }
14097
14098 pub fn toggle_git_blame_inline(
14099 &mut self,
14100 _: &ToggleGitBlameInline,
14101 window: &mut Window,
14102 cx: &mut Context<Self>,
14103 ) {
14104 self.toggle_git_blame_inline_internal(true, window, cx);
14105 cx.notify();
14106 }
14107
14108 pub fn git_blame_inline_enabled(&self) -> bool {
14109 self.git_blame_inline_enabled
14110 }
14111
14112 pub fn toggle_selection_menu(
14113 &mut self,
14114 _: &ToggleSelectionMenu,
14115 _: &mut Window,
14116 cx: &mut Context<Self>,
14117 ) {
14118 self.show_selection_menu = self
14119 .show_selection_menu
14120 .map(|show_selections_menu| !show_selections_menu)
14121 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14122
14123 cx.notify();
14124 }
14125
14126 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14127 self.show_selection_menu
14128 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14129 }
14130
14131 fn start_git_blame(
14132 &mut self,
14133 user_triggered: bool,
14134 window: &mut Window,
14135 cx: &mut Context<Self>,
14136 ) {
14137 if let Some(project) = self.project.as_ref() {
14138 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14139 return;
14140 };
14141
14142 if buffer.read(cx).file().is_none() {
14143 return;
14144 }
14145
14146 let focused = self.focus_handle(cx).contains_focused(window, cx);
14147
14148 let project = project.clone();
14149 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14150 self.blame_subscription =
14151 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14152 self.blame = Some(blame);
14153 }
14154 }
14155
14156 fn toggle_git_blame_inline_internal(
14157 &mut self,
14158 user_triggered: bool,
14159 window: &mut Window,
14160 cx: &mut Context<Self>,
14161 ) {
14162 if self.git_blame_inline_enabled {
14163 self.git_blame_inline_enabled = false;
14164 self.show_git_blame_inline = false;
14165 self.show_git_blame_inline_delay_task.take();
14166 } else {
14167 self.git_blame_inline_enabled = true;
14168 self.start_git_blame_inline(user_triggered, window, cx);
14169 }
14170
14171 cx.notify();
14172 }
14173
14174 fn start_git_blame_inline(
14175 &mut self,
14176 user_triggered: bool,
14177 window: &mut Window,
14178 cx: &mut Context<Self>,
14179 ) {
14180 self.start_git_blame(user_triggered, window, cx);
14181
14182 if ProjectSettings::get_global(cx)
14183 .git
14184 .inline_blame_delay()
14185 .is_some()
14186 {
14187 self.start_inline_blame_timer(window, cx);
14188 } else {
14189 self.show_git_blame_inline = true
14190 }
14191 }
14192
14193 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14194 self.blame.as_ref()
14195 }
14196
14197 pub fn show_git_blame_gutter(&self) -> bool {
14198 self.show_git_blame_gutter
14199 }
14200
14201 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14202 self.show_git_blame_gutter && self.has_blame_entries(cx)
14203 }
14204
14205 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14206 self.show_git_blame_inline
14207 && (self.focus_handle.is_focused(window)
14208 || self
14209 .git_blame_inline_tooltip
14210 .as_ref()
14211 .and_then(|t| t.upgrade())
14212 .is_some())
14213 && !self.newest_selection_head_on_empty_line(cx)
14214 && self.has_blame_entries(cx)
14215 }
14216
14217 fn has_blame_entries(&self, cx: &App) -> bool {
14218 self.blame()
14219 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14220 }
14221
14222 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14223 let cursor_anchor = self.selections.newest_anchor().head();
14224
14225 let snapshot = self.buffer.read(cx).snapshot(cx);
14226 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14227
14228 snapshot.line_len(buffer_row) == 0
14229 }
14230
14231 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14232 let buffer_and_selection = maybe!({
14233 let selection = self.selections.newest::<Point>(cx);
14234 let selection_range = selection.range();
14235
14236 let multi_buffer = self.buffer().read(cx);
14237 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14238 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14239
14240 let (buffer, range, _) = if selection.reversed {
14241 buffer_ranges.first()
14242 } else {
14243 buffer_ranges.last()
14244 }?;
14245
14246 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14247 ..text::ToPoint::to_point(&range.end, &buffer).row;
14248 Some((
14249 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14250 selection,
14251 ))
14252 });
14253
14254 let Some((buffer, selection)) = buffer_and_selection else {
14255 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14256 };
14257
14258 let Some(project) = self.project.as_ref() else {
14259 return Task::ready(Err(anyhow!("editor does not have project")));
14260 };
14261
14262 project.update(cx, |project, cx| {
14263 project.get_permalink_to_line(&buffer, selection, cx)
14264 })
14265 }
14266
14267 pub fn copy_permalink_to_line(
14268 &mut self,
14269 _: &CopyPermalinkToLine,
14270 window: &mut Window,
14271 cx: &mut Context<Self>,
14272 ) {
14273 let permalink_task = self.get_permalink_to_line(cx);
14274 let workspace = self.workspace();
14275
14276 cx.spawn_in(window, |_, mut cx| async move {
14277 match permalink_task.await {
14278 Ok(permalink) => {
14279 cx.update(|_, cx| {
14280 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14281 })
14282 .ok();
14283 }
14284 Err(err) => {
14285 let message = format!("Failed to copy permalink: {err}");
14286
14287 Err::<(), anyhow::Error>(err).log_err();
14288
14289 if let Some(workspace) = workspace {
14290 workspace
14291 .update_in(&mut cx, |workspace, _, cx| {
14292 struct CopyPermalinkToLine;
14293
14294 workspace.show_toast(
14295 Toast::new(
14296 NotificationId::unique::<CopyPermalinkToLine>(),
14297 message,
14298 ),
14299 cx,
14300 )
14301 })
14302 .ok();
14303 }
14304 }
14305 }
14306 })
14307 .detach();
14308 }
14309
14310 pub fn copy_file_location(
14311 &mut self,
14312 _: &CopyFileLocation,
14313 _: &mut Window,
14314 cx: &mut Context<Self>,
14315 ) {
14316 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14317 if let Some(file) = self.target_file(cx) {
14318 if let Some(path) = file.path().to_str() {
14319 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14320 }
14321 }
14322 }
14323
14324 pub fn open_permalink_to_line(
14325 &mut self,
14326 _: &OpenPermalinkToLine,
14327 window: &mut Window,
14328 cx: &mut Context<Self>,
14329 ) {
14330 let permalink_task = self.get_permalink_to_line(cx);
14331 let workspace = self.workspace();
14332
14333 cx.spawn_in(window, |_, mut cx| async move {
14334 match permalink_task.await {
14335 Ok(permalink) => {
14336 cx.update(|_, cx| {
14337 cx.open_url(permalink.as_ref());
14338 })
14339 .ok();
14340 }
14341 Err(err) => {
14342 let message = format!("Failed to open permalink: {err}");
14343
14344 Err::<(), anyhow::Error>(err).log_err();
14345
14346 if let Some(workspace) = workspace {
14347 workspace
14348 .update(&mut cx, |workspace, cx| {
14349 struct OpenPermalinkToLine;
14350
14351 workspace.show_toast(
14352 Toast::new(
14353 NotificationId::unique::<OpenPermalinkToLine>(),
14354 message,
14355 ),
14356 cx,
14357 )
14358 })
14359 .ok();
14360 }
14361 }
14362 }
14363 })
14364 .detach();
14365 }
14366
14367 pub fn insert_uuid_v4(
14368 &mut self,
14369 _: &InsertUuidV4,
14370 window: &mut Window,
14371 cx: &mut Context<Self>,
14372 ) {
14373 self.insert_uuid(UuidVersion::V4, window, cx);
14374 }
14375
14376 pub fn insert_uuid_v7(
14377 &mut self,
14378 _: &InsertUuidV7,
14379 window: &mut Window,
14380 cx: &mut Context<Self>,
14381 ) {
14382 self.insert_uuid(UuidVersion::V7, window, cx);
14383 }
14384
14385 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14386 self.transact(window, cx, |this, window, cx| {
14387 let edits = this
14388 .selections
14389 .all::<Point>(cx)
14390 .into_iter()
14391 .map(|selection| {
14392 let uuid = match version {
14393 UuidVersion::V4 => uuid::Uuid::new_v4(),
14394 UuidVersion::V7 => uuid::Uuid::now_v7(),
14395 };
14396
14397 (selection.range(), uuid.to_string())
14398 });
14399 this.edit(edits, cx);
14400 this.refresh_inline_completion(true, false, window, cx);
14401 });
14402 }
14403
14404 pub fn open_selections_in_multibuffer(
14405 &mut self,
14406 _: &OpenSelectionsInMultibuffer,
14407 window: &mut Window,
14408 cx: &mut Context<Self>,
14409 ) {
14410 let multibuffer = self.buffer.read(cx);
14411
14412 let Some(buffer) = multibuffer.as_singleton() else {
14413 return;
14414 };
14415
14416 let Some(workspace) = self.workspace() else {
14417 return;
14418 };
14419
14420 let locations = self
14421 .selections
14422 .disjoint_anchors()
14423 .iter()
14424 .map(|range| Location {
14425 buffer: buffer.clone(),
14426 range: range.start.text_anchor..range.end.text_anchor,
14427 })
14428 .collect::<Vec<_>>();
14429
14430 let title = multibuffer.title(cx).to_string();
14431
14432 cx.spawn_in(window, |_, mut cx| async move {
14433 workspace.update_in(&mut cx, |workspace, window, cx| {
14434 Self::open_locations_in_multibuffer(
14435 workspace,
14436 locations,
14437 format!("Selections for '{title}'"),
14438 false,
14439 MultibufferSelectionMode::All,
14440 window,
14441 cx,
14442 );
14443 })
14444 })
14445 .detach();
14446 }
14447
14448 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14449 /// last highlight added will be used.
14450 ///
14451 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14452 pub fn highlight_rows<T: 'static>(
14453 &mut self,
14454 range: Range<Anchor>,
14455 color: Hsla,
14456 should_autoscroll: bool,
14457 cx: &mut Context<Self>,
14458 ) {
14459 let snapshot = self.buffer().read(cx).snapshot(cx);
14460 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14461 let ix = row_highlights.binary_search_by(|highlight| {
14462 Ordering::Equal
14463 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14464 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14465 });
14466
14467 if let Err(mut ix) = ix {
14468 let index = post_inc(&mut self.highlight_order);
14469
14470 // If this range intersects with the preceding highlight, then merge it with
14471 // the preceding highlight. Otherwise insert a new highlight.
14472 let mut merged = false;
14473 if ix > 0 {
14474 let prev_highlight = &mut row_highlights[ix - 1];
14475 if prev_highlight
14476 .range
14477 .end
14478 .cmp(&range.start, &snapshot)
14479 .is_ge()
14480 {
14481 ix -= 1;
14482 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14483 prev_highlight.range.end = range.end;
14484 }
14485 merged = true;
14486 prev_highlight.index = index;
14487 prev_highlight.color = color;
14488 prev_highlight.should_autoscroll = should_autoscroll;
14489 }
14490 }
14491
14492 if !merged {
14493 row_highlights.insert(
14494 ix,
14495 RowHighlight {
14496 range: range.clone(),
14497 index,
14498 color,
14499 should_autoscroll,
14500 },
14501 );
14502 }
14503
14504 // If any of the following highlights intersect with this one, merge them.
14505 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14506 let highlight = &row_highlights[ix];
14507 if next_highlight
14508 .range
14509 .start
14510 .cmp(&highlight.range.end, &snapshot)
14511 .is_le()
14512 {
14513 if next_highlight
14514 .range
14515 .end
14516 .cmp(&highlight.range.end, &snapshot)
14517 .is_gt()
14518 {
14519 row_highlights[ix].range.end = next_highlight.range.end;
14520 }
14521 row_highlights.remove(ix + 1);
14522 } else {
14523 break;
14524 }
14525 }
14526 }
14527 }
14528
14529 /// Remove any highlighted row ranges of the given type that intersect the
14530 /// given ranges.
14531 pub fn remove_highlighted_rows<T: 'static>(
14532 &mut self,
14533 ranges_to_remove: Vec<Range<Anchor>>,
14534 cx: &mut Context<Self>,
14535 ) {
14536 let snapshot = self.buffer().read(cx).snapshot(cx);
14537 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14538 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14539 row_highlights.retain(|highlight| {
14540 while let Some(range_to_remove) = ranges_to_remove.peek() {
14541 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14542 Ordering::Less | Ordering::Equal => {
14543 ranges_to_remove.next();
14544 }
14545 Ordering::Greater => {
14546 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14547 Ordering::Less | Ordering::Equal => {
14548 return false;
14549 }
14550 Ordering::Greater => break,
14551 }
14552 }
14553 }
14554 }
14555
14556 true
14557 })
14558 }
14559
14560 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14561 pub fn clear_row_highlights<T: 'static>(&mut self) {
14562 self.highlighted_rows.remove(&TypeId::of::<T>());
14563 }
14564
14565 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14566 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14567 self.highlighted_rows
14568 .get(&TypeId::of::<T>())
14569 .map_or(&[] as &[_], |vec| vec.as_slice())
14570 .iter()
14571 .map(|highlight| (highlight.range.clone(), highlight.color))
14572 }
14573
14574 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14575 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14576 /// Allows to ignore certain kinds of highlights.
14577 pub fn highlighted_display_rows(
14578 &self,
14579 window: &mut Window,
14580 cx: &mut App,
14581 ) -> BTreeMap<DisplayRow, Background> {
14582 let snapshot = self.snapshot(window, cx);
14583 let mut used_highlight_orders = HashMap::default();
14584 self.highlighted_rows
14585 .iter()
14586 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14587 .fold(
14588 BTreeMap::<DisplayRow, Background>::new(),
14589 |mut unique_rows, highlight| {
14590 let start = highlight.range.start.to_display_point(&snapshot);
14591 let end = highlight.range.end.to_display_point(&snapshot);
14592 let start_row = start.row().0;
14593 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14594 && end.column() == 0
14595 {
14596 end.row().0.saturating_sub(1)
14597 } else {
14598 end.row().0
14599 };
14600 for row in start_row..=end_row {
14601 let used_index =
14602 used_highlight_orders.entry(row).or_insert(highlight.index);
14603 if highlight.index >= *used_index {
14604 *used_index = highlight.index;
14605 unique_rows.insert(DisplayRow(row), highlight.color.into());
14606 }
14607 }
14608 unique_rows
14609 },
14610 )
14611 }
14612
14613 pub fn highlighted_display_row_for_autoscroll(
14614 &self,
14615 snapshot: &DisplaySnapshot,
14616 ) -> Option<DisplayRow> {
14617 self.highlighted_rows
14618 .values()
14619 .flat_map(|highlighted_rows| highlighted_rows.iter())
14620 .filter_map(|highlight| {
14621 if highlight.should_autoscroll {
14622 Some(highlight.range.start.to_display_point(snapshot).row())
14623 } else {
14624 None
14625 }
14626 })
14627 .min()
14628 }
14629
14630 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14631 self.highlight_background::<SearchWithinRange>(
14632 ranges,
14633 |colors| colors.editor_document_highlight_read_background,
14634 cx,
14635 )
14636 }
14637
14638 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14639 self.breadcrumb_header = Some(new_header);
14640 }
14641
14642 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14643 self.clear_background_highlights::<SearchWithinRange>(cx);
14644 }
14645
14646 pub fn highlight_background<T: 'static>(
14647 &mut self,
14648 ranges: &[Range<Anchor>],
14649 color_fetcher: fn(&ThemeColors) -> Hsla,
14650 cx: &mut Context<Self>,
14651 ) {
14652 self.background_highlights
14653 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14654 self.scrollbar_marker_state.dirty = true;
14655 cx.notify();
14656 }
14657
14658 pub fn clear_background_highlights<T: 'static>(
14659 &mut self,
14660 cx: &mut Context<Self>,
14661 ) -> Option<BackgroundHighlight> {
14662 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14663 if !text_highlights.1.is_empty() {
14664 self.scrollbar_marker_state.dirty = true;
14665 cx.notify();
14666 }
14667 Some(text_highlights)
14668 }
14669
14670 pub fn highlight_gutter<T: 'static>(
14671 &mut self,
14672 ranges: &[Range<Anchor>],
14673 color_fetcher: fn(&App) -> Hsla,
14674 cx: &mut Context<Self>,
14675 ) {
14676 self.gutter_highlights
14677 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14678 cx.notify();
14679 }
14680
14681 pub fn clear_gutter_highlights<T: 'static>(
14682 &mut self,
14683 cx: &mut Context<Self>,
14684 ) -> Option<GutterHighlight> {
14685 cx.notify();
14686 self.gutter_highlights.remove(&TypeId::of::<T>())
14687 }
14688
14689 #[cfg(feature = "test-support")]
14690 pub fn all_text_background_highlights(
14691 &self,
14692 window: &mut Window,
14693 cx: &mut Context<Self>,
14694 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14695 let snapshot = self.snapshot(window, cx);
14696 let buffer = &snapshot.buffer_snapshot;
14697 let start = buffer.anchor_before(0);
14698 let end = buffer.anchor_after(buffer.len());
14699 let theme = cx.theme().colors();
14700 self.background_highlights_in_range(start..end, &snapshot, theme)
14701 }
14702
14703 #[cfg(feature = "test-support")]
14704 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14705 let snapshot = self.buffer().read(cx).snapshot(cx);
14706
14707 let highlights = self
14708 .background_highlights
14709 .get(&TypeId::of::<items::BufferSearchHighlights>());
14710
14711 if let Some((_color, ranges)) = highlights {
14712 ranges
14713 .iter()
14714 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14715 .collect_vec()
14716 } else {
14717 vec![]
14718 }
14719 }
14720
14721 fn document_highlights_for_position<'a>(
14722 &'a self,
14723 position: Anchor,
14724 buffer: &'a MultiBufferSnapshot,
14725 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14726 let read_highlights = self
14727 .background_highlights
14728 .get(&TypeId::of::<DocumentHighlightRead>())
14729 .map(|h| &h.1);
14730 let write_highlights = self
14731 .background_highlights
14732 .get(&TypeId::of::<DocumentHighlightWrite>())
14733 .map(|h| &h.1);
14734 let left_position = position.bias_left(buffer);
14735 let right_position = position.bias_right(buffer);
14736 read_highlights
14737 .into_iter()
14738 .chain(write_highlights)
14739 .flat_map(move |ranges| {
14740 let start_ix = match ranges.binary_search_by(|probe| {
14741 let cmp = probe.end.cmp(&left_position, buffer);
14742 if cmp.is_ge() {
14743 Ordering::Greater
14744 } else {
14745 Ordering::Less
14746 }
14747 }) {
14748 Ok(i) | Err(i) => i,
14749 };
14750
14751 ranges[start_ix..]
14752 .iter()
14753 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14754 })
14755 }
14756
14757 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14758 self.background_highlights
14759 .get(&TypeId::of::<T>())
14760 .map_or(false, |(_, highlights)| !highlights.is_empty())
14761 }
14762
14763 pub fn background_highlights_in_range(
14764 &self,
14765 search_range: Range<Anchor>,
14766 display_snapshot: &DisplaySnapshot,
14767 theme: &ThemeColors,
14768 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14769 let mut results = Vec::new();
14770 for (color_fetcher, ranges) in self.background_highlights.values() {
14771 let color = color_fetcher(theme);
14772 let start_ix = match ranges.binary_search_by(|probe| {
14773 let cmp = probe
14774 .end
14775 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14776 if cmp.is_gt() {
14777 Ordering::Greater
14778 } else {
14779 Ordering::Less
14780 }
14781 }) {
14782 Ok(i) | Err(i) => i,
14783 };
14784 for range in &ranges[start_ix..] {
14785 if range
14786 .start
14787 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14788 .is_ge()
14789 {
14790 break;
14791 }
14792
14793 let start = range.start.to_display_point(display_snapshot);
14794 let end = range.end.to_display_point(display_snapshot);
14795 results.push((start..end, color))
14796 }
14797 }
14798 results
14799 }
14800
14801 pub fn background_highlight_row_ranges<T: 'static>(
14802 &self,
14803 search_range: Range<Anchor>,
14804 display_snapshot: &DisplaySnapshot,
14805 count: usize,
14806 ) -> Vec<RangeInclusive<DisplayPoint>> {
14807 let mut results = Vec::new();
14808 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14809 return vec![];
14810 };
14811
14812 let start_ix = match ranges.binary_search_by(|probe| {
14813 let cmp = probe
14814 .end
14815 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14816 if cmp.is_gt() {
14817 Ordering::Greater
14818 } else {
14819 Ordering::Less
14820 }
14821 }) {
14822 Ok(i) | Err(i) => i,
14823 };
14824 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14825 if let (Some(start_display), Some(end_display)) = (start, end) {
14826 results.push(
14827 start_display.to_display_point(display_snapshot)
14828 ..=end_display.to_display_point(display_snapshot),
14829 );
14830 }
14831 };
14832 let mut start_row: Option<Point> = None;
14833 let mut end_row: Option<Point> = None;
14834 if ranges.len() > count {
14835 return Vec::new();
14836 }
14837 for range in &ranges[start_ix..] {
14838 if range
14839 .start
14840 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14841 .is_ge()
14842 {
14843 break;
14844 }
14845 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14846 if let Some(current_row) = &end_row {
14847 if end.row == current_row.row {
14848 continue;
14849 }
14850 }
14851 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14852 if start_row.is_none() {
14853 assert_eq!(end_row, None);
14854 start_row = Some(start);
14855 end_row = Some(end);
14856 continue;
14857 }
14858 if let Some(current_end) = end_row.as_mut() {
14859 if start.row > current_end.row + 1 {
14860 push_region(start_row, end_row);
14861 start_row = Some(start);
14862 end_row = Some(end);
14863 } else {
14864 // Merge two hunks.
14865 *current_end = end;
14866 }
14867 } else {
14868 unreachable!();
14869 }
14870 }
14871 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14872 push_region(start_row, end_row);
14873 results
14874 }
14875
14876 pub fn gutter_highlights_in_range(
14877 &self,
14878 search_range: Range<Anchor>,
14879 display_snapshot: &DisplaySnapshot,
14880 cx: &App,
14881 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14882 let mut results = Vec::new();
14883 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14884 let color = color_fetcher(cx);
14885 let start_ix = match ranges.binary_search_by(|probe| {
14886 let cmp = probe
14887 .end
14888 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14889 if cmp.is_gt() {
14890 Ordering::Greater
14891 } else {
14892 Ordering::Less
14893 }
14894 }) {
14895 Ok(i) | Err(i) => i,
14896 };
14897 for range in &ranges[start_ix..] {
14898 if range
14899 .start
14900 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14901 .is_ge()
14902 {
14903 break;
14904 }
14905
14906 let start = range.start.to_display_point(display_snapshot);
14907 let end = range.end.to_display_point(display_snapshot);
14908 results.push((start..end, color))
14909 }
14910 }
14911 results
14912 }
14913
14914 /// Get the text ranges corresponding to the redaction query
14915 pub fn redacted_ranges(
14916 &self,
14917 search_range: Range<Anchor>,
14918 display_snapshot: &DisplaySnapshot,
14919 cx: &App,
14920 ) -> Vec<Range<DisplayPoint>> {
14921 display_snapshot
14922 .buffer_snapshot
14923 .redacted_ranges(search_range, |file| {
14924 if let Some(file) = file {
14925 file.is_private()
14926 && EditorSettings::get(
14927 Some(SettingsLocation {
14928 worktree_id: file.worktree_id(cx),
14929 path: file.path().as_ref(),
14930 }),
14931 cx,
14932 )
14933 .redact_private_values
14934 } else {
14935 false
14936 }
14937 })
14938 .map(|range| {
14939 range.start.to_display_point(display_snapshot)
14940 ..range.end.to_display_point(display_snapshot)
14941 })
14942 .collect()
14943 }
14944
14945 pub fn highlight_text<T: 'static>(
14946 &mut self,
14947 ranges: Vec<Range<Anchor>>,
14948 style: HighlightStyle,
14949 cx: &mut Context<Self>,
14950 ) {
14951 self.display_map.update(cx, |map, _| {
14952 map.highlight_text(TypeId::of::<T>(), ranges, style)
14953 });
14954 cx.notify();
14955 }
14956
14957 pub(crate) fn highlight_inlays<T: 'static>(
14958 &mut self,
14959 highlights: Vec<InlayHighlight>,
14960 style: HighlightStyle,
14961 cx: &mut Context<Self>,
14962 ) {
14963 self.display_map.update(cx, |map, _| {
14964 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14965 });
14966 cx.notify();
14967 }
14968
14969 pub fn text_highlights<'a, T: 'static>(
14970 &'a self,
14971 cx: &'a App,
14972 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14973 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14974 }
14975
14976 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14977 let cleared = self
14978 .display_map
14979 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14980 if cleared {
14981 cx.notify();
14982 }
14983 }
14984
14985 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14986 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14987 && self.focus_handle.is_focused(window)
14988 }
14989
14990 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14991 self.show_cursor_when_unfocused = is_enabled;
14992 cx.notify();
14993 }
14994
14995 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14996 cx.notify();
14997 }
14998
14999 fn on_buffer_event(
15000 &mut self,
15001 multibuffer: &Entity<MultiBuffer>,
15002 event: &multi_buffer::Event,
15003 window: &mut Window,
15004 cx: &mut Context<Self>,
15005 ) {
15006 match event {
15007 multi_buffer::Event::Edited {
15008 singleton_buffer_edited,
15009 edited_buffer: buffer_edited,
15010 } => {
15011 self.scrollbar_marker_state.dirty = true;
15012 self.active_indent_guides_state.dirty = true;
15013 self.refresh_active_diagnostics(cx);
15014 self.refresh_code_actions(window, cx);
15015 if self.has_active_inline_completion() {
15016 self.update_visible_inline_completion(window, cx);
15017 }
15018 if let Some(buffer) = buffer_edited {
15019 let buffer_id = buffer.read(cx).remote_id();
15020 if !self.registered_buffers.contains_key(&buffer_id) {
15021 if let Some(project) = self.project.as_ref() {
15022 project.update(cx, |project, cx| {
15023 self.registered_buffers.insert(
15024 buffer_id,
15025 project.register_buffer_with_language_servers(&buffer, cx),
15026 );
15027 })
15028 }
15029 }
15030 }
15031 cx.emit(EditorEvent::BufferEdited);
15032 cx.emit(SearchEvent::MatchesInvalidated);
15033 if *singleton_buffer_edited {
15034 if let Some(project) = &self.project {
15035 #[allow(clippy::mutable_key_type)]
15036 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15037 multibuffer
15038 .all_buffers()
15039 .into_iter()
15040 .filter_map(|buffer| {
15041 buffer.update(cx, |buffer, cx| {
15042 let language = buffer.language()?;
15043 let should_discard = project.update(cx, |project, cx| {
15044 project.is_local()
15045 && !project.has_language_servers_for(buffer, cx)
15046 });
15047 should_discard.not().then_some(language.clone())
15048 })
15049 })
15050 .collect::<HashSet<_>>()
15051 });
15052 if !languages_affected.is_empty() {
15053 self.refresh_inlay_hints(
15054 InlayHintRefreshReason::BufferEdited(languages_affected),
15055 cx,
15056 );
15057 }
15058 }
15059 }
15060
15061 let Some(project) = &self.project else { return };
15062 let (telemetry, is_via_ssh) = {
15063 let project = project.read(cx);
15064 let telemetry = project.client().telemetry().clone();
15065 let is_via_ssh = project.is_via_ssh();
15066 (telemetry, is_via_ssh)
15067 };
15068 refresh_linked_ranges(self, window, cx);
15069 telemetry.log_edit_event("editor", is_via_ssh);
15070 }
15071 multi_buffer::Event::ExcerptsAdded {
15072 buffer,
15073 predecessor,
15074 excerpts,
15075 } => {
15076 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15077 let buffer_id = buffer.read(cx).remote_id();
15078 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15079 if let Some(project) = &self.project {
15080 get_uncommitted_diff_for_buffer(
15081 project,
15082 [buffer.clone()],
15083 self.buffer.clone(),
15084 cx,
15085 )
15086 .detach();
15087 }
15088 }
15089 cx.emit(EditorEvent::ExcerptsAdded {
15090 buffer: buffer.clone(),
15091 predecessor: *predecessor,
15092 excerpts: excerpts.clone(),
15093 });
15094 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15095 }
15096 multi_buffer::Event::ExcerptsRemoved { ids } => {
15097 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15098 let buffer = self.buffer.read(cx);
15099 self.registered_buffers
15100 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15101 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15102 }
15103 multi_buffer::Event::ExcerptsEdited { ids } => {
15104 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15105 }
15106 multi_buffer::Event::ExcerptsExpanded { ids } => {
15107 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15108 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15109 }
15110 multi_buffer::Event::Reparsed(buffer_id) => {
15111 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15112
15113 cx.emit(EditorEvent::Reparsed(*buffer_id));
15114 }
15115 multi_buffer::Event::DiffHunksToggled => {
15116 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15117 }
15118 multi_buffer::Event::LanguageChanged(buffer_id) => {
15119 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15120 cx.emit(EditorEvent::Reparsed(*buffer_id));
15121 cx.notify();
15122 }
15123 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15124 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15125 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15126 cx.emit(EditorEvent::TitleChanged)
15127 }
15128 // multi_buffer::Event::DiffBaseChanged => {
15129 // self.scrollbar_marker_state.dirty = true;
15130 // cx.emit(EditorEvent::DiffBaseChanged);
15131 // cx.notify();
15132 // }
15133 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15134 multi_buffer::Event::DiagnosticsUpdated => {
15135 self.refresh_active_diagnostics(cx);
15136 self.refresh_inline_diagnostics(true, window, cx);
15137 self.scrollbar_marker_state.dirty = true;
15138 cx.notify();
15139 }
15140 _ => {}
15141 };
15142 }
15143
15144 fn on_display_map_changed(
15145 &mut self,
15146 _: Entity<DisplayMap>,
15147 _: &mut Window,
15148 cx: &mut Context<Self>,
15149 ) {
15150 cx.notify();
15151 }
15152
15153 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15154 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15155 self.refresh_inline_completion(true, false, window, cx);
15156 self.refresh_inlay_hints(
15157 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15158 self.selections.newest_anchor().head(),
15159 &self.buffer.read(cx).snapshot(cx),
15160 cx,
15161 )),
15162 cx,
15163 );
15164
15165 let old_cursor_shape = self.cursor_shape;
15166
15167 {
15168 let editor_settings = EditorSettings::get_global(cx);
15169 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15170 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15171 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15172 }
15173
15174 if old_cursor_shape != self.cursor_shape {
15175 cx.emit(EditorEvent::CursorShapeChanged);
15176 }
15177
15178 let project_settings = ProjectSettings::get_global(cx);
15179 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15180
15181 if self.mode == EditorMode::Full {
15182 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15183 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15184 if self.show_inline_diagnostics != show_inline_diagnostics {
15185 self.show_inline_diagnostics = show_inline_diagnostics;
15186 self.refresh_inline_diagnostics(false, window, cx);
15187 }
15188
15189 if self.git_blame_inline_enabled != inline_blame_enabled {
15190 self.toggle_git_blame_inline_internal(false, window, cx);
15191 }
15192 }
15193
15194 cx.notify();
15195 }
15196
15197 pub fn set_searchable(&mut self, searchable: bool) {
15198 self.searchable = searchable;
15199 }
15200
15201 pub fn searchable(&self) -> bool {
15202 self.searchable
15203 }
15204
15205 fn open_proposed_changes_editor(
15206 &mut self,
15207 _: &OpenProposedChangesEditor,
15208 window: &mut Window,
15209 cx: &mut Context<Self>,
15210 ) {
15211 let Some(workspace) = self.workspace() else {
15212 cx.propagate();
15213 return;
15214 };
15215
15216 let selections = self.selections.all::<usize>(cx);
15217 let multi_buffer = self.buffer.read(cx);
15218 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15219 let mut new_selections_by_buffer = HashMap::default();
15220 for selection in selections {
15221 for (buffer, range, _) in
15222 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15223 {
15224 let mut range = range.to_point(buffer);
15225 range.start.column = 0;
15226 range.end.column = buffer.line_len(range.end.row);
15227 new_selections_by_buffer
15228 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15229 .or_insert(Vec::new())
15230 .push(range)
15231 }
15232 }
15233
15234 let proposed_changes_buffers = new_selections_by_buffer
15235 .into_iter()
15236 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15237 .collect::<Vec<_>>();
15238 let proposed_changes_editor = cx.new(|cx| {
15239 ProposedChangesEditor::new(
15240 "Proposed changes",
15241 proposed_changes_buffers,
15242 self.project.clone(),
15243 window,
15244 cx,
15245 )
15246 });
15247
15248 window.defer(cx, move |window, cx| {
15249 workspace.update(cx, |workspace, cx| {
15250 workspace.active_pane().update(cx, |pane, cx| {
15251 pane.add_item(
15252 Box::new(proposed_changes_editor),
15253 true,
15254 true,
15255 None,
15256 window,
15257 cx,
15258 );
15259 });
15260 });
15261 });
15262 }
15263
15264 pub fn open_excerpts_in_split(
15265 &mut self,
15266 _: &OpenExcerptsSplit,
15267 window: &mut Window,
15268 cx: &mut Context<Self>,
15269 ) {
15270 self.open_excerpts_common(None, true, window, cx)
15271 }
15272
15273 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15274 self.open_excerpts_common(None, false, window, cx)
15275 }
15276
15277 fn open_excerpts_common(
15278 &mut self,
15279 jump_data: Option<JumpData>,
15280 split: bool,
15281 window: &mut Window,
15282 cx: &mut Context<Self>,
15283 ) {
15284 let Some(workspace) = self.workspace() else {
15285 cx.propagate();
15286 return;
15287 };
15288
15289 if self.buffer.read(cx).is_singleton() {
15290 cx.propagate();
15291 return;
15292 }
15293
15294 let mut new_selections_by_buffer = HashMap::default();
15295 match &jump_data {
15296 Some(JumpData::MultiBufferPoint {
15297 excerpt_id,
15298 position,
15299 anchor,
15300 line_offset_from_top,
15301 }) => {
15302 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15303 if let Some(buffer) = multi_buffer_snapshot
15304 .buffer_id_for_excerpt(*excerpt_id)
15305 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15306 {
15307 let buffer_snapshot = buffer.read(cx).snapshot();
15308 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15309 language::ToPoint::to_point(anchor, &buffer_snapshot)
15310 } else {
15311 buffer_snapshot.clip_point(*position, Bias::Left)
15312 };
15313 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15314 new_selections_by_buffer.insert(
15315 buffer,
15316 (
15317 vec![jump_to_offset..jump_to_offset],
15318 Some(*line_offset_from_top),
15319 ),
15320 );
15321 }
15322 }
15323 Some(JumpData::MultiBufferRow {
15324 row,
15325 line_offset_from_top,
15326 }) => {
15327 let point = MultiBufferPoint::new(row.0, 0);
15328 if let Some((buffer, buffer_point, _)) =
15329 self.buffer.read(cx).point_to_buffer_point(point, cx)
15330 {
15331 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15332 new_selections_by_buffer
15333 .entry(buffer)
15334 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15335 .0
15336 .push(buffer_offset..buffer_offset)
15337 }
15338 }
15339 None => {
15340 let selections = self.selections.all::<usize>(cx);
15341 let multi_buffer = self.buffer.read(cx);
15342 for selection in selections {
15343 for (snapshot, range, _, anchor) in multi_buffer
15344 .snapshot(cx)
15345 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15346 {
15347 if let Some(anchor) = anchor {
15348 // selection is in a deleted hunk
15349 let Some(buffer_id) = anchor.buffer_id else {
15350 continue;
15351 };
15352 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15353 continue;
15354 };
15355 let offset = text::ToOffset::to_offset(
15356 &anchor.text_anchor,
15357 &buffer_handle.read(cx).snapshot(),
15358 );
15359 let range = offset..offset;
15360 new_selections_by_buffer
15361 .entry(buffer_handle)
15362 .or_insert((Vec::new(), None))
15363 .0
15364 .push(range)
15365 } else {
15366 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15367 else {
15368 continue;
15369 };
15370 new_selections_by_buffer
15371 .entry(buffer_handle)
15372 .or_insert((Vec::new(), None))
15373 .0
15374 .push(range)
15375 }
15376 }
15377 }
15378 }
15379 }
15380
15381 if new_selections_by_buffer.is_empty() {
15382 return;
15383 }
15384
15385 // We defer the pane interaction because we ourselves are a workspace item
15386 // and activating a new item causes the pane to call a method on us reentrantly,
15387 // which panics if we're on the stack.
15388 window.defer(cx, move |window, cx| {
15389 workspace.update(cx, |workspace, cx| {
15390 let pane = if split {
15391 workspace.adjacent_pane(window, cx)
15392 } else {
15393 workspace.active_pane().clone()
15394 };
15395
15396 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15397 let editor = buffer
15398 .read(cx)
15399 .file()
15400 .is_none()
15401 .then(|| {
15402 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15403 // so `workspace.open_project_item` will never find them, always opening a new editor.
15404 // Instead, we try to activate the existing editor in the pane first.
15405 let (editor, pane_item_index) =
15406 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15407 let editor = item.downcast::<Editor>()?;
15408 let singleton_buffer =
15409 editor.read(cx).buffer().read(cx).as_singleton()?;
15410 if singleton_buffer == buffer {
15411 Some((editor, i))
15412 } else {
15413 None
15414 }
15415 })?;
15416 pane.update(cx, |pane, cx| {
15417 pane.activate_item(pane_item_index, true, true, window, cx)
15418 });
15419 Some(editor)
15420 })
15421 .flatten()
15422 .unwrap_or_else(|| {
15423 workspace.open_project_item::<Self>(
15424 pane.clone(),
15425 buffer,
15426 true,
15427 true,
15428 window,
15429 cx,
15430 )
15431 });
15432
15433 editor.update(cx, |editor, cx| {
15434 let autoscroll = match scroll_offset {
15435 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15436 None => Autoscroll::newest(),
15437 };
15438 let nav_history = editor.nav_history.take();
15439 editor.change_selections(Some(autoscroll), window, cx, |s| {
15440 s.select_ranges(ranges);
15441 });
15442 editor.nav_history = nav_history;
15443 });
15444 }
15445 })
15446 });
15447 }
15448
15449 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15450 let snapshot = self.buffer.read(cx).read(cx);
15451 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15452 Some(
15453 ranges
15454 .iter()
15455 .map(move |range| {
15456 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15457 })
15458 .collect(),
15459 )
15460 }
15461
15462 fn selection_replacement_ranges(
15463 &self,
15464 range: Range<OffsetUtf16>,
15465 cx: &mut App,
15466 ) -> Vec<Range<OffsetUtf16>> {
15467 let selections = self.selections.all::<OffsetUtf16>(cx);
15468 let newest_selection = selections
15469 .iter()
15470 .max_by_key(|selection| selection.id)
15471 .unwrap();
15472 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15473 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15474 let snapshot = self.buffer.read(cx).read(cx);
15475 selections
15476 .into_iter()
15477 .map(|mut selection| {
15478 selection.start.0 =
15479 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15480 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15481 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15482 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15483 })
15484 .collect()
15485 }
15486
15487 fn report_editor_event(
15488 &self,
15489 event_type: &'static str,
15490 file_extension: Option<String>,
15491 cx: &App,
15492 ) {
15493 if cfg!(any(test, feature = "test-support")) {
15494 return;
15495 }
15496
15497 let Some(project) = &self.project else { return };
15498
15499 // If None, we are in a file without an extension
15500 let file = self
15501 .buffer
15502 .read(cx)
15503 .as_singleton()
15504 .and_then(|b| b.read(cx).file());
15505 let file_extension = file_extension.or(file
15506 .as_ref()
15507 .and_then(|file| Path::new(file.file_name(cx)).extension())
15508 .and_then(|e| e.to_str())
15509 .map(|a| a.to_string()));
15510
15511 let vim_mode = cx
15512 .global::<SettingsStore>()
15513 .raw_user_settings()
15514 .get("vim_mode")
15515 == Some(&serde_json::Value::Bool(true));
15516
15517 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15518 let copilot_enabled = edit_predictions_provider
15519 == language::language_settings::EditPredictionProvider::Copilot;
15520 let copilot_enabled_for_language = self
15521 .buffer
15522 .read(cx)
15523 .settings_at(0, cx)
15524 .show_edit_predictions;
15525
15526 let project = project.read(cx);
15527 telemetry::event!(
15528 event_type,
15529 file_extension,
15530 vim_mode,
15531 copilot_enabled,
15532 copilot_enabled_for_language,
15533 edit_predictions_provider,
15534 is_via_ssh = project.is_via_ssh(),
15535 );
15536 }
15537
15538 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15539 /// with each line being an array of {text, highlight} objects.
15540 fn copy_highlight_json(
15541 &mut self,
15542 _: &CopyHighlightJson,
15543 window: &mut Window,
15544 cx: &mut Context<Self>,
15545 ) {
15546 #[derive(Serialize)]
15547 struct Chunk<'a> {
15548 text: String,
15549 highlight: Option<&'a str>,
15550 }
15551
15552 let snapshot = self.buffer.read(cx).snapshot(cx);
15553 let range = self
15554 .selected_text_range(false, window, cx)
15555 .and_then(|selection| {
15556 if selection.range.is_empty() {
15557 None
15558 } else {
15559 Some(selection.range)
15560 }
15561 })
15562 .unwrap_or_else(|| 0..snapshot.len());
15563
15564 let chunks = snapshot.chunks(range, true);
15565 let mut lines = Vec::new();
15566 let mut line: VecDeque<Chunk> = VecDeque::new();
15567
15568 let Some(style) = self.style.as_ref() else {
15569 return;
15570 };
15571
15572 for chunk in chunks {
15573 let highlight = chunk
15574 .syntax_highlight_id
15575 .and_then(|id| id.name(&style.syntax));
15576 let mut chunk_lines = chunk.text.split('\n').peekable();
15577 while let Some(text) = chunk_lines.next() {
15578 let mut merged_with_last_token = false;
15579 if let Some(last_token) = line.back_mut() {
15580 if last_token.highlight == highlight {
15581 last_token.text.push_str(text);
15582 merged_with_last_token = true;
15583 }
15584 }
15585
15586 if !merged_with_last_token {
15587 line.push_back(Chunk {
15588 text: text.into(),
15589 highlight,
15590 });
15591 }
15592
15593 if chunk_lines.peek().is_some() {
15594 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15595 line.pop_front();
15596 }
15597 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15598 line.pop_back();
15599 }
15600
15601 lines.push(mem::take(&mut line));
15602 }
15603 }
15604 }
15605
15606 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15607 return;
15608 };
15609 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15610 }
15611
15612 pub fn open_context_menu(
15613 &mut self,
15614 _: &OpenContextMenu,
15615 window: &mut Window,
15616 cx: &mut Context<Self>,
15617 ) {
15618 self.request_autoscroll(Autoscroll::newest(), cx);
15619 let position = self.selections.newest_display(cx).start;
15620 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15621 }
15622
15623 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15624 &self.inlay_hint_cache
15625 }
15626
15627 pub fn replay_insert_event(
15628 &mut self,
15629 text: &str,
15630 relative_utf16_range: Option<Range<isize>>,
15631 window: &mut Window,
15632 cx: &mut Context<Self>,
15633 ) {
15634 if !self.input_enabled {
15635 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15636 return;
15637 }
15638 if let Some(relative_utf16_range) = relative_utf16_range {
15639 let selections = self.selections.all::<OffsetUtf16>(cx);
15640 self.change_selections(None, window, cx, |s| {
15641 let new_ranges = selections.into_iter().map(|range| {
15642 let start = OffsetUtf16(
15643 range
15644 .head()
15645 .0
15646 .saturating_add_signed(relative_utf16_range.start),
15647 );
15648 let end = OffsetUtf16(
15649 range
15650 .head()
15651 .0
15652 .saturating_add_signed(relative_utf16_range.end),
15653 );
15654 start..end
15655 });
15656 s.select_ranges(new_ranges);
15657 });
15658 }
15659
15660 self.handle_input(text, window, cx);
15661 }
15662
15663 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15664 let Some(provider) = self.semantics_provider.as_ref() else {
15665 return false;
15666 };
15667
15668 let mut supports = false;
15669 self.buffer().update(cx, |this, cx| {
15670 this.for_each_buffer(|buffer| {
15671 supports |= provider.supports_inlay_hints(buffer, cx);
15672 });
15673 });
15674
15675 supports
15676 }
15677
15678 pub fn is_focused(&self, window: &Window) -> bool {
15679 self.focus_handle.is_focused(window)
15680 }
15681
15682 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15683 cx.emit(EditorEvent::Focused);
15684
15685 if let Some(descendant) = self
15686 .last_focused_descendant
15687 .take()
15688 .and_then(|descendant| descendant.upgrade())
15689 {
15690 window.focus(&descendant);
15691 } else {
15692 if let Some(blame) = self.blame.as_ref() {
15693 blame.update(cx, GitBlame::focus)
15694 }
15695
15696 self.blink_manager.update(cx, BlinkManager::enable);
15697 self.show_cursor_names(window, cx);
15698 self.buffer.update(cx, |buffer, cx| {
15699 buffer.finalize_last_transaction(cx);
15700 if self.leader_peer_id.is_none() {
15701 buffer.set_active_selections(
15702 &self.selections.disjoint_anchors(),
15703 self.selections.line_mode,
15704 self.cursor_shape,
15705 cx,
15706 );
15707 }
15708 });
15709 }
15710 }
15711
15712 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15713 cx.emit(EditorEvent::FocusedIn)
15714 }
15715
15716 fn handle_focus_out(
15717 &mut self,
15718 event: FocusOutEvent,
15719 _window: &mut Window,
15720 _cx: &mut Context<Self>,
15721 ) {
15722 if event.blurred != self.focus_handle {
15723 self.last_focused_descendant = Some(event.blurred);
15724 }
15725 }
15726
15727 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15728 self.blink_manager.update(cx, BlinkManager::disable);
15729 self.buffer
15730 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15731
15732 if let Some(blame) = self.blame.as_ref() {
15733 blame.update(cx, GitBlame::blur)
15734 }
15735 if !self.hover_state.focused(window, cx) {
15736 hide_hover(self, cx);
15737 }
15738 if !self
15739 .context_menu
15740 .borrow()
15741 .as_ref()
15742 .is_some_and(|context_menu| context_menu.focused(window, cx))
15743 {
15744 self.hide_context_menu(window, cx);
15745 }
15746 self.discard_inline_completion(false, cx);
15747 cx.emit(EditorEvent::Blurred);
15748 cx.notify();
15749 }
15750
15751 pub fn register_action<A: Action>(
15752 &mut self,
15753 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15754 ) -> Subscription {
15755 let id = self.next_editor_action_id.post_inc();
15756 let listener = Arc::new(listener);
15757 self.editor_actions.borrow_mut().insert(
15758 id,
15759 Box::new(move |window, _| {
15760 let listener = listener.clone();
15761 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15762 let action = action.downcast_ref().unwrap();
15763 if phase == DispatchPhase::Bubble {
15764 listener(action, window, cx)
15765 }
15766 })
15767 }),
15768 );
15769
15770 let editor_actions = self.editor_actions.clone();
15771 Subscription::new(move || {
15772 editor_actions.borrow_mut().remove(&id);
15773 })
15774 }
15775
15776 pub fn file_header_size(&self) -> u32 {
15777 FILE_HEADER_HEIGHT
15778 }
15779
15780 pub fn revert(
15781 &mut self,
15782 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15783 window: &mut Window,
15784 cx: &mut Context<Self>,
15785 ) {
15786 self.buffer().update(cx, |multi_buffer, cx| {
15787 for (buffer_id, changes) in revert_changes {
15788 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15789 buffer.update(cx, |buffer, cx| {
15790 buffer.edit(
15791 changes.into_iter().map(|(range, text)| {
15792 (range, text.to_string().map(Arc::<str>::from))
15793 }),
15794 None,
15795 cx,
15796 );
15797 });
15798 }
15799 }
15800 });
15801 self.change_selections(None, window, cx, |selections| selections.refresh());
15802 }
15803
15804 pub fn to_pixel_point(
15805 &self,
15806 source: multi_buffer::Anchor,
15807 editor_snapshot: &EditorSnapshot,
15808 window: &mut Window,
15809 ) -> Option<gpui::Point<Pixels>> {
15810 let source_point = source.to_display_point(editor_snapshot);
15811 self.display_to_pixel_point(source_point, editor_snapshot, window)
15812 }
15813
15814 pub fn display_to_pixel_point(
15815 &self,
15816 source: DisplayPoint,
15817 editor_snapshot: &EditorSnapshot,
15818 window: &mut Window,
15819 ) -> Option<gpui::Point<Pixels>> {
15820 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15821 let text_layout_details = self.text_layout_details(window);
15822 let scroll_top = text_layout_details
15823 .scroll_anchor
15824 .scroll_position(editor_snapshot)
15825 .y;
15826
15827 if source.row().as_f32() < scroll_top.floor() {
15828 return None;
15829 }
15830 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15831 let source_y = line_height * (source.row().as_f32() - scroll_top);
15832 Some(gpui::Point::new(source_x, source_y))
15833 }
15834
15835 pub fn has_visible_completions_menu(&self) -> bool {
15836 !self.edit_prediction_preview_is_active()
15837 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15838 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15839 })
15840 }
15841
15842 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15843 self.addons
15844 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15845 }
15846
15847 pub fn unregister_addon<T: Addon>(&mut self) {
15848 self.addons.remove(&std::any::TypeId::of::<T>());
15849 }
15850
15851 pub fn addon<T: Addon>(&self) -> Option<&T> {
15852 let type_id = std::any::TypeId::of::<T>();
15853 self.addons
15854 .get(&type_id)
15855 .and_then(|item| item.to_any().downcast_ref::<T>())
15856 }
15857
15858 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15859 let text_layout_details = self.text_layout_details(window);
15860 let style = &text_layout_details.editor_style;
15861 let font_id = window.text_system().resolve_font(&style.text.font());
15862 let font_size = style.text.font_size.to_pixels(window.rem_size());
15863 let line_height = style.text.line_height_in_pixels(window.rem_size());
15864 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15865
15866 gpui::Size::new(em_width, line_height)
15867 }
15868
15869 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15870 self.load_diff_task.clone()
15871 }
15872
15873 fn read_selections_from_db(
15874 &mut self,
15875 item_id: u64,
15876 workspace_id: WorkspaceId,
15877 window: &mut Window,
15878 cx: &mut Context<Editor>,
15879 ) {
15880 if !self.is_singleton(cx)
15881 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15882 {
15883 return;
15884 }
15885 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15886 return;
15887 };
15888 if selections.is_empty() {
15889 return;
15890 }
15891
15892 let snapshot = self.buffer.read(cx).snapshot(cx);
15893 self.change_selections(None, window, cx, |s| {
15894 s.select_ranges(selections.into_iter().map(|(start, end)| {
15895 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15896 }));
15897 });
15898 }
15899}
15900
15901fn insert_extra_newline_brackets(
15902 buffer: &MultiBufferSnapshot,
15903 range: Range<usize>,
15904 language: &language::LanguageScope,
15905) -> bool {
15906 let leading_whitespace_len = buffer
15907 .reversed_chars_at(range.start)
15908 .take_while(|c| c.is_whitespace() && *c != '\n')
15909 .map(|c| c.len_utf8())
15910 .sum::<usize>();
15911 let trailing_whitespace_len = buffer
15912 .chars_at(range.end)
15913 .take_while(|c| c.is_whitespace() && *c != '\n')
15914 .map(|c| c.len_utf8())
15915 .sum::<usize>();
15916 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15917
15918 language.brackets().any(|(pair, enabled)| {
15919 let pair_start = pair.start.trim_end();
15920 let pair_end = pair.end.trim_start();
15921
15922 enabled
15923 && pair.newline
15924 && buffer.contains_str_at(range.end, pair_end)
15925 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15926 })
15927}
15928
15929fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15930 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15931 [(buffer, range, _)] => (*buffer, range.clone()),
15932 _ => return false,
15933 };
15934 let pair = {
15935 let mut result: Option<BracketMatch> = None;
15936
15937 for pair in buffer
15938 .all_bracket_ranges(range.clone())
15939 .filter(move |pair| {
15940 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15941 })
15942 {
15943 let len = pair.close_range.end - pair.open_range.start;
15944
15945 if let Some(existing) = &result {
15946 let existing_len = existing.close_range.end - existing.open_range.start;
15947 if len > existing_len {
15948 continue;
15949 }
15950 }
15951
15952 result = Some(pair);
15953 }
15954
15955 result
15956 };
15957 let Some(pair) = pair else {
15958 return false;
15959 };
15960 pair.newline_only
15961 && buffer
15962 .chars_for_range(pair.open_range.end..range.start)
15963 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15964 .all(|c| c.is_whitespace() && c != '\n')
15965}
15966
15967fn get_uncommitted_diff_for_buffer(
15968 project: &Entity<Project>,
15969 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15970 buffer: Entity<MultiBuffer>,
15971 cx: &mut App,
15972) -> Task<()> {
15973 let mut tasks = Vec::new();
15974 project.update(cx, |project, cx| {
15975 for buffer in buffers {
15976 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15977 }
15978 });
15979 cx.spawn(|mut cx| async move {
15980 let diffs = futures::future::join_all(tasks).await;
15981 buffer
15982 .update(&mut cx, |buffer, cx| {
15983 for diff in diffs.into_iter().flatten() {
15984 buffer.add_diff(diff, cx);
15985 }
15986 })
15987 .ok();
15988 })
15989}
15990
15991fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15992 let tab_size = tab_size.get() as usize;
15993 let mut width = offset;
15994
15995 for ch in text.chars() {
15996 width += if ch == '\t' {
15997 tab_size - (width % tab_size)
15998 } else {
15999 1
16000 };
16001 }
16002
16003 width - offset
16004}
16005
16006#[cfg(test)]
16007mod tests {
16008 use super::*;
16009
16010 #[test]
16011 fn test_string_size_with_expanded_tabs() {
16012 let nz = |val| NonZeroU32::new(val).unwrap();
16013 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16014 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16015 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16016 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16017 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16018 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16019 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16020 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16021 }
16022}
16023
16024/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16025struct WordBreakingTokenizer<'a> {
16026 input: &'a str,
16027}
16028
16029impl<'a> WordBreakingTokenizer<'a> {
16030 fn new(input: &'a str) -> Self {
16031 Self { input }
16032 }
16033}
16034
16035fn is_char_ideographic(ch: char) -> bool {
16036 use unicode_script::Script::*;
16037 use unicode_script::UnicodeScript;
16038 matches!(ch.script(), Han | Tangut | Yi)
16039}
16040
16041fn is_grapheme_ideographic(text: &str) -> bool {
16042 text.chars().any(is_char_ideographic)
16043}
16044
16045fn is_grapheme_whitespace(text: &str) -> bool {
16046 text.chars().any(|x| x.is_whitespace())
16047}
16048
16049fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16050 text.chars().next().map_or(false, |ch| {
16051 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16052 })
16053}
16054
16055#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16056struct WordBreakToken<'a> {
16057 token: &'a str,
16058 grapheme_len: usize,
16059 is_whitespace: bool,
16060}
16061
16062impl<'a> Iterator for WordBreakingTokenizer<'a> {
16063 /// Yields a span, the count of graphemes in the token, and whether it was
16064 /// whitespace. Note that it also breaks at word boundaries.
16065 type Item = WordBreakToken<'a>;
16066
16067 fn next(&mut self) -> Option<Self::Item> {
16068 use unicode_segmentation::UnicodeSegmentation;
16069 if self.input.is_empty() {
16070 return None;
16071 }
16072
16073 let mut iter = self.input.graphemes(true).peekable();
16074 let mut offset = 0;
16075 let mut graphemes = 0;
16076 if let Some(first_grapheme) = iter.next() {
16077 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16078 offset += first_grapheme.len();
16079 graphemes += 1;
16080 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16081 if let Some(grapheme) = iter.peek().copied() {
16082 if should_stay_with_preceding_ideograph(grapheme) {
16083 offset += grapheme.len();
16084 graphemes += 1;
16085 }
16086 }
16087 } else {
16088 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16089 let mut next_word_bound = words.peek().copied();
16090 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16091 next_word_bound = words.next();
16092 }
16093 while let Some(grapheme) = iter.peek().copied() {
16094 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16095 break;
16096 };
16097 if is_grapheme_whitespace(grapheme) != is_whitespace {
16098 break;
16099 };
16100 offset += grapheme.len();
16101 graphemes += 1;
16102 iter.next();
16103 }
16104 }
16105 let token = &self.input[..offset];
16106 self.input = &self.input[offset..];
16107 if is_whitespace {
16108 Some(WordBreakToken {
16109 token: " ",
16110 grapheme_len: 1,
16111 is_whitespace: true,
16112 })
16113 } else {
16114 Some(WordBreakToken {
16115 token,
16116 grapheme_len: graphemes,
16117 is_whitespace: false,
16118 })
16119 }
16120 } else {
16121 None
16122 }
16123 }
16124}
16125
16126#[test]
16127fn test_word_breaking_tokenizer() {
16128 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16129 ("", &[]),
16130 (" ", &[(" ", 1, true)]),
16131 ("Ʒ", &[("Ʒ", 1, false)]),
16132 ("Ǽ", &[("Ǽ", 1, false)]),
16133 ("⋑", &[("⋑", 1, false)]),
16134 ("⋑⋑", &[("⋑⋑", 2, false)]),
16135 (
16136 "原理,进而",
16137 &[
16138 ("原", 1, false),
16139 ("理,", 2, false),
16140 ("进", 1, false),
16141 ("而", 1, false),
16142 ],
16143 ),
16144 (
16145 "hello world",
16146 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16147 ),
16148 (
16149 "hello, world",
16150 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16151 ),
16152 (
16153 " hello world",
16154 &[
16155 (" ", 1, true),
16156 ("hello", 5, false),
16157 (" ", 1, true),
16158 ("world", 5, false),
16159 ],
16160 ),
16161 (
16162 "这是什么 \n 钢笔",
16163 &[
16164 ("这", 1, false),
16165 ("是", 1, false),
16166 ("什", 1, false),
16167 ("么", 1, false),
16168 (" ", 1, true),
16169 ("钢", 1, false),
16170 ("笔", 1, false),
16171 ],
16172 ),
16173 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16174 ];
16175
16176 for (input, result) in tests {
16177 assert_eq!(
16178 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16179 result
16180 .iter()
16181 .copied()
16182 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16183 token,
16184 grapheme_len,
16185 is_whitespace,
16186 })
16187 .collect::<Vec<_>>()
16188 );
16189 }
16190}
16191
16192fn wrap_with_prefix(
16193 line_prefix: String,
16194 unwrapped_text: String,
16195 wrap_column: usize,
16196 tab_size: NonZeroU32,
16197) -> String {
16198 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16199 let mut wrapped_text = String::new();
16200 let mut current_line = line_prefix.clone();
16201
16202 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16203 let mut current_line_len = line_prefix_len;
16204 for WordBreakToken {
16205 token,
16206 grapheme_len,
16207 is_whitespace,
16208 } in tokenizer
16209 {
16210 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16211 wrapped_text.push_str(current_line.trim_end());
16212 wrapped_text.push('\n');
16213 current_line.truncate(line_prefix.len());
16214 current_line_len = line_prefix_len;
16215 if !is_whitespace {
16216 current_line.push_str(token);
16217 current_line_len += grapheme_len;
16218 }
16219 } else if !is_whitespace {
16220 current_line.push_str(token);
16221 current_line_len += grapheme_len;
16222 } else if current_line_len != line_prefix_len {
16223 current_line.push(' ');
16224 current_line_len += 1;
16225 }
16226 }
16227
16228 if !current_line.is_empty() {
16229 wrapped_text.push_str(¤t_line);
16230 }
16231 wrapped_text
16232}
16233
16234#[test]
16235fn test_wrap_with_prefix() {
16236 assert_eq!(
16237 wrap_with_prefix(
16238 "# ".to_string(),
16239 "abcdefg".to_string(),
16240 4,
16241 NonZeroU32::new(4).unwrap()
16242 ),
16243 "# abcdefg"
16244 );
16245 assert_eq!(
16246 wrap_with_prefix(
16247 "".to_string(),
16248 "\thello world".to_string(),
16249 8,
16250 NonZeroU32::new(4).unwrap()
16251 ),
16252 "hello\nworld"
16253 );
16254 assert_eq!(
16255 wrap_with_prefix(
16256 "// ".to_string(),
16257 "xx \nyy zz aa bb cc".to_string(),
16258 12,
16259 NonZeroU32::new(4).unwrap()
16260 ),
16261 "// xx yy zz\n// aa bb cc"
16262 );
16263 assert_eq!(
16264 wrap_with_prefix(
16265 String::new(),
16266 "这是什么 \n 钢笔".to_string(),
16267 3,
16268 NonZeroU32::new(4).unwrap()
16269 ),
16270 "这是什\n么 钢\n笔"
16271 );
16272}
16273
16274pub trait CollaborationHub {
16275 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16276 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16277 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16278}
16279
16280impl CollaborationHub for Entity<Project> {
16281 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16282 self.read(cx).collaborators()
16283 }
16284
16285 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16286 self.read(cx).user_store().read(cx).participant_indices()
16287 }
16288
16289 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16290 let this = self.read(cx);
16291 let user_ids = this.collaborators().values().map(|c| c.user_id);
16292 this.user_store().read_with(cx, |user_store, cx| {
16293 user_store.participant_names(user_ids, cx)
16294 })
16295 }
16296}
16297
16298pub trait SemanticsProvider {
16299 fn hover(
16300 &self,
16301 buffer: &Entity<Buffer>,
16302 position: text::Anchor,
16303 cx: &mut App,
16304 ) -> Option<Task<Vec<project::Hover>>>;
16305
16306 fn inlay_hints(
16307 &self,
16308 buffer_handle: Entity<Buffer>,
16309 range: Range<text::Anchor>,
16310 cx: &mut App,
16311 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16312
16313 fn resolve_inlay_hint(
16314 &self,
16315 hint: InlayHint,
16316 buffer_handle: Entity<Buffer>,
16317 server_id: LanguageServerId,
16318 cx: &mut App,
16319 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16320
16321 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16322
16323 fn document_highlights(
16324 &self,
16325 buffer: &Entity<Buffer>,
16326 position: text::Anchor,
16327 cx: &mut App,
16328 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16329
16330 fn definitions(
16331 &self,
16332 buffer: &Entity<Buffer>,
16333 position: text::Anchor,
16334 kind: GotoDefinitionKind,
16335 cx: &mut App,
16336 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16337
16338 fn range_for_rename(
16339 &self,
16340 buffer: &Entity<Buffer>,
16341 position: text::Anchor,
16342 cx: &mut App,
16343 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16344
16345 fn perform_rename(
16346 &self,
16347 buffer: &Entity<Buffer>,
16348 position: text::Anchor,
16349 new_name: String,
16350 cx: &mut App,
16351 ) -> Option<Task<Result<ProjectTransaction>>>;
16352}
16353
16354pub trait CompletionProvider {
16355 fn completions(
16356 &self,
16357 buffer: &Entity<Buffer>,
16358 buffer_position: text::Anchor,
16359 trigger: CompletionContext,
16360 window: &mut Window,
16361 cx: &mut Context<Editor>,
16362 ) -> Task<Result<Vec<Completion>>>;
16363
16364 fn resolve_completions(
16365 &self,
16366 buffer: Entity<Buffer>,
16367 completion_indices: Vec<usize>,
16368 completions: Rc<RefCell<Box<[Completion]>>>,
16369 cx: &mut Context<Editor>,
16370 ) -> Task<Result<bool>>;
16371
16372 fn apply_additional_edits_for_completion(
16373 &self,
16374 _buffer: Entity<Buffer>,
16375 _completions: Rc<RefCell<Box<[Completion]>>>,
16376 _completion_index: usize,
16377 _push_to_history: bool,
16378 _cx: &mut Context<Editor>,
16379 ) -> Task<Result<Option<language::Transaction>>> {
16380 Task::ready(Ok(None))
16381 }
16382
16383 fn is_completion_trigger(
16384 &self,
16385 buffer: &Entity<Buffer>,
16386 position: language::Anchor,
16387 text: &str,
16388 trigger_in_words: bool,
16389 cx: &mut Context<Editor>,
16390 ) -> bool;
16391
16392 fn sort_completions(&self) -> bool {
16393 true
16394 }
16395}
16396
16397pub trait CodeActionProvider {
16398 fn id(&self) -> Arc<str>;
16399
16400 fn code_actions(
16401 &self,
16402 buffer: &Entity<Buffer>,
16403 range: Range<text::Anchor>,
16404 window: &mut Window,
16405 cx: &mut App,
16406 ) -> Task<Result<Vec<CodeAction>>>;
16407
16408 fn apply_code_action(
16409 &self,
16410 buffer_handle: Entity<Buffer>,
16411 action: CodeAction,
16412 excerpt_id: ExcerptId,
16413 push_to_history: bool,
16414 window: &mut Window,
16415 cx: &mut App,
16416 ) -> Task<Result<ProjectTransaction>>;
16417}
16418
16419impl CodeActionProvider for Entity<Project> {
16420 fn id(&self) -> Arc<str> {
16421 "project".into()
16422 }
16423
16424 fn code_actions(
16425 &self,
16426 buffer: &Entity<Buffer>,
16427 range: Range<text::Anchor>,
16428 _window: &mut Window,
16429 cx: &mut App,
16430 ) -> Task<Result<Vec<CodeAction>>> {
16431 self.update(cx, |project, cx| {
16432 project.code_actions(buffer, range, None, cx)
16433 })
16434 }
16435
16436 fn apply_code_action(
16437 &self,
16438 buffer_handle: Entity<Buffer>,
16439 action: CodeAction,
16440 _excerpt_id: ExcerptId,
16441 push_to_history: bool,
16442 _window: &mut Window,
16443 cx: &mut App,
16444 ) -> Task<Result<ProjectTransaction>> {
16445 self.update(cx, |project, cx| {
16446 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16447 })
16448 }
16449}
16450
16451fn snippet_completions(
16452 project: &Project,
16453 buffer: &Entity<Buffer>,
16454 buffer_position: text::Anchor,
16455 cx: &mut App,
16456) -> Task<Result<Vec<Completion>>> {
16457 let language = buffer.read(cx).language_at(buffer_position);
16458 let language_name = language.as_ref().map(|language| language.lsp_id());
16459 let snippet_store = project.snippets().read(cx);
16460 let snippets = snippet_store.snippets_for(language_name, cx);
16461
16462 if snippets.is_empty() {
16463 return Task::ready(Ok(vec![]));
16464 }
16465 let snapshot = buffer.read(cx).text_snapshot();
16466 let chars: String = snapshot
16467 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16468 .collect();
16469
16470 let scope = language.map(|language| language.default_scope());
16471 let executor = cx.background_executor().clone();
16472
16473 cx.background_spawn(async move {
16474 let classifier = CharClassifier::new(scope).for_completion(true);
16475 let mut last_word = chars
16476 .chars()
16477 .take_while(|c| classifier.is_word(*c))
16478 .collect::<String>();
16479 last_word = last_word.chars().rev().collect();
16480
16481 if last_word.is_empty() {
16482 return Ok(vec![]);
16483 }
16484
16485 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16486 let to_lsp = |point: &text::Anchor| {
16487 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16488 point_to_lsp(end)
16489 };
16490 let lsp_end = to_lsp(&buffer_position);
16491
16492 let candidates = snippets
16493 .iter()
16494 .enumerate()
16495 .flat_map(|(ix, snippet)| {
16496 snippet
16497 .prefix
16498 .iter()
16499 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16500 })
16501 .collect::<Vec<StringMatchCandidate>>();
16502
16503 let mut matches = fuzzy::match_strings(
16504 &candidates,
16505 &last_word,
16506 last_word.chars().any(|c| c.is_uppercase()),
16507 100,
16508 &Default::default(),
16509 executor,
16510 )
16511 .await;
16512
16513 // Remove all candidates where the query's start does not match the start of any word in the candidate
16514 if let Some(query_start) = last_word.chars().next() {
16515 matches.retain(|string_match| {
16516 split_words(&string_match.string).any(|word| {
16517 // Check that the first codepoint of the word as lowercase matches the first
16518 // codepoint of the query as lowercase
16519 word.chars()
16520 .flat_map(|codepoint| codepoint.to_lowercase())
16521 .zip(query_start.to_lowercase())
16522 .all(|(word_cp, query_cp)| word_cp == query_cp)
16523 })
16524 });
16525 }
16526
16527 let matched_strings = matches
16528 .into_iter()
16529 .map(|m| m.string)
16530 .collect::<HashSet<_>>();
16531
16532 let result: Vec<Completion> = snippets
16533 .into_iter()
16534 .filter_map(|snippet| {
16535 let matching_prefix = snippet
16536 .prefix
16537 .iter()
16538 .find(|prefix| matched_strings.contains(*prefix))?;
16539 let start = as_offset - last_word.len();
16540 let start = snapshot.anchor_before(start);
16541 let range = start..buffer_position;
16542 let lsp_start = to_lsp(&start);
16543 let lsp_range = lsp::Range {
16544 start: lsp_start,
16545 end: lsp_end,
16546 };
16547 Some(Completion {
16548 old_range: range,
16549 new_text: snippet.body.clone(),
16550 resolved: false,
16551 label: CodeLabel {
16552 text: matching_prefix.clone(),
16553 runs: vec![],
16554 filter_range: 0..matching_prefix.len(),
16555 },
16556 server_id: LanguageServerId(usize::MAX),
16557 documentation: snippet
16558 .description
16559 .clone()
16560 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16561 lsp_completion: lsp::CompletionItem {
16562 label: snippet.prefix.first().unwrap().clone(),
16563 kind: Some(CompletionItemKind::SNIPPET),
16564 label_details: snippet.description.as_ref().map(|description| {
16565 lsp::CompletionItemLabelDetails {
16566 detail: Some(description.clone()),
16567 description: None,
16568 }
16569 }),
16570 insert_text_format: Some(InsertTextFormat::SNIPPET),
16571 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16572 lsp::InsertReplaceEdit {
16573 new_text: snippet.body.clone(),
16574 insert: lsp_range,
16575 replace: lsp_range,
16576 },
16577 )),
16578 filter_text: Some(snippet.body.clone()),
16579 sort_text: Some(char::MAX.to_string()),
16580 ..Default::default()
16581 },
16582 confirm: None,
16583 })
16584 })
16585 .collect();
16586
16587 Ok(result)
16588 })
16589}
16590
16591impl CompletionProvider for Entity<Project> {
16592 fn completions(
16593 &self,
16594 buffer: &Entity<Buffer>,
16595 buffer_position: text::Anchor,
16596 options: CompletionContext,
16597 _window: &mut Window,
16598 cx: &mut Context<Editor>,
16599 ) -> Task<Result<Vec<Completion>>> {
16600 self.update(cx, |project, cx| {
16601 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16602 let project_completions = project.completions(buffer, buffer_position, options, cx);
16603 cx.background_spawn(async move {
16604 let mut completions = project_completions.await?;
16605 let snippets_completions = snippets.await?;
16606 completions.extend(snippets_completions);
16607 Ok(completions)
16608 })
16609 })
16610 }
16611
16612 fn resolve_completions(
16613 &self,
16614 buffer: Entity<Buffer>,
16615 completion_indices: Vec<usize>,
16616 completions: Rc<RefCell<Box<[Completion]>>>,
16617 cx: &mut Context<Editor>,
16618 ) -> Task<Result<bool>> {
16619 self.update(cx, |project, cx| {
16620 project.lsp_store().update(cx, |lsp_store, cx| {
16621 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16622 })
16623 })
16624 }
16625
16626 fn apply_additional_edits_for_completion(
16627 &self,
16628 buffer: Entity<Buffer>,
16629 completions: Rc<RefCell<Box<[Completion]>>>,
16630 completion_index: usize,
16631 push_to_history: bool,
16632 cx: &mut Context<Editor>,
16633 ) -> Task<Result<Option<language::Transaction>>> {
16634 self.update(cx, |project, cx| {
16635 project.lsp_store().update(cx, |lsp_store, cx| {
16636 lsp_store.apply_additional_edits_for_completion(
16637 buffer,
16638 completions,
16639 completion_index,
16640 push_to_history,
16641 cx,
16642 )
16643 })
16644 })
16645 }
16646
16647 fn is_completion_trigger(
16648 &self,
16649 buffer: &Entity<Buffer>,
16650 position: language::Anchor,
16651 text: &str,
16652 trigger_in_words: bool,
16653 cx: &mut Context<Editor>,
16654 ) -> bool {
16655 let mut chars = text.chars();
16656 let char = if let Some(char) = chars.next() {
16657 char
16658 } else {
16659 return false;
16660 };
16661 if chars.next().is_some() {
16662 return false;
16663 }
16664
16665 let buffer = buffer.read(cx);
16666 let snapshot = buffer.snapshot();
16667 if !snapshot.settings_at(position, cx).show_completions_on_input {
16668 return false;
16669 }
16670 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16671 if trigger_in_words && classifier.is_word(char) {
16672 return true;
16673 }
16674
16675 buffer.completion_triggers().contains(text)
16676 }
16677}
16678
16679impl SemanticsProvider for Entity<Project> {
16680 fn hover(
16681 &self,
16682 buffer: &Entity<Buffer>,
16683 position: text::Anchor,
16684 cx: &mut App,
16685 ) -> Option<Task<Vec<project::Hover>>> {
16686 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16687 }
16688
16689 fn document_highlights(
16690 &self,
16691 buffer: &Entity<Buffer>,
16692 position: text::Anchor,
16693 cx: &mut App,
16694 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16695 Some(self.update(cx, |project, cx| {
16696 project.document_highlights(buffer, position, cx)
16697 }))
16698 }
16699
16700 fn definitions(
16701 &self,
16702 buffer: &Entity<Buffer>,
16703 position: text::Anchor,
16704 kind: GotoDefinitionKind,
16705 cx: &mut App,
16706 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16707 Some(self.update(cx, |project, cx| match kind {
16708 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16709 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16710 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16711 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16712 }))
16713 }
16714
16715 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16716 // TODO: make this work for remote projects
16717 self.update(cx, |this, cx| {
16718 buffer.update(cx, |buffer, cx| {
16719 this.any_language_server_supports_inlay_hints(buffer, cx)
16720 })
16721 })
16722 }
16723
16724 fn inlay_hints(
16725 &self,
16726 buffer_handle: Entity<Buffer>,
16727 range: Range<text::Anchor>,
16728 cx: &mut App,
16729 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16730 Some(self.update(cx, |project, cx| {
16731 project.inlay_hints(buffer_handle, range, cx)
16732 }))
16733 }
16734
16735 fn resolve_inlay_hint(
16736 &self,
16737 hint: InlayHint,
16738 buffer_handle: Entity<Buffer>,
16739 server_id: LanguageServerId,
16740 cx: &mut App,
16741 ) -> Option<Task<anyhow::Result<InlayHint>>> {
16742 Some(self.update(cx, |project, cx| {
16743 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16744 }))
16745 }
16746
16747 fn range_for_rename(
16748 &self,
16749 buffer: &Entity<Buffer>,
16750 position: text::Anchor,
16751 cx: &mut App,
16752 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16753 Some(self.update(cx, |project, cx| {
16754 let buffer = buffer.clone();
16755 let task = project.prepare_rename(buffer.clone(), position, cx);
16756 cx.spawn(|_, mut cx| async move {
16757 Ok(match task.await? {
16758 PrepareRenameResponse::Success(range) => Some(range),
16759 PrepareRenameResponse::InvalidPosition => None,
16760 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16761 // Fallback on using TreeSitter info to determine identifier range
16762 buffer.update(&mut cx, |buffer, _| {
16763 let snapshot = buffer.snapshot();
16764 let (range, kind) = snapshot.surrounding_word(position);
16765 if kind != Some(CharKind::Word) {
16766 return None;
16767 }
16768 Some(
16769 snapshot.anchor_before(range.start)
16770 ..snapshot.anchor_after(range.end),
16771 )
16772 })?
16773 }
16774 })
16775 })
16776 }))
16777 }
16778
16779 fn perform_rename(
16780 &self,
16781 buffer: &Entity<Buffer>,
16782 position: text::Anchor,
16783 new_name: String,
16784 cx: &mut App,
16785 ) -> Option<Task<Result<ProjectTransaction>>> {
16786 Some(self.update(cx, |project, cx| {
16787 project.perform_rename(buffer.clone(), position, new_name, cx)
16788 }))
16789 }
16790}
16791
16792fn inlay_hint_settings(
16793 location: Anchor,
16794 snapshot: &MultiBufferSnapshot,
16795 cx: &mut Context<Editor>,
16796) -> InlayHintSettings {
16797 let file = snapshot.file_at(location);
16798 let language = snapshot.language_at(location).map(|l| l.name());
16799 language_settings(language, file, cx).inlay_hints
16800}
16801
16802fn consume_contiguous_rows(
16803 contiguous_row_selections: &mut Vec<Selection<Point>>,
16804 selection: &Selection<Point>,
16805 display_map: &DisplaySnapshot,
16806 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16807) -> (MultiBufferRow, MultiBufferRow) {
16808 contiguous_row_selections.push(selection.clone());
16809 let start_row = MultiBufferRow(selection.start.row);
16810 let mut end_row = ending_row(selection, display_map);
16811
16812 while let Some(next_selection) = selections.peek() {
16813 if next_selection.start.row <= end_row.0 {
16814 end_row = ending_row(next_selection, display_map);
16815 contiguous_row_selections.push(selections.next().unwrap().clone());
16816 } else {
16817 break;
16818 }
16819 }
16820 (start_row, end_row)
16821}
16822
16823fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16824 if next_selection.end.column > 0 || next_selection.is_empty() {
16825 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16826 } else {
16827 MultiBufferRow(next_selection.end.row)
16828 }
16829}
16830
16831impl EditorSnapshot {
16832 pub fn remote_selections_in_range<'a>(
16833 &'a self,
16834 range: &'a Range<Anchor>,
16835 collaboration_hub: &dyn CollaborationHub,
16836 cx: &'a App,
16837 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16838 let participant_names = collaboration_hub.user_names(cx);
16839 let participant_indices = collaboration_hub.user_participant_indices(cx);
16840 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16841 let collaborators_by_replica_id = collaborators_by_peer_id
16842 .iter()
16843 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16844 .collect::<HashMap<_, _>>();
16845 self.buffer_snapshot
16846 .selections_in_range(range, false)
16847 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16848 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16849 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16850 let user_name = participant_names.get(&collaborator.user_id).cloned();
16851 Some(RemoteSelection {
16852 replica_id,
16853 selection,
16854 cursor_shape,
16855 line_mode,
16856 participant_index,
16857 peer_id: collaborator.peer_id,
16858 user_name,
16859 })
16860 })
16861 }
16862
16863 pub fn hunks_for_ranges(
16864 &self,
16865 ranges: impl Iterator<Item = Range<Point>>,
16866 ) -> Vec<MultiBufferDiffHunk> {
16867 let mut hunks = Vec::new();
16868 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16869 HashMap::default();
16870 for query_range in ranges {
16871 let query_rows =
16872 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16873 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16874 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16875 ) {
16876 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16877 // when the caret is just above or just below the deleted hunk.
16878 let allow_adjacent = hunk.status().is_deleted();
16879 let related_to_selection = if allow_adjacent {
16880 hunk.row_range.overlaps(&query_rows)
16881 || hunk.row_range.start == query_rows.end
16882 || hunk.row_range.end == query_rows.start
16883 } else {
16884 hunk.row_range.overlaps(&query_rows)
16885 };
16886 if related_to_selection {
16887 if !processed_buffer_rows
16888 .entry(hunk.buffer_id)
16889 .or_default()
16890 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16891 {
16892 continue;
16893 }
16894 hunks.push(hunk);
16895 }
16896 }
16897 }
16898
16899 hunks
16900 }
16901
16902 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16903 self.display_snapshot.buffer_snapshot.language_at(position)
16904 }
16905
16906 pub fn is_focused(&self) -> bool {
16907 self.is_focused
16908 }
16909
16910 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16911 self.placeholder_text.as_ref()
16912 }
16913
16914 pub fn scroll_position(&self) -> gpui::Point<f32> {
16915 self.scroll_anchor.scroll_position(&self.display_snapshot)
16916 }
16917
16918 fn gutter_dimensions(
16919 &self,
16920 font_id: FontId,
16921 font_size: Pixels,
16922 max_line_number_width: Pixels,
16923 cx: &App,
16924 ) -> Option<GutterDimensions> {
16925 if !self.show_gutter {
16926 return None;
16927 }
16928
16929 let descent = cx.text_system().descent(font_id, font_size);
16930 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16931 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16932
16933 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16934 matches!(
16935 ProjectSettings::get_global(cx).git.git_gutter,
16936 Some(GitGutterSetting::TrackedFiles)
16937 )
16938 });
16939 let gutter_settings = EditorSettings::get_global(cx).gutter;
16940 let show_line_numbers = self
16941 .show_line_numbers
16942 .unwrap_or(gutter_settings.line_numbers);
16943 let line_gutter_width = if show_line_numbers {
16944 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16945 let min_width_for_number_on_gutter = em_advance * 4.0;
16946 max_line_number_width.max(min_width_for_number_on_gutter)
16947 } else {
16948 0.0.into()
16949 };
16950
16951 let show_code_actions = self
16952 .show_code_actions
16953 .unwrap_or(gutter_settings.code_actions);
16954
16955 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16956
16957 let git_blame_entries_width =
16958 self.git_blame_gutter_max_author_length
16959 .map(|max_author_length| {
16960 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16961
16962 /// The number of characters to dedicate to gaps and margins.
16963 const SPACING_WIDTH: usize = 4;
16964
16965 let max_char_count = max_author_length
16966 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16967 + ::git::SHORT_SHA_LENGTH
16968 + MAX_RELATIVE_TIMESTAMP.len()
16969 + SPACING_WIDTH;
16970
16971 em_advance * max_char_count
16972 });
16973
16974 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16975 left_padding += if show_code_actions || show_runnables {
16976 em_width * 3.0
16977 } else if show_git_gutter && show_line_numbers {
16978 em_width * 2.0
16979 } else if show_git_gutter || show_line_numbers {
16980 em_width
16981 } else {
16982 px(0.)
16983 };
16984
16985 let right_padding = if gutter_settings.folds && show_line_numbers {
16986 em_width * 4.0
16987 } else if gutter_settings.folds {
16988 em_width * 3.0
16989 } else if show_line_numbers {
16990 em_width
16991 } else {
16992 px(0.)
16993 };
16994
16995 Some(GutterDimensions {
16996 left_padding,
16997 right_padding,
16998 width: line_gutter_width + left_padding + right_padding,
16999 margin: -descent,
17000 git_blame_entries_width,
17001 })
17002 }
17003
17004 pub fn render_crease_toggle(
17005 &self,
17006 buffer_row: MultiBufferRow,
17007 row_contains_cursor: bool,
17008 editor: Entity<Editor>,
17009 window: &mut Window,
17010 cx: &mut App,
17011 ) -> Option<AnyElement> {
17012 let folded = self.is_line_folded(buffer_row);
17013 let mut is_foldable = false;
17014
17015 if let Some(crease) = self
17016 .crease_snapshot
17017 .query_row(buffer_row, &self.buffer_snapshot)
17018 {
17019 is_foldable = true;
17020 match crease {
17021 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17022 if let Some(render_toggle) = render_toggle {
17023 let toggle_callback =
17024 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17025 if folded {
17026 editor.update(cx, |editor, cx| {
17027 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17028 });
17029 } else {
17030 editor.update(cx, |editor, cx| {
17031 editor.unfold_at(
17032 &crate::UnfoldAt { buffer_row },
17033 window,
17034 cx,
17035 )
17036 });
17037 }
17038 });
17039 return Some((render_toggle)(
17040 buffer_row,
17041 folded,
17042 toggle_callback,
17043 window,
17044 cx,
17045 ));
17046 }
17047 }
17048 }
17049 }
17050
17051 is_foldable |= self.starts_indent(buffer_row);
17052
17053 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17054 Some(
17055 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17056 .toggle_state(folded)
17057 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17058 if folded {
17059 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17060 } else {
17061 this.fold_at(&FoldAt { buffer_row }, window, cx);
17062 }
17063 }))
17064 .into_any_element(),
17065 )
17066 } else {
17067 None
17068 }
17069 }
17070
17071 pub fn render_crease_trailer(
17072 &self,
17073 buffer_row: MultiBufferRow,
17074 window: &mut Window,
17075 cx: &mut App,
17076 ) -> Option<AnyElement> {
17077 let folded = self.is_line_folded(buffer_row);
17078 if let Crease::Inline { render_trailer, .. } = self
17079 .crease_snapshot
17080 .query_row(buffer_row, &self.buffer_snapshot)?
17081 {
17082 let render_trailer = render_trailer.as_ref()?;
17083 Some(render_trailer(buffer_row, folded, window, cx))
17084 } else {
17085 None
17086 }
17087 }
17088}
17089
17090impl Deref for EditorSnapshot {
17091 type Target = DisplaySnapshot;
17092
17093 fn deref(&self) -> &Self::Target {
17094 &self.display_snapshot
17095 }
17096}
17097
17098#[derive(Clone, Debug, PartialEq, Eq)]
17099pub enum EditorEvent {
17100 InputIgnored {
17101 text: Arc<str>,
17102 },
17103 InputHandled {
17104 utf16_range_to_replace: Option<Range<isize>>,
17105 text: Arc<str>,
17106 },
17107 ExcerptsAdded {
17108 buffer: Entity<Buffer>,
17109 predecessor: ExcerptId,
17110 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17111 },
17112 ExcerptsRemoved {
17113 ids: Vec<ExcerptId>,
17114 },
17115 BufferFoldToggled {
17116 ids: Vec<ExcerptId>,
17117 folded: bool,
17118 },
17119 ExcerptsEdited {
17120 ids: Vec<ExcerptId>,
17121 },
17122 ExcerptsExpanded {
17123 ids: Vec<ExcerptId>,
17124 },
17125 BufferEdited,
17126 Edited {
17127 transaction_id: clock::Lamport,
17128 },
17129 Reparsed(BufferId),
17130 Focused,
17131 FocusedIn,
17132 Blurred,
17133 DirtyChanged,
17134 Saved,
17135 TitleChanged,
17136 DiffBaseChanged,
17137 SelectionsChanged {
17138 local: bool,
17139 },
17140 ScrollPositionChanged {
17141 local: bool,
17142 autoscroll: bool,
17143 },
17144 Closed,
17145 TransactionUndone {
17146 transaction_id: clock::Lamport,
17147 },
17148 TransactionBegun {
17149 transaction_id: clock::Lamport,
17150 },
17151 Reloaded,
17152 CursorShapeChanged,
17153}
17154
17155impl EventEmitter<EditorEvent> for Editor {}
17156
17157impl Focusable for Editor {
17158 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17159 self.focus_handle.clone()
17160 }
17161}
17162
17163impl Render for Editor {
17164 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17165 let settings = ThemeSettings::get_global(cx);
17166
17167 let mut text_style = match self.mode {
17168 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17169 color: cx.theme().colors().editor_foreground,
17170 font_family: settings.ui_font.family.clone(),
17171 font_features: settings.ui_font.features.clone(),
17172 font_fallbacks: settings.ui_font.fallbacks.clone(),
17173 font_size: rems(0.875).into(),
17174 font_weight: settings.ui_font.weight,
17175 line_height: relative(settings.buffer_line_height.value()),
17176 ..Default::default()
17177 },
17178 EditorMode::Full => TextStyle {
17179 color: cx.theme().colors().editor_foreground,
17180 font_family: settings.buffer_font.family.clone(),
17181 font_features: settings.buffer_font.features.clone(),
17182 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17183 font_size: settings.buffer_font_size(cx).into(),
17184 font_weight: settings.buffer_font.weight,
17185 line_height: relative(settings.buffer_line_height.value()),
17186 ..Default::default()
17187 },
17188 };
17189 if let Some(text_style_refinement) = &self.text_style_refinement {
17190 text_style.refine(text_style_refinement)
17191 }
17192
17193 let background = match self.mode {
17194 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17195 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17196 EditorMode::Full => cx.theme().colors().editor_background,
17197 };
17198
17199 EditorElement::new(
17200 &cx.entity(),
17201 EditorStyle {
17202 background,
17203 local_player: cx.theme().players().local(),
17204 text: text_style,
17205 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17206 syntax: cx.theme().syntax().clone(),
17207 status: cx.theme().status().clone(),
17208 inlay_hints_style: make_inlay_hints_style(cx),
17209 inline_completion_styles: make_suggestion_styles(cx),
17210 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17211 },
17212 )
17213 }
17214}
17215
17216impl EntityInputHandler for Editor {
17217 fn text_for_range(
17218 &mut self,
17219 range_utf16: Range<usize>,
17220 adjusted_range: &mut Option<Range<usize>>,
17221 _: &mut Window,
17222 cx: &mut Context<Self>,
17223 ) -> Option<String> {
17224 let snapshot = self.buffer.read(cx).read(cx);
17225 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17226 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17227 if (start.0..end.0) != range_utf16 {
17228 adjusted_range.replace(start.0..end.0);
17229 }
17230 Some(snapshot.text_for_range(start..end).collect())
17231 }
17232
17233 fn selected_text_range(
17234 &mut self,
17235 ignore_disabled_input: bool,
17236 _: &mut Window,
17237 cx: &mut Context<Self>,
17238 ) -> Option<UTF16Selection> {
17239 // Prevent the IME menu from appearing when holding down an alphabetic key
17240 // while input is disabled.
17241 if !ignore_disabled_input && !self.input_enabled {
17242 return None;
17243 }
17244
17245 let selection = self.selections.newest::<OffsetUtf16>(cx);
17246 let range = selection.range();
17247
17248 Some(UTF16Selection {
17249 range: range.start.0..range.end.0,
17250 reversed: selection.reversed,
17251 })
17252 }
17253
17254 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17255 let snapshot = self.buffer.read(cx).read(cx);
17256 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17257 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17258 }
17259
17260 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17261 self.clear_highlights::<InputComposition>(cx);
17262 self.ime_transaction.take();
17263 }
17264
17265 fn replace_text_in_range(
17266 &mut self,
17267 range_utf16: Option<Range<usize>>,
17268 text: &str,
17269 window: &mut Window,
17270 cx: &mut Context<Self>,
17271 ) {
17272 if !self.input_enabled {
17273 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17274 return;
17275 }
17276
17277 self.transact(window, cx, |this, window, cx| {
17278 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17279 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17280 Some(this.selection_replacement_ranges(range_utf16, cx))
17281 } else {
17282 this.marked_text_ranges(cx)
17283 };
17284
17285 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17286 let newest_selection_id = this.selections.newest_anchor().id;
17287 this.selections
17288 .all::<OffsetUtf16>(cx)
17289 .iter()
17290 .zip(ranges_to_replace.iter())
17291 .find_map(|(selection, range)| {
17292 if selection.id == newest_selection_id {
17293 Some(
17294 (range.start.0 as isize - selection.head().0 as isize)
17295 ..(range.end.0 as isize - selection.head().0 as isize),
17296 )
17297 } else {
17298 None
17299 }
17300 })
17301 });
17302
17303 cx.emit(EditorEvent::InputHandled {
17304 utf16_range_to_replace: range_to_replace,
17305 text: text.into(),
17306 });
17307
17308 if let Some(new_selected_ranges) = new_selected_ranges {
17309 this.change_selections(None, window, cx, |selections| {
17310 selections.select_ranges(new_selected_ranges)
17311 });
17312 this.backspace(&Default::default(), window, cx);
17313 }
17314
17315 this.handle_input(text, window, cx);
17316 });
17317
17318 if let Some(transaction) = self.ime_transaction {
17319 self.buffer.update(cx, |buffer, cx| {
17320 buffer.group_until_transaction(transaction, cx);
17321 });
17322 }
17323
17324 self.unmark_text(window, cx);
17325 }
17326
17327 fn replace_and_mark_text_in_range(
17328 &mut self,
17329 range_utf16: Option<Range<usize>>,
17330 text: &str,
17331 new_selected_range_utf16: Option<Range<usize>>,
17332 window: &mut Window,
17333 cx: &mut Context<Self>,
17334 ) {
17335 if !self.input_enabled {
17336 return;
17337 }
17338
17339 let transaction = self.transact(window, cx, |this, window, cx| {
17340 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17341 let snapshot = this.buffer.read(cx).read(cx);
17342 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17343 for marked_range in &mut marked_ranges {
17344 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17345 marked_range.start.0 += relative_range_utf16.start;
17346 marked_range.start =
17347 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17348 marked_range.end =
17349 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17350 }
17351 }
17352 Some(marked_ranges)
17353 } else if let Some(range_utf16) = range_utf16 {
17354 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17355 Some(this.selection_replacement_ranges(range_utf16, cx))
17356 } else {
17357 None
17358 };
17359
17360 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17361 let newest_selection_id = this.selections.newest_anchor().id;
17362 this.selections
17363 .all::<OffsetUtf16>(cx)
17364 .iter()
17365 .zip(ranges_to_replace.iter())
17366 .find_map(|(selection, range)| {
17367 if selection.id == newest_selection_id {
17368 Some(
17369 (range.start.0 as isize - selection.head().0 as isize)
17370 ..(range.end.0 as isize - selection.head().0 as isize),
17371 )
17372 } else {
17373 None
17374 }
17375 })
17376 });
17377
17378 cx.emit(EditorEvent::InputHandled {
17379 utf16_range_to_replace: range_to_replace,
17380 text: text.into(),
17381 });
17382
17383 if let Some(ranges) = ranges_to_replace {
17384 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17385 }
17386
17387 let marked_ranges = {
17388 let snapshot = this.buffer.read(cx).read(cx);
17389 this.selections
17390 .disjoint_anchors()
17391 .iter()
17392 .map(|selection| {
17393 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17394 })
17395 .collect::<Vec<_>>()
17396 };
17397
17398 if text.is_empty() {
17399 this.unmark_text(window, cx);
17400 } else {
17401 this.highlight_text::<InputComposition>(
17402 marked_ranges.clone(),
17403 HighlightStyle {
17404 underline: Some(UnderlineStyle {
17405 thickness: px(1.),
17406 color: None,
17407 wavy: false,
17408 }),
17409 ..Default::default()
17410 },
17411 cx,
17412 );
17413 }
17414
17415 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17416 let use_autoclose = this.use_autoclose;
17417 let use_auto_surround = this.use_auto_surround;
17418 this.set_use_autoclose(false);
17419 this.set_use_auto_surround(false);
17420 this.handle_input(text, window, cx);
17421 this.set_use_autoclose(use_autoclose);
17422 this.set_use_auto_surround(use_auto_surround);
17423
17424 if let Some(new_selected_range) = new_selected_range_utf16 {
17425 let snapshot = this.buffer.read(cx).read(cx);
17426 let new_selected_ranges = marked_ranges
17427 .into_iter()
17428 .map(|marked_range| {
17429 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17430 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17431 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17432 snapshot.clip_offset_utf16(new_start, Bias::Left)
17433 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17434 })
17435 .collect::<Vec<_>>();
17436
17437 drop(snapshot);
17438 this.change_selections(None, window, cx, |selections| {
17439 selections.select_ranges(new_selected_ranges)
17440 });
17441 }
17442 });
17443
17444 self.ime_transaction = self.ime_transaction.or(transaction);
17445 if let Some(transaction) = self.ime_transaction {
17446 self.buffer.update(cx, |buffer, cx| {
17447 buffer.group_until_transaction(transaction, cx);
17448 });
17449 }
17450
17451 if self.text_highlights::<InputComposition>(cx).is_none() {
17452 self.ime_transaction.take();
17453 }
17454 }
17455
17456 fn bounds_for_range(
17457 &mut self,
17458 range_utf16: Range<usize>,
17459 element_bounds: gpui::Bounds<Pixels>,
17460 window: &mut Window,
17461 cx: &mut Context<Self>,
17462 ) -> Option<gpui::Bounds<Pixels>> {
17463 let text_layout_details = self.text_layout_details(window);
17464 let gpui::Size {
17465 width: em_width,
17466 height: line_height,
17467 } = self.character_size(window);
17468
17469 let snapshot = self.snapshot(window, cx);
17470 let scroll_position = snapshot.scroll_position();
17471 let scroll_left = scroll_position.x * em_width;
17472
17473 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17474 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17475 + self.gutter_dimensions.width
17476 + self.gutter_dimensions.margin;
17477 let y = line_height * (start.row().as_f32() - scroll_position.y);
17478
17479 Some(Bounds {
17480 origin: element_bounds.origin + point(x, y),
17481 size: size(em_width, line_height),
17482 })
17483 }
17484
17485 fn character_index_for_point(
17486 &mut self,
17487 point: gpui::Point<Pixels>,
17488 _window: &mut Window,
17489 _cx: &mut Context<Self>,
17490 ) -> Option<usize> {
17491 let position_map = self.last_position_map.as_ref()?;
17492 if !position_map.text_hitbox.contains(&point) {
17493 return None;
17494 }
17495 let display_point = position_map.point_for_position(point).previous_valid;
17496 let anchor = position_map
17497 .snapshot
17498 .display_point_to_anchor(display_point, Bias::Left);
17499 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17500 Some(utf16_offset.0)
17501 }
17502}
17503
17504trait SelectionExt {
17505 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17506 fn spanned_rows(
17507 &self,
17508 include_end_if_at_line_start: bool,
17509 map: &DisplaySnapshot,
17510 ) -> Range<MultiBufferRow>;
17511}
17512
17513impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17514 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17515 let start = self
17516 .start
17517 .to_point(&map.buffer_snapshot)
17518 .to_display_point(map);
17519 let end = self
17520 .end
17521 .to_point(&map.buffer_snapshot)
17522 .to_display_point(map);
17523 if self.reversed {
17524 end..start
17525 } else {
17526 start..end
17527 }
17528 }
17529
17530 fn spanned_rows(
17531 &self,
17532 include_end_if_at_line_start: bool,
17533 map: &DisplaySnapshot,
17534 ) -> Range<MultiBufferRow> {
17535 let start = self.start.to_point(&map.buffer_snapshot);
17536 let mut end = self.end.to_point(&map.buffer_snapshot);
17537 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17538 end.row -= 1;
17539 }
17540
17541 let buffer_start = map.prev_line_boundary(start).0;
17542 let buffer_end = map.next_line_boundary(end).0;
17543 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17544 }
17545}
17546
17547impl<T: InvalidationRegion> InvalidationStack<T> {
17548 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17549 where
17550 S: Clone + ToOffset,
17551 {
17552 while let Some(region) = self.last() {
17553 let all_selections_inside_invalidation_ranges =
17554 if selections.len() == region.ranges().len() {
17555 selections
17556 .iter()
17557 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17558 .all(|(selection, invalidation_range)| {
17559 let head = selection.head().to_offset(buffer);
17560 invalidation_range.start <= head && invalidation_range.end >= head
17561 })
17562 } else {
17563 false
17564 };
17565
17566 if all_selections_inside_invalidation_ranges {
17567 break;
17568 } else {
17569 self.pop();
17570 }
17571 }
17572 }
17573}
17574
17575impl<T> Default for InvalidationStack<T> {
17576 fn default() -> Self {
17577 Self(Default::default())
17578 }
17579}
17580
17581impl<T> Deref for InvalidationStack<T> {
17582 type Target = Vec<T>;
17583
17584 fn deref(&self) -> &Self::Target {
17585 &self.0
17586 }
17587}
17588
17589impl<T> DerefMut for InvalidationStack<T> {
17590 fn deref_mut(&mut self) -> &mut Self::Target {
17591 &mut self.0
17592 }
17593}
17594
17595impl InvalidationRegion for SnippetState {
17596 fn ranges(&self) -> &[Range<Anchor>] {
17597 &self.ranges[self.active_index]
17598 }
17599}
17600
17601pub fn diagnostic_block_renderer(
17602 diagnostic: Diagnostic,
17603 max_message_rows: Option<u8>,
17604 allow_closing: bool,
17605 _is_valid: bool,
17606) -> RenderBlock {
17607 let (text_without_backticks, code_ranges) =
17608 highlight_diagnostic_message(&diagnostic, max_message_rows);
17609
17610 Arc::new(move |cx: &mut BlockContext| {
17611 let group_id: SharedString = cx.block_id.to_string().into();
17612
17613 let mut text_style = cx.window.text_style().clone();
17614 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17615 let theme_settings = ThemeSettings::get_global(cx);
17616 text_style.font_family = theme_settings.buffer_font.family.clone();
17617 text_style.font_style = theme_settings.buffer_font.style;
17618 text_style.font_features = theme_settings.buffer_font.features.clone();
17619 text_style.font_weight = theme_settings.buffer_font.weight;
17620
17621 let multi_line_diagnostic = diagnostic.message.contains('\n');
17622
17623 let buttons = |diagnostic: &Diagnostic| {
17624 if multi_line_diagnostic {
17625 v_flex()
17626 } else {
17627 h_flex()
17628 }
17629 .when(allow_closing, |div| {
17630 div.children(diagnostic.is_primary.then(|| {
17631 IconButton::new("close-block", IconName::XCircle)
17632 .icon_color(Color::Muted)
17633 .size(ButtonSize::Compact)
17634 .style(ButtonStyle::Transparent)
17635 .visible_on_hover(group_id.clone())
17636 .on_click(move |_click, window, cx| {
17637 window.dispatch_action(Box::new(Cancel), cx)
17638 })
17639 .tooltip(|window, cx| {
17640 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17641 })
17642 }))
17643 })
17644 .child(
17645 IconButton::new("copy-block", IconName::Copy)
17646 .icon_color(Color::Muted)
17647 .size(ButtonSize::Compact)
17648 .style(ButtonStyle::Transparent)
17649 .visible_on_hover(group_id.clone())
17650 .on_click({
17651 let message = diagnostic.message.clone();
17652 move |_click, _, cx| {
17653 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17654 }
17655 })
17656 .tooltip(Tooltip::text("Copy diagnostic message")),
17657 )
17658 };
17659
17660 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17661 AvailableSpace::min_size(),
17662 cx.window,
17663 cx.app,
17664 );
17665
17666 h_flex()
17667 .id(cx.block_id)
17668 .group(group_id.clone())
17669 .relative()
17670 .size_full()
17671 .block_mouse_down()
17672 .pl(cx.gutter_dimensions.width)
17673 .w(cx.max_width - cx.gutter_dimensions.full_width())
17674 .child(
17675 div()
17676 .flex()
17677 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17678 .flex_shrink(),
17679 )
17680 .child(buttons(&diagnostic))
17681 .child(div().flex().flex_shrink_0().child(
17682 StyledText::new(text_without_backticks.clone()).with_highlights(
17683 &text_style,
17684 code_ranges.iter().map(|range| {
17685 (
17686 range.clone(),
17687 HighlightStyle {
17688 font_weight: Some(FontWeight::BOLD),
17689 ..Default::default()
17690 },
17691 )
17692 }),
17693 ),
17694 ))
17695 .into_any_element()
17696 })
17697}
17698
17699fn inline_completion_edit_text(
17700 current_snapshot: &BufferSnapshot,
17701 edits: &[(Range<Anchor>, String)],
17702 edit_preview: &EditPreview,
17703 include_deletions: bool,
17704 cx: &App,
17705) -> HighlightedText {
17706 let edits = edits
17707 .iter()
17708 .map(|(anchor, text)| {
17709 (
17710 anchor.start.text_anchor..anchor.end.text_anchor,
17711 text.clone(),
17712 )
17713 })
17714 .collect::<Vec<_>>();
17715
17716 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17717}
17718
17719pub fn highlight_diagnostic_message(
17720 diagnostic: &Diagnostic,
17721 mut max_message_rows: Option<u8>,
17722) -> (SharedString, Vec<Range<usize>>) {
17723 let mut text_without_backticks = String::new();
17724 let mut code_ranges = Vec::new();
17725
17726 if let Some(source) = &diagnostic.source {
17727 text_without_backticks.push_str(source);
17728 code_ranges.push(0..source.len());
17729 text_without_backticks.push_str(": ");
17730 }
17731
17732 let mut prev_offset = 0;
17733 let mut in_code_block = false;
17734 let has_row_limit = max_message_rows.is_some();
17735 let mut newline_indices = diagnostic
17736 .message
17737 .match_indices('\n')
17738 .filter(|_| has_row_limit)
17739 .map(|(ix, _)| ix)
17740 .fuse()
17741 .peekable();
17742
17743 for (quote_ix, _) in diagnostic
17744 .message
17745 .match_indices('`')
17746 .chain([(diagnostic.message.len(), "")])
17747 {
17748 let mut first_newline_ix = None;
17749 let mut last_newline_ix = None;
17750 while let Some(newline_ix) = newline_indices.peek() {
17751 if *newline_ix < quote_ix {
17752 if first_newline_ix.is_none() {
17753 first_newline_ix = Some(*newline_ix);
17754 }
17755 last_newline_ix = Some(*newline_ix);
17756
17757 if let Some(rows_left) = &mut max_message_rows {
17758 if *rows_left == 0 {
17759 break;
17760 } else {
17761 *rows_left -= 1;
17762 }
17763 }
17764 let _ = newline_indices.next();
17765 } else {
17766 break;
17767 }
17768 }
17769 let prev_len = text_without_backticks.len();
17770 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17771 text_without_backticks.push_str(new_text);
17772 if in_code_block {
17773 code_ranges.push(prev_len..text_without_backticks.len());
17774 }
17775 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17776 in_code_block = !in_code_block;
17777 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17778 text_without_backticks.push_str("...");
17779 break;
17780 }
17781 }
17782
17783 (text_without_backticks.into(), code_ranges)
17784}
17785
17786fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17787 match severity {
17788 DiagnosticSeverity::ERROR => colors.error,
17789 DiagnosticSeverity::WARNING => colors.warning,
17790 DiagnosticSeverity::INFORMATION => colors.info,
17791 DiagnosticSeverity::HINT => colors.info,
17792 _ => colors.ignored,
17793 }
17794}
17795
17796pub fn styled_runs_for_code_label<'a>(
17797 label: &'a CodeLabel,
17798 syntax_theme: &'a theme::SyntaxTheme,
17799) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17800 let fade_out = HighlightStyle {
17801 fade_out: Some(0.35),
17802 ..Default::default()
17803 };
17804
17805 let mut prev_end = label.filter_range.end;
17806 label
17807 .runs
17808 .iter()
17809 .enumerate()
17810 .flat_map(move |(ix, (range, highlight_id))| {
17811 let style = if let Some(style) = highlight_id.style(syntax_theme) {
17812 style
17813 } else {
17814 return Default::default();
17815 };
17816 let mut muted_style = style;
17817 muted_style.highlight(fade_out);
17818
17819 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17820 if range.start >= label.filter_range.end {
17821 if range.start > prev_end {
17822 runs.push((prev_end..range.start, fade_out));
17823 }
17824 runs.push((range.clone(), muted_style));
17825 } else if range.end <= label.filter_range.end {
17826 runs.push((range.clone(), style));
17827 } else {
17828 runs.push((range.start..label.filter_range.end, style));
17829 runs.push((label.filter_range.end..range.end, muted_style));
17830 }
17831 prev_end = cmp::max(prev_end, range.end);
17832
17833 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17834 runs.push((prev_end..label.text.len(), fade_out));
17835 }
17836
17837 runs
17838 })
17839}
17840
17841pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17842 let mut prev_index = 0;
17843 let mut prev_codepoint: Option<char> = None;
17844 text.char_indices()
17845 .chain([(text.len(), '\0')])
17846 .filter_map(move |(index, codepoint)| {
17847 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17848 let is_boundary = index == text.len()
17849 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17850 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17851 if is_boundary {
17852 let chunk = &text[prev_index..index];
17853 prev_index = index;
17854 Some(chunk)
17855 } else {
17856 None
17857 }
17858 })
17859}
17860
17861pub trait RangeToAnchorExt: Sized {
17862 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17863
17864 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17865 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17866 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17867 }
17868}
17869
17870impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17871 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17872 let start_offset = self.start.to_offset(snapshot);
17873 let end_offset = self.end.to_offset(snapshot);
17874 if start_offset == end_offset {
17875 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17876 } else {
17877 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17878 }
17879 }
17880}
17881
17882pub trait RowExt {
17883 fn as_f32(&self) -> f32;
17884
17885 fn next_row(&self) -> Self;
17886
17887 fn previous_row(&self) -> Self;
17888
17889 fn minus(&self, other: Self) -> u32;
17890}
17891
17892impl RowExt for DisplayRow {
17893 fn as_f32(&self) -> f32 {
17894 self.0 as f32
17895 }
17896
17897 fn next_row(&self) -> Self {
17898 Self(self.0 + 1)
17899 }
17900
17901 fn previous_row(&self) -> Self {
17902 Self(self.0.saturating_sub(1))
17903 }
17904
17905 fn minus(&self, other: Self) -> u32 {
17906 self.0 - other.0
17907 }
17908}
17909
17910impl RowExt for MultiBufferRow {
17911 fn as_f32(&self) -> f32 {
17912 self.0 as f32
17913 }
17914
17915 fn next_row(&self) -> Self {
17916 Self(self.0 + 1)
17917 }
17918
17919 fn previous_row(&self) -> Self {
17920 Self(self.0.saturating_sub(1))
17921 }
17922
17923 fn minus(&self, other: Self) -> u32 {
17924 self.0 - other.0
17925 }
17926}
17927
17928trait RowRangeExt {
17929 type Row;
17930
17931 fn len(&self) -> usize;
17932
17933 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17934}
17935
17936impl RowRangeExt for Range<MultiBufferRow> {
17937 type Row = MultiBufferRow;
17938
17939 fn len(&self) -> usize {
17940 (self.end.0 - self.start.0) as usize
17941 }
17942
17943 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17944 (self.start.0..self.end.0).map(MultiBufferRow)
17945 }
17946}
17947
17948impl RowRangeExt for Range<DisplayRow> {
17949 type Row = DisplayRow;
17950
17951 fn len(&self) -> usize {
17952 (self.end.0 - self.start.0) as usize
17953 }
17954
17955 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17956 (self.start.0..self.end.0).map(DisplayRow)
17957 }
17958}
17959
17960/// If select range has more than one line, we
17961/// just point the cursor to range.start.
17962fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17963 if range.start.row == range.end.row {
17964 range
17965 } else {
17966 range.start..range.start
17967 }
17968}
17969pub struct KillRing(ClipboardItem);
17970impl Global for KillRing {}
17971
17972const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17973
17974fn all_edits_insertions_or_deletions(
17975 edits: &Vec<(Range<Anchor>, String)>,
17976 snapshot: &MultiBufferSnapshot,
17977) -> bool {
17978 let mut all_insertions = true;
17979 let mut all_deletions = true;
17980
17981 for (range, new_text) in edits.iter() {
17982 let range_is_empty = range.to_offset(&snapshot).is_empty();
17983 let text_is_empty = new_text.is_empty();
17984
17985 if range_is_empty != text_is_empty {
17986 if range_is_empty {
17987 all_deletions = false;
17988 } else {
17989 all_insertions = false;
17990 }
17991 } else {
17992 return false;
17993 }
17994
17995 if !all_insertions && !all_deletions {
17996 return false;
17997 }
17998 }
17999 all_insertions || all_deletions
18000}