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 display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26pub mod hover_popover;
27mod indent_guides;
28mod inlay_hint_cache;
29pub mod items;
30mod jsx_tag_auto_close;
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::{Context as _, Result, anyhow};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkStatus;
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::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
62use editor_settings::GoToDefinitionFallback;
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
65 ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use feature_flags::{Debugger, FeatureFlagAppExt};
73use futures::{
74 FutureExt,
75 future::{self, Shared, join},
76};
77use fuzzy::StringMatchCandidate;
78
79use ::git::Restore;
80use code_context_menus::{
81 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
82 CompletionsMenu, ContextMenuOrigin,
83};
84use git::blame::{GitBlame, GlobalBlameRenderer};
85use gpui::{
86 Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
87 AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
88 ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
89 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
90 KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
91 SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
92 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
93 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
94};
95use highlight_matching_bracket::refresh_matching_bracket_highlights;
96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
97pub use hover_popover::hover_markdown_style;
98use hover_popover::{HoverState, hide_hover};
99use indent_guides::ActiveIndentGuidesState;
100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
101pub use inline_completion::Direction;
102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
103pub use items::MAX_TAB_TITLE_LEN;
104use itertools::Itertools;
105use language::{
106 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
107 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
108 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
109 TransactionId, TreeSitterOptions, WordsQuery,
110 language_settings::{
111 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
112 all_language_settings, language_settings,
113 },
114 point_from_lsp, text_diff_with_options,
115};
116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
117use linked_editing_ranges::refresh_linked_ranges;
118use mouse_context_menu::MouseContextMenu;
119use persistence::DB;
120use project::{
121 ProjectPath,
122 debugger::breakpoint_store::{
123 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
124 },
125};
126
127pub use git::blame::BlameRenderer;
128pub use proposed_changes_editor::{
129 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
130};
131use smallvec::smallvec;
132use std::{cell::OnceCell, iter::Peekable};
133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
134
135pub use lsp::CompletionContext;
136use lsp::{
137 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
138 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
139};
140
141use language::BufferSnapshot;
142pub use lsp_ext::lsp_tasks;
143use movement::TextLayoutDetails;
144pub use multi_buffer::{
145 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
146 RowInfo, ToOffset, ToPoint,
147};
148use multi_buffer::{
149 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
150 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
151};
152use parking_lot::Mutex;
153use project::{
154 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
155 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
156 TaskSourceKind,
157 debugger::breakpoint_store::Breakpoint,
158 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
159 project_settings::{GitGutterSetting, ProjectSettings},
160};
161use rand::prelude::*;
162use rpc::{ErrorExt, proto::*};
163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
164use selections_collection::{
165 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
166};
167use serde::{Deserialize, Serialize};
168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
169use smallvec::SmallVec;
170use snippet::Snippet;
171use std::sync::Arc;
172use std::{
173 any::TypeId,
174 borrow::Cow,
175 cell::RefCell,
176 cmp::{self, Ordering, Reverse},
177 mem,
178 num::NonZeroU32,
179 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
180 path::{Path, PathBuf},
181 rc::Rc,
182 time::{Duration, Instant},
183};
184pub use sum_tree::Bias;
185use sum_tree::TreeMap;
186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
187use theme::{
188 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
189 observe_buffer_font_size_adjustment,
190};
191use ui::{
192 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
193 IconSize, Key, Tooltip, h_flex, prelude::*,
194};
195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
196use workspace::{
197 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
198 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
199 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
200 item::{ItemHandle, PreviewTabsSettings},
201 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
202 searchable::SearchEvent,
203};
204
205use crate::hover_links::{find_url, find_url_from_range};
206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
207
208pub const FILE_HEADER_HEIGHT: u32 = 2;
209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
212const MAX_LINE_LEN: usize = 1024;
213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
216#[doc(hidden)]
217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
218
219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
222
223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
226
227pub type RenderDiffHunkControlsFn = Arc<
228 dyn Fn(
229 u32,
230 &DiffHunkStatus,
231 Range<Anchor>,
232 bool,
233 Pixels,
234 &Entity<Editor>,
235 &mut Window,
236 &mut App,
237 ) -> AnyElement,
238>;
239
240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
241 alt: true,
242 shift: true,
243 control: false,
244 platform: false,
245 function: false,
246};
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
249pub enum InlayId {
250 InlineCompletion(usize),
251 Hint(usize),
252}
253
254impl InlayId {
255 fn id(&self) -> usize {
256 match self {
257 Self::InlineCompletion(id) => *id,
258 Self::Hint(id) => *id,
259 }
260 }
261}
262
263pub enum DebugCurrentRowHighlight {}
264enum DocumentHighlightRead {}
265enum DocumentHighlightWrite {}
266enum InputComposition {}
267enum SelectedTextHighlight {}
268
269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
270pub enum Navigated {
271 Yes,
272 No,
273}
274
275impl Navigated {
276 pub fn from_bool(yes: bool) -> Navigated {
277 if yes { Navigated::Yes } else { Navigated::No }
278 }
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
282enum DisplayDiffHunk {
283 Folded {
284 display_row: DisplayRow,
285 },
286 Unfolded {
287 is_created_file: bool,
288 diff_base_byte_range: Range<usize>,
289 display_row_range: Range<DisplayRow>,
290 multi_buffer_range: Range<Anchor>,
291 status: DiffHunkStatus,
292 },
293}
294
295pub enum HideMouseCursorOrigin {
296 TypingAction,
297 MovementAction,
298}
299
300pub fn init_settings(cx: &mut App) {
301 EditorSettings::register(cx);
302}
303
304pub fn init(cx: &mut App) {
305 init_settings(cx);
306
307 cx.set_global(GlobalBlameRenderer(Arc::new(())));
308
309 workspace::register_project_item::<Editor>(cx);
310 workspace::FollowableViewRegistry::register::<Editor>(cx);
311 workspace::register_serializable_item::<Editor>(cx);
312
313 cx.observe_new(
314 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
315 workspace.register_action(Editor::new_file);
316 workspace.register_action(Editor::new_file_vertical);
317 workspace.register_action(Editor::new_file_horizontal);
318 workspace.register_action(Editor::cancel_language_server_work);
319 },
320 )
321 .detach();
322
323 cx.on_action(move |_: &workspace::NewFile, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(
327 Default::default(),
328 app_state,
329 cx,
330 |workspace, window, cx| {
331 Editor::new_file(workspace, &Default::default(), window, cx)
332 },
333 )
334 .detach();
335 }
336 });
337 cx.on_action(move |_: &workspace::NewWindow, cx| {
338 let app_state = workspace::AppState::global(cx);
339 if let Some(app_state) = app_state.upgrade() {
340 workspace::open_new(
341 Default::default(),
342 app_state,
343 cx,
344 |workspace, window, cx| {
345 cx.activate(true);
346 Editor::new_file(workspace, &Default::default(), window, cx)
347 },
348 )
349 .detach();
350 }
351 });
352}
353
354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
355 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
356}
357
358pub trait DiagnosticRenderer {
359 fn render_group(
360 &self,
361 diagnostic_group: Vec<DiagnosticEntry<Point>>,
362 buffer_id: BufferId,
363 snapshot: EditorSnapshot,
364 editor: WeakEntity<Editor>,
365 cx: &mut App,
366 ) -> Vec<BlockProperties<Anchor>>;
367}
368
369pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
370
371impl gpui::Global for GlobalDiagnosticRenderer {}
372pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
373 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
374}
375
376pub struct SearchWithinRange;
377
378trait InvalidationRegion {
379 fn ranges(&self) -> &[Range<Anchor>];
380}
381
382#[derive(Clone, Debug, PartialEq)]
383pub enum SelectPhase {
384 Begin {
385 position: DisplayPoint,
386 add: bool,
387 click_count: usize,
388 },
389 BeginColumnar {
390 position: DisplayPoint,
391 reset: bool,
392 goal_column: u32,
393 },
394 Extend {
395 position: DisplayPoint,
396 click_count: usize,
397 },
398 Update {
399 position: DisplayPoint,
400 goal_column: u32,
401 scroll_delta: gpui::Point<f32>,
402 },
403 End,
404}
405
406#[derive(Clone, Debug)]
407pub enum SelectMode {
408 Character,
409 Word(Range<Anchor>),
410 Line(Range<Anchor>),
411 All,
412}
413
414#[derive(Copy, Clone, PartialEq, Eq, Debug)]
415pub enum EditorMode {
416 SingleLine {
417 auto_width: bool,
418 },
419 AutoHeight {
420 max_lines: usize,
421 },
422 Full {
423 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
424 scale_ui_elements_with_buffer_font_size: bool,
425 /// When set to `true`, the editor will render a background for the active line.
426 show_active_line_background: bool,
427 },
428}
429
430impl EditorMode {
431 pub fn full() -> Self {
432 Self::Full {
433 scale_ui_elements_with_buffer_font_size: true,
434 show_active_line_background: true,
435 }
436 }
437
438 pub fn is_full(&self) -> bool {
439 matches!(self, Self::Full { .. })
440 }
441}
442
443#[derive(Copy, Clone, Debug)]
444pub enum SoftWrap {
445 /// Prefer not to wrap at all.
446 ///
447 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
448 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
449 GitDiff,
450 /// Prefer a single line generally, unless an overly long line is encountered.
451 None,
452 /// Soft wrap lines that exceed the editor width.
453 EditorWidth,
454 /// Soft wrap lines at the preferred line length.
455 Column(u32),
456 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
457 Bounded(u32),
458}
459
460#[derive(Clone)]
461pub struct EditorStyle {
462 pub background: Hsla,
463 pub local_player: PlayerColor,
464 pub text: TextStyle,
465 pub scrollbar_width: Pixels,
466 pub syntax: Arc<SyntaxTheme>,
467 pub status: StatusColors,
468 pub inlay_hints_style: HighlightStyle,
469 pub inline_completion_styles: InlineCompletionStyles,
470 pub unnecessary_code_fade: f32,
471}
472
473impl Default for EditorStyle {
474 fn default() -> Self {
475 Self {
476 background: Hsla::default(),
477 local_player: PlayerColor::default(),
478 text: TextStyle::default(),
479 scrollbar_width: Pixels::default(),
480 syntax: Default::default(),
481 // HACK: Status colors don't have a real default.
482 // We should look into removing the status colors from the editor
483 // style and retrieve them directly from the theme.
484 status: StatusColors::dark(),
485 inlay_hints_style: HighlightStyle::default(),
486 inline_completion_styles: InlineCompletionStyles {
487 insertion: HighlightStyle::default(),
488 whitespace: HighlightStyle::default(),
489 },
490 unnecessary_code_fade: Default::default(),
491 }
492 }
493}
494
495pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
496 let show_background = language_settings::language_settings(None, None, cx)
497 .inlay_hints
498 .show_background;
499
500 HighlightStyle {
501 color: Some(cx.theme().status().hint),
502 background_color: show_background.then(|| cx.theme().status().hint_background),
503 ..HighlightStyle::default()
504 }
505}
506
507pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
508 InlineCompletionStyles {
509 insertion: HighlightStyle {
510 color: Some(cx.theme().status().predictive),
511 ..HighlightStyle::default()
512 },
513 whitespace: HighlightStyle {
514 background_color: Some(cx.theme().status().created_background),
515 ..HighlightStyle::default()
516 },
517 }
518}
519
520type CompletionId = usize;
521
522pub(crate) enum EditDisplayMode {
523 TabAccept,
524 DiffPopover,
525 Inline,
526}
527
528enum InlineCompletion {
529 Edit {
530 edits: Vec<(Range<Anchor>, String)>,
531 edit_preview: Option<EditPreview>,
532 display_mode: EditDisplayMode,
533 snapshot: BufferSnapshot,
534 },
535 Move {
536 target: Anchor,
537 snapshot: BufferSnapshot,
538 },
539}
540
541struct InlineCompletionState {
542 inlay_ids: Vec<InlayId>,
543 completion: InlineCompletion,
544 completion_id: Option<SharedString>,
545 invalidation_range: Range<Anchor>,
546}
547
548enum EditPredictionSettings {
549 Disabled,
550 Enabled {
551 show_in_menu: bool,
552 preview_requires_modifier: bool,
553 },
554}
555
556enum InlineCompletionHighlight {}
557
558#[derive(Debug, Clone)]
559struct InlineDiagnostic {
560 message: SharedString,
561 group_id: usize,
562 is_primary: bool,
563 start: Point,
564 severity: DiagnosticSeverity,
565}
566
567pub enum MenuInlineCompletionsPolicy {
568 Never,
569 ByProvider,
570}
571
572pub enum EditPredictionPreview {
573 /// Modifier is not pressed
574 Inactive { released_too_fast: bool },
575 /// Modifier pressed
576 Active {
577 since: Instant,
578 previous_scroll_position: Option<ScrollAnchor>,
579 },
580}
581
582impl EditPredictionPreview {
583 pub fn released_too_fast(&self) -> bool {
584 match self {
585 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
586 EditPredictionPreview::Active { .. } => false,
587 }
588 }
589
590 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
591 if let EditPredictionPreview::Active {
592 previous_scroll_position,
593 ..
594 } = self
595 {
596 *previous_scroll_position = scroll_position;
597 }
598 }
599}
600
601pub struct ContextMenuOptions {
602 pub min_entries_visible: usize,
603 pub max_entries_visible: usize,
604 pub placement: Option<ContextMenuPlacement>,
605}
606
607#[derive(Debug, Clone, PartialEq, Eq)]
608pub enum ContextMenuPlacement {
609 Above,
610 Below,
611}
612
613#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
614struct EditorActionId(usize);
615
616impl EditorActionId {
617 pub fn post_inc(&mut self) -> Self {
618 let answer = self.0;
619
620 *self = Self(answer + 1);
621
622 Self(answer)
623 }
624}
625
626// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
627// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
628
629type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
630type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
631
632#[derive(Default)]
633struct ScrollbarMarkerState {
634 scrollbar_size: Size<Pixels>,
635 dirty: bool,
636 markers: Arc<[PaintQuad]>,
637 pending_refresh: Option<Task<Result<()>>>,
638}
639
640impl ScrollbarMarkerState {
641 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
642 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
643 }
644}
645
646#[derive(Clone, Debug)]
647struct RunnableTasks {
648 templates: Vec<(TaskSourceKind, TaskTemplate)>,
649 offset: multi_buffer::Anchor,
650 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
651 column: u32,
652 // Values of all named captures, including those starting with '_'
653 extra_variables: HashMap<String, String>,
654 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
655 context_range: Range<BufferOffset>,
656}
657
658impl RunnableTasks {
659 fn resolve<'a>(
660 &'a self,
661 cx: &'a task::TaskContext,
662 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
663 self.templates.iter().filter_map(|(kind, template)| {
664 template
665 .resolve_task(&kind.to_id_base(), cx)
666 .map(|task| (kind.clone(), task))
667 })
668 }
669}
670
671#[derive(Clone)]
672struct ResolvedTasks {
673 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
674 position: Anchor,
675}
676
677#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
678struct BufferOffset(usize);
679
680// Addons allow storing per-editor state in other crates (e.g. Vim)
681pub trait Addon: 'static {
682 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
683
684 fn render_buffer_header_controls(
685 &self,
686 _: &ExcerptInfo,
687 _: &Window,
688 _: &App,
689 ) -> Option<AnyElement> {
690 None
691 }
692
693 fn to_any(&self) -> &dyn std::any::Any;
694}
695
696/// A set of caret positions, registered when the editor was edited.
697pub struct ChangeList {
698 changes: Vec<Vec<Anchor>>,
699 /// Currently "selected" change.
700 position: Option<usize>,
701}
702
703impl ChangeList {
704 pub fn new() -> Self {
705 Self {
706 changes: Vec::new(),
707 position: None,
708 }
709 }
710
711 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
712 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
713 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
714 if self.changes.is_empty() {
715 return None;
716 }
717
718 let prev = self.position.unwrap_or(self.changes.len());
719 let next = if direction == Direction::Prev {
720 prev.saturating_sub(count)
721 } else {
722 (prev + count).min(self.changes.len() - 1)
723 };
724 self.position = Some(next);
725 self.changes.get(next).map(|anchors| anchors.as_slice())
726 }
727
728 /// Adds a new change to the list, resetting the change list position.
729 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
730 self.position.take();
731 if pop_state {
732 self.changes.pop();
733 }
734 self.changes.push(new_positions.clone());
735 }
736
737 pub fn last(&self) -> Option<&[Anchor]> {
738 self.changes.last().map(|anchors| anchors.as_slice())
739 }
740}
741
742/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
743///
744/// See the [module level documentation](self) for more information.
745pub struct Editor {
746 focus_handle: FocusHandle,
747 last_focused_descendant: Option<WeakFocusHandle>,
748 /// The text buffer being edited
749 buffer: Entity<MultiBuffer>,
750 /// Map of how text in the buffer should be displayed.
751 /// Handles soft wraps, folds, fake inlay text insertions, etc.
752 pub display_map: Entity<DisplayMap>,
753 pub selections: SelectionsCollection,
754 pub scroll_manager: ScrollManager,
755 /// When inline assist editors are linked, they all render cursors because
756 /// typing enters text into each of them, even the ones that aren't focused.
757 pub(crate) show_cursor_when_unfocused: bool,
758 columnar_selection_tail: Option<Anchor>,
759 add_selections_state: Option<AddSelectionsState>,
760 select_next_state: Option<SelectNextState>,
761 select_prev_state: Option<SelectNextState>,
762 selection_history: SelectionHistory,
763 autoclose_regions: Vec<AutocloseRegion>,
764 snippet_stack: InvalidationStack<SnippetState>,
765 select_syntax_node_history: SelectSyntaxNodeHistory,
766 ime_transaction: Option<TransactionId>,
767 active_diagnostics: ActiveDiagnostic,
768 show_inline_diagnostics: bool,
769 inline_diagnostics_update: Task<()>,
770 inline_diagnostics_enabled: bool,
771 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
772 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
773 hard_wrap: Option<usize>,
774
775 // TODO: make this a access method
776 pub project: Option<Entity<Project>>,
777 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
778 completion_provider: Option<Box<dyn CompletionProvider>>,
779 collaboration_hub: Option<Box<dyn CollaborationHub>>,
780 blink_manager: Entity<BlinkManager>,
781 show_cursor_names: bool,
782 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
783 pub show_local_selections: bool,
784 mode: EditorMode,
785 show_breadcrumbs: bool,
786 show_gutter: bool,
787 show_scrollbars: bool,
788 show_line_numbers: Option<bool>,
789 use_relative_line_numbers: Option<bool>,
790 show_git_diff_gutter: Option<bool>,
791 show_code_actions: Option<bool>,
792 show_runnables: Option<bool>,
793 show_breakpoints: Option<bool>,
794 show_wrap_guides: Option<bool>,
795 show_indent_guides: Option<bool>,
796 placeholder_text: Option<Arc<str>>,
797 highlight_order: usize,
798 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
799 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
800 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
801 scrollbar_marker_state: ScrollbarMarkerState,
802 active_indent_guides_state: ActiveIndentGuidesState,
803 nav_history: Option<ItemNavHistory>,
804 context_menu: RefCell<Option<CodeContextMenu>>,
805 context_menu_options: Option<ContextMenuOptions>,
806 mouse_context_menu: Option<MouseContextMenu>,
807 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
808 signature_help_state: SignatureHelpState,
809 auto_signature_help: Option<bool>,
810 find_all_references_task_sources: Vec<Anchor>,
811 next_completion_id: CompletionId,
812 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
813 code_actions_task: Option<Task<Result<()>>>,
814 selection_highlight_task: Option<Task<()>>,
815 document_highlights_task: Option<Task<()>>,
816 linked_editing_range_task: Option<Task<Option<()>>>,
817 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
818 pending_rename: Option<RenameState>,
819 searchable: bool,
820 cursor_shape: CursorShape,
821 current_line_highlight: Option<CurrentLineHighlight>,
822 collapse_matches: bool,
823 autoindent_mode: Option<AutoindentMode>,
824 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
825 input_enabled: bool,
826 use_modal_editing: bool,
827 read_only: bool,
828 leader_peer_id: Option<PeerId>,
829 remote_id: Option<ViewId>,
830 hover_state: HoverState,
831 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
832 gutter_hovered: bool,
833 hovered_link_state: Option<HoveredLinkState>,
834 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
835 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
836 active_inline_completion: Option<InlineCompletionState>,
837 /// Used to prevent flickering as the user types while the menu is open
838 stale_inline_completion_in_menu: Option<InlineCompletionState>,
839 edit_prediction_settings: EditPredictionSettings,
840 inline_completions_hidden_for_vim_mode: bool,
841 show_inline_completions_override: Option<bool>,
842 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
843 edit_prediction_preview: EditPredictionPreview,
844 edit_prediction_indent_conflict: bool,
845 edit_prediction_requires_modifier_in_indent_conflict: bool,
846 inlay_hint_cache: InlayHintCache,
847 next_inlay_id: usize,
848 _subscriptions: Vec<Subscription>,
849 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
850 gutter_dimensions: GutterDimensions,
851 style: Option<EditorStyle>,
852 text_style_refinement: Option<TextStyleRefinement>,
853 next_editor_action_id: EditorActionId,
854 editor_actions:
855 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
856 use_autoclose: bool,
857 use_auto_surround: bool,
858 auto_replace_emoji_shortcode: bool,
859 jsx_tag_auto_close_enabled_in_any_buffer: bool,
860 show_git_blame_gutter: bool,
861 show_git_blame_inline: bool,
862 show_git_blame_inline_delay_task: Option<Task<()>>,
863 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
864 git_blame_inline_enabled: bool,
865 render_diff_hunk_controls: RenderDiffHunkControlsFn,
866 serialize_dirty_buffers: bool,
867 show_selection_menu: Option<bool>,
868 blame: Option<Entity<GitBlame>>,
869 blame_subscription: Option<Subscription>,
870 custom_context_menu: Option<
871 Box<
872 dyn 'static
873 + Fn(
874 &mut Self,
875 DisplayPoint,
876 &mut Window,
877 &mut Context<Self>,
878 ) -> Option<Entity<ui::ContextMenu>>,
879 >,
880 >,
881 last_bounds: Option<Bounds<Pixels>>,
882 last_position_map: Option<Rc<PositionMap>>,
883 expect_bounds_change: Option<Bounds<Pixels>>,
884 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
885 tasks_update_task: Option<Task<()>>,
886 breakpoint_store: Option<Entity<BreakpointStore>>,
887 /// Allow's a user to create a breakpoint by selecting this indicator
888 /// It should be None while a user is not hovering over the gutter
889 /// Otherwise it represents the point that the breakpoint will be shown
890 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
891 in_project_search: bool,
892 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
893 breadcrumb_header: Option<String>,
894 focused_block: Option<FocusedBlock>,
895 next_scroll_position: NextScrollCursorCenterTopBottom,
896 addons: HashMap<TypeId, Box<dyn Addon>>,
897 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
898 load_diff_task: Option<Shared<Task<()>>>,
899 selection_mark_mode: bool,
900 toggle_fold_multiple_buffers: Task<()>,
901 _scroll_cursor_center_top_bottom_task: Task<()>,
902 serialize_selections: Task<()>,
903 serialize_folds: Task<()>,
904 mouse_cursor_hidden: bool,
905 hide_mouse_mode: HideMouseMode,
906 pub change_list: ChangeList,
907}
908
909#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
910enum NextScrollCursorCenterTopBottom {
911 #[default]
912 Center,
913 Top,
914 Bottom,
915}
916
917impl NextScrollCursorCenterTopBottom {
918 fn next(&self) -> Self {
919 match self {
920 Self::Center => Self::Top,
921 Self::Top => Self::Bottom,
922 Self::Bottom => Self::Center,
923 }
924 }
925}
926
927#[derive(Clone)]
928pub struct EditorSnapshot {
929 pub mode: EditorMode,
930 show_gutter: bool,
931 show_line_numbers: Option<bool>,
932 show_git_diff_gutter: Option<bool>,
933 show_code_actions: Option<bool>,
934 show_runnables: Option<bool>,
935 show_breakpoints: Option<bool>,
936 git_blame_gutter_max_author_length: Option<usize>,
937 pub display_snapshot: DisplaySnapshot,
938 pub placeholder_text: Option<Arc<str>>,
939 is_focused: bool,
940 scroll_anchor: ScrollAnchor,
941 ongoing_scroll: OngoingScroll,
942 current_line_highlight: CurrentLineHighlight,
943 gutter_hovered: bool,
944}
945
946#[derive(Default, Debug, Clone, Copy)]
947pub struct GutterDimensions {
948 pub left_padding: Pixels,
949 pub right_padding: Pixels,
950 pub width: Pixels,
951 pub margin: Pixels,
952 pub git_blame_entries_width: Option<Pixels>,
953}
954
955impl GutterDimensions {
956 /// The full width of the space taken up by the gutter.
957 pub fn full_width(&self) -> Pixels {
958 self.margin + self.width
959 }
960
961 /// The width of the space reserved for the fold indicators,
962 /// use alongside 'justify_end' and `gutter_width` to
963 /// right align content with the line numbers
964 pub fn fold_area_width(&self) -> Pixels {
965 self.margin + self.right_padding
966 }
967}
968
969#[derive(Debug)]
970pub struct RemoteSelection {
971 pub replica_id: ReplicaId,
972 pub selection: Selection<Anchor>,
973 pub cursor_shape: CursorShape,
974 pub peer_id: PeerId,
975 pub line_mode: bool,
976 pub participant_index: Option<ParticipantIndex>,
977 pub user_name: Option<SharedString>,
978}
979
980#[derive(Clone, Debug)]
981struct SelectionHistoryEntry {
982 selections: Arc<[Selection<Anchor>]>,
983 select_next_state: Option<SelectNextState>,
984 select_prev_state: Option<SelectNextState>,
985 add_selections_state: Option<AddSelectionsState>,
986}
987
988enum SelectionHistoryMode {
989 Normal,
990 Undoing,
991 Redoing,
992}
993
994#[derive(Clone, PartialEq, Eq, Hash)]
995struct HoveredCursor {
996 replica_id: u16,
997 selection_id: usize,
998}
999
1000impl Default for SelectionHistoryMode {
1001 fn default() -> Self {
1002 Self::Normal
1003 }
1004}
1005
1006#[derive(Default)]
1007struct SelectionHistory {
1008 #[allow(clippy::type_complexity)]
1009 selections_by_transaction:
1010 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1011 mode: SelectionHistoryMode,
1012 undo_stack: VecDeque<SelectionHistoryEntry>,
1013 redo_stack: VecDeque<SelectionHistoryEntry>,
1014}
1015
1016impl SelectionHistory {
1017 fn insert_transaction(
1018 &mut self,
1019 transaction_id: TransactionId,
1020 selections: Arc<[Selection<Anchor>]>,
1021 ) {
1022 self.selections_by_transaction
1023 .insert(transaction_id, (selections, None));
1024 }
1025
1026 #[allow(clippy::type_complexity)]
1027 fn transaction(
1028 &self,
1029 transaction_id: TransactionId,
1030 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1031 self.selections_by_transaction.get(&transaction_id)
1032 }
1033
1034 #[allow(clippy::type_complexity)]
1035 fn transaction_mut(
1036 &mut self,
1037 transaction_id: TransactionId,
1038 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1039 self.selections_by_transaction.get_mut(&transaction_id)
1040 }
1041
1042 fn push(&mut self, entry: SelectionHistoryEntry) {
1043 if !entry.selections.is_empty() {
1044 match self.mode {
1045 SelectionHistoryMode::Normal => {
1046 self.push_undo(entry);
1047 self.redo_stack.clear();
1048 }
1049 SelectionHistoryMode::Undoing => self.push_redo(entry),
1050 SelectionHistoryMode::Redoing => self.push_undo(entry),
1051 }
1052 }
1053 }
1054
1055 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1056 if self
1057 .undo_stack
1058 .back()
1059 .map_or(true, |e| e.selections != entry.selections)
1060 {
1061 self.undo_stack.push_back(entry);
1062 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1063 self.undo_stack.pop_front();
1064 }
1065 }
1066 }
1067
1068 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1069 if self
1070 .redo_stack
1071 .back()
1072 .map_or(true, |e| e.selections != entry.selections)
1073 {
1074 self.redo_stack.push_back(entry);
1075 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1076 self.redo_stack.pop_front();
1077 }
1078 }
1079 }
1080}
1081
1082struct RowHighlight {
1083 index: usize,
1084 range: Range<Anchor>,
1085 color: Hsla,
1086 should_autoscroll: bool,
1087}
1088
1089#[derive(Clone, Debug)]
1090struct AddSelectionsState {
1091 above: bool,
1092 stack: Vec<usize>,
1093}
1094
1095#[derive(Clone)]
1096struct SelectNextState {
1097 query: AhoCorasick,
1098 wordwise: bool,
1099 done: bool,
1100}
1101
1102impl std::fmt::Debug for SelectNextState {
1103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1104 f.debug_struct(std::any::type_name::<Self>())
1105 .field("wordwise", &self.wordwise)
1106 .field("done", &self.done)
1107 .finish()
1108 }
1109}
1110
1111#[derive(Debug)]
1112struct AutocloseRegion {
1113 selection_id: usize,
1114 range: Range<Anchor>,
1115 pair: BracketPair,
1116}
1117
1118#[derive(Debug)]
1119struct SnippetState {
1120 ranges: Vec<Vec<Range<Anchor>>>,
1121 active_index: usize,
1122 choices: Vec<Option<Vec<String>>>,
1123}
1124
1125#[doc(hidden)]
1126pub struct RenameState {
1127 pub range: Range<Anchor>,
1128 pub old_name: Arc<str>,
1129 pub editor: Entity<Editor>,
1130 block_id: CustomBlockId,
1131}
1132
1133struct InvalidationStack<T>(Vec<T>);
1134
1135struct RegisteredInlineCompletionProvider {
1136 provider: Arc<dyn InlineCompletionProviderHandle>,
1137 _subscription: Subscription,
1138}
1139
1140#[derive(Debug, PartialEq, Eq)]
1141pub struct ActiveDiagnosticGroup {
1142 pub active_range: Range<Anchor>,
1143 pub active_message: String,
1144 pub group_id: usize,
1145 pub blocks: HashSet<CustomBlockId>,
1146}
1147
1148#[derive(Debug, PartialEq, Eq)]
1149#[allow(clippy::large_enum_variant)]
1150pub(crate) enum ActiveDiagnostic {
1151 None,
1152 All,
1153 Group(ActiveDiagnosticGroup),
1154}
1155
1156#[derive(Serialize, Deserialize, Clone, Debug)]
1157pub struct ClipboardSelection {
1158 /// The number of bytes in this selection.
1159 pub len: usize,
1160 /// Whether this was a full-line selection.
1161 pub is_entire_line: bool,
1162 /// The indentation of the first line when this content was originally copied.
1163 pub first_line_indent: u32,
1164}
1165
1166// selections, scroll behavior, was newest selection reversed
1167type SelectSyntaxNodeHistoryState = (
1168 Box<[Selection<usize>]>,
1169 SelectSyntaxNodeScrollBehavior,
1170 bool,
1171);
1172
1173#[derive(Default)]
1174struct SelectSyntaxNodeHistory {
1175 stack: Vec<SelectSyntaxNodeHistoryState>,
1176 // disable temporarily to allow changing selections without losing the stack
1177 pub disable_clearing: bool,
1178}
1179
1180impl SelectSyntaxNodeHistory {
1181 pub fn try_clear(&mut self) {
1182 if !self.disable_clearing {
1183 self.stack.clear();
1184 }
1185 }
1186
1187 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1188 self.stack.push(selection);
1189 }
1190
1191 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1192 self.stack.pop()
1193 }
1194}
1195
1196enum SelectSyntaxNodeScrollBehavior {
1197 CursorTop,
1198 FitSelection,
1199 CursorBottom,
1200}
1201
1202#[derive(Debug)]
1203pub(crate) struct NavigationData {
1204 cursor_anchor: Anchor,
1205 cursor_position: Point,
1206 scroll_anchor: ScrollAnchor,
1207 scroll_top_row: u32,
1208}
1209
1210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1211pub enum GotoDefinitionKind {
1212 Symbol,
1213 Declaration,
1214 Type,
1215 Implementation,
1216}
1217
1218#[derive(Debug, Clone)]
1219enum InlayHintRefreshReason {
1220 ModifiersChanged(bool),
1221 Toggle(bool),
1222 SettingsChange(InlayHintSettings),
1223 NewLinesShown,
1224 BufferEdited(HashSet<Arc<Language>>),
1225 RefreshRequested,
1226 ExcerptsRemoved(Vec<ExcerptId>),
1227}
1228
1229impl InlayHintRefreshReason {
1230 fn description(&self) -> &'static str {
1231 match self {
1232 Self::ModifiersChanged(_) => "modifiers changed",
1233 Self::Toggle(_) => "toggle",
1234 Self::SettingsChange(_) => "settings change",
1235 Self::NewLinesShown => "new lines shown",
1236 Self::BufferEdited(_) => "buffer edited",
1237 Self::RefreshRequested => "refresh requested",
1238 Self::ExcerptsRemoved(_) => "excerpts removed",
1239 }
1240 }
1241}
1242
1243pub enum FormatTarget {
1244 Buffers,
1245 Ranges(Vec<Range<MultiBufferPoint>>),
1246}
1247
1248pub(crate) struct FocusedBlock {
1249 id: BlockId,
1250 focus_handle: WeakFocusHandle,
1251}
1252
1253#[derive(Clone)]
1254enum JumpData {
1255 MultiBufferRow {
1256 row: MultiBufferRow,
1257 line_offset_from_top: u32,
1258 },
1259 MultiBufferPoint {
1260 excerpt_id: ExcerptId,
1261 position: Point,
1262 anchor: text::Anchor,
1263 line_offset_from_top: u32,
1264 },
1265}
1266
1267pub enum MultibufferSelectionMode {
1268 First,
1269 All,
1270}
1271
1272#[derive(Clone, Copy, Debug, Default)]
1273pub struct RewrapOptions {
1274 pub override_language_settings: bool,
1275 pub preserve_existing_whitespace: bool,
1276}
1277
1278impl Editor {
1279 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1280 let buffer = cx.new(|cx| Buffer::local("", cx));
1281 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1282 Self::new(
1283 EditorMode::SingleLine { auto_width: false },
1284 buffer,
1285 None,
1286 window,
1287 cx,
1288 )
1289 }
1290
1291 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1292 let buffer = cx.new(|cx| Buffer::local("", cx));
1293 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1294 Self::new(EditorMode::full(), buffer, None, window, cx)
1295 }
1296
1297 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1298 let buffer = cx.new(|cx| Buffer::local("", cx));
1299 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1300 Self::new(
1301 EditorMode::SingleLine { auto_width: true },
1302 buffer,
1303 None,
1304 window,
1305 cx,
1306 )
1307 }
1308
1309 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1310 let buffer = cx.new(|cx| Buffer::local("", cx));
1311 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1312 Self::new(
1313 EditorMode::AutoHeight { max_lines },
1314 buffer,
1315 None,
1316 window,
1317 cx,
1318 )
1319 }
1320
1321 pub fn for_buffer(
1322 buffer: Entity<Buffer>,
1323 project: Option<Entity<Project>>,
1324 window: &mut Window,
1325 cx: &mut Context<Self>,
1326 ) -> Self {
1327 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1328 Self::new(EditorMode::full(), buffer, project, window, cx)
1329 }
1330
1331 pub fn for_multibuffer(
1332 buffer: Entity<MultiBuffer>,
1333 project: Option<Entity<Project>>,
1334 window: &mut Window,
1335 cx: &mut Context<Self>,
1336 ) -> Self {
1337 Self::new(EditorMode::full(), buffer, project, window, cx)
1338 }
1339
1340 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1341 let mut clone = Self::new(
1342 self.mode,
1343 self.buffer.clone(),
1344 self.project.clone(),
1345 window,
1346 cx,
1347 );
1348 self.display_map.update(cx, |display_map, cx| {
1349 let snapshot = display_map.snapshot(cx);
1350 clone.display_map.update(cx, |display_map, cx| {
1351 display_map.set_state(&snapshot, cx);
1352 });
1353 });
1354 clone.folds_did_change(cx);
1355 clone.selections.clone_state(&self.selections);
1356 clone.scroll_manager.clone_state(&self.scroll_manager);
1357 clone.searchable = self.searchable;
1358 clone.read_only = self.read_only;
1359 clone
1360 }
1361
1362 pub fn new(
1363 mode: EditorMode,
1364 buffer: Entity<MultiBuffer>,
1365 project: Option<Entity<Project>>,
1366 window: &mut Window,
1367 cx: &mut Context<Self>,
1368 ) -> Self {
1369 let style = window.text_style();
1370 let font_size = style.font_size.to_pixels(window.rem_size());
1371 let editor = cx.entity().downgrade();
1372 let fold_placeholder = FoldPlaceholder {
1373 constrain_width: true,
1374 render: Arc::new(move |fold_id, fold_range, cx| {
1375 let editor = editor.clone();
1376 div()
1377 .id(fold_id)
1378 .bg(cx.theme().colors().ghost_element_background)
1379 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1380 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1381 .rounded_xs()
1382 .size_full()
1383 .cursor_pointer()
1384 .child("⋯")
1385 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1386 .on_click(move |_, _window, cx| {
1387 editor
1388 .update(cx, |editor, cx| {
1389 editor.unfold_ranges(
1390 &[fold_range.start..fold_range.end],
1391 true,
1392 false,
1393 cx,
1394 );
1395 cx.stop_propagation();
1396 })
1397 .ok();
1398 })
1399 .into_any()
1400 }),
1401 merge_adjacent: true,
1402 ..Default::default()
1403 };
1404 let display_map = cx.new(|cx| {
1405 DisplayMap::new(
1406 buffer.clone(),
1407 style.font(),
1408 font_size,
1409 None,
1410 FILE_HEADER_HEIGHT,
1411 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1412 fold_placeholder,
1413 cx,
1414 )
1415 });
1416
1417 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1418
1419 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1420
1421 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1422 .then(|| language_settings::SoftWrap::None);
1423
1424 let mut project_subscriptions = Vec::new();
1425 if mode.is_full() {
1426 if let Some(project) = project.as_ref() {
1427 project_subscriptions.push(cx.subscribe_in(
1428 project,
1429 window,
1430 |editor, _, event, window, cx| match event {
1431 project::Event::RefreshCodeLens => {
1432 // we always query lens with actions, without storing them, always refreshing them
1433 }
1434 project::Event::RefreshInlayHints => {
1435 editor
1436 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1437 }
1438 project::Event::SnippetEdit(id, snippet_edits) => {
1439 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1440 let focus_handle = editor.focus_handle(cx);
1441 if focus_handle.is_focused(window) {
1442 let snapshot = buffer.read(cx).snapshot();
1443 for (range, snippet) in snippet_edits {
1444 let editor_range =
1445 language::range_from_lsp(*range).to_offset(&snapshot);
1446 editor
1447 .insert_snippet(
1448 &[editor_range],
1449 snippet.clone(),
1450 window,
1451 cx,
1452 )
1453 .ok();
1454 }
1455 }
1456 }
1457 }
1458 _ => {}
1459 },
1460 ));
1461 if let Some(task_inventory) = project
1462 .read(cx)
1463 .task_store()
1464 .read(cx)
1465 .task_inventory()
1466 .cloned()
1467 {
1468 project_subscriptions.push(cx.observe_in(
1469 &task_inventory,
1470 window,
1471 |editor, _, window, cx| {
1472 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1473 },
1474 ));
1475 };
1476
1477 project_subscriptions.push(cx.subscribe_in(
1478 &project.read(cx).breakpoint_store(),
1479 window,
1480 |editor, _, event, window, cx| match event {
1481 BreakpointStoreEvent::ActiveDebugLineChanged => {
1482 if editor.go_to_active_debug_line(window, cx) {
1483 cx.stop_propagation();
1484 }
1485 }
1486 _ => {}
1487 },
1488 ));
1489 }
1490 }
1491
1492 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1493
1494 let inlay_hint_settings =
1495 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1496 let focus_handle = cx.focus_handle();
1497 cx.on_focus(&focus_handle, window, Self::handle_focus)
1498 .detach();
1499 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1500 .detach();
1501 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1502 .detach();
1503 cx.on_blur(&focus_handle, window, Self::handle_blur)
1504 .detach();
1505
1506 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1507 Some(false)
1508 } else {
1509 None
1510 };
1511
1512 let breakpoint_store = match (mode, project.as_ref()) {
1513 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1514 _ => None,
1515 };
1516
1517 let mut code_action_providers = Vec::new();
1518 let mut load_uncommitted_diff = None;
1519 if let Some(project) = project.clone() {
1520 load_uncommitted_diff = Some(
1521 get_uncommitted_diff_for_buffer(
1522 &project,
1523 buffer.read(cx).all_buffers(),
1524 buffer.clone(),
1525 cx,
1526 )
1527 .shared(),
1528 );
1529 code_action_providers.push(Rc::new(project) as Rc<_>);
1530 }
1531
1532 let mut this = Self {
1533 focus_handle,
1534 show_cursor_when_unfocused: false,
1535 last_focused_descendant: None,
1536 buffer: buffer.clone(),
1537 display_map: display_map.clone(),
1538 selections,
1539 scroll_manager: ScrollManager::new(cx),
1540 columnar_selection_tail: None,
1541 add_selections_state: None,
1542 select_next_state: None,
1543 select_prev_state: None,
1544 selection_history: Default::default(),
1545 autoclose_regions: Default::default(),
1546 snippet_stack: Default::default(),
1547 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1548 ime_transaction: Default::default(),
1549 active_diagnostics: ActiveDiagnostic::None,
1550 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1551 inline_diagnostics_update: Task::ready(()),
1552 inline_diagnostics: Vec::new(),
1553 soft_wrap_mode_override,
1554 hard_wrap: None,
1555 completion_provider: project.clone().map(|project| Box::new(project) as _),
1556 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1557 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1558 project,
1559 blink_manager: blink_manager.clone(),
1560 show_local_selections: true,
1561 show_scrollbars: true,
1562 mode,
1563 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1564 show_gutter: mode.is_full(),
1565 show_line_numbers: None,
1566 use_relative_line_numbers: None,
1567 show_git_diff_gutter: None,
1568 show_code_actions: None,
1569 show_runnables: None,
1570 show_breakpoints: None,
1571 show_wrap_guides: None,
1572 show_indent_guides,
1573 placeholder_text: None,
1574 highlight_order: 0,
1575 highlighted_rows: HashMap::default(),
1576 background_highlights: Default::default(),
1577 gutter_highlights: TreeMap::default(),
1578 scrollbar_marker_state: ScrollbarMarkerState::default(),
1579 active_indent_guides_state: ActiveIndentGuidesState::default(),
1580 nav_history: None,
1581 context_menu: RefCell::new(None),
1582 context_menu_options: None,
1583 mouse_context_menu: None,
1584 completion_tasks: Default::default(),
1585 signature_help_state: SignatureHelpState::default(),
1586 auto_signature_help: None,
1587 find_all_references_task_sources: Vec::new(),
1588 next_completion_id: 0,
1589 next_inlay_id: 0,
1590 code_action_providers,
1591 available_code_actions: Default::default(),
1592 code_actions_task: Default::default(),
1593 selection_highlight_task: Default::default(),
1594 document_highlights_task: Default::default(),
1595 linked_editing_range_task: Default::default(),
1596 pending_rename: Default::default(),
1597 searchable: true,
1598 cursor_shape: EditorSettings::get_global(cx)
1599 .cursor_shape
1600 .unwrap_or_default(),
1601 current_line_highlight: None,
1602 autoindent_mode: Some(AutoindentMode::EachLine),
1603 collapse_matches: false,
1604 workspace: None,
1605 input_enabled: true,
1606 use_modal_editing: mode.is_full(),
1607 read_only: false,
1608 use_autoclose: true,
1609 use_auto_surround: true,
1610 auto_replace_emoji_shortcode: false,
1611 jsx_tag_auto_close_enabled_in_any_buffer: false,
1612 leader_peer_id: None,
1613 remote_id: None,
1614 hover_state: Default::default(),
1615 pending_mouse_down: None,
1616 hovered_link_state: Default::default(),
1617 edit_prediction_provider: None,
1618 active_inline_completion: None,
1619 stale_inline_completion_in_menu: None,
1620 edit_prediction_preview: EditPredictionPreview::Inactive {
1621 released_too_fast: false,
1622 },
1623 inline_diagnostics_enabled: mode.is_full(),
1624 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1625
1626 gutter_hovered: false,
1627 pixel_position_of_newest_cursor: None,
1628 last_bounds: None,
1629 last_position_map: None,
1630 expect_bounds_change: None,
1631 gutter_dimensions: GutterDimensions::default(),
1632 style: None,
1633 show_cursor_names: false,
1634 hovered_cursors: Default::default(),
1635 next_editor_action_id: EditorActionId::default(),
1636 editor_actions: Rc::default(),
1637 inline_completions_hidden_for_vim_mode: false,
1638 show_inline_completions_override: None,
1639 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1640 edit_prediction_settings: EditPredictionSettings::Disabled,
1641 edit_prediction_indent_conflict: false,
1642 edit_prediction_requires_modifier_in_indent_conflict: true,
1643 custom_context_menu: None,
1644 show_git_blame_gutter: false,
1645 show_git_blame_inline: false,
1646 show_selection_menu: None,
1647 show_git_blame_inline_delay_task: None,
1648 git_blame_inline_tooltip: None,
1649 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1650 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1651 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1652 .session
1653 .restore_unsaved_buffers,
1654 blame: None,
1655 blame_subscription: None,
1656 tasks: Default::default(),
1657
1658 breakpoint_store,
1659 gutter_breakpoint_indicator: (None, None),
1660 _subscriptions: vec![
1661 cx.observe(&buffer, Self::on_buffer_changed),
1662 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1663 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1664 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1665 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1666 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1667 cx.observe_window_activation(window, |editor, window, cx| {
1668 let active = window.is_window_active();
1669 editor.blink_manager.update(cx, |blink_manager, cx| {
1670 if active {
1671 blink_manager.enable(cx);
1672 } else {
1673 blink_manager.disable(cx);
1674 }
1675 });
1676 }),
1677 ],
1678 tasks_update_task: None,
1679 linked_edit_ranges: Default::default(),
1680 in_project_search: false,
1681 previous_search_ranges: None,
1682 breadcrumb_header: None,
1683 focused_block: None,
1684 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1685 addons: HashMap::default(),
1686 registered_buffers: HashMap::default(),
1687 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1688 selection_mark_mode: false,
1689 toggle_fold_multiple_buffers: Task::ready(()),
1690 serialize_selections: Task::ready(()),
1691 serialize_folds: Task::ready(()),
1692 text_style_refinement: None,
1693 load_diff_task: load_uncommitted_diff,
1694 mouse_cursor_hidden: false,
1695 hide_mouse_mode: EditorSettings::get_global(cx)
1696 .hide_mouse
1697 .unwrap_or_default(),
1698 change_list: ChangeList::new(),
1699 };
1700 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1701 this._subscriptions
1702 .push(cx.observe(breakpoints, |_, _, cx| {
1703 cx.notify();
1704 }));
1705 }
1706 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1707 this._subscriptions.extend(project_subscriptions);
1708
1709 this._subscriptions.push(cx.subscribe_in(
1710 &cx.entity(),
1711 window,
1712 |editor, _, e: &EditorEvent, window, cx| match e {
1713 EditorEvent::ScrollPositionChanged { local, .. } => {
1714 if *local {
1715 let new_anchor = editor.scroll_manager.anchor();
1716 let snapshot = editor.snapshot(window, cx);
1717 editor.update_restoration_data(cx, move |data| {
1718 data.scroll_position = (
1719 new_anchor.top_row(&snapshot.buffer_snapshot),
1720 new_anchor.offset,
1721 );
1722 });
1723 }
1724 }
1725 EditorEvent::Edited { .. } => {
1726 if !vim_enabled(cx) {
1727 let (map, selections) = editor.selections.all_adjusted_display(cx);
1728 let pop_state = editor
1729 .change_list
1730 .last()
1731 .map(|previous| {
1732 previous.len() == selections.len()
1733 && previous.iter().enumerate().all(|(ix, p)| {
1734 p.to_display_point(&map).row()
1735 == selections[ix].head().row()
1736 })
1737 })
1738 .unwrap_or(false);
1739 let new_positions = selections
1740 .into_iter()
1741 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1742 .collect();
1743 editor
1744 .change_list
1745 .push_to_change_list(pop_state, new_positions);
1746 }
1747 }
1748 _ => (),
1749 },
1750 ));
1751
1752 this.end_selection(window, cx);
1753 this.scroll_manager.show_scrollbars(window, cx);
1754 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1755
1756 if mode.is_full() {
1757 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1758 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1759
1760 if this.git_blame_inline_enabled {
1761 this.git_blame_inline_enabled = true;
1762 this.start_git_blame_inline(false, window, cx);
1763 }
1764
1765 this.go_to_active_debug_line(window, cx);
1766
1767 if let Some(buffer) = buffer.read(cx).as_singleton() {
1768 if let Some(project) = this.project.as_ref() {
1769 let handle = project.update(cx, |project, cx| {
1770 project.register_buffer_with_language_servers(&buffer, cx)
1771 });
1772 this.registered_buffers
1773 .insert(buffer.read(cx).remote_id(), handle);
1774 }
1775 }
1776 }
1777
1778 this.report_editor_event("Editor Opened", None, cx);
1779 this
1780 }
1781
1782 pub fn deploy_mouse_context_menu(
1783 &mut self,
1784 position: gpui::Point<Pixels>,
1785 context_menu: Entity<ContextMenu>,
1786 window: &mut Window,
1787 cx: &mut Context<Self>,
1788 ) {
1789 self.mouse_context_menu = Some(MouseContextMenu::new(
1790 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1791 context_menu,
1792 None,
1793 window,
1794 cx,
1795 ));
1796 }
1797
1798 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1799 self.mouse_context_menu
1800 .as_ref()
1801 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1802 }
1803
1804 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1805 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1806 }
1807
1808 fn key_context_internal(
1809 &self,
1810 has_active_edit_prediction: bool,
1811 window: &Window,
1812 cx: &App,
1813 ) -> KeyContext {
1814 let mut key_context = KeyContext::new_with_defaults();
1815 key_context.add("Editor");
1816 let mode = match self.mode {
1817 EditorMode::SingleLine { .. } => "single_line",
1818 EditorMode::AutoHeight { .. } => "auto_height",
1819 EditorMode::Full { .. } => "full",
1820 };
1821
1822 if EditorSettings::jupyter_enabled(cx) {
1823 key_context.add("jupyter");
1824 }
1825
1826 key_context.set("mode", mode);
1827 if self.pending_rename.is_some() {
1828 key_context.add("renaming");
1829 }
1830
1831 match self.context_menu.borrow().as_ref() {
1832 Some(CodeContextMenu::Completions(_)) => {
1833 key_context.add("menu");
1834 key_context.add("showing_completions");
1835 }
1836 Some(CodeContextMenu::CodeActions(_)) => {
1837 key_context.add("menu");
1838 key_context.add("showing_code_actions")
1839 }
1840 None => {}
1841 }
1842
1843 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1844 if !self.focus_handle(cx).contains_focused(window, cx)
1845 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1846 {
1847 for addon in self.addons.values() {
1848 addon.extend_key_context(&mut key_context, cx)
1849 }
1850 }
1851
1852 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1853 if let Some(extension) = singleton_buffer
1854 .read(cx)
1855 .file()
1856 .and_then(|file| file.path().extension()?.to_str())
1857 {
1858 key_context.set("extension", extension.to_string());
1859 }
1860 } else {
1861 key_context.add("multibuffer");
1862 }
1863
1864 if has_active_edit_prediction {
1865 if self.edit_prediction_in_conflict() {
1866 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1867 } else {
1868 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1869 key_context.add("copilot_suggestion");
1870 }
1871 }
1872
1873 if self.selection_mark_mode {
1874 key_context.add("selection_mode");
1875 }
1876
1877 key_context
1878 }
1879
1880 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1881 self.mouse_cursor_hidden = match origin {
1882 HideMouseCursorOrigin::TypingAction => {
1883 matches!(
1884 self.hide_mouse_mode,
1885 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1886 )
1887 }
1888 HideMouseCursorOrigin::MovementAction => {
1889 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1890 }
1891 };
1892 }
1893
1894 pub fn edit_prediction_in_conflict(&self) -> bool {
1895 if !self.show_edit_predictions_in_menu() {
1896 return false;
1897 }
1898
1899 let showing_completions = self
1900 .context_menu
1901 .borrow()
1902 .as_ref()
1903 .map_or(false, |context| {
1904 matches!(context, CodeContextMenu::Completions(_))
1905 });
1906
1907 showing_completions
1908 || self.edit_prediction_requires_modifier()
1909 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1910 // bindings to insert tab characters.
1911 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1912 }
1913
1914 pub fn accept_edit_prediction_keybind(
1915 &self,
1916 window: &Window,
1917 cx: &App,
1918 ) -> AcceptEditPredictionBinding {
1919 let key_context = self.key_context_internal(true, window, cx);
1920 let in_conflict = self.edit_prediction_in_conflict();
1921
1922 AcceptEditPredictionBinding(
1923 window
1924 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1925 .into_iter()
1926 .filter(|binding| {
1927 !in_conflict
1928 || binding
1929 .keystrokes()
1930 .first()
1931 .map_or(false, |keystroke| keystroke.modifiers.modified())
1932 })
1933 .rev()
1934 .min_by_key(|binding| {
1935 binding
1936 .keystrokes()
1937 .first()
1938 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1939 }),
1940 )
1941 }
1942
1943 pub fn new_file(
1944 workspace: &mut Workspace,
1945 _: &workspace::NewFile,
1946 window: &mut Window,
1947 cx: &mut Context<Workspace>,
1948 ) {
1949 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1950 "Failed to create buffer",
1951 window,
1952 cx,
1953 |e, _, _| match e.error_code() {
1954 ErrorCode::RemoteUpgradeRequired => Some(format!(
1955 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1956 e.error_tag("required").unwrap_or("the latest version")
1957 )),
1958 _ => None,
1959 },
1960 );
1961 }
1962
1963 pub fn new_in_workspace(
1964 workspace: &mut Workspace,
1965 window: &mut Window,
1966 cx: &mut Context<Workspace>,
1967 ) -> Task<Result<Entity<Editor>>> {
1968 let project = workspace.project().clone();
1969 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1970
1971 cx.spawn_in(window, async move |workspace, cx| {
1972 let buffer = create.await?;
1973 workspace.update_in(cx, |workspace, window, cx| {
1974 let editor =
1975 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1976 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1977 editor
1978 })
1979 })
1980 }
1981
1982 fn new_file_vertical(
1983 workspace: &mut Workspace,
1984 _: &workspace::NewFileSplitVertical,
1985 window: &mut Window,
1986 cx: &mut Context<Workspace>,
1987 ) {
1988 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1989 }
1990
1991 fn new_file_horizontal(
1992 workspace: &mut Workspace,
1993 _: &workspace::NewFileSplitHorizontal,
1994 window: &mut Window,
1995 cx: &mut Context<Workspace>,
1996 ) {
1997 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1998 }
1999
2000 fn new_file_in_direction(
2001 workspace: &mut Workspace,
2002 direction: SplitDirection,
2003 window: &mut Window,
2004 cx: &mut Context<Workspace>,
2005 ) {
2006 let project = workspace.project().clone();
2007 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2008
2009 cx.spawn_in(window, async move |workspace, cx| {
2010 let buffer = create.await?;
2011 workspace.update_in(cx, move |workspace, window, cx| {
2012 workspace.split_item(
2013 direction,
2014 Box::new(
2015 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2016 ),
2017 window,
2018 cx,
2019 )
2020 })?;
2021 anyhow::Ok(())
2022 })
2023 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2024 match e.error_code() {
2025 ErrorCode::RemoteUpgradeRequired => Some(format!(
2026 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2027 e.error_tag("required").unwrap_or("the latest version")
2028 )),
2029 _ => None,
2030 }
2031 });
2032 }
2033
2034 pub fn leader_peer_id(&self) -> Option<PeerId> {
2035 self.leader_peer_id
2036 }
2037
2038 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2039 &self.buffer
2040 }
2041
2042 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2043 self.workspace.as_ref()?.0.upgrade()
2044 }
2045
2046 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2047 self.buffer().read(cx).title(cx)
2048 }
2049
2050 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2051 let git_blame_gutter_max_author_length = self
2052 .render_git_blame_gutter(cx)
2053 .then(|| {
2054 if let Some(blame) = self.blame.as_ref() {
2055 let max_author_length =
2056 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2057 Some(max_author_length)
2058 } else {
2059 None
2060 }
2061 })
2062 .flatten();
2063
2064 EditorSnapshot {
2065 mode: self.mode,
2066 show_gutter: self.show_gutter,
2067 show_line_numbers: self.show_line_numbers,
2068 show_git_diff_gutter: self.show_git_diff_gutter,
2069 show_code_actions: self.show_code_actions,
2070 show_runnables: self.show_runnables,
2071 show_breakpoints: self.show_breakpoints,
2072 git_blame_gutter_max_author_length,
2073 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2074 scroll_anchor: self.scroll_manager.anchor(),
2075 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2076 placeholder_text: self.placeholder_text.clone(),
2077 is_focused: self.focus_handle.is_focused(window),
2078 current_line_highlight: self
2079 .current_line_highlight
2080 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2081 gutter_hovered: self.gutter_hovered,
2082 }
2083 }
2084
2085 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2086 self.buffer.read(cx).language_at(point, cx)
2087 }
2088
2089 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2090 self.buffer.read(cx).read(cx).file_at(point).cloned()
2091 }
2092
2093 pub fn active_excerpt(
2094 &self,
2095 cx: &App,
2096 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2097 self.buffer
2098 .read(cx)
2099 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2100 }
2101
2102 pub fn mode(&self) -> EditorMode {
2103 self.mode
2104 }
2105
2106 pub fn set_mode(&mut self, mode: EditorMode) {
2107 self.mode = mode;
2108 }
2109
2110 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2111 self.collaboration_hub.as_deref()
2112 }
2113
2114 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2115 self.collaboration_hub = Some(hub);
2116 }
2117
2118 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2119 self.in_project_search = in_project_search;
2120 }
2121
2122 pub fn set_custom_context_menu(
2123 &mut self,
2124 f: impl 'static
2125 + Fn(
2126 &mut Self,
2127 DisplayPoint,
2128 &mut Window,
2129 &mut Context<Self>,
2130 ) -> Option<Entity<ui::ContextMenu>>,
2131 ) {
2132 self.custom_context_menu = Some(Box::new(f))
2133 }
2134
2135 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2136 self.completion_provider = provider;
2137 }
2138
2139 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2140 self.semantics_provider.clone()
2141 }
2142
2143 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2144 self.semantics_provider = provider;
2145 }
2146
2147 pub fn set_edit_prediction_provider<T>(
2148 &mut self,
2149 provider: Option<Entity<T>>,
2150 window: &mut Window,
2151 cx: &mut Context<Self>,
2152 ) where
2153 T: EditPredictionProvider,
2154 {
2155 self.edit_prediction_provider =
2156 provider.map(|provider| RegisteredInlineCompletionProvider {
2157 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2158 if this.focus_handle.is_focused(window) {
2159 this.update_visible_inline_completion(window, cx);
2160 }
2161 }),
2162 provider: Arc::new(provider),
2163 });
2164 self.update_edit_prediction_settings(cx);
2165 self.refresh_inline_completion(false, false, window, cx);
2166 }
2167
2168 pub fn placeholder_text(&self) -> Option<&str> {
2169 self.placeholder_text.as_deref()
2170 }
2171
2172 pub fn set_placeholder_text(
2173 &mut self,
2174 placeholder_text: impl Into<Arc<str>>,
2175 cx: &mut Context<Self>,
2176 ) {
2177 let placeholder_text = Some(placeholder_text.into());
2178 if self.placeholder_text != placeholder_text {
2179 self.placeholder_text = placeholder_text;
2180 cx.notify();
2181 }
2182 }
2183
2184 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2185 self.cursor_shape = cursor_shape;
2186
2187 // Disrupt blink for immediate user feedback that the cursor shape has changed
2188 self.blink_manager.update(cx, BlinkManager::show_cursor);
2189
2190 cx.notify();
2191 }
2192
2193 pub fn set_current_line_highlight(
2194 &mut self,
2195 current_line_highlight: Option<CurrentLineHighlight>,
2196 ) {
2197 self.current_line_highlight = current_line_highlight;
2198 }
2199
2200 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2201 self.collapse_matches = collapse_matches;
2202 }
2203
2204 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2205 let buffers = self.buffer.read(cx).all_buffers();
2206 let Some(project) = self.project.as_ref() else {
2207 return;
2208 };
2209 project.update(cx, |project, cx| {
2210 for buffer in buffers {
2211 self.registered_buffers
2212 .entry(buffer.read(cx).remote_id())
2213 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2214 }
2215 })
2216 }
2217
2218 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2219 if self.collapse_matches {
2220 return range.start..range.start;
2221 }
2222 range.clone()
2223 }
2224
2225 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2226 if self.display_map.read(cx).clip_at_line_ends != clip {
2227 self.display_map
2228 .update(cx, |map, _| map.clip_at_line_ends = clip);
2229 }
2230 }
2231
2232 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2233 self.input_enabled = input_enabled;
2234 }
2235
2236 pub fn set_inline_completions_hidden_for_vim_mode(
2237 &mut self,
2238 hidden: bool,
2239 window: &mut Window,
2240 cx: &mut Context<Self>,
2241 ) {
2242 if hidden != self.inline_completions_hidden_for_vim_mode {
2243 self.inline_completions_hidden_for_vim_mode = hidden;
2244 if hidden {
2245 self.update_visible_inline_completion(window, cx);
2246 } else {
2247 self.refresh_inline_completion(true, false, window, cx);
2248 }
2249 }
2250 }
2251
2252 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2253 self.menu_inline_completions_policy = value;
2254 }
2255
2256 pub fn set_autoindent(&mut self, autoindent: bool) {
2257 if autoindent {
2258 self.autoindent_mode = Some(AutoindentMode::EachLine);
2259 } else {
2260 self.autoindent_mode = None;
2261 }
2262 }
2263
2264 pub fn read_only(&self, cx: &App) -> bool {
2265 self.read_only || self.buffer.read(cx).read_only()
2266 }
2267
2268 pub fn set_read_only(&mut self, read_only: bool) {
2269 self.read_only = read_only;
2270 }
2271
2272 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2273 self.use_autoclose = autoclose;
2274 }
2275
2276 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2277 self.use_auto_surround = auto_surround;
2278 }
2279
2280 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2281 self.auto_replace_emoji_shortcode = auto_replace;
2282 }
2283
2284 pub fn toggle_edit_predictions(
2285 &mut self,
2286 _: &ToggleEditPrediction,
2287 window: &mut Window,
2288 cx: &mut Context<Self>,
2289 ) {
2290 if self.show_inline_completions_override.is_some() {
2291 self.set_show_edit_predictions(None, window, cx);
2292 } else {
2293 let show_edit_predictions = !self.edit_predictions_enabled();
2294 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2295 }
2296 }
2297
2298 pub fn set_show_edit_predictions(
2299 &mut self,
2300 show_edit_predictions: Option<bool>,
2301 window: &mut Window,
2302 cx: &mut Context<Self>,
2303 ) {
2304 self.show_inline_completions_override = show_edit_predictions;
2305 self.update_edit_prediction_settings(cx);
2306
2307 if let Some(false) = show_edit_predictions {
2308 self.discard_inline_completion(false, cx);
2309 } else {
2310 self.refresh_inline_completion(false, true, window, cx);
2311 }
2312 }
2313
2314 fn inline_completions_disabled_in_scope(
2315 &self,
2316 buffer: &Entity<Buffer>,
2317 buffer_position: language::Anchor,
2318 cx: &App,
2319 ) -> bool {
2320 let snapshot = buffer.read(cx).snapshot();
2321 let settings = snapshot.settings_at(buffer_position, cx);
2322
2323 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2324 return false;
2325 };
2326
2327 scope.override_name().map_or(false, |scope_name| {
2328 settings
2329 .edit_predictions_disabled_in
2330 .iter()
2331 .any(|s| s == scope_name)
2332 })
2333 }
2334
2335 pub fn set_use_modal_editing(&mut self, to: bool) {
2336 self.use_modal_editing = to;
2337 }
2338
2339 pub fn use_modal_editing(&self) -> bool {
2340 self.use_modal_editing
2341 }
2342
2343 fn selections_did_change(
2344 &mut self,
2345 local: bool,
2346 old_cursor_position: &Anchor,
2347 show_completions: bool,
2348 window: &mut Window,
2349 cx: &mut Context<Self>,
2350 ) {
2351 window.invalidate_character_coordinates();
2352
2353 // Copy selections to primary selection buffer
2354 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2355 if local {
2356 let selections = self.selections.all::<usize>(cx);
2357 let buffer_handle = self.buffer.read(cx).read(cx);
2358
2359 let mut text = String::new();
2360 for (index, selection) in selections.iter().enumerate() {
2361 let text_for_selection = buffer_handle
2362 .text_for_range(selection.start..selection.end)
2363 .collect::<String>();
2364
2365 text.push_str(&text_for_selection);
2366 if index != selections.len() - 1 {
2367 text.push('\n');
2368 }
2369 }
2370
2371 if !text.is_empty() {
2372 cx.write_to_primary(ClipboardItem::new_string(text));
2373 }
2374 }
2375
2376 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2377 self.buffer.update(cx, |buffer, cx| {
2378 buffer.set_active_selections(
2379 &self.selections.disjoint_anchors(),
2380 self.selections.line_mode,
2381 self.cursor_shape,
2382 cx,
2383 )
2384 });
2385 }
2386 let display_map = self
2387 .display_map
2388 .update(cx, |display_map, cx| display_map.snapshot(cx));
2389 let buffer = &display_map.buffer_snapshot;
2390 self.add_selections_state = None;
2391 self.select_next_state = None;
2392 self.select_prev_state = None;
2393 self.select_syntax_node_history.try_clear();
2394 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2395 self.snippet_stack
2396 .invalidate(&self.selections.disjoint_anchors(), buffer);
2397 self.take_rename(false, window, cx);
2398
2399 let new_cursor_position = self.selections.newest_anchor().head();
2400
2401 self.push_to_nav_history(
2402 *old_cursor_position,
2403 Some(new_cursor_position.to_point(buffer)),
2404 false,
2405 cx,
2406 );
2407
2408 if local {
2409 let new_cursor_position = self.selections.newest_anchor().head();
2410 let mut context_menu = self.context_menu.borrow_mut();
2411 let completion_menu = match context_menu.as_ref() {
2412 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2413 _ => {
2414 *context_menu = None;
2415 None
2416 }
2417 };
2418 if let Some(buffer_id) = new_cursor_position.buffer_id {
2419 if !self.registered_buffers.contains_key(&buffer_id) {
2420 if let Some(project) = self.project.as_ref() {
2421 project.update(cx, |project, cx| {
2422 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2423 return;
2424 };
2425 self.registered_buffers.insert(
2426 buffer_id,
2427 project.register_buffer_with_language_servers(&buffer, cx),
2428 );
2429 })
2430 }
2431 }
2432 }
2433
2434 if let Some(completion_menu) = completion_menu {
2435 let cursor_position = new_cursor_position.to_offset(buffer);
2436 let (word_range, kind) =
2437 buffer.surrounding_word(completion_menu.initial_position, true);
2438 if kind == Some(CharKind::Word)
2439 && word_range.to_inclusive().contains(&cursor_position)
2440 {
2441 let mut completion_menu = completion_menu.clone();
2442 drop(context_menu);
2443
2444 let query = Self::completion_query(buffer, cursor_position);
2445 cx.spawn(async move |this, cx| {
2446 completion_menu
2447 .filter(query.as_deref(), cx.background_executor().clone())
2448 .await;
2449
2450 this.update(cx, |this, cx| {
2451 let mut context_menu = this.context_menu.borrow_mut();
2452 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2453 else {
2454 return;
2455 };
2456
2457 if menu.id > completion_menu.id {
2458 return;
2459 }
2460
2461 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2462 drop(context_menu);
2463 cx.notify();
2464 })
2465 })
2466 .detach();
2467
2468 if show_completions {
2469 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2470 }
2471 } else {
2472 drop(context_menu);
2473 self.hide_context_menu(window, cx);
2474 }
2475 } else {
2476 drop(context_menu);
2477 }
2478
2479 hide_hover(self, cx);
2480
2481 if old_cursor_position.to_display_point(&display_map).row()
2482 != new_cursor_position.to_display_point(&display_map).row()
2483 {
2484 self.available_code_actions.take();
2485 }
2486 self.refresh_code_actions(window, cx);
2487 self.refresh_document_highlights(cx);
2488 self.refresh_selected_text_highlights(window, cx);
2489 refresh_matching_bracket_highlights(self, window, cx);
2490 self.update_visible_inline_completion(window, cx);
2491 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2492 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2493 if self.git_blame_inline_enabled {
2494 self.start_inline_blame_timer(window, cx);
2495 }
2496 }
2497
2498 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2499 cx.emit(EditorEvent::SelectionsChanged { local });
2500
2501 let selections = &self.selections.disjoint;
2502 if selections.len() == 1 {
2503 cx.emit(SearchEvent::ActiveMatchChanged)
2504 }
2505 if local {
2506 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2507 let inmemory_selections = selections
2508 .iter()
2509 .map(|s| {
2510 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2511 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2512 })
2513 .collect();
2514 self.update_restoration_data(cx, |data| {
2515 data.selections = inmemory_selections;
2516 });
2517
2518 if WorkspaceSettings::get(None, cx).restore_on_startup
2519 != RestoreOnStartupBehavior::None
2520 {
2521 if let Some(workspace_id) =
2522 self.workspace.as_ref().and_then(|workspace| workspace.1)
2523 {
2524 let snapshot = self.buffer().read(cx).snapshot(cx);
2525 let selections = selections.clone();
2526 let background_executor = cx.background_executor().clone();
2527 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2528 self.serialize_selections = cx.background_spawn(async move {
2529 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2530 let db_selections = selections
2531 .iter()
2532 .map(|selection| {
2533 (
2534 selection.start.to_offset(&snapshot),
2535 selection.end.to_offset(&snapshot),
2536 )
2537 })
2538 .collect();
2539
2540 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2541 .await
2542 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2543 .log_err();
2544 });
2545 }
2546 }
2547 }
2548 }
2549
2550 cx.notify();
2551 }
2552
2553 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2554 use text::ToOffset as _;
2555 use text::ToPoint as _;
2556
2557 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2558 return;
2559 }
2560
2561 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2562 return;
2563 };
2564
2565 let snapshot = singleton.read(cx).snapshot();
2566 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2567 let display_snapshot = display_map.snapshot(cx);
2568
2569 display_snapshot
2570 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2571 .map(|fold| {
2572 fold.range.start.text_anchor.to_point(&snapshot)
2573 ..fold.range.end.text_anchor.to_point(&snapshot)
2574 })
2575 .collect()
2576 });
2577 self.update_restoration_data(cx, |data| {
2578 data.folds = inmemory_folds;
2579 });
2580
2581 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2582 return;
2583 };
2584 let background_executor = cx.background_executor().clone();
2585 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2586 let db_folds = self.display_map.update(cx, |display_map, cx| {
2587 display_map
2588 .snapshot(cx)
2589 .folds_in_range(0..snapshot.len())
2590 .map(|fold| {
2591 (
2592 fold.range.start.text_anchor.to_offset(&snapshot),
2593 fold.range.end.text_anchor.to_offset(&snapshot),
2594 )
2595 })
2596 .collect()
2597 });
2598 self.serialize_folds = cx.background_spawn(async move {
2599 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2600 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2601 .await
2602 .with_context(|| {
2603 format!(
2604 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2605 )
2606 })
2607 .log_err();
2608 });
2609 }
2610
2611 pub fn sync_selections(
2612 &mut self,
2613 other: Entity<Editor>,
2614 cx: &mut Context<Self>,
2615 ) -> gpui::Subscription {
2616 let other_selections = other.read(cx).selections.disjoint.to_vec();
2617 self.selections.change_with(cx, |selections| {
2618 selections.select_anchors(other_selections);
2619 });
2620
2621 let other_subscription =
2622 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2623 EditorEvent::SelectionsChanged { local: true } => {
2624 let other_selections = other.read(cx).selections.disjoint.to_vec();
2625 if other_selections.is_empty() {
2626 return;
2627 }
2628 this.selections.change_with(cx, |selections| {
2629 selections.select_anchors(other_selections);
2630 });
2631 }
2632 _ => {}
2633 });
2634
2635 let this_subscription =
2636 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2637 EditorEvent::SelectionsChanged { local: true } => {
2638 let these_selections = this.selections.disjoint.to_vec();
2639 if these_selections.is_empty() {
2640 return;
2641 }
2642 other.update(cx, |other_editor, cx| {
2643 other_editor.selections.change_with(cx, |selections| {
2644 selections.select_anchors(these_selections);
2645 })
2646 });
2647 }
2648 _ => {}
2649 });
2650
2651 Subscription::join(other_subscription, this_subscription)
2652 }
2653
2654 pub fn change_selections<R>(
2655 &mut self,
2656 autoscroll: Option<Autoscroll>,
2657 window: &mut Window,
2658 cx: &mut Context<Self>,
2659 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2660 ) -> R {
2661 self.change_selections_inner(autoscroll, true, window, cx, change)
2662 }
2663
2664 fn change_selections_inner<R>(
2665 &mut self,
2666 autoscroll: Option<Autoscroll>,
2667 request_completions: bool,
2668 window: &mut Window,
2669 cx: &mut Context<Self>,
2670 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2671 ) -> R {
2672 let old_cursor_position = self.selections.newest_anchor().head();
2673 self.push_to_selection_history();
2674
2675 let (changed, result) = self.selections.change_with(cx, change);
2676
2677 if changed {
2678 if let Some(autoscroll) = autoscroll {
2679 self.request_autoscroll(autoscroll, cx);
2680 }
2681 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2682
2683 if self.should_open_signature_help_automatically(
2684 &old_cursor_position,
2685 self.signature_help_state.backspace_pressed(),
2686 cx,
2687 ) {
2688 self.show_signature_help(&ShowSignatureHelp, window, cx);
2689 }
2690 self.signature_help_state.set_backspace_pressed(false);
2691 }
2692
2693 result
2694 }
2695
2696 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2697 where
2698 I: IntoIterator<Item = (Range<S>, T)>,
2699 S: ToOffset,
2700 T: Into<Arc<str>>,
2701 {
2702 if self.read_only(cx) {
2703 return;
2704 }
2705
2706 self.buffer
2707 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2708 }
2709
2710 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2711 where
2712 I: IntoIterator<Item = (Range<S>, T)>,
2713 S: ToOffset,
2714 T: Into<Arc<str>>,
2715 {
2716 if self.read_only(cx) {
2717 return;
2718 }
2719
2720 self.buffer.update(cx, |buffer, cx| {
2721 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2722 });
2723 }
2724
2725 pub fn edit_with_block_indent<I, S, T>(
2726 &mut self,
2727 edits: I,
2728 original_indent_columns: Vec<Option<u32>>,
2729 cx: &mut Context<Self>,
2730 ) where
2731 I: IntoIterator<Item = (Range<S>, T)>,
2732 S: ToOffset,
2733 T: Into<Arc<str>>,
2734 {
2735 if self.read_only(cx) {
2736 return;
2737 }
2738
2739 self.buffer.update(cx, |buffer, cx| {
2740 buffer.edit(
2741 edits,
2742 Some(AutoindentMode::Block {
2743 original_indent_columns,
2744 }),
2745 cx,
2746 )
2747 });
2748 }
2749
2750 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2751 self.hide_context_menu(window, cx);
2752
2753 match phase {
2754 SelectPhase::Begin {
2755 position,
2756 add,
2757 click_count,
2758 } => self.begin_selection(position, add, click_count, window, cx),
2759 SelectPhase::BeginColumnar {
2760 position,
2761 goal_column,
2762 reset,
2763 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2764 SelectPhase::Extend {
2765 position,
2766 click_count,
2767 } => self.extend_selection(position, click_count, window, cx),
2768 SelectPhase::Update {
2769 position,
2770 goal_column,
2771 scroll_delta,
2772 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2773 SelectPhase::End => self.end_selection(window, cx),
2774 }
2775 }
2776
2777 fn extend_selection(
2778 &mut self,
2779 position: DisplayPoint,
2780 click_count: usize,
2781 window: &mut Window,
2782 cx: &mut Context<Self>,
2783 ) {
2784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2785 let tail = self.selections.newest::<usize>(cx).tail();
2786 self.begin_selection(position, false, click_count, window, cx);
2787
2788 let position = position.to_offset(&display_map, Bias::Left);
2789 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2790
2791 let mut pending_selection = self
2792 .selections
2793 .pending_anchor()
2794 .expect("extend_selection not called with pending selection");
2795 if position >= tail {
2796 pending_selection.start = tail_anchor;
2797 } else {
2798 pending_selection.end = tail_anchor;
2799 pending_selection.reversed = true;
2800 }
2801
2802 let mut pending_mode = self.selections.pending_mode().unwrap();
2803 match &mut pending_mode {
2804 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2805 _ => {}
2806 }
2807
2808 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2809 s.set_pending(pending_selection, pending_mode)
2810 });
2811 }
2812
2813 fn begin_selection(
2814 &mut self,
2815 position: DisplayPoint,
2816 add: bool,
2817 click_count: usize,
2818 window: &mut Window,
2819 cx: &mut Context<Self>,
2820 ) {
2821 if !self.focus_handle.is_focused(window) {
2822 self.last_focused_descendant = None;
2823 window.focus(&self.focus_handle);
2824 }
2825
2826 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2827 let buffer = &display_map.buffer_snapshot;
2828 let newest_selection = self.selections.newest_anchor().clone();
2829 let position = display_map.clip_point(position, Bias::Left);
2830
2831 let start;
2832 let end;
2833 let mode;
2834 let mut auto_scroll;
2835 match click_count {
2836 1 => {
2837 start = buffer.anchor_before(position.to_point(&display_map));
2838 end = start;
2839 mode = SelectMode::Character;
2840 auto_scroll = true;
2841 }
2842 2 => {
2843 let range = movement::surrounding_word(&display_map, position);
2844 start = buffer.anchor_before(range.start.to_point(&display_map));
2845 end = buffer.anchor_before(range.end.to_point(&display_map));
2846 mode = SelectMode::Word(start..end);
2847 auto_scroll = true;
2848 }
2849 3 => {
2850 let position = display_map
2851 .clip_point(position, Bias::Left)
2852 .to_point(&display_map);
2853 let line_start = display_map.prev_line_boundary(position).0;
2854 let next_line_start = buffer.clip_point(
2855 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2856 Bias::Left,
2857 );
2858 start = buffer.anchor_before(line_start);
2859 end = buffer.anchor_before(next_line_start);
2860 mode = SelectMode::Line(start..end);
2861 auto_scroll = true;
2862 }
2863 _ => {
2864 start = buffer.anchor_before(0);
2865 end = buffer.anchor_before(buffer.len());
2866 mode = SelectMode::All;
2867 auto_scroll = false;
2868 }
2869 }
2870 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2871
2872 let point_to_delete: Option<usize> = {
2873 let selected_points: Vec<Selection<Point>> =
2874 self.selections.disjoint_in_range(start..end, cx);
2875
2876 if !add || click_count > 1 {
2877 None
2878 } else if !selected_points.is_empty() {
2879 Some(selected_points[0].id)
2880 } else {
2881 let clicked_point_already_selected =
2882 self.selections.disjoint.iter().find(|selection| {
2883 selection.start.to_point(buffer) == start.to_point(buffer)
2884 || selection.end.to_point(buffer) == end.to_point(buffer)
2885 });
2886
2887 clicked_point_already_selected.map(|selection| selection.id)
2888 }
2889 };
2890
2891 let selections_count = self.selections.count();
2892
2893 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2894 if let Some(point_to_delete) = point_to_delete {
2895 s.delete(point_to_delete);
2896
2897 if selections_count == 1 {
2898 s.set_pending_anchor_range(start..end, mode);
2899 }
2900 } else {
2901 if !add {
2902 s.clear_disjoint();
2903 } else if click_count > 1 {
2904 s.delete(newest_selection.id)
2905 }
2906
2907 s.set_pending_anchor_range(start..end, mode);
2908 }
2909 });
2910 }
2911
2912 fn begin_columnar_selection(
2913 &mut self,
2914 position: DisplayPoint,
2915 goal_column: u32,
2916 reset: bool,
2917 window: &mut Window,
2918 cx: &mut Context<Self>,
2919 ) {
2920 if !self.focus_handle.is_focused(window) {
2921 self.last_focused_descendant = None;
2922 window.focus(&self.focus_handle);
2923 }
2924
2925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2926
2927 if reset {
2928 let pointer_position = display_map
2929 .buffer_snapshot
2930 .anchor_before(position.to_point(&display_map));
2931
2932 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2933 s.clear_disjoint();
2934 s.set_pending_anchor_range(
2935 pointer_position..pointer_position,
2936 SelectMode::Character,
2937 );
2938 });
2939 }
2940
2941 let tail = self.selections.newest::<Point>(cx).tail();
2942 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2943
2944 if !reset {
2945 self.select_columns(
2946 tail.to_display_point(&display_map),
2947 position,
2948 goal_column,
2949 &display_map,
2950 window,
2951 cx,
2952 );
2953 }
2954 }
2955
2956 fn update_selection(
2957 &mut self,
2958 position: DisplayPoint,
2959 goal_column: u32,
2960 scroll_delta: gpui::Point<f32>,
2961 window: &mut Window,
2962 cx: &mut Context<Self>,
2963 ) {
2964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2965
2966 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2967 let tail = tail.to_display_point(&display_map);
2968 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2969 } else if let Some(mut pending) = self.selections.pending_anchor() {
2970 let buffer = self.buffer.read(cx).snapshot(cx);
2971 let head;
2972 let tail;
2973 let mode = self.selections.pending_mode().unwrap();
2974 match &mode {
2975 SelectMode::Character => {
2976 head = position.to_point(&display_map);
2977 tail = pending.tail().to_point(&buffer);
2978 }
2979 SelectMode::Word(original_range) => {
2980 let original_display_range = original_range.start.to_display_point(&display_map)
2981 ..original_range.end.to_display_point(&display_map);
2982 let original_buffer_range = original_display_range.start.to_point(&display_map)
2983 ..original_display_range.end.to_point(&display_map);
2984 if movement::is_inside_word(&display_map, position)
2985 || original_display_range.contains(&position)
2986 {
2987 let word_range = movement::surrounding_word(&display_map, position);
2988 if word_range.start < original_display_range.start {
2989 head = word_range.start.to_point(&display_map);
2990 } else {
2991 head = word_range.end.to_point(&display_map);
2992 }
2993 } else {
2994 head = position.to_point(&display_map);
2995 }
2996
2997 if head <= original_buffer_range.start {
2998 tail = original_buffer_range.end;
2999 } else {
3000 tail = original_buffer_range.start;
3001 }
3002 }
3003 SelectMode::Line(original_range) => {
3004 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3005
3006 let position = display_map
3007 .clip_point(position, Bias::Left)
3008 .to_point(&display_map);
3009 let line_start = display_map.prev_line_boundary(position).0;
3010 let next_line_start = buffer.clip_point(
3011 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3012 Bias::Left,
3013 );
3014
3015 if line_start < original_range.start {
3016 head = line_start
3017 } else {
3018 head = next_line_start
3019 }
3020
3021 if head <= original_range.start {
3022 tail = original_range.end;
3023 } else {
3024 tail = original_range.start;
3025 }
3026 }
3027 SelectMode::All => {
3028 return;
3029 }
3030 };
3031
3032 if head < tail {
3033 pending.start = buffer.anchor_before(head);
3034 pending.end = buffer.anchor_before(tail);
3035 pending.reversed = true;
3036 } else {
3037 pending.start = buffer.anchor_before(tail);
3038 pending.end = buffer.anchor_before(head);
3039 pending.reversed = false;
3040 }
3041
3042 self.change_selections(None, window, cx, |s| {
3043 s.set_pending(pending, mode);
3044 });
3045 } else {
3046 log::error!("update_selection dispatched with no pending selection");
3047 return;
3048 }
3049
3050 self.apply_scroll_delta(scroll_delta, window, cx);
3051 cx.notify();
3052 }
3053
3054 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3055 self.columnar_selection_tail.take();
3056 if self.selections.pending_anchor().is_some() {
3057 let selections = self.selections.all::<usize>(cx);
3058 self.change_selections(None, window, cx, |s| {
3059 s.select(selections);
3060 s.clear_pending();
3061 });
3062 }
3063 }
3064
3065 fn select_columns(
3066 &mut self,
3067 tail: DisplayPoint,
3068 head: DisplayPoint,
3069 goal_column: u32,
3070 display_map: &DisplaySnapshot,
3071 window: &mut Window,
3072 cx: &mut Context<Self>,
3073 ) {
3074 let start_row = cmp::min(tail.row(), head.row());
3075 let end_row = cmp::max(tail.row(), head.row());
3076 let start_column = cmp::min(tail.column(), goal_column);
3077 let end_column = cmp::max(tail.column(), goal_column);
3078 let reversed = start_column < tail.column();
3079
3080 let selection_ranges = (start_row.0..=end_row.0)
3081 .map(DisplayRow)
3082 .filter_map(|row| {
3083 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3084 let start = display_map
3085 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3086 .to_point(display_map);
3087 let end = display_map
3088 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3089 .to_point(display_map);
3090 if reversed {
3091 Some(end..start)
3092 } else {
3093 Some(start..end)
3094 }
3095 } else {
3096 None
3097 }
3098 })
3099 .collect::<Vec<_>>();
3100
3101 self.change_selections(None, window, cx, |s| {
3102 s.select_ranges(selection_ranges);
3103 });
3104 cx.notify();
3105 }
3106
3107 pub fn has_pending_nonempty_selection(&self) -> bool {
3108 let pending_nonempty_selection = match self.selections.pending_anchor() {
3109 Some(Selection { start, end, .. }) => start != end,
3110 None => false,
3111 };
3112
3113 pending_nonempty_selection
3114 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3115 }
3116
3117 pub fn has_pending_selection(&self) -> bool {
3118 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3119 }
3120
3121 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3122 self.selection_mark_mode = false;
3123
3124 if self.clear_expanded_diff_hunks(cx) {
3125 cx.notify();
3126 return;
3127 }
3128 if self.dismiss_menus_and_popups(true, window, cx) {
3129 return;
3130 }
3131
3132 if self.mode.is_full()
3133 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3134 {
3135 return;
3136 }
3137
3138 cx.propagate();
3139 }
3140
3141 pub fn dismiss_menus_and_popups(
3142 &mut self,
3143 is_user_requested: bool,
3144 window: &mut Window,
3145 cx: &mut Context<Self>,
3146 ) -> bool {
3147 if self.take_rename(false, window, cx).is_some() {
3148 return true;
3149 }
3150
3151 if hide_hover(self, cx) {
3152 return true;
3153 }
3154
3155 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3156 return true;
3157 }
3158
3159 if self.hide_context_menu(window, cx).is_some() {
3160 return true;
3161 }
3162
3163 if self.mouse_context_menu.take().is_some() {
3164 return true;
3165 }
3166
3167 if is_user_requested && self.discard_inline_completion(true, cx) {
3168 return true;
3169 }
3170
3171 if self.snippet_stack.pop().is_some() {
3172 return true;
3173 }
3174
3175 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3176 self.dismiss_diagnostics(cx);
3177 return true;
3178 }
3179
3180 false
3181 }
3182
3183 fn linked_editing_ranges_for(
3184 &self,
3185 selection: Range<text::Anchor>,
3186 cx: &App,
3187 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3188 if self.linked_edit_ranges.is_empty() {
3189 return None;
3190 }
3191 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3192 selection.end.buffer_id.and_then(|end_buffer_id| {
3193 if selection.start.buffer_id != Some(end_buffer_id) {
3194 return None;
3195 }
3196 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3197 let snapshot = buffer.read(cx).snapshot();
3198 self.linked_edit_ranges
3199 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3200 .map(|ranges| (ranges, snapshot, buffer))
3201 })?;
3202 use text::ToOffset as TO;
3203 // find offset from the start of current range to current cursor position
3204 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3205
3206 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3207 let start_difference = start_offset - start_byte_offset;
3208 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3209 let end_difference = end_offset - start_byte_offset;
3210 // Current range has associated linked ranges.
3211 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3212 for range in linked_ranges.iter() {
3213 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3214 let end_offset = start_offset + end_difference;
3215 let start_offset = start_offset + start_difference;
3216 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3217 continue;
3218 }
3219 if self.selections.disjoint_anchor_ranges().any(|s| {
3220 if s.start.buffer_id != selection.start.buffer_id
3221 || s.end.buffer_id != selection.end.buffer_id
3222 {
3223 return false;
3224 }
3225 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3226 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3227 }) {
3228 continue;
3229 }
3230 let start = buffer_snapshot.anchor_after(start_offset);
3231 let end = buffer_snapshot.anchor_after(end_offset);
3232 linked_edits
3233 .entry(buffer.clone())
3234 .or_default()
3235 .push(start..end);
3236 }
3237 Some(linked_edits)
3238 }
3239
3240 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3241 let text: Arc<str> = text.into();
3242
3243 if self.read_only(cx) {
3244 return;
3245 }
3246
3247 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3248
3249 let selections = self.selections.all_adjusted(cx);
3250 let mut bracket_inserted = false;
3251 let mut edits = Vec::new();
3252 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3253 let mut new_selections = Vec::with_capacity(selections.len());
3254 let mut new_autoclose_regions = Vec::new();
3255 let snapshot = self.buffer.read(cx).read(cx);
3256 let mut clear_linked_edit_ranges = false;
3257
3258 for (selection, autoclose_region) in
3259 self.selections_with_autoclose_regions(selections, &snapshot)
3260 {
3261 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3262 // Determine if the inserted text matches the opening or closing
3263 // bracket of any of this language's bracket pairs.
3264 let mut bracket_pair = None;
3265 let mut is_bracket_pair_start = false;
3266 let mut is_bracket_pair_end = false;
3267 if !text.is_empty() {
3268 let mut bracket_pair_matching_end = None;
3269 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3270 // and they are removing the character that triggered IME popup.
3271 for (pair, enabled) in scope.brackets() {
3272 if !pair.close && !pair.surround {
3273 continue;
3274 }
3275
3276 if enabled && pair.start.ends_with(text.as_ref()) {
3277 let prefix_len = pair.start.len() - text.len();
3278 let preceding_text_matches_prefix = prefix_len == 0
3279 || (selection.start.column >= (prefix_len as u32)
3280 && snapshot.contains_str_at(
3281 Point::new(
3282 selection.start.row,
3283 selection.start.column - (prefix_len as u32),
3284 ),
3285 &pair.start[..prefix_len],
3286 ));
3287 if preceding_text_matches_prefix {
3288 bracket_pair = Some(pair.clone());
3289 is_bracket_pair_start = true;
3290 break;
3291 }
3292 }
3293 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3294 {
3295 // take first bracket pair matching end, but don't break in case a later bracket
3296 // pair matches start
3297 bracket_pair_matching_end = Some(pair.clone());
3298 }
3299 }
3300 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3301 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3302 is_bracket_pair_end = true;
3303 }
3304 }
3305
3306 if let Some(bracket_pair) = bracket_pair {
3307 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3308 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3309 let auto_surround =
3310 self.use_auto_surround && snapshot_settings.use_auto_surround;
3311 if selection.is_empty() {
3312 if is_bracket_pair_start {
3313 // If the inserted text is a suffix of an opening bracket and the
3314 // selection is preceded by the rest of the opening bracket, then
3315 // insert the closing bracket.
3316 let following_text_allows_autoclose = snapshot
3317 .chars_at(selection.start)
3318 .next()
3319 .map_or(true, |c| scope.should_autoclose_before(c));
3320
3321 let preceding_text_allows_autoclose = selection.start.column == 0
3322 || snapshot.reversed_chars_at(selection.start).next().map_or(
3323 true,
3324 |c| {
3325 bracket_pair.start != bracket_pair.end
3326 || !snapshot
3327 .char_classifier_at(selection.start)
3328 .is_word(c)
3329 },
3330 );
3331
3332 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3333 && bracket_pair.start.len() == 1
3334 {
3335 let target = bracket_pair.start.chars().next().unwrap();
3336 let current_line_count = snapshot
3337 .reversed_chars_at(selection.start)
3338 .take_while(|&c| c != '\n')
3339 .filter(|&c| c == target)
3340 .count();
3341 current_line_count % 2 == 1
3342 } else {
3343 false
3344 };
3345
3346 if autoclose
3347 && bracket_pair.close
3348 && following_text_allows_autoclose
3349 && preceding_text_allows_autoclose
3350 && !is_closing_quote
3351 {
3352 let anchor = snapshot.anchor_before(selection.end);
3353 new_selections.push((selection.map(|_| anchor), text.len()));
3354 new_autoclose_regions.push((
3355 anchor,
3356 text.len(),
3357 selection.id,
3358 bracket_pair.clone(),
3359 ));
3360 edits.push((
3361 selection.range(),
3362 format!("{}{}", text, bracket_pair.end).into(),
3363 ));
3364 bracket_inserted = true;
3365 continue;
3366 }
3367 }
3368
3369 if let Some(region) = autoclose_region {
3370 // If the selection is followed by an auto-inserted closing bracket,
3371 // then don't insert that closing bracket again; just move the selection
3372 // past the closing bracket.
3373 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3374 && text.as_ref() == region.pair.end.as_str();
3375 if should_skip {
3376 let anchor = snapshot.anchor_after(selection.end);
3377 new_selections
3378 .push((selection.map(|_| anchor), region.pair.end.len()));
3379 continue;
3380 }
3381 }
3382
3383 let always_treat_brackets_as_autoclosed = snapshot
3384 .language_settings_at(selection.start, cx)
3385 .always_treat_brackets_as_autoclosed;
3386 if always_treat_brackets_as_autoclosed
3387 && is_bracket_pair_end
3388 && snapshot.contains_str_at(selection.end, text.as_ref())
3389 {
3390 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3391 // and the inserted text is a closing bracket and the selection is followed
3392 // by the closing bracket then move the selection past the closing bracket.
3393 let anchor = snapshot.anchor_after(selection.end);
3394 new_selections.push((selection.map(|_| anchor), text.len()));
3395 continue;
3396 }
3397 }
3398 // If an opening bracket is 1 character long and is typed while
3399 // text is selected, then surround that text with the bracket pair.
3400 else if auto_surround
3401 && bracket_pair.surround
3402 && is_bracket_pair_start
3403 && bracket_pair.start.chars().count() == 1
3404 {
3405 edits.push((selection.start..selection.start, text.clone()));
3406 edits.push((
3407 selection.end..selection.end,
3408 bracket_pair.end.as_str().into(),
3409 ));
3410 bracket_inserted = true;
3411 new_selections.push((
3412 Selection {
3413 id: selection.id,
3414 start: snapshot.anchor_after(selection.start),
3415 end: snapshot.anchor_before(selection.end),
3416 reversed: selection.reversed,
3417 goal: selection.goal,
3418 },
3419 0,
3420 ));
3421 continue;
3422 }
3423 }
3424 }
3425
3426 if self.auto_replace_emoji_shortcode
3427 && selection.is_empty()
3428 && text.as_ref().ends_with(':')
3429 {
3430 if let Some(possible_emoji_short_code) =
3431 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3432 {
3433 if !possible_emoji_short_code.is_empty() {
3434 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3435 let emoji_shortcode_start = Point::new(
3436 selection.start.row,
3437 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3438 );
3439
3440 // Remove shortcode from buffer
3441 edits.push((
3442 emoji_shortcode_start..selection.start,
3443 "".to_string().into(),
3444 ));
3445 new_selections.push((
3446 Selection {
3447 id: selection.id,
3448 start: snapshot.anchor_after(emoji_shortcode_start),
3449 end: snapshot.anchor_before(selection.start),
3450 reversed: selection.reversed,
3451 goal: selection.goal,
3452 },
3453 0,
3454 ));
3455
3456 // Insert emoji
3457 let selection_start_anchor = snapshot.anchor_after(selection.start);
3458 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3459 edits.push((selection.start..selection.end, emoji.to_string().into()));
3460
3461 continue;
3462 }
3463 }
3464 }
3465 }
3466
3467 // If not handling any auto-close operation, then just replace the selected
3468 // text with the given input and move the selection to the end of the
3469 // newly inserted text.
3470 let anchor = snapshot.anchor_after(selection.end);
3471 if !self.linked_edit_ranges.is_empty() {
3472 let start_anchor = snapshot.anchor_before(selection.start);
3473
3474 let is_word_char = text.chars().next().map_or(true, |char| {
3475 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3476 classifier.is_word(char)
3477 });
3478
3479 if is_word_char {
3480 if let Some(ranges) = self
3481 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3482 {
3483 for (buffer, edits) in ranges {
3484 linked_edits
3485 .entry(buffer.clone())
3486 .or_default()
3487 .extend(edits.into_iter().map(|range| (range, text.clone())));
3488 }
3489 }
3490 } else {
3491 clear_linked_edit_ranges = true;
3492 }
3493 }
3494
3495 new_selections.push((selection.map(|_| anchor), 0));
3496 edits.push((selection.start..selection.end, text.clone()));
3497 }
3498
3499 drop(snapshot);
3500
3501 self.transact(window, cx, |this, window, cx| {
3502 if clear_linked_edit_ranges {
3503 this.linked_edit_ranges.clear();
3504 }
3505 let initial_buffer_versions =
3506 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3507
3508 this.buffer.update(cx, |buffer, cx| {
3509 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3510 });
3511 for (buffer, edits) in linked_edits {
3512 buffer.update(cx, |buffer, cx| {
3513 let snapshot = buffer.snapshot();
3514 let edits = edits
3515 .into_iter()
3516 .map(|(range, text)| {
3517 use text::ToPoint as TP;
3518 let end_point = TP::to_point(&range.end, &snapshot);
3519 let start_point = TP::to_point(&range.start, &snapshot);
3520 (start_point..end_point, text)
3521 })
3522 .sorted_by_key(|(range, _)| range.start);
3523 buffer.edit(edits, None, cx);
3524 })
3525 }
3526 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3527 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3528 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3529 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3530 .zip(new_selection_deltas)
3531 .map(|(selection, delta)| Selection {
3532 id: selection.id,
3533 start: selection.start + delta,
3534 end: selection.end + delta,
3535 reversed: selection.reversed,
3536 goal: SelectionGoal::None,
3537 })
3538 .collect::<Vec<_>>();
3539
3540 let mut i = 0;
3541 for (position, delta, selection_id, pair) in new_autoclose_regions {
3542 let position = position.to_offset(&map.buffer_snapshot) + delta;
3543 let start = map.buffer_snapshot.anchor_before(position);
3544 let end = map.buffer_snapshot.anchor_after(position);
3545 while let Some(existing_state) = this.autoclose_regions.get(i) {
3546 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3547 Ordering::Less => i += 1,
3548 Ordering::Greater => break,
3549 Ordering::Equal => {
3550 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3551 Ordering::Less => i += 1,
3552 Ordering::Equal => break,
3553 Ordering::Greater => break,
3554 }
3555 }
3556 }
3557 }
3558 this.autoclose_regions.insert(
3559 i,
3560 AutocloseRegion {
3561 selection_id,
3562 range: start..end,
3563 pair,
3564 },
3565 );
3566 }
3567
3568 let had_active_inline_completion = this.has_active_inline_completion();
3569 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3570 s.select(new_selections)
3571 });
3572
3573 if !bracket_inserted {
3574 if let Some(on_type_format_task) =
3575 this.trigger_on_type_formatting(text.to_string(), window, cx)
3576 {
3577 on_type_format_task.detach_and_log_err(cx);
3578 }
3579 }
3580
3581 let editor_settings = EditorSettings::get_global(cx);
3582 if bracket_inserted
3583 && (editor_settings.auto_signature_help
3584 || editor_settings.show_signature_help_after_edits)
3585 {
3586 this.show_signature_help(&ShowSignatureHelp, window, cx);
3587 }
3588
3589 let trigger_in_words =
3590 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3591 if this.hard_wrap.is_some() {
3592 let latest: Range<Point> = this.selections.newest(cx).range();
3593 if latest.is_empty()
3594 && this
3595 .buffer()
3596 .read(cx)
3597 .snapshot(cx)
3598 .line_len(MultiBufferRow(latest.start.row))
3599 == latest.start.column
3600 {
3601 this.rewrap_impl(
3602 RewrapOptions {
3603 override_language_settings: true,
3604 preserve_existing_whitespace: true,
3605 },
3606 cx,
3607 )
3608 }
3609 }
3610 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3611 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3612 this.refresh_inline_completion(true, false, window, cx);
3613 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3614 });
3615 }
3616
3617 fn find_possible_emoji_shortcode_at_position(
3618 snapshot: &MultiBufferSnapshot,
3619 position: Point,
3620 ) -> Option<String> {
3621 let mut chars = Vec::new();
3622 let mut found_colon = false;
3623 for char in snapshot.reversed_chars_at(position).take(100) {
3624 // Found a possible emoji shortcode in the middle of the buffer
3625 if found_colon {
3626 if char.is_whitespace() {
3627 chars.reverse();
3628 return Some(chars.iter().collect());
3629 }
3630 // If the previous character is not a whitespace, we are in the middle of a word
3631 // and we only want to complete the shortcode if the word is made up of other emojis
3632 let mut containing_word = String::new();
3633 for ch in snapshot
3634 .reversed_chars_at(position)
3635 .skip(chars.len() + 1)
3636 .take(100)
3637 {
3638 if ch.is_whitespace() {
3639 break;
3640 }
3641 containing_word.push(ch);
3642 }
3643 let containing_word = containing_word.chars().rev().collect::<String>();
3644 if util::word_consists_of_emojis(containing_word.as_str()) {
3645 chars.reverse();
3646 return Some(chars.iter().collect());
3647 }
3648 }
3649
3650 if char.is_whitespace() || !char.is_ascii() {
3651 return None;
3652 }
3653 if char == ':' {
3654 found_colon = true;
3655 } else {
3656 chars.push(char);
3657 }
3658 }
3659 // Found a possible emoji shortcode at the beginning of the buffer
3660 chars.reverse();
3661 Some(chars.iter().collect())
3662 }
3663
3664 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3665 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3666 self.transact(window, cx, |this, window, cx| {
3667 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3668 let selections = this.selections.all::<usize>(cx);
3669 let multi_buffer = this.buffer.read(cx);
3670 let buffer = multi_buffer.snapshot(cx);
3671 selections
3672 .iter()
3673 .map(|selection| {
3674 let start_point = selection.start.to_point(&buffer);
3675 let mut indent =
3676 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3677 indent.len = cmp::min(indent.len, start_point.column);
3678 let start = selection.start;
3679 let end = selection.end;
3680 let selection_is_empty = start == end;
3681 let language_scope = buffer.language_scope_at(start);
3682 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3683 &language_scope
3684 {
3685 let insert_extra_newline =
3686 insert_extra_newline_brackets(&buffer, start..end, language)
3687 || insert_extra_newline_tree_sitter(&buffer, start..end);
3688
3689 // Comment extension on newline is allowed only for cursor selections
3690 let comment_delimiter = maybe!({
3691 if !selection_is_empty {
3692 return None;
3693 }
3694
3695 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3696 return None;
3697 }
3698
3699 let delimiters = language.line_comment_prefixes();
3700 let max_len_of_delimiter =
3701 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3702 let (snapshot, range) =
3703 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3704
3705 let mut index_of_first_non_whitespace = 0;
3706 let comment_candidate = snapshot
3707 .chars_for_range(range)
3708 .skip_while(|c| {
3709 let should_skip = c.is_whitespace();
3710 if should_skip {
3711 index_of_first_non_whitespace += 1;
3712 }
3713 should_skip
3714 })
3715 .take(max_len_of_delimiter)
3716 .collect::<String>();
3717 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3718 comment_candidate.starts_with(comment_prefix.as_ref())
3719 })?;
3720 let cursor_is_placed_after_comment_marker =
3721 index_of_first_non_whitespace + comment_prefix.len()
3722 <= start_point.column as usize;
3723 if cursor_is_placed_after_comment_marker {
3724 Some(comment_prefix.clone())
3725 } else {
3726 None
3727 }
3728 });
3729 (comment_delimiter, insert_extra_newline)
3730 } else {
3731 (None, false)
3732 };
3733
3734 let capacity_for_delimiter = comment_delimiter
3735 .as_deref()
3736 .map(str::len)
3737 .unwrap_or_default();
3738 let mut new_text =
3739 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3740 new_text.push('\n');
3741 new_text.extend(indent.chars());
3742 if let Some(delimiter) = &comment_delimiter {
3743 new_text.push_str(delimiter);
3744 }
3745 if insert_extra_newline {
3746 new_text = new_text.repeat(2);
3747 }
3748
3749 let anchor = buffer.anchor_after(end);
3750 let new_selection = selection.map(|_| anchor);
3751 (
3752 (start..end, new_text),
3753 (insert_extra_newline, new_selection),
3754 )
3755 })
3756 .unzip()
3757 };
3758
3759 this.edit_with_autoindent(edits, cx);
3760 let buffer = this.buffer.read(cx).snapshot(cx);
3761 let new_selections = selection_fixup_info
3762 .into_iter()
3763 .map(|(extra_newline_inserted, new_selection)| {
3764 let mut cursor = new_selection.end.to_point(&buffer);
3765 if extra_newline_inserted {
3766 cursor.row -= 1;
3767 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3768 }
3769 new_selection.map(|_| cursor)
3770 })
3771 .collect();
3772
3773 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3774 s.select(new_selections)
3775 });
3776 this.refresh_inline_completion(true, false, window, cx);
3777 });
3778 }
3779
3780 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3781 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3782
3783 let buffer = self.buffer.read(cx);
3784 let snapshot = buffer.snapshot(cx);
3785
3786 let mut edits = Vec::new();
3787 let mut rows = Vec::new();
3788
3789 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3790 let cursor = selection.head();
3791 let row = cursor.row;
3792
3793 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3794
3795 let newline = "\n".to_string();
3796 edits.push((start_of_line..start_of_line, newline));
3797
3798 rows.push(row + rows_inserted as u32);
3799 }
3800
3801 self.transact(window, cx, |editor, window, cx| {
3802 editor.edit(edits, cx);
3803
3804 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3805 let mut index = 0;
3806 s.move_cursors_with(|map, _, _| {
3807 let row = rows[index];
3808 index += 1;
3809
3810 let point = Point::new(row, 0);
3811 let boundary = map.next_line_boundary(point).1;
3812 let clipped = map.clip_point(boundary, Bias::Left);
3813
3814 (clipped, SelectionGoal::None)
3815 });
3816 });
3817
3818 let mut indent_edits = Vec::new();
3819 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3820 for row in rows {
3821 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3822 for (row, indent) in indents {
3823 if indent.len == 0 {
3824 continue;
3825 }
3826
3827 let text = match indent.kind {
3828 IndentKind::Space => " ".repeat(indent.len as usize),
3829 IndentKind::Tab => "\t".repeat(indent.len as usize),
3830 };
3831 let point = Point::new(row.0, 0);
3832 indent_edits.push((point..point, text));
3833 }
3834 }
3835 editor.edit(indent_edits, cx);
3836 });
3837 }
3838
3839 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3840 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3841
3842 let buffer = self.buffer.read(cx);
3843 let snapshot = buffer.snapshot(cx);
3844
3845 let mut edits = Vec::new();
3846 let mut rows = Vec::new();
3847 let mut rows_inserted = 0;
3848
3849 for selection in self.selections.all_adjusted(cx) {
3850 let cursor = selection.head();
3851 let row = cursor.row;
3852
3853 let point = Point::new(row + 1, 0);
3854 let start_of_line = snapshot.clip_point(point, Bias::Left);
3855
3856 let newline = "\n".to_string();
3857 edits.push((start_of_line..start_of_line, newline));
3858
3859 rows_inserted += 1;
3860 rows.push(row + rows_inserted);
3861 }
3862
3863 self.transact(window, cx, |editor, window, cx| {
3864 editor.edit(edits, cx);
3865
3866 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3867 let mut index = 0;
3868 s.move_cursors_with(|map, _, _| {
3869 let row = rows[index];
3870 index += 1;
3871
3872 let point = Point::new(row, 0);
3873 let boundary = map.next_line_boundary(point).1;
3874 let clipped = map.clip_point(boundary, Bias::Left);
3875
3876 (clipped, SelectionGoal::None)
3877 });
3878 });
3879
3880 let mut indent_edits = Vec::new();
3881 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3882 for row in rows {
3883 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3884 for (row, indent) in indents {
3885 if indent.len == 0 {
3886 continue;
3887 }
3888
3889 let text = match indent.kind {
3890 IndentKind::Space => " ".repeat(indent.len as usize),
3891 IndentKind::Tab => "\t".repeat(indent.len as usize),
3892 };
3893 let point = Point::new(row.0, 0);
3894 indent_edits.push((point..point, text));
3895 }
3896 }
3897 editor.edit(indent_edits, cx);
3898 });
3899 }
3900
3901 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3902 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3903 original_indent_columns: Vec::new(),
3904 });
3905 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3906 }
3907
3908 fn insert_with_autoindent_mode(
3909 &mut self,
3910 text: &str,
3911 autoindent_mode: Option<AutoindentMode>,
3912 window: &mut Window,
3913 cx: &mut Context<Self>,
3914 ) {
3915 if self.read_only(cx) {
3916 return;
3917 }
3918
3919 let text: Arc<str> = text.into();
3920 self.transact(window, cx, |this, window, cx| {
3921 let old_selections = this.selections.all_adjusted(cx);
3922 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3923 let anchors = {
3924 let snapshot = buffer.read(cx);
3925 old_selections
3926 .iter()
3927 .map(|s| {
3928 let anchor = snapshot.anchor_after(s.head());
3929 s.map(|_| anchor)
3930 })
3931 .collect::<Vec<_>>()
3932 };
3933 buffer.edit(
3934 old_selections
3935 .iter()
3936 .map(|s| (s.start..s.end, text.clone())),
3937 autoindent_mode,
3938 cx,
3939 );
3940 anchors
3941 });
3942
3943 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3944 s.select_anchors(selection_anchors);
3945 });
3946
3947 cx.notify();
3948 });
3949 }
3950
3951 fn trigger_completion_on_input(
3952 &mut self,
3953 text: &str,
3954 trigger_in_words: bool,
3955 window: &mut Window,
3956 cx: &mut Context<Self>,
3957 ) {
3958 let ignore_completion_provider = self
3959 .context_menu
3960 .borrow()
3961 .as_ref()
3962 .map(|menu| match menu {
3963 CodeContextMenu::Completions(completions_menu) => {
3964 completions_menu.ignore_completion_provider
3965 }
3966 CodeContextMenu::CodeActions(_) => false,
3967 })
3968 .unwrap_or(false);
3969
3970 if ignore_completion_provider {
3971 self.show_word_completions(&ShowWordCompletions, window, cx);
3972 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3973 self.show_completions(
3974 &ShowCompletions {
3975 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3976 },
3977 window,
3978 cx,
3979 );
3980 } else {
3981 self.hide_context_menu(window, cx);
3982 }
3983 }
3984
3985 fn is_completion_trigger(
3986 &self,
3987 text: &str,
3988 trigger_in_words: bool,
3989 cx: &mut Context<Self>,
3990 ) -> bool {
3991 let position = self.selections.newest_anchor().head();
3992 let multibuffer = self.buffer.read(cx);
3993 let Some(buffer) = position
3994 .buffer_id
3995 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3996 else {
3997 return false;
3998 };
3999
4000 if let Some(completion_provider) = &self.completion_provider {
4001 completion_provider.is_completion_trigger(
4002 &buffer,
4003 position.text_anchor,
4004 text,
4005 trigger_in_words,
4006 cx,
4007 )
4008 } else {
4009 false
4010 }
4011 }
4012
4013 /// If any empty selections is touching the start of its innermost containing autoclose
4014 /// region, expand it to select the brackets.
4015 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4016 let selections = self.selections.all::<usize>(cx);
4017 let buffer = self.buffer.read(cx).read(cx);
4018 let new_selections = self
4019 .selections_with_autoclose_regions(selections, &buffer)
4020 .map(|(mut selection, region)| {
4021 if !selection.is_empty() {
4022 return selection;
4023 }
4024
4025 if let Some(region) = region {
4026 let mut range = region.range.to_offset(&buffer);
4027 if selection.start == range.start && range.start >= region.pair.start.len() {
4028 range.start -= region.pair.start.len();
4029 if buffer.contains_str_at(range.start, ®ion.pair.start)
4030 && buffer.contains_str_at(range.end, ®ion.pair.end)
4031 {
4032 range.end += region.pair.end.len();
4033 selection.start = range.start;
4034 selection.end = range.end;
4035
4036 return selection;
4037 }
4038 }
4039 }
4040
4041 let always_treat_brackets_as_autoclosed = buffer
4042 .language_settings_at(selection.start, cx)
4043 .always_treat_brackets_as_autoclosed;
4044
4045 if !always_treat_brackets_as_autoclosed {
4046 return selection;
4047 }
4048
4049 if let Some(scope) = buffer.language_scope_at(selection.start) {
4050 for (pair, enabled) in scope.brackets() {
4051 if !enabled || !pair.close {
4052 continue;
4053 }
4054
4055 if buffer.contains_str_at(selection.start, &pair.end) {
4056 let pair_start_len = pair.start.len();
4057 if buffer.contains_str_at(
4058 selection.start.saturating_sub(pair_start_len),
4059 &pair.start,
4060 ) {
4061 selection.start -= pair_start_len;
4062 selection.end += pair.end.len();
4063
4064 return selection;
4065 }
4066 }
4067 }
4068 }
4069
4070 selection
4071 })
4072 .collect();
4073
4074 drop(buffer);
4075 self.change_selections(None, window, cx, |selections| {
4076 selections.select(new_selections)
4077 });
4078 }
4079
4080 /// Iterate the given selections, and for each one, find the smallest surrounding
4081 /// autoclose region. This uses the ordering of the selections and the autoclose
4082 /// regions to avoid repeated comparisons.
4083 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4084 &'a self,
4085 selections: impl IntoIterator<Item = Selection<D>>,
4086 buffer: &'a MultiBufferSnapshot,
4087 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4088 let mut i = 0;
4089 let mut regions = self.autoclose_regions.as_slice();
4090 selections.into_iter().map(move |selection| {
4091 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4092
4093 let mut enclosing = None;
4094 while let Some(pair_state) = regions.get(i) {
4095 if pair_state.range.end.to_offset(buffer) < range.start {
4096 regions = ®ions[i + 1..];
4097 i = 0;
4098 } else if pair_state.range.start.to_offset(buffer) > range.end {
4099 break;
4100 } else {
4101 if pair_state.selection_id == selection.id {
4102 enclosing = Some(pair_state);
4103 }
4104 i += 1;
4105 }
4106 }
4107
4108 (selection, enclosing)
4109 })
4110 }
4111
4112 /// Remove any autoclose regions that no longer contain their selection.
4113 fn invalidate_autoclose_regions(
4114 &mut self,
4115 mut selections: &[Selection<Anchor>],
4116 buffer: &MultiBufferSnapshot,
4117 ) {
4118 self.autoclose_regions.retain(|state| {
4119 let mut i = 0;
4120 while let Some(selection) = selections.get(i) {
4121 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4122 selections = &selections[1..];
4123 continue;
4124 }
4125 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4126 break;
4127 }
4128 if selection.id == state.selection_id {
4129 return true;
4130 } else {
4131 i += 1;
4132 }
4133 }
4134 false
4135 });
4136 }
4137
4138 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4139 let offset = position.to_offset(buffer);
4140 let (word_range, kind) = buffer.surrounding_word(offset, true);
4141 if offset > word_range.start && kind == Some(CharKind::Word) {
4142 Some(
4143 buffer
4144 .text_for_range(word_range.start..offset)
4145 .collect::<String>(),
4146 )
4147 } else {
4148 None
4149 }
4150 }
4151
4152 pub fn toggle_inlay_hints(
4153 &mut self,
4154 _: &ToggleInlayHints,
4155 _: &mut Window,
4156 cx: &mut Context<Self>,
4157 ) {
4158 self.refresh_inlay_hints(
4159 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4160 cx,
4161 );
4162 }
4163
4164 pub fn inlay_hints_enabled(&self) -> bool {
4165 self.inlay_hint_cache.enabled
4166 }
4167
4168 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4169 if self.semantics_provider.is_none() || !self.mode.is_full() {
4170 return;
4171 }
4172
4173 let reason_description = reason.description();
4174 let ignore_debounce = matches!(
4175 reason,
4176 InlayHintRefreshReason::SettingsChange(_)
4177 | InlayHintRefreshReason::Toggle(_)
4178 | InlayHintRefreshReason::ExcerptsRemoved(_)
4179 | InlayHintRefreshReason::ModifiersChanged(_)
4180 );
4181 let (invalidate_cache, required_languages) = match reason {
4182 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4183 match self.inlay_hint_cache.modifiers_override(enabled) {
4184 Some(enabled) => {
4185 if enabled {
4186 (InvalidationStrategy::RefreshRequested, None)
4187 } else {
4188 self.splice_inlays(
4189 &self
4190 .visible_inlay_hints(cx)
4191 .iter()
4192 .map(|inlay| inlay.id)
4193 .collect::<Vec<InlayId>>(),
4194 Vec::new(),
4195 cx,
4196 );
4197 return;
4198 }
4199 }
4200 None => return,
4201 }
4202 }
4203 InlayHintRefreshReason::Toggle(enabled) => {
4204 if self.inlay_hint_cache.toggle(enabled) {
4205 if enabled {
4206 (InvalidationStrategy::RefreshRequested, None)
4207 } else {
4208 self.splice_inlays(
4209 &self
4210 .visible_inlay_hints(cx)
4211 .iter()
4212 .map(|inlay| inlay.id)
4213 .collect::<Vec<InlayId>>(),
4214 Vec::new(),
4215 cx,
4216 );
4217 return;
4218 }
4219 } else {
4220 return;
4221 }
4222 }
4223 InlayHintRefreshReason::SettingsChange(new_settings) => {
4224 match self.inlay_hint_cache.update_settings(
4225 &self.buffer,
4226 new_settings,
4227 self.visible_inlay_hints(cx),
4228 cx,
4229 ) {
4230 ControlFlow::Break(Some(InlaySplice {
4231 to_remove,
4232 to_insert,
4233 })) => {
4234 self.splice_inlays(&to_remove, to_insert, cx);
4235 return;
4236 }
4237 ControlFlow::Break(None) => return,
4238 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4239 }
4240 }
4241 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4242 if let Some(InlaySplice {
4243 to_remove,
4244 to_insert,
4245 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4246 {
4247 self.splice_inlays(&to_remove, to_insert, cx);
4248 }
4249 self.display_map.update(cx, |display_map, _| {
4250 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4251 });
4252 return;
4253 }
4254 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4255 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4256 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4257 }
4258 InlayHintRefreshReason::RefreshRequested => {
4259 (InvalidationStrategy::RefreshRequested, None)
4260 }
4261 };
4262
4263 if let Some(InlaySplice {
4264 to_remove,
4265 to_insert,
4266 }) = self.inlay_hint_cache.spawn_hint_refresh(
4267 reason_description,
4268 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4269 invalidate_cache,
4270 ignore_debounce,
4271 cx,
4272 ) {
4273 self.splice_inlays(&to_remove, to_insert, cx);
4274 }
4275 }
4276
4277 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4278 self.display_map
4279 .read(cx)
4280 .current_inlays()
4281 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4282 .cloned()
4283 .collect()
4284 }
4285
4286 pub fn excerpts_for_inlay_hints_query(
4287 &self,
4288 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4289 cx: &mut Context<Editor>,
4290 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4291 let Some(project) = self.project.as_ref() else {
4292 return HashMap::default();
4293 };
4294 let project = project.read(cx);
4295 let multi_buffer = self.buffer().read(cx);
4296 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4297 let multi_buffer_visible_start = self
4298 .scroll_manager
4299 .anchor()
4300 .anchor
4301 .to_point(&multi_buffer_snapshot);
4302 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4303 multi_buffer_visible_start
4304 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4305 Bias::Left,
4306 );
4307 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4308 multi_buffer_snapshot
4309 .range_to_buffer_ranges(multi_buffer_visible_range)
4310 .into_iter()
4311 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4312 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4313 let buffer_file = project::File::from_dyn(buffer.file())?;
4314 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4315 let worktree_entry = buffer_worktree
4316 .read(cx)
4317 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4318 if worktree_entry.is_ignored {
4319 return None;
4320 }
4321
4322 let language = buffer.language()?;
4323 if let Some(restrict_to_languages) = restrict_to_languages {
4324 if !restrict_to_languages.contains(language) {
4325 return None;
4326 }
4327 }
4328 Some((
4329 excerpt_id,
4330 (
4331 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4332 buffer.version().clone(),
4333 excerpt_visible_range,
4334 ),
4335 ))
4336 })
4337 .collect()
4338 }
4339
4340 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4341 TextLayoutDetails {
4342 text_system: window.text_system().clone(),
4343 editor_style: self.style.clone().unwrap(),
4344 rem_size: window.rem_size(),
4345 scroll_anchor: self.scroll_manager.anchor(),
4346 visible_rows: self.visible_line_count(),
4347 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4348 }
4349 }
4350
4351 pub fn splice_inlays(
4352 &self,
4353 to_remove: &[InlayId],
4354 to_insert: Vec<Inlay>,
4355 cx: &mut Context<Self>,
4356 ) {
4357 self.display_map.update(cx, |display_map, cx| {
4358 display_map.splice_inlays(to_remove, to_insert, cx)
4359 });
4360 cx.notify();
4361 }
4362
4363 fn trigger_on_type_formatting(
4364 &self,
4365 input: String,
4366 window: &mut Window,
4367 cx: &mut Context<Self>,
4368 ) -> Option<Task<Result<()>>> {
4369 if input.len() != 1 {
4370 return None;
4371 }
4372
4373 let project = self.project.as_ref()?;
4374 let position = self.selections.newest_anchor().head();
4375 let (buffer, buffer_position) = self
4376 .buffer
4377 .read(cx)
4378 .text_anchor_for_position(position, cx)?;
4379
4380 let settings = language_settings::language_settings(
4381 buffer
4382 .read(cx)
4383 .language_at(buffer_position)
4384 .map(|l| l.name()),
4385 buffer.read(cx).file(),
4386 cx,
4387 );
4388 if !settings.use_on_type_format {
4389 return None;
4390 }
4391
4392 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4393 // hence we do LSP request & edit on host side only — add formats to host's history.
4394 let push_to_lsp_host_history = true;
4395 // If this is not the host, append its history with new edits.
4396 let push_to_client_history = project.read(cx).is_via_collab();
4397
4398 let on_type_formatting = project.update(cx, |project, cx| {
4399 project.on_type_format(
4400 buffer.clone(),
4401 buffer_position,
4402 input,
4403 push_to_lsp_host_history,
4404 cx,
4405 )
4406 });
4407 Some(cx.spawn_in(window, async move |editor, cx| {
4408 if let Some(transaction) = on_type_formatting.await? {
4409 if push_to_client_history {
4410 buffer
4411 .update(cx, |buffer, _| {
4412 buffer.push_transaction(transaction, Instant::now());
4413 buffer.finalize_last_transaction();
4414 })
4415 .ok();
4416 }
4417 editor.update(cx, |editor, cx| {
4418 editor.refresh_document_highlights(cx);
4419 })?;
4420 }
4421 Ok(())
4422 }))
4423 }
4424
4425 pub fn show_word_completions(
4426 &mut self,
4427 _: &ShowWordCompletions,
4428 window: &mut Window,
4429 cx: &mut Context<Self>,
4430 ) {
4431 self.open_completions_menu(true, None, window, cx);
4432 }
4433
4434 pub fn show_completions(
4435 &mut self,
4436 options: &ShowCompletions,
4437 window: &mut Window,
4438 cx: &mut Context<Self>,
4439 ) {
4440 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4441 }
4442
4443 fn open_completions_menu(
4444 &mut self,
4445 ignore_completion_provider: bool,
4446 trigger: Option<&str>,
4447 window: &mut Window,
4448 cx: &mut Context<Self>,
4449 ) {
4450 if self.pending_rename.is_some() {
4451 return;
4452 }
4453 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4454 return;
4455 }
4456
4457 let position = self.selections.newest_anchor().head();
4458 if position.diff_base_anchor.is_some() {
4459 return;
4460 }
4461 let (buffer, buffer_position) =
4462 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4463 output
4464 } else {
4465 return;
4466 };
4467 let buffer_snapshot = buffer.read(cx).snapshot();
4468 let show_completion_documentation = buffer_snapshot
4469 .settings_at(buffer_position, cx)
4470 .show_completion_documentation;
4471
4472 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4473
4474 let trigger_kind = match trigger {
4475 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4476 CompletionTriggerKind::TRIGGER_CHARACTER
4477 }
4478 _ => CompletionTriggerKind::INVOKED,
4479 };
4480 let completion_context = CompletionContext {
4481 trigger_character: trigger.and_then(|trigger| {
4482 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4483 Some(String::from(trigger))
4484 } else {
4485 None
4486 }
4487 }),
4488 trigger_kind,
4489 };
4490
4491 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4492 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4493 let word_to_exclude = buffer_snapshot
4494 .text_for_range(old_range.clone())
4495 .collect::<String>();
4496 (
4497 buffer_snapshot.anchor_before(old_range.start)
4498 ..buffer_snapshot.anchor_after(old_range.end),
4499 Some(word_to_exclude),
4500 )
4501 } else {
4502 (buffer_position..buffer_position, None)
4503 };
4504
4505 let completion_settings = language_settings(
4506 buffer_snapshot
4507 .language_at(buffer_position)
4508 .map(|language| language.name()),
4509 buffer_snapshot.file(),
4510 cx,
4511 )
4512 .completions;
4513
4514 // The document can be large, so stay in reasonable bounds when searching for words,
4515 // otherwise completion pop-up might be slow to appear.
4516 const WORD_LOOKUP_ROWS: u32 = 5_000;
4517 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4518 let min_word_search = buffer_snapshot.clip_point(
4519 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4520 Bias::Left,
4521 );
4522 let max_word_search = buffer_snapshot.clip_point(
4523 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4524 Bias::Right,
4525 );
4526 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4527 ..buffer_snapshot.point_to_offset(max_word_search);
4528
4529 let provider = self
4530 .completion_provider
4531 .as_ref()
4532 .filter(|_| !ignore_completion_provider);
4533 let skip_digits = query
4534 .as_ref()
4535 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4536
4537 let (mut words, provided_completions) = match provider {
4538 Some(provider) => {
4539 let completions = provider.completions(
4540 position.excerpt_id,
4541 &buffer,
4542 buffer_position,
4543 completion_context,
4544 window,
4545 cx,
4546 );
4547
4548 let words = match completion_settings.words {
4549 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4550 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4551 .background_spawn(async move {
4552 buffer_snapshot.words_in_range(WordsQuery {
4553 fuzzy_contents: None,
4554 range: word_search_range,
4555 skip_digits,
4556 })
4557 }),
4558 };
4559
4560 (words, completions)
4561 }
4562 None => (
4563 cx.background_spawn(async move {
4564 buffer_snapshot.words_in_range(WordsQuery {
4565 fuzzy_contents: None,
4566 range: word_search_range,
4567 skip_digits,
4568 })
4569 }),
4570 Task::ready(Ok(None)),
4571 ),
4572 };
4573
4574 let sort_completions = provider
4575 .as_ref()
4576 .map_or(false, |provider| provider.sort_completions());
4577
4578 let filter_completions = provider
4579 .as_ref()
4580 .map_or(true, |provider| provider.filter_completions());
4581
4582 let id = post_inc(&mut self.next_completion_id);
4583 let task = cx.spawn_in(window, async move |editor, cx| {
4584 async move {
4585 editor.update(cx, |this, _| {
4586 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4587 })?;
4588
4589 let mut completions = Vec::new();
4590 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4591 completions.extend(provided_completions);
4592 if completion_settings.words == WordsCompletionMode::Fallback {
4593 words = Task::ready(BTreeMap::default());
4594 }
4595 }
4596
4597 let mut words = words.await;
4598 if let Some(word_to_exclude) = &word_to_exclude {
4599 words.remove(word_to_exclude);
4600 }
4601 for lsp_completion in &completions {
4602 words.remove(&lsp_completion.new_text);
4603 }
4604 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4605 replace_range: old_range.clone(),
4606 new_text: word.clone(),
4607 label: CodeLabel::plain(word, None),
4608 icon_path: None,
4609 documentation: None,
4610 source: CompletionSource::BufferWord {
4611 word_range,
4612 resolved: false,
4613 },
4614 insert_text_mode: Some(InsertTextMode::AS_IS),
4615 confirm: None,
4616 }));
4617
4618 let menu = if completions.is_empty() {
4619 None
4620 } else {
4621 let mut menu = CompletionsMenu::new(
4622 id,
4623 sort_completions,
4624 show_completion_documentation,
4625 ignore_completion_provider,
4626 position,
4627 buffer.clone(),
4628 completions.into(),
4629 );
4630
4631 menu.filter(
4632 if filter_completions {
4633 query.as_deref()
4634 } else {
4635 None
4636 },
4637 cx.background_executor().clone(),
4638 )
4639 .await;
4640
4641 menu.visible().then_some(menu)
4642 };
4643
4644 editor.update_in(cx, |editor, window, cx| {
4645 match editor.context_menu.borrow().as_ref() {
4646 None => {}
4647 Some(CodeContextMenu::Completions(prev_menu)) => {
4648 if prev_menu.id > id {
4649 return;
4650 }
4651 }
4652 _ => return,
4653 }
4654
4655 if editor.focus_handle.is_focused(window) && menu.is_some() {
4656 let mut menu = menu.unwrap();
4657 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4658
4659 *editor.context_menu.borrow_mut() =
4660 Some(CodeContextMenu::Completions(menu));
4661
4662 if editor.show_edit_predictions_in_menu() {
4663 editor.update_visible_inline_completion(window, cx);
4664 } else {
4665 editor.discard_inline_completion(false, cx);
4666 }
4667
4668 cx.notify();
4669 } else if editor.completion_tasks.len() <= 1 {
4670 // If there are no more completion tasks and the last menu was
4671 // empty, we should hide it.
4672 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4673 // If it was already hidden and we don't show inline
4674 // completions in the menu, we should also show the
4675 // inline-completion when available.
4676 if was_hidden && editor.show_edit_predictions_in_menu() {
4677 editor.update_visible_inline_completion(window, cx);
4678 }
4679 }
4680 })?;
4681
4682 anyhow::Ok(())
4683 }
4684 .log_err()
4685 .await
4686 });
4687
4688 self.completion_tasks.push((id, task));
4689 }
4690
4691 #[cfg(feature = "test-support")]
4692 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4693 let menu = self.context_menu.borrow();
4694 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4695 let completions = menu.completions.borrow();
4696 Some(completions.to_vec())
4697 } else {
4698 None
4699 }
4700 }
4701
4702 pub fn confirm_completion(
4703 &mut self,
4704 action: &ConfirmCompletion,
4705 window: &mut Window,
4706 cx: &mut Context<Self>,
4707 ) -> Option<Task<Result<()>>> {
4708 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4709 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4710 }
4711
4712 pub fn confirm_completion_insert(
4713 &mut self,
4714 _: &ConfirmCompletionInsert,
4715 window: &mut Window,
4716 cx: &mut Context<Self>,
4717 ) -> Option<Task<Result<()>>> {
4718 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4719 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4720 }
4721
4722 pub fn confirm_completion_replace(
4723 &mut self,
4724 _: &ConfirmCompletionReplace,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) -> Option<Task<Result<()>>> {
4728 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4729 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4730 }
4731
4732 pub fn compose_completion(
4733 &mut self,
4734 action: &ComposeCompletion,
4735 window: &mut Window,
4736 cx: &mut Context<Self>,
4737 ) -> Option<Task<Result<()>>> {
4738 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4739 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4740 }
4741
4742 fn do_completion(
4743 &mut self,
4744 item_ix: Option<usize>,
4745 intent: CompletionIntent,
4746 window: &mut Window,
4747 cx: &mut Context<Editor>,
4748 ) -> Option<Task<Result<()>>> {
4749 use language::ToOffset as _;
4750
4751 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4752 else {
4753 return None;
4754 };
4755
4756 let candidate_id = {
4757 let entries = completions_menu.entries.borrow();
4758 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4759 if self.show_edit_predictions_in_menu() {
4760 self.discard_inline_completion(true, cx);
4761 }
4762 mat.candidate_id
4763 };
4764
4765 let buffer_handle = completions_menu.buffer;
4766 let completion = completions_menu
4767 .completions
4768 .borrow()
4769 .get(candidate_id)?
4770 .clone();
4771 cx.stop_propagation();
4772
4773 let snippet;
4774 let new_text;
4775 if completion.is_snippet() {
4776 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4777 new_text = snippet.as_ref().unwrap().text.clone();
4778 } else {
4779 snippet = None;
4780 new_text = completion.new_text.clone();
4781 };
4782
4783 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4784 let buffer = buffer_handle.read(cx);
4785 let snapshot = self.buffer.read(cx).snapshot(cx);
4786 let replace_range_multibuffer = {
4787 let excerpt = snapshot
4788 .excerpt_containing(self.selections.newest_anchor().range())
4789 .unwrap();
4790 let multibuffer_anchor = snapshot
4791 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4792 .unwrap()
4793 ..snapshot
4794 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4795 .unwrap();
4796 multibuffer_anchor.start.to_offset(&snapshot)
4797 ..multibuffer_anchor.end.to_offset(&snapshot)
4798 };
4799 let newest_anchor = self.selections.newest_anchor();
4800 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4801 return None;
4802 }
4803
4804 let old_text = buffer
4805 .text_for_range(replace_range.clone())
4806 .collect::<String>();
4807 let lookbehind = newest_anchor
4808 .start
4809 .text_anchor
4810 .to_offset(buffer)
4811 .saturating_sub(replace_range.start);
4812 let lookahead = replace_range
4813 .end
4814 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4815 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4816 let suffix = &old_text[lookbehind.min(old_text.len())..];
4817
4818 let selections = self.selections.all::<usize>(cx);
4819 let mut edits = Vec::new();
4820 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4821
4822 for selection in &selections {
4823 let edit = if selection.id == newest_anchor.id {
4824 (replace_range_multibuffer.clone(), new_text.as_str())
4825 } else {
4826 let mut range = selection.range();
4827 let mut text = new_text.as_str();
4828
4829 // if prefix is present, don't duplicate it
4830 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4831 text = &new_text[lookbehind.min(new_text.len())..];
4832
4833 // if suffix is also present, mimic the newest cursor and replace it
4834 if selection.id != newest_anchor.id
4835 && snapshot.contains_str_at(range.end, suffix)
4836 {
4837 range.end += lookahead;
4838 }
4839 }
4840 (range, text)
4841 };
4842
4843 edits.push(edit);
4844
4845 if !self.linked_edit_ranges.is_empty() {
4846 let start_anchor = snapshot.anchor_before(selection.head());
4847 let end_anchor = snapshot.anchor_after(selection.tail());
4848 if let Some(ranges) = self
4849 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4850 {
4851 for (buffer, edits) in ranges {
4852 linked_edits
4853 .entry(buffer.clone())
4854 .or_default()
4855 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4856 }
4857 }
4858 }
4859 }
4860
4861 cx.emit(EditorEvent::InputHandled {
4862 utf16_range_to_replace: None,
4863 text: new_text.clone().into(),
4864 });
4865
4866 self.transact(window, cx, |this, window, cx| {
4867 if let Some(mut snippet) = snippet {
4868 snippet.text = new_text.to_string();
4869 let ranges = edits
4870 .iter()
4871 .map(|(range, _)| range.clone())
4872 .collect::<Vec<_>>();
4873 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4874 } else {
4875 this.buffer.update(cx, |buffer, cx| {
4876 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4877 {
4878 None
4879 } else {
4880 this.autoindent_mode.clone()
4881 };
4882 buffer.edit(edits, auto_indent, cx);
4883 });
4884 }
4885 for (buffer, edits) in linked_edits {
4886 buffer.update(cx, |buffer, cx| {
4887 let snapshot = buffer.snapshot();
4888 let edits = edits
4889 .into_iter()
4890 .map(|(range, text)| {
4891 use text::ToPoint as TP;
4892 let end_point = TP::to_point(&range.end, &snapshot);
4893 let start_point = TP::to_point(&range.start, &snapshot);
4894 (start_point..end_point, text)
4895 })
4896 .sorted_by_key(|(range, _)| range.start);
4897 buffer.edit(edits, None, cx);
4898 })
4899 }
4900
4901 this.refresh_inline_completion(true, false, window, cx);
4902 });
4903
4904 let show_new_completions_on_confirm = completion
4905 .confirm
4906 .as_ref()
4907 .map_or(false, |confirm| confirm(intent, window, cx));
4908 if show_new_completions_on_confirm {
4909 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4910 }
4911
4912 let provider = self.completion_provider.as_ref()?;
4913 drop(completion);
4914 let apply_edits = provider.apply_additional_edits_for_completion(
4915 buffer_handle,
4916 completions_menu.completions.clone(),
4917 candidate_id,
4918 true,
4919 cx,
4920 );
4921
4922 let editor_settings = EditorSettings::get_global(cx);
4923 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4924 // After the code completion is finished, users often want to know what signatures are needed.
4925 // so we should automatically call signature_help
4926 self.show_signature_help(&ShowSignatureHelp, window, cx);
4927 }
4928
4929 Some(cx.foreground_executor().spawn(async move {
4930 apply_edits.await?;
4931 Ok(())
4932 }))
4933 }
4934
4935 fn prepare_code_actions_task(
4936 &mut self,
4937 action: &ToggleCodeActions,
4938 window: &mut Window,
4939 cx: &mut Context<Self>,
4940 ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
4941 let snapshot = self.snapshot(window, cx);
4942 let multibuffer_point = action
4943 .deployed_from_indicator
4944 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4945 .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
4946
4947 let Some((buffer, buffer_row)) = snapshot
4948 .buffer_snapshot
4949 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4950 .and_then(|(buffer_snapshot, range)| {
4951 self.buffer
4952 .read(cx)
4953 .buffer(buffer_snapshot.remote_id())
4954 .map(|buffer| (buffer, range.start.row))
4955 })
4956 else {
4957 return Task::ready(None);
4958 };
4959
4960 let (_, code_actions) = self
4961 .available_code_actions
4962 .clone()
4963 .and_then(|(location, code_actions)| {
4964 let snapshot = location.buffer.read(cx).snapshot();
4965 let point_range = location.range.to_point(&snapshot);
4966 let point_range = point_range.start.row..=point_range.end.row;
4967 if point_range.contains(&buffer_row) {
4968 Some((location, code_actions))
4969 } else {
4970 None
4971 }
4972 })
4973 .unzip();
4974
4975 let buffer_id = buffer.read(cx).remote_id();
4976 let tasks = self
4977 .tasks
4978 .get(&(buffer_id, buffer_row))
4979 .map(|t| Arc::new(t.to_owned()));
4980
4981 if tasks.is_none() && code_actions.is_none() {
4982 return Task::ready(None);
4983 }
4984
4985 self.completion_tasks.clear();
4986 self.discard_inline_completion(false, cx);
4987
4988 let task_context = tasks
4989 .as_ref()
4990 .zip(self.project.clone())
4991 .map(|(tasks, project)| {
4992 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4993 });
4994
4995 cx.spawn_in(window, async move |_, _| {
4996 let task_context = match task_context {
4997 Some(task_context) => task_context.await,
4998 None => None,
4999 };
5000 let resolved_tasks = tasks.zip(task_context).map(|(tasks, task_context)| {
5001 Rc::new(ResolvedTasks {
5002 templates: tasks.resolve(&task_context).collect(),
5003 position: snapshot
5004 .buffer_snapshot
5005 .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
5006 })
5007 });
5008 Some((
5009 buffer,
5010 CodeActionContents {
5011 actions: code_actions,
5012 tasks: resolved_tasks,
5013 },
5014 ))
5015 })
5016 }
5017
5018 pub fn toggle_code_actions(
5019 &mut self,
5020 action: &ToggleCodeActions,
5021 window: &mut Window,
5022 cx: &mut Context<Self>,
5023 ) {
5024 let mut context_menu = self.context_menu.borrow_mut();
5025 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5026 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5027 // Toggle if we're selecting the same one
5028 *context_menu = None;
5029 cx.notify();
5030 return;
5031 } else {
5032 // Otherwise, clear it and start a new one
5033 *context_menu = None;
5034 cx.notify();
5035 }
5036 }
5037 drop(context_menu);
5038
5039 let deployed_from_indicator = action.deployed_from_indicator;
5040 let mut task = self.code_actions_task.take();
5041 let action = action.clone();
5042
5043 cx.spawn_in(window, async move |editor, cx| {
5044 while let Some(prev_task) = task {
5045 prev_task.await.log_err();
5046 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5047 }
5048
5049 let context_menu_task = editor.update_in(cx, |editor, window, cx| {
5050 if !editor.focus_handle.is_focused(window) {
5051 return Some(Task::ready(Ok(())));
5052 }
5053 let debugger_flag = cx.has_flag::<Debugger>();
5054 let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
5055 Some(cx.spawn_in(window, async move |editor, cx| {
5056 if let Some((buffer, code_action_contents)) = code_actions_task.await {
5057 let spawn_straight_away =
5058 code_action_contents.tasks.as_ref().map_or(false, |tasks| {
5059 tasks
5060 .templates
5061 .iter()
5062 .filter(|task| {
5063 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5064 debugger_flag
5065 } else {
5066 true
5067 }
5068 })
5069 .count()
5070 == 1
5071 }) && code_action_contents
5072 .actions
5073 .as_ref()
5074 .map_or(true, |actions| actions.is_empty());
5075 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5076 *editor.context_menu.borrow_mut() =
5077 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5078 buffer,
5079 actions: code_action_contents,
5080 selected_item: Default::default(),
5081 scroll_handle: UniformListScrollHandle::default(),
5082 deployed_from_indicator,
5083 }));
5084 if spawn_straight_away {
5085 if let Some(task) = editor.confirm_code_action(
5086 &ConfirmCodeAction {
5087 item_ix: Some(0),
5088 from_mouse_context_menu: false,
5089 },
5090 window,
5091 cx,
5092 ) {
5093 cx.notify();
5094 return task;
5095 }
5096 }
5097 cx.notify();
5098 Task::ready(Ok(()))
5099 }) {
5100 task.await
5101 } else {
5102 Ok(())
5103 }
5104 } else {
5105 Ok(())
5106 }
5107 }))
5108 })?;
5109 if let Some(task) = context_menu_task {
5110 task.await?;
5111 }
5112
5113 Ok::<_, anyhow::Error>(())
5114 })
5115 .detach_and_log_err(cx);
5116 }
5117
5118 pub fn confirm_code_action(
5119 &mut self,
5120 action: &ConfirmCodeAction,
5121 window: &mut Window,
5122 cx: &mut Context<Self>,
5123 ) -> Option<Task<Result<()>>> {
5124 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5125
5126 let (action, buffer) = if action.from_mouse_context_menu {
5127 if let Some(menu) = self.mouse_context_menu.take() {
5128 let code_action = menu.code_action?;
5129 let index = action.item_ix?;
5130 let action = code_action.actions.get(index)?;
5131 (action, code_action.buffer)
5132 } else {
5133 return None;
5134 }
5135 } else {
5136 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5137 let action_ix = action.item_ix.unwrap_or(menu.selected_item);
5138 let action = menu.actions.get(action_ix)?;
5139 let buffer = menu.buffer;
5140 (action, buffer)
5141 } else {
5142 return None;
5143 }
5144 };
5145
5146 let title = action.label();
5147 let workspace = self.workspace()?;
5148
5149 match action {
5150 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5151 match resolved_task.task_type() {
5152 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5153 workspace::tasks::schedule_resolved_task(
5154 workspace,
5155 task_source_kind,
5156 resolved_task,
5157 false,
5158 cx,
5159 );
5160
5161 Some(Task::ready(Ok(())))
5162 }),
5163 task::TaskType::Debug(debug_args) => {
5164 if debug_args.locator.is_some() {
5165 workspace.update(cx, |workspace, cx| {
5166 workspace::tasks::schedule_resolved_task(
5167 workspace,
5168 task_source_kind,
5169 resolved_task,
5170 false,
5171 cx,
5172 );
5173 });
5174
5175 return Some(Task::ready(Ok(())));
5176 }
5177
5178 if let Some(project) = self.project.as_ref() {
5179 project
5180 .update(cx, |project, cx| {
5181 project.start_debug_session(
5182 resolved_task.resolved_debug_adapter_config().unwrap(),
5183 cx,
5184 )
5185 })
5186 .detach_and_log_err(cx);
5187 Some(Task::ready(Ok(())))
5188 } else {
5189 Some(Task::ready(Ok(())))
5190 }
5191 }
5192 }
5193 }
5194 CodeActionsItem::CodeAction {
5195 excerpt_id,
5196 action,
5197 provider,
5198 } => {
5199 let apply_code_action =
5200 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5201 let workspace = workspace.downgrade();
5202 Some(cx.spawn_in(window, async move |editor, cx| {
5203 let project_transaction = apply_code_action.await?;
5204 Self::open_project_transaction(
5205 &editor,
5206 workspace,
5207 project_transaction,
5208 title,
5209 cx,
5210 )
5211 .await
5212 }))
5213 }
5214 }
5215 }
5216
5217 pub async fn open_project_transaction(
5218 this: &WeakEntity<Editor>,
5219 workspace: WeakEntity<Workspace>,
5220 transaction: ProjectTransaction,
5221 title: String,
5222 cx: &mut AsyncWindowContext,
5223 ) -> Result<()> {
5224 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5225 cx.update(|_, cx| {
5226 entries.sort_unstable_by_key(|(buffer, _)| {
5227 buffer.read(cx).file().map(|f| f.path().clone())
5228 });
5229 })?;
5230
5231 // If the project transaction's edits are all contained within this editor, then
5232 // avoid opening a new editor to display them.
5233
5234 if let Some((buffer, transaction)) = entries.first() {
5235 if entries.len() == 1 {
5236 let excerpt = this.update(cx, |editor, cx| {
5237 editor
5238 .buffer()
5239 .read(cx)
5240 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5241 })?;
5242 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5243 if excerpted_buffer == *buffer {
5244 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5245 let excerpt_range = excerpt_range.to_offset(buffer);
5246 buffer
5247 .edited_ranges_for_transaction::<usize>(transaction)
5248 .all(|range| {
5249 excerpt_range.start <= range.start
5250 && excerpt_range.end >= range.end
5251 })
5252 })?;
5253
5254 if all_edits_within_excerpt {
5255 return Ok(());
5256 }
5257 }
5258 }
5259 }
5260 } else {
5261 return Ok(());
5262 }
5263
5264 let mut ranges_to_highlight = Vec::new();
5265 let excerpt_buffer = cx.new(|cx| {
5266 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5267 for (buffer_handle, transaction) in &entries {
5268 let edited_ranges = buffer_handle
5269 .read(cx)
5270 .edited_ranges_for_transaction::<Point>(transaction)
5271 .collect::<Vec<_>>();
5272 let (ranges, _) = multibuffer.set_excerpts_for_path(
5273 PathKey::for_buffer(buffer_handle, cx),
5274 buffer_handle.clone(),
5275 edited_ranges,
5276 DEFAULT_MULTIBUFFER_CONTEXT,
5277 cx,
5278 );
5279
5280 ranges_to_highlight.extend(ranges);
5281 }
5282 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5283 multibuffer
5284 })?;
5285
5286 workspace.update_in(cx, |workspace, window, cx| {
5287 let project = workspace.project().clone();
5288 let editor =
5289 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5290 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5291 editor.update(cx, |editor, cx| {
5292 editor.highlight_background::<Self>(
5293 &ranges_to_highlight,
5294 |theme| theme.editor_highlighted_line_background,
5295 cx,
5296 );
5297 });
5298 })?;
5299
5300 Ok(())
5301 }
5302
5303 pub fn clear_code_action_providers(&mut self) {
5304 self.code_action_providers.clear();
5305 self.available_code_actions.take();
5306 }
5307
5308 pub fn add_code_action_provider(
5309 &mut self,
5310 provider: Rc<dyn CodeActionProvider>,
5311 window: &mut Window,
5312 cx: &mut Context<Self>,
5313 ) {
5314 if self
5315 .code_action_providers
5316 .iter()
5317 .any(|existing_provider| existing_provider.id() == provider.id())
5318 {
5319 return;
5320 }
5321
5322 self.code_action_providers.push(provider);
5323 self.refresh_code_actions(window, cx);
5324 }
5325
5326 pub fn remove_code_action_provider(
5327 &mut self,
5328 id: Arc<str>,
5329 window: &mut Window,
5330 cx: &mut Context<Self>,
5331 ) {
5332 self.code_action_providers
5333 .retain(|provider| provider.id() != id);
5334 self.refresh_code_actions(window, cx);
5335 }
5336
5337 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5338 let newest_selection = self.selections.newest_anchor().clone();
5339 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5340 let buffer = self.buffer.read(cx);
5341 if newest_selection.head().diff_base_anchor.is_some() {
5342 return None;
5343 }
5344 let (start_buffer, start) =
5345 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5346 let (end_buffer, end) =
5347 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5348 if start_buffer != end_buffer {
5349 return None;
5350 }
5351
5352 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5353 cx.background_executor()
5354 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5355 .await;
5356
5357 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5358 let providers = this.code_action_providers.clone();
5359 let tasks = this
5360 .code_action_providers
5361 .iter()
5362 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5363 .collect::<Vec<_>>();
5364 (providers, tasks)
5365 })?;
5366
5367 let mut actions = Vec::new();
5368 for (provider, provider_actions) in
5369 providers.into_iter().zip(future::join_all(tasks).await)
5370 {
5371 if let Some(provider_actions) = provider_actions.log_err() {
5372 actions.extend(provider_actions.into_iter().map(|action| {
5373 AvailableCodeAction {
5374 excerpt_id: newest_selection.start.excerpt_id,
5375 action,
5376 provider: provider.clone(),
5377 }
5378 }));
5379 }
5380 }
5381
5382 this.update(cx, |this, cx| {
5383 this.available_code_actions = if actions.is_empty() {
5384 None
5385 } else {
5386 Some((
5387 Location {
5388 buffer: start_buffer,
5389 range: start..end,
5390 },
5391 actions.into(),
5392 ))
5393 };
5394 cx.notify();
5395 })
5396 }));
5397 None
5398 }
5399
5400 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5401 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5402 self.show_git_blame_inline = false;
5403
5404 self.show_git_blame_inline_delay_task =
5405 Some(cx.spawn_in(window, async move |this, cx| {
5406 cx.background_executor().timer(delay).await;
5407
5408 this.update(cx, |this, cx| {
5409 this.show_git_blame_inline = true;
5410 cx.notify();
5411 })
5412 .log_err();
5413 }));
5414 }
5415 }
5416
5417 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5418 if self.pending_rename.is_some() {
5419 return None;
5420 }
5421
5422 let provider = self.semantics_provider.clone()?;
5423 let buffer = self.buffer.read(cx);
5424 let newest_selection = self.selections.newest_anchor().clone();
5425 let cursor_position = newest_selection.head();
5426 let (cursor_buffer, cursor_buffer_position) =
5427 buffer.text_anchor_for_position(cursor_position, cx)?;
5428 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5429 if cursor_buffer != tail_buffer {
5430 return None;
5431 }
5432 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5433 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5434 cx.background_executor()
5435 .timer(Duration::from_millis(debounce))
5436 .await;
5437
5438 let highlights = if let Some(highlights) = cx
5439 .update(|cx| {
5440 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5441 })
5442 .ok()
5443 .flatten()
5444 {
5445 highlights.await.log_err()
5446 } else {
5447 None
5448 };
5449
5450 if let Some(highlights) = highlights {
5451 this.update(cx, |this, cx| {
5452 if this.pending_rename.is_some() {
5453 return;
5454 }
5455
5456 let buffer_id = cursor_position.buffer_id;
5457 let buffer = this.buffer.read(cx);
5458 if !buffer
5459 .text_anchor_for_position(cursor_position, cx)
5460 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5461 {
5462 return;
5463 }
5464
5465 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5466 let mut write_ranges = Vec::new();
5467 let mut read_ranges = Vec::new();
5468 for highlight in highlights {
5469 for (excerpt_id, excerpt_range) in
5470 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5471 {
5472 let start = highlight
5473 .range
5474 .start
5475 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5476 let end = highlight
5477 .range
5478 .end
5479 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5480 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5481 continue;
5482 }
5483
5484 let range = Anchor {
5485 buffer_id,
5486 excerpt_id,
5487 text_anchor: start,
5488 diff_base_anchor: None,
5489 }..Anchor {
5490 buffer_id,
5491 excerpt_id,
5492 text_anchor: end,
5493 diff_base_anchor: None,
5494 };
5495 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5496 write_ranges.push(range);
5497 } else {
5498 read_ranges.push(range);
5499 }
5500 }
5501 }
5502
5503 this.highlight_background::<DocumentHighlightRead>(
5504 &read_ranges,
5505 |theme| theme.editor_document_highlight_read_background,
5506 cx,
5507 );
5508 this.highlight_background::<DocumentHighlightWrite>(
5509 &write_ranges,
5510 |theme| theme.editor_document_highlight_write_background,
5511 cx,
5512 );
5513 cx.notify();
5514 })
5515 .log_err();
5516 }
5517 }));
5518 None
5519 }
5520
5521 pub fn refresh_selected_text_highlights(
5522 &mut self,
5523 window: &mut Window,
5524 cx: &mut Context<Editor>,
5525 ) {
5526 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5527 return;
5528 }
5529 self.selection_highlight_task.take();
5530 if !EditorSettings::get_global(cx).selection_highlight {
5531 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5532 return;
5533 }
5534 if self.selections.count() != 1 || self.selections.line_mode {
5535 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5536 return;
5537 }
5538 let selection = self.selections.newest::<Point>(cx);
5539 if selection.is_empty() || selection.start.row != selection.end.row {
5540 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5541 return;
5542 }
5543 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5544 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5545 cx.background_executor()
5546 .timer(Duration::from_millis(debounce))
5547 .await;
5548 let Some(Some(matches_task)) = editor
5549 .update_in(cx, |editor, _, cx| {
5550 if editor.selections.count() != 1 || editor.selections.line_mode {
5551 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5552 return None;
5553 }
5554 let selection = editor.selections.newest::<Point>(cx);
5555 if selection.is_empty() || selection.start.row != selection.end.row {
5556 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5557 return None;
5558 }
5559 let buffer = editor.buffer().read(cx).snapshot(cx);
5560 let query = buffer.text_for_range(selection.range()).collect::<String>();
5561 if query.trim().is_empty() {
5562 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5563 return None;
5564 }
5565 Some(cx.background_spawn(async move {
5566 let mut ranges = Vec::new();
5567 let selection_anchors = selection.range().to_anchors(&buffer);
5568 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5569 for (search_buffer, search_range, excerpt_id) in
5570 buffer.range_to_buffer_ranges(range)
5571 {
5572 ranges.extend(
5573 project::search::SearchQuery::text(
5574 query.clone(),
5575 false,
5576 false,
5577 false,
5578 Default::default(),
5579 Default::default(),
5580 None,
5581 )
5582 .unwrap()
5583 .search(search_buffer, Some(search_range.clone()))
5584 .await
5585 .into_iter()
5586 .filter_map(
5587 |match_range| {
5588 let start = search_buffer.anchor_after(
5589 search_range.start + match_range.start,
5590 );
5591 let end = search_buffer.anchor_before(
5592 search_range.start + match_range.end,
5593 );
5594 let range = Anchor::range_in_buffer(
5595 excerpt_id,
5596 search_buffer.remote_id(),
5597 start..end,
5598 );
5599 (range != selection_anchors).then_some(range)
5600 },
5601 ),
5602 );
5603 }
5604 }
5605 ranges
5606 }))
5607 })
5608 .log_err()
5609 else {
5610 return;
5611 };
5612 let matches = matches_task.await;
5613 editor
5614 .update_in(cx, |editor, _, cx| {
5615 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5616 if !matches.is_empty() {
5617 editor.highlight_background::<SelectedTextHighlight>(
5618 &matches,
5619 |theme| theme.editor_document_highlight_bracket_background,
5620 cx,
5621 )
5622 }
5623 })
5624 .log_err();
5625 }));
5626 }
5627
5628 pub fn refresh_inline_completion(
5629 &mut self,
5630 debounce: bool,
5631 user_requested: bool,
5632 window: &mut Window,
5633 cx: &mut Context<Self>,
5634 ) -> Option<()> {
5635 let provider = self.edit_prediction_provider()?;
5636 let cursor = self.selections.newest_anchor().head();
5637 let (buffer, cursor_buffer_position) =
5638 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5639
5640 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5641 self.discard_inline_completion(false, cx);
5642 return None;
5643 }
5644
5645 if !user_requested
5646 && (!self.should_show_edit_predictions()
5647 || !self.is_focused(window)
5648 || buffer.read(cx).is_empty())
5649 {
5650 self.discard_inline_completion(false, cx);
5651 return None;
5652 }
5653
5654 self.update_visible_inline_completion(window, cx);
5655 provider.refresh(
5656 self.project.clone(),
5657 buffer,
5658 cursor_buffer_position,
5659 debounce,
5660 cx,
5661 );
5662 Some(())
5663 }
5664
5665 fn show_edit_predictions_in_menu(&self) -> bool {
5666 match self.edit_prediction_settings {
5667 EditPredictionSettings::Disabled => false,
5668 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5669 }
5670 }
5671
5672 pub fn edit_predictions_enabled(&self) -> bool {
5673 match self.edit_prediction_settings {
5674 EditPredictionSettings::Disabled => false,
5675 EditPredictionSettings::Enabled { .. } => true,
5676 }
5677 }
5678
5679 fn edit_prediction_requires_modifier(&self) -> bool {
5680 match self.edit_prediction_settings {
5681 EditPredictionSettings::Disabled => false,
5682 EditPredictionSettings::Enabled {
5683 preview_requires_modifier,
5684 ..
5685 } => preview_requires_modifier,
5686 }
5687 }
5688
5689 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5690 if self.edit_prediction_provider.is_none() {
5691 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5692 } else {
5693 let selection = self.selections.newest_anchor();
5694 let cursor = selection.head();
5695
5696 if let Some((buffer, cursor_buffer_position)) =
5697 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5698 {
5699 self.edit_prediction_settings =
5700 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5701 }
5702 }
5703 }
5704
5705 fn edit_prediction_settings_at_position(
5706 &self,
5707 buffer: &Entity<Buffer>,
5708 buffer_position: language::Anchor,
5709 cx: &App,
5710 ) -> EditPredictionSettings {
5711 if !self.mode.is_full()
5712 || !self.show_inline_completions_override.unwrap_or(true)
5713 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5714 {
5715 return EditPredictionSettings::Disabled;
5716 }
5717
5718 let buffer = buffer.read(cx);
5719
5720 let file = buffer.file();
5721
5722 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5723 return EditPredictionSettings::Disabled;
5724 };
5725
5726 let by_provider = matches!(
5727 self.menu_inline_completions_policy,
5728 MenuInlineCompletionsPolicy::ByProvider
5729 );
5730
5731 let show_in_menu = by_provider
5732 && self
5733 .edit_prediction_provider
5734 .as_ref()
5735 .map_or(false, |provider| {
5736 provider.provider.show_completions_in_menu()
5737 });
5738
5739 let preview_requires_modifier =
5740 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5741
5742 EditPredictionSettings::Enabled {
5743 show_in_menu,
5744 preview_requires_modifier,
5745 }
5746 }
5747
5748 fn should_show_edit_predictions(&self) -> bool {
5749 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5750 }
5751
5752 pub fn edit_prediction_preview_is_active(&self) -> bool {
5753 matches!(
5754 self.edit_prediction_preview,
5755 EditPredictionPreview::Active { .. }
5756 )
5757 }
5758
5759 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5760 let cursor = self.selections.newest_anchor().head();
5761 if let Some((buffer, cursor_position)) =
5762 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5763 {
5764 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5765 } else {
5766 false
5767 }
5768 }
5769
5770 fn edit_predictions_enabled_in_buffer(
5771 &self,
5772 buffer: &Entity<Buffer>,
5773 buffer_position: language::Anchor,
5774 cx: &App,
5775 ) -> bool {
5776 maybe!({
5777 if self.read_only(cx) {
5778 return Some(false);
5779 }
5780 let provider = self.edit_prediction_provider()?;
5781 if !provider.is_enabled(&buffer, buffer_position, cx) {
5782 return Some(false);
5783 }
5784 let buffer = buffer.read(cx);
5785 let Some(file) = buffer.file() else {
5786 return Some(true);
5787 };
5788 let settings = all_language_settings(Some(file), cx);
5789 Some(settings.edit_predictions_enabled_for_file(file, cx))
5790 })
5791 .unwrap_or(false)
5792 }
5793
5794 fn cycle_inline_completion(
5795 &mut self,
5796 direction: Direction,
5797 window: &mut Window,
5798 cx: &mut Context<Self>,
5799 ) -> Option<()> {
5800 let provider = self.edit_prediction_provider()?;
5801 let cursor = self.selections.newest_anchor().head();
5802 let (buffer, cursor_buffer_position) =
5803 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5804 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5805 return None;
5806 }
5807
5808 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5809 self.update_visible_inline_completion(window, cx);
5810
5811 Some(())
5812 }
5813
5814 pub fn show_inline_completion(
5815 &mut self,
5816 _: &ShowEditPrediction,
5817 window: &mut Window,
5818 cx: &mut Context<Self>,
5819 ) {
5820 if !self.has_active_inline_completion() {
5821 self.refresh_inline_completion(false, true, window, cx);
5822 return;
5823 }
5824
5825 self.update_visible_inline_completion(window, cx);
5826 }
5827
5828 pub fn display_cursor_names(
5829 &mut self,
5830 _: &DisplayCursorNames,
5831 window: &mut Window,
5832 cx: &mut Context<Self>,
5833 ) {
5834 self.show_cursor_names(window, cx);
5835 }
5836
5837 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5838 self.show_cursor_names = true;
5839 cx.notify();
5840 cx.spawn_in(window, async move |this, cx| {
5841 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5842 this.update(cx, |this, cx| {
5843 this.show_cursor_names = false;
5844 cx.notify()
5845 })
5846 .ok()
5847 })
5848 .detach();
5849 }
5850
5851 pub fn next_edit_prediction(
5852 &mut self,
5853 _: &NextEditPrediction,
5854 window: &mut Window,
5855 cx: &mut Context<Self>,
5856 ) {
5857 if self.has_active_inline_completion() {
5858 self.cycle_inline_completion(Direction::Next, window, cx);
5859 } else {
5860 let is_copilot_disabled = self
5861 .refresh_inline_completion(false, true, window, cx)
5862 .is_none();
5863 if is_copilot_disabled {
5864 cx.propagate();
5865 }
5866 }
5867 }
5868
5869 pub fn previous_edit_prediction(
5870 &mut self,
5871 _: &PreviousEditPrediction,
5872 window: &mut Window,
5873 cx: &mut Context<Self>,
5874 ) {
5875 if self.has_active_inline_completion() {
5876 self.cycle_inline_completion(Direction::Prev, window, cx);
5877 } else {
5878 let is_copilot_disabled = self
5879 .refresh_inline_completion(false, true, window, cx)
5880 .is_none();
5881 if is_copilot_disabled {
5882 cx.propagate();
5883 }
5884 }
5885 }
5886
5887 pub fn accept_edit_prediction(
5888 &mut self,
5889 _: &AcceptEditPrediction,
5890 window: &mut Window,
5891 cx: &mut Context<Self>,
5892 ) {
5893 if self.show_edit_predictions_in_menu() {
5894 self.hide_context_menu(window, cx);
5895 }
5896
5897 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5898 return;
5899 };
5900
5901 self.report_inline_completion_event(
5902 active_inline_completion.completion_id.clone(),
5903 true,
5904 cx,
5905 );
5906
5907 match &active_inline_completion.completion {
5908 InlineCompletion::Move { target, .. } => {
5909 let target = *target;
5910
5911 if let Some(position_map) = &self.last_position_map {
5912 if position_map
5913 .visible_row_range
5914 .contains(&target.to_display_point(&position_map.snapshot).row())
5915 || !self.edit_prediction_requires_modifier()
5916 {
5917 self.unfold_ranges(&[target..target], true, false, cx);
5918 // Note that this is also done in vim's handler of the Tab action.
5919 self.change_selections(
5920 Some(Autoscroll::newest()),
5921 window,
5922 cx,
5923 |selections| {
5924 selections.select_anchor_ranges([target..target]);
5925 },
5926 );
5927 self.clear_row_highlights::<EditPredictionPreview>();
5928
5929 self.edit_prediction_preview
5930 .set_previous_scroll_position(None);
5931 } else {
5932 self.edit_prediction_preview
5933 .set_previous_scroll_position(Some(
5934 position_map.snapshot.scroll_anchor,
5935 ));
5936
5937 self.highlight_rows::<EditPredictionPreview>(
5938 target..target,
5939 cx.theme().colors().editor_highlighted_line_background,
5940 true,
5941 cx,
5942 );
5943 self.request_autoscroll(Autoscroll::fit(), cx);
5944 }
5945 }
5946 }
5947 InlineCompletion::Edit { edits, .. } => {
5948 if let Some(provider) = self.edit_prediction_provider() {
5949 provider.accept(cx);
5950 }
5951
5952 let snapshot = self.buffer.read(cx).snapshot(cx);
5953 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5954
5955 self.buffer.update(cx, |buffer, cx| {
5956 buffer.edit(edits.iter().cloned(), None, cx)
5957 });
5958
5959 self.change_selections(None, window, cx, |s| {
5960 s.select_anchor_ranges([last_edit_end..last_edit_end])
5961 });
5962
5963 self.update_visible_inline_completion(window, cx);
5964 if self.active_inline_completion.is_none() {
5965 self.refresh_inline_completion(true, true, window, cx);
5966 }
5967
5968 cx.notify();
5969 }
5970 }
5971
5972 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5973 }
5974
5975 pub fn accept_partial_inline_completion(
5976 &mut self,
5977 _: &AcceptPartialEditPrediction,
5978 window: &mut Window,
5979 cx: &mut Context<Self>,
5980 ) {
5981 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5982 return;
5983 };
5984 if self.selections.count() != 1 {
5985 return;
5986 }
5987
5988 self.report_inline_completion_event(
5989 active_inline_completion.completion_id.clone(),
5990 true,
5991 cx,
5992 );
5993
5994 match &active_inline_completion.completion {
5995 InlineCompletion::Move { target, .. } => {
5996 let target = *target;
5997 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5998 selections.select_anchor_ranges([target..target]);
5999 });
6000 }
6001 InlineCompletion::Edit { edits, .. } => {
6002 // Find an insertion that starts at the cursor position.
6003 let snapshot = self.buffer.read(cx).snapshot(cx);
6004 let cursor_offset = self.selections.newest::<usize>(cx).head();
6005 let insertion = edits.iter().find_map(|(range, text)| {
6006 let range = range.to_offset(&snapshot);
6007 if range.is_empty() && range.start == cursor_offset {
6008 Some(text)
6009 } else {
6010 None
6011 }
6012 });
6013
6014 if let Some(text) = insertion {
6015 let mut partial_completion = text
6016 .chars()
6017 .by_ref()
6018 .take_while(|c| c.is_alphabetic())
6019 .collect::<String>();
6020 if partial_completion.is_empty() {
6021 partial_completion = text
6022 .chars()
6023 .by_ref()
6024 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6025 .collect::<String>();
6026 }
6027
6028 cx.emit(EditorEvent::InputHandled {
6029 utf16_range_to_replace: None,
6030 text: partial_completion.clone().into(),
6031 });
6032
6033 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6034
6035 self.refresh_inline_completion(true, true, window, cx);
6036 cx.notify();
6037 } else {
6038 self.accept_edit_prediction(&Default::default(), window, cx);
6039 }
6040 }
6041 }
6042 }
6043
6044 fn discard_inline_completion(
6045 &mut self,
6046 should_report_inline_completion_event: bool,
6047 cx: &mut Context<Self>,
6048 ) -> bool {
6049 if should_report_inline_completion_event {
6050 let completion_id = self
6051 .active_inline_completion
6052 .as_ref()
6053 .and_then(|active_completion| active_completion.completion_id.clone());
6054
6055 self.report_inline_completion_event(completion_id, false, cx);
6056 }
6057
6058 if let Some(provider) = self.edit_prediction_provider() {
6059 provider.discard(cx);
6060 }
6061
6062 self.take_active_inline_completion(cx)
6063 }
6064
6065 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6066 let Some(provider) = self.edit_prediction_provider() else {
6067 return;
6068 };
6069
6070 let Some((_, buffer, _)) = self
6071 .buffer
6072 .read(cx)
6073 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6074 else {
6075 return;
6076 };
6077
6078 let extension = buffer
6079 .read(cx)
6080 .file()
6081 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6082
6083 let event_type = match accepted {
6084 true => "Edit Prediction Accepted",
6085 false => "Edit Prediction Discarded",
6086 };
6087 telemetry::event!(
6088 event_type,
6089 provider = provider.name(),
6090 prediction_id = id,
6091 suggestion_accepted = accepted,
6092 file_extension = extension,
6093 );
6094 }
6095
6096 pub fn has_active_inline_completion(&self) -> bool {
6097 self.active_inline_completion.is_some()
6098 }
6099
6100 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6101 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6102 return false;
6103 };
6104
6105 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6106 self.clear_highlights::<InlineCompletionHighlight>(cx);
6107 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6108 true
6109 }
6110
6111 /// Returns true when we're displaying the edit prediction popover below the cursor
6112 /// like we are not previewing and the LSP autocomplete menu is visible
6113 /// or we are in `when_holding_modifier` mode.
6114 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6115 if self.edit_prediction_preview_is_active()
6116 || !self.show_edit_predictions_in_menu()
6117 || !self.edit_predictions_enabled()
6118 {
6119 return false;
6120 }
6121
6122 if self.has_visible_completions_menu() {
6123 return true;
6124 }
6125
6126 has_completion && self.edit_prediction_requires_modifier()
6127 }
6128
6129 fn handle_modifiers_changed(
6130 &mut self,
6131 modifiers: Modifiers,
6132 position_map: &PositionMap,
6133 window: &mut Window,
6134 cx: &mut Context<Self>,
6135 ) {
6136 if self.show_edit_predictions_in_menu() {
6137 self.update_edit_prediction_preview(&modifiers, window, cx);
6138 }
6139
6140 self.update_selection_mode(&modifiers, position_map, window, cx);
6141
6142 let mouse_position = window.mouse_position();
6143 if !position_map.text_hitbox.is_hovered(window) {
6144 return;
6145 }
6146
6147 self.update_hovered_link(
6148 position_map.point_for_position(mouse_position),
6149 &position_map.snapshot,
6150 modifiers,
6151 window,
6152 cx,
6153 )
6154 }
6155
6156 fn update_selection_mode(
6157 &mut self,
6158 modifiers: &Modifiers,
6159 position_map: &PositionMap,
6160 window: &mut Window,
6161 cx: &mut Context<Self>,
6162 ) {
6163 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6164 return;
6165 }
6166
6167 let mouse_position = window.mouse_position();
6168 let point_for_position = position_map.point_for_position(mouse_position);
6169 let position = point_for_position.previous_valid;
6170
6171 self.select(
6172 SelectPhase::BeginColumnar {
6173 position,
6174 reset: false,
6175 goal_column: point_for_position.exact_unclipped.column(),
6176 },
6177 window,
6178 cx,
6179 );
6180 }
6181
6182 fn update_edit_prediction_preview(
6183 &mut self,
6184 modifiers: &Modifiers,
6185 window: &mut Window,
6186 cx: &mut Context<Self>,
6187 ) {
6188 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6189 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6190 return;
6191 };
6192
6193 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6194 if matches!(
6195 self.edit_prediction_preview,
6196 EditPredictionPreview::Inactive { .. }
6197 ) {
6198 self.edit_prediction_preview = EditPredictionPreview::Active {
6199 previous_scroll_position: None,
6200 since: Instant::now(),
6201 };
6202
6203 self.update_visible_inline_completion(window, cx);
6204 cx.notify();
6205 }
6206 } else if let EditPredictionPreview::Active {
6207 previous_scroll_position,
6208 since,
6209 } = self.edit_prediction_preview
6210 {
6211 if let (Some(previous_scroll_position), Some(position_map)) =
6212 (previous_scroll_position, self.last_position_map.as_ref())
6213 {
6214 self.set_scroll_position(
6215 previous_scroll_position
6216 .scroll_position(&position_map.snapshot.display_snapshot),
6217 window,
6218 cx,
6219 );
6220 }
6221
6222 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6223 released_too_fast: since.elapsed() < Duration::from_millis(200),
6224 };
6225 self.clear_row_highlights::<EditPredictionPreview>();
6226 self.update_visible_inline_completion(window, cx);
6227 cx.notify();
6228 }
6229 }
6230
6231 fn update_visible_inline_completion(
6232 &mut self,
6233 _window: &mut Window,
6234 cx: &mut Context<Self>,
6235 ) -> Option<()> {
6236 let selection = self.selections.newest_anchor();
6237 let cursor = selection.head();
6238 let multibuffer = self.buffer.read(cx).snapshot(cx);
6239 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6240 let excerpt_id = cursor.excerpt_id;
6241
6242 let show_in_menu = self.show_edit_predictions_in_menu();
6243 let completions_menu_has_precedence = !show_in_menu
6244 && (self.context_menu.borrow().is_some()
6245 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6246
6247 if completions_menu_has_precedence
6248 || !offset_selection.is_empty()
6249 || self
6250 .active_inline_completion
6251 .as_ref()
6252 .map_or(false, |completion| {
6253 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6254 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6255 !invalidation_range.contains(&offset_selection.head())
6256 })
6257 {
6258 self.discard_inline_completion(false, cx);
6259 return None;
6260 }
6261
6262 self.take_active_inline_completion(cx);
6263 let Some(provider) = self.edit_prediction_provider() else {
6264 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6265 return None;
6266 };
6267
6268 let (buffer, cursor_buffer_position) =
6269 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6270
6271 self.edit_prediction_settings =
6272 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6273
6274 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6275
6276 if self.edit_prediction_indent_conflict {
6277 let cursor_point = cursor.to_point(&multibuffer);
6278
6279 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6280
6281 if let Some((_, indent)) = indents.iter().next() {
6282 if indent.len == cursor_point.column {
6283 self.edit_prediction_indent_conflict = false;
6284 }
6285 }
6286 }
6287
6288 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6289 let edits = inline_completion
6290 .edits
6291 .into_iter()
6292 .flat_map(|(range, new_text)| {
6293 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6294 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6295 Some((start..end, new_text))
6296 })
6297 .collect::<Vec<_>>();
6298 if edits.is_empty() {
6299 return None;
6300 }
6301
6302 let first_edit_start = edits.first().unwrap().0.start;
6303 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6304 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6305
6306 let last_edit_end = edits.last().unwrap().0.end;
6307 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6308 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6309
6310 let cursor_row = cursor.to_point(&multibuffer).row;
6311
6312 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6313
6314 let mut inlay_ids = Vec::new();
6315 let invalidation_row_range;
6316 let move_invalidation_row_range = if cursor_row < edit_start_row {
6317 Some(cursor_row..edit_end_row)
6318 } else if cursor_row > edit_end_row {
6319 Some(edit_start_row..cursor_row)
6320 } else {
6321 None
6322 };
6323 let is_move =
6324 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6325 let completion = if is_move {
6326 invalidation_row_range =
6327 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6328 let target = first_edit_start;
6329 InlineCompletion::Move { target, snapshot }
6330 } else {
6331 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6332 && !self.inline_completions_hidden_for_vim_mode;
6333
6334 if show_completions_in_buffer {
6335 if edits
6336 .iter()
6337 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6338 {
6339 let mut inlays = Vec::new();
6340 for (range, new_text) in &edits {
6341 let inlay = Inlay::inline_completion(
6342 post_inc(&mut self.next_inlay_id),
6343 range.start,
6344 new_text.as_str(),
6345 );
6346 inlay_ids.push(inlay.id);
6347 inlays.push(inlay);
6348 }
6349
6350 self.splice_inlays(&[], inlays, cx);
6351 } else {
6352 let background_color = cx.theme().status().deleted_background;
6353 self.highlight_text::<InlineCompletionHighlight>(
6354 edits.iter().map(|(range, _)| range.clone()).collect(),
6355 HighlightStyle {
6356 background_color: Some(background_color),
6357 ..Default::default()
6358 },
6359 cx,
6360 );
6361 }
6362 }
6363
6364 invalidation_row_range = edit_start_row..edit_end_row;
6365
6366 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6367 if provider.show_tab_accept_marker() {
6368 EditDisplayMode::TabAccept
6369 } else {
6370 EditDisplayMode::Inline
6371 }
6372 } else {
6373 EditDisplayMode::DiffPopover
6374 };
6375
6376 InlineCompletion::Edit {
6377 edits,
6378 edit_preview: inline_completion.edit_preview,
6379 display_mode,
6380 snapshot,
6381 }
6382 };
6383
6384 let invalidation_range = multibuffer
6385 .anchor_before(Point::new(invalidation_row_range.start, 0))
6386 ..multibuffer.anchor_after(Point::new(
6387 invalidation_row_range.end,
6388 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6389 ));
6390
6391 self.stale_inline_completion_in_menu = None;
6392 self.active_inline_completion = Some(InlineCompletionState {
6393 inlay_ids,
6394 completion,
6395 completion_id: inline_completion.id,
6396 invalidation_range,
6397 });
6398
6399 cx.notify();
6400
6401 Some(())
6402 }
6403
6404 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6405 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6406 }
6407
6408 fn render_code_actions_indicator(
6409 &self,
6410 _style: &EditorStyle,
6411 row: DisplayRow,
6412 is_active: bool,
6413 breakpoint: Option<&(Anchor, Breakpoint)>,
6414 cx: &mut Context<Self>,
6415 ) -> Option<IconButton> {
6416 let color = Color::Muted;
6417 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6418 let show_tooltip = !self.context_menu_visible();
6419
6420 if self.available_code_actions.is_some() {
6421 Some(
6422 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6423 .shape(ui::IconButtonShape::Square)
6424 .icon_size(IconSize::XSmall)
6425 .icon_color(color)
6426 .toggle_state(is_active)
6427 .when(show_tooltip, |this| {
6428 this.tooltip({
6429 let focus_handle = self.focus_handle.clone();
6430 move |window, cx| {
6431 Tooltip::for_action_in(
6432 "Toggle Code Actions",
6433 &ToggleCodeActions {
6434 deployed_from_indicator: None,
6435 },
6436 &focus_handle,
6437 window,
6438 cx,
6439 )
6440 }
6441 })
6442 })
6443 .on_click(cx.listener(move |editor, _e, window, cx| {
6444 window.focus(&editor.focus_handle(cx));
6445 editor.toggle_code_actions(
6446 &ToggleCodeActions {
6447 deployed_from_indicator: Some(row),
6448 },
6449 window,
6450 cx,
6451 );
6452 }))
6453 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6454 editor.set_breakpoint_context_menu(
6455 row,
6456 position,
6457 event.down.position,
6458 window,
6459 cx,
6460 );
6461 })),
6462 )
6463 } else {
6464 None
6465 }
6466 }
6467
6468 fn clear_tasks(&mut self) {
6469 self.tasks.clear()
6470 }
6471
6472 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6473 if self.tasks.insert(key, value).is_some() {
6474 // This case should hopefully be rare, but just in case...
6475 log::error!(
6476 "multiple different run targets found on a single line, only the last target will be rendered"
6477 )
6478 }
6479 }
6480
6481 /// Get all display points of breakpoints that will be rendered within editor
6482 ///
6483 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6484 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6485 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6486 fn active_breakpoints(
6487 &self,
6488 range: Range<DisplayRow>,
6489 window: &mut Window,
6490 cx: &mut Context<Self>,
6491 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6492 let mut breakpoint_display_points = HashMap::default();
6493
6494 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6495 return breakpoint_display_points;
6496 };
6497
6498 let snapshot = self.snapshot(window, cx);
6499
6500 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6501 let Some(project) = self.project.as_ref() else {
6502 return breakpoint_display_points;
6503 };
6504
6505 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6506 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6507
6508 for (buffer_snapshot, range, excerpt_id) in
6509 multi_buffer_snapshot.range_to_buffer_ranges(range)
6510 {
6511 let Some(buffer) = project.read_with(cx, |this, cx| {
6512 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6513 }) else {
6514 continue;
6515 };
6516 let breakpoints = breakpoint_store.read(cx).breakpoints(
6517 &buffer,
6518 Some(
6519 buffer_snapshot.anchor_before(range.start)
6520 ..buffer_snapshot.anchor_after(range.end),
6521 ),
6522 buffer_snapshot,
6523 cx,
6524 );
6525 for (anchor, breakpoint) in breakpoints {
6526 let multi_buffer_anchor =
6527 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6528 let position = multi_buffer_anchor
6529 .to_point(&multi_buffer_snapshot)
6530 .to_display_point(&snapshot);
6531
6532 breakpoint_display_points
6533 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6534 }
6535 }
6536
6537 breakpoint_display_points
6538 }
6539
6540 fn breakpoint_context_menu(
6541 &self,
6542 anchor: Anchor,
6543 window: &mut Window,
6544 cx: &mut Context<Self>,
6545 ) -> Entity<ui::ContextMenu> {
6546 let weak_editor = cx.weak_entity();
6547 let focus_handle = self.focus_handle(cx);
6548
6549 let row = self
6550 .buffer
6551 .read(cx)
6552 .snapshot(cx)
6553 .summary_for_anchor::<Point>(&anchor)
6554 .row;
6555
6556 let breakpoint = self
6557 .breakpoint_at_row(row, window, cx)
6558 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6559
6560 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6561 "Edit Log Breakpoint"
6562 } else {
6563 "Set Log Breakpoint"
6564 };
6565
6566 let condition_breakpoint_msg = if breakpoint
6567 .as_ref()
6568 .is_some_and(|bp| bp.1.condition.is_some())
6569 {
6570 "Edit Condition Breakpoint"
6571 } else {
6572 "Set Condition Breakpoint"
6573 };
6574
6575 let hit_condition_breakpoint_msg = if breakpoint
6576 .as_ref()
6577 .is_some_and(|bp| bp.1.hit_condition.is_some())
6578 {
6579 "Edit Hit Condition Breakpoint"
6580 } else {
6581 "Set Hit Condition Breakpoint"
6582 };
6583
6584 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6585 "Unset Breakpoint"
6586 } else {
6587 "Set Breakpoint"
6588 };
6589
6590 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6591 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6592
6593 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6594 BreakpointState::Enabled => Some("Disable"),
6595 BreakpointState::Disabled => Some("Enable"),
6596 });
6597
6598 let (anchor, breakpoint) =
6599 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6600
6601 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6602 menu.on_blur_subscription(Subscription::new(|| {}))
6603 .context(focus_handle)
6604 .when(run_to_cursor, |this| {
6605 let weak_editor = weak_editor.clone();
6606 this.entry("Run to cursor", None, move |window, cx| {
6607 weak_editor
6608 .update(cx, |editor, cx| {
6609 editor.change_selections(None, window, cx, |s| {
6610 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6611 });
6612 })
6613 .ok();
6614
6615 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6616 })
6617 .separator()
6618 })
6619 .when_some(toggle_state_msg, |this, msg| {
6620 this.entry(msg, None, {
6621 let weak_editor = weak_editor.clone();
6622 let breakpoint = breakpoint.clone();
6623 move |_window, cx| {
6624 weak_editor
6625 .update(cx, |this, cx| {
6626 this.edit_breakpoint_at_anchor(
6627 anchor,
6628 breakpoint.as_ref().clone(),
6629 BreakpointEditAction::InvertState,
6630 cx,
6631 );
6632 })
6633 .log_err();
6634 }
6635 })
6636 })
6637 .entry(set_breakpoint_msg, None, {
6638 let weak_editor = weak_editor.clone();
6639 let breakpoint = breakpoint.clone();
6640 move |_window, cx| {
6641 weak_editor
6642 .update(cx, |this, cx| {
6643 this.edit_breakpoint_at_anchor(
6644 anchor,
6645 breakpoint.as_ref().clone(),
6646 BreakpointEditAction::Toggle,
6647 cx,
6648 );
6649 })
6650 .log_err();
6651 }
6652 })
6653 .entry(log_breakpoint_msg, None, {
6654 let breakpoint = breakpoint.clone();
6655 let weak_editor = weak_editor.clone();
6656 move |window, cx| {
6657 weak_editor
6658 .update(cx, |this, cx| {
6659 this.add_edit_breakpoint_block(
6660 anchor,
6661 breakpoint.as_ref(),
6662 BreakpointPromptEditAction::Log,
6663 window,
6664 cx,
6665 );
6666 })
6667 .log_err();
6668 }
6669 })
6670 .entry(condition_breakpoint_msg, None, {
6671 let breakpoint = breakpoint.clone();
6672 let weak_editor = weak_editor.clone();
6673 move |window, cx| {
6674 weak_editor
6675 .update(cx, |this, cx| {
6676 this.add_edit_breakpoint_block(
6677 anchor,
6678 breakpoint.as_ref(),
6679 BreakpointPromptEditAction::Condition,
6680 window,
6681 cx,
6682 );
6683 })
6684 .log_err();
6685 }
6686 })
6687 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6688 weak_editor
6689 .update(cx, |this, cx| {
6690 this.add_edit_breakpoint_block(
6691 anchor,
6692 breakpoint.as_ref(),
6693 BreakpointPromptEditAction::HitCondition,
6694 window,
6695 cx,
6696 );
6697 })
6698 .log_err();
6699 })
6700 })
6701 }
6702
6703 fn render_breakpoint(
6704 &self,
6705 position: Anchor,
6706 row: DisplayRow,
6707 breakpoint: &Breakpoint,
6708 cx: &mut Context<Self>,
6709 ) -> IconButton {
6710 let (color, icon) = {
6711 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6712 (false, false) => ui::IconName::DebugBreakpoint,
6713 (true, false) => ui::IconName::DebugLogBreakpoint,
6714 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6715 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6716 };
6717
6718 let color = if self
6719 .gutter_breakpoint_indicator
6720 .0
6721 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6722 {
6723 Color::Hint
6724 } else {
6725 Color::Debugger
6726 };
6727
6728 (color, icon)
6729 };
6730
6731 let breakpoint = Arc::from(breakpoint.clone());
6732
6733 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6734 .icon_size(IconSize::XSmall)
6735 .size(ui::ButtonSize::None)
6736 .icon_color(color)
6737 .style(ButtonStyle::Transparent)
6738 .on_click(cx.listener({
6739 let breakpoint = breakpoint.clone();
6740
6741 move |editor, event: &ClickEvent, window, cx| {
6742 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6743 BreakpointEditAction::InvertState
6744 } else {
6745 BreakpointEditAction::Toggle
6746 };
6747
6748 window.focus(&editor.focus_handle(cx));
6749 editor.edit_breakpoint_at_anchor(
6750 position,
6751 breakpoint.as_ref().clone(),
6752 edit_action,
6753 cx,
6754 );
6755 }
6756 }))
6757 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6758 editor.set_breakpoint_context_menu(
6759 row,
6760 Some(position),
6761 event.down.position,
6762 window,
6763 cx,
6764 );
6765 }))
6766 }
6767
6768 fn build_tasks_context(
6769 project: &Entity<Project>,
6770 buffer: &Entity<Buffer>,
6771 buffer_row: u32,
6772 tasks: &Arc<RunnableTasks>,
6773 cx: &mut Context<Self>,
6774 ) -> Task<Option<task::TaskContext>> {
6775 let position = Point::new(buffer_row, tasks.column);
6776 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6777 let location = Location {
6778 buffer: buffer.clone(),
6779 range: range_start..range_start,
6780 };
6781 // Fill in the environmental variables from the tree-sitter captures
6782 let mut captured_task_variables = TaskVariables::default();
6783 for (capture_name, value) in tasks.extra_variables.clone() {
6784 captured_task_variables.insert(
6785 task::VariableName::Custom(capture_name.into()),
6786 value.clone(),
6787 );
6788 }
6789 project.update(cx, |project, cx| {
6790 project.task_store().update(cx, |task_store, cx| {
6791 task_store.task_context_for_location(captured_task_variables, location, cx)
6792 })
6793 })
6794 }
6795
6796 pub fn spawn_nearest_task(
6797 &mut self,
6798 action: &SpawnNearestTask,
6799 window: &mut Window,
6800 cx: &mut Context<Self>,
6801 ) {
6802 let Some((workspace, _)) = self.workspace.clone() else {
6803 return;
6804 };
6805 let Some(project) = self.project.clone() else {
6806 return;
6807 };
6808
6809 // Try to find a closest, enclosing node using tree-sitter that has a
6810 // task
6811 let Some((buffer, buffer_row, tasks)) = self
6812 .find_enclosing_node_task(cx)
6813 // Or find the task that's closest in row-distance.
6814 .or_else(|| self.find_closest_task(cx))
6815 else {
6816 return;
6817 };
6818
6819 let reveal_strategy = action.reveal;
6820 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6821 cx.spawn_in(window, async move |_, cx| {
6822 let context = task_context.await?;
6823 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6824
6825 let resolved = resolved_task.resolved.as_mut()?;
6826 resolved.reveal = reveal_strategy;
6827
6828 workspace
6829 .update(cx, |workspace, cx| {
6830 workspace::tasks::schedule_resolved_task(
6831 workspace,
6832 task_source_kind,
6833 resolved_task,
6834 false,
6835 cx,
6836 );
6837 })
6838 .ok()
6839 })
6840 .detach();
6841 }
6842
6843 fn find_closest_task(
6844 &mut self,
6845 cx: &mut Context<Self>,
6846 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6847 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6848
6849 let ((buffer_id, row), tasks) = self
6850 .tasks
6851 .iter()
6852 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6853
6854 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6855 let tasks = Arc::new(tasks.to_owned());
6856 Some((buffer, *row, tasks))
6857 }
6858
6859 fn find_enclosing_node_task(
6860 &mut self,
6861 cx: &mut Context<Self>,
6862 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6863 let snapshot = self.buffer.read(cx).snapshot(cx);
6864 let offset = self.selections.newest::<usize>(cx).head();
6865 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6866 let buffer_id = excerpt.buffer().remote_id();
6867
6868 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6869 let mut cursor = layer.node().walk();
6870
6871 while cursor.goto_first_child_for_byte(offset).is_some() {
6872 if cursor.node().end_byte() == offset {
6873 cursor.goto_next_sibling();
6874 }
6875 }
6876
6877 // Ascend to the smallest ancestor that contains the range and has a task.
6878 loop {
6879 let node = cursor.node();
6880 let node_range = node.byte_range();
6881 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6882
6883 // Check if this node contains our offset
6884 if node_range.start <= offset && node_range.end >= offset {
6885 // If it contains offset, check for task
6886 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6887 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6888 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6889 }
6890 }
6891
6892 if !cursor.goto_parent() {
6893 break;
6894 }
6895 }
6896 None
6897 }
6898
6899 fn render_run_indicator(
6900 &self,
6901 _style: &EditorStyle,
6902 is_active: bool,
6903 row: DisplayRow,
6904 breakpoint: Option<(Anchor, Breakpoint)>,
6905 cx: &mut Context<Self>,
6906 ) -> IconButton {
6907 let color = Color::Muted;
6908 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6909
6910 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6911 .shape(ui::IconButtonShape::Square)
6912 .icon_size(IconSize::XSmall)
6913 .icon_color(color)
6914 .toggle_state(is_active)
6915 .on_click(cx.listener(move |editor, _e, window, cx| {
6916 window.focus(&editor.focus_handle(cx));
6917 editor.toggle_code_actions(
6918 &ToggleCodeActions {
6919 deployed_from_indicator: Some(row),
6920 },
6921 window,
6922 cx,
6923 );
6924 }))
6925 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6926 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6927 }))
6928 }
6929
6930 pub fn context_menu_visible(&self) -> bool {
6931 !self.edit_prediction_preview_is_active()
6932 && self
6933 .context_menu
6934 .borrow()
6935 .as_ref()
6936 .map_or(false, |menu| menu.visible())
6937 }
6938
6939 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6940 self.context_menu
6941 .borrow()
6942 .as_ref()
6943 .map(|menu| menu.origin())
6944 }
6945
6946 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6947 self.context_menu_options = Some(options);
6948 }
6949
6950 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6951 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6952
6953 fn render_edit_prediction_popover(
6954 &mut self,
6955 text_bounds: &Bounds<Pixels>,
6956 content_origin: gpui::Point<Pixels>,
6957 editor_snapshot: &EditorSnapshot,
6958 visible_row_range: Range<DisplayRow>,
6959 scroll_top: f32,
6960 scroll_bottom: f32,
6961 line_layouts: &[LineWithInvisibles],
6962 line_height: Pixels,
6963 scroll_pixel_position: gpui::Point<Pixels>,
6964 newest_selection_head: Option<DisplayPoint>,
6965 editor_width: Pixels,
6966 style: &EditorStyle,
6967 window: &mut Window,
6968 cx: &mut App,
6969 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6970 let active_inline_completion = self.active_inline_completion.as_ref()?;
6971
6972 if self.edit_prediction_visible_in_cursor_popover(true) {
6973 return None;
6974 }
6975
6976 match &active_inline_completion.completion {
6977 InlineCompletion::Move { target, .. } => {
6978 let target_display_point = target.to_display_point(editor_snapshot);
6979
6980 if self.edit_prediction_requires_modifier() {
6981 if !self.edit_prediction_preview_is_active() {
6982 return None;
6983 }
6984
6985 self.render_edit_prediction_modifier_jump_popover(
6986 text_bounds,
6987 content_origin,
6988 visible_row_range,
6989 line_layouts,
6990 line_height,
6991 scroll_pixel_position,
6992 newest_selection_head,
6993 target_display_point,
6994 window,
6995 cx,
6996 )
6997 } else {
6998 self.render_edit_prediction_eager_jump_popover(
6999 text_bounds,
7000 content_origin,
7001 editor_snapshot,
7002 visible_row_range,
7003 scroll_top,
7004 scroll_bottom,
7005 line_height,
7006 scroll_pixel_position,
7007 target_display_point,
7008 editor_width,
7009 window,
7010 cx,
7011 )
7012 }
7013 }
7014 InlineCompletion::Edit {
7015 display_mode: EditDisplayMode::Inline,
7016 ..
7017 } => None,
7018 InlineCompletion::Edit {
7019 display_mode: EditDisplayMode::TabAccept,
7020 edits,
7021 ..
7022 } => {
7023 let range = &edits.first()?.0;
7024 let target_display_point = range.end.to_display_point(editor_snapshot);
7025
7026 self.render_edit_prediction_end_of_line_popover(
7027 "Accept",
7028 editor_snapshot,
7029 visible_row_range,
7030 target_display_point,
7031 line_height,
7032 scroll_pixel_position,
7033 content_origin,
7034 editor_width,
7035 window,
7036 cx,
7037 )
7038 }
7039 InlineCompletion::Edit {
7040 edits,
7041 edit_preview,
7042 display_mode: EditDisplayMode::DiffPopover,
7043 snapshot,
7044 } => self.render_edit_prediction_diff_popover(
7045 text_bounds,
7046 content_origin,
7047 editor_snapshot,
7048 visible_row_range,
7049 line_layouts,
7050 line_height,
7051 scroll_pixel_position,
7052 newest_selection_head,
7053 editor_width,
7054 style,
7055 edits,
7056 edit_preview,
7057 snapshot,
7058 window,
7059 cx,
7060 ),
7061 }
7062 }
7063
7064 fn render_edit_prediction_modifier_jump_popover(
7065 &mut self,
7066 text_bounds: &Bounds<Pixels>,
7067 content_origin: gpui::Point<Pixels>,
7068 visible_row_range: Range<DisplayRow>,
7069 line_layouts: &[LineWithInvisibles],
7070 line_height: Pixels,
7071 scroll_pixel_position: gpui::Point<Pixels>,
7072 newest_selection_head: Option<DisplayPoint>,
7073 target_display_point: DisplayPoint,
7074 window: &mut Window,
7075 cx: &mut App,
7076 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7077 let scrolled_content_origin =
7078 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7079
7080 const SCROLL_PADDING_Y: Pixels = px(12.);
7081
7082 if target_display_point.row() < visible_row_range.start {
7083 return self.render_edit_prediction_scroll_popover(
7084 |_| SCROLL_PADDING_Y,
7085 IconName::ArrowUp,
7086 visible_row_range,
7087 line_layouts,
7088 newest_selection_head,
7089 scrolled_content_origin,
7090 window,
7091 cx,
7092 );
7093 } else if target_display_point.row() >= visible_row_range.end {
7094 return self.render_edit_prediction_scroll_popover(
7095 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7096 IconName::ArrowDown,
7097 visible_row_range,
7098 line_layouts,
7099 newest_selection_head,
7100 scrolled_content_origin,
7101 window,
7102 cx,
7103 );
7104 }
7105
7106 const POLE_WIDTH: Pixels = px(2.);
7107
7108 let line_layout =
7109 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7110 let target_column = target_display_point.column() as usize;
7111
7112 let target_x = line_layout.x_for_index(target_column);
7113 let target_y =
7114 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7115
7116 let flag_on_right = target_x < text_bounds.size.width / 2.;
7117
7118 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7119 border_color.l += 0.001;
7120
7121 let mut element = v_flex()
7122 .items_end()
7123 .when(flag_on_right, |el| el.items_start())
7124 .child(if flag_on_right {
7125 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7126 .rounded_bl(px(0.))
7127 .rounded_tl(px(0.))
7128 .border_l_2()
7129 .border_color(border_color)
7130 } else {
7131 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7132 .rounded_br(px(0.))
7133 .rounded_tr(px(0.))
7134 .border_r_2()
7135 .border_color(border_color)
7136 })
7137 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7138 .into_any();
7139
7140 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7141
7142 let mut origin = scrolled_content_origin + point(target_x, target_y)
7143 - point(
7144 if flag_on_right {
7145 POLE_WIDTH
7146 } else {
7147 size.width - POLE_WIDTH
7148 },
7149 size.height - line_height,
7150 );
7151
7152 origin.x = origin.x.max(content_origin.x);
7153
7154 element.prepaint_at(origin, window, cx);
7155
7156 Some((element, origin))
7157 }
7158
7159 fn render_edit_prediction_scroll_popover(
7160 &mut self,
7161 to_y: impl Fn(Size<Pixels>) -> Pixels,
7162 scroll_icon: IconName,
7163 visible_row_range: Range<DisplayRow>,
7164 line_layouts: &[LineWithInvisibles],
7165 newest_selection_head: Option<DisplayPoint>,
7166 scrolled_content_origin: gpui::Point<Pixels>,
7167 window: &mut Window,
7168 cx: &mut App,
7169 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7170 let mut element = self
7171 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7172 .into_any();
7173
7174 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7175
7176 let cursor = newest_selection_head?;
7177 let cursor_row_layout =
7178 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7179 let cursor_column = cursor.column() as usize;
7180
7181 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7182
7183 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7184
7185 element.prepaint_at(origin, window, cx);
7186 Some((element, origin))
7187 }
7188
7189 fn render_edit_prediction_eager_jump_popover(
7190 &mut self,
7191 text_bounds: &Bounds<Pixels>,
7192 content_origin: gpui::Point<Pixels>,
7193 editor_snapshot: &EditorSnapshot,
7194 visible_row_range: Range<DisplayRow>,
7195 scroll_top: f32,
7196 scroll_bottom: f32,
7197 line_height: Pixels,
7198 scroll_pixel_position: gpui::Point<Pixels>,
7199 target_display_point: DisplayPoint,
7200 editor_width: Pixels,
7201 window: &mut Window,
7202 cx: &mut App,
7203 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7204 if target_display_point.row().as_f32() < scroll_top {
7205 let mut element = self
7206 .render_edit_prediction_line_popover(
7207 "Jump to Edit",
7208 Some(IconName::ArrowUp),
7209 window,
7210 cx,
7211 )?
7212 .into_any();
7213
7214 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7215 let offset = point(
7216 (text_bounds.size.width - size.width) / 2.,
7217 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7218 );
7219
7220 let origin = text_bounds.origin + offset;
7221 element.prepaint_at(origin, window, cx);
7222 Some((element, origin))
7223 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7224 let mut element = self
7225 .render_edit_prediction_line_popover(
7226 "Jump to Edit",
7227 Some(IconName::ArrowDown),
7228 window,
7229 cx,
7230 )?
7231 .into_any();
7232
7233 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7234 let offset = point(
7235 (text_bounds.size.width - size.width) / 2.,
7236 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7237 );
7238
7239 let origin = text_bounds.origin + offset;
7240 element.prepaint_at(origin, window, cx);
7241 Some((element, origin))
7242 } else {
7243 self.render_edit_prediction_end_of_line_popover(
7244 "Jump to Edit",
7245 editor_snapshot,
7246 visible_row_range,
7247 target_display_point,
7248 line_height,
7249 scroll_pixel_position,
7250 content_origin,
7251 editor_width,
7252 window,
7253 cx,
7254 )
7255 }
7256 }
7257
7258 fn render_edit_prediction_end_of_line_popover(
7259 self: &mut Editor,
7260 label: &'static str,
7261 editor_snapshot: &EditorSnapshot,
7262 visible_row_range: Range<DisplayRow>,
7263 target_display_point: DisplayPoint,
7264 line_height: Pixels,
7265 scroll_pixel_position: gpui::Point<Pixels>,
7266 content_origin: gpui::Point<Pixels>,
7267 editor_width: Pixels,
7268 window: &mut Window,
7269 cx: &mut App,
7270 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7271 let target_line_end = DisplayPoint::new(
7272 target_display_point.row(),
7273 editor_snapshot.line_len(target_display_point.row()),
7274 );
7275
7276 let mut element = self
7277 .render_edit_prediction_line_popover(label, None, window, cx)?
7278 .into_any();
7279
7280 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7281
7282 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7283
7284 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7285 let mut origin = start_point
7286 + line_origin
7287 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7288 origin.x = origin.x.max(content_origin.x);
7289
7290 let max_x = content_origin.x + editor_width - size.width;
7291
7292 if origin.x > max_x {
7293 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7294
7295 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7296 origin.y += offset;
7297 IconName::ArrowUp
7298 } else {
7299 origin.y -= offset;
7300 IconName::ArrowDown
7301 };
7302
7303 element = self
7304 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7305 .into_any();
7306
7307 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7308
7309 origin.x = content_origin.x + editor_width - size.width - px(2.);
7310 }
7311
7312 element.prepaint_at(origin, window, cx);
7313 Some((element, origin))
7314 }
7315
7316 fn render_edit_prediction_diff_popover(
7317 self: &Editor,
7318 text_bounds: &Bounds<Pixels>,
7319 content_origin: gpui::Point<Pixels>,
7320 editor_snapshot: &EditorSnapshot,
7321 visible_row_range: Range<DisplayRow>,
7322 line_layouts: &[LineWithInvisibles],
7323 line_height: Pixels,
7324 scroll_pixel_position: gpui::Point<Pixels>,
7325 newest_selection_head: Option<DisplayPoint>,
7326 editor_width: Pixels,
7327 style: &EditorStyle,
7328 edits: &Vec<(Range<Anchor>, String)>,
7329 edit_preview: &Option<language::EditPreview>,
7330 snapshot: &language::BufferSnapshot,
7331 window: &mut Window,
7332 cx: &mut App,
7333 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7334 let edit_start = edits
7335 .first()
7336 .unwrap()
7337 .0
7338 .start
7339 .to_display_point(editor_snapshot);
7340 let edit_end = edits
7341 .last()
7342 .unwrap()
7343 .0
7344 .end
7345 .to_display_point(editor_snapshot);
7346
7347 let is_visible = visible_row_range.contains(&edit_start.row())
7348 || visible_row_range.contains(&edit_end.row());
7349 if !is_visible {
7350 return None;
7351 }
7352
7353 let highlighted_edits =
7354 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7355
7356 let styled_text = highlighted_edits.to_styled_text(&style.text);
7357 let line_count = highlighted_edits.text.lines().count();
7358
7359 const BORDER_WIDTH: Pixels = px(1.);
7360
7361 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7362 let has_keybind = keybind.is_some();
7363
7364 let mut element = h_flex()
7365 .items_start()
7366 .child(
7367 h_flex()
7368 .bg(cx.theme().colors().editor_background)
7369 .border(BORDER_WIDTH)
7370 .shadow_sm()
7371 .border_color(cx.theme().colors().border)
7372 .rounded_l_lg()
7373 .when(line_count > 1, |el| el.rounded_br_lg())
7374 .pr_1()
7375 .child(styled_text),
7376 )
7377 .child(
7378 h_flex()
7379 .h(line_height + BORDER_WIDTH * 2.)
7380 .px_1p5()
7381 .gap_1()
7382 // Workaround: For some reason, there's a gap if we don't do this
7383 .ml(-BORDER_WIDTH)
7384 .shadow(smallvec![gpui::BoxShadow {
7385 color: gpui::black().opacity(0.05),
7386 offset: point(px(1.), px(1.)),
7387 blur_radius: px(2.),
7388 spread_radius: px(0.),
7389 }])
7390 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7391 .border(BORDER_WIDTH)
7392 .border_color(cx.theme().colors().border)
7393 .rounded_r_lg()
7394 .id("edit_prediction_diff_popover_keybind")
7395 .when(!has_keybind, |el| {
7396 let status_colors = cx.theme().status();
7397
7398 el.bg(status_colors.error_background)
7399 .border_color(status_colors.error.opacity(0.6))
7400 .child(Icon::new(IconName::Info).color(Color::Error))
7401 .cursor_default()
7402 .hoverable_tooltip(move |_window, cx| {
7403 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7404 })
7405 })
7406 .children(keybind),
7407 )
7408 .into_any();
7409
7410 let longest_row =
7411 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7412 let longest_line_width = if visible_row_range.contains(&longest_row) {
7413 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7414 } else {
7415 layout_line(
7416 longest_row,
7417 editor_snapshot,
7418 style,
7419 editor_width,
7420 |_| false,
7421 window,
7422 cx,
7423 )
7424 .width
7425 };
7426
7427 let viewport_bounds =
7428 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7429 right: -EditorElement::SCROLLBAR_WIDTH,
7430 ..Default::default()
7431 });
7432
7433 let x_after_longest =
7434 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7435 - scroll_pixel_position.x;
7436
7437 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7438
7439 // Fully visible if it can be displayed within the window (allow overlapping other
7440 // panes). However, this is only allowed if the popover starts within text_bounds.
7441 let can_position_to_the_right = x_after_longest < text_bounds.right()
7442 && x_after_longest + element_bounds.width < viewport_bounds.right();
7443
7444 let mut origin = if can_position_to_the_right {
7445 point(
7446 x_after_longest,
7447 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7448 - scroll_pixel_position.y,
7449 )
7450 } else {
7451 let cursor_row = newest_selection_head.map(|head| head.row());
7452 let above_edit = edit_start
7453 .row()
7454 .0
7455 .checked_sub(line_count as u32)
7456 .map(DisplayRow);
7457 let below_edit = Some(edit_end.row() + 1);
7458 let above_cursor =
7459 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7460 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7461
7462 // Place the edit popover adjacent to the edit if there is a location
7463 // available that is onscreen and does not obscure the cursor. Otherwise,
7464 // place it adjacent to the cursor.
7465 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7466 .into_iter()
7467 .flatten()
7468 .find(|&start_row| {
7469 let end_row = start_row + line_count as u32;
7470 visible_row_range.contains(&start_row)
7471 && visible_row_range.contains(&end_row)
7472 && cursor_row.map_or(true, |cursor_row| {
7473 !((start_row..end_row).contains(&cursor_row))
7474 })
7475 })?;
7476
7477 content_origin
7478 + point(
7479 -scroll_pixel_position.x,
7480 row_target.as_f32() * line_height - scroll_pixel_position.y,
7481 )
7482 };
7483
7484 origin.x -= BORDER_WIDTH;
7485
7486 window.defer_draw(element, origin, 1);
7487
7488 // Do not return an element, since it will already be drawn due to defer_draw.
7489 None
7490 }
7491
7492 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7493 px(30.)
7494 }
7495
7496 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7497 if self.read_only(cx) {
7498 cx.theme().players().read_only()
7499 } else {
7500 self.style.as_ref().unwrap().local_player
7501 }
7502 }
7503
7504 fn render_edit_prediction_accept_keybind(
7505 &self,
7506 window: &mut Window,
7507 cx: &App,
7508 ) -> Option<AnyElement> {
7509 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7510 let accept_keystroke = accept_binding.keystroke()?;
7511
7512 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7513
7514 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7515 Color::Accent
7516 } else {
7517 Color::Muted
7518 };
7519
7520 h_flex()
7521 .px_0p5()
7522 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7523 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7524 .text_size(TextSize::XSmall.rems(cx))
7525 .child(h_flex().children(ui::render_modifiers(
7526 &accept_keystroke.modifiers,
7527 PlatformStyle::platform(),
7528 Some(modifiers_color),
7529 Some(IconSize::XSmall.rems().into()),
7530 true,
7531 )))
7532 .when(is_platform_style_mac, |parent| {
7533 parent.child(accept_keystroke.key.clone())
7534 })
7535 .when(!is_platform_style_mac, |parent| {
7536 parent.child(
7537 Key::new(
7538 util::capitalize(&accept_keystroke.key),
7539 Some(Color::Default),
7540 )
7541 .size(Some(IconSize::XSmall.rems().into())),
7542 )
7543 })
7544 .into_any()
7545 .into()
7546 }
7547
7548 fn render_edit_prediction_line_popover(
7549 &self,
7550 label: impl Into<SharedString>,
7551 icon: Option<IconName>,
7552 window: &mut Window,
7553 cx: &App,
7554 ) -> Option<Stateful<Div>> {
7555 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7556
7557 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7558 let has_keybind = keybind.is_some();
7559
7560 let result = h_flex()
7561 .id("ep-line-popover")
7562 .py_0p5()
7563 .pl_1()
7564 .pr(padding_right)
7565 .gap_1()
7566 .rounded_md()
7567 .border_1()
7568 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7569 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7570 .shadow_sm()
7571 .when(!has_keybind, |el| {
7572 let status_colors = cx.theme().status();
7573
7574 el.bg(status_colors.error_background)
7575 .border_color(status_colors.error.opacity(0.6))
7576 .pl_2()
7577 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7578 .cursor_default()
7579 .hoverable_tooltip(move |_window, cx| {
7580 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7581 })
7582 })
7583 .children(keybind)
7584 .child(
7585 Label::new(label)
7586 .size(LabelSize::Small)
7587 .when(!has_keybind, |el| {
7588 el.color(cx.theme().status().error.into()).strikethrough()
7589 }),
7590 )
7591 .when(!has_keybind, |el| {
7592 el.child(
7593 h_flex().ml_1().child(
7594 Icon::new(IconName::Info)
7595 .size(IconSize::Small)
7596 .color(cx.theme().status().error.into()),
7597 ),
7598 )
7599 })
7600 .when_some(icon, |element, icon| {
7601 element.child(
7602 div()
7603 .mt(px(1.5))
7604 .child(Icon::new(icon).size(IconSize::Small)),
7605 )
7606 });
7607
7608 Some(result)
7609 }
7610
7611 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7612 let accent_color = cx.theme().colors().text_accent;
7613 let editor_bg_color = cx.theme().colors().editor_background;
7614 editor_bg_color.blend(accent_color.opacity(0.1))
7615 }
7616
7617 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7618 let accent_color = cx.theme().colors().text_accent;
7619 let editor_bg_color = cx.theme().colors().editor_background;
7620 editor_bg_color.blend(accent_color.opacity(0.6))
7621 }
7622
7623 fn render_edit_prediction_cursor_popover(
7624 &self,
7625 min_width: Pixels,
7626 max_width: Pixels,
7627 cursor_point: Point,
7628 style: &EditorStyle,
7629 accept_keystroke: Option<&gpui::Keystroke>,
7630 _window: &Window,
7631 cx: &mut Context<Editor>,
7632 ) -> Option<AnyElement> {
7633 let provider = self.edit_prediction_provider.as_ref()?;
7634
7635 if provider.provider.needs_terms_acceptance(cx) {
7636 return Some(
7637 h_flex()
7638 .min_w(min_width)
7639 .flex_1()
7640 .px_2()
7641 .py_1()
7642 .gap_3()
7643 .elevation_2(cx)
7644 .hover(|style| style.bg(cx.theme().colors().element_hover))
7645 .id("accept-terms")
7646 .cursor_pointer()
7647 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7648 .on_click(cx.listener(|this, _event, window, cx| {
7649 cx.stop_propagation();
7650 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7651 window.dispatch_action(
7652 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7653 cx,
7654 );
7655 }))
7656 .child(
7657 h_flex()
7658 .flex_1()
7659 .gap_2()
7660 .child(Icon::new(IconName::ZedPredict))
7661 .child(Label::new("Accept Terms of Service"))
7662 .child(div().w_full())
7663 .child(
7664 Icon::new(IconName::ArrowUpRight)
7665 .color(Color::Muted)
7666 .size(IconSize::Small),
7667 )
7668 .into_any_element(),
7669 )
7670 .into_any(),
7671 );
7672 }
7673
7674 let is_refreshing = provider.provider.is_refreshing(cx);
7675
7676 fn pending_completion_container() -> Div {
7677 h_flex()
7678 .h_full()
7679 .flex_1()
7680 .gap_2()
7681 .child(Icon::new(IconName::ZedPredict))
7682 }
7683
7684 let completion = match &self.active_inline_completion {
7685 Some(prediction) => {
7686 if !self.has_visible_completions_menu() {
7687 const RADIUS: Pixels = px(6.);
7688 const BORDER_WIDTH: Pixels = px(1.);
7689
7690 return Some(
7691 h_flex()
7692 .elevation_2(cx)
7693 .border(BORDER_WIDTH)
7694 .border_color(cx.theme().colors().border)
7695 .when(accept_keystroke.is_none(), |el| {
7696 el.border_color(cx.theme().status().error)
7697 })
7698 .rounded(RADIUS)
7699 .rounded_tl(px(0.))
7700 .overflow_hidden()
7701 .child(div().px_1p5().child(match &prediction.completion {
7702 InlineCompletion::Move { target, snapshot } => {
7703 use text::ToPoint as _;
7704 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7705 {
7706 Icon::new(IconName::ZedPredictDown)
7707 } else {
7708 Icon::new(IconName::ZedPredictUp)
7709 }
7710 }
7711 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7712 }))
7713 .child(
7714 h_flex()
7715 .gap_1()
7716 .py_1()
7717 .px_2()
7718 .rounded_r(RADIUS - BORDER_WIDTH)
7719 .border_l_1()
7720 .border_color(cx.theme().colors().border)
7721 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7722 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7723 el.child(
7724 Label::new("Hold")
7725 .size(LabelSize::Small)
7726 .when(accept_keystroke.is_none(), |el| {
7727 el.strikethrough()
7728 })
7729 .line_height_style(LineHeightStyle::UiLabel),
7730 )
7731 })
7732 .id("edit_prediction_cursor_popover_keybind")
7733 .when(accept_keystroke.is_none(), |el| {
7734 let status_colors = cx.theme().status();
7735
7736 el.bg(status_colors.error_background)
7737 .border_color(status_colors.error.opacity(0.6))
7738 .child(Icon::new(IconName::Info).color(Color::Error))
7739 .cursor_default()
7740 .hoverable_tooltip(move |_window, cx| {
7741 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7742 .into()
7743 })
7744 })
7745 .when_some(
7746 accept_keystroke.as_ref(),
7747 |el, accept_keystroke| {
7748 el.child(h_flex().children(ui::render_modifiers(
7749 &accept_keystroke.modifiers,
7750 PlatformStyle::platform(),
7751 Some(Color::Default),
7752 Some(IconSize::XSmall.rems().into()),
7753 false,
7754 )))
7755 },
7756 ),
7757 )
7758 .into_any(),
7759 );
7760 }
7761
7762 self.render_edit_prediction_cursor_popover_preview(
7763 prediction,
7764 cursor_point,
7765 style,
7766 cx,
7767 )?
7768 }
7769
7770 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7771 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7772 stale_completion,
7773 cursor_point,
7774 style,
7775 cx,
7776 )?,
7777
7778 None => {
7779 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7780 }
7781 },
7782
7783 None => pending_completion_container().child(Label::new("No Prediction")),
7784 };
7785
7786 let completion = if is_refreshing {
7787 completion
7788 .with_animation(
7789 "loading-completion",
7790 Animation::new(Duration::from_secs(2))
7791 .repeat()
7792 .with_easing(pulsating_between(0.4, 0.8)),
7793 |label, delta| label.opacity(delta),
7794 )
7795 .into_any_element()
7796 } else {
7797 completion.into_any_element()
7798 };
7799
7800 let has_completion = self.active_inline_completion.is_some();
7801
7802 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7803 Some(
7804 h_flex()
7805 .min_w(min_width)
7806 .max_w(max_width)
7807 .flex_1()
7808 .elevation_2(cx)
7809 .border_color(cx.theme().colors().border)
7810 .child(
7811 div()
7812 .flex_1()
7813 .py_1()
7814 .px_2()
7815 .overflow_hidden()
7816 .child(completion),
7817 )
7818 .when_some(accept_keystroke, |el, accept_keystroke| {
7819 if !accept_keystroke.modifiers.modified() {
7820 return el;
7821 }
7822
7823 el.child(
7824 h_flex()
7825 .h_full()
7826 .border_l_1()
7827 .rounded_r_lg()
7828 .border_color(cx.theme().colors().border)
7829 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7830 .gap_1()
7831 .py_1()
7832 .px_2()
7833 .child(
7834 h_flex()
7835 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7836 .when(is_platform_style_mac, |parent| parent.gap_1())
7837 .child(h_flex().children(ui::render_modifiers(
7838 &accept_keystroke.modifiers,
7839 PlatformStyle::platform(),
7840 Some(if !has_completion {
7841 Color::Muted
7842 } else {
7843 Color::Default
7844 }),
7845 None,
7846 false,
7847 ))),
7848 )
7849 .child(Label::new("Preview").into_any_element())
7850 .opacity(if has_completion { 1.0 } else { 0.4 }),
7851 )
7852 })
7853 .into_any(),
7854 )
7855 }
7856
7857 fn render_edit_prediction_cursor_popover_preview(
7858 &self,
7859 completion: &InlineCompletionState,
7860 cursor_point: Point,
7861 style: &EditorStyle,
7862 cx: &mut Context<Editor>,
7863 ) -> Option<Div> {
7864 use text::ToPoint as _;
7865
7866 fn render_relative_row_jump(
7867 prefix: impl Into<String>,
7868 current_row: u32,
7869 target_row: u32,
7870 ) -> Div {
7871 let (row_diff, arrow) = if target_row < current_row {
7872 (current_row - target_row, IconName::ArrowUp)
7873 } else {
7874 (target_row - current_row, IconName::ArrowDown)
7875 };
7876
7877 h_flex()
7878 .child(
7879 Label::new(format!("{}{}", prefix.into(), row_diff))
7880 .color(Color::Muted)
7881 .size(LabelSize::Small),
7882 )
7883 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7884 }
7885
7886 match &completion.completion {
7887 InlineCompletion::Move {
7888 target, snapshot, ..
7889 } => Some(
7890 h_flex()
7891 .px_2()
7892 .gap_2()
7893 .flex_1()
7894 .child(
7895 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7896 Icon::new(IconName::ZedPredictDown)
7897 } else {
7898 Icon::new(IconName::ZedPredictUp)
7899 },
7900 )
7901 .child(Label::new("Jump to Edit")),
7902 ),
7903
7904 InlineCompletion::Edit {
7905 edits,
7906 edit_preview,
7907 snapshot,
7908 display_mode: _,
7909 } => {
7910 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7911
7912 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7913 &snapshot,
7914 &edits,
7915 edit_preview.as_ref()?,
7916 true,
7917 cx,
7918 )
7919 .first_line_preview();
7920
7921 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7922 .with_default_highlights(&style.text, highlighted_edits.highlights);
7923
7924 let preview = h_flex()
7925 .gap_1()
7926 .min_w_16()
7927 .child(styled_text)
7928 .when(has_more_lines, |parent| parent.child("…"));
7929
7930 let left = if first_edit_row != cursor_point.row {
7931 render_relative_row_jump("", cursor_point.row, first_edit_row)
7932 .into_any_element()
7933 } else {
7934 Icon::new(IconName::ZedPredict).into_any_element()
7935 };
7936
7937 Some(
7938 h_flex()
7939 .h_full()
7940 .flex_1()
7941 .gap_2()
7942 .pr_1()
7943 .overflow_x_hidden()
7944 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7945 .child(left)
7946 .child(preview),
7947 )
7948 }
7949 }
7950 }
7951
7952 fn render_context_menu(
7953 &self,
7954 style: &EditorStyle,
7955 max_height_in_lines: u32,
7956 window: &mut Window,
7957 cx: &mut Context<Editor>,
7958 ) -> Option<AnyElement> {
7959 let menu = self.context_menu.borrow();
7960 let menu = menu.as_ref()?;
7961 if !menu.visible() {
7962 return None;
7963 };
7964 Some(menu.render(style, max_height_in_lines, window, cx))
7965 }
7966
7967 fn render_context_menu_aside(
7968 &mut self,
7969 max_size: Size<Pixels>,
7970 window: &mut Window,
7971 cx: &mut Context<Editor>,
7972 ) -> Option<AnyElement> {
7973 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7974 if menu.visible() {
7975 menu.render_aside(self, max_size, window, cx)
7976 } else {
7977 None
7978 }
7979 })
7980 }
7981
7982 fn hide_context_menu(
7983 &mut self,
7984 window: &mut Window,
7985 cx: &mut Context<Self>,
7986 ) -> Option<CodeContextMenu> {
7987 cx.notify();
7988 self.completion_tasks.clear();
7989 let context_menu = self.context_menu.borrow_mut().take();
7990 self.stale_inline_completion_in_menu.take();
7991 self.update_visible_inline_completion(window, cx);
7992 context_menu
7993 }
7994
7995 fn show_snippet_choices(
7996 &mut self,
7997 choices: &Vec<String>,
7998 selection: Range<Anchor>,
7999 cx: &mut Context<Self>,
8000 ) {
8001 if selection.start.buffer_id.is_none() {
8002 return;
8003 }
8004 let buffer_id = selection.start.buffer_id.unwrap();
8005 let buffer = self.buffer().read(cx).buffer(buffer_id);
8006 let id = post_inc(&mut self.next_completion_id);
8007
8008 if let Some(buffer) = buffer {
8009 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8010 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
8011 ));
8012 }
8013 }
8014
8015 pub fn insert_snippet(
8016 &mut self,
8017 insertion_ranges: &[Range<usize>],
8018 snippet: Snippet,
8019 window: &mut Window,
8020 cx: &mut Context<Self>,
8021 ) -> Result<()> {
8022 struct Tabstop<T> {
8023 is_end_tabstop: bool,
8024 ranges: Vec<Range<T>>,
8025 choices: Option<Vec<String>>,
8026 }
8027
8028 let tabstops = self.buffer.update(cx, |buffer, cx| {
8029 let snippet_text: Arc<str> = snippet.text.clone().into();
8030 let edits = insertion_ranges
8031 .iter()
8032 .cloned()
8033 .map(|range| (range, snippet_text.clone()));
8034 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8035
8036 let snapshot = &*buffer.read(cx);
8037 let snippet = &snippet;
8038 snippet
8039 .tabstops
8040 .iter()
8041 .map(|tabstop| {
8042 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8043 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8044 });
8045 let mut tabstop_ranges = tabstop
8046 .ranges
8047 .iter()
8048 .flat_map(|tabstop_range| {
8049 let mut delta = 0_isize;
8050 insertion_ranges.iter().map(move |insertion_range| {
8051 let insertion_start = insertion_range.start as isize + delta;
8052 delta +=
8053 snippet.text.len() as isize - insertion_range.len() as isize;
8054
8055 let start = ((insertion_start + tabstop_range.start) as usize)
8056 .min(snapshot.len());
8057 let end = ((insertion_start + tabstop_range.end) as usize)
8058 .min(snapshot.len());
8059 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8060 })
8061 })
8062 .collect::<Vec<_>>();
8063 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8064
8065 Tabstop {
8066 is_end_tabstop,
8067 ranges: tabstop_ranges,
8068 choices: tabstop.choices.clone(),
8069 }
8070 })
8071 .collect::<Vec<_>>()
8072 });
8073 if let Some(tabstop) = tabstops.first() {
8074 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8075 s.select_ranges(tabstop.ranges.iter().cloned());
8076 });
8077
8078 if let Some(choices) = &tabstop.choices {
8079 if let Some(selection) = tabstop.ranges.first() {
8080 self.show_snippet_choices(choices, selection.clone(), cx)
8081 }
8082 }
8083
8084 // If we're already at the last tabstop and it's at the end of the snippet,
8085 // we're done, we don't need to keep the state around.
8086 if !tabstop.is_end_tabstop {
8087 let choices = tabstops
8088 .iter()
8089 .map(|tabstop| tabstop.choices.clone())
8090 .collect();
8091
8092 let ranges = tabstops
8093 .into_iter()
8094 .map(|tabstop| tabstop.ranges)
8095 .collect::<Vec<_>>();
8096
8097 self.snippet_stack.push(SnippetState {
8098 active_index: 0,
8099 ranges,
8100 choices,
8101 });
8102 }
8103
8104 // Check whether the just-entered snippet ends with an auto-closable bracket.
8105 if self.autoclose_regions.is_empty() {
8106 let snapshot = self.buffer.read(cx).snapshot(cx);
8107 for selection in &mut self.selections.all::<Point>(cx) {
8108 let selection_head = selection.head();
8109 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8110 continue;
8111 };
8112
8113 let mut bracket_pair = None;
8114 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8115 let prev_chars = snapshot
8116 .reversed_chars_at(selection_head)
8117 .collect::<String>();
8118 for (pair, enabled) in scope.brackets() {
8119 if enabled
8120 && pair.close
8121 && prev_chars.starts_with(pair.start.as_str())
8122 && next_chars.starts_with(pair.end.as_str())
8123 {
8124 bracket_pair = Some(pair.clone());
8125 break;
8126 }
8127 }
8128 if let Some(pair) = bracket_pair {
8129 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8130 let autoclose_enabled =
8131 self.use_autoclose && snapshot_settings.use_autoclose;
8132 if autoclose_enabled {
8133 let start = snapshot.anchor_after(selection_head);
8134 let end = snapshot.anchor_after(selection_head);
8135 self.autoclose_regions.push(AutocloseRegion {
8136 selection_id: selection.id,
8137 range: start..end,
8138 pair,
8139 });
8140 }
8141 }
8142 }
8143 }
8144 }
8145 Ok(())
8146 }
8147
8148 pub fn move_to_next_snippet_tabstop(
8149 &mut self,
8150 window: &mut Window,
8151 cx: &mut Context<Self>,
8152 ) -> bool {
8153 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8154 }
8155
8156 pub fn move_to_prev_snippet_tabstop(
8157 &mut self,
8158 window: &mut Window,
8159 cx: &mut Context<Self>,
8160 ) -> bool {
8161 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8162 }
8163
8164 pub fn move_to_snippet_tabstop(
8165 &mut self,
8166 bias: Bias,
8167 window: &mut Window,
8168 cx: &mut Context<Self>,
8169 ) -> bool {
8170 if let Some(mut snippet) = self.snippet_stack.pop() {
8171 match bias {
8172 Bias::Left => {
8173 if snippet.active_index > 0 {
8174 snippet.active_index -= 1;
8175 } else {
8176 self.snippet_stack.push(snippet);
8177 return false;
8178 }
8179 }
8180 Bias::Right => {
8181 if snippet.active_index + 1 < snippet.ranges.len() {
8182 snippet.active_index += 1;
8183 } else {
8184 self.snippet_stack.push(snippet);
8185 return false;
8186 }
8187 }
8188 }
8189 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8190 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8191 s.select_anchor_ranges(current_ranges.iter().cloned())
8192 });
8193
8194 if let Some(choices) = &snippet.choices[snippet.active_index] {
8195 if let Some(selection) = current_ranges.first() {
8196 self.show_snippet_choices(&choices, selection.clone(), cx);
8197 }
8198 }
8199
8200 // If snippet state is not at the last tabstop, push it back on the stack
8201 if snippet.active_index + 1 < snippet.ranges.len() {
8202 self.snippet_stack.push(snippet);
8203 }
8204 return true;
8205 }
8206 }
8207
8208 false
8209 }
8210
8211 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8212 self.transact(window, cx, |this, window, cx| {
8213 this.select_all(&SelectAll, window, cx);
8214 this.insert("", window, cx);
8215 });
8216 }
8217
8218 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8219 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8220 self.transact(window, cx, |this, window, cx| {
8221 this.select_autoclose_pair(window, cx);
8222 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8223 if !this.linked_edit_ranges.is_empty() {
8224 let selections = this.selections.all::<MultiBufferPoint>(cx);
8225 let snapshot = this.buffer.read(cx).snapshot(cx);
8226
8227 for selection in selections.iter() {
8228 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8229 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8230 if selection_start.buffer_id != selection_end.buffer_id {
8231 continue;
8232 }
8233 if let Some(ranges) =
8234 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8235 {
8236 for (buffer, entries) in ranges {
8237 linked_ranges.entry(buffer).or_default().extend(entries);
8238 }
8239 }
8240 }
8241 }
8242
8243 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8244 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8245 for selection in &mut selections {
8246 if selection.is_empty() {
8247 let old_head = selection.head();
8248 let mut new_head =
8249 movement::left(&display_map, old_head.to_display_point(&display_map))
8250 .to_point(&display_map);
8251 if let Some((buffer, line_buffer_range)) = display_map
8252 .buffer_snapshot
8253 .buffer_line_for_row(MultiBufferRow(old_head.row))
8254 {
8255 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8256 let indent_len = match indent_size.kind {
8257 IndentKind::Space => {
8258 buffer.settings_at(line_buffer_range.start, cx).tab_size
8259 }
8260 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8261 };
8262 if old_head.column <= indent_size.len && old_head.column > 0 {
8263 let indent_len = indent_len.get();
8264 new_head = cmp::min(
8265 new_head,
8266 MultiBufferPoint::new(
8267 old_head.row,
8268 ((old_head.column - 1) / indent_len) * indent_len,
8269 ),
8270 );
8271 }
8272 }
8273
8274 selection.set_head(new_head, SelectionGoal::None);
8275 }
8276 }
8277
8278 this.signature_help_state.set_backspace_pressed(true);
8279 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8280 s.select(selections)
8281 });
8282 this.insert("", window, cx);
8283 let empty_str: Arc<str> = Arc::from("");
8284 for (buffer, edits) in linked_ranges {
8285 let snapshot = buffer.read(cx).snapshot();
8286 use text::ToPoint as TP;
8287
8288 let edits = edits
8289 .into_iter()
8290 .map(|range| {
8291 let end_point = TP::to_point(&range.end, &snapshot);
8292 let mut start_point = TP::to_point(&range.start, &snapshot);
8293
8294 if end_point == start_point {
8295 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8296 .saturating_sub(1);
8297 start_point =
8298 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8299 };
8300
8301 (start_point..end_point, empty_str.clone())
8302 })
8303 .sorted_by_key(|(range, _)| range.start)
8304 .collect::<Vec<_>>();
8305 buffer.update(cx, |this, cx| {
8306 this.edit(edits, None, cx);
8307 })
8308 }
8309 this.refresh_inline_completion(true, false, window, cx);
8310 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8311 });
8312 }
8313
8314 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8315 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8316 self.transact(window, cx, |this, window, cx| {
8317 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8318 s.move_with(|map, selection| {
8319 if selection.is_empty() {
8320 let cursor = movement::right(map, selection.head());
8321 selection.end = cursor;
8322 selection.reversed = true;
8323 selection.goal = SelectionGoal::None;
8324 }
8325 })
8326 });
8327 this.insert("", window, cx);
8328 this.refresh_inline_completion(true, false, window, cx);
8329 });
8330 }
8331
8332 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8333 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8334 if self.move_to_prev_snippet_tabstop(window, cx) {
8335 return;
8336 }
8337 self.outdent(&Outdent, window, cx);
8338 }
8339
8340 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8341 if self.move_to_next_snippet_tabstop(window, cx) {
8342 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8343 return;
8344 }
8345 if self.read_only(cx) {
8346 return;
8347 }
8348 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8349 let mut selections = self.selections.all_adjusted(cx);
8350 let buffer = self.buffer.read(cx);
8351 let snapshot = buffer.snapshot(cx);
8352 let rows_iter = selections.iter().map(|s| s.head().row);
8353 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8354
8355 let mut edits = Vec::new();
8356 let mut prev_edited_row = 0;
8357 let mut row_delta = 0;
8358 for selection in &mut selections {
8359 if selection.start.row != prev_edited_row {
8360 row_delta = 0;
8361 }
8362 prev_edited_row = selection.end.row;
8363
8364 // If the selection is non-empty, then increase the indentation of the selected lines.
8365 if !selection.is_empty() {
8366 row_delta =
8367 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8368 continue;
8369 }
8370
8371 // If the selection is empty and the cursor is in the leading whitespace before the
8372 // suggested indentation, then auto-indent the line.
8373 let cursor = selection.head();
8374 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8375 if let Some(suggested_indent) =
8376 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8377 {
8378 if cursor.column < suggested_indent.len
8379 && cursor.column <= current_indent.len
8380 && current_indent.len <= suggested_indent.len
8381 {
8382 selection.start = Point::new(cursor.row, suggested_indent.len);
8383 selection.end = selection.start;
8384 if row_delta == 0 {
8385 edits.extend(Buffer::edit_for_indent_size_adjustment(
8386 cursor.row,
8387 current_indent,
8388 suggested_indent,
8389 ));
8390 row_delta = suggested_indent.len - current_indent.len;
8391 }
8392 continue;
8393 }
8394 }
8395
8396 // Otherwise, insert a hard or soft tab.
8397 let settings = buffer.language_settings_at(cursor, cx);
8398 let tab_size = if settings.hard_tabs {
8399 IndentSize::tab()
8400 } else {
8401 let tab_size = settings.tab_size.get();
8402 let indent_remainder = snapshot
8403 .text_for_range(Point::new(cursor.row, 0)..cursor)
8404 .flat_map(str::chars)
8405 .fold(row_delta % tab_size, |counter: u32, c| {
8406 if c == '\t' {
8407 0
8408 } else {
8409 (counter + 1) % tab_size
8410 }
8411 });
8412
8413 let chars_to_next_tab_stop = tab_size - indent_remainder;
8414 IndentSize::spaces(chars_to_next_tab_stop)
8415 };
8416 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8417 selection.end = selection.start;
8418 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8419 row_delta += tab_size.len;
8420 }
8421
8422 self.transact(window, cx, |this, window, cx| {
8423 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8424 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8425 s.select(selections)
8426 });
8427 this.refresh_inline_completion(true, false, window, cx);
8428 });
8429 }
8430
8431 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8432 if self.read_only(cx) {
8433 return;
8434 }
8435 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8436 let mut selections = self.selections.all::<Point>(cx);
8437 let mut prev_edited_row = 0;
8438 let mut row_delta = 0;
8439 let mut edits = Vec::new();
8440 let buffer = self.buffer.read(cx);
8441 let snapshot = buffer.snapshot(cx);
8442 for selection in &mut selections {
8443 if selection.start.row != prev_edited_row {
8444 row_delta = 0;
8445 }
8446 prev_edited_row = selection.end.row;
8447
8448 row_delta =
8449 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8450 }
8451
8452 self.transact(window, cx, |this, window, cx| {
8453 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8454 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8455 s.select(selections)
8456 });
8457 });
8458 }
8459
8460 fn indent_selection(
8461 buffer: &MultiBuffer,
8462 snapshot: &MultiBufferSnapshot,
8463 selection: &mut Selection<Point>,
8464 edits: &mut Vec<(Range<Point>, String)>,
8465 delta_for_start_row: u32,
8466 cx: &App,
8467 ) -> u32 {
8468 let settings = buffer.language_settings_at(selection.start, cx);
8469 let tab_size = settings.tab_size.get();
8470 let indent_kind = if settings.hard_tabs {
8471 IndentKind::Tab
8472 } else {
8473 IndentKind::Space
8474 };
8475 let mut start_row = selection.start.row;
8476 let mut end_row = selection.end.row + 1;
8477
8478 // If a selection ends at the beginning of a line, don't indent
8479 // that last line.
8480 if selection.end.column == 0 && selection.end.row > selection.start.row {
8481 end_row -= 1;
8482 }
8483
8484 // Avoid re-indenting a row that has already been indented by a
8485 // previous selection, but still update this selection's column
8486 // to reflect that indentation.
8487 if delta_for_start_row > 0 {
8488 start_row += 1;
8489 selection.start.column += delta_for_start_row;
8490 if selection.end.row == selection.start.row {
8491 selection.end.column += delta_for_start_row;
8492 }
8493 }
8494
8495 let mut delta_for_end_row = 0;
8496 let has_multiple_rows = start_row + 1 != end_row;
8497 for row in start_row..end_row {
8498 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8499 let indent_delta = match (current_indent.kind, indent_kind) {
8500 (IndentKind::Space, IndentKind::Space) => {
8501 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8502 IndentSize::spaces(columns_to_next_tab_stop)
8503 }
8504 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8505 (_, IndentKind::Tab) => IndentSize::tab(),
8506 };
8507
8508 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8509 0
8510 } else {
8511 selection.start.column
8512 };
8513 let row_start = Point::new(row, start);
8514 edits.push((
8515 row_start..row_start,
8516 indent_delta.chars().collect::<String>(),
8517 ));
8518
8519 // Update this selection's endpoints to reflect the indentation.
8520 if row == selection.start.row {
8521 selection.start.column += indent_delta.len;
8522 }
8523 if row == selection.end.row {
8524 selection.end.column += indent_delta.len;
8525 delta_for_end_row = indent_delta.len;
8526 }
8527 }
8528
8529 if selection.start.row == selection.end.row {
8530 delta_for_start_row + delta_for_end_row
8531 } else {
8532 delta_for_end_row
8533 }
8534 }
8535
8536 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8537 if self.read_only(cx) {
8538 return;
8539 }
8540 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8542 let selections = self.selections.all::<Point>(cx);
8543 let mut deletion_ranges = Vec::new();
8544 let mut last_outdent = None;
8545 {
8546 let buffer = self.buffer.read(cx);
8547 let snapshot = buffer.snapshot(cx);
8548 for selection in &selections {
8549 let settings = buffer.language_settings_at(selection.start, cx);
8550 let tab_size = settings.tab_size.get();
8551 let mut rows = selection.spanned_rows(false, &display_map);
8552
8553 // Avoid re-outdenting a row that has already been outdented by a
8554 // previous selection.
8555 if let Some(last_row) = last_outdent {
8556 if last_row == rows.start {
8557 rows.start = rows.start.next_row();
8558 }
8559 }
8560 let has_multiple_rows = rows.len() > 1;
8561 for row in rows.iter_rows() {
8562 let indent_size = snapshot.indent_size_for_line(row);
8563 if indent_size.len > 0 {
8564 let deletion_len = match indent_size.kind {
8565 IndentKind::Space => {
8566 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8567 if columns_to_prev_tab_stop == 0 {
8568 tab_size
8569 } else {
8570 columns_to_prev_tab_stop
8571 }
8572 }
8573 IndentKind::Tab => 1,
8574 };
8575 let start = if has_multiple_rows
8576 || deletion_len > selection.start.column
8577 || indent_size.len < selection.start.column
8578 {
8579 0
8580 } else {
8581 selection.start.column - deletion_len
8582 };
8583 deletion_ranges.push(
8584 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8585 );
8586 last_outdent = Some(row);
8587 }
8588 }
8589 }
8590 }
8591
8592 self.transact(window, cx, |this, window, cx| {
8593 this.buffer.update(cx, |buffer, cx| {
8594 let empty_str: Arc<str> = Arc::default();
8595 buffer.edit(
8596 deletion_ranges
8597 .into_iter()
8598 .map(|range| (range, empty_str.clone())),
8599 None,
8600 cx,
8601 );
8602 });
8603 let selections = this.selections.all::<usize>(cx);
8604 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8605 s.select(selections)
8606 });
8607 });
8608 }
8609
8610 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8611 if self.read_only(cx) {
8612 return;
8613 }
8614 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8615 let selections = self
8616 .selections
8617 .all::<usize>(cx)
8618 .into_iter()
8619 .map(|s| s.range());
8620
8621 self.transact(window, cx, |this, window, cx| {
8622 this.buffer.update(cx, |buffer, cx| {
8623 buffer.autoindent_ranges(selections, cx);
8624 });
8625 let selections = this.selections.all::<usize>(cx);
8626 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8627 s.select(selections)
8628 });
8629 });
8630 }
8631
8632 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8633 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8634 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8635 let selections = self.selections.all::<Point>(cx);
8636
8637 let mut new_cursors = Vec::new();
8638 let mut edit_ranges = Vec::new();
8639 let mut selections = selections.iter().peekable();
8640 while let Some(selection) = selections.next() {
8641 let mut rows = selection.spanned_rows(false, &display_map);
8642 let goal_display_column = selection.head().to_display_point(&display_map).column();
8643
8644 // Accumulate contiguous regions of rows that we want to delete.
8645 while let Some(next_selection) = selections.peek() {
8646 let next_rows = next_selection.spanned_rows(false, &display_map);
8647 if next_rows.start <= rows.end {
8648 rows.end = next_rows.end;
8649 selections.next().unwrap();
8650 } else {
8651 break;
8652 }
8653 }
8654
8655 let buffer = &display_map.buffer_snapshot;
8656 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8657 let edit_end;
8658 let cursor_buffer_row;
8659 if buffer.max_point().row >= rows.end.0 {
8660 // If there's a line after the range, delete the \n from the end of the row range
8661 // and position the cursor on the next line.
8662 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8663 cursor_buffer_row = rows.end;
8664 } else {
8665 // If there isn't a line after the range, delete the \n from the line before the
8666 // start of the row range and position the cursor there.
8667 edit_start = edit_start.saturating_sub(1);
8668 edit_end = buffer.len();
8669 cursor_buffer_row = rows.start.previous_row();
8670 }
8671
8672 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8673 *cursor.column_mut() =
8674 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8675
8676 new_cursors.push((
8677 selection.id,
8678 buffer.anchor_after(cursor.to_point(&display_map)),
8679 ));
8680 edit_ranges.push(edit_start..edit_end);
8681 }
8682
8683 self.transact(window, cx, |this, window, cx| {
8684 let buffer = this.buffer.update(cx, |buffer, cx| {
8685 let empty_str: Arc<str> = Arc::default();
8686 buffer.edit(
8687 edit_ranges
8688 .into_iter()
8689 .map(|range| (range, empty_str.clone())),
8690 None,
8691 cx,
8692 );
8693 buffer.snapshot(cx)
8694 });
8695 let new_selections = new_cursors
8696 .into_iter()
8697 .map(|(id, cursor)| {
8698 let cursor = cursor.to_point(&buffer);
8699 Selection {
8700 id,
8701 start: cursor,
8702 end: cursor,
8703 reversed: false,
8704 goal: SelectionGoal::None,
8705 }
8706 })
8707 .collect();
8708
8709 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8710 s.select(new_selections);
8711 });
8712 });
8713 }
8714
8715 pub fn join_lines_impl(
8716 &mut self,
8717 insert_whitespace: bool,
8718 window: &mut Window,
8719 cx: &mut Context<Self>,
8720 ) {
8721 if self.read_only(cx) {
8722 return;
8723 }
8724 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8725 for selection in self.selections.all::<Point>(cx) {
8726 let start = MultiBufferRow(selection.start.row);
8727 // Treat single line selections as if they include the next line. Otherwise this action
8728 // would do nothing for single line selections individual cursors.
8729 let end = if selection.start.row == selection.end.row {
8730 MultiBufferRow(selection.start.row + 1)
8731 } else {
8732 MultiBufferRow(selection.end.row)
8733 };
8734
8735 if let Some(last_row_range) = row_ranges.last_mut() {
8736 if start <= last_row_range.end {
8737 last_row_range.end = end;
8738 continue;
8739 }
8740 }
8741 row_ranges.push(start..end);
8742 }
8743
8744 let snapshot = self.buffer.read(cx).snapshot(cx);
8745 let mut cursor_positions = Vec::new();
8746 for row_range in &row_ranges {
8747 let anchor = snapshot.anchor_before(Point::new(
8748 row_range.end.previous_row().0,
8749 snapshot.line_len(row_range.end.previous_row()),
8750 ));
8751 cursor_positions.push(anchor..anchor);
8752 }
8753
8754 self.transact(window, cx, |this, window, cx| {
8755 for row_range in row_ranges.into_iter().rev() {
8756 for row in row_range.iter_rows().rev() {
8757 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8758 let next_line_row = row.next_row();
8759 let indent = snapshot.indent_size_for_line(next_line_row);
8760 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8761
8762 let replace =
8763 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8764 " "
8765 } else {
8766 ""
8767 };
8768
8769 this.buffer.update(cx, |buffer, cx| {
8770 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8771 });
8772 }
8773 }
8774
8775 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8776 s.select_anchor_ranges(cursor_positions)
8777 });
8778 });
8779 }
8780
8781 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8782 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8783 self.join_lines_impl(true, window, cx);
8784 }
8785
8786 pub fn sort_lines_case_sensitive(
8787 &mut self,
8788 _: &SortLinesCaseSensitive,
8789 window: &mut Window,
8790 cx: &mut Context<Self>,
8791 ) {
8792 self.manipulate_lines(window, cx, |lines| lines.sort())
8793 }
8794
8795 pub fn sort_lines_case_insensitive(
8796 &mut self,
8797 _: &SortLinesCaseInsensitive,
8798 window: &mut Window,
8799 cx: &mut Context<Self>,
8800 ) {
8801 self.manipulate_lines(window, cx, |lines| {
8802 lines.sort_by_key(|line| line.to_lowercase())
8803 })
8804 }
8805
8806 pub fn unique_lines_case_insensitive(
8807 &mut self,
8808 _: &UniqueLinesCaseInsensitive,
8809 window: &mut Window,
8810 cx: &mut Context<Self>,
8811 ) {
8812 self.manipulate_lines(window, cx, |lines| {
8813 let mut seen = HashSet::default();
8814 lines.retain(|line| seen.insert(line.to_lowercase()));
8815 })
8816 }
8817
8818 pub fn unique_lines_case_sensitive(
8819 &mut self,
8820 _: &UniqueLinesCaseSensitive,
8821 window: &mut Window,
8822 cx: &mut Context<Self>,
8823 ) {
8824 self.manipulate_lines(window, cx, |lines| {
8825 let mut seen = HashSet::default();
8826 lines.retain(|line| seen.insert(*line));
8827 })
8828 }
8829
8830 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8831 let Some(project) = self.project.clone() else {
8832 return;
8833 };
8834 self.reload(project, window, cx)
8835 .detach_and_notify_err(window, cx);
8836 }
8837
8838 pub fn restore_file(
8839 &mut self,
8840 _: &::git::RestoreFile,
8841 window: &mut Window,
8842 cx: &mut Context<Self>,
8843 ) {
8844 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8845 let mut buffer_ids = HashSet::default();
8846 let snapshot = self.buffer().read(cx).snapshot(cx);
8847 for selection in self.selections.all::<usize>(cx) {
8848 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8849 }
8850
8851 let buffer = self.buffer().read(cx);
8852 let ranges = buffer_ids
8853 .into_iter()
8854 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8855 .collect::<Vec<_>>();
8856
8857 self.restore_hunks_in_ranges(ranges, window, cx);
8858 }
8859
8860 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8861 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8862 let selections = self
8863 .selections
8864 .all(cx)
8865 .into_iter()
8866 .map(|s| s.range())
8867 .collect();
8868 self.restore_hunks_in_ranges(selections, window, cx);
8869 }
8870
8871 pub fn restore_hunks_in_ranges(
8872 &mut self,
8873 ranges: Vec<Range<Point>>,
8874 window: &mut Window,
8875 cx: &mut Context<Editor>,
8876 ) {
8877 let mut revert_changes = HashMap::default();
8878 let chunk_by = self
8879 .snapshot(window, cx)
8880 .hunks_for_ranges(ranges)
8881 .into_iter()
8882 .chunk_by(|hunk| hunk.buffer_id);
8883 for (buffer_id, hunks) in &chunk_by {
8884 let hunks = hunks.collect::<Vec<_>>();
8885 for hunk in &hunks {
8886 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8887 }
8888 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8889 }
8890 drop(chunk_by);
8891 if !revert_changes.is_empty() {
8892 self.transact(window, cx, |editor, window, cx| {
8893 editor.restore(revert_changes, window, cx);
8894 });
8895 }
8896 }
8897
8898 pub fn open_active_item_in_terminal(
8899 &mut self,
8900 _: &OpenInTerminal,
8901 window: &mut Window,
8902 cx: &mut Context<Self>,
8903 ) {
8904 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8905 let project_path = buffer.read(cx).project_path(cx)?;
8906 let project = self.project.as_ref()?.read(cx);
8907 let entry = project.entry_for_path(&project_path, cx)?;
8908 let parent = match &entry.canonical_path {
8909 Some(canonical_path) => canonical_path.to_path_buf(),
8910 None => project.absolute_path(&project_path, cx)?,
8911 }
8912 .parent()?
8913 .to_path_buf();
8914 Some(parent)
8915 }) {
8916 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8917 }
8918 }
8919
8920 fn set_breakpoint_context_menu(
8921 &mut self,
8922 display_row: DisplayRow,
8923 position: Option<Anchor>,
8924 clicked_point: gpui::Point<Pixels>,
8925 window: &mut Window,
8926 cx: &mut Context<Self>,
8927 ) {
8928 if !cx.has_flag::<Debugger>() {
8929 return;
8930 }
8931 let source = self
8932 .buffer
8933 .read(cx)
8934 .snapshot(cx)
8935 .anchor_before(Point::new(display_row.0, 0u32));
8936
8937 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8938
8939 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8940 self,
8941 source,
8942 clicked_point,
8943 None,
8944 context_menu,
8945 window,
8946 cx,
8947 );
8948 }
8949
8950 fn add_edit_breakpoint_block(
8951 &mut self,
8952 anchor: Anchor,
8953 breakpoint: &Breakpoint,
8954 edit_action: BreakpointPromptEditAction,
8955 window: &mut Window,
8956 cx: &mut Context<Self>,
8957 ) {
8958 let weak_editor = cx.weak_entity();
8959 let bp_prompt = cx.new(|cx| {
8960 BreakpointPromptEditor::new(
8961 weak_editor,
8962 anchor,
8963 breakpoint.clone(),
8964 edit_action,
8965 window,
8966 cx,
8967 )
8968 });
8969
8970 let height = bp_prompt.update(cx, |this, cx| {
8971 this.prompt
8972 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8973 });
8974 let cloned_prompt = bp_prompt.clone();
8975 let blocks = vec![BlockProperties {
8976 style: BlockStyle::Sticky,
8977 placement: BlockPlacement::Above(anchor),
8978 height: Some(height),
8979 render: Arc::new(move |cx| {
8980 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8981 cloned_prompt.clone().into_any_element()
8982 }),
8983 priority: 0,
8984 }];
8985
8986 let focus_handle = bp_prompt.focus_handle(cx);
8987 window.focus(&focus_handle);
8988
8989 let block_ids = self.insert_blocks(blocks, None, cx);
8990 bp_prompt.update(cx, |prompt, _| {
8991 prompt.add_block_ids(block_ids);
8992 });
8993 }
8994
8995 pub(crate) fn breakpoint_at_row(
8996 &self,
8997 row: u32,
8998 window: &mut Window,
8999 cx: &mut Context<Self>,
9000 ) -> Option<(Anchor, Breakpoint)> {
9001 let snapshot = self.snapshot(window, cx);
9002 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9003
9004 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9005 }
9006
9007 pub(crate) fn breakpoint_at_anchor(
9008 &self,
9009 breakpoint_position: Anchor,
9010 snapshot: &EditorSnapshot,
9011 cx: &mut Context<Self>,
9012 ) -> Option<(Anchor, Breakpoint)> {
9013 let project = self.project.clone()?;
9014
9015 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9016 snapshot
9017 .buffer_snapshot
9018 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9019 })?;
9020
9021 let enclosing_excerpt = breakpoint_position.excerpt_id;
9022 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9023 let buffer_snapshot = buffer.read(cx).snapshot();
9024
9025 let row = buffer_snapshot
9026 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9027 .row;
9028
9029 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9030 let anchor_end = snapshot
9031 .buffer_snapshot
9032 .anchor_after(Point::new(row, line_len));
9033
9034 let bp = self
9035 .breakpoint_store
9036 .as_ref()?
9037 .read_with(cx, |breakpoint_store, cx| {
9038 breakpoint_store
9039 .breakpoints(
9040 &buffer,
9041 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9042 &buffer_snapshot,
9043 cx,
9044 )
9045 .next()
9046 .and_then(|(anchor, bp)| {
9047 let breakpoint_row = buffer_snapshot
9048 .summary_for_anchor::<text::PointUtf16>(anchor)
9049 .row;
9050
9051 if breakpoint_row == row {
9052 snapshot
9053 .buffer_snapshot
9054 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9055 .map(|anchor| (anchor, bp.clone()))
9056 } else {
9057 None
9058 }
9059 })
9060 });
9061 bp
9062 }
9063
9064 pub fn edit_log_breakpoint(
9065 &mut self,
9066 _: &EditLogBreakpoint,
9067 window: &mut Window,
9068 cx: &mut Context<Self>,
9069 ) {
9070 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9071 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9072 message: None,
9073 state: BreakpointState::Enabled,
9074 condition: None,
9075 hit_condition: None,
9076 });
9077
9078 self.add_edit_breakpoint_block(
9079 anchor,
9080 &breakpoint,
9081 BreakpointPromptEditAction::Log,
9082 window,
9083 cx,
9084 );
9085 }
9086 }
9087
9088 fn breakpoints_at_cursors(
9089 &self,
9090 window: &mut Window,
9091 cx: &mut Context<Self>,
9092 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9093 let snapshot = self.snapshot(window, cx);
9094 let cursors = self
9095 .selections
9096 .disjoint_anchors()
9097 .into_iter()
9098 .map(|selection| {
9099 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9100
9101 let breakpoint_position = self
9102 .breakpoint_at_row(cursor_position.row, window, cx)
9103 .map(|bp| bp.0)
9104 .unwrap_or_else(|| {
9105 snapshot
9106 .display_snapshot
9107 .buffer_snapshot
9108 .anchor_after(Point::new(cursor_position.row, 0))
9109 });
9110
9111 let breakpoint = self
9112 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9113 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9114
9115 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9116 })
9117 // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
9118 .collect::<HashMap<Anchor, _>>();
9119
9120 cursors.into_iter().collect()
9121 }
9122
9123 pub fn enable_breakpoint(
9124 &mut self,
9125 _: &crate::actions::EnableBreakpoint,
9126 window: &mut Window,
9127 cx: &mut Context<Self>,
9128 ) {
9129 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9130 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9131 continue;
9132 };
9133 self.edit_breakpoint_at_anchor(
9134 anchor,
9135 breakpoint,
9136 BreakpointEditAction::InvertState,
9137 cx,
9138 );
9139 }
9140 }
9141
9142 pub fn disable_breakpoint(
9143 &mut self,
9144 _: &crate::actions::DisableBreakpoint,
9145 window: &mut Window,
9146 cx: &mut Context<Self>,
9147 ) {
9148 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9149 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9150 continue;
9151 };
9152 self.edit_breakpoint_at_anchor(
9153 anchor,
9154 breakpoint,
9155 BreakpointEditAction::InvertState,
9156 cx,
9157 );
9158 }
9159 }
9160
9161 pub fn toggle_breakpoint(
9162 &mut self,
9163 _: &crate::actions::ToggleBreakpoint,
9164 window: &mut Window,
9165 cx: &mut Context<Self>,
9166 ) {
9167 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9168 if let Some(breakpoint) = breakpoint {
9169 self.edit_breakpoint_at_anchor(
9170 anchor,
9171 breakpoint,
9172 BreakpointEditAction::Toggle,
9173 cx,
9174 );
9175 } else {
9176 self.edit_breakpoint_at_anchor(
9177 anchor,
9178 Breakpoint::new_standard(),
9179 BreakpointEditAction::Toggle,
9180 cx,
9181 );
9182 }
9183 }
9184 }
9185
9186 pub fn edit_breakpoint_at_anchor(
9187 &mut self,
9188 breakpoint_position: Anchor,
9189 breakpoint: Breakpoint,
9190 edit_action: BreakpointEditAction,
9191 cx: &mut Context<Self>,
9192 ) {
9193 let Some(breakpoint_store) = &self.breakpoint_store else {
9194 return;
9195 };
9196
9197 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9198 if breakpoint_position == Anchor::min() {
9199 self.buffer()
9200 .read(cx)
9201 .excerpt_buffer_ids()
9202 .into_iter()
9203 .next()
9204 } else {
9205 None
9206 }
9207 }) else {
9208 return;
9209 };
9210
9211 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9212 return;
9213 };
9214
9215 breakpoint_store.update(cx, |breakpoint_store, cx| {
9216 breakpoint_store.toggle_breakpoint(
9217 buffer,
9218 (breakpoint_position.text_anchor, breakpoint),
9219 edit_action,
9220 cx,
9221 );
9222 });
9223
9224 cx.notify();
9225 }
9226
9227 #[cfg(any(test, feature = "test-support"))]
9228 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9229 self.breakpoint_store.clone()
9230 }
9231
9232 pub fn prepare_restore_change(
9233 &self,
9234 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9235 hunk: &MultiBufferDiffHunk,
9236 cx: &mut App,
9237 ) -> Option<()> {
9238 if hunk.is_created_file() {
9239 return None;
9240 }
9241 let buffer = self.buffer.read(cx);
9242 let diff = buffer.diff_for(hunk.buffer_id)?;
9243 let buffer = buffer.buffer(hunk.buffer_id)?;
9244 let buffer = buffer.read(cx);
9245 let original_text = diff
9246 .read(cx)
9247 .base_text()
9248 .as_rope()
9249 .slice(hunk.diff_base_byte_range.clone());
9250 let buffer_snapshot = buffer.snapshot();
9251 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9252 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9253 probe
9254 .0
9255 .start
9256 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9257 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9258 }) {
9259 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9260 Some(())
9261 } else {
9262 None
9263 }
9264 }
9265
9266 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9267 self.manipulate_lines(window, cx, |lines| lines.reverse())
9268 }
9269
9270 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9271 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9272 }
9273
9274 fn manipulate_lines<Fn>(
9275 &mut self,
9276 window: &mut Window,
9277 cx: &mut Context<Self>,
9278 mut callback: Fn,
9279 ) where
9280 Fn: FnMut(&mut Vec<&str>),
9281 {
9282 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9283
9284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9285 let buffer = self.buffer.read(cx).snapshot(cx);
9286
9287 let mut edits = Vec::new();
9288
9289 let selections = self.selections.all::<Point>(cx);
9290 let mut selections = selections.iter().peekable();
9291 let mut contiguous_row_selections = Vec::new();
9292 let mut new_selections = Vec::new();
9293 let mut added_lines = 0;
9294 let mut removed_lines = 0;
9295
9296 while let Some(selection) = selections.next() {
9297 let (start_row, end_row) = consume_contiguous_rows(
9298 &mut contiguous_row_selections,
9299 selection,
9300 &display_map,
9301 &mut selections,
9302 );
9303
9304 let start_point = Point::new(start_row.0, 0);
9305 let end_point = Point::new(
9306 end_row.previous_row().0,
9307 buffer.line_len(end_row.previous_row()),
9308 );
9309 let text = buffer
9310 .text_for_range(start_point..end_point)
9311 .collect::<String>();
9312
9313 let mut lines = text.split('\n').collect_vec();
9314
9315 let lines_before = lines.len();
9316 callback(&mut lines);
9317 let lines_after = lines.len();
9318
9319 edits.push((start_point..end_point, lines.join("\n")));
9320
9321 // Selections must change based on added and removed line count
9322 let start_row =
9323 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9324 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9325 new_selections.push(Selection {
9326 id: selection.id,
9327 start: start_row,
9328 end: end_row,
9329 goal: SelectionGoal::None,
9330 reversed: selection.reversed,
9331 });
9332
9333 if lines_after > lines_before {
9334 added_lines += lines_after - lines_before;
9335 } else if lines_before > lines_after {
9336 removed_lines += lines_before - lines_after;
9337 }
9338 }
9339
9340 self.transact(window, cx, |this, window, cx| {
9341 let buffer = this.buffer.update(cx, |buffer, cx| {
9342 buffer.edit(edits, None, cx);
9343 buffer.snapshot(cx)
9344 });
9345
9346 // Recalculate offsets on newly edited buffer
9347 let new_selections = new_selections
9348 .iter()
9349 .map(|s| {
9350 let start_point = Point::new(s.start.0, 0);
9351 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9352 Selection {
9353 id: s.id,
9354 start: buffer.point_to_offset(start_point),
9355 end: buffer.point_to_offset(end_point),
9356 goal: s.goal,
9357 reversed: s.reversed,
9358 }
9359 })
9360 .collect();
9361
9362 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9363 s.select(new_selections);
9364 });
9365
9366 this.request_autoscroll(Autoscroll::fit(), cx);
9367 });
9368 }
9369
9370 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9371 self.manipulate_text(window, cx, |text| {
9372 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9373 if has_upper_case_characters {
9374 text.to_lowercase()
9375 } else {
9376 text.to_uppercase()
9377 }
9378 })
9379 }
9380
9381 pub fn convert_to_upper_case(
9382 &mut self,
9383 _: &ConvertToUpperCase,
9384 window: &mut Window,
9385 cx: &mut Context<Self>,
9386 ) {
9387 self.manipulate_text(window, cx, |text| text.to_uppercase())
9388 }
9389
9390 pub fn convert_to_lower_case(
9391 &mut self,
9392 _: &ConvertToLowerCase,
9393 window: &mut Window,
9394 cx: &mut Context<Self>,
9395 ) {
9396 self.manipulate_text(window, cx, |text| text.to_lowercase())
9397 }
9398
9399 pub fn convert_to_title_case(
9400 &mut self,
9401 _: &ConvertToTitleCase,
9402 window: &mut Window,
9403 cx: &mut Context<Self>,
9404 ) {
9405 self.manipulate_text(window, cx, |text| {
9406 text.split('\n')
9407 .map(|line| line.to_case(Case::Title))
9408 .join("\n")
9409 })
9410 }
9411
9412 pub fn convert_to_snake_case(
9413 &mut self,
9414 _: &ConvertToSnakeCase,
9415 window: &mut Window,
9416 cx: &mut Context<Self>,
9417 ) {
9418 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9419 }
9420
9421 pub fn convert_to_kebab_case(
9422 &mut self,
9423 _: &ConvertToKebabCase,
9424 window: &mut Window,
9425 cx: &mut Context<Self>,
9426 ) {
9427 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9428 }
9429
9430 pub fn convert_to_upper_camel_case(
9431 &mut self,
9432 _: &ConvertToUpperCamelCase,
9433 window: &mut Window,
9434 cx: &mut Context<Self>,
9435 ) {
9436 self.manipulate_text(window, cx, |text| {
9437 text.split('\n')
9438 .map(|line| line.to_case(Case::UpperCamel))
9439 .join("\n")
9440 })
9441 }
9442
9443 pub fn convert_to_lower_camel_case(
9444 &mut self,
9445 _: &ConvertToLowerCamelCase,
9446 window: &mut Window,
9447 cx: &mut Context<Self>,
9448 ) {
9449 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9450 }
9451
9452 pub fn convert_to_opposite_case(
9453 &mut self,
9454 _: &ConvertToOppositeCase,
9455 window: &mut Window,
9456 cx: &mut Context<Self>,
9457 ) {
9458 self.manipulate_text(window, cx, |text| {
9459 text.chars()
9460 .fold(String::with_capacity(text.len()), |mut t, c| {
9461 if c.is_uppercase() {
9462 t.extend(c.to_lowercase());
9463 } else {
9464 t.extend(c.to_uppercase());
9465 }
9466 t
9467 })
9468 })
9469 }
9470
9471 pub fn convert_to_rot13(
9472 &mut self,
9473 _: &ConvertToRot13,
9474 window: &mut Window,
9475 cx: &mut Context<Self>,
9476 ) {
9477 self.manipulate_text(window, cx, |text| {
9478 text.chars()
9479 .map(|c| match c {
9480 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9481 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9482 _ => c,
9483 })
9484 .collect()
9485 })
9486 }
9487
9488 pub fn convert_to_rot47(
9489 &mut self,
9490 _: &ConvertToRot47,
9491 window: &mut Window,
9492 cx: &mut Context<Self>,
9493 ) {
9494 self.manipulate_text(window, cx, |text| {
9495 text.chars()
9496 .map(|c| {
9497 let code_point = c as u32;
9498 if code_point >= 33 && code_point <= 126 {
9499 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9500 }
9501 c
9502 })
9503 .collect()
9504 })
9505 }
9506
9507 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9508 where
9509 Fn: FnMut(&str) -> String,
9510 {
9511 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9512 let buffer = self.buffer.read(cx).snapshot(cx);
9513
9514 let mut new_selections = Vec::new();
9515 let mut edits = Vec::new();
9516 let mut selection_adjustment = 0i32;
9517
9518 for selection in self.selections.all::<usize>(cx) {
9519 let selection_is_empty = selection.is_empty();
9520
9521 let (start, end) = if selection_is_empty {
9522 let word_range = movement::surrounding_word(
9523 &display_map,
9524 selection.start.to_display_point(&display_map),
9525 );
9526 let start = word_range.start.to_offset(&display_map, Bias::Left);
9527 let end = word_range.end.to_offset(&display_map, Bias::Left);
9528 (start, end)
9529 } else {
9530 (selection.start, selection.end)
9531 };
9532
9533 let text = buffer.text_for_range(start..end).collect::<String>();
9534 let old_length = text.len() as i32;
9535 let text = callback(&text);
9536
9537 new_selections.push(Selection {
9538 start: (start as i32 - selection_adjustment) as usize,
9539 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9540 goal: SelectionGoal::None,
9541 ..selection
9542 });
9543
9544 selection_adjustment += old_length - text.len() as i32;
9545
9546 edits.push((start..end, text));
9547 }
9548
9549 self.transact(window, cx, |this, window, cx| {
9550 this.buffer.update(cx, |buffer, cx| {
9551 buffer.edit(edits, None, cx);
9552 });
9553
9554 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9555 s.select(new_selections);
9556 });
9557
9558 this.request_autoscroll(Autoscroll::fit(), cx);
9559 });
9560 }
9561
9562 pub fn duplicate(
9563 &mut self,
9564 upwards: bool,
9565 whole_lines: bool,
9566 window: &mut Window,
9567 cx: &mut Context<Self>,
9568 ) {
9569 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9570
9571 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9572 let buffer = &display_map.buffer_snapshot;
9573 let selections = self.selections.all::<Point>(cx);
9574
9575 let mut edits = Vec::new();
9576 let mut selections_iter = selections.iter().peekable();
9577 while let Some(selection) = selections_iter.next() {
9578 let mut rows = selection.spanned_rows(false, &display_map);
9579 // duplicate line-wise
9580 if whole_lines || selection.start == selection.end {
9581 // Avoid duplicating the same lines twice.
9582 while let Some(next_selection) = selections_iter.peek() {
9583 let next_rows = next_selection.spanned_rows(false, &display_map);
9584 if next_rows.start < rows.end {
9585 rows.end = next_rows.end;
9586 selections_iter.next().unwrap();
9587 } else {
9588 break;
9589 }
9590 }
9591
9592 // Copy the text from the selected row region and splice it either at the start
9593 // or end of the region.
9594 let start = Point::new(rows.start.0, 0);
9595 let end = Point::new(
9596 rows.end.previous_row().0,
9597 buffer.line_len(rows.end.previous_row()),
9598 );
9599 let text = buffer
9600 .text_for_range(start..end)
9601 .chain(Some("\n"))
9602 .collect::<String>();
9603 let insert_location = if upwards {
9604 Point::new(rows.end.0, 0)
9605 } else {
9606 start
9607 };
9608 edits.push((insert_location..insert_location, text));
9609 } else {
9610 // duplicate character-wise
9611 let start = selection.start;
9612 let end = selection.end;
9613 let text = buffer.text_for_range(start..end).collect::<String>();
9614 edits.push((selection.end..selection.end, text));
9615 }
9616 }
9617
9618 self.transact(window, cx, |this, _, cx| {
9619 this.buffer.update(cx, |buffer, cx| {
9620 buffer.edit(edits, None, cx);
9621 });
9622
9623 this.request_autoscroll(Autoscroll::fit(), cx);
9624 });
9625 }
9626
9627 pub fn duplicate_line_up(
9628 &mut self,
9629 _: &DuplicateLineUp,
9630 window: &mut Window,
9631 cx: &mut Context<Self>,
9632 ) {
9633 self.duplicate(true, true, window, cx);
9634 }
9635
9636 pub fn duplicate_line_down(
9637 &mut self,
9638 _: &DuplicateLineDown,
9639 window: &mut Window,
9640 cx: &mut Context<Self>,
9641 ) {
9642 self.duplicate(false, true, window, cx);
9643 }
9644
9645 pub fn duplicate_selection(
9646 &mut self,
9647 _: &DuplicateSelection,
9648 window: &mut Window,
9649 cx: &mut Context<Self>,
9650 ) {
9651 self.duplicate(false, false, window, cx);
9652 }
9653
9654 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9655 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9656
9657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9658 let buffer = self.buffer.read(cx).snapshot(cx);
9659
9660 let mut edits = Vec::new();
9661 let mut unfold_ranges = Vec::new();
9662 let mut refold_creases = Vec::new();
9663
9664 let selections = self.selections.all::<Point>(cx);
9665 let mut selections = selections.iter().peekable();
9666 let mut contiguous_row_selections = Vec::new();
9667 let mut new_selections = Vec::new();
9668
9669 while let Some(selection) = selections.next() {
9670 // Find all the selections that span a contiguous row range
9671 let (start_row, end_row) = consume_contiguous_rows(
9672 &mut contiguous_row_selections,
9673 selection,
9674 &display_map,
9675 &mut selections,
9676 );
9677
9678 // Move the text spanned by the row range to be before the line preceding the row range
9679 if start_row.0 > 0 {
9680 let range_to_move = Point::new(
9681 start_row.previous_row().0,
9682 buffer.line_len(start_row.previous_row()),
9683 )
9684 ..Point::new(
9685 end_row.previous_row().0,
9686 buffer.line_len(end_row.previous_row()),
9687 );
9688 let insertion_point = display_map
9689 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9690 .0;
9691
9692 // Don't move lines across excerpts
9693 if buffer
9694 .excerpt_containing(insertion_point..range_to_move.end)
9695 .is_some()
9696 {
9697 let text = buffer
9698 .text_for_range(range_to_move.clone())
9699 .flat_map(|s| s.chars())
9700 .skip(1)
9701 .chain(['\n'])
9702 .collect::<String>();
9703
9704 edits.push((
9705 buffer.anchor_after(range_to_move.start)
9706 ..buffer.anchor_before(range_to_move.end),
9707 String::new(),
9708 ));
9709 let insertion_anchor = buffer.anchor_after(insertion_point);
9710 edits.push((insertion_anchor..insertion_anchor, text));
9711
9712 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9713
9714 // Move selections up
9715 new_selections.extend(contiguous_row_selections.drain(..).map(
9716 |mut selection| {
9717 selection.start.row -= row_delta;
9718 selection.end.row -= row_delta;
9719 selection
9720 },
9721 ));
9722
9723 // Move folds up
9724 unfold_ranges.push(range_to_move.clone());
9725 for fold in display_map.folds_in_range(
9726 buffer.anchor_before(range_to_move.start)
9727 ..buffer.anchor_after(range_to_move.end),
9728 ) {
9729 let mut start = fold.range.start.to_point(&buffer);
9730 let mut end = fold.range.end.to_point(&buffer);
9731 start.row -= row_delta;
9732 end.row -= row_delta;
9733 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9734 }
9735 }
9736 }
9737
9738 // If we didn't move line(s), preserve the existing selections
9739 new_selections.append(&mut contiguous_row_selections);
9740 }
9741
9742 self.transact(window, cx, |this, window, cx| {
9743 this.unfold_ranges(&unfold_ranges, true, true, cx);
9744 this.buffer.update(cx, |buffer, cx| {
9745 for (range, text) in edits {
9746 buffer.edit([(range, text)], None, cx);
9747 }
9748 });
9749 this.fold_creases(refold_creases, true, window, cx);
9750 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9751 s.select(new_selections);
9752 })
9753 });
9754 }
9755
9756 pub fn move_line_down(
9757 &mut self,
9758 _: &MoveLineDown,
9759 window: &mut Window,
9760 cx: &mut Context<Self>,
9761 ) {
9762 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9763
9764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9765 let buffer = self.buffer.read(cx).snapshot(cx);
9766
9767 let mut edits = Vec::new();
9768 let mut unfold_ranges = Vec::new();
9769 let mut refold_creases = Vec::new();
9770
9771 let selections = self.selections.all::<Point>(cx);
9772 let mut selections = selections.iter().peekable();
9773 let mut contiguous_row_selections = Vec::new();
9774 let mut new_selections = Vec::new();
9775
9776 while let Some(selection) = selections.next() {
9777 // Find all the selections that span a contiguous row range
9778 let (start_row, end_row) = consume_contiguous_rows(
9779 &mut contiguous_row_selections,
9780 selection,
9781 &display_map,
9782 &mut selections,
9783 );
9784
9785 // Move the text spanned by the row range to be after the last line of the row range
9786 if end_row.0 <= buffer.max_point().row {
9787 let range_to_move =
9788 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9789 let insertion_point = display_map
9790 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9791 .0;
9792
9793 // Don't move lines across excerpt boundaries
9794 if buffer
9795 .excerpt_containing(range_to_move.start..insertion_point)
9796 .is_some()
9797 {
9798 let mut text = String::from("\n");
9799 text.extend(buffer.text_for_range(range_to_move.clone()));
9800 text.pop(); // Drop trailing newline
9801 edits.push((
9802 buffer.anchor_after(range_to_move.start)
9803 ..buffer.anchor_before(range_to_move.end),
9804 String::new(),
9805 ));
9806 let insertion_anchor = buffer.anchor_after(insertion_point);
9807 edits.push((insertion_anchor..insertion_anchor, text));
9808
9809 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9810
9811 // Move selections down
9812 new_selections.extend(contiguous_row_selections.drain(..).map(
9813 |mut selection| {
9814 selection.start.row += row_delta;
9815 selection.end.row += row_delta;
9816 selection
9817 },
9818 ));
9819
9820 // Move folds down
9821 unfold_ranges.push(range_to_move.clone());
9822 for fold in display_map.folds_in_range(
9823 buffer.anchor_before(range_to_move.start)
9824 ..buffer.anchor_after(range_to_move.end),
9825 ) {
9826 let mut start = fold.range.start.to_point(&buffer);
9827 let mut end = fold.range.end.to_point(&buffer);
9828 start.row += row_delta;
9829 end.row += row_delta;
9830 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9831 }
9832 }
9833 }
9834
9835 // If we didn't move line(s), preserve the existing selections
9836 new_selections.append(&mut contiguous_row_selections);
9837 }
9838
9839 self.transact(window, cx, |this, window, cx| {
9840 this.unfold_ranges(&unfold_ranges, true, true, cx);
9841 this.buffer.update(cx, |buffer, cx| {
9842 for (range, text) in edits {
9843 buffer.edit([(range, text)], None, cx);
9844 }
9845 });
9846 this.fold_creases(refold_creases, true, window, cx);
9847 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9848 s.select(new_selections)
9849 });
9850 });
9851 }
9852
9853 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9854 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9855 let text_layout_details = &self.text_layout_details(window);
9856 self.transact(window, cx, |this, window, cx| {
9857 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9858 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9859 s.move_with(|display_map, selection| {
9860 if !selection.is_empty() {
9861 return;
9862 }
9863
9864 let mut head = selection.head();
9865 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9866 if head.column() == display_map.line_len(head.row()) {
9867 transpose_offset = display_map
9868 .buffer_snapshot
9869 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9870 }
9871
9872 if transpose_offset == 0 {
9873 return;
9874 }
9875
9876 *head.column_mut() += 1;
9877 head = display_map.clip_point(head, Bias::Right);
9878 let goal = SelectionGoal::HorizontalPosition(
9879 display_map
9880 .x_for_display_point(head, text_layout_details)
9881 .into(),
9882 );
9883 selection.collapse_to(head, goal);
9884
9885 let transpose_start = display_map
9886 .buffer_snapshot
9887 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9888 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9889 let transpose_end = display_map
9890 .buffer_snapshot
9891 .clip_offset(transpose_offset + 1, Bias::Right);
9892 if let Some(ch) =
9893 display_map.buffer_snapshot.chars_at(transpose_start).next()
9894 {
9895 edits.push((transpose_start..transpose_offset, String::new()));
9896 edits.push((transpose_end..transpose_end, ch.to_string()));
9897 }
9898 }
9899 });
9900 edits
9901 });
9902 this.buffer
9903 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9904 let selections = this.selections.all::<usize>(cx);
9905 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9906 s.select(selections);
9907 });
9908 });
9909 }
9910
9911 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9912 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9913 self.rewrap_impl(RewrapOptions::default(), cx)
9914 }
9915
9916 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9917 let buffer = self.buffer.read(cx).snapshot(cx);
9918 let selections = self.selections.all::<Point>(cx);
9919 let mut selections = selections.iter().peekable();
9920
9921 let mut edits = Vec::new();
9922 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9923
9924 while let Some(selection) = selections.next() {
9925 let mut start_row = selection.start.row;
9926 let mut end_row = selection.end.row;
9927
9928 // Skip selections that overlap with a range that has already been rewrapped.
9929 let selection_range = start_row..end_row;
9930 if rewrapped_row_ranges
9931 .iter()
9932 .any(|range| range.overlaps(&selection_range))
9933 {
9934 continue;
9935 }
9936
9937 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9938
9939 // Since not all lines in the selection may be at the same indent
9940 // level, choose the indent size that is the most common between all
9941 // of the lines.
9942 //
9943 // If there is a tie, we use the deepest indent.
9944 let (indent_size, indent_end) = {
9945 let mut indent_size_occurrences = HashMap::default();
9946 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9947
9948 for row in start_row..=end_row {
9949 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9950 rows_by_indent_size.entry(indent).or_default().push(row);
9951 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9952 }
9953
9954 let indent_size = indent_size_occurrences
9955 .into_iter()
9956 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9957 .map(|(indent, _)| indent)
9958 .unwrap_or_default();
9959 let row = rows_by_indent_size[&indent_size][0];
9960 let indent_end = Point::new(row, indent_size.len);
9961
9962 (indent_size, indent_end)
9963 };
9964
9965 let mut line_prefix = indent_size.chars().collect::<String>();
9966
9967 let mut inside_comment = false;
9968 if let Some(comment_prefix) =
9969 buffer
9970 .language_scope_at(selection.head())
9971 .and_then(|language| {
9972 language
9973 .line_comment_prefixes()
9974 .iter()
9975 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9976 .cloned()
9977 })
9978 {
9979 line_prefix.push_str(&comment_prefix);
9980 inside_comment = true;
9981 }
9982
9983 let language_settings = buffer.language_settings_at(selection.head(), cx);
9984 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9985 RewrapBehavior::InComments => inside_comment,
9986 RewrapBehavior::InSelections => !selection.is_empty(),
9987 RewrapBehavior::Anywhere => true,
9988 };
9989
9990 let should_rewrap = options.override_language_settings
9991 || allow_rewrap_based_on_language
9992 || self.hard_wrap.is_some();
9993 if !should_rewrap {
9994 continue;
9995 }
9996
9997 if selection.is_empty() {
9998 'expand_upwards: while start_row > 0 {
9999 let prev_row = start_row - 1;
10000 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10001 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10002 {
10003 start_row = prev_row;
10004 } else {
10005 break 'expand_upwards;
10006 }
10007 }
10008
10009 'expand_downwards: while end_row < buffer.max_point().row {
10010 let next_row = end_row + 1;
10011 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10012 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10013 {
10014 end_row = next_row;
10015 } else {
10016 break 'expand_downwards;
10017 }
10018 }
10019 }
10020
10021 let start = Point::new(start_row, 0);
10022 let start_offset = start.to_offset(&buffer);
10023 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10024 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10025 let Some(lines_without_prefixes) = selection_text
10026 .lines()
10027 .map(|line| {
10028 line.strip_prefix(&line_prefix)
10029 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10030 .ok_or_else(|| {
10031 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10032 })
10033 })
10034 .collect::<Result<Vec<_>, _>>()
10035 .log_err()
10036 else {
10037 continue;
10038 };
10039
10040 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10041 buffer
10042 .language_settings_at(Point::new(start_row, 0), cx)
10043 .preferred_line_length as usize
10044 });
10045 let wrapped_text = wrap_with_prefix(
10046 line_prefix,
10047 lines_without_prefixes.join("\n"),
10048 wrap_column,
10049 tab_size,
10050 options.preserve_existing_whitespace,
10051 );
10052
10053 // TODO: should always use char-based diff while still supporting cursor behavior that
10054 // matches vim.
10055 let mut diff_options = DiffOptions::default();
10056 if options.override_language_settings {
10057 diff_options.max_word_diff_len = 0;
10058 diff_options.max_word_diff_line_count = 0;
10059 } else {
10060 diff_options.max_word_diff_len = usize::MAX;
10061 diff_options.max_word_diff_line_count = usize::MAX;
10062 }
10063
10064 for (old_range, new_text) in
10065 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10066 {
10067 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10068 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10069 edits.push((edit_start..edit_end, new_text));
10070 }
10071
10072 rewrapped_row_ranges.push(start_row..=end_row);
10073 }
10074
10075 self.buffer
10076 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10077 }
10078
10079 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10080 let mut text = String::new();
10081 let buffer = self.buffer.read(cx).snapshot(cx);
10082 let mut selections = self.selections.all::<Point>(cx);
10083 let mut clipboard_selections = Vec::with_capacity(selections.len());
10084 {
10085 let max_point = buffer.max_point();
10086 let mut is_first = true;
10087 for selection in &mut selections {
10088 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10089 if is_entire_line {
10090 selection.start = Point::new(selection.start.row, 0);
10091 if !selection.is_empty() && selection.end.column == 0 {
10092 selection.end = cmp::min(max_point, selection.end);
10093 } else {
10094 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10095 }
10096 selection.goal = SelectionGoal::None;
10097 }
10098 if is_first {
10099 is_first = false;
10100 } else {
10101 text += "\n";
10102 }
10103 let mut len = 0;
10104 for chunk in buffer.text_for_range(selection.start..selection.end) {
10105 text.push_str(chunk);
10106 len += chunk.len();
10107 }
10108 clipboard_selections.push(ClipboardSelection {
10109 len,
10110 is_entire_line,
10111 first_line_indent: buffer
10112 .indent_size_for_line(MultiBufferRow(selection.start.row))
10113 .len,
10114 });
10115 }
10116 }
10117
10118 self.transact(window, cx, |this, window, cx| {
10119 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10120 s.select(selections);
10121 });
10122 this.insert("", window, cx);
10123 });
10124 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10125 }
10126
10127 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10128 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10129 let item = self.cut_common(window, cx);
10130 cx.write_to_clipboard(item);
10131 }
10132
10133 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10134 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10135 self.change_selections(None, window, cx, |s| {
10136 s.move_with(|snapshot, sel| {
10137 if sel.is_empty() {
10138 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10139 }
10140 });
10141 });
10142 let item = self.cut_common(window, cx);
10143 cx.set_global(KillRing(item))
10144 }
10145
10146 pub fn kill_ring_yank(
10147 &mut self,
10148 _: &KillRingYank,
10149 window: &mut Window,
10150 cx: &mut Context<Self>,
10151 ) {
10152 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10153 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10154 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10155 (kill_ring.text().to_string(), kill_ring.metadata_json())
10156 } else {
10157 return;
10158 }
10159 } else {
10160 return;
10161 };
10162 self.do_paste(&text, metadata, false, window, cx);
10163 }
10164
10165 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10166 self.do_copy(true, cx);
10167 }
10168
10169 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10170 self.do_copy(false, cx);
10171 }
10172
10173 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10174 let selections = self.selections.all::<Point>(cx);
10175 let buffer = self.buffer.read(cx).read(cx);
10176 let mut text = String::new();
10177
10178 let mut clipboard_selections = Vec::with_capacity(selections.len());
10179 {
10180 let max_point = buffer.max_point();
10181 let mut is_first = true;
10182 for selection in &selections {
10183 let mut start = selection.start;
10184 let mut end = selection.end;
10185 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10186 if is_entire_line {
10187 start = Point::new(start.row, 0);
10188 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10189 }
10190
10191 let mut trimmed_selections = Vec::new();
10192 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10193 let row = MultiBufferRow(start.row);
10194 let first_indent = buffer.indent_size_for_line(row);
10195 if first_indent.len == 0 || start.column > first_indent.len {
10196 trimmed_selections.push(start..end);
10197 } else {
10198 trimmed_selections.push(
10199 Point::new(row.0, first_indent.len)
10200 ..Point::new(row.0, buffer.line_len(row)),
10201 );
10202 for row in start.row + 1..=end.row {
10203 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10204 if row_indent_size.len >= first_indent.len {
10205 trimmed_selections.push(
10206 Point::new(row, first_indent.len)
10207 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10208 );
10209 } else {
10210 trimmed_selections.clear();
10211 trimmed_selections.push(start..end);
10212 break;
10213 }
10214 }
10215 }
10216 } else {
10217 trimmed_selections.push(start..end);
10218 }
10219
10220 for trimmed_range in trimmed_selections {
10221 if is_first {
10222 is_first = false;
10223 } else {
10224 text += "\n";
10225 }
10226 let mut len = 0;
10227 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10228 text.push_str(chunk);
10229 len += chunk.len();
10230 }
10231 clipboard_selections.push(ClipboardSelection {
10232 len,
10233 is_entire_line,
10234 first_line_indent: buffer
10235 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10236 .len,
10237 });
10238 }
10239 }
10240 }
10241
10242 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10243 text,
10244 clipboard_selections,
10245 ));
10246 }
10247
10248 pub fn do_paste(
10249 &mut self,
10250 text: &String,
10251 clipboard_selections: Option<Vec<ClipboardSelection>>,
10252 handle_entire_lines: bool,
10253 window: &mut Window,
10254 cx: &mut Context<Self>,
10255 ) {
10256 if self.read_only(cx) {
10257 return;
10258 }
10259
10260 let clipboard_text = Cow::Borrowed(text);
10261
10262 self.transact(window, cx, |this, window, cx| {
10263 if let Some(mut clipboard_selections) = clipboard_selections {
10264 let old_selections = this.selections.all::<usize>(cx);
10265 let all_selections_were_entire_line =
10266 clipboard_selections.iter().all(|s| s.is_entire_line);
10267 let first_selection_indent_column =
10268 clipboard_selections.first().map(|s| s.first_line_indent);
10269 if clipboard_selections.len() != old_selections.len() {
10270 clipboard_selections.drain(..);
10271 }
10272 let cursor_offset = this.selections.last::<usize>(cx).head();
10273 let mut auto_indent_on_paste = true;
10274
10275 this.buffer.update(cx, |buffer, cx| {
10276 let snapshot = buffer.read(cx);
10277 auto_indent_on_paste = snapshot
10278 .language_settings_at(cursor_offset, cx)
10279 .auto_indent_on_paste;
10280
10281 let mut start_offset = 0;
10282 let mut edits = Vec::new();
10283 let mut original_indent_columns = Vec::new();
10284 for (ix, selection) in old_selections.iter().enumerate() {
10285 let to_insert;
10286 let entire_line;
10287 let original_indent_column;
10288 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10289 let end_offset = start_offset + clipboard_selection.len;
10290 to_insert = &clipboard_text[start_offset..end_offset];
10291 entire_line = clipboard_selection.is_entire_line;
10292 start_offset = end_offset + 1;
10293 original_indent_column = Some(clipboard_selection.first_line_indent);
10294 } else {
10295 to_insert = clipboard_text.as_str();
10296 entire_line = all_selections_were_entire_line;
10297 original_indent_column = first_selection_indent_column
10298 }
10299
10300 // If the corresponding selection was empty when this slice of the
10301 // clipboard text was written, then the entire line containing the
10302 // selection was copied. If this selection is also currently empty,
10303 // then paste the line before the current line of the buffer.
10304 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10305 let column = selection.start.to_point(&snapshot).column as usize;
10306 let line_start = selection.start - column;
10307 line_start..line_start
10308 } else {
10309 selection.range()
10310 };
10311
10312 edits.push((range, to_insert));
10313 original_indent_columns.push(original_indent_column);
10314 }
10315 drop(snapshot);
10316
10317 buffer.edit(
10318 edits,
10319 if auto_indent_on_paste {
10320 Some(AutoindentMode::Block {
10321 original_indent_columns,
10322 })
10323 } else {
10324 None
10325 },
10326 cx,
10327 );
10328 });
10329
10330 let selections = this.selections.all::<usize>(cx);
10331 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10332 s.select(selections)
10333 });
10334 } else {
10335 this.insert(&clipboard_text, window, cx);
10336 }
10337 });
10338 }
10339
10340 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10341 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10342 if let Some(item) = cx.read_from_clipboard() {
10343 let entries = item.entries();
10344
10345 match entries.first() {
10346 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10347 // of all the pasted entries.
10348 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10349 .do_paste(
10350 clipboard_string.text(),
10351 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10352 true,
10353 window,
10354 cx,
10355 ),
10356 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10357 }
10358 }
10359 }
10360
10361 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10362 if self.read_only(cx) {
10363 return;
10364 }
10365
10366 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10367
10368 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10369 if let Some((selections, _)) =
10370 self.selection_history.transaction(transaction_id).cloned()
10371 {
10372 self.change_selections(None, window, cx, |s| {
10373 s.select_anchors(selections.to_vec());
10374 });
10375 } else {
10376 log::error!(
10377 "No entry in selection_history found for undo. \
10378 This may correspond to a bug where undo does not update the selection. \
10379 If this is occurring, please add details to \
10380 https://github.com/zed-industries/zed/issues/22692"
10381 );
10382 }
10383 self.request_autoscroll(Autoscroll::fit(), cx);
10384 self.unmark_text(window, cx);
10385 self.refresh_inline_completion(true, false, window, cx);
10386 cx.emit(EditorEvent::Edited { transaction_id });
10387 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10388 }
10389 }
10390
10391 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10392 if self.read_only(cx) {
10393 return;
10394 }
10395
10396 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10397
10398 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10399 if let Some((_, Some(selections))) =
10400 self.selection_history.transaction(transaction_id).cloned()
10401 {
10402 self.change_selections(None, window, cx, |s| {
10403 s.select_anchors(selections.to_vec());
10404 });
10405 } else {
10406 log::error!(
10407 "No entry in selection_history found for redo. \
10408 This may correspond to a bug where undo does not update the selection. \
10409 If this is occurring, please add details to \
10410 https://github.com/zed-industries/zed/issues/22692"
10411 );
10412 }
10413 self.request_autoscroll(Autoscroll::fit(), cx);
10414 self.unmark_text(window, cx);
10415 self.refresh_inline_completion(true, false, window, cx);
10416 cx.emit(EditorEvent::Edited { transaction_id });
10417 }
10418 }
10419
10420 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10421 self.buffer
10422 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10423 }
10424
10425 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10426 self.buffer
10427 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10428 }
10429
10430 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10431 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10432 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10433 s.move_with(|map, selection| {
10434 let cursor = if selection.is_empty() {
10435 movement::left(map, selection.start)
10436 } else {
10437 selection.start
10438 };
10439 selection.collapse_to(cursor, SelectionGoal::None);
10440 });
10441 })
10442 }
10443
10444 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10445 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10447 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10448 })
10449 }
10450
10451 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10452 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10453 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10454 s.move_with(|map, selection| {
10455 let cursor = if selection.is_empty() {
10456 movement::right(map, selection.end)
10457 } else {
10458 selection.end
10459 };
10460 selection.collapse_to(cursor, SelectionGoal::None)
10461 });
10462 })
10463 }
10464
10465 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10466 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10468 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10469 })
10470 }
10471
10472 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10473 if self.take_rename(true, window, cx).is_some() {
10474 return;
10475 }
10476
10477 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10478 cx.propagate();
10479 return;
10480 }
10481
10482 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10483
10484 let text_layout_details = &self.text_layout_details(window);
10485 let selection_count = self.selections.count();
10486 let first_selection = self.selections.first_anchor();
10487
10488 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10489 s.move_with(|map, selection| {
10490 if !selection.is_empty() {
10491 selection.goal = SelectionGoal::None;
10492 }
10493 let (cursor, goal) = movement::up(
10494 map,
10495 selection.start,
10496 selection.goal,
10497 false,
10498 text_layout_details,
10499 );
10500 selection.collapse_to(cursor, goal);
10501 });
10502 });
10503
10504 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10505 {
10506 cx.propagate();
10507 }
10508 }
10509
10510 pub fn move_up_by_lines(
10511 &mut self,
10512 action: &MoveUpByLines,
10513 window: &mut Window,
10514 cx: &mut Context<Self>,
10515 ) {
10516 if self.take_rename(true, window, cx).is_some() {
10517 return;
10518 }
10519
10520 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10521 cx.propagate();
10522 return;
10523 }
10524
10525 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10526
10527 let text_layout_details = &self.text_layout_details(window);
10528
10529 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10530 s.move_with(|map, selection| {
10531 if !selection.is_empty() {
10532 selection.goal = SelectionGoal::None;
10533 }
10534 let (cursor, goal) = movement::up_by_rows(
10535 map,
10536 selection.start,
10537 action.lines,
10538 selection.goal,
10539 false,
10540 text_layout_details,
10541 );
10542 selection.collapse_to(cursor, goal);
10543 });
10544 })
10545 }
10546
10547 pub fn move_down_by_lines(
10548 &mut self,
10549 action: &MoveDownByLines,
10550 window: &mut Window,
10551 cx: &mut Context<Self>,
10552 ) {
10553 if self.take_rename(true, window, cx).is_some() {
10554 return;
10555 }
10556
10557 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10558 cx.propagate();
10559 return;
10560 }
10561
10562 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10563
10564 let text_layout_details = &self.text_layout_details(window);
10565
10566 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10567 s.move_with(|map, selection| {
10568 if !selection.is_empty() {
10569 selection.goal = SelectionGoal::None;
10570 }
10571 let (cursor, goal) = movement::down_by_rows(
10572 map,
10573 selection.start,
10574 action.lines,
10575 selection.goal,
10576 false,
10577 text_layout_details,
10578 );
10579 selection.collapse_to(cursor, goal);
10580 });
10581 })
10582 }
10583
10584 pub fn select_down_by_lines(
10585 &mut self,
10586 action: &SelectDownByLines,
10587 window: &mut Window,
10588 cx: &mut Context<Self>,
10589 ) {
10590 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10591 let text_layout_details = &self.text_layout_details(window);
10592 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10593 s.move_heads_with(|map, head, goal| {
10594 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10595 })
10596 })
10597 }
10598
10599 pub fn select_up_by_lines(
10600 &mut self,
10601 action: &SelectUpByLines,
10602 window: &mut Window,
10603 cx: &mut Context<Self>,
10604 ) {
10605 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10606 let text_layout_details = &self.text_layout_details(window);
10607 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10608 s.move_heads_with(|map, head, goal| {
10609 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10610 })
10611 })
10612 }
10613
10614 pub fn select_page_up(
10615 &mut self,
10616 _: &SelectPageUp,
10617 window: &mut Window,
10618 cx: &mut Context<Self>,
10619 ) {
10620 let Some(row_count) = self.visible_row_count() else {
10621 return;
10622 };
10623
10624 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10625
10626 let text_layout_details = &self.text_layout_details(window);
10627
10628 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10629 s.move_heads_with(|map, head, goal| {
10630 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10631 })
10632 })
10633 }
10634
10635 pub fn move_page_up(
10636 &mut self,
10637 action: &MovePageUp,
10638 window: &mut Window,
10639 cx: &mut Context<Self>,
10640 ) {
10641 if self.take_rename(true, window, cx).is_some() {
10642 return;
10643 }
10644
10645 if self
10646 .context_menu
10647 .borrow_mut()
10648 .as_mut()
10649 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10650 .unwrap_or(false)
10651 {
10652 return;
10653 }
10654
10655 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10656 cx.propagate();
10657 return;
10658 }
10659
10660 let Some(row_count) = self.visible_row_count() else {
10661 return;
10662 };
10663
10664 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10665
10666 let autoscroll = if action.center_cursor {
10667 Autoscroll::center()
10668 } else {
10669 Autoscroll::fit()
10670 };
10671
10672 let text_layout_details = &self.text_layout_details(window);
10673
10674 self.change_selections(Some(autoscroll), window, cx, |s| {
10675 s.move_with(|map, selection| {
10676 if !selection.is_empty() {
10677 selection.goal = SelectionGoal::None;
10678 }
10679 let (cursor, goal) = movement::up_by_rows(
10680 map,
10681 selection.end,
10682 row_count,
10683 selection.goal,
10684 false,
10685 text_layout_details,
10686 );
10687 selection.collapse_to(cursor, goal);
10688 });
10689 });
10690 }
10691
10692 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10693 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10694 let text_layout_details = &self.text_layout_details(window);
10695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10696 s.move_heads_with(|map, head, goal| {
10697 movement::up(map, head, goal, false, text_layout_details)
10698 })
10699 })
10700 }
10701
10702 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10703 self.take_rename(true, window, cx);
10704
10705 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10706 cx.propagate();
10707 return;
10708 }
10709
10710 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10711
10712 let text_layout_details = &self.text_layout_details(window);
10713 let selection_count = self.selections.count();
10714 let first_selection = self.selections.first_anchor();
10715
10716 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10717 s.move_with(|map, selection| {
10718 if !selection.is_empty() {
10719 selection.goal = SelectionGoal::None;
10720 }
10721 let (cursor, goal) = movement::down(
10722 map,
10723 selection.end,
10724 selection.goal,
10725 false,
10726 text_layout_details,
10727 );
10728 selection.collapse_to(cursor, goal);
10729 });
10730 });
10731
10732 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10733 {
10734 cx.propagate();
10735 }
10736 }
10737
10738 pub fn select_page_down(
10739 &mut self,
10740 _: &SelectPageDown,
10741 window: &mut Window,
10742 cx: &mut Context<Self>,
10743 ) {
10744 let Some(row_count) = self.visible_row_count() else {
10745 return;
10746 };
10747
10748 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10749
10750 let text_layout_details = &self.text_layout_details(window);
10751
10752 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10753 s.move_heads_with(|map, head, goal| {
10754 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10755 })
10756 })
10757 }
10758
10759 pub fn move_page_down(
10760 &mut self,
10761 action: &MovePageDown,
10762 window: &mut Window,
10763 cx: &mut Context<Self>,
10764 ) {
10765 if self.take_rename(true, window, cx).is_some() {
10766 return;
10767 }
10768
10769 if self
10770 .context_menu
10771 .borrow_mut()
10772 .as_mut()
10773 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10774 .unwrap_or(false)
10775 {
10776 return;
10777 }
10778
10779 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10780 cx.propagate();
10781 return;
10782 }
10783
10784 let Some(row_count) = self.visible_row_count() else {
10785 return;
10786 };
10787
10788 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10789
10790 let autoscroll = if action.center_cursor {
10791 Autoscroll::center()
10792 } else {
10793 Autoscroll::fit()
10794 };
10795
10796 let text_layout_details = &self.text_layout_details(window);
10797 self.change_selections(Some(autoscroll), window, cx, |s| {
10798 s.move_with(|map, selection| {
10799 if !selection.is_empty() {
10800 selection.goal = SelectionGoal::None;
10801 }
10802 let (cursor, goal) = movement::down_by_rows(
10803 map,
10804 selection.end,
10805 row_count,
10806 selection.goal,
10807 false,
10808 text_layout_details,
10809 );
10810 selection.collapse_to(cursor, goal);
10811 });
10812 });
10813 }
10814
10815 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10816 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10817 let text_layout_details = &self.text_layout_details(window);
10818 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10819 s.move_heads_with(|map, head, goal| {
10820 movement::down(map, head, goal, false, text_layout_details)
10821 })
10822 });
10823 }
10824
10825 pub fn context_menu_first(
10826 &mut self,
10827 _: &ContextMenuFirst,
10828 _window: &mut Window,
10829 cx: &mut Context<Self>,
10830 ) {
10831 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10832 context_menu.select_first(self.completion_provider.as_deref(), cx);
10833 }
10834 }
10835
10836 pub fn context_menu_prev(
10837 &mut self,
10838 _: &ContextMenuPrevious,
10839 _window: &mut Window,
10840 cx: &mut Context<Self>,
10841 ) {
10842 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10843 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10844 }
10845 }
10846
10847 pub fn context_menu_next(
10848 &mut self,
10849 _: &ContextMenuNext,
10850 _window: &mut Window,
10851 cx: &mut Context<Self>,
10852 ) {
10853 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10854 context_menu.select_next(self.completion_provider.as_deref(), cx);
10855 }
10856 }
10857
10858 pub fn context_menu_last(
10859 &mut self,
10860 _: &ContextMenuLast,
10861 _window: &mut Window,
10862 cx: &mut Context<Self>,
10863 ) {
10864 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10865 context_menu.select_last(self.completion_provider.as_deref(), cx);
10866 }
10867 }
10868
10869 pub fn move_to_previous_word_start(
10870 &mut self,
10871 _: &MoveToPreviousWordStart,
10872 window: &mut Window,
10873 cx: &mut Context<Self>,
10874 ) {
10875 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10876 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10877 s.move_cursors_with(|map, head, _| {
10878 (
10879 movement::previous_word_start(map, head),
10880 SelectionGoal::None,
10881 )
10882 });
10883 })
10884 }
10885
10886 pub fn move_to_previous_subword_start(
10887 &mut self,
10888 _: &MoveToPreviousSubwordStart,
10889 window: &mut Window,
10890 cx: &mut Context<Self>,
10891 ) {
10892 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10894 s.move_cursors_with(|map, head, _| {
10895 (
10896 movement::previous_subword_start(map, head),
10897 SelectionGoal::None,
10898 )
10899 });
10900 })
10901 }
10902
10903 pub fn select_to_previous_word_start(
10904 &mut self,
10905 _: &SelectToPreviousWordStart,
10906 window: &mut Window,
10907 cx: &mut Context<Self>,
10908 ) {
10909 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10910 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10911 s.move_heads_with(|map, head, _| {
10912 (
10913 movement::previous_word_start(map, head),
10914 SelectionGoal::None,
10915 )
10916 });
10917 })
10918 }
10919
10920 pub fn select_to_previous_subword_start(
10921 &mut self,
10922 _: &SelectToPreviousSubwordStart,
10923 window: &mut Window,
10924 cx: &mut Context<Self>,
10925 ) {
10926 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10927 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10928 s.move_heads_with(|map, head, _| {
10929 (
10930 movement::previous_subword_start(map, head),
10931 SelectionGoal::None,
10932 )
10933 });
10934 })
10935 }
10936
10937 pub fn delete_to_previous_word_start(
10938 &mut self,
10939 action: &DeleteToPreviousWordStart,
10940 window: &mut Window,
10941 cx: &mut Context<Self>,
10942 ) {
10943 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10944 self.transact(window, cx, |this, window, cx| {
10945 this.select_autoclose_pair(window, cx);
10946 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947 s.move_with(|map, selection| {
10948 if selection.is_empty() {
10949 let cursor = if action.ignore_newlines {
10950 movement::previous_word_start(map, selection.head())
10951 } else {
10952 movement::previous_word_start_or_newline(map, selection.head())
10953 };
10954 selection.set_head(cursor, SelectionGoal::None);
10955 }
10956 });
10957 });
10958 this.insert("", window, cx);
10959 });
10960 }
10961
10962 pub fn delete_to_previous_subword_start(
10963 &mut self,
10964 _: &DeleteToPreviousSubwordStart,
10965 window: &mut Window,
10966 cx: &mut Context<Self>,
10967 ) {
10968 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10969 self.transact(window, cx, |this, window, cx| {
10970 this.select_autoclose_pair(window, cx);
10971 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10972 s.move_with(|map, selection| {
10973 if selection.is_empty() {
10974 let cursor = movement::previous_subword_start(map, selection.head());
10975 selection.set_head(cursor, SelectionGoal::None);
10976 }
10977 });
10978 });
10979 this.insert("", window, cx);
10980 });
10981 }
10982
10983 pub fn move_to_next_word_end(
10984 &mut self,
10985 _: &MoveToNextWordEnd,
10986 window: &mut Window,
10987 cx: &mut Context<Self>,
10988 ) {
10989 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10990 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10991 s.move_cursors_with(|map, head, _| {
10992 (movement::next_word_end(map, head), SelectionGoal::None)
10993 });
10994 })
10995 }
10996
10997 pub fn move_to_next_subword_end(
10998 &mut self,
10999 _: &MoveToNextSubwordEnd,
11000 window: &mut Window,
11001 cx: &mut Context<Self>,
11002 ) {
11003 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11004 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11005 s.move_cursors_with(|map, head, _| {
11006 (movement::next_subword_end(map, head), SelectionGoal::None)
11007 });
11008 })
11009 }
11010
11011 pub fn select_to_next_word_end(
11012 &mut self,
11013 _: &SelectToNextWordEnd,
11014 window: &mut Window,
11015 cx: &mut Context<Self>,
11016 ) {
11017 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11018 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11019 s.move_heads_with(|map, head, _| {
11020 (movement::next_word_end(map, head), SelectionGoal::None)
11021 });
11022 })
11023 }
11024
11025 pub fn select_to_next_subword_end(
11026 &mut self,
11027 _: &SelectToNextSubwordEnd,
11028 window: &mut Window,
11029 cx: &mut Context<Self>,
11030 ) {
11031 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11032 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11033 s.move_heads_with(|map, head, _| {
11034 (movement::next_subword_end(map, head), SelectionGoal::None)
11035 });
11036 })
11037 }
11038
11039 pub fn delete_to_next_word_end(
11040 &mut self,
11041 action: &DeleteToNextWordEnd,
11042 window: &mut Window,
11043 cx: &mut Context<Self>,
11044 ) {
11045 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11046 self.transact(window, cx, |this, window, cx| {
11047 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11048 s.move_with(|map, selection| {
11049 if selection.is_empty() {
11050 let cursor = if action.ignore_newlines {
11051 movement::next_word_end(map, selection.head())
11052 } else {
11053 movement::next_word_end_or_newline(map, selection.head())
11054 };
11055 selection.set_head(cursor, SelectionGoal::None);
11056 }
11057 });
11058 });
11059 this.insert("", window, cx);
11060 });
11061 }
11062
11063 pub fn delete_to_next_subword_end(
11064 &mut self,
11065 _: &DeleteToNextSubwordEnd,
11066 window: &mut Window,
11067 cx: &mut Context<Self>,
11068 ) {
11069 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11070 self.transact(window, cx, |this, window, cx| {
11071 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11072 s.move_with(|map, selection| {
11073 if selection.is_empty() {
11074 let cursor = movement::next_subword_end(map, selection.head());
11075 selection.set_head(cursor, SelectionGoal::None);
11076 }
11077 });
11078 });
11079 this.insert("", window, cx);
11080 });
11081 }
11082
11083 pub fn move_to_beginning_of_line(
11084 &mut self,
11085 action: &MoveToBeginningOfLine,
11086 window: &mut Window,
11087 cx: &mut Context<Self>,
11088 ) {
11089 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11091 s.move_cursors_with(|map, head, _| {
11092 (
11093 movement::indented_line_beginning(
11094 map,
11095 head,
11096 action.stop_at_soft_wraps,
11097 action.stop_at_indent,
11098 ),
11099 SelectionGoal::None,
11100 )
11101 });
11102 })
11103 }
11104
11105 pub fn select_to_beginning_of_line(
11106 &mut self,
11107 action: &SelectToBeginningOfLine,
11108 window: &mut Window,
11109 cx: &mut Context<Self>,
11110 ) {
11111 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11112 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11113 s.move_heads_with(|map, head, _| {
11114 (
11115 movement::indented_line_beginning(
11116 map,
11117 head,
11118 action.stop_at_soft_wraps,
11119 action.stop_at_indent,
11120 ),
11121 SelectionGoal::None,
11122 )
11123 });
11124 });
11125 }
11126
11127 pub fn delete_to_beginning_of_line(
11128 &mut self,
11129 action: &DeleteToBeginningOfLine,
11130 window: &mut Window,
11131 cx: &mut Context<Self>,
11132 ) {
11133 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11134 self.transact(window, cx, |this, window, cx| {
11135 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11136 s.move_with(|_, selection| {
11137 selection.reversed = true;
11138 });
11139 });
11140
11141 this.select_to_beginning_of_line(
11142 &SelectToBeginningOfLine {
11143 stop_at_soft_wraps: false,
11144 stop_at_indent: action.stop_at_indent,
11145 },
11146 window,
11147 cx,
11148 );
11149 this.backspace(&Backspace, window, cx);
11150 });
11151 }
11152
11153 pub fn move_to_end_of_line(
11154 &mut self,
11155 action: &MoveToEndOfLine,
11156 window: &mut Window,
11157 cx: &mut Context<Self>,
11158 ) {
11159 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11160 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11161 s.move_cursors_with(|map, head, _| {
11162 (
11163 movement::line_end(map, head, action.stop_at_soft_wraps),
11164 SelectionGoal::None,
11165 )
11166 });
11167 })
11168 }
11169
11170 pub fn select_to_end_of_line(
11171 &mut self,
11172 action: &SelectToEndOfLine,
11173 window: &mut Window,
11174 cx: &mut Context<Self>,
11175 ) {
11176 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11177 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11178 s.move_heads_with(|map, head, _| {
11179 (
11180 movement::line_end(map, head, action.stop_at_soft_wraps),
11181 SelectionGoal::None,
11182 )
11183 });
11184 })
11185 }
11186
11187 pub fn delete_to_end_of_line(
11188 &mut self,
11189 _: &DeleteToEndOfLine,
11190 window: &mut Window,
11191 cx: &mut Context<Self>,
11192 ) {
11193 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11194 self.transact(window, cx, |this, window, cx| {
11195 this.select_to_end_of_line(
11196 &SelectToEndOfLine {
11197 stop_at_soft_wraps: false,
11198 },
11199 window,
11200 cx,
11201 );
11202 this.delete(&Delete, window, cx);
11203 });
11204 }
11205
11206 pub fn cut_to_end_of_line(
11207 &mut self,
11208 _: &CutToEndOfLine,
11209 window: &mut Window,
11210 cx: &mut Context<Self>,
11211 ) {
11212 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11213 self.transact(window, cx, |this, window, cx| {
11214 this.select_to_end_of_line(
11215 &SelectToEndOfLine {
11216 stop_at_soft_wraps: false,
11217 },
11218 window,
11219 cx,
11220 );
11221 this.cut(&Cut, window, cx);
11222 });
11223 }
11224
11225 pub fn move_to_start_of_paragraph(
11226 &mut self,
11227 _: &MoveToStartOfParagraph,
11228 window: &mut Window,
11229 cx: &mut Context<Self>,
11230 ) {
11231 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11232 cx.propagate();
11233 return;
11234 }
11235 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11236 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11237 s.move_with(|map, selection| {
11238 selection.collapse_to(
11239 movement::start_of_paragraph(map, selection.head(), 1),
11240 SelectionGoal::None,
11241 )
11242 });
11243 })
11244 }
11245
11246 pub fn move_to_end_of_paragraph(
11247 &mut self,
11248 _: &MoveToEndOfParagraph,
11249 window: &mut Window,
11250 cx: &mut Context<Self>,
11251 ) {
11252 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11253 cx.propagate();
11254 return;
11255 }
11256 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11257 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11258 s.move_with(|map, selection| {
11259 selection.collapse_to(
11260 movement::end_of_paragraph(map, selection.head(), 1),
11261 SelectionGoal::None,
11262 )
11263 });
11264 })
11265 }
11266
11267 pub fn select_to_start_of_paragraph(
11268 &mut self,
11269 _: &SelectToStartOfParagraph,
11270 window: &mut Window,
11271 cx: &mut Context<Self>,
11272 ) {
11273 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11274 cx.propagate();
11275 return;
11276 }
11277 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11279 s.move_heads_with(|map, head, _| {
11280 (
11281 movement::start_of_paragraph(map, head, 1),
11282 SelectionGoal::None,
11283 )
11284 });
11285 })
11286 }
11287
11288 pub fn select_to_end_of_paragraph(
11289 &mut self,
11290 _: &SelectToEndOfParagraph,
11291 window: &mut Window,
11292 cx: &mut Context<Self>,
11293 ) {
11294 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11295 cx.propagate();
11296 return;
11297 }
11298 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11299 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11300 s.move_heads_with(|map, head, _| {
11301 (
11302 movement::end_of_paragraph(map, head, 1),
11303 SelectionGoal::None,
11304 )
11305 });
11306 })
11307 }
11308
11309 pub fn move_to_start_of_excerpt(
11310 &mut self,
11311 _: &MoveToStartOfExcerpt,
11312 window: &mut Window,
11313 cx: &mut Context<Self>,
11314 ) {
11315 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11316 cx.propagate();
11317 return;
11318 }
11319 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11320 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11321 s.move_with(|map, selection| {
11322 selection.collapse_to(
11323 movement::start_of_excerpt(
11324 map,
11325 selection.head(),
11326 workspace::searchable::Direction::Prev,
11327 ),
11328 SelectionGoal::None,
11329 )
11330 });
11331 })
11332 }
11333
11334 pub fn move_to_start_of_next_excerpt(
11335 &mut self,
11336 _: &MoveToStartOfNextExcerpt,
11337 window: &mut Window,
11338 cx: &mut Context<Self>,
11339 ) {
11340 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11341 cx.propagate();
11342 return;
11343 }
11344
11345 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11346 s.move_with(|map, selection| {
11347 selection.collapse_to(
11348 movement::start_of_excerpt(
11349 map,
11350 selection.head(),
11351 workspace::searchable::Direction::Next,
11352 ),
11353 SelectionGoal::None,
11354 )
11355 });
11356 })
11357 }
11358
11359 pub fn move_to_end_of_excerpt(
11360 &mut self,
11361 _: &MoveToEndOfExcerpt,
11362 window: &mut Window,
11363 cx: &mut Context<Self>,
11364 ) {
11365 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11366 cx.propagate();
11367 return;
11368 }
11369 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11370 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11371 s.move_with(|map, selection| {
11372 selection.collapse_to(
11373 movement::end_of_excerpt(
11374 map,
11375 selection.head(),
11376 workspace::searchable::Direction::Next,
11377 ),
11378 SelectionGoal::None,
11379 )
11380 });
11381 })
11382 }
11383
11384 pub fn move_to_end_of_previous_excerpt(
11385 &mut self,
11386 _: &MoveToEndOfPreviousExcerpt,
11387 window: &mut Window,
11388 cx: &mut Context<Self>,
11389 ) {
11390 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11391 cx.propagate();
11392 return;
11393 }
11394 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11395 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11396 s.move_with(|map, selection| {
11397 selection.collapse_to(
11398 movement::end_of_excerpt(
11399 map,
11400 selection.head(),
11401 workspace::searchable::Direction::Prev,
11402 ),
11403 SelectionGoal::None,
11404 )
11405 });
11406 })
11407 }
11408
11409 pub fn select_to_start_of_excerpt(
11410 &mut self,
11411 _: &SelectToStartOfExcerpt,
11412 window: &mut Window,
11413 cx: &mut Context<Self>,
11414 ) {
11415 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11416 cx.propagate();
11417 return;
11418 }
11419 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11421 s.move_heads_with(|map, head, _| {
11422 (
11423 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11424 SelectionGoal::None,
11425 )
11426 });
11427 })
11428 }
11429
11430 pub fn select_to_start_of_next_excerpt(
11431 &mut self,
11432 _: &SelectToStartOfNextExcerpt,
11433 window: &mut Window,
11434 cx: &mut Context<Self>,
11435 ) {
11436 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11437 cx.propagate();
11438 return;
11439 }
11440 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11441 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11442 s.move_heads_with(|map, head, _| {
11443 (
11444 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11445 SelectionGoal::None,
11446 )
11447 });
11448 })
11449 }
11450
11451 pub fn select_to_end_of_excerpt(
11452 &mut self,
11453 _: &SelectToEndOfExcerpt,
11454 window: &mut Window,
11455 cx: &mut Context<Self>,
11456 ) {
11457 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11458 cx.propagate();
11459 return;
11460 }
11461 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11462 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11463 s.move_heads_with(|map, head, _| {
11464 (
11465 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11466 SelectionGoal::None,
11467 )
11468 });
11469 })
11470 }
11471
11472 pub fn select_to_end_of_previous_excerpt(
11473 &mut self,
11474 _: &SelectToEndOfPreviousExcerpt,
11475 window: &mut Window,
11476 cx: &mut Context<Self>,
11477 ) {
11478 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11479 cx.propagate();
11480 return;
11481 }
11482 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11483 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11484 s.move_heads_with(|map, head, _| {
11485 (
11486 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11487 SelectionGoal::None,
11488 )
11489 });
11490 })
11491 }
11492
11493 pub fn move_to_beginning(
11494 &mut self,
11495 _: &MoveToBeginning,
11496 window: &mut Window,
11497 cx: &mut Context<Self>,
11498 ) {
11499 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11500 cx.propagate();
11501 return;
11502 }
11503 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11504 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11505 s.select_ranges(vec![0..0]);
11506 });
11507 }
11508
11509 pub fn select_to_beginning(
11510 &mut self,
11511 _: &SelectToBeginning,
11512 window: &mut Window,
11513 cx: &mut Context<Self>,
11514 ) {
11515 let mut selection = self.selections.last::<Point>(cx);
11516 selection.set_head(Point::zero(), SelectionGoal::None);
11517 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11519 s.select(vec![selection]);
11520 });
11521 }
11522
11523 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11524 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11525 cx.propagate();
11526 return;
11527 }
11528 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11529 let cursor = self.buffer.read(cx).read(cx).len();
11530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531 s.select_ranges(vec![cursor..cursor])
11532 });
11533 }
11534
11535 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11536 self.nav_history = nav_history;
11537 }
11538
11539 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11540 self.nav_history.as_ref()
11541 }
11542
11543 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11544 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11545 }
11546
11547 fn push_to_nav_history(
11548 &mut self,
11549 cursor_anchor: Anchor,
11550 new_position: Option<Point>,
11551 is_deactivate: bool,
11552 cx: &mut Context<Self>,
11553 ) {
11554 if let Some(nav_history) = self.nav_history.as_mut() {
11555 let buffer = self.buffer.read(cx).read(cx);
11556 let cursor_position = cursor_anchor.to_point(&buffer);
11557 let scroll_state = self.scroll_manager.anchor();
11558 let scroll_top_row = scroll_state.top_row(&buffer);
11559 drop(buffer);
11560
11561 if let Some(new_position) = new_position {
11562 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11563 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11564 return;
11565 }
11566 }
11567
11568 nav_history.push(
11569 Some(NavigationData {
11570 cursor_anchor,
11571 cursor_position,
11572 scroll_anchor: scroll_state,
11573 scroll_top_row,
11574 }),
11575 cx,
11576 );
11577 cx.emit(EditorEvent::PushedToNavHistory {
11578 anchor: cursor_anchor,
11579 is_deactivate,
11580 })
11581 }
11582 }
11583
11584 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11585 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11586 let buffer = self.buffer.read(cx).snapshot(cx);
11587 let mut selection = self.selections.first::<usize>(cx);
11588 selection.set_head(buffer.len(), SelectionGoal::None);
11589 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11590 s.select(vec![selection]);
11591 });
11592 }
11593
11594 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11595 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11596 let end = self.buffer.read(cx).read(cx).len();
11597 self.change_selections(None, window, cx, |s| {
11598 s.select_ranges(vec![0..end]);
11599 });
11600 }
11601
11602 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11603 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11604 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11605 let mut selections = self.selections.all::<Point>(cx);
11606 let max_point = display_map.buffer_snapshot.max_point();
11607 for selection in &mut selections {
11608 let rows = selection.spanned_rows(true, &display_map);
11609 selection.start = Point::new(rows.start.0, 0);
11610 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11611 selection.reversed = false;
11612 }
11613 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11614 s.select(selections);
11615 });
11616 }
11617
11618 pub fn split_selection_into_lines(
11619 &mut self,
11620 _: &SplitSelectionIntoLines,
11621 window: &mut Window,
11622 cx: &mut Context<Self>,
11623 ) {
11624 let selections = self
11625 .selections
11626 .all::<Point>(cx)
11627 .into_iter()
11628 .map(|selection| selection.start..selection.end)
11629 .collect::<Vec<_>>();
11630 self.unfold_ranges(&selections, true, true, cx);
11631
11632 let mut new_selection_ranges = Vec::new();
11633 {
11634 let buffer = self.buffer.read(cx).read(cx);
11635 for selection in selections {
11636 for row in selection.start.row..selection.end.row {
11637 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11638 new_selection_ranges.push(cursor..cursor);
11639 }
11640
11641 let is_multiline_selection = selection.start.row != selection.end.row;
11642 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11643 // so this action feels more ergonomic when paired with other selection operations
11644 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11645 if !should_skip_last {
11646 new_selection_ranges.push(selection.end..selection.end);
11647 }
11648 }
11649 }
11650 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11651 s.select_ranges(new_selection_ranges);
11652 });
11653 }
11654
11655 pub fn add_selection_above(
11656 &mut self,
11657 _: &AddSelectionAbove,
11658 window: &mut Window,
11659 cx: &mut Context<Self>,
11660 ) {
11661 self.add_selection(true, window, cx);
11662 }
11663
11664 pub fn add_selection_below(
11665 &mut self,
11666 _: &AddSelectionBelow,
11667 window: &mut Window,
11668 cx: &mut Context<Self>,
11669 ) {
11670 self.add_selection(false, window, cx);
11671 }
11672
11673 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11674 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11675
11676 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11677 let mut selections = self.selections.all::<Point>(cx);
11678 let text_layout_details = self.text_layout_details(window);
11679 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11680 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11681 let range = oldest_selection.display_range(&display_map).sorted();
11682
11683 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11684 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11685 let positions = start_x.min(end_x)..start_x.max(end_x);
11686
11687 selections.clear();
11688 let mut stack = Vec::new();
11689 for row in range.start.row().0..=range.end.row().0 {
11690 if let Some(selection) = self.selections.build_columnar_selection(
11691 &display_map,
11692 DisplayRow(row),
11693 &positions,
11694 oldest_selection.reversed,
11695 &text_layout_details,
11696 ) {
11697 stack.push(selection.id);
11698 selections.push(selection);
11699 }
11700 }
11701
11702 if above {
11703 stack.reverse();
11704 }
11705
11706 AddSelectionsState { above, stack }
11707 });
11708
11709 let last_added_selection = *state.stack.last().unwrap();
11710 let mut new_selections = Vec::new();
11711 if above == state.above {
11712 let end_row = if above {
11713 DisplayRow(0)
11714 } else {
11715 display_map.max_point().row()
11716 };
11717
11718 'outer: for selection in selections {
11719 if selection.id == last_added_selection {
11720 let range = selection.display_range(&display_map).sorted();
11721 debug_assert_eq!(range.start.row(), range.end.row());
11722 let mut row = range.start.row();
11723 let positions =
11724 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11725 px(start)..px(end)
11726 } else {
11727 let start_x =
11728 display_map.x_for_display_point(range.start, &text_layout_details);
11729 let end_x =
11730 display_map.x_for_display_point(range.end, &text_layout_details);
11731 start_x.min(end_x)..start_x.max(end_x)
11732 };
11733
11734 while row != end_row {
11735 if above {
11736 row.0 -= 1;
11737 } else {
11738 row.0 += 1;
11739 }
11740
11741 if let Some(new_selection) = self.selections.build_columnar_selection(
11742 &display_map,
11743 row,
11744 &positions,
11745 selection.reversed,
11746 &text_layout_details,
11747 ) {
11748 state.stack.push(new_selection.id);
11749 if above {
11750 new_selections.push(new_selection);
11751 new_selections.push(selection);
11752 } else {
11753 new_selections.push(selection);
11754 new_selections.push(new_selection);
11755 }
11756
11757 continue 'outer;
11758 }
11759 }
11760 }
11761
11762 new_selections.push(selection);
11763 }
11764 } else {
11765 new_selections = selections;
11766 new_selections.retain(|s| s.id != last_added_selection);
11767 state.stack.pop();
11768 }
11769
11770 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11771 s.select(new_selections);
11772 });
11773 if state.stack.len() > 1 {
11774 self.add_selections_state = Some(state);
11775 }
11776 }
11777
11778 pub fn select_next_match_internal(
11779 &mut self,
11780 display_map: &DisplaySnapshot,
11781 replace_newest: bool,
11782 autoscroll: Option<Autoscroll>,
11783 window: &mut Window,
11784 cx: &mut Context<Self>,
11785 ) -> Result<()> {
11786 fn select_next_match_ranges(
11787 this: &mut Editor,
11788 range: Range<usize>,
11789 replace_newest: bool,
11790 auto_scroll: Option<Autoscroll>,
11791 window: &mut Window,
11792 cx: &mut Context<Editor>,
11793 ) {
11794 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11795 this.change_selections(auto_scroll, window, cx, |s| {
11796 if replace_newest {
11797 s.delete(s.newest_anchor().id);
11798 }
11799 s.insert_range(range.clone());
11800 });
11801 }
11802
11803 let buffer = &display_map.buffer_snapshot;
11804 let mut selections = self.selections.all::<usize>(cx);
11805 if let Some(mut select_next_state) = self.select_next_state.take() {
11806 let query = &select_next_state.query;
11807 if !select_next_state.done {
11808 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11809 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11810 let mut next_selected_range = None;
11811
11812 let bytes_after_last_selection =
11813 buffer.bytes_in_range(last_selection.end..buffer.len());
11814 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11815 let query_matches = query
11816 .stream_find_iter(bytes_after_last_selection)
11817 .map(|result| (last_selection.end, result))
11818 .chain(
11819 query
11820 .stream_find_iter(bytes_before_first_selection)
11821 .map(|result| (0, result)),
11822 );
11823
11824 for (start_offset, query_match) in query_matches {
11825 let query_match = query_match.unwrap(); // can only fail due to I/O
11826 let offset_range =
11827 start_offset + query_match.start()..start_offset + query_match.end();
11828 let display_range = offset_range.start.to_display_point(display_map)
11829 ..offset_range.end.to_display_point(display_map);
11830
11831 if !select_next_state.wordwise
11832 || (!movement::is_inside_word(display_map, display_range.start)
11833 && !movement::is_inside_word(display_map, display_range.end))
11834 {
11835 // TODO: This is n^2, because we might check all the selections
11836 if !selections
11837 .iter()
11838 .any(|selection| selection.range().overlaps(&offset_range))
11839 {
11840 next_selected_range = Some(offset_range);
11841 break;
11842 }
11843 }
11844 }
11845
11846 if let Some(next_selected_range) = next_selected_range {
11847 select_next_match_ranges(
11848 self,
11849 next_selected_range,
11850 replace_newest,
11851 autoscroll,
11852 window,
11853 cx,
11854 );
11855 } else {
11856 select_next_state.done = true;
11857 }
11858 }
11859
11860 self.select_next_state = Some(select_next_state);
11861 } else {
11862 let mut only_carets = true;
11863 let mut same_text_selected = true;
11864 let mut selected_text = None;
11865
11866 let mut selections_iter = selections.iter().peekable();
11867 while let Some(selection) = selections_iter.next() {
11868 if selection.start != selection.end {
11869 only_carets = false;
11870 }
11871
11872 if same_text_selected {
11873 if selected_text.is_none() {
11874 selected_text =
11875 Some(buffer.text_for_range(selection.range()).collect::<String>());
11876 }
11877
11878 if let Some(next_selection) = selections_iter.peek() {
11879 if next_selection.range().len() == selection.range().len() {
11880 let next_selected_text = buffer
11881 .text_for_range(next_selection.range())
11882 .collect::<String>();
11883 if Some(next_selected_text) != selected_text {
11884 same_text_selected = false;
11885 selected_text = None;
11886 }
11887 } else {
11888 same_text_selected = false;
11889 selected_text = None;
11890 }
11891 }
11892 }
11893 }
11894
11895 if only_carets {
11896 for selection in &mut selections {
11897 let word_range = movement::surrounding_word(
11898 display_map,
11899 selection.start.to_display_point(display_map),
11900 );
11901 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11902 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11903 selection.goal = SelectionGoal::None;
11904 selection.reversed = false;
11905 select_next_match_ranges(
11906 self,
11907 selection.start..selection.end,
11908 replace_newest,
11909 autoscroll,
11910 window,
11911 cx,
11912 );
11913 }
11914
11915 if selections.len() == 1 {
11916 let selection = selections
11917 .last()
11918 .expect("ensured that there's only one selection");
11919 let query = buffer
11920 .text_for_range(selection.start..selection.end)
11921 .collect::<String>();
11922 let is_empty = query.is_empty();
11923 let select_state = SelectNextState {
11924 query: AhoCorasick::new(&[query])?,
11925 wordwise: true,
11926 done: is_empty,
11927 };
11928 self.select_next_state = Some(select_state);
11929 } else {
11930 self.select_next_state = None;
11931 }
11932 } else if let Some(selected_text) = selected_text {
11933 self.select_next_state = Some(SelectNextState {
11934 query: AhoCorasick::new(&[selected_text])?,
11935 wordwise: false,
11936 done: false,
11937 });
11938 self.select_next_match_internal(
11939 display_map,
11940 replace_newest,
11941 autoscroll,
11942 window,
11943 cx,
11944 )?;
11945 }
11946 }
11947 Ok(())
11948 }
11949
11950 pub fn select_all_matches(
11951 &mut self,
11952 _action: &SelectAllMatches,
11953 window: &mut Window,
11954 cx: &mut Context<Self>,
11955 ) -> Result<()> {
11956 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11957
11958 self.push_to_selection_history();
11959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11960
11961 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11962 let Some(select_next_state) = self.select_next_state.as_mut() else {
11963 return Ok(());
11964 };
11965 if select_next_state.done {
11966 return Ok(());
11967 }
11968
11969 let mut new_selections = Vec::new();
11970
11971 let reversed = self.selections.oldest::<usize>(cx).reversed;
11972 let buffer = &display_map.buffer_snapshot;
11973 let query_matches = select_next_state
11974 .query
11975 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11976
11977 for query_match in query_matches.into_iter() {
11978 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11979 let offset_range = if reversed {
11980 query_match.end()..query_match.start()
11981 } else {
11982 query_match.start()..query_match.end()
11983 };
11984 let display_range = offset_range.start.to_display_point(&display_map)
11985 ..offset_range.end.to_display_point(&display_map);
11986
11987 if !select_next_state.wordwise
11988 || (!movement::is_inside_word(&display_map, display_range.start)
11989 && !movement::is_inside_word(&display_map, display_range.end))
11990 {
11991 new_selections.push(offset_range.start..offset_range.end);
11992 }
11993 }
11994
11995 select_next_state.done = true;
11996 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11997 self.change_selections(None, window, cx, |selections| {
11998 selections.select_ranges(new_selections)
11999 });
12000
12001 Ok(())
12002 }
12003
12004 pub fn select_next(
12005 &mut self,
12006 action: &SelectNext,
12007 window: &mut Window,
12008 cx: &mut Context<Self>,
12009 ) -> Result<()> {
12010 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12011 self.push_to_selection_history();
12012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12013 self.select_next_match_internal(
12014 &display_map,
12015 action.replace_newest,
12016 Some(Autoscroll::newest()),
12017 window,
12018 cx,
12019 )?;
12020 Ok(())
12021 }
12022
12023 pub fn select_previous(
12024 &mut self,
12025 action: &SelectPrevious,
12026 window: &mut Window,
12027 cx: &mut Context<Self>,
12028 ) -> Result<()> {
12029 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12030 self.push_to_selection_history();
12031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12032 let buffer = &display_map.buffer_snapshot;
12033 let mut selections = self.selections.all::<usize>(cx);
12034 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12035 let query = &select_prev_state.query;
12036 if !select_prev_state.done {
12037 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12038 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12039 let mut next_selected_range = None;
12040 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12041 let bytes_before_last_selection =
12042 buffer.reversed_bytes_in_range(0..last_selection.start);
12043 let bytes_after_first_selection =
12044 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12045 let query_matches = query
12046 .stream_find_iter(bytes_before_last_selection)
12047 .map(|result| (last_selection.start, result))
12048 .chain(
12049 query
12050 .stream_find_iter(bytes_after_first_selection)
12051 .map(|result| (buffer.len(), result)),
12052 );
12053 for (end_offset, query_match) in query_matches {
12054 let query_match = query_match.unwrap(); // can only fail due to I/O
12055 let offset_range =
12056 end_offset - query_match.end()..end_offset - query_match.start();
12057 let display_range = offset_range.start.to_display_point(&display_map)
12058 ..offset_range.end.to_display_point(&display_map);
12059
12060 if !select_prev_state.wordwise
12061 || (!movement::is_inside_word(&display_map, display_range.start)
12062 && !movement::is_inside_word(&display_map, display_range.end))
12063 {
12064 next_selected_range = Some(offset_range);
12065 break;
12066 }
12067 }
12068
12069 if let Some(next_selected_range) = next_selected_range {
12070 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12071 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12072 if action.replace_newest {
12073 s.delete(s.newest_anchor().id);
12074 }
12075 s.insert_range(next_selected_range);
12076 });
12077 } else {
12078 select_prev_state.done = true;
12079 }
12080 }
12081
12082 self.select_prev_state = Some(select_prev_state);
12083 } else {
12084 let mut only_carets = true;
12085 let mut same_text_selected = true;
12086 let mut selected_text = None;
12087
12088 let mut selections_iter = selections.iter().peekable();
12089 while let Some(selection) = selections_iter.next() {
12090 if selection.start != selection.end {
12091 only_carets = false;
12092 }
12093
12094 if same_text_selected {
12095 if selected_text.is_none() {
12096 selected_text =
12097 Some(buffer.text_for_range(selection.range()).collect::<String>());
12098 }
12099
12100 if let Some(next_selection) = selections_iter.peek() {
12101 if next_selection.range().len() == selection.range().len() {
12102 let next_selected_text = buffer
12103 .text_for_range(next_selection.range())
12104 .collect::<String>();
12105 if Some(next_selected_text) != selected_text {
12106 same_text_selected = false;
12107 selected_text = None;
12108 }
12109 } else {
12110 same_text_selected = false;
12111 selected_text = None;
12112 }
12113 }
12114 }
12115 }
12116
12117 if only_carets {
12118 for selection in &mut selections {
12119 let word_range = movement::surrounding_word(
12120 &display_map,
12121 selection.start.to_display_point(&display_map),
12122 );
12123 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12124 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12125 selection.goal = SelectionGoal::None;
12126 selection.reversed = false;
12127 }
12128 if selections.len() == 1 {
12129 let selection = selections
12130 .last()
12131 .expect("ensured that there's only one selection");
12132 let query = buffer
12133 .text_for_range(selection.start..selection.end)
12134 .collect::<String>();
12135 let is_empty = query.is_empty();
12136 let select_state = SelectNextState {
12137 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12138 wordwise: true,
12139 done: is_empty,
12140 };
12141 self.select_prev_state = Some(select_state);
12142 } else {
12143 self.select_prev_state = None;
12144 }
12145
12146 self.unfold_ranges(
12147 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12148 false,
12149 true,
12150 cx,
12151 );
12152 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12153 s.select(selections);
12154 });
12155 } else if let Some(selected_text) = selected_text {
12156 self.select_prev_state = Some(SelectNextState {
12157 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12158 wordwise: false,
12159 done: false,
12160 });
12161 self.select_previous(action, window, cx)?;
12162 }
12163 }
12164 Ok(())
12165 }
12166
12167 pub fn find_next_match(
12168 &mut self,
12169 _: &FindNextMatch,
12170 window: &mut Window,
12171 cx: &mut Context<Self>,
12172 ) -> Result<()> {
12173 let selections = self.selections.disjoint_anchors();
12174 match selections.first() {
12175 Some(first) if selections.len() >= 2 => {
12176 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12177 s.select_ranges([first.range()]);
12178 });
12179 }
12180 _ => self.select_next(
12181 &SelectNext {
12182 replace_newest: true,
12183 },
12184 window,
12185 cx,
12186 )?,
12187 }
12188 Ok(())
12189 }
12190
12191 pub fn find_previous_match(
12192 &mut self,
12193 _: &FindPreviousMatch,
12194 window: &mut Window,
12195 cx: &mut Context<Self>,
12196 ) -> Result<()> {
12197 let selections = self.selections.disjoint_anchors();
12198 match selections.last() {
12199 Some(last) if selections.len() >= 2 => {
12200 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12201 s.select_ranges([last.range()]);
12202 });
12203 }
12204 _ => self.select_previous(
12205 &SelectPrevious {
12206 replace_newest: true,
12207 },
12208 window,
12209 cx,
12210 )?,
12211 }
12212 Ok(())
12213 }
12214
12215 pub fn toggle_comments(
12216 &mut self,
12217 action: &ToggleComments,
12218 window: &mut Window,
12219 cx: &mut Context<Self>,
12220 ) {
12221 if self.read_only(cx) {
12222 return;
12223 }
12224 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12225 let text_layout_details = &self.text_layout_details(window);
12226 self.transact(window, cx, |this, window, cx| {
12227 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12228 let mut edits = Vec::new();
12229 let mut selection_edit_ranges = Vec::new();
12230 let mut last_toggled_row = None;
12231 let snapshot = this.buffer.read(cx).read(cx);
12232 let empty_str: Arc<str> = Arc::default();
12233 let mut suffixes_inserted = Vec::new();
12234 let ignore_indent = action.ignore_indent;
12235
12236 fn comment_prefix_range(
12237 snapshot: &MultiBufferSnapshot,
12238 row: MultiBufferRow,
12239 comment_prefix: &str,
12240 comment_prefix_whitespace: &str,
12241 ignore_indent: bool,
12242 ) -> Range<Point> {
12243 let indent_size = if ignore_indent {
12244 0
12245 } else {
12246 snapshot.indent_size_for_line(row).len
12247 };
12248
12249 let start = Point::new(row.0, indent_size);
12250
12251 let mut line_bytes = snapshot
12252 .bytes_in_range(start..snapshot.max_point())
12253 .flatten()
12254 .copied();
12255
12256 // If this line currently begins with the line comment prefix, then record
12257 // the range containing the prefix.
12258 if line_bytes
12259 .by_ref()
12260 .take(comment_prefix.len())
12261 .eq(comment_prefix.bytes())
12262 {
12263 // Include any whitespace that matches the comment prefix.
12264 let matching_whitespace_len = line_bytes
12265 .zip(comment_prefix_whitespace.bytes())
12266 .take_while(|(a, b)| a == b)
12267 .count() as u32;
12268 let end = Point::new(
12269 start.row,
12270 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12271 );
12272 start..end
12273 } else {
12274 start..start
12275 }
12276 }
12277
12278 fn comment_suffix_range(
12279 snapshot: &MultiBufferSnapshot,
12280 row: MultiBufferRow,
12281 comment_suffix: &str,
12282 comment_suffix_has_leading_space: bool,
12283 ) -> Range<Point> {
12284 let end = Point::new(row.0, snapshot.line_len(row));
12285 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12286
12287 let mut line_end_bytes = snapshot
12288 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12289 .flatten()
12290 .copied();
12291
12292 let leading_space_len = if suffix_start_column > 0
12293 && line_end_bytes.next() == Some(b' ')
12294 && comment_suffix_has_leading_space
12295 {
12296 1
12297 } else {
12298 0
12299 };
12300
12301 // If this line currently begins with the line comment prefix, then record
12302 // the range containing the prefix.
12303 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12304 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12305 start..end
12306 } else {
12307 end..end
12308 }
12309 }
12310
12311 // TODO: Handle selections that cross excerpts
12312 for selection in &mut selections {
12313 let start_column = snapshot
12314 .indent_size_for_line(MultiBufferRow(selection.start.row))
12315 .len;
12316 let language = if let Some(language) =
12317 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12318 {
12319 language
12320 } else {
12321 continue;
12322 };
12323
12324 selection_edit_ranges.clear();
12325
12326 // If multiple selections contain a given row, avoid processing that
12327 // row more than once.
12328 let mut start_row = MultiBufferRow(selection.start.row);
12329 if last_toggled_row == Some(start_row) {
12330 start_row = start_row.next_row();
12331 }
12332 let end_row =
12333 if selection.end.row > selection.start.row && selection.end.column == 0 {
12334 MultiBufferRow(selection.end.row - 1)
12335 } else {
12336 MultiBufferRow(selection.end.row)
12337 };
12338 last_toggled_row = Some(end_row);
12339
12340 if start_row > end_row {
12341 continue;
12342 }
12343
12344 // If the language has line comments, toggle those.
12345 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12346
12347 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12348 if ignore_indent {
12349 full_comment_prefixes = full_comment_prefixes
12350 .into_iter()
12351 .map(|s| Arc::from(s.trim_end()))
12352 .collect();
12353 }
12354
12355 if !full_comment_prefixes.is_empty() {
12356 let first_prefix = full_comment_prefixes
12357 .first()
12358 .expect("prefixes is non-empty");
12359 let prefix_trimmed_lengths = full_comment_prefixes
12360 .iter()
12361 .map(|p| p.trim_end_matches(' ').len())
12362 .collect::<SmallVec<[usize; 4]>>();
12363
12364 let mut all_selection_lines_are_comments = true;
12365
12366 for row in start_row.0..=end_row.0 {
12367 let row = MultiBufferRow(row);
12368 if start_row < end_row && snapshot.is_line_blank(row) {
12369 continue;
12370 }
12371
12372 let prefix_range = full_comment_prefixes
12373 .iter()
12374 .zip(prefix_trimmed_lengths.iter().copied())
12375 .map(|(prefix, trimmed_prefix_len)| {
12376 comment_prefix_range(
12377 snapshot.deref(),
12378 row,
12379 &prefix[..trimmed_prefix_len],
12380 &prefix[trimmed_prefix_len..],
12381 ignore_indent,
12382 )
12383 })
12384 .max_by_key(|range| range.end.column - range.start.column)
12385 .expect("prefixes is non-empty");
12386
12387 if prefix_range.is_empty() {
12388 all_selection_lines_are_comments = false;
12389 }
12390
12391 selection_edit_ranges.push(prefix_range);
12392 }
12393
12394 if all_selection_lines_are_comments {
12395 edits.extend(
12396 selection_edit_ranges
12397 .iter()
12398 .cloned()
12399 .map(|range| (range, empty_str.clone())),
12400 );
12401 } else {
12402 let min_column = selection_edit_ranges
12403 .iter()
12404 .map(|range| range.start.column)
12405 .min()
12406 .unwrap_or(0);
12407 edits.extend(selection_edit_ranges.iter().map(|range| {
12408 let position = Point::new(range.start.row, min_column);
12409 (position..position, first_prefix.clone())
12410 }));
12411 }
12412 } else if let Some((full_comment_prefix, comment_suffix)) =
12413 language.block_comment_delimiters()
12414 {
12415 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12416 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12417 let prefix_range = comment_prefix_range(
12418 snapshot.deref(),
12419 start_row,
12420 comment_prefix,
12421 comment_prefix_whitespace,
12422 ignore_indent,
12423 );
12424 let suffix_range = comment_suffix_range(
12425 snapshot.deref(),
12426 end_row,
12427 comment_suffix.trim_start_matches(' '),
12428 comment_suffix.starts_with(' '),
12429 );
12430
12431 if prefix_range.is_empty() || suffix_range.is_empty() {
12432 edits.push((
12433 prefix_range.start..prefix_range.start,
12434 full_comment_prefix.clone(),
12435 ));
12436 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12437 suffixes_inserted.push((end_row, comment_suffix.len()));
12438 } else {
12439 edits.push((prefix_range, empty_str.clone()));
12440 edits.push((suffix_range, empty_str.clone()));
12441 }
12442 } else {
12443 continue;
12444 }
12445 }
12446
12447 drop(snapshot);
12448 this.buffer.update(cx, |buffer, cx| {
12449 buffer.edit(edits, None, cx);
12450 });
12451
12452 // Adjust selections so that they end before any comment suffixes that
12453 // were inserted.
12454 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12455 let mut selections = this.selections.all::<Point>(cx);
12456 let snapshot = this.buffer.read(cx).read(cx);
12457 for selection in &mut selections {
12458 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12459 match row.cmp(&MultiBufferRow(selection.end.row)) {
12460 Ordering::Less => {
12461 suffixes_inserted.next();
12462 continue;
12463 }
12464 Ordering::Greater => break,
12465 Ordering::Equal => {
12466 if selection.end.column == snapshot.line_len(row) {
12467 if selection.is_empty() {
12468 selection.start.column -= suffix_len as u32;
12469 }
12470 selection.end.column -= suffix_len as u32;
12471 }
12472 break;
12473 }
12474 }
12475 }
12476 }
12477
12478 drop(snapshot);
12479 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12480 s.select(selections)
12481 });
12482
12483 let selections = this.selections.all::<Point>(cx);
12484 let selections_on_single_row = selections.windows(2).all(|selections| {
12485 selections[0].start.row == selections[1].start.row
12486 && selections[0].end.row == selections[1].end.row
12487 && selections[0].start.row == selections[0].end.row
12488 });
12489 let selections_selecting = selections
12490 .iter()
12491 .any(|selection| selection.start != selection.end);
12492 let advance_downwards = action.advance_downwards
12493 && selections_on_single_row
12494 && !selections_selecting
12495 && !matches!(this.mode, EditorMode::SingleLine { .. });
12496
12497 if advance_downwards {
12498 let snapshot = this.buffer.read(cx).snapshot(cx);
12499
12500 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12501 s.move_cursors_with(|display_snapshot, display_point, _| {
12502 let mut point = display_point.to_point(display_snapshot);
12503 point.row += 1;
12504 point = snapshot.clip_point(point, Bias::Left);
12505 let display_point = point.to_display_point(display_snapshot);
12506 let goal = SelectionGoal::HorizontalPosition(
12507 display_snapshot
12508 .x_for_display_point(display_point, text_layout_details)
12509 .into(),
12510 );
12511 (display_point, goal)
12512 })
12513 });
12514 }
12515 });
12516 }
12517
12518 pub fn select_enclosing_symbol(
12519 &mut self,
12520 _: &SelectEnclosingSymbol,
12521 window: &mut Window,
12522 cx: &mut Context<Self>,
12523 ) {
12524 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12525
12526 let buffer = self.buffer.read(cx).snapshot(cx);
12527 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12528
12529 fn update_selection(
12530 selection: &Selection<usize>,
12531 buffer_snap: &MultiBufferSnapshot,
12532 ) -> Option<Selection<usize>> {
12533 let cursor = selection.head();
12534 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12535 for symbol in symbols.iter().rev() {
12536 let start = symbol.range.start.to_offset(buffer_snap);
12537 let end = symbol.range.end.to_offset(buffer_snap);
12538 let new_range = start..end;
12539 if start < selection.start || end > selection.end {
12540 return Some(Selection {
12541 id: selection.id,
12542 start: new_range.start,
12543 end: new_range.end,
12544 goal: SelectionGoal::None,
12545 reversed: selection.reversed,
12546 });
12547 }
12548 }
12549 None
12550 }
12551
12552 let mut selected_larger_symbol = false;
12553 let new_selections = old_selections
12554 .iter()
12555 .map(|selection| match update_selection(selection, &buffer) {
12556 Some(new_selection) => {
12557 if new_selection.range() != selection.range() {
12558 selected_larger_symbol = true;
12559 }
12560 new_selection
12561 }
12562 None => selection.clone(),
12563 })
12564 .collect::<Vec<_>>();
12565
12566 if selected_larger_symbol {
12567 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12568 s.select(new_selections);
12569 });
12570 }
12571 }
12572
12573 pub fn select_larger_syntax_node(
12574 &mut self,
12575 _: &SelectLargerSyntaxNode,
12576 window: &mut Window,
12577 cx: &mut Context<Self>,
12578 ) {
12579 let Some(visible_row_count) = self.visible_row_count() else {
12580 return;
12581 };
12582 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12583 if old_selections.is_empty() {
12584 return;
12585 }
12586
12587 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12588
12589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12590 let buffer = self.buffer.read(cx).snapshot(cx);
12591
12592 let mut selected_larger_node = false;
12593 let mut new_selections = old_selections
12594 .iter()
12595 .map(|selection| {
12596 let old_range = selection.start..selection.end;
12597
12598 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12599 // manually select word at selection
12600 if ["string_content", "inline"].contains(&node.kind()) {
12601 let word_range = {
12602 let display_point = buffer
12603 .offset_to_point(old_range.start)
12604 .to_display_point(&display_map);
12605 let Range { start, end } =
12606 movement::surrounding_word(&display_map, display_point);
12607 start.to_point(&display_map).to_offset(&buffer)
12608 ..end.to_point(&display_map).to_offset(&buffer)
12609 };
12610 // ignore if word is already selected
12611 if !word_range.is_empty() && old_range != word_range {
12612 let last_word_range = {
12613 let display_point = buffer
12614 .offset_to_point(old_range.end)
12615 .to_display_point(&display_map);
12616 let Range { start, end } =
12617 movement::surrounding_word(&display_map, display_point);
12618 start.to_point(&display_map).to_offset(&buffer)
12619 ..end.to_point(&display_map).to_offset(&buffer)
12620 };
12621 // only select word if start and end point belongs to same word
12622 if word_range == last_word_range {
12623 selected_larger_node = true;
12624 return Selection {
12625 id: selection.id,
12626 start: word_range.start,
12627 end: word_range.end,
12628 goal: SelectionGoal::None,
12629 reversed: selection.reversed,
12630 };
12631 }
12632 }
12633 }
12634 }
12635
12636 let mut new_range = old_range.clone();
12637 let mut new_node = None;
12638 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12639 {
12640 new_node = Some(node);
12641 new_range = match containing_range {
12642 MultiOrSingleBufferOffsetRange::Single(_) => break,
12643 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12644 };
12645 if !display_map.intersects_fold(new_range.start)
12646 && !display_map.intersects_fold(new_range.end)
12647 {
12648 break;
12649 }
12650 }
12651
12652 if let Some(node) = new_node {
12653 // Log the ancestor, to support using this action as a way to explore TreeSitter
12654 // nodes. Parent and grandparent are also logged because this operation will not
12655 // visit nodes that have the same range as their parent.
12656 log::info!("Node: {node:?}");
12657 let parent = node.parent();
12658 log::info!("Parent: {parent:?}");
12659 let grandparent = parent.and_then(|x| x.parent());
12660 log::info!("Grandparent: {grandparent:?}");
12661 }
12662
12663 selected_larger_node |= new_range != old_range;
12664 Selection {
12665 id: selection.id,
12666 start: new_range.start,
12667 end: new_range.end,
12668 goal: SelectionGoal::None,
12669 reversed: selection.reversed,
12670 }
12671 })
12672 .collect::<Vec<_>>();
12673
12674 if !selected_larger_node {
12675 return; // don't put this call in the history
12676 }
12677
12678 // scroll based on transformation done to the last selection created by the user
12679 let (last_old, last_new) = old_selections
12680 .last()
12681 .zip(new_selections.last().cloned())
12682 .expect("old_selections isn't empty");
12683
12684 // revert selection
12685 let is_selection_reversed = {
12686 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12687 new_selections.last_mut().expect("checked above").reversed =
12688 should_newest_selection_be_reversed;
12689 should_newest_selection_be_reversed
12690 };
12691
12692 if selected_larger_node {
12693 self.select_syntax_node_history.disable_clearing = true;
12694 self.change_selections(None, window, cx, |s| {
12695 s.select(new_selections.clone());
12696 });
12697 self.select_syntax_node_history.disable_clearing = false;
12698 }
12699
12700 let start_row = last_new.start.to_display_point(&display_map).row().0;
12701 let end_row = last_new.end.to_display_point(&display_map).row().0;
12702 let selection_height = end_row - start_row + 1;
12703 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12704
12705 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12706 let scroll_behavior = if fits_on_the_screen {
12707 self.request_autoscroll(Autoscroll::fit(), cx);
12708 SelectSyntaxNodeScrollBehavior::FitSelection
12709 } else if is_selection_reversed {
12710 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12711 SelectSyntaxNodeScrollBehavior::CursorTop
12712 } else {
12713 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12714 SelectSyntaxNodeScrollBehavior::CursorBottom
12715 };
12716
12717 self.select_syntax_node_history.push((
12718 old_selections,
12719 scroll_behavior,
12720 is_selection_reversed,
12721 ));
12722 }
12723
12724 pub fn select_smaller_syntax_node(
12725 &mut self,
12726 _: &SelectSmallerSyntaxNode,
12727 window: &mut Window,
12728 cx: &mut Context<Self>,
12729 ) {
12730 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12731
12732 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12733 self.select_syntax_node_history.pop()
12734 {
12735 if let Some(selection) = selections.last_mut() {
12736 selection.reversed = is_selection_reversed;
12737 }
12738
12739 self.select_syntax_node_history.disable_clearing = true;
12740 self.change_selections(None, window, cx, |s| {
12741 s.select(selections.to_vec());
12742 });
12743 self.select_syntax_node_history.disable_clearing = false;
12744
12745 match scroll_behavior {
12746 SelectSyntaxNodeScrollBehavior::CursorTop => {
12747 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12748 }
12749 SelectSyntaxNodeScrollBehavior::FitSelection => {
12750 self.request_autoscroll(Autoscroll::fit(), cx);
12751 }
12752 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12753 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12754 }
12755 }
12756 }
12757 }
12758
12759 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12760 if !EditorSettings::get_global(cx).gutter.runnables {
12761 self.clear_tasks();
12762 return Task::ready(());
12763 }
12764 let project = self.project.as_ref().map(Entity::downgrade);
12765 let task_sources = self.lsp_task_sources(cx);
12766 cx.spawn_in(window, async move |editor, cx| {
12767 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12768 let Some(project) = project.and_then(|p| p.upgrade()) else {
12769 return;
12770 };
12771 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12772 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12773 }) else {
12774 return;
12775 };
12776
12777 let hide_runnables = project
12778 .update(cx, |project, cx| {
12779 // Do not display any test indicators in non-dev server remote projects.
12780 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12781 })
12782 .unwrap_or(true);
12783 if hide_runnables {
12784 return;
12785 }
12786 let new_rows =
12787 cx.background_spawn({
12788 let snapshot = display_snapshot.clone();
12789 async move {
12790 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12791 }
12792 })
12793 .await;
12794 let Ok(lsp_tasks) =
12795 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12796 else {
12797 return;
12798 };
12799 let lsp_tasks = lsp_tasks.await;
12800
12801 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12802 lsp_tasks
12803 .into_iter()
12804 .flat_map(|(kind, tasks)| {
12805 tasks.into_iter().filter_map(move |(location, task)| {
12806 Some((kind.clone(), location?, task))
12807 })
12808 })
12809 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12810 let buffer = location.target.buffer;
12811 let buffer_snapshot = buffer.read(cx).snapshot();
12812 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12813 |(excerpt_id, snapshot, _)| {
12814 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12815 display_snapshot
12816 .buffer_snapshot
12817 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12818 } else {
12819 None
12820 }
12821 },
12822 );
12823 if let Some(offset) = offset {
12824 let task_buffer_range =
12825 location.target.range.to_point(&buffer_snapshot);
12826 let context_buffer_range =
12827 task_buffer_range.to_offset(&buffer_snapshot);
12828 let context_range = BufferOffset(context_buffer_range.start)
12829 ..BufferOffset(context_buffer_range.end);
12830
12831 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12832 .or_insert_with(|| RunnableTasks {
12833 templates: Vec::new(),
12834 offset,
12835 column: task_buffer_range.start.column,
12836 extra_variables: HashMap::default(),
12837 context_range,
12838 })
12839 .templates
12840 .push((kind, task.original_task().clone()));
12841 }
12842
12843 acc
12844 })
12845 }) else {
12846 return;
12847 };
12848
12849 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12850 editor
12851 .update(cx, |editor, _| {
12852 editor.clear_tasks();
12853 for (key, mut value) in rows {
12854 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12855 value.templates.extend(lsp_tasks.templates);
12856 }
12857
12858 editor.insert_tasks(key, value);
12859 }
12860 for (key, value) in lsp_tasks_by_rows {
12861 editor.insert_tasks(key, value);
12862 }
12863 })
12864 .ok();
12865 })
12866 }
12867 fn fetch_runnable_ranges(
12868 snapshot: &DisplaySnapshot,
12869 range: Range<Anchor>,
12870 ) -> Vec<language::RunnableRange> {
12871 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12872 }
12873
12874 fn runnable_rows(
12875 project: Entity<Project>,
12876 snapshot: DisplaySnapshot,
12877 runnable_ranges: Vec<RunnableRange>,
12878 mut cx: AsyncWindowContext,
12879 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12880 runnable_ranges
12881 .into_iter()
12882 .filter_map(|mut runnable| {
12883 let tasks = cx
12884 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12885 .ok()?;
12886 if tasks.is_empty() {
12887 return None;
12888 }
12889
12890 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12891
12892 let row = snapshot
12893 .buffer_snapshot
12894 .buffer_line_for_row(MultiBufferRow(point.row))?
12895 .1
12896 .start
12897 .row;
12898
12899 let context_range =
12900 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12901 Some((
12902 (runnable.buffer_id, row),
12903 RunnableTasks {
12904 templates: tasks,
12905 offset: snapshot
12906 .buffer_snapshot
12907 .anchor_before(runnable.run_range.start),
12908 context_range,
12909 column: point.column,
12910 extra_variables: runnable.extra_captures,
12911 },
12912 ))
12913 })
12914 .collect()
12915 }
12916
12917 fn templates_with_tags(
12918 project: &Entity<Project>,
12919 runnable: &mut Runnable,
12920 cx: &mut App,
12921 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12922 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12923 let (worktree_id, file) = project
12924 .buffer_for_id(runnable.buffer, cx)
12925 .and_then(|buffer| buffer.read(cx).file())
12926 .map(|file| (file.worktree_id(cx), file.clone()))
12927 .unzip();
12928
12929 (
12930 project.task_store().read(cx).task_inventory().cloned(),
12931 worktree_id,
12932 file,
12933 )
12934 });
12935
12936 let mut templates_with_tags = mem::take(&mut runnable.tags)
12937 .into_iter()
12938 .flat_map(|RunnableTag(tag)| {
12939 inventory
12940 .as_ref()
12941 .into_iter()
12942 .flat_map(|inventory| {
12943 inventory.read(cx).list_tasks(
12944 file.clone(),
12945 Some(runnable.language.clone()),
12946 worktree_id,
12947 cx,
12948 )
12949 })
12950 .filter(move |(_, template)| {
12951 template.tags.iter().any(|source_tag| source_tag == &tag)
12952 })
12953 })
12954 .sorted_by_key(|(kind, _)| kind.to_owned())
12955 .collect::<Vec<_>>();
12956 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12957 // Strongest source wins; if we have worktree tag binding, prefer that to
12958 // global and language bindings;
12959 // if we have a global binding, prefer that to language binding.
12960 let first_mismatch = templates_with_tags
12961 .iter()
12962 .position(|(tag_source, _)| tag_source != leading_tag_source);
12963 if let Some(index) = first_mismatch {
12964 templates_with_tags.truncate(index);
12965 }
12966 }
12967
12968 templates_with_tags
12969 }
12970
12971 pub fn move_to_enclosing_bracket(
12972 &mut self,
12973 _: &MoveToEnclosingBracket,
12974 window: &mut Window,
12975 cx: &mut Context<Self>,
12976 ) {
12977 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12979 s.move_offsets_with(|snapshot, selection| {
12980 let Some(enclosing_bracket_ranges) =
12981 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12982 else {
12983 return;
12984 };
12985
12986 let mut best_length = usize::MAX;
12987 let mut best_inside = false;
12988 let mut best_in_bracket_range = false;
12989 let mut best_destination = None;
12990 for (open, close) in enclosing_bracket_ranges {
12991 let close = close.to_inclusive();
12992 let length = close.end() - open.start;
12993 let inside = selection.start >= open.end && selection.end <= *close.start();
12994 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12995 || close.contains(&selection.head());
12996
12997 // If best is next to a bracket and current isn't, skip
12998 if !in_bracket_range && best_in_bracket_range {
12999 continue;
13000 }
13001
13002 // Prefer smaller lengths unless best is inside and current isn't
13003 if length > best_length && (best_inside || !inside) {
13004 continue;
13005 }
13006
13007 best_length = length;
13008 best_inside = inside;
13009 best_in_bracket_range = in_bracket_range;
13010 best_destination = Some(
13011 if close.contains(&selection.start) && close.contains(&selection.end) {
13012 if inside { open.end } else { open.start }
13013 } else if inside {
13014 *close.start()
13015 } else {
13016 *close.end()
13017 },
13018 );
13019 }
13020
13021 if let Some(destination) = best_destination {
13022 selection.collapse_to(destination, SelectionGoal::None);
13023 }
13024 })
13025 });
13026 }
13027
13028 pub fn undo_selection(
13029 &mut self,
13030 _: &UndoSelection,
13031 window: &mut Window,
13032 cx: &mut Context<Self>,
13033 ) {
13034 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13035 self.end_selection(window, cx);
13036 self.selection_history.mode = SelectionHistoryMode::Undoing;
13037 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13038 self.change_selections(None, window, cx, |s| {
13039 s.select_anchors(entry.selections.to_vec())
13040 });
13041 self.select_next_state = entry.select_next_state;
13042 self.select_prev_state = entry.select_prev_state;
13043 self.add_selections_state = entry.add_selections_state;
13044 self.request_autoscroll(Autoscroll::newest(), cx);
13045 }
13046 self.selection_history.mode = SelectionHistoryMode::Normal;
13047 }
13048
13049 pub fn redo_selection(
13050 &mut self,
13051 _: &RedoSelection,
13052 window: &mut Window,
13053 cx: &mut Context<Self>,
13054 ) {
13055 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13056 self.end_selection(window, cx);
13057 self.selection_history.mode = SelectionHistoryMode::Redoing;
13058 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13059 self.change_selections(None, window, cx, |s| {
13060 s.select_anchors(entry.selections.to_vec())
13061 });
13062 self.select_next_state = entry.select_next_state;
13063 self.select_prev_state = entry.select_prev_state;
13064 self.add_selections_state = entry.add_selections_state;
13065 self.request_autoscroll(Autoscroll::newest(), cx);
13066 }
13067 self.selection_history.mode = SelectionHistoryMode::Normal;
13068 }
13069
13070 pub fn expand_excerpts(
13071 &mut self,
13072 action: &ExpandExcerpts,
13073 _: &mut Window,
13074 cx: &mut Context<Self>,
13075 ) {
13076 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13077 }
13078
13079 pub fn expand_excerpts_down(
13080 &mut self,
13081 action: &ExpandExcerptsDown,
13082 _: &mut Window,
13083 cx: &mut Context<Self>,
13084 ) {
13085 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13086 }
13087
13088 pub fn expand_excerpts_up(
13089 &mut self,
13090 action: &ExpandExcerptsUp,
13091 _: &mut Window,
13092 cx: &mut Context<Self>,
13093 ) {
13094 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13095 }
13096
13097 pub fn expand_excerpts_for_direction(
13098 &mut self,
13099 lines: u32,
13100 direction: ExpandExcerptDirection,
13101
13102 cx: &mut Context<Self>,
13103 ) {
13104 let selections = self.selections.disjoint_anchors();
13105
13106 let lines = if lines == 0 {
13107 EditorSettings::get_global(cx).expand_excerpt_lines
13108 } else {
13109 lines
13110 };
13111
13112 self.buffer.update(cx, |buffer, cx| {
13113 let snapshot = buffer.snapshot(cx);
13114 let mut excerpt_ids = selections
13115 .iter()
13116 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13117 .collect::<Vec<_>>();
13118 excerpt_ids.sort();
13119 excerpt_ids.dedup();
13120 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13121 })
13122 }
13123
13124 pub fn expand_excerpt(
13125 &mut self,
13126 excerpt: ExcerptId,
13127 direction: ExpandExcerptDirection,
13128 window: &mut Window,
13129 cx: &mut Context<Self>,
13130 ) {
13131 let current_scroll_position = self.scroll_position(cx);
13132 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13133 let mut should_scroll_up = false;
13134
13135 if direction == ExpandExcerptDirection::Down {
13136 let multi_buffer = self.buffer.read(cx);
13137 let snapshot = multi_buffer.snapshot(cx);
13138 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13139 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13140 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13141 let buffer_snapshot = buffer.read(cx).snapshot();
13142 let excerpt_end_row =
13143 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13144 let last_row = buffer_snapshot.max_point().row;
13145 let lines_below = last_row.saturating_sub(excerpt_end_row);
13146 should_scroll_up = lines_below >= lines_to_expand;
13147 }
13148 }
13149 }
13150 }
13151
13152 self.buffer.update(cx, |buffer, cx| {
13153 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13154 });
13155
13156 if should_scroll_up {
13157 let new_scroll_position =
13158 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13159 self.set_scroll_position(new_scroll_position, window, cx);
13160 }
13161 }
13162
13163 pub fn go_to_singleton_buffer_point(
13164 &mut self,
13165 point: Point,
13166 window: &mut Window,
13167 cx: &mut Context<Self>,
13168 ) {
13169 self.go_to_singleton_buffer_range(point..point, window, cx);
13170 }
13171
13172 pub fn go_to_singleton_buffer_range(
13173 &mut self,
13174 range: Range<Point>,
13175 window: &mut Window,
13176 cx: &mut Context<Self>,
13177 ) {
13178 let multibuffer = self.buffer().read(cx);
13179 let Some(buffer) = multibuffer.as_singleton() else {
13180 return;
13181 };
13182 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13183 return;
13184 };
13185 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13186 return;
13187 };
13188 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13189 s.select_anchor_ranges([start..end])
13190 });
13191 }
13192
13193 pub fn go_to_diagnostic(
13194 &mut self,
13195 _: &GoToDiagnostic,
13196 window: &mut Window,
13197 cx: &mut Context<Self>,
13198 ) {
13199 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13200 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13201 }
13202
13203 pub fn go_to_prev_diagnostic(
13204 &mut self,
13205 _: &GoToPreviousDiagnostic,
13206 window: &mut Window,
13207 cx: &mut Context<Self>,
13208 ) {
13209 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13210 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13211 }
13212
13213 pub fn go_to_diagnostic_impl(
13214 &mut self,
13215 direction: Direction,
13216 window: &mut Window,
13217 cx: &mut Context<Self>,
13218 ) {
13219 let buffer = self.buffer.read(cx).snapshot(cx);
13220 let selection = self.selections.newest::<usize>(cx);
13221
13222 let mut active_group_id = None;
13223 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13224 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13225 active_group_id = Some(active_group.group_id);
13226 }
13227 }
13228
13229 fn filtered(
13230 snapshot: EditorSnapshot,
13231 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13232 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13233 diagnostics
13234 .filter(|entry| entry.range.start != entry.range.end)
13235 .filter(|entry| !entry.diagnostic.is_unnecessary)
13236 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13237 }
13238
13239 let snapshot = self.snapshot(window, cx);
13240 let before = filtered(
13241 snapshot.clone(),
13242 buffer
13243 .diagnostics_in_range(0..selection.start)
13244 .filter(|entry| entry.range.start <= selection.start),
13245 );
13246 let after = filtered(
13247 snapshot,
13248 buffer
13249 .diagnostics_in_range(selection.start..buffer.len())
13250 .filter(|entry| entry.range.start >= selection.start),
13251 );
13252
13253 let mut found: Option<DiagnosticEntry<usize>> = None;
13254 if direction == Direction::Prev {
13255 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13256 {
13257 for diagnostic in prev_diagnostics.into_iter().rev() {
13258 if diagnostic.range.start != selection.start
13259 || active_group_id
13260 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13261 {
13262 found = Some(diagnostic);
13263 break 'outer;
13264 }
13265 }
13266 }
13267 } else {
13268 for diagnostic in after.chain(before) {
13269 if diagnostic.range.start != selection.start
13270 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13271 {
13272 found = Some(diagnostic);
13273 break;
13274 }
13275 }
13276 }
13277 let Some(next_diagnostic) = found else {
13278 return;
13279 };
13280
13281 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13282 return;
13283 };
13284 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13285 s.select_ranges(vec![
13286 next_diagnostic.range.start..next_diagnostic.range.start,
13287 ])
13288 });
13289 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13290 self.refresh_inline_completion(false, true, window, cx);
13291 }
13292
13293 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13294 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13295 let snapshot = self.snapshot(window, cx);
13296 let selection = self.selections.newest::<Point>(cx);
13297 self.go_to_hunk_before_or_after_position(
13298 &snapshot,
13299 selection.head(),
13300 Direction::Next,
13301 window,
13302 cx,
13303 );
13304 }
13305
13306 pub fn go_to_hunk_before_or_after_position(
13307 &mut self,
13308 snapshot: &EditorSnapshot,
13309 position: Point,
13310 direction: Direction,
13311 window: &mut Window,
13312 cx: &mut Context<Editor>,
13313 ) {
13314 let row = if direction == Direction::Next {
13315 self.hunk_after_position(snapshot, position)
13316 .map(|hunk| hunk.row_range.start)
13317 } else {
13318 self.hunk_before_position(snapshot, position)
13319 };
13320
13321 if let Some(row) = row {
13322 let destination = Point::new(row.0, 0);
13323 let autoscroll = Autoscroll::center();
13324
13325 self.unfold_ranges(&[destination..destination], false, false, cx);
13326 self.change_selections(Some(autoscroll), window, cx, |s| {
13327 s.select_ranges([destination..destination]);
13328 });
13329 }
13330 }
13331
13332 fn hunk_after_position(
13333 &mut self,
13334 snapshot: &EditorSnapshot,
13335 position: Point,
13336 ) -> Option<MultiBufferDiffHunk> {
13337 snapshot
13338 .buffer_snapshot
13339 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13340 .find(|hunk| hunk.row_range.start.0 > position.row)
13341 .or_else(|| {
13342 snapshot
13343 .buffer_snapshot
13344 .diff_hunks_in_range(Point::zero()..position)
13345 .find(|hunk| hunk.row_range.end.0 < position.row)
13346 })
13347 }
13348
13349 fn go_to_prev_hunk(
13350 &mut self,
13351 _: &GoToPreviousHunk,
13352 window: &mut Window,
13353 cx: &mut Context<Self>,
13354 ) {
13355 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13356 let snapshot = self.snapshot(window, cx);
13357 let selection = self.selections.newest::<Point>(cx);
13358 self.go_to_hunk_before_or_after_position(
13359 &snapshot,
13360 selection.head(),
13361 Direction::Prev,
13362 window,
13363 cx,
13364 );
13365 }
13366
13367 fn hunk_before_position(
13368 &mut self,
13369 snapshot: &EditorSnapshot,
13370 position: Point,
13371 ) -> Option<MultiBufferRow> {
13372 snapshot
13373 .buffer_snapshot
13374 .diff_hunk_before(position)
13375 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13376 }
13377
13378 fn go_to_next_change(
13379 &mut self,
13380 _: &GoToNextChange,
13381 window: &mut Window,
13382 cx: &mut Context<Self>,
13383 ) {
13384 if let Some(selections) = self
13385 .change_list
13386 .next_change(1, Direction::Next)
13387 .map(|s| s.to_vec())
13388 {
13389 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13390 let map = s.display_map();
13391 s.select_display_ranges(selections.iter().map(|a| {
13392 let point = a.to_display_point(&map);
13393 point..point
13394 }))
13395 })
13396 }
13397 }
13398
13399 fn go_to_previous_change(
13400 &mut self,
13401 _: &GoToPreviousChange,
13402 window: &mut Window,
13403 cx: &mut Context<Self>,
13404 ) {
13405 if let Some(selections) = self
13406 .change_list
13407 .next_change(1, Direction::Prev)
13408 .map(|s| s.to_vec())
13409 {
13410 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13411 let map = s.display_map();
13412 s.select_display_ranges(selections.iter().map(|a| {
13413 let point = a.to_display_point(&map);
13414 point..point
13415 }))
13416 })
13417 }
13418 }
13419
13420 fn go_to_line<T: 'static>(
13421 &mut self,
13422 position: Anchor,
13423 highlight_color: Option<Hsla>,
13424 window: &mut Window,
13425 cx: &mut Context<Self>,
13426 ) {
13427 let snapshot = self.snapshot(window, cx).display_snapshot;
13428 let position = position.to_point(&snapshot.buffer_snapshot);
13429 let start = snapshot
13430 .buffer_snapshot
13431 .clip_point(Point::new(position.row, 0), Bias::Left);
13432 let end = start + Point::new(1, 0);
13433 let start = snapshot.buffer_snapshot.anchor_before(start);
13434 let end = snapshot.buffer_snapshot.anchor_before(end);
13435
13436 self.highlight_rows::<T>(
13437 start..end,
13438 highlight_color
13439 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13440 false,
13441 cx,
13442 );
13443 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13444 }
13445
13446 pub fn go_to_definition(
13447 &mut self,
13448 _: &GoToDefinition,
13449 window: &mut Window,
13450 cx: &mut Context<Self>,
13451 ) -> Task<Result<Navigated>> {
13452 let definition =
13453 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13454 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13455 cx.spawn_in(window, async move |editor, cx| {
13456 if definition.await? == Navigated::Yes {
13457 return Ok(Navigated::Yes);
13458 }
13459 match fallback_strategy {
13460 GoToDefinitionFallback::None => Ok(Navigated::No),
13461 GoToDefinitionFallback::FindAllReferences => {
13462 match editor.update_in(cx, |editor, window, cx| {
13463 editor.find_all_references(&FindAllReferences, window, cx)
13464 })? {
13465 Some(references) => references.await,
13466 None => Ok(Navigated::No),
13467 }
13468 }
13469 }
13470 })
13471 }
13472
13473 pub fn go_to_declaration(
13474 &mut self,
13475 _: &GoToDeclaration,
13476 window: &mut Window,
13477 cx: &mut Context<Self>,
13478 ) -> Task<Result<Navigated>> {
13479 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13480 }
13481
13482 pub fn go_to_declaration_split(
13483 &mut self,
13484 _: &GoToDeclaration,
13485 window: &mut Window,
13486 cx: &mut Context<Self>,
13487 ) -> Task<Result<Navigated>> {
13488 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13489 }
13490
13491 pub fn go_to_implementation(
13492 &mut self,
13493 _: &GoToImplementation,
13494 window: &mut Window,
13495 cx: &mut Context<Self>,
13496 ) -> Task<Result<Navigated>> {
13497 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13498 }
13499
13500 pub fn go_to_implementation_split(
13501 &mut self,
13502 _: &GoToImplementationSplit,
13503 window: &mut Window,
13504 cx: &mut Context<Self>,
13505 ) -> Task<Result<Navigated>> {
13506 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13507 }
13508
13509 pub fn go_to_type_definition(
13510 &mut self,
13511 _: &GoToTypeDefinition,
13512 window: &mut Window,
13513 cx: &mut Context<Self>,
13514 ) -> Task<Result<Navigated>> {
13515 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13516 }
13517
13518 pub fn go_to_definition_split(
13519 &mut self,
13520 _: &GoToDefinitionSplit,
13521 window: &mut Window,
13522 cx: &mut Context<Self>,
13523 ) -> Task<Result<Navigated>> {
13524 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13525 }
13526
13527 pub fn go_to_type_definition_split(
13528 &mut self,
13529 _: &GoToTypeDefinitionSplit,
13530 window: &mut Window,
13531 cx: &mut Context<Self>,
13532 ) -> Task<Result<Navigated>> {
13533 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13534 }
13535
13536 fn go_to_definition_of_kind(
13537 &mut self,
13538 kind: GotoDefinitionKind,
13539 split: bool,
13540 window: &mut Window,
13541 cx: &mut Context<Self>,
13542 ) -> Task<Result<Navigated>> {
13543 let Some(provider) = self.semantics_provider.clone() else {
13544 return Task::ready(Ok(Navigated::No));
13545 };
13546 let head = self.selections.newest::<usize>(cx).head();
13547 let buffer = self.buffer.read(cx);
13548 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13549 text_anchor
13550 } else {
13551 return Task::ready(Ok(Navigated::No));
13552 };
13553
13554 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13555 return Task::ready(Ok(Navigated::No));
13556 };
13557
13558 cx.spawn_in(window, async move |editor, cx| {
13559 let definitions = definitions.await?;
13560 let navigated = editor
13561 .update_in(cx, |editor, window, cx| {
13562 editor.navigate_to_hover_links(
13563 Some(kind),
13564 definitions
13565 .into_iter()
13566 .filter(|location| {
13567 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13568 })
13569 .map(HoverLink::Text)
13570 .collect::<Vec<_>>(),
13571 split,
13572 window,
13573 cx,
13574 )
13575 })?
13576 .await?;
13577 anyhow::Ok(navigated)
13578 })
13579 }
13580
13581 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13582 let selection = self.selections.newest_anchor();
13583 let head = selection.head();
13584 let tail = selection.tail();
13585
13586 let Some((buffer, start_position)) =
13587 self.buffer.read(cx).text_anchor_for_position(head, cx)
13588 else {
13589 return;
13590 };
13591
13592 let end_position = if head != tail {
13593 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13594 return;
13595 };
13596 Some(pos)
13597 } else {
13598 None
13599 };
13600
13601 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13602 let url = if let Some(end_pos) = end_position {
13603 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13604 } else {
13605 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13606 };
13607
13608 if let Some(url) = url {
13609 editor.update(cx, |_, cx| {
13610 cx.open_url(&url);
13611 })
13612 } else {
13613 Ok(())
13614 }
13615 });
13616
13617 url_finder.detach();
13618 }
13619
13620 pub fn open_selected_filename(
13621 &mut self,
13622 _: &OpenSelectedFilename,
13623 window: &mut Window,
13624 cx: &mut Context<Self>,
13625 ) {
13626 let Some(workspace) = self.workspace() else {
13627 return;
13628 };
13629
13630 let position = self.selections.newest_anchor().head();
13631
13632 let Some((buffer, buffer_position)) =
13633 self.buffer.read(cx).text_anchor_for_position(position, cx)
13634 else {
13635 return;
13636 };
13637
13638 let project = self.project.clone();
13639
13640 cx.spawn_in(window, async move |_, cx| {
13641 let result = find_file(&buffer, project, buffer_position, cx).await;
13642
13643 if let Some((_, path)) = result {
13644 workspace
13645 .update_in(cx, |workspace, window, cx| {
13646 workspace.open_resolved_path(path, window, cx)
13647 })?
13648 .await?;
13649 }
13650 anyhow::Ok(())
13651 })
13652 .detach();
13653 }
13654
13655 pub(crate) fn navigate_to_hover_links(
13656 &mut self,
13657 kind: Option<GotoDefinitionKind>,
13658 mut definitions: Vec<HoverLink>,
13659 split: bool,
13660 window: &mut Window,
13661 cx: &mut Context<Editor>,
13662 ) -> Task<Result<Navigated>> {
13663 // If there is one definition, just open it directly
13664 if definitions.len() == 1 {
13665 let definition = definitions.pop().unwrap();
13666
13667 enum TargetTaskResult {
13668 Location(Option<Location>),
13669 AlreadyNavigated,
13670 }
13671
13672 let target_task = match definition {
13673 HoverLink::Text(link) => {
13674 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13675 }
13676 HoverLink::InlayHint(lsp_location, server_id) => {
13677 let computation =
13678 self.compute_target_location(lsp_location, server_id, window, cx);
13679 cx.background_spawn(async move {
13680 let location = computation.await?;
13681 Ok(TargetTaskResult::Location(location))
13682 })
13683 }
13684 HoverLink::Url(url) => {
13685 cx.open_url(&url);
13686 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13687 }
13688 HoverLink::File(path) => {
13689 if let Some(workspace) = self.workspace() {
13690 cx.spawn_in(window, async move |_, cx| {
13691 workspace
13692 .update_in(cx, |workspace, window, cx| {
13693 workspace.open_resolved_path(path, window, cx)
13694 })?
13695 .await
13696 .map(|_| TargetTaskResult::AlreadyNavigated)
13697 })
13698 } else {
13699 Task::ready(Ok(TargetTaskResult::Location(None)))
13700 }
13701 }
13702 };
13703 cx.spawn_in(window, async move |editor, cx| {
13704 let target = match target_task.await.context("target resolution task")? {
13705 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13706 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13707 TargetTaskResult::Location(Some(target)) => target,
13708 };
13709
13710 editor.update_in(cx, |editor, window, cx| {
13711 let Some(workspace) = editor.workspace() else {
13712 return Navigated::No;
13713 };
13714 let pane = workspace.read(cx).active_pane().clone();
13715
13716 let range = target.range.to_point(target.buffer.read(cx));
13717 let range = editor.range_for_match(&range);
13718 let range = collapse_multiline_range(range);
13719
13720 if !split
13721 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13722 {
13723 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13724 } else {
13725 window.defer(cx, move |window, cx| {
13726 let target_editor: Entity<Self> =
13727 workspace.update(cx, |workspace, cx| {
13728 let pane = if split {
13729 workspace.adjacent_pane(window, cx)
13730 } else {
13731 workspace.active_pane().clone()
13732 };
13733
13734 workspace.open_project_item(
13735 pane,
13736 target.buffer.clone(),
13737 true,
13738 true,
13739 window,
13740 cx,
13741 )
13742 });
13743 target_editor.update(cx, |target_editor, cx| {
13744 // When selecting a definition in a different buffer, disable the nav history
13745 // to avoid creating a history entry at the previous cursor location.
13746 pane.update(cx, |pane, _| pane.disable_history());
13747 target_editor.go_to_singleton_buffer_range(range, window, cx);
13748 pane.update(cx, |pane, _| pane.enable_history());
13749 });
13750 });
13751 }
13752 Navigated::Yes
13753 })
13754 })
13755 } else if !definitions.is_empty() {
13756 cx.spawn_in(window, async move |editor, cx| {
13757 let (title, location_tasks, workspace) = editor
13758 .update_in(cx, |editor, window, cx| {
13759 let tab_kind = match kind {
13760 Some(GotoDefinitionKind::Implementation) => "Implementations",
13761 _ => "Definitions",
13762 };
13763 let title = definitions
13764 .iter()
13765 .find_map(|definition| match definition {
13766 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13767 let buffer = origin.buffer.read(cx);
13768 format!(
13769 "{} for {}",
13770 tab_kind,
13771 buffer
13772 .text_for_range(origin.range.clone())
13773 .collect::<String>()
13774 )
13775 }),
13776 HoverLink::InlayHint(_, _) => None,
13777 HoverLink::Url(_) => None,
13778 HoverLink::File(_) => None,
13779 })
13780 .unwrap_or(tab_kind.to_string());
13781 let location_tasks = definitions
13782 .into_iter()
13783 .map(|definition| match definition {
13784 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13785 HoverLink::InlayHint(lsp_location, server_id) => editor
13786 .compute_target_location(lsp_location, server_id, window, cx),
13787 HoverLink::Url(_) => Task::ready(Ok(None)),
13788 HoverLink::File(_) => Task::ready(Ok(None)),
13789 })
13790 .collect::<Vec<_>>();
13791 (title, location_tasks, editor.workspace().clone())
13792 })
13793 .context("location tasks preparation")?;
13794
13795 let locations = future::join_all(location_tasks)
13796 .await
13797 .into_iter()
13798 .filter_map(|location| location.transpose())
13799 .collect::<Result<_>>()
13800 .context("location tasks")?;
13801
13802 let Some(workspace) = workspace else {
13803 return Ok(Navigated::No);
13804 };
13805 let opened = workspace
13806 .update_in(cx, |workspace, window, cx| {
13807 Self::open_locations_in_multibuffer(
13808 workspace,
13809 locations,
13810 title,
13811 split,
13812 MultibufferSelectionMode::First,
13813 window,
13814 cx,
13815 )
13816 })
13817 .ok();
13818
13819 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13820 })
13821 } else {
13822 Task::ready(Ok(Navigated::No))
13823 }
13824 }
13825
13826 fn compute_target_location(
13827 &self,
13828 lsp_location: lsp::Location,
13829 server_id: LanguageServerId,
13830 window: &mut Window,
13831 cx: &mut Context<Self>,
13832 ) -> Task<anyhow::Result<Option<Location>>> {
13833 let Some(project) = self.project.clone() else {
13834 return Task::ready(Ok(None));
13835 };
13836
13837 cx.spawn_in(window, async move |editor, cx| {
13838 let location_task = editor.update(cx, |_, cx| {
13839 project.update(cx, |project, cx| {
13840 let language_server_name = project
13841 .language_server_statuses(cx)
13842 .find(|(id, _)| server_id == *id)
13843 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13844 language_server_name.map(|language_server_name| {
13845 project.open_local_buffer_via_lsp(
13846 lsp_location.uri.clone(),
13847 server_id,
13848 language_server_name,
13849 cx,
13850 )
13851 })
13852 })
13853 })?;
13854 let location = match location_task {
13855 Some(task) => Some({
13856 let target_buffer_handle = task.await.context("open local buffer")?;
13857 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13858 let target_start = target_buffer
13859 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13860 let target_end = target_buffer
13861 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13862 target_buffer.anchor_after(target_start)
13863 ..target_buffer.anchor_before(target_end)
13864 })?;
13865 Location {
13866 buffer: target_buffer_handle,
13867 range,
13868 }
13869 }),
13870 None => None,
13871 };
13872 Ok(location)
13873 })
13874 }
13875
13876 pub fn find_all_references(
13877 &mut self,
13878 _: &FindAllReferences,
13879 window: &mut Window,
13880 cx: &mut Context<Self>,
13881 ) -> Option<Task<Result<Navigated>>> {
13882 let selection = self.selections.newest::<usize>(cx);
13883 let multi_buffer = self.buffer.read(cx);
13884 let head = selection.head();
13885
13886 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13887 let head_anchor = multi_buffer_snapshot.anchor_at(
13888 head,
13889 if head < selection.tail() {
13890 Bias::Right
13891 } else {
13892 Bias::Left
13893 },
13894 );
13895
13896 match self
13897 .find_all_references_task_sources
13898 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13899 {
13900 Ok(_) => {
13901 log::info!(
13902 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13903 );
13904 return None;
13905 }
13906 Err(i) => {
13907 self.find_all_references_task_sources.insert(i, head_anchor);
13908 }
13909 }
13910
13911 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13912 let workspace = self.workspace()?;
13913 let project = workspace.read(cx).project().clone();
13914 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13915 Some(cx.spawn_in(window, async move |editor, cx| {
13916 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13917 if let Ok(i) = editor
13918 .find_all_references_task_sources
13919 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13920 {
13921 editor.find_all_references_task_sources.remove(i);
13922 }
13923 });
13924
13925 let locations = references.await?;
13926 if locations.is_empty() {
13927 return anyhow::Ok(Navigated::No);
13928 }
13929
13930 workspace.update_in(cx, |workspace, window, cx| {
13931 let title = locations
13932 .first()
13933 .as_ref()
13934 .map(|location| {
13935 let buffer = location.buffer.read(cx);
13936 format!(
13937 "References to `{}`",
13938 buffer
13939 .text_for_range(location.range.clone())
13940 .collect::<String>()
13941 )
13942 })
13943 .unwrap();
13944 Self::open_locations_in_multibuffer(
13945 workspace,
13946 locations,
13947 title,
13948 false,
13949 MultibufferSelectionMode::First,
13950 window,
13951 cx,
13952 );
13953 Navigated::Yes
13954 })
13955 }))
13956 }
13957
13958 /// Opens a multibuffer with the given project locations in it
13959 pub fn open_locations_in_multibuffer(
13960 workspace: &mut Workspace,
13961 mut locations: Vec<Location>,
13962 title: String,
13963 split: bool,
13964 multibuffer_selection_mode: MultibufferSelectionMode,
13965 window: &mut Window,
13966 cx: &mut Context<Workspace>,
13967 ) {
13968 // If there are multiple definitions, open them in a multibuffer
13969 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13970 let mut locations = locations.into_iter().peekable();
13971 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13972 let capability = workspace.project().read(cx).capability();
13973
13974 let excerpt_buffer = cx.new(|cx| {
13975 let mut multibuffer = MultiBuffer::new(capability);
13976 while let Some(location) = locations.next() {
13977 let buffer = location.buffer.read(cx);
13978 let mut ranges_for_buffer = Vec::new();
13979 let range = location.range.to_point(buffer);
13980 ranges_for_buffer.push(range.clone());
13981
13982 while let Some(next_location) = locations.peek() {
13983 if next_location.buffer == location.buffer {
13984 ranges_for_buffer.push(next_location.range.to_point(buffer));
13985 locations.next();
13986 } else {
13987 break;
13988 }
13989 }
13990
13991 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13992 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13993 PathKey::for_buffer(&location.buffer, cx),
13994 location.buffer.clone(),
13995 ranges_for_buffer,
13996 DEFAULT_MULTIBUFFER_CONTEXT,
13997 cx,
13998 );
13999 ranges.extend(new_ranges)
14000 }
14001
14002 multibuffer.with_title(title)
14003 });
14004
14005 let editor = cx.new(|cx| {
14006 Editor::for_multibuffer(
14007 excerpt_buffer,
14008 Some(workspace.project().clone()),
14009 window,
14010 cx,
14011 )
14012 });
14013 editor.update(cx, |editor, cx| {
14014 match multibuffer_selection_mode {
14015 MultibufferSelectionMode::First => {
14016 if let Some(first_range) = ranges.first() {
14017 editor.change_selections(None, window, cx, |selections| {
14018 selections.clear_disjoint();
14019 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14020 });
14021 }
14022 editor.highlight_background::<Self>(
14023 &ranges,
14024 |theme| theme.editor_highlighted_line_background,
14025 cx,
14026 );
14027 }
14028 MultibufferSelectionMode::All => {
14029 editor.change_selections(None, window, cx, |selections| {
14030 selections.clear_disjoint();
14031 selections.select_anchor_ranges(ranges);
14032 });
14033 }
14034 }
14035 editor.register_buffers_with_language_servers(cx);
14036 });
14037
14038 let item = Box::new(editor);
14039 let item_id = item.item_id();
14040
14041 if split {
14042 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14043 } else {
14044 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14045 let (preview_item_id, preview_item_idx) =
14046 workspace.active_pane().update(cx, |pane, _| {
14047 (pane.preview_item_id(), pane.preview_item_idx())
14048 });
14049
14050 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14051
14052 if let Some(preview_item_id) = preview_item_id {
14053 workspace.active_pane().update(cx, |pane, cx| {
14054 pane.remove_item(preview_item_id, false, false, window, cx);
14055 });
14056 }
14057 } else {
14058 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14059 }
14060 }
14061 workspace.active_pane().update(cx, |pane, cx| {
14062 pane.set_preview_item_id(Some(item_id), cx);
14063 });
14064 }
14065
14066 pub fn rename(
14067 &mut self,
14068 _: &Rename,
14069 window: &mut Window,
14070 cx: &mut Context<Self>,
14071 ) -> Option<Task<Result<()>>> {
14072 use language::ToOffset as _;
14073
14074 let provider = self.semantics_provider.clone()?;
14075 let selection = self.selections.newest_anchor().clone();
14076 let (cursor_buffer, cursor_buffer_position) = self
14077 .buffer
14078 .read(cx)
14079 .text_anchor_for_position(selection.head(), cx)?;
14080 let (tail_buffer, cursor_buffer_position_end) = self
14081 .buffer
14082 .read(cx)
14083 .text_anchor_for_position(selection.tail(), cx)?;
14084 if tail_buffer != cursor_buffer {
14085 return None;
14086 }
14087
14088 let snapshot = cursor_buffer.read(cx).snapshot();
14089 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14090 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14091 let prepare_rename = provider
14092 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14093 .unwrap_or_else(|| Task::ready(Ok(None)));
14094 drop(snapshot);
14095
14096 Some(cx.spawn_in(window, async move |this, cx| {
14097 let rename_range = if let Some(range) = prepare_rename.await? {
14098 Some(range)
14099 } else {
14100 this.update(cx, |this, cx| {
14101 let buffer = this.buffer.read(cx).snapshot(cx);
14102 let mut buffer_highlights = this
14103 .document_highlights_for_position(selection.head(), &buffer)
14104 .filter(|highlight| {
14105 highlight.start.excerpt_id == selection.head().excerpt_id
14106 && highlight.end.excerpt_id == selection.head().excerpt_id
14107 });
14108 buffer_highlights
14109 .next()
14110 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14111 })?
14112 };
14113 if let Some(rename_range) = rename_range {
14114 this.update_in(cx, |this, window, cx| {
14115 let snapshot = cursor_buffer.read(cx).snapshot();
14116 let rename_buffer_range = rename_range.to_offset(&snapshot);
14117 let cursor_offset_in_rename_range =
14118 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14119 let cursor_offset_in_rename_range_end =
14120 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14121
14122 this.take_rename(false, window, cx);
14123 let buffer = this.buffer.read(cx).read(cx);
14124 let cursor_offset = selection.head().to_offset(&buffer);
14125 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14126 let rename_end = rename_start + rename_buffer_range.len();
14127 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14128 let mut old_highlight_id = None;
14129 let old_name: Arc<str> = buffer
14130 .chunks(rename_start..rename_end, true)
14131 .map(|chunk| {
14132 if old_highlight_id.is_none() {
14133 old_highlight_id = chunk.syntax_highlight_id;
14134 }
14135 chunk.text
14136 })
14137 .collect::<String>()
14138 .into();
14139
14140 drop(buffer);
14141
14142 // Position the selection in the rename editor so that it matches the current selection.
14143 this.show_local_selections = false;
14144 let rename_editor = cx.new(|cx| {
14145 let mut editor = Editor::single_line(window, cx);
14146 editor.buffer.update(cx, |buffer, cx| {
14147 buffer.edit([(0..0, old_name.clone())], None, cx)
14148 });
14149 let rename_selection_range = match cursor_offset_in_rename_range
14150 .cmp(&cursor_offset_in_rename_range_end)
14151 {
14152 Ordering::Equal => {
14153 editor.select_all(&SelectAll, window, cx);
14154 return editor;
14155 }
14156 Ordering::Less => {
14157 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14158 }
14159 Ordering::Greater => {
14160 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14161 }
14162 };
14163 if rename_selection_range.end > old_name.len() {
14164 editor.select_all(&SelectAll, window, cx);
14165 } else {
14166 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14167 s.select_ranges([rename_selection_range]);
14168 });
14169 }
14170 editor
14171 });
14172 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14173 if e == &EditorEvent::Focused {
14174 cx.emit(EditorEvent::FocusedIn)
14175 }
14176 })
14177 .detach();
14178
14179 let write_highlights =
14180 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14181 let read_highlights =
14182 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14183 let ranges = write_highlights
14184 .iter()
14185 .flat_map(|(_, ranges)| ranges.iter())
14186 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14187 .cloned()
14188 .collect();
14189
14190 this.highlight_text::<Rename>(
14191 ranges,
14192 HighlightStyle {
14193 fade_out: Some(0.6),
14194 ..Default::default()
14195 },
14196 cx,
14197 );
14198 let rename_focus_handle = rename_editor.focus_handle(cx);
14199 window.focus(&rename_focus_handle);
14200 let block_id = this.insert_blocks(
14201 [BlockProperties {
14202 style: BlockStyle::Flex,
14203 placement: BlockPlacement::Below(range.start),
14204 height: Some(1),
14205 render: Arc::new({
14206 let rename_editor = rename_editor.clone();
14207 move |cx: &mut BlockContext| {
14208 let mut text_style = cx.editor_style.text.clone();
14209 if let Some(highlight_style) = old_highlight_id
14210 .and_then(|h| h.style(&cx.editor_style.syntax))
14211 {
14212 text_style = text_style.highlight(highlight_style);
14213 }
14214 div()
14215 .block_mouse_down()
14216 .pl(cx.anchor_x)
14217 .child(EditorElement::new(
14218 &rename_editor,
14219 EditorStyle {
14220 background: cx.theme().system().transparent,
14221 local_player: cx.editor_style.local_player,
14222 text: text_style,
14223 scrollbar_width: cx.editor_style.scrollbar_width,
14224 syntax: cx.editor_style.syntax.clone(),
14225 status: cx.editor_style.status.clone(),
14226 inlay_hints_style: HighlightStyle {
14227 font_weight: Some(FontWeight::BOLD),
14228 ..make_inlay_hints_style(cx.app)
14229 },
14230 inline_completion_styles: make_suggestion_styles(
14231 cx.app,
14232 ),
14233 ..EditorStyle::default()
14234 },
14235 ))
14236 .into_any_element()
14237 }
14238 }),
14239 priority: 0,
14240 }],
14241 Some(Autoscroll::fit()),
14242 cx,
14243 )[0];
14244 this.pending_rename = Some(RenameState {
14245 range,
14246 old_name,
14247 editor: rename_editor,
14248 block_id,
14249 });
14250 })?;
14251 }
14252
14253 Ok(())
14254 }))
14255 }
14256
14257 pub fn confirm_rename(
14258 &mut self,
14259 _: &ConfirmRename,
14260 window: &mut Window,
14261 cx: &mut Context<Self>,
14262 ) -> Option<Task<Result<()>>> {
14263 let rename = self.take_rename(false, window, cx)?;
14264 let workspace = self.workspace()?.downgrade();
14265 let (buffer, start) = self
14266 .buffer
14267 .read(cx)
14268 .text_anchor_for_position(rename.range.start, cx)?;
14269 let (end_buffer, _) = self
14270 .buffer
14271 .read(cx)
14272 .text_anchor_for_position(rename.range.end, cx)?;
14273 if buffer != end_buffer {
14274 return None;
14275 }
14276
14277 let old_name = rename.old_name;
14278 let new_name = rename.editor.read(cx).text(cx);
14279
14280 let rename = self.semantics_provider.as_ref()?.perform_rename(
14281 &buffer,
14282 start,
14283 new_name.clone(),
14284 cx,
14285 )?;
14286
14287 Some(cx.spawn_in(window, async move |editor, cx| {
14288 let project_transaction = rename.await?;
14289 Self::open_project_transaction(
14290 &editor,
14291 workspace,
14292 project_transaction,
14293 format!("Rename: {} → {}", old_name, new_name),
14294 cx,
14295 )
14296 .await?;
14297
14298 editor.update(cx, |editor, cx| {
14299 editor.refresh_document_highlights(cx);
14300 })?;
14301 Ok(())
14302 }))
14303 }
14304
14305 fn take_rename(
14306 &mut self,
14307 moving_cursor: bool,
14308 window: &mut Window,
14309 cx: &mut Context<Self>,
14310 ) -> Option<RenameState> {
14311 let rename = self.pending_rename.take()?;
14312 if rename.editor.focus_handle(cx).is_focused(window) {
14313 window.focus(&self.focus_handle);
14314 }
14315
14316 self.remove_blocks(
14317 [rename.block_id].into_iter().collect(),
14318 Some(Autoscroll::fit()),
14319 cx,
14320 );
14321 self.clear_highlights::<Rename>(cx);
14322 self.show_local_selections = true;
14323
14324 if moving_cursor {
14325 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14326 editor.selections.newest::<usize>(cx).head()
14327 });
14328
14329 // Update the selection to match the position of the selection inside
14330 // the rename editor.
14331 let snapshot = self.buffer.read(cx).read(cx);
14332 let rename_range = rename.range.to_offset(&snapshot);
14333 let cursor_in_editor = snapshot
14334 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14335 .min(rename_range.end);
14336 drop(snapshot);
14337
14338 self.change_selections(None, window, cx, |s| {
14339 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14340 });
14341 } else {
14342 self.refresh_document_highlights(cx);
14343 }
14344
14345 Some(rename)
14346 }
14347
14348 pub fn pending_rename(&self) -> Option<&RenameState> {
14349 self.pending_rename.as_ref()
14350 }
14351
14352 fn format(
14353 &mut self,
14354 _: &Format,
14355 window: &mut Window,
14356 cx: &mut Context<Self>,
14357 ) -> Option<Task<Result<()>>> {
14358 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14359
14360 let project = match &self.project {
14361 Some(project) => project.clone(),
14362 None => return None,
14363 };
14364
14365 Some(self.perform_format(
14366 project,
14367 FormatTrigger::Manual,
14368 FormatTarget::Buffers,
14369 window,
14370 cx,
14371 ))
14372 }
14373
14374 fn format_selections(
14375 &mut self,
14376 _: &FormatSelections,
14377 window: &mut Window,
14378 cx: &mut Context<Self>,
14379 ) -> Option<Task<Result<()>>> {
14380 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14381
14382 let project = match &self.project {
14383 Some(project) => project.clone(),
14384 None => return None,
14385 };
14386
14387 let ranges = self
14388 .selections
14389 .all_adjusted(cx)
14390 .into_iter()
14391 .map(|selection| selection.range())
14392 .collect_vec();
14393
14394 Some(self.perform_format(
14395 project,
14396 FormatTrigger::Manual,
14397 FormatTarget::Ranges(ranges),
14398 window,
14399 cx,
14400 ))
14401 }
14402
14403 fn perform_format(
14404 &mut self,
14405 project: Entity<Project>,
14406 trigger: FormatTrigger,
14407 target: FormatTarget,
14408 window: &mut Window,
14409 cx: &mut Context<Self>,
14410 ) -> Task<Result<()>> {
14411 let buffer = self.buffer.clone();
14412 let (buffers, target) = match target {
14413 FormatTarget::Buffers => {
14414 let mut buffers = buffer.read(cx).all_buffers();
14415 if trigger == FormatTrigger::Save {
14416 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14417 }
14418 (buffers, LspFormatTarget::Buffers)
14419 }
14420 FormatTarget::Ranges(selection_ranges) => {
14421 let multi_buffer = buffer.read(cx);
14422 let snapshot = multi_buffer.read(cx);
14423 let mut buffers = HashSet::default();
14424 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14425 BTreeMap::new();
14426 for selection_range in selection_ranges {
14427 for (buffer, buffer_range, _) in
14428 snapshot.range_to_buffer_ranges(selection_range)
14429 {
14430 let buffer_id = buffer.remote_id();
14431 let start = buffer.anchor_before(buffer_range.start);
14432 let end = buffer.anchor_after(buffer_range.end);
14433 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14434 buffer_id_to_ranges
14435 .entry(buffer_id)
14436 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14437 .or_insert_with(|| vec![start..end]);
14438 }
14439 }
14440 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14441 }
14442 };
14443
14444 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14445 let selections_prev = transaction_id_prev
14446 .and_then(|transaction_id_prev| {
14447 // default to selections as they were after the last edit, if we have them,
14448 // instead of how they are now.
14449 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14450 // will take you back to where you made the last edit, instead of staying where you scrolled
14451 self.selection_history
14452 .transaction(transaction_id_prev)
14453 .map(|t| t.0.clone())
14454 })
14455 .unwrap_or_else(|| {
14456 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14457 self.selections.disjoint_anchors()
14458 });
14459
14460 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14461 let format = project.update(cx, |project, cx| {
14462 project.format(buffers, target, true, trigger, cx)
14463 });
14464
14465 cx.spawn_in(window, async move |editor, cx| {
14466 let transaction = futures::select_biased! {
14467 transaction = format.log_err().fuse() => transaction,
14468 () = timeout => {
14469 log::warn!("timed out waiting for formatting");
14470 None
14471 }
14472 };
14473
14474 buffer
14475 .update(cx, |buffer, cx| {
14476 if let Some(transaction) = transaction {
14477 if !buffer.is_singleton() {
14478 buffer.push_transaction(&transaction.0, cx);
14479 }
14480 }
14481 cx.notify();
14482 })
14483 .ok();
14484
14485 if let Some(transaction_id_now) =
14486 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14487 {
14488 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14489 if has_new_transaction {
14490 _ = editor.update(cx, |editor, _| {
14491 editor
14492 .selection_history
14493 .insert_transaction(transaction_id_now, selections_prev);
14494 });
14495 }
14496 }
14497
14498 Ok(())
14499 })
14500 }
14501
14502 fn organize_imports(
14503 &mut self,
14504 _: &OrganizeImports,
14505 window: &mut Window,
14506 cx: &mut Context<Self>,
14507 ) -> Option<Task<Result<()>>> {
14508 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14509 let project = match &self.project {
14510 Some(project) => project.clone(),
14511 None => return None,
14512 };
14513 Some(self.perform_code_action_kind(
14514 project,
14515 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14516 window,
14517 cx,
14518 ))
14519 }
14520
14521 fn perform_code_action_kind(
14522 &mut self,
14523 project: Entity<Project>,
14524 kind: CodeActionKind,
14525 window: &mut Window,
14526 cx: &mut Context<Self>,
14527 ) -> Task<Result<()>> {
14528 let buffer = self.buffer.clone();
14529 let buffers = buffer.read(cx).all_buffers();
14530 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14531 let apply_action = project.update(cx, |project, cx| {
14532 project.apply_code_action_kind(buffers, kind, true, cx)
14533 });
14534 cx.spawn_in(window, async move |_, cx| {
14535 let transaction = futures::select_biased! {
14536 () = timeout => {
14537 log::warn!("timed out waiting for executing code action");
14538 None
14539 }
14540 transaction = apply_action.log_err().fuse() => transaction,
14541 };
14542 buffer
14543 .update(cx, |buffer, cx| {
14544 // check if we need this
14545 if let Some(transaction) = transaction {
14546 if !buffer.is_singleton() {
14547 buffer.push_transaction(&transaction.0, cx);
14548 }
14549 }
14550 cx.notify();
14551 })
14552 .ok();
14553 Ok(())
14554 })
14555 }
14556
14557 fn restart_language_server(
14558 &mut self,
14559 _: &RestartLanguageServer,
14560 _: &mut Window,
14561 cx: &mut Context<Self>,
14562 ) {
14563 if let Some(project) = self.project.clone() {
14564 self.buffer.update(cx, |multi_buffer, cx| {
14565 project.update(cx, |project, cx| {
14566 project.restart_language_servers_for_buffers(
14567 multi_buffer.all_buffers().into_iter().collect(),
14568 cx,
14569 );
14570 });
14571 })
14572 }
14573 }
14574
14575 fn stop_language_server(
14576 &mut self,
14577 _: &StopLanguageServer,
14578 _: &mut Window,
14579 cx: &mut Context<Self>,
14580 ) {
14581 if let Some(project) = self.project.clone() {
14582 self.buffer.update(cx, |multi_buffer, cx| {
14583 project.update(cx, |project, cx| {
14584 project.stop_language_servers_for_buffers(
14585 multi_buffer.all_buffers().into_iter().collect(),
14586 cx,
14587 );
14588 cx.emit(project::Event::RefreshInlayHints);
14589 });
14590 });
14591 }
14592 }
14593
14594 fn cancel_language_server_work(
14595 workspace: &mut Workspace,
14596 _: &actions::CancelLanguageServerWork,
14597 _: &mut Window,
14598 cx: &mut Context<Workspace>,
14599 ) {
14600 let project = workspace.project();
14601 let buffers = workspace
14602 .active_item(cx)
14603 .and_then(|item| item.act_as::<Editor>(cx))
14604 .map_or(HashSet::default(), |editor| {
14605 editor.read(cx).buffer.read(cx).all_buffers()
14606 });
14607 project.update(cx, |project, cx| {
14608 project.cancel_language_server_work_for_buffers(buffers, cx);
14609 });
14610 }
14611
14612 fn show_character_palette(
14613 &mut self,
14614 _: &ShowCharacterPalette,
14615 window: &mut Window,
14616 _: &mut Context<Self>,
14617 ) {
14618 window.show_character_palette();
14619 }
14620
14621 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14622 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14623 let buffer = self.buffer.read(cx).snapshot(cx);
14624 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14625 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14626 let is_valid = buffer
14627 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14628 .any(|entry| {
14629 entry.diagnostic.is_primary
14630 && !entry.range.is_empty()
14631 && entry.range.start == primary_range_start
14632 && entry.diagnostic.message == active_diagnostics.active_message
14633 });
14634
14635 if !is_valid {
14636 self.dismiss_diagnostics(cx);
14637 }
14638 }
14639 }
14640
14641 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14642 match &self.active_diagnostics {
14643 ActiveDiagnostic::Group(group) => Some(group),
14644 _ => None,
14645 }
14646 }
14647
14648 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14649 self.dismiss_diagnostics(cx);
14650 self.active_diagnostics = ActiveDiagnostic::All;
14651 }
14652
14653 fn activate_diagnostics(
14654 &mut self,
14655 buffer_id: BufferId,
14656 diagnostic: DiagnosticEntry<usize>,
14657 window: &mut Window,
14658 cx: &mut Context<Self>,
14659 ) {
14660 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14661 return;
14662 }
14663 self.dismiss_diagnostics(cx);
14664 let snapshot = self.snapshot(window, cx);
14665 let Some(diagnostic_renderer) = cx
14666 .try_global::<GlobalDiagnosticRenderer>()
14667 .map(|g| g.0.clone())
14668 else {
14669 return;
14670 };
14671 let buffer = self.buffer.read(cx).snapshot(cx);
14672
14673 let diagnostic_group = buffer
14674 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14675 .collect::<Vec<_>>();
14676
14677 let blocks = diagnostic_renderer.render_group(
14678 diagnostic_group,
14679 buffer_id,
14680 snapshot,
14681 cx.weak_entity(),
14682 cx,
14683 );
14684
14685 let blocks = self.display_map.update(cx, |display_map, cx| {
14686 display_map.insert_blocks(blocks, cx).into_iter().collect()
14687 });
14688 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14689 active_range: buffer.anchor_before(diagnostic.range.start)
14690 ..buffer.anchor_after(diagnostic.range.end),
14691 active_message: diagnostic.diagnostic.message.clone(),
14692 group_id: diagnostic.diagnostic.group_id,
14693 blocks,
14694 });
14695 cx.notify();
14696 }
14697
14698 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14699 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14700 return;
14701 };
14702
14703 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14704 if let ActiveDiagnostic::Group(group) = prev {
14705 self.display_map.update(cx, |display_map, cx| {
14706 display_map.remove_blocks(group.blocks, cx);
14707 });
14708 cx.notify();
14709 }
14710 }
14711
14712 /// Disable inline diagnostics rendering for this editor.
14713 pub fn disable_inline_diagnostics(&mut self) {
14714 self.inline_diagnostics_enabled = false;
14715 self.inline_diagnostics_update = Task::ready(());
14716 self.inline_diagnostics.clear();
14717 }
14718
14719 pub fn inline_diagnostics_enabled(&self) -> bool {
14720 self.inline_diagnostics_enabled
14721 }
14722
14723 pub fn show_inline_diagnostics(&self) -> bool {
14724 self.show_inline_diagnostics
14725 }
14726
14727 pub fn toggle_inline_diagnostics(
14728 &mut self,
14729 _: &ToggleInlineDiagnostics,
14730 window: &mut Window,
14731 cx: &mut Context<Editor>,
14732 ) {
14733 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14734 self.refresh_inline_diagnostics(false, window, cx);
14735 }
14736
14737 fn refresh_inline_diagnostics(
14738 &mut self,
14739 debounce: bool,
14740 window: &mut Window,
14741 cx: &mut Context<Self>,
14742 ) {
14743 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14744 self.inline_diagnostics_update = Task::ready(());
14745 self.inline_diagnostics.clear();
14746 return;
14747 }
14748
14749 let debounce_ms = ProjectSettings::get_global(cx)
14750 .diagnostics
14751 .inline
14752 .update_debounce_ms;
14753 let debounce = if debounce && debounce_ms > 0 {
14754 Some(Duration::from_millis(debounce_ms))
14755 } else {
14756 None
14757 };
14758 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14759 let editor = editor.upgrade().unwrap();
14760
14761 if let Some(debounce) = debounce {
14762 cx.background_executor().timer(debounce).await;
14763 }
14764 let Some(snapshot) = editor
14765 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14766 .ok()
14767 else {
14768 return;
14769 };
14770
14771 let new_inline_diagnostics = cx
14772 .background_spawn(async move {
14773 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14774 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14775 let message = diagnostic_entry
14776 .diagnostic
14777 .message
14778 .split_once('\n')
14779 .map(|(line, _)| line)
14780 .map(SharedString::new)
14781 .unwrap_or_else(|| {
14782 SharedString::from(diagnostic_entry.diagnostic.message)
14783 });
14784 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14785 let (Ok(i) | Err(i)) = inline_diagnostics
14786 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14787 inline_diagnostics.insert(
14788 i,
14789 (
14790 start_anchor,
14791 InlineDiagnostic {
14792 message,
14793 group_id: diagnostic_entry.diagnostic.group_id,
14794 start: diagnostic_entry.range.start.to_point(&snapshot),
14795 is_primary: diagnostic_entry.diagnostic.is_primary,
14796 severity: diagnostic_entry.diagnostic.severity,
14797 },
14798 ),
14799 );
14800 }
14801 inline_diagnostics
14802 })
14803 .await;
14804
14805 editor
14806 .update(cx, |editor, cx| {
14807 editor.inline_diagnostics = new_inline_diagnostics;
14808 cx.notify();
14809 })
14810 .ok();
14811 });
14812 }
14813
14814 pub fn set_selections_from_remote(
14815 &mut self,
14816 selections: Vec<Selection<Anchor>>,
14817 pending_selection: Option<Selection<Anchor>>,
14818 window: &mut Window,
14819 cx: &mut Context<Self>,
14820 ) {
14821 let old_cursor_position = self.selections.newest_anchor().head();
14822 self.selections.change_with(cx, |s| {
14823 s.select_anchors(selections);
14824 if let Some(pending_selection) = pending_selection {
14825 s.set_pending(pending_selection, SelectMode::Character);
14826 } else {
14827 s.clear_pending();
14828 }
14829 });
14830 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14831 }
14832
14833 fn push_to_selection_history(&mut self) {
14834 self.selection_history.push(SelectionHistoryEntry {
14835 selections: self.selections.disjoint_anchors(),
14836 select_next_state: self.select_next_state.clone(),
14837 select_prev_state: self.select_prev_state.clone(),
14838 add_selections_state: self.add_selections_state.clone(),
14839 });
14840 }
14841
14842 pub fn transact(
14843 &mut self,
14844 window: &mut Window,
14845 cx: &mut Context<Self>,
14846 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14847 ) -> Option<TransactionId> {
14848 self.start_transaction_at(Instant::now(), window, cx);
14849 update(self, window, cx);
14850 self.end_transaction_at(Instant::now(), cx)
14851 }
14852
14853 pub fn start_transaction_at(
14854 &mut self,
14855 now: Instant,
14856 window: &mut Window,
14857 cx: &mut Context<Self>,
14858 ) {
14859 self.end_selection(window, cx);
14860 if let Some(tx_id) = self
14861 .buffer
14862 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14863 {
14864 self.selection_history
14865 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14866 cx.emit(EditorEvent::TransactionBegun {
14867 transaction_id: tx_id,
14868 })
14869 }
14870 }
14871
14872 pub fn end_transaction_at(
14873 &mut self,
14874 now: Instant,
14875 cx: &mut Context<Self>,
14876 ) -> Option<TransactionId> {
14877 if let Some(transaction_id) = self
14878 .buffer
14879 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14880 {
14881 if let Some((_, end_selections)) =
14882 self.selection_history.transaction_mut(transaction_id)
14883 {
14884 *end_selections = Some(self.selections.disjoint_anchors());
14885 } else {
14886 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14887 }
14888
14889 cx.emit(EditorEvent::Edited { transaction_id });
14890 Some(transaction_id)
14891 } else {
14892 None
14893 }
14894 }
14895
14896 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14897 if self.selection_mark_mode {
14898 self.change_selections(None, window, cx, |s| {
14899 s.move_with(|_, sel| {
14900 sel.collapse_to(sel.head(), SelectionGoal::None);
14901 });
14902 })
14903 }
14904 self.selection_mark_mode = true;
14905 cx.notify();
14906 }
14907
14908 pub fn swap_selection_ends(
14909 &mut self,
14910 _: &actions::SwapSelectionEnds,
14911 window: &mut Window,
14912 cx: &mut Context<Self>,
14913 ) {
14914 self.change_selections(None, window, cx, |s| {
14915 s.move_with(|_, sel| {
14916 if sel.start != sel.end {
14917 sel.reversed = !sel.reversed
14918 }
14919 });
14920 });
14921 self.request_autoscroll(Autoscroll::newest(), cx);
14922 cx.notify();
14923 }
14924
14925 pub fn toggle_fold(
14926 &mut self,
14927 _: &actions::ToggleFold,
14928 window: &mut Window,
14929 cx: &mut Context<Self>,
14930 ) {
14931 if self.is_singleton(cx) {
14932 let selection = self.selections.newest::<Point>(cx);
14933
14934 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14935 let range = if selection.is_empty() {
14936 let point = selection.head().to_display_point(&display_map);
14937 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14938 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14939 .to_point(&display_map);
14940 start..end
14941 } else {
14942 selection.range()
14943 };
14944 if display_map.folds_in_range(range).next().is_some() {
14945 self.unfold_lines(&Default::default(), window, cx)
14946 } else {
14947 self.fold(&Default::default(), window, cx)
14948 }
14949 } else {
14950 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14951 let buffer_ids: HashSet<_> = self
14952 .selections
14953 .disjoint_anchor_ranges()
14954 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14955 .collect();
14956
14957 let should_unfold = buffer_ids
14958 .iter()
14959 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14960
14961 for buffer_id in buffer_ids {
14962 if should_unfold {
14963 self.unfold_buffer(buffer_id, cx);
14964 } else {
14965 self.fold_buffer(buffer_id, cx);
14966 }
14967 }
14968 }
14969 }
14970
14971 pub fn toggle_fold_recursive(
14972 &mut self,
14973 _: &actions::ToggleFoldRecursive,
14974 window: &mut Window,
14975 cx: &mut Context<Self>,
14976 ) {
14977 let selection = self.selections.newest::<Point>(cx);
14978
14979 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14980 let range = if selection.is_empty() {
14981 let point = selection.head().to_display_point(&display_map);
14982 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14983 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14984 .to_point(&display_map);
14985 start..end
14986 } else {
14987 selection.range()
14988 };
14989 if display_map.folds_in_range(range).next().is_some() {
14990 self.unfold_recursive(&Default::default(), window, cx)
14991 } else {
14992 self.fold_recursive(&Default::default(), window, cx)
14993 }
14994 }
14995
14996 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14997 if self.is_singleton(cx) {
14998 let mut to_fold = Vec::new();
14999 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15000 let selections = self.selections.all_adjusted(cx);
15001
15002 for selection in selections {
15003 let range = selection.range().sorted();
15004 let buffer_start_row = range.start.row;
15005
15006 if range.start.row != range.end.row {
15007 let mut found = false;
15008 let mut row = range.start.row;
15009 while row <= range.end.row {
15010 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15011 {
15012 found = true;
15013 row = crease.range().end.row + 1;
15014 to_fold.push(crease);
15015 } else {
15016 row += 1
15017 }
15018 }
15019 if found {
15020 continue;
15021 }
15022 }
15023
15024 for row in (0..=range.start.row).rev() {
15025 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15026 if crease.range().end.row >= buffer_start_row {
15027 to_fold.push(crease);
15028 if row <= range.start.row {
15029 break;
15030 }
15031 }
15032 }
15033 }
15034 }
15035
15036 self.fold_creases(to_fold, true, window, cx);
15037 } else {
15038 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15039 let buffer_ids = self
15040 .selections
15041 .disjoint_anchor_ranges()
15042 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15043 .collect::<HashSet<_>>();
15044 for buffer_id in buffer_ids {
15045 self.fold_buffer(buffer_id, cx);
15046 }
15047 }
15048 }
15049
15050 fn fold_at_level(
15051 &mut self,
15052 fold_at: &FoldAtLevel,
15053 window: &mut Window,
15054 cx: &mut Context<Self>,
15055 ) {
15056 if !self.buffer.read(cx).is_singleton() {
15057 return;
15058 }
15059
15060 let fold_at_level = fold_at.0;
15061 let snapshot = self.buffer.read(cx).snapshot(cx);
15062 let mut to_fold = Vec::new();
15063 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15064
15065 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15066 while start_row < end_row {
15067 match self
15068 .snapshot(window, cx)
15069 .crease_for_buffer_row(MultiBufferRow(start_row))
15070 {
15071 Some(crease) => {
15072 let nested_start_row = crease.range().start.row + 1;
15073 let nested_end_row = crease.range().end.row;
15074
15075 if current_level < fold_at_level {
15076 stack.push((nested_start_row, nested_end_row, current_level + 1));
15077 } else if current_level == fold_at_level {
15078 to_fold.push(crease);
15079 }
15080
15081 start_row = nested_end_row + 1;
15082 }
15083 None => start_row += 1,
15084 }
15085 }
15086 }
15087
15088 self.fold_creases(to_fold, true, window, cx);
15089 }
15090
15091 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15092 if self.buffer.read(cx).is_singleton() {
15093 let mut fold_ranges = Vec::new();
15094 let snapshot = self.buffer.read(cx).snapshot(cx);
15095
15096 for row in 0..snapshot.max_row().0 {
15097 if let Some(foldable_range) = self
15098 .snapshot(window, cx)
15099 .crease_for_buffer_row(MultiBufferRow(row))
15100 {
15101 fold_ranges.push(foldable_range);
15102 }
15103 }
15104
15105 self.fold_creases(fold_ranges, true, window, cx);
15106 } else {
15107 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15108 editor
15109 .update_in(cx, |editor, _, cx| {
15110 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15111 editor.fold_buffer(buffer_id, cx);
15112 }
15113 })
15114 .ok();
15115 });
15116 }
15117 }
15118
15119 pub fn fold_function_bodies(
15120 &mut self,
15121 _: &actions::FoldFunctionBodies,
15122 window: &mut Window,
15123 cx: &mut Context<Self>,
15124 ) {
15125 let snapshot = self.buffer.read(cx).snapshot(cx);
15126
15127 let ranges = snapshot
15128 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15129 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15130 .collect::<Vec<_>>();
15131
15132 let creases = ranges
15133 .into_iter()
15134 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15135 .collect();
15136
15137 self.fold_creases(creases, true, window, cx);
15138 }
15139
15140 pub fn fold_recursive(
15141 &mut self,
15142 _: &actions::FoldRecursive,
15143 window: &mut Window,
15144 cx: &mut Context<Self>,
15145 ) {
15146 let mut to_fold = Vec::new();
15147 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15148 let selections = self.selections.all_adjusted(cx);
15149
15150 for selection in selections {
15151 let range = selection.range().sorted();
15152 let buffer_start_row = range.start.row;
15153
15154 if range.start.row != range.end.row {
15155 let mut found = false;
15156 for row in range.start.row..=range.end.row {
15157 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15158 found = true;
15159 to_fold.push(crease);
15160 }
15161 }
15162 if found {
15163 continue;
15164 }
15165 }
15166
15167 for row in (0..=range.start.row).rev() {
15168 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15169 if crease.range().end.row >= buffer_start_row {
15170 to_fold.push(crease);
15171 } else {
15172 break;
15173 }
15174 }
15175 }
15176 }
15177
15178 self.fold_creases(to_fold, true, window, cx);
15179 }
15180
15181 pub fn fold_at(
15182 &mut self,
15183 buffer_row: MultiBufferRow,
15184 window: &mut Window,
15185 cx: &mut Context<Self>,
15186 ) {
15187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15188
15189 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15190 let autoscroll = self
15191 .selections
15192 .all::<Point>(cx)
15193 .iter()
15194 .any(|selection| crease.range().overlaps(&selection.range()));
15195
15196 self.fold_creases(vec![crease], autoscroll, window, cx);
15197 }
15198 }
15199
15200 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15201 if self.is_singleton(cx) {
15202 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15203 let buffer = &display_map.buffer_snapshot;
15204 let selections = self.selections.all::<Point>(cx);
15205 let ranges = selections
15206 .iter()
15207 .map(|s| {
15208 let range = s.display_range(&display_map).sorted();
15209 let mut start = range.start.to_point(&display_map);
15210 let mut end = range.end.to_point(&display_map);
15211 start.column = 0;
15212 end.column = buffer.line_len(MultiBufferRow(end.row));
15213 start..end
15214 })
15215 .collect::<Vec<_>>();
15216
15217 self.unfold_ranges(&ranges, true, true, cx);
15218 } else {
15219 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15220 let buffer_ids = self
15221 .selections
15222 .disjoint_anchor_ranges()
15223 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15224 .collect::<HashSet<_>>();
15225 for buffer_id in buffer_ids {
15226 self.unfold_buffer(buffer_id, cx);
15227 }
15228 }
15229 }
15230
15231 pub fn unfold_recursive(
15232 &mut self,
15233 _: &UnfoldRecursive,
15234 _window: &mut Window,
15235 cx: &mut Context<Self>,
15236 ) {
15237 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15238 let selections = self.selections.all::<Point>(cx);
15239 let ranges = selections
15240 .iter()
15241 .map(|s| {
15242 let mut range = s.display_range(&display_map).sorted();
15243 *range.start.column_mut() = 0;
15244 *range.end.column_mut() = display_map.line_len(range.end.row());
15245 let start = range.start.to_point(&display_map);
15246 let end = range.end.to_point(&display_map);
15247 start..end
15248 })
15249 .collect::<Vec<_>>();
15250
15251 self.unfold_ranges(&ranges, true, true, cx);
15252 }
15253
15254 pub fn unfold_at(
15255 &mut self,
15256 buffer_row: MultiBufferRow,
15257 _window: &mut Window,
15258 cx: &mut Context<Self>,
15259 ) {
15260 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15261
15262 let intersection_range = Point::new(buffer_row.0, 0)
15263 ..Point::new(
15264 buffer_row.0,
15265 display_map.buffer_snapshot.line_len(buffer_row),
15266 );
15267
15268 let autoscroll = self
15269 .selections
15270 .all::<Point>(cx)
15271 .iter()
15272 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15273
15274 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15275 }
15276
15277 pub fn unfold_all(
15278 &mut self,
15279 _: &actions::UnfoldAll,
15280 _window: &mut Window,
15281 cx: &mut Context<Self>,
15282 ) {
15283 if self.buffer.read(cx).is_singleton() {
15284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15285 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15286 } else {
15287 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15288 editor
15289 .update(cx, |editor, cx| {
15290 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15291 editor.unfold_buffer(buffer_id, cx);
15292 }
15293 })
15294 .ok();
15295 });
15296 }
15297 }
15298
15299 pub fn fold_selected_ranges(
15300 &mut self,
15301 _: &FoldSelectedRanges,
15302 window: &mut Window,
15303 cx: &mut Context<Self>,
15304 ) {
15305 let selections = self.selections.all_adjusted(cx);
15306 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15307 let ranges = selections
15308 .into_iter()
15309 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15310 .collect::<Vec<_>>();
15311 self.fold_creases(ranges, true, window, cx);
15312 }
15313
15314 pub fn fold_ranges<T: ToOffset + Clone>(
15315 &mut self,
15316 ranges: Vec<Range<T>>,
15317 auto_scroll: bool,
15318 window: &mut Window,
15319 cx: &mut Context<Self>,
15320 ) {
15321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15322 let ranges = ranges
15323 .into_iter()
15324 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15325 .collect::<Vec<_>>();
15326 self.fold_creases(ranges, auto_scroll, window, cx);
15327 }
15328
15329 pub fn fold_creases<T: ToOffset + Clone>(
15330 &mut self,
15331 creases: Vec<Crease<T>>,
15332 auto_scroll: bool,
15333 _window: &mut Window,
15334 cx: &mut Context<Self>,
15335 ) {
15336 if creases.is_empty() {
15337 return;
15338 }
15339
15340 let mut buffers_affected = HashSet::default();
15341 let multi_buffer = self.buffer().read(cx);
15342 for crease in &creases {
15343 if let Some((_, buffer, _)) =
15344 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15345 {
15346 buffers_affected.insert(buffer.read(cx).remote_id());
15347 };
15348 }
15349
15350 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15351
15352 if auto_scroll {
15353 self.request_autoscroll(Autoscroll::fit(), cx);
15354 }
15355
15356 cx.notify();
15357
15358 self.scrollbar_marker_state.dirty = true;
15359 self.folds_did_change(cx);
15360 }
15361
15362 /// Removes any folds whose ranges intersect any of the given ranges.
15363 pub fn unfold_ranges<T: ToOffset + Clone>(
15364 &mut self,
15365 ranges: &[Range<T>],
15366 inclusive: bool,
15367 auto_scroll: bool,
15368 cx: &mut Context<Self>,
15369 ) {
15370 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15371 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15372 });
15373 self.folds_did_change(cx);
15374 }
15375
15376 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15377 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15378 return;
15379 }
15380 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15381 self.display_map.update(cx, |display_map, cx| {
15382 display_map.fold_buffers([buffer_id], cx)
15383 });
15384 cx.emit(EditorEvent::BufferFoldToggled {
15385 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15386 folded: true,
15387 });
15388 cx.notify();
15389 }
15390
15391 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15392 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15393 return;
15394 }
15395 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15396 self.display_map.update(cx, |display_map, cx| {
15397 display_map.unfold_buffers([buffer_id], cx);
15398 });
15399 cx.emit(EditorEvent::BufferFoldToggled {
15400 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15401 folded: false,
15402 });
15403 cx.notify();
15404 }
15405
15406 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15407 self.display_map.read(cx).is_buffer_folded(buffer)
15408 }
15409
15410 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15411 self.display_map.read(cx).folded_buffers()
15412 }
15413
15414 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15415 self.display_map.update(cx, |display_map, cx| {
15416 display_map.disable_header_for_buffer(buffer_id, cx);
15417 });
15418 cx.notify();
15419 }
15420
15421 /// Removes any folds with the given ranges.
15422 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15423 &mut self,
15424 ranges: &[Range<T>],
15425 type_id: TypeId,
15426 auto_scroll: bool,
15427 cx: &mut Context<Self>,
15428 ) {
15429 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15430 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15431 });
15432 self.folds_did_change(cx);
15433 }
15434
15435 fn remove_folds_with<T: ToOffset + Clone>(
15436 &mut self,
15437 ranges: &[Range<T>],
15438 auto_scroll: bool,
15439 cx: &mut Context<Self>,
15440 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15441 ) {
15442 if ranges.is_empty() {
15443 return;
15444 }
15445
15446 let mut buffers_affected = HashSet::default();
15447 let multi_buffer = self.buffer().read(cx);
15448 for range in ranges {
15449 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15450 buffers_affected.insert(buffer.read(cx).remote_id());
15451 };
15452 }
15453
15454 self.display_map.update(cx, update);
15455
15456 if auto_scroll {
15457 self.request_autoscroll(Autoscroll::fit(), cx);
15458 }
15459
15460 cx.notify();
15461 self.scrollbar_marker_state.dirty = true;
15462 self.active_indent_guides_state.dirty = true;
15463 }
15464
15465 pub fn update_fold_widths(
15466 &mut self,
15467 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15468 cx: &mut Context<Self>,
15469 ) -> bool {
15470 self.display_map
15471 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15472 }
15473
15474 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15475 self.display_map.read(cx).fold_placeholder.clone()
15476 }
15477
15478 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15479 self.buffer.update(cx, |buffer, cx| {
15480 buffer.set_all_diff_hunks_expanded(cx);
15481 });
15482 }
15483
15484 pub fn expand_all_diff_hunks(
15485 &mut self,
15486 _: &ExpandAllDiffHunks,
15487 _window: &mut Window,
15488 cx: &mut Context<Self>,
15489 ) {
15490 self.buffer.update(cx, |buffer, cx| {
15491 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15492 });
15493 }
15494
15495 pub fn toggle_selected_diff_hunks(
15496 &mut self,
15497 _: &ToggleSelectedDiffHunks,
15498 _window: &mut Window,
15499 cx: &mut Context<Self>,
15500 ) {
15501 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15502 self.toggle_diff_hunks_in_ranges(ranges, cx);
15503 }
15504
15505 pub fn diff_hunks_in_ranges<'a>(
15506 &'a self,
15507 ranges: &'a [Range<Anchor>],
15508 buffer: &'a MultiBufferSnapshot,
15509 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15510 ranges.iter().flat_map(move |range| {
15511 let end_excerpt_id = range.end.excerpt_id;
15512 let range = range.to_point(buffer);
15513 let mut peek_end = range.end;
15514 if range.end.row < buffer.max_row().0 {
15515 peek_end = Point::new(range.end.row + 1, 0);
15516 }
15517 buffer
15518 .diff_hunks_in_range(range.start..peek_end)
15519 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15520 })
15521 }
15522
15523 pub fn has_stageable_diff_hunks_in_ranges(
15524 &self,
15525 ranges: &[Range<Anchor>],
15526 snapshot: &MultiBufferSnapshot,
15527 ) -> bool {
15528 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15529 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15530 }
15531
15532 pub fn toggle_staged_selected_diff_hunks(
15533 &mut self,
15534 _: &::git::ToggleStaged,
15535 _: &mut Window,
15536 cx: &mut Context<Self>,
15537 ) {
15538 let snapshot = self.buffer.read(cx).snapshot(cx);
15539 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15540 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15541 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15542 }
15543
15544 pub fn set_render_diff_hunk_controls(
15545 &mut self,
15546 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15547 cx: &mut Context<Self>,
15548 ) {
15549 self.render_diff_hunk_controls = render_diff_hunk_controls;
15550 cx.notify();
15551 }
15552
15553 pub fn stage_and_next(
15554 &mut self,
15555 _: &::git::StageAndNext,
15556 window: &mut Window,
15557 cx: &mut Context<Self>,
15558 ) {
15559 self.do_stage_or_unstage_and_next(true, window, cx);
15560 }
15561
15562 pub fn unstage_and_next(
15563 &mut self,
15564 _: &::git::UnstageAndNext,
15565 window: &mut Window,
15566 cx: &mut Context<Self>,
15567 ) {
15568 self.do_stage_or_unstage_and_next(false, window, cx);
15569 }
15570
15571 pub fn stage_or_unstage_diff_hunks(
15572 &mut self,
15573 stage: bool,
15574 ranges: Vec<Range<Anchor>>,
15575 cx: &mut Context<Self>,
15576 ) {
15577 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15578 cx.spawn(async move |this, cx| {
15579 task.await?;
15580 this.update(cx, |this, cx| {
15581 let snapshot = this.buffer.read(cx).snapshot(cx);
15582 let chunk_by = this
15583 .diff_hunks_in_ranges(&ranges, &snapshot)
15584 .chunk_by(|hunk| hunk.buffer_id);
15585 for (buffer_id, hunks) in &chunk_by {
15586 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15587 }
15588 })
15589 })
15590 .detach_and_log_err(cx);
15591 }
15592
15593 fn save_buffers_for_ranges_if_needed(
15594 &mut self,
15595 ranges: &[Range<Anchor>],
15596 cx: &mut Context<Editor>,
15597 ) -> Task<Result<()>> {
15598 let multibuffer = self.buffer.read(cx);
15599 let snapshot = multibuffer.read(cx);
15600 let buffer_ids: HashSet<_> = ranges
15601 .iter()
15602 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15603 .collect();
15604 drop(snapshot);
15605
15606 let mut buffers = HashSet::default();
15607 for buffer_id in buffer_ids {
15608 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15609 let buffer = buffer_entity.read(cx);
15610 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15611 {
15612 buffers.insert(buffer_entity);
15613 }
15614 }
15615 }
15616
15617 if let Some(project) = &self.project {
15618 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15619 } else {
15620 Task::ready(Ok(()))
15621 }
15622 }
15623
15624 fn do_stage_or_unstage_and_next(
15625 &mut self,
15626 stage: bool,
15627 window: &mut Window,
15628 cx: &mut Context<Self>,
15629 ) {
15630 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15631
15632 if ranges.iter().any(|range| range.start != range.end) {
15633 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15634 return;
15635 }
15636
15637 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15638 let snapshot = self.snapshot(window, cx);
15639 let position = self.selections.newest::<Point>(cx).head();
15640 let mut row = snapshot
15641 .buffer_snapshot
15642 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15643 .find(|hunk| hunk.row_range.start.0 > position.row)
15644 .map(|hunk| hunk.row_range.start);
15645
15646 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15647 // Outside of the project diff editor, wrap around to the beginning.
15648 if !all_diff_hunks_expanded {
15649 row = row.or_else(|| {
15650 snapshot
15651 .buffer_snapshot
15652 .diff_hunks_in_range(Point::zero()..position)
15653 .find(|hunk| hunk.row_range.end.0 < position.row)
15654 .map(|hunk| hunk.row_range.start)
15655 });
15656 }
15657
15658 if let Some(row) = row {
15659 let destination = Point::new(row.0, 0);
15660 let autoscroll = Autoscroll::center();
15661
15662 self.unfold_ranges(&[destination..destination], false, false, cx);
15663 self.change_selections(Some(autoscroll), window, cx, |s| {
15664 s.select_ranges([destination..destination]);
15665 });
15666 }
15667 }
15668
15669 fn do_stage_or_unstage(
15670 &self,
15671 stage: bool,
15672 buffer_id: BufferId,
15673 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15674 cx: &mut App,
15675 ) -> Option<()> {
15676 let project = self.project.as_ref()?;
15677 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15678 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15679 let buffer_snapshot = buffer.read(cx).snapshot();
15680 let file_exists = buffer_snapshot
15681 .file()
15682 .is_some_and(|file| file.disk_state().exists());
15683 diff.update(cx, |diff, cx| {
15684 diff.stage_or_unstage_hunks(
15685 stage,
15686 &hunks
15687 .map(|hunk| buffer_diff::DiffHunk {
15688 buffer_range: hunk.buffer_range,
15689 diff_base_byte_range: hunk.diff_base_byte_range,
15690 secondary_status: hunk.secondary_status,
15691 range: Point::zero()..Point::zero(), // unused
15692 })
15693 .collect::<Vec<_>>(),
15694 &buffer_snapshot,
15695 file_exists,
15696 cx,
15697 )
15698 });
15699 None
15700 }
15701
15702 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15703 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15704 self.buffer
15705 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15706 }
15707
15708 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15709 self.buffer.update(cx, |buffer, cx| {
15710 let ranges = vec![Anchor::min()..Anchor::max()];
15711 if !buffer.all_diff_hunks_expanded()
15712 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15713 {
15714 buffer.collapse_diff_hunks(ranges, cx);
15715 true
15716 } else {
15717 false
15718 }
15719 })
15720 }
15721
15722 fn toggle_diff_hunks_in_ranges(
15723 &mut self,
15724 ranges: Vec<Range<Anchor>>,
15725 cx: &mut Context<Editor>,
15726 ) {
15727 self.buffer.update(cx, |buffer, cx| {
15728 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15729 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15730 })
15731 }
15732
15733 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15734 self.buffer.update(cx, |buffer, cx| {
15735 let snapshot = buffer.snapshot(cx);
15736 let excerpt_id = range.end.excerpt_id;
15737 let point_range = range.to_point(&snapshot);
15738 let expand = !buffer.single_hunk_is_expanded(range, cx);
15739 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15740 })
15741 }
15742
15743 pub(crate) fn apply_all_diff_hunks(
15744 &mut self,
15745 _: &ApplyAllDiffHunks,
15746 window: &mut Window,
15747 cx: &mut Context<Self>,
15748 ) {
15749 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15750
15751 let buffers = self.buffer.read(cx).all_buffers();
15752 for branch_buffer in buffers {
15753 branch_buffer.update(cx, |branch_buffer, cx| {
15754 branch_buffer.merge_into_base(Vec::new(), cx);
15755 });
15756 }
15757
15758 if let Some(project) = self.project.clone() {
15759 self.save(true, project, window, cx).detach_and_log_err(cx);
15760 }
15761 }
15762
15763 pub(crate) fn apply_selected_diff_hunks(
15764 &mut self,
15765 _: &ApplyDiffHunk,
15766 window: &mut Window,
15767 cx: &mut Context<Self>,
15768 ) {
15769 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15770 let snapshot = self.snapshot(window, cx);
15771 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15772 let mut ranges_by_buffer = HashMap::default();
15773 self.transact(window, cx, |editor, _window, cx| {
15774 for hunk in hunks {
15775 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15776 ranges_by_buffer
15777 .entry(buffer.clone())
15778 .or_insert_with(Vec::new)
15779 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15780 }
15781 }
15782
15783 for (buffer, ranges) in ranges_by_buffer {
15784 buffer.update(cx, |buffer, cx| {
15785 buffer.merge_into_base(ranges, cx);
15786 });
15787 }
15788 });
15789
15790 if let Some(project) = self.project.clone() {
15791 self.save(true, project, window, cx).detach_and_log_err(cx);
15792 }
15793 }
15794
15795 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15796 if hovered != self.gutter_hovered {
15797 self.gutter_hovered = hovered;
15798 cx.notify();
15799 }
15800 }
15801
15802 pub fn insert_blocks(
15803 &mut self,
15804 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15805 autoscroll: Option<Autoscroll>,
15806 cx: &mut Context<Self>,
15807 ) -> Vec<CustomBlockId> {
15808 let blocks = self
15809 .display_map
15810 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15811 if let Some(autoscroll) = autoscroll {
15812 self.request_autoscroll(autoscroll, cx);
15813 }
15814 cx.notify();
15815 blocks
15816 }
15817
15818 pub fn resize_blocks(
15819 &mut self,
15820 heights: HashMap<CustomBlockId, u32>,
15821 autoscroll: Option<Autoscroll>,
15822 cx: &mut Context<Self>,
15823 ) {
15824 self.display_map
15825 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15826 if let Some(autoscroll) = autoscroll {
15827 self.request_autoscroll(autoscroll, cx);
15828 }
15829 cx.notify();
15830 }
15831
15832 pub fn replace_blocks(
15833 &mut self,
15834 renderers: HashMap<CustomBlockId, RenderBlock>,
15835 autoscroll: Option<Autoscroll>,
15836 cx: &mut Context<Self>,
15837 ) {
15838 self.display_map
15839 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15840 if let Some(autoscroll) = autoscroll {
15841 self.request_autoscroll(autoscroll, cx);
15842 }
15843 cx.notify();
15844 }
15845
15846 pub fn remove_blocks(
15847 &mut self,
15848 block_ids: HashSet<CustomBlockId>,
15849 autoscroll: Option<Autoscroll>,
15850 cx: &mut Context<Self>,
15851 ) {
15852 self.display_map.update(cx, |display_map, cx| {
15853 display_map.remove_blocks(block_ids, cx)
15854 });
15855 if let Some(autoscroll) = autoscroll {
15856 self.request_autoscroll(autoscroll, cx);
15857 }
15858 cx.notify();
15859 }
15860
15861 pub fn row_for_block(
15862 &self,
15863 block_id: CustomBlockId,
15864 cx: &mut Context<Self>,
15865 ) -> Option<DisplayRow> {
15866 self.display_map
15867 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15868 }
15869
15870 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15871 self.focused_block = Some(focused_block);
15872 }
15873
15874 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15875 self.focused_block.take()
15876 }
15877
15878 pub fn insert_creases(
15879 &mut self,
15880 creases: impl IntoIterator<Item = Crease<Anchor>>,
15881 cx: &mut Context<Self>,
15882 ) -> Vec<CreaseId> {
15883 self.display_map
15884 .update(cx, |map, cx| map.insert_creases(creases, cx))
15885 }
15886
15887 pub fn remove_creases(
15888 &mut self,
15889 ids: impl IntoIterator<Item = CreaseId>,
15890 cx: &mut Context<Self>,
15891 ) {
15892 self.display_map
15893 .update(cx, |map, cx| map.remove_creases(ids, cx));
15894 }
15895
15896 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15897 self.display_map
15898 .update(cx, |map, cx| map.snapshot(cx))
15899 .longest_row()
15900 }
15901
15902 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15903 self.display_map
15904 .update(cx, |map, cx| map.snapshot(cx))
15905 .max_point()
15906 }
15907
15908 pub fn text(&self, cx: &App) -> String {
15909 self.buffer.read(cx).read(cx).text()
15910 }
15911
15912 pub fn is_empty(&self, cx: &App) -> bool {
15913 self.buffer.read(cx).read(cx).is_empty()
15914 }
15915
15916 pub fn text_option(&self, cx: &App) -> Option<String> {
15917 let text = self.text(cx);
15918 let text = text.trim();
15919
15920 if text.is_empty() {
15921 return None;
15922 }
15923
15924 Some(text.to_string())
15925 }
15926
15927 pub fn set_text(
15928 &mut self,
15929 text: impl Into<Arc<str>>,
15930 window: &mut Window,
15931 cx: &mut Context<Self>,
15932 ) {
15933 self.transact(window, cx, |this, _, cx| {
15934 this.buffer
15935 .read(cx)
15936 .as_singleton()
15937 .expect("you can only call set_text on editors for singleton buffers")
15938 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15939 });
15940 }
15941
15942 pub fn display_text(&self, cx: &mut App) -> String {
15943 self.display_map
15944 .update(cx, |map, cx| map.snapshot(cx))
15945 .text()
15946 }
15947
15948 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15949 let mut wrap_guides = smallvec::smallvec![];
15950
15951 if self.show_wrap_guides == Some(false) {
15952 return wrap_guides;
15953 }
15954
15955 let settings = self.buffer.read(cx).language_settings(cx);
15956 if settings.show_wrap_guides {
15957 match self.soft_wrap_mode(cx) {
15958 SoftWrap::Column(soft_wrap) => {
15959 wrap_guides.push((soft_wrap as usize, true));
15960 }
15961 SoftWrap::Bounded(soft_wrap) => {
15962 wrap_guides.push((soft_wrap as usize, true));
15963 }
15964 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15965 }
15966 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15967 }
15968
15969 wrap_guides
15970 }
15971
15972 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15973 let settings = self.buffer.read(cx).language_settings(cx);
15974 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15975 match mode {
15976 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15977 SoftWrap::None
15978 }
15979 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15980 language_settings::SoftWrap::PreferredLineLength => {
15981 SoftWrap::Column(settings.preferred_line_length)
15982 }
15983 language_settings::SoftWrap::Bounded => {
15984 SoftWrap::Bounded(settings.preferred_line_length)
15985 }
15986 }
15987 }
15988
15989 pub fn set_soft_wrap_mode(
15990 &mut self,
15991 mode: language_settings::SoftWrap,
15992
15993 cx: &mut Context<Self>,
15994 ) {
15995 self.soft_wrap_mode_override = Some(mode);
15996 cx.notify();
15997 }
15998
15999 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16000 self.hard_wrap = hard_wrap;
16001 cx.notify();
16002 }
16003
16004 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16005 self.text_style_refinement = Some(style);
16006 }
16007
16008 /// called by the Element so we know what style we were most recently rendered with.
16009 pub(crate) fn set_style(
16010 &mut self,
16011 style: EditorStyle,
16012 window: &mut Window,
16013 cx: &mut Context<Self>,
16014 ) {
16015 let rem_size = window.rem_size();
16016 self.display_map.update(cx, |map, cx| {
16017 map.set_font(
16018 style.text.font(),
16019 style.text.font_size.to_pixels(rem_size),
16020 cx,
16021 )
16022 });
16023 self.style = Some(style);
16024 }
16025
16026 pub fn style(&self) -> Option<&EditorStyle> {
16027 self.style.as_ref()
16028 }
16029
16030 // Called by the element. This method is not designed to be called outside of the editor
16031 // element's layout code because it does not notify when rewrapping is computed synchronously.
16032 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16033 self.display_map
16034 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16035 }
16036
16037 pub fn set_soft_wrap(&mut self) {
16038 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16039 }
16040
16041 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16042 if self.soft_wrap_mode_override.is_some() {
16043 self.soft_wrap_mode_override.take();
16044 } else {
16045 let soft_wrap = match self.soft_wrap_mode(cx) {
16046 SoftWrap::GitDiff => return,
16047 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16048 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16049 language_settings::SoftWrap::None
16050 }
16051 };
16052 self.soft_wrap_mode_override = Some(soft_wrap);
16053 }
16054 cx.notify();
16055 }
16056
16057 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16058 let Some(workspace) = self.workspace() else {
16059 return;
16060 };
16061 let fs = workspace.read(cx).app_state().fs.clone();
16062 let current_show = TabBarSettings::get_global(cx).show;
16063 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16064 setting.show = Some(!current_show);
16065 });
16066 }
16067
16068 pub fn toggle_indent_guides(
16069 &mut self,
16070 _: &ToggleIndentGuides,
16071 _: &mut Window,
16072 cx: &mut Context<Self>,
16073 ) {
16074 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16075 self.buffer
16076 .read(cx)
16077 .language_settings(cx)
16078 .indent_guides
16079 .enabled
16080 });
16081 self.show_indent_guides = Some(!currently_enabled);
16082 cx.notify();
16083 }
16084
16085 fn should_show_indent_guides(&self) -> Option<bool> {
16086 self.show_indent_guides
16087 }
16088
16089 pub fn toggle_line_numbers(
16090 &mut self,
16091 _: &ToggleLineNumbers,
16092 _: &mut Window,
16093 cx: &mut Context<Self>,
16094 ) {
16095 let mut editor_settings = EditorSettings::get_global(cx).clone();
16096 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16097 EditorSettings::override_global(editor_settings, cx);
16098 }
16099
16100 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16101 if let Some(show_line_numbers) = self.show_line_numbers {
16102 return show_line_numbers;
16103 }
16104 EditorSettings::get_global(cx).gutter.line_numbers
16105 }
16106
16107 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16108 self.use_relative_line_numbers
16109 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16110 }
16111
16112 pub fn toggle_relative_line_numbers(
16113 &mut self,
16114 _: &ToggleRelativeLineNumbers,
16115 _: &mut Window,
16116 cx: &mut Context<Self>,
16117 ) {
16118 let is_relative = self.should_use_relative_line_numbers(cx);
16119 self.set_relative_line_number(Some(!is_relative), cx)
16120 }
16121
16122 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16123 self.use_relative_line_numbers = is_relative;
16124 cx.notify();
16125 }
16126
16127 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16128 self.show_gutter = show_gutter;
16129 cx.notify();
16130 }
16131
16132 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16133 self.show_scrollbars = show_scrollbars;
16134 cx.notify();
16135 }
16136
16137 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16138 self.show_line_numbers = Some(show_line_numbers);
16139 cx.notify();
16140 }
16141
16142 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16143 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16144 cx.notify();
16145 }
16146
16147 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16148 self.show_code_actions = Some(show_code_actions);
16149 cx.notify();
16150 }
16151
16152 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16153 self.show_runnables = Some(show_runnables);
16154 cx.notify();
16155 }
16156
16157 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16158 self.show_breakpoints = Some(show_breakpoints);
16159 cx.notify();
16160 }
16161
16162 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16163 if self.display_map.read(cx).masked != masked {
16164 self.display_map.update(cx, |map, _| map.masked = masked);
16165 }
16166 cx.notify()
16167 }
16168
16169 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16170 self.show_wrap_guides = Some(show_wrap_guides);
16171 cx.notify();
16172 }
16173
16174 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16175 self.show_indent_guides = Some(show_indent_guides);
16176 cx.notify();
16177 }
16178
16179 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16180 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16181 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16182 if let Some(dir) = file.abs_path(cx).parent() {
16183 return Some(dir.to_owned());
16184 }
16185 }
16186
16187 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16188 return Some(project_path.path.to_path_buf());
16189 }
16190 }
16191
16192 None
16193 }
16194
16195 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16196 self.active_excerpt(cx)?
16197 .1
16198 .read(cx)
16199 .file()
16200 .and_then(|f| f.as_local())
16201 }
16202
16203 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16204 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16205 let buffer = buffer.read(cx);
16206 if let Some(project_path) = buffer.project_path(cx) {
16207 let project = self.project.as_ref()?.read(cx);
16208 project.absolute_path(&project_path, cx)
16209 } else {
16210 buffer
16211 .file()
16212 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16213 }
16214 })
16215 }
16216
16217 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16218 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16219 let project_path = buffer.read(cx).project_path(cx)?;
16220 let project = self.project.as_ref()?.read(cx);
16221 let entry = project.entry_for_path(&project_path, cx)?;
16222 let path = entry.path.to_path_buf();
16223 Some(path)
16224 })
16225 }
16226
16227 pub fn reveal_in_finder(
16228 &mut self,
16229 _: &RevealInFileManager,
16230 _window: &mut Window,
16231 cx: &mut Context<Self>,
16232 ) {
16233 if let Some(target) = self.target_file(cx) {
16234 cx.reveal_path(&target.abs_path(cx));
16235 }
16236 }
16237
16238 pub fn copy_path(
16239 &mut self,
16240 _: &zed_actions::workspace::CopyPath,
16241 _window: &mut Window,
16242 cx: &mut Context<Self>,
16243 ) {
16244 if let Some(path) = self.target_file_abs_path(cx) {
16245 if let Some(path) = path.to_str() {
16246 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16247 }
16248 }
16249 }
16250
16251 pub fn copy_relative_path(
16252 &mut self,
16253 _: &zed_actions::workspace::CopyRelativePath,
16254 _window: &mut Window,
16255 cx: &mut Context<Self>,
16256 ) {
16257 if let Some(path) = self.target_file_path(cx) {
16258 if let Some(path) = path.to_str() {
16259 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16260 }
16261 }
16262 }
16263
16264 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16265 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16266 buffer.read(cx).project_path(cx)
16267 } else {
16268 None
16269 }
16270 }
16271
16272 // Returns true if the editor handled a go-to-line request
16273 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16274 maybe!({
16275 let breakpoint_store = self.breakpoint_store.as_ref()?;
16276
16277 let Some((_, _, active_position)) =
16278 breakpoint_store.read(cx).active_position().cloned()
16279 else {
16280 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16281 return None;
16282 };
16283
16284 let snapshot = self
16285 .project
16286 .as_ref()?
16287 .read(cx)
16288 .buffer_for_id(active_position.buffer_id?, cx)?
16289 .read(cx)
16290 .snapshot();
16291
16292 let mut handled = false;
16293 for (id, ExcerptRange { context, .. }) in self
16294 .buffer
16295 .read(cx)
16296 .excerpts_for_buffer(active_position.buffer_id?, cx)
16297 {
16298 if context.start.cmp(&active_position, &snapshot).is_ge()
16299 || context.end.cmp(&active_position, &snapshot).is_lt()
16300 {
16301 continue;
16302 }
16303 let snapshot = self.buffer.read(cx).snapshot(cx);
16304 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16305
16306 handled = true;
16307 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16308 self.go_to_line::<DebugCurrentRowHighlight>(
16309 multibuffer_anchor,
16310 Some(cx.theme().colors().editor_debugger_active_line_background),
16311 window,
16312 cx,
16313 );
16314
16315 cx.notify();
16316 }
16317 handled.then_some(())
16318 })
16319 .is_some()
16320 }
16321
16322 pub fn copy_file_name_without_extension(
16323 &mut self,
16324 _: &CopyFileNameWithoutExtension,
16325 _: &mut Window,
16326 cx: &mut Context<Self>,
16327 ) {
16328 if let Some(file) = self.target_file(cx) {
16329 if let Some(file_stem) = file.path().file_stem() {
16330 if let Some(name) = file_stem.to_str() {
16331 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16332 }
16333 }
16334 }
16335 }
16336
16337 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16338 if let Some(file) = self.target_file(cx) {
16339 if let Some(file_name) = file.path().file_name() {
16340 if let Some(name) = file_name.to_str() {
16341 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16342 }
16343 }
16344 }
16345 }
16346
16347 pub fn toggle_git_blame(
16348 &mut self,
16349 _: &::git::Blame,
16350 window: &mut Window,
16351 cx: &mut Context<Self>,
16352 ) {
16353 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16354
16355 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16356 self.start_git_blame(true, window, cx);
16357 }
16358
16359 cx.notify();
16360 }
16361
16362 pub fn toggle_git_blame_inline(
16363 &mut self,
16364 _: &ToggleGitBlameInline,
16365 window: &mut Window,
16366 cx: &mut Context<Self>,
16367 ) {
16368 self.toggle_git_blame_inline_internal(true, window, cx);
16369 cx.notify();
16370 }
16371
16372 pub fn open_git_blame_commit(
16373 &mut self,
16374 _: &OpenGitBlameCommit,
16375 window: &mut Window,
16376 cx: &mut Context<Self>,
16377 ) {
16378 self.open_git_blame_commit_internal(window, cx);
16379 }
16380
16381 fn open_git_blame_commit_internal(
16382 &mut self,
16383 window: &mut Window,
16384 cx: &mut Context<Self>,
16385 ) -> Option<()> {
16386 let blame = self.blame.as_ref()?;
16387 let snapshot = self.snapshot(window, cx);
16388 let cursor = self.selections.newest::<Point>(cx).head();
16389 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16390 let blame_entry = blame
16391 .update(cx, |blame, cx| {
16392 blame
16393 .blame_for_rows(
16394 &[RowInfo {
16395 buffer_id: Some(buffer.remote_id()),
16396 buffer_row: Some(point.row),
16397 ..Default::default()
16398 }],
16399 cx,
16400 )
16401 .next()
16402 })
16403 .flatten()?;
16404 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16405 let repo = blame.read(cx).repository(cx)?;
16406 let workspace = self.workspace()?.downgrade();
16407 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16408 None
16409 }
16410
16411 pub fn git_blame_inline_enabled(&self) -> bool {
16412 self.git_blame_inline_enabled
16413 }
16414
16415 pub fn toggle_selection_menu(
16416 &mut self,
16417 _: &ToggleSelectionMenu,
16418 _: &mut Window,
16419 cx: &mut Context<Self>,
16420 ) {
16421 self.show_selection_menu = self
16422 .show_selection_menu
16423 .map(|show_selections_menu| !show_selections_menu)
16424 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16425
16426 cx.notify();
16427 }
16428
16429 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16430 self.show_selection_menu
16431 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16432 }
16433
16434 fn start_git_blame(
16435 &mut self,
16436 user_triggered: bool,
16437 window: &mut Window,
16438 cx: &mut Context<Self>,
16439 ) {
16440 if let Some(project) = self.project.as_ref() {
16441 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16442 return;
16443 };
16444
16445 if buffer.read(cx).file().is_none() {
16446 return;
16447 }
16448
16449 let focused = self.focus_handle(cx).contains_focused(window, cx);
16450
16451 let project = project.clone();
16452 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16453 self.blame_subscription =
16454 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16455 self.blame = Some(blame);
16456 }
16457 }
16458
16459 fn toggle_git_blame_inline_internal(
16460 &mut self,
16461 user_triggered: bool,
16462 window: &mut Window,
16463 cx: &mut Context<Self>,
16464 ) {
16465 if self.git_blame_inline_enabled {
16466 self.git_blame_inline_enabled = false;
16467 self.show_git_blame_inline = false;
16468 self.show_git_blame_inline_delay_task.take();
16469 } else {
16470 self.git_blame_inline_enabled = true;
16471 self.start_git_blame_inline(user_triggered, window, cx);
16472 }
16473
16474 cx.notify();
16475 }
16476
16477 fn start_git_blame_inline(
16478 &mut self,
16479 user_triggered: bool,
16480 window: &mut Window,
16481 cx: &mut Context<Self>,
16482 ) {
16483 self.start_git_blame(user_triggered, window, cx);
16484
16485 if ProjectSettings::get_global(cx)
16486 .git
16487 .inline_blame_delay()
16488 .is_some()
16489 {
16490 self.start_inline_blame_timer(window, cx);
16491 } else {
16492 self.show_git_blame_inline = true
16493 }
16494 }
16495
16496 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16497 self.blame.as_ref()
16498 }
16499
16500 pub fn show_git_blame_gutter(&self) -> bool {
16501 self.show_git_blame_gutter
16502 }
16503
16504 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16505 self.show_git_blame_gutter && self.has_blame_entries(cx)
16506 }
16507
16508 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16509 self.show_git_blame_inline
16510 && (self.focus_handle.is_focused(window)
16511 || self
16512 .git_blame_inline_tooltip
16513 .as_ref()
16514 .and_then(|t| t.upgrade())
16515 .is_some())
16516 && !self.newest_selection_head_on_empty_line(cx)
16517 && self.has_blame_entries(cx)
16518 }
16519
16520 fn has_blame_entries(&self, cx: &App) -> bool {
16521 self.blame()
16522 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16523 }
16524
16525 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16526 let cursor_anchor = self.selections.newest_anchor().head();
16527
16528 let snapshot = self.buffer.read(cx).snapshot(cx);
16529 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16530
16531 snapshot.line_len(buffer_row) == 0
16532 }
16533
16534 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16535 let buffer_and_selection = maybe!({
16536 let selection = self.selections.newest::<Point>(cx);
16537 let selection_range = selection.range();
16538
16539 let multi_buffer = self.buffer().read(cx);
16540 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16541 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16542
16543 let (buffer, range, _) = if selection.reversed {
16544 buffer_ranges.first()
16545 } else {
16546 buffer_ranges.last()
16547 }?;
16548
16549 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16550 ..text::ToPoint::to_point(&range.end, &buffer).row;
16551 Some((
16552 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16553 selection,
16554 ))
16555 });
16556
16557 let Some((buffer, selection)) = buffer_and_selection else {
16558 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16559 };
16560
16561 let Some(project) = self.project.as_ref() else {
16562 return Task::ready(Err(anyhow!("editor does not have project")));
16563 };
16564
16565 project.update(cx, |project, cx| {
16566 project.get_permalink_to_line(&buffer, selection, cx)
16567 })
16568 }
16569
16570 pub fn copy_permalink_to_line(
16571 &mut self,
16572 _: &CopyPermalinkToLine,
16573 window: &mut Window,
16574 cx: &mut Context<Self>,
16575 ) {
16576 let permalink_task = self.get_permalink_to_line(cx);
16577 let workspace = self.workspace();
16578
16579 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16580 Ok(permalink) => {
16581 cx.update(|_, cx| {
16582 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16583 })
16584 .ok();
16585 }
16586 Err(err) => {
16587 let message = format!("Failed to copy permalink: {err}");
16588
16589 Err::<(), anyhow::Error>(err).log_err();
16590
16591 if let Some(workspace) = workspace {
16592 workspace
16593 .update_in(cx, |workspace, _, cx| {
16594 struct CopyPermalinkToLine;
16595
16596 workspace.show_toast(
16597 Toast::new(
16598 NotificationId::unique::<CopyPermalinkToLine>(),
16599 message,
16600 ),
16601 cx,
16602 )
16603 })
16604 .ok();
16605 }
16606 }
16607 })
16608 .detach();
16609 }
16610
16611 pub fn copy_file_location(
16612 &mut self,
16613 _: &CopyFileLocation,
16614 _: &mut Window,
16615 cx: &mut Context<Self>,
16616 ) {
16617 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16618 if let Some(file) = self.target_file(cx) {
16619 if let Some(path) = file.path().to_str() {
16620 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16621 }
16622 }
16623 }
16624
16625 pub fn open_permalink_to_line(
16626 &mut self,
16627 _: &OpenPermalinkToLine,
16628 window: &mut Window,
16629 cx: &mut Context<Self>,
16630 ) {
16631 let permalink_task = self.get_permalink_to_line(cx);
16632 let workspace = self.workspace();
16633
16634 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16635 Ok(permalink) => {
16636 cx.update(|_, cx| {
16637 cx.open_url(permalink.as_ref());
16638 })
16639 .ok();
16640 }
16641 Err(err) => {
16642 let message = format!("Failed to open permalink: {err}");
16643
16644 Err::<(), anyhow::Error>(err).log_err();
16645
16646 if let Some(workspace) = workspace {
16647 workspace
16648 .update(cx, |workspace, cx| {
16649 struct OpenPermalinkToLine;
16650
16651 workspace.show_toast(
16652 Toast::new(
16653 NotificationId::unique::<OpenPermalinkToLine>(),
16654 message,
16655 ),
16656 cx,
16657 )
16658 })
16659 .ok();
16660 }
16661 }
16662 })
16663 .detach();
16664 }
16665
16666 pub fn insert_uuid_v4(
16667 &mut self,
16668 _: &InsertUuidV4,
16669 window: &mut Window,
16670 cx: &mut Context<Self>,
16671 ) {
16672 self.insert_uuid(UuidVersion::V4, window, cx);
16673 }
16674
16675 pub fn insert_uuid_v7(
16676 &mut self,
16677 _: &InsertUuidV7,
16678 window: &mut Window,
16679 cx: &mut Context<Self>,
16680 ) {
16681 self.insert_uuid(UuidVersion::V7, window, cx);
16682 }
16683
16684 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16685 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16686 self.transact(window, cx, |this, window, cx| {
16687 let edits = this
16688 .selections
16689 .all::<Point>(cx)
16690 .into_iter()
16691 .map(|selection| {
16692 let uuid = match version {
16693 UuidVersion::V4 => uuid::Uuid::new_v4(),
16694 UuidVersion::V7 => uuid::Uuid::now_v7(),
16695 };
16696
16697 (selection.range(), uuid.to_string())
16698 });
16699 this.edit(edits, cx);
16700 this.refresh_inline_completion(true, false, window, cx);
16701 });
16702 }
16703
16704 pub fn open_selections_in_multibuffer(
16705 &mut self,
16706 _: &OpenSelectionsInMultibuffer,
16707 window: &mut Window,
16708 cx: &mut Context<Self>,
16709 ) {
16710 let multibuffer = self.buffer.read(cx);
16711
16712 let Some(buffer) = multibuffer.as_singleton() else {
16713 return;
16714 };
16715
16716 let Some(workspace) = self.workspace() else {
16717 return;
16718 };
16719
16720 let locations = self
16721 .selections
16722 .disjoint_anchors()
16723 .iter()
16724 .map(|range| Location {
16725 buffer: buffer.clone(),
16726 range: range.start.text_anchor..range.end.text_anchor,
16727 })
16728 .collect::<Vec<_>>();
16729
16730 let title = multibuffer.title(cx).to_string();
16731
16732 cx.spawn_in(window, async move |_, cx| {
16733 workspace.update_in(cx, |workspace, window, cx| {
16734 Self::open_locations_in_multibuffer(
16735 workspace,
16736 locations,
16737 format!("Selections for '{title}'"),
16738 false,
16739 MultibufferSelectionMode::All,
16740 window,
16741 cx,
16742 );
16743 })
16744 })
16745 .detach();
16746 }
16747
16748 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16749 /// last highlight added will be used.
16750 ///
16751 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16752 pub fn highlight_rows<T: 'static>(
16753 &mut self,
16754 range: Range<Anchor>,
16755 color: Hsla,
16756 should_autoscroll: bool,
16757 cx: &mut Context<Self>,
16758 ) {
16759 let snapshot = self.buffer().read(cx).snapshot(cx);
16760 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16761 let ix = row_highlights.binary_search_by(|highlight| {
16762 Ordering::Equal
16763 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16764 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16765 });
16766
16767 if let Err(mut ix) = ix {
16768 let index = post_inc(&mut self.highlight_order);
16769
16770 // If this range intersects with the preceding highlight, then merge it with
16771 // the preceding highlight. Otherwise insert a new highlight.
16772 let mut merged = false;
16773 if ix > 0 {
16774 let prev_highlight = &mut row_highlights[ix - 1];
16775 if prev_highlight
16776 .range
16777 .end
16778 .cmp(&range.start, &snapshot)
16779 .is_ge()
16780 {
16781 ix -= 1;
16782 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16783 prev_highlight.range.end = range.end;
16784 }
16785 merged = true;
16786 prev_highlight.index = index;
16787 prev_highlight.color = color;
16788 prev_highlight.should_autoscroll = should_autoscroll;
16789 }
16790 }
16791
16792 if !merged {
16793 row_highlights.insert(
16794 ix,
16795 RowHighlight {
16796 range: range.clone(),
16797 index,
16798 color,
16799 should_autoscroll,
16800 },
16801 );
16802 }
16803
16804 // If any of the following highlights intersect with this one, merge them.
16805 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16806 let highlight = &row_highlights[ix];
16807 if next_highlight
16808 .range
16809 .start
16810 .cmp(&highlight.range.end, &snapshot)
16811 .is_le()
16812 {
16813 if next_highlight
16814 .range
16815 .end
16816 .cmp(&highlight.range.end, &snapshot)
16817 .is_gt()
16818 {
16819 row_highlights[ix].range.end = next_highlight.range.end;
16820 }
16821 row_highlights.remove(ix + 1);
16822 } else {
16823 break;
16824 }
16825 }
16826 }
16827 }
16828
16829 /// Remove any highlighted row ranges of the given type that intersect the
16830 /// given ranges.
16831 pub fn remove_highlighted_rows<T: 'static>(
16832 &mut self,
16833 ranges_to_remove: Vec<Range<Anchor>>,
16834 cx: &mut Context<Self>,
16835 ) {
16836 let snapshot = self.buffer().read(cx).snapshot(cx);
16837 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16838 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16839 row_highlights.retain(|highlight| {
16840 while let Some(range_to_remove) = ranges_to_remove.peek() {
16841 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16842 Ordering::Less | Ordering::Equal => {
16843 ranges_to_remove.next();
16844 }
16845 Ordering::Greater => {
16846 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16847 Ordering::Less | Ordering::Equal => {
16848 return false;
16849 }
16850 Ordering::Greater => break,
16851 }
16852 }
16853 }
16854 }
16855
16856 true
16857 })
16858 }
16859
16860 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16861 pub fn clear_row_highlights<T: 'static>(&mut self) {
16862 self.highlighted_rows.remove(&TypeId::of::<T>());
16863 }
16864
16865 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16866 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16867 self.highlighted_rows
16868 .get(&TypeId::of::<T>())
16869 .map_or(&[] as &[_], |vec| vec.as_slice())
16870 .iter()
16871 .map(|highlight| (highlight.range.clone(), highlight.color))
16872 }
16873
16874 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16875 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16876 /// Allows to ignore certain kinds of highlights.
16877 pub fn highlighted_display_rows(
16878 &self,
16879 window: &mut Window,
16880 cx: &mut App,
16881 ) -> BTreeMap<DisplayRow, LineHighlight> {
16882 let snapshot = self.snapshot(window, cx);
16883 let mut used_highlight_orders = HashMap::default();
16884 self.highlighted_rows
16885 .iter()
16886 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16887 .fold(
16888 BTreeMap::<DisplayRow, LineHighlight>::new(),
16889 |mut unique_rows, highlight| {
16890 let start = highlight.range.start.to_display_point(&snapshot);
16891 let end = highlight.range.end.to_display_point(&snapshot);
16892 let start_row = start.row().0;
16893 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16894 && end.column() == 0
16895 {
16896 end.row().0.saturating_sub(1)
16897 } else {
16898 end.row().0
16899 };
16900 for row in start_row..=end_row {
16901 let used_index =
16902 used_highlight_orders.entry(row).or_insert(highlight.index);
16903 if highlight.index >= *used_index {
16904 *used_index = highlight.index;
16905 unique_rows.insert(DisplayRow(row), highlight.color.into());
16906 }
16907 }
16908 unique_rows
16909 },
16910 )
16911 }
16912
16913 pub fn highlighted_display_row_for_autoscroll(
16914 &self,
16915 snapshot: &DisplaySnapshot,
16916 ) -> Option<DisplayRow> {
16917 self.highlighted_rows
16918 .values()
16919 .flat_map(|highlighted_rows| highlighted_rows.iter())
16920 .filter_map(|highlight| {
16921 if highlight.should_autoscroll {
16922 Some(highlight.range.start.to_display_point(snapshot).row())
16923 } else {
16924 None
16925 }
16926 })
16927 .min()
16928 }
16929
16930 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16931 self.highlight_background::<SearchWithinRange>(
16932 ranges,
16933 |colors| colors.editor_document_highlight_read_background,
16934 cx,
16935 )
16936 }
16937
16938 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16939 self.breadcrumb_header = Some(new_header);
16940 }
16941
16942 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16943 self.clear_background_highlights::<SearchWithinRange>(cx);
16944 }
16945
16946 pub fn highlight_background<T: 'static>(
16947 &mut self,
16948 ranges: &[Range<Anchor>],
16949 color_fetcher: fn(&ThemeColors) -> Hsla,
16950 cx: &mut Context<Self>,
16951 ) {
16952 self.background_highlights
16953 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16954 self.scrollbar_marker_state.dirty = true;
16955 cx.notify();
16956 }
16957
16958 pub fn clear_background_highlights<T: 'static>(
16959 &mut self,
16960 cx: &mut Context<Self>,
16961 ) -> Option<BackgroundHighlight> {
16962 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16963 if !text_highlights.1.is_empty() {
16964 self.scrollbar_marker_state.dirty = true;
16965 cx.notify();
16966 }
16967 Some(text_highlights)
16968 }
16969
16970 pub fn highlight_gutter<T: 'static>(
16971 &mut self,
16972 ranges: &[Range<Anchor>],
16973 color_fetcher: fn(&App) -> Hsla,
16974 cx: &mut Context<Self>,
16975 ) {
16976 self.gutter_highlights
16977 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16978 cx.notify();
16979 }
16980
16981 pub fn clear_gutter_highlights<T: 'static>(
16982 &mut self,
16983 cx: &mut Context<Self>,
16984 ) -> Option<GutterHighlight> {
16985 cx.notify();
16986 self.gutter_highlights.remove(&TypeId::of::<T>())
16987 }
16988
16989 #[cfg(feature = "test-support")]
16990 pub fn all_text_background_highlights(
16991 &self,
16992 window: &mut Window,
16993 cx: &mut Context<Self>,
16994 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16995 let snapshot = self.snapshot(window, cx);
16996 let buffer = &snapshot.buffer_snapshot;
16997 let start = buffer.anchor_before(0);
16998 let end = buffer.anchor_after(buffer.len());
16999 let theme = cx.theme().colors();
17000 self.background_highlights_in_range(start..end, &snapshot, theme)
17001 }
17002
17003 #[cfg(feature = "test-support")]
17004 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17005 let snapshot = self.buffer().read(cx).snapshot(cx);
17006
17007 let highlights = self
17008 .background_highlights
17009 .get(&TypeId::of::<items::BufferSearchHighlights>());
17010
17011 if let Some((_color, ranges)) = highlights {
17012 ranges
17013 .iter()
17014 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17015 .collect_vec()
17016 } else {
17017 vec![]
17018 }
17019 }
17020
17021 fn document_highlights_for_position<'a>(
17022 &'a self,
17023 position: Anchor,
17024 buffer: &'a MultiBufferSnapshot,
17025 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17026 let read_highlights = self
17027 .background_highlights
17028 .get(&TypeId::of::<DocumentHighlightRead>())
17029 .map(|h| &h.1);
17030 let write_highlights = self
17031 .background_highlights
17032 .get(&TypeId::of::<DocumentHighlightWrite>())
17033 .map(|h| &h.1);
17034 let left_position = position.bias_left(buffer);
17035 let right_position = position.bias_right(buffer);
17036 read_highlights
17037 .into_iter()
17038 .chain(write_highlights)
17039 .flat_map(move |ranges| {
17040 let start_ix = match ranges.binary_search_by(|probe| {
17041 let cmp = probe.end.cmp(&left_position, buffer);
17042 if cmp.is_ge() {
17043 Ordering::Greater
17044 } else {
17045 Ordering::Less
17046 }
17047 }) {
17048 Ok(i) | Err(i) => i,
17049 };
17050
17051 ranges[start_ix..]
17052 .iter()
17053 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17054 })
17055 }
17056
17057 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17058 self.background_highlights
17059 .get(&TypeId::of::<T>())
17060 .map_or(false, |(_, highlights)| !highlights.is_empty())
17061 }
17062
17063 pub fn background_highlights_in_range(
17064 &self,
17065 search_range: Range<Anchor>,
17066 display_snapshot: &DisplaySnapshot,
17067 theme: &ThemeColors,
17068 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17069 let mut results = Vec::new();
17070 for (color_fetcher, ranges) in self.background_highlights.values() {
17071 let color = color_fetcher(theme);
17072 let start_ix = match ranges.binary_search_by(|probe| {
17073 let cmp = probe
17074 .end
17075 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17076 if cmp.is_gt() {
17077 Ordering::Greater
17078 } else {
17079 Ordering::Less
17080 }
17081 }) {
17082 Ok(i) | Err(i) => i,
17083 };
17084 for range in &ranges[start_ix..] {
17085 if range
17086 .start
17087 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17088 .is_ge()
17089 {
17090 break;
17091 }
17092
17093 let start = range.start.to_display_point(display_snapshot);
17094 let end = range.end.to_display_point(display_snapshot);
17095 results.push((start..end, color))
17096 }
17097 }
17098 results
17099 }
17100
17101 pub fn background_highlight_row_ranges<T: 'static>(
17102 &self,
17103 search_range: Range<Anchor>,
17104 display_snapshot: &DisplaySnapshot,
17105 count: usize,
17106 ) -> Vec<RangeInclusive<DisplayPoint>> {
17107 let mut results = Vec::new();
17108 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17109 return vec![];
17110 };
17111
17112 let start_ix = match ranges.binary_search_by(|probe| {
17113 let cmp = probe
17114 .end
17115 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17116 if cmp.is_gt() {
17117 Ordering::Greater
17118 } else {
17119 Ordering::Less
17120 }
17121 }) {
17122 Ok(i) | Err(i) => i,
17123 };
17124 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17125 if let (Some(start_display), Some(end_display)) = (start, end) {
17126 results.push(
17127 start_display.to_display_point(display_snapshot)
17128 ..=end_display.to_display_point(display_snapshot),
17129 );
17130 }
17131 };
17132 let mut start_row: Option<Point> = None;
17133 let mut end_row: Option<Point> = None;
17134 if ranges.len() > count {
17135 return Vec::new();
17136 }
17137 for range in &ranges[start_ix..] {
17138 if range
17139 .start
17140 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17141 .is_ge()
17142 {
17143 break;
17144 }
17145 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17146 if let Some(current_row) = &end_row {
17147 if end.row == current_row.row {
17148 continue;
17149 }
17150 }
17151 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17152 if start_row.is_none() {
17153 assert_eq!(end_row, None);
17154 start_row = Some(start);
17155 end_row = Some(end);
17156 continue;
17157 }
17158 if let Some(current_end) = end_row.as_mut() {
17159 if start.row > current_end.row + 1 {
17160 push_region(start_row, end_row);
17161 start_row = Some(start);
17162 end_row = Some(end);
17163 } else {
17164 // Merge two hunks.
17165 *current_end = end;
17166 }
17167 } else {
17168 unreachable!();
17169 }
17170 }
17171 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17172 push_region(start_row, end_row);
17173 results
17174 }
17175
17176 pub fn gutter_highlights_in_range(
17177 &self,
17178 search_range: Range<Anchor>,
17179 display_snapshot: &DisplaySnapshot,
17180 cx: &App,
17181 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17182 let mut results = Vec::new();
17183 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17184 let color = color_fetcher(cx);
17185 let start_ix = match ranges.binary_search_by(|probe| {
17186 let cmp = probe
17187 .end
17188 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17189 if cmp.is_gt() {
17190 Ordering::Greater
17191 } else {
17192 Ordering::Less
17193 }
17194 }) {
17195 Ok(i) | Err(i) => i,
17196 };
17197 for range in &ranges[start_ix..] {
17198 if range
17199 .start
17200 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17201 .is_ge()
17202 {
17203 break;
17204 }
17205
17206 let start = range.start.to_display_point(display_snapshot);
17207 let end = range.end.to_display_point(display_snapshot);
17208 results.push((start..end, color))
17209 }
17210 }
17211 results
17212 }
17213
17214 /// Get the text ranges corresponding to the redaction query
17215 pub fn redacted_ranges(
17216 &self,
17217 search_range: Range<Anchor>,
17218 display_snapshot: &DisplaySnapshot,
17219 cx: &App,
17220 ) -> Vec<Range<DisplayPoint>> {
17221 display_snapshot
17222 .buffer_snapshot
17223 .redacted_ranges(search_range, |file| {
17224 if let Some(file) = file {
17225 file.is_private()
17226 && EditorSettings::get(
17227 Some(SettingsLocation {
17228 worktree_id: file.worktree_id(cx),
17229 path: file.path().as_ref(),
17230 }),
17231 cx,
17232 )
17233 .redact_private_values
17234 } else {
17235 false
17236 }
17237 })
17238 .map(|range| {
17239 range.start.to_display_point(display_snapshot)
17240 ..range.end.to_display_point(display_snapshot)
17241 })
17242 .collect()
17243 }
17244
17245 pub fn highlight_text<T: 'static>(
17246 &mut self,
17247 ranges: Vec<Range<Anchor>>,
17248 style: HighlightStyle,
17249 cx: &mut Context<Self>,
17250 ) {
17251 self.display_map.update(cx, |map, _| {
17252 map.highlight_text(TypeId::of::<T>(), ranges, style)
17253 });
17254 cx.notify();
17255 }
17256
17257 pub(crate) fn highlight_inlays<T: 'static>(
17258 &mut self,
17259 highlights: Vec<InlayHighlight>,
17260 style: HighlightStyle,
17261 cx: &mut Context<Self>,
17262 ) {
17263 self.display_map.update(cx, |map, _| {
17264 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17265 });
17266 cx.notify();
17267 }
17268
17269 pub fn text_highlights<'a, T: 'static>(
17270 &'a self,
17271 cx: &'a App,
17272 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17273 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17274 }
17275
17276 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17277 let cleared = self
17278 .display_map
17279 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17280 if cleared {
17281 cx.notify();
17282 }
17283 }
17284
17285 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17286 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17287 && self.focus_handle.is_focused(window)
17288 }
17289
17290 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17291 self.show_cursor_when_unfocused = is_enabled;
17292 cx.notify();
17293 }
17294
17295 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17296 cx.notify();
17297 }
17298
17299 fn on_buffer_event(
17300 &mut self,
17301 multibuffer: &Entity<MultiBuffer>,
17302 event: &multi_buffer::Event,
17303 window: &mut Window,
17304 cx: &mut Context<Self>,
17305 ) {
17306 match event {
17307 multi_buffer::Event::Edited {
17308 singleton_buffer_edited,
17309 edited_buffer: buffer_edited,
17310 } => {
17311 self.scrollbar_marker_state.dirty = true;
17312 self.active_indent_guides_state.dirty = true;
17313 self.refresh_active_diagnostics(cx);
17314 self.refresh_code_actions(window, cx);
17315 if self.has_active_inline_completion() {
17316 self.update_visible_inline_completion(window, cx);
17317 }
17318 if let Some(buffer) = buffer_edited {
17319 let buffer_id = buffer.read(cx).remote_id();
17320 if !self.registered_buffers.contains_key(&buffer_id) {
17321 if let Some(project) = self.project.as_ref() {
17322 project.update(cx, |project, cx| {
17323 self.registered_buffers.insert(
17324 buffer_id,
17325 project.register_buffer_with_language_servers(&buffer, cx),
17326 );
17327 })
17328 }
17329 }
17330 }
17331 cx.emit(EditorEvent::BufferEdited);
17332 cx.emit(SearchEvent::MatchesInvalidated);
17333 if *singleton_buffer_edited {
17334 if let Some(project) = &self.project {
17335 #[allow(clippy::mutable_key_type)]
17336 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17337 multibuffer
17338 .all_buffers()
17339 .into_iter()
17340 .filter_map(|buffer| {
17341 buffer.update(cx, |buffer, cx| {
17342 let language = buffer.language()?;
17343 let should_discard = project.update(cx, |project, cx| {
17344 project.is_local()
17345 && !project.has_language_servers_for(buffer, cx)
17346 });
17347 should_discard.not().then_some(language.clone())
17348 })
17349 })
17350 .collect::<HashSet<_>>()
17351 });
17352 if !languages_affected.is_empty() {
17353 self.refresh_inlay_hints(
17354 InlayHintRefreshReason::BufferEdited(languages_affected),
17355 cx,
17356 );
17357 }
17358 }
17359 }
17360
17361 let Some(project) = &self.project else { return };
17362 let (telemetry, is_via_ssh) = {
17363 let project = project.read(cx);
17364 let telemetry = project.client().telemetry().clone();
17365 let is_via_ssh = project.is_via_ssh();
17366 (telemetry, is_via_ssh)
17367 };
17368 refresh_linked_ranges(self, window, cx);
17369 telemetry.log_edit_event("editor", is_via_ssh);
17370 }
17371 multi_buffer::Event::ExcerptsAdded {
17372 buffer,
17373 predecessor,
17374 excerpts,
17375 } => {
17376 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17377 let buffer_id = buffer.read(cx).remote_id();
17378 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17379 if let Some(project) = &self.project {
17380 get_uncommitted_diff_for_buffer(
17381 project,
17382 [buffer.clone()],
17383 self.buffer.clone(),
17384 cx,
17385 )
17386 .detach();
17387 }
17388 }
17389 cx.emit(EditorEvent::ExcerptsAdded {
17390 buffer: buffer.clone(),
17391 predecessor: *predecessor,
17392 excerpts: excerpts.clone(),
17393 });
17394 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17395 }
17396 multi_buffer::Event::ExcerptsRemoved { ids } => {
17397 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17398 let buffer = self.buffer.read(cx);
17399 self.registered_buffers
17400 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17401 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17402 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17403 }
17404 multi_buffer::Event::ExcerptsEdited {
17405 excerpt_ids,
17406 buffer_ids,
17407 } => {
17408 self.display_map.update(cx, |map, cx| {
17409 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17410 });
17411 cx.emit(EditorEvent::ExcerptsEdited {
17412 ids: excerpt_ids.clone(),
17413 })
17414 }
17415 multi_buffer::Event::ExcerptsExpanded { ids } => {
17416 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17417 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17418 }
17419 multi_buffer::Event::Reparsed(buffer_id) => {
17420 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17421 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17422
17423 cx.emit(EditorEvent::Reparsed(*buffer_id));
17424 }
17425 multi_buffer::Event::DiffHunksToggled => {
17426 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17427 }
17428 multi_buffer::Event::LanguageChanged(buffer_id) => {
17429 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17430 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17431 cx.emit(EditorEvent::Reparsed(*buffer_id));
17432 cx.notify();
17433 }
17434 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17435 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17436 multi_buffer::Event::FileHandleChanged
17437 | multi_buffer::Event::Reloaded
17438 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17439 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17440 multi_buffer::Event::DiagnosticsUpdated => {
17441 self.refresh_active_diagnostics(cx);
17442 self.refresh_inline_diagnostics(true, window, cx);
17443 self.scrollbar_marker_state.dirty = true;
17444 cx.notify();
17445 }
17446 _ => {}
17447 };
17448 }
17449
17450 fn on_display_map_changed(
17451 &mut self,
17452 _: Entity<DisplayMap>,
17453 _: &mut Window,
17454 cx: &mut Context<Self>,
17455 ) {
17456 cx.notify();
17457 }
17458
17459 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17460 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17461 self.update_edit_prediction_settings(cx);
17462 self.refresh_inline_completion(true, false, window, cx);
17463 self.refresh_inlay_hints(
17464 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17465 self.selections.newest_anchor().head(),
17466 &self.buffer.read(cx).snapshot(cx),
17467 cx,
17468 )),
17469 cx,
17470 );
17471
17472 let old_cursor_shape = self.cursor_shape;
17473
17474 {
17475 let editor_settings = EditorSettings::get_global(cx);
17476 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17477 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17478 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17479 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17480 }
17481
17482 if old_cursor_shape != self.cursor_shape {
17483 cx.emit(EditorEvent::CursorShapeChanged);
17484 }
17485
17486 let project_settings = ProjectSettings::get_global(cx);
17487 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17488
17489 if self.mode.is_full() {
17490 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17491 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17492 if self.show_inline_diagnostics != show_inline_diagnostics {
17493 self.show_inline_diagnostics = show_inline_diagnostics;
17494 self.refresh_inline_diagnostics(false, window, cx);
17495 }
17496
17497 if self.git_blame_inline_enabled != inline_blame_enabled {
17498 self.toggle_git_blame_inline_internal(false, window, cx);
17499 }
17500 }
17501
17502 cx.notify();
17503 }
17504
17505 pub fn set_searchable(&mut self, searchable: bool) {
17506 self.searchable = searchable;
17507 }
17508
17509 pub fn searchable(&self) -> bool {
17510 self.searchable
17511 }
17512
17513 fn open_proposed_changes_editor(
17514 &mut self,
17515 _: &OpenProposedChangesEditor,
17516 window: &mut Window,
17517 cx: &mut Context<Self>,
17518 ) {
17519 let Some(workspace) = self.workspace() else {
17520 cx.propagate();
17521 return;
17522 };
17523
17524 let selections = self.selections.all::<usize>(cx);
17525 let multi_buffer = self.buffer.read(cx);
17526 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17527 let mut new_selections_by_buffer = HashMap::default();
17528 for selection in selections {
17529 for (buffer, range, _) in
17530 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17531 {
17532 let mut range = range.to_point(buffer);
17533 range.start.column = 0;
17534 range.end.column = buffer.line_len(range.end.row);
17535 new_selections_by_buffer
17536 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17537 .or_insert(Vec::new())
17538 .push(range)
17539 }
17540 }
17541
17542 let proposed_changes_buffers = new_selections_by_buffer
17543 .into_iter()
17544 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17545 .collect::<Vec<_>>();
17546 let proposed_changes_editor = cx.new(|cx| {
17547 ProposedChangesEditor::new(
17548 "Proposed changes",
17549 proposed_changes_buffers,
17550 self.project.clone(),
17551 window,
17552 cx,
17553 )
17554 });
17555
17556 window.defer(cx, move |window, cx| {
17557 workspace.update(cx, |workspace, cx| {
17558 workspace.active_pane().update(cx, |pane, cx| {
17559 pane.add_item(
17560 Box::new(proposed_changes_editor),
17561 true,
17562 true,
17563 None,
17564 window,
17565 cx,
17566 );
17567 });
17568 });
17569 });
17570 }
17571
17572 pub fn open_excerpts_in_split(
17573 &mut self,
17574 _: &OpenExcerptsSplit,
17575 window: &mut Window,
17576 cx: &mut Context<Self>,
17577 ) {
17578 self.open_excerpts_common(None, true, window, cx)
17579 }
17580
17581 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17582 self.open_excerpts_common(None, false, window, cx)
17583 }
17584
17585 fn open_excerpts_common(
17586 &mut self,
17587 jump_data: Option<JumpData>,
17588 split: bool,
17589 window: &mut Window,
17590 cx: &mut Context<Self>,
17591 ) {
17592 let Some(workspace) = self.workspace() else {
17593 cx.propagate();
17594 return;
17595 };
17596
17597 if self.buffer.read(cx).is_singleton() {
17598 cx.propagate();
17599 return;
17600 }
17601
17602 let mut new_selections_by_buffer = HashMap::default();
17603 match &jump_data {
17604 Some(JumpData::MultiBufferPoint {
17605 excerpt_id,
17606 position,
17607 anchor,
17608 line_offset_from_top,
17609 }) => {
17610 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17611 if let Some(buffer) = multi_buffer_snapshot
17612 .buffer_id_for_excerpt(*excerpt_id)
17613 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17614 {
17615 let buffer_snapshot = buffer.read(cx).snapshot();
17616 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17617 language::ToPoint::to_point(anchor, &buffer_snapshot)
17618 } else {
17619 buffer_snapshot.clip_point(*position, Bias::Left)
17620 };
17621 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17622 new_selections_by_buffer.insert(
17623 buffer,
17624 (
17625 vec![jump_to_offset..jump_to_offset],
17626 Some(*line_offset_from_top),
17627 ),
17628 );
17629 }
17630 }
17631 Some(JumpData::MultiBufferRow {
17632 row,
17633 line_offset_from_top,
17634 }) => {
17635 let point = MultiBufferPoint::new(row.0, 0);
17636 if let Some((buffer, buffer_point, _)) =
17637 self.buffer.read(cx).point_to_buffer_point(point, cx)
17638 {
17639 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17640 new_selections_by_buffer
17641 .entry(buffer)
17642 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17643 .0
17644 .push(buffer_offset..buffer_offset)
17645 }
17646 }
17647 None => {
17648 let selections = self.selections.all::<usize>(cx);
17649 let multi_buffer = self.buffer.read(cx);
17650 for selection in selections {
17651 for (snapshot, range, _, anchor) in multi_buffer
17652 .snapshot(cx)
17653 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17654 {
17655 if let Some(anchor) = anchor {
17656 // selection is in a deleted hunk
17657 let Some(buffer_id) = anchor.buffer_id else {
17658 continue;
17659 };
17660 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17661 continue;
17662 };
17663 let offset = text::ToOffset::to_offset(
17664 &anchor.text_anchor,
17665 &buffer_handle.read(cx).snapshot(),
17666 );
17667 let range = offset..offset;
17668 new_selections_by_buffer
17669 .entry(buffer_handle)
17670 .or_insert((Vec::new(), None))
17671 .0
17672 .push(range)
17673 } else {
17674 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17675 else {
17676 continue;
17677 };
17678 new_selections_by_buffer
17679 .entry(buffer_handle)
17680 .or_insert((Vec::new(), None))
17681 .0
17682 .push(range)
17683 }
17684 }
17685 }
17686 }
17687 }
17688
17689 new_selections_by_buffer
17690 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17691
17692 if new_selections_by_buffer.is_empty() {
17693 return;
17694 }
17695
17696 // We defer the pane interaction because we ourselves are a workspace item
17697 // and activating a new item causes the pane to call a method on us reentrantly,
17698 // which panics if we're on the stack.
17699 window.defer(cx, move |window, cx| {
17700 workspace.update(cx, |workspace, cx| {
17701 let pane = if split {
17702 workspace.adjacent_pane(window, cx)
17703 } else {
17704 workspace.active_pane().clone()
17705 };
17706
17707 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17708 let editor = buffer
17709 .read(cx)
17710 .file()
17711 .is_none()
17712 .then(|| {
17713 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17714 // so `workspace.open_project_item` will never find them, always opening a new editor.
17715 // Instead, we try to activate the existing editor in the pane first.
17716 let (editor, pane_item_index) =
17717 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17718 let editor = item.downcast::<Editor>()?;
17719 let singleton_buffer =
17720 editor.read(cx).buffer().read(cx).as_singleton()?;
17721 if singleton_buffer == buffer {
17722 Some((editor, i))
17723 } else {
17724 None
17725 }
17726 })?;
17727 pane.update(cx, |pane, cx| {
17728 pane.activate_item(pane_item_index, true, true, window, cx)
17729 });
17730 Some(editor)
17731 })
17732 .flatten()
17733 .unwrap_or_else(|| {
17734 workspace.open_project_item::<Self>(
17735 pane.clone(),
17736 buffer,
17737 true,
17738 true,
17739 window,
17740 cx,
17741 )
17742 });
17743
17744 editor.update(cx, |editor, cx| {
17745 let autoscroll = match scroll_offset {
17746 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17747 None => Autoscroll::newest(),
17748 };
17749 let nav_history = editor.nav_history.take();
17750 editor.change_selections(Some(autoscroll), window, cx, |s| {
17751 s.select_ranges(ranges);
17752 });
17753 editor.nav_history = nav_history;
17754 });
17755 }
17756 })
17757 });
17758 }
17759
17760 // For now, don't allow opening excerpts in buffers that aren't backed by
17761 // regular project files.
17762 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17763 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17764 }
17765
17766 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17767 let snapshot = self.buffer.read(cx).read(cx);
17768 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17769 Some(
17770 ranges
17771 .iter()
17772 .map(move |range| {
17773 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17774 })
17775 .collect(),
17776 )
17777 }
17778
17779 fn selection_replacement_ranges(
17780 &self,
17781 range: Range<OffsetUtf16>,
17782 cx: &mut App,
17783 ) -> Vec<Range<OffsetUtf16>> {
17784 let selections = self.selections.all::<OffsetUtf16>(cx);
17785 let newest_selection = selections
17786 .iter()
17787 .max_by_key(|selection| selection.id)
17788 .unwrap();
17789 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17790 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17791 let snapshot = self.buffer.read(cx).read(cx);
17792 selections
17793 .into_iter()
17794 .map(|mut selection| {
17795 selection.start.0 =
17796 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17797 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17798 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17799 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17800 })
17801 .collect()
17802 }
17803
17804 fn report_editor_event(
17805 &self,
17806 event_type: &'static str,
17807 file_extension: Option<String>,
17808 cx: &App,
17809 ) {
17810 if cfg!(any(test, feature = "test-support")) {
17811 return;
17812 }
17813
17814 let Some(project) = &self.project else { return };
17815
17816 // If None, we are in a file without an extension
17817 let file = self
17818 .buffer
17819 .read(cx)
17820 .as_singleton()
17821 .and_then(|b| b.read(cx).file());
17822 let file_extension = file_extension.or(file
17823 .as_ref()
17824 .and_then(|file| Path::new(file.file_name(cx)).extension())
17825 .and_then(|e| e.to_str())
17826 .map(|a| a.to_string()));
17827
17828 let vim_mode = vim_enabled(cx);
17829
17830 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17831 let copilot_enabled = edit_predictions_provider
17832 == language::language_settings::EditPredictionProvider::Copilot;
17833 let copilot_enabled_for_language = self
17834 .buffer
17835 .read(cx)
17836 .language_settings(cx)
17837 .show_edit_predictions;
17838
17839 let project = project.read(cx);
17840 telemetry::event!(
17841 event_type,
17842 file_extension,
17843 vim_mode,
17844 copilot_enabled,
17845 copilot_enabled_for_language,
17846 edit_predictions_provider,
17847 is_via_ssh = project.is_via_ssh(),
17848 );
17849 }
17850
17851 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17852 /// with each line being an array of {text, highlight} objects.
17853 fn copy_highlight_json(
17854 &mut self,
17855 _: &CopyHighlightJson,
17856 window: &mut Window,
17857 cx: &mut Context<Self>,
17858 ) {
17859 #[derive(Serialize)]
17860 struct Chunk<'a> {
17861 text: String,
17862 highlight: Option<&'a str>,
17863 }
17864
17865 let snapshot = self.buffer.read(cx).snapshot(cx);
17866 let range = self
17867 .selected_text_range(false, window, cx)
17868 .and_then(|selection| {
17869 if selection.range.is_empty() {
17870 None
17871 } else {
17872 Some(selection.range)
17873 }
17874 })
17875 .unwrap_or_else(|| 0..snapshot.len());
17876
17877 let chunks = snapshot.chunks(range, true);
17878 let mut lines = Vec::new();
17879 let mut line: VecDeque<Chunk> = VecDeque::new();
17880
17881 let Some(style) = self.style.as_ref() else {
17882 return;
17883 };
17884
17885 for chunk in chunks {
17886 let highlight = chunk
17887 .syntax_highlight_id
17888 .and_then(|id| id.name(&style.syntax));
17889 let mut chunk_lines = chunk.text.split('\n').peekable();
17890 while let Some(text) = chunk_lines.next() {
17891 let mut merged_with_last_token = false;
17892 if let Some(last_token) = line.back_mut() {
17893 if last_token.highlight == highlight {
17894 last_token.text.push_str(text);
17895 merged_with_last_token = true;
17896 }
17897 }
17898
17899 if !merged_with_last_token {
17900 line.push_back(Chunk {
17901 text: text.into(),
17902 highlight,
17903 });
17904 }
17905
17906 if chunk_lines.peek().is_some() {
17907 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17908 line.pop_front();
17909 }
17910 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17911 line.pop_back();
17912 }
17913
17914 lines.push(mem::take(&mut line));
17915 }
17916 }
17917 }
17918
17919 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17920 return;
17921 };
17922 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17923 }
17924
17925 pub fn open_context_menu(
17926 &mut self,
17927 _: &OpenContextMenu,
17928 window: &mut Window,
17929 cx: &mut Context<Self>,
17930 ) {
17931 self.request_autoscroll(Autoscroll::newest(), cx);
17932 let position = self.selections.newest_display(cx).start;
17933 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17934 }
17935
17936 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17937 &self.inlay_hint_cache
17938 }
17939
17940 pub fn replay_insert_event(
17941 &mut self,
17942 text: &str,
17943 relative_utf16_range: Option<Range<isize>>,
17944 window: &mut Window,
17945 cx: &mut Context<Self>,
17946 ) {
17947 if !self.input_enabled {
17948 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17949 return;
17950 }
17951 if let Some(relative_utf16_range) = relative_utf16_range {
17952 let selections = self.selections.all::<OffsetUtf16>(cx);
17953 self.change_selections(None, window, cx, |s| {
17954 let new_ranges = selections.into_iter().map(|range| {
17955 let start = OffsetUtf16(
17956 range
17957 .head()
17958 .0
17959 .saturating_add_signed(relative_utf16_range.start),
17960 );
17961 let end = OffsetUtf16(
17962 range
17963 .head()
17964 .0
17965 .saturating_add_signed(relative_utf16_range.end),
17966 );
17967 start..end
17968 });
17969 s.select_ranges(new_ranges);
17970 });
17971 }
17972
17973 self.handle_input(text, window, cx);
17974 }
17975
17976 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17977 let Some(provider) = self.semantics_provider.as_ref() else {
17978 return false;
17979 };
17980
17981 let mut supports = false;
17982 self.buffer().update(cx, |this, cx| {
17983 this.for_each_buffer(|buffer| {
17984 supports |= provider.supports_inlay_hints(buffer, cx);
17985 });
17986 });
17987
17988 supports
17989 }
17990
17991 pub fn is_focused(&self, window: &Window) -> bool {
17992 self.focus_handle.is_focused(window)
17993 }
17994
17995 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17996 cx.emit(EditorEvent::Focused);
17997
17998 if let Some(descendant) = self
17999 .last_focused_descendant
18000 .take()
18001 .and_then(|descendant| descendant.upgrade())
18002 {
18003 window.focus(&descendant);
18004 } else {
18005 if let Some(blame) = self.blame.as_ref() {
18006 blame.update(cx, GitBlame::focus)
18007 }
18008
18009 self.blink_manager.update(cx, BlinkManager::enable);
18010 self.show_cursor_names(window, cx);
18011 self.buffer.update(cx, |buffer, cx| {
18012 buffer.finalize_last_transaction(cx);
18013 if self.leader_peer_id.is_none() {
18014 buffer.set_active_selections(
18015 &self.selections.disjoint_anchors(),
18016 self.selections.line_mode,
18017 self.cursor_shape,
18018 cx,
18019 );
18020 }
18021 });
18022 }
18023 }
18024
18025 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18026 cx.emit(EditorEvent::FocusedIn)
18027 }
18028
18029 fn handle_focus_out(
18030 &mut self,
18031 event: FocusOutEvent,
18032 _window: &mut Window,
18033 cx: &mut Context<Self>,
18034 ) {
18035 if event.blurred != self.focus_handle {
18036 self.last_focused_descendant = Some(event.blurred);
18037 }
18038 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18039 }
18040
18041 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18042 self.blink_manager.update(cx, BlinkManager::disable);
18043 self.buffer
18044 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18045
18046 if let Some(blame) = self.blame.as_ref() {
18047 blame.update(cx, GitBlame::blur)
18048 }
18049 if !self.hover_state.focused(window, cx) {
18050 hide_hover(self, cx);
18051 }
18052 if !self
18053 .context_menu
18054 .borrow()
18055 .as_ref()
18056 .is_some_and(|context_menu| context_menu.focused(window, cx))
18057 {
18058 self.hide_context_menu(window, cx);
18059 }
18060 self.discard_inline_completion(false, cx);
18061 cx.emit(EditorEvent::Blurred);
18062 cx.notify();
18063 }
18064
18065 pub fn register_action<A: Action>(
18066 &mut self,
18067 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18068 ) -> Subscription {
18069 let id = self.next_editor_action_id.post_inc();
18070 let listener = Arc::new(listener);
18071 self.editor_actions.borrow_mut().insert(
18072 id,
18073 Box::new(move |window, _| {
18074 let listener = listener.clone();
18075 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18076 let action = action.downcast_ref().unwrap();
18077 if phase == DispatchPhase::Bubble {
18078 listener(action, window, cx)
18079 }
18080 })
18081 }),
18082 );
18083
18084 let editor_actions = self.editor_actions.clone();
18085 Subscription::new(move || {
18086 editor_actions.borrow_mut().remove(&id);
18087 })
18088 }
18089
18090 pub fn file_header_size(&self) -> u32 {
18091 FILE_HEADER_HEIGHT
18092 }
18093
18094 pub fn restore(
18095 &mut self,
18096 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18097 window: &mut Window,
18098 cx: &mut Context<Self>,
18099 ) {
18100 let workspace = self.workspace();
18101 let project = self.project.as_ref();
18102 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18103 let mut tasks = Vec::new();
18104 for (buffer_id, changes) in revert_changes {
18105 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18106 buffer.update(cx, |buffer, cx| {
18107 buffer.edit(
18108 changes
18109 .into_iter()
18110 .map(|(range, text)| (range, text.to_string())),
18111 None,
18112 cx,
18113 );
18114 });
18115
18116 if let Some(project) =
18117 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18118 {
18119 project.update(cx, |project, cx| {
18120 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18121 })
18122 }
18123 }
18124 }
18125 tasks
18126 });
18127 cx.spawn_in(window, async move |_, cx| {
18128 for (buffer, task) in save_tasks {
18129 let result = task.await;
18130 if result.is_err() {
18131 let Some(path) = buffer
18132 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18133 .ok()
18134 else {
18135 continue;
18136 };
18137 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18138 let Some(task) = cx
18139 .update_window_entity(&workspace, |workspace, window, cx| {
18140 workspace
18141 .open_path_preview(path, None, false, false, false, window, cx)
18142 })
18143 .ok()
18144 else {
18145 continue;
18146 };
18147 task.await.log_err();
18148 }
18149 }
18150 }
18151 })
18152 .detach();
18153 self.change_selections(None, window, cx, |selections| selections.refresh());
18154 }
18155
18156 pub fn to_pixel_point(
18157 &self,
18158 source: multi_buffer::Anchor,
18159 editor_snapshot: &EditorSnapshot,
18160 window: &mut Window,
18161 ) -> Option<gpui::Point<Pixels>> {
18162 let source_point = source.to_display_point(editor_snapshot);
18163 self.display_to_pixel_point(source_point, editor_snapshot, window)
18164 }
18165
18166 pub fn display_to_pixel_point(
18167 &self,
18168 source: DisplayPoint,
18169 editor_snapshot: &EditorSnapshot,
18170 window: &mut Window,
18171 ) -> Option<gpui::Point<Pixels>> {
18172 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18173 let text_layout_details = self.text_layout_details(window);
18174 let scroll_top = text_layout_details
18175 .scroll_anchor
18176 .scroll_position(editor_snapshot)
18177 .y;
18178
18179 if source.row().as_f32() < scroll_top.floor() {
18180 return None;
18181 }
18182 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18183 let source_y = line_height * (source.row().as_f32() - scroll_top);
18184 Some(gpui::Point::new(source_x, source_y))
18185 }
18186
18187 pub fn has_visible_completions_menu(&self) -> bool {
18188 !self.edit_prediction_preview_is_active()
18189 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18190 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18191 })
18192 }
18193
18194 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18195 self.addons
18196 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18197 }
18198
18199 pub fn unregister_addon<T: Addon>(&mut self) {
18200 self.addons.remove(&std::any::TypeId::of::<T>());
18201 }
18202
18203 pub fn addon<T: Addon>(&self) -> Option<&T> {
18204 let type_id = std::any::TypeId::of::<T>();
18205 self.addons
18206 .get(&type_id)
18207 .and_then(|item| item.to_any().downcast_ref::<T>())
18208 }
18209
18210 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18211 let text_layout_details = self.text_layout_details(window);
18212 let style = &text_layout_details.editor_style;
18213 let font_id = window.text_system().resolve_font(&style.text.font());
18214 let font_size = style.text.font_size.to_pixels(window.rem_size());
18215 let line_height = style.text.line_height_in_pixels(window.rem_size());
18216 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18217
18218 gpui::Size::new(em_width, line_height)
18219 }
18220
18221 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18222 self.load_diff_task.clone()
18223 }
18224
18225 fn read_metadata_from_db(
18226 &mut self,
18227 item_id: u64,
18228 workspace_id: WorkspaceId,
18229 window: &mut Window,
18230 cx: &mut Context<Editor>,
18231 ) {
18232 if self.is_singleton(cx)
18233 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18234 {
18235 let buffer_snapshot = OnceCell::new();
18236
18237 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18238 if !folds.is_empty() {
18239 let snapshot =
18240 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18241 self.fold_ranges(
18242 folds
18243 .into_iter()
18244 .map(|(start, end)| {
18245 snapshot.clip_offset(start, Bias::Left)
18246 ..snapshot.clip_offset(end, Bias::Right)
18247 })
18248 .collect(),
18249 false,
18250 window,
18251 cx,
18252 );
18253 }
18254 }
18255
18256 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18257 if !selections.is_empty() {
18258 let snapshot =
18259 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18260 self.change_selections(None, window, cx, |s| {
18261 s.select_ranges(selections.into_iter().map(|(start, end)| {
18262 snapshot.clip_offset(start, Bias::Left)
18263 ..snapshot.clip_offset(end, Bias::Right)
18264 }));
18265 });
18266 }
18267 };
18268 }
18269
18270 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18271 }
18272}
18273
18274fn vim_enabled(cx: &App) -> bool {
18275 cx.global::<SettingsStore>()
18276 .raw_user_settings()
18277 .get("vim_mode")
18278 == Some(&serde_json::Value::Bool(true))
18279}
18280
18281// Consider user intent and default settings
18282fn choose_completion_range(
18283 completion: &Completion,
18284 intent: CompletionIntent,
18285 buffer: &Entity<Buffer>,
18286 cx: &mut Context<Editor>,
18287) -> Range<usize> {
18288 fn should_replace(
18289 completion: &Completion,
18290 insert_range: &Range<text::Anchor>,
18291 intent: CompletionIntent,
18292 completion_mode_setting: LspInsertMode,
18293 buffer: &Buffer,
18294 ) -> bool {
18295 // specific actions take precedence over settings
18296 match intent {
18297 CompletionIntent::CompleteWithInsert => return false,
18298 CompletionIntent::CompleteWithReplace => return true,
18299 CompletionIntent::Complete | CompletionIntent::Compose => {}
18300 }
18301
18302 match completion_mode_setting {
18303 LspInsertMode::Insert => false,
18304 LspInsertMode::Replace => true,
18305 LspInsertMode::ReplaceSubsequence => {
18306 let mut text_to_replace = buffer.chars_for_range(
18307 buffer.anchor_before(completion.replace_range.start)
18308 ..buffer.anchor_after(completion.replace_range.end),
18309 );
18310 let mut completion_text = completion.new_text.chars();
18311
18312 // is `text_to_replace` a subsequence of `completion_text`
18313 text_to_replace
18314 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18315 }
18316 LspInsertMode::ReplaceSuffix => {
18317 let range_after_cursor = insert_range.end..completion.replace_range.end;
18318
18319 let text_after_cursor = buffer
18320 .text_for_range(
18321 buffer.anchor_before(range_after_cursor.start)
18322 ..buffer.anchor_after(range_after_cursor.end),
18323 )
18324 .collect::<String>();
18325 completion.new_text.ends_with(&text_after_cursor)
18326 }
18327 }
18328 }
18329
18330 let buffer = buffer.read(cx);
18331
18332 if let CompletionSource::Lsp {
18333 insert_range: Some(insert_range),
18334 ..
18335 } = &completion.source
18336 {
18337 let completion_mode_setting =
18338 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18339 .completions
18340 .lsp_insert_mode;
18341
18342 if !should_replace(
18343 completion,
18344 &insert_range,
18345 intent,
18346 completion_mode_setting,
18347 buffer,
18348 ) {
18349 return insert_range.to_offset(buffer);
18350 }
18351 }
18352
18353 completion.replace_range.to_offset(buffer)
18354}
18355
18356fn insert_extra_newline_brackets(
18357 buffer: &MultiBufferSnapshot,
18358 range: Range<usize>,
18359 language: &language::LanguageScope,
18360) -> bool {
18361 let leading_whitespace_len = buffer
18362 .reversed_chars_at(range.start)
18363 .take_while(|c| c.is_whitespace() && *c != '\n')
18364 .map(|c| c.len_utf8())
18365 .sum::<usize>();
18366 let trailing_whitespace_len = buffer
18367 .chars_at(range.end)
18368 .take_while(|c| c.is_whitespace() && *c != '\n')
18369 .map(|c| c.len_utf8())
18370 .sum::<usize>();
18371 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18372
18373 language.brackets().any(|(pair, enabled)| {
18374 let pair_start = pair.start.trim_end();
18375 let pair_end = pair.end.trim_start();
18376
18377 enabled
18378 && pair.newline
18379 && buffer.contains_str_at(range.end, pair_end)
18380 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18381 })
18382}
18383
18384fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18385 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18386 [(buffer, range, _)] => (*buffer, range.clone()),
18387 _ => return false,
18388 };
18389 let pair = {
18390 let mut result: Option<BracketMatch> = None;
18391
18392 for pair in buffer
18393 .all_bracket_ranges(range.clone())
18394 .filter(move |pair| {
18395 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18396 })
18397 {
18398 let len = pair.close_range.end - pair.open_range.start;
18399
18400 if let Some(existing) = &result {
18401 let existing_len = existing.close_range.end - existing.open_range.start;
18402 if len > existing_len {
18403 continue;
18404 }
18405 }
18406
18407 result = Some(pair);
18408 }
18409
18410 result
18411 };
18412 let Some(pair) = pair else {
18413 return false;
18414 };
18415 pair.newline_only
18416 && buffer
18417 .chars_for_range(pair.open_range.end..range.start)
18418 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18419 .all(|c| c.is_whitespace() && c != '\n')
18420}
18421
18422fn get_uncommitted_diff_for_buffer(
18423 project: &Entity<Project>,
18424 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18425 buffer: Entity<MultiBuffer>,
18426 cx: &mut App,
18427) -> Task<()> {
18428 let mut tasks = Vec::new();
18429 project.update(cx, |project, cx| {
18430 for buffer in buffers {
18431 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18432 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18433 }
18434 }
18435 });
18436 cx.spawn(async move |cx| {
18437 let diffs = future::join_all(tasks).await;
18438 buffer
18439 .update(cx, |buffer, cx| {
18440 for diff in diffs.into_iter().flatten() {
18441 buffer.add_diff(diff, cx);
18442 }
18443 })
18444 .ok();
18445 })
18446}
18447
18448fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18449 let tab_size = tab_size.get() as usize;
18450 let mut width = offset;
18451
18452 for ch in text.chars() {
18453 width += if ch == '\t' {
18454 tab_size - (width % tab_size)
18455 } else {
18456 1
18457 };
18458 }
18459
18460 width - offset
18461}
18462
18463#[cfg(test)]
18464mod tests {
18465 use super::*;
18466
18467 #[test]
18468 fn test_string_size_with_expanded_tabs() {
18469 let nz = |val| NonZeroU32::new(val).unwrap();
18470 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18471 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18472 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18473 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18474 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18475 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18476 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18477 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18478 }
18479}
18480
18481/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18482struct WordBreakingTokenizer<'a> {
18483 input: &'a str,
18484}
18485
18486impl<'a> WordBreakingTokenizer<'a> {
18487 fn new(input: &'a str) -> Self {
18488 Self { input }
18489 }
18490}
18491
18492fn is_char_ideographic(ch: char) -> bool {
18493 use unicode_script::Script::*;
18494 use unicode_script::UnicodeScript;
18495 matches!(ch.script(), Han | Tangut | Yi)
18496}
18497
18498fn is_grapheme_ideographic(text: &str) -> bool {
18499 text.chars().any(is_char_ideographic)
18500}
18501
18502fn is_grapheme_whitespace(text: &str) -> bool {
18503 text.chars().any(|x| x.is_whitespace())
18504}
18505
18506fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18507 text.chars().next().map_or(false, |ch| {
18508 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18509 })
18510}
18511
18512#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18513enum WordBreakToken<'a> {
18514 Word { token: &'a str, grapheme_len: usize },
18515 InlineWhitespace { token: &'a str, grapheme_len: usize },
18516 Newline,
18517}
18518
18519impl<'a> Iterator for WordBreakingTokenizer<'a> {
18520 /// Yields a span, the count of graphemes in the token, and whether it was
18521 /// whitespace. Note that it also breaks at word boundaries.
18522 type Item = WordBreakToken<'a>;
18523
18524 fn next(&mut self) -> Option<Self::Item> {
18525 use unicode_segmentation::UnicodeSegmentation;
18526 if self.input.is_empty() {
18527 return None;
18528 }
18529
18530 let mut iter = self.input.graphemes(true).peekable();
18531 let mut offset = 0;
18532 let mut grapheme_len = 0;
18533 if let Some(first_grapheme) = iter.next() {
18534 let is_newline = first_grapheme == "\n";
18535 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18536 offset += first_grapheme.len();
18537 grapheme_len += 1;
18538 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18539 if let Some(grapheme) = iter.peek().copied() {
18540 if should_stay_with_preceding_ideograph(grapheme) {
18541 offset += grapheme.len();
18542 grapheme_len += 1;
18543 }
18544 }
18545 } else {
18546 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18547 let mut next_word_bound = words.peek().copied();
18548 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18549 next_word_bound = words.next();
18550 }
18551 while let Some(grapheme) = iter.peek().copied() {
18552 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18553 break;
18554 };
18555 if is_grapheme_whitespace(grapheme) != is_whitespace
18556 || (grapheme == "\n") != is_newline
18557 {
18558 break;
18559 };
18560 offset += grapheme.len();
18561 grapheme_len += 1;
18562 iter.next();
18563 }
18564 }
18565 let token = &self.input[..offset];
18566 self.input = &self.input[offset..];
18567 if token == "\n" {
18568 Some(WordBreakToken::Newline)
18569 } else if is_whitespace {
18570 Some(WordBreakToken::InlineWhitespace {
18571 token,
18572 grapheme_len,
18573 })
18574 } else {
18575 Some(WordBreakToken::Word {
18576 token,
18577 grapheme_len,
18578 })
18579 }
18580 } else {
18581 None
18582 }
18583 }
18584}
18585
18586#[test]
18587fn test_word_breaking_tokenizer() {
18588 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18589 ("", &[]),
18590 (" ", &[whitespace(" ", 2)]),
18591 ("Ʒ", &[word("Ʒ", 1)]),
18592 ("Ǽ", &[word("Ǽ", 1)]),
18593 ("⋑", &[word("⋑", 1)]),
18594 ("⋑⋑", &[word("⋑⋑", 2)]),
18595 (
18596 "原理,进而",
18597 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18598 ),
18599 (
18600 "hello world",
18601 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18602 ),
18603 (
18604 "hello, world",
18605 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18606 ),
18607 (
18608 " hello world",
18609 &[
18610 whitespace(" ", 2),
18611 word("hello", 5),
18612 whitespace(" ", 1),
18613 word("world", 5),
18614 ],
18615 ),
18616 (
18617 "这是什么 \n 钢笔",
18618 &[
18619 word("这", 1),
18620 word("是", 1),
18621 word("什", 1),
18622 word("么", 1),
18623 whitespace(" ", 1),
18624 newline(),
18625 whitespace(" ", 1),
18626 word("钢", 1),
18627 word("笔", 1),
18628 ],
18629 ),
18630 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18631 ];
18632
18633 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18634 WordBreakToken::Word {
18635 token,
18636 grapheme_len,
18637 }
18638 }
18639
18640 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18641 WordBreakToken::InlineWhitespace {
18642 token,
18643 grapheme_len,
18644 }
18645 }
18646
18647 fn newline() -> WordBreakToken<'static> {
18648 WordBreakToken::Newline
18649 }
18650
18651 for (input, result) in tests {
18652 assert_eq!(
18653 WordBreakingTokenizer::new(input)
18654 .collect::<Vec<_>>()
18655 .as_slice(),
18656 *result,
18657 );
18658 }
18659}
18660
18661fn wrap_with_prefix(
18662 line_prefix: String,
18663 unwrapped_text: String,
18664 wrap_column: usize,
18665 tab_size: NonZeroU32,
18666 preserve_existing_whitespace: bool,
18667) -> String {
18668 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18669 let mut wrapped_text = String::new();
18670 let mut current_line = line_prefix.clone();
18671
18672 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18673 let mut current_line_len = line_prefix_len;
18674 let mut in_whitespace = false;
18675 for token in tokenizer {
18676 let have_preceding_whitespace = in_whitespace;
18677 match token {
18678 WordBreakToken::Word {
18679 token,
18680 grapheme_len,
18681 } => {
18682 in_whitespace = false;
18683 if current_line_len + grapheme_len > wrap_column
18684 && current_line_len != line_prefix_len
18685 {
18686 wrapped_text.push_str(current_line.trim_end());
18687 wrapped_text.push('\n');
18688 current_line.truncate(line_prefix.len());
18689 current_line_len = line_prefix_len;
18690 }
18691 current_line.push_str(token);
18692 current_line_len += grapheme_len;
18693 }
18694 WordBreakToken::InlineWhitespace {
18695 mut token,
18696 mut grapheme_len,
18697 } => {
18698 in_whitespace = true;
18699 if have_preceding_whitespace && !preserve_existing_whitespace {
18700 continue;
18701 }
18702 if !preserve_existing_whitespace {
18703 token = " ";
18704 grapheme_len = 1;
18705 }
18706 if current_line_len + grapheme_len > wrap_column {
18707 wrapped_text.push_str(current_line.trim_end());
18708 wrapped_text.push('\n');
18709 current_line.truncate(line_prefix.len());
18710 current_line_len = line_prefix_len;
18711 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18712 current_line.push_str(token);
18713 current_line_len += grapheme_len;
18714 }
18715 }
18716 WordBreakToken::Newline => {
18717 in_whitespace = true;
18718 if preserve_existing_whitespace {
18719 wrapped_text.push_str(current_line.trim_end());
18720 wrapped_text.push('\n');
18721 current_line.truncate(line_prefix.len());
18722 current_line_len = line_prefix_len;
18723 } else if have_preceding_whitespace {
18724 continue;
18725 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18726 {
18727 wrapped_text.push_str(current_line.trim_end());
18728 wrapped_text.push('\n');
18729 current_line.truncate(line_prefix.len());
18730 current_line_len = line_prefix_len;
18731 } else if current_line_len != line_prefix_len {
18732 current_line.push(' ');
18733 current_line_len += 1;
18734 }
18735 }
18736 }
18737 }
18738
18739 if !current_line.is_empty() {
18740 wrapped_text.push_str(¤t_line);
18741 }
18742 wrapped_text
18743}
18744
18745#[test]
18746fn test_wrap_with_prefix() {
18747 assert_eq!(
18748 wrap_with_prefix(
18749 "# ".to_string(),
18750 "abcdefg".to_string(),
18751 4,
18752 NonZeroU32::new(4).unwrap(),
18753 false,
18754 ),
18755 "# abcdefg"
18756 );
18757 assert_eq!(
18758 wrap_with_prefix(
18759 "".to_string(),
18760 "\thello world".to_string(),
18761 8,
18762 NonZeroU32::new(4).unwrap(),
18763 false,
18764 ),
18765 "hello\nworld"
18766 );
18767 assert_eq!(
18768 wrap_with_prefix(
18769 "// ".to_string(),
18770 "xx \nyy zz aa bb cc".to_string(),
18771 12,
18772 NonZeroU32::new(4).unwrap(),
18773 false,
18774 ),
18775 "// xx yy zz\n// aa bb cc"
18776 );
18777 assert_eq!(
18778 wrap_with_prefix(
18779 String::new(),
18780 "这是什么 \n 钢笔".to_string(),
18781 3,
18782 NonZeroU32::new(4).unwrap(),
18783 false,
18784 ),
18785 "这是什\n么 钢\n笔"
18786 );
18787}
18788
18789pub trait CollaborationHub {
18790 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18791 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18792 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18793}
18794
18795impl CollaborationHub for Entity<Project> {
18796 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18797 self.read(cx).collaborators()
18798 }
18799
18800 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18801 self.read(cx).user_store().read(cx).participant_indices()
18802 }
18803
18804 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18805 let this = self.read(cx);
18806 let user_ids = this.collaborators().values().map(|c| c.user_id);
18807 this.user_store().read_with(cx, |user_store, cx| {
18808 user_store.participant_names(user_ids, cx)
18809 })
18810 }
18811}
18812
18813pub trait SemanticsProvider {
18814 fn hover(
18815 &self,
18816 buffer: &Entity<Buffer>,
18817 position: text::Anchor,
18818 cx: &mut App,
18819 ) -> Option<Task<Vec<project::Hover>>>;
18820
18821 fn inlay_hints(
18822 &self,
18823 buffer_handle: Entity<Buffer>,
18824 range: Range<text::Anchor>,
18825 cx: &mut App,
18826 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18827
18828 fn resolve_inlay_hint(
18829 &self,
18830 hint: InlayHint,
18831 buffer_handle: Entity<Buffer>,
18832 server_id: LanguageServerId,
18833 cx: &mut App,
18834 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18835
18836 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18837
18838 fn document_highlights(
18839 &self,
18840 buffer: &Entity<Buffer>,
18841 position: text::Anchor,
18842 cx: &mut App,
18843 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18844
18845 fn definitions(
18846 &self,
18847 buffer: &Entity<Buffer>,
18848 position: text::Anchor,
18849 kind: GotoDefinitionKind,
18850 cx: &mut App,
18851 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18852
18853 fn range_for_rename(
18854 &self,
18855 buffer: &Entity<Buffer>,
18856 position: text::Anchor,
18857 cx: &mut App,
18858 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18859
18860 fn perform_rename(
18861 &self,
18862 buffer: &Entity<Buffer>,
18863 position: text::Anchor,
18864 new_name: String,
18865 cx: &mut App,
18866 ) -> Option<Task<Result<ProjectTransaction>>>;
18867}
18868
18869pub trait CompletionProvider {
18870 fn completions(
18871 &self,
18872 excerpt_id: ExcerptId,
18873 buffer: &Entity<Buffer>,
18874 buffer_position: text::Anchor,
18875 trigger: CompletionContext,
18876 window: &mut Window,
18877 cx: &mut Context<Editor>,
18878 ) -> Task<Result<Option<Vec<Completion>>>>;
18879
18880 fn resolve_completions(
18881 &self,
18882 buffer: Entity<Buffer>,
18883 completion_indices: Vec<usize>,
18884 completions: Rc<RefCell<Box<[Completion]>>>,
18885 cx: &mut Context<Editor>,
18886 ) -> Task<Result<bool>>;
18887
18888 fn apply_additional_edits_for_completion(
18889 &self,
18890 _buffer: Entity<Buffer>,
18891 _completions: Rc<RefCell<Box<[Completion]>>>,
18892 _completion_index: usize,
18893 _push_to_history: bool,
18894 _cx: &mut Context<Editor>,
18895 ) -> Task<Result<Option<language::Transaction>>> {
18896 Task::ready(Ok(None))
18897 }
18898
18899 fn is_completion_trigger(
18900 &self,
18901 buffer: &Entity<Buffer>,
18902 position: language::Anchor,
18903 text: &str,
18904 trigger_in_words: bool,
18905 cx: &mut Context<Editor>,
18906 ) -> bool;
18907
18908 fn sort_completions(&self) -> bool {
18909 true
18910 }
18911
18912 fn filter_completions(&self) -> bool {
18913 true
18914 }
18915}
18916
18917pub trait CodeActionProvider {
18918 fn id(&self) -> Arc<str>;
18919
18920 fn code_actions(
18921 &self,
18922 buffer: &Entity<Buffer>,
18923 range: Range<text::Anchor>,
18924 window: &mut Window,
18925 cx: &mut App,
18926 ) -> Task<Result<Vec<CodeAction>>>;
18927
18928 fn apply_code_action(
18929 &self,
18930 buffer_handle: Entity<Buffer>,
18931 action: CodeAction,
18932 excerpt_id: ExcerptId,
18933 push_to_history: bool,
18934 window: &mut Window,
18935 cx: &mut App,
18936 ) -> Task<Result<ProjectTransaction>>;
18937}
18938
18939impl CodeActionProvider for Entity<Project> {
18940 fn id(&self) -> Arc<str> {
18941 "project".into()
18942 }
18943
18944 fn code_actions(
18945 &self,
18946 buffer: &Entity<Buffer>,
18947 range: Range<text::Anchor>,
18948 _window: &mut Window,
18949 cx: &mut App,
18950 ) -> Task<Result<Vec<CodeAction>>> {
18951 self.update(cx, |project, cx| {
18952 let code_lens = project.code_lens(buffer, range.clone(), cx);
18953 let code_actions = project.code_actions(buffer, range, None, cx);
18954 cx.background_spawn(async move {
18955 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18956 Ok(code_lens
18957 .context("code lens fetch")?
18958 .into_iter()
18959 .chain(code_actions.context("code action fetch")?)
18960 .collect())
18961 })
18962 })
18963 }
18964
18965 fn apply_code_action(
18966 &self,
18967 buffer_handle: Entity<Buffer>,
18968 action: CodeAction,
18969 _excerpt_id: ExcerptId,
18970 push_to_history: bool,
18971 _window: &mut Window,
18972 cx: &mut App,
18973 ) -> Task<Result<ProjectTransaction>> {
18974 self.update(cx, |project, cx| {
18975 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18976 })
18977 }
18978}
18979
18980fn snippet_completions(
18981 project: &Project,
18982 buffer: &Entity<Buffer>,
18983 buffer_position: text::Anchor,
18984 cx: &mut App,
18985) -> Task<Result<Vec<Completion>>> {
18986 let languages = buffer.read(cx).languages_at(buffer_position);
18987 let snippet_store = project.snippets().read(cx);
18988
18989 let scopes: Vec<_> = languages
18990 .iter()
18991 .filter_map(|language| {
18992 let language_name = language.lsp_id();
18993 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18994
18995 if snippets.is_empty() {
18996 None
18997 } else {
18998 Some((language.default_scope(), snippets))
18999 }
19000 })
19001 .collect();
19002
19003 if scopes.is_empty() {
19004 return Task::ready(Ok(vec![]));
19005 }
19006
19007 let snapshot = buffer.read(cx).text_snapshot();
19008 let chars: String = snapshot
19009 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19010 .collect();
19011 let executor = cx.background_executor().clone();
19012
19013 cx.background_spawn(async move {
19014 let mut all_results: Vec<Completion> = Vec::new();
19015 for (scope, snippets) in scopes.into_iter() {
19016 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19017 let mut last_word = chars
19018 .chars()
19019 .take_while(|c| classifier.is_word(*c))
19020 .collect::<String>();
19021 last_word = last_word.chars().rev().collect();
19022
19023 if last_word.is_empty() {
19024 return Ok(vec![]);
19025 }
19026
19027 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19028 let to_lsp = |point: &text::Anchor| {
19029 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19030 point_to_lsp(end)
19031 };
19032 let lsp_end = to_lsp(&buffer_position);
19033
19034 let candidates = snippets
19035 .iter()
19036 .enumerate()
19037 .flat_map(|(ix, snippet)| {
19038 snippet
19039 .prefix
19040 .iter()
19041 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19042 })
19043 .collect::<Vec<StringMatchCandidate>>();
19044
19045 let mut matches = fuzzy::match_strings(
19046 &candidates,
19047 &last_word,
19048 last_word.chars().any(|c| c.is_uppercase()),
19049 100,
19050 &Default::default(),
19051 executor.clone(),
19052 )
19053 .await;
19054
19055 // Remove all candidates where the query's start does not match the start of any word in the candidate
19056 if let Some(query_start) = last_word.chars().next() {
19057 matches.retain(|string_match| {
19058 split_words(&string_match.string).any(|word| {
19059 // Check that the first codepoint of the word as lowercase matches the first
19060 // codepoint of the query as lowercase
19061 word.chars()
19062 .flat_map(|codepoint| codepoint.to_lowercase())
19063 .zip(query_start.to_lowercase())
19064 .all(|(word_cp, query_cp)| word_cp == query_cp)
19065 })
19066 });
19067 }
19068
19069 let matched_strings = matches
19070 .into_iter()
19071 .map(|m| m.string)
19072 .collect::<HashSet<_>>();
19073
19074 let mut result: Vec<Completion> = snippets
19075 .iter()
19076 .filter_map(|snippet| {
19077 let matching_prefix = snippet
19078 .prefix
19079 .iter()
19080 .find(|prefix| matched_strings.contains(*prefix))?;
19081 let start = as_offset - last_word.len();
19082 let start = snapshot.anchor_before(start);
19083 let range = start..buffer_position;
19084 let lsp_start = to_lsp(&start);
19085 let lsp_range = lsp::Range {
19086 start: lsp_start,
19087 end: lsp_end,
19088 };
19089 Some(Completion {
19090 replace_range: range,
19091 new_text: snippet.body.clone(),
19092 source: CompletionSource::Lsp {
19093 insert_range: None,
19094 server_id: LanguageServerId(usize::MAX),
19095 resolved: true,
19096 lsp_completion: Box::new(lsp::CompletionItem {
19097 label: snippet.prefix.first().unwrap().clone(),
19098 kind: Some(CompletionItemKind::SNIPPET),
19099 label_details: snippet.description.as_ref().map(|description| {
19100 lsp::CompletionItemLabelDetails {
19101 detail: Some(description.clone()),
19102 description: None,
19103 }
19104 }),
19105 insert_text_format: Some(InsertTextFormat::SNIPPET),
19106 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19107 lsp::InsertReplaceEdit {
19108 new_text: snippet.body.clone(),
19109 insert: lsp_range,
19110 replace: lsp_range,
19111 },
19112 )),
19113 filter_text: Some(snippet.body.clone()),
19114 sort_text: Some(char::MAX.to_string()),
19115 ..lsp::CompletionItem::default()
19116 }),
19117 lsp_defaults: None,
19118 },
19119 label: CodeLabel {
19120 text: matching_prefix.clone(),
19121 runs: Vec::new(),
19122 filter_range: 0..matching_prefix.len(),
19123 },
19124 icon_path: None,
19125 documentation: snippet.description.clone().map(|description| {
19126 CompletionDocumentation::SingleLine(description.into())
19127 }),
19128 insert_text_mode: None,
19129 confirm: None,
19130 })
19131 })
19132 .collect();
19133
19134 all_results.append(&mut result);
19135 }
19136
19137 Ok(all_results)
19138 })
19139}
19140
19141impl CompletionProvider for Entity<Project> {
19142 fn completions(
19143 &self,
19144 _excerpt_id: ExcerptId,
19145 buffer: &Entity<Buffer>,
19146 buffer_position: text::Anchor,
19147 options: CompletionContext,
19148 _window: &mut Window,
19149 cx: &mut Context<Editor>,
19150 ) -> Task<Result<Option<Vec<Completion>>>> {
19151 self.update(cx, |project, cx| {
19152 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19153 let project_completions = project.completions(buffer, buffer_position, options, cx);
19154 cx.background_spawn(async move {
19155 let snippets_completions = snippets.await?;
19156 match project_completions.await? {
19157 Some(mut completions) => {
19158 completions.extend(snippets_completions);
19159 Ok(Some(completions))
19160 }
19161 None => {
19162 if snippets_completions.is_empty() {
19163 Ok(None)
19164 } else {
19165 Ok(Some(snippets_completions))
19166 }
19167 }
19168 }
19169 })
19170 })
19171 }
19172
19173 fn resolve_completions(
19174 &self,
19175 buffer: Entity<Buffer>,
19176 completion_indices: Vec<usize>,
19177 completions: Rc<RefCell<Box<[Completion]>>>,
19178 cx: &mut Context<Editor>,
19179 ) -> Task<Result<bool>> {
19180 self.update(cx, |project, cx| {
19181 project.lsp_store().update(cx, |lsp_store, cx| {
19182 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19183 })
19184 })
19185 }
19186
19187 fn apply_additional_edits_for_completion(
19188 &self,
19189 buffer: Entity<Buffer>,
19190 completions: Rc<RefCell<Box<[Completion]>>>,
19191 completion_index: usize,
19192 push_to_history: bool,
19193 cx: &mut Context<Editor>,
19194 ) -> Task<Result<Option<language::Transaction>>> {
19195 self.update(cx, |project, cx| {
19196 project.lsp_store().update(cx, |lsp_store, cx| {
19197 lsp_store.apply_additional_edits_for_completion(
19198 buffer,
19199 completions,
19200 completion_index,
19201 push_to_history,
19202 cx,
19203 )
19204 })
19205 })
19206 }
19207
19208 fn is_completion_trigger(
19209 &self,
19210 buffer: &Entity<Buffer>,
19211 position: language::Anchor,
19212 text: &str,
19213 trigger_in_words: bool,
19214 cx: &mut Context<Editor>,
19215 ) -> bool {
19216 let mut chars = text.chars();
19217 let char = if let Some(char) = chars.next() {
19218 char
19219 } else {
19220 return false;
19221 };
19222 if chars.next().is_some() {
19223 return false;
19224 }
19225
19226 let buffer = buffer.read(cx);
19227 let snapshot = buffer.snapshot();
19228 if !snapshot.settings_at(position, cx).show_completions_on_input {
19229 return false;
19230 }
19231 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19232 if trigger_in_words && classifier.is_word(char) {
19233 return true;
19234 }
19235
19236 buffer.completion_triggers().contains(text)
19237 }
19238}
19239
19240impl SemanticsProvider for Entity<Project> {
19241 fn hover(
19242 &self,
19243 buffer: &Entity<Buffer>,
19244 position: text::Anchor,
19245 cx: &mut App,
19246 ) -> Option<Task<Vec<project::Hover>>> {
19247 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19248 }
19249
19250 fn document_highlights(
19251 &self,
19252 buffer: &Entity<Buffer>,
19253 position: text::Anchor,
19254 cx: &mut App,
19255 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19256 Some(self.update(cx, |project, cx| {
19257 project.document_highlights(buffer, position, cx)
19258 }))
19259 }
19260
19261 fn definitions(
19262 &self,
19263 buffer: &Entity<Buffer>,
19264 position: text::Anchor,
19265 kind: GotoDefinitionKind,
19266 cx: &mut App,
19267 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19268 Some(self.update(cx, |project, cx| match kind {
19269 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19270 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19271 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19272 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19273 }))
19274 }
19275
19276 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19277 // TODO: make this work for remote projects
19278 self.update(cx, |this, cx| {
19279 buffer.update(cx, |buffer, cx| {
19280 this.any_language_server_supports_inlay_hints(buffer, cx)
19281 })
19282 })
19283 }
19284
19285 fn inlay_hints(
19286 &self,
19287 buffer_handle: Entity<Buffer>,
19288 range: Range<text::Anchor>,
19289 cx: &mut App,
19290 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19291 Some(self.update(cx, |project, cx| {
19292 project.inlay_hints(buffer_handle, range, cx)
19293 }))
19294 }
19295
19296 fn resolve_inlay_hint(
19297 &self,
19298 hint: InlayHint,
19299 buffer_handle: Entity<Buffer>,
19300 server_id: LanguageServerId,
19301 cx: &mut App,
19302 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19303 Some(self.update(cx, |project, cx| {
19304 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19305 }))
19306 }
19307
19308 fn range_for_rename(
19309 &self,
19310 buffer: &Entity<Buffer>,
19311 position: text::Anchor,
19312 cx: &mut App,
19313 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19314 Some(self.update(cx, |project, cx| {
19315 let buffer = buffer.clone();
19316 let task = project.prepare_rename(buffer.clone(), position, cx);
19317 cx.spawn(async move |_, cx| {
19318 Ok(match task.await? {
19319 PrepareRenameResponse::Success(range) => Some(range),
19320 PrepareRenameResponse::InvalidPosition => None,
19321 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19322 // Fallback on using TreeSitter info to determine identifier range
19323 buffer.update(cx, |buffer, _| {
19324 let snapshot = buffer.snapshot();
19325 let (range, kind) = snapshot.surrounding_word(position);
19326 if kind != Some(CharKind::Word) {
19327 return None;
19328 }
19329 Some(
19330 snapshot.anchor_before(range.start)
19331 ..snapshot.anchor_after(range.end),
19332 )
19333 })?
19334 }
19335 })
19336 })
19337 }))
19338 }
19339
19340 fn perform_rename(
19341 &self,
19342 buffer: &Entity<Buffer>,
19343 position: text::Anchor,
19344 new_name: String,
19345 cx: &mut App,
19346 ) -> Option<Task<Result<ProjectTransaction>>> {
19347 Some(self.update(cx, |project, cx| {
19348 project.perform_rename(buffer.clone(), position, new_name, cx)
19349 }))
19350 }
19351}
19352
19353fn inlay_hint_settings(
19354 location: Anchor,
19355 snapshot: &MultiBufferSnapshot,
19356 cx: &mut Context<Editor>,
19357) -> InlayHintSettings {
19358 let file = snapshot.file_at(location);
19359 let language = snapshot.language_at(location).map(|l| l.name());
19360 language_settings(language, file, cx).inlay_hints
19361}
19362
19363fn consume_contiguous_rows(
19364 contiguous_row_selections: &mut Vec<Selection<Point>>,
19365 selection: &Selection<Point>,
19366 display_map: &DisplaySnapshot,
19367 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19368) -> (MultiBufferRow, MultiBufferRow) {
19369 contiguous_row_selections.push(selection.clone());
19370 let start_row = MultiBufferRow(selection.start.row);
19371 let mut end_row = ending_row(selection, display_map);
19372
19373 while let Some(next_selection) = selections.peek() {
19374 if next_selection.start.row <= end_row.0 {
19375 end_row = ending_row(next_selection, display_map);
19376 contiguous_row_selections.push(selections.next().unwrap().clone());
19377 } else {
19378 break;
19379 }
19380 }
19381 (start_row, end_row)
19382}
19383
19384fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19385 if next_selection.end.column > 0 || next_selection.is_empty() {
19386 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19387 } else {
19388 MultiBufferRow(next_selection.end.row)
19389 }
19390}
19391
19392impl EditorSnapshot {
19393 pub fn remote_selections_in_range<'a>(
19394 &'a self,
19395 range: &'a Range<Anchor>,
19396 collaboration_hub: &dyn CollaborationHub,
19397 cx: &'a App,
19398 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19399 let participant_names = collaboration_hub.user_names(cx);
19400 let participant_indices = collaboration_hub.user_participant_indices(cx);
19401 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19402 let collaborators_by_replica_id = collaborators_by_peer_id
19403 .iter()
19404 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19405 .collect::<HashMap<_, _>>();
19406 self.buffer_snapshot
19407 .selections_in_range(range, false)
19408 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19409 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19410 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19411 let user_name = participant_names.get(&collaborator.user_id).cloned();
19412 Some(RemoteSelection {
19413 replica_id,
19414 selection,
19415 cursor_shape,
19416 line_mode,
19417 participant_index,
19418 peer_id: collaborator.peer_id,
19419 user_name,
19420 })
19421 })
19422 }
19423
19424 pub fn hunks_for_ranges(
19425 &self,
19426 ranges: impl IntoIterator<Item = Range<Point>>,
19427 ) -> Vec<MultiBufferDiffHunk> {
19428 let mut hunks = Vec::new();
19429 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19430 HashMap::default();
19431 for query_range in ranges {
19432 let query_rows =
19433 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19434 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19435 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19436 ) {
19437 // Include deleted hunks that are adjacent to the query range, because
19438 // otherwise they would be missed.
19439 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19440 if hunk.status().is_deleted() {
19441 intersects_range |= hunk.row_range.start == query_rows.end;
19442 intersects_range |= hunk.row_range.end == query_rows.start;
19443 }
19444 if intersects_range {
19445 if !processed_buffer_rows
19446 .entry(hunk.buffer_id)
19447 .or_default()
19448 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19449 {
19450 continue;
19451 }
19452 hunks.push(hunk);
19453 }
19454 }
19455 }
19456
19457 hunks
19458 }
19459
19460 fn display_diff_hunks_for_rows<'a>(
19461 &'a self,
19462 display_rows: Range<DisplayRow>,
19463 folded_buffers: &'a HashSet<BufferId>,
19464 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19465 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19466 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19467
19468 self.buffer_snapshot
19469 .diff_hunks_in_range(buffer_start..buffer_end)
19470 .filter_map(|hunk| {
19471 if folded_buffers.contains(&hunk.buffer_id) {
19472 return None;
19473 }
19474
19475 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19476 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19477
19478 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19479 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19480
19481 let display_hunk = if hunk_display_start.column() != 0 {
19482 DisplayDiffHunk::Folded {
19483 display_row: hunk_display_start.row(),
19484 }
19485 } else {
19486 let mut end_row = hunk_display_end.row();
19487 if hunk_display_end.column() > 0 {
19488 end_row.0 += 1;
19489 }
19490 let is_created_file = hunk.is_created_file();
19491 DisplayDiffHunk::Unfolded {
19492 status: hunk.status(),
19493 diff_base_byte_range: hunk.diff_base_byte_range,
19494 display_row_range: hunk_display_start.row()..end_row,
19495 multi_buffer_range: Anchor::range_in_buffer(
19496 hunk.excerpt_id,
19497 hunk.buffer_id,
19498 hunk.buffer_range,
19499 ),
19500 is_created_file,
19501 }
19502 };
19503
19504 Some(display_hunk)
19505 })
19506 }
19507
19508 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19509 self.display_snapshot.buffer_snapshot.language_at(position)
19510 }
19511
19512 pub fn is_focused(&self) -> bool {
19513 self.is_focused
19514 }
19515
19516 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19517 self.placeholder_text.as_ref()
19518 }
19519
19520 pub fn scroll_position(&self) -> gpui::Point<f32> {
19521 self.scroll_anchor.scroll_position(&self.display_snapshot)
19522 }
19523
19524 fn gutter_dimensions(
19525 &self,
19526 font_id: FontId,
19527 font_size: Pixels,
19528 max_line_number_width: Pixels,
19529 cx: &App,
19530 ) -> Option<GutterDimensions> {
19531 if !self.show_gutter {
19532 return None;
19533 }
19534
19535 let descent = cx.text_system().descent(font_id, font_size);
19536 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19537 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19538
19539 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19540 matches!(
19541 ProjectSettings::get_global(cx).git.git_gutter,
19542 Some(GitGutterSetting::TrackedFiles)
19543 )
19544 });
19545 let gutter_settings = EditorSettings::get_global(cx).gutter;
19546 let show_line_numbers = self
19547 .show_line_numbers
19548 .unwrap_or(gutter_settings.line_numbers);
19549 let line_gutter_width = if show_line_numbers {
19550 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19551 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19552 max_line_number_width.max(min_width_for_number_on_gutter)
19553 } else {
19554 0.0.into()
19555 };
19556
19557 let show_code_actions = self
19558 .show_code_actions
19559 .unwrap_or(gutter_settings.code_actions);
19560
19561 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19562 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19563
19564 let git_blame_entries_width =
19565 self.git_blame_gutter_max_author_length
19566 .map(|max_author_length| {
19567 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19568 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19569
19570 /// The number of characters to dedicate to gaps and margins.
19571 const SPACING_WIDTH: usize = 4;
19572
19573 let max_char_count = max_author_length.min(renderer.max_author_length())
19574 + ::git::SHORT_SHA_LENGTH
19575 + MAX_RELATIVE_TIMESTAMP.len()
19576 + SPACING_WIDTH;
19577
19578 em_advance * max_char_count
19579 });
19580
19581 let is_singleton = self.buffer_snapshot.is_singleton();
19582
19583 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19584 left_padding += if !is_singleton {
19585 em_width * 4.0
19586 } else if show_code_actions || show_runnables || show_breakpoints {
19587 em_width * 3.0
19588 } else if show_git_gutter && show_line_numbers {
19589 em_width * 2.0
19590 } else if show_git_gutter || show_line_numbers {
19591 em_width
19592 } else {
19593 px(0.)
19594 };
19595
19596 let shows_folds = is_singleton && gutter_settings.folds;
19597
19598 let right_padding = if shows_folds && show_line_numbers {
19599 em_width * 4.0
19600 } else if shows_folds || (!is_singleton && show_line_numbers) {
19601 em_width * 3.0
19602 } else if show_line_numbers {
19603 em_width
19604 } else {
19605 px(0.)
19606 };
19607
19608 Some(GutterDimensions {
19609 left_padding,
19610 right_padding,
19611 width: line_gutter_width + left_padding + right_padding,
19612 margin: -descent,
19613 git_blame_entries_width,
19614 })
19615 }
19616
19617 pub fn render_crease_toggle(
19618 &self,
19619 buffer_row: MultiBufferRow,
19620 row_contains_cursor: bool,
19621 editor: Entity<Editor>,
19622 window: &mut Window,
19623 cx: &mut App,
19624 ) -> Option<AnyElement> {
19625 let folded = self.is_line_folded(buffer_row);
19626 let mut is_foldable = false;
19627
19628 if let Some(crease) = self
19629 .crease_snapshot
19630 .query_row(buffer_row, &self.buffer_snapshot)
19631 {
19632 is_foldable = true;
19633 match crease {
19634 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19635 if let Some(render_toggle) = render_toggle {
19636 let toggle_callback =
19637 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19638 if folded {
19639 editor.update(cx, |editor, cx| {
19640 editor.fold_at(buffer_row, window, cx)
19641 });
19642 } else {
19643 editor.update(cx, |editor, cx| {
19644 editor.unfold_at(buffer_row, window, cx)
19645 });
19646 }
19647 });
19648 return Some((render_toggle)(
19649 buffer_row,
19650 folded,
19651 toggle_callback,
19652 window,
19653 cx,
19654 ));
19655 }
19656 }
19657 }
19658 }
19659
19660 is_foldable |= self.starts_indent(buffer_row);
19661
19662 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19663 Some(
19664 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19665 .toggle_state(folded)
19666 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19667 if folded {
19668 this.unfold_at(buffer_row, window, cx);
19669 } else {
19670 this.fold_at(buffer_row, window, cx);
19671 }
19672 }))
19673 .into_any_element(),
19674 )
19675 } else {
19676 None
19677 }
19678 }
19679
19680 pub fn render_crease_trailer(
19681 &self,
19682 buffer_row: MultiBufferRow,
19683 window: &mut Window,
19684 cx: &mut App,
19685 ) -> Option<AnyElement> {
19686 let folded = self.is_line_folded(buffer_row);
19687 if let Crease::Inline { render_trailer, .. } = self
19688 .crease_snapshot
19689 .query_row(buffer_row, &self.buffer_snapshot)?
19690 {
19691 let render_trailer = render_trailer.as_ref()?;
19692 Some(render_trailer(buffer_row, folded, window, cx))
19693 } else {
19694 None
19695 }
19696 }
19697}
19698
19699impl Deref for EditorSnapshot {
19700 type Target = DisplaySnapshot;
19701
19702 fn deref(&self) -> &Self::Target {
19703 &self.display_snapshot
19704 }
19705}
19706
19707#[derive(Clone, Debug, PartialEq, Eq)]
19708pub enum EditorEvent {
19709 InputIgnored {
19710 text: Arc<str>,
19711 },
19712 InputHandled {
19713 utf16_range_to_replace: Option<Range<isize>>,
19714 text: Arc<str>,
19715 },
19716 ExcerptsAdded {
19717 buffer: Entity<Buffer>,
19718 predecessor: ExcerptId,
19719 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19720 },
19721 ExcerptsRemoved {
19722 ids: Vec<ExcerptId>,
19723 },
19724 BufferFoldToggled {
19725 ids: Vec<ExcerptId>,
19726 folded: bool,
19727 },
19728 ExcerptsEdited {
19729 ids: Vec<ExcerptId>,
19730 },
19731 ExcerptsExpanded {
19732 ids: Vec<ExcerptId>,
19733 },
19734 BufferEdited,
19735 Edited {
19736 transaction_id: clock::Lamport,
19737 },
19738 Reparsed(BufferId),
19739 Focused,
19740 FocusedIn,
19741 Blurred,
19742 DirtyChanged,
19743 Saved,
19744 TitleChanged,
19745 DiffBaseChanged,
19746 SelectionsChanged {
19747 local: bool,
19748 },
19749 ScrollPositionChanged {
19750 local: bool,
19751 autoscroll: bool,
19752 },
19753 Closed,
19754 TransactionUndone {
19755 transaction_id: clock::Lamport,
19756 },
19757 TransactionBegun {
19758 transaction_id: clock::Lamport,
19759 },
19760 Reloaded,
19761 CursorShapeChanged,
19762 PushedToNavHistory {
19763 anchor: Anchor,
19764 is_deactivate: bool,
19765 },
19766}
19767
19768impl EventEmitter<EditorEvent> for Editor {}
19769
19770impl Focusable for Editor {
19771 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19772 self.focus_handle.clone()
19773 }
19774}
19775
19776impl Render for Editor {
19777 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19778 let settings = ThemeSettings::get_global(cx);
19779
19780 let mut text_style = match self.mode {
19781 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19782 color: cx.theme().colors().editor_foreground,
19783 font_family: settings.ui_font.family.clone(),
19784 font_features: settings.ui_font.features.clone(),
19785 font_fallbacks: settings.ui_font.fallbacks.clone(),
19786 font_size: rems(0.875).into(),
19787 font_weight: settings.ui_font.weight,
19788 line_height: relative(settings.buffer_line_height.value()),
19789 ..Default::default()
19790 },
19791 EditorMode::Full { .. } => TextStyle {
19792 color: cx.theme().colors().editor_foreground,
19793 font_family: settings.buffer_font.family.clone(),
19794 font_features: settings.buffer_font.features.clone(),
19795 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19796 font_size: settings.buffer_font_size(cx).into(),
19797 font_weight: settings.buffer_font.weight,
19798 line_height: relative(settings.buffer_line_height.value()),
19799 ..Default::default()
19800 },
19801 };
19802 if let Some(text_style_refinement) = &self.text_style_refinement {
19803 text_style.refine(text_style_refinement)
19804 }
19805
19806 let background = match self.mode {
19807 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19808 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19809 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19810 };
19811
19812 EditorElement::new(
19813 &cx.entity(),
19814 EditorStyle {
19815 background,
19816 local_player: cx.theme().players().local(),
19817 text: text_style,
19818 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19819 syntax: cx.theme().syntax().clone(),
19820 status: cx.theme().status().clone(),
19821 inlay_hints_style: make_inlay_hints_style(cx),
19822 inline_completion_styles: make_suggestion_styles(cx),
19823 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19824 },
19825 )
19826 }
19827}
19828
19829impl EntityInputHandler for Editor {
19830 fn text_for_range(
19831 &mut self,
19832 range_utf16: Range<usize>,
19833 adjusted_range: &mut Option<Range<usize>>,
19834 _: &mut Window,
19835 cx: &mut Context<Self>,
19836 ) -> Option<String> {
19837 let snapshot = self.buffer.read(cx).read(cx);
19838 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19839 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19840 if (start.0..end.0) != range_utf16 {
19841 adjusted_range.replace(start.0..end.0);
19842 }
19843 Some(snapshot.text_for_range(start..end).collect())
19844 }
19845
19846 fn selected_text_range(
19847 &mut self,
19848 ignore_disabled_input: bool,
19849 _: &mut Window,
19850 cx: &mut Context<Self>,
19851 ) -> Option<UTF16Selection> {
19852 // Prevent the IME menu from appearing when holding down an alphabetic key
19853 // while input is disabled.
19854 if !ignore_disabled_input && !self.input_enabled {
19855 return None;
19856 }
19857
19858 let selection = self.selections.newest::<OffsetUtf16>(cx);
19859 let range = selection.range();
19860
19861 Some(UTF16Selection {
19862 range: range.start.0..range.end.0,
19863 reversed: selection.reversed,
19864 })
19865 }
19866
19867 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19868 let snapshot = self.buffer.read(cx).read(cx);
19869 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19870 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19871 }
19872
19873 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19874 self.clear_highlights::<InputComposition>(cx);
19875 self.ime_transaction.take();
19876 }
19877
19878 fn replace_text_in_range(
19879 &mut self,
19880 range_utf16: Option<Range<usize>>,
19881 text: &str,
19882 window: &mut Window,
19883 cx: &mut Context<Self>,
19884 ) {
19885 if !self.input_enabled {
19886 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19887 return;
19888 }
19889
19890 self.transact(window, cx, |this, window, cx| {
19891 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19892 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19893 Some(this.selection_replacement_ranges(range_utf16, cx))
19894 } else {
19895 this.marked_text_ranges(cx)
19896 };
19897
19898 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19899 let newest_selection_id = this.selections.newest_anchor().id;
19900 this.selections
19901 .all::<OffsetUtf16>(cx)
19902 .iter()
19903 .zip(ranges_to_replace.iter())
19904 .find_map(|(selection, range)| {
19905 if selection.id == newest_selection_id {
19906 Some(
19907 (range.start.0 as isize - selection.head().0 as isize)
19908 ..(range.end.0 as isize - selection.head().0 as isize),
19909 )
19910 } else {
19911 None
19912 }
19913 })
19914 });
19915
19916 cx.emit(EditorEvent::InputHandled {
19917 utf16_range_to_replace: range_to_replace,
19918 text: text.into(),
19919 });
19920
19921 if let Some(new_selected_ranges) = new_selected_ranges {
19922 this.change_selections(None, window, cx, |selections| {
19923 selections.select_ranges(new_selected_ranges)
19924 });
19925 this.backspace(&Default::default(), window, cx);
19926 }
19927
19928 this.handle_input(text, window, cx);
19929 });
19930
19931 if let Some(transaction) = self.ime_transaction {
19932 self.buffer.update(cx, |buffer, cx| {
19933 buffer.group_until_transaction(transaction, cx);
19934 });
19935 }
19936
19937 self.unmark_text(window, cx);
19938 }
19939
19940 fn replace_and_mark_text_in_range(
19941 &mut self,
19942 range_utf16: Option<Range<usize>>,
19943 text: &str,
19944 new_selected_range_utf16: Option<Range<usize>>,
19945 window: &mut Window,
19946 cx: &mut Context<Self>,
19947 ) {
19948 if !self.input_enabled {
19949 return;
19950 }
19951
19952 let transaction = self.transact(window, cx, |this, window, cx| {
19953 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19954 let snapshot = this.buffer.read(cx).read(cx);
19955 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19956 for marked_range in &mut marked_ranges {
19957 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19958 marked_range.start.0 += relative_range_utf16.start;
19959 marked_range.start =
19960 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19961 marked_range.end =
19962 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19963 }
19964 }
19965 Some(marked_ranges)
19966 } else if let Some(range_utf16) = range_utf16 {
19967 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19968 Some(this.selection_replacement_ranges(range_utf16, cx))
19969 } else {
19970 None
19971 };
19972
19973 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19974 let newest_selection_id = this.selections.newest_anchor().id;
19975 this.selections
19976 .all::<OffsetUtf16>(cx)
19977 .iter()
19978 .zip(ranges_to_replace.iter())
19979 .find_map(|(selection, range)| {
19980 if selection.id == newest_selection_id {
19981 Some(
19982 (range.start.0 as isize - selection.head().0 as isize)
19983 ..(range.end.0 as isize - selection.head().0 as isize),
19984 )
19985 } else {
19986 None
19987 }
19988 })
19989 });
19990
19991 cx.emit(EditorEvent::InputHandled {
19992 utf16_range_to_replace: range_to_replace,
19993 text: text.into(),
19994 });
19995
19996 if let Some(ranges) = ranges_to_replace {
19997 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19998 }
19999
20000 let marked_ranges = {
20001 let snapshot = this.buffer.read(cx).read(cx);
20002 this.selections
20003 .disjoint_anchors()
20004 .iter()
20005 .map(|selection| {
20006 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20007 })
20008 .collect::<Vec<_>>()
20009 };
20010
20011 if text.is_empty() {
20012 this.unmark_text(window, cx);
20013 } else {
20014 this.highlight_text::<InputComposition>(
20015 marked_ranges.clone(),
20016 HighlightStyle {
20017 underline: Some(UnderlineStyle {
20018 thickness: px(1.),
20019 color: None,
20020 wavy: false,
20021 }),
20022 ..Default::default()
20023 },
20024 cx,
20025 );
20026 }
20027
20028 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20029 let use_autoclose = this.use_autoclose;
20030 let use_auto_surround = this.use_auto_surround;
20031 this.set_use_autoclose(false);
20032 this.set_use_auto_surround(false);
20033 this.handle_input(text, window, cx);
20034 this.set_use_autoclose(use_autoclose);
20035 this.set_use_auto_surround(use_auto_surround);
20036
20037 if let Some(new_selected_range) = new_selected_range_utf16 {
20038 let snapshot = this.buffer.read(cx).read(cx);
20039 let new_selected_ranges = marked_ranges
20040 .into_iter()
20041 .map(|marked_range| {
20042 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20043 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20044 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20045 snapshot.clip_offset_utf16(new_start, Bias::Left)
20046 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20047 })
20048 .collect::<Vec<_>>();
20049
20050 drop(snapshot);
20051 this.change_selections(None, window, cx, |selections| {
20052 selections.select_ranges(new_selected_ranges)
20053 });
20054 }
20055 });
20056
20057 self.ime_transaction = self.ime_transaction.or(transaction);
20058 if let Some(transaction) = self.ime_transaction {
20059 self.buffer.update(cx, |buffer, cx| {
20060 buffer.group_until_transaction(transaction, cx);
20061 });
20062 }
20063
20064 if self.text_highlights::<InputComposition>(cx).is_none() {
20065 self.ime_transaction.take();
20066 }
20067 }
20068
20069 fn bounds_for_range(
20070 &mut self,
20071 range_utf16: Range<usize>,
20072 element_bounds: gpui::Bounds<Pixels>,
20073 window: &mut Window,
20074 cx: &mut Context<Self>,
20075 ) -> Option<gpui::Bounds<Pixels>> {
20076 let text_layout_details = self.text_layout_details(window);
20077 let gpui::Size {
20078 width: em_width,
20079 height: line_height,
20080 } = self.character_size(window);
20081
20082 let snapshot = self.snapshot(window, cx);
20083 let scroll_position = snapshot.scroll_position();
20084 let scroll_left = scroll_position.x * em_width;
20085
20086 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20087 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20088 + self.gutter_dimensions.width
20089 + self.gutter_dimensions.margin;
20090 let y = line_height * (start.row().as_f32() - scroll_position.y);
20091
20092 Some(Bounds {
20093 origin: element_bounds.origin + point(x, y),
20094 size: size(em_width, line_height),
20095 })
20096 }
20097
20098 fn character_index_for_point(
20099 &mut self,
20100 point: gpui::Point<Pixels>,
20101 _window: &mut Window,
20102 _cx: &mut Context<Self>,
20103 ) -> Option<usize> {
20104 let position_map = self.last_position_map.as_ref()?;
20105 if !position_map.text_hitbox.contains(&point) {
20106 return None;
20107 }
20108 let display_point = position_map.point_for_position(point).previous_valid;
20109 let anchor = position_map
20110 .snapshot
20111 .display_point_to_anchor(display_point, Bias::Left);
20112 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20113 Some(utf16_offset.0)
20114 }
20115}
20116
20117trait SelectionExt {
20118 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20119 fn spanned_rows(
20120 &self,
20121 include_end_if_at_line_start: bool,
20122 map: &DisplaySnapshot,
20123 ) -> Range<MultiBufferRow>;
20124}
20125
20126impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20127 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20128 let start = self
20129 .start
20130 .to_point(&map.buffer_snapshot)
20131 .to_display_point(map);
20132 let end = self
20133 .end
20134 .to_point(&map.buffer_snapshot)
20135 .to_display_point(map);
20136 if self.reversed {
20137 end..start
20138 } else {
20139 start..end
20140 }
20141 }
20142
20143 fn spanned_rows(
20144 &self,
20145 include_end_if_at_line_start: bool,
20146 map: &DisplaySnapshot,
20147 ) -> Range<MultiBufferRow> {
20148 let start = self.start.to_point(&map.buffer_snapshot);
20149 let mut end = self.end.to_point(&map.buffer_snapshot);
20150 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20151 end.row -= 1;
20152 }
20153
20154 let buffer_start = map.prev_line_boundary(start).0;
20155 let buffer_end = map.next_line_boundary(end).0;
20156 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20157 }
20158}
20159
20160impl<T: InvalidationRegion> InvalidationStack<T> {
20161 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20162 where
20163 S: Clone + ToOffset,
20164 {
20165 while let Some(region) = self.last() {
20166 let all_selections_inside_invalidation_ranges =
20167 if selections.len() == region.ranges().len() {
20168 selections
20169 .iter()
20170 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20171 .all(|(selection, invalidation_range)| {
20172 let head = selection.head().to_offset(buffer);
20173 invalidation_range.start <= head && invalidation_range.end >= head
20174 })
20175 } else {
20176 false
20177 };
20178
20179 if all_selections_inside_invalidation_ranges {
20180 break;
20181 } else {
20182 self.pop();
20183 }
20184 }
20185 }
20186}
20187
20188impl<T> Default for InvalidationStack<T> {
20189 fn default() -> Self {
20190 Self(Default::default())
20191 }
20192}
20193
20194impl<T> Deref for InvalidationStack<T> {
20195 type Target = Vec<T>;
20196
20197 fn deref(&self) -> &Self::Target {
20198 &self.0
20199 }
20200}
20201
20202impl<T> DerefMut for InvalidationStack<T> {
20203 fn deref_mut(&mut self) -> &mut Self::Target {
20204 &mut self.0
20205 }
20206}
20207
20208impl InvalidationRegion for SnippetState {
20209 fn ranges(&self) -> &[Range<Anchor>] {
20210 &self.ranges[self.active_index]
20211 }
20212}
20213
20214fn inline_completion_edit_text(
20215 current_snapshot: &BufferSnapshot,
20216 edits: &[(Range<Anchor>, String)],
20217 edit_preview: &EditPreview,
20218 include_deletions: bool,
20219 cx: &App,
20220) -> HighlightedText {
20221 let edits = edits
20222 .iter()
20223 .map(|(anchor, text)| {
20224 (
20225 anchor.start.text_anchor..anchor.end.text_anchor,
20226 text.clone(),
20227 )
20228 })
20229 .collect::<Vec<_>>();
20230
20231 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20232}
20233
20234pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20235 match severity {
20236 DiagnosticSeverity::ERROR => colors.error,
20237 DiagnosticSeverity::WARNING => colors.warning,
20238 DiagnosticSeverity::INFORMATION => colors.info,
20239 DiagnosticSeverity::HINT => colors.info,
20240 _ => colors.ignored,
20241 }
20242}
20243
20244pub fn styled_runs_for_code_label<'a>(
20245 label: &'a CodeLabel,
20246 syntax_theme: &'a theme::SyntaxTheme,
20247) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20248 let fade_out = HighlightStyle {
20249 fade_out: Some(0.35),
20250 ..Default::default()
20251 };
20252
20253 let mut prev_end = label.filter_range.end;
20254 label
20255 .runs
20256 .iter()
20257 .enumerate()
20258 .flat_map(move |(ix, (range, highlight_id))| {
20259 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20260 style
20261 } else {
20262 return Default::default();
20263 };
20264 let mut muted_style = style;
20265 muted_style.highlight(fade_out);
20266
20267 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20268 if range.start >= label.filter_range.end {
20269 if range.start > prev_end {
20270 runs.push((prev_end..range.start, fade_out));
20271 }
20272 runs.push((range.clone(), muted_style));
20273 } else if range.end <= label.filter_range.end {
20274 runs.push((range.clone(), style));
20275 } else {
20276 runs.push((range.start..label.filter_range.end, style));
20277 runs.push((label.filter_range.end..range.end, muted_style));
20278 }
20279 prev_end = cmp::max(prev_end, range.end);
20280
20281 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20282 runs.push((prev_end..label.text.len(), fade_out));
20283 }
20284
20285 runs
20286 })
20287}
20288
20289pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20290 let mut prev_index = 0;
20291 let mut prev_codepoint: Option<char> = None;
20292 text.char_indices()
20293 .chain([(text.len(), '\0')])
20294 .filter_map(move |(index, codepoint)| {
20295 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20296 let is_boundary = index == text.len()
20297 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20298 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20299 if is_boundary {
20300 let chunk = &text[prev_index..index];
20301 prev_index = index;
20302 Some(chunk)
20303 } else {
20304 None
20305 }
20306 })
20307}
20308
20309pub trait RangeToAnchorExt: Sized {
20310 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20311
20312 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20313 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20314 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20315 }
20316}
20317
20318impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20319 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20320 let start_offset = self.start.to_offset(snapshot);
20321 let end_offset = self.end.to_offset(snapshot);
20322 if start_offset == end_offset {
20323 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20324 } else {
20325 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20326 }
20327 }
20328}
20329
20330pub trait RowExt {
20331 fn as_f32(&self) -> f32;
20332
20333 fn next_row(&self) -> Self;
20334
20335 fn previous_row(&self) -> Self;
20336
20337 fn minus(&self, other: Self) -> u32;
20338}
20339
20340impl RowExt for DisplayRow {
20341 fn as_f32(&self) -> f32 {
20342 self.0 as f32
20343 }
20344
20345 fn next_row(&self) -> Self {
20346 Self(self.0 + 1)
20347 }
20348
20349 fn previous_row(&self) -> Self {
20350 Self(self.0.saturating_sub(1))
20351 }
20352
20353 fn minus(&self, other: Self) -> u32 {
20354 self.0 - other.0
20355 }
20356}
20357
20358impl RowExt for MultiBufferRow {
20359 fn as_f32(&self) -> f32 {
20360 self.0 as f32
20361 }
20362
20363 fn next_row(&self) -> Self {
20364 Self(self.0 + 1)
20365 }
20366
20367 fn previous_row(&self) -> Self {
20368 Self(self.0.saturating_sub(1))
20369 }
20370
20371 fn minus(&self, other: Self) -> u32 {
20372 self.0 - other.0
20373 }
20374}
20375
20376trait RowRangeExt {
20377 type Row;
20378
20379 fn len(&self) -> usize;
20380
20381 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20382}
20383
20384impl RowRangeExt for Range<MultiBufferRow> {
20385 type Row = MultiBufferRow;
20386
20387 fn len(&self) -> usize {
20388 (self.end.0 - self.start.0) as usize
20389 }
20390
20391 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20392 (self.start.0..self.end.0).map(MultiBufferRow)
20393 }
20394}
20395
20396impl RowRangeExt for Range<DisplayRow> {
20397 type Row = DisplayRow;
20398
20399 fn len(&self) -> usize {
20400 (self.end.0 - self.start.0) as usize
20401 }
20402
20403 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20404 (self.start.0..self.end.0).map(DisplayRow)
20405 }
20406}
20407
20408/// If select range has more than one line, we
20409/// just point the cursor to range.start.
20410fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20411 if range.start.row == range.end.row {
20412 range
20413 } else {
20414 range.start..range.start
20415 }
20416}
20417pub struct KillRing(ClipboardItem);
20418impl Global for KillRing {}
20419
20420const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20421
20422enum BreakpointPromptEditAction {
20423 Log,
20424 Condition,
20425 HitCondition,
20426}
20427
20428struct BreakpointPromptEditor {
20429 pub(crate) prompt: Entity<Editor>,
20430 editor: WeakEntity<Editor>,
20431 breakpoint_anchor: Anchor,
20432 breakpoint: Breakpoint,
20433 edit_action: BreakpointPromptEditAction,
20434 block_ids: HashSet<CustomBlockId>,
20435 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20436 _subscriptions: Vec<Subscription>,
20437}
20438
20439impl BreakpointPromptEditor {
20440 const MAX_LINES: u8 = 4;
20441
20442 fn new(
20443 editor: WeakEntity<Editor>,
20444 breakpoint_anchor: Anchor,
20445 breakpoint: Breakpoint,
20446 edit_action: BreakpointPromptEditAction,
20447 window: &mut Window,
20448 cx: &mut Context<Self>,
20449 ) -> Self {
20450 let base_text = match edit_action {
20451 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20452 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20453 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20454 }
20455 .map(|msg| msg.to_string())
20456 .unwrap_or_default();
20457
20458 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20459 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20460
20461 let prompt = cx.new(|cx| {
20462 let mut prompt = Editor::new(
20463 EditorMode::AutoHeight {
20464 max_lines: Self::MAX_LINES as usize,
20465 },
20466 buffer,
20467 None,
20468 window,
20469 cx,
20470 );
20471 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20472 prompt.set_show_cursor_when_unfocused(false, cx);
20473 prompt.set_placeholder_text(
20474 match edit_action {
20475 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20476 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20477 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20478 },
20479 cx,
20480 );
20481
20482 prompt
20483 });
20484
20485 Self {
20486 prompt,
20487 editor,
20488 breakpoint_anchor,
20489 breakpoint,
20490 edit_action,
20491 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20492 block_ids: Default::default(),
20493 _subscriptions: vec![],
20494 }
20495 }
20496
20497 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20498 self.block_ids.extend(block_ids)
20499 }
20500
20501 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20502 if let Some(editor) = self.editor.upgrade() {
20503 let message = self
20504 .prompt
20505 .read(cx)
20506 .buffer
20507 .read(cx)
20508 .as_singleton()
20509 .expect("A multi buffer in breakpoint prompt isn't possible")
20510 .read(cx)
20511 .as_rope()
20512 .to_string();
20513
20514 editor.update(cx, |editor, cx| {
20515 editor.edit_breakpoint_at_anchor(
20516 self.breakpoint_anchor,
20517 self.breakpoint.clone(),
20518 match self.edit_action {
20519 BreakpointPromptEditAction::Log => {
20520 BreakpointEditAction::EditLogMessage(message.into())
20521 }
20522 BreakpointPromptEditAction::Condition => {
20523 BreakpointEditAction::EditCondition(message.into())
20524 }
20525 BreakpointPromptEditAction::HitCondition => {
20526 BreakpointEditAction::EditHitCondition(message.into())
20527 }
20528 },
20529 cx,
20530 );
20531
20532 editor.remove_blocks(self.block_ids.clone(), None, cx);
20533 cx.focus_self(window);
20534 });
20535 }
20536 }
20537
20538 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20539 self.editor
20540 .update(cx, |editor, cx| {
20541 editor.remove_blocks(self.block_ids.clone(), None, cx);
20542 window.focus(&editor.focus_handle);
20543 })
20544 .log_err();
20545 }
20546
20547 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20548 let settings = ThemeSettings::get_global(cx);
20549 let text_style = TextStyle {
20550 color: if self.prompt.read(cx).read_only(cx) {
20551 cx.theme().colors().text_disabled
20552 } else {
20553 cx.theme().colors().text
20554 },
20555 font_family: settings.buffer_font.family.clone(),
20556 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20557 font_size: settings.buffer_font_size(cx).into(),
20558 font_weight: settings.buffer_font.weight,
20559 line_height: relative(settings.buffer_line_height.value()),
20560 ..Default::default()
20561 };
20562 EditorElement::new(
20563 &self.prompt,
20564 EditorStyle {
20565 background: cx.theme().colors().editor_background,
20566 local_player: cx.theme().players().local(),
20567 text: text_style,
20568 ..Default::default()
20569 },
20570 )
20571 }
20572}
20573
20574impl Render for BreakpointPromptEditor {
20575 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20576 let gutter_dimensions = *self.gutter_dimensions.lock();
20577 h_flex()
20578 .key_context("Editor")
20579 .bg(cx.theme().colors().editor_background)
20580 .border_y_1()
20581 .border_color(cx.theme().status().info_border)
20582 .size_full()
20583 .py(window.line_height() / 2.5)
20584 .on_action(cx.listener(Self::confirm))
20585 .on_action(cx.listener(Self::cancel))
20586 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20587 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20588 }
20589}
20590
20591impl Focusable for BreakpointPromptEditor {
20592 fn focus_handle(&self, cx: &App) -> FocusHandle {
20593 self.prompt.focus_handle(cx)
20594 }
20595}
20596
20597fn all_edits_insertions_or_deletions(
20598 edits: &Vec<(Range<Anchor>, String)>,
20599 snapshot: &MultiBufferSnapshot,
20600) -> bool {
20601 let mut all_insertions = true;
20602 let mut all_deletions = true;
20603
20604 for (range, new_text) in edits.iter() {
20605 let range_is_empty = range.to_offset(&snapshot).is_empty();
20606 let text_is_empty = new_text.is_empty();
20607
20608 if range_is_empty != text_is_empty {
20609 if range_is_empty {
20610 all_deletions = false;
20611 } else {
20612 all_insertions = false;
20613 }
20614 } else {
20615 return false;
20616 }
20617
20618 if !all_insertions && !all_deletions {
20619 return false;
20620 }
20621 }
20622 all_insertions || all_deletions
20623}
20624
20625struct MissingEditPredictionKeybindingTooltip;
20626
20627impl Render for MissingEditPredictionKeybindingTooltip {
20628 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20629 ui::tooltip_container(window, cx, |container, _, cx| {
20630 container
20631 .flex_shrink_0()
20632 .max_w_80()
20633 .min_h(rems_from_px(124.))
20634 .justify_between()
20635 .child(
20636 v_flex()
20637 .flex_1()
20638 .text_ui_sm(cx)
20639 .child(Label::new("Conflict with Accept Keybinding"))
20640 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20641 )
20642 .child(
20643 h_flex()
20644 .pb_1()
20645 .gap_1()
20646 .items_end()
20647 .w_full()
20648 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20649 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20650 }))
20651 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20652 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20653 })),
20654 )
20655 })
20656 }
20657}
20658
20659#[derive(Debug, Clone, Copy, PartialEq)]
20660pub struct LineHighlight {
20661 pub background: Background,
20662 pub border: Option<gpui::Hsla>,
20663}
20664
20665impl From<Hsla> for LineHighlight {
20666 fn from(hsla: Hsla) -> Self {
20667 Self {
20668 background: hsla.into(),
20669 border: None,
20670 }
20671 }
20672}
20673
20674impl From<Background> for LineHighlight {
20675 fn from(background: Background) -> Self {
20676 Self {
20677 background,
20678 border: None,
20679 }
20680 }
20681}
20682
20683fn render_diff_hunk_controls(
20684 row: u32,
20685 status: &DiffHunkStatus,
20686 hunk_range: Range<Anchor>,
20687 is_created_file: bool,
20688 line_height: Pixels,
20689 editor: &Entity<Editor>,
20690 _window: &mut Window,
20691 cx: &mut App,
20692) -> AnyElement {
20693 h_flex()
20694 .h(line_height)
20695 .mr_1()
20696 .gap_1()
20697 .px_0p5()
20698 .pb_1()
20699 .border_x_1()
20700 .border_b_1()
20701 .border_color(cx.theme().colors().border_variant)
20702 .rounded_b_lg()
20703 .bg(cx.theme().colors().editor_background)
20704 .gap_1()
20705 .occlude()
20706 .shadow_md()
20707 .child(if status.has_secondary_hunk() {
20708 Button::new(("stage", row as u64), "Stage")
20709 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20710 .tooltip({
20711 let focus_handle = editor.focus_handle(cx);
20712 move |window, cx| {
20713 Tooltip::for_action_in(
20714 "Stage Hunk",
20715 &::git::ToggleStaged,
20716 &focus_handle,
20717 window,
20718 cx,
20719 )
20720 }
20721 })
20722 .on_click({
20723 let editor = editor.clone();
20724 move |_event, _window, cx| {
20725 editor.update(cx, |editor, cx| {
20726 editor.stage_or_unstage_diff_hunks(
20727 true,
20728 vec![hunk_range.start..hunk_range.start],
20729 cx,
20730 );
20731 });
20732 }
20733 })
20734 } else {
20735 Button::new(("unstage", row as u64), "Unstage")
20736 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20737 .tooltip({
20738 let focus_handle = editor.focus_handle(cx);
20739 move |window, cx| {
20740 Tooltip::for_action_in(
20741 "Unstage Hunk",
20742 &::git::ToggleStaged,
20743 &focus_handle,
20744 window,
20745 cx,
20746 )
20747 }
20748 })
20749 .on_click({
20750 let editor = editor.clone();
20751 move |_event, _window, cx| {
20752 editor.update(cx, |editor, cx| {
20753 editor.stage_or_unstage_diff_hunks(
20754 false,
20755 vec![hunk_range.start..hunk_range.start],
20756 cx,
20757 );
20758 });
20759 }
20760 })
20761 })
20762 .child(
20763 Button::new(("restore", row as u64), "Restore")
20764 .tooltip({
20765 let focus_handle = editor.focus_handle(cx);
20766 move |window, cx| {
20767 Tooltip::for_action_in(
20768 "Restore Hunk",
20769 &::git::Restore,
20770 &focus_handle,
20771 window,
20772 cx,
20773 )
20774 }
20775 })
20776 .on_click({
20777 let editor = editor.clone();
20778 move |_event, window, cx| {
20779 editor.update(cx, |editor, cx| {
20780 let snapshot = editor.snapshot(window, cx);
20781 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20782 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20783 });
20784 }
20785 })
20786 .disabled(is_created_file),
20787 )
20788 .when(
20789 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20790 |el| {
20791 el.child(
20792 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20793 .shape(IconButtonShape::Square)
20794 .icon_size(IconSize::Small)
20795 // .disabled(!has_multiple_hunks)
20796 .tooltip({
20797 let focus_handle = editor.focus_handle(cx);
20798 move |window, cx| {
20799 Tooltip::for_action_in(
20800 "Next Hunk",
20801 &GoToHunk,
20802 &focus_handle,
20803 window,
20804 cx,
20805 )
20806 }
20807 })
20808 .on_click({
20809 let editor = editor.clone();
20810 move |_event, window, cx| {
20811 editor.update(cx, |editor, cx| {
20812 let snapshot = editor.snapshot(window, cx);
20813 let position =
20814 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20815 editor.go_to_hunk_before_or_after_position(
20816 &snapshot,
20817 position,
20818 Direction::Next,
20819 window,
20820 cx,
20821 );
20822 editor.expand_selected_diff_hunks(cx);
20823 });
20824 }
20825 }),
20826 )
20827 .child(
20828 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20829 .shape(IconButtonShape::Square)
20830 .icon_size(IconSize::Small)
20831 // .disabled(!has_multiple_hunks)
20832 .tooltip({
20833 let focus_handle = editor.focus_handle(cx);
20834 move |window, cx| {
20835 Tooltip::for_action_in(
20836 "Previous Hunk",
20837 &GoToPreviousHunk,
20838 &focus_handle,
20839 window,
20840 cx,
20841 )
20842 }
20843 })
20844 .on_click({
20845 let editor = editor.clone();
20846 move |_event, window, cx| {
20847 editor.update(cx, |editor, cx| {
20848 let snapshot = editor.snapshot(window, cx);
20849 let point =
20850 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20851 editor.go_to_hunk_before_or_after_position(
20852 &snapshot,
20853 point,
20854 Direction::Prev,
20855 window,
20856 cx,
20857 );
20858 editor.expand_selected_diff_hunks(cx);
20859 });
20860 }
20861 }),
20862 )
20863 },
20864 )
20865 .into_any_element()
20866}