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);
218const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
219
220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
223
224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
227
228pub type RenderDiffHunkControlsFn = Arc<
229 dyn Fn(
230 u32,
231 &DiffHunkStatus,
232 Range<Anchor>,
233 bool,
234 Pixels,
235 &Entity<Editor>,
236 &mut Window,
237 &mut App,
238 ) -> AnyElement,
239>;
240
241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
242 alt: true,
243 shift: true,
244 control: false,
245 platform: false,
246 function: false,
247};
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
250pub enum InlayId {
251 InlineCompletion(usize),
252 Hint(usize),
253}
254
255impl InlayId {
256 fn id(&self) -> usize {
257 match self {
258 Self::InlineCompletion(id) => *id,
259 Self::Hint(id) => *id,
260 }
261 }
262}
263
264pub enum DebugCurrentRowHighlight {}
265enum DocumentHighlightRead {}
266enum DocumentHighlightWrite {}
267enum InputComposition {}
268enum SelectedTextHighlight {}
269
270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
271pub enum Navigated {
272 Yes,
273 No,
274}
275
276impl Navigated {
277 pub fn from_bool(yes: bool) -> Navigated {
278 if yes { Navigated::Yes } else { Navigated::No }
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283enum DisplayDiffHunk {
284 Folded {
285 display_row: DisplayRow,
286 },
287 Unfolded {
288 is_created_file: bool,
289 diff_base_byte_range: Range<usize>,
290 display_row_range: Range<DisplayRow>,
291 multi_buffer_range: Range<Anchor>,
292 status: DiffHunkStatus,
293 },
294}
295
296pub enum HideMouseCursorOrigin {
297 TypingAction,
298 MovementAction,
299}
300
301pub fn init_settings(cx: &mut App) {
302 EditorSettings::register(cx);
303}
304
305pub fn init(cx: &mut App) {
306 init_settings(cx);
307
308 cx.set_global(GlobalBlameRenderer(Arc::new(())));
309
310 workspace::register_project_item::<Editor>(cx);
311 workspace::FollowableViewRegistry::register::<Editor>(cx);
312 workspace::register_serializable_item::<Editor>(cx);
313
314 cx.observe_new(
315 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
316 workspace.register_action(Editor::new_file);
317 workspace.register_action(Editor::new_file_vertical);
318 workspace.register_action(Editor::new_file_horizontal);
319 workspace.register_action(Editor::cancel_language_server_work);
320 },
321 )
322 .detach();
323
324 cx.on_action(move |_: &workspace::NewFile, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(
328 Default::default(),
329 app_state,
330 cx,
331 |workspace, window, cx| {
332 Editor::new_file(workspace, &Default::default(), window, cx)
333 },
334 )
335 .detach();
336 }
337 });
338 cx.on_action(move |_: &workspace::NewWindow, cx| {
339 let app_state = workspace::AppState::global(cx);
340 if let Some(app_state) = app_state.upgrade() {
341 workspace::open_new(
342 Default::default(),
343 app_state,
344 cx,
345 |workspace, window, cx| {
346 cx.activate(true);
347 Editor::new_file(workspace, &Default::default(), window, cx)
348 },
349 )
350 .detach();
351 }
352 });
353}
354
355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
356 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
357}
358
359pub trait DiagnosticRenderer {
360 fn render_group(
361 &self,
362 diagnostic_group: Vec<DiagnosticEntry<Point>>,
363 buffer_id: BufferId,
364 snapshot: EditorSnapshot,
365 editor: WeakEntity<Editor>,
366 cx: &mut App,
367 ) -> Vec<BlockProperties<Anchor>>;
368}
369
370pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
371
372impl gpui::Global for GlobalDiagnosticRenderer {}
373pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
374 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
375}
376
377pub struct SearchWithinRange;
378
379trait InvalidationRegion {
380 fn ranges(&self) -> &[Range<Anchor>];
381}
382
383#[derive(Clone, Debug, PartialEq)]
384pub enum SelectPhase {
385 Begin {
386 position: DisplayPoint,
387 add: bool,
388 click_count: usize,
389 },
390 BeginColumnar {
391 position: DisplayPoint,
392 reset: bool,
393 goal_column: u32,
394 },
395 Extend {
396 position: DisplayPoint,
397 click_count: usize,
398 },
399 Update {
400 position: DisplayPoint,
401 goal_column: u32,
402 scroll_delta: gpui::Point<f32>,
403 },
404 End,
405}
406
407#[derive(Clone, Debug)]
408pub enum SelectMode {
409 Character,
410 Word(Range<Anchor>),
411 Line(Range<Anchor>),
412 All,
413}
414
415#[derive(Copy, Clone, PartialEq, Eq, Debug)]
416pub enum EditorMode {
417 SingleLine {
418 auto_width: bool,
419 },
420 AutoHeight {
421 max_lines: usize,
422 },
423 Full {
424 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
425 scale_ui_elements_with_buffer_font_size: bool,
426 /// When set to `true`, the editor will render a background for the active line.
427 show_active_line_background: bool,
428 },
429}
430
431impl EditorMode {
432 pub fn full() -> Self {
433 Self::Full {
434 scale_ui_elements_with_buffer_font_size: true,
435 show_active_line_background: true,
436 }
437 }
438
439 pub fn is_full(&self) -> bool {
440 matches!(self, Self::Full { .. })
441 }
442}
443
444#[derive(Copy, Clone, Debug)]
445pub enum SoftWrap {
446 /// Prefer not to wrap at all.
447 ///
448 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
449 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
450 GitDiff,
451 /// Prefer a single line generally, unless an overly long line is encountered.
452 None,
453 /// Soft wrap lines that exceed the editor width.
454 EditorWidth,
455 /// Soft wrap lines at the preferred line length.
456 Column(u32),
457 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
458 Bounded(u32),
459}
460
461#[derive(Clone)]
462pub struct EditorStyle {
463 pub background: Hsla,
464 pub local_player: PlayerColor,
465 pub text: TextStyle,
466 pub scrollbar_width: Pixels,
467 pub syntax: Arc<SyntaxTheme>,
468 pub status: StatusColors,
469 pub inlay_hints_style: HighlightStyle,
470 pub inline_completion_styles: InlineCompletionStyles,
471 pub unnecessary_code_fade: f32,
472}
473
474impl Default for EditorStyle {
475 fn default() -> Self {
476 Self {
477 background: Hsla::default(),
478 local_player: PlayerColor::default(),
479 text: TextStyle::default(),
480 scrollbar_width: Pixels::default(),
481 syntax: Default::default(),
482 // HACK: Status colors don't have a real default.
483 // We should look into removing the status colors from the editor
484 // style and retrieve them directly from the theme.
485 status: StatusColors::dark(),
486 inlay_hints_style: HighlightStyle::default(),
487 inline_completion_styles: InlineCompletionStyles {
488 insertion: HighlightStyle::default(),
489 whitespace: HighlightStyle::default(),
490 },
491 unnecessary_code_fade: Default::default(),
492 }
493 }
494}
495
496pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
497 let show_background = language_settings::language_settings(None, None, cx)
498 .inlay_hints
499 .show_background;
500
501 HighlightStyle {
502 color: Some(cx.theme().status().hint),
503 background_color: show_background.then(|| cx.theme().status().hint_background),
504 ..HighlightStyle::default()
505 }
506}
507
508pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
509 InlineCompletionStyles {
510 insertion: HighlightStyle {
511 color: Some(cx.theme().status().predictive),
512 ..HighlightStyle::default()
513 },
514 whitespace: HighlightStyle {
515 background_color: Some(cx.theme().status().created_background),
516 ..HighlightStyle::default()
517 },
518 }
519}
520
521type CompletionId = usize;
522
523pub(crate) enum EditDisplayMode {
524 TabAccept,
525 DiffPopover,
526 Inline,
527}
528
529enum InlineCompletion {
530 Edit {
531 edits: Vec<(Range<Anchor>, String)>,
532 edit_preview: Option<EditPreview>,
533 display_mode: EditDisplayMode,
534 snapshot: BufferSnapshot,
535 },
536 Move {
537 target: Anchor,
538 snapshot: BufferSnapshot,
539 },
540}
541
542struct InlineCompletionState {
543 inlay_ids: Vec<InlayId>,
544 completion: InlineCompletion,
545 completion_id: Option<SharedString>,
546 invalidation_range: Range<Anchor>,
547}
548
549enum EditPredictionSettings {
550 Disabled,
551 Enabled {
552 show_in_menu: bool,
553 preview_requires_modifier: bool,
554 },
555}
556
557enum InlineCompletionHighlight {}
558
559#[derive(Debug, Clone)]
560struct InlineDiagnostic {
561 message: SharedString,
562 group_id: usize,
563 is_primary: bool,
564 start: Point,
565 severity: DiagnosticSeverity,
566}
567
568pub enum MenuInlineCompletionsPolicy {
569 Never,
570 ByProvider,
571}
572
573pub enum EditPredictionPreview {
574 /// Modifier is not pressed
575 Inactive { released_too_fast: bool },
576 /// Modifier pressed
577 Active {
578 since: Instant,
579 previous_scroll_position: Option<ScrollAnchor>,
580 },
581}
582
583impl EditPredictionPreview {
584 pub fn released_too_fast(&self) -> bool {
585 match self {
586 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
587 EditPredictionPreview::Active { .. } => false,
588 }
589 }
590
591 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
592 if let EditPredictionPreview::Active {
593 previous_scroll_position,
594 ..
595 } = self
596 {
597 *previous_scroll_position = scroll_position;
598 }
599 }
600}
601
602pub struct ContextMenuOptions {
603 pub min_entries_visible: usize,
604 pub max_entries_visible: usize,
605 pub placement: Option<ContextMenuPlacement>,
606}
607
608#[derive(Debug, Clone, PartialEq, Eq)]
609pub enum ContextMenuPlacement {
610 Above,
611 Below,
612}
613
614#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
615struct EditorActionId(usize);
616
617impl EditorActionId {
618 pub fn post_inc(&mut self) -> Self {
619 let answer = self.0;
620
621 *self = Self(answer + 1);
622
623 Self(answer)
624 }
625}
626
627// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
628// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
629
630type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
631type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
632
633#[derive(Default)]
634struct ScrollbarMarkerState {
635 scrollbar_size: Size<Pixels>,
636 dirty: bool,
637 markers: Arc<[PaintQuad]>,
638 pending_refresh: Option<Task<Result<()>>>,
639}
640
641impl ScrollbarMarkerState {
642 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
643 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
644 }
645}
646
647#[derive(Clone, Debug)]
648struct RunnableTasks {
649 templates: Vec<(TaskSourceKind, TaskTemplate)>,
650 offset: multi_buffer::Anchor,
651 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
652 column: u32,
653 // Values of all named captures, including those starting with '_'
654 extra_variables: HashMap<String, String>,
655 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
656 context_range: Range<BufferOffset>,
657}
658
659impl RunnableTasks {
660 fn resolve<'a>(
661 &'a self,
662 cx: &'a task::TaskContext,
663 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
664 self.templates.iter().filter_map(|(kind, template)| {
665 template
666 .resolve_task(&kind.to_id_base(), cx)
667 .map(|task| (kind.clone(), task))
668 })
669 }
670}
671
672#[derive(Clone)]
673struct ResolvedTasks {
674 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
675 position: Anchor,
676}
677
678#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
679struct BufferOffset(usize);
680
681// Addons allow storing per-editor state in other crates (e.g. Vim)
682pub trait Addon: 'static {
683 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
684
685 fn render_buffer_header_controls(
686 &self,
687 _: &ExcerptInfo,
688 _: &Window,
689 _: &App,
690 ) -> Option<AnyElement> {
691 None
692 }
693
694 fn to_any(&self) -> &dyn std::any::Any;
695}
696
697/// A set of caret positions, registered when the editor was edited.
698pub struct ChangeList {
699 changes: Vec<Vec<Anchor>>,
700 /// Currently "selected" change.
701 position: Option<usize>,
702}
703
704impl ChangeList {
705 pub fn new() -> Self {
706 Self {
707 changes: Vec::new(),
708 position: None,
709 }
710 }
711
712 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
713 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
714 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
715 if self.changes.is_empty() {
716 return None;
717 }
718
719 let prev = self.position.unwrap_or(self.changes.len());
720 let next = if direction == Direction::Prev {
721 prev.saturating_sub(count)
722 } else {
723 (prev + count).min(self.changes.len() - 1)
724 };
725 self.position = Some(next);
726 self.changes.get(next).map(|anchors| anchors.as_slice())
727 }
728
729 /// Adds a new change to the list, resetting the change list position.
730 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
731 self.position.take();
732 if pop_state {
733 self.changes.pop();
734 }
735 self.changes.push(new_positions.clone());
736 }
737
738 pub fn last(&self) -> Option<&[Anchor]> {
739 self.changes.last().map(|anchors| anchors.as_slice())
740 }
741}
742
743/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
744///
745/// See the [module level documentation](self) for more information.
746pub struct Editor {
747 focus_handle: FocusHandle,
748 last_focused_descendant: Option<WeakFocusHandle>,
749 /// The text buffer being edited
750 buffer: Entity<MultiBuffer>,
751 /// Map of how text in the buffer should be displayed.
752 /// Handles soft wraps, folds, fake inlay text insertions, etc.
753 pub display_map: Entity<DisplayMap>,
754 pub selections: SelectionsCollection,
755 pub scroll_manager: ScrollManager,
756 /// When inline assist editors are linked, they all render cursors because
757 /// typing enters text into each of them, even the ones that aren't focused.
758 pub(crate) show_cursor_when_unfocused: bool,
759 columnar_selection_tail: Option<Anchor>,
760 add_selections_state: Option<AddSelectionsState>,
761 select_next_state: Option<SelectNextState>,
762 select_prev_state: Option<SelectNextState>,
763 selection_history: SelectionHistory,
764 autoclose_regions: Vec<AutocloseRegion>,
765 snippet_stack: InvalidationStack<SnippetState>,
766 select_syntax_node_history: SelectSyntaxNodeHistory,
767 ime_transaction: Option<TransactionId>,
768 active_diagnostics: ActiveDiagnostic,
769 show_inline_diagnostics: bool,
770 inline_diagnostics_update: Task<()>,
771 inline_diagnostics_enabled: bool,
772 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
773 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
774 hard_wrap: Option<usize>,
775
776 // TODO: make this a access method
777 pub project: Option<Entity<Project>>,
778 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
779 completion_provider: Option<Box<dyn CompletionProvider>>,
780 collaboration_hub: Option<Box<dyn CollaborationHub>>,
781 blink_manager: Entity<BlinkManager>,
782 show_cursor_names: bool,
783 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
784 pub show_local_selections: bool,
785 mode: EditorMode,
786 show_breadcrumbs: bool,
787 show_gutter: bool,
788 show_scrollbars: bool,
789 show_line_numbers: Option<bool>,
790 use_relative_line_numbers: Option<bool>,
791 show_git_diff_gutter: Option<bool>,
792 show_code_actions: Option<bool>,
793 show_runnables: Option<bool>,
794 show_breakpoints: Option<bool>,
795 show_wrap_guides: Option<bool>,
796 show_indent_guides: Option<bool>,
797 placeholder_text: Option<Arc<str>>,
798 highlight_order: usize,
799 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
800 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
801 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
802 scrollbar_marker_state: ScrollbarMarkerState,
803 active_indent_guides_state: ActiveIndentGuidesState,
804 nav_history: Option<ItemNavHistory>,
805 context_menu: RefCell<Option<CodeContextMenu>>,
806 context_menu_options: Option<ContextMenuOptions>,
807 mouse_context_menu: Option<MouseContextMenu>,
808 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
809 signature_help_state: SignatureHelpState,
810 auto_signature_help: Option<bool>,
811 find_all_references_task_sources: Vec<Anchor>,
812 next_completion_id: CompletionId,
813 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
814 code_actions_task: Option<Task<Result<()>>>,
815 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
816 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
817 document_highlights_task: Option<Task<()>>,
818 linked_editing_range_task: Option<Task<Option<()>>>,
819 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
820 pending_rename: Option<RenameState>,
821 searchable: bool,
822 cursor_shape: CursorShape,
823 current_line_highlight: Option<CurrentLineHighlight>,
824 collapse_matches: bool,
825 autoindent_mode: Option<AutoindentMode>,
826 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
827 input_enabled: bool,
828 use_modal_editing: bool,
829 read_only: bool,
830 leader_peer_id: Option<PeerId>,
831 remote_id: Option<ViewId>,
832 hover_state: HoverState,
833 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
834 gutter_hovered: bool,
835 hovered_link_state: Option<HoveredLinkState>,
836 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
837 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
838 active_inline_completion: Option<InlineCompletionState>,
839 /// Used to prevent flickering as the user types while the menu is open
840 stale_inline_completion_in_menu: Option<InlineCompletionState>,
841 edit_prediction_settings: EditPredictionSettings,
842 inline_completions_hidden_for_vim_mode: bool,
843 show_inline_completions_override: Option<bool>,
844 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
845 edit_prediction_preview: EditPredictionPreview,
846 edit_prediction_indent_conflict: bool,
847 edit_prediction_requires_modifier_in_indent_conflict: bool,
848 inlay_hint_cache: InlayHintCache,
849 next_inlay_id: usize,
850 _subscriptions: Vec<Subscription>,
851 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
852 gutter_dimensions: GutterDimensions,
853 style: Option<EditorStyle>,
854 text_style_refinement: Option<TextStyleRefinement>,
855 next_editor_action_id: EditorActionId,
856 editor_actions:
857 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
858 use_autoclose: bool,
859 use_auto_surround: bool,
860 auto_replace_emoji_shortcode: bool,
861 jsx_tag_auto_close_enabled_in_any_buffer: bool,
862 show_git_blame_gutter: bool,
863 show_git_blame_inline: bool,
864 show_git_blame_inline_delay_task: Option<Task<()>>,
865 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
866 git_blame_inline_enabled: bool,
867 render_diff_hunk_controls: RenderDiffHunkControlsFn,
868 serialize_dirty_buffers: bool,
869 show_selection_menu: Option<bool>,
870 blame: Option<Entity<GitBlame>>,
871 blame_subscription: Option<Subscription>,
872 custom_context_menu: Option<
873 Box<
874 dyn 'static
875 + Fn(
876 &mut Self,
877 DisplayPoint,
878 &mut Window,
879 &mut Context<Self>,
880 ) -> Option<Entity<ui::ContextMenu>>,
881 >,
882 >,
883 last_bounds: Option<Bounds<Pixels>>,
884 last_position_map: Option<Rc<PositionMap>>,
885 expect_bounds_change: Option<Bounds<Pixels>>,
886 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
887 tasks_update_task: Option<Task<()>>,
888 breakpoint_store: Option<Entity<BreakpointStore>>,
889 /// Allow's a user to create a breakpoint by selecting this indicator
890 /// It should be None while a user is not hovering over the gutter
891 /// Otherwise it represents the point that the breakpoint will be shown
892 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
893 in_project_search: bool,
894 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
895 breadcrumb_header: Option<String>,
896 focused_block: Option<FocusedBlock>,
897 next_scroll_position: NextScrollCursorCenterTopBottom,
898 addons: HashMap<TypeId, Box<dyn Addon>>,
899 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
900 load_diff_task: Option<Shared<Task<()>>>,
901 selection_mark_mode: bool,
902 toggle_fold_multiple_buffers: Task<()>,
903 _scroll_cursor_center_top_bottom_task: Task<()>,
904 serialize_selections: Task<()>,
905 serialize_folds: Task<()>,
906 mouse_cursor_hidden: bool,
907 hide_mouse_mode: HideMouseMode,
908 pub change_list: ChangeList,
909}
910
911#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
912enum NextScrollCursorCenterTopBottom {
913 #[default]
914 Center,
915 Top,
916 Bottom,
917}
918
919impl NextScrollCursorCenterTopBottom {
920 fn next(&self) -> Self {
921 match self {
922 Self::Center => Self::Top,
923 Self::Top => Self::Bottom,
924 Self::Bottom => Self::Center,
925 }
926 }
927}
928
929#[derive(Clone)]
930pub struct EditorSnapshot {
931 pub mode: EditorMode,
932 show_gutter: bool,
933 show_line_numbers: Option<bool>,
934 show_git_diff_gutter: Option<bool>,
935 show_code_actions: Option<bool>,
936 show_runnables: Option<bool>,
937 show_breakpoints: Option<bool>,
938 git_blame_gutter_max_author_length: Option<usize>,
939 pub display_snapshot: DisplaySnapshot,
940 pub placeholder_text: Option<Arc<str>>,
941 is_focused: bool,
942 scroll_anchor: ScrollAnchor,
943 ongoing_scroll: OngoingScroll,
944 current_line_highlight: CurrentLineHighlight,
945 gutter_hovered: bool,
946}
947
948#[derive(Default, Debug, Clone, Copy)]
949pub struct GutterDimensions {
950 pub left_padding: Pixels,
951 pub right_padding: Pixels,
952 pub width: Pixels,
953 pub margin: Pixels,
954 pub git_blame_entries_width: Option<Pixels>,
955}
956
957impl GutterDimensions {
958 /// The full width of the space taken up by the gutter.
959 pub fn full_width(&self) -> Pixels {
960 self.margin + self.width
961 }
962
963 /// The width of the space reserved for the fold indicators,
964 /// use alongside 'justify_end' and `gutter_width` to
965 /// right align content with the line numbers
966 pub fn fold_area_width(&self) -> Pixels {
967 self.margin + self.right_padding
968 }
969}
970
971#[derive(Debug)]
972pub struct RemoteSelection {
973 pub replica_id: ReplicaId,
974 pub selection: Selection<Anchor>,
975 pub cursor_shape: CursorShape,
976 pub peer_id: PeerId,
977 pub line_mode: bool,
978 pub participant_index: Option<ParticipantIndex>,
979 pub user_name: Option<SharedString>,
980}
981
982#[derive(Clone, Debug)]
983struct SelectionHistoryEntry {
984 selections: Arc<[Selection<Anchor>]>,
985 select_next_state: Option<SelectNextState>,
986 select_prev_state: Option<SelectNextState>,
987 add_selections_state: Option<AddSelectionsState>,
988}
989
990enum SelectionHistoryMode {
991 Normal,
992 Undoing,
993 Redoing,
994}
995
996#[derive(Clone, PartialEq, Eq, Hash)]
997struct HoveredCursor {
998 replica_id: u16,
999 selection_id: usize,
1000}
1001
1002impl Default for SelectionHistoryMode {
1003 fn default() -> Self {
1004 Self::Normal
1005 }
1006}
1007
1008#[derive(Default)]
1009struct SelectionHistory {
1010 #[allow(clippy::type_complexity)]
1011 selections_by_transaction:
1012 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1013 mode: SelectionHistoryMode,
1014 undo_stack: VecDeque<SelectionHistoryEntry>,
1015 redo_stack: VecDeque<SelectionHistoryEntry>,
1016}
1017
1018impl SelectionHistory {
1019 fn insert_transaction(
1020 &mut self,
1021 transaction_id: TransactionId,
1022 selections: Arc<[Selection<Anchor>]>,
1023 ) {
1024 self.selections_by_transaction
1025 .insert(transaction_id, (selections, None));
1026 }
1027
1028 #[allow(clippy::type_complexity)]
1029 fn transaction(
1030 &self,
1031 transaction_id: TransactionId,
1032 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1033 self.selections_by_transaction.get(&transaction_id)
1034 }
1035
1036 #[allow(clippy::type_complexity)]
1037 fn transaction_mut(
1038 &mut self,
1039 transaction_id: TransactionId,
1040 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1041 self.selections_by_transaction.get_mut(&transaction_id)
1042 }
1043
1044 fn push(&mut self, entry: SelectionHistoryEntry) {
1045 if !entry.selections.is_empty() {
1046 match self.mode {
1047 SelectionHistoryMode::Normal => {
1048 self.push_undo(entry);
1049 self.redo_stack.clear();
1050 }
1051 SelectionHistoryMode::Undoing => self.push_redo(entry),
1052 SelectionHistoryMode::Redoing => self.push_undo(entry),
1053 }
1054 }
1055 }
1056
1057 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1058 if self
1059 .undo_stack
1060 .back()
1061 .map_or(true, |e| e.selections != entry.selections)
1062 {
1063 self.undo_stack.push_back(entry);
1064 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1065 self.undo_stack.pop_front();
1066 }
1067 }
1068 }
1069
1070 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1071 if self
1072 .redo_stack
1073 .back()
1074 .map_or(true, |e| e.selections != entry.selections)
1075 {
1076 self.redo_stack.push_back(entry);
1077 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1078 self.redo_stack.pop_front();
1079 }
1080 }
1081 }
1082}
1083
1084struct RowHighlight {
1085 index: usize,
1086 range: Range<Anchor>,
1087 color: Hsla,
1088 should_autoscroll: bool,
1089}
1090
1091#[derive(Clone, Debug)]
1092struct AddSelectionsState {
1093 above: bool,
1094 stack: Vec<usize>,
1095}
1096
1097#[derive(Clone)]
1098struct SelectNextState {
1099 query: AhoCorasick,
1100 wordwise: bool,
1101 done: bool,
1102}
1103
1104impl std::fmt::Debug for SelectNextState {
1105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1106 f.debug_struct(std::any::type_name::<Self>())
1107 .field("wordwise", &self.wordwise)
1108 .field("done", &self.done)
1109 .finish()
1110 }
1111}
1112
1113#[derive(Debug)]
1114struct AutocloseRegion {
1115 selection_id: usize,
1116 range: Range<Anchor>,
1117 pair: BracketPair,
1118}
1119
1120#[derive(Debug)]
1121struct SnippetState {
1122 ranges: Vec<Vec<Range<Anchor>>>,
1123 active_index: usize,
1124 choices: Vec<Option<Vec<String>>>,
1125}
1126
1127#[doc(hidden)]
1128pub struct RenameState {
1129 pub range: Range<Anchor>,
1130 pub old_name: Arc<str>,
1131 pub editor: Entity<Editor>,
1132 block_id: CustomBlockId,
1133}
1134
1135struct InvalidationStack<T>(Vec<T>);
1136
1137struct RegisteredInlineCompletionProvider {
1138 provider: Arc<dyn InlineCompletionProviderHandle>,
1139 _subscription: Subscription,
1140}
1141
1142#[derive(Debug, PartialEq, Eq)]
1143pub struct ActiveDiagnosticGroup {
1144 pub active_range: Range<Anchor>,
1145 pub active_message: String,
1146 pub group_id: usize,
1147 pub blocks: HashSet<CustomBlockId>,
1148}
1149
1150#[derive(Debug, PartialEq, Eq)]
1151#[allow(clippy::large_enum_variant)]
1152pub(crate) enum ActiveDiagnostic {
1153 None,
1154 All,
1155 Group(ActiveDiagnosticGroup),
1156}
1157
1158#[derive(Serialize, Deserialize, Clone, Debug)]
1159pub struct ClipboardSelection {
1160 /// The number of bytes in this selection.
1161 pub len: usize,
1162 /// Whether this was a full-line selection.
1163 pub is_entire_line: bool,
1164 /// The indentation of the first line when this content was originally copied.
1165 pub first_line_indent: u32,
1166}
1167
1168// selections, scroll behavior, was newest selection reversed
1169type SelectSyntaxNodeHistoryState = (
1170 Box<[Selection<usize>]>,
1171 SelectSyntaxNodeScrollBehavior,
1172 bool,
1173);
1174
1175#[derive(Default)]
1176struct SelectSyntaxNodeHistory {
1177 stack: Vec<SelectSyntaxNodeHistoryState>,
1178 // disable temporarily to allow changing selections without losing the stack
1179 pub disable_clearing: bool,
1180}
1181
1182impl SelectSyntaxNodeHistory {
1183 pub fn try_clear(&mut self) {
1184 if !self.disable_clearing {
1185 self.stack.clear();
1186 }
1187 }
1188
1189 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1190 self.stack.push(selection);
1191 }
1192
1193 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1194 self.stack.pop()
1195 }
1196}
1197
1198enum SelectSyntaxNodeScrollBehavior {
1199 CursorTop,
1200 FitSelection,
1201 CursorBottom,
1202}
1203
1204#[derive(Debug)]
1205pub(crate) struct NavigationData {
1206 cursor_anchor: Anchor,
1207 cursor_position: Point,
1208 scroll_anchor: ScrollAnchor,
1209 scroll_top_row: u32,
1210}
1211
1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213pub enum GotoDefinitionKind {
1214 Symbol,
1215 Declaration,
1216 Type,
1217 Implementation,
1218}
1219
1220#[derive(Debug, Clone)]
1221enum InlayHintRefreshReason {
1222 ModifiersChanged(bool),
1223 Toggle(bool),
1224 SettingsChange(InlayHintSettings),
1225 NewLinesShown,
1226 BufferEdited(HashSet<Arc<Language>>),
1227 RefreshRequested,
1228 ExcerptsRemoved(Vec<ExcerptId>),
1229}
1230
1231impl InlayHintRefreshReason {
1232 fn description(&self) -> &'static str {
1233 match self {
1234 Self::ModifiersChanged(_) => "modifiers changed",
1235 Self::Toggle(_) => "toggle",
1236 Self::SettingsChange(_) => "settings change",
1237 Self::NewLinesShown => "new lines shown",
1238 Self::BufferEdited(_) => "buffer edited",
1239 Self::RefreshRequested => "refresh requested",
1240 Self::ExcerptsRemoved(_) => "excerpts removed",
1241 }
1242 }
1243}
1244
1245pub enum FormatTarget {
1246 Buffers,
1247 Ranges(Vec<Range<MultiBufferPoint>>),
1248}
1249
1250pub(crate) struct FocusedBlock {
1251 id: BlockId,
1252 focus_handle: WeakFocusHandle,
1253}
1254
1255#[derive(Clone)]
1256enum JumpData {
1257 MultiBufferRow {
1258 row: MultiBufferRow,
1259 line_offset_from_top: u32,
1260 },
1261 MultiBufferPoint {
1262 excerpt_id: ExcerptId,
1263 position: Point,
1264 anchor: text::Anchor,
1265 line_offset_from_top: u32,
1266 },
1267}
1268
1269pub enum MultibufferSelectionMode {
1270 First,
1271 All,
1272}
1273
1274#[derive(Clone, Copy, Debug, Default)]
1275pub struct RewrapOptions {
1276 pub override_language_settings: bool,
1277 pub preserve_existing_whitespace: bool,
1278}
1279
1280impl Editor {
1281 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1282 let buffer = cx.new(|cx| Buffer::local("", cx));
1283 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1284 Self::new(
1285 EditorMode::SingleLine { auto_width: false },
1286 buffer,
1287 None,
1288 window,
1289 cx,
1290 )
1291 }
1292
1293 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1294 let buffer = cx.new(|cx| Buffer::local("", cx));
1295 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1296 Self::new(EditorMode::full(), buffer, None, window, cx)
1297 }
1298
1299 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1300 let buffer = cx.new(|cx| Buffer::local("", cx));
1301 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1302 Self::new(
1303 EditorMode::SingleLine { auto_width: true },
1304 buffer,
1305 None,
1306 window,
1307 cx,
1308 )
1309 }
1310
1311 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1312 let buffer = cx.new(|cx| Buffer::local("", cx));
1313 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1314 Self::new(
1315 EditorMode::AutoHeight { max_lines },
1316 buffer,
1317 None,
1318 window,
1319 cx,
1320 )
1321 }
1322
1323 pub fn for_buffer(
1324 buffer: Entity<Buffer>,
1325 project: Option<Entity<Project>>,
1326 window: &mut Window,
1327 cx: &mut Context<Self>,
1328 ) -> Self {
1329 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1330 Self::new(EditorMode::full(), buffer, project, window, cx)
1331 }
1332
1333 pub fn for_multibuffer(
1334 buffer: Entity<MultiBuffer>,
1335 project: Option<Entity<Project>>,
1336 window: &mut Window,
1337 cx: &mut Context<Self>,
1338 ) -> Self {
1339 Self::new(EditorMode::full(), buffer, project, window, cx)
1340 }
1341
1342 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1343 let mut clone = Self::new(
1344 self.mode,
1345 self.buffer.clone(),
1346 self.project.clone(),
1347 window,
1348 cx,
1349 );
1350 self.display_map.update(cx, |display_map, cx| {
1351 let snapshot = display_map.snapshot(cx);
1352 clone.display_map.update(cx, |display_map, cx| {
1353 display_map.set_state(&snapshot, cx);
1354 });
1355 });
1356 clone.folds_did_change(cx);
1357 clone.selections.clone_state(&self.selections);
1358 clone.scroll_manager.clone_state(&self.scroll_manager);
1359 clone.searchable = self.searchable;
1360 clone.read_only = self.read_only;
1361 clone
1362 }
1363
1364 pub fn new(
1365 mode: EditorMode,
1366 buffer: Entity<MultiBuffer>,
1367 project: Option<Entity<Project>>,
1368 window: &mut Window,
1369 cx: &mut Context<Self>,
1370 ) -> Self {
1371 let style = window.text_style();
1372 let font_size = style.font_size.to_pixels(window.rem_size());
1373 let editor = cx.entity().downgrade();
1374 let fold_placeholder = FoldPlaceholder {
1375 constrain_width: true,
1376 render: Arc::new(move |fold_id, fold_range, cx| {
1377 let editor = editor.clone();
1378 div()
1379 .id(fold_id)
1380 .bg(cx.theme().colors().ghost_element_background)
1381 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1382 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1383 .rounded_xs()
1384 .size_full()
1385 .cursor_pointer()
1386 .child("⋯")
1387 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1388 .on_click(move |_, _window, cx| {
1389 editor
1390 .update(cx, |editor, cx| {
1391 editor.unfold_ranges(
1392 &[fold_range.start..fold_range.end],
1393 true,
1394 false,
1395 cx,
1396 );
1397 cx.stop_propagation();
1398 })
1399 .ok();
1400 })
1401 .into_any()
1402 }),
1403 merge_adjacent: true,
1404 ..Default::default()
1405 };
1406 let display_map = cx.new(|cx| {
1407 DisplayMap::new(
1408 buffer.clone(),
1409 style.font(),
1410 font_size,
1411 None,
1412 FILE_HEADER_HEIGHT,
1413 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1414 fold_placeholder,
1415 cx,
1416 )
1417 });
1418
1419 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1420
1421 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1422
1423 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1424 .then(|| language_settings::SoftWrap::None);
1425
1426 let mut project_subscriptions = Vec::new();
1427 if mode.is_full() {
1428 if let Some(project) = project.as_ref() {
1429 project_subscriptions.push(cx.subscribe_in(
1430 project,
1431 window,
1432 |editor, _, event, window, cx| match event {
1433 project::Event::RefreshCodeLens => {
1434 // we always query lens with actions, without storing them, always refreshing them
1435 }
1436 project::Event::RefreshInlayHints => {
1437 editor
1438 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1439 }
1440 project::Event::SnippetEdit(id, snippet_edits) => {
1441 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1442 let focus_handle = editor.focus_handle(cx);
1443 if focus_handle.is_focused(window) {
1444 let snapshot = buffer.read(cx).snapshot();
1445 for (range, snippet) in snippet_edits {
1446 let editor_range =
1447 language::range_from_lsp(*range).to_offset(&snapshot);
1448 editor
1449 .insert_snippet(
1450 &[editor_range],
1451 snippet.clone(),
1452 window,
1453 cx,
1454 )
1455 .ok();
1456 }
1457 }
1458 }
1459 }
1460 _ => {}
1461 },
1462 ));
1463 if let Some(task_inventory) = project
1464 .read(cx)
1465 .task_store()
1466 .read(cx)
1467 .task_inventory()
1468 .cloned()
1469 {
1470 project_subscriptions.push(cx.observe_in(
1471 &task_inventory,
1472 window,
1473 |editor, _, window, cx| {
1474 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1475 },
1476 ));
1477 };
1478
1479 project_subscriptions.push(cx.subscribe_in(
1480 &project.read(cx).breakpoint_store(),
1481 window,
1482 |editor, _, event, window, cx| match event {
1483 BreakpointStoreEvent::ActiveDebugLineChanged => {
1484 if editor.go_to_active_debug_line(window, cx) {
1485 cx.stop_propagation();
1486 }
1487 }
1488 _ => {}
1489 },
1490 ));
1491 }
1492 }
1493
1494 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1495
1496 let inlay_hint_settings =
1497 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1498 let focus_handle = cx.focus_handle();
1499 cx.on_focus(&focus_handle, window, Self::handle_focus)
1500 .detach();
1501 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1502 .detach();
1503 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1504 .detach();
1505 cx.on_blur(&focus_handle, window, Self::handle_blur)
1506 .detach();
1507
1508 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1509 Some(false)
1510 } else {
1511 None
1512 };
1513
1514 let breakpoint_store = match (mode, project.as_ref()) {
1515 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1516 _ => None,
1517 };
1518
1519 let mut code_action_providers = Vec::new();
1520 let mut load_uncommitted_diff = None;
1521 if let Some(project) = project.clone() {
1522 load_uncommitted_diff = Some(
1523 get_uncommitted_diff_for_buffer(
1524 &project,
1525 buffer.read(cx).all_buffers(),
1526 buffer.clone(),
1527 cx,
1528 )
1529 .shared(),
1530 );
1531 code_action_providers.push(Rc::new(project) as Rc<_>);
1532 }
1533
1534 let mut this = Self {
1535 focus_handle,
1536 show_cursor_when_unfocused: false,
1537 last_focused_descendant: None,
1538 buffer: buffer.clone(),
1539 display_map: display_map.clone(),
1540 selections,
1541 scroll_manager: ScrollManager::new(cx),
1542 columnar_selection_tail: None,
1543 add_selections_state: None,
1544 select_next_state: None,
1545 select_prev_state: None,
1546 selection_history: Default::default(),
1547 autoclose_regions: Default::default(),
1548 snippet_stack: Default::default(),
1549 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1550 ime_transaction: Default::default(),
1551 active_diagnostics: ActiveDiagnostic::None,
1552 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1553 inline_diagnostics_update: Task::ready(()),
1554 inline_diagnostics: Vec::new(),
1555 soft_wrap_mode_override,
1556 hard_wrap: None,
1557 completion_provider: project.clone().map(|project| Box::new(project) as _),
1558 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1559 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1560 project,
1561 blink_manager: blink_manager.clone(),
1562 show_local_selections: true,
1563 show_scrollbars: true,
1564 mode,
1565 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1566 show_gutter: mode.is_full(),
1567 show_line_numbers: None,
1568 use_relative_line_numbers: None,
1569 show_git_diff_gutter: None,
1570 show_code_actions: None,
1571 show_runnables: None,
1572 show_breakpoints: None,
1573 show_wrap_guides: None,
1574 show_indent_guides,
1575 placeholder_text: None,
1576 highlight_order: 0,
1577 highlighted_rows: HashMap::default(),
1578 background_highlights: Default::default(),
1579 gutter_highlights: TreeMap::default(),
1580 scrollbar_marker_state: ScrollbarMarkerState::default(),
1581 active_indent_guides_state: ActiveIndentGuidesState::default(),
1582 nav_history: None,
1583 context_menu: RefCell::new(None),
1584 context_menu_options: None,
1585 mouse_context_menu: None,
1586 completion_tasks: Default::default(),
1587 signature_help_state: SignatureHelpState::default(),
1588 auto_signature_help: None,
1589 find_all_references_task_sources: Vec::new(),
1590 next_completion_id: 0,
1591 next_inlay_id: 0,
1592 code_action_providers,
1593 available_code_actions: Default::default(),
1594 code_actions_task: Default::default(),
1595 quick_selection_highlight_task: Default::default(),
1596 debounced_selection_highlight_task: Default::default(),
1597 document_highlights_task: Default::default(),
1598 linked_editing_range_task: Default::default(),
1599 pending_rename: Default::default(),
1600 searchable: true,
1601 cursor_shape: EditorSettings::get_global(cx)
1602 .cursor_shape
1603 .unwrap_or_default(),
1604 current_line_highlight: None,
1605 autoindent_mode: Some(AutoindentMode::EachLine),
1606 collapse_matches: false,
1607 workspace: None,
1608 input_enabled: true,
1609 use_modal_editing: mode.is_full(),
1610 read_only: false,
1611 use_autoclose: true,
1612 use_auto_surround: true,
1613 auto_replace_emoji_shortcode: false,
1614 jsx_tag_auto_close_enabled_in_any_buffer: false,
1615 leader_peer_id: None,
1616 remote_id: None,
1617 hover_state: Default::default(),
1618 pending_mouse_down: None,
1619 hovered_link_state: Default::default(),
1620 edit_prediction_provider: None,
1621 active_inline_completion: None,
1622 stale_inline_completion_in_menu: None,
1623 edit_prediction_preview: EditPredictionPreview::Inactive {
1624 released_too_fast: false,
1625 },
1626 inline_diagnostics_enabled: mode.is_full(),
1627 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1628
1629 gutter_hovered: false,
1630 pixel_position_of_newest_cursor: None,
1631 last_bounds: None,
1632 last_position_map: None,
1633 expect_bounds_change: None,
1634 gutter_dimensions: GutterDimensions::default(),
1635 style: None,
1636 show_cursor_names: false,
1637 hovered_cursors: Default::default(),
1638 next_editor_action_id: EditorActionId::default(),
1639 editor_actions: Rc::default(),
1640 inline_completions_hidden_for_vim_mode: false,
1641 show_inline_completions_override: None,
1642 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1643 edit_prediction_settings: EditPredictionSettings::Disabled,
1644 edit_prediction_indent_conflict: false,
1645 edit_prediction_requires_modifier_in_indent_conflict: true,
1646 custom_context_menu: None,
1647 show_git_blame_gutter: false,
1648 show_git_blame_inline: false,
1649 show_selection_menu: None,
1650 show_git_blame_inline_delay_task: None,
1651 git_blame_inline_tooltip: None,
1652 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1653 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1654 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1655 .session
1656 .restore_unsaved_buffers,
1657 blame: None,
1658 blame_subscription: None,
1659 tasks: Default::default(),
1660
1661 breakpoint_store,
1662 gutter_breakpoint_indicator: (None, None),
1663 _subscriptions: vec![
1664 cx.observe(&buffer, Self::on_buffer_changed),
1665 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1666 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1667 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1668 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1669 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1670 cx.observe_window_activation(window, |editor, window, cx| {
1671 let active = window.is_window_active();
1672 editor.blink_manager.update(cx, |blink_manager, cx| {
1673 if active {
1674 blink_manager.enable(cx);
1675 } else {
1676 blink_manager.disable(cx);
1677 }
1678 });
1679 }),
1680 ],
1681 tasks_update_task: None,
1682 linked_edit_ranges: Default::default(),
1683 in_project_search: false,
1684 previous_search_ranges: None,
1685 breadcrumb_header: None,
1686 focused_block: None,
1687 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1688 addons: HashMap::default(),
1689 registered_buffers: HashMap::default(),
1690 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1691 selection_mark_mode: false,
1692 toggle_fold_multiple_buffers: Task::ready(()),
1693 serialize_selections: Task::ready(()),
1694 serialize_folds: Task::ready(()),
1695 text_style_refinement: None,
1696 load_diff_task: load_uncommitted_diff,
1697 mouse_cursor_hidden: false,
1698 hide_mouse_mode: EditorSettings::get_global(cx)
1699 .hide_mouse
1700 .unwrap_or_default(),
1701 change_list: ChangeList::new(),
1702 };
1703 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1704 this._subscriptions
1705 .push(cx.observe(breakpoints, |_, _, cx| {
1706 cx.notify();
1707 }));
1708 }
1709 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1710 this._subscriptions.extend(project_subscriptions);
1711
1712 this._subscriptions.push(cx.subscribe_in(
1713 &cx.entity(),
1714 window,
1715 |editor, _, e: &EditorEvent, window, cx| match e {
1716 EditorEvent::ScrollPositionChanged { local, .. } => {
1717 if *local {
1718 let new_anchor = editor.scroll_manager.anchor();
1719 let snapshot = editor.snapshot(window, cx);
1720 editor.update_restoration_data(cx, move |data| {
1721 data.scroll_position = (
1722 new_anchor.top_row(&snapshot.buffer_snapshot),
1723 new_anchor.offset,
1724 );
1725 });
1726 }
1727 }
1728 EditorEvent::Edited { .. } => {
1729 if !vim_enabled(cx) {
1730 let (map, selections) = editor.selections.all_adjusted_display(cx);
1731 let pop_state = editor
1732 .change_list
1733 .last()
1734 .map(|previous| {
1735 previous.len() == selections.len()
1736 && previous.iter().enumerate().all(|(ix, p)| {
1737 p.to_display_point(&map).row()
1738 == selections[ix].head().row()
1739 })
1740 })
1741 .unwrap_or(false);
1742 let new_positions = selections
1743 .into_iter()
1744 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1745 .collect();
1746 editor
1747 .change_list
1748 .push_to_change_list(pop_state, new_positions);
1749 }
1750 }
1751 _ => (),
1752 },
1753 ));
1754
1755 this.end_selection(window, cx);
1756 this.scroll_manager.show_scrollbars(window, cx);
1757 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1758
1759 if mode.is_full() {
1760 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1761 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1762
1763 if this.git_blame_inline_enabled {
1764 this.git_blame_inline_enabled = true;
1765 this.start_git_blame_inline(false, window, cx);
1766 }
1767
1768 this.go_to_active_debug_line(window, cx);
1769
1770 if let Some(buffer) = buffer.read(cx).as_singleton() {
1771 if let Some(project) = this.project.as_ref() {
1772 let handle = project.update(cx, |project, cx| {
1773 project.register_buffer_with_language_servers(&buffer, cx)
1774 });
1775 this.registered_buffers
1776 .insert(buffer.read(cx).remote_id(), handle);
1777 }
1778 }
1779 }
1780
1781 this.report_editor_event("Editor Opened", None, cx);
1782 this
1783 }
1784
1785 pub fn deploy_mouse_context_menu(
1786 &mut self,
1787 position: gpui::Point<Pixels>,
1788 context_menu: Entity<ContextMenu>,
1789 window: &mut Window,
1790 cx: &mut Context<Self>,
1791 ) {
1792 self.mouse_context_menu = Some(MouseContextMenu::new(
1793 self,
1794 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1795 context_menu,
1796 window,
1797 cx,
1798 ));
1799 }
1800
1801 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1802 self.mouse_context_menu
1803 .as_ref()
1804 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1805 }
1806
1807 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1808 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1809 }
1810
1811 fn key_context_internal(
1812 &self,
1813 has_active_edit_prediction: bool,
1814 window: &Window,
1815 cx: &App,
1816 ) -> KeyContext {
1817 let mut key_context = KeyContext::new_with_defaults();
1818 key_context.add("Editor");
1819 let mode = match self.mode {
1820 EditorMode::SingleLine { .. } => "single_line",
1821 EditorMode::AutoHeight { .. } => "auto_height",
1822 EditorMode::Full { .. } => "full",
1823 };
1824
1825 if EditorSettings::jupyter_enabled(cx) {
1826 key_context.add("jupyter");
1827 }
1828
1829 key_context.set("mode", mode);
1830 if self.pending_rename.is_some() {
1831 key_context.add("renaming");
1832 }
1833
1834 match self.context_menu.borrow().as_ref() {
1835 Some(CodeContextMenu::Completions(_)) => {
1836 key_context.add("menu");
1837 key_context.add("showing_completions");
1838 }
1839 Some(CodeContextMenu::CodeActions(_)) => {
1840 key_context.add("menu");
1841 key_context.add("showing_code_actions")
1842 }
1843 None => {}
1844 }
1845
1846 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1847 if !self.focus_handle(cx).contains_focused(window, cx)
1848 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1849 {
1850 for addon in self.addons.values() {
1851 addon.extend_key_context(&mut key_context, cx)
1852 }
1853 }
1854
1855 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1856 if let Some(extension) = singleton_buffer
1857 .read(cx)
1858 .file()
1859 .and_then(|file| file.path().extension()?.to_str())
1860 {
1861 key_context.set("extension", extension.to_string());
1862 }
1863 } else {
1864 key_context.add("multibuffer");
1865 }
1866
1867 if has_active_edit_prediction {
1868 if self.edit_prediction_in_conflict() {
1869 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1870 } else {
1871 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1872 key_context.add("copilot_suggestion");
1873 }
1874 }
1875
1876 if self.selection_mark_mode {
1877 key_context.add("selection_mode");
1878 }
1879
1880 key_context
1881 }
1882
1883 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1884 self.mouse_cursor_hidden = match origin {
1885 HideMouseCursorOrigin::TypingAction => {
1886 matches!(
1887 self.hide_mouse_mode,
1888 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1889 )
1890 }
1891 HideMouseCursorOrigin::MovementAction => {
1892 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1893 }
1894 };
1895 }
1896
1897 pub fn edit_prediction_in_conflict(&self) -> bool {
1898 if !self.show_edit_predictions_in_menu() {
1899 return false;
1900 }
1901
1902 let showing_completions = self
1903 .context_menu
1904 .borrow()
1905 .as_ref()
1906 .map_or(false, |context| {
1907 matches!(context, CodeContextMenu::Completions(_))
1908 });
1909
1910 showing_completions
1911 || self.edit_prediction_requires_modifier()
1912 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1913 // bindings to insert tab characters.
1914 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1915 }
1916
1917 pub fn accept_edit_prediction_keybind(
1918 &self,
1919 window: &Window,
1920 cx: &App,
1921 ) -> AcceptEditPredictionBinding {
1922 let key_context = self.key_context_internal(true, window, cx);
1923 let in_conflict = self.edit_prediction_in_conflict();
1924
1925 AcceptEditPredictionBinding(
1926 window
1927 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1928 .into_iter()
1929 .filter(|binding| {
1930 !in_conflict
1931 || binding
1932 .keystrokes()
1933 .first()
1934 .map_or(false, |keystroke| keystroke.modifiers.modified())
1935 })
1936 .rev()
1937 .min_by_key(|binding| {
1938 binding
1939 .keystrokes()
1940 .first()
1941 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1942 }),
1943 )
1944 }
1945
1946 pub fn new_file(
1947 workspace: &mut Workspace,
1948 _: &workspace::NewFile,
1949 window: &mut Window,
1950 cx: &mut Context<Workspace>,
1951 ) {
1952 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1953 "Failed to create buffer",
1954 window,
1955 cx,
1956 |e, _, _| match e.error_code() {
1957 ErrorCode::RemoteUpgradeRequired => Some(format!(
1958 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1959 e.error_tag("required").unwrap_or("the latest version")
1960 )),
1961 _ => None,
1962 },
1963 );
1964 }
1965
1966 pub fn new_in_workspace(
1967 workspace: &mut Workspace,
1968 window: &mut Window,
1969 cx: &mut Context<Workspace>,
1970 ) -> Task<Result<Entity<Editor>>> {
1971 let project = workspace.project().clone();
1972 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1973
1974 cx.spawn_in(window, async move |workspace, cx| {
1975 let buffer = create.await?;
1976 workspace.update_in(cx, |workspace, window, cx| {
1977 let editor =
1978 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1979 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1980 editor
1981 })
1982 })
1983 }
1984
1985 fn new_file_vertical(
1986 workspace: &mut Workspace,
1987 _: &workspace::NewFileSplitVertical,
1988 window: &mut Window,
1989 cx: &mut Context<Workspace>,
1990 ) {
1991 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1992 }
1993
1994 fn new_file_horizontal(
1995 workspace: &mut Workspace,
1996 _: &workspace::NewFileSplitHorizontal,
1997 window: &mut Window,
1998 cx: &mut Context<Workspace>,
1999 ) {
2000 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2001 }
2002
2003 fn new_file_in_direction(
2004 workspace: &mut Workspace,
2005 direction: SplitDirection,
2006 window: &mut Window,
2007 cx: &mut Context<Workspace>,
2008 ) {
2009 let project = workspace.project().clone();
2010 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2011
2012 cx.spawn_in(window, async move |workspace, cx| {
2013 let buffer = create.await?;
2014 workspace.update_in(cx, move |workspace, window, cx| {
2015 workspace.split_item(
2016 direction,
2017 Box::new(
2018 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2019 ),
2020 window,
2021 cx,
2022 )
2023 })?;
2024 anyhow::Ok(())
2025 })
2026 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2027 match e.error_code() {
2028 ErrorCode::RemoteUpgradeRequired => Some(format!(
2029 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2030 e.error_tag("required").unwrap_or("the latest version")
2031 )),
2032 _ => None,
2033 }
2034 });
2035 }
2036
2037 pub fn leader_peer_id(&self) -> Option<PeerId> {
2038 self.leader_peer_id
2039 }
2040
2041 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2042 &self.buffer
2043 }
2044
2045 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2046 self.workspace.as_ref()?.0.upgrade()
2047 }
2048
2049 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2050 self.buffer().read(cx).title(cx)
2051 }
2052
2053 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2054 let git_blame_gutter_max_author_length = self
2055 .render_git_blame_gutter(cx)
2056 .then(|| {
2057 if let Some(blame) = self.blame.as_ref() {
2058 let max_author_length =
2059 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2060 Some(max_author_length)
2061 } else {
2062 None
2063 }
2064 })
2065 .flatten();
2066
2067 EditorSnapshot {
2068 mode: self.mode,
2069 show_gutter: self.show_gutter,
2070 show_line_numbers: self.show_line_numbers,
2071 show_git_diff_gutter: self.show_git_diff_gutter,
2072 show_code_actions: self.show_code_actions,
2073 show_runnables: self.show_runnables,
2074 show_breakpoints: self.show_breakpoints,
2075 git_blame_gutter_max_author_length,
2076 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2077 scroll_anchor: self.scroll_manager.anchor(),
2078 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2079 placeholder_text: self.placeholder_text.clone(),
2080 is_focused: self.focus_handle.is_focused(window),
2081 current_line_highlight: self
2082 .current_line_highlight
2083 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2084 gutter_hovered: self.gutter_hovered,
2085 }
2086 }
2087
2088 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2089 self.buffer.read(cx).language_at(point, cx)
2090 }
2091
2092 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2093 self.buffer.read(cx).read(cx).file_at(point).cloned()
2094 }
2095
2096 pub fn active_excerpt(
2097 &self,
2098 cx: &App,
2099 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2100 self.buffer
2101 .read(cx)
2102 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2103 }
2104
2105 pub fn mode(&self) -> EditorMode {
2106 self.mode
2107 }
2108
2109 pub fn set_mode(&mut self, mode: EditorMode) {
2110 self.mode = mode;
2111 }
2112
2113 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2114 self.collaboration_hub.as_deref()
2115 }
2116
2117 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2118 self.collaboration_hub = Some(hub);
2119 }
2120
2121 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2122 self.in_project_search = in_project_search;
2123 }
2124
2125 pub fn set_custom_context_menu(
2126 &mut self,
2127 f: impl 'static
2128 + Fn(
2129 &mut Self,
2130 DisplayPoint,
2131 &mut Window,
2132 &mut Context<Self>,
2133 ) -> Option<Entity<ui::ContextMenu>>,
2134 ) {
2135 self.custom_context_menu = Some(Box::new(f))
2136 }
2137
2138 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2139 self.completion_provider = provider;
2140 }
2141
2142 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2143 self.semantics_provider.clone()
2144 }
2145
2146 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2147 self.semantics_provider = provider;
2148 }
2149
2150 pub fn set_edit_prediction_provider<T>(
2151 &mut self,
2152 provider: Option<Entity<T>>,
2153 window: &mut Window,
2154 cx: &mut Context<Self>,
2155 ) where
2156 T: EditPredictionProvider,
2157 {
2158 self.edit_prediction_provider =
2159 provider.map(|provider| RegisteredInlineCompletionProvider {
2160 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2161 if this.focus_handle.is_focused(window) {
2162 this.update_visible_inline_completion(window, cx);
2163 }
2164 }),
2165 provider: Arc::new(provider),
2166 });
2167 self.update_edit_prediction_settings(cx);
2168 self.refresh_inline_completion(false, false, window, cx);
2169 }
2170
2171 pub fn placeholder_text(&self) -> Option<&str> {
2172 self.placeholder_text.as_deref()
2173 }
2174
2175 pub fn set_placeholder_text(
2176 &mut self,
2177 placeholder_text: impl Into<Arc<str>>,
2178 cx: &mut Context<Self>,
2179 ) {
2180 let placeholder_text = Some(placeholder_text.into());
2181 if self.placeholder_text != placeholder_text {
2182 self.placeholder_text = placeholder_text;
2183 cx.notify();
2184 }
2185 }
2186
2187 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2188 self.cursor_shape = cursor_shape;
2189
2190 // Disrupt blink for immediate user feedback that the cursor shape has changed
2191 self.blink_manager.update(cx, BlinkManager::show_cursor);
2192
2193 cx.notify();
2194 }
2195
2196 pub fn set_current_line_highlight(
2197 &mut self,
2198 current_line_highlight: Option<CurrentLineHighlight>,
2199 ) {
2200 self.current_line_highlight = current_line_highlight;
2201 }
2202
2203 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2204 self.collapse_matches = collapse_matches;
2205 }
2206
2207 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2208 let buffers = self.buffer.read(cx).all_buffers();
2209 let Some(project) = self.project.as_ref() else {
2210 return;
2211 };
2212 project.update(cx, |project, cx| {
2213 for buffer in buffers {
2214 self.registered_buffers
2215 .entry(buffer.read(cx).remote_id())
2216 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2217 }
2218 })
2219 }
2220
2221 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2222 if self.collapse_matches {
2223 return range.start..range.start;
2224 }
2225 range.clone()
2226 }
2227
2228 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2229 if self.display_map.read(cx).clip_at_line_ends != clip {
2230 self.display_map
2231 .update(cx, |map, _| map.clip_at_line_ends = clip);
2232 }
2233 }
2234
2235 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2236 self.input_enabled = input_enabled;
2237 }
2238
2239 pub fn set_inline_completions_hidden_for_vim_mode(
2240 &mut self,
2241 hidden: bool,
2242 window: &mut Window,
2243 cx: &mut Context<Self>,
2244 ) {
2245 if hidden != self.inline_completions_hidden_for_vim_mode {
2246 self.inline_completions_hidden_for_vim_mode = hidden;
2247 if hidden {
2248 self.update_visible_inline_completion(window, cx);
2249 } else {
2250 self.refresh_inline_completion(true, false, window, cx);
2251 }
2252 }
2253 }
2254
2255 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2256 self.menu_inline_completions_policy = value;
2257 }
2258
2259 pub fn set_autoindent(&mut self, autoindent: bool) {
2260 if autoindent {
2261 self.autoindent_mode = Some(AutoindentMode::EachLine);
2262 } else {
2263 self.autoindent_mode = None;
2264 }
2265 }
2266
2267 pub fn read_only(&self, cx: &App) -> bool {
2268 self.read_only || self.buffer.read(cx).read_only()
2269 }
2270
2271 pub fn set_read_only(&mut self, read_only: bool) {
2272 self.read_only = read_only;
2273 }
2274
2275 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2276 self.use_autoclose = autoclose;
2277 }
2278
2279 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2280 self.use_auto_surround = auto_surround;
2281 }
2282
2283 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2284 self.auto_replace_emoji_shortcode = auto_replace;
2285 }
2286
2287 pub fn toggle_edit_predictions(
2288 &mut self,
2289 _: &ToggleEditPrediction,
2290 window: &mut Window,
2291 cx: &mut Context<Self>,
2292 ) {
2293 if self.show_inline_completions_override.is_some() {
2294 self.set_show_edit_predictions(None, window, cx);
2295 } else {
2296 let show_edit_predictions = !self.edit_predictions_enabled();
2297 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2298 }
2299 }
2300
2301 pub fn set_show_edit_predictions(
2302 &mut self,
2303 show_edit_predictions: Option<bool>,
2304 window: &mut Window,
2305 cx: &mut Context<Self>,
2306 ) {
2307 self.show_inline_completions_override = show_edit_predictions;
2308 self.update_edit_prediction_settings(cx);
2309
2310 if let Some(false) = show_edit_predictions {
2311 self.discard_inline_completion(false, cx);
2312 } else {
2313 self.refresh_inline_completion(false, true, window, cx);
2314 }
2315 }
2316
2317 fn inline_completions_disabled_in_scope(
2318 &self,
2319 buffer: &Entity<Buffer>,
2320 buffer_position: language::Anchor,
2321 cx: &App,
2322 ) -> bool {
2323 let snapshot = buffer.read(cx).snapshot();
2324 let settings = snapshot.settings_at(buffer_position, cx);
2325
2326 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2327 return false;
2328 };
2329
2330 scope.override_name().map_or(false, |scope_name| {
2331 settings
2332 .edit_predictions_disabled_in
2333 .iter()
2334 .any(|s| s == scope_name)
2335 })
2336 }
2337
2338 pub fn set_use_modal_editing(&mut self, to: bool) {
2339 self.use_modal_editing = to;
2340 }
2341
2342 pub fn use_modal_editing(&self) -> bool {
2343 self.use_modal_editing
2344 }
2345
2346 fn selections_did_change(
2347 &mut self,
2348 local: bool,
2349 old_cursor_position: &Anchor,
2350 show_completions: bool,
2351 window: &mut Window,
2352 cx: &mut Context<Self>,
2353 ) {
2354 window.invalidate_character_coordinates();
2355
2356 // Copy selections to primary selection buffer
2357 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2358 if local {
2359 let selections = self.selections.all::<usize>(cx);
2360 let buffer_handle = self.buffer.read(cx).read(cx);
2361
2362 let mut text = String::new();
2363 for (index, selection) in selections.iter().enumerate() {
2364 let text_for_selection = buffer_handle
2365 .text_for_range(selection.start..selection.end)
2366 .collect::<String>();
2367
2368 text.push_str(&text_for_selection);
2369 if index != selections.len() - 1 {
2370 text.push('\n');
2371 }
2372 }
2373
2374 if !text.is_empty() {
2375 cx.write_to_primary(ClipboardItem::new_string(text));
2376 }
2377 }
2378
2379 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2380 self.buffer.update(cx, |buffer, cx| {
2381 buffer.set_active_selections(
2382 &self.selections.disjoint_anchors(),
2383 self.selections.line_mode,
2384 self.cursor_shape,
2385 cx,
2386 )
2387 });
2388 }
2389 let display_map = self
2390 .display_map
2391 .update(cx, |display_map, cx| display_map.snapshot(cx));
2392 let buffer = &display_map.buffer_snapshot;
2393 self.add_selections_state = None;
2394 self.select_next_state = None;
2395 self.select_prev_state = None;
2396 self.select_syntax_node_history.try_clear();
2397 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2398 self.snippet_stack
2399 .invalidate(&self.selections.disjoint_anchors(), buffer);
2400 self.take_rename(false, window, cx);
2401
2402 let new_cursor_position = self.selections.newest_anchor().head();
2403
2404 self.push_to_nav_history(
2405 *old_cursor_position,
2406 Some(new_cursor_position.to_point(buffer)),
2407 false,
2408 cx,
2409 );
2410
2411 if local {
2412 let new_cursor_position = self.selections.newest_anchor().head();
2413 let mut context_menu = self.context_menu.borrow_mut();
2414 let completion_menu = match context_menu.as_ref() {
2415 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2416 _ => {
2417 *context_menu = None;
2418 None
2419 }
2420 };
2421 if let Some(buffer_id) = new_cursor_position.buffer_id {
2422 if !self.registered_buffers.contains_key(&buffer_id) {
2423 if let Some(project) = self.project.as_ref() {
2424 project.update(cx, |project, cx| {
2425 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2426 return;
2427 };
2428 self.registered_buffers.insert(
2429 buffer_id,
2430 project.register_buffer_with_language_servers(&buffer, cx),
2431 );
2432 })
2433 }
2434 }
2435 }
2436
2437 if let Some(completion_menu) = completion_menu {
2438 let cursor_position = new_cursor_position.to_offset(buffer);
2439 let (word_range, kind) =
2440 buffer.surrounding_word(completion_menu.initial_position, true);
2441 if kind == Some(CharKind::Word)
2442 && word_range.to_inclusive().contains(&cursor_position)
2443 {
2444 let mut completion_menu = completion_menu.clone();
2445 drop(context_menu);
2446
2447 let query = Self::completion_query(buffer, cursor_position);
2448 cx.spawn(async move |this, cx| {
2449 completion_menu
2450 .filter(query.as_deref(), cx.background_executor().clone())
2451 .await;
2452
2453 this.update(cx, |this, cx| {
2454 let mut context_menu = this.context_menu.borrow_mut();
2455 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2456 else {
2457 return;
2458 };
2459
2460 if menu.id > completion_menu.id {
2461 return;
2462 }
2463
2464 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2465 drop(context_menu);
2466 cx.notify();
2467 })
2468 })
2469 .detach();
2470
2471 if show_completions {
2472 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2473 }
2474 } else {
2475 drop(context_menu);
2476 self.hide_context_menu(window, cx);
2477 }
2478 } else {
2479 drop(context_menu);
2480 }
2481
2482 hide_hover(self, cx);
2483
2484 if old_cursor_position.to_display_point(&display_map).row()
2485 != new_cursor_position.to_display_point(&display_map).row()
2486 {
2487 self.available_code_actions.take();
2488 }
2489 self.refresh_code_actions(window, cx);
2490 self.refresh_document_highlights(cx);
2491 self.refresh_selected_text_highlights(window, cx);
2492 refresh_matching_bracket_highlights(self, window, cx);
2493 self.update_visible_inline_completion(window, cx);
2494 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2495 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2496 if self.git_blame_inline_enabled {
2497 self.start_inline_blame_timer(window, cx);
2498 }
2499 }
2500
2501 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2502 cx.emit(EditorEvent::SelectionsChanged { local });
2503
2504 let selections = &self.selections.disjoint;
2505 if selections.len() == 1 {
2506 cx.emit(SearchEvent::ActiveMatchChanged)
2507 }
2508 if local {
2509 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2510 let inmemory_selections = selections
2511 .iter()
2512 .map(|s| {
2513 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2514 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2515 })
2516 .collect();
2517 self.update_restoration_data(cx, |data| {
2518 data.selections = inmemory_selections;
2519 });
2520
2521 if WorkspaceSettings::get(None, cx).restore_on_startup
2522 != RestoreOnStartupBehavior::None
2523 {
2524 if let Some(workspace_id) =
2525 self.workspace.as_ref().and_then(|workspace| workspace.1)
2526 {
2527 let snapshot = self.buffer().read(cx).snapshot(cx);
2528 let selections = selections.clone();
2529 let background_executor = cx.background_executor().clone();
2530 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2531 self.serialize_selections = cx.background_spawn(async move {
2532 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2533 let db_selections = selections
2534 .iter()
2535 .map(|selection| {
2536 (
2537 selection.start.to_offset(&snapshot),
2538 selection.end.to_offset(&snapshot),
2539 )
2540 })
2541 .collect();
2542
2543 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2544 .await
2545 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2546 .log_err();
2547 });
2548 }
2549 }
2550 }
2551 }
2552
2553 cx.notify();
2554 }
2555
2556 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2557 use text::ToOffset as _;
2558 use text::ToPoint as _;
2559
2560 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2561 return;
2562 }
2563
2564 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2565 return;
2566 };
2567
2568 let snapshot = singleton.read(cx).snapshot();
2569 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2570 let display_snapshot = display_map.snapshot(cx);
2571
2572 display_snapshot
2573 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2574 .map(|fold| {
2575 fold.range.start.text_anchor.to_point(&snapshot)
2576 ..fold.range.end.text_anchor.to_point(&snapshot)
2577 })
2578 .collect()
2579 });
2580 self.update_restoration_data(cx, |data| {
2581 data.folds = inmemory_folds;
2582 });
2583
2584 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2585 return;
2586 };
2587 let background_executor = cx.background_executor().clone();
2588 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2589 let db_folds = self.display_map.update(cx, |display_map, cx| {
2590 display_map
2591 .snapshot(cx)
2592 .folds_in_range(0..snapshot.len())
2593 .map(|fold| {
2594 (
2595 fold.range.start.text_anchor.to_offset(&snapshot),
2596 fold.range.end.text_anchor.to_offset(&snapshot),
2597 )
2598 })
2599 .collect()
2600 });
2601 self.serialize_folds = cx.background_spawn(async move {
2602 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2603 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2604 .await
2605 .with_context(|| {
2606 format!(
2607 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2608 )
2609 })
2610 .log_err();
2611 });
2612 }
2613
2614 pub fn sync_selections(
2615 &mut self,
2616 other: Entity<Editor>,
2617 cx: &mut Context<Self>,
2618 ) -> gpui::Subscription {
2619 let other_selections = other.read(cx).selections.disjoint.to_vec();
2620 self.selections.change_with(cx, |selections| {
2621 selections.select_anchors(other_selections);
2622 });
2623
2624 let other_subscription =
2625 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2626 EditorEvent::SelectionsChanged { local: true } => {
2627 let other_selections = other.read(cx).selections.disjoint.to_vec();
2628 if other_selections.is_empty() {
2629 return;
2630 }
2631 this.selections.change_with(cx, |selections| {
2632 selections.select_anchors(other_selections);
2633 });
2634 }
2635 _ => {}
2636 });
2637
2638 let this_subscription =
2639 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2640 EditorEvent::SelectionsChanged { local: true } => {
2641 let these_selections = this.selections.disjoint.to_vec();
2642 if these_selections.is_empty() {
2643 return;
2644 }
2645 other.update(cx, |other_editor, cx| {
2646 other_editor.selections.change_with(cx, |selections| {
2647 selections.select_anchors(these_selections);
2648 })
2649 });
2650 }
2651 _ => {}
2652 });
2653
2654 Subscription::join(other_subscription, this_subscription)
2655 }
2656
2657 pub fn change_selections<R>(
2658 &mut self,
2659 autoscroll: Option<Autoscroll>,
2660 window: &mut Window,
2661 cx: &mut Context<Self>,
2662 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2663 ) -> R {
2664 self.change_selections_inner(autoscroll, true, window, cx, change)
2665 }
2666
2667 fn change_selections_inner<R>(
2668 &mut self,
2669 autoscroll: Option<Autoscroll>,
2670 request_completions: bool,
2671 window: &mut Window,
2672 cx: &mut Context<Self>,
2673 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2674 ) -> R {
2675 let old_cursor_position = self.selections.newest_anchor().head();
2676 self.push_to_selection_history();
2677
2678 let (changed, result) = self.selections.change_with(cx, change);
2679
2680 if changed {
2681 if let Some(autoscroll) = autoscroll {
2682 self.request_autoscroll(autoscroll, cx);
2683 }
2684 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2685
2686 if self.should_open_signature_help_automatically(
2687 &old_cursor_position,
2688 self.signature_help_state.backspace_pressed(),
2689 cx,
2690 ) {
2691 self.show_signature_help(&ShowSignatureHelp, window, cx);
2692 }
2693 self.signature_help_state.set_backspace_pressed(false);
2694 }
2695
2696 result
2697 }
2698
2699 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2700 where
2701 I: IntoIterator<Item = (Range<S>, T)>,
2702 S: ToOffset,
2703 T: Into<Arc<str>>,
2704 {
2705 if self.read_only(cx) {
2706 return;
2707 }
2708
2709 self.buffer
2710 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2711 }
2712
2713 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2714 where
2715 I: IntoIterator<Item = (Range<S>, T)>,
2716 S: ToOffset,
2717 T: Into<Arc<str>>,
2718 {
2719 if self.read_only(cx) {
2720 return;
2721 }
2722
2723 self.buffer.update(cx, |buffer, cx| {
2724 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2725 });
2726 }
2727
2728 pub fn edit_with_block_indent<I, S, T>(
2729 &mut self,
2730 edits: I,
2731 original_indent_columns: Vec<Option<u32>>,
2732 cx: &mut Context<Self>,
2733 ) where
2734 I: IntoIterator<Item = (Range<S>, T)>,
2735 S: ToOffset,
2736 T: Into<Arc<str>>,
2737 {
2738 if self.read_only(cx) {
2739 return;
2740 }
2741
2742 self.buffer.update(cx, |buffer, cx| {
2743 buffer.edit(
2744 edits,
2745 Some(AutoindentMode::Block {
2746 original_indent_columns,
2747 }),
2748 cx,
2749 )
2750 });
2751 }
2752
2753 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2754 self.hide_context_menu(window, cx);
2755
2756 match phase {
2757 SelectPhase::Begin {
2758 position,
2759 add,
2760 click_count,
2761 } => self.begin_selection(position, add, click_count, window, cx),
2762 SelectPhase::BeginColumnar {
2763 position,
2764 goal_column,
2765 reset,
2766 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2767 SelectPhase::Extend {
2768 position,
2769 click_count,
2770 } => self.extend_selection(position, click_count, window, cx),
2771 SelectPhase::Update {
2772 position,
2773 goal_column,
2774 scroll_delta,
2775 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2776 SelectPhase::End => self.end_selection(window, cx),
2777 }
2778 }
2779
2780 fn extend_selection(
2781 &mut self,
2782 position: DisplayPoint,
2783 click_count: usize,
2784 window: &mut Window,
2785 cx: &mut Context<Self>,
2786 ) {
2787 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2788 let tail = self.selections.newest::<usize>(cx).tail();
2789 self.begin_selection(position, false, click_count, window, cx);
2790
2791 let position = position.to_offset(&display_map, Bias::Left);
2792 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2793
2794 let mut pending_selection = self
2795 .selections
2796 .pending_anchor()
2797 .expect("extend_selection not called with pending selection");
2798 if position >= tail {
2799 pending_selection.start = tail_anchor;
2800 } else {
2801 pending_selection.end = tail_anchor;
2802 pending_selection.reversed = true;
2803 }
2804
2805 let mut pending_mode = self.selections.pending_mode().unwrap();
2806 match &mut pending_mode {
2807 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2808 _ => {}
2809 }
2810
2811 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2812 s.set_pending(pending_selection, pending_mode)
2813 });
2814 }
2815
2816 fn begin_selection(
2817 &mut self,
2818 position: DisplayPoint,
2819 add: bool,
2820 click_count: usize,
2821 window: &mut Window,
2822 cx: &mut Context<Self>,
2823 ) {
2824 if !self.focus_handle.is_focused(window) {
2825 self.last_focused_descendant = None;
2826 window.focus(&self.focus_handle);
2827 }
2828
2829 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2830 let buffer = &display_map.buffer_snapshot;
2831 let newest_selection = self.selections.newest_anchor().clone();
2832 let position = display_map.clip_point(position, Bias::Left);
2833
2834 let start;
2835 let end;
2836 let mode;
2837 let mut auto_scroll;
2838 match click_count {
2839 1 => {
2840 start = buffer.anchor_before(position.to_point(&display_map));
2841 end = start;
2842 mode = SelectMode::Character;
2843 auto_scroll = true;
2844 }
2845 2 => {
2846 let range = movement::surrounding_word(&display_map, position);
2847 start = buffer.anchor_before(range.start.to_point(&display_map));
2848 end = buffer.anchor_before(range.end.to_point(&display_map));
2849 mode = SelectMode::Word(start..end);
2850 auto_scroll = true;
2851 }
2852 3 => {
2853 let position = display_map
2854 .clip_point(position, Bias::Left)
2855 .to_point(&display_map);
2856 let line_start = display_map.prev_line_boundary(position).0;
2857 let next_line_start = buffer.clip_point(
2858 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2859 Bias::Left,
2860 );
2861 start = buffer.anchor_before(line_start);
2862 end = buffer.anchor_before(next_line_start);
2863 mode = SelectMode::Line(start..end);
2864 auto_scroll = true;
2865 }
2866 _ => {
2867 start = buffer.anchor_before(0);
2868 end = buffer.anchor_before(buffer.len());
2869 mode = SelectMode::All;
2870 auto_scroll = false;
2871 }
2872 }
2873 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2874
2875 let point_to_delete: Option<usize> = {
2876 let selected_points: Vec<Selection<Point>> =
2877 self.selections.disjoint_in_range(start..end, cx);
2878
2879 if !add || click_count > 1 {
2880 None
2881 } else if !selected_points.is_empty() {
2882 Some(selected_points[0].id)
2883 } else {
2884 let clicked_point_already_selected =
2885 self.selections.disjoint.iter().find(|selection| {
2886 selection.start.to_point(buffer) == start.to_point(buffer)
2887 || selection.end.to_point(buffer) == end.to_point(buffer)
2888 });
2889
2890 clicked_point_already_selected.map(|selection| selection.id)
2891 }
2892 };
2893
2894 let selections_count = self.selections.count();
2895
2896 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2897 if let Some(point_to_delete) = point_to_delete {
2898 s.delete(point_to_delete);
2899
2900 if selections_count == 1 {
2901 s.set_pending_anchor_range(start..end, mode);
2902 }
2903 } else {
2904 if !add {
2905 s.clear_disjoint();
2906 } else if click_count > 1 {
2907 s.delete(newest_selection.id)
2908 }
2909
2910 s.set_pending_anchor_range(start..end, mode);
2911 }
2912 });
2913 }
2914
2915 fn begin_columnar_selection(
2916 &mut self,
2917 position: DisplayPoint,
2918 goal_column: u32,
2919 reset: bool,
2920 window: &mut Window,
2921 cx: &mut Context<Self>,
2922 ) {
2923 if !self.focus_handle.is_focused(window) {
2924 self.last_focused_descendant = None;
2925 window.focus(&self.focus_handle);
2926 }
2927
2928 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2929
2930 if reset {
2931 let pointer_position = display_map
2932 .buffer_snapshot
2933 .anchor_before(position.to_point(&display_map));
2934
2935 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2936 s.clear_disjoint();
2937 s.set_pending_anchor_range(
2938 pointer_position..pointer_position,
2939 SelectMode::Character,
2940 );
2941 });
2942 }
2943
2944 let tail = self.selections.newest::<Point>(cx).tail();
2945 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2946
2947 if !reset {
2948 self.select_columns(
2949 tail.to_display_point(&display_map),
2950 position,
2951 goal_column,
2952 &display_map,
2953 window,
2954 cx,
2955 );
2956 }
2957 }
2958
2959 fn update_selection(
2960 &mut self,
2961 position: DisplayPoint,
2962 goal_column: u32,
2963 scroll_delta: gpui::Point<f32>,
2964 window: &mut Window,
2965 cx: &mut Context<Self>,
2966 ) {
2967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2968
2969 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2970 let tail = tail.to_display_point(&display_map);
2971 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2972 } else if let Some(mut pending) = self.selections.pending_anchor() {
2973 let buffer = self.buffer.read(cx).snapshot(cx);
2974 let head;
2975 let tail;
2976 let mode = self.selections.pending_mode().unwrap();
2977 match &mode {
2978 SelectMode::Character => {
2979 head = position.to_point(&display_map);
2980 tail = pending.tail().to_point(&buffer);
2981 }
2982 SelectMode::Word(original_range) => {
2983 let original_display_range = original_range.start.to_display_point(&display_map)
2984 ..original_range.end.to_display_point(&display_map);
2985 let original_buffer_range = original_display_range.start.to_point(&display_map)
2986 ..original_display_range.end.to_point(&display_map);
2987 if movement::is_inside_word(&display_map, position)
2988 || original_display_range.contains(&position)
2989 {
2990 let word_range = movement::surrounding_word(&display_map, position);
2991 if word_range.start < original_display_range.start {
2992 head = word_range.start.to_point(&display_map);
2993 } else {
2994 head = word_range.end.to_point(&display_map);
2995 }
2996 } else {
2997 head = position.to_point(&display_map);
2998 }
2999
3000 if head <= original_buffer_range.start {
3001 tail = original_buffer_range.end;
3002 } else {
3003 tail = original_buffer_range.start;
3004 }
3005 }
3006 SelectMode::Line(original_range) => {
3007 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3008
3009 let position = display_map
3010 .clip_point(position, Bias::Left)
3011 .to_point(&display_map);
3012 let line_start = display_map.prev_line_boundary(position).0;
3013 let next_line_start = buffer.clip_point(
3014 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3015 Bias::Left,
3016 );
3017
3018 if line_start < original_range.start {
3019 head = line_start
3020 } else {
3021 head = next_line_start
3022 }
3023
3024 if head <= original_range.start {
3025 tail = original_range.end;
3026 } else {
3027 tail = original_range.start;
3028 }
3029 }
3030 SelectMode::All => {
3031 return;
3032 }
3033 };
3034
3035 if head < tail {
3036 pending.start = buffer.anchor_before(head);
3037 pending.end = buffer.anchor_before(tail);
3038 pending.reversed = true;
3039 } else {
3040 pending.start = buffer.anchor_before(tail);
3041 pending.end = buffer.anchor_before(head);
3042 pending.reversed = false;
3043 }
3044
3045 self.change_selections(None, window, cx, |s| {
3046 s.set_pending(pending, mode);
3047 });
3048 } else {
3049 log::error!("update_selection dispatched with no pending selection");
3050 return;
3051 }
3052
3053 self.apply_scroll_delta(scroll_delta, window, cx);
3054 cx.notify();
3055 }
3056
3057 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3058 self.columnar_selection_tail.take();
3059 if self.selections.pending_anchor().is_some() {
3060 let selections = self.selections.all::<usize>(cx);
3061 self.change_selections(None, window, cx, |s| {
3062 s.select(selections);
3063 s.clear_pending();
3064 });
3065 }
3066 }
3067
3068 fn select_columns(
3069 &mut self,
3070 tail: DisplayPoint,
3071 head: DisplayPoint,
3072 goal_column: u32,
3073 display_map: &DisplaySnapshot,
3074 window: &mut Window,
3075 cx: &mut Context<Self>,
3076 ) {
3077 let start_row = cmp::min(tail.row(), head.row());
3078 let end_row = cmp::max(tail.row(), head.row());
3079 let start_column = cmp::min(tail.column(), goal_column);
3080 let end_column = cmp::max(tail.column(), goal_column);
3081 let reversed = start_column < tail.column();
3082
3083 let selection_ranges = (start_row.0..=end_row.0)
3084 .map(DisplayRow)
3085 .filter_map(|row| {
3086 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3087 let start = display_map
3088 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3089 .to_point(display_map);
3090 let end = display_map
3091 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3092 .to_point(display_map);
3093 if reversed {
3094 Some(end..start)
3095 } else {
3096 Some(start..end)
3097 }
3098 } else {
3099 None
3100 }
3101 })
3102 .collect::<Vec<_>>();
3103
3104 self.change_selections(None, window, cx, |s| {
3105 s.select_ranges(selection_ranges);
3106 });
3107 cx.notify();
3108 }
3109
3110 pub fn has_pending_nonempty_selection(&self) -> bool {
3111 let pending_nonempty_selection = match self.selections.pending_anchor() {
3112 Some(Selection { start, end, .. }) => start != end,
3113 None => false,
3114 };
3115
3116 pending_nonempty_selection
3117 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3118 }
3119
3120 pub fn has_pending_selection(&self) -> bool {
3121 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3122 }
3123
3124 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3125 self.selection_mark_mode = false;
3126
3127 if self.clear_expanded_diff_hunks(cx) {
3128 cx.notify();
3129 return;
3130 }
3131 if self.dismiss_menus_and_popups(true, window, cx) {
3132 return;
3133 }
3134
3135 if self.mode.is_full()
3136 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3137 {
3138 return;
3139 }
3140
3141 cx.propagate();
3142 }
3143
3144 pub fn dismiss_menus_and_popups(
3145 &mut self,
3146 is_user_requested: bool,
3147 window: &mut Window,
3148 cx: &mut Context<Self>,
3149 ) -> bool {
3150 if self.take_rename(false, window, cx).is_some() {
3151 return true;
3152 }
3153
3154 if hide_hover(self, cx) {
3155 return true;
3156 }
3157
3158 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3159 return true;
3160 }
3161
3162 if self.hide_context_menu(window, cx).is_some() {
3163 return true;
3164 }
3165
3166 if self.mouse_context_menu.take().is_some() {
3167 return true;
3168 }
3169
3170 if is_user_requested && self.discard_inline_completion(true, cx) {
3171 return true;
3172 }
3173
3174 if self.snippet_stack.pop().is_some() {
3175 return true;
3176 }
3177
3178 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3179 self.dismiss_diagnostics(cx);
3180 return true;
3181 }
3182
3183 false
3184 }
3185
3186 fn linked_editing_ranges_for(
3187 &self,
3188 selection: Range<text::Anchor>,
3189 cx: &App,
3190 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3191 if self.linked_edit_ranges.is_empty() {
3192 return None;
3193 }
3194 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3195 selection.end.buffer_id.and_then(|end_buffer_id| {
3196 if selection.start.buffer_id != Some(end_buffer_id) {
3197 return None;
3198 }
3199 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3200 let snapshot = buffer.read(cx).snapshot();
3201 self.linked_edit_ranges
3202 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3203 .map(|ranges| (ranges, snapshot, buffer))
3204 })?;
3205 use text::ToOffset as TO;
3206 // find offset from the start of current range to current cursor position
3207 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3208
3209 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3210 let start_difference = start_offset - start_byte_offset;
3211 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3212 let end_difference = end_offset - start_byte_offset;
3213 // Current range has associated linked ranges.
3214 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3215 for range in linked_ranges.iter() {
3216 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3217 let end_offset = start_offset + end_difference;
3218 let start_offset = start_offset + start_difference;
3219 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3220 continue;
3221 }
3222 if self.selections.disjoint_anchor_ranges().any(|s| {
3223 if s.start.buffer_id != selection.start.buffer_id
3224 || s.end.buffer_id != selection.end.buffer_id
3225 {
3226 return false;
3227 }
3228 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3229 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3230 }) {
3231 continue;
3232 }
3233 let start = buffer_snapshot.anchor_after(start_offset);
3234 let end = buffer_snapshot.anchor_after(end_offset);
3235 linked_edits
3236 .entry(buffer.clone())
3237 .or_default()
3238 .push(start..end);
3239 }
3240 Some(linked_edits)
3241 }
3242
3243 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3244 let text: Arc<str> = text.into();
3245
3246 if self.read_only(cx) {
3247 return;
3248 }
3249
3250 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3251
3252 let selections = self.selections.all_adjusted(cx);
3253 let mut bracket_inserted = false;
3254 let mut edits = Vec::new();
3255 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3256 let mut new_selections = Vec::with_capacity(selections.len());
3257 let mut new_autoclose_regions = Vec::new();
3258 let snapshot = self.buffer.read(cx).read(cx);
3259 let mut clear_linked_edit_ranges = false;
3260
3261 for (selection, autoclose_region) in
3262 self.selections_with_autoclose_regions(selections, &snapshot)
3263 {
3264 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3265 // Determine if the inserted text matches the opening or closing
3266 // bracket of any of this language's bracket pairs.
3267 let mut bracket_pair = None;
3268 let mut is_bracket_pair_start = false;
3269 let mut is_bracket_pair_end = false;
3270 if !text.is_empty() {
3271 let mut bracket_pair_matching_end = None;
3272 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3273 // and they are removing the character that triggered IME popup.
3274 for (pair, enabled) in scope.brackets() {
3275 if !pair.close && !pair.surround {
3276 continue;
3277 }
3278
3279 if enabled && pair.start.ends_with(text.as_ref()) {
3280 let prefix_len = pair.start.len() - text.len();
3281 let preceding_text_matches_prefix = prefix_len == 0
3282 || (selection.start.column >= (prefix_len as u32)
3283 && snapshot.contains_str_at(
3284 Point::new(
3285 selection.start.row,
3286 selection.start.column - (prefix_len as u32),
3287 ),
3288 &pair.start[..prefix_len],
3289 ));
3290 if preceding_text_matches_prefix {
3291 bracket_pair = Some(pair.clone());
3292 is_bracket_pair_start = true;
3293 break;
3294 }
3295 }
3296 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3297 {
3298 // take first bracket pair matching end, but don't break in case a later bracket
3299 // pair matches start
3300 bracket_pair_matching_end = Some(pair.clone());
3301 }
3302 }
3303 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3304 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3305 is_bracket_pair_end = true;
3306 }
3307 }
3308
3309 if let Some(bracket_pair) = bracket_pair {
3310 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3311 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3312 let auto_surround =
3313 self.use_auto_surround && snapshot_settings.use_auto_surround;
3314 if selection.is_empty() {
3315 if is_bracket_pair_start {
3316 // If the inserted text is a suffix of an opening bracket and the
3317 // selection is preceded by the rest of the opening bracket, then
3318 // insert the closing bracket.
3319 let following_text_allows_autoclose = snapshot
3320 .chars_at(selection.start)
3321 .next()
3322 .map_or(true, |c| scope.should_autoclose_before(c));
3323
3324 let preceding_text_allows_autoclose = selection.start.column == 0
3325 || snapshot.reversed_chars_at(selection.start).next().map_or(
3326 true,
3327 |c| {
3328 bracket_pair.start != bracket_pair.end
3329 || !snapshot
3330 .char_classifier_at(selection.start)
3331 .is_word(c)
3332 },
3333 );
3334
3335 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3336 && bracket_pair.start.len() == 1
3337 {
3338 let target = bracket_pair.start.chars().next().unwrap();
3339 let current_line_count = snapshot
3340 .reversed_chars_at(selection.start)
3341 .take_while(|&c| c != '\n')
3342 .filter(|&c| c == target)
3343 .count();
3344 current_line_count % 2 == 1
3345 } else {
3346 false
3347 };
3348
3349 if autoclose
3350 && bracket_pair.close
3351 && following_text_allows_autoclose
3352 && preceding_text_allows_autoclose
3353 && !is_closing_quote
3354 {
3355 let anchor = snapshot.anchor_before(selection.end);
3356 new_selections.push((selection.map(|_| anchor), text.len()));
3357 new_autoclose_regions.push((
3358 anchor,
3359 text.len(),
3360 selection.id,
3361 bracket_pair.clone(),
3362 ));
3363 edits.push((
3364 selection.range(),
3365 format!("{}{}", text, bracket_pair.end).into(),
3366 ));
3367 bracket_inserted = true;
3368 continue;
3369 }
3370 }
3371
3372 if let Some(region) = autoclose_region {
3373 // If the selection is followed by an auto-inserted closing bracket,
3374 // then don't insert that closing bracket again; just move the selection
3375 // past the closing bracket.
3376 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3377 && text.as_ref() == region.pair.end.as_str();
3378 if should_skip {
3379 let anchor = snapshot.anchor_after(selection.end);
3380 new_selections
3381 .push((selection.map(|_| anchor), region.pair.end.len()));
3382 continue;
3383 }
3384 }
3385
3386 let always_treat_brackets_as_autoclosed = snapshot
3387 .language_settings_at(selection.start, cx)
3388 .always_treat_brackets_as_autoclosed;
3389 if always_treat_brackets_as_autoclosed
3390 && is_bracket_pair_end
3391 && snapshot.contains_str_at(selection.end, text.as_ref())
3392 {
3393 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3394 // and the inserted text is a closing bracket and the selection is followed
3395 // by the closing bracket then move the selection past the closing bracket.
3396 let anchor = snapshot.anchor_after(selection.end);
3397 new_selections.push((selection.map(|_| anchor), text.len()));
3398 continue;
3399 }
3400 }
3401 // If an opening bracket is 1 character long and is typed while
3402 // text is selected, then surround that text with the bracket pair.
3403 else if auto_surround
3404 && bracket_pair.surround
3405 && is_bracket_pair_start
3406 && bracket_pair.start.chars().count() == 1
3407 {
3408 edits.push((selection.start..selection.start, text.clone()));
3409 edits.push((
3410 selection.end..selection.end,
3411 bracket_pair.end.as_str().into(),
3412 ));
3413 bracket_inserted = true;
3414 new_selections.push((
3415 Selection {
3416 id: selection.id,
3417 start: snapshot.anchor_after(selection.start),
3418 end: snapshot.anchor_before(selection.end),
3419 reversed: selection.reversed,
3420 goal: selection.goal,
3421 },
3422 0,
3423 ));
3424 continue;
3425 }
3426 }
3427 }
3428
3429 if self.auto_replace_emoji_shortcode
3430 && selection.is_empty()
3431 && text.as_ref().ends_with(':')
3432 {
3433 if let Some(possible_emoji_short_code) =
3434 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3435 {
3436 if !possible_emoji_short_code.is_empty() {
3437 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3438 let emoji_shortcode_start = Point::new(
3439 selection.start.row,
3440 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3441 );
3442
3443 // Remove shortcode from buffer
3444 edits.push((
3445 emoji_shortcode_start..selection.start,
3446 "".to_string().into(),
3447 ));
3448 new_selections.push((
3449 Selection {
3450 id: selection.id,
3451 start: snapshot.anchor_after(emoji_shortcode_start),
3452 end: snapshot.anchor_before(selection.start),
3453 reversed: selection.reversed,
3454 goal: selection.goal,
3455 },
3456 0,
3457 ));
3458
3459 // Insert emoji
3460 let selection_start_anchor = snapshot.anchor_after(selection.start);
3461 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3462 edits.push((selection.start..selection.end, emoji.to_string().into()));
3463
3464 continue;
3465 }
3466 }
3467 }
3468 }
3469
3470 // If not handling any auto-close operation, then just replace the selected
3471 // text with the given input and move the selection to the end of the
3472 // newly inserted text.
3473 let anchor = snapshot.anchor_after(selection.end);
3474 if !self.linked_edit_ranges.is_empty() {
3475 let start_anchor = snapshot.anchor_before(selection.start);
3476
3477 let is_word_char = text.chars().next().map_or(true, |char| {
3478 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3479 classifier.is_word(char)
3480 });
3481
3482 if is_word_char {
3483 if let Some(ranges) = self
3484 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3485 {
3486 for (buffer, edits) in ranges {
3487 linked_edits
3488 .entry(buffer.clone())
3489 .or_default()
3490 .extend(edits.into_iter().map(|range| (range, text.clone())));
3491 }
3492 }
3493 } else {
3494 clear_linked_edit_ranges = true;
3495 }
3496 }
3497
3498 new_selections.push((selection.map(|_| anchor), 0));
3499 edits.push((selection.start..selection.end, text.clone()));
3500 }
3501
3502 drop(snapshot);
3503
3504 self.transact(window, cx, |this, window, cx| {
3505 if clear_linked_edit_ranges {
3506 this.linked_edit_ranges.clear();
3507 }
3508 let initial_buffer_versions =
3509 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3510
3511 this.buffer.update(cx, |buffer, cx| {
3512 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3513 });
3514 for (buffer, edits) in linked_edits {
3515 buffer.update(cx, |buffer, cx| {
3516 let snapshot = buffer.snapshot();
3517 let edits = edits
3518 .into_iter()
3519 .map(|(range, text)| {
3520 use text::ToPoint as TP;
3521 let end_point = TP::to_point(&range.end, &snapshot);
3522 let start_point = TP::to_point(&range.start, &snapshot);
3523 (start_point..end_point, text)
3524 })
3525 .sorted_by_key(|(range, _)| range.start);
3526 buffer.edit(edits, None, cx);
3527 })
3528 }
3529 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3530 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3531 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3532 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3533 .zip(new_selection_deltas)
3534 .map(|(selection, delta)| Selection {
3535 id: selection.id,
3536 start: selection.start + delta,
3537 end: selection.end + delta,
3538 reversed: selection.reversed,
3539 goal: SelectionGoal::None,
3540 })
3541 .collect::<Vec<_>>();
3542
3543 let mut i = 0;
3544 for (position, delta, selection_id, pair) in new_autoclose_regions {
3545 let position = position.to_offset(&map.buffer_snapshot) + delta;
3546 let start = map.buffer_snapshot.anchor_before(position);
3547 let end = map.buffer_snapshot.anchor_after(position);
3548 while let Some(existing_state) = this.autoclose_regions.get(i) {
3549 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3550 Ordering::Less => i += 1,
3551 Ordering::Greater => break,
3552 Ordering::Equal => {
3553 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3554 Ordering::Less => i += 1,
3555 Ordering::Equal => break,
3556 Ordering::Greater => break,
3557 }
3558 }
3559 }
3560 }
3561 this.autoclose_regions.insert(
3562 i,
3563 AutocloseRegion {
3564 selection_id,
3565 range: start..end,
3566 pair,
3567 },
3568 );
3569 }
3570
3571 let had_active_inline_completion = this.has_active_inline_completion();
3572 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3573 s.select(new_selections)
3574 });
3575
3576 if !bracket_inserted {
3577 if let Some(on_type_format_task) =
3578 this.trigger_on_type_formatting(text.to_string(), window, cx)
3579 {
3580 on_type_format_task.detach_and_log_err(cx);
3581 }
3582 }
3583
3584 let editor_settings = EditorSettings::get_global(cx);
3585 if bracket_inserted
3586 && (editor_settings.auto_signature_help
3587 || editor_settings.show_signature_help_after_edits)
3588 {
3589 this.show_signature_help(&ShowSignatureHelp, window, cx);
3590 }
3591
3592 let trigger_in_words =
3593 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3594 if this.hard_wrap.is_some() {
3595 let latest: Range<Point> = this.selections.newest(cx).range();
3596 if latest.is_empty()
3597 && this
3598 .buffer()
3599 .read(cx)
3600 .snapshot(cx)
3601 .line_len(MultiBufferRow(latest.start.row))
3602 == latest.start.column
3603 {
3604 this.rewrap_impl(
3605 RewrapOptions {
3606 override_language_settings: true,
3607 preserve_existing_whitespace: true,
3608 },
3609 cx,
3610 )
3611 }
3612 }
3613 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3614 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3615 this.refresh_inline_completion(true, false, window, cx);
3616 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3617 });
3618 }
3619
3620 fn find_possible_emoji_shortcode_at_position(
3621 snapshot: &MultiBufferSnapshot,
3622 position: Point,
3623 ) -> Option<String> {
3624 let mut chars = Vec::new();
3625 let mut found_colon = false;
3626 for char in snapshot.reversed_chars_at(position).take(100) {
3627 // Found a possible emoji shortcode in the middle of the buffer
3628 if found_colon {
3629 if char.is_whitespace() {
3630 chars.reverse();
3631 return Some(chars.iter().collect());
3632 }
3633 // If the previous character is not a whitespace, we are in the middle of a word
3634 // and we only want to complete the shortcode if the word is made up of other emojis
3635 let mut containing_word = String::new();
3636 for ch in snapshot
3637 .reversed_chars_at(position)
3638 .skip(chars.len() + 1)
3639 .take(100)
3640 {
3641 if ch.is_whitespace() {
3642 break;
3643 }
3644 containing_word.push(ch);
3645 }
3646 let containing_word = containing_word.chars().rev().collect::<String>();
3647 if util::word_consists_of_emojis(containing_word.as_str()) {
3648 chars.reverse();
3649 return Some(chars.iter().collect());
3650 }
3651 }
3652
3653 if char.is_whitespace() || !char.is_ascii() {
3654 return None;
3655 }
3656 if char == ':' {
3657 found_colon = true;
3658 } else {
3659 chars.push(char);
3660 }
3661 }
3662 // Found a possible emoji shortcode at the beginning of the buffer
3663 chars.reverse();
3664 Some(chars.iter().collect())
3665 }
3666
3667 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3668 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3669 self.transact(window, cx, |this, window, cx| {
3670 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3671 let selections = this.selections.all::<usize>(cx);
3672 let multi_buffer = this.buffer.read(cx);
3673 let buffer = multi_buffer.snapshot(cx);
3674 selections
3675 .iter()
3676 .map(|selection| {
3677 let start_point = selection.start.to_point(&buffer);
3678 let mut indent =
3679 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3680 indent.len = cmp::min(indent.len, start_point.column);
3681 let start = selection.start;
3682 let end = selection.end;
3683 let selection_is_empty = start == end;
3684 let language_scope = buffer.language_scope_at(start);
3685 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3686 &language_scope
3687 {
3688 let insert_extra_newline =
3689 insert_extra_newline_brackets(&buffer, start..end, language)
3690 || insert_extra_newline_tree_sitter(&buffer, start..end);
3691
3692 // Comment extension on newline is allowed only for cursor selections
3693 let comment_delimiter = maybe!({
3694 if !selection_is_empty {
3695 return None;
3696 }
3697
3698 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3699 return None;
3700 }
3701
3702 let delimiters = language.line_comment_prefixes();
3703 let max_len_of_delimiter =
3704 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3705 let (snapshot, range) =
3706 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3707
3708 let mut index_of_first_non_whitespace = 0;
3709 let comment_candidate = snapshot
3710 .chars_for_range(range)
3711 .skip_while(|c| {
3712 let should_skip = c.is_whitespace();
3713 if should_skip {
3714 index_of_first_non_whitespace += 1;
3715 }
3716 should_skip
3717 })
3718 .take(max_len_of_delimiter)
3719 .collect::<String>();
3720 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3721 comment_candidate.starts_with(comment_prefix.as_ref())
3722 })?;
3723 let cursor_is_placed_after_comment_marker =
3724 index_of_first_non_whitespace + comment_prefix.len()
3725 <= start_point.column as usize;
3726 if cursor_is_placed_after_comment_marker {
3727 Some(comment_prefix.clone())
3728 } else {
3729 None
3730 }
3731 });
3732 (comment_delimiter, insert_extra_newline)
3733 } else {
3734 (None, false)
3735 };
3736
3737 let capacity_for_delimiter = comment_delimiter
3738 .as_deref()
3739 .map(str::len)
3740 .unwrap_or_default();
3741 let mut new_text =
3742 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3743 new_text.push('\n');
3744 new_text.extend(indent.chars());
3745 if let Some(delimiter) = &comment_delimiter {
3746 new_text.push_str(delimiter);
3747 }
3748 if insert_extra_newline {
3749 new_text = new_text.repeat(2);
3750 }
3751
3752 let anchor = buffer.anchor_after(end);
3753 let new_selection = selection.map(|_| anchor);
3754 (
3755 (start..end, new_text),
3756 (insert_extra_newline, new_selection),
3757 )
3758 })
3759 .unzip()
3760 };
3761
3762 this.edit_with_autoindent(edits, cx);
3763 let buffer = this.buffer.read(cx).snapshot(cx);
3764 let new_selections = selection_fixup_info
3765 .into_iter()
3766 .map(|(extra_newline_inserted, new_selection)| {
3767 let mut cursor = new_selection.end.to_point(&buffer);
3768 if extra_newline_inserted {
3769 cursor.row -= 1;
3770 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3771 }
3772 new_selection.map(|_| cursor)
3773 })
3774 .collect();
3775
3776 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3777 s.select(new_selections)
3778 });
3779 this.refresh_inline_completion(true, false, window, cx);
3780 });
3781 }
3782
3783 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3784 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3785
3786 let buffer = self.buffer.read(cx);
3787 let snapshot = buffer.snapshot(cx);
3788
3789 let mut edits = Vec::new();
3790 let mut rows = Vec::new();
3791
3792 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3793 let cursor = selection.head();
3794 let row = cursor.row;
3795
3796 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3797
3798 let newline = "\n".to_string();
3799 edits.push((start_of_line..start_of_line, newline));
3800
3801 rows.push(row + rows_inserted as u32);
3802 }
3803
3804 self.transact(window, cx, |editor, window, cx| {
3805 editor.edit(edits, cx);
3806
3807 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3808 let mut index = 0;
3809 s.move_cursors_with(|map, _, _| {
3810 let row = rows[index];
3811 index += 1;
3812
3813 let point = Point::new(row, 0);
3814 let boundary = map.next_line_boundary(point).1;
3815 let clipped = map.clip_point(boundary, Bias::Left);
3816
3817 (clipped, SelectionGoal::None)
3818 });
3819 });
3820
3821 let mut indent_edits = Vec::new();
3822 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3823 for row in rows {
3824 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3825 for (row, indent) in indents {
3826 if indent.len == 0 {
3827 continue;
3828 }
3829
3830 let text = match indent.kind {
3831 IndentKind::Space => " ".repeat(indent.len as usize),
3832 IndentKind::Tab => "\t".repeat(indent.len as usize),
3833 };
3834 let point = Point::new(row.0, 0);
3835 indent_edits.push((point..point, text));
3836 }
3837 }
3838 editor.edit(indent_edits, cx);
3839 });
3840 }
3841
3842 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3843 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3844
3845 let buffer = self.buffer.read(cx);
3846 let snapshot = buffer.snapshot(cx);
3847
3848 let mut edits = Vec::new();
3849 let mut rows = Vec::new();
3850 let mut rows_inserted = 0;
3851
3852 for selection in self.selections.all_adjusted(cx) {
3853 let cursor = selection.head();
3854 let row = cursor.row;
3855
3856 let point = Point::new(row + 1, 0);
3857 let start_of_line = snapshot.clip_point(point, Bias::Left);
3858
3859 let newline = "\n".to_string();
3860 edits.push((start_of_line..start_of_line, newline));
3861
3862 rows_inserted += 1;
3863 rows.push(row + rows_inserted);
3864 }
3865
3866 self.transact(window, cx, |editor, window, cx| {
3867 editor.edit(edits, cx);
3868
3869 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3870 let mut index = 0;
3871 s.move_cursors_with(|map, _, _| {
3872 let row = rows[index];
3873 index += 1;
3874
3875 let point = Point::new(row, 0);
3876 let boundary = map.next_line_boundary(point).1;
3877 let clipped = map.clip_point(boundary, Bias::Left);
3878
3879 (clipped, SelectionGoal::None)
3880 });
3881 });
3882
3883 let mut indent_edits = Vec::new();
3884 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3885 for row in rows {
3886 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3887 for (row, indent) in indents {
3888 if indent.len == 0 {
3889 continue;
3890 }
3891
3892 let text = match indent.kind {
3893 IndentKind::Space => " ".repeat(indent.len as usize),
3894 IndentKind::Tab => "\t".repeat(indent.len as usize),
3895 };
3896 let point = Point::new(row.0, 0);
3897 indent_edits.push((point..point, text));
3898 }
3899 }
3900 editor.edit(indent_edits, cx);
3901 });
3902 }
3903
3904 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3905 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3906 original_indent_columns: Vec::new(),
3907 });
3908 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3909 }
3910
3911 fn insert_with_autoindent_mode(
3912 &mut self,
3913 text: &str,
3914 autoindent_mode: Option<AutoindentMode>,
3915 window: &mut Window,
3916 cx: &mut Context<Self>,
3917 ) {
3918 if self.read_only(cx) {
3919 return;
3920 }
3921
3922 let text: Arc<str> = text.into();
3923 self.transact(window, cx, |this, window, cx| {
3924 let old_selections = this.selections.all_adjusted(cx);
3925 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3926 let anchors = {
3927 let snapshot = buffer.read(cx);
3928 old_selections
3929 .iter()
3930 .map(|s| {
3931 let anchor = snapshot.anchor_after(s.head());
3932 s.map(|_| anchor)
3933 })
3934 .collect::<Vec<_>>()
3935 };
3936 buffer.edit(
3937 old_selections
3938 .iter()
3939 .map(|s| (s.start..s.end, text.clone())),
3940 autoindent_mode,
3941 cx,
3942 );
3943 anchors
3944 });
3945
3946 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3947 s.select_anchors(selection_anchors);
3948 });
3949
3950 cx.notify();
3951 });
3952 }
3953
3954 fn trigger_completion_on_input(
3955 &mut self,
3956 text: &str,
3957 trigger_in_words: bool,
3958 window: &mut Window,
3959 cx: &mut Context<Self>,
3960 ) {
3961 let ignore_completion_provider = self
3962 .context_menu
3963 .borrow()
3964 .as_ref()
3965 .map(|menu| match menu {
3966 CodeContextMenu::Completions(completions_menu) => {
3967 completions_menu.ignore_completion_provider
3968 }
3969 CodeContextMenu::CodeActions(_) => false,
3970 })
3971 .unwrap_or(false);
3972
3973 if ignore_completion_provider {
3974 self.show_word_completions(&ShowWordCompletions, window, cx);
3975 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3976 self.show_completions(
3977 &ShowCompletions {
3978 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3979 },
3980 window,
3981 cx,
3982 );
3983 } else {
3984 self.hide_context_menu(window, cx);
3985 }
3986 }
3987
3988 fn is_completion_trigger(
3989 &self,
3990 text: &str,
3991 trigger_in_words: bool,
3992 cx: &mut Context<Self>,
3993 ) -> bool {
3994 let position = self.selections.newest_anchor().head();
3995 let multibuffer = self.buffer.read(cx);
3996 let Some(buffer) = position
3997 .buffer_id
3998 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3999 else {
4000 return false;
4001 };
4002
4003 if let Some(completion_provider) = &self.completion_provider {
4004 completion_provider.is_completion_trigger(
4005 &buffer,
4006 position.text_anchor,
4007 text,
4008 trigger_in_words,
4009 cx,
4010 )
4011 } else {
4012 false
4013 }
4014 }
4015
4016 /// If any empty selections is touching the start of its innermost containing autoclose
4017 /// region, expand it to select the brackets.
4018 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4019 let selections = self.selections.all::<usize>(cx);
4020 let buffer = self.buffer.read(cx).read(cx);
4021 let new_selections = self
4022 .selections_with_autoclose_regions(selections, &buffer)
4023 .map(|(mut selection, region)| {
4024 if !selection.is_empty() {
4025 return selection;
4026 }
4027
4028 if let Some(region) = region {
4029 let mut range = region.range.to_offset(&buffer);
4030 if selection.start == range.start && range.start >= region.pair.start.len() {
4031 range.start -= region.pair.start.len();
4032 if buffer.contains_str_at(range.start, ®ion.pair.start)
4033 && buffer.contains_str_at(range.end, ®ion.pair.end)
4034 {
4035 range.end += region.pair.end.len();
4036 selection.start = range.start;
4037 selection.end = range.end;
4038
4039 return selection;
4040 }
4041 }
4042 }
4043
4044 let always_treat_brackets_as_autoclosed = buffer
4045 .language_settings_at(selection.start, cx)
4046 .always_treat_brackets_as_autoclosed;
4047
4048 if !always_treat_brackets_as_autoclosed {
4049 return selection;
4050 }
4051
4052 if let Some(scope) = buffer.language_scope_at(selection.start) {
4053 for (pair, enabled) in scope.brackets() {
4054 if !enabled || !pair.close {
4055 continue;
4056 }
4057
4058 if buffer.contains_str_at(selection.start, &pair.end) {
4059 let pair_start_len = pair.start.len();
4060 if buffer.contains_str_at(
4061 selection.start.saturating_sub(pair_start_len),
4062 &pair.start,
4063 ) {
4064 selection.start -= pair_start_len;
4065 selection.end += pair.end.len();
4066
4067 return selection;
4068 }
4069 }
4070 }
4071 }
4072
4073 selection
4074 })
4075 .collect();
4076
4077 drop(buffer);
4078 self.change_selections(None, window, cx, |selections| {
4079 selections.select(new_selections)
4080 });
4081 }
4082
4083 /// Iterate the given selections, and for each one, find the smallest surrounding
4084 /// autoclose region. This uses the ordering of the selections and the autoclose
4085 /// regions to avoid repeated comparisons.
4086 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4087 &'a self,
4088 selections: impl IntoIterator<Item = Selection<D>>,
4089 buffer: &'a MultiBufferSnapshot,
4090 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4091 let mut i = 0;
4092 let mut regions = self.autoclose_regions.as_slice();
4093 selections.into_iter().map(move |selection| {
4094 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4095
4096 let mut enclosing = None;
4097 while let Some(pair_state) = regions.get(i) {
4098 if pair_state.range.end.to_offset(buffer) < range.start {
4099 regions = ®ions[i + 1..];
4100 i = 0;
4101 } else if pair_state.range.start.to_offset(buffer) > range.end {
4102 break;
4103 } else {
4104 if pair_state.selection_id == selection.id {
4105 enclosing = Some(pair_state);
4106 }
4107 i += 1;
4108 }
4109 }
4110
4111 (selection, enclosing)
4112 })
4113 }
4114
4115 /// Remove any autoclose regions that no longer contain their selection.
4116 fn invalidate_autoclose_regions(
4117 &mut self,
4118 mut selections: &[Selection<Anchor>],
4119 buffer: &MultiBufferSnapshot,
4120 ) {
4121 self.autoclose_regions.retain(|state| {
4122 let mut i = 0;
4123 while let Some(selection) = selections.get(i) {
4124 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4125 selections = &selections[1..];
4126 continue;
4127 }
4128 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4129 break;
4130 }
4131 if selection.id == state.selection_id {
4132 return true;
4133 } else {
4134 i += 1;
4135 }
4136 }
4137 false
4138 });
4139 }
4140
4141 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4142 let offset = position.to_offset(buffer);
4143 let (word_range, kind) = buffer.surrounding_word(offset, true);
4144 if offset > word_range.start && kind == Some(CharKind::Word) {
4145 Some(
4146 buffer
4147 .text_for_range(word_range.start..offset)
4148 .collect::<String>(),
4149 )
4150 } else {
4151 None
4152 }
4153 }
4154
4155 pub fn toggle_inlay_hints(
4156 &mut self,
4157 _: &ToggleInlayHints,
4158 _: &mut Window,
4159 cx: &mut Context<Self>,
4160 ) {
4161 self.refresh_inlay_hints(
4162 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4163 cx,
4164 );
4165 }
4166
4167 pub fn inlay_hints_enabled(&self) -> bool {
4168 self.inlay_hint_cache.enabled
4169 }
4170
4171 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4172 if self.semantics_provider.is_none() || !self.mode.is_full() {
4173 return;
4174 }
4175
4176 let reason_description = reason.description();
4177 let ignore_debounce = matches!(
4178 reason,
4179 InlayHintRefreshReason::SettingsChange(_)
4180 | InlayHintRefreshReason::Toggle(_)
4181 | InlayHintRefreshReason::ExcerptsRemoved(_)
4182 | InlayHintRefreshReason::ModifiersChanged(_)
4183 );
4184 let (invalidate_cache, required_languages) = match reason {
4185 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4186 match self.inlay_hint_cache.modifiers_override(enabled) {
4187 Some(enabled) => {
4188 if enabled {
4189 (InvalidationStrategy::RefreshRequested, None)
4190 } else {
4191 self.splice_inlays(
4192 &self
4193 .visible_inlay_hints(cx)
4194 .iter()
4195 .map(|inlay| inlay.id)
4196 .collect::<Vec<InlayId>>(),
4197 Vec::new(),
4198 cx,
4199 );
4200 return;
4201 }
4202 }
4203 None => return,
4204 }
4205 }
4206 InlayHintRefreshReason::Toggle(enabled) => {
4207 if self.inlay_hint_cache.toggle(enabled) {
4208 if enabled {
4209 (InvalidationStrategy::RefreshRequested, None)
4210 } else {
4211 self.splice_inlays(
4212 &self
4213 .visible_inlay_hints(cx)
4214 .iter()
4215 .map(|inlay| inlay.id)
4216 .collect::<Vec<InlayId>>(),
4217 Vec::new(),
4218 cx,
4219 );
4220 return;
4221 }
4222 } else {
4223 return;
4224 }
4225 }
4226 InlayHintRefreshReason::SettingsChange(new_settings) => {
4227 match self.inlay_hint_cache.update_settings(
4228 &self.buffer,
4229 new_settings,
4230 self.visible_inlay_hints(cx),
4231 cx,
4232 ) {
4233 ControlFlow::Break(Some(InlaySplice {
4234 to_remove,
4235 to_insert,
4236 })) => {
4237 self.splice_inlays(&to_remove, to_insert, cx);
4238 return;
4239 }
4240 ControlFlow::Break(None) => return,
4241 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4242 }
4243 }
4244 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4245 if let Some(InlaySplice {
4246 to_remove,
4247 to_insert,
4248 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4249 {
4250 self.splice_inlays(&to_remove, to_insert, cx);
4251 }
4252 self.display_map.update(cx, |display_map, _| {
4253 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4254 });
4255 return;
4256 }
4257 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4258 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4259 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4260 }
4261 InlayHintRefreshReason::RefreshRequested => {
4262 (InvalidationStrategy::RefreshRequested, None)
4263 }
4264 };
4265
4266 if let Some(InlaySplice {
4267 to_remove,
4268 to_insert,
4269 }) = self.inlay_hint_cache.spawn_hint_refresh(
4270 reason_description,
4271 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4272 invalidate_cache,
4273 ignore_debounce,
4274 cx,
4275 ) {
4276 self.splice_inlays(&to_remove, to_insert, cx);
4277 }
4278 }
4279
4280 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4281 self.display_map
4282 .read(cx)
4283 .current_inlays()
4284 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4285 .cloned()
4286 .collect()
4287 }
4288
4289 pub fn excerpts_for_inlay_hints_query(
4290 &self,
4291 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4292 cx: &mut Context<Editor>,
4293 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4294 let Some(project) = self.project.as_ref() else {
4295 return HashMap::default();
4296 };
4297 let project = project.read(cx);
4298 let multi_buffer = self.buffer().read(cx);
4299 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4300 let multi_buffer_visible_start = self
4301 .scroll_manager
4302 .anchor()
4303 .anchor
4304 .to_point(&multi_buffer_snapshot);
4305 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4306 multi_buffer_visible_start
4307 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4308 Bias::Left,
4309 );
4310 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4311 multi_buffer_snapshot
4312 .range_to_buffer_ranges(multi_buffer_visible_range)
4313 .into_iter()
4314 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4315 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4316 let buffer_file = project::File::from_dyn(buffer.file())?;
4317 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4318 let worktree_entry = buffer_worktree
4319 .read(cx)
4320 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4321 if worktree_entry.is_ignored {
4322 return None;
4323 }
4324
4325 let language = buffer.language()?;
4326 if let Some(restrict_to_languages) = restrict_to_languages {
4327 if !restrict_to_languages.contains(language) {
4328 return None;
4329 }
4330 }
4331 Some((
4332 excerpt_id,
4333 (
4334 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4335 buffer.version().clone(),
4336 excerpt_visible_range,
4337 ),
4338 ))
4339 })
4340 .collect()
4341 }
4342
4343 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4344 TextLayoutDetails {
4345 text_system: window.text_system().clone(),
4346 editor_style: self.style.clone().unwrap(),
4347 rem_size: window.rem_size(),
4348 scroll_anchor: self.scroll_manager.anchor(),
4349 visible_rows: self.visible_line_count(),
4350 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4351 }
4352 }
4353
4354 pub fn splice_inlays(
4355 &self,
4356 to_remove: &[InlayId],
4357 to_insert: Vec<Inlay>,
4358 cx: &mut Context<Self>,
4359 ) {
4360 self.display_map.update(cx, |display_map, cx| {
4361 display_map.splice_inlays(to_remove, to_insert, cx)
4362 });
4363 cx.notify();
4364 }
4365
4366 fn trigger_on_type_formatting(
4367 &self,
4368 input: String,
4369 window: &mut Window,
4370 cx: &mut Context<Self>,
4371 ) -> Option<Task<Result<()>>> {
4372 if input.len() != 1 {
4373 return None;
4374 }
4375
4376 let project = self.project.as_ref()?;
4377 let position = self.selections.newest_anchor().head();
4378 let (buffer, buffer_position) = self
4379 .buffer
4380 .read(cx)
4381 .text_anchor_for_position(position, cx)?;
4382
4383 let settings = language_settings::language_settings(
4384 buffer
4385 .read(cx)
4386 .language_at(buffer_position)
4387 .map(|l| l.name()),
4388 buffer.read(cx).file(),
4389 cx,
4390 );
4391 if !settings.use_on_type_format {
4392 return None;
4393 }
4394
4395 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4396 // hence we do LSP request & edit on host side only — add formats to host's history.
4397 let push_to_lsp_host_history = true;
4398 // If this is not the host, append its history with new edits.
4399 let push_to_client_history = project.read(cx).is_via_collab();
4400
4401 let on_type_formatting = project.update(cx, |project, cx| {
4402 project.on_type_format(
4403 buffer.clone(),
4404 buffer_position,
4405 input,
4406 push_to_lsp_host_history,
4407 cx,
4408 )
4409 });
4410 Some(cx.spawn_in(window, async move |editor, cx| {
4411 if let Some(transaction) = on_type_formatting.await? {
4412 if push_to_client_history {
4413 buffer
4414 .update(cx, |buffer, _| {
4415 buffer.push_transaction(transaction, Instant::now());
4416 buffer.finalize_last_transaction();
4417 })
4418 .ok();
4419 }
4420 editor.update(cx, |editor, cx| {
4421 editor.refresh_document_highlights(cx);
4422 })?;
4423 }
4424 Ok(())
4425 }))
4426 }
4427
4428 pub fn show_word_completions(
4429 &mut self,
4430 _: &ShowWordCompletions,
4431 window: &mut Window,
4432 cx: &mut Context<Self>,
4433 ) {
4434 self.open_completions_menu(true, None, window, cx);
4435 }
4436
4437 pub fn show_completions(
4438 &mut self,
4439 options: &ShowCompletions,
4440 window: &mut Window,
4441 cx: &mut Context<Self>,
4442 ) {
4443 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4444 }
4445
4446 fn open_completions_menu(
4447 &mut self,
4448 ignore_completion_provider: bool,
4449 trigger: Option<&str>,
4450 window: &mut Window,
4451 cx: &mut Context<Self>,
4452 ) {
4453 if self.pending_rename.is_some() {
4454 return;
4455 }
4456 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4457 return;
4458 }
4459
4460 let position = self.selections.newest_anchor().head();
4461 if position.diff_base_anchor.is_some() {
4462 return;
4463 }
4464 let (buffer, buffer_position) =
4465 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4466 output
4467 } else {
4468 return;
4469 };
4470 let buffer_snapshot = buffer.read(cx).snapshot();
4471 let show_completion_documentation = buffer_snapshot
4472 .settings_at(buffer_position, cx)
4473 .show_completion_documentation;
4474
4475 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4476
4477 let trigger_kind = match trigger {
4478 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4479 CompletionTriggerKind::TRIGGER_CHARACTER
4480 }
4481 _ => CompletionTriggerKind::INVOKED,
4482 };
4483 let completion_context = CompletionContext {
4484 trigger_character: trigger.and_then(|trigger| {
4485 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4486 Some(String::from(trigger))
4487 } else {
4488 None
4489 }
4490 }),
4491 trigger_kind,
4492 };
4493
4494 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4495 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4496 let word_to_exclude = buffer_snapshot
4497 .text_for_range(old_range.clone())
4498 .collect::<String>();
4499 (
4500 buffer_snapshot.anchor_before(old_range.start)
4501 ..buffer_snapshot.anchor_after(old_range.end),
4502 Some(word_to_exclude),
4503 )
4504 } else {
4505 (buffer_position..buffer_position, None)
4506 };
4507
4508 let completion_settings = language_settings(
4509 buffer_snapshot
4510 .language_at(buffer_position)
4511 .map(|language| language.name()),
4512 buffer_snapshot.file(),
4513 cx,
4514 )
4515 .completions;
4516
4517 // The document can be large, so stay in reasonable bounds when searching for words,
4518 // otherwise completion pop-up might be slow to appear.
4519 const WORD_LOOKUP_ROWS: u32 = 5_000;
4520 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4521 let min_word_search = buffer_snapshot.clip_point(
4522 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4523 Bias::Left,
4524 );
4525 let max_word_search = buffer_snapshot.clip_point(
4526 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4527 Bias::Right,
4528 );
4529 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4530 ..buffer_snapshot.point_to_offset(max_word_search);
4531
4532 let provider = self
4533 .completion_provider
4534 .as_ref()
4535 .filter(|_| !ignore_completion_provider);
4536 let skip_digits = query
4537 .as_ref()
4538 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4539
4540 let (mut words, provided_completions) = match provider {
4541 Some(provider) => {
4542 let completions = provider.completions(
4543 position.excerpt_id,
4544 &buffer,
4545 buffer_position,
4546 completion_context,
4547 window,
4548 cx,
4549 );
4550
4551 let words = match completion_settings.words {
4552 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4553 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4554 .background_spawn(async move {
4555 buffer_snapshot.words_in_range(WordsQuery {
4556 fuzzy_contents: None,
4557 range: word_search_range,
4558 skip_digits,
4559 })
4560 }),
4561 };
4562
4563 (words, completions)
4564 }
4565 None => (
4566 cx.background_spawn(async move {
4567 buffer_snapshot.words_in_range(WordsQuery {
4568 fuzzy_contents: None,
4569 range: word_search_range,
4570 skip_digits,
4571 })
4572 }),
4573 Task::ready(Ok(None)),
4574 ),
4575 };
4576
4577 let sort_completions = provider
4578 .as_ref()
4579 .map_or(false, |provider| provider.sort_completions());
4580
4581 let filter_completions = provider
4582 .as_ref()
4583 .map_or(true, |provider| provider.filter_completions());
4584
4585 let id = post_inc(&mut self.next_completion_id);
4586 let task = cx.spawn_in(window, async move |editor, cx| {
4587 async move {
4588 editor.update(cx, |this, _| {
4589 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4590 })?;
4591
4592 let mut completions = Vec::new();
4593 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4594 completions.extend(provided_completions);
4595 if completion_settings.words == WordsCompletionMode::Fallback {
4596 words = Task::ready(BTreeMap::default());
4597 }
4598 }
4599
4600 let mut words = words.await;
4601 if let Some(word_to_exclude) = &word_to_exclude {
4602 words.remove(word_to_exclude);
4603 }
4604 for lsp_completion in &completions {
4605 words.remove(&lsp_completion.new_text);
4606 }
4607 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4608 replace_range: old_range.clone(),
4609 new_text: word.clone(),
4610 label: CodeLabel::plain(word, None),
4611 icon_path: None,
4612 documentation: None,
4613 source: CompletionSource::BufferWord {
4614 word_range,
4615 resolved: false,
4616 },
4617 insert_text_mode: Some(InsertTextMode::AS_IS),
4618 confirm: None,
4619 }));
4620
4621 let menu = if completions.is_empty() {
4622 None
4623 } else {
4624 let mut menu = CompletionsMenu::new(
4625 id,
4626 sort_completions,
4627 show_completion_documentation,
4628 ignore_completion_provider,
4629 position,
4630 buffer.clone(),
4631 completions.into(),
4632 );
4633
4634 menu.filter(
4635 if filter_completions {
4636 query.as_deref()
4637 } else {
4638 None
4639 },
4640 cx.background_executor().clone(),
4641 )
4642 .await;
4643
4644 menu.visible().then_some(menu)
4645 };
4646
4647 editor.update_in(cx, |editor, window, cx| {
4648 match editor.context_menu.borrow().as_ref() {
4649 None => {}
4650 Some(CodeContextMenu::Completions(prev_menu)) => {
4651 if prev_menu.id > id {
4652 return;
4653 }
4654 }
4655 _ => return,
4656 }
4657
4658 if editor.focus_handle.is_focused(window) && menu.is_some() {
4659 let mut menu = menu.unwrap();
4660 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4661
4662 *editor.context_menu.borrow_mut() =
4663 Some(CodeContextMenu::Completions(menu));
4664
4665 if editor.show_edit_predictions_in_menu() {
4666 editor.update_visible_inline_completion(window, cx);
4667 } else {
4668 editor.discard_inline_completion(false, cx);
4669 }
4670
4671 cx.notify();
4672 } else if editor.completion_tasks.len() <= 1 {
4673 // If there are no more completion tasks and the last menu was
4674 // empty, we should hide it.
4675 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4676 // If it was already hidden and we don't show inline
4677 // completions in the menu, we should also show the
4678 // inline-completion when available.
4679 if was_hidden && editor.show_edit_predictions_in_menu() {
4680 editor.update_visible_inline_completion(window, cx);
4681 }
4682 }
4683 })?;
4684
4685 anyhow::Ok(())
4686 }
4687 .log_err()
4688 .await
4689 });
4690
4691 self.completion_tasks.push((id, task));
4692 }
4693
4694 #[cfg(feature = "test-support")]
4695 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4696 let menu = self.context_menu.borrow();
4697 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4698 let completions = menu.completions.borrow();
4699 Some(completions.to_vec())
4700 } else {
4701 None
4702 }
4703 }
4704
4705 pub fn confirm_completion(
4706 &mut self,
4707 action: &ConfirmCompletion,
4708 window: &mut Window,
4709 cx: &mut Context<Self>,
4710 ) -> Option<Task<Result<()>>> {
4711 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4712 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4713 }
4714
4715 pub fn confirm_completion_insert(
4716 &mut self,
4717 _: &ConfirmCompletionInsert,
4718 window: &mut Window,
4719 cx: &mut Context<Self>,
4720 ) -> Option<Task<Result<()>>> {
4721 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4722 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4723 }
4724
4725 pub fn confirm_completion_replace(
4726 &mut self,
4727 _: &ConfirmCompletionReplace,
4728 window: &mut Window,
4729 cx: &mut Context<Self>,
4730 ) -> Option<Task<Result<()>>> {
4731 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4732 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4733 }
4734
4735 pub fn compose_completion(
4736 &mut self,
4737 action: &ComposeCompletion,
4738 window: &mut Window,
4739 cx: &mut Context<Self>,
4740 ) -> Option<Task<Result<()>>> {
4741 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4742 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4743 }
4744
4745 fn do_completion(
4746 &mut self,
4747 item_ix: Option<usize>,
4748 intent: CompletionIntent,
4749 window: &mut Window,
4750 cx: &mut Context<Editor>,
4751 ) -> Option<Task<Result<()>>> {
4752 use language::ToOffset as _;
4753
4754 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4755 else {
4756 return None;
4757 };
4758
4759 let candidate_id = {
4760 let entries = completions_menu.entries.borrow();
4761 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4762 if self.show_edit_predictions_in_menu() {
4763 self.discard_inline_completion(true, cx);
4764 }
4765 mat.candidate_id
4766 };
4767
4768 let buffer_handle = completions_menu.buffer;
4769 let completion = completions_menu
4770 .completions
4771 .borrow()
4772 .get(candidate_id)?
4773 .clone();
4774 cx.stop_propagation();
4775
4776 let snippet;
4777 let new_text;
4778 if completion.is_snippet() {
4779 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4780 new_text = snippet.as_ref().unwrap().text.clone();
4781 } else {
4782 snippet = None;
4783 new_text = completion.new_text.clone();
4784 };
4785
4786 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4787 let buffer = buffer_handle.read(cx);
4788 let snapshot = self.buffer.read(cx).snapshot(cx);
4789 let replace_range_multibuffer = {
4790 let excerpt = snapshot
4791 .excerpt_containing(self.selections.newest_anchor().range())
4792 .unwrap();
4793 let multibuffer_anchor = snapshot
4794 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4795 .unwrap()
4796 ..snapshot
4797 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4798 .unwrap();
4799 multibuffer_anchor.start.to_offset(&snapshot)
4800 ..multibuffer_anchor.end.to_offset(&snapshot)
4801 };
4802 let newest_anchor = self.selections.newest_anchor();
4803 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4804 return None;
4805 }
4806
4807 let old_text = buffer
4808 .text_for_range(replace_range.clone())
4809 .collect::<String>();
4810 let lookbehind = newest_anchor
4811 .start
4812 .text_anchor
4813 .to_offset(buffer)
4814 .saturating_sub(replace_range.start);
4815 let lookahead = replace_range
4816 .end
4817 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4818 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4819 let suffix = &old_text[lookbehind.min(old_text.len())..];
4820
4821 let selections = self.selections.all::<usize>(cx);
4822 let mut ranges = Vec::new();
4823 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4824
4825 for selection in &selections {
4826 let range = if selection.id == newest_anchor.id {
4827 replace_range_multibuffer.clone()
4828 } else {
4829 let mut range = selection.range();
4830
4831 // if prefix is present, don't duplicate it
4832 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4833 range.start = range.start.saturating_sub(lookbehind);
4834
4835 // if suffix is also present, mimic the newest cursor and replace it
4836 if selection.id != newest_anchor.id
4837 && snapshot.contains_str_at(range.end, suffix)
4838 {
4839 range.end += lookahead;
4840 }
4841 }
4842 range
4843 };
4844
4845 ranges.push(range);
4846
4847 if !self.linked_edit_ranges.is_empty() {
4848 let start_anchor = snapshot.anchor_before(selection.head());
4849 let end_anchor = snapshot.anchor_after(selection.tail());
4850 if let Some(ranges) = self
4851 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4852 {
4853 for (buffer, edits) in ranges {
4854 linked_edits
4855 .entry(buffer.clone())
4856 .or_default()
4857 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4858 }
4859 }
4860 }
4861 }
4862
4863 cx.emit(EditorEvent::InputHandled {
4864 utf16_range_to_replace: None,
4865 text: new_text.clone().into(),
4866 });
4867
4868 self.transact(window, cx, |this, window, cx| {
4869 if let Some(mut snippet) = snippet {
4870 snippet.text = new_text.to_string();
4871 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4872 } else {
4873 this.buffer.update(cx, |buffer, cx| {
4874 let auto_indent = match completion.insert_text_mode {
4875 Some(InsertTextMode::AS_IS) => None,
4876 _ => this.autoindent_mode.clone(),
4877 };
4878 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4879 buffer.edit(edits, auto_indent, cx);
4880 });
4881 }
4882 for (buffer, edits) in linked_edits {
4883 buffer.update(cx, |buffer, cx| {
4884 let snapshot = buffer.snapshot();
4885 let edits = edits
4886 .into_iter()
4887 .map(|(range, text)| {
4888 use text::ToPoint as TP;
4889 let end_point = TP::to_point(&range.end, &snapshot);
4890 let start_point = TP::to_point(&range.start, &snapshot);
4891 (start_point..end_point, text)
4892 })
4893 .sorted_by_key(|(range, _)| range.start);
4894 buffer.edit(edits, None, cx);
4895 })
4896 }
4897
4898 this.refresh_inline_completion(true, false, window, cx);
4899 });
4900
4901 let show_new_completions_on_confirm = completion
4902 .confirm
4903 .as_ref()
4904 .map_or(false, |confirm| confirm(intent, window, cx));
4905 if show_new_completions_on_confirm {
4906 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4907 }
4908
4909 let provider = self.completion_provider.as_ref()?;
4910 drop(completion);
4911 let apply_edits = provider.apply_additional_edits_for_completion(
4912 buffer_handle,
4913 completions_menu.completions.clone(),
4914 candidate_id,
4915 true,
4916 cx,
4917 );
4918
4919 let editor_settings = EditorSettings::get_global(cx);
4920 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4921 // After the code completion is finished, users often want to know what signatures are needed.
4922 // so we should automatically call signature_help
4923 self.show_signature_help(&ShowSignatureHelp, window, cx);
4924 }
4925
4926 Some(cx.foreground_executor().spawn(async move {
4927 apply_edits.await?;
4928 Ok(())
4929 }))
4930 }
4931
4932 pub fn toggle_code_actions(
4933 &mut self,
4934 action: &ToggleCodeActions,
4935 window: &mut Window,
4936 cx: &mut Context<Self>,
4937 ) {
4938 let mut context_menu = self.context_menu.borrow_mut();
4939 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4940 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4941 // Toggle if we're selecting the same one
4942 *context_menu = None;
4943 cx.notify();
4944 return;
4945 } else {
4946 // Otherwise, clear it and start a new one
4947 *context_menu = None;
4948 cx.notify();
4949 }
4950 }
4951 drop(context_menu);
4952 let snapshot = self.snapshot(window, cx);
4953 let deployed_from_indicator = action.deployed_from_indicator;
4954 let mut task = self.code_actions_task.take();
4955 let action = action.clone();
4956 cx.spawn_in(window, async move |editor, cx| {
4957 while let Some(prev_task) = task {
4958 prev_task.await.log_err();
4959 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4960 }
4961
4962 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4963 if editor.focus_handle.is_focused(window) {
4964 let multibuffer_point = action
4965 .deployed_from_indicator
4966 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4967 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4968 let (buffer, buffer_row) = snapshot
4969 .buffer_snapshot
4970 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4971 .and_then(|(buffer_snapshot, range)| {
4972 editor
4973 .buffer
4974 .read(cx)
4975 .buffer(buffer_snapshot.remote_id())
4976 .map(|buffer| (buffer, range.start.row))
4977 })?;
4978 let (_, code_actions) = editor
4979 .available_code_actions
4980 .clone()
4981 .and_then(|(location, code_actions)| {
4982 let snapshot = location.buffer.read(cx).snapshot();
4983 let point_range = location.range.to_point(&snapshot);
4984 let point_range = point_range.start.row..=point_range.end.row;
4985 if point_range.contains(&buffer_row) {
4986 Some((location, code_actions))
4987 } else {
4988 None
4989 }
4990 })
4991 .unzip();
4992 let buffer_id = buffer.read(cx).remote_id();
4993 let tasks = editor
4994 .tasks
4995 .get(&(buffer_id, buffer_row))
4996 .map(|t| Arc::new(t.to_owned()));
4997 if tasks.is_none() && code_actions.is_none() {
4998 return None;
4999 }
5000
5001 editor.completion_tasks.clear();
5002 editor.discard_inline_completion(false, cx);
5003 let task_context =
5004 tasks
5005 .as_ref()
5006 .zip(editor.project.clone())
5007 .map(|(tasks, project)| {
5008 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5009 });
5010
5011 let debugger_flag = cx.has_flag::<Debugger>();
5012
5013 Some(cx.spawn_in(window, async move |editor, cx| {
5014 let task_context = match task_context {
5015 Some(task_context) => task_context.await,
5016 None => None,
5017 };
5018 let resolved_tasks =
5019 tasks
5020 .zip(task_context)
5021 .map(|(tasks, task_context)| ResolvedTasks {
5022 templates: tasks.resolve(&task_context).collect(),
5023 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5024 multibuffer_point.row,
5025 tasks.column,
5026 )),
5027 });
5028 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
5029 tasks
5030 .templates
5031 .iter()
5032 .filter(|task| {
5033 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5034 debugger_flag
5035 } else {
5036 true
5037 }
5038 })
5039 .count()
5040 == 1
5041 }) && code_actions
5042 .as_ref()
5043 .map_or(true, |actions| actions.is_empty());
5044 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5045 *editor.context_menu.borrow_mut() =
5046 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5047 buffer,
5048 actions: CodeActionContents::new(
5049 resolved_tasks,
5050 code_actions,
5051 cx,
5052 ),
5053 selected_item: Default::default(),
5054 scroll_handle: UniformListScrollHandle::default(),
5055 deployed_from_indicator,
5056 }));
5057 if spawn_straight_away {
5058 if let Some(task) = editor.confirm_code_action(
5059 &ConfirmCodeAction { item_ix: Some(0) },
5060 window,
5061 cx,
5062 ) {
5063 cx.notify();
5064 return task;
5065 }
5066 }
5067 cx.notify();
5068 Task::ready(Ok(()))
5069 }) {
5070 task.await
5071 } else {
5072 Ok(())
5073 }
5074 }))
5075 } else {
5076 Some(Task::ready(Ok(())))
5077 }
5078 })?;
5079 if let Some(task) = spawned_test_task {
5080 task.await?;
5081 }
5082
5083 Ok::<_, anyhow::Error>(())
5084 })
5085 .detach_and_log_err(cx);
5086 }
5087
5088 pub fn confirm_code_action(
5089 &mut self,
5090 action: &ConfirmCodeAction,
5091 window: &mut Window,
5092 cx: &mut Context<Self>,
5093 ) -> Option<Task<Result<()>>> {
5094 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5095
5096 let actions_menu =
5097 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5098 menu
5099 } else {
5100 return None;
5101 };
5102
5103 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5104 let action = actions_menu.actions.get(action_ix)?;
5105 let title = action.label();
5106 let buffer = actions_menu.buffer;
5107 let workspace = self.workspace()?;
5108
5109 match action {
5110 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5111 match resolved_task.task_type() {
5112 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5113 workspace::tasks::schedule_resolved_task(
5114 workspace,
5115 task_source_kind,
5116 resolved_task,
5117 false,
5118 cx,
5119 );
5120
5121 Some(Task::ready(Ok(())))
5122 }),
5123 task::TaskType::Debug(debug_args) => {
5124 if debug_args.locator.is_some() {
5125 workspace.update(cx, |workspace, cx| {
5126 workspace::tasks::schedule_resolved_task(
5127 workspace,
5128 task_source_kind,
5129 resolved_task,
5130 false,
5131 cx,
5132 );
5133 });
5134
5135 return Some(Task::ready(Ok(())));
5136 }
5137
5138 if let Some(project) = self.project.as_ref() {
5139 project
5140 .update(cx, |project, cx| {
5141 project.start_debug_session(
5142 resolved_task.resolved_debug_adapter_config().unwrap(),
5143 cx,
5144 )
5145 })
5146 .detach_and_log_err(cx);
5147 Some(Task::ready(Ok(())))
5148 } else {
5149 Some(Task::ready(Ok(())))
5150 }
5151 }
5152 }
5153 }
5154 CodeActionsItem::CodeAction {
5155 excerpt_id,
5156 action,
5157 provider,
5158 } => {
5159 let apply_code_action =
5160 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5161 let workspace = workspace.downgrade();
5162 Some(cx.spawn_in(window, async move |editor, cx| {
5163 let project_transaction = apply_code_action.await?;
5164 Self::open_project_transaction(
5165 &editor,
5166 workspace,
5167 project_transaction,
5168 title,
5169 cx,
5170 )
5171 .await
5172 }))
5173 }
5174 }
5175 }
5176
5177 pub async fn open_project_transaction(
5178 this: &WeakEntity<Editor>,
5179 workspace: WeakEntity<Workspace>,
5180 transaction: ProjectTransaction,
5181 title: String,
5182 cx: &mut AsyncWindowContext,
5183 ) -> Result<()> {
5184 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5185 cx.update(|_, cx| {
5186 entries.sort_unstable_by_key(|(buffer, _)| {
5187 buffer.read(cx).file().map(|f| f.path().clone())
5188 });
5189 })?;
5190
5191 // If the project transaction's edits are all contained within this editor, then
5192 // avoid opening a new editor to display them.
5193
5194 if let Some((buffer, transaction)) = entries.first() {
5195 if entries.len() == 1 {
5196 let excerpt = this.update(cx, |editor, cx| {
5197 editor
5198 .buffer()
5199 .read(cx)
5200 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5201 })?;
5202 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5203 if excerpted_buffer == *buffer {
5204 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5205 let excerpt_range = excerpt_range.to_offset(buffer);
5206 buffer
5207 .edited_ranges_for_transaction::<usize>(transaction)
5208 .all(|range| {
5209 excerpt_range.start <= range.start
5210 && excerpt_range.end >= range.end
5211 })
5212 })?;
5213
5214 if all_edits_within_excerpt {
5215 return Ok(());
5216 }
5217 }
5218 }
5219 }
5220 } else {
5221 return Ok(());
5222 }
5223
5224 let mut ranges_to_highlight = Vec::new();
5225 let excerpt_buffer = cx.new(|cx| {
5226 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5227 for (buffer_handle, transaction) in &entries {
5228 let edited_ranges = buffer_handle
5229 .read(cx)
5230 .edited_ranges_for_transaction::<Point>(transaction)
5231 .collect::<Vec<_>>();
5232 let (ranges, _) = multibuffer.set_excerpts_for_path(
5233 PathKey::for_buffer(buffer_handle, cx),
5234 buffer_handle.clone(),
5235 edited_ranges,
5236 DEFAULT_MULTIBUFFER_CONTEXT,
5237 cx,
5238 );
5239
5240 ranges_to_highlight.extend(ranges);
5241 }
5242 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5243 multibuffer
5244 })?;
5245
5246 workspace.update_in(cx, |workspace, window, cx| {
5247 let project = workspace.project().clone();
5248 let editor =
5249 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5250 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5251 editor.update(cx, |editor, cx| {
5252 editor.highlight_background::<Self>(
5253 &ranges_to_highlight,
5254 |theme| theme.editor_highlighted_line_background,
5255 cx,
5256 );
5257 });
5258 })?;
5259
5260 Ok(())
5261 }
5262
5263 pub fn clear_code_action_providers(&mut self) {
5264 self.code_action_providers.clear();
5265 self.available_code_actions.take();
5266 }
5267
5268 pub fn add_code_action_provider(
5269 &mut self,
5270 provider: Rc<dyn CodeActionProvider>,
5271 window: &mut Window,
5272 cx: &mut Context<Self>,
5273 ) {
5274 if self
5275 .code_action_providers
5276 .iter()
5277 .any(|existing_provider| existing_provider.id() == provider.id())
5278 {
5279 return;
5280 }
5281
5282 self.code_action_providers.push(provider);
5283 self.refresh_code_actions(window, cx);
5284 }
5285
5286 pub fn remove_code_action_provider(
5287 &mut self,
5288 id: Arc<str>,
5289 window: &mut Window,
5290 cx: &mut Context<Self>,
5291 ) {
5292 self.code_action_providers
5293 .retain(|provider| provider.id() != id);
5294 self.refresh_code_actions(window, cx);
5295 }
5296
5297 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5298 let newest_selection = self.selections.newest_anchor().clone();
5299 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5300 let buffer = self.buffer.read(cx);
5301 if newest_selection.head().diff_base_anchor.is_some() {
5302 return None;
5303 }
5304 let (start_buffer, start) =
5305 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5306 let (end_buffer, end) =
5307 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5308 if start_buffer != end_buffer {
5309 return None;
5310 }
5311
5312 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5313 cx.background_executor()
5314 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5315 .await;
5316
5317 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5318 let providers = this.code_action_providers.clone();
5319 let tasks = this
5320 .code_action_providers
5321 .iter()
5322 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5323 .collect::<Vec<_>>();
5324 (providers, tasks)
5325 })?;
5326
5327 let mut actions = Vec::new();
5328 for (provider, provider_actions) in
5329 providers.into_iter().zip(future::join_all(tasks).await)
5330 {
5331 if let Some(provider_actions) = provider_actions.log_err() {
5332 actions.extend(provider_actions.into_iter().map(|action| {
5333 AvailableCodeAction {
5334 excerpt_id: newest_selection.start.excerpt_id,
5335 action,
5336 provider: provider.clone(),
5337 }
5338 }));
5339 }
5340 }
5341
5342 this.update(cx, |this, cx| {
5343 this.available_code_actions = if actions.is_empty() {
5344 None
5345 } else {
5346 Some((
5347 Location {
5348 buffer: start_buffer,
5349 range: start..end,
5350 },
5351 actions.into(),
5352 ))
5353 };
5354 cx.notify();
5355 })
5356 }));
5357 None
5358 }
5359
5360 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5361 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5362 self.show_git_blame_inline = false;
5363
5364 self.show_git_blame_inline_delay_task =
5365 Some(cx.spawn_in(window, async move |this, cx| {
5366 cx.background_executor().timer(delay).await;
5367
5368 this.update(cx, |this, cx| {
5369 this.show_git_blame_inline = true;
5370 cx.notify();
5371 })
5372 .log_err();
5373 }));
5374 }
5375 }
5376
5377 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5378 if self.pending_rename.is_some() {
5379 return None;
5380 }
5381
5382 let provider = self.semantics_provider.clone()?;
5383 let buffer = self.buffer.read(cx);
5384 let newest_selection = self.selections.newest_anchor().clone();
5385 let cursor_position = newest_selection.head();
5386 let (cursor_buffer, cursor_buffer_position) =
5387 buffer.text_anchor_for_position(cursor_position, cx)?;
5388 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5389 if cursor_buffer != tail_buffer {
5390 return None;
5391 }
5392 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5393 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5394 cx.background_executor()
5395 .timer(Duration::from_millis(debounce))
5396 .await;
5397
5398 let highlights = if let Some(highlights) = cx
5399 .update(|cx| {
5400 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5401 })
5402 .ok()
5403 .flatten()
5404 {
5405 highlights.await.log_err()
5406 } else {
5407 None
5408 };
5409
5410 if let Some(highlights) = highlights {
5411 this.update(cx, |this, cx| {
5412 if this.pending_rename.is_some() {
5413 return;
5414 }
5415
5416 let buffer_id = cursor_position.buffer_id;
5417 let buffer = this.buffer.read(cx);
5418 if !buffer
5419 .text_anchor_for_position(cursor_position, cx)
5420 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5421 {
5422 return;
5423 }
5424
5425 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5426 let mut write_ranges = Vec::new();
5427 let mut read_ranges = Vec::new();
5428 for highlight in highlights {
5429 for (excerpt_id, excerpt_range) in
5430 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5431 {
5432 let start = highlight
5433 .range
5434 .start
5435 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5436 let end = highlight
5437 .range
5438 .end
5439 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5440 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5441 continue;
5442 }
5443
5444 let range = Anchor {
5445 buffer_id,
5446 excerpt_id,
5447 text_anchor: start,
5448 diff_base_anchor: None,
5449 }..Anchor {
5450 buffer_id,
5451 excerpt_id,
5452 text_anchor: end,
5453 diff_base_anchor: None,
5454 };
5455 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5456 write_ranges.push(range);
5457 } else {
5458 read_ranges.push(range);
5459 }
5460 }
5461 }
5462
5463 this.highlight_background::<DocumentHighlightRead>(
5464 &read_ranges,
5465 |theme| theme.editor_document_highlight_read_background,
5466 cx,
5467 );
5468 this.highlight_background::<DocumentHighlightWrite>(
5469 &write_ranges,
5470 |theme| theme.editor_document_highlight_write_background,
5471 cx,
5472 );
5473 cx.notify();
5474 })
5475 .log_err();
5476 }
5477 }));
5478 None
5479 }
5480
5481 fn prepare_highlight_query_from_selection(
5482 &mut self,
5483 cx: &mut Context<Editor>,
5484 ) -> Option<(String, Range<Anchor>)> {
5485 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5486 return None;
5487 }
5488 if !EditorSettings::get_global(cx).selection_highlight {
5489 return None;
5490 }
5491 if self.selections.count() != 1 || self.selections.line_mode {
5492 return None;
5493 }
5494 let selection = self.selections.newest::<Point>(cx);
5495 if selection.is_empty() || selection.start.row != selection.end.row {
5496 return None;
5497 }
5498 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5499 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5500 let query = multi_buffer_snapshot
5501 .text_for_range(selection_anchor_range.clone())
5502 .collect::<String>();
5503 if query.trim().is_empty() {
5504 return None;
5505 }
5506 Some((query, selection_anchor_range))
5507 }
5508
5509 fn update_selection_occurrence_highlights(
5510 &mut self,
5511 query_text: String,
5512 query_range: Range<Anchor>,
5513 multi_buffer_range_to_query: Range<Point>,
5514 use_debounce: bool,
5515 window: &mut Window,
5516 cx: &mut Context<Editor>,
5517 ) -> Task<()> {
5518 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5519 cx.spawn_in(window, async move |editor, cx| {
5520 if use_debounce {
5521 cx.background_executor()
5522 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5523 .await;
5524 }
5525 let match_task = cx.background_spawn(async move {
5526 let buffer_ranges = multi_buffer_snapshot
5527 .range_to_buffer_ranges(multi_buffer_range_to_query)
5528 .into_iter()
5529 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5530 let mut match_ranges = Vec::new();
5531 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5532 match_ranges.extend(
5533 project::search::SearchQuery::text(
5534 query_text.clone(),
5535 false,
5536 false,
5537 false,
5538 Default::default(),
5539 Default::default(),
5540 None,
5541 )
5542 .unwrap()
5543 .search(&buffer_snapshot, Some(search_range.clone()))
5544 .await
5545 .into_iter()
5546 .filter_map(|match_range| {
5547 let match_start = buffer_snapshot
5548 .anchor_after(search_range.start + match_range.start);
5549 let match_end =
5550 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5551 let match_anchor_range = Anchor::range_in_buffer(
5552 excerpt_id,
5553 buffer_snapshot.remote_id(),
5554 match_start..match_end,
5555 );
5556 (match_anchor_range != query_range).then_some(match_anchor_range)
5557 }),
5558 );
5559 }
5560 match_ranges
5561 });
5562 let match_ranges = match_task.await;
5563 editor
5564 .update_in(cx, |editor, _, cx| {
5565 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5566 if !match_ranges.is_empty() {
5567 editor.highlight_background::<SelectedTextHighlight>(
5568 &match_ranges,
5569 |theme| theme.editor_document_highlight_bracket_background,
5570 cx,
5571 )
5572 }
5573 })
5574 .log_err();
5575 })
5576 }
5577
5578 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5579 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5580 else {
5581 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5582 self.quick_selection_highlight_task.take();
5583 self.debounced_selection_highlight_task.take();
5584 return;
5585 };
5586 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5587 if self
5588 .quick_selection_highlight_task
5589 .as_ref()
5590 .map_or(true, |(prev_anchor_range, _)| {
5591 prev_anchor_range != &query_range
5592 })
5593 {
5594 let multi_buffer_visible_start = self
5595 .scroll_manager
5596 .anchor()
5597 .anchor
5598 .to_point(&multi_buffer_snapshot);
5599 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5600 multi_buffer_visible_start
5601 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5602 Bias::Left,
5603 );
5604 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5605 self.quick_selection_highlight_task = Some((
5606 query_range.clone(),
5607 self.update_selection_occurrence_highlights(
5608 query_text.clone(),
5609 query_range.clone(),
5610 multi_buffer_visible_range,
5611 false,
5612 window,
5613 cx,
5614 ),
5615 ));
5616 }
5617 if self
5618 .debounced_selection_highlight_task
5619 .as_ref()
5620 .map_or(true, |(prev_anchor_range, _)| {
5621 prev_anchor_range != &query_range
5622 })
5623 {
5624 let multi_buffer_start = multi_buffer_snapshot
5625 .anchor_before(0)
5626 .to_point(&multi_buffer_snapshot);
5627 let multi_buffer_end = multi_buffer_snapshot
5628 .anchor_after(multi_buffer_snapshot.len())
5629 .to_point(&multi_buffer_snapshot);
5630 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5631 self.debounced_selection_highlight_task = Some((
5632 query_range.clone(),
5633 self.update_selection_occurrence_highlights(
5634 query_text,
5635 query_range,
5636 multi_buffer_full_range,
5637 true,
5638 window,
5639 cx,
5640 ),
5641 ));
5642 }
5643 }
5644
5645 pub fn refresh_inline_completion(
5646 &mut self,
5647 debounce: bool,
5648 user_requested: bool,
5649 window: &mut Window,
5650 cx: &mut Context<Self>,
5651 ) -> Option<()> {
5652 let provider = self.edit_prediction_provider()?;
5653 let cursor = self.selections.newest_anchor().head();
5654 let (buffer, cursor_buffer_position) =
5655 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5656
5657 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5658 self.discard_inline_completion(false, cx);
5659 return None;
5660 }
5661
5662 if !user_requested
5663 && (!self.should_show_edit_predictions()
5664 || !self.is_focused(window)
5665 || buffer.read(cx).is_empty())
5666 {
5667 self.discard_inline_completion(false, cx);
5668 return None;
5669 }
5670
5671 self.update_visible_inline_completion(window, cx);
5672 provider.refresh(
5673 self.project.clone(),
5674 buffer,
5675 cursor_buffer_position,
5676 debounce,
5677 cx,
5678 );
5679 Some(())
5680 }
5681
5682 fn show_edit_predictions_in_menu(&self) -> bool {
5683 match self.edit_prediction_settings {
5684 EditPredictionSettings::Disabled => false,
5685 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5686 }
5687 }
5688
5689 pub fn edit_predictions_enabled(&self) -> bool {
5690 match self.edit_prediction_settings {
5691 EditPredictionSettings::Disabled => false,
5692 EditPredictionSettings::Enabled { .. } => true,
5693 }
5694 }
5695
5696 fn edit_prediction_requires_modifier(&self) -> bool {
5697 match self.edit_prediction_settings {
5698 EditPredictionSettings::Disabled => false,
5699 EditPredictionSettings::Enabled {
5700 preview_requires_modifier,
5701 ..
5702 } => preview_requires_modifier,
5703 }
5704 }
5705
5706 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5707 if self.edit_prediction_provider.is_none() {
5708 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5709 } else {
5710 let selection = self.selections.newest_anchor();
5711 let cursor = selection.head();
5712
5713 if let Some((buffer, cursor_buffer_position)) =
5714 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5715 {
5716 self.edit_prediction_settings =
5717 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5718 }
5719 }
5720 }
5721
5722 fn edit_prediction_settings_at_position(
5723 &self,
5724 buffer: &Entity<Buffer>,
5725 buffer_position: language::Anchor,
5726 cx: &App,
5727 ) -> EditPredictionSettings {
5728 if !self.mode.is_full()
5729 || !self.show_inline_completions_override.unwrap_or(true)
5730 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5731 {
5732 return EditPredictionSettings::Disabled;
5733 }
5734
5735 let buffer = buffer.read(cx);
5736
5737 let file = buffer.file();
5738
5739 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5740 return EditPredictionSettings::Disabled;
5741 };
5742
5743 let by_provider = matches!(
5744 self.menu_inline_completions_policy,
5745 MenuInlineCompletionsPolicy::ByProvider
5746 );
5747
5748 let show_in_menu = by_provider
5749 && self
5750 .edit_prediction_provider
5751 .as_ref()
5752 .map_or(false, |provider| {
5753 provider.provider.show_completions_in_menu()
5754 });
5755
5756 let preview_requires_modifier =
5757 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5758
5759 EditPredictionSettings::Enabled {
5760 show_in_menu,
5761 preview_requires_modifier,
5762 }
5763 }
5764
5765 fn should_show_edit_predictions(&self) -> bool {
5766 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5767 }
5768
5769 pub fn edit_prediction_preview_is_active(&self) -> bool {
5770 matches!(
5771 self.edit_prediction_preview,
5772 EditPredictionPreview::Active { .. }
5773 )
5774 }
5775
5776 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5777 let cursor = self.selections.newest_anchor().head();
5778 if let Some((buffer, cursor_position)) =
5779 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5780 {
5781 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5782 } else {
5783 false
5784 }
5785 }
5786
5787 fn edit_predictions_enabled_in_buffer(
5788 &self,
5789 buffer: &Entity<Buffer>,
5790 buffer_position: language::Anchor,
5791 cx: &App,
5792 ) -> bool {
5793 maybe!({
5794 if self.read_only(cx) {
5795 return Some(false);
5796 }
5797 let provider = self.edit_prediction_provider()?;
5798 if !provider.is_enabled(&buffer, buffer_position, cx) {
5799 return Some(false);
5800 }
5801 let buffer = buffer.read(cx);
5802 let Some(file) = buffer.file() else {
5803 return Some(true);
5804 };
5805 let settings = all_language_settings(Some(file), cx);
5806 Some(settings.edit_predictions_enabled_for_file(file, cx))
5807 })
5808 .unwrap_or(false)
5809 }
5810
5811 fn cycle_inline_completion(
5812 &mut self,
5813 direction: Direction,
5814 window: &mut Window,
5815 cx: &mut Context<Self>,
5816 ) -> Option<()> {
5817 let provider = self.edit_prediction_provider()?;
5818 let cursor = self.selections.newest_anchor().head();
5819 let (buffer, cursor_buffer_position) =
5820 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5821 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5822 return None;
5823 }
5824
5825 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5826 self.update_visible_inline_completion(window, cx);
5827
5828 Some(())
5829 }
5830
5831 pub fn show_inline_completion(
5832 &mut self,
5833 _: &ShowEditPrediction,
5834 window: &mut Window,
5835 cx: &mut Context<Self>,
5836 ) {
5837 if !self.has_active_inline_completion() {
5838 self.refresh_inline_completion(false, true, window, cx);
5839 return;
5840 }
5841
5842 self.update_visible_inline_completion(window, cx);
5843 }
5844
5845 pub fn display_cursor_names(
5846 &mut self,
5847 _: &DisplayCursorNames,
5848 window: &mut Window,
5849 cx: &mut Context<Self>,
5850 ) {
5851 self.show_cursor_names(window, cx);
5852 }
5853
5854 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5855 self.show_cursor_names = true;
5856 cx.notify();
5857 cx.spawn_in(window, async move |this, cx| {
5858 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5859 this.update(cx, |this, cx| {
5860 this.show_cursor_names = false;
5861 cx.notify()
5862 })
5863 .ok()
5864 })
5865 .detach();
5866 }
5867
5868 pub fn next_edit_prediction(
5869 &mut self,
5870 _: &NextEditPrediction,
5871 window: &mut Window,
5872 cx: &mut Context<Self>,
5873 ) {
5874 if self.has_active_inline_completion() {
5875 self.cycle_inline_completion(Direction::Next, window, cx);
5876 } else {
5877 let is_copilot_disabled = self
5878 .refresh_inline_completion(false, true, window, cx)
5879 .is_none();
5880 if is_copilot_disabled {
5881 cx.propagate();
5882 }
5883 }
5884 }
5885
5886 pub fn previous_edit_prediction(
5887 &mut self,
5888 _: &PreviousEditPrediction,
5889 window: &mut Window,
5890 cx: &mut Context<Self>,
5891 ) {
5892 if self.has_active_inline_completion() {
5893 self.cycle_inline_completion(Direction::Prev, window, cx);
5894 } else {
5895 let is_copilot_disabled = self
5896 .refresh_inline_completion(false, true, window, cx)
5897 .is_none();
5898 if is_copilot_disabled {
5899 cx.propagate();
5900 }
5901 }
5902 }
5903
5904 pub fn accept_edit_prediction(
5905 &mut self,
5906 _: &AcceptEditPrediction,
5907 window: &mut Window,
5908 cx: &mut Context<Self>,
5909 ) {
5910 if self.show_edit_predictions_in_menu() {
5911 self.hide_context_menu(window, cx);
5912 }
5913
5914 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5915 return;
5916 };
5917
5918 self.report_inline_completion_event(
5919 active_inline_completion.completion_id.clone(),
5920 true,
5921 cx,
5922 );
5923
5924 match &active_inline_completion.completion {
5925 InlineCompletion::Move { target, .. } => {
5926 let target = *target;
5927
5928 if let Some(position_map) = &self.last_position_map {
5929 if position_map
5930 .visible_row_range
5931 .contains(&target.to_display_point(&position_map.snapshot).row())
5932 || !self.edit_prediction_requires_modifier()
5933 {
5934 self.unfold_ranges(&[target..target], true, false, cx);
5935 // Note that this is also done in vim's handler of the Tab action.
5936 self.change_selections(
5937 Some(Autoscroll::newest()),
5938 window,
5939 cx,
5940 |selections| {
5941 selections.select_anchor_ranges([target..target]);
5942 },
5943 );
5944 self.clear_row_highlights::<EditPredictionPreview>();
5945
5946 self.edit_prediction_preview
5947 .set_previous_scroll_position(None);
5948 } else {
5949 self.edit_prediction_preview
5950 .set_previous_scroll_position(Some(
5951 position_map.snapshot.scroll_anchor,
5952 ));
5953
5954 self.highlight_rows::<EditPredictionPreview>(
5955 target..target,
5956 cx.theme().colors().editor_highlighted_line_background,
5957 true,
5958 cx,
5959 );
5960 self.request_autoscroll(Autoscroll::fit(), cx);
5961 }
5962 }
5963 }
5964 InlineCompletion::Edit { edits, .. } => {
5965 if let Some(provider) = self.edit_prediction_provider() {
5966 provider.accept(cx);
5967 }
5968
5969 let snapshot = self.buffer.read(cx).snapshot(cx);
5970 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5971
5972 self.buffer.update(cx, |buffer, cx| {
5973 buffer.edit(edits.iter().cloned(), None, cx)
5974 });
5975
5976 self.change_selections(None, window, cx, |s| {
5977 s.select_anchor_ranges([last_edit_end..last_edit_end])
5978 });
5979
5980 self.update_visible_inline_completion(window, cx);
5981 if self.active_inline_completion.is_none() {
5982 self.refresh_inline_completion(true, true, window, cx);
5983 }
5984
5985 cx.notify();
5986 }
5987 }
5988
5989 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5990 }
5991
5992 pub fn accept_partial_inline_completion(
5993 &mut self,
5994 _: &AcceptPartialEditPrediction,
5995 window: &mut Window,
5996 cx: &mut Context<Self>,
5997 ) {
5998 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5999 return;
6000 };
6001 if self.selections.count() != 1 {
6002 return;
6003 }
6004
6005 self.report_inline_completion_event(
6006 active_inline_completion.completion_id.clone(),
6007 true,
6008 cx,
6009 );
6010
6011 match &active_inline_completion.completion {
6012 InlineCompletion::Move { target, .. } => {
6013 let target = *target;
6014 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6015 selections.select_anchor_ranges([target..target]);
6016 });
6017 }
6018 InlineCompletion::Edit { edits, .. } => {
6019 // Find an insertion that starts at the cursor position.
6020 let snapshot = self.buffer.read(cx).snapshot(cx);
6021 let cursor_offset = self.selections.newest::<usize>(cx).head();
6022 let insertion = edits.iter().find_map(|(range, text)| {
6023 let range = range.to_offset(&snapshot);
6024 if range.is_empty() && range.start == cursor_offset {
6025 Some(text)
6026 } else {
6027 None
6028 }
6029 });
6030
6031 if let Some(text) = insertion {
6032 let mut partial_completion = text
6033 .chars()
6034 .by_ref()
6035 .take_while(|c| c.is_alphabetic())
6036 .collect::<String>();
6037 if partial_completion.is_empty() {
6038 partial_completion = text
6039 .chars()
6040 .by_ref()
6041 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6042 .collect::<String>();
6043 }
6044
6045 cx.emit(EditorEvent::InputHandled {
6046 utf16_range_to_replace: None,
6047 text: partial_completion.clone().into(),
6048 });
6049
6050 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6051
6052 self.refresh_inline_completion(true, true, window, cx);
6053 cx.notify();
6054 } else {
6055 self.accept_edit_prediction(&Default::default(), window, cx);
6056 }
6057 }
6058 }
6059 }
6060
6061 fn discard_inline_completion(
6062 &mut self,
6063 should_report_inline_completion_event: bool,
6064 cx: &mut Context<Self>,
6065 ) -> bool {
6066 if should_report_inline_completion_event {
6067 let completion_id = self
6068 .active_inline_completion
6069 .as_ref()
6070 .and_then(|active_completion| active_completion.completion_id.clone());
6071
6072 self.report_inline_completion_event(completion_id, false, cx);
6073 }
6074
6075 if let Some(provider) = self.edit_prediction_provider() {
6076 provider.discard(cx);
6077 }
6078
6079 self.take_active_inline_completion(cx)
6080 }
6081
6082 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6083 let Some(provider) = self.edit_prediction_provider() else {
6084 return;
6085 };
6086
6087 let Some((_, buffer, _)) = self
6088 .buffer
6089 .read(cx)
6090 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6091 else {
6092 return;
6093 };
6094
6095 let extension = buffer
6096 .read(cx)
6097 .file()
6098 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6099
6100 let event_type = match accepted {
6101 true => "Edit Prediction Accepted",
6102 false => "Edit Prediction Discarded",
6103 };
6104 telemetry::event!(
6105 event_type,
6106 provider = provider.name(),
6107 prediction_id = id,
6108 suggestion_accepted = accepted,
6109 file_extension = extension,
6110 );
6111 }
6112
6113 pub fn has_active_inline_completion(&self) -> bool {
6114 self.active_inline_completion.is_some()
6115 }
6116
6117 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6118 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6119 return false;
6120 };
6121
6122 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6123 self.clear_highlights::<InlineCompletionHighlight>(cx);
6124 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6125 true
6126 }
6127
6128 /// Returns true when we're displaying the edit prediction popover below the cursor
6129 /// like we are not previewing and the LSP autocomplete menu is visible
6130 /// or we are in `when_holding_modifier` mode.
6131 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6132 if self.edit_prediction_preview_is_active()
6133 || !self.show_edit_predictions_in_menu()
6134 || !self.edit_predictions_enabled()
6135 {
6136 return false;
6137 }
6138
6139 if self.has_visible_completions_menu() {
6140 return true;
6141 }
6142
6143 has_completion && self.edit_prediction_requires_modifier()
6144 }
6145
6146 fn handle_modifiers_changed(
6147 &mut self,
6148 modifiers: Modifiers,
6149 position_map: &PositionMap,
6150 window: &mut Window,
6151 cx: &mut Context<Self>,
6152 ) {
6153 if self.show_edit_predictions_in_menu() {
6154 self.update_edit_prediction_preview(&modifiers, window, cx);
6155 }
6156
6157 self.update_selection_mode(&modifiers, position_map, window, cx);
6158
6159 let mouse_position = window.mouse_position();
6160 if !position_map.text_hitbox.is_hovered(window) {
6161 return;
6162 }
6163
6164 self.update_hovered_link(
6165 position_map.point_for_position(mouse_position),
6166 &position_map.snapshot,
6167 modifiers,
6168 window,
6169 cx,
6170 )
6171 }
6172
6173 fn update_selection_mode(
6174 &mut self,
6175 modifiers: &Modifiers,
6176 position_map: &PositionMap,
6177 window: &mut Window,
6178 cx: &mut Context<Self>,
6179 ) {
6180 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6181 return;
6182 }
6183
6184 let mouse_position = window.mouse_position();
6185 let point_for_position = position_map.point_for_position(mouse_position);
6186 let position = point_for_position.previous_valid;
6187
6188 self.select(
6189 SelectPhase::BeginColumnar {
6190 position,
6191 reset: false,
6192 goal_column: point_for_position.exact_unclipped.column(),
6193 },
6194 window,
6195 cx,
6196 );
6197 }
6198
6199 fn update_edit_prediction_preview(
6200 &mut self,
6201 modifiers: &Modifiers,
6202 window: &mut Window,
6203 cx: &mut Context<Self>,
6204 ) {
6205 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6206 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6207 return;
6208 };
6209
6210 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6211 if matches!(
6212 self.edit_prediction_preview,
6213 EditPredictionPreview::Inactive { .. }
6214 ) {
6215 self.edit_prediction_preview = EditPredictionPreview::Active {
6216 previous_scroll_position: None,
6217 since: Instant::now(),
6218 };
6219
6220 self.update_visible_inline_completion(window, cx);
6221 cx.notify();
6222 }
6223 } else if let EditPredictionPreview::Active {
6224 previous_scroll_position,
6225 since,
6226 } = self.edit_prediction_preview
6227 {
6228 if let (Some(previous_scroll_position), Some(position_map)) =
6229 (previous_scroll_position, self.last_position_map.as_ref())
6230 {
6231 self.set_scroll_position(
6232 previous_scroll_position
6233 .scroll_position(&position_map.snapshot.display_snapshot),
6234 window,
6235 cx,
6236 );
6237 }
6238
6239 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6240 released_too_fast: since.elapsed() < Duration::from_millis(200),
6241 };
6242 self.clear_row_highlights::<EditPredictionPreview>();
6243 self.update_visible_inline_completion(window, cx);
6244 cx.notify();
6245 }
6246 }
6247
6248 fn update_visible_inline_completion(
6249 &mut self,
6250 _window: &mut Window,
6251 cx: &mut Context<Self>,
6252 ) -> Option<()> {
6253 let selection = self.selections.newest_anchor();
6254 let cursor = selection.head();
6255 let multibuffer = self.buffer.read(cx).snapshot(cx);
6256 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6257 let excerpt_id = cursor.excerpt_id;
6258
6259 let show_in_menu = self.show_edit_predictions_in_menu();
6260 let completions_menu_has_precedence = !show_in_menu
6261 && (self.context_menu.borrow().is_some()
6262 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6263
6264 if completions_menu_has_precedence
6265 || !offset_selection.is_empty()
6266 || self
6267 .active_inline_completion
6268 .as_ref()
6269 .map_or(false, |completion| {
6270 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6271 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6272 !invalidation_range.contains(&offset_selection.head())
6273 })
6274 {
6275 self.discard_inline_completion(false, cx);
6276 return None;
6277 }
6278
6279 self.take_active_inline_completion(cx);
6280 let Some(provider) = self.edit_prediction_provider() else {
6281 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6282 return None;
6283 };
6284
6285 let (buffer, cursor_buffer_position) =
6286 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6287
6288 self.edit_prediction_settings =
6289 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6290
6291 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6292
6293 if self.edit_prediction_indent_conflict {
6294 let cursor_point = cursor.to_point(&multibuffer);
6295
6296 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6297
6298 if let Some((_, indent)) = indents.iter().next() {
6299 if indent.len == cursor_point.column {
6300 self.edit_prediction_indent_conflict = false;
6301 }
6302 }
6303 }
6304
6305 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6306 let edits = inline_completion
6307 .edits
6308 .into_iter()
6309 .flat_map(|(range, new_text)| {
6310 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6311 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6312 Some((start..end, new_text))
6313 })
6314 .collect::<Vec<_>>();
6315 if edits.is_empty() {
6316 return None;
6317 }
6318
6319 let first_edit_start = edits.first().unwrap().0.start;
6320 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6321 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6322
6323 let last_edit_end = edits.last().unwrap().0.end;
6324 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6325 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6326
6327 let cursor_row = cursor.to_point(&multibuffer).row;
6328
6329 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6330
6331 let mut inlay_ids = Vec::new();
6332 let invalidation_row_range;
6333 let move_invalidation_row_range = if cursor_row < edit_start_row {
6334 Some(cursor_row..edit_end_row)
6335 } else if cursor_row > edit_end_row {
6336 Some(edit_start_row..cursor_row)
6337 } else {
6338 None
6339 };
6340 let is_move =
6341 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6342 let completion = if is_move {
6343 invalidation_row_range =
6344 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6345 let target = first_edit_start;
6346 InlineCompletion::Move { target, snapshot }
6347 } else {
6348 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6349 && !self.inline_completions_hidden_for_vim_mode;
6350
6351 if show_completions_in_buffer {
6352 if edits
6353 .iter()
6354 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6355 {
6356 let mut inlays = Vec::new();
6357 for (range, new_text) in &edits {
6358 let inlay = Inlay::inline_completion(
6359 post_inc(&mut self.next_inlay_id),
6360 range.start,
6361 new_text.as_str(),
6362 );
6363 inlay_ids.push(inlay.id);
6364 inlays.push(inlay);
6365 }
6366
6367 self.splice_inlays(&[], inlays, cx);
6368 } else {
6369 let background_color = cx.theme().status().deleted_background;
6370 self.highlight_text::<InlineCompletionHighlight>(
6371 edits.iter().map(|(range, _)| range.clone()).collect(),
6372 HighlightStyle {
6373 background_color: Some(background_color),
6374 ..Default::default()
6375 },
6376 cx,
6377 );
6378 }
6379 }
6380
6381 invalidation_row_range = edit_start_row..edit_end_row;
6382
6383 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6384 if provider.show_tab_accept_marker() {
6385 EditDisplayMode::TabAccept
6386 } else {
6387 EditDisplayMode::Inline
6388 }
6389 } else {
6390 EditDisplayMode::DiffPopover
6391 };
6392
6393 InlineCompletion::Edit {
6394 edits,
6395 edit_preview: inline_completion.edit_preview,
6396 display_mode,
6397 snapshot,
6398 }
6399 };
6400
6401 let invalidation_range = multibuffer
6402 .anchor_before(Point::new(invalidation_row_range.start, 0))
6403 ..multibuffer.anchor_after(Point::new(
6404 invalidation_row_range.end,
6405 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6406 ));
6407
6408 self.stale_inline_completion_in_menu = None;
6409 self.active_inline_completion = Some(InlineCompletionState {
6410 inlay_ids,
6411 completion,
6412 completion_id: inline_completion.id,
6413 invalidation_range,
6414 });
6415
6416 cx.notify();
6417
6418 Some(())
6419 }
6420
6421 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6422 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6423 }
6424
6425 fn render_code_actions_indicator(
6426 &self,
6427 _style: &EditorStyle,
6428 row: DisplayRow,
6429 is_active: bool,
6430 breakpoint: Option<&(Anchor, Breakpoint)>,
6431 cx: &mut Context<Self>,
6432 ) -> Option<IconButton> {
6433 let color = Color::Muted;
6434 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6435 let show_tooltip = !self.context_menu_visible();
6436
6437 if self.available_code_actions.is_some() {
6438 Some(
6439 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6440 .shape(ui::IconButtonShape::Square)
6441 .icon_size(IconSize::XSmall)
6442 .icon_color(color)
6443 .toggle_state(is_active)
6444 .when(show_tooltip, |this| {
6445 this.tooltip({
6446 let focus_handle = self.focus_handle.clone();
6447 move |window, cx| {
6448 Tooltip::for_action_in(
6449 "Toggle Code Actions",
6450 &ToggleCodeActions {
6451 deployed_from_indicator: None,
6452 },
6453 &focus_handle,
6454 window,
6455 cx,
6456 )
6457 }
6458 })
6459 })
6460 .on_click(cx.listener(move |editor, _e, window, cx| {
6461 window.focus(&editor.focus_handle(cx));
6462 editor.toggle_code_actions(
6463 &ToggleCodeActions {
6464 deployed_from_indicator: Some(row),
6465 },
6466 window,
6467 cx,
6468 );
6469 }))
6470 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6471 editor.set_breakpoint_context_menu(
6472 row,
6473 position,
6474 event.down.position,
6475 window,
6476 cx,
6477 );
6478 })),
6479 )
6480 } else {
6481 None
6482 }
6483 }
6484
6485 fn clear_tasks(&mut self) {
6486 self.tasks.clear()
6487 }
6488
6489 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6490 if self.tasks.insert(key, value).is_some() {
6491 // This case should hopefully be rare, but just in case...
6492 log::error!(
6493 "multiple different run targets found on a single line, only the last target will be rendered"
6494 )
6495 }
6496 }
6497
6498 /// Get all display points of breakpoints that will be rendered within editor
6499 ///
6500 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6501 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6502 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6503 fn active_breakpoints(
6504 &self,
6505 range: Range<DisplayRow>,
6506 window: &mut Window,
6507 cx: &mut Context<Self>,
6508 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6509 let mut breakpoint_display_points = HashMap::default();
6510
6511 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6512 return breakpoint_display_points;
6513 };
6514
6515 let snapshot = self.snapshot(window, cx);
6516
6517 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6518 let Some(project) = self.project.as_ref() else {
6519 return breakpoint_display_points;
6520 };
6521
6522 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6523 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6524
6525 for (buffer_snapshot, range, excerpt_id) in
6526 multi_buffer_snapshot.range_to_buffer_ranges(range)
6527 {
6528 let Some(buffer) = project.read_with(cx, |this, cx| {
6529 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6530 }) else {
6531 continue;
6532 };
6533 let breakpoints = breakpoint_store.read(cx).breakpoints(
6534 &buffer,
6535 Some(
6536 buffer_snapshot.anchor_before(range.start)
6537 ..buffer_snapshot.anchor_after(range.end),
6538 ),
6539 buffer_snapshot,
6540 cx,
6541 );
6542 for (anchor, breakpoint) in breakpoints {
6543 let multi_buffer_anchor =
6544 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6545 let position = multi_buffer_anchor
6546 .to_point(&multi_buffer_snapshot)
6547 .to_display_point(&snapshot);
6548
6549 breakpoint_display_points
6550 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6551 }
6552 }
6553
6554 breakpoint_display_points
6555 }
6556
6557 fn breakpoint_context_menu(
6558 &self,
6559 anchor: Anchor,
6560 window: &mut Window,
6561 cx: &mut Context<Self>,
6562 ) -> Entity<ui::ContextMenu> {
6563 let weak_editor = cx.weak_entity();
6564 let focus_handle = self.focus_handle(cx);
6565
6566 let row = self
6567 .buffer
6568 .read(cx)
6569 .snapshot(cx)
6570 .summary_for_anchor::<Point>(&anchor)
6571 .row;
6572
6573 let breakpoint = self
6574 .breakpoint_at_row(row, window, cx)
6575 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6576
6577 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6578 "Edit Log Breakpoint"
6579 } else {
6580 "Set Log Breakpoint"
6581 };
6582
6583 let condition_breakpoint_msg = if breakpoint
6584 .as_ref()
6585 .is_some_and(|bp| bp.1.condition.is_some())
6586 {
6587 "Edit Condition Breakpoint"
6588 } else {
6589 "Set Condition Breakpoint"
6590 };
6591
6592 let hit_condition_breakpoint_msg = if breakpoint
6593 .as_ref()
6594 .is_some_and(|bp| bp.1.hit_condition.is_some())
6595 {
6596 "Edit Hit Condition Breakpoint"
6597 } else {
6598 "Set Hit Condition Breakpoint"
6599 };
6600
6601 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6602 "Unset Breakpoint"
6603 } else {
6604 "Set Breakpoint"
6605 };
6606
6607 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6608 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6609
6610 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6611 BreakpointState::Enabled => Some("Disable"),
6612 BreakpointState::Disabled => Some("Enable"),
6613 });
6614
6615 let (anchor, breakpoint) =
6616 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6617
6618 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6619 menu.on_blur_subscription(Subscription::new(|| {}))
6620 .context(focus_handle)
6621 .when(run_to_cursor, |this| {
6622 let weak_editor = weak_editor.clone();
6623 this.entry("Run to cursor", None, move |window, cx| {
6624 weak_editor
6625 .update(cx, |editor, cx| {
6626 editor.change_selections(None, window, cx, |s| {
6627 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6628 });
6629 })
6630 .ok();
6631
6632 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6633 })
6634 .separator()
6635 })
6636 .when_some(toggle_state_msg, |this, msg| {
6637 this.entry(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::InvertState,
6647 cx,
6648 );
6649 })
6650 .log_err();
6651 }
6652 })
6653 })
6654 .entry(set_breakpoint_msg, None, {
6655 let weak_editor = weak_editor.clone();
6656 let breakpoint = breakpoint.clone();
6657 move |_window, cx| {
6658 weak_editor
6659 .update(cx, |this, cx| {
6660 this.edit_breakpoint_at_anchor(
6661 anchor,
6662 breakpoint.as_ref().clone(),
6663 BreakpointEditAction::Toggle,
6664 cx,
6665 );
6666 })
6667 .log_err();
6668 }
6669 })
6670 .entry(log_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::Log,
6680 window,
6681 cx,
6682 );
6683 })
6684 .log_err();
6685 }
6686 })
6687 .entry(condition_breakpoint_msg, None, {
6688 let breakpoint = breakpoint.clone();
6689 let weak_editor = weak_editor.clone();
6690 move |window, cx| {
6691 weak_editor
6692 .update(cx, |this, cx| {
6693 this.add_edit_breakpoint_block(
6694 anchor,
6695 breakpoint.as_ref(),
6696 BreakpointPromptEditAction::Condition,
6697 window,
6698 cx,
6699 );
6700 })
6701 .log_err();
6702 }
6703 })
6704 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6705 weak_editor
6706 .update(cx, |this, cx| {
6707 this.add_edit_breakpoint_block(
6708 anchor,
6709 breakpoint.as_ref(),
6710 BreakpointPromptEditAction::HitCondition,
6711 window,
6712 cx,
6713 );
6714 })
6715 .log_err();
6716 })
6717 })
6718 }
6719
6720 fn render_breakpoint(
6721 &self,
6722 position: Anchor,
6723 row: DisplayRow,
6724 breakpoint: &Breakpoint,
6725 cx: &mut Context<Self>,
6726 ) -> IconButton {
6727 let (color, icon) = {
6728 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6729 (false, false) => ui::IconName::DebugBreakpoint,
6730 (true, false) => ui::IconName::DebugLogBreakpoint,
6731 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6732 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6733 };
6734
6735 let color = if self
6736 .gutter_breakpoint_indicator
6737 .0
6738 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6739 {
6740 Color::Hint
6741 } else {
6742 Color::Debugger
6743 };
6744
6745 (color, icon)
6746 };
6747
6748 let breakpoint = Arc::from(breakpoint.clone());
6749
6750 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6751 .icon_size(IconSize::XSmall)
6752 .size(ui::ButtonSize::None)
6753 .icon_color(color)
6754 .style(ButtonStyle::Transparent)
6755 .on_click(cx.listener({
6756 let breakpoint = breakpoint.clone();
6757
6758 move |editor, event: &ClickEvent, window, cx| {
6759 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6760 BreakpointEditAction::InvertState
6761 } else {
6762 BreakpointEditAction::Toggle
6763 };
6764
6765 window.focus(&editor.focus_handle(cx));
6766 editor.edit_breakpoint_at_anchor(
6767 position,
6768 breakpoint.as_ref().clone(),
6769 edit_action,
6770 cx,
6771 );
6772 }
6773 }))
6774 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6775 editor.set_breakpoint_context_menu(
6776 row,
6777 Some(position),
6778 event.down.position,
6779 window,
6780 cx,
6781 );
6782 }))
6783 }
6784
6785 fn build_tasks_context(
6786 project: &Entity<Project>,
6787 buffer: &Entity<Buffer>,
6788 buffer_row: u32,
6789 tasks: &Arc<RunnableTasks>,
6790 cx: &mut Context<Self>,
6791 ) -> Task<Option<task::TaskContext>> {
6792 let position = Point::new(buffer_row, tasks.column);
6793 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6794 let location = Location {
6795 buffer: buffer.clone(),
6796 range: range_start..range_start,
6797 };
6798 // Fill in the environmental variables from the tree-sitter captures
6799 let mut captured_task_variables = TaskVariables::default();
6800 for (capture_name, value) in tasks.extra_variables.clone() {
6801 captured_task_variables.insert(
6802 task::VariableName::Custom(capture_name.into()),
6803 value.clone(),
6804 );
6805 }
6806 project.update(cx, |project, cx| {
6807 project.task_store().update(cx, |task_store, cx| {
6808 task_store.task_context_for_location(captured_task_variables, location, cx)
6809 })
6810 })
6811 }
6812
6813 pub fn spawn_nearest_task(
6814 &mut self,
6815 action: &SpawnNearestTask,
6816 window: &mut Window,
6817 cx: &mut Context<Self>,
6818 ) {
6819 let Some((workspace, _)) = self.workspace.clone() else {
6820 return;
6821 };
6822 let Some(project) = self.project.clone() else {
6823 return;
6824 };
6825
6826 // Try to find a closest, enclosing node using tree-sitter that has a
6827 // task
6828 let Some((buffer, buffer_row, tasks)) = self
6829 .find_enclosing_node_task(cx)
6830 // Or find the task that's closest in row-distance.
6831 .or_else(|| self.find_closest_task(cx))
6832 else {
6833 return;
6834 };
6835
6836 let reveal_strategy = action.reveal;
6837 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6838 cx.spawn_in(window, async move |_, cx| {
6839 let context = task_context.await?;
6840 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6841
6842 let resolved = resolved_task.resolved.as_mut()?;
6843 resolved.reveal = reveal_strategy;
6844
6845 workspace
6846 .update(cx, |workspace, cx| {
6847 workspace::tasks::schedule_resolved_task(
6848 workspace,
6849 task_source_kind,
6850 resolved_task,
6851 false,
6852 cx,
6853 );
6854 })
6855 .ok()
6856 })
6857 .detach();
6858 }
6859
6860 fn find_closest_task(
6861 &mut self,
6862 cx: &mut Context<Self>,
6863 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6864 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6865
6866 let ((buffer_id, row), tasks) = self
6867 .tasks
6868 .iter()
6869 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6870
6871 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6872 let tasks = Arc::new(tasks.to_owned());
6873 Some((buffer, *row, tasks))
6874 }
6875
6876 fn find_enclosing_node_task(
6877 &mut self,
6878 cx: &mut Context<Self>,
6879 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6880 let snapshot = self.buffer.read(cx).snapshot(cx);
6881 let offset = self.selections.newest::<usize>(cx).head();
6882 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6883 let buffer_id = excerpt.buffer().remote_id();
6884
6885 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6886 let mut cursor = layer.node().walk();
6887
6888 while cursor.goto_first_child_for_byte(offset).is_some() {
6889 if cursor.node().end_byte() == offset {
6890 cursor.goto_next_sibling();
6891 }
6892 }
6893
6894 // Ascend to the smallest ancestor that contains the range and has a task.
6895 loop {
6896 let node = cursor.node();
6897 let node_range = node.byte_range();
6898 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6899
6900 // Check if this node contains our offset
6901 if node_range.start <= offset && node_range.end >= offset {
6902 // If it contains offset, check for task
6903 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6904 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6905 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6906 }
6907 }
6908
6909 if !cursor.goto_parent() {
6910 break;
6911 }
6912 }
6913 None
6914 }
6915
6916 fn render_run_indicator(
6917 &self,
6918 _style: &EditorStyle,
6919 is_active: bool,
6920 row: DisplayRow,
6921 breakpoint: Option<(Anchor, Breakpoint)>,
6922 cx: &mut Context<Self>,
6923 ) -> IconButton {
6924 let color = Color::Muted;
6925 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6926
6927 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6928 .shape(ui::IconButtonShape::Square)
6929 .icon_size(IconSize::XSmall)
6930 .icon_color(color)
6931 .toggle_state(is_active)
6932 .on_click(cx.listener(move |editor, _e, window, cx| {
6933 window.focus(&editor.focus_handle(cx));
6934 editor.toggle_code_actions(
6935 &ToggleCodeActions {
6936 deployed_from_indicator: Some(row),
6937 },
6938 window,
6939 cx,
6940 );
6941 }))
6942 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6943 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6944 }))
6945 }
6946
6947 pub fn context_menu_visible(&self) -> bool {
6948 !self.edit_prediction_preview_is_active()
6949 && self
6950 .context_menu
6951 .borrow()
6952 .as_ref()
6953 .map_or(false, |menu| menu.visible())
6954 }
6955
6956 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6957 self.context_menu
6958 .borrow()
6959 .as_ref()
6960 .map(|menu| menu.origin())
6961 }
6962
6963 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6964 self.context_menu_options = Some(options);
6965 }
6966
6967 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6968 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6969
6970 fn render_edit_prediction_popover(
6971 &mut self,
6972 text_bounds: &Bounds<Pixels>,
6973 content_origin: gpui::Point<Pixels>,
6974 editor_snapshot: &EditorSnapshot,
6975 visible_row_range: Range<DisplayRow>,
6976 scroll_top: f32,
6977 scroll_bottom: f32,
6978 line_layouts: &[LineWithInvisibles],
6979 line_height: Pixels,
6980 scroll_pixel_position: gpui::Point<Pixels>,
6981 newest_selection_head: Option<DisplayPoint>,
6982 editor_width: Pixels,
6983 style: &EditorStyle,
6984 window: &mut Window,
6985 cx: &mut App,
6986 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6987 let active_inline_completion = self.active_inline_completion.as_ref()?;
6988
6989 if self.edit_prediction_visible_in_cursor_popover(true) {
6990 return None;
6991 }
6992
6993 match &active_inline_completion.completion {
6994 InlineCompletion::Move { target, .. } => {
6995 let target_display_point = target.to_display_point(editor_snapshot);
6996
6997 if self.edit_prediction_requires_modifier() {
6998 if !self.edit_prediction_preview_is_active() {
6999 return None;
7000 }
7001
7002 self.render_edit_prediction_modifier_jump_popover(
7003 text_bounds,
7004 content_origin,
7005 visible_row_range,
7006 line_layouts,
7007 line_height,
7008 scroll_pixel_position,
7009 newest_selection_head,
7010 target_display_point,
7011 window,
7012 cx,
7013 )
7014 } else {
7015 self.render_edit_prediction_eager_jump_popover(
7016 text_bounds,
7017 content_origin,
7018 editor_snapshot,
7019 visible_row_range,
7020 scroll_top,
7021 scroll_bottom,
7022 line_height,
7023 scroll_pixel_position,
7024 target_display_point,
7025 editor_width,
7026 window,
7027 cx,
7028 )
7029 }
7030 }
7031 InlineCompletion::Edit {
7032 display_mode: EditDisplayMode::Inline,
7033 ..
7034 } => None,
7035 InlineCompletion::Edit {
7036 display_mode: EditDisplayMode::TabAccept,
7037 edits,
7038 ..
7039 } => {
7040 let range = &edits.first()?.0;
7041 let target_display_point = range.end.to_display_point(editor_snapshot);
7042
7043 self.render_edit_prediction_end_of_line_popover(
7044 "Accept",
7045 editor_snapshot,
7046 visible_row_range,
7047 target_display_point,
7048 line_height,
7049 scroll_pixel_position,
7050 content_origin,
7051 editor_width,
7052 window,
7053 cx,
7054 )
7055 }
7056 InlineCompletion::Edit {
7057 edits,
7058 edit_preview,
7059 display_mode: EditDisplayMode::DiffPopover,
7060 snapshot,
7061 } => self.render_edit_prediction_diff_popover(
7062 text_bounds,
7063 content_origin,
7064 editor_snapshot,
7065 visible_row_range,
7066 line_layouts,
7067 line_height,
7068 scroll_pixel_position,
7069 newest_selection_head,
7070 editor_width,
7071 style,
7072 edits,
7073 edit_preview,
7074 snapshot,
7075 window,
7076 cx,
7077 ),
7078 }
7079 }
7080
7081 fn render_edit_prediction_modifier_jump_popover(
7082 &mut self,
7083 text_bounds: &Bounds<Pixels>,
7084 content_origin: gpui::Point<Pixels>,
7085 visible_row_range: Range<DisplayRow>,
7086 line_layouts: &[LineWithInvisibles],
7087 line_height: Pixels,
7088 scroll_pixel_position: gpui::Point<Pixels>,
7089 newest_selection_head: Option<DisplayPoint>,
7090 target_display_point: DisplayPoint,
7091 window: &mut Window,
7092 cx: &mut App,
7093 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7094 let scrolled_content_origin =
7095 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7096
7097 const SCROLL_PADDING_Y: Pixels = px(12.);
7098
7099 if target_display_point.row() < visible_row_range.start {
7100 return self.render_edit_prediction_scroll_popover(
7101 |_| SCROLL_PADDING_Y,
7102 IconName::ArrowUp,
7103 visible_row_range,
7104 line_layouts,
7105 newest_selection_head,
7106 scrolled_content_origin,
7107 window,
7108 cx,
7109 );
7110 } else if target_display_point.row() >= visible_row_range.end {
7111 return self.render_edit_prediction_scroll_popover(
7112 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7113 IconName::ArrowDown,
7114 visible_row_range,
7115 line_layouts,
7116 newest_selection_head,
7117 scrolled_content_origin,
7118 window,
7119 cx,
7120 );
7121 }
7122
7123 const POLE_WIDTH: Pixels = px(2.);
7124
7125 let line_layout =
7126 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7127 let target_column = target_display_point.column() as usize;
7128
7129 let target_x = line_layout.x_for_index(target_column);
7130 let target_y =
7131 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7132
7133 let flag_on_right = target_x < text_bounds.size.width / 2.;
7134
7135 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7136 border_color.l += 0.001;
7137
7138 let mut element = v_flex()
7139 .items_end()
7140 .when(flag_on_right, |el| el.items_start())
7141 .child(if flag_on_right {
7142 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7143 .rounded_bl(px(0.))
7144 .rounded_tl(px(0.))
7145 .border_l_2()
7146 .border_color(border_color)
7147 } else {
7148 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7149 .rounded_br(px(0.))
7150 .rounded_tr(px(0.))
7151 .border_r_2()
7152 .border_color(border_color)
7153 })
7154 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7155 .into_any();
7156
7157 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7158
7159 let mut origin = scrolled_content_origin + point(target_x, target_y)
7160 - point(
7161 if flag_on_right {
7162 POLE_WIDTH
7163 } else {
7164 size.width - POLE_WIDTH
7165 },
7166 size.height - line_height,
7167 );
7168
7169 origin.x = origin.x.max(content_origin.x);
7170
7171 element.prepaint_at(origin, window, cx);
7172
7173 Some((element, origin))
7174 }
7175
7176 fn render_edit_prediction_scroll_popover(
7177 &mut self,
7178 to_y: impl Fn(Size<Pixels>) -> Pixels,
7179 scroll_icon: IconName,
7180 visible_row_range: Range<DisplayRow>,
7181 line_layouts: &[LineWithInvisibles],
7182 newest_selection_head: Option<DisplayPoint>,
7183 scrolled_content_origin: gpui::Point<Pixels>,
7184 window: &mut Window,
7185 cx: &mut App,
7186 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7187 let mut element = self
7188 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7189 .into_any();
7190
7191 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7192
7193 let cursor = newest_selection_head?;
7194 let cursor_row_layout =
7195 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7196 let cursor_column = cursor.column() as usize;
7197
7198 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7199
7200 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7201
7202 element.prepaint_at(origin, window, cx);
7203 Some((element, origin))
7204 }
7205
7206 fn render_edit_prediction_eager_jump_popover(
7207 &mut self,
7208 text_bounds: &Bounds<Pixels>,
7209 content_origin: gpui::Point<Pixels>,
7210 editor_snapshot: &EditorSnapshot,
7211 visible_row_range: Range<DisplayRow>,
7212 scroll_top: f32,
7213 scroll_bottom: f32,
7214 line_height: Pixels,
7215 scroll_pixel_position: gpui::Point<Pixels>,
7216 target_display_point: DisplayPoint,
7217 editor_width: Pixels,
7218 window: &mut Window,
7219 cx: &mut App,
7220 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7221 if target_display_point.row().as_f32() < scroll_top {
7222 let mut element = self
7223 .render_edit_prediction_line_popover(
7224 "Jump to Edit",
7225 Some(IconName::ArrowUp),
7226 window,
7227 cx,
7228 )?
7229 .into_any();
7230
7231 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7232 let offset = point(
7233 (text_bounds.size.width - size.width) / 2.,
7234 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7235 );
7236
7237 let origin = text_bounds.origin + offset;
7238 element.prepaint_at(origin, window, cx);
7239 Some((element, origin))
7240 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7241 let mut element = self
7242 .render_edit_prediction_line_popover(
7243 "Jump to Edit",
7244 Some(IconName::ArrowDown),
7245 window,
7246 cx,
7247 )?
7248 .into_any();
7249
7250 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7251 let offset = point(
7252 (text_bounds.size.width - size.width) / 2.,
7253 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7254 );
7255
7256 let origin = text_bounds.origin + offset;
7257 element.prepaint_at(origin, window, cx);
7258 Some((element, origin))
7259 } else {
7260 self.render_edit_prediction_end_of_line_popover(
7261 "Jump to Edit",
7262 editor_snapshot,
7263 visible_row_range,
7264 target_display_point,
7265 line_height,
7266 scroll_pixel_position,
7267 content_origin,
7268 editor_width,
7269 window,
7270 cx,
7271 )
7272 }
7273 }
7274
7275 fn render_edit_prediction_end_of_line_popover(
7276 self: &mut Editor,
7277 label: &'static str,
7278 editor_snapshot: &EditorSnapshot,
7279 visible_row_range: Range<DisplayRow>,
7280 target_display_point: DisplayPoint,
7281 line_height: Pixels,
7282 scroll_pixel_position: gpui::Point<Pixels>,
7283 content_origin: gpui::Point<Pixels>,
7284 editor_width: Pixels,
7285 window: &mut Window,
7286 cx: &mut App,
7287 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7288 let target_line_end = DisplayPoint::new(
7289 target_display_point.row(),
7290 editor_snapshot.line_len(target_display_point.row()),
7291 );
7292
7293 let mut element = self
7294 .render_edit_prediction_line_popover(label, None, window, cx)?
7295 .into_any();
7296
7297 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7298
7299 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7300
7301 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7302 let mut origin = start_point
7303 + line_origin
7304 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7305 origin.x = origin.x.max(content_origin.x);
7306
7307 let max_x = content_origin.x + editor_width - size.width;
7308
7309 if origin.x > max_x {
7310 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7311
7312 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7313 origin.y += offset;
7314 IconName::ArrowUp
7315 } else {
7316 origin.y -= offset;
7317 IconName::ArrowDown
7318 };
7319
7320 element = self
7321 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7322 .into_any();
7323
7324 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7325
7326 origin.x = content_origin.x + editor_width - size.width - px(2.);
7327 }
7328
7329 element.prepaint_at(origin, window, cx);
7330 Some((element, origin))
7331 }
7332
7333 fn render_edit_prediction_diff_popover(
7334 self: &Editor,
7335 text_bounds: &Bounds<Pixels>,
7336 content_origin: gpui::Point<Pixels>,
7337 editor_snapshot: &EditorSnapshot,
7338 visible_row_range: Range<DisplayRow>,
7339 line_layouts: &[LineWithInvisibles],
7340 line_height: Pixels,
7341 scroll_pixel_position: gpui::Point<Pixels>,
7342 newest_selection_head: Option<DisplayPoint>,
7343 editor_width: Pixels,
7344 style: &EditorStyle,
7345 edits: &Vec<(Range<Anchor>, String)>,
7346 edit_preview: &Option<language::EditPreview>,
7347 snapshot: &language::BufferSnapshot,
7348 window: &mut Window,
7349 cx: &mut App,
7350 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7351 let edit_start = edits
7352 .first()
7353 .unwrap()
7354 .0
7355 .start
7356 .to_display_point(editor_snapshot);
7357 let edit_end = edits
7358 .last()
7359 .unwrap()
7360 .0
7361 .end
7362 .to_display_point(editor_snapshot);
7363
7364 let is_visible = visible_row_range.contains(&edit_start.row())
7365 || visible_row_range.contains(&edit_end.row());
7366 if !is_visible {
7367 return None;
7368 }
7369
7370 let highlighted_edits =
7371 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7372
7373 let styled_text = highlighted_edits.to_styled_text(&style.text);
7374 let line_count = highlighted_edits.text.lines().count();
7375
7376 const BORDER_WIDTH: Pixels = px(1.);
7377
7378 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7379 let has_keybind = keybind.is_some();
7380
7381 let mut element = h_flex()
7382 .items_start()
7383 .child(
7384 h_flex()
7385 .bg(cx.theme().colors().editor_background)
7386 .border(BORDER_WIDTH)
7387 .shadow_sm()
7388 .border_color(cx.theme().colors().border)
7389 .rounded_l_lg()
7390 .when(line_count > 1, |el| el.rounded_br_lg())
7391 .pr_1()
7392 .child(styled_text),
7393 )
7394 .child(
7395 h_flex()
7396 .h(line_height + BORDER_WIDTH * 2.)
7397 .px_1p5()
7398 .gap_1()
7399 // Workaround: For some reason, there's a gap if we don't do this
7400 .ml(-BORDER_WIDTH)
7401 .shadow(smallvec![gpui::BoxShadow {
7402 color: gpui::black().opacity(0.05),
7403 offset: point(px(1.), px(1.)),
7404 blur_radius: px(2.),
7405 spread_radius: px(0.),
7406 }])
7407 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7408 .border(BORDER_WIDTH)
7409 .border_color(cx.theme().colors().border)
7410 .rounded_r_lg()
7411 .id("edit_prediction_diff_popover_keybind")
7412 .when(!has_keybind, |el| {
7413 let status_colors = cx.theme().status();
7414
7415 el.bg(status_colors.error_background)
7416 .border_color(status_colors.error.opacity(0.6))
7417 .child(Icon::new(IconName::Info).color(Color::Error))
7418 .cursor_default()
7419 .hoverable_tooltip(move |_window, cx| {
7420 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7421 })
7422 })
7423 .children(keybind),
7424 )
7425 .into_any();
7426
7427 let longest_row =
7428 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7429 let longest_line_width = if visible_row_range.contains(&longest_row) {
7430 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7431 } else {
7432 layout_line(
7433 longest_row,
7434 editor_snapshot,
7435 style,
7436 editor_width,
7437 |_| false,
7438 window,
7439 cx,
7440 )
7441 .width
7442 };
7443
7444 let viewport_bounds =
7445 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7446 right: -EditorElement::SCROLLBAR_WIDTH,
7447 ..Default::default()
7448 });
7449
7450 let x_after_longest =
7451 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7452 - scroll_pixel_position.x;
7453
7454 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7455
7456 // Fully visible if it can be displayed within the window (allow overlapping other
7457 // panes). However, this is only allowed if the popover starts within text_bounds.
7458 let can_position_to_the_right = x_after_longest < text_bounds.right()
7459 && x_after_longest + element_bounds.width < viewport_bounds.right();
7460
7461 let mut origin = if can_position_to_the_right {
7462 point(
7463 x_after_longest,
7464 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7465 - scroll_pixel_position.y,
7466 )
7467 } else {
7468 let cursor_row = newest_selection_head.map(|head| head.row());
7469 let above_edit = edit_start
7470 .row()
7471 .0
7472 .checked_sub(line_count as u32)
7473 .map(DisplayRow);
7474 let below_edit = Some(edit_end.row() + 1);
7475 let above_cursor =
7476 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7477 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7478
7479 // Place the edit popover adjacent to the edit if there is a location
7480 // available that is onscreen and does not obscure the cursor. Otherwise,
7481 // place it adjacent to the cursor.
7482 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7483 .into_iter()
7484 .flatten()
7485 .find(|&start_row| {
7486 let end_row = start_row + line_count as u32;
7487 visible_row_range.contains(&start_row)
7488 && visible_row_range.contains(&end_row)
7489 && cursor_row.map_or(true, |cursor_row| {
7490 !((start_row..end_row).contains(&cursor_row))
7491 })
7492 })?;
7493
7494 content_origin
7495 + point(
7496 -scroll_pixel_position.x,
7497 row_target.as_f32() * line_height - scroll_pixel_position.y,
7498 )
7499 };
7500
7501 origin.x -= BORDER_WIDTH;
7502
7503 window.defer_draw(element, origin, 1);
7504
7505 // Do not return an element, since it will already be drawn due to defer_draw.
7506 None
7507 }
7508
7509 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7510 px(30.)
7511 }
7512
7513 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7514 if self.read_only(cx) {
7515 cx.theme().players().read_only()
7516 } else {
7517 self.style.as_ref().unwrap().local_player
7518 }
7519 }
7520
7521 fn render_edit_prediction_accept_keybind(
7522 &self,
7523 window: &mut Window,
7524 cx: &App,
7525 ) -> Option<AnyElement> {
7526 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7527 let accept_keystroke = accept_binding.keystroke()?;
7528
7529 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7530
7531 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7532 Color::Accent
7533 } else {
7534 Color::Muted
7535 };
7536
7537 h_flex()
7538 .px_0p5()
7539 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7540 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7541 .text_size(TextSize::XSmall.rems(cx))
7542 .child(h_flex().children(ui::render_modifiers(
7543 &accept_keystroke.modifiers,
7544 PlatformStyle::platform(),
7545 Some(modifiers_color),
7546 Some(IconSize::XSmall.rems().into()),
7547 true,
7548 )))
7549 .when(is_platform_style_mac, |parent| {
7550 parent.child(accept_keystroke.key.clone())
7551 })
7552 .when(!is_platform_style_mac, |parent| {
7553 parent.child(
7554 Key::new(
7555 util::capitalize(&accept_keystroke.key),
7556 Some(Color::Default),
7557 )
7558 .size(Some(IconSize::XSmall.rems().into())),
7559 )
7560 })
7561 .into_any()
7562 .into()
7563 }
7564
7565 fn render_edit_prediction_line_popover(
7566 &self,
7567 label: impl Into<SharedString>,
7568 icon: Option<IconName>,
7569 window: &mut Window,
7570 cx: &App,
7571 ) -> Option<Stateful<Div>> {
7572 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7573
7574 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7575 let has_keybind = keybind.is_some();
7576
7577 let result = h_flex()
7578 .id("ep-line-popover")
7579 .py_0p5()
7580 .pl_1()
7581 .pr(padding_right)
7582 .gap_1()
7583 .rounded_md()
7584 .border_1()
7585 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7586 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7587 .shadow_sm()
7588 .when(!has_keybind, |el| {
7589 let status_colors = cx.theme().status();
7590
7591 el.bg(status_colors.error_background)
7592 .border_color(status_colors.error.opacity(0.6))
7593 .pl_2()
7594 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7595 .cursor_default()
7596 .hoverable_tooltip(move |_window, cx| {
7597 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7598 })
7599 })
7600 .children(keybind)
7601 .child(
7602 Label::new(label)
7603 .size(LabelSize::Small)
7604 .when(!has_keybind, |el| {
7605 el.color(cx.theme().status().error.into()).strikethrough()
7606 }),
7607 )
7608 .when(!has_keybind, |el| {
7609 el.child(
7610 h_flex().ml_1().child(
7611 Icon::new(IconName::Info)
7612 .size(IconSize::Small)
7613 .color(cx.theme().status().error.into()),
7614 ),
7615 )
7616 })
7617 .when_some(icon, |element, icon| {
7618 element.child(
7619 div()
7620 .mt(px(1.5))
7621 .child(Icon::new(icon).size(IconSize::Small)),
7622 )
7623 });
7624
7625 Some(result)
7626 }
7627
7628 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7629 let accent_color = cx.theme().colors().text_accent;
7630 let editor_bg_color = cx.theme().colors().editor_background;
7631 editor_bg_color.blend(accent_color.opacity(0.1))
7632 }
7633
7634 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7635 let accent_color = cx.theme().colors().text_accent;
7636 let editor_bg_color = cx.theme().colors().editor_background;
7637 editor_bg_color.blend(accent_color.opacity(0.6))
7638 }
7639
7640 fn render_edit_prediction_cursor_popover(
7641 &self,
7642 min_width: Pixels,
7643 max_width: Pixels,
7644 cursor_point: Point,
7645 style: &EditorStyle,
7646 accept_keystroke: Option<&gpui::Keystroke>,
7647 _window: &Window,
7648 cx: &mut Context<Editor>,
7649 ) -> Option<AnyElement> {
7650 let provider = self.edit_prediction_provider.as_ref()?;
7651
7652 if provider.provider.needs_terms_acceptance(cx) {
7653 return Some(
7654 h_flex()
7655 .min_w(min_width)
7656 .flex_1()
7657 .px_2()
7658 .py_1()
7659 .gap_3()
7660 .elevation_2(cx)
7661 .hover(|style| style.bg(cx.theme().colors().element_hover))
7662 .id("accept-terms")
7663 .cursor_pointer()
7664 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7665 .on_click(cx.listener(|this, _event, window, cx| {
7666 cx.stop_propagation();
7667 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7668 window.dispatch_action(
7669 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7670 cx,
7671 );
7672 }))
7673 .child(
7674 h_flex()
7675 .flex_1()
7676 .gap_2()
7677 .child(Icon::new(IconName::ZedPredict))
7678 .child(Label::new("Accept Terms of Service"))
7679 .child(div().w_full())
7680 .child(
7681 Icon::new(IconName::ArrowUpRight)
7682 .color(Color::Muted)
7683 .size(IconSize::Small),
7684 )
7685 .into_any_element(),
7686 )
7687 .into_any(),
7688 );
7689 }
7690
7691 let is_refreshing = provider.provider.is_refreshing(cx);
7692
7693 fn pending_completion_container() -> Div {
7694 h_flex()
7695 .h_full()
7696 .flex_1()
7697 .gap_2()
7698 .child(Icon::new(IconName::ZedPredict))
7699 }
7700
7701 let completion = match &self.active_inline_completion {
7702 Some(prediction) => {
7703 if !self.has_visible_completions_menu() {
7704 const RADIUS: Pixels = px(6.);
7705 const BORDER_WIDTH: Pixels = px(1.);
7706
7707 return Some(
7708 h_flex()
7709 .elevation_2(cx)
7710 .border(BORDER_WIDTH)
7711 .border_color(cx.theme().colors().border)
7712 .when(accept_keystroke.is_none(), |el| {
7713 el.border_color(cx.theme().status().error)
7714 })
7715 .rounded(RADIUS)
7716 .rounded_tl(px(0.))
7717 .overflow_hidden()
7718 .child(div().px_1p5().child(match &prediction.completion {
7719 InlineCompletion::Move { target, snapshot } => {
7720 use text::ToPoint as _;
7721 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7722 {
7723 Icon::new(IconName::ZedPredictDown)
7724 } else {
7725 Icon::new(IconName::ZedPredictUp)
7726 }
7727 }
7728 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7729 }))
7730 .child(
7731 h_flex()
7732 .gap_1()
7733 .py_1()
7734 .px_2()
7735 .rounded_r(RADIUS - BORDER_WIDTH)
7736 .border_l_1()
7737 .border_color(cx.theme().colors().border)
7738 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7739 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7740 el.child(
7741 Label::new("Hold")
7742 .size(LabelSize::Small)
7743 .when(accept_keystroke.is_none(), |el| {
7744 el.strikethrough()
7745 })
7746 .line_height_style(LineHeightStyle::UiLabel),
7747 )
7748 })
7749 .id("edit_prediction_cursor_popover_keybind")
7750 .when(accept_keystroke.is_none(), |el| {
7751 let status_colors = cx.theme().status();
7752
7753 el.bg(status_colors.error_background)
7754 .border_color(status_colors.error.opacity(0.6))
7755 .child(Icon::new(IconName::Info).color(Color::Error))
7756 .cursor_default()
7757 .hoverable_tooltip(move |_window, cx| {
7758 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7759 .into()
7760 })
7761 })
7762 .when_some(
7763 accept_keystroke.as_ref(),
7764 |el, accept_keystroke| {
7765 el.child(h_flex().children(ui::render_modifiers(
7766 &accept_keystroke.modifiers,
7767 PlatformStyle::platform(),
7768 Some(Color::Default),
7769 Some(IconSize::XSmall.rems().into()),
7770 false,
7771 )))
7772 },
7773 ),
7774 )
7775 .into_any(),
7776 );
7777 }
7778
7779 self.render_edit_prediction_cursor_popover_preview(
7780 prediction,
7781 cursor_point,
7782 style,
7783 cx,
7784 )?
7785 }
7786
7787 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7788 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7789 stale_completion,
7790 cursor_point,
7791 style,
7792 cx,
7793 )?,
7794
7795 None => {
7796 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7797 }
7798 },
7799
7800 None => pending_completion_container().child(Label::new("No Prediction")),
7801 };
7802
7803 let completion = if is_refreshing {
7804 completion
7805 .with_animation(
7806 "loading-completion",
7807 Animation::new(Duration::from_secs(2))
7808 .repeat()
7809 .with_easing(pulsating_between(0.4, 0.8)),
7810 |label, delta| label.opacity(delta),
7811 )
7812 .into_any_element()
7813 } else {
7814 completion.into_any_element()
7815 };
7816
7817 let has_completion = self.active_inline_completion.is_some();
7818
7819 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7820 Some(
7821 h_flex()
7822 .min_w(min_width)
7823 .max_w(max_width)
7824 .flex_1()
7825 .elevation_2(cx)
7826 .border_color(cx.theme().colors().border)
7827 .child(
7828 div()
7829 .flex_1()
7830 .py_1()
7831 .px_2()
7832 .overflow_hidden()
7833 .child(completion),
7834 )
7835 .when_some(accept_keystroke, |el, accept_keystroke| {
7836 if !accept_keystroke.modifiers.modified() {
7837 return el;
7838 }
7839
7840 el.child(
7841 h_flex()
7842 .h_full()
7843 .border_l_1()
7844 .rounded_r_lg()
7845 .border_color(cx.theme().colors().border)
7846 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7847 .gap_1()
7848 .py_1()
7849 .px_2()
7850 .child(
7851 h_flex()
7852 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7853 .when(is_platform_style_mac, |parent| parent.gap_1())
7854 .child(h_flex().children(ui::render_modifiers(
7855 &accept_keystroke.modifiers,
7856 PlatformStyle::platform(),
7857 Some(if !has_completion {
7858 Color::Muted
7859 } else {
7860 Color::Default
7861 }),
7862 None,
7863 false,
7864 ))),
7865 )
7866 .child(Label::new("Preview").into_any_element())
7867 .opacity(if has_completion { 1.0 } else { 0.4 }),
7868 )
7869 })
7870 .into_any(),
7871 )
7872 }
7873
7874 fn render_edit_prediction_cursor_popover_preview(
7875 &self,
7876 completion: &InlineCompletionState,
7877 cursor_point: Point,
7878 style: &EditorStyle,
7879 cx: &mut Context<Editor>,
7880 ) -> Option<Div> {
7881 use text::ToPoint as _;
7882
7883 fn render_relative_row_jump(
7884 prefix: impl Into<String>,
7885 current_row: u32,
7886 target_row: u32,
7887 ) -> Div {
7888 let (row_diff, arrow) = if target_row < current_row {
7889 (current_row - target_row, IconName::ArrowUp)
7890 } else {
7891 (target_row - current_row, IconName::ArrowDown)
7892 };
7893
7894 h_flex()
7895 .child(
7896 Label::new(format!("{}{}", prefix.into(), row_diff))
7897 .color(Color::Muted)
7898 .size(LabelSize::Small),
7899 )
7900 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7901 }
7902
7903 match &completion.completion {
7904 InlineCompletion::Move {
7905 target, snapshot, ..
7906 } => Some(
7907 h_flex()
7908 .px_2()
7909 .gap_2()
7910 .flex_1()
7911 .child(
7912 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7913 Icon::new(IconName::ZedPredictDown)
7914 } else {
7915 Icon::new(IconName::ZedPredictUp)
7916 },
7917 )
7918 .child(Label::new("Jump to Edit")),
7919 ),
7920
7921 InlineCompletion::Edit {
7922 edits,
7923 edit_preview,
7924 snapshot,
7925 display_mode: _,
7926 } => {
7927 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7928
7929 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7930 &snapshot,
7931 &edits,
7932 edit_preview.as_ref()?,
7933 true,
7934 cx,
7935 )
7936 .first_line_preview();
7937
7938 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7939 .with_default_highlights(&style.text, highlighted_edits.highlights);
7940
7941 let preview = h_flex()
7942 .gap_1()
7943 .min_w_16()
7944 .child(styled_text)
7945 .when(has_more_lines, |parent| parent.child("…"));
7946
7947 let left = if first_edit_row != cursor_point.row {
7948 render_relative_row_jump("", cursor_point.row, first_edit_row)
7949 .into_any_element()
7950 } else {
7951 Icon::new(IconName::ZedPredict).into_any_element()
7952 };
7953
7954 Some(
7955 h_flex()
7956 .h_full()
7957 .flex_1()
7958 .gap_2()
7959 .pr_1()
7960 .overflow_x_hidden()
7961 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7962 .child(left)
7963 .child(preview),
7964 )
7965 }
7966 }
7967 }
7968
7969 fn render_context_menu(
7970 &self,
7971 style: &EditorStyle,
7972 max_height_in_lines: u32,
7973 window: &mut Window,
7974 cx: &mut Context<Editor>,
7975 ) -> Option<AnyElement> {
7976 let menu = self.context_menu.borrow();
7977 let menu = menu.as_ref()?;
7978 if !menu.visible() {
7979 return None;
7980 };
7981 Some(menu.render(style, max_height_in_lines, window, cx))
7982 }
7983
7984 fn render_context_menu_aside(
7985 &mut self,
7986 max_size: Size<Pixels>,
7987 window: &mut Window,
7988 cx: &mut Context<Editor>,
7989 ) -> Option<AnyElement> {
7990 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7991 if menu.visible() {
7992 menu.render_aside(self, max_size, window, cx)
7993 } else {
7994 None
7995 }
7996 })
7997 }
7998
7999 fn hide_context_menu(
8000 &mut self,
8001 window: &mut Window,
8002 cx: &mut Context<Self>,
8003 ) -> Option<CodeContextMenu> {
8004 cx.notify();
8005 self.completion_tasks.clear();
8006 let context_menu = self.context_menu.borrow_mut().take();
8007 self.stale_inline_completion_in_menu.take();
8008 self.update_visible_inline_completion(window, cx);
8009 context_menu
8010 }
8011
8012 fn show_snippet_choices(
8013 &mut self,
8014 choices: &Vec<String>,
8015 selection: Range<Anchor>,
8016 cx: &mut Context<Self>,
8017 ) {
8018 if selection.start.buffer_id.is_none() {
8019 return;
8020 }
8021 let buffer_id = selection.start.buffer_id.unwrap();
8022 let buffer = self.buffer().read(cx).buffer(buffer_id);
8023 let id = post_inc(&mut self.next_completion_id);
8024
8025 if let Some(buffer) = buffer {
8026 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8027 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
8028 ));
8029 }
8030 }
8031
8032 pub fn insert_snippet(
8033 &mut self,
8034 insertion_ranges: &[Range<usize>],
8035 snippet: Snippet,
8036 window: &mut Window,
8037 cx: &mut Context<Self>,
8038 ) -> Result<()> {
8039 struct Tabstop<T> {
8040 is_end_tabstop: bool,
8041 ranges: Vec<Range<T>>,
8042 choices: Option<Vec<String>>,
8043 }
8044
8045 let tabstops = self.buffer.update(cx, |buffer, cx| {
8046 let snippet_text: Arc<str> = snippet.text.clone().into();
8047 let edits = insertion_ranges
8048 .iter()
8049 .cloned()
8050 .map(|range| (range, snippet_text.clone()));
8051 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8052
8053 let snapshot = &*buffer.read(cx);
8054 let snippet = &snippet;
8055 snippet
8056 .tabstops
8057 .iter()
8058 .map(|tabstop| {
8059 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8060 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8061 });
8062 let mut tabstop_ranges = tabstop
8063 .ranges
8064 .iter()
8065 .flat_map(|tabstop_range| {
8066 let mut delta = 0_isize;
8067 insertion_ranges.iter().map(move |insertion_range| {
8068 let insertion_start = insertion_range.start as isize + delta;
8069 delta +=
8070 snippet.text.len() as isize - insertion_range.len() as isize;
8071
8072 let start = ((insertion_start + tabstop_range.start) as usize)
8073 .min(snapshot.len());
8074 let end = ((insertion_start + tabstop_range.end) as usize)
8075 .min(snapshot.len());
8076 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8077 })
8078 })
8079 .collect::<Vec<_>>();
8080 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8081
8082 Tabstop {
8083 is_end_tabstop,
8084 ranges: tabstop_ranges,
8085 choices: tabstop.choices.clone(),
8086 }
8087 })
8088 .collect::<Vec<_>>()
8089 });
8090 if let Some(tabstop) = tabstops.first() {
8091 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8092 s.select_ranges(tabstop.ranges.iter().cloned());
8093 });
8094
8095 if let Some(choices) = &tabstop.choices {
8096 if let Some(selection) = tabstop.ranges.first() {
8097 self.show_snippet_choices(choices, selection.clone(), cx)
8098 }
8099 }
8100
8101 // If we're already at the last tabstop and it's at the end of the snippet,
8102 // we're done, we don't need to keep the state around.
8103 if !tabstop.is_end_tabstop {
8104 let choices = tabstops
8105 .iter()
8106 .map(|tabstop| tabstop.choices.clone())
8107 .collect();
8108
8109 let ranges = tabstops
8110 .into_iter()
8111 .map(|tabstop| tabstop.ranges)
8112 .collect::<Vec<_>>();
8113
8114 self.snippet_stack.push(SnippetState {
8115 active_index: 0,
8116 ranges,
8117 choices,
8118 });
8119 }
8120
8121 // Check whether the just-entered snippet ends with an auto-closable bracket.
8122 if self.autoclose_regions.is_empty() {
8123 let snapshot = self.buffer.read(cx).snapshot(cx);
8124 for selection in &mut self.selections.all::<Point>(cx) {
8125 let selection_head = selection.head();
8126 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8127 continue;
8128 };
8129
8130 let mut bracket_pair = None;
8131 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8132 let prev_chars = snapshot
8133 .reversed_chars_at(selection_head)
8134 .collect::<String>();
8135 for (pair, enabled) in scope.brackets() {
8136 if enabled
8137 && pair.close
8138 && prev_chars.starts_with(pair.start.as_str())
8139 && next_chars.starts_with(pair.end.as_str())
8140 {
8141 bracket_pair = Some(pair.clone());
8142 break;
8143 }
8144 }
8145 if let Some(pair) = bracket_pair {
8146 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8147 let autoclose_enabled =
8148 self.use_autoclose && snapshot_settings.use_autoclose;
8149 if autoclose_enabled {
8150 let start = snapshot.anchor_after(selection_head);
8151 let end = snapshot.anchor_after(selection_head);
8152 self.autoclose_regions.push(AutocloseRegion {
8153 selection_id: selection.id,
8154 range: start..end,
8155 pair,
8156 });
8157 }
8158 }
8159 }
8160 }
8161 }
8162 Ok(())
8163 }
8164
8165 pub fn move_to_next_snippet_tabstop(
8166 &mut self,
8167 window: &mut Window,
8168 cx: &mut Context<Self>,
8169 ) -> bool {
8170 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8171 }
8172
8173 pub fn move_to_prev_snippet_tabstop(
8174 &mut self,
8175 window: &mut Window,
8176 cx: &mut Context<Self>,
8177 ) -> bool {
8178 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8179 }
8180
8181 pub fn move_to_snippet_tabstop(
8182 &mut self,
8183 bias: Bias,
8184 window: &mut Window,
8185 cx: &mut Context<Self>,
8186 ) -> bool {
8187 if let Some(mut snippet) = self.snippet_stack.pop() {
8188 match bias {
8189 Bias::Left => {
8190 if snippet.active_index > 0 {
8191 snippet.active_index -= 1;
8192 } else {
8193 self.snippet_stack.push(snippet);
8194 return false;
8195 }
8196 }
8197 Bias::Right => {
8198 if snippet.active_index + 1 < snippet.ranges.len() {
8199 snippet.active_index += 1;
8200 } else {
8201 self.snippet_stack.push(snippet);
8202 return false;
8203 }
8204 }
8205 }
8206 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8207 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8208 s.select_anchor_ranges(current_ranges.iter().cloned())
8209 });
8210
8211 if let Some(choices) = &snippet.choices[snippet.active_index] {
8212 if let Some(selection) = current_ranges.first() {
8213 self.show_snippet_choices(&choices, selection.clone(), cx);
8214 }
8215 }
8216
8217 // If snippet state is not at the last tabstop, push it back on the stack
8218 if snippet.active_index + 1 < snippet.ranges.len() {
8219 self.snippet_stack.push(snippet);
8220 }
8221 return true;
8222 }
8223 }
8224
8225 false
8226 }
8227
8228 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8229 self.transact(window, cx, |this, window, cx| {
8230 this.select_all(&SelectAll, window, cx);
8231 this.insert("", window, cx);
8232 });
8233 }
8234
8235 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8236 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8237 self.transact(window, cx, |this, window, cx| {
8238 this.select_autoclose_pair(window, cx);
8239 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8240 if !this.linked_edit_ranges.is_empty() {
8241 let selections = this.selections.all::<MultiBufferPoint>(cx);
8242 let snapshot = this.buffer.read(cx).snapshot(cx);
8243
8244 for selection in selections.iter() {
8245 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8246 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8247 if selection_start.buffer_id != selection_end.buffer_id {
8248 continue;
8249 }
8250 if let Some(ranges) =
8251 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8252 {
8253 for (buffer, entries) in ranges {
8254 linked_ranges.entry(buffer).or_default().extend(entries);
8255 }
8256 }
8257 }
8258 }
8259
8260 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8261 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8262 for selection in &mut selections {
8263 if selection.is_empty() {
8264 let old_head = selection.head();
8265 let mut new_head =
8266 movement::left(&display_map, old_head.to_display_point(&display_map))
8267 .to_point(&display_map);
8268 if let Some((buffer, line_buffer_range)) = display_map
8269 .buffer_snapshot
8270 .buffer_line_for_row(MultiBufferRow(old_head.row))
8271 {
8272 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8273 let indent_len = match indent_size.kind {
8274 IndentKind::Space => {
8275 buffer.settings_at(line_buffer_range.start, cx).tab_size
8276 }
8277 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8278 };
8279 if old_head.column <= indent_size.len && old_head.column > 0 {
8280 let indent_len = indent_len.get();
8281 new_head = cmp::min(
8282 new_head,
8283 MultiBufferPoint::new(
8284 old_head.row,
8285 ((old_head.column - 1) / indent_len) * indent_len,
8286 ),
8287 );
8288 }
8289 }
8290
8291 selection.set_head(new_head, SelectionGoal::None);
8292 }
8293 }
8294
8295 this.signature_help_state.set_backspace_pressed(true);
8296 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8297 s.select(selections)
8298 });
8299 this.insert("", window, cx);
8300 let empty_str: Arc<str> = Arc::from("");
8301 for (buffer, edits) in linked_ranges {
8302 let snapshot = buffer.read(cx).snapshot();
8303 use text::ToPoint as TP;
8304
8305 let edits = edits
8306 .into_iter()
8307 .map(|range| {
8308 let end_point = TP::to_point(&range.end, &snapshot);
8309 let mut start_point = TP::to_point(&range.start, &snapshot);
8310
8311 if end_point == start_point {
8312 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8313 .saturating_sub(1);
8314 start_point =
8315 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8316 };
8317
8318 (start_point..end_point, empty_str.clone())
8319 })
8320 .sorted_by_key(|(range, _)| range.start)
8321 .collect::<Vec<_>>();
8322 buffer.update(cx, |this, cx| {
8323 this.edit(edits, None, cx);
8324 })
8325 }
8326 this.refresh_inline_completion(true, false, window, cx);
8327 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8328 });
8329 }
8330
8331 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8332 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8333 self.transact(window, cx, |this, window, cx| {
8334 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8335 s.move_with(|map, selection| {
8336 if selection.is_empty() {
8337 let cursor = movement::right(map, selection.head());
8338 selection.end = cursor;
8339 selection.reversed = true;
8340 selection.goal = SelectionGoal::None;
8341 }
8342 })
8343 });
8344 this.insert("", window, cx);
8345 this.refresh_inline_completion(true, false, window, cx);
8346 });
8347 }
8348
8349 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8350 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8351 if self.move_to_prev_snippet_tabstop(window, cx) {
8352 return;
8353 }
8354 self.outdent(&Outdent, window, cx);
8355 }
8356
8357 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8358 if self.move_to_next_snippet_tabstop(window, cx) {
8359 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8360 return;
8361 }
8362 if self.read_only(cx) {
8363 return;
8364 }
8365 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8366 let mut selections = self.selections.all_adjusted(cx);
8367 let buffer = self.buffer.read(cx);
8368 let snapshot = buffer.snapshot(cx);
8369 let rows_iter = selections.iter().map(|s| s.head().row);
8370 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8371
8372 let mut edits = Vec::new();
8373 let mut prev_edited_row = 0;
8374 let mut row_delta = 0;
8375 for selection in &mut selections {
8376 if selection.start.row != prev_edited_row {
8377 row_delta = 0;
8378 }
8379 prev_edited_row = selection.end.row;
8380
8381 // If the selection is non-empty, then increase the indentation of the selected lines.
8382 if !selection.is_empty() {
8383 row_delta =
8384 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8385 continue;
8386 }
8387
8388 // If the selection is empty and the cursor is in the leading whitespace before the
8389 // suggested indentation, then auto-indent the line.
8390 let cursor = selection.head();
8391 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8392 if let Some(suggested_indent) =
8393 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8394 {
8395 if cursor.column < suggested_indent.len
8396 && cursor.column <= current_indent.len
8397 && current_indent.len <= suggested_indent.len
8398 {
8399 selection.start = Point::new(cursor.row, suggested_indent.len);
8400 selection.end = selection.start;
8401 if row_delta == 0 {
8402 edits.extend(Buffer::edit_for_indent_size_adjustment(
8403 cursor.row,
8404 current_indent,
8405 suggested_indent,
8406 ));
8407 row_delta = suggested_indent.len - current_indent.len;
8408 }
8409 continue;
8410 }
8411 }
8412
8413 // Otherwise, insert a hard or soft tab.
8414 let settings = buffer.language_settings_at(cursor, cx);
8415 let tab_size = if settings.hard_tabs {
8416 IndentSize::tab()
8417 } else {
8418 let tab_size = settings.tab_size.get();
8419 let indent_remainder = snapshot
8420 .text_for_range(Point::new(cursor.row, 0)..cursor)
8421 .flat_map(str::chars)
8422 .fold(row_delta % tab_size, |counter: u32, c| {
8423 if c == '\t' {
8424 0
8425 } else {
8426 (counter + 1) % tab_size
8427 }
8428 });
8429
8430 let chars_to_next_tab_stop = tab_size - indent_remainder;
8431 IndentSize::spaces(chars_to_next_tab_stop)
8432 };
8433 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8434 selection.end = selection.start;
8435 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8436 row_delta += tab_size.len;
8437 }
8438
8439 self.transact(window, cx, |this, window, cx| {
8440 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8441 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8442 s.select(selections)
8443 });
8444 this.refresh_inline_completion(true, false, window, cx);
8445 });
8446 }
8447
8448 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8449 if self.read_only(cx) {
8450 return;
8451 }
8452 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8453 let mut selections = self.selections.all::<Point>(cx);
8454 let mut prev_edited_row = 0;
8455 let mut row_delta = 0;
8456 let mut edits = Vec::new();
8457 let buffer = self.buffer.read(cx);
8458 let snapshot = buffer.snapshot(cx);
8459 for selection in &mut selections {
8460 if selection.start.row != prev_edited_row {
8461 row_delta = 0;
8462 }
8463 prev_edited_row = selection.end.row;
8464
8465 row_delta =
8466 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8467 }
8468
8469 self.transact(window, cx, |this, window, cx| {
8470 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8471 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8472 s.select(selections)
8473 });
8474 });
8475 }
8476
8477 fn indent_selection(
8478 buffer: &MultiBuffer,
8479 snapshot: &MultiBufferSnapshot,
8480 selection: &mut Selection<Point>,
8481 edits: &mut Vec<(Range<Point>, String)>,
8482 delta_for_start_row: u32,
8483 cx: &App,
8484 ) -> u32 {
8485 let settings = buffer.language_settings_at(selection.start, cx);
8486 let tab_size = settings.tab_size.get();
8487 let indent_kind = if settings.hard_tabs {
8488 IndentKind::Tab
8489 } else {
8490 IndentKind::Space
8491 };
8492 let mut start_row = selection.start.row;
8493 let mut end_row = selection.end.row + 1;
8494
8495 // If a selection ends at the beginning of a line, don't indent
8496 // that last line.
8497 if selection.end.column == 0 && selection.end.row > selection.start.row {
8498 end_row -= 1;
8499 }
8500
8501 // Avoid re-indenting a row that has already been indented by a
8502 // previous selection, but still update this selection's column
8503 // to reflect that indentation.
8504 if delta_for_start_row > 0 {
8505 start_row += 1;
8506 selection.start.column += delta_for_start_row;
8507 if selection.end.row == selection.start.row {
8508 selection.end.column += delta_for_start_row;
8509 }
8510 }
8511
8512 let mut delta_for_end_row = 0;
8513 let has_multiple_rows = start_row + 1 != end_row;
8514 for row in start_row..end_row {
8515 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8516 let indent_delta = match (current_indent.kind, indent_kind) {
8517 (IndentKind::Space, IndentKind::Space) => {
8518 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8519 IndentSize::spaces(columns_to_next_tab_stop)
8520 }
8521 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8522 (_, IndentKind::Tab) => IndentSize::tab(),
8523 };
8524
8525 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8526 0
8527 } else {
8528 selection.start.column
8529 };
8530 let row_start = Point::new(row, start);
8531 edits.push((
8532 row_start..row_start,
8533 indent_delta.chars().collect::<String>(),
8534 ));
8535
8536 // Update this selection's endpoints to reflect the indentation.
8537 if row == selection.start.row {
8538 selection.start.column += indent_delta.len;
8539 }
8540 if row == selection.end.row {
8541 selection.end.column += indent_delta.len;
8542 delta_for_end_row = indent_delta.len;
8543 }
8544 }
8545
8546 if selection.start.row == selection.end.row {
8547 delta_for_start_row + delta_for_end_row
8548 } else {
8549 delta_for_end_row
8550 }
8551 }
8552
8553 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8554 if self.read_only(cx) {
8555 return;
8556 }
8557 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8558 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8559 let selections = self.selections.all::<Point>(cx);
8560 let mut deletion_ranges = Vec::new();
8561 let mut last_outdent = None;
8562 {
8563 let buffer = self.buffer.read(cx);
8564 let snapshot = buffer.snapshot(cx);
8565 for selection in &selections {
8566 let settings = buffer.language_settings_at(selection.start, cx);
8567 let tab_size = settings.tab_size.get();
8568 let mut rows = selection.spanned_rows(false, &display_map);
8569
8570 // Avoid re-outdenting a row that has already been outdented by a
8571 // previous selection.
8572 if let Some(last_row) = last_outdent {
8573 if last_row == rows.start {
8574 rows.start = rows.start.next_row();
8575 }
8576 }
8577 let has_multiple_rows = rows.len() > 1;
8578 for row in rows.iter_rows() {
8579 let indent_size = snapshot.indent_size_for_line(row);
8580 if indent_size.len > 0 {
8581 let deletion_len = match indent_size.kind {
8582 IndentKind::Space => {
8583 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8584 if columns_to_prev_tab_stop == 0 {
8585 tab_size
8586 } else {
8587 columns_to_prev_tab_stop
8588 }
8589 }
8590 IndentKind::Tab => 1,
8591 };
8592 let start = if has_multiple_rows
8593 || deletion_len > selection.start.column
8594 || indent_size.len < selection.start.column
8595 {
8596 0
8597 } else {
8598 selection.start.column - deletion_len
8599 };
8600 deletion_ranges.push(
8601 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8602 );
8603 last_outdent = Some(row);
8604 }
8605 }
8606 }
8607 }
8608
8609 self.transact(window, cx, |this, window, cx| {
8610 this.buffer.update(cx, |buffer, cx| {
8611 let empty_str: Arc<str> = Arc::default();
8612 buffer.edit(
8613 deletion_ranges
8614 .into_iter()
8615 .map(|range| (range, empty_str.clone())),
8616 None,
8617 cx,
8618 );
8619 });
8620 let selections = this.selections.all::<usize>(cx);
8621 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8622 s.select(selections)
8623 });
8624 });
8625 }
8626
8627 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8628 if self.read_only(cx) {
8629 return;
8630 }
8631 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8632 let selections = self
8633 .selections
8634 .all::<usize>(cx)
8635 .into_iter()
8636 .map(|s| s.range());
8637
8638 self.transact(window, cx, |this, window, cx| {
8639 this.buffer.update(cx, |buffer, cx| {
8640 buffer.autoindent_ranges(selections, cx);
8641 });
8642 let selections = this.selections.all::<usize>(cx);
8643 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8644 s.select(selections)
8645 });
8646 });
8647 }
8648
8649 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8650 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8651 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8652 let selections = self.selections.all::<Point>(cx);
8653
8654 let mut new_cursors = Vec::new();
8655 let mut edit_ranges = Vec::new();
8656 let mut selections = selections.iter().peekable();
8657 while let Some(selection) = selections.next() {
8658 let mut rows = selection.spanned_rows(false, &display_map);
8659 let goal_display_column = selection.head().to_display_point(&display_map).column();
8660
8661 // Accumulate contiguous regions of rows that we want to delete.
8662 while let Some(next_selection) = selections.peek() {
8663 let next_rows = next_selection.spanned_rows(false, &display_map);
8664 if next_rows.start <= rows.end {
8665 rows.end = next_rows.end;
8666 selections.next().unwrap();
8667 } else {
8668 break;
8669 }
8670 }
8671
8672 let buffer = &display_map.buffer_snapshot;
8673 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8674 let edit_end;
8675 let cursor_buffer_row;
8676 if buffer.max_point().row >= rows.end.0 {
8677 // If there's a line after the range, delete the \n from the end of the row range
8678 // and position the cursor on the next line.
8679 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8680 cursor_buffer_row = rows.end;
8681 } else {
8682 // If there isn't a line after the range, delete the \n from the line before the
8683 // start of the row range and position the cursor there.
8684 edit_start = edit_start.saturating_sub(1);
8685 edit_end = buffer.len();
8686 cursor_buffer_row = rows.start.previous_row();
8687 }
8688
8689 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8690 *cursor.column_mut() =
8691 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8692
8693 new_cursors.push((
8694 selection.id,
8695 buffer.anchor_after(cursor.to_point(&display_map)),
8696 ));
8697 edit_ranges.push(edit_start..edit_end);
8698 }
8699
8700 self.transact(window, cx, |this, window, cx| {
8701 let buffer = this.buffer.update(cx, |buffer, cx| {
8702 let empty_str: Arc<str> = Arc::default();
8703 buffer.edit(
8704 edit_ranges
8705 .into_iter()
8706 .map(|range| (range, empty_str.clone())),
8707 None,
8708 cx,
8709 );
8710 buffer.snapshot(cx)
8711 });
8712 let new_selections = new_cursors
8713 .into_iter()
8714 .map(|(id, cursor)| {
8715 let cursor = cursor.to_point(&buffer);
8716 Selection {
8717 id,
8718 start: cursor,
8719 end: cursor,
8720 reversed: false,
8721 goal: SelectionGoal::None,
8722 }
8723 })
8724 .collect();
8725
8726 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8727 s.select(new_selections);
8728 });
8729 });
8730 }
8731
8732 pub fn join_lines_impl(
8733 &mut self,
8734 insert_whitespace: bool,
8735 window: &mut Window,
8736 cx: &mut Context<Self>,
8737 ) {
8738 if self.read_only(cx) {
8739 return;
8740 }
8741 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8742 for selection in self.selections.all::<Point>(cx) {
8743 let start = MultiBufferRow(selection.start.row);
8744 // Treat single line selections as if they include the next line. Otherwise this action
8745 // would do nothing for single line selections individual cursors.
8746 let end = if selection.start.row == selection.end.row {
8747 MultiBufferRow(selection.start.row + 1)
8748 } else {
8749 MultiBufferRow(selection.end.row)
8750 };
8751
8752 if let Some(last_row_range) = row_ranges.last_mut() {
8753 if start <= last_row_range.end {
8754 last_row_range.end = end;
8755 continue;
8756 }
8757 }
8758 row_ranges.push(start..end);
8759 }
8760
8761 let snapshot = self.buffer.read(cx).snapshot(cx);
8762 let mut cursor_positions = Vec::new();
8763 for row_range in &row_ranges {
8764 let anchor = snapshot.anchor_before(Point::new(
8765 row_range.end.previous_row().0,
8766 snapshot.line_len(row_range.end.previous_row()),
8767 ));
8768 cursor_positions.push(anchor..anchor);
8769 }
8770
8771 self.transact(window, cx, |this, window, cx| {
8772 for row_range in row_ranges.into_iter().rev() {
8773 for row in row_range.iter_rows().rev() {
8774 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8775 let next_line_row = row.next_row();
8776 let indent = snapshot.indent_size_for_line(next_line_row);
8777 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8778
8779 let replace =
8780 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8781 " "
8782 } else {
8783 ""
8784 };
8785
8786 this.buffer.update(cx, |buffer, cx| {
8787 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8788 });
8789 }
8790 }
8791
8792 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8793 s.select_anchor_ranges(cursor_positions)
8794 });
8795 });
8796 }
8797
8798 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8799 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8800 self.join_lines_impl(true, window, cx);
8801 }
8802
8803 pub fn sort_lines_case_sensitive(
8804 &mut self,
8805 _: &SortLinesCaseSensitive,
8806 window: &mut Window,
8807 cx: &mut Context<Self>,
8808 ) {
8809 self.manipulate_lines(window, cx, |lines| lines.sort())
8810 }
8811
8812 pub fn sort_lines_case_insensitive(
8813 &mut self,
8814 _: &SortLinesCaseInsensitive,
8815 window: &mut Window,
8816 cx: &mut Context<Self>,
8817 ) {
8818 self.manipulate_lines(window, cx, |lines| {
8819 lines.sort_by_key(|line| line.to_lowercase())
8820 })
8821 }
8822
8823 pub fn unique_lines_case_insensitive(
8824 &mut self,
8825 _: &UniqueLinesCaseInsensitive,
8826 window: &mut Window,
8827 cx: &mut Context<Self>,
8828 ) {
8829 self.manipulate_lines(window, cx, |lines| {
8830 let mut seen = HashSet::default();
8831 lines.retain(|line| seen.insert(line.to_lowercase()));
8832 })
8833 }
8834
8835 pub fn unique_lines_case_sensitive(
8836 &mut self,
8837 _: &UniqueLinesCaseSensitive,
8838 window: &mut Window,
8839 cx: &mut Context<Self>,
8840 ) {
8841 self.manipulate_lines(window, cx, |lines| {
8842 let mut seen = HashSet::default();
8843 lines.retain(|line| seen.insert(*line));
8844 })
8845 }
8846
8847 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8848 let Some(project) = self.project.clone() else {
8849 return;
8850 };
8851 self.reload(project, window, cx)
8852 .detach_and_notify_err(window, cx);
8853 }
8854
8855 pub fn restore_file(
8856 &mut self,
8857 _: &::git::RestoreFile,
8858 window: &mut Window,
8859 cx: &mut Context<Self>,
8860 ) {
8861 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8862 let mut buffer_ids = HashSet::default();
8863 let snapshot = self.buffer().read(cx).snapshot(cx);
8864 for selection in self.selections.all::<usize>(cx) {
8865 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8866 }
8867
8868 let buffer = self.buffer().read(cx);
8869 let ranges = buffer_ids
8870 .into_iter()
8871 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8872 .collect::<Vec<_>>();
8873
8874 self.restore_hunks_in_ranges(ranges, window, cx);
8875 }
8876
8877 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8878 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8879 let selections = self
8880 .selections
8881 .all(cx)
8882 .into_iter()
8883 .map(|s| s.range())
8884 .collect();
8885 self.restore_hunks_in_ranges(selections, window, cx);
8886 }
8887
8888 pub fn restore_hunks_in_ranges(
8889 &mut self,
8890 ranges: Vec<Range<Point>>,
8891 window: &mut Window,
8892 cx: &mut Context<Editor>,
8893 ) {
8894 let mut revert_changes = HashMap::default();
8895 let chunk_by = self
8896 .snapshot(window, cx)
8897 .hunks_for_ranges(ranges)
8898 .into_iter()
8899 .chunk_by(|hunk| hunk.buffer_id);
8900 for (buffer_id, hunks) in &chunk_by {
8901 let hunks = hunks.collect::<Vec<_>>();
8902 for hunk in &hunks {
8903 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8904 }
8905 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8906 }
8907 drop(chunk_by);
8908 if !revert_changes.is_empty() {
8909 self.transact(window, cx, |editor, window, cx| {
8910 editor.restore(revert_changes, window, cx);
8911 });
8912 }
8913 }
8914
8915 pub fn open_active_item_in_terminal(
8916 &mut self,
8917 _: &OpenInTerminal,
8918 window: &mut Window,
8919 cx: &mut Context<Self>,
8920 ) {
8921 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8922 let project_path = buffer.read(cx).project_path(cx)?;
8923 let project = self.project.as_ref()?.read(cx);
8924 let entry = project.entry_for_path(&project_path, cx)?;
8925 let parent = match &entry.canonical_path {
8926 Some(canonical_path) => canonical_path.to_path_buf(),
8927 None => project.absolute_path(&project_path, cx)?,
8928 }
8929 .parent()?
8930 .to_path_buf();
8931 Some(parent)
8932 }) {
8933 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8934 }
8935 }
8936
8937 fn set_breakpoint_context_menu(
8938 &mut self,
8939 display_row: DisplayRow,
8940 position: Option<Anchor>,
8941 clicked_point: gpui::Point<Pixels>,
8942 window: &mut Window,
8943 cx: &mut Context<Self>,
8944 ) {
8945 if !cx.has_flag::<Debugger>() {
8946 return;
8947 }
8948 let source = self
8949 .buffer
8950 .read(cx)
8951 .snapshot(cx)
8952 .anchor_before(Point::new(display_row.0, 0u32));
8953
8954 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8955
8956 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8957 self,
8958 source,
8959 clicked_point,
8960 context_menu,
8961 window,
8962 cx,
8963 );
8964 }
8965
8966 fn add_edit_breakpoint_block(
8967 &mut self,
8968 anchor: Anchor,
8969 breakpoint: &Breakpoint,
8970 edit_action: BreakpointPromptEditAction,
8971 window: &mut Window,
8972 cx: &mut Context<Self>,
8973 ) {
8974 let weak_editor = cx.weak_entity();
8975 let bp_prompt = cx.new(|cx| {
8976 BreakpointPromptEditor::new(
8977 weak_editor,
8978 anchor,
8979 breakpoint.clone(),
8980 edit_action,
8981 window,
8982 cx,
8983 )
8984 });
8985
8986 let height = bp_prompt.update(cx, |this, cx| {
8987 this.prompt
8988 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8989 });
8990 let cloned_prompt = bp_prompt.clone();
8991 let blocks = vec![BlockProperties {
8992 style: BlockStyle::Sticky,
8993 placement: BlockPlacement::Above(anchor),
8994 height: Some(height),
8995 render: Arc::new(move |cx| {
8996 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8997 cloned_prompt.clone().into_any_element()
8998 }),
8999 priority: 0,
9000 }];
9001
9002 let focus_handle = bp_prompt.focus_handle(cx);
9003 window.focus(&focus_handle);
9004
9005 let block_ids = self.insert_blocks(blocks, None, cx);
9006 bp_prompt.update(cx, |prompt, _| {
9007 prompt.add_block_ids(block_ids);
9008 });
9009 }
9010
9011 pub(crate) fn breakpoint_at_row(
9012 &self,
9013 row: u32,
9014 window: &mut Window,
9015 cx: &mut Context<Self>,
9016 ) -> Option<(Anchor, Breakpoint)> {
9017 let snapshot = self.snapshot(window, cx);
9018 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9019
9020 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9021 }
9022
9023 pub(crate) fn breakpoint_at_anchor(
9024 &self,
9025 breakpoint_position: Anchor,
9026 snapshot: &EditorSnapshot,
9027 cx: &mut Context<Self>,
9028 ) -> Option<(Anchor, Breakpoint)> {
9029 let project = self.project.clone()?;
9030
9031 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9032 snapshot
9033 .buffer_snapshot
9034 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9035 })?;
9036
9037 let enclosing_excerpt = breakpoint_position.excerpt_id;
9038 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9039 let buffer_snapshot = buffer.read(cx).snapshot();
9040
9041 let row = buffer_snapshot
9042 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9043 .row;
9044
9045 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9046 let anchor_end = snapshot
9047 .buffer_snapshot
9048 .anchor_after(Point::new(row, line_len));
9049
9050 let bp = self
9051 .breakpoint_store
9052 .as_ref()?
9053 .read_with(cx, |breakpoint_store, cx| {
9054 breakpoint_store
9055 .breakpoints(
9056 &buffer,
9057 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9058 &buffer_snapshot,
9059 cx,
9060 )
9061 .next()
9062 .and_then(|(anchor, bp)| {
9063 let breakpoint_row = buffer_snapshot
9064 .summary_for_anchor::<text::PointUtf16>(anchor)
9065 .row;
9066
9067 if breakpoint_row == row {
9068 snapshot
9069 .buffer_snapshot
9070 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9071 .map(|anchor| (anchor, bp.clone()))
9072 } else {
9073 None
9074 }
9075 })
9076 });
9077 bp
9078 }
9079
9080 pub fn edit_log_breakpoint(
9081 &mut self,
9082 _: &EditLogBreakpoint,
9083 window: &mut Window,
9084 cx: &mut Context<Self>,
9085 ) {
9086 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9087 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9088 message: None,
9089 state: BreakpointState::Enabled,
9090 condition: None,
9091 hit_condition: None,
9092 });
9093
9094 self.add_edit_breakpoint_block(
9095 anchor,
9096 &breakpoint,
9097 BreakpointPromptEditAction::Log,
9098 window,
9099 cx,
9100 );
9101 }
9102 }
9103
9104 fn breakpoints_at_cursors(
9105 &self,
9106 window: &mut Window,
9107 cx: &mut Context<Self>,
9108 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9109 let snapshot = self.snapshot(window, cx);
9110 let cursors = self
9111 .selections
9112 .disjoint_anchors()
9113 .into_iter()
9114 .map(|selection| {
9115 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9116
9117 let breakpoint_position = self
9118 .breakpoint_at_row(cursor_position.row, window, cx)
9119 .map(|bp| bp.0)
9120 .unwrap_or_else(|| {
9121 snapshot
9122 .display_snapshot
9123 .buffer_snapshot
9124 .anchor_after(Point::new(cursor_position.row, 0))
9125 });
9126
9127 let breakpoint = self
9128 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9129 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9130
9131 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9132 })
9133 // 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.
9134 .collect::<HashMap<Anchor, _>>();
9135
9136 cursors.into_iter().collect()
9137 }
9138
9139 pub fn enable_breakpoint(
9140 &mut self,
9141 _: &crate::actions::EnableBreakpoint,
9142 window: &mut Window,
9143 cx: &mut Context<Self>,
9144 ) {
9145 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9146 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9147 continue;
9148 };
9149 self.edit_breakpoint_at_anchor(
9150 anchor,
9151 breakpoint,
9152 BreakpointEditAction::InvertState,
9153 cx,
9154 );
9155 }
9156 }
9157
9158 pub fn disable_breakpoint(
9159 &mut self,
9160 _: &crate::actions::DisableBreakpoint,
9161 window: &mut Window,
9162 cx: &mut Context<Self>,
9163 ) {
9164 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9165 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9166 continue;
9167 };
9168 self.edit_breakpoint_at_anchor(
9169 anchor,
9170 breakpoint,
9171 BreakpointEditAction::InvertState,
9172 cx,
9173 );
9174 }
9175 }
9176
9177 pub fn toggle_breakpoint(
9178 &mut self,
9179 _: &crate::actions::ToggleBreakpoint,
9180 window: &mut Window,
9181 cx: &mut Context<Self>,
9182 ) {
9183 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9184 if let Some(breakpoint) = breakpoint {
9185 self.edit_breakpoint_at_anchor(
9186 anchor,
9187 breakpoint,
9188 BreakpointEditAction::Toggle,
9189 cx,
9190 );
9191 } else {
9192 self.edit_breakpoint_at_anchor(
9193 anchor,
9194 Breakpoint::new_standard(),
9195 BreakpointEditAction::Toggle,
9196 cx,
9197 );
9198 }
9199 }
9200 }
9201
9202 pub fn edit_breakpoint_at_anchor(
9203 &mut self,
9204 breakpoint_position: Anchor,
9205 breakpoint: Breakpoint,
9206 edit_action: BreakpointEditAction,
9207 cx: &mut Context<Self>,
9208 ) {
9209 let Some(breakpoint_store) = &self.breakpoint_store else {
9210 return;
9211 };
9212
9213 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9214 if breakpoint_position == Anchor::min() {
9215 self.buffer()
9216 .read(cx)
9217 .excerpt_buffer_ids()
9218 .into_iter()
9219 .next()
9220 } else {
9221 None
9222 }
9223 }) else {
9224 return;
9225 };
9226
9227 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9228 return;
9229 };
9230
9231 breakpoint_store.update(cx, |breakpoint_store, cx| {
9232 breakpoint_store.toggle_breakpoint(
9233 buffer,
9234 (breakpoint_position.text_anchor, breakpoint),
9235 edit_action,
9236 cx,
9237 );
9238 });
9239
9240 cx.notify();
9241 }
9242
9243 #[cfg(any(test, feature = "test-support"))]
9244 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9245 self.breakpoint_store.clone()
9246 }
9247
9248 pub fn prepare_restore_change(
9249 &self,
9250 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9251 hunk: &MultiBufferDiffHunk,
9252 cx: &mut App,
9253 ) -> Option<()> {
9254 if hunk.is_created_file() {
9255 return None;
9256 }
9257 let buffer = self.buffer.read(cx);
9258 let diff = buffer.diff_for(hunk.buffer_id)?;
9259 let buffer = buffer.buffer(hunk.buffer_id)?;
9260 let buffer = buffer.read(cx);
9261 let original_text = diff
9262 .read(cx)
9263 .base_text()
9264 .as_rope()
9265 .slice(hunk.diff_base_byte_range.clone());
9266 let buffer_snapshot = buffer.snapshot();
9267 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9268 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9269 probe
9270 .0
9271 .start
9272 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9273 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9274 }) {
9275 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9276 Some(())
9277 } else {
9278 None
9279 }
9280 }
9281
9282 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9283 self.manipulate_lines(window, cx, |lines| lines.reverse())
9284 }
9285
9286 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9287 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9288 }
9289
9290 fn manipulate_lines<Fn>(
9291 &mut self,
9292 window: &mut Window,
9293 cx: &mut Context<Self>,
9294 mut callback: Fn,
9295 ) where
9296 Fn: FnMut(&mut Vec<&str>),
9297 {
9298 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9299
9300 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9301 let buffer = self.buffer.read(cx).snapshot(cx);
9302
9303 let mut edits = Vec::new();
9304
9305 let selections = self.selections.all::<Point>(cx);
9306 let mut selections = selections.iter().peekable();
9307 let mut contiguous_row_selections = Vec::new();
9308 let mut new_selections = Vec::new();
9309 let mut added_lines = 0;
9310 let mut removed_lines = 0;
9311
9312 while let Some(selection) = selections.next() {
9313 let (start_row, end_row) = consume_contiguous_rows(
9314 &mut contiguous_row_selections,
9315 selection,
9316 &display_map,
9317 &mut selections,
9318 );
9319
9320 let start_point = Point::new(start_row.0, 0);
9321 let end_point = Point::new(
9322 end_row.previous_row().0,
9323 buffer.line_len(end_row.previous_row()),
9324 );
9325 let text = buffer
9326 .text_for_range(start_point..end_point)
9327 .collect::<String>();
9328
9329 let mut lines = text.split('\n').collect_vec();
9330
9331 let lines_before = lines.len();
9332 callback(&mut lines);
9333 let lines_after = lines.len();
9334
9335 edits.push((start_point..end_point, lines.join("\n")));
9336
9337 // Selections must change based on added and removed line count
9338 let start_row =
9339 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9340 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9341 new_selections.push(Selection {
9342 id: selection.id,
9343 start: start_row,
9344 end: end_row,
9345 goal: SelectionGoal::None,
9346 reversed: selection.reversed,
9347 });
9348
9349 if lines_after > lines_before {
9350 added_lines += lines_after - lines_before;
9351 } else if lines_before > lines_after {
9352 removed_lines += lines_before - lines_after;
9353 }
9354 }
9355
9356 self.transact(window, cx, |this, window, cx| {
9357 let buffer = this.buffer.update(cx, |buffer, cx| {
9358 buffer.edit(edits, None, cx);
9359 buffer.snapshot(cx)
9360 });
9361
9362 // Recalculate offsets on newly edited buffer
9363 let new_selections = new_selections
9364 .iter()
9365 .map(|s| {
9366 let start_point = Point::new(s.start.0, 0);
9367 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9368 Selection {
9369 id: s.id,
9370 start: buffer.point_to_offset(start_point),
9371 end: buffer.point_to_offset(end_point),
9372 goal: s.goal,
9373 reversed: s.reversed,
9374 }
9375 })
9376 .collect();
9377
9378 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9379 s.select(new_selections);
9380 });
9381
9382 this.request_autoscroll(Autoscroll::fit(), cx);
9383 });
9384 }
9385
9386 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9387 self.manipulate_text(window, cx, |text| {
9388 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9389 if has_upper_case_characters {
9390 text.to_lowercase()
9391 } else {
9392 text.to_uppercase()
9393 }
9394 })
9395 }
9396
9397 pub fn convert_to_upper_case(
9398 &mut self,
9399 _: &ConvertToUpperCase,
9400 window: &mut Window,
9401 cx: &mut Context<Self>,
9402 ) {
9403 self.manipulate_text(window, cx, |text| text.to_uppercase())
9404 }
9405
9406 pub fn convert_to_lower_case(
9407 &mut self,
9408 _: &ConvertToLowerCase,
9409 window: &mut Window,
9410 cx: &mut Context<Self>,
9411 ) {
9412 self.manipulate_text(window, cx, |text| text.to_lowercase())
9413 }
9414
9415 pub fn convert_to_title_case(
9416 &mut self,
9417 _: &ConvertToTitleCase,
9418 window: &mut Window,
9419 cx: &mut Context<Self>,
9420 ) {
9421 self.manipulate_text(window, cx, |text| {
9422 text.split('\n')
9423 .map(|line| line.to_case(Case::Title))
9424 .join("\n")
9425 })
9426 }
9427
9428 pub fn convert_to_snake_case(
9429 &mut self,
9430 _: &ConvertToSnakeCase,
9431 window: &mut Window,
9432 cx: &mut Context<Self>,
9433 ) {
9434 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9435 }
9436
9437 pub fn convert_to_kebab_case(
9438 &mut self,
9439 _: &ConvertToKebabCase,
9440 window: &mut Window,
9441 cx: &mut Context<Self>,
9442 ) {
9443 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9444 }
9445
9446 pub fn convert_to_upper_camel_case(
9447 &mut self,
9448 _: &ConvertToUpperCamelCase,
9449 window: &mut Window,
9450 cx: &mut Context<Self>,
9451 ) {
9452 self.manipulate_text(window, cx, |text| {
9453 text.split('\n')
9454 .map(|line| line.to_case(Case::UpperCamel))
9455 .join("\n")
9456 })
9457 }
9458
9459 pub fn convert_to_lower_camel_case(
9460 &mut self,
9461 _: &ConvertToLowerCamelCase,
9462 window: &mut Window,
9463 cx: &mut Context<Self>,
9464 ) {
9465 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9466 }
9467
9468 pub fn convert_to_opposite_case(
9469 &mut self,
9470 _: &ConvertToOppositeCase,
9471 window: &mut Window,
9472 cx: &mut Context<Self>,
9473 ) {
9474 self.manipulate_text(window, cx, |text| {
9475 text.chars()
9476 .fold(String::with_capacity(text.len()), |mut t, c| {
9477 if c.is_uppercase() {
9478 t.extend(c.to_lowercase());
9479 } else {
9480 t.extend(c.to_uppercase());
9481 }
9482 t
9483 })
9484 })
9485 }
9486
9487 pub fn convert_to_rot13(
9488 &mut self,
9489 _: &ConvertToRot13,
9490 window: &mut Window,
9491 cx: &mut Context<Self>,
9492 ) {
9493 self.manipulate_text(window, cx, |text| {
9494 text.chars()
9495 .map(|c| match c {
9496 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9497 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9498 _ => c,
9499 })
9500 .collect()
9501 })
9502 }
9503
9504 pub fn convert_to_rot47(
9505 &mut self,
9506 _: &ConvertToRot47,
9507 window: &mut Window,
9508 cx: &mut Context<Self>,
9509 ) {
9510 self.manipulate_text(window, cx, |text| {
9511 text.chars()
9512 .map(|c| {
9513 let code_point = c as u32;
9514 if code_point >= 33 && code_point <= 126 {
9515 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9516 }
9517 c
9518 })
9519 .collect()
9520 })
9521 }
9522
9523 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9524 where
9525 Fn: FnMut(&str) -> String,
9526 {
9527 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9528 let buffer = self.buffer.read(cx).snapshot(cx);
9529
9530 let mut new_selections = Vec::new();
9531 let mut edits = Vec::new();
9532 let mut selection_adjustment = 0i32;
9533
9534 for selection in self.selections.all::<usize>(cx) {
9535 let selection_is_empty = selection.is_empty();
9536
9537 let (start, end) = if selection_is_empty {
9538 let word_range = movement::surrounding_word(
9539 &display_map,
9540 selection.start.to_display_point(&display_map),
9541 );
9542 let start = word_range.start.to_offset(&display_map, Bias::Left);
9543 let end = word_range.end.to_offset(&display_map, Bias::Left);
9544 (start, end)
9545 } else {
9546 (selection.start, selection.end)
9547 };
9548
9549 let text = buffer.text_for_range(start..end).collect::<String>();
9550 let old_length = text.len() as i32;
9551 let text = callback(&text);
9552
9553 new_selections.push(Selection {
9554 start: (start as i32 - selection_adjustment) as usize,
9555 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9556 goal: SelectionGoal::None,
9557 ..selection
9558 });
9559
9560 selection_adjustment += old_length - text.len() as i32;
9561
9562 edits.push((start..end, text));
9563 }
9564
9565 self.transact(window, cx, |this, window, cx| {
9566 this.buffer.update(cx, |buffer, cx| {
9567 buffer.edit(edits, None, cx);
9568 });
9569
9570 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9571 s.select(new_selections);
9572 });
9573
9574 this.request_autoscroll(Autoscroll::fit(), cx);
9575 });
9576 }
9577
9578 pub fn duplicate(
9579 &mut self,
9580 upwards: bool,
9581 whole_lines: bool,
9582 window: &mut Window,
9583 cx: &mut Context<Self>,
9584 ) {
9585 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9586
9587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9588 let buffer = &display_map.buffer_snapshot;
9589 let selections = self.selections.all::<Point>(cx);
9590
9591 let mut edits = Vec::new();
9592 let mut selections_iter = selections.iter().peekable();
9593 while let Some(selection) = selections_iter.next() {
9594 let mut rows = selection.spanned_rows(false, &display_map);
9595 // duplicate line-wise
9596 if whole_lines || selection.start == selection.end {
9597 // Avoid duplicating the same lines twice.
9598 while let Some(next_selection) = selections_iter.peek() {
9599 let next_rows = next_selection.spanned_rows(false, &display_map);
9600 if next_rows.start < rows.end {
9601 rows.end = next_rows.end;
9602 selections_iter.next().unwrap();
9603 } else {
9604 break;
9605 }
9606 }
9607
9608 // Copy the text from the selected row region and splice it either at the start
9609 // or end of the region.
9610 let start = Point::new(rows.start.0, 0);
9611 let end = Point::new(
9612 rows.end.previous_row().0,
9613 buffer.line_len(rows.end.previous_row()),
9614 );
9615 let text = buffer
9616 .text_for_range(start..end)
9617 .chain(Some("\n"))
9618 .collect::<String>();
9619 let insert_location = if upwards {
9620 Point::new(rows.end.0, 0)
9621 } else {
9622 start
9623 };
9624 edits.push((insert_location..insert_location, text));
9625 } else {
9626 // duplicate character-wise
9627 let start = selection.start;
9628 let end = selection.end;
9629 let text = buffer.text_for_range(start..end).collect::<String>();
9630 edits.push((selection.end..selection.end, text));
9631 }
9632 }
9633
9634 self.transact(window, cx, |this, _, cx| {
9635 this.buffer.update(cx, |buffer, cx| {
9636 buffer.edit(edits, None, cx);
9637 });
9638
9639 this.request_autoscroll(Autoscroll::fit(), cx);
9640 });
9641 }
9642
9643 pub fn duplicate_line_up(
9644 &mut self,
9645 _: &DuplicateLineUp,
9646 window: &mut Window,
9647 cx: &mut Context<Self>,
9648 ) {
9649 self.duplicate(true, true, window, cx);
9650 }
9651
9652 pub fn duplicate_line_down(
9653 &mut self,
9654 _: &DuplicateLineDown,
9655 window: &mut Window,
9656 cx: &mut Context<Self>,
9657 ) {
9658 self.duplicate(false, true, window, cx);
9659 }
9660
9661 pub fn duplicate_selection(
9662 &mut self,
9663 _: &DuplicateSelection,
9664 window: &mut Window,
9665 cx: &mut Context<Self>,
9666 ) {
9667 self.duplicate(false, false, window, cx);
9668 }
9669
9670 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9671 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9672
9673 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9674 let buffer = self.buffer.read(cx).snapshot(cx);
9675
9676 let mut edits = Vec::new();
9677 let mut unfold_ranges = Vec::new();
9678 let mut refold_creases = Vec::new();
9679
9680 let selections = self.selections.all::<Point>(cx);
9681 let mut selections = selections.iter().peekable();
9682 let mut contiguous_row_selections = Vec::new();
9683 let mut new_selections = Vec::new();
9684
9685 while let Some(selection) = selections.next() {
9686 // Find all the selections that span a contiguous row range
9687 let (start_row, end_row) = consume_contiguous_rows(
9688 &mut contiguous_row_selections,
9689 selection,
9690 &display_map,
9691 &mut selections,
9692 );
9693
9694 // Move the text spanned by the row range to be before the line preceding the row range
9695 if start_row.0 > 0 {
9696 let range_to_move = Point::new(
9697 start_row.previous_row().0,
9698 buffer.line_len(start_row.previous_row()),
9699 )
9700 ..Point::new(
9701 end_row.previous_row().0,
9702 buffer.line_len(end_row.previous_row()),
9703 );
9704 let insertion_point = display_map
9705 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9706 .0;
9707
9708 // Don't move lines across excerpts
9709 if buffer
9710 .excerpt_containing(insertion_point..range_to_move.end)
9711 .is_some()
9712 {
9713 let text = buffer
9714 .text_for_range(range_to_move.clone())
9715 .flat_map(|s| s.chars())
9716 .skip(1)
9717 .chain(['\n'])
9718 .collect::<String>();
9719
9720 edits.push((
9721 buffer.anchor_after(range_to_move.start)
9722 ..buffer.anchor_before(range_to_move.end),
9723 String::new(),
9724 ));
9725 let insertion_anchor = buffer.anchor_after(insertion_point);
9726 edits.push((insertion_anchor..insertion_anchor, text));
9727
9728 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9729
9730 // Move selections up
9731 new_selections.extend(contiguous_row_selections.drain(..).map(
9732 |mut selection| {
9733 selection.start.row -= row_delta;
9734 selection.end.row -= row_delta;
9735 selection
9736 },
9737 ));
9738
9739 // Move folds up
9740 unfold_ranges.push(range_to_move.clone());
9741 for fold in display_map.folds_in_range(
9742 buffer.anchor_before(range_to_move.start)
9743 ..buffer.anchor_after(range_to_move.end),
9744 ) {
9745 let mut start = fold.range.start.to_point(&buffer);
9746 let mut end = fold.range.end.to_point(&buffer);
9747 start.row -= row_delta;
9748 end.row -= row_delta;
9749 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9750 }
9751 }
9752 }
9753
9754 // If we didn't move line(s), preserve the existing selections
9755 new_selections.append(&mut contiguous_row_selections);
9756 }
9757
9758 self.transact(window, cx, |this, window, cx| {
9759 this.unfold_ranges(&unfold_ranges, true, true, cx);
9760 this.buffer.update(cx, |buffer, cx| {
9761 for (range, text) in edits {
9762 buffer.edit([(range, text)], None, cx);
9763 }
9764 });
9765 this.fold_creases(refold_creases, true, window, cx);
9766 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9767 s.select(new_selections);
9768 })
9769 });
9770 }
9771
9772 pub fn move_line_down(
9773 &mut self,
9774 _: &MoveLineDown,
9775 window: &mut Window,
9776 cx: &mut Context<Self>,
9777 ) {
9778 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9779
9780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9781 let buffer = self.buffer.read(cx).snapshot(cx);
9782
9783 let mut edits = Vec::new();
9784 let mut unfold_ranges = Vec::new();
9785 let mut refold_creases = Vec::new();
9786
9787 let selections = self.selections.all::<Point>(cx);
9788 let mut selections = selections.iter().peekable();
9789 let mut contiguous_row_selections = Vec::new();
9790 let mut new_selections = Vec::new();
9791
9792 while let Some(selection) = selections.next() {
9793 // Find all the selections that span a contiguous row range
9794 let (start_row, end_row) = consume_contiguous_rows(
9795 &mut contiguous_row_selections,
9796 selection,
9797 &display_map,
9798 &mut selections,
9799 );
9800
9801 // Move the text spanned by the row range to be after the last line of the row range
9802 if end_row.0 <= buffer.max_point().row {
9803 let range_to_move =
9804 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9805 let insertion_point = display_map
9806 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9807 .0;
9808
9809 // Don't move lines across excerpt boundaries
9810 if buffer
9811 .excerpt_containing(range_to_move.start..insertion_point)
9812 .is_some()
9813 {
9814 let mut text = String::from("\n");
9815 text.extend(buffer.text_for_range(range_to_move.clone()));
9816 text.pop(); // Drop trailing newline
9817 edits.push((
9818 buffer.anchor_after(range_to_move.start)
9819 ..buffer.anchor_before(range_to_move.end),
9820 String::new(),
9821 ));
9822 let insertion_anchor = buffer.anchor_after(insertion_point);
9823 edits.push((insertion_anchor..insertion_anchor, text));
9824
9825 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9826
9827 // Move selections down
9828 new_selections.extend(contiguous_row_selections.drain(..).map(
9829 |mut selection| {
9830 selection.start.row += row_delta;
9831 selection.end.row += row_delta;
9832 selection
9833 },
9834 ));
9835
9836 // Move folds down
9837 unfold_ranges.push(range_to_move.clone());
9838 for fold in display_map.folds_in_range(
9839 buffer.anchor_before(range_to_move.start)
9840 ..buffer.anchor_after(range_to_move.end),
9841 ) {
9842 let mut start = fold.range.start.to_point(&buffer);
9843 let mut end = fold.range.end.to_point(&buffer);
9844 start.row += row_delta;
9845 end.row += row_delta;
9846 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9847 }
9848 }
9849 }
9850
9851 // If we didn't move line(s), preserve the existing selections
9852 new_selections.append(&mut contiguous_row_selections);
9853 }
9854
9855 self.transact(window, cx, |this, window, cx| {
9856 this.unfold_ranges(&unfold_ranges, true, true, cx);
9857 this.buffer.update(cx, |buffer, cx| {
9858 for (range, text) in edits {
9859 buffer.edit([(range, text)], None, cx);
9860 }
9861 });
9862 this.fold_creases(refold_creases, true, window, cx);
9863 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9864 s.select(new_selections)
9865 });
9866 });
9867 }
9868
9869 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9870 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9871 let text_layout_details = &self.text_layout_details(window);
9872 self.transact(window, cx, |this, window, cx| {
9873 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9874 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9875 s.move_with(|display_map, selection| {
9876 if !selection.is_empty() {
9877 return;
9878 }
9879
9880 let mut head = selection.head();
9881 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9882 if head.column() == display_map.line_len(head.row()) {
9883 transpose_offset = display_map
9884 .buffer_snapshot
9885 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9886 }
9887
9888 if transpose_offset == 0 {
9889 return;
9890 }
9891
9892 *head.column_mut() += 1;
9893 head = display_map.clip_point(head, Bias::Right);
9894 let goal = SelectionGoal::HorizontalPosition(
9895 display_map
9896 .x_for_display_point(head, text_layout_details)
9897 .into(),
9898 );
9899 selection.collapse_to(head, goal);
9900
9901 let transpose_start = display_map
9902 .buffer_snapshot
9903 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9904 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9905 let transpose_end = display_map
9906 .buffer_snapshot
9907 .clip_offset(transpose_offset + 1, Bias::Right);
9908 if let Some(ch) =
9909 display_map.buffer_snapshot.chars_at(transpose_start).next()
9910 {
9911 edits.push((transpose_start..transpose_offset, String::new()));
9912 edits.push((transpose_end..transpose_end, ch.to_string()));
9913 }
9914 }
9915 });
9916 edits
9917 });
9918 this.buffer
9919 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9920 let selections = this.selections.all::<usize>(cx);
9921 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9922 s.select(selections);
9923 });
9924 });
9925 }
9926
9927 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9928 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9929 self.rewrap_impl(RewrapOptions::default(), cx)
9930 }
9931
9932 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9933 let buffer = self.buffer.read(cx).snapshot(cx);
9934 let selections = self.selections.all::<Point>(cx);
9935 let mut selections = selections.iter().peekable();
9936
9937 let mut edits = Vec::new();
9938 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9939
9940 while let Some(selection) = selections.next() {
9941 let mut start_row = selection.start.row;
9942 let mut end_row = selection.end.row;
9943
9944 // Skip selections that overlap with a range that has already been rewrapped.
9945 let selection_range = start_row..end_row;
9946 if rewrapped_row_ranges
9947 .iter()
9948 .any(|range| range.overlaps(&selection_range))
9949 {
9950 continue;
9951 }
9952
9953 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9954
9955 // Since not all lines in the selection may be at the same indent
9956 // level, choose the indent size that is the most common between all
9957 // of the lines.
9958 //
9959 // If there is a tie, we use the deepest indent.
9960 let (indent_size, indent_end) = {
9961 let mut indent_size_occurrences = HashMap::default();
9962 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9963
9964 for row in start_row..=end_row {
9965 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9966 rows_by_indent_size.entry(indent).or_default().push(row);
9967 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9968 }
9969
9970 let indent_size = indent_size_occurrences
9971 .into_iter()
9972 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9973 .map(|(indent, _)| indent)
9974 .unwrap_or_default();
9975 let row = rows_by_indent_size[&indent_size][0];
9976 let indent_end = Point::new(row, indent_size.len);
9977
9978 (indent_size, indent_end)
9979 };
9980
9981 let mut line_prefix = indent_size.chars().collect::<String>();
9982
9983 let mut inside_comment = false;
9984 if let Some(comment_prefix) =
9985 buffer
9986 .language_scope_at(selection.head())
9987 .and_then(|language| {
9988 language
9989 .line_comment_prefixes()
9990 .iter()
9991 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9992 .cloned()
9993 })
9994 {
9995 line_prefix.push_str(&comment_prefix);
9996 inside_comment = true;
9997 }
9998
9999 let language_settings = buffer.language_settings_at(selection.head(), cx);
10000 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10001 RewrapBehavior::InComments => inside_comment,
10002 RewrapBehavior::InSelections => !selection.is_empty(),
10003 RewrapBehavior::Anywhere => true,
10004 };
10005
10006 let should_rewrap = options.override_language_settings
10007 || allow_rewrap_based_on_language
10008 || self.hard_wrap.is_some();
10009 if !should_rewrap {
10010 continue;
10011 }
10012
10013 if selection.is_empty() {
10014 'expand_upwards: while start_row > 0 {
10015 let prev_row = start_row - 1;
10016 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10017 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10018 {
10019 start_row = prev_row;
10020 } else {
10021 break 'expand_upwards;
10022 }
10023 }
10024
10025 'expand_downwards: while end_row < buffer.max_point().row {
10026 let next_row = end_row + 1;
10027 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10028 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10029 {
10030 end_row = next_row;
10031 } else {
10032 break 'expand_downwards;
10033 }
10034 }
10035 }
10036
10037 let start = Point::new(start_row, 0);
10038 let start_offset = start.to_offset(&buffer);
10039 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10040 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10041 let Some(lines_without_prefixes) = selection_text
10042 .lines()
10043 .map(|line| {
10044 line.strip_prefix(&line_prefix)
10045 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10046 .ok_or_else(|| {
10047 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10048 })
10049 })
10050 .collect::<Result<Vec<_>, _>>()
10051 .log_err()
10052 else {
10053 continue;
10054 };
10055
10056 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10057 buffer
10058 .language_settings_at(Point::new(start_row, 0), cx)
10059 .preferred_line_length as usize
10060 });
10061 let wrapped_text = wrap_with_prefix(
10062 line_prefix,
10063 lines_without_prefixes.join("\n"),
10064 wrap_column,
10065 tab_size,
10066 options.preserve_existing_whitespace,
10067 );
10068
10069 // TODO: should always use char-based diff while still supporting cursor behavior that
10070 // matches vim.
10071 let mut diff_options = DiffOptions::default();
10072 if options.override_language_settings {
10073 diff_options.max_word_diff_len = 0;
10074 diff_options.max_word_diff_line_count = 0;
10075 } else {
10076 diff_options.max_word_diff_len = usize::MAX;
10077 diff_options.max_word_diff_line_count = usize::MAX;
10078 }
10079
10080 for (old_range, new_text) in
10081 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10082 {
10083 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10084 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10085 edits.push((edit_start..edit_end, new_text));
10086 }
10087
10088 rewrapped_row_ranges.push(start_row..=end_row);
10089 }
10090
10091 self.buffer
10092 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10093 }
10094
10095 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10096 let mut text = String::new();
10097 let buffer = self.buffer.read(cx).snapshot(cx);
10098 let mut selections = self.selections.all::<Point>(cx);
10099 let mut clipboard_selections = Vec::with_capacity(selections.len());
10100 {
10101 let max_point = buffer.max_point();
10102 let mut is_first = true;
10103 for selection in &mut selections {
10104 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10105 if is_entire_line {
10106 selection.start = Point::new(selection.start.row, 0);
10107 if !selection.is_empty() && selection.end.column == 0 {
10108 selection.end = cmp::min(max_point, selection.end);
10109 } else {
10110 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10111 }
10112 selection.goal = SelectionGoal::None;
10113 }
10114 if is_first {
10115 is_first = false;
10116 } else {
10117 text += "\n";
10118 }
10119 let mut len = 0;
10120 for chunk in buffer.text_for_range(selection.start..selection.end) {
10121 text.push_str(chunk);
10122 len += chunk.len();
10123 }
10124 clipboard_selections.push(ClipboardSelection {
10125 len,
10126 is_entire_line,
10127 first_line_indent: buffer
10128 .indent_size_for_line(MultiBufferRow(selection.start.row))
10129 .len,
10130 });
10131 }
10132 }
10133
10134 self.transact(window, cx, |this, window, cx| {
10135 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10136 s.select(selections);
10137 });
10138 this.insert("", window, cx);
10139 });
10140 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10141 }
10142
10143 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10144 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10145 let item = self.cut_common(window, cx);
10146 cx.write_to_clipboard(item);
10147 }
10148
10149 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10150 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10151 self.change_selections(None, window, cx, |s| {
10152 s.move_with(|snapshot, sel| {
10153 if sel.is_empty() {
10154 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10155 }
10156 });
10157 });
10158 let item = self.cut_common(window, cx);
10159 cx.set_global(KillRing(item))
10160 }
10161
10162 pub fn kill_ring_yank(
10163 &mut self,
10164 _: &KillRingYank,
10165 window: &mut Window,
10166 cx: &mut Context<Self>,
10167 ) {
10168 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10169 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10170 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10171 (kill_ring.text().to_string(), kill_ring.metadata_json())
10172 } else {
10173 return;
10174 }
10175 } else {
10176 return;
10177 };
10178 self.do_paste(&text, metadata, false, window, cx);
10179 }
10180
10181 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10182 self.do_copy(true, cx);
10183 }
10184
10185 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10186 self.do_copy(false, cx);
10187 }
10188
10189 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10190 let selections = self.selections.all::<Point>(cx);
10191 let buffer = self.buffer.read(cx).read(cx);
10192 let mut text = String::new();
10193
10194 let mut clipboard_selections = Vec::with_capacity(selections.len());
10195 {
10196 let max_point = buffer.max_point();
10197 let mut is_first = true;
10198 for selection in &selections {
10199 let mut start = selection.start;
10200 let mut end = selection.end;
10201 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10202 if is_entire_line {
10203 start = Point::new(start.row, 0);
10204 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10205 }
10206
10207 let mut trimmed_selections = Vec::new();
10208 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10209 let row = MultiBufferRow(start.row);
10210 let first_indent = buffer.indent_size_for_line(row);
10211 if first_indent.len == 0 || start.column > first_indent.len {
10212 trimmed_selections.push(start..end);
10213 } else {
10214 trimmed_selections.push(
10215 Point::new(row.0, first_indent.len)
10216 ..Point::new(row.0, buffer.line_len(row)),
10217 );
10218 for row in start.row + 1..=end.row {
10219 let mut line_len = buffer.line_len(MultiBufferRow(row));
10220 if row == end.row {
10221 line_len = end.column;
10222 }
10223 if line_len == 0 {
10224 trimmed_selections
10225 .push(Point::new(row, 0)..Point::new(row, line_len));
10226 continue;
10227 }
10228 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10229 if row_indent_size.len >= first_indent.len {
10230 trimmed_selections.push(
10231 Point::new(row, first_indent.len)..Point::new(row, line_len),
10232 );
10233 } else {
10234 trimmed_selections.clear();
10235 trimmed_selections.push(start..end);
10236 break;
10237 }
10238 }
10239 }
10240 } else {
10241 trimmed_selections.push(start..end);
10242 }
10243
10244 for trimmed_range in trimmed_selections {
10245 if is_first {
10246 is_first = false;
10247 } else {
10248 text += "\n";
10249 }
10250 let mut len = 0;
10251 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10252 text.push_str(chunk);
10253 len += chunk.len();
10254 }
10255 clipboard_selections.push(ClipboardSelection {
10256 len,
10257 is_entire_line,
10258 first_line_indent: buffer
10259 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10260 .len,
10261 });
10262 }
10263 }
10264 }
10265
10266 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10267 text,
10268 clipboard_selections,
10269 ));
10270 }
10271
10272 pub fn do_paste(
10273 &mut self,
10274 text: &String,
10275 clipboard_selections: Option<Vec<ClipboardSelection>>,
10276 handle_entire_lines: bool,
10277 window: &mut Window,
10278 cx: &mut Context<Self>,
10279 ) {
10280 if self.read_only(cx) {
10281 return;
10282 }
10283
10284 let clipboard_text = Cow::Borrowed(text);
10285
10286 self.transact(window, cx, |this, window, cx| {
10287 if let Some(mut clipboard_selections) = clipboard_selections {
10288 let old_selections = this.selections.all::<usize>(cx);
10289 let all_selections_were_entire_line =
10290 clipboard_selections.iter().all(|s| s.is_entire_line);
10291 let first_selection_indent_column =
10292 clipboard_selections.first().map(|s| s.first_line_indent);
10293 if clipboard_selections.len() != old_selections.len() {
10294 clipboard_selections.drain(..);
10295 }
10296 let cursor_offset = this.selections.last::<usize>(cx).head();
10297 let mut auto_indent_on_paste = true;
10298
10299 this.buffer.update(cx, |buffer, cx| {
10300 let snapshot = buffer.read(cx);
10301 auto_indent_on_paste = snapshot
10302 .language_settings_at(cursor_offset, cx)
10303 .auto_indent_on_paste;
10304
10305 let mut start_offset = 0;
10306 let mut edits = Vec::new();
10307 let mut original_indent_columns = Vec::new();
10308 for (ix, selection) in old_selections.iter().enumerate() {
10309 let to_insert;
10310 let entire_line;
10311 let original_indent_column;
10312 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10313 let end_offset = start_offset + clipboard_selection.len;
10314 to_insert = &clipboard_text[start_offset..end_offset];
10315 entire_line = clipboard_selection.is_entire_line;
10316 start_offset = end_offset + 1;
10317 original_indent_column = Some(clipboard_selection.first_line_indent);
10318 } else {
10319 to_insert = clipboard_text.as_str();
10320 entire_line = all_selections_were_entire_line;
10321 original_indent_column = first_selection_indent_column
10322 }
10323
10324 // If the corresponding selection was empty when this slice of the
10325 // clipboard text was written, then the entire line containing the
10326 // selection was copied. If this selection is also currently empty,
10327 // then paste the line before the current line of the buffer.
10328 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10329 let column = selection.start.to_point(&snapshot).column as usize;
10330 let line_start = selection.start - column;
10331 line_start..line_start
10332 } else {
10333 selection.range()
10334 };
10335
10336 edits.push((range, to_insert));
10337 original_indent_columns.push(original_indent_column);
10338 }
10339 drop(snapshot);
10340
10341 buffer.edit(
10342 edits,
10343 if auto_indent_on_paste {
10344 Some(AutoindentMode::Block {
10345 original_indent_columns,
10346 })
10347 } else {
10348 None
10349 },
10350 cx,
10351 );
10352 });
10353
10354 let selections = this.selections.all::<usize>(cx);
10355 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10356 s.select(selections)
10357 });
10358 } else {
10359 this.insert(&clipboard_text, window, cx);
10360 }
10361 });
10362 }
10363
10364 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10365 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10366 if let Some(item) = cx.read_from_clipboard() {
10367 let entries = item.entries();
10368
10369 match entries.first() {
10370 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10371 // of all the pasted entries.
10372 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10373 .do_paste(
10374 clipboard_string.text(),
10375 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10376 true,
10377 window,
10378 cx,
10379 ),
10380 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10381 }
10382 }
10383 }
10384
10385 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10386 if self.read_only(cx) {
10387 return;
10388 }
10389
10390 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10391
10392 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10393 if let Some((selections, _)) =
10394 self.selection_history.transaction(transaction_id).cloned()
10395 {
10396 self.change_selections(None, window, cx, |s| {
10397 s.select_anchors(selections.to_vec());
10398 });
10399 } else {
10400 log::error!(
10401 "No entry in selection_history found for undo. \
10402 This may correspond to a bug where undo does not update the selection. \
10403 If this is occurring, please add details to \
10404 https://github.com/zed-industries/zed/issues/22692"
10405 );
10406 }
10407 self.request_autoscroll(Autoscroll::fit(), cx);
10408 self.unmark_text(window, cx);
10409 self.refresh_inline_completion(true, false, window, cx);
10410 cx.emit(EditorEvent::Edited { transaction_id });
10411 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10412 }
10413 }
10414
10415 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10416 if self.read_only(cx) {
10417 return;
10418 }
10419
10420 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10421
10422 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10423 if let Some((_, Some(selections))) =
10424 self.selection_history.transaction(transaction_id).cloned()
10425 {
10426 self.change_selections(None, window, cx, |s| {
10427 s.select_anchors(selections.to_vec());
10428 });
10429 } else {
10430 log::error!(
10431 "No entry in selection_history found for redo. \
10432 This may correspond to a bug where undo does not update the selection. \
10433 If this is occurring, please add details to \
10434 https://github.com/zed-industries/zed/issues/22692"
10435 );
10436 }
10437 self.request_autoscroll(Autoscroll::fit(), cx);
10438 self.unmark_text(window, cx);
10439 self.refresh_inline_completion(true, false, window, cx);
10440 cx.emit(EditorEvent::Edited { transaction_id });
10441 }
10442 }
10443
10444 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10445 self.buffer
10446 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10447 }
10448
10449 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10450 self.buffer
10451 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10452 }
10453
10454 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10455 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10456 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457 s.move_with(|map, selection| {
10458 let cursor = if selection.is_empty() {
10459 movement::left(map, selection.start)
10460 } else {
10461 selection.start
10462 };
10463 selection.collapse_to(cursor, SelectionGoal::None);
10464 });
10465 })
10466 }
10467
10468 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10469 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10470 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10471 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10472 })
10473 }
10474
10475 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10476 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10477 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10478 s.move_with(|map, selection| {
10479 let cursor = if selection.is_empty() {
10480 movement::right(map, selection.end)
10481 } else {
10482 selection.end
10483 };
10484 selection.collapse_to(cursor, SelectionGoal::None)
10485 });
10486 })
10487 }
10488
10489 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10490 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10491 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10492 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10493 })
10494 }
10495
10496 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10497 if self.take_rename(true, window, cx).is_some() {
10498 return;
10499 }
10500
10501 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10502 cx.propagate();
10503 return;
10504 }
10505
10506 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10507
10508 let text_layout_details = &self.text_layout_details(window);
10509 let selection_count = self.selections.count();
10510 let first_selection = self.selections.first_anchor();
10511
10512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10513 s.move_with(|map, selection| {
10514 if !selection.is_empty() {
10515 selection.goal = SelectionGoal::None;
10516 }
10517 let (cursor, goal) = movement::up(
10518 map,
10519 selection.start,
10520 selection.goal,
10521 false,
10522 text_layout_details,
10523 );
10524 selection.collapse_to(cursor, goal);
10525 });
10526 });
10527
10528 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10529 {
10530 cx.propagate();
10531 }
10532 }
10533
10534 pub fn move_up_by_lines(
10535 &mut self,
10536 action: &MoveUpByLines,
10537 window: &mut Window,
10538 cx: &mut Context<Self>,
10539 ) {
10540 if self.take_rename(true, window, cx).is_some() {
10541 return;
10542 }
10543
10544 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10545 cx.propagate();
10546 return;
10547 }
10548
10549 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10550
10551 let text_layout_details = &self.text_layout_details(window);
10552
10553 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10554 s.move_with(|map, selection| {
10555 if !selection.is_empty() {
10556 selection.goal = SelectionGoal::None;
10557 }
10558 let (cursor, goal) = movement::up_by_rows(
10559 map,
10560 selection.start,
10561 action.lines,
10562 selection.goal,
10563 false,
10564 text_layout_details,
10565 );
10566 selection.collapse_to(cursor, goal);
10567 });
10568 })
10569 }
10570
10571 pub fn move_down_by_lines(
10572 &mut self,
10573 action: &MoveDownByLines,
10574 window: &mut Window,
10575 cx: &mut Context<Self>,
10576 ) {
10577 if self.take_rename(true, window, cx).is_some() {
10578 return;
10579 }
10580
10581 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10582 cx.propagate();
10583 return;
10584 }
10585
10586 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10587
10588 let text_layout_details = &self.text_layout_details(window);
10589
10590 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10591 s.move_with(|map, selection| {
10592 if !selection.is_empty() {
10593 selection.goal = SelectionGoal::None;
10594 }
10595 let (cursor, goal) = movement::down_by_rows(
10596 map,
10597 selection.start,
10598 action.lines,
10599 selection.goal,
10600 false,
10601 text_layout_details,
10602 );
10603 selection.collapse_to(cursor, goal);
10604 });
10605 })
10606 }
10607
10608 pub fn select_down_by_lines(
10609 &mut self,
10610 action: &SelectDownByLines,
10611 window: &mut Window,
10612 cx: &mut Context<Self>,
10613 ) {
10614 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10615 let text_layout_details = &self.text_layout_details(window);
10616 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10617 s.move_heads_with(|map, head, goal| {
10618 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10619 })
10620 })
10621 }
10622
10623 pub fn select_up_by_lines(
10624 &mut self,
10625 action: &SelectUpByLines,
10626 window: &mut Window,
10627 cx: &mut Context<Self>,
10628 ) {
10629 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10630 let text_layout_details = &self.text_layout_details(window);
10631 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10632 s.move_heads_with(|map, head, goal| {
10633 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10634 })
10635 })
10636 }
10637
10638 pub fn select_page_up(
10639 &mut self,
10640 _: &SelectPageUp,
10641 window: &mut Window,
10642 cx: &mut Context<Self>,
10643 ) {
10644 let Some(row_count) = self.visible_row_count() else {
10645 return;
10646 };
10647
10648 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10649
10650 let text_layout_details = &self.text_layout_details(window);
10651
10652 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10653 s.move_heads_with(|map, head, goal| {
10654 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10655 })
10656 })
10657 }
10658
10659 pub fn move_page_up(
10660 &mut self,
10661 action: &MovePageUp,
10662 window: &mut Window,
10663 cx: &mut Context<Self>,
10664 ) {
10665 if self.take_rename(true, window, cx).is_some() {
10666 return;
10667 }
10668
10669 if self
10670 .context_menu
10671 .borrow_mut()
10672 .as_mut()
10673 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10674 .unwrap_or(false)
10675 {
10676 return;
10677 }
10678
10679 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10680 cx.propagate();
10681 return;
10682 }
10683
10684 let Some(row_count) = self.visible_row_count() else {
10685 return;
10686 };
10687
10688 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10689
10690 let autoscroll = if action.center_cursor {
10691 Autoscroll::center()
10692 } else {
10693 Autoscroll::fit()
10694 };
10695
10696 let text_layout_details = &self.text_layout_details(window);
10697
10698 self.change_selections(Some(autoscroll), window, cx, |s| {
10699 s.move_with(|map, selection| {
10700 if !selection.is_empty() {
10701 selection.goal = SelectionGoal::None;
10702 }
10703 let (cursor, goal) = movement::up_by_rows(
10704 map,
10705 selection.end,
10706 row_count,
10707 selection.goal,
10708 false,
10709 text_layout_details,
10710 );
10711 selection.collapse_to(cursor, goal);
10712 });
10713 });
10714 }
10715
10716 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10717 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10718 let text_layout_details = &self.text_layout_details(window);
10719 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10720 s.move_heads_with(|map, head, goal| {
10721 movement::up(map, head, goal, false, text_layout_details)
10722 })
10723 })
10724 }
10725
10726 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10727 self.take_rename(true, window, cx);
10728
10729 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10730 cx.propagate();
10731 return;
10732 }
10733
10734 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10735
10736 let text_layout_details = &self.text_layout_details(window);
10737 let selection_count = self.selections.count();
10738 let first_selection = self.selections.first_anchor();
10739
10740 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10741 s.move_with(|map, selection| {
10742 if !selection.is_empty() {
10743 selection.goal = SelectionGoal::None;
10744 }
10745 let (cursor, goal) = movement::down(
10746 map,
10747 selection.end,
10748 selection.goal,
10749 false,
10750 text_layout_details,
10751 );
10752 selection.collapse_to(cursor, goal);
10753 });
10754 });
10755
10756 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10757 {
10758 cx.propagate();
10759 }
10760 }
10761
10762 pub fn select_page_down(
10763 &mut self,
10764 _: &SelectPageDown,
10765 window: &mut Window,
10766 cx: &mut Context<Self>,
10767 ) {
10768 let Some(row_count) = self.visible_row_count() else {
10769 return;
10770 };
10771
10772 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10773
10774 let text_layout_details = &self.text_layout_details(window);
10775
10776 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10777 s.move_heads_with(|map, head, goal| {
10778 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10779 })
10780 })
10781 }
10782
10783 pub fn move_page_down(
10784 &mut self,
10785 action: &MovePageDown,
10786 window: &mut Window,
10787 cx: &mut Context<Self>,
10788 ) {
10789 if self.take_rename(true, window, cx).is_some() {
10790 return;
10791 }
10792
10793 if self
10794 .context_menu
10795 .borrow_mut()
10796 .as_mut()
10797 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10798 .unwrap_or(false)
10799 {
10800 return;
10801 }
10802
10803 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10804 cx.propagate();
10805 return;
10806 }
10807
10808 let Some(row_count) = self.visible_row_count() else {
10809 return;
10810 };
10811
10812 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10813
10814 let autoscroll = if action.center_cursor {
10815 Autoscroll::center()
10816 } else {
10817 Autoscroll::fit()
10818 };
10819
10820 let text_layout_details = &self.text_layout_details(window);
10821 self.change_selections(Some(autoscroll), window, cx, |s| {
10822 s.move_with(|map, selection| {
10823 if !selection.is_empty() {
10824 selection.goal = SelectionGoal::None;
10825 }
10826 let (cursor, goal) = movement::down_by_rows(
10827 map,
10828 selection.end,
10829 row_count,
10830 selection.goal,
10831 false,
10832 text_layout_details,
10833 );
10834 selection.collapse_to(cursor, goal);
10835 });
10836 });
10837 }
10838
10839 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10840 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10841 let text_layout_details = &self.text_layout_details(window);
10842 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10843 s.move_heads_with(|map, head, goal| {
10844 movement::down(map, head, goal, false, text_layout_details)
10845 })
10846 });
10847 }
10848
10849 pub fn context_menu_first(
10850 &mut self,
10851 _: &ContextMenuFirst,
10852 _window: &mut Window,
10853 cx: &mut Context<Self>,
10854 ) {
10855 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10856 context_menu.select_first(self.completion_provider.as_deref(), cx);
10857 }
10858 }
10859
10860 pub fn context_menu_prev(
10861 &mut self,
10862 _: &ContextMenuPrevious,
10863 _window: &mut Window,
10864 cx: &mut Context<Self>,
10865 ) {
10866 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10867 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10868 }
10869 }
10870
10871 pub fn context_menu_next(
10872 &mut self,
10873 _: &ContextMenuNext,
10874 _window: &mut Window,
10875 cx: &mut Context<Self>,
10876 ) {
10877 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10878 context_menu.select_next(self.completion_provider.as_deref(), cx);
10879 }
10880 }
10881
10882 pub fn context_menu_last(
10883 &mut self,
10884 _: &ContextMenuLast,
10885 _window: &mut Window,
10886 cx: &mut Context<Self>,
10887 ) {
10888 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10889 context_menu.select_last(self.completion_provider.as_deref(), cx);
10890 }
10891 }
10892
10893 pub fn move_to_previous_word_start(
10894 &mut self,
10895 _: &MoveToPreviousWordStart,
10896 window: &mut Window,
10897 cx: &mut Context<Self>,
10898 ) {
10899 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10901 s.move_cursors_with(|map, head, _| {
10902 (
10903 movement::previous_word_start(map, head),
10904 SelectionGoal::None,
10905 )
10906 });
10907 })
10908 }
10909
10910 pub fn move_to_previous_subword_start(
10911 &mut self,
10912 _: &MoveToPreviousSubwordStart,
10913 window: &mut Window,
10914 cx: &mut Context<Self>,
10915 ) {
10916 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10917 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10918 s.move_cursors_with(|map, head, _| {
10919 (
10920 movement::previous_subword_start(map, head),
10921 SelectionGoal::None,
10922 )
10923 });
10924 })
10925 }
10926
10927 pub fn select_to_previous_word_start(
10928 &mut self,
10929 _: &SelectToPreviousWordStart,
10930 window: &mut Window,
10931 cx: &mut Context<Self>,
10932 ) {
10933 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10934 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10935 s.move_heads_with(|map, head, _| {
10936 (
10937 movement::previous_word_start(map, head),
10938 SelectionGoal::None,
10939 )
10940 });
10941 })
10942 }
10943
10944 pub fn select_to_previous_subword_start(
10945 &mut self,
10946 _: &SelectToPreviousSubwordStart,
10947 window: &mut Window,
10948 cx: &mut Context<Self>,
10949 ) {
10950 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10951 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10952 s.move_heads_with(|map, head, _| {
10953 (
10954 movement::previous_subword_start(map, head),
10955 SelectionGoal::None,
10956 )
10957 });
10958 })
10959 }
10960
10961 pub fn delete_to_previous_word_start(
10962 &mut self,
10963 action: &DeleteToPreviousWordStart,
10964 window: &mut Window,
10965 cx: &mut Context<Self>,
10966 ) {
10967 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10968 self.transact(window, cx, |this, window, cx| {
10969 this.select_autoclose_pair(window, cx);
10970 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10971 s.move_with(|map, selection| {
10972 if selection.is_empty() {
10973 let cursor = if action.ignore_newlines {
10974 movement::previous_word_start(map, selection.head())
10975 } else {
10976 movement::previous_word_start_or_newline(map, selection.head())
10977 };
10978 selection.set_head(cursor, SelectionGoal::None);
10979 }
10980 });
10981 });
10982 this.insert("", window, cx);
10983 });
10984 }
10985
10986 pub fn delete_to_previous_subword_start(
10987 &mut self,
10988 _: &DeleteToPreviousSubwordStart,
10989 window: &mut Window,
10990 cx: &mut Context<Self>,
10991 ) {
10992 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10993 self.transact(window, cx, |this, window, cx| {
10994 this.select_autoclose_pair(window, cx);
10995 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10996 s.move_with(|map, selection| {
10997 if selection.is_empty() {
10998 let cursor = movement::previous_subword_start(map, selection.head());
10999 selection.set_head(cursor, SelectionGoal::None);
11000 }
11001 });
11002 });
11003 this.insert("", window, cx);
11004 });
11005 }
11006
11007 pub fn move_to_next_word_end(
11008 &mut self,
11009 _: &MoveToNextWordEnd,
11010 window: &mut Window,
11011 cx: &mut Context<Self>,
11012 ) {
11013 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11014 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11015 s.move_cursors_with(|map, head, _| {
11016 (movement::next_word_end(map, head), SelectionGoal::None)
11017 });
11018 })
11019 }
11020
11021 pub fn move_to_next_subword_end(
11022 &mut self,
11023 _: &MoveToNextSubwordEnd,
11024 window: &mut Window,
11025 cx: &mut Context<Self>,
11026 ) {
11027 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11028 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11029 s.move_cursors_with(|map, head, _| {
11030 (movement::next_subword_end(map, head), SelectionGoal::None)
11031 });
11032 })
11033 }
11034
11035 pub fn select_to_next_word_end(
11036 &mut self,
11037 _: &SelectToNextWordEnd,
11038 window: &mut Window,
11039 cx: &mut Context<Self>,
11040 ) {
11041 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11042 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11043 s.move_heads_with(|map, head, _| {
11044 (movement::next_word_end(map, head), SelectionGoal::None)
11045 });
11046 })
11047 }
11048
11049 pub fn select_to_next_subword_end(
11050 &mut self,
11051 _: &SelectToNextSubwordEnd,
11052 window: &mut Window,
11053 cx: &mut Context<Self>,
11054 ) {
11055 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11056 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11057 s.move_heads_with(|map, head, _| {
11058 (movement::next_subword_end(map, head), SelectionGoal::None)
11059 });
11060 })
11061 }
11062
11063 pub fn delete_to_next_word_end(
11064 &mut self,
11065 action: &DeleteToNextWordEnd,
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 = if action.ignore_newlines {
11075 movement::next_word_end(map, selection.head())
11076 } else {
11077 movement::next_word_end_or_newline(map, selection.head())
11078 };
11079 selection.set_head(cursor, SelectionGoal::None);
11080 }
11081 });
11082 });
11083 this.insert("", window, cx);
11084 });
11085 }
11086
11087 pub fn delete_to_next_subword_end(
11088 &mut self,
11089 _: &DeleteToNextSubwordEnd,
11090 window: &mut Window,
11091 cx: &mut Context<Self>,
11092 ) {
11093 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11094 self.transact(window, cx, |this, window, cx| {
11095 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11096 s.move_with(|map, selection| {
11097 if selection.is_empty() {
11098 let cursor = movement::next_subword_end(map, selection.head());
11099 selection.set_head(cursor, SelectionGoal::None);
11100 }
11101 });
11102 });
11103 this.insert("", window, cx);
11104 });
11105 }
11106
11107 pub fn move_to_beginning_of_line(
11108 &mut self,
11109 action: &MoveToBeginningOfLine,
11110 window: &mut Window,
11111 cx: &mut Context<Self>,
11112 ) {
11113 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11114 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11115 s.move_cursors_with(|map, head, _| {
11116 (
11117 movement::indented_line_beginning(
11118 map,
11119 head,
11120 action.stop_at_soft_wraps,
11121 action.stop_at_indent,
11122 ),
11123 SelectionGoal::None,
11124 )
11125 });
11126 })
11127 }
11128
11129 pub fn select_to_beginning_of_line(
11130 &mut self,
11131 action: &SelectToBeginningOfLine,
11132 window: &mut Window,
11133 cx: &mut Context<Self>,
11134 ) {
11135 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11136 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11137 s.move_heads_with(|map, head, _| {
11138 (
11139 movement::indented_line_beginning(
11140 map,
11141 head,
11142 action.stop_at_soft_wraps,
11143 action.stop_at_indent,
11144 ),
11145 SelectionGoal::None,
11146 )
11147 });
11148 });
11149 }
11150
11151 pub fn delete_to_beginning_of_line(
11152 &mut self,
11153 action: &DeleteToBeginningOfLine,
11154 window: &mut Window,
11155 cx: &mut Context<Self>,
11156 ) {
11157 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11158 self.transact(window, cx, |this, window, cx| {
11159 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11160 s.move_with(|_, selection| {
11161 selection.reversed = true;
11162 });
11163 });
11164
11165 this.select_to_beginning_of_line(
11166 &SelectToBeginningOfLine {
11167 stop_at_soft_wraps: false,
11168 stop_at_indent: action.stop_at_indent,
11169 },
11170 window,
11171 cx,
11172 );
11173 this.backspace(&Backspace, window, cx);
11174 });
11175 }
11176
11177 pub fn move_to_end_of_line(
11178 &mut self,
11179 action: &MoveToEndOfLine,
11180 window: &mut Window,
11181 cx: &mut Context<Self>,
11182 ) {
11183 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11184 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11185 s.move_cursors_with(|map, head, _| {
11186 (
11187 movement::line_end(map, head, action.stop_at_soft_wraps),
11188 SelectionGoal::None,
11189 )
11190 });
11191 })
11192 }
11193
11194 pub fn select_to_end_of_line(
11195 &mut self,
11196 action: &SelectToEndOfLine,
11197 window: &mut Window,
11198 cx: &mut Context<Self>,
11199 ) {
11200 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11201 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11202 s.move_heads_with(|map, head, _| {
11203 (
11204 movement::line_end(map, head, action.stop_at_soft_wraps),
11205 SelectionGoal::None,
11206 )
11207 });
11208 })
11209 }
11210
11211 pub fn delete_to_end_of_line(
11212 &mut self,
11213 _: &DeleteToEndOfLine,
11214 window: &mut Window,
11215 cx: &mut Context<Self>,
11216 ) {
11217 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11218 self.transact(window, cx, |this, window, cx| {
11219 this.select_to_end_of_line(
11220 &SelectToEndOfLine {
11221 stop_at_soft_wraps: false,
11222 },
11223 window,
11224 cx,
11225 );
11226 this.delete(&Delete, window, cx);
11227 });
11228 }
11229
11230 pub fn cut_to_end_of_line(
11231 &mut self,
11232 _: &CutToEndOfLine,
11233 window: &mut Window,
11234 cx: &mut Context<Self>,
11235 ) {
11236 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11237 self.transact(window, cx, |this, window, cx| {
11238 this.select_to_end_of_line(
11239 &SelectToEndOfLine {
11240 stop_at_soft_wraps: false,
11241 },
11242 window,
11243 cx,
11244 );
11245 this.cut(&Cut, window, cx);
11246 });
11247 }
11248
11249 pub fn move_to_start_of_paragraph(
11250 &mut self,
11251 _: &MoveToStartOfParagraph,
11252 window: &mut Window,
11253 cx: &mut Context<Self>,
11254 ) {
11255 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11256 cx.propagate();
11257 return;
11258 }
11259 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11260 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11261 s.move_with(|map, selection| {
11262 selection.collapse_to(
11263 movement::start_of_paragraph(map, selection.head(), 1),
11264 SelectionGoal::None,
11265 )
11266 });
11267 })
11268 }
11269
11270 pub fn move_to_end_of_paragraph(
11271 &mut self,
11272 _: &MoveToEndOfParagraph,
11273 window: &mut Window,
11274 cx: &mut Context<Self>,
11275 ) {
11276 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11277 cx.propagate();
11278 return;
11279 }
11280 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11282 s.move_with(|map, selection| {
11283 selection.collapse_to(
11284 movement::end_of_paragraph(map, selection.head(), 1),
11285 SelectionGoal::None,
11286 )
11287 });
11288 })
11289 }
11290
11291 pub fn select_to_start_of_paragraph(
11292 &mut self,
11293 _: &SelectToStartOfParagraph,
11294 window: &mut Window,
11295 cx: &mut Context<Self>,
11296 ) {
11297 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11298 cx.propagate();
11299 return;
11300 }
11301 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11303 s.move_heads_with(|map, head, _| {
11304 (
11305 movement::start_of_paragraph(map, head, 1),
11306 SelectionGoal::None,
11307 )
11308 });
11309 })
11310 }
11311
11312 pub fn select_to_end_of_paragraph(
11313 &mut self,
11314 _: &SelectToEndOfParagraph,
11315 window: &mut Window,
11316 cx: &mut Context<Self>,
11317 ) {
11318 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11319 cx.propagate();
11320 return;
11321 }
11322 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11323 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11324 s.move_heads_with(|map, head, _| {
11325 (
11326 movement::end_of_paragraph(map, head, 1),
11327 SelectionGoal::None,
11328 )
11329 });
11330 })
11331 }
11332
11333 pub fn move_to_start_of_excerpt(
11334 &mut self,
11335 _: &MoveToStartOfExcerpt,
11336 window: &mut Window,
11337 cx: &mut Context<Self>,
11338 ) {
11339 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11340 cx.propagate();
11341 return;
11342 }
11343 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11344 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11345 s.move_with(|map, selection| {
11346 selection.collapse_to(
11347 movement::start_of_excerpt(
11348 map,
11349 selection.head(),
11350 workspace::searchable::Direction::Prev,
11351 ),
11352 SelectionGoal::None,
11353 )
11354 });
11355 })
11356 }
11357
11358 pub fn move_to_start_of_next_excerpt(
11359 &mut self,
11360 _: &MoveToStartOfNextExcerpt,
11361 window: &mut Window,
11362 cx: &mut Context<Self>,
11363 ) {
11364 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11365 cx.propagate();
11366 return;
11367 }
11368
11369 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11370 s.move_with(|map, selection| {
11371 selection.collapse_to(
11372 movement::start_of_excerpt(
11373 map,
11374 selection.head(),
11375 workspace::searchable::Direction::Next,
11376 ),
11377 SelectionGoal::None,
11378 )
11379 });
11380 })
11381 }
11382
11383 pub fn move_to_end_of_excerpt(
11384 &mut self,
11385 _: &MoveToEndOfExcerpt,
11386 window: &mut Window,
11387 cx: &mut Context<Self>,
11388 ) {
11389 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11390 cx.propagate();
11391 return;
11392 }
11393 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11394 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11395 s.move_with(|map, selection| {
11396 selection.collapse_to(
11397 movement::end_of_excerpt(
11398 map,
11399 selection.head(),
11400 workspace::searchable::Direction::Next,
11401 ),
11402 SelectionGoal::None,
11403 )
11404 });
11405 })
11406 }
11407
11408 pub fn move_to_end_of_previous_excerpt(
11409 &mut self,
11410 _: &MoveToEndOfPreviousExcerpt,
11411 window: &mut Window,
11412 cx: &mut Context<Self>,
11413 ) {
11414 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11415 cx.propagate();
11416 return;
11417 }
11418 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11419 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11420 s.move_with(|map, selection| {
11421 selection.collapse_to(
11422 movement::end_of_excerpt(
11423 map,
11424 selection.head(),
11425 workspace::searchable::Direction::Prev,
11426 ),
11427 SelectionGoal::None,
11428 )
11429 });
11430 })
11431 }
11432
11433 pub fn select_to_start_of_excerpt(
11434 &mut self,
11435 _: &SelectToStartOfExcerpt,
11436 window: &mut Window,
11437 cx: &mut Context<Self>,
11438 ) {
11439 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11440 cx.propagate();
11441 return;
11442 }
11443 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11445 s.move_heads_with(|map, head, _| {
11446 (
11447 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11448 SelectionGoal::None,
11449 )
11450 });
11451 })
11452 }
11453
11454 pub fn select_to_start_of_next_excerpt(
11455 &mut self,
11456 _: &SelectToStartOfNextExcerpt,
11457 window: &mut Window,
11458 cx: &mut Context<Self>,
11459 ) {
11460 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11461 cx.propagate();
11462 return;
11463 }
11464 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11465 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11466 s.move_heads_with(|map, head, _| {
11467 (
11468 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11469 SelectionGoal::None,
11470 )
11471 });
11472 })
11473 }
11474
11475 pub fn select_to_end_of_excerpt(
11476 &mut self,
11477 _: &SelectToEndOfExcerpt,
11478 window: &mut Window,
11479 cx: &mut Context<Self>,
11480 ) {
11481 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11482 cx.propagate();
11483 return;
11484 }
11485 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11486 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11487 s.move_heads_with(|map, head, _| {
11488 (
11489 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11490 SelectionGoal::None,
11491 )
11492 });
11493 })
11494 }
11495
11496 pub fn select_to_end_of_previous_excerpt(
11497 &mut self,
11498 _: &SelectToEndOfPreviousExcerpt,
11499 window: &mut Window,
11500 cx: &mut Context<Self>,
11501 ) {
11502 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11503 cx.propagate();
11504 return;
11505 }
11506 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11507 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11508 s.move_heads_with(|map, head, _| {
11509 (
11510 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11511 SelectionGoal::None,
11512 )
11513 });
11514 })
11515 }
11516
11517 pub fn move_to_beginning(
11518 &mut self,
11519 _: &MoveToBeginning,
11520 window: &mut Window,
11521 cx: &mut Context<Self>,
11522 ) {
11523 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11524 cx.propagate();
11525 return;
11526 }
11527 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11528 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11529 s.select_ranges(vec![0..0]);
11530 });
11531 }
11532
11533 pub fn select_to_beginning(
11534 &mut self,
11535 _: &SelectToBeginning,
11536 window: &mut Window,
11537 cx: &mut Context<Self>,
11538 ) {
11539 let mut selection = self.selections.last::<Point>(cx);
11540 selection.set_head(Point::zero(), SelectionGoal::None);
11541 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11542 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11543 s.select(vec![selection]);
11544 });
11545 }
11546
11547 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11548 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11549 cx.propagate();
11550 return;
11551 }
11552 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11553 let cursor = self.buffer.read(cx).read(cx).len();
11554 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11555 s.select_ranges(vec![cursor..cursor])
11556 });
11557 }
11558
11559 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11560 self.nav_history = nav_history;
11561 }
11562
11563 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11564 self.nav_history.as_ref()
11565 }
11566
11567 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11568 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11569 }
11570
11571 fn push_to_nav_history(
11572 &mut self,
11573 cursor_anchor: Anchor,
11574 new_position: Option<Point>,
11575 is_deactivate: bool,
11576 cx: &mut Context<Self>,
11577 ) {
11578 if let Some(nav_history) = self.nav_history.as_mut() {
11579 let buffer = self.buffer.read(cx).read(cx);
11580 let cursor_position = cursor_anchor.to_point(&buffer);
11581 let scroll_state = self.scroll_manager.anchor();
11582 let scroll_top_row = scroll_state.top_row(&buffer);
11583 drop(buffer);
11584
11585 if let Some(new_position) = new_position {
11586 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11587 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11588 return;
11589 }
11590 }
11591
11592 nav_history.push(
11593 Some(NavigationData {
11594 cursor_anchor,
11595 cursor_position,
11596 scroll_anchor: scroll_state,
11597 scroll_top_row,
11598 }),
11599 cx,
11600 );
11601 cx.emit(EditorEvent::PushedToNavHistory {
11602 anchor: cursor_anchor,
11603 is_deactivate,
11604 })
11605 }
11606 }
11607
11608 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11609 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11610 let buffer = self.buffer.read(cx).snapshot(cx);
11611 let mut selection = self.selections.first::<usize>(cx);
11612 selection.set_head(buffer.len(), SelectionGoal::None);
11613 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11614 s.select(vec![selection]);
11615 });
11616 }
11617
11618 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11619 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11620 let end = self.buffer.read(cx).read(cx).len();
11621 self.change_selections(None, window, cx, |s| {
11622 s.select_ranges(vec![0..end]);
11623 });
11624 }
11625
11626 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11627 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11628 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11629 let mut selections = self.selections.all::<Point>(cx);
11630 let max_point = display_map.buffer_snapshot.max_point();
11631 for selection in &mut selections {
11632 let rows = selection.spanned_rows(true, &display_map);
11633 selection.start = Point::new(rows.start.0, 0);
11634 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11635 selection.reversed = false;
11636 }
11637 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11638 s.select(selections);
11639 });
11640 }
11641
11642 pub fn split_selection_into_lines(
11643 &mut self,
11644 _: &SplitSelectionIntoLines,
11645 window: &mut Window,
11646 cx: &mut Context<Self>,
11647 ) {
11648 let selections = self
11649 .selections
11650 .all::<Point>(cx)
11651 .into_iter()
11652 .map(|selection| selection.start..selection.end)
11653 .collect::<Vec<_>>();
11654 self.unfold_ranges(&selections, true, true, cx);
11655
11656 let mut new_selection_ranges = Vec::new();
11657 {
11658 let buffer = self.buffer.read(cx).read(cx);
11659 for selection in selections {
11660 for row in selection.start.row..selection.end.row {
11661 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11662 new_selection_ranges.push(cursor..cursor);
11663 }
11664
11665 let is_multiline_selection = selection.start.row != selection.end.row;
11666 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11667 // so this action feels more ergonomic when paired with other selection operations
11668 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11669 if !should_skip_last {
11670 new_selection_ranges.push(selection.end..selection.end);
11671 }
11672 }
11673 }
11674 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11675 s.select_ranges(new_selection_ranges);
11676 });
11677 }
11678
11679 pub fn add_selection_above(
11680 &mut self,
11681 _: &AddSelectionAbove,
11682 window: &mut Window,
11683 cx: &mut Context<Self>,
11684 ) {
11685 self.add_selection(true, window, cx);
11686 }
11687
11688 pub fn add_selection_below(
11689 &mut self,
11690 _: &AddSelectionBelow,
11691 window: &mut Window,
11692 cx: &mut Context<Self>,
11693 ) {
11694 self.add_selection(false, window, cx);
11695 }
11696
11697 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11698 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11699
11700 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11701 let mut selections = self.selections.all::<Point>(cx);
11702 let text_layout_details = self.text_layout_details(window);
11703 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11704 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11705 let range = oldest_selection.display_range(&display_map).sorted();
11706
11707 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11708 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11709 let positions = start_x.min(end_x)..start_x.max(end_x);
11710
11711 selections.clear();
11712 let mut stack = Vec::new();
11713 for row in range.start.row().0..=range.end.row().0 {
11714 if let Some(selection) = self.selections.build_columnar_selection(
11715 &display_map,
11716 DisplayRow(row),
11717 &positions,
11718 oldest_selection.reversed,
11719 &text_layout_details,
11720 ) {
11721 stack.push(selection.id);
11722 selections.push(selection);
11723 }
11724 }
11725
11726 if above {
11727 stack.reverse();
11728 }
11729
11730 AddSelectionsState { above, stack }
11731 });
11732
11733 let last_added_selection = *state.stack.last().unwrap();
11734 let mut new_selections = Vec::new();
11735 if above == state.above {
11736 let end_row = if above {
11737 DisplayRow(0)
11738 } else {
11739 display_map.max_point().row()
11740 };
11741
11742 'outer: for selection in selections {
11743 if selection.id == last_added_selection {
11744 let range = selection.display_range(&display_map).sorted();
11745 debug_assert_eq!(range.start.row(), range.end.row());
11746 let mut row = range.start.row();
11747 let positions =
11748 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11749 px(start)..px(end)
11750 } else {
11751 let start_x =
11752 display_map.x_for_display_point(range.start, &text_layout_details);
11753 let end_x =
11754 display_map.x_for_display_point(range.end, &text_layout_details);
11755 start_x.min(end_x)..start_x.max(end_x)
11756 };
11757
11758 while row != end_row {
11759 if above {
11760 row.0 -= 1;
11761 } else {
11762 row.0 += 1;
11763 }
11764
11765 if let Some(new_selection) = self.selections.build_columnar_selection(
11766 &display_map,
11767 row,
11768 &positions,
11769 selection.reversed,
11770 &text_layout_details,
11771 ) {
11772 state.stack.push(new_selection.id);
11773 if above {
11774 new_selections.push(new_selection);
11775 new_selections.push(selection);
11776 } else {
11777 new_selections.push(selection);
11778 new_selections.push(new_selection);
11779 }
11780
11781 continue 'outer;
11782 }
11783 }
11784 }
11785
11786 new_selections.push(selection);
11787 }
11788 } else {
11789 new_selections = selections;
11790 new_selections.retain(|s| s.id != last_added_selection);
11791 state.stack.pop();
11792 }
11793
11794 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11795 s.select(new_selections);
11796 });
11797 if state.stack.len() > 1 {
11798 self.add_selections_state = Some(state);
11799 }
11800 }
11801
11802 pub fn select_next_match_internal(
11803 &mut self,
11804 display_map: &DisplaySnapshot,
11805 replace_newest: bool,
11806 autoscroll: Option<Autoscroll>,
11807 window: &mut Window,
11808 cx: &mut Context<Self>,
11809 ) -> Result<()> {
11810 fn select_next_match_ranges(
11811 this: &mut Editor,
11812 range: Range<usize>,
11813 replace_newest: bool,
11814 auto_scroll: Option<Autoscroll>,
11815 window: &mut Window,
11816 cx: &mut Context<Editor>,
11817 ) {
11818 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11819 this.change_selections(auto_scroll, window, cx, |s| {
11820 if replace_newest {
11821 s.delete(s.newest_anchor().id);
11822 }
11823 s.insert_range(range.clone());
11824 });
11825 }
11826
11827 let buffer = &display_map.buffer_snapshot;
11828 let mut selections = self.selections.all::<usize>(cx);
11829 if let Some(mut select_next_state) = self.select_next_state.take() {
11830 let query = &select_next_state.query;
11831 if !select_next_state.done {
11832 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11833 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11834 let mut next_selected_range = None;
11835
11836 let bytes_after_last_selection =
11837 buffer.bytes_in_range(last_selection.end..buffer.len());
11838 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11839 let query_matches = query
11840 .stream_find_iter(bytes_after_last_selection)
11841 .map(|result| (last_selection.end, result))
11842 .chain(
11843 query
11844 .stream_find_iter(bytes_before_first_selection)
11845 .map(|result| (0, result)),
11846 );
11847
11848 for (start_offset, query_match) in query_matches {
11849 let query_match = query_match.unwrap(); // can only fail due to I/O
11850 let offset_range =
11851 start_offset + query_match.start()..start_offset + query_match.end();
11852 let display_range = offset_range.start.to_display_point(display_map)
11853 ..offset_range.end.to_display_point(display_map);
11854
11855 if !select_next_state.wordwise
11856 || (!movement::is_inside_word(display_map, display_range.start)
11857 && !movement::is_inside_word(display_map, display_range.end))
11858 {
11859 // TODO: This is n^2, because we might check all the selections
11860 if !selections
11861 .iter()
11862 .any(|selection| selection.range().overlaps(&offset_range))
11863 {
11864 next_selected_range = Some(offset_range);
11865 break;
11866 }
11867 }
11868 }
11869
11870 if let Some(next_selected_range) = next_selected_range {
11871 select_next_match_ranges(
11872 self,
11873 next_selected_range,
11874 replace_newest,
11875 autoscroll,
11876 window,
11877 cx,
11878 );
11879 } else {
11880 select_next_state.done = true;
11881 }
11882 }
11883
11884 self.select_next_state = Some(select_next_state);
11885 } else {
11886 let mut only_carets = true;
11887 let mut same_text_selected = true;
11888 let mut selected_text = None;
11889
11890 let mut selections_iter = selections.iter().peekable();
11891 while let Some(selection) = selections_iter.next() {
11892 if selection.start != selection.end {
11893 only_carets = false;
11894 }
11895
11896 if same_text_selected {
11897 if selected_text.is_none() {
11898 selected_text =
11899 Some(buffer.text_for_range(selection.range()).collect::<String>());
11900 }
11901
11902 if let Some(next_selection) = selections_iter.peek() {
11903 if next_selection.range().len() == selection.range().len() {
11904 let next_selected_text = buffer
11905 .text_for_range(next_selection.range())
11906 .collect::<String>();
11907 if Some(next_selected_text) != selected_text {
11908 same_text_selected = false;
11909 selected_text = None;
11910 }
11911 } else {
11912 same_text_selected = false;
11913 selected_text = None;
11914 }
11915 }
11916 }
11917 }
11918
11919 if only_carets {
11920 for selection in &mut selections {
11921 let word_range = movement::surrounding_word(
11922 display_map,
11923 selection.start.to_display_point(display_map),
11924 );
11925 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11926 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11927 selection.goal = SelectionGoal::None;
11928 selection.reversed = false;
11929 select_next_match_ranges(
11930 self,
11931 selection.start..selection.end,
11932 replace_newest,
11933 autoscroll,
11934 window,
11935 cx,
11936 );
11937 }
11938
11939 if selections.len() == 1 {
11940 let selection = selections
11941 .last()
11942 .expect("ensured that there's only one selection");
11943 let query = buffer
11944 .text_for_range(selection.start..selection.end)
11945 .collect::<String>();
11946 let is_empty = query.is_empty();
11947 let select_state = SelectNextState {
11948 query: AhoCorasick::new(&[query])?,
11949 wordwise: true,
11950 done: is_empty,
11951 };
11952 self.select_next_state = Some(select_state);
11953 } else {
11954 self.select_next_state = None;
11955 }
11956 } else if let Some(selected_text) = selected_text {
11957 self.select_next_state = Some(SelectNextState {
11958 query: AhoCorasick::new(&[selected_text])?,
11959 wordwise: false,
11960 done: false,
11961 });
11962 self.select_next_match_internal(
11963 display_map,
11964 replace_newest,
11965 autoscroll,
11966 window,
11967 cx,
11968 )?;
11969 }
11970 }
11971 Ok(())
11972 }
11973
11974 pub fn select_all_matches(
11975 &mut self,
11976 _action: &SelectAllMatches,
11977 window: &mut Window,
11978 cx: &mut Context<Self>,
11979 ) -> Result<()> {
11980 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11981
11982 self.push_to_selection_history();
11983 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11984
11985 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11986 let Some(select_next_state) = self.select_next_state.as_mut() else {
11987 return Ok(());
11988 };
11989 if select_next_state.done {
11990 return Ok(());
11991 }
11992
11993 let mut new_selections = Vec::new();
11994
11995 let reversed = self.selections.oldest::<usize>(cx).reversed;
11996 let buffer = &display_map.buffer_snapshot;
11997 let query_matches = select_next_state
11998 .query
11999 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12000
12001 for query_match in query_matches.into_iter() {
12002 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12003 let offset_range = if reversed {
12004 query_match.end()..query_match.start()
12005 } else {
12006 query_match.start()..query_match.end()
12007 };
12008 let display_range = offset_range.start.to_display_point(&display_map)
12009 ..offset_range.end.to_display_point(&display_map);
12010
12011 if !select_next_state.wordwise
12012 || (!movement::is_inside_word(&display_map, display_range.start)
12013 && !movement::is_inside_word(&display_map, display_range.end))
12014 {
12015 new_selections.push(offset_range.start..offset_range.end);
12016 }
12017 }
12018
12019 select_next_state.done = true;
12020 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12021 self.change_selections(None, window, cx, |selections| {
12022 selections.select_ranges(new_selections)
12023 });
12024
12025 Ok(())
12026 }
12027
12028 pub fn select_next(
12029 &mut self,
12030 action: &SelectNext,
12031 window: &mut Window,
12032 cx: &mut Context<Self>,
12033 ) -> Result<()> {
12034 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12035 self.push_to_selection_history();
12036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12037 self.select_next_match_internal(
12038 &display_map,
12039 action.replace_newest,
12040 Some(Autoscroll::newest()),
12041 window,
12042 cx,
12043 )?;
12044 Ok(())
12045 }
12046
12047 pub fn select_previous(
12048 &mut self,
12049 action: &SelectPrevious,
12050 window: &mut Window,
12051 cx: &mut Context<Self>,
12052 ) -> Result<()> {
12053 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12054 self.push_to_selection_history();
12055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12056 let buffer = &display_map.buffer_snapshot;
12057 let mut selections = self.selections.all::<usize>(cx);
12058 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12059 let query = &select_prev_state.query;
12060 if !select_prev_state.done {
12061 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12062 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12063 let mut next_selected_range = None;
12064 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12065 let bytes_before_last_selection =
12066 buffer.reversed_bytes_in_range(0..last_selection.start);
12067 let bytes_after_first_selection =
12068 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12069 let query_matches = query
12070 .stream_find_iter(bytes_before_last_selection)
12071 .map(|result| (last_selection.start, result))
12072 .chain(
12073 query
12074 .stream_find_iter(bytes_after_first_selection)
12075 .map(|result| (buffer.len(), result)),
12076 );
12077 for (end_offset, query_match) in query_matches {
12078 let query_match = query_match.unwrap(); // can only fail due to I/O
12079 let offset_range =
12080 end_offset - query_match.end()..end_offset - query_match.start();
12081 let display_range = offset_range.start.to_display_point(&display_map)
12082 ..offset_range.end.to_display_point(&display_map);
12083
12084 if !select_prev_state.wordwise
12085 || (!movement::is_inside_word(&display_map, display_range.start)
12086 && !movement::is_inside_word(&display_map, display_range.end))
12087 {
12088 next_selected_range = Some(offset_range);
12089 break;
12090 }
12091 }
12092
12093 if let Some(next_selected_range) = next_selected_range {
12094 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12095 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12096 if action.replace_newest {
12097 s.delete(s.newest_anchor().id);
12098 }
12099 s.insert_range(next_selected_range);
12100 });
12101 } else {
12102 select_prev_state.done = true;
12103 }
12104 }
12105
12106 self.select_prev_state = Some(select_prev_state);
12107 } else {
12108 let mut only_carets = true;
12109 let mut same_text_selected = true;
12110 let mut selected_text = None;
12111
12112 let mut selections_iter = selections.iter().peekable();
12113 while let Some(selection) = selections_iter.next() {
12114 if selection.start != selection.end {
12115 only_carets = false;
12116 }
12117
12118 if same_text_selected {
12119 if selected_text.is_none() {
12120 selected_text =
12121 Some(buffer.text_for_range(selection.range()).collect::<String>());
12122 }
12123
12124 if let Some(next_selection) = selections_iter.peek() {
12125 if next_selection.range().len() == selection.range().len() {
12126 let next_selected_text = buffer
12127 .text_for_range(next_selection.range())
12128 .collect::<String>();
12129 if Some(next_selected_text) != selected_text {
12130 same_text_selected = false;
12131 selected_text = None;
12132 }
12133 } else {
12134 same_text_selected = false;
12135 selected_text = None;
12136 }
12137 }
12138 }
12139 }
12140
12141 if only_carets {
12142 for selection in &mut selections {
12143 let word_range = movement::surrounding_word(
12144 &display_map,
12145 selection.start.to_display_point(&display_map),
12146 );
12147 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12148 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12149 selection.goal = SelectionGoal::None;
12150 selection.reversed = false;
12151 }
12152 if selections.len() == 1 {
12153 let selection = selections
12154 .last()
12155 .expect("ensured that there's only one selection");
12156 let query = buffer
12157 .text_for_range(selection.start..selection.end)
12158 .collect::<String>();
12159 let is_empty = query.is_empty();
12160 let select_state = SelectNextState {
12161 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12162 wordwise: true,
12163 done: is_empty,
12164 };
12165 self.select_prev_state = Some(select_state);
12166 } else {
12167 self.select_prev_state = None;
12168 }
12169
12170 self.unfold_ranges(
12171 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12172 false,
12173 true,
12174 cx,
12175 );
12176 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12177 s.select(selections);
12178 });
12179 } else if let Some(selected_text) = selected_text {
12180 self.select_prev_state = Some(SelectNextState {
12181 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12182 wordwise: false,
12183 done: false,
12184 });
12185 self.select_previous(action, window, cx)?;
12186 }
12187 }
12188 Ok(())
12189 }
12190
12191 pub fn find_next_match(
12192 &mut self,
12193 _: &FindNextMatch,
12194 window: &mut Window,
12195 cx: &mut Context<Self>,
12196 ) -> Result<()> {
12197 let selections = self.selections.disjoint_anchors();
12198 match selections.first() {
12199 Some(first) if selections.len() >= 2 => {
12200 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12201 s.select_ranges([first.range()]);
12202 });
12203 }
12204 _ => self.select_next(
12205 &SelectNext {
12206 replace_newest: true,
12207 },
12208 window,
12209 cx,
12210 )?,
12211 }
12212 Ok(())
12213 }
12214
12215 pub fn find_previous_match(
12216 &mut self,
12217 _: &FindPreviousMatch,
12218 window: &mut Window,
12219 cx: &mut Context<Self>,
12220 ) -> Result<()> {
12221 let selections = self.selections.disjoint_anchors();
12222 match selections.last() {
12223 Some(last) if selections.len() >= 2 => {
12224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12225 s.select_ranges([last.range()]);
12226 });
12227 }
12228 _ => self.select_previous(
12229 &SelectPrevious {
12230 replace_newest: true,
12231 },
12232 window,
12233 cx,
12234 )?,
12235 }
12236 Ok(())
12237 }
12238
12239 pub fn toggle_comments(
12240 &mut self,
12241 action: &ToggleComments,
12242 window: &mut Window,
12243 cx: &mut Context<Self>,
12244 ) {
12245 if self.read_only(cx) {
12246 return;
12247 }
12248 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12249 let text_layout_details = &self.text_layout_details(window);
12250 self.transact(window, cx, |this, window, cx| {
12251 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12252 let mut edits = Vec::new();
12253 let mut selection_edit_ranges = Vec::new();
12254 let mut last_toggled_row = None;
12255 let snapshot = this.buffer.read(cx).read(cx);
12256 let empty_str: Arc<str> = Arc::default();
12257 let mut suffixes_inserted = Vec::new();
12258 let ignore_indent = action.ignore_indent;
12259
12260 fn comment_prefix_range(
12261 snapshot: &MultiBufferSnapshot,
12262 row: MultiBufferRow,
12263 comment_prefix: &str,
12264 comment_prefix_whitespace: &str,
12265 ignore_indent: bool,
12266 ) -> Range<Point> {
12267 let indent_size = if ignore_indent {
12268 0
12269 } else {
12270 snapshot.indent_size_for_line(row).len
12271 };
12272
12273 let start = Point::new(row.0, indent_size);
12274
12275 let mut line_bytes = snapshot
12276 .bytes_in_range(start..snapshot.max_point())
12277 .flatten()
12278 .copied();
12279
12280 // If this line currently begins with the line comment prefix, then record
12281 // the range containing the prefix.
12282 if line_bytes
12283 .by_ref()
12284 .take(comment_prefix.len())
12285 .eq(comment_prefix.bytes())
12286 {
12287 // Include any whitespace that matches the comment prefix.
12288 let matching_whitespace_len = line_bytes
12289 .zip(comment_prefix_whitespace.bytes())
12290 .take_while(|(a, b)| a == b)
12291 .count() as u32;
12292 let end = Point::new(
12293 start.row,
12294 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12295 );
12296 start..end
12297 } else {
12298 start..start
12299 }
12300 }
12301
12302 fn comment_suffix_range(
12303 snapshot: &MultiBufferSnapshot,
12304 row: MultiBufferRow,
12305 comment_suffix: &str,
12306 comment_suffix_has_leading_space: bool,
12307 ) -> Range<Point> {
12308 let end = Point::new(row.0, snapshot.line_len(row));
12309 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12310
12311 let mut line_end_bytes = snapshot
12312 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12313 .flatten()
12314 .copied();
12315
12316 let leading_space_len = if suffix_start_column > 0
12317 && line_end_bytes.next() == Some(b' ')
12318 && comment_suffix_has_leading_space
12319 {
12320 1
12321 } else {
12322 0
12323 };
12324
12325 // If this line currently begins with the line comment prefix, then record
12326 // the range containing the prefix.
12327 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12328 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12329 start..end
12330 } else {
12331 end..end
12332 }
12333 }
12334
12335 // TODO: Handle selections that cross excerpts
12336 for selection in &mut selections {
12337 let start_column = snapshot
12338 .indent_size_for_line(MultiBufferRow(selection.start.row))
12339 .len;
12340 let language = if let Some(language) =
12341 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12342 {
12343 language
12344 } else {
12345 continue;
12346 };
12347
12348 selection_edit_ranges.clear();
12349
12350 // If multiple selections contain a given row, avoid processing that
12351 // row more than once.
12352 let mut start_row = MultiBufferRow(selection.start.row);
12353 if last_toggled_row == Some(start_row) {
12354 start_row = start_row.next_row();
12355 }
12356 let end_row =
12357 if selection.end.row > selection.start.row && selection.end.column == 0 {
12358 MultiBufferRow(selection.end.row - 1)
12359 } else {
12360 MultiBufferRow(selection.end.row)
12361 };
12362 last_toggled_row = Some(end_row);
12363
12364 if start_row > end_row {
12365 continue;
12366 }
12367
12368 // If the language has line comments, toggle those.
12369 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12370
12371 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12372 if ignore_indent {
12373 full_comment_prefixes = full_comment_prefixes
12374 .into_iter()
12375 .map(|s| Arc::from(s.trim_end()))
12376 .collect();
12377 }
12378
12379 if !full_comment_prefixes.is_empty() {
12380 let first_prefix = full_comment_prefixes
12381 .first()
12382 .expect("prefixes is non-empty");
12383 let prefix_trimmed_lengths = full_comment_prefixes
12384 .iter()
12385 .map(|p| p.trim_end_matches(' ').len())
12386 .collect::<SmallVec<[usize; 4]>>();
12387
12388 let mut all_selection_lines_are_comments = true;
12389
12390 for row in start_row.0..=end_row.0 {
12391 let row = MultiBufferRow(row);
12392 if start_row < end_row && snapshot.is_line_blank(row) {
12393 continue;
12394 }
12395
12396 let prefix_range = full_comment_prefixes
12397 .iter()
12398 .zip(prefix_trimmed_lengths.iter().copied())
12399 .map(|(prefix, trimmed_prefix_len)| {
12400 comment_prefix_range(
12401 snapshot.deref(),
12402 row,
12403 &prefix[..trimmed_prefix_len],
12404 &prefix[trimmed_prefix_len..],
12405 ignore_indent,
12406 )
12407 })
12408 .max_by_key(|range| range.end.column - range.start.column)
12409 .expect("prefixes is non-empty");
12410
12411 if prefix_range.is_empty() {
12412 all_selection_lines_are_comments = false;
12413 }
12414
12415 selection_edit_ranges.push(prefix_range);
12416 }
12417
12418 if all_selection_lines_are_comments {
12419 edits.extend(
12420 selection_edit_ranges
12421 .iter()
12422 .cloned()
12423 .map(|range| (range, empty_str.clone())),
12424 );
12425 } else {
12426 let min_column = selection_edit_ranges
12427 .iter()
12428 .map(|range| range.start.column)
12429 .min()
12430 .unwrap_or(0);
12431 edits.extend(selection_edit_ranges.iter().map(|range| {
12432 let position = Point::new(range.start.row, min_column);
12433 (position..position, first_prefix.clone())
12434 }));
12435 }
12436 } else if let Some((full_comment_prefix, comment_suffix)) =
12437 language.block_comment_delimiters()
12438 {
12439 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12440 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12441 let prefix_range = comment_prefix_range(
12442 snapshot.deref(),
12443 start_row,
12444 comment_prefix,
12445 comment_prefix_whitespace,
12446 ignore_indent,
12447 );
12448 let suffix_range = comment_suffix_range(
12449 snapshot.deref(),
12450 end_row,
12451 comment_suffix.trim_start_matches(' '),
12452 comment_suffix.starts_with(' '),
12453 );
12454
12455 if prefix_range.is_empty() || suffix_range.is_empty() {
12456 edits.push((
12457 prefix_range.start..prefix_range.start,
12458 full_comment_prefix.clone(),
12459 ));
12460 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12461 suffixes_inserted.push((end_row, comment_suffix.len()));
12462 } else {
12463 edits.push((prefix_range, empty_str.clone()));
12464 edits.push((suffix_range, empty_str.clone()));
12465 }
12466 } else {
12467 continue;
12468 }
12469 }
12470
12471 drop(snapshot);
12472 this.buffer.update(cx, |buffer, cx| {
12473 buffer.edit(edits, None, cx);
12474 });
12475
12476 // Adjust selections so that they end before any comment suffixes that
12477 // were inserted.
12478 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12479 let mut selections = this.selections.all::<Point>(cx);
12480 let snapshot = this.buffer.read(cx).read(cx);
12481 for selection in &mut selections {
12482 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12483 match row.cmp(&MultiBufferRow(selection.end.row)) {
12484 Ordering::Less => {
12485 suffixes_inserted.next();
12486 continue;
12487 }
12488 Ordering::Greater => break,
12489 Ordering::Equal => {
12490 if selection.end.column == snapshot.line_len(row) {
12491 if selection.is_empty() {
12492 selection.start.column -= suffix_len as u32;
12493 }
12494 selection.end.column -= suffix_len as u32;
12495 }
12496 break;
12497 }
12498 }
12499 }
12500 }
12501
12502 drop(snapshot);
12503 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12504 s.select(selections)
12505 });
12506
12507 let selections = this.selections.all::<Point>(cx);
12508 let selections_on_single_row = selections.windows(2).all(|selections| {
12509 selections[0].start.row == selections[1].start.row
12510 && selections[0].end.row == selections[1].end.row
12511 && selections[0].start.row == selections[0].end.row
12512 });
12513 let selections_selecting = selections
12514 .iter()
12515 .any(|selection| selection.start != selection.end);
12516 let advance_downwards = action.advance_downwards
12517 && selections_on_single_row
12518 && !selections_selecting
12519 && !matches!(this.mode, EditorMode::SingleLine { .. });
12520
12521 if advance_downwards {
12522 let snapshot = this.buffer.read(cx).snapshot(cx);
12523
12524 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12525 s.move_cursors_with(|display_snapshot, display_point, _| {
12526 let mut point = display_point.to_point(display_snapshot);
12527 point.row += 1;
12528 point = snapshot.clip_point(point, Bias::Left);
12529 let display_point = point.to_display_point(display_snapshot);
12530 let goal = SelectionGoal::HorizontalPosition(
12531 display_snapshot
12532 .x_for_display_point(display_point, text_layout_details)
12533 .into(),
12534 );
12535 (display_point, goal)
12536 })
12537 });
12538 }
12539 });
12540 }
12541
12542 pub fn select_enclosing_symbol(
12543 &mut self,
12544 _: &SelectEnclosingSymbol,
12545 window: &mut Window,
12546 cx: &mut Context<Self>,
12547 ) {
12548 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12549
12550 let buffer = self.buffer.read(cx).snapshot(cx);
12551 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12552
12553 fn update_selection(
12554 selection: &Selection<usize>,
12555 buffer_snap: &MultiBufferSnapshot,
12556 ) -> Option<Selection<usize>> {
12557 let cursor = selection.head();
12558 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12559 for symbol in symbols.iter().rev() {
12560 let start = symbol.range.start.to_offset(buffer_snap);
12561 let end = symbol.range.end.to_offset(buffer_snap);
12562 let new_range = start..end;
12563 if start < selection.start || end > selection.end {
12564 return Some(Selection {
12565 id: selection.id,
12566 start: new_range.start,
12567 end: new_range.end,
12568 goal: SelectionGoal::None,
12569 reversed: selection.reversed,
12570 });
12571 }
12572 }
12573 None
12574 }
12575
12576 let mut selected_larger_symbol = false;
12577 let new_selections = old_selections
12578 .iter()
12579 .map(|selection| match update_selection(selection, &buffer) {
12580 Some(new_selection) => {
12581 if new_selection.range() != selection.range() {
12582 selected_larger_symbol = true;
12583 }
12584 new_selection
12585 }
12586 None => selection.clone(),
12587 })
12588 .collect::<Vec<_>>();
12589
12590 if selected_larger_symbol {
12591 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12592 s.select(new_selections);
12593 });
12594 }
12595 }
12596
12597 pub fn select_larger_syntax_node(
12598 &mut self,
12599 _: &SelectLargerSyntaxNode,
12600 window: &mut Window,
12601 cx: &mut Context<Self>,
12602 ) {
12603 let Some(visible_row_count) = self.visible_row_count() else {
12604 return;
12605 };
12606 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12607 if old_selections.is_empty() {
12608 return;
12609 }
12610
12611 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12612
12613 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12614 let buffer = self.buffer.read(cx).snapshot(cx);
12615
12616 let mut selected_larger_node = false;
12617 let mut new_selections = old_selections
12618 .iter()
12619 .map(|selection| {
12620 let old_range = selection.start..selection.end;
12621
12622 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12623 // manually select word at selection
12624 if ["string_content", "inline"].contains(&node.kind()) {
12625 let word_range = {
12626 let display_point = buffer
12627 .offset_to_point(old_range.start)
12628 .to_display_point(&display_map);
12629 let Range { start, end } =
12630 movement::surrounding_word(&display_map, display_point);
12631 start.to_point(&display_map).to_offset(&buffer)
12632 ..end.to_point(&display_map).to_offset(&buffer)
12633 };
12634 // ignore if word is already selected
12635 if !word_range.is_empty() && old_range != word_range {
12636 let last_word_range = {
12637 let display_point = buffer
12638 .offset_to_point(old_range.end)
12639 .to_display_point(&display_map);
12640 let Range { start, end } =
12641 movement::surrounding_word(&display_map, display_point);
12642 start.to_point(&display_map).to_offset(&buffer)
12643 ..end.to_point(&display_map).to_offset(&buffer)
12644 };
12645 // only select word if start and end point belongs to same word
12646 if word_range == last_word_range {
12647 selected_larger_node = true;
12648 return Selection {
12649 id: selection.id,
12650 start: word_range.start,
12651 end: word_range.end,
12652 goal: SelectionGoal::None,
12653 reversed: selection.reversed,
12654 };
12655 }
12656 }
12657 }
12658 }
12659
12660 let mut new_range = old_range.clone();
12661 let mut new_node = None;
12662 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12663 {
12664 new_node = Some(node);
12665 new_range = match containing_range {
12666 MultiOrSingleBufferOffsetRange::Single(_) => break,
12667 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12668 };
12669 if !display_map.intersects_fold(new_range.start)
12670 && !display_map.intersects_fold(new_range.end)
12671 {
12672 break;
12673 }
12674 }
12675
12676 if let Some(node) = new_node {
12677 // Log the ancestor, to support using this action as a way to explore TreeSitter
12678 // nodes. Parent and grandparent are also logged because this operation will not
12679 // visit nodes that have the same range as their parent.
12680 log::info!("Node: {node:?}");
12681 let parent = node.parent();
12682 log::info!("Parent: {parent:?}");
12683 let grandparent = parent.and_then(|x| x.parent());
12684 log::info!("Grandparent: {grandparent:?}");
12685 }
12686
12687 selected_larger_node |= new_range != old_range;
12688 Selection {
12689 id: selection.id,
12690 start: new_range.start,
12691 end: new_range.end,
12692 goal: SelectionGoal::None,
12693 reversed: selection.reversed,
12694 }
12695 })
12696 .collect::<Vec<_>>();
12697
12698 if !selected_larger_node {
12699 return; // don't put this call in the history
12700 }
12701
12702 // scroll based on transformation done to the last selection created by the user
12703 let (last_old, last_new) = old_selections
12704 .last()
12705 .zip(new_selections.last().cloned())
12706 .expect("old_selections isn't empty");
12707
12708 // revert selection
12709 let is_selection_reversed = {
12710 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12711 new_selections.last_mut().expect("checked above").reversed =
12712 should_newest_selection_be_reversed;
12713 should_newest_selection_be_reversed
12714 };
12715
12716 if selected_larger_node {
12717 self.select_syntax_node_history.disable_clearing = true;
12718 self.change_selections(None, window, cx, |s| {
12719 s.select(new_selections.clone());
12720 });
12721 self.select_syntax_node_history.disable_clearing = false;
12722 }
12723
12724 let start_row = last_new.start.to_display_point(&display_map).row().0;
12725 let end_row = last_new.end.to_display_point(&display_map).row().0;
12726 let selection_height = end_row - start_row + 1;
12727 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12728
12729 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12730 let scroll_behavior = if fits_on_the_screen {
12731 self.request_autoscroll(Autoscroll::fit(), cx);
12732 SelectSyntaxNodeScrollBehavior::FitSelection
12733 } else if is_selection_reversed {
12734 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12735 SelectSyntaxNodeScrollBehavior::CursorTop
12736 } else {
12737 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12738 SelectSyntaxNodeScrollBehavior::CursorBottom
12739 };
12740
12741 self.select_syntax_node_history.push((
12742 old_selections,
12743 scroll_behavior,
12744 is_selection_reversed,
12745 ));
12746 }
12747
12748 pub fn select_smaller_syntax_node(
12749 &mut self,
12750 _: &SelectSmallerSyntaxNode,
12751 window: &mut Window,
12752 cx: &mut Context<Self>,
12753 ) {
12754 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12755
12756 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12757 self.select_syntax_node_history.pop()
12758 {
12759 if let Some(selection) = selections.last_mut() {
12760 selection.reversed = is_selection_reversed;
12761 }
12762
12763 self.select_syntax_node_history.disable_clearing = true;
12764 self.change_selections(None, window, cx, |s| {
12765 s.select(selections.to_vec());
12766 });
12767 self.select_syntax_node_history.disable_clearing = false;
12768
12769 match scroll_behavior {
12770 SelectSyntaxNodeScrollBehavior::CursorTop => {
12771 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12772 }
12773 SelectSyntaxNodeScrollBehavior::FitSelection => {
12774 self.request_autoscroll(Autoscroll::fit(), cx);
12775 }
12776 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12777 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12778 }
12779 }
12780 }
12781 }
12782
12783 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12784 if !EditorSettings::get_global(cx).gutter.runnables {
12785 self.clear_tasks();
12786 return Task::ready(());
12787 }
12788 let project = self.project.as_ref().map(Entity::downgrade);
12789 let task_sources = self.lsp_task_sources(cx);
12790 cx.spawn_in(window, async move |editor, cx| {
12791 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12792 let Some(project) = project.and_then(|p| p.upgrade()) else {
12793 return;
12794 };
12795 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12796 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12797 }) else {
12798 return;
12799 };
12800
12801 let hide_runnables = project
12802 .update(cx, |project, cx| {
12803 // Do not display any test indicators in non-dev server remote projects.
12804 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12805 })
12806 .unwrap_or(true);
12807 if hide_runnables {
12808 return;
12809 }
12810 let new_rows =
12811 cx.background_spawn({
12812 let snapshot = display_snapshot.clone();
12813 async move {
12814 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12815 }
12816 })
12817 .await;
12818 let Ok(lsp_tasks) =
12819 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12820 else {
12821 return;
12822 };
12823 let lsp_tasks = lsp_tasks.await;
12824
12825 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12826 lsp_tasks
12827 .into_iter()
12828 .flat_map(|(kind, tasks)| {
12829 tasks.into_iter().filter_map(move |(location, task)| {
12830 Some((kind.clone(), location?, task))
12831 })
12832 })
12833 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12834 let buffer = location.target.buffer;
12835 let buffer_snapshot = buffer.read(cx).snapshot();
12836 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12837 |(excerpt_id, snapshot, _)| {
12838 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12839 display_snapshot
12840 .buffer_snapshot
12841 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12842 } else {
12843 None
12844 }
12845 },
12846 );
12847 if let Some(offset) = offset {
12848 let task_buffer_range =
12849 location.target.range.to_point(&buffer_snapshot);
12850 let context_buffer_range =
12851 task_buffer_range.to_offset(&buffer_snapshot);
12852 let context_range = BufferOffset(context_buffer_range.start)
12853 ..BufferOffset(context_buffer_range.end);
12854
12855 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12856 .or_insert_with(|| RunnableTasks {
12857 templates: Vec::new(),
12858 offset,
12859 column: task_buffer_range.start.column,
12860 extra_variables: HashMap::default(),
12861 context_range,
12862 })
12863 .templates
12864 .push((kind, task.original_task().clone()));
12865 }
12866
12867 acc
12868 })
12869 }) else {
12870 return;
12871 };
12872
12873 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12874 editor
12875 .update(cx, |editor, _| {
12876 editor.clear_tasks();
12877 for (key, mut value) in rows {
12878 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12879 value.templates.extend(lsp_tasks.templates);
12880 }
12881
12882 editor.insert_tasks(key, value);
12883 }
12884 for (key, value) in lsp_tasks_by_rows {
12885 editor.insert_tasks(key, value);
12886 }
12887 })
12888 .ok();
12889 })
12890 }
12891 fn fetch_runnable_ranges(
12892 snapshot: &DisplaySnapshot,
12893 range: Range<Anchor>,
12894 ) -> Vec<language::RunnableRange> {
12895 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12896 }
12897
12898 fn runnable_rows(
12899 project: Entity<Project>,
12900 snapshot: DisplaySnapshot,
12901 runnable_ranges: Vec<RunnableRange>,
12902 mut cx: AsyncWindowContext,
12903 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12904 runnable_ranges
12905 .into_iter()
12906 .filter_map(|mut runnable| {
12907 let tasks = cx
12908 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12909 .ok()?;
12910 if tasks.is_empty() {
12911 return None;
12912 }
12913
12914 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12915
12916 let row = snapshot
12917 .buffer_snapshot
12918 .buffer_line_for_row(MultiBufferRow(point.row))?
12919 .1
12920 .start
12921 .row;
12922
12923 let context_range =
12924 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12925 Some((
12926 (runnable.buffer_id, row),
12927 RunnableTasks {
12928 templates: tasks,
12929 offset: snapshot
12930 .buffer_snapshot
12931 .anchor_before(runnable.run_range.start),
12932 context_range,
12933 column: point.column,
12934 extra_variables: runnable.extra_captures,
12935 },
12936 ))
12937 })
12938 .collect()
12939 }
12940
12941 fn templates_with_tags(
12942 project: &Entity<Project>,
12943 runnable: &mut Runnable,
12944 cx: &mut App,
12945 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12946 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12947 let (worktree_id, file) = project
12948 .buffer_for_id(runnable.buffer, cx)
12949 .and_then(|buffer| buffer.read(cx).file())
12950 .map(|file| (file.worktree_id(cx), file.clone()))
12951 .unzip();
12952
12953 (
12954 project.task_store().read(cx).task_inventory().cloned(),
12955 worktree_id,
12956 file,
12957 )
12958 });
12959
12960 let mut templates_with_tags = mem::take(&mut runnable.tags)
12961 .into_iter()
12962 .flat_map(|RunnableTag(tag)| {
12963 inventory
12964 .as_ref()
12965 .into_iter()
12966 .flat_map(|inventory| {
12967 inventory.read(cx).list_tasks(
12968 file.clone(),
12969 Some(runnable.language.clone()),
12970 worktree_id,
12971 cx,
12972 )
12973 })
12974 .filter(move |(_, template)| {
12975 template.tags.iter().any(|source_tag| source_tag == &tag)
12976 })
12977 })
12978 .sorted_by_key(|(kind, _)| kind.to_owned())
12979 .collect::<Vec<_>>();
12980 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12981 // Strongest source wins; if we have worktree tag binding, prefer that to
12982 // global and language bindings;
12983 // if we have a global binding, prefer that to language binding.
12984 let first_mismatch = templates_with_tags
12985 .iter()
12986 .position(|(tag_source, _)| tag_source != leading_tag_source);
12987 if let Some(index) = first_mismatch {
12988 templates_with_tags.truncate(index);
12989 }
12990 }
12991
12992 templates_with_tags
12993 }
12994
12995 pub fn move_to_enclosing_bracket(
12996 &mut self,
12997 _: &MoveToEnclosingBracket,
12998 window: &mut Window,
12999 cx: &mut Context<Self>,
13000 ) {
13001 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13002 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13003 s.move_offsets_with(|snapshot, selection| {
13004 let Some(enclosing_bracket_ranges) =
13005 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13006 else {
13007 return;
13008 };
13009
13010 let mut best_length = usize::MAX;
13011 let mut best_inside = false;
13012 let mut best_in_bracket_range = false;
13013 let mut best_destination = None;
13014 for (open, close) in enclosing_bracket_ranges {
13015 let close = close.to_inclusive();
13016 let length = close.end() - open.start;
13017 let inside = selection.start >= open.end && selection.end <= *close.start();
13018 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13019 || close.contains(&selection.head());
13020
13021 // If best is next to a bracket and current isn't, skip
13022 if !in_bracket_range && best_in_bracket_range {
13023 continue;
13024 }
13025
13026 // Prefer smaller lengths unless best is inside and current isn't
13027 if length > best_length && (best_inside || !inside) {
13028 continue;
13029 }
13030
13031 best_length = length;
13032 best_inside = inside;
13033 best_in_bracket_range = in_bracket_range;
13034 best_destination = Some(
13035 if close.contains(&selection.start) && close.contains(&selection.end) {
13036 if inside { open.end } else { open.start }
13037 } else if inside {
13038 *close.start()
13039 } else {
13040 *close.end()
13041 },
13042 );
13043 }
13044
13045 if let Some(destination) = best_destination {
13046 selection.collapse_to(destination, SelectionGoal::None);
13047 }
13048 })
13049 });
13050 }
13051
13052 pub fn undo_selection(
13053 &mut self,
13054 _: &UndoSelection,
13055 window: &mut Window,
13056 cx: &mut Context<Self>,
13057 ) {
13058 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13059 self.end_selection(window, cx);
13060 self.selection_history.mode = SelectionHistoryMode::Undoing;
13061 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13062 self.change_selections(None, window, cx, |s| {
13063 s.select_anchors(entry.selections.to_vec())
13064 });
13065 self.select_next_state = entry.select_next_state;
13066 self.select_prev_state = entry.select_prev_state;
13067 self.add_selections_state = entry.add_selections_state;
13068 self.request_autoscroll(Autoscroll::newest(), cx);
13069 }
13070 self.selection_history.mode = SelectionHistoryMode::Normal;
13071 }
13072
13073 pub fn redo_selection(
13074 &mut self,
13075 _: &RedoSelection,
13076 window: &mut Window,
13077 cx: &mut Context<Self>,
13078 ) {
13079 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13080 self.end_selection(window, cx);
13081 self.selection_history.mode = SelectionHistoryMode::Redoing;
13082 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13083 self.change_selections(None, window, cx, |s| {
13084 s.select_anchors(entry.selections.to_vec())
13085 });
13086 self.select_next_state = entry.select_next_state;
13087 self.select_prev_state = entry.select_prev_state;
13088 self.add_selections_state = entry.add_selections_state;
13089 self.request_autoscroll(Autoscroll::newest(), cx);
13090 }
13091 self.selection_history.mode = SelectionHistoryMode::Normal;
13092 }
13093
13094 pub fn expand_excerpts(
13095 &mut self,
13096 action: &ExpandExcerpts,
13097 _: &mut Window,
13098 cx: &mut Context<Self>,
13099 ) {
13100 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13101 }
13102
13103 pub fn expand_excerpts_down(
13104 &mut self,
13105 action: &ExpandExcerptsDown,
13106 _: &mut Window,
13107 cx: &mut Context<Self>,
13108 ) {
13109 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13110 }
13111
13112 pub fn expand_excerpts_up(
13113 &mut self,
13114 action: &ExpandExcerptsUp,
13115 _: &mut Window,
13116 cx: &mut Context<Self>,
13117 ) {
13118 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13119 }
13120
13121 pub fn expand_excerpts_for_direction(
13122 &mut self,
13123 lines: u32,
13124 direction: ExpandExcerptDirection,
13125
13126 cx: &mut Context<Self>,
13127 ) {
13128 let selections = self.selections.disjoint_anchors();
13129
13130 let lines = if lines == 0 {
13131 EditorSettings::get_global(cx).expand_excerpt_lines
13132 } else {
13133 lines
13134 };
13135
13136 self.buffer.update(cx, |buffer, cx| {
13137 let snapshot = buffer.snapshot(cx);
13138 let mut excerpt_ids = selections
13139 .iter()
13140 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13141 .collect::<Vec<_>>();
13142 excerpt_ids.sort();
13143 excerpt_ids.dedup();
13144 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13145 })
13146 }
13147
13148 pub fn expand_excerpt(
13149 &mut self,
13150 excerpt: ExcerptId,
13151 direction: ExpandExcerptDirection,
13152 window: &mut Window,
13153 cx: &mut Context<Self>,
13154 ) {
13155 let current_scroll_position = self.scroll_position(cx);
13156 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13157 let mut should_scroll_up = false;
13158
13159 if direction == ExpandExcerptDirection::Down {
13160 let multi_buffer = self.buffer.read(cx);
13161 let snapshot = multi_buffer.snapshot(cx);
13162 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13163 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13164 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13165 let buffer_snapshot = buffer.read(cx).snapshot();
13166 let excerpt_end_row =
13167 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13168 let last_row = buffer_snapshot.max_point().row;
13169 let lines_below = last_row.saturating_sub(excerpt_end_row);
13170 should_scroll_up = lines_below >= lines_to_expand;
13171 }
13172 }
13173 }
13174 }
13175
13176 self.buffer.update(cx, |buffer, cx| {
13177 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13178 });
13179
13180 if should_scroll_up {
13181 let new_scroll_position =
13182 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13183 self.set_scroll_position(new_scroll_position, window, cx);
13184 }
13185 }
13186
13187 pub fn go_to_singleton_buffer_point(
13188 &mut self,
13189 point: Point,
13190 window: &mut Window,
13191 cx: &mut Context<Self>,
13192 ) {
13193 self.go_to_singleton_buffer_range(point..point, window, cx);
13194 }
13195
13196 pub fn go_to_singleton_buffer_range(
13197 &mut self,
13198 range: Range<Point>,
13199 window: &mut Window,
13200 cx: &mut Context<Self>,
13201 ) {
13202 let multibuffer = self.buffer().read(cx);
13203 let Some(buffer) = multibuffer.as_singleton() else {
13204 return;
13205 };
13206 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13207 return;
13208 };
13209 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13210 return;
13211 };
13212 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13213 s.select_anchor_ranges([start..end])
13214 });
13215 }
13216
13217 pub fn go_to_diagnostic(
13218 &mut self,
13219 _: &GoToDiagnostic,
13220 window: &mut Window,
13221 cx: &mut Context<Self>,
13222 ) {
13223 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13224 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13225 }
13226
13227 pub fn go_to_prev_diagnostic(
13228 &mut self,
13229 _: &GoToPreviousDiagnostic,
13230 window: &mut Window,
13231 cx: &mut Context<Self>,
13232 ) {
13233 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13234 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13235 }
13236
13237 pub fn go_to_diagnostic_impl(
13238 &mut self,
13239 direction: Direction,
13240 window: &mut Window,
13241 cx: &mut Context<Self>,
13242 ) {
13243 let buffer = self.buffer.read(cx).snapshot(cx);
13244 let selection = self.selections.newest::<usize>(cx);
13245
13246 let mut active_group_id = None;
13247 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13248 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13249 active_group_id = Some(active_group.group_id);
13250 }
13251 }
13252
13253 fn filtered(
13254 snapshot: EditorSnapshot,
13255 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13256 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13257 diagnostics
13258 .filter(|entry| entry.range.start != entry.range.end)
13259 .filter(|entry| !entry.diagnostic.is_unnecessary)
13260 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13261 }
13262
13263 let snapshot = self.snapshot(window, cx);
13264 let before = filtered(
13265 snapshot.clone(),
13266 buffer
13267 .diagnostics_in_range(0..selection.start)
13268 .filter(|entry| entry.range.start <= selection.start),
13269 );
13270 let after = filtered(
13271 snapshot,
13272 buffer
13273 .diagnostics_in_range(selection.start..buffer.len())
13274 .filter(|entry| entry.range.start >= selection.start),
13275 );
13276
13277 let mut found: Option<DiagnosticEntry<usize>> = None;
13278 if direction == Direction::Prev {
13279 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13280 {
13281 for diagnostic in prev_diagnostics.into_iter().rev() {
13282 if diagnostic.range.start != selection.start
13283 || active_group_id
13284 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13285 {
13286 found = Some(diagnostic);
13287 break 'outer;
13288 }
13289 }
13290 }
13291 } else {
13292 for diagnostic in after.chain(before) {
13293 if diagnostic.range.start != selection.start
13294 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13295 {
13296 found = Some(diagnostic);
13297 break;
13298 }
13299 }
13300 }
13301 let Some(next_diagnostic) = found else {
13302 return;
13303 };
13304
13305 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13306 return;
13307 };
13308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13309 s.select_ranges(vec![
13310 next_diagnostic.range.start..next_diagnostic.range.start,
13311 ])
13312 });
13313 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13314 self.refresh_inline_completion(false, true, window, cx);
13315 }
13316
13317 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13318 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13319 let snapshot = self.snapshot(window, cx);
13320 let selection = self.selections.newest::<Point>(cx);
13321 self.go_to_hunk_before_or_after_position(
13322 &snapshot,
13323 selection.head(),
13324 Direction::Next,
13325 window,
13326 cx,
13327 );
13328 }
13329
13330 pub fn go_to_hunk_before_or_after_position(
13331 &mut self,
13332 snapshot: &EditorSnapshot,
13333 position: Point,
13334 direction: Direction,
13335 window: &mut Window,
13336 cx: &mut Context<Editor>,
13337 ) {
13338 let row = if direction == Direction::Next {
13339 self.hunk_after_position(snapshot, position)
13340 .map(|hunk| hunk.row_range.start)
13341 } else {
13342 self.hunk_before_position(snapshot, position)
13343 };
13344
13345 if let Some(row) = row {
13346 let destination = Point::new(row.0, 0);
13347 let autoscroll = Autoscroll::center();
13348
13349 self.unfold_ranges(&[destination..destination], false, false, cx);
13350 self.change_selections(Some(autoscroll), window, cx, |s| {
13351 s.select_ranges([destination..destination]);
13352 });
13353 }
13354 }
13355
13356 fn hunk_after_position(
13357 &mut self,
13358 snapshot: &EditorSnapshot,
13359 position: Point,
13360 ) -> Option<MultiBufferDiffHunk> {
13361 snapshot
13362 .buffer_snapshot
13363 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13364 .find(|hunk| hunk.row_range.start.0 > position.row)
13365 .or_else(|| {
13366 snapshot
13367 .buffer_snapshot
13368 .diff_hunks_in_range(Point::zero()..position)
13369 .find(|hunk| hunk.row_range.end.0 < position.row)
13370 })
13371 }
13372
13373 fn go_to_prev_hunk(
13374 &mut self,
13375 _: &GoToPreviousHunk,
13376 window: &mut Window,
13377 cx: &mut Context<Self>,
13378 ) {
13379 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13380 let snapshot = self.snapshot(window, cx);
13381 let selection = self.selections.newest::<Point>(cx);
13382 self.go_to_hunk_before_or_after_position(
13383 &snapshot,
13384 selection.head(),
13385 Direction::Prev,
13386 window,
13387 cx,
13388 );
13389 }
13390
13391 fn hunk_before_position(
13392 &mut self,
13393 snapshot: &EditorSnapshot,
13394 position: Point,
13395 ) -> Option<MultiBufferRow> {
13396 snapshot
13397 .buffer_snapshot
13398 .diff_hunk_before(position)
13399 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13400 }
13401
13402 fn go_to_next_change(
13403 &mut self,
13404 _: &GoToNextChange,
13405 window: &mut Window,
13406 cx: &mut Context<Self>,
13407 ) {
13408 if let Some(selections) = self
13409 .change_list
13410 .next_change(1, Direction::Next)
13411 .map(|s| s.to_vec())
13412 {
13413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13414 let map = s.display_map();
13415 s.select_display_ranges(selections.iter().map(|a| {
13416 let point = a.to_display_point(&map);
13417 point..point
13418 }))
13419 })
13420 }
13421 }
13422
13423 fn go_to_previous_change(
13424 &mut self,
13425 _: &GoToPreviousChange,
13426 window: &mut Window,
13427 cx: &mut Context<Self>,
13428 ) {
13429 if let Some(selections) = self
13430 .change_list
13431 .next_change(1, Direction::Prev)
13432 .map(|s| s.to_vec())
13433 {
13434 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13435 let map = s.display_map();
13436 s.select_display_ranges(selections.iter().map(|a| {
13437 let point = a.to_display_point(&map);
13438 point..point
13439 }))
13440 })
13441 }
13442 }
13443
13444 fn go_to_line<T: 'static>(
13445 &mut self,
13446 position: Anchor,
13447 highlight_color: Option<Hsla>,
13448 window: &mut Window,
13449 cx: &mut Context<Self>,
13450 ) {
13451 let snapshot = self.snapshot(window, cx).display_snapshot;
13452 let position = position.to_point(&snapshot.buffer_snapshot);
13453 let start = snapshot
13454 .buffer_snapshot
13455 .clip_point(Point::new(position.row, 0), Bias::Left);
13456 let end = start + Point::new(1, 0);
13457 let start = snapshot.buffer_snapshot.anchor_before(start);
13458 let end = snapshot.buffer_snapshot.anchor_before(end);
13459
13460 self.highlight_rows::<T>(
13461 start..end,
13462 highlight_color
13463 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13464 false,
13465 cx,
13466 );
13467 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13468 }
13469
13470 pub fn go_to_definition(
13471 &mut self,
13472 _: &GoToDefinition,
13473 window: &mut Window,
13474 cx: &mut Context<Self>,
13475 ) -> Task<Result<Navigated>> {
13476 let definition =
13477 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13478 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13479 cx.spawn_in(window, async move |editor, cx| {
13480 if definition.await? == Navigated::Yes {
13481 return Ok(Navigated::Yes);
13482 }
13483 match fallback_strategy {
13484 GoToDefinitionFallback::None => Ok(Navigated::No),
13485 GoToDefinitionFallback::FindAllReferences => {
13486 match editor.update_in(cx, |editor, window, cx| {
13487 editor.find_all_references(&FindAllReferences, window, cx)
13488 })? {
13489 Some(references) => references.await,
13490 None => Ok(Navigated::No),
13491 }
13492 }
13493 }
13494 })
13495 }
13496
13497 pub fn go_to_declaration(
13498 &mut self,
13499 _: &GoToDeclaration,
13500 window: &mut Window,
13501 cx: &mut Context<Self>,
13502 ) -> Task<Result<Navigated>> {
13503 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13504 }
13505
13506 pub fn go_to_declaration_split(
13507 &mut self,
13508 _: &GoToDeclaration,
13509 window: &mut Window,
13510 cx: &mut Context<Self>,
13511 ) -> Task<Result<Navigated>> {
13512 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13513 }
13514
13515 pub fn go_to_implementation(
13516 &mut self,
13517 _: &GoToImplementation,
13518 window: &mut Window,
13519 cx: &mut Context<Self>,
13520 ) -> Task<Result<Navigated>> {
13521 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13522 }
13523
13524 pub fn go_to_implementation_split(
13525 &mut self,
13526 _: &GoToImplementationSplit,
13527 window: &mut Window,
13528 cx: &mut Context<Self>,
13529 ) -> Task<Result<Navigated>> {
13530 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13531 }
13532
13533 pub fn go_to_type_definition(
13534 &mut self,
13535 _: &GoToTypeDefinition,
13536 window: &mut Window,
13537 cx: &mut Context<Self>,
13538 ) -> Task<Result<Navigated>> {
13539 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13540 }
13541
13542 pub fn go_to_definition_split(
13543 &mut self,
13544 _: &GoToDefinitionSplit,
13545 window: &mut Window,
13546 cx: &mut Context<Self>,
13547 ) -> Task<Result<Navigated>> {
13548 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13549 }
13550
13551 pub fn go_to_type_definition_split(
13552 &mut self,
13553 _: &GoToTypeDefinitionSplit,
13554 window: &mut Window,
13555 cx: &mut Context<Self>,
13556 ) -> Task<Result<Navigated>> {
13557 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13558 }
13559
13560 fn go_to_definition_of_kind(
13561 &mut self,
13562 kind: GotoDefinitionKind,
13563 split: bool,
13564 window: &mut Window,
13565 cx: &mut Context<Self>,
13566 ) -> Task<Result<Navigated>> {
13567 let Some(provider) = self.semantics_provider.clone() else {
13568 return Task::ready(Ok(Navigated::No));
13569 };
13570 let head = self.selections.newest::<usize>(cx).head();
13571 let buffer = self.buffer.read(cx);
13572 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13573 text_anchor
13574 } else {
13575 return Task::ready(Ok(Navigated::No));
13576 };
13577
13578 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13579 return Task::ready(Ok(Navigated::No));
13580 };
13581
13582 cx.spawn_in(window, async move |editor, cx| {
13583 let definitions = definitions.await?;
13584 let navigated = editor
13585 .update_in(cx, |editor, window, cx| {
13586 editor.navigate_to_hover_links(
13587 Some(kind),
13588 definitions
13589 .into_iter()
13590 .filter(|location| {
13591 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13592 })
13593 .map(HoverLink::Text)
13594 .collect::<Vec<_>>(),
13595 split,
13596 window,
13597 cx,
13598 )
13599 })?
13600 .await?;
13601 anyhow::Ok(navigated)
13602 })
13603 }
13604
13605 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13606 let selection = self.selections.newest_anchor();
13607 let head = selection.head();
13608 let tail = selection.tail();
13609
13610 let Some((buffer, start_position)) =
13611 self.buffer.read(cx).text_anchor_for_position(head, cx)
13612 else {
13613 return;
13614 };
13615
13616 let end_position = if head != tail {
13617 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13618 return;
13619 };
13620 Some(pos)
13621 } else {
13622 None
13623 };
13624
13625 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13626 let url = if let Some(end_pos) = end_position {
13627 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13628 } else {
13629 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13630 };
13631
13632 if let Some(url) = url {
13633 editor.update(cx, |_, cx| {
13634 cx.open_url(&url);
13635 })
13636 } else {
13637 Ok(())
13638 }
13639 });
13640
13641 url_finder.detach();
13642 }
13643
13644 pub fn open_selected_filename(
13645 &mut self,
13646 _: &OpenSelectedFilename,
13647 window: &mut Window,
13648 cx: &mut Context<Self>,
13649 ) {
13650 let Some(workspace) = self.workspace() else {
13651 return;
13652 };
13653
13654 let position = self.selections.newest_anchor().head();
13655
13656 let Some((buffer, buffer_position)) =
13657 self.buffer.read(cx).text_anchor_for_position(position, cx)
13658 else {
13659 return;
13660 };
13661
13662 let project = self.project.clone();
13663
13664 cx.spawn_in(window, async move |_, cx| {
13665 let result = find_file(&buffer, project, buffer_position, cx).await;
13666
13667 if let Some((_, path)) = result {
13668 workspace
13669 .update_in(cx, |workspace, window, cx| {
13670 workspace.open_resolved_path(path, window, cx)
13671 })?
13672 .await?;
13673 }
13674 anyhow::Ok(())
13675 })
13676 .detach();
13677 }
13678
13679 pub(crate) fn navigate_to_hover_links(
13680 &mut self,
13681 kind: Option<GotoDefinitionKind>,
13682 mut definitions: Vec<HoverLink>,
13683 split: bool,
13684 window: &mut Window,
13685 cx: &mut Context<Editor>,
13686 ) -> Task<Result<Navigated>> {
13687 // If there is one definition, just open it directly
13688 if definitions.len() == 1 {
13689 let definition = definitions.pop().unwrap();
13690
13691 enum TargetTaskResult {
13692 Location(Option<Location>),
13693 AlreadyNavigated,
13694 }
13695
13696 let target_task = match definition {
13697 HoverLink::Text(link) => {
13698 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13699 }
13700 HoverLink::InlayHint(lsp_location, server_id) => {
13701 let computation =
13702 self.compute_target_location(lsp_location, server_id, window, cx);
13703 cx.background_spawn(async move {
13704 let location = computation.await?;
13705 Ok(TargetTaskResult::Location(location))
13706 })
13707 }
13708 HoverLink::Url(url) => {
13709 cx.open_url(&url);
13710 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13711 }
13712 HoverLink::File(path) => {
13713 if let Some(workspace) = self.workspace() {
13714 cx.spawn_in(window, async move |_, cx| {
13715 workspace
13716 .update_in(cx, |workspace, window, cx| {
13717 workspace.open_resolved_path(path, window, cx)
13718 })?
13719 .await
13720 .map(|_| TargetTaskResult::AlreadyNavigated)
13721 })
13722 } else {
13723 Task::ready(Ok(TargetTaskResult::Location(None)))
13724 }
13725 }
13726 };
13727 cx.spawn_in(window, async move |editor, cx| {
13728 let target = match target_task.await.context("target resolution task")? {
13729 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13730 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13731 TargetTaskResult::Location(Some(target)) => target,
13732 };
13733
13734 editor.update_in(cx, |editor, window, cx| {
13735 let Some(workspace) = editor.workspace() else {
13736 return Navigated::No;
13737 };
13738 let pane = workspace.read(cx).active_pane().clone();
13739
13740 let range = target.range.to_point(target.buffer.read(cx));
13741 let range = editor.range_for_match(&range);
13742 let range = collapse_multiline_range(range);
13743
13744 if !split
13745 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13746 {
13747 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13748 } else {
13749 window.defer(cx, move |window, cx| {
13750 let target_editor: Entity<Self> =
13751 workspace.update(cx, |workspace, cx| {
13752 let pane = if split {
13753 workspace.adjacent_pane(window, cx)
13754 } else {
13755 workspace.active_pane().clone()
13756 };
13757
13758 workspace.open_project_item(
13759 pane,
13760 target.buffer.clone(),
13761 true,
13762 true,
13763 window,
13764 cx,
13765 )
13766 });
13767 target_editor.update(cx, |target_editor, cx| {
13768 // When selecting a definition in a different buffer, disable the nav history
13769 // to avoid creating a history entry at the previous cursor location.
13770 pane.update(cx, |pane, _| pane.disable_history());
13771 target_editor.go_to_singleton_buffer_range(range, window, cx);
13772 pane.update(cx, |pane, _| pane.enable_history());
13773 });
13774 });
13775 }
13776 Navigated::Yes
13777 })
13778 })
13779 } else if !definitions.is_empty() {
13780 cx.spawn_in(window, async move |editor, cx| {
13781 let (title, location_tasks, workspace) = editor
13782 .update_in(cx, |editor, window, cx| {
13783 let tab_kind = match kind {
13784 Some(GotoDefinitionKind::Implementation) => "Implementations",
13785 _ => "Definitions",
13786 };
13787 let title = definitions
13788 .iter()
13789 .find_map(|definition| match definition {
13790 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13791 let buffer = origin.buffer.read(cx);
13792 format!(
13793 "{} for {}",
13794 tab_kind,
13795 buffer
13796 .text_for_range(origin.range.clone())
13797 .collect::<String>()
13798 )
13799 }),
13800 HoverLink::InlayHint(_, _) => None,
13801 HoverLink::Url(_) => None,
13802 HoverLink::File(_) => None,
13803 })
13804 .unwrap_or(tab_kind.to_string());
13805 let location_tasks = definitions
13806 .into_iter()
13807 .map(|definition| match definition {
13808 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13809 HoverLink::InlayHint(lsp_location, server_id) => editor
13810 .compute_target_location(lsp_location, server_id, window, cx),
13811 HoverLink::Url(_) => Task::ready(Ok(None)),
13812 HoverLink::File(_) => Task::ready(Ok(None)),
13813 })
13814 .collect::<Vec<_>>();
13815 (title, location_tasks, editor.workspace().clone())
13816 })
13817 .context("location tasks preparation")?;
13818
13819 let locations = future::join_all(location_tasks)
13820 .await
13821 .into_iter()
13822 .filter_map(|location| location.transpose())
13823 .collect::<Result<_>>()
13824 .context("location tasks")?;
13825
13826 let Some(workspace) = workspace else {
13827 return Ok(Navigated::No);
13828 };
13829 let opened = workspace
13830 .update_in(cx, |workspace, window, cx| {
13831 Self::open_locations_in_multibuffer(
13832 workspace,
13833 locations,
13834 title,
13835 split,
13836 MultibufferSelectionMode::First,
13837 window,
13838 cx,
13839 )
13840 })
13841 .ok();
13842
13843 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13844 })
13845 } else {
13846 Task::ready(Ok(Navigated::No))
13847 }
13848 }
13849
13850 fn compute_target_location(
13851 &self,
13852 lsp_location: lsp::Location,
13853 server_id: LanguageServerId,
13854 window: &mut Window,
13855 cx: &mut Context<Self>,
13856 ) -> Task<anyhow::Result<Option<Location>>> {
13857 let Some(project) = self.project.clone() else {
13858 return Task::ready(Ok(None));
13859 };
13860
13861 cx.spawn_in(window, async move |editor, cx| {
13862 let location_task = editor.update(cx, |_, cx| {
13863 project.update(cx, |project, cx| {
13864 let language_server_name = project
13865 .language_server_statuses(cx)
13866 .find(|(id, _)| server_id == *id)
13867 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13868 language_server_name.map(|language_server_name| {
13869 project.open_local_buffer_via_lsp(
13870 lsp_location.uri.clone(),
13871 server_id,
13872 language_server_name,
13873 cx,
13874 )
13875 })
13876 })
13877 })?;
13878 let location = match location_task {
13879 Some(task) => Some({
13880 let target_buffer_handle = task.await.context("open local buffer")?;
13881 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13882 let target_start = target_buffer
13883 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13884 let target_end = target_buffer
13885 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13886 target_buffer.anchor_after(target_start)
13887 ..target_buffer.anchor_before(target_end)
13888 })?;
13889 Location {
13890 buffer: target_buffer_handle,
13891 range,
13892 }
13893 }),
13894 None => None,
13895 };
13896 Ok(location)
13897 })
13898 }
13899
13900 pub fn find_all_references(
13901 &mut self,
13902 _: &FindAllReferences,
13903 window: &mut Window,
13904 cx: &mut Context<Self>,
13905 ) -> Option<Task<Result<Navigated>>> {
13906 let selection = self.selections.newest::<usize>(cx);
13907 let multi_buffer = self.buffer.read(cx);
13908 let head = selection.head();
13909
13910 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13911 let head_anchor = multi_buffer_snapshot.anchor_at(
13912 head,
13913 if head < selection.tail() {
13914 Bias::Right
13915 } else {
13916 Bias::Left
13917 },
13918 );
13919
13920 match self
13921 .find_all_references_task_sources
13922 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13923 {
13924 Ok(_) => {
13925 log::info!(
13926 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13927 );
13928 return None;
13929 }
13930 Err(i) => {
13931 self.find_all_references_task_sources.insert(i, head_anchor);
13932 }
13933 }
13934
13935 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13936 let workspace = self.workspace()?;
13937 let project = workspace.read(cx).project().clone();
13938 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13939 Some(cx.spawn_in(window, async move |editor, cx| {
13940 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13941 if let Ok(i) = editor
13942 .find_all_references_task_sources
13943 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13944 {
13945 editor.find_all_references_task_sources.remove(i);
13946 }
13947 });
13948
13949 let locations = references.await?;
13950 if locations.is_empty() {
13951 return anyhow::Ok(Navigated::No);
13952 }
13953
13954 workspace.update_in(cx, |workspace, window, cx| {
13955 let title = locations
13956 .first()
13957 .as_ref()
13958 .map(|location| {
13959 let buffer = location.buffer.read(cx);
13960 format!(
13961 "References to `{}`",
13962 buffer
13963 .text_for_range(location.range.clone())
13964 .collect::<String>()
13965 )
13966 })
13967 .unwrap();
13968 Self::open_locations_in_multibuffer(
13969 workspace,
13970 locations,
13971 title,
13972 false,
13973 MultibufferSelectionMode::First,
13974 window,
13975 cx,
13976 );
13977 Navigated::Yes
13978 })
13979 }))
13980 }
13981
13982 /// Opens a multibuffer with the given project locations in it
13983 pub fn open_locations_in_multibuffer(
13984 workspace: &mut Workspace,
13985 mut locations: Vec<Location>,
13986 title: String,
13987 split: bool,
13988 multibuffer_selection_mode: MultibufferSelectionMode,
13989 window: &mut Window,
13990 cx: &mut Context<Workspace>,
13991 ) {
13992 // If there are multiple definitions, open them in a multibuffer
13993 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13994 let mut locations = locations.into_iter().peekable();
13995 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13996 let capability = workspace.project().read(cx).capability();
13997
13998 let excerpt_buffer = cx.new(|cx| {
13999 let mut multibuffer = MultiBuffer::new(capability);
14000 while let Some(location) = locations.next() {
14001 let buffer = location.buffer.read(cx);
14002 let mut ranges_for_buffer = Vec::new();
14003 let range = location.range.to_point(buffer);
14004 ranges_for_buffer.push(range.clone());
14005
14006 while let Some(next_location) = locations.peek() {
14007 if next_location.buffer == location.buffer {
14008 ranges_for_buffer.push(next_location.range.to_point(buffer));
14009 locations.next();
14010 } else {
14011 break;
14012 }
14013 }
14014
14015 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14016 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14017 PathKey::for_buffer(&location.buffer, cx),
14018 location.buffer.clone(),
14019 ranges_for_buffer,
14020 DEFAULT_MULTIBUFFER_CONTEXT,
14021 cx,
14022 );
14023 ranges.extend(new_ranges)
14024 }
14025
14026 multibuffer.with_title(title)
14027 });
14028
14029 let editor = cx.new(|cx| {
14030 Editor::for_multibuffer(
14031 excerpt_buffer,
14032 Some(workspace.project().clone()),
14033 window,
14034 cx,
14035 )
14036 });
14037 editor.update(cx, |editor, cx| {
14038 match multibuffer_selection_mode {
14039 MultibufferSelectionMode::First => {
14040 if let Some(first_range) = ranges.first() {
14041 editor.change_selections(None, window, cx, |selections| {
14042 selections.clear_disjoint();
14043 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14044 });
14045 }
14046 editor.highlight_background::<Self>(
14047 &ranges,
14048 |theme| theme.editor_highlighted_line_background,
14049 cx,
14050 );
14051 }
14052 MultibufferSelectionMode::All => {
14053 editor.change_selections(None, window, cx, |selections| {
14054 selections.clear_disjoint();
14055 selections.select_anchor_ranges(ranges);
14056 });
14057 }
14058 }
14059 editor.register_buffers_with_language_servers(cx);
14060 });
14061
14062 let item = Box::new(editor);
14063 let item_id = item.item_id();
14064
14065 if split {
14066 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14067 } else {
14068 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14069 let (preview_item_id, preview_item_idx) =
14070 workspace.active_pane().update(cx, |pane, _| {
14071 (pane.preview_item_id(), pane.preview_item_idx())
14072 });
14073
14074 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14075
14076 if let Some(preview_item_id) = preview_item_id {
14077 workspace.active_pane().update(cx, |pane, cx| {
14078 pane.remove_item(preview_item_id, false, false, window, cx);
14079 });
14080 }
14081 } else {
14082 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14083 }
14084 }
14085 workspace.active_pane().update(cx, |pane, cx| {
14086 pane.set_preview_item_id(Some(item_id), cx);
14087 });
14088 }
14089
14090 pub fn rename(
14091 &mut self,
14092 _: &Rename,
14093 window: &mut Window,
14094 cx: &mut Context<Self>,
14095 ) -> Option<Task<Result<()>>> {
14096 use language::ToOffset as _;
14097
14098 let provider = self.semantics_provider.clone()?;
14099 let selection = self.selections.newest_anchor().clone();
14100 let (cursor_buffer, cursor_buffer_position) = self
14101 .buffer
14102 .read(cx)
14103 .text_anchor_for_position(selection.head(), cx)?;
14104 let (tail_buffer, cursor_buffer_position_end) = self
14105 .buffer
14106 .read(cx)
14107 .text_anchor_for_position(selection.tail(), cx)?;
14108 if tail_buffer != cursor_buffer {
14109 return None;
14110 }
14111
14112 let snapshot = cursor_buffer.read(cx).snapshot();
14113 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14114 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14115 let prepare_rename = provider
14116 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14117 .unwrap_or_else(|| Task::ready(Ok(None)));
14118 drop(snapshot);
14119
14120 Some(cx.spawn_in(window, async move |this, cx| {
14121 let rename_range = if let Some(range) = prepare_rename.await? {
14122 Some(range)
14123 } else {
14124 this.update(cx, |this, cx| {
14125 let buffer = this.buffer.read(cx).snapshot(cx);
14126 let mut buffer_highlights = this
14127 .document_highlights_for_position(selection.head(), &buffer)
14128 .filter(|highlight| {
14129 highlight.start.excerpt_id == selection.head().excerpt_id
14130 && highlight.end.excerpt_id == selection.head().excerpt_id
14131 });
14132 buffer_highlights
14133 .next()
14134 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14135 })?
14136 };
14137 if let Some(rename_range) = rename_range {
14138 this.update_in(cx, |this, window, cx| {
14139 let snapshot = cursor_buffer.read(cx).snapshot();
14140 let rename_buffer_range = rename_range.to_offset(&snapshot);
14141 let cursor_offset_in_rename_range =
14142 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14143 let cursor_offset_in_rename_range_end =
14144 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14145
14146 this.take_rename(false, window, cx);
14147 let buffer = this.buffer.read(cx).read(cx);
14148 let cursor_offset = selection.head().to_offset(&buffer);
14149 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14150 let rename_end = rename_start + rename_buffer_range.len();
14151 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14152 let mut old_highlight_id = None;
14153 let old_name: Arc<str> = buffer
14154 .chunks(rename_start..rename_end, true)
14155 .map(|chunk| {
14156 if old_highlight_id.is_none() {
14157 old_highlight_id = chunk.syntax_highlight_id;
14158 }
14159 chunk.text
14160 })
14161 .collect::<String>()
14162 .into();
14163
14164 drop(buffer);
14165
14166 // Position the selection in the rename editor so that it matches the current selection.
14167 this.show_local_selections = false;
14168 let rename_editor = cx.new(|cx| {
14169 let mut editor = Editor::single_line(window, cx);
14170 editor.buffer.update(cx, |buffer, cx| {
14171 buffer.edit([(0..0, old_name.clone())], None, cx)
14172 });
14173 let rename_selection_range = match cursor_offset_in_rename_range
14174 .cmp(&cursor_offset_in_rename_range_end)
14175 {
14176 Ordering::Equal => {
14177 editor.select_all(&SelectAll, window, cx);
14178 return editor;
14179 }
14180 Ordering::Less => {
14181 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14182 }
14183 Ordering::Greater => {
14184 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14185 }
14186 };
14187 if rename_selection_range.end > old_name.len() {
14188 editor.select_all(&SelectAll, window, cx);
14189 } else {
14190 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14191 s.select_ranges([rename_selection_range]);
14192 });
14193 }
14194 editor
14195 });
14196 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14197 if e == &EditorEvent::Focused {
14198 cx.emit(EditorEvent::FocusedIn)
14199 }
14200 })
14201 .detach();
14202
14203 let write_highlights =
14204 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14205 let read_highlights =
14206 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14207 let ranges = write_highlights
14208 .iter()
14209 .flat_map(|(_, ranges)| ranges.iter())
14210 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14211 .cloned()
14212 .collect();
14213
14214 this.highlight_text::<Rename>(
14215 ranges,
14216 HighlightStyle {
14217 fade_out: Some(0.6),
14218 ..Default::default()
14219 },
14220 cx,
14221 );
14222 let rename_focus_handle = rename_editor.focus_handle(cx);
14223 window.focus(&rename_focus_handle);
14224 let block_id = this.insert_blocks(
14225 [BlockProperties {
14226 style: BlockStyle::Flex,
14227 placement: BlockPlacement::Below(range.start),
14228 height: Some(1),
14229 render: Arc::new({
14230 let rename_editor = rename_editor.clone();
14231 move |cx: &mut BlockContext| {
14232 let mut text_style = cx.editor_style.text.clone();
14233 if let Some(highlight_style) = old_highlight_id
14234 .and_then(|h| h.style(&cx.editor_style.syntax))
14235 {
14236 text_style = text_style.highlight(highlight_style);
14237 }
14238 div()
14239 .block_mouse_down()
14240 .pl(cx.anchor_x)
14241 .child(EditorElement::new(
14242 &rename_editor,
14243 EditorStyle {
14244 background: cx.theme().system().transparent,
14245 local_player: cx.editor_style.local_player,
14246 text: text_style,
14247 scrollbar_width: cx.editor_style.scrollbar_width,
14248 syntax: cx.editor_style.syntax.clone(),
14249 status: cx.editor_style.status.clone(),
14250 inlay_hints_style: HighlightStyle {
14251 font_weight: Some(FontWeight::BOLD),
14252 ..make_inlay_hints_style(cx.app)
14253 },
14254 inline_completion_styles: make_suggestion_styles(
14255 cx.app,
14256 ),
14257 ..EditorStyle::default()
14258 },
14259 ))
14260 .into_any_element()
14261 }
14262 }),
14263 priority: 0,
14264 }],
14265 Some(Autoscroll::fit()),
14266 cx,
14267 )[0];
14268 this.pending_rename = Some(RenameState {
14269 range,
14270 old_name,
14271 editor: rename_editor,
14272 block_id,
14273 });
14274 })?;
14275 }
14276
14277 Ok(())
14278 }))
14279 }
14280
14281 pub fn confirm_rename(
14282 &mut self,
14283 _: &ConfirmRename,
14284 window: &mut Window,
14285 cx: &mut Context<Self>,
14286 ) -> Option<Task<Result<()>>> {
14287 let rename = self.take_rename(false, window, cx)?;
14288 let workspace = self.workspace()?.downgrade();
14289 let (buffer, start) = self
14290 .buffer
14291 .read(cx)
14292 .text_anchor_for_position(rename.range.start, cx)?;
14293 let (end_buffer, _) = self
14294 .buffer
14295 .read(cx)
14296 .text_anchor_for_position(rename.range.end, cx)?;
14297 if buffer != end_buffer {
14298 return None;
14299 }
14300
14301 let old_name = rename.old_name;
14302 let new_name = rename.editor.read(cx).text(cx);
14303
14304 let rename = self.semantics_provider.as_ref()?.perform_rename(
14305 &buffer,
14306 start,
14307 new_name.clone(),
14308 cx,
14309 )?;
14310
14311 Some(cx.spawn_in(window, async move |editor, cx| {
14312 let project_transaction = rename.await?;
14313 Self::open_project_transaction(
14314 &editor,
14315 workspace,
14316 project_transaction,
14317 format!("Rename: {} → {}", old_name, new_name),
14318 cx,
14319 )
14320 .await?;
14321
14322 editor.update(cx, |editor, cx| {
14323 editor.refresh_document_highlights(cx);
14324 })?;
14325 Ok(())
14326 }))
14327 }
14328
14329 fn take_rename(
14330 &mut self,
14331 moving_cursor: bool,
14332 window: &mut Window,
14333 cx: &mut Context<Self>,
14334 ) -> Option<RenameState> {
14335 let rename = self.pending_rename.take()?;
14336 if rename.editor.focus_handle(cx).is_focused(window) {
14337 window.focus(&self.focus_handle);
14338 }
14339
14340 self.remove_blocks(
14341 [rename.block_id].into_iter().collect(),
14342 Some(Autoscroll::fit()),
14343 cx,
14344 );
14345 self.clear_highlights::<Rename>(cx);
14346 self.show_local_selections = true;
14347
14348 if moving_cursor {
14349 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14350 editor.selections.newest::<usize>(cx).head()
14351 });
14352
14353 // Update the selection to match the position of the selection inside
14354 // the rename editor.
14355 let snapshot = self.buffer.read(cx).read(cx);
14356 let rename_range = rename.range.to_offset(&snapshot);
14357 let cursor_in_editor = snapshot
14358 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14359 .min(rename_range.end);
14360 drop(snapshot);
14361
14362 self.change_selections(None, window, cx, |s| {
14363 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14364 });
14365 } else {
14366 self.refresh_document_highlights(cx);
14367 }
14368
14369 Some(rename)
14370 }
14371
14372 pub fn pending_rename(&self) -> Option<&RenameState> {
14373 self.pending_rename.as_ref()
14374 }
14375
14376 fn format(
14377 &mut self,
14378 _: &Format,
14379 window: &mut Window,
14380 cx: &mut Context<Self>,
14381 ) -> Option<Task<Result<()>>> {
14382 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14383
14384 let project = match &self.project {
14385 Some(project) => project.clone(),
14386 None => return None,
14387 };
14388
14389 Some(self.perform_format(
14390 project,
14391 FormatTrigger::Manual,
14392 FormatTarget::Buffers,
14393 window,
14394 cx,
14395 ))
14396 }
14397
14398 fn format_selections(
14399 &mut self,
14400 _: &FormatSelections,
14401 window: &mut Window,
14402 cx: &mut Context<Self>,
14403 ) -> Option<Task<Result<()>>> {
14404 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14405
14406 let project = match &self.project {
14407 Some(project) => project.clone(),
14408 None => return None,
14409 };
14410
14411 let ranges = self
14412 .selections
14413 .all_adjusted(cx)
14414 .into_iter()
14415 .map(|selection| selection.range())
14416 .collect_vec();
14417
14418 Some(self.perform_format(
14419 project,
14420 FormatTrigger::Manual,
14421 FormatTarget::Ranges(ranges),
14422 window,
14423 cx,
14424 ))
14425 }
14426
14427 fn perform_format(
14428 &mut self,
14429 project: Entity<Project>,
14430 trigger: FormatTrigger,
14431 target: FormatTarget,
14432 window: &mut Window,
14433 cx: &mut Context<Self>,
14434 ) -> Task<Result<()>> {
14435 let buffer = self.buffer.clone();
14436 let (buffers, target) = match target {
14437 FormatTarget::Buffers => {
14438 let mut buffers = buffer.read(cx).all_buffers();
14439 if trigger == FormatTrigger::Save {
14440 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14441 }
14442 (buffers, LspFormatTarget::Buffers)
14443 }
14444 FormatTarget::Ranges(selection_ranges) => {
14445 let multi_buffer = buffer.read(cx);
14446 let snapshot = multi_buffer.read(cx);
14447 let mut buffers = HashSet::default();
14448 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14449 BTreeMap::new();
14450 for selection_range in selection_ranges {
14451 for (buffer, buffer_range, _) in
14452 snapshot.range_to_buffer_ranges(selection_range)
14453 {
14454 let buffer_id = buffer.remote_id();
14455 let start = buffer.anchor_before(buffer_range.start);
14456 let end = buffer.anchor_after(buffer_range.end);
14457 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14458 buffer_id_to_ranges
14459 .entry(buffer_id)
14460 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14461 .or_insert_with(|| vec![start..end]);
14462 }
14463 }
14464 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14465 }
14466 };
14467
14468 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14469 let selections_prev = transaction_id_prev
14470 .and_then(|transaction_id_prev| {
14471 // default to selections as they were after the last edit, if we have them,
14472 // instead of how they are now.
14473 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14474 // will take you back to where you made the last edit, instead of staying where you scrolled
14475 self.selection_history
14476 .transaction(transaction_id_prev)
14477 .map(|t| t.0.clone())
14478 })
14479 .unwrap_or_else(|| {
14480 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14481 self.selections.disjoint_anchors()
14482 });
14483
14484 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14485 let format = project.update(cx, |project, cx| {
14486 project.format(buffers, target, true, trigger, cx)
14487 });
14488
14489 cx.spawn_in(window, async move |editor, cx| {
14490 let transaction = futures::select_biased! {
14491 transaction = format.log_err().fuse() => transaction,
14492 () = timeout => {
14493 log::warn!("timed out waiting for formatting");
14494 None
14495 }
14496 };
14497
14498 buffer
14499 .update(cx, |buffer, cx| {
14500 if let Some(transaction) = transaction {
14501 if !buffer.is_singleton() {
14502 buffer.push_transaction(&transaction.0, cx);
14503 }
14504 }
14505 cx.notify();
14506 })
14507 .ok();
14508
14509 if let Some(transaction_id_now) =
14510 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14511 {
14512 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14513 if has_new_transaction {
14514 _ = editor.update(cx, |editor, _| {
14515 editor
14516 .selection_history
14517 .insert_transaction(transaction_id_now, selections_prev);
14518 });
14519 }
14520 }
14521
14522 Ok(())
14523 })
14524 }
14525
14526 fn organize_imports(
14527 &mut self,
14528 _: &OrganizeImports,
14529 window: &mut Window,
14530 cx: &mut Context<Self>,
14531 ) -> Option<Task<Result<()>>> {
14532 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14533 let project = match &self.project {
14534 Some(project) => project.clone(),
14535 None => return None,
14536 };
14537 Some(self.perform_code_action_kind(
14538 project,
14539 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14540 window,
14541 cx,
14542 ))
14543 }
14544
14545 fn perform_code_action_kind(
14546 &mut self,
14547 project: Entity<Project>,
14548 kind: CodeActionKind,
14549 window: &mut Window,
14550 cx: &mut Context<Self>,
14551 ) -> Task<Result<()>> {
14552 let buffer = self.buffer.clone();
14553 let buffers = buffer.read(cx).all_buffers();
14554 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14555 let apply_action = project.update(cx, |project, cx| {
14556 project.apply_code_action_kind(buffers, kind, true, cx)
14557 });
14558 cx.spawn_in(window, async move |_, cx| {
14559 let transaction = futures::select_biased! {
14560 () = timeout => {
14561 log::warn!("timed out waiting for executing code action");
14562 None
14563 }
14564 transaction = apply_action.log_err().fuse() => transaction,
14565 };
14566 buffer
14567 .update(cx, |buffer, cx| {
14568 // check if we need this
14569 if let Some(transaction) = transaction {
14570 if !buffer.is_singleton() {
14571 buffer.push_transaction(&transaction.0, cx);
14572 }
14573 }
14574 cx.notify();
14575 })
14576 .ok();
14577 Ok(())
14578 })
14579 }
14580
14581 fn restart_language_server(
14582 &mut self,
14583 _: &RestartLanguageServer,
14584 _: &mut Window,
14585 cx: &mut Context<Self>,
14586 ) {
14587 if let Some(project) = self.project.clone() {
14588 self.buffer.update(cx, |multi_buffer, cx| {
14589 project.update(cx, |project, cx| {
14590 project.restart_language_servers_for_buffers(
14591 multi_buffer.all_buffers().into_iter().collect(),
14592 cx,
14593 );
14594 });
14595 })
14596 }
14597 }
14598
14599 fn stop_language_server(
14600 &mut self,
14601 _: &StopLanguageServer,
14602 _: &mut Window,
14603 cx: &mut Context<Self>,
14604 ) {
14605 if let Some(project) = self.project.clone() {
14606 self.buffer.update(cx, |multi_buffer, cx| {
14607 project.update(cx, |project, cx| {
14608 project.stop_language_servers_for_buffers(
14609 multi_buffer.all_buffers().into_iter().collect(),
14610 cx,
14611 );
14612 cx.emit(project::Event::RefreshInlayHints);
14613 });
14614 });
14615 }
14616 }
14617
14618 fn cancel_language_server_work(
14619 workspace: &mut Workspace,
14620 _: &actions::CancelLanguageServerWork,
14621 _: &mut Window,
14622 cx: &mut Context<Workspace>,
14623 ) {
14624 let project = workspace.project();
14625 let buffers = workspace
14626 .active_item(cx)
14627 .and_then(|item| item.act_as::<Editor>(cx))
14628 .map_or(HashSet::default(), |editor| {
14629 editor.read(cx).buffer.read(cx).all_buffers()
14630 });
14631 project.update(cx, |project, cx| {
14632 project.cancel_language_server_work_for_buffers(buffers, cx);
14633 });
14634 }
14635
14636 fn show_character_palette(
14637 &mut self,
14638 _: &ShowCharacterPalette,
14639 window: &mut Window,
14640 _: &mut Context<Self>,
14641 ) {
14642 window.show_character_palette();
14643 }
14644
14645 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14646 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14647 let buffer = self.buffer.read(cx).snapshot(cx);
14648 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14649 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14650 let is_valid = buffer
14651 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14652 .any(|entry| {
14653 entry.diagnostic.is_primary
14654 && !entry.range.is_empty()
14655 && entry.range.start == primary_range_start
14656 && entry.diagnostic.message == active_diagnostics.active_message
14657 });
14658
14659 if !is_valid {
14660 self.dismiss_diagnostics(cx);
14661 }
14662 }
14663 }
14664
14665 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14666 match &self.active_diagnostics {
14667 ActiveDiagnostic::Group(group) => Some(group),
14668 _ => None,
14669 }
14670 }
14671
14672 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14673 self.dismiss_diagnostics(cx);
14674 self.active_diagnostics = ActiveDiagnostic::All;
14675 }
14676
14677 fn activate_diagnostics(
14678 &mut self,
14679 buffer_id: BufferId,
14680 diagnostic: DiagnosticEntry<usize>,
14681 window: &mut Window,
14682 cx: &mut Context<Self>,
14683 ) {
14684 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14685 return;
14686 }
14687 self.dismiss_diagnostics(cx);
14688 let snapshot = self.snapshot(window, cx);
14689 let Some(diagnostic_renderer) = cx
14690 .try_global::<GlobalDiagnosticRenderer>()
14691 .map(|g| g.0.clone())
14692 else {
14693 return;
14694 };
14695 let buffer = self.buffer.read(cx).snapshot(cx);
14696
14697 let diagnostic_group = buffer
14698 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14699 .collect::<Vec<_>>();
14700
14701 let blocks = diagnostic_renderer.render_group(
14702 diagnostic_group,
14703 buffer_id,
14704 snapshot,
14705 cx.weak_entity(),
14706 cx,
14707 );
14708
14709 let blocks = self.display_map.update(cx, |display_map, cx| {
14710 display_map.insert_blocks(blocks, cx).into_iter().collect()
14711 });
14712 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14713 active_range: buffer.anchor_before(diagnostic.range.start)
14714 ..buffer.anchor_after(diagnostic.range.end),
14715 active_message: diagnostic.diagnostic.message.clone(),
14716 group_id: diagnostic.diagnostic.group_id,
14717 blocks,
14718 });
14719 cx.notify();
14720 }
14721
14722 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14723 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14724 return;
14725 };
14726
14727 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14728 if let ActiveDiagnostic::Group(group) = prev {
14729 self.display_map.update(cx, |display_map, cx| {
14730 display_map.remove_blocks(group.blocks, cx);
14731 });
14732 cx.notify();
14733 }
14734 }
14735
14736 /// Disable inline diagnostics rendering for this editor.
14737 pub fn disable_inline_diagnostics(&mut self) {
14738 self.inline_diagnostics_enabled = false;
14739 self.inline_diagnostics_update = Task::ready(());
14740 self.inline_diagnostics.clear();
14741 }
14742
14743 pub fn inline_diagnostics_enabled(&self) -> bool {
14744 self.inline_diagnostics_enabled
14745 }
14746
14747 pub fn show_inline_diagnostics(&self) -> bool {
14748 self.show_inline_diagnostics
14749 }
14750
14751 pub fn toggle_inline_diagnostics(
14752 &mut self,
14753 _: &ToggleInlineDiagnostics,
14754 window: &mut Window,
14755 cx: &mut Context<Editor>,
14756 ) {
14757 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14758 self.refresh_inline_diagnostics(false, window, cx);
14759 }
14760
14761 fn refresh_inline_diagnostics(
14762 &mut self,
14763 debounce: bool,
14764 window: &mut Window,
14765 cx: &mut Context<Self>,
14766 ) {
14767 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14768 self.inline_diagnostics_update = Task::ready(());
14769 self.inline_diagnostics.clear();
14770 return;
14771 }
14772
14773 let debounce_ms = ProjectSettings::get_global(cx)
14774 .diagnostics
14775 .inline
14776 .update_debounce_ms;
14777 let debounce = if debounce && debounce_ms > 0 {
14778 Some(Duration::from_millis(debounce_ms))
14779 } else {
14780 None
14781 };
14782 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14783 let editor = editor.upgrade().unwrap();
14784
14785 if let Some(debounce) = debounce {
14786 cx.background_executor().timer(debounce).await;
14787 }
14788 let Some(snapshot) = editor
14789 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14790 .ok()
14791 else {
14792 return;
14793 };
14794
14795 let new_inline_diagnostics = cx
14796 .background_spawn(async move {
14797 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14798 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14799 let message = diagnostic_entry
14800 .diagnostic
14801 .message
14802 .split_once('\n')
14803 .map(|(line, _)| line)
14804 .map(SharedString::new)
14805 .unwrap_or_else(|| {
14806 SharedString::from(diagnostic_entry.diagnostic.message)
14807 });
14808 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14809 let (Ok(i) | Err(i)) = inline_diagnostics
14810 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14811 inline_diagnostics.insert(
14812 i,
14813 (
14814 start_anchor,
14815 InlineDiagnostic {
14816 message,
14817 group_id: diagnostic_entry.diagnostic.group_id,
14818 start: diagnostic_entry.range.start.to_point(&snapshot),
14819 is_primary: diagnostic_entry.diagnostic.is_primary,
14820 severity: diagnostic_entry.diagnostic.severity,
14821 },
14822 ),
14823 );
14824 }
14825 inline_diagnostics
14826 })
14827 .await;
14828
14829 editor
14830 .update(cx, |editor, cx| {
14831 editor.inline_diagnostics = new_inline_diagnostics;
14832 cx.notify();
14833 })
14834 .ok();
14835 });
14836 }
14837
14838 pub fn set_selections_from_remote(
14839 &mut self,
14840 selections: Vec<Selection<Anchor>>,
14841 pending_selection: Option<Selection<Anchor>>,
14842 window: &mut Window,
14843 cx: &mut Context<Self>,
14844 ) {
14845 let old_cursor_position = self.selections.newest_anchor().head();
14846 self.selections.change_with(cx, |s| {
14847 s.select_anchors(selections);
14848 if let Some(pending_selection) = pending_selection {
14849 s.set_pending(pending_selection, SelectMode::Character);
14850 } else {
14851 s.clear_pending();
14852 }
14853 });
14854 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14855 }
14856
14857 fn push_to_selection_history(&mut self) {
14858 self.selection_history.push(SelectionHistoryEntry {
14859 selections: self.selections.disjoint_anchors(),
14860 select_next_state: self.select_next_state.clone(),
14861 select_prev_state: self.select_prev_state.clone(),
14862 add_selections_state: self.add_selections_state.clone(),
14863 });
14864 }
14865
14866 pub fn transact(
14867 &mut self,
14868 window: &mut Window,
14869 cx: &mut Context<Self>,
14870 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14871 ) -> Option<TransactionId> {
14872 self.start_transaction_at(Instant::now(), window, cx);
14873 update(self, window, cx);
14874 self.end_transaction_at(Instant::now(), cx)
14875 }
14876
14877 pub fn start_transaction_at(
14878 &mut self,
14879 now: Instant,
14880 window: &mut Window,
14881 cx: &mut Context<Self>,
14882 ) {
14883 self.end_selection(window, cx);
14884 if let Some(tx_id) = self
14885 .buffer
14886 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14887 {
14888 self.selection_history
14889 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14890 cx.emit(EditorEvent::TransactionBegun {
14891 transaction_id: tx_id,
14892 })
14893 }
14894 }
14895
14896 pub fn end_transaction_at(
14897 &mut self,
14898 now: Instant,
14899 cx: &mut Context<Self>,
14900 ) -> Option<TransactionId> {
14901 if let Some(transaction_id) = self
14902 .buffer
14903 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14904 {
14905 if let Some((_, end_selections)) =
14906 self.selection_history.transaction_mut(transaction_id)
14907 {
14908 *end_selections = Some(self.selections.disjoint_anchors());
14909 } else {
14910 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14911 }
14912
14913 cx.emit(EditorEvent::Edited { transaction_id });
14914 Some(transaction_id)
14915 } else {
14916 None
14917 }
14918 }
14919
14920 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14921 if self.selection_mark_mode {
14922 self.change_selections(None, window, cx, |s| {
14923 s.move_with(|_, sel| {
14924 sel.collapse_to(sel.head(), SelectionGoal::None);
14925 });
14926 })
14927 }
14928 self.selection_mark_mode = true;
14929 cx.notify();
14930 }
14931
14932 pub fn swap_selection_ends(
14933 &mut self,
14934 _: &actions::SwapSelectionEnds,
14935 window: &mut Window,
14936 cx: &mut Context<Self>,
14937 ) {
14938 self.change_selections(None, window, cx, |s| {
14939 s.move_with(|_, sel| {
14940 if sel.start != sel.end {
14941 sel.reversed = !sel.reversed
14942 }
14943 });
14944 });
14945 self.request_autoscroll(Autoscroll::newest(), cx);
14946 cx.notify();
14947 }
14948
14949 pub fn toggle_fold(
14950 &mut self,
14951 _: &actions::ToggleFold,
14952 window: &mut Window,
14953 cx: &mut Context<Self>,
14954 ) {
14955 if self.is_singleton(cx) {
14956 let selection = self.selections.newest::<Point>(cx);
14957
14958 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14959 let range = if selection.is_empty() {
14960 let point = selection.head().to_display_point(&display_map);
14961 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14962 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14963 .to_point(&display_map);
14964 start..end
14965 } else {
14966 selection.range()
14967 };
14968 if display_map.folds_in_range(range).next().is_some() {
14969 self.unfold_lines(&Default::default(), window, cx)
14970 } else {
14971 self.fold(&Default::default(), window, cx)
14972 }
14973 } else {
14974 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14975 let buffer_ids: HashSet<_> = self
14976 .selections
14977 .disjoint_anchor_ranges()
14978 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14979 .collect();
14980
14981 let should_unfold = buffer_ids
14982 .iter()
14983 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14984
14985 for buffer_id in buffer_ids {
14986 if should_unfold {
14987 self.unfold_buffer(buffer_id, cx);
14988 } else {
14989 self.fold_buffer(buffer_id, cx);
14990 }
14991 }
14992 }
14993 }
14994
14995 pub fn toggle_fold_recursive(
14996 &mut self,
14997 _: &actions::ToggleFoldRecursive,
14998 window: &mut Window,
14999 cx: &mut Context<Self>,
15000 ) {
15001 let selection = self.selections.newest::<Point>(cx);
15002
15003 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15004 let range = if selection.is_empty() {
15005 let point = selection.head().to_display_point(&display_map);
15006 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15007 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15008 .to_point(&display_map);
15009 start..end
15010 } else {
15011 selection.range()
15012 };
15013 if display_map.folds_in_range(range).next().is_some() {
15014 self.unfold_recursive(&Default::default(), window, cx)
15015 } else {
15016 self.fold_recursive(&Default::default(), window, cx)
15017 }
15018 }
15019
15020 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15021 if self.is_singleton(cx) {
15022 let mut to_fold = Vec::new();
15023 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15024 let selections = self.selections.all_adjusted(cx);
15025
15026 for selection in selections {
15027 let range = selection.range().sorted();
15028 let buffer_start_row = range.start.row;
15029
15030 if range.start.row != range.end.row {
15031 let mut found = false;
15032 let mut row = range.start.row;
15033 while row <= range.end.row {
15034 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15035 {
15036 found = true;
15037 row = crease.range().end.row + 1;
15038 to_fold.push(crease);
15039 } else {
15040 row += 1
15041 }
15042 }
15043 if found {
15044 continue;
15045 }
15046 }
15047
15048 for row in (0..=range.start.row).rev() {
15049 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15050 if crease.range().end.row >= buffer_start_row {
15051 to_fold.push(crease);
15052 if row <= range.start.row {
15053 break;
15054 }
15055 }
15056 }
15057 }
15058 }
15059
15060 self.fold_creases(to_fold, true, window, cx);
15061 } else {
15062 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15063 let buffer_ids = self
15064 .selections
15065 .disjoint_anchor_ranges()
15066 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15067 .collect::<HashSet<_>>();
15068 for buffer_id in buffer_ids {
15069 self.fold_buffer(buffer_id, cx);
15070 }
15071 }
15072 }
15073
15074 fn fold_at_level(
15075 &mut self,
15076 fold_at: &FoldAtLevel,
15077 window: &mut Window,
15078 cx: &mut Context<Self>,
15079 ) {
15080 if !self.buffer.read(cx).is_singleton() {
15081 return;
15082 }
15083
15084 let fold_at_level = fold_at.0;
15085 let snapshot = self.buffer.read(cx).snapshot(cx);
15086 let mut to_fold = Vec::new();
15087 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15088
15089 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15090 while start_row < end_row {
15091 match self
15092 .snapshot(window, cx)
15093 .crease_for_buffer_row(MultiBufferRow(start_row))
15094 {
15095 Some(crease) => {
15096 let nested_start_row = crease.range().start.row + 1;
15097 let nested_end_row = crease.range().end.row;
15098
15099 if current_level < fold_at_level {
15100 stack.push((nested_start_row, nested_end_row, current_level + 1));
15101 } else if current_level == fold_at_level {
15102 to_fold.push(crease);
15103 }
15104
15105 start_row = nested_end_row + 1;
15106 }
15107 None => start_row += 1,
15108 }
15109 }
15110 }
15111
15112 self.fold_creases(to_fold, true, window, cx);
15113 }
15114
15115 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15116 if self.buffer.read(cx).is_singleton() {
15117 let mut fold_ranges = Vec::new();
15118 let snapshot = self.buffer.read(cx).snapshot(cx);
15119
15120 for row in 0..snapshot.max_row().0 {
15121 if let Some(foldable_range) = self
15122 .snapshot(window, cx)
15123 .crease_for_buffer_row(MultiBufferRow(row))
15124 {
15125 fold_ranges.push(foldable_range);
15126 }
15127 }
15128
15129 self.fold_creases(fold_ranges, true, window, cx);
15130 } else {
15131 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15132 editor
15133 .update_in(cx, |editor, _, cx| {
15134 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15135 editor.fold_buffer(buffer_id, cx);
15136 }
15137 })
15138 .ok();
15139 });
15140 }
15141 }
15142
15143 pub fn fold_function_bodies(
15144 &mut self,
15145 _: &actions::FoldFunctionBodies,
15146 window: &mut Window,
15147 cx: &mut Context<Self>,
15148 ) {
15149 let snapshot = self.buffer.read(cx).snapshot(cx);
15150
15151 let ranges = snapshot
15152 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15153 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15154 .collect::<Vec<_>>();
15155
15156 let creases = ranges
15157 .into_iter()
15158 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15159 .collect();
15160
15161 self.fold_creases(creases, true, window, cx);
15162 }
15163
15164 pub fn fold_recursive(
15165 &mut self,
15166 _: &actions::FoldRecursive,
15167 window: &mut Window,
15168 cx: &mut Context<Self>,
15169 ) {
15170 let mut to_fold = Vec::new();
15171 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15172 let selections = self.selections.all_adjusted(cx);
15173
15174 for selection in selections {
15175 let range = selection.range().sorted();
15176 let buffer_start_row = range.start.row;
15177
15178 if range.start.row != range.end.row {
15179 let mut found = false;
15180 for row in range.start.row..=range.end.row {
15181 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15182 found = true;
15183 to_fold.push(crease);
15184 }
15185 }
15186 if found {
15187 continue;
15188 }
15189 }
15190
15191 for row in (0..=range.start.row).rev() {
15192 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15193 if crease.range().end.row >= buffer_start_row {
15194 to_fold.push(crease);
15195 } else {
15196 break;
15197 }
15198 }
15199 }
15200 }
15201
15202 self.fold_creases(to_fold, true, window, cx);
15203 }
15204
15205 pub fn fold_at(
15206 &mut self,
15207 buffer_row: MultiBufferRow,
15208 window: &mut Window,
15209 cx: &mut Context<Self>,
15210 ) {
15211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15212
15213 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15214 let autoscroll = self
15215 .selections
15216 .all::<Point>(cx)
15217 .iter()
15218 .any(|selection| crease.range().overlaps(&selection.range()));
15219
15220 self.fold_creases(vec![crease], autoscroll, window, cx);
15221 }
15222 }
15223
15224 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15225 if self.is_singleton(cx) {
15226 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15227 let buffer = &display_map.buffer_snapshot;
15228 let selections = self.selections.all::<Point>(cx);
15229 let ranges = selections
15230 .iter()
15231 .map(|s| {
15232 let range = s.display_range(&display_map).sorted();
15233 let mut start = range.start.to_point(&display_map);
15234 let mut end = range.end.to_point(&display_map);
15235 start.column = 0;
15236 end.column = buffer.line_len(MultiBufferRow(end.row));
15237 start..end
15238 })
15239 .collect::<Vec<_>>();
15240
15241 self.unfold_ranges(&ranges, true, true, cx);
15242 } else {
15243 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15244 let buffer_ids = self
15245 .selections
15246 .disjoint_anchor_ranges()
15247 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15248 .collect::<HashSet<_>>();
15249 for buffer_id in buffer_ids {
15250 self.unfold_buffer(buffer_id, cx);
15251 }
15252 }
15253 }
15254
15255 pub fn unfold_recursive(
15256 &mut self,
15257 _: &UnfoldRecursive,
15258 _window: &mut Window,
15259 cx: &mut Context<Self>,
15260 ) {
15261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15262 let selections = self.selections.all::<Point>(cx);
15263 let ranges = selections
15264 .iter()
15265 .map(|s| {
15266 let mut range = s.display_range(&display_map).sorted();
15267 *range.start.column_mut() = 0;
15268 *range.end.column_mut() = display_map.line_len(range.end.row());
15269 let start = range.start.to_point(&display_map);
15270 let end = range.end.to_point(&display_map);
15271 start..end
15272 })
15273 .collect::<Vec<_>>();
15274
15275 self.unfold_ranges(&ranges, true, true, cx);
15276 }
15277
15278 pub fn unfold_at(
15279 &mut self,
15280 buffer_row: MultiBufferRow,
15281 _window: &mut Window,
15282 cx: &mut Context<Self>,
15283 ) {
15284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15285
15286 let intersection_range = Point::new(buffer_row.0, 0)
15287 ..Point::new(
15288 buffer_row.0,
15289 display_map.buffer_snapshot.line_len(buffer_row),
15290 );
15291
15292 let autoscroll = self
15293 .selections
15294 .all::<Point>(cx)
15295 .iter()
15296 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15297
15298 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15299 }
15300
15301 pub fn unfold_all(
15302 &mut self,
15303 _: &actions::UnfoldAll,
15304 _window: &mut Window,
15305 cx: &mut Context<Self>,
15306 ) {
15307 if self.buffer.read(cx).is_singleton() {
15308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15309 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15310 } else {
15311 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15312 editor
15313 .update(cx, |editor, cx| {
15314 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15315 editor.unfold_buffer(buffer_id, cx);
15316 }
15317 })
15318 .ok();
15319 });
15320 }
15321 }
15322
15323 pub fn fold_selected_ranges(
15324 &mut self,
15325 _: &FoldSelectedRanges,
15326 window: &mut Window,
15327 cx: &mut Context<Self>,
15328 ) {
15329 let selections = self.selections.all_adjusted(cx);
15330 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15331 let ranges = selections
15332 .into_iter()
15333 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15334 .collect::<Vec<_>>();
15335 self.fold_creases(ranges, true, window, cx);
15336 }
15337
15338 pub fn fold_ranges<T: ToOffset + Clone>(
15339 &mut self,
15340 ranges: Vec<Range<T>>,
15341 auto_scroll: bool,
15342 window: &mut Window,
15343 cx: &mut Context<Self>,
15344 ) {
15345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15346 let ranges = ranges
15347 .into_iter()
15348 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15349 .collect::<Vec<_>>();
15350 self.fold_creases(ranges, auto_scroll, window, cx);
15351 }
15352
15353 pub fn fold_creases<T: ToOffset + Clone>(
15354 &mut self,
15355 creases: Vec<Crease<T>>,
15356 auto_scroll: bool,
15357 _window: &mut Window,
15358 cx: &mut Context<Self>,
15359 ) {
15360 if creases.is_empty() {
15361 return;
15362 }
15363
15364 let mut buffers_affected = HashSet::default();
15365 let multi_buffer = self.buffer().read(cx);
15366 for crease in &creases {
15367 if let Some((_, buffer, _)) =
15368 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15369 {
15370 buffers_affected.insert(buffer.read(cx).remote_id());
15371 };
15372 }
15373
15374 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15375
15376 if auto_scroll {
15377 self.request_autoscroll(Autoscroll::fit(), cx);
15378 }
15379
15380 cx.notify();
15381
15382 self.scrollbar_marker_state.dirty = true;
15383 self.folds_did_change(cx);
15384 }
15385
15386 /// Removes any folds whose ranges intersect any of the given ranges.
15387 pub fn unfold_ranges<T: ToOffset + Clone>(
15388 &mut self,
15389 ranges: &[Range<T>],
15390 inclusive: bool,
15391 auto_scroll: bool,
15392 cx: &mut Context<Self>,
15393 ) {
15394 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15395 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15396 });
15397 self.folds_did_change(cx);
15398 }
15399
15400 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15401 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15402 return;
15403 }
15404 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15405 self.display_map.update(cx, |display_map, cx| {
15406 display_map.fold_buffers([buffer_id], cx)
15407 });
15408 cx.emit(EditorEvent::BufferFoldToggled {
15409 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15410 folded: true,
15411 });
15412 cx.notify();
15413 }
15414
15415 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15416 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15417 return;
15418 }
15419 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15420 self.display_map.update(cx, |display_map, cx| {
15421 display_map.unfold_buffers([buffer_id], cx);
15422 });
15423 cx.emit(EditorEvent::BufferFoldToggled {
15424 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15425 folded: false,
15426 });
15427 cx.notify();
15428 }
15429
15430 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15431 self.display_map.read(cx).is_buffer_folded(buffer)
15432 }
15433
15434 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15435 self.display_map.read(cx).folded_buffers()
15436 }
15437
15438 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15439 self.display_map.update(cx, |display_map, cx| {
15440 display_map.disable_header_for_buffer(buffer_id, cx);
15441 });
15442 cx.notify();
15443 }
15444
15445 /// Removes any folds with the given ranges.
15446 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15447 &mut self,
15448 ranges: &[Range<T>],
15449 type_id: TypeId,
15450 auto_scroll: bool,
15451 cx: &mut Context<Self>,
15452 ) {
15453 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15454 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15455 });
15456 self.folds_did_change(cx);
15457 }
15458
15459 fn remove_folds_with<T: ToOffset + Clone>(
15460 &mut self,
15461 ranges: &[Range<T>],
15462 auto_scroll: bool,
15463 cx: &mut Context<Self>,
15464 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15465 ) {
15466 if ranges.is_empty() {
15467 return;
15468 }
15469
15470 let mut buffers_affected = HashSet::default();
15471 let multi_buffer = self.buffer().read(cx);
15472 for range in ranges {
15473 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15474 buffers_affected.insert(buffer.read(cx).remote_id());
15475 };
15476 }
15477
15478 self.display_map.update(cx, update);
15479
15480 if auto_scroll {
15481 self.request_autoscroll(Autoscroll::fit(), cx);
15482 }
15483
15484 cx.notify();
15485 self.scrollbar_marker_state.dirty = true;
15486 self.active_indent_guides_state.dirty = true;
15487 }
15488
15489 pub fn update_fold_widths(
15490 &mut self,
15491 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15492 cx: &mut Context<Self>,
15493 ) -> bool {
15494 self.display_map
15495 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15496 }
15497
15498 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15499 self.display_map.read(cx).fold_placeholder.clone()
15500 }
15501
15502 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15503 self.buffer.update(cx, |buffer, cx| {
15504 buffer.set_all_diff_hunks_expanded(cx);
15505 });
15506 }
15507
15508 pub fn expand_all_diff_hunks(
15509 &mut self,
15510 _: &ExpandAllDiffHunks,
15511 _window: &mut Window,
15512 cx: &mut Context<Self>,
15513 ) {
15514 self.buffer.update(cx, |buffer, cx| {
15515 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15516 });
15517 }
15518
15519 pub fn toggle_selected_diff_hunks(
15520 &mut self,
15521 _: &ToggleSelectedDiffHunks,
15522 _window: &mut Window,
15523 cx: &mut Context<Self>,
15524 ) {
15525 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15526 self.toggle_diff_hunks_in_ranges(ranges, cx);
15527 }
15528
15529 pub fn diff_hunks_in_ranges<'a>(
15530 &'a self,
15531 ranges: &'a [Range<Anchor>],
15532 buffer: &'a MultiBufferSnapshot,
15533 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15534 ranges.iter().flat_map(move |range| {
15535 let end_excerpt_id = range.end.excerpt_id;
15536 let range = range.to_point(buffer);
15537 let mut peek_end = range.end;
15538 if range.end.row < buffer.max_row().0 {
15539 peek_end = Point::new(range.end.row + 1, 0);
15540 }
15541 buffer
15542 .diff_hunks_in_range(range.start..peek_end)
15543 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15544 })
15545 }
15546
15547 pub fn has_stageable_diff_hunks_in_ranges(
15548 &self,
15549 ranges: &[Range<Anchor>],
15550 snapshot: &MultiBufferSnapshot,
15551 ) -> bool {
15552 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15553 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15554 }
15555
15556 pub fn toggle_staged_selected_diff_hunks(
15557 &mut self,
15558 _: &::git::ToggleStaged,
15559 _: &mut Window,
15560 cx: &mut Context<Self>,
15561 ) {
15562 let snapshot = self.buffer.read(cx).snapshot(cx);
15563 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15564 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15565 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15566 }
15567
15568 pub fn set_render_diff_hunk_controls(
15569 &mut self,
15570 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15571 cx: &mut Context<Self>,
15572 ) {
15573 self.render_diff_hunk_controls = render_diff_hunk_controls;
15574 cx.notify();
15575 }
15576
15577 pub fn stage_and_next(
15578 &mut self,
15579 _: &::git::StageAndNext,
15580 window: &mut Window,
15581 cx: &mut Context<Self>,
15582 ) {
15583 self.do_stage_or_unstage_and_next(true, window, cx);
15584 }
15585
15586 pub fn unstage_and_next(
15587 &mut self,
15588 _: &::git::UnstageAndNext,
15589 window: &mut Window,
15590 cx: &mut Context<Self>,
15591 ) {
15592 self.do_stage_or_unstage_and_next(false, window, cx);
15593 }
15594
15595 pub fn stage_or_unstage_diff_hunks(
15596 &mut self,
15597 stage: bool,
15598 ranges: Vec<Range<Anchor>>,
15599 cx: &mut Context<Self>,
15600 ) {
15601 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15602 cx.spawn(async move |this, cx| {
15603 task.await?;
15604 this.update(cx, |this, cx| {
15605 let snapshot = this.buffer.read(cx).snapshot(cx);
15606 let chunk_by = this
15607 .diff_hunks_in_ranges(&ranges, &snapshot)
15608 .chunk_by(|hunk| hunk.buffer_id);
15609 for (buffer_id, hunks) in &chunk_by {
15610 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15611 }
15612 })
15613 })
15614 .detach_and_log_err(cx);
15615 }
15616
15617 fn save_buffers_for_ranges_if_needed(
15618 &mut self,
15619 ranges: &[Range<Anchor>],
15620 cx: &mut Context<Editor>,
15621 ) -> Task<Result<()>> {
15622 let multibuffer = self.buffer.read(cx);
15623 let snapshot = multibuffer.read(cx);
15624 let buffer_ids: HashSet<_> = ranges
15625 .iter()
15626 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15627 .collect();
15628 drop(snapshot);
15629
15630 let mut buffers = HashSet::default();
15631 for buffer_id in buffer_ids {
15632 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15633 let buffer = buffer_entity.read(cx);
15634 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15635 {
15636 buffers.insert(buffer_entity);
15637 }
15638 }
15639 }
15640
15641 if let Some(project) = &self.project {
15642 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15643 } else {
15644 Task::ready(Ok(()))
15645 }
15646 }
15647
15648 fn do_stage_or_unstage_and_next(
15649 &mut self,
15650 stage: bool,
15651 window: &mut Window,
15652 cx: &mut Context<Self>,
15653 ) {
15654 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15655
15656 if ranges.iter().any(|range| range.start != range.end) {
15657 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15658 return;
15659 }
15660
15661 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15662 let snapshot = self.snapshot(window, cx);
15663 let position = self.selections.newest::<Point>(cx).head();
15664 let mut row = snapshot
15665 .buffer_snapshot
15666 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15667 .find(|hunk| hunk.row_range.start.0 > position.row)
15668 .map(|hunk| hunk.row_range.start);
15669
15670 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15671 // Outside of the project diff editor, wrap around to the beginning.
15672 if !all_diff_hunks_expanded {
15673 row = row.or_else(|| {
15674 snapshot
15675 .buffer_snapshot
15676 .diff_hunks_in_range(Point::zero()..position)
15677 .find(|hunk| hunk.row_range.end.0 < position.row)
15678 .map(|hunk| hunk.row_range.start)
15679 });
15680 }
15681
15682 if let Some(row) = row {
15683 let destination = Point::new(row.0, 0);
15684 let autoscroll = Autoscroll::center();
15685
15686 self.unfold_ranges(&[destination..destination], false, false, cx);
15687 self.change_selections(Some(autoscroll), window, cx, |s| {
15688 s.select_ranges([destination..destination]);
15689 });
15690 }
15691 }
15692
15693 fn do_stage_or_unstage(
15694 &self,
15695 stage: bool,
15696 buffer_id: BufferId,
15697 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15698 cx: &mut App,
15699 ) -> Option<()> {
15700 let project = self.project.as_ref()?;
15701 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15702 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15703 let buffer_snapshot = buffer.read(cx).snapshot();
15704 let file_exists = buffer_snapshot
15705 .file()
15706 .is_some_and(|file| file.disk_state().exists());
15707 diff.update(cx, |diff, cx| {
15708 diff.stage_or_unstage_hunks(
15709 stage,
15710 &hunks
15711 .map(|hunk| buffer_diff::DiffHunk {
15712 buffer_range: hunk.buffer_range,
15713 diff_base_byte_range: hunk.diff_base_byte_range,
15714 secondary_status: hunk.secondary_status,
15715 range: Point::zero()..Point::zero(), // unused
15716 })
15717 .collect::<Vec<_>>(),
15718 &buffer_snapshot,
15719 file_exists,
15720 cx,
15721 )
15722 });
15723 None
15724 }
15725
15726 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15727 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15728 self.buffer
15729 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15730 }
15731
15732 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15733 self.buffer.update(cx, |buffer, cx| {
15734 let ranges = vec![Anchor::min()..Anchor::max()];
15735 if !buffer.all_diff_hunks_expanded()
15736 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15737 {
15738 buffer.collapse_diff_hunks(ranges, cx);
15739 true
15740 } else {
15741 false
15742 }
15743 })
15744 }
15745
15746 fn toggle_diff_hunks_in_ranges(
15747 &mut self,
15748 ranges: Vec<Range<Anchor>>,
15749 cx: &mut Context<Editor>,
15750 ) {
15751 self.buffer.update(cx, |buffer, cx| {
15752 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15753 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15754 })
15755 }
15756
15757 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15758 self.buffer.update(cx, |buffer, cx| {
15759 let snapshot = buffer.snapshot(cx);
15760 let excerpt_id = range.end.excerpt_id;
15761 let point_range = range.to_point(&snapshot);
15762 let expand = !buffer.single_hunk_is_expanded(range, cx);
15763 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15764 })
15765 }
15766
15767 pub(crate) fn apply_all_diff_hunks(
15768 &mut self,
15769 _: &ApplyAllDiffHunks,
15770 window: &mut Window,
15771 cx: &mut Context<Self>,
15772 ) {
15773 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15774
15775 let buffers = self.buffer.read(cx).all_buffers();
15776 for branch_buffer in buffers {
15777 branch_buffer.update(cx, |branch_buffer, cx| {
15778 branch_buffer.merge_into_base(Vec::new(), cx);
15779 });
15780 }
15781
15782 if let Some(project) = self.project.clone() {
15783 self.save(true, project, window, cx).detach_and_log_err(cx);
15784 }
15785 }
15786
15787 pub(crate) fn apply_selected_diff_hunks(
15788 &mut self,
15789 _: &ApplyDiffHunk,
15790 window: &mut Window,
15791 cx: &mut Context<Self>,
15792 ) {
15793 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15794 let snapshot = self.snapshot(window, cx);
15795 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15796 let mut ranges_by_buffer = HashMap::default();
15797 self.transact(window, cx, |editor, _window, cx| {
15798 for hunk in hunks {
15799 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15800 ranges_by_buffer
15801 .entry(buffer.clone())
15802 .or_insert_with(Vec::new)
15803 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15804 }
15805 }
15806
15807 for (buffer, ranges) in ranges_by_buffer {
15808 buffer.update(cx, |buffer, cx| {
15809 buffer.merge_into_base(ranges, cx);
15810 });
15811 }
15812 });
15813
15814 if let Some(project) = self.project.clone() {
15815 self.save(true, project, window, cx).detach_and_log_err(cx);
15816 }
15817 }
15818
15819 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15820 if hovered != self.gutter_hovered {
15821 self.gutter_hovered = hovered;
15822 cx.notify();
15823 }
15824 }
15825
15826 pub fn insert_blocks(
15827 &mut self,
15828 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15829 autoscroll: Option<Autoscroll>,
15830 cx: &mut Context<Self>,
15831 ) -> Vec<CustomBlockId> {
15832 let blocks = self
15833 .display_map
15834 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15835 if let Some(autoscroll) = autoscroll {
15836 self.request_autoscroll(autoscroll, cx);
15837 }
15838 cx.notify();
15839 blocks
15840 }
15841
15842 pub fn resize_blocks(
15843 &mut self,
15844 heights: HashMap<CustomBlockId, u32>,
15845 autoscroll: Option<Autoscroll>,
15846 cx: &mut Context<Self>,
15847 ) {
15848 self.display_map
15849 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15850 if let Some(autoscroll) = autoscroll {
15851 self.request_autoscroll(autoscroll, cx);
15852 }
15853 cx.notify();
15854 }
15855
15856 pub fn replace_blocks(
15857 &mut self,
15858 renderers: HashMap<CustomBlockId, RenderBlock>,
15859 autoscroll: Option<Autoscroll>,
15860 cx: &mut Context<Self>,
15861 ) {
15862 self.display_map
15863 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15864 if let Some(autoscroll) = autoscroll {
15865 self.request_autoscroll(autoscroll, cx);
15866 }
15867 cx.notify();
15868 }
15869
15870 pub fn remove_blocks(
15871 &mut self,
15872 block_ids: HashSet<CustomBlockId>,
15873 autoscroll: Option<Autoscroll>,
15874 cx: &mut Context<Self>,
15875 ) {
15876 self.display_map.update(cx, |display_map, cx| {
15877 display_map.remove_blocks(block_ids, cx)
15878 });
15879 if let Some(autoscroll) = autoscroll {
15880 self.request_autoscroll(autoscroll, cx);
15881 }
15882 cx.notify();
15883 }
15884
15885 pub fn row_for_block(
15886 &self,
15887 block_id: CustomBlockId,
15888 cx: &mut Context<Self>,
15889 ) -> Option<DisplayRow> {
15890 self.display_map
15891 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15892 }
15893
15894 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15895 self.focused_block = Some(focused_block);
15896 }
15897
15898 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15899 self.focused_block.take()
15900 }
15901
15902 pub fn insert_creases(
15903 &mut self,
15904 creases: impl IntoIterator<Item = Crease<Anchor>>,
15905 cx: &mut Context<Self>,
15906 ) -> Vec<CreaseId> {
15907 self.display_map
15908 .update(cx, |map, cx| map.insert_creases(creases, cx))
15909 }
15910
15911 pub fn remove_creases(
15912 &mut self,
15913 ids: impl IntoIterator<Item = CreaseId>,
15914 cx: &mut Context<Self>,
15915 ) {
15916 self.display_map
15917 .update(cx, |map, cx| map.remove_creases(ids, cx));
15918 }
15919
15920 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15921 self.display_map
15922 .update(cx, |map, cx| map.snapshot(cx))
15923 .longest_row()
15924 }
15925
15926 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15927 self.display_map
15928 .update(cx, |map, cx| map.snapshot(cx))
15929 .max_point()
15930 }
15931
15932 pub fn text(&self, cx: &App) -> String {
15933 self.buffer.read(cx).read(cx).text()
15934 }
15935
15936 pub fn is_empty(&self, cx: &App) -> bool {
15937 self.buffer.read(cx).read(cx).is_empty()
15938 }
15939
15940 pub fn text_option(&self, cx: &App) -> Option<String> {
15941 let text = self.text(cx);
15942 let text = text.trim();
15943
15944 if text.is_empty() {
15945 return None;
15946 }
15947
15948 Some(text.to_string())
15949 }
15950
15951 pub fn set_text(
15952 &mut self,
15953 text: impl Into<Arc<str>>,
15954 window: &mut Window,
15955 cx: &mut Context<Self>,
15956 ) {
15957 self.transact(window, cx, |this, _, cx| {
15958 this.buffer
15959 .read(cx)
15960 .as_singleton()
15961 .expect("you can only call set_text on editors for singleton buffers")
15962 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15963 });
15964 }
15965
15966 pub fn display_text(&self, cx: &mut App) -> String {
15967 self.display_map
15968 .update(cx, |map, cx| map.snapshot(cx))
15969 .text()
15970 }
15971
15972 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15973 let mut wrap_guides = smallvec::smallvec![];
15974
15975 if self.show_wrap_guides == Some(false) {
15976 return wrap_guides;
15977 }
15978
15979 let settings = self.buffer.read(cx).language_settings(cx);
15980 if settings.show_wrap_guides {
15981 match self.soft_wrap_mode(cx) {
15982 SoftWrap::Column(soft_wrap) => {
15983 wrap_guides.push((soft_wrap as usize, true));
15984 }
15985 SoftWrap::Bounded(soft_wrap) => {
15986 wrap_guides.push((soft_wrap as usize, true));
15987 }
15988 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15989 }
15990 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15991 }
15992
15993 wrap_guides
15994 }
15995
15996 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15997 let settings = self.buffer.read(cx).language_settings(cx);
15998 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15999 match mode {
16000 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16001 SoftWrap::None
16002 }
16003 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16004 language_settings::SoftWrap::PreferredLineLength => {
16005 SoftWrap::Column(settings.preferred_line_length)
16006 }
16007 language_settings::SoftWrap::Bounded => {
16008 SoftWrap::Bounded(settings.preferred_line_length)
16009 }
16010 }
16011 }
16012
16013 pub fn set_soft_wrap_mode(
16014 &mut self,
16015 mode: language_settings::SoftWrap,
16016
16017 cx: &mut Context<Self>,
16018 ) {
16019 self.soft_wrap_mode_override = Some(mode);
16020 cx.notify();
16021 }
16022
16023 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16024 self.hard_wrap = hard_wrap;
16025 cx.notify();
16026 }
16027
16028 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16029 self.text_style_refinement = Some(style);
16030 }
16031
16032 /// called by the Element so we know what style we were most recently rendered with.
16033 pub(crate) fn set_style(
16034 &mut self,
16035 style: EditorStyle,
16036 window: &mut Window,
16037 cx: &mut Context<Self>,
16038 ) {
16039 let rem_size = window.rem_size();
16040 self.display_map.update(cx, |map, cx| {
16041 map.set_font(
16042 style.text.font(),
16043 style.text.font_size.to_pixels(rem_size),
16044 cx,
16045 )
16046 });
16047 self.style = Some(style);
16048 }
16049
16050 pub fn style(&self) -> Option<&EditorStyle> {
16051 self.style.as_ref()
16052 }
16053
16054 // Called by the element. This method is not designed to be called outside of the editor
16055 // element's layout code because it does not notify when rewrapping is computed synchronously.
16056 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16057 self.display_map
16058 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16059 }
16060
16061 pub fn set_soft_wrap(&mut self) {
16062 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16063 }
16064
16065 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16066 if self.soft_wrap_mode_override.is_some() {
16067 self.soft_wrap_mode_override.take();
16068 } else {
16069 let soft_wrap = match self.soft_wrap_mode(cx) {
16070 SoftWrap::GitDiff => return,
16071 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16072 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16073 language_settings::SoftWrap::None
16074 }
16075 };
16076 self.soft_wrap_mode_override = Some(soft_wrap);
16077 }
16078 cx.notify();
16079 }
16080
16081 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16082 let Some(workspace) = self.workspace() else {
16083 return;
16084 };
16085 let fs = workspace.read(cx).app_state().fs.clone();
16086 let current_show = TabBarSettings::get_global(cx).show;
16087 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16088 setting.show = Some(!current_show);
16089 });
16090 }
16091
16092 pub fn toggle_indent_guides(
16093 &mut self,
16094 _: &ToggleIndentGuides,
16095 _: &mut Window,
16096 cx: &mut Context<Self>,
16097 ) {
16098 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16099 self.buffer
16100 .read(cx)
16101 .language_settings(cx)
16102 .indent_guides
16103 .enabled
16104 });
16105 self.show_indent_guides = Some(!currently_enabled);
16106 cx.notify();
16107 }
16108
16109 fn should_show_indent_guides(&self) -> Option<bool> {
16110 self.show_indent_guides
16111 }
16112
16113 pub fn toggle_line_numbers(
16114 &mut self,
16115 _: &ToggleLineNumbers,
16116 _: &mut Window,
16117 cx: &mut Context<Self>,
16118 ) {
16119 let mut editor_settings = EditorSettings::get_global(cx).clone();
16120 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16121 EditorSettings::override_global(editor_settings, cx);
16122 }
16123
16124 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16125 if let Some(show_line_numbers) = self.show_line_numbers {
16126 return show_line_numbers;
16127 }
16128 EditorSettings::get_global(cx).gutter.line_numbers
16129 }
16130
16131 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16132 self.use_relative_line_numbers
16133 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16134 }
16135
16136 pub fn toggle_relative_line_numbers(
16137 &mut self,
16138 _: &ToggleRelativeLineNumbers,
16139 _: &mut Window,
16140 cx: &mut Context<Self>,
16141 ) {
16142 let is_relative = self.should_use_relative_line_numbers(cx);
16143 self.set_relative_line_number(Some(!is_relative), cx)
16144 }
16145
16146 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16147 self.use_relative_line_numbers = is_relative;
16148 cx.notify();
16149 }
16150
16151 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16152 self.show_gutter = show_gutter;
16153 cx.notify();
16154 }
16155
16156 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16157 self.show_scrollbars = show_scrollbars;
16158 cx.notify();
16159 }
16160
16161 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16162 self.show_line_numbers = Some(show_line_numbers);
16163 cx.notify();
16164 }
16165
16166 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16167 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16168 cx.notify();
16169 }
16170
16171 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16172 self.show_code_actions = Some(show_code_actions);
16173 cx.notify();
16174 }
16175
16176 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16177 self.show_runnables = Some(show_runnables);
16178 cx.notify();
16179 }
16180
16181 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16182 self.show_breakpoints = Some(show_breakpoints);
16183 cx.notify();
16184 }
16185
16186 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16187 if self.display_map.read(cx).masked != masked {
16188 self.display_map.update(cx, |map, _| map.masked = masked);
16189 }
16190 cx.notify()
16191 }
16192
16193 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16194 self.show_wrap_guides = Some(show_wrap_guides);
16195 cx.notify();
16196 }
16197
16198 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16199 self.show_indent_guides = Some(show_indent_guides);
16200 cx.notify();
16201 }
16202
16203 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16204 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16205 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16206 if let Some(dir) = file.abs_path(cx).parent() {
16207 return Some(dir.to_owned());
16208 }
16209 }
16210
16211 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16212 return Some(project_path.path.to_path_buf());
16213 }
16214 }
16215
16216 None
16217 }
16218
16219 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16220 self.active_excerpt(cx)?
16221 .1
16222 .read(cx)
16223 .file()
16224 .and_then(|f| f.as_local())
16225 }
16226
16227 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16228 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16229 let buffer = buffer.read(cx);
16230 if let Some(project_path) = buffer.project_path(cx) {
16231 let project = self.project.as_ref()?.read(cx);
16232 project.absolute_path(&project_path, cx)
16233 } else {
16234 buffer
16235 .file()
16236 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16237 }
16238 })
16239 }
16240
16241 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16242 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16243 let project_path = buffer.read(cx).project_path(cx)?;
16244 let project = self.project.as_ref()?.read(cx);
16245 let entry = project.entry_for_path(&project_path, cx)?;
16246 let path = entry.path.to_path_buf();
16247 Some(path)
16248 })
16249 }
16250
16251 pub fn reveal_in_finder(
16252 &mut self,
16253 _: &RevealInFileManager,
16254 _window: &mut Window,
16255 cx: &mut Context<Self>,
16256 ) {
16257 if let Some(target) = self.target_file(cx) {
16258 cx.reveal_path(&target.abs_path(cx));
16259 }
16260 }
16261
16262 pub fn copy_path(
16263 &mut self,
16264 _: &zed_actions::workspace::CopyPath,
16265 _window: &mut Window,
16266 cx: &mut Context<Self>,
16267 ) {
16268 if let Some(path) = self.target_file_abs_path(cx) {
16269 if let Some(path) = path.to_str() {
16270 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16271 }
16272 }
16273 }
16274
16275 pub fn copy_relative_path(
16276 &mut self,
16277 _: &zed_actions::workspace::CopyRelativePath,
16278 _window: &mut Window,
16279 cx: &mut Context<Self>,
16280 ) {
16281 if let Some(path) = self.target_file_path(cx) {
16282 if let Some(path) = path.to_str() {
16283 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16284 }
16285 }
16286 }
16287
16288 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16289 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16290 buffer.read(cx).project_path(cx)
16291 } else {
16292 None
16293 }
16294 }
16295
16296 // Returns true if the editor handled a go-to-line request
16297 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16298 maybe!({
16299 let breakpoint_store = self.breakpoint_store.as_ref()?;
16300
16301 let Some((_, _, active_position)) =
16302 breakpoint_store.read(cx).active_position().cloned()
16303 else {
16304 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16305 return None;
16306 };
16307
16308 let snapshot = self
16309 .project
16310 .as_ref()?
16311 .read(cx)
16312 .buffer_for_id(active_position.buffer_id?, cx)?
16313 .read(cx)
16314 .snapshot();
16315
16316 let mut handled = false;
16317 for (id, ExcerptRange { context, .. }) in self
16318 .buffer
16319 .read(cx)
16320 .excerpts_for_buffer(active_position.buffer_id?, cx)
16321 {
16322 if context.start.cmp(&active_position, &snapshot).is_ge()
16323 || context.end.cmp(&active_position, &snapshot).is_lt()
16324 {
16325 continue;
16326 }
16327 let snapshot = self.buffer.read(cx).snapshot(cx);
16328 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16329
16330 handled = true;
16331 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16332 self.go_to_line::<DebugCurrentRowHighlight>(
16333 multibuffer_anchor,
16334 Some(cx.theme().colors().editor_debugger_active_line_background),
16335 window,
16336 cx,
16337 );
16338
16339 cx.notify();
16340 }
16341 handled.then_some(())
16342 })
16343 .is_some()
16344 }
16345
16346 pub fn copy_file_name_without_extension(
16347 &mut self,
16348 _: &CopyFileNameWithoutExtension,
16349 _: &mut Window,
16350 cx: &mut Context<Self>,
16351 ) {
16352 if let Some(file) = self.target_file(cx) {
16353 if let Some(file_stem) = file.path().file_stem() {
16354 if let Some(name) = file_stem.to_str() {
16355 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16356 }
16357 }
16358 }
16359 }
16360
16361 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16362 if let Some(file) = self.target_file(cx) {
16363 if let Some(file_name) = file.path().file_name() {
16364 if let Some(name) = file_name.to_str() {
16365 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16366 }
16367 }
16368 }
16369 }
16370
16371 pub fn toggle_git_blame(
16372 &mut self,
16373 _: &::git::Blame,
16374 window: &mut Window,
16375 cx: &mut Context<Self>,
16376 ) {
16377 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16378
16379 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16380 self.start_git_blame(true, window, cx);
16381 }
16382
16383 cx.notify();
16384 }
16385
16386 pub fn toggle_git_blame_inline(
16387 &mut self,
16388 _: &ToggleGitBlameInline,
16389 window: &mut Window,
16390 cx: &mut Context<Self>,
16391 ) {
16392 self.toggle_git_blame_inline_internal(true, window, cx);
16393 cx.notify();
16394 }
16395
16396 pub fn open_git_blame_commit(
16397 &mut self,
16398 _: &OpenGitBlameCommit,
16399 window: &mut Window,
16400 cx: &mut Context<Self>,
16401 ) {
16402 self.open_git_blame_commit_internal(window, cx);
16403 }
16404
16405 fn open_git_blame_commit_internal(
16406 &mut self,
16407 window: &mut Window,
16408 cx: &mut Context<Self>,
16409 ) -> Option<()> {
16410 let blame = self.blame.as_ref()?;
16411 let snapshot = self.snapshot(window, cx);
16412 let cursor = self.selections.newest::<Point>(cx).head();
16413 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16414 let blame_entry = blame
16415 .update(cx, |blame, cx| {
16416 blame
16417 .blame_for_rows(
16418 &[RowInfo {
16419 buffer_id: Some(buffer.remote_id()),
16420 buffer_row: Some(point.row),
16421 ..Default::default()
16422 }],
16423 cx,
16424 )
16425 .next()
16426 })
16427 .flatten()?;
16428 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16429 let repo = blame.read(cx).repository(cx)?;
16430 let workspace = self.workspace()?.downgrade();
16431 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16432 None
16433 }
16434
16435 pub fn git_blame_inline_enabled(&self) -> bool {
16436 self.git_blame_inline_enabled
16437 }
16438
16439 pub fn toggle_selection_menu(
16440 &mut self,
16441 _: &ToggleSelectionMenu,
16442 _: &mut Window,
16443 cx: &mut Context<Self>,
16444 ) {
16445 self.show_selection_menu = self
16446 .show_selection_menu
16447 .map(|show_selections_menu| !show_selections_menu)
16448 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16449
16450 cx.notify();
16451 }
16452
16453 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16454 self.show_selection_menu
16455 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16456 }
16457
16458 fn start_git_blame(
16459 &mut self,
16460 user_triggered: bool,
16461 window: &mut Window,
16462 cx: &mut Context<Self>,
16463 ) {
16464 if let Some(project) = self.project.as_ref() {
16465 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16466 return;
16467 };
16468
16469 if buffer.read(cx).file().is_none() {
16470 return;
16471 }
16472
16473 let focused = self.focus_handle(cx).contains_focused(window, cx);
16474
16475 let project = project.clone();
16476 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16477 self.blame_subscription =
16478 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16479 self.blame = Some(blame);
16480 }
16481 }
16482
16483 fn toggle_git_blame_inline_internal(
16484 &mut self,
16485 user_triggered: bool,
16486 window: &mut Window,
16487 cx: &mut Context<Self>,
16488 ) {
16489 if self.git_blame_inline_enabled {
16490 self.git_blame_inline_enabled = false;
16491 self.show_git_blame_inline = false;
16492 self.show_git_blame_inline_delay_task.take();
16493 } else {
16494 self.git_blame_inline_enabled = true;
16495 self.start_git_blame_inline(user_triggered, window, cx);
16496 }
16497
16498 cx.notify();
16499 }
16500
16501 fn start_git_blame_inline(
16502 &mut self,
16503 user_triggered: bool,
16504 window: &mut Window,
16505 cx: &mut Context<Self>,
16506 ) {
16507 self.start_git_blame(user_triggered, window, cx);
16508
16509 if ProjectSettings::get_global(cx)
16510 .git
16511 .inline_blame_delay()
16512 .is_some()
16513 {
16514 self.start_inline_blame_timer(window, cx);
16515 } else {
16516 self.show_git_blame_inline = true
16517 }
16518 }
16519
16520 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16521 self.blame.as_ref()
16522 }
16523
16524 pub fn show_git_blame_gutter(&self) -> bool {
16525 self.show_git_blame_gutter
16526 }
16527
16528 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16529 self.show_git_blame_gutter && self.has_blame_entries(cx)
16530 }
16531
16532 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16533 self.show_git_blame_inline
16534 && (self.focus_handle.is_focused(window)
16535 || self
16536 .git_blame_inline_tooltip
16537 .as_ref()
16538 .and_then(|t| t.upgrade())
16539 .is_some())
16540 && !self.newest_selection_head_on_empty_line(cx)
16541 && self.has_blame_entries(cx)
16542 }
16543
16544 fn has_blame_entries(&self, cx: &App) -> bool {
16545 self.blame()
16546 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16547 }
16548
16549 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16550 let cursor_anchor = self.selections.newest_anchor().head();
16551
16552 let snapshot = self.buffer.read(cx).snapshot(cx);
16553 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16554
16555 snapshot.line_len(buffer_row) == 0
16556 }
16557
16558 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16559 let buffer_and_selection = maybe!({
16560 let selection = self.selections.newest::<Point>(cx);
16561 let selection_range = selection.range();
16562
16563 let multi_buffer = self.buffer().read(cx);
16564 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16565 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16566
16567 let (buffer, range, _) = if selection.reversed {
16568 buffer_ranges.first()
16569 } else {
16570 buffer_ranges.last()
16571 }?;
16572
16573 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16574 ..text::ToPoint::to_point(&range.end, &buffer).row;
16575 Some((
16576 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16577 selection,
16578 ))
16579 });
16580
16581 let Some((buffer, selection)) = buffer_and_selection else {
16582 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16583 };
16584
16585 let Some(project) = self.project.as_ref() else {
16586 return Task::ready(Err(anyhow!("editor does not have project")));
16587 };
16588
16589 project.update(cx, |project, cx| {
16590 project.get_permalink_to_line(&buffer, selection, cx)
16591 })
16592 }
16593
16594 pub fn copy_permalink_to_line(
16595 &mut self,
16596 _: &CopyPermalinkToLine,
16597 window: &mut Window,
16598 cx: &mut Context<Self>,
16599 ) {
16600 let permalink_task = self.get_permalink_to_line(cx);
16601 let workspace = self.workspace();
16602
16603 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16604 Ok(permalink) => {
16605 cx.update(|_, cx| {
16606 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16607 })
16608 .ok();
16609 }
16610 Err(err) => {
16611 let message = format!("Failed to copy permalink: {err}");
16612
16613 Err::<(), anyhow::Error>(err).log_err();
16614
16615 if let Some(workspace) = workspace {
16616 workspace
16617 .update_in(cx, |workspace, _, cx| {
16618 struct CopyPermalinkToLine;
16619
16620 workspace.show_toast(
16621 Toast::new(
16622 NotificationId::unique::<CopyPermalinkToLine>(),
16623 message,
16624 ),
16625 cx,
16626 )
16627 })
16628 .ok();
16629 }
16630 }
16631 })
16632 .detach();
16633 }
16634
16635 pub fn copy_file_location(
16636 &mut self,
16637 _: &CopyFileLocation,
16638 _: &mut Window,
16639 cx: &mut Context<Self>,
16640 ) {
16641 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16642 if let Some(file) = self.target_file(cx) {
16643 if let Some(path) = file.path().to_str() {
16644 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16645 }
16646 }
16647 }
16648
16649 pub fn open_permalink_to_line(
16650 &mut self,
16651 _: &OpenPermalinkToLine,
16652 window: &mut Window,
16653 cx: &mut Context<Self>,
16654 ) {
16655 let permalink_task = self.get_permalink_to_line(cx);
16656 let workspace = self.workspace();
16657
16658 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16659 Ok(permalink) => {
16660 cx.update(|_, cx| {
16661 cx.open_url(permalink.as_ref());
16662 })
16663 .ok();
16664 }
16665 Err(err) => {
16666 let message = format!("Failed to open permalink: {err}");
16667
16668 Err::<(), anyhow::Error>(err).log_err();
16669
16670 if let Some(workspace) = workspace {
16671 workspace
16672 .update(cx, |workspace, cx| {
16673 struct OpenPermalinkToLine;
16674
16675 workspace.show_toast(
16676 Toast::new(
16677 NotificationId::unique::<OpenPermalinkToLine>(),
16678 message,
16679 ),
16680 cx,
16681 )
16682 })
16683 .ok();
16684 }
16685 }
16686 })
16687 .detach();
16688 }
16689
16690 pub fn insert_uuid_v4(
16691 &mut self,
16692 _: &InsertUuidV4,
16693 window: &mut Window,
16694 cx: &mut Context<Self>,
16695 ) {
16696 self.insert_uuid(UuidVersion::V4, window, cx);
16697 }
16698
16699 pub fn insert_uuid_v7(
16700 &mut self,
16701 _: &InsertUuidV7,
16702 window: &mut Window,
16703 cx: &mut Context<Self>,
16704 ) {
16705 self.insert_uuid(UuidVersion::V7, window, cx);
16706 }
16707
16708 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16709 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16710 self.transact(window, cx, |this, window, cx| {
16711 let edits = this
16712 .selections
16713 .all::<Point>(cx)
16714 .into_iter()
16715 .map(|selection| {
16716 let uuid = match version {
16717 UuidVersion::V4 => uuid::Uuid::new_v4(),
16718 UuidVersion::V7 => uuid::Uuid::now_v7(),
16719 };
16720
16721 (selection.range(), uuid.to_string())
16722 });
16723 this.edit(edits, cx);
16724 this.refresh_inline_completion(true, false, window, cx);
16725 });
16726 }
16727
16728 pub fn open_selections_in_multibuffer(
16729 &mut self,
16730 _: &OpenSelectionsInMultibuffer,
16731 window: &mut Window,
16732 cx: &mut Context<Self>,
16733 ) {
16734 let multibuffer = self.buffer.read(cx);
16735
16736 let Some(buffer) = multibuffer.as_singleton() else {
16737 return;
16738 };
16739
16740 let Some(workspace) = self.workspace() else {
16741 return;
16742 };
16743
16744 let locations = self
16745 .selections
16746 .disjoint_anchors()
16747 .iter()
16748 .map(|range| Location {
16749 buffer: buffer.clone(),
16750 range: range.start.text_anchor..range.end.text_anchor,
16751 })
16752 .collect::<Vec<_>>();
16753
16754 let title = multibuffer.title(cx).to_string();
16755
16756 cx.spawn_in(window, async move |_, cx| {
16757 workspace.update_in(cx, |workspace, window, cx| {
16758 Self::open_locations_in_multibuffer(
16759 workspace,
16760 locations,
16761 format!("Selections for '{title}'"),
16762 false,
16763 MultibufferSelectionMode::All,
16764 window,
16765 cx,
16766 );
16767 })
16768 })
16769 .detach();
16770 }
16771
16772 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16773 /// last highlight added will be used.
16774 ///
16775 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16776 pub fn highlight_rows<T: 'static>(
16777 &mut self,
16778 range: Range<Anchor>,
16779 color: Hsla,
16780 should_autoscroll: bool,
16781 cx: &mut Context<Self>,
16782 ) {
16783 let snapshot = self.buffer().read(cx).snapshot(cx);
16784 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16785 let ix = row_highlights.binary_search_by(|highlight| {
16786 Ordering::Equal
16787 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16788 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16789 });
16790
16791 if let Err(mut ix) = ix {
16792 let index = post_inc(&mut self.highlight_order);
16793
16794 // If this range intersects with the preceding highlight, then merge it with
16795 // the preceding highlight. Otherwise insert a new highlight.
16796 let mut merged = false;
16797 if ix > 0 {
16798 let prev_highlight = &mut row_highlights[ix - 1];
16799 if prev_highlight
16800 .range
16801 .end
16802 .cmp(&range.start, &snapshot)
16803 .is_ge()
16804 {
16805 ix -= 1;
16806 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16807 prev_highlight.range.end = range.end;
16808 }
16809 merged = true;
16810 prev_highlight.index = index;
16811 prev_highlight.color = color;
16812 prev_highlight.should_autoscroll = should_autoscroll;
16813 }
16814 }
16815
16816 if !merged {
16817 row_highlights.insert(
16818 ix,
16819 RowHighlight {
16820 range: range.clone(),
16821 index,
16822 color,
16823 should_autoscroll,
16824 },
16825 );
16826 }
16827
16828 // If any of the following highlights intersect with this one, merge them.
16829 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16830 let highlight = &row_highlights[ix];
16831 if next_highlight
16832 .range
16833 .start
16834 .cmp(&highlight.range.end, &snapshot)
16835 .is_le()
16836 {
16837 if next_highlight
16838 .range
16839 .end
16840 .cmp(&highlight.range.end, &snapshot)
16841 .is_gt()
16842 {
16843 row_highlights[ix].range.end = next_highlight.range.end;
16844 }
16845 row_highlights.remove(ix + 1);
16846 } else {
16847 break;
16848 }
16849 }
16850 }
16851 }
16852
16853 /// Remove any highlighted row ranges of the given type that intersect the
16854 /// given ranges.
16855 pub fn remove_highlighted_rows<T: 'static>(
16856 &mut self,
16857 ranges_to_remove: Vec<Range<Anchor>>,
16858 cx: &mut Context<Self>,
16859 ) {
16860 let snapshot = self.buffer().read(cx).snapshot(cx);
16861 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16862 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16863 row_highlights.retain(|highlight| {
16864 while let Some(range_to_remove) = ranges_to_remove.peek() {
16865 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16866 Ordering::Less | Ordering::Equal => {
16867 ranges_to_remove.next();
16868 }
16869 Ordering::Greater => {
16870 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16871 Ordering::Less | Ordering::Equal => {
16872 return false;
16873 }
16874 Ordering::Greater => break,
16875 }
16876 }
16877 }
16878 }
16879
16880 true
16881 })
16882 }
16883
16884 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16885 pub fn clear_row_highlights<T: 'static>(&mut self) {
16886 self.highlighted_rows.remove(&TypeId::of::<T>());
16887 }
16888
16889 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16890 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16891 self.highlighted_rows
16892 .get(&TypeId::of::<T>())
16893 .map_or(&[] as &[_], |vec| vec.as_slice())
16894 .iter()
16895 .map(|highlight| (highlight.range.clone(), highlight.color))
16896 }
16897
16898 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16899 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16900 /// Allows to ignore certain kinds of highlights.
16901 pub fn highlighted_display_rows(
16902 &self,
16903 window: &mut Window,
16904 cx: &mut App,
16905 ) -> BTreeMap<DisplayRow, LineHighlight> {
16906 let snapshot = self.snapshot(window, cx);
16907 let mut used_highlight_orders = HashMap::default();
16908 self.highlighted_rows
16909 .iter()
16910 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16911 .fold(
16912 BTreeMap::<DisplayRow, LineHighlight>::new(),
16913 |mut unique_rows, highlight| {
16914 let start = highlight.range.start.to_display_point(&snapshot);
16915 let end = highlight.range.end.to_display_point(&snapshot);
16916 let start_row = start.row().0;
16917 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16918 && end.column() == 0
16919 {
16920 end.row().0.saturating_sub(1)
16921 } else {
16922 end.row().0
16923 };
16924 for row in start_row..=end_row {
16925 let used_index =
16926 used_highlight_orders.entry(row).or_insert(highlight.index);
16927 if highlight.index >= *used_index {
16928 *used_index = highlight.index;
16929 unique_rows.insert(DisplayRow(row), highlight.color.into());
16930 }
16931 }
16932 unique_rows
16933 },
16934 )
16935 }
16936
16937 pub fn highlighted_display_row_for_autoscroll(
16938 &self,
16939 snapshot: &DisplaySnapshot,
16940 ) -> Option<DisplayRow> {
16941 self.highlighted_rows
16942 .values()
16943 .flat_map(|highlighted_rows| highlighted_rows.iter())
16944 .filter_map(|highlight| {
16945 if highlight.should_autoscroll {
16946 Some(highlight.range.start.to_display_point(snapshot).row())
16947 } else {
16948 None
16949 }
16950 })
16951 .min()
16952 }
16953
16954 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16955 self.highlight_background::<SearchWithinRange>(
16956 ranges,
16957 |colors| colors.editor_document_highlight_read_background,
16958 cx,
16959 )
16960 }
16961
16962 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16963 self.breadcrumb_header = Some(new_header);
16964 }
16965
16966 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16967 self.clear_background_highlights::<SearchWithinRange>(cx);
16968 }
16969
16970 pub fn highlight_background<T: 'static>(
16971 &mut self,
16972 ranges: &[Range<Anchor>],
16973 color_fetcher: fn(&ThemeColors) -> Hsla,
16974 cx: &mut Context<Self>,
16975 ) {
16976 self.background_highlights
16977 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16978 self.scrollbar_marker_state.dirty = true;
16979 cx.notify();
16980 }
16981
16982 pub fn clear_background_highlights<T: 'static>(
16983 &mut self,
16984 cx: &mut Context<Self>,
16985 ) -> Option<BackgroundHighlight> {
16986 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16987 if !text_highlights.1.is_empty() {
16988 self.scrollbar_marker_state.dirty = true;
16989 cx.notify();
16990 }
16991 Some(text_highlights)
16992 }
16993
16994 pub fn highlight_gutter<T: 'static>(
16995 &mut self,
16996 ranges: &[Range<Anchor>],
16997 color_fetcher: fn(&App) -> Hsla,
16998 cx: &mut Context<Self>,
16999 ) {
17000 self.gutter_highlights
17001 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17002 cx.notify();
17003 }
17004
17005 pub fn clear_gutter_highlights<T: 'static>(
17006 &mut self,
17007 cx: &mut Context<Self>,
17008 ) -> Option<GutterHighlight> {
17009 cx.notify();
17010 self.gutter_highlights.remove(&TypeId::of::<T>())
17011 }
17012
17013 #[cfg(feature = "test-support")]
17014 pub fn all_text_background_highlights(
17015 &self,
17016 window: &mut Window,
17017 cx: &mut Context<Self>,
17018 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17019 let snapshot = self.snapshot(window, cx);
17020 let buffer = &snapshot.buffer_snapshot;
17021 let start = buffer.anchor_before(0);
17022 let end = buffer.anchor_after(buffer.len());
17023 let theme = cx.theme().colors();
17024 self.background_highlights_in_range(start..end, &snapshot, theme)
17025 }
17026
17027 #[cfg(feature = "test-support")]
17028 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17029 let snapshot = self.buffer().read(cx).snapshot(cx);
17030
17031 let highlights = self
17032 .background_highlights
17033 .get(&TypeId::of::<items::BufferSearchHighlights>());
17034
17035 if let Some((_color, ranges)) = highlights {
17036 ranges
17037 .iter()
17038 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17039 .collect_vec()
17040 } else {
17041 vec![]
17042 }
17043 }
17044
17045 fn document_highlights_for_position<'a>(
17046 &'a self,
17047 position: Anchor,
17048 buffer: &'a MultiBufferSnapshot,
17049 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17050 let read_highlights = self
17051 .background_highlights
17052 .get(&TypeId::of::<DocumentHighlightRead>())
17053 .map(|h| &h.1);
17054 let write_highlights = self
17055 .background_highlights
17056 .get(&TypeId::of::<DocumentHighlightWrite>())
17057 .map(|h| &h.1);
17058 let left_position = position.bias_left(buffer);
17059 let right_position = position.bias_right(buffer);
17060 read_highlights
17061 .into_iter()
17062 .chain(write_highlights)
17063 .flat_map(move |ranges| {
17064 let start_ix = match ranges.binary_search_by(|probe| {
17065 let cmp = probe.end.cmp(&left_position, buffer);
17066 if cmp.is_ge() {
17067 Ordering::Greater
17068 } else {
17069 Ordering::Less
17070 }
17071 }) {
17072 Ok(i) | Err(i) => i,
17073 };
17074
17075 ranges[start_ix..]
17076 .iter()
17077 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17078 })
17079 }
17080
17081 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17082 self.background_highlights
17083 .get(&TypeId::of::<T>())
17084 .map_or(false, |(_, highlights)| !highlights.is_empty())
17085 }
17086
17087 pub fn background_highlights_in_range(
17088 &self,
17089 search_range: Range<Anchor>,
17090 display_snapshot: &DisplaySnapshot,
17091 theme: &ThemeColors,
17092 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17093 let mut results = Vec::new();
17094 for (color_fetcher, ranges) in self.background_highlights.values() {
17095 let color = color_fetcher(theme);
17096 let start_ix = match ranges.binary_search_by(|probe| {
17097 let cmp = probe
17098 .end
17099 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17100 if cmp.is_gt() {
17101 Ordering::Greater
17102 } else {
17103 Ordering::Less
17104 }
17105 }) {
17106 Ok(i) | Err(i) => i,
17107 };
17108 for range in &ranges[start_ix..] {
17109 if range
17110 .start
17111 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17112 .is_ge()
17113 {
17114 break;
17115 }
17116
17117 let start = range.start.to_display_point(display_snapshot);
17118 let end = range.end.to_display_point(display_snapshot);
17119 results.push((start..end, color))
17120 }
17121 }
17122 results
17123 }
17124
17125 pub fn background_highlight_row_ranges<T: 'static>(
17126 &self,
17127 search_range: Range<Anchor>,
17128 display_snapshot: &DisplaySnapshot,
17129 count: usize,
17130 ) -> Vec<RangeInclusive<DisplayPoint>> {
17131 let mut results = Vec::new();
17132 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17133 return vec![];
17134 };
17135
17136 let start_ix = match ranges.binary_search_by(|probe| {
17137 let cmp = probe
17138 .end
17139 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17140 if cmp.is_gt() {
17141 Ordering::Greater
17142 } else {
17143 Ordering::Less
17144 }
17145 }) {
17146 Ok(i) | Err(i) => i,
17147 };
17148 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17149 if let (Some(start_display), Some(end_display)) = (start, end) {
17150 results.push(
17151 start_display.to_display_point(display_snapshot)
17152 ..=end_display.to_display_point(display_snapshot),
17153 );
17154 }
17155 };
17156 let mut start_row: Option<Point> = None;
17157 let mut end_row: Option<Point> = None;
17158 if ranges.len() > count {
17159 return Vec::new();
17160 }
17161 for range in &ranges[start_ix..] {
17162 if range
17163 .start
17164 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17165 .is_ge()
17166 {
17167 break;
17168 }
17169 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17170 if let Some(current_row) = &end_row {
17171 if end.row == current_row.row {
17172 continue;
17173 }
17174 }
17175 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17176 if start_row.is_none() {
17177 assert_eq!(end_row, None);
17178 start_row = Some(start);
17179 end_row = Some(end);
17180 continue;
17181 }
17182 if let Some(current_end) = end_row.as_mut() {
17183 if start.row > current_end.row + 1 {
17184 push_region(start_row, end_row);
17185 start_row = Some(start);
17186 end_row = Some(end);
17187 } else {
17188 // Merge two hunks.
17189 *current_end = end;
17190 }
17191 } else {
17192 unreachable!();
17193 }
17194 }
17195 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17196 push_region(start_row, end_row);
17197 results
17198 }
17199
17200 pub fn gutter_highlights_in_range(
17201 &self,
17202 search_range: Range<Anchor>,
17203 display_snapshot: &DisplaySnapshot,
17204 cx: &App,
17205 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17206 let mut results = Vec::new();
17207 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17208 let color = color_fetcher(cx);
17209 let start_ix = match ranges.binary_search_by(|probe| {
17210 let cmp = probe
17211 .end
17212 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17213 if cmp.is_gt() {
17214 Ordering::Greater
17215 } else {
17216 Ordering::Less
17217 }
17218 }) {
17219 Ok(i) | Err(i) => i,
17220 };
17221 for range in &ranges[start_ix..] {
17222 if range
17223 .start
17224 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17225 .is_ge()
17226 {
17227 break;
17228 }
17229
17230 let start = range.start.to_display_point(display_snapshot);
17231 let end = range.end.to_display_point(display_snapshot);
17232 results.push((start..end, color))
17233 }
17234 }
17235 results
17236 }
17237
17238 /// Get the text ranges corresponding to the redaction query
17239 pub fn redacted_ranges(
17240 &self,
17241 search_range: Range<Anchor>,
17242 display_snapshot: &DisplaySnapshot,
17243 cx: &App,
17244 ) -> Vec<Range<DisplayPoint>> {
17245 display_snapshot
17246 .buffer_snapshot
17247 .redacted_ranges(search_range, |file| {
17248 if let Some(file) = file {
17249 file.is_private()
17250 && EditorSettings::get(
17251 Some(SettingsLocation {
17252 worktree_id: file.worktree_id(cx),
17253 path: file.path().as_ref(),
17254 }),
17255 cx,
17256 )
17257 .redact_private_values
17258 } else {
17259 false
17260 }
17261 })
17262 .map(|range| {
17263 range.start.to_display_point(display_snapshot)
17264 ..range.end.to_display_point(display_snapshot)
17265 })
17266 .collect()
17267 }
17268
17269 pub fn highlight_text<T: 'static>(
17270 &mut self,
17271 ranges: Vec<Range<Anchor>>,
17272 style: HighlightStyle,
17273 cx: &mut Context<Self>,
17274 ) {
17275 self.display_map.update(cx, |map, _| {
17276 map.highlight_text(TypeId::of::<T>(), ranges, style)
17277 });
17278 cx.notify();
17279 }
17280
17281 pub(crate) fn highlight_inlays<T: 'static>(
17282 &mut self,
17283 highlights: Vec<InlayHighlight>,
17284 style: HighlightStyle,
17285 cx: &mut Context<Self>,
17286 ) {
17287 self.display_map.update(cx, |map, _| {
17288 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17289 });
17290 cx.notify();
17291 }
17292
17293 pub fn text_highlights<'a, T: 'static>(
17294 &'a self,
17295 cx: &'a App,
17296 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17297 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17298 }
17299
17300 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17301 let cleared = self
17302 .display_map
17303 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17304 if cleared {
17305 cx.notify();
17306 }
17307 }
17308
17309 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17310 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17311 && self.focus_handle.is_focused(window)
17312 }
17313
17314 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17315 self.show_cursor_when_unfocused = is_enabled;
17316 cx.notify();
17317 }
17318
17319 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17320 cx.notify();
17321 }
17322
17323 fn on_buffer_event(
17324 &mut self,
17325 multibuffer: &Entity<MultiBuffer>,
17326 event: &multi_buffer::Event,
17327 window: &mut Window,
17328 cx: &mut Context<Self>,
17329 ) {
17330 match event {
17331 multi_buffer::Event::Edited {
17332 singleton_buffer_edited,
17333 edited_buffer: buffer_edited,
17334 } => {
17335 self.scrollbar_marker_state.dirty = true;
17336 self.active_indent_guides_state.dirty = true;
17337 self.refresh_active_diagnostics(cx);
17338 self.refresh_code_actions(window, cx);
17339 if self.has_active_inline_completion() {
17340 self.update_visible_inline_completion(window, cx);
17341 }
17342 if let Some(buffer) = buffer_edited {
17343 let buffer_id = buffer.read(cx).remote_id();
17344 if !self.registered_buffers.contains_key(&buffer_id) {
17345 if let Some(project) = self.project.as_ref() {
17346 project.update(cx, |project, cx| {
17347 self.registered_buffers.insert(
17348 buffer_id,
17349 project.register_buffer_with_language_servers(&buffer, cx),
17350 );
17351 })
17352 }
17353 }
17354 }
17355 cx.emit(EditorEvent::BufferEdited);
17356 cx.emit(SearchEvent::MatchesInvalidated);
17357 if *singleton_buffer_edited {
17358 if let Some(project) = &self.project {
17359 #[allow(clippy::mutable_key_type)]
17360 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17361 multibuffer
17362 .all_buffers()
17363 .into_iter()
17364 .filter_map(|buffer| {
17365 buffer.update(cx, |buffer, cx| {
17366 let language = buffer.language()?;
17367 let should_discard = project.update(cx, |project, cx| {
17368 project.is_local()
17369 && !project.has_language_servers_for(buffer, cx)
17370 });
17371 should_discard.not().then_some(language.clone())
17372 })
17373 })
17374 .collect::<HashSet<_>>()
17375 });
17376 if !languages_affected.is_empty() {
17377 self.refresh_inlay_hints(
17378 InlayHintRefreshReason::BufferEdited(languages_affected),
17379 cx,
17380 );
17381 }
17382 }
17383 }
17384
17385 let Some(project) = &self.project else { return };
17386 let (telemetry, is_via_ssh) = {
17387 let project = project.read(cx);
17388 let telemetry = project.client().telemetry().clone();
17389 let is_via_ssh = project.is_via_ssh();
17390 (telemetry, is_via_ssh)
17391 };
17392 refresh_linked_ranges(self, window, cx);
17393 telemetry.log_edit_event("editor", is_via_ssh);
17394 }
17395 multi_buffer::Event::ExcerptsAdded {
17396 buffer,
17397 predecessor,
17398 excerpts,
17399 } => {
17400 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17401 let buffer_id = buffer.read(cx).remote_id();
17402 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17403 if let Some(project) = &self.project {
17404 get_uncommitted_diff_for_buffer(
17405 project,
17406 [buffer.clone()],
17407 self.buffer.clone(),
17408 cx,
17409 )
17410 .detach();
17411 }
17412 }
17413 cx.emit(EditorEvent::ExcerptsAdded {
17414 buffer: buffer.clone(),
17415 predecessor: *predecessor,
17416 excerpts: excerpts.clone(),
17417 });
17418 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17419 }
17420 multi_buffer::Event::ExcerptsRemoved { ids } => {
17421 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17422 let buffer = self.buffer.read(cx);
17423 self.registered_buffers
17424 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17425 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17426 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17427 }
17428 multi_buffer::Event::ExcerptsEdited {
17429 excerpt_ids,
17430 buffer_ids,
17431 } => {
17432 self.display_map.update(cx, |map, cx| {
17433 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17434 });
17435 cx.emit(EditorEvent::ExcerptsEdited {
17436 ids: excerpt_ids.clone(),
17437 })
17438 }
17439 multi_buffer::Event::ExcerptsExpanded { ids } => {
17440 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17441 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17442 }
17443 multi_buffer::Event::Reparsed(buffer_id) => {
17444 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17445 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17446
17447 cx.emit(EditorEvent::Reparsed(*buffer_id));
17448 }
17449 multi_buffer::Event::DiffHunksToggled => {
17450 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17451 }
17452 multi_buffer::Event::LanguageChanged(buffer_id) => {
17453 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17454 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17455 cx.emit(EditorEvent::Reparsed(*buffer_id));
17456 cx.notify();
17457 }
17458 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17459 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17460 multi_buffer::Event::FileHandleChanged
17461 | multi_buffer::Event::Reloaded
17462 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17463 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17464 multi_buffer::Event::DiagnosticsUpdated => {
17465 self.refresh_active_diagnostics(cx);
17466 self.refresh_inline_diagnostics(true, window, cx);
17467 self.scrollbar_marker_state.dirty = true;
17468 cx.notify();
17469 }
17470 _ => {}
17471 };
17472 }
17473
17474 fn on_display_map_changed(
17475 &mut self,
17476 _: Entity<DisplayMap>,
17477 _: &mut Window,
17478 cx: &mut Context<Self>,
17479 ) {
17480 cx.notify();
17481 }
17482
17483 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17484 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17485 self.update_edit_prediction_settings(cx);
17486 self.refresh_inline_completion(true, false, window, cx);
17487 self.refresh_inlay_hints(
17488 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17489 self.selections.newest_anchor().head(),
17490 &self.buffer.read(cx).snapshot(cx),
17491 cx,
17492 )),
17493 cx,
17494 );
17495
17496 let old_cursor_shape = self.cursor_shape;
17497
17498 {
17499 let editor_settings = EditorSettings::get_global(cx);
17500 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17501 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17502 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17503 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17504 }
17505
17506 if old_cursor_shape != self.cursor_shape {
17507 cx.emit(EditorEvent::CursorShapeChanged);
17508 }
17509
17510 let project_settings = ProjectSettings::get_global(cx);
17511 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17512
17513 if self.mode.is_full() {
17514 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17515 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17516 if self.show_inline_diagnostics != show_inline_diagnostics {
17517 self.show_inline_diagnostics = show_inline_diagnostics;
17518 self.refresh_inline_diagnostics(false, window, cx);
17519 }
17520
17521 if self.git_blame_inline_enabled != inline_blame_enabled {
17522 self.toggle_git_blame_inline_internal(false, window, cx);
17523 }
17524 }
17525
17526 cx.notify();
17527 }
17528
17529 pub fn set_searchable(&mut self, searchable: bool) {
17530 self.searchable = searchable;
17531 }
17532
17533 pub fn searchable(&self) -> bool {
17534 self.searchable
17535 }
17536
17537 fn open_proposed_changes_editor(
17538 &mut self,
17539 _: &OpenProposedChangesEditor,
17540 window: &mut Window,
17541 cx: &mut Context<Self>,
17542 ) {
17543 let Some(workspace) = self.workspace() else {
17544 cx.propagate();
17545 return;
17546 };
17547
17548 let selections = self.selections.all::<usize>(cx);
17549 let multi_buffer = self.buffer.read(cx);
17550 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17551 let mut new_selections_by_buffer = HashMap::default();
17552 for selection in selections {
17553 for (buffer, range, _) in
17554 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17555 {
17556 let mut range = range.to_point(buffer);
17557 range.start.column = 0;
17558 range.end.column = buffer.line_len(range.end.row);
17559 new_selections_by_buffer
17560 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17561 .or_insert(Vec::new())
17562 .push(range)
17563 }
17564 }
17565
17566 let proposed_changes_buffers = new_selections_by_buffer
17567 .into_iter()
17568 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17569 .collect::<Vec<_>>();
17570 let proposed_changes_editor = cx.new(|cx| {
17571 ProposedChangesEditor::new(
17572 "Proposed changes",
17573 proposed_changes_buffers,
17574 self.project.clone(),
17575 window,
17576 cx,
17577 )
17578 });
17579
17580 window.defer(cx, move |window, cx| {
17581 workspace.update(cx, |workspace, cx| {
17582 workspace.active_pane().update(cx, |pane, cx| {
17583 pane.add_item(
17584 Box::new(proposed_changes_editor),
17585 true,
17586 true,
17587 None,
17588 window,
17589 cx,
17590 );
17591 });
17592 });
17593 });
17594 }
17595
17596 pub fn open_excerpts_in_split(
17597 &mut self,
17598 _: &OpenExcerptsSplit,
17599 window: &mut Window,
17600 cx: &mut Context<Self>,
17601 ) {
17602 self.open_excerpts_common(None, true, window, cx)
17603 }
17604
17605 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17606 self.open_excerpts_common(None, false, window, cx)
17607 }
17608
17609 fn open_excerpts_common(
17610 &mut self,
17611 jump_data: Option<JumpData>,
17612 split: bool,
17613 window: &mut Window,
17614 cx: &mut Context<Self>,
17615 ) {
17616 let Some(workspace) = self.workspace() else {
17617 cx.propagate();
17618 return;
17619 };
17620
17621 if self.buffer.read(cx).is_singleton() {
17622 cx.propagate();
17623 return;
17624 }
17625
17626 let mut new_selections_by_buffer = HashMap::default();
17627 match &jump_data {
17628 Some(JumpData::MultiBufferPoint {
17629 excerpt_id,
17630 position,
17631 anchor,
17632 line_offset_from_top,
17633 }) => {
17634 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17635 if let Some(buffer) = multi_buffer_snapshot
17636 .buffer_id_for_excerpt(*excerpt_id)
17637 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17638 {
17639 let buffer_snapshot = buffer.read(cx).snapshot();
17640 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17641 language::ToPoint::to_point(anchor, &buffer_snapshot)
17642 } else {
17643 buffer_snapshot.clip_point(*position, Bias::Left)
17644 };
17645 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17646 new_selections_by_buffer.insert(
17647 buffer,
17648 (
17649 vec![jump_to_offset..jump_to_offset],
17650 Some(*line_offset_from_top),
17651 ),
17652 );
17653 }
17654 }
17655 Some(JumpData::MultiBufferRow {
17656 row,
17657 line_offset_from_top,
17658 }) => {
17659 let point = MultiBufferPoint::new(row.0, 0);
17660 if let Some((buffer, buffer_point, _)) =
17661 self.buffer.read(cx).point_to_buffer_point(point, cx)
17662 {
17663 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17664 new_selections_by_buffer
17665 .entry(buffer)
17666 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17667 .0
17668 .push(buffer_offset..buffer_offset)
17669 }
17670 }
17671 None => {
17672 let selections = self.selections.all::<usize>(cx);
17673 let multi_buffer = self.buffer.read(cx);
17674 for selection in selections {
17675 for (snapshot, range, _, anchor) in multi_buffer
17676 .snapshot(cx)
17677 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17678 {
17679 if let Some(anchor) = anchor {
17680 // selection is in a deleted hunk
17681 let Some(buffer_id) = anchor.buffer_id else {
17682 continue;
17683 };
17684 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17685 continue;
17686 };
17687 let offset = text::ToOffset::to_offset(
17688 &anchor.text_anchor,
17689 &buffer_handle.read(cx).snapshot(),
17690 );
17691 let range = offset..offset;
17692 new_selections_by_buffer
17693 .entry(buffer_handle)
17694 .or_insert((Vec::new(), None))
17695 .0
17696 .push(range)
17697 } else {
17698 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17699 else {
17700 continue;
17701 };
17702 new_selections_by_buffer
17703 .entry(buffer_handle)
17704 .or_insert((Vec::new(), None))
17705 .0
17706 .push(range)
17707 }
17708 }
17709 }
17710 }
17711 }
17712
17713 new_selections_by_buffer
17714 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17715
17716 if new_selections_by_buffer.is_empty() {
17717 return;
17718 }
17719
17720 // We defer the pane interaction because we ourselves are a workspace item
17721 // and activating a new item causes the pane to call a method on us reentrantly,
17722 // which panics if we're on the stack.
17723 window.defer(cx, move |window, cx| {
17724 workspace.update(cx, |workspace, cx| {
17725 let pane = if split {
17726 workspace.adjacent_pane(window, cx)
17727 } else {
17728 workspace.active_pane().clone()
17729 };
17730
17731 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17732 let editor = buffer
17733 .read(cx)
17734 .file()
17735 .is_none()
17736 .then(|| {
17737 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17738 // so `workspace.open_project_item` will never find them, always opening a new editor.
17739 // Instead, we try to activate the existing editor in the pane first.
17740 let (editor, pane_item_index) =
17741 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17742 let editor = item.downcast::<Editor>()?;
17743 let singleton_buffer =
17744 editor.read(cx).buffer().read(cx).as_singleton()?;
17745 if singleton_buffer == buffer {
17746 Some((editor, i))
17747 } else {
17748 None
17749 }
17750 })?;
17751 pane.update(cx, |pane, cx| {
17752 pane.activate_item(pane_item_index, true, true, window, cx)
17753 });
17754 Some(editor)
17755 })
17756 .flatten()
17757 .unwrap_or_else(|| {
17758 workspace.open_project_item::<Self>(
17759 pane.clone(),
17760 buffer,
17761 true,
17762 true,
17763 window,
17764 cx,
17765 )
17766 });
17767
17768 editor.update(cx, |editor, cx| {
17769 let autoscroll = match scroll_offset {
17770 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17771 None => Autoscroll::newest(),
17772 };
17773 let nav_history = editor.nav_history.take();
17774 editor.change_selections(Some(autoscroll), window, cx, |s| {
17775 s.select_ranges(ranges);
17776 });
17777 editor.nav_history = nav_history;
17778 });
17779 }
17780 })
17781 });
17782 }
17783
17784 // For now, don't allow opening excerpts in buffers that aren't backed by
17785 // regular project files.
17786 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17787 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17788 }
17789
17790 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17791 let snapshot = self.buffer.read(cx).read(cx);
17792 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17793 Some(
17794 ranges
17795 .iter()
17796 .map(move |range| {
17797 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17798 })
17799 .collect(),
17800 )
17801 }
17802
17803 fn selection_replacement_ranges(
17804 &self,
17805 range: Range<OffsetUtf16>,
17806 cx: &mut App,
17807 ) -> Vec<Range<OffsetUtf16>> {
17808 let selections = self.selections.all::<OffsetUtf16>(cx);
17809 let newest_selection = selections
17810 .iter()
17811 .max_by_key(|selection| selection.id)
17812 .unwrap();
17813 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17814 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17815 let snapshot = self.buffer.read(cx).read(cx);
17816 selections
17817 .into_iter()
17818 .map(|mut selection| {
17819 selection.start.0 =
17820 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17821 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17822 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17823 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17824 })
17825 .collect()
17826 }
17827
17828 fn report_editor_event(
17829 &self,
17830 event_type: &'static str,
17831 file_extension: Option<String>,
17832 cx: &App,
17833 ) {
17834 if cfg!(any(test, feature = "test-support")) {
17835 return;
17836 }
17837
17838 let Some(project) = &self.project else { return };
17839
17840 // If None, we are in a file without an extension
17841 let file = self
17842 .buffer
17843 .read(cx)
17844 .as_singleton()
17845 .and_then(|b| b.read(cx).file());
17846 let file_extension = file_extension.or(file
17847 .as_ref()
17848 .and_then(|file| Path::new(file.file_name(cx)).extension())
17849 .and_then(|e| e.to_str())
17850 .map(|a| a.to_string()));
17851
17852 let vim_mode = vim_enabled(cx);
17853
17854 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17855 let copilot_enabled = edit_predictions_provider
17856 == language::language_settings::EditPredictionProvider::Copilot;
17857 let copilot_enabled_for_language = self
17858 .buffer
17859 .read(cx)
17860 .language_settings(cx)
17861 .show_edit_predictions;
17862
17863 let project = project.read(cx);
17864 telemetry::event!(
17865 event_type,
17866 file_extension,
17867 vim_mode,
17868 copilot_enabled,
17869 copilot_enabled_for_language,
17870 edit_predictions_provider,
17871 is_via_ssh = project.is_via_ssh(),
17872 );
17873 }
17874
17875 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17876 /// with each line being an array of {text, highlight} objects.
17877 fn copy_highlight_json(
17878 &mut self,
17879 _: &CopyHighlightJson,
17880 window: &mut Window,
17881 cx: &mut Context<Self>,
17882 ) {
17883 #[derive(Serialize)]
17884 struct Chunk<'a> {
17885 text: String,
17886 highlight: Option<&'a str>,
17887 }
17888
17889 let snapshot = self.buffer.read(cx).snapshot(cx);
17890 let range = self
17891 .selected_text_range(false, window, cx)
17892 .and_then(|selection| {
17893 if selection.range.is_empty() {
17894 None
17895 } else {
17896 Some(selection.range)
17897 }
17898 })
17899 .unwrap_or_else(|| 0..snapshot.len());
17900
17901 let chunks = snapshot.chunks(range, true);
17902 let mut lines = Vec::new();
17903 let mut line: VecDeque<Chunk> = VecDeque::new();
17904
17905 let Some(style) = self.style.as_ref() else {
17906 return;
17907 };
17908
17909 for chunk in chunks {
17910 let highlight = chunk
17911 .syntax_highlight_id
17912 .and_then(|id| id.name(&style.syntax));
17913 let mut chunk_lines = chunk.text.split('\n').peekable();
17914 while let Some(text) = chunk_lines.next() {
17915 let mut merged_with_last_token = false;
17916 if let Some(last_token) = line.back_mut() {
17917 if last_token.highlight == highlight {
17918 last_token.text.push_str(text);
17919 merged_with_last_token = true;
17920 }
17921 }
17922
17923 if !merged_with_last_token {
17924 line.push_back(Chunk {
17925 text: text.into(),
17926 highlight,
17927 });
17928 }
17929
17930 if chunk_lines.peek().is_some() {
17931 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17932 line.pop_front();
17933 }
17934 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17935 line.pop_back();
17936 }
17937
17938 lines.push(mem::take(&mut line));
17939 }
17940 }
17941 }
17942
17943 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17944 return;
17945 };
17946 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17947 }
17948
17949 pub fn open_context_menu(
17950 &mut self,
17951 _: &OpenContextMenu,
17952 window: &mut Window,
17953 cx: &mut Context<Self>,
17954 ) {
17955 self.request_autoscroll(Autoscroll::newest(), cx);
17956 let position = self.selections.newest_display(cx).start;
17957 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17958 }
17959
17960 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17961 &self.inlay_hint_cache
17962 }
17963
17964 pub fn replay_insert_event(
17965 &mut self,
17966 text: &str,
17967 relative_utf16_range: Option<Range<isize>>,
17968 window: &mut Window,
17969 cx: &mut Context<Self>,
17970 ) {
17971 if !self.input_enabled {
17972 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17973 return;
17974 }
17975 if let Some(relative_utf16_range) = relative_utf16_range {
17976 let selections = self.selections.all::<OffsetUtf16>(cx);
17977 self.change_selections(None, window, cx, |s| {
17978 let new_ranges = selections.into_iter().map(|range| {
17979 let start = OffsetUtf16(
17980 range
17981 .head()
17982 .0
17983 .saturating_add_signed(relative_utf16_range.start),
17984 );
17985 let end = OffsetUtf16(
17986 range
17987 .head()
17988 .0
17989 .saturating_add_signed(relative_utf16_range.end),
17990 );
17991 start..end
17992 });
17993 s.select_ranges(new_ranges);
17994 });
17995 }
17996
17997 self.handle_input(text, window, cx);
17998 }
17999
18000 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18001 let Some(provider) = self.semantics_provider.as_ref() else {
18002 return false;
18003 };
18004
18005 let mut supports = false;
18006 self.buffer().update(cx, |this, cx| {
18007 this.for_each_buffer(|buffer| {
18008 supports |= provider.supports_inlay_hints(buffer, cx);
18009 });
18010 });
18011
18012 supports
18013 }
18014
18015 pub fn is_focused(&self, window: &Window) -> bool {
18016 self.focus_handle.is_focused(window)
18017 }
18018
18019 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18020 cx.emit(EditorEvent::Focused);
18021
18022 if let Some(descendant) = self
18023 .last_focused_descendant
18024 .take()
18025 .and_then(|descendant| descendant.upgrade())
18026 {
18027 window.focus(&descendant);
18028 } else {
18029 if let Some(blame) = self.blame.as_ref() {
18030 blame.update(cx, GitBlame::focus)
18031 }
18032
18033 self.blink_manager.update(cx, BlinkManager::enable);
18034 self.show_cursor_names(window, cx);
18035 self.buffer.update(cx, |buffer, cx| {
18036 buffer.finalize_last_transaction(cx);
18037 if self.leader_peer_id.is_none() {
18038 buffer.set_active_selections(
18039 &self.selections.disjoint_anchors(),
18040 self.selections.line_mode,
18041 self.cursor_shape,
18042 cx,
18043 );
18044 }
18045 });
18046 }
18047 }
18048
18049 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18050 cx.emit(EditorEvent::FocusedIn)
18051 }
18052
18053 fn handle_focus_out(
18054 &mut self,
18055 event: FocusOutEvent,
18056 _window: &mut Window,
18057 cx: &mut Context<Self>,
18058 ) {
18059 if event.blurred != self.focus_handle {
18060 self.last_focused_descendant = Some(event.blurred);
18061 }
18062 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18063 }
18064
18065 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18066 self.blink_manager.update(cx, BlinkManager::disable);
18067 self.buffer
18068 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18069
18070 if let Some(blame) = self.blame.as_ref() {
18071 blame.update(cx, GitBlame::blur)
18072 }
18073 if !self.hover_state.focused(window, cx) {
18074 hide_hover(self, cx);
18075 }
18076 if !self
18077 .context_menu
18078 .borrow()
18079 .as_ref()
18080 .is_some_and(|context_menu| context_menu.focused(window, cx))
18081 {
18082 self.hide_context_menu(window, cx);
18083 }
18084 self.discard_inline_completion(false, cx);
18085 cx.emit(EditorEvent::Blurred);
18086 cx.notify();
18087 }
18088
18089 pub fn register_action<A: Action>(
18090 &mut self,
18091 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18092 ) -> Subscription {
18093 let id = self.next_editor_action_id.post_inc();
18094 let listener = Arc::new(listener);
18095 self.editor_actions.borrow_mut().insert(
18096 id,
18097 Box::new(move |window, _| {
18098 let listener = listener.clone();
18099 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18100 let action = action.downcast_ref().unwrap();
18101 if phase == DispatchPhase::Bubble {
18102 listener(action, window, cx)
18103 }
18104 })
18105 }),
18106 );
18107
18108 let editor_actions = self.editor_actions.clone();
18109 Subscription::new(move || {
18110 editor_actions.borrow_mut().remove(&id);
18111 })
18112 }
18113
18114 pub fn file_header_size(&self) -> u32 {
18115 FILE_HEADER_HEIGHT
18116 }
18117
18118 pub fn restore(
18119 &mut self,
18120 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18121 window: &mut Window,
18122 cx: &mut Context<Self>,
18123 ) {
18124 let workspace = self.workspace();
18125 let project = self.project.as_ref();
18126 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18127 let mut tasks = Vec::new();
18128 for (buffer_id, changes) in revert_changes {
18129 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18130 buffer.update(cx, |buffer, cx| {
18131 buffer.edit(
18132 changes
18133 .into_iter()
18134 .map(|(range, text)| (range, text.to_string())),
18135 None,
18136 cx,
18137 );
18138 });
18139
18140 if let Some(project) =
18141 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18142 {
18143 project.update(cx, |project, cx| {
18144 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18145 })
18146 }
18147 }
18148 }
18149 tasks
18150 });
18151 cx.spawn_in(window, async move |_, cx| {
18152 for (buffer, task) in save_tasks {
18153 let result = task.await;
18154 if result.is_err() {
18155 let Some(path) = buffer
18156 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18157 .ok()
18158 else {
18159 continue;
18160 };
18161 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18162 let Some(task) = cx
18163 .update_window_entity(&workspace, |workspace, window, cx| {
18164 workspace
18165 .open_path_preview(path, None, false, false, false, window, cx)
18166 })
18167 .ok()
18168 else {
18169 continue;
18170 };
18171 task.await.log_err();
18172 }
18173 }
18174 }
18175 })
18176 .detach();
18177 self.change_selections(None, window, cx, |selections| selections.refresh());
18178 }
18179
18180 pub fn to_pixel_point(
18181 &self,
18182 source: multi_buffer::Anchor,
18183 editor_snapshot: &EditorSnapshot,
18184 window: &mut Window,
18185 ) -> Option<gpui::Point<Pixels>> {
18186 let source_point = source.to_display_point(editor_snapshot);
18187 self.display_to_pixel_point(source_point, editor_snapshot, window)
18188 }
18189
18190 pub fn display_to_pixel_point(
18191 &self,
18192 source: DisplayPoint,
18193 editor_snapshot: &EditorSnapshot,
18194 window: &mut Window,
18195 ) -> Option<gpui::Point<Pixels>> {
18196 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18197 let text_layout_details = self.text_layout_details(window);
18198 let scroll_top = text_layout_details
18199 .scroll_anchor
18200 .scroll_position(editor_snapshot)
18201 .y;
18202
18203 if source.row().as_f32() < scroll_top.floor() {
18204 return None;
18205 }
18206 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18207 let source_y = line_height * (source.row().as_f32() - scroll_top);
18208 Some(gpui::Point::new(source_x, source_y))
18209 }
18210
18211 pub fn has_visible_completions_menu(&self) -> bool {
18212 !self.edit_prediction_preview_is_active()
18213 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18214 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18215 })
18216 }
18217
18218 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18219 self.addons
18220 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18221 }
18222
18223 pub fn unregister_addon<T: Addon>(&mut self) {
18224 self.addons.remove(&std::any::TypeId::of::<T>());
18225 }
18226
18227 pub fn addon<T: Addon>(&self) -> Option<&T> {
18228 let type_id = std::any::TypeId::of::<T>();
18229 self.addons
18230 .get(&type_id)
18231 .and_then(|item| item.to_any().downcast_ref::<T>())
18232 }
18233
18234 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18235 let text_layout_details = self.text_layout_details(window);
18236 let style = &text_layout_details.editor_style;
18237 let font_id = window.text_system().resolve_font(&style.text.font());
18238 let font_size = style.text.font_size.to_pixels(window.rem_size());
18239 let line_height = style.text.line_height_in_pixels(window.rem_size());
18240 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18241
18242 gpui::Size::new(em_width, line_height)
18243 }
18244
18245 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18246 self.load_diff_task.clone()
18247 }
18248
18249 fn read_metadata_from_db(
18250 &mut self,
18251 item_id: u64,
18252 workspace_id: WorkspaceId,
18253 window: &mut Window,
18254 cx: &mut Context<Editor>,
18255 ) {
18256 if self.is_singleton(cx)
18257 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18258 {
18259 let buffer_snapshot = OnceCell::new();
18260
18261 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18262 if !folds.is_empty() {
18263 let snapshot =
18264 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18265 self.fold_ranges(
18266 folds
18267 .into_iter()
18268 .map(|(start, end)| {
18269 snapshot.clip_offset(start, Bias::Left)
18270 ..snapshot.clip_offset(end, Bias::Right)
18271 })
18272 .collect(),
18273 false,
18274 window,
18275 cx,
18276 );
18277 }
18278 }
18279
18280 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18281 if !selections.is_empty() {
18282 let snapshot =
18283 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18284 self.change_selections(None, window, cx, |s| {
18285 s.select_ranges(selections.into_iter().map(|(start, end)| {
18286 snapshot.clip_offset(start, Bias::Left)
18287 ..snapshot.clip_offset(end, Bias::Right)
18288 }));
18289 });
18290 }
18291 };
18292 }
18293
18294 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18295 }
18296}
18297
18298fn vim_enabled(cx: &App) -> bool {
18299 cx.global::<SettingsStore>()
18300 .raw_user_settings()
18301 .get("vim_mode")
18302 == Some(&serde_json::Value::Bool(true))
18303}
18304
18305// Consider user intent and default settings
18306fn choose_completion_range(
18307 completion: &Completion,
18308 intent: CompletionIntent,
18309 buffer: &Entity<Buffer>,
18310 cx: &mut Context<Editor>,
18311) -> Range<usize> {
18312 fn should_replace(
18313 completion: &Completion,
18314 insert_range: &Range<text::Anchor>,
18315 intent: CompletionIntent,
18316 completion_mode_setting: LspInsertMode,
18317 buffer: &Buffer,
18318 ) -> bool {
18319 // specific actions take precedence over settings
18320 match intent {
18321 CompletionIntent::CompleteWithInsert => return false,
18322 CompletionIntent::CompleteWithReplace => return true,
18323 CompletionIntent::Complete | CompletionIntent::Compose => {}
18324 }
18325
18326 match completion_mode_setting {
18327 LspInsertMode::Insert => false,
18328 LspInsertMode::Replace => true,
18329 LspInsertMode::ReplaceSubsequence => {
18330 let mut text_to_replace = buffer.chars_for_range(
18331 buffer.anchor_before(completion.replace_range.start)
18332 ..buffer.anchor_after(completion.replace_range.end),
18333 );
18334 let mut completion_text = completion.new_text.chars();
18335
18336 // is `text_to_replace` a subsequence of `completion_text`
18337 text_to_replace
18338 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18339 }
18340 LspInsertMode::ReplaceSuffix => {
18341 let range_after_cursor = insert_range.end..completion.replace_range.end;
18342
18343 let text_after_cursor = buffer
18344 .text_for_range(
18345 buffer.anchor_before(range_after_cursor.start)
18346 ..buffer.anchor_after(range_after_cursor.end),
18347 )
18348 .collect::<String>();
18349 completion.new_text.ends_with(&text_after_cursor)
18350 }
18351 }
18352 }
18353
18354 let buffer = buffer.read(cx);
18355
18356 if let CompletionSource::Lsp {
18357 insert_range: Some(insert_range),
18358 ..
18359 } = &completion.source
18360 {
18361 let completion_mode_setting =
18362 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18363 .completions
18364 .lsp_insert_mode;
18365
18366 if !should_replace(
18367 completion,
18368 &insert_range,
18369 intent,
18370 completion_mode_setting,
18371 buffer,
18372 ) {
18373 return insert_range.to_offset(buffer);
18374 }
18375 }
18376
18377 completion.replace_range.to_offset(buffer)
18378}
18379
18380fn insert_extra_newline_brackets(
18381 buffer: &MultiBufferSnapshot,
18382 range: Range<usize>,
18383 language: &language::LanguageScope,
18384) -> bool {
18385 let leading_whitespace_len = buffer
18386 .reversed_chars_at(range.start)
18387 .take_while(|c| c.is_whitespace() && *c != '\n')
18388 .map(|c| c.len_utf8())
18389 .sum::<usize>();
18390 let trailing_whitespace_len = buffer
18391 .chars_at(range.end)
18392 .take_while(|c| c.is_whitespace() && *c != '\n')
18393 .map(|c| c.len_utf8())
18394 .sum::<usize>();
18395 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18396
18397 language.brackets().any(|(pair, enabled)| {
18398 let pair_start = pair.start.trim_end();
18399 let pair_end = pair.end.trim_start();
18400
18401 enabled
18402 && pair.newline
18403 && buffer.contains_str_at(range.end, pair_end)
18404 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18405 })
18406}
18407
18408fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18409 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18410 [(buffer, range, _)] => (*buffer, range.clone()),
18411 _ => return false,
18412 };
18413 let pair = {
18414 let mut result: Option<BracketMatch> = None;
18415
18416 for pair in buffer
18417 .all_bracket_ranges(range.clone())
18418 .filter(move |pair| {
18419 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18420 })
18421 {
18422 let len = pair.close_range.end - pair.open_range.start;
18423
18424 if let Some(existing) = &result {
18425 let existing_len = existing.close_range.end - existing.open_range.start;
18426 if len > existing_len {
18427 continue;
18428 }
18429 }
18430
18431 result = Some(pair);
18432 }
18433
18434 result
18435 };
18436 let Some(pair) = pair else {
18437 return false;
18438 };
18439 pair.newline_only
18440 && buffer
18441 .chars_for_range(pair.open_range.end..range.start)
18442 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18443 .all(|c| c.is_whitespace() && c != '\n')
18444}
18445
18446fn get_uncommitted_diff_for_buffer(
18447 project: &Entity<Project>,
18448 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18449 buffer: Entity<MultiBuffer>,
18450 cx: &mut App,
18451) -> Task<()> {
18452 let mut tasks = Vec::new();
18453 project.update(cx, |project, cx| {
18454 for buffer in buffers {
18455 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18456 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18457 }
18458 }
18459 });
18460 cx.spawn(async move |cx| {
18461 let diffs = future::join_all(tasks).await;
18462 buffer
18463 .update(cx, |buffer, cx| {
18464 for diff in diffs.into_iter().flatten() {
18465 buffer.add_diff(diff, cx);
18466 }
18467 })
18468 .ok();
18469 })
18470}
18471
18472fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18473 let tab_size = tab_size.get() as usize;
18474 let mut width = offset;
18475
18476 for ch in text.chars() {
18477 width += if ch == '\t' {
18478 tab_size - (width % tab_size)
18479 } else {
18480 1
18481 };
18482 }
18483
18484 width - offset
18485}
18486
18487#[cfg(test)]
18488mod tests {
18489 use super::*;
18490
18491 #[test]
18492 fn test_string_size_with_expanded_tabs() {
18493 let nz = |val| NonZeroU32::new(val).unwrap();
18494 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18495 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18496 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18497 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18498 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18499 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18500 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18501 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18502 }
18503}
18504
18505/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18506struct WordBreakingTokenizer<'a> {
18507 input: &'a str,
18508}
18509
18510impl<'a> WordBreakingTokenizer<'a> {
18511 fn new(input: &'a str) -> Self {
18512 Self { input }
18513 }
18514}
18515
18516fn is_char_ideographic(ch: char) -> bool {
18517 use unicode_script::Script::*;
18518 use unicode_script::UnicodeScript;
18519 matches!(ch.script(), Han | Tangut | Yi)
18520}
18521
18522fn is_grapheme_ideographic(text: &str) -> bool {
18523 text.chars().any(is_char_ideographic)
18524}
18525
18526fn is_grapheme_whitespace(text: &str) -> bool {
18527 text.chars().any(|x| x.is_whitespace())
18528}
18529
18530fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18531 text.chars().next().map_or(false, |ch| {
18532 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18533 })
18534}
18535
18536#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18537enum WordBreakToken<'a> {
18538 Word { token: &'a str, grapheme_len: usize },
18539 InlineWhitespace { token: &'a str, grapheme_len: usize },
18540 Newline,
18541}
18542
18543impl<'a> Iterator for WordBreakingTokenizer<'a> {
18544 /// Yields a span, the count of graphemes in the token, and whether it was
18545 /// whitespace. Note that it also breaks at word boundaries.
18546 type Item = WordBreakToken<'a>;
18547
18548 fn next(&mut self) -> Option<Self::Item> {
18549 use unicode_segmentation::UnicodeSegmentation;
18550 if self.input.is_empty() {
18551 return None;
18552 }
18553
18554 let mut iter = self.input.graphemes(true).peekable();
18555 let mut offset = 0;
18556 let mut grapheme_len = 0;
18557 if let Some(first_grapheme) = iter.next() {
18558 let is_newline = first_grapheme == "\n";
18559 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18560 offset += first_grapheme.len();
18561 grapheme_len += 1;
18562 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18563 if let Some(grapheme) = iter.peek().copied() {
18564 if should_stay_with_preceding_ideograph(grapheme) {
18565 offset += grapheme.len();
18566 grapheme_len += 1;
18567 }
18568 }
18569 } else {
18570 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18571 let mut next_word_bound = words.peek().copied();
18572 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18573 next_word_bound = words.next();
18574 }
18575 while let Some(grapheme) = iter.peek().copied() {
18576 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18577 break;
18578 };
18579 if is_grapheme_whitespace(grapheme) != is_whitespace
18580 || (grapheme == "\n") != is_newline
18581 {
18582 break;
18583 };
18584 offset += grapheme.len();
18585 grapheme_len += 1;
18586 iter.next();
18587 }
18588 }
18589 let token = &self.input[..offset];
18590 self.input = &self.input[offset..];
18591 if token == "\n" {
18592 Some(WordBreakToken::Newline)
18593 } else if is_whitespace {
18594 Some(WordBreakToken::InlineWhitespace {
18595 token,
18596 grapheme_len,
18597 })
18598 } else {
18599 Some(WordBreakToken::Word {
18600 token,
18601 grapheme_len,
18602 })
18603 }
18604 } else {
18605 None
18606 }
18607 }
18608}
18609
18610#[test]
18611fn test_word_breaking_tokenizer() {
18612 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18613 ("", &[]),
18614 (" ", &[whitespace(" ", 2)]),
18615 ("Ʒ", &[word("Ʒ", 1)]),
18616 ("Ǽ", &[word("Ǽ", 1)]),
18617 ("⋑", &[word("⋑", 1)]),
18618 ("⋑⋑", &[word("⋑⋑", 2)]),
18619 (
18620 "原理,进而",
18621 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18622 ),
18623 (
18624 "hello world",
18625 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18626 ),
18627 (
18628 "hello, world",
18629 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18630 ),
18631 (
18632 " hello world",
18633 &[
18634 whitespace(" ", 2),
18635 word("hello", 5),
18636 whitespace(" ", 1),
18637 word("world", 5),
18638 ],
18639 ),
18640 (
18641 "这是什么 \n 钢笔",
18642 &[
18643 word("这", 1),
18644 word("是", 1),
18645 word("什", 1),
18646 word("么", 1),
18647 whitespace(" ", 1),
18648 newline(),
18649 whitespace(" ", 1),
18650 word("钢", 1),
18651 word("笔", 1),
18652 ],
18653 ),
18654 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18655 ];
18656
18657 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18658 WordBreakToken::Word {
18659 token,
18660 grapheme_len,
18661 }
18662 }
18663
18664 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18665 WordBreakToken::InlineWhitespace {
18666 token,
18667 grapheme_len,
18668 }
18669 }
18670
18671 fn newline() -> WordBreakToken<'static> {
18672 WordBreakToken::Newline
18673 }
18674
18675 for (input, result) in tests {
18676 assert_eq!(
18677 WordBreakingTokenizer::new(input)
18678 .collect::<Vec<_>>()
18679 .as_slice(),
18680 *result,
18681 );
18682 }
18683}
18684
18685fn wrap_with_prefix(
18686 line_prefix: String,
18687 unwrapped_text: String,
18688 wrap_column: usize,
18689 tab_size: NonZeroU32,
18690 preserve_existing_whitespace: bool,
18691) -> String {
18692 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18693 let mut wrapped_text = String::new();
18694 let mut current_line = line_prefix.clone();
18695
18696 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18697 let mut current_line_len = line_prefix_len;
18698 let mut in_whitespace = false;
18699 for token in tokenizer {
18700 let have_preceding_whitespace = in_whitespace;
18701 match token {
18702 WordBreakToken::Word {
18703 token,
18704 grapheme_len,
18705 } => {
18706 in_whitespace = false;
18707 if current_line_len + grapheme_len > wrap_column
18708 && current_line_len != line_prefix_len
18709 {
18710 wrapped_text.push_str(current_line.trim_end());
18711 wrapped_text.push('\n');
18712 current_line.truncate(line_prefix.len());
18713 current_line_len = line_prefix_len;
18714 }
18715 current_line.push_str(token);
18716 current_line_len += grapheme_len;
18717 }
18718 WordBreakToken::InlineWhitespace {
18719 mut token,
18720 mut grapheme_len,
18721 } => {
18722 in_whitespace = true;
18723 if have_preceding_whitespace && !preserve_existing_whitespace {
18724 continue;
18725 }
18726 if !preserve_existing_whitespace {
18727 token = " ";
18728 grapheme_len = 1;
18729 }
18730 if current_line_len + grapheme_len > wrap_column {
18731 wrapped_text.push_str(current_line.trim_end());
18732 wrapped_text.push('\n');
18733 current_line.truncate(line_prefix.len());
18734 current_line_len = line_prefix_len;
18735 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18736 current_line.push_str(token);
18737 current_line_len += grapheme_len;
18738 }
18739 }
18740 WordBreakToken::Newline => {
18741 in_whitespace = true;
18742 if preserve_existing_whitespace {
18743 wrapped_text.push_str(current_line.trim_end());
18744 wrapped_text.push('\n');
18745 current_line.truncate(line_prefix.len());
18746 current_line_len = line_prefix_len;
18747 } else if have_preceding_whitespace {
18748 continue;
18749 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18750 {
18751 wrapped_text.push_str(current_line.trim_end());
18752 wrapped_text.push('\n');
18753 current_line.truncate(line_prefix.len());
18754 current_line_len = line_prefix_len;
18755 } else if current_line_len != line_prefix_len {
18756 current_line.push(' ');
18757 current_line_len += 1;
18758 }
18759 }
18760 }
18761 }
18762
18763 if !current_line.is_empty() {
18764 wrapped_text.push_str(¤t_line);
18765 }
18766 wrapped_text
18767}
18768
18769#[test]
18770fn test_wrap_with_prefix() {
18771 assert_eq!(
18772 wrap_with_prefix(
18773 "# ".to_string(),
18774 "abcdefg".to_string(),
18775 4,
18776 NonZeroU32::new(4).unwrap(),
18777 false,
18778 ),
18779 "# abcdefg"
18780 );
18781 assert_eq!(
18782 wrap_with_prefix(
18783 "".to_string(),
18784 "\thello world".to_string(),
18785 8,
18786 NonZeroU32::new(4).unwrap(),
18787 false,
18788 ),
18789 "hello\nworld"
18790 );
18791 assert_eq!(
18792 wrap_with_prefix(
18793 "// ".to_string(),
18794 "xx \nyy zz aa bb cc".to_string(),
18795 12,
18796 NonZeroU32::new(4).unwrap(),
18797 false,
18798 ),
18799 "// xx yy zz\n// aa bb cc"
18800 );
18801 assert_eq!(
18802 wrap_with_prefix(
18803 String::new(),
18804 "这是什么 \n 钢笔".to_string(),
18805 3,
18806 NonZeroU32::new(4).unwrap(),
18807 false,
18808 ),
18809 "这是什\n么 钢\n笔"
18810 );
18811}
18812
18813pub trait CollaborationHub {
18814 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18815 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18816 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18817}
18818
18819impl CollaborationHub for Entity<Project> {
18820 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18821 self.read(cx).collaborators()
18822 }
18823
18824 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18825 self.read(cx).user_store().read(cx).participant_indices()
18826 }
18827
18828 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18829 let this = self.read(cx);
18830 let user_ids = this.collaborators().values().map(|c| c.user_id);
18831 this.user_store().read_with(cx, |user_store, cx| {
18832 user_store.participant_names(user_ids, cx)
18833 })
18834 }
18835}
18836
18837pub trait SemanticsProvider {
18838 fn hover(
18839 &self,
18840 buffer: &Entity<Buffer>,
18841 position: text::Anchor,
18842 cx: &mut App,
18843 ) -> Option<Task<Vec<project::Hover>>>;
18844
18845 fn inlay_hints(
18846 &self,
18847 buffer_handle: Entity<Buffer>,
18848 range: Range<text::Anchor>,
18849 cx: &mut App,
18850 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18851
18852 fn resolve_inlay_hint(
18853 &self,
18854 hint: InlayHint,
18855 buffer_handle: Entity<Buffer>,
18856 server_id: LanguageServerId,
18857 cx: &mut App,
18858 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18859
18860 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18861
18862 fn document_highlights(
18863 &self,
18864 buffer: &Entity<Buffer>,
18865 position: text::Anchor,
18866 cx: &mut App,
18867 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18868
18869 fn definitions(
18870 &self,
18871 buffer: &Entity<Buffer>,
18872 position: text::Anchor,
18873 kind: GotoDefinitionKind,
18874 cx: &mut App,
18875 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18876
18877 fn range_for_rename(
18878 &self,
18879 buffer: &Entity<Buffer>,
18880 position: text::Anchor,
18881 cx: &mut App,
18882 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18883
18884 fn perform_rename(
18885 &self,
18886 buffer: &Entity<Buffer>,
18887 position: text::Anchor,
18888 new_name: String,
18889 cx: &mut App,
18890 ) -> Option<Task<Result<ProjectTransaction>>>;
18891}
18892
18893pub trait CompletionProvider {
18894 fn completions(
18895 &self,
18896 excerpt_id: ExcerptId,
18897 buffer: &Entity<Buffer>,
18898 buffer_position: text::Anchor,
18899 trigger: CompletionContext,
18900 window: &mut Window,
18901 cx: &mut Context<Editor>,
18902 ) -> Task<Result<Option<Vec<Completion>>>>;
18903
18904 fn resolve_completions(
18905 &self,
18906 buffer: Entity<Buffer>,
18907 completion_indices: Vec<usize>,
18908 completions: Rc<RefCell<Box<[Completion]>>>,
18909 cx: &mut Context<Editor>,
18910 ) -> Task<Result<bool>>;
18911
18912 fn apply_additional_edits_for_completion(
18913 &self,
18914 _buffer: Entity<Buffer>,
18915 _completions: Rc<RefCell<Box<[Completion]>>>,
18916 _completion_index: usize,
18917 _push_to_history: bool,
18918 _cx: &mut Context<Editor>,
18919 ) -> Task<Result<Option<language::Transaction>>> {
18920 Task::ready(Ok(None))
18921 }
18922
18923 fn is_completion_trigger(
18924 &self,
18925 buffer: &Entity<Buffer>,
18926 position: language::Anchor,
18927 text: &str,
18928 trigger_in_words: bool,
18929 cx: &mut Context<Editor>,
18930 ) -> bool;
18931
18932 fn sort_completions(&self) -> bool {
18933 true
18934 }
18935
18936 fn filter_completions(&self) -> bool {
18937 true
18938 }
18939}
18940
18941pub trait CodeActionProvider {
18942 fn id(&self) -> Arc<str>;
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
18952 fn apply_code_action(
18953 &self,
18954 buffer_handle: Entity<Buffer>,
18955 action: CodeAction,
18956 excerpt_id: ExcerptId,
18957 push_to_history: bool,
18958 window: &mut Window,
18959 cx: &mut App,
18960 ) -> Task<Result<ProjectTransaction>>;
18961}
18962
18963impl CodeActionProvider for Entity<Project> {
18964 fn id(&self) -> Arc<str> {
18965 "project".into()
18966 }
18967
18968 fn code_actions(
18969 &self,
18970 buffer: &Entity<Buffer>,
18971 range: Range<text::Anchor>,
18972 _window: &mut Window,
18973 cx: &mut App,
18974 ) -> Task<Result<Vec<CodeAction>>> {
18975 self.update(cx, |project, cx| {
18976 let code_lens = project.code_lens(buffer, range.clone(), cx);
18977 let code_actions = project.code_actions(buffer, range, None, cx);
18978 cx.background_spawn(async move {
18979 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18980 Ok(code_lens
18981 .context("code lens fetch")?
18982 .into_iter()
18983 .chain(code_actions.context("code action fetch")?)
18984 .collect())
18985 })
18986 })
18987 }
18988
18989 fn apply_code_action(
18990 &self,
18991 buffer_handle: Entity<Buffer>,
18992 action: CodeAction,
18993 _excerpt_id: ExcerptId,
18994 push_to_history: bool,
18995 _window: &mut Window,
18996 cx: &mut App,
18997 ) -> Task<Result<ProjectTransaction>> {
18998 self.update(cx, |project, cx| {
18999 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19000 })
19001 }
19002}
19003
19004fn snippet_completions(
19005 project: &Project,
19006 buffer: &Entity<Buffer>,
19007 buffer_position: text::Anchor,
19008 cx: &mut App,
19009) -> Task<Result<Vec<Completion>>> {
19010 let languages = buffer.read(cx).languages_at(buffer_position);
19011 let snippet_store = project.snippets().read(cx);
19012
19013 let scopes: Vec<_> = languages
19014 .iter()
19015 .filter_map(|language| {
19016 let language_name = language.lsp_id();
19017 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19018
19019 if snippets.is_empty() {
19020 None
19021 } else {
19022 Some((language.default_scope(), snippets))
19023 }
19024 })
19025 .collect();
19026
19027 if scopes.is_empty() {
19028 return Task::ready(Ok(vec![]));
19029 }
19030
19031 let snapshot = buffer.read(cx).text_snapshot();
19032 let chars: String = snapshot
19033 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19034 .collect();
19035 let executor = cx.background_executor().clone();
19036
19037 cx.background_spawn(async move {
19038 let mut all_results: Vec<Completion> = Vec::new();
19039 for (scope, snippets) in scopes.into_iter() {
19040 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19041 let mut last_word = chars
19042 .chars()
19043 .take_while(|c| classifier.is_word(*c))
19044 .collect::<String>();
19045 last_word = last_word.chars().rev().collect();
19046
19047 if last_word.is_empty() {
19048 return Ok(vec![]);
19049 }
19050
19051 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19052 let to_lsp = |point: &text::Anchor| {
19053 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19054 point_to_lsp(end)
19055 };
19056 let lsp_end = to_lsp(&buffer_position);
19057
19058 let candidates = snippets
19059 .iter()
19060 .enumerate()
19061 .flat_map(|(ix, snippet)| {
19062 snippet
19063 .prefix
19064 .iter()
19065 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19066 })
19067 .collect::<Vec<StringMatchCandidate>>();
19068
19069 let mut matches = fuzzy::match_strings(
19070 &candidates,
19071 &last_word,
19072 last_word.chars().any(|c| c.is_uppercase()),
19073 100,
19074 &Default::default(),
19075 executor.clone(),
19076 )
19077 .await;
19078
19079 // Remove all candidates where the query's start does not match the start of any word in the candidate
19080 if let Some(query_start) = last_word.chars().next() {
19081 matches.retain(|string_match| {
19082 split_words(&string_match.string).any(|word| {
19083 // Check that the first codepoint of the word as lowercase matches the first
19084 // codepoint of the query as lowercase
19085 word.chars()
19086 .flat_map(|codepoint| codepoint.to_lowercase())
19087 .zip(query_start.to_lowercase())
19088 .all(|(word_cp, query_cp)| word_cp == query_cp)
19089 })
19090 });
19091 }
19092
19093 let matched_strings = matches
19094 .into_iter()
19095 .map(|m| m.string)
19096 .collect::<HashSet<_>>();
19097
19098 let mut result: Vec<Completion> = snippets
19099 .iter()
19100 .filter_map(|snippet| {
19101 let matching_prefix = snippet
19102 .prefix
19103 .iter()
19104 .find(|prefix| matched_strings.contains(*prefix))?;
19105 let start = as_offset - last_word.len();
19106 let start = snapshot.anchor_before(start);
19107 let range = start..buffer_position;
19108 let lsp_start = to_lsp(&start);
19109 let lsp_range = lsp::Range {
19110 start: lsp_start,
19111 end: lsp_end,
19112 };
19113 Some(Completion {
19114 replace_range: range,
19115 new_text: snippet.body.clone(),
19116 source: CompletionSource::Lsp {
19117 insert_range: None,
19118 server_id: LanguageServerId(usize::MAX),
19119 resolved: true,
19120 lsp_completion: Box::new(lsp::CompletionItem {
19121 label: snippet.prefix.first().unwrap().clone(),
19122 kind: Some(CompletionItemKind::SNIPPET),
19123 label_details: snippet.description.as_ref().map(|description| {
19124 lsp::CompletionItemLabelDetails {
19125 detail: Some(description.clone()),
19126 description: None,
19127 }
19128 }),
19129 insert_text_format: Some(InsertTextFormat::SNIPPET),
19130 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19131 lsp::InsertReplaceEdit {
19132 new_text: snippet.body.clone(),
19133 insert: lsp_range,
19134 replace: lsp_range,
19135 },
19136 )),
19137 filter_text: Some(snippet.body.clone()),
19138 sort_text: Some(char::MAX.to_string()),
19139 ..lsp::CompletionItem::default()
19140 }),
19141 lsp_defaults: None,
19142 },
19143 label: CodeLabel {
19144 text: matching_prefix.clone(),
19145 runs: Vec::new(),
19146 filter_range: 0..matching_prefix.len(),
19147 },
19148 icon_path: None,
19149 documentation: snippet.description.clone().map(|description| {
19150 CompletionDocumentation::SingleLine(description.into())
19151 }),
19152 insert_text_mode: None,
19153 confirm: None,
19154 })
19155 })
19156 .collect();
19157
19158 all_results.append(&mut result);
19159 }
19160
19161 Ok(all_results)
19162 })
19163}
19164
19165impl CompletionProvider for Entity<Project> {
19166 fn completions(
19167 &self,
19168 _excerpt_id: ExcerptId,
19169 buffer: &Entity<Buffer>,
19170 buffer_position: text::Anchor,
19171 options: CompletionContext,
19172 _window: &mut Window,
19173 cx: &mut Context<Editor>,
19174 ) -> Task<Result<Option<Vec<Completion>>>> {
19175 self.update(cx, |project, cx| {
19176 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19177 let project_completions = project.completions(buffer, buffer_position, options, cx);
19178 cx.background_spawn(async move {
19179 let snippets_completions = snippets.await?;
19180 match project_completions.await? {
19181 Some(mut completions) => {
19182 completions.extend(snippets_completions);
19183 Ok(Some(completions))
19184 }
19185 None => {
19186 if snippets_completions.is_empty() {
19187 Ok(None)
19188 } else {
19189 Ok(Some(snippets_completions))
19190 }
19191 }
19192 }
19193 })
19194 })
19195 }
19196
19197 fn resolve_completions(
19198 &self,
19199 buffer: Entity<Buffer>,
19200 completion_indices: Vec<usize>,
19201 completions: Rc<RefCell<Box<[Completion]>>>,
19202 cx: &mut Context<Editor>,
19203 ) -> Task<Result<bool>> {
19204 self.update(cx, |project, cx| {
19205 project.lsp_store().update(cx, |lsp_store, cx| {
19206 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19207 })
19208 })
19209 }
19210
19211 fn apply_additional_edits_for_completion(
19212 &self,
19213 buffer: Entity<Buffer>,
19214 completions: Rc<RefCell<Box<[Completion]>>>,
19215 completion_index: usize,
19216 push_to_history: bool,
19217 cx: &mut Context<Editor>,
19218 ) -> Task<Result<Option<language::Transaction>>> {
19219 self.update(cx, |project, cx| {
19220 project.lsp_store().update(cx, |lsp_store, cx| {
19221 lsp_store.apply_additional_edits_for_completion(
19222 buffer,
19223 completions,
19224 completion_index,
19225 push_to_history,
19226 cx,
19227 )
19228 })
19229 })
19230 }
19231
19232 fn is_completion_trigger(
19233 &self,
19234 buffer: &Entity<Buffer>,
19235 position: language::Anchor,
19236 text: &str,
19237 trigger_in_words: bool,
19238 cx: &mut Context<Editor>,
19239 ) -> bool {
19240 let mut chars = text.chars();
19241 let char = if let Some(char) = chars.next() {
19242 char
19243 } else {
19244 return false;
19245 };
19246 if chars.next().is_some() {
19247 return false;
19248 }
19249
19250 let buffer = buffer.read(cx);
19251 let snapshot = buffer.snapshot();
19252 if !snapshot.settings_at(position, cx).show_completions_on_input {
19253 return false;
19254 }
19255 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19256 if trigger_in_words && classifier.is_word(char) {
19257 return true;
19258 }
19259
19260 buffer.completion_triggers().contains(text)
19261 }
19262}
19263
19264impl SemanticsProvider for Entity<Project> {
19265 fn hover(
19266 &self,
19267 buffer: &Entity<Buffer>,
19268 position: text::Anchor,
19269 cx: &mut App,
19270 ) -> Option<Task<Vec<project::Hover>>> {
19271 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19272 }
19273
19274 fn document_highlights(
19275 &self,
19276 buffer: &Entity<Buffer>,
19277 position: text::Anchor,
19278 cx: &mut App,
19279 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19280 Some(self.update(cx, |project, cx| {
19281 project.document_highlights(buffer, position, cx)
19282 }))
19283 }
19284
19285 fn definitions(
19286 &self,
19287 buffer: &Entity<Buffer>,
19288 position: text::Anchor,
19289 kind: GotoDefinitionKind,
19290 cx: &mut App,
19291 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19292 Some(self.update(cx, |project, cx| match kind {
19293 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19294 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19295 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19296 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19297 }))
19298 }
19299
19300 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19301 // TODO: make this work for remote projects
19302 self.update(cx, |this, cx| {
19303 buffer.update(cx, |buffer, cx| {
19304 this.any_language_server_supports_inlay_hints(buffer, cx)
19305 })
19306 })
19307 }
19308
19309 fn inlay_hints(
19310 &self,
19311 buffer_handle: Entity<Buffer>,
19312 range: Range<text::Anchor>,
19313 cx: &mut App,
19314 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19315 Some(self.update(cx, |project, cx| {
19316 project.inlay_hints(buffer_handle, range, cx)
19317 }))
19318 }
19319
19320 fn resolve_inlay_hint(
19321 &self,
19322 hint: InlayHint,
19323 buffer_handle: Entity<Buffer>,
19324 server_id: LanguageServerId,
19325 cx: &mut App,
19326 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19327 Some(self.update(cx, |project, cx| {
19328 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19329 }))
19330 }
19331
19332 fn range_for_rename(
19333 &self,
19334 buffer: &Entity<Buffer>,
19335 position: text::Anchor,
19336 cx: &mut App,
19337 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19338 Some(self.update(cx, |project, cx| {
19339 let buffer = buffer.clone();
19340 let task = project.prepare_rename(buffer.clone(), position, cx);
19341 cx.spawn(async move |_, cx| {
19342 Ok(match task.await? {
19343 PrepareRenameResponse::Success(range) => Some(range),
19344 PrepareRenameResponse::InvalidPosition => None,
19345 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19346 // Fallback on using TreeSitter info to determine identifier range
19347 buffer.update(cx, |buffer, _| {
19348 let snapshot = buffer.snapshot();
19349 let (range, kind) = snapshot.surrounding_word(position);
19350 if kind != Some(CharKind::Word) {
19351 return None;
19352 }
19353 Some(
19354 snapshot.anchor_before(range.start)
19355 ..snapshot.anchor_after(range.end),
19356 )
19357 })?
19358 }
19359 })
19360 })
19361 }))
19362 }
19363
19364 fn perform_rename(
19365 &self,
19366 buffer: &Entity<Buffer>,
19367 position: text::Anchor,
19368 new_name: String,
19369 cx: &mut App,
19370 ) -> Option<Task<Result<ProjectTransaction>>> {
19371 Some(self.update(cx, |project, cx| {
19372 project.perform_rename(buffer.clone(), position, new_name, cx)
19373 }))
19374 }
19375}
19376
19377fn inlay_hint_settings(
19378 location: Anchor,
19379 snapshot: &MultiBufferSnapshot,
19380 cx: &mut Context<Editor>,
19381) -> InlayHintSettings {
19382 let file = snapshot.file_at(location);
19383 let language = snapshot.language_at(location).map(|l| l.name());
19384 language_settings(language, file, cx).inlay_hints
19385}
19386
19387fn consume_contiguous_rows(
19388 contiguous_row_selections: &mut Vec<Selection<Point>>,
19389 selection: &Selection<Point>,
19390 display_map: &DisplaySnapshot,
19391 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19392) -> (MultiBufferRow, MultiBufferRow) {
19393 contiguous_row_selections.push(selection.clone());
19394 let start_row = MultiBufferRow(selection.start.row);
19395 let mut end_row = ending_row(selection, display_map);
19396
19397 while let Some(next_selection) = selections.peek() {
19398 if next_selection.start.row <= end_row.0 {
19399 end_row = ending_row(next_selection, display_map);
19400 contiguous_row_selections.push(selections.next().unwrap().clone());
19401 } else {
19402 break;
19403 }
19404 }
19405 (start_row, end_row)
19406}
19407
19408fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19409 if next_selection.end.column > 0 || next_selection.is_empty() {
19410 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19411 } else {
19412 MultiBufferRow(next_selection.end.row)
19413 }
19414}
19415
19416impl EditorSnapshot {
19417 pub fn remote_selections_in_range<'a>(
19418 &'a self,
19419 range: &'a Range<Anchor>,
19420 collaboration_hub: &dyn CollaborationHub,
19421 cx: &'a App,
19422 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19423 let participant_names = collaboration_hub.user_names(cx);
19424 let participant_indices = collaboration_hub.user_participant_indices(cx);
19425 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19426 let collaborators_by_replica_id = collaborators_by_peer_id
19427 .iter()
19428 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19429 .collect::<HashMap<_, _>>();
19430 self.buffer_snapshot
19431 .selections_in_range(range, false)
19432 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19433 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19434 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19435 let user_name = participant_names.get(&collaborator.user_id).cloned();
19436 Some(RemoteSelection {
19437 replica_id,
19438 selection,
19439 cursor_shape,
19440 line_mode,
19441 participant_index,
19442 peer_id: collaborator.peer_id,
19443 user_name,
19444 })
19445 })
19446 }
19447
19448 pub fn hunks_for_ranges(
19449 &self,
19450 ranges: impl IntoIterator<Item = Range<Point>>,
19451 ) -> Vec<MultiBufferDiffHunk> {
19452 let mut hunks = Vec::new();
19453 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19454 HashMap::default();
19455 for query_range in ranges {
19456 let query_rows =
19457 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19458 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19459 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19460 ) {
19461 // Include deleted hunks that are adjacent to the query range, because
19462 // otherwise they would be missed.
19463 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19464 if hunk.status().is_deleted() {
19465 intersects_range |= hunk.row_range.start == query_rows.end;
19466 intersects_range |= hunk.row_range.end == query_rows.start;
19467 }
19468 if intersects_range {
19469 if !processed_buffer_rows
19470 .entry(hunk.buffer_id)
19471 .or_default()
19472 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19473 {
19474 continue;
19475 }
19476 hunks.push(hunk);
19477 }
19478 }
19479 }
19480
19481 hunks
19482 }
19483
19484 fn display_diff_hunks_for_rows<'a>(
19485 &'a self,
19486 display_rows: Range<DisplayRow>,
19487 folded_buffers: &'a HashSet<BufferId>,
19488 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19489 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19490 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19491
19492 self.buffer_snapshot
19493 .diff_hunks_in_range(buffer_start..buffer_end)
19494 .filter_map(|hunk| {
19495 if folded_buffers.contains(&hunk.buffer_id) {
19496 return None;
19497 }
19498
19499 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19500 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19501
19502 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19503 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19504
19505 let display_hunk = if hunk_display_start.column() != 0 {
19506 DisplayDiffHunk::Folded {
19507 display_row: hunk_display_start.row(),
19508 }
19509 } else {
19510 let mut end_row = hunk_display_end.row();
19511 if hunk_display_end.column() > 0 {
19512 end_row.0 += 1;
19513 }
19514 let is_created_file = hunk.is_created_file();
19515 DisplayDiffHunk::Unfolded {
19516 status: hunk.status(),
19517 diff_base_byte_range: hunk.diff_base_byte_range,
19518 display_row_range: hunk_display_start.row()..end_row,
19519 multi_buffer_range: Anchor::range_in_buffer(
19520 hunk.excerpt_id,
19521 hunk.buffer_id,
19522 hunk.buffer_range,
19523 ),
19524 is_created_file,
19525 }
19526 };
19527
19528 Some(display_hunk)
19529 })
19530 }
19531
19532 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19533 self.display_snapshot.buffer_snapshot.language_at(position)
19534 }
19535
19536 pub fn is_focused(&self) -> bool {
19537 self.is_focused
19538 }
19539
19540 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19541 self.placeholder_text.as_ref()
19542 }
19543
19544 pub fn scroll_position(&self) -> gpui::Point<f32> {
19545 self.scroll_anchor.scroll_position(&self.display_snapshot)
19546 }
19547
19548 fn gutter_dimensions(
19549 &self,
19550 font_id: FontId,
19551 font_size: Pixels,
19552 max_line_number_width: Pixels,
19553 cx: &App,
19554 ) -> Option<GutterDimensions> {
19555 if !self.show_gutter {
19556 return None;
19557 }
19558
19559 let descent = cx.text_system().descent(font_id, font_size);
19560 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19561 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19562
19563 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19564 matches!(
19565 ProjectSettings::get_global(cx).git.git_gutter,
19566 Some(GitGutterSetting::TrackedFiles)
19567 )
19568 });
19569 let gutter_settings = EditorSettings::get_global(cx).gutter;
19570 let show_line_numbers = self
19571 .show_line_numbers
19572 .unwrap_or(gutter_settings.line_numbers);
19573 let line_gutter_width = if show_line_numbers {
19574 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19575 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19576 max_line_number_width.max(min_width_for_number_on_gutter)
19577 } else {
19578 0.0.into()
19579 };
19580
19581 let show_code_actions = self
19582 .show_code_actions
19583 .unwrap_or(gutter_settings.code_actions);
19584
19585 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19586 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19587
19588 let git_blame_entries_width =
19589 self.git_blame_gutter_max_author_length
19590 .map(|max_author_length| {
19591 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19592 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19593
19594 /// The number of characters to dedicate to gaps and margins.
19595 const SPACING_WIDTH: usize = 4;
19596
19597 let max_char_count = max_author_length.min(renderer.max_author_length())
19598 + ::git::SHORT_SHA_LENGTH
19599 + MAX_RELATIVE_TIMESTAMP.len()
19600 + SPACING_WIDTH;
19601
19602 em_advance * max_char_count
19603 });
19604
19605 let is_singleton = self.buffer_snapshot.is_singleton();
19606
19607 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19608 left_padding += if !is_singleton {
19609 em_width * 4.0
19610 } else if show_code_actions || show_runnables || show_breakpoints {
19611 em_width * 3.0
19612 } else if show_git_gutter && show_line_numbers {
19613 em_width * 2.0
19614 } else if show_git_gutter || show_line_numbers {
19615 em_width
19616 } else {
19617 px(0.)
19618 };
19619
19620 let shows_folds = is_singleton && gutter_settings.folds;
19621
19622 let right_padding = if shows_folds && show_line_numbers {
19623 em_width * 4.0
19624 } else if shows_folds || (!is_singleton && show_line_numbers) {
19625 em_width * 3.0
19626 } else if show_line_numbers {
19627 em_width
19628 } else {
19629 px(0.)
19630 };
19631
19632 Some(GutterDimensions {
19633 left_padding,
19634 right_padding,
19635 width: line_gutter_width + left_padding + right_padding,
19636 margin: -descent,
19637 git_blame_entries_width,
19638 })
19639 }
19640
19641 pub fn render_crease_toggle(
19642 &self,
19643 buffer_row: MultiBufferRow,
19644 row_contains_cursor: bool,
19645 editor: Entity<Editor>,
19646 window: &mut Window,
19647 cx: &mut App,
19648 ) -> Option<AnyElement> {
19649 let folded = self.is_line_folded(buffer_row);
19650 let mut is_foldable = false;
19651
19652 if let Some(crease) = self
19653 .crease_snapshot
19654 .query_row(buffer_row, &self.buffer_snapshot)
19655 {
19656 is_foldable = true;
19657 match crease {
19658 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19659 if let Some(render_toggle) = render_toggle {
19660 let toggle_callback =
19661 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19662 if folded {
19663 editor.update(cx, |editor, cx| {
19664 editor.fold_at(buffer_row, window, cx)
19665 });
19666 } else {
19667 editor.update(cx, |editor, cx| {
19668 editor.unfold_at(buffer_row, window, cx)
19669 });
19670 }
19671 });
19672 return Some((render_toggle)(
19673 buffer_row,
19674 folded,
19675 toggle_callback,
19676 window,
19677 cx,
19678 ));
19679 }
19680 }
19681 }
19682 }
19683
19684 is_foldable |= self.starts_indent(buffer_row);
19685
19686 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19687 Some(
19688 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19689 .toggle_state(folded)
19690 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19691 if folded {
19692 this.unfold_at(buffer_row, window, cx);
19693 } else {
19694 this.fold_at(buffer_row, window, cx);
19695 }
19696 }))
19697 .into_any_element(),
19698 )
19699 } else {
19700 None
19701 }
19702 }
19703
19704 pub fn render_crease_trailer(
19705 &self,
19706 buffer_row: MultiBufferRow,
19707 window: &mut Window,
19708 cx: &mut App,
19709 ) -> Option<AnyElement> {
19710 let folded = self.is_line_folded(buffer_row);
19711 if let Crease::Inline { render_trailer, .. } = self
19712 .crease_snapshot
19713 .query_row(buffer_row, &self.buffer_snapshot)?
19714 {
19715 let render_trailer = render_trailer.as_ref()?;
19716 Some(render_trailer(buffer_row, folded, window, cx))
19717 } else {
19718 None
19719 }
19720 }
19721}
19722
19723impl Deref for EditorSnapshot {
19724 type Target = DisplaySnapshot;
19725
19726 fn deref(&self) -> &Self::Target {
19727 &self.display_snapshot
19728 }
19729}
19730
19731#[derive(Clone, Debug, PartialEq, Eq)]
19732pub enum EditorEvent {
19733 InputIgnored {
19734 text: Arc<str>,
19735 },
19736 InputHandled {
19737 utf16_range_to_replace: Option<Range<isize>>,
19738 text: Arc<str>,
19739 },
19740 ExcerptsAdded {
19741 buffer: Entity<Buffer>,
19742 predecessor: ExcerptId,
19743 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19744 },
19745 ExcerptsRemoved {
19746 ids: Vec<ExcerptId>,
19747 },
19748 BufferFoldToggled {
19749 ids: Vec<ExcerptId>,
19750 folded: bool,
19751 },
19752 ExcerptsEdited {
19753 ids: Vec<ExcerptId>,
19754 },
19755 ExcerptsExpanded {
19756 ids: Vec<ExcerptId>,
19757 },
19758 BufferEdited,
19759 Edited {
19760 transaction_id: clock::Lamport,
19761 },
19762 Reparsed(BufferId),
19763 Focused,
19764 FocusedIn,
19765 Blurred,
19766 DirtyChanged,
19767 Saved,
19768 TitleChanged,
19769 DiffBaseChanged,
19770 SelectionsChanged {
19771 local: bool,
19772 },
19773 ScrollPositionChanged {
19774 local: bool,
19775 autoscroll: bool,
19776 },
19777 Closed,
19778 TransactionUndone {
19779 transaction_id: clock::Lamport,
19780 },
19781 TransactionBegun {
19782 transaction_id: clock::Lamport,
19783 },
19784 Reloaded,
19785 CursorShapeChanged,
19786 PushedToNavHistory {
19787 anchor: Anchor,
19788 is_deactivate: bool,
19789 },
19790}
19791
19792impl EventEmitter<EditorEvent> for Editor {}
19793
19794impl Focusable for Editor {
19795 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19796 self.focus_handle.clone()
19797 }
19798}
19799
19800impl Render for Editor {
19801 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19802 let settings = ThemeSettings::get_global(cx);
19803
19804 let mut text_style = match self.mode {
19805 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19806 color: cx.theme().colors().editor_foreground,
19807 font_family: settings.ui_font.family.clone(),
19808 font_features: settings.ui_font.features.clone(),
19809 font_fallbacks: settings.ui_font.fallbacks.clone(),
19810 font_size: rems(0.875).into(),
19811 font_weight: settings.ui_font.weight,
19812 line_height: relative(settings.buffer_line_height.value()),
19813 ..Default::default()
19814 },
19815 EditorMode::Full { .. } => TextStyle {
19816 color: cx.theme().colors().editor_foreground,
19817 font_family: settings.buffer_font.family.clone(),
19818 font_features: settings.buffer_font.features.clone(),
19819 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19820 font_size: settings.buffer_font_size(cx).into(),
19821 font_weight: settings.buffer_font.weight,
19822 line_height: relative(settings.buffer_line_height.value()),
19823 ..Default::default()
19824 },
19825 };
19826 if let Some(text_style_refinement) = &self.text_style_refinement {
19827 text_style.refine(text_style_refinement)
19828 }
19829
19830 let background = match self.mode {
19831 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19832 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19833 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19834 };
19835
19836 EditorElement::new(
19837 &cx.entity(),
19838 EditorStyle {
19839 background,
19840 local_player: cx.theme().players().local(),
19841 text: text_style,
19842 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19843 syntax: cx.theme().syntax().clone(),
19844 status: cx.theme().status().clone(),
19845 inlay_hints_style: make_inlay_hints_style(cx),
19846 inline_completion_styles: make_suggestion_styles(cx),
19847 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19848 },
19849 )
19850 }
19851}
19852
19853impl EntityInputHandler for Editor {
19854 fn text_for_range(
19855 &mut self,
19856 range_utf16: Range<usize>,
19857 adjusted_range: &mut Option<Range<usize>>,
19858 _: &mut Window,
19859 cx: &mut Context<Self>,
19860 ) -> Option<String> {
19861 let snapshot = self.buffer.read(cx).read(cx);
19862 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19863 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19864 if (start.0..end.0) != range_utf16 {
19865 adjusted_range.replace(start.0..end.0);
19866 }
19867 Some(snapshot.text_for_range(start..end).collect())
19868 }
19869
19870 fn selected_text_range(
19871 &mut self,
19872 ignore_disabled_input: bool,
19873 _: &mut Window,
19874 cx: &mut Context<Self>,
19875 ) -> Option<UTF16Selection> {
19876 // Prevent the IME menu from appearing when holding down an alphabetic key
19877 // while input is disabled.
19878 if !ignore_disabled_input && !self.input_enabled {
19879 return None;
19880 }
19881
19882 let selection = self.selections.newest::<OffsetUtf16>(cx);
19883 let range = selection.range();
19884
19885 Some(UTF16Selection {
19886 range: range.start.0..range.end.0,
19887 reversed: selection.reversed,
19888 })
19889 }
19890
19891 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19892 let snapshot = self.buffer.read(cx).read(cx);
19893 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19894 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19895 }
19896
19897 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19898 self.clear_highlights::<InputComposition>(cx);
19899 self.ime_transaction.take();
19900 }
19901
19902 fn replace_text_in_range(
19903 &mut self,
19904 range_utf16: Option<Range<usize>>,
19905 text: &str,
19906 window: &mut Window,
19907 cx: &mut Context<Self>,
19908 ) {
19909 if !self.input_enabled {
19910 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19911 return;
19912 }
19913
19914 self.transact(window, cx, |this, window, cx| {
19915 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19916 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19917 Some(this.selection_replacement_ranges(range_utf16, cx))
19918 } else {
19919 this.marked_text_ranges(cx)
19920 };
19921
19922 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19923 let newest_selection_id = this.selections.newest_anchor().id;
19924 this.selections
19925 .all::<OffsetUtf16>(cx)
19926 .iter()
19927 .zip(ranges_to_replace.iter())
19928 .find_map(|(selection, range)| {
19929 if selection.id == newest_selection_id {
19930 Some(
19931 (range.start.0 as isize - selection.head().0 as isize)
19932 ..(range.end.0 as isize - selection.head().0 as isize),
19933 )
19934 } else {
19935 None
19936 }
19937 })
19938 });
19939
19940 cx.emit(EditorEvent::InputHandled {
19941 utf16_range_to_replace: range_to_replace,
19942 text: text.into(),
19943 });
19944
19945 if let Some(new_selected_ranges) = new_selected_ranges {
19946 this.change_selections(None, window, cx, |selections| {
19947 selections.select_ranges(new_selected_ranges)
19948 });
19949 this.backspace(&Default::default(), window, cx);
19950 }
19951
19952 this.handle_input(text, window, cx);
19953 });
19954
19955 if let Some(transaction) = self.ime_transaction {
19956 self.buffer.update(cx, |buffer, cx| {
19957 buffer.group_until_transaction(transaction, cx);
19958 });
19959 }
19960
19961 self.unmark_text(window, cx);
19962 }
19963
19964 fn replace_and_mark_text_in_range(
19965 &mut self,
19966 range_utf16: Option<Range<usize>>,
19967 text: &str,
19968 new_selected_range_utf16: Option<Range<usize>>,
19969 window: &mut Window,
19970 cx: &mut Context<Self>,
19971 ) {
19972 if !self.input_enabled {
19973 return;
19974 }
19975
19976 let transaction = self.transact(window, cx, |this, window, cx| {
19977 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19978 let snapshot = this.buffer.read(cx).read(cx);
19979 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19980 for marked_range in &mut marked_ranges {
19981 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19982 marked_range.start.0 += relative_range_utf16.start;
19983 marked_range.start =
19984 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19985 marked_range.end =
19986 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19987 }
19988 }
19989 Some(marked_ranges)
19990 } else if let Some(range_utf16) = range_utf16 {
19991 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19992 Some(this.selection_replacement_ranges(range_utf16, cx))
19993 } else {
19994 None
19995 };
19996
19997 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19998 let newest_selection_id = this.selections.newest_anchor().id;
19999 this.selections
20000 .all::<OffsetUtf16>(cx)
20001 .iter()
20002 .zip(ranges_to_replace.iter())
20003 .find_map(|(selection, range)| {
20004 if selection.id == newest_selection_id {
20005 Some(
20006 (range.start.0 as isize - selection.head().0 as isize)
20007 ..(range.end.0 as isize - selection.head().0 as isize),
20008 )
20009 } else {
20010 None
20011 }
20012 })
20013 });
20014
20015 cx.emit(EditorEvent::InputHandled {
20016 utf16_range_to_replace: range_to_replace,
20017 text: text.into(),
20018 });
20019
20020 if let Some(ranges) = ranges_to_replace {
20021 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20022 }
20023
20024 let marked_ranges = {
20025 let snapshot = this.buffer.read(cx).read(cx);
20026 this.selections
20027 .disjoint_anchors()
20028 .iter()
20029 .map(|selection| {
20030 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20031 })
20032 .collect::<Vec<_>>()
20033 };
20034
20035 if text.is_empty() {
20036 this.unmark_text(window, cx);
20037 } else {
20038 this.highlight_text::<InputComposition>(
20039 marked_ranges.clone(),
20040 HighlightStyle {
20041 underline: Some(UnderlineStyle {
20042 thickness: px(1.),
20043 color: None,
20044 wavy: false,
20045 }),
20046 ..Default::default()
20047 },
20048 cx,
20049 );
20050 }
20051
20052 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20053 let use_autoclose = this.use_autoclose;
20054 let use_auto_surround = this.use_auto_surround;
20055 this.set_use_autoclose(false);
20056 this.set_use_auto_surround(false);
20057 this.handle_input(text, window, cx);
20058 this.set_use_autoclose(use_autoclose);
20059 this.set_use_auto_surround(use_auto_surround);
20060
20061 if let Some(new_selected_range) = new_selected_range_utf16 {
20062 let snapshot = this.buffer.read(cx).read(cx);
20063 let new_selected_ranges = marked_ranges
20064 .into_iter()
20065 .map(|marked_range| {
20066 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20067 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20068 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20069 snapshot.clip_offset_utf16(new_start, Bias::Left)
20070 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20071 })
20072 .collect::<Vec<_>>();
20073
20074 drop(snapshot);
20075 this.change_selections(None, window, cx, |selections| {
20076 selections.select_ranges(new_selected_ranges)
20077 });
20078 }
20079 });
20080
20081 self.ime_transaction = self.ime_transaction.or(transaction);
20082 if let Some(transaction) = self.ime_transaction {
20083 self.buffer.update(cx, |buffer, cx| {
20084 buffer.group_until_transaction(transaction, cx);
20085 });
20086 }
20087
20088 if self.text_highlights::<InputComposition>(cx).is_none() {
20089 self.ime_transaction.take();
20090 }
20091 }
20092
20093 fn bounds_for_range(
20094 &mut self,
20095 range_utf16: Range<usize>,
20096 element_bounds: gpui::Bounds<Pixels>,
20097 window: &mut Window,
20098 cx: &mut Context<Self>,
20099 ) -> Option<gpui::Bounds<Pixels>> {
20100 let text_layout_details = self.text_layout_details(window);
20101 let gpui::Size {
20102 width: em_width,
20103 height: line_height,
20104 } = self.character_size(window);
20105
20106 let snapshot = self.snapshot(window, cx);
20107 let scroll_position = snapshot.scroll_position();
20108 let scroll_left = scroll_position.x * em_width;
20109
20110 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20111 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20112 + self.gutter_dimensions.width
20113 + self.gutter_dimensions.margin;
20114 let y = line_height * (start.row().as_f32() - scroll_position.y);
20115
20116 Some(Bounds {
20117 origin: element_bounds.origin + point(x, y),
20118 size: size(em_width, line_height),
20119 })
20120 }
20121
20122 fn character_index_for_point(
20123 &mut self,
20124 point: gpui::Point<Pixels>,
20125 _window: &mut Window,
20126 _cx: &mut Context<Self>,
20127 ) -> Option<usize> {
20128 let position_map = self.last_position_map.as_ref()?;
20129 if !position_map.text_hitbox.contains(&point) {
20130 return None;
20131 }
20132 let display_point = position_map.point_for_position(point).previous_valid;
20133 let anchor = position_map
20134 .snapshot
20135 .display_point_to_anchor(display_point, Bias::Left);
20136 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20137 Some(utf16_offset.0)
20138 }
20139}
20140
20141trait SelectionExt {
20142 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20143 fn spanned_rows(
20144 &self,
20145 include_end_if_at_line_start: bool,
20146 map: &DisplaySnapshot,
20147 ) -> Range<MultiBufferRow>;
20148}
20149
20150impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20151 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20152 let start = self
20153 .start
20154 .to_point(&map.buffer_snapshot)
20155 .to_display_point(map);
20156 let end = self
20157 .end
20158 .to_point(&map.buffer_snapshot)
20159 .to_display_point(map);
20160 if self.reversed {
20161 end..start
20162 } else {
20163 start..end
20164 }
20165 }
20166
20167 fn spanned_rows(
20168 &self,
20169 include_end_if_at_line_start: bool,
20170 map: &DisplaySnapshot,
20171 ) -> Range<MultiBufferRow> {
20172 let start = self.start.to_point(&map.buffer_snapshot);
20173 let mut end = self.end.to_point(&map.buffer_snapshot);
20174 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20175 end.row -= 1;
20176 }
20177
20178 let buffer_start = map.prev_line_boundary(start).0;
20179 let buffer_end = map.next_line_boundary(end).0;
20180 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20181 }
20182}
20183
20184impl<T: InvalidationRegion> InvalidationStack<T> {
20185 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20186 where
20187 S: Clone + ToOffset,
20188 {
20189 while let Some(region) = self.last() {
20190 let all_selections_inside_invalidation_ranges =
20191 if selections.len() == region.ranges().len() {
20192 selections
20193 .iter()
20194 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20195 .all(|(selection, invalidation_range)| {
20196 let head = selection.head().to_offset(buffer);
20197 invalidation_range.start <= head && invalidation_range.end >= head
20198 })
20199 } else {
20200 false
20201 };
20202
20203 if all_selections_inside_invalidation_ranges {
20204 break;
20205 } else {
20206 self.pop();
20207 }
20208 }
20209 }
20210}
20211
20212impl<T> Default for InvalidationStack<T> {
20213 fn default() -> Self {
20214 Self(Default::default())
20215 }
20216}
20217
20218impl<T> Deref for InvalidationStack<T> {
20219 type Target = Vec<T>;
20220
20221 fn deref(&self) -> &Self::Target {
20222 &self.0
20223 }
20224}
20225
20226impl<T> DerefMut for InvalidationStack<T> {
20227 fn deref_mut(&mut self) -> &mut Self::Target {
20228 &mut self.0
20229 }
20230}
20231
20232impl InvalidationRegion for SnippetState {
20233 fn ranges(&self) -> &[Range<Anchor>] {
20234 &self.ranges[self.active_index]
20235 }
20236}
20237
20238fn inline_completion_edit_text(
20239 current_snapshot: &BufferSnapshot,
20240 edits: &[(Range<Anchor>, String)],
20241 edit_preview: &EditPreview,
20242 include_deletions: bool,
20243 cx: &App,
20244) -> HighlightedText {
20245 let edits = edits
20246 .iter()
20247 .map(|(anchor, text)| {
20248 (
20249 anchor.start.text_anchor..anchor.end.text_anchor,
20250 text.clone(),
20251 )
20252 })
20253 .collect::<Vec<_>>();
20254
20255 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20256}
20257
20258pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20259 match severity {
20260 DiagnosticSeverity::ERROR => colors.error,
20261 DiagnosticSeverity::WARNING => colors.warning,
20262 DiagnosticSeverity::INFORMATION => colors.info,
20263 DiagnosticSeverity::HINT => colors.info,
20264 _ => colors.ignored,
20265 }
20266}
20267
20268pub fn styled_runs_for_code_label<'a>(
20269 label: &'a CodeLabel,
20270 syntax_theme: &'a theme::SyntaxTheme,
20271) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20272 let fade_out = HighlightStyle {
20273 fade_out: Some(0.35),
20274 ..Default::default()
20275 };
20276
20277 let mut prev_end = label.filter_range.end;
20278 label
20279 .runs
20280 .iter()
20281 .enumerate()
20282 .flat_map(move |(ix, (range, highlight_id))| {
20283 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20284 style
20285 } else {
20286 return Default::default();
20287 };
20288 let mut muted_style = style;
20289 muted_style.highlight(fade_out);
20290
20291 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20292 if range.start >= label.filter_range.end {
20293 if range.start > prev_end {
20294 runs.push((prev_end..range.start, fade_out));
20295 }
20296 runs.push((range.clone(), muted_style));
20297 } else if range.end <= label.filter_range.end {
20298 runs.push((range.clone(), style));
20299 } else {
20300 runs.push((range.start..label.filter_range.end, style));
20301 runs.push((label.filter_range.end..range.end, muted_style));
20302 }
20303 prev_end = cmp::max(prev_end, range.end);
20304
20305 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20306 runs.push((prev_end..label.text.len(), fade_out));
20307 }
20308
20309 runs
20310 })
20311}
20312
20313pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20314 let mut prev_index = 0;
20315 let mut prev_codepoint: Option<char> = None;
20316 text.char_indices()
20317 .chain([(text.len(), '\0')])
20318 .filter_map(move |(index, codepoint)| {
20319 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20320 let is_boundary = index == text.len()
20321 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20322 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20323 if is_boundary {
20324 let chunk = &text[prev_index..index];
20325 prev_index = index;
20326 Some(chunk)
20327 } else {
20328 None
20329 }
20330 })
20331}
20332
20333pub trait RangeToAnchorExt: Sized {
20334 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20335
20336 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20337 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20338 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20339 }
20340}
20341
20342impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20343 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20344 let start_offset = self.start.to_offset(snapshot);
20345 let end_offset = self.end.to_offset(snapshot);
20346 if start_offset == end_offset {
20347 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20348 } else {
20349 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20350 }
20351 }
20352}
20353
20354pub trait RowExt {
20355 fn as_f32(&self) -> f32;
20356
20357 fn next_row(&self) -> Self;
20358
20359 fn previous_row(&self) -> Self;
20360
20361 fn minus(&self, other: Self) -> u32;
20362}
20363
20364impl RowExt for DisplayRow {
20365 fn as_f32(&self) -> f32 {
20366 self.0 as f32
20367 }
20368
20369 fn next_row(&self) -> Self {
20370 Self(self.0 + 1)
20371 }
20372
20373 fn previous_row(&self) -> Self {
20374 Self(self.0.saturating_sub(1))
20375 }
20376
20377 fn minus(&self, other: Self) -> u32 {
20378 self.0 - other.0
20379 }
20380}
20381
20382impl RowExt for MultiBufferRow {
20383 fn as_f32(&self) -> f32 {
20384 self.0 as f32
20385 }
20386
20387 fn next_row(&self) -> Self {
20388 Self(self.0 + 1)
20389 }
20390
20391 fn previous_row(&self) -> Self {
20392 Self(self.0.saturating_sub(1))
20393 }
20394
20395 fn minus(&self, other: Self) -> u32 {
20396 self.0 - other.0
20397 }
20398}
20399
20400trait RowRangeExt {
20401 type Row;
20402
20403 fn len(&self) -> usize;
20404
20405 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20406}
20407
20408impl RowRangeExt for Range<MultiBufferRow> {
20409 type Row = MultiBufferRow;
20410
20411 fn len(&self) -> usize {
20412 (self.end.0 - self.start.0) as usize
20413 }
20414
20415 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20416 (self.start.0..self.end.0).map(MultiBufferRow)
20417 }
20418}
20419
20420impl RowRangeExt for Range<DisplayRow> {
20421 type Row = DisplayRow;
20422
20423 fn len(&self) -> usize {
20424 (self.end.0 - self.start.0) as usize
20425 }
20426
20427 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20428 (self.start.0..self.end.0).map(DisplayRow)
20429 }
20430}
20431
20432/// If select range has more than one line, we
20433/// just point the cursor to range.start.
20434fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20435 if range.start.row == range.end.row {
20436 range
20437 } else {
20438 range.start..range.start
20439 }
20440}
20441pub struct KillRing(ClipboardItem);
20442impl Global for KillRing {}
20443
20444const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20445
20446enum BreakpointPromptEditAction {
20447 Log,
20448 Condition,
20449 HitCondition,
20450}
20451
20452struct BreakpointPromptEditor {
20453 pub(crate) prompt: Entity<Editor>,
20454 editor: WeakEntity<Editor>,
20455 breakpoint_anchor: Anchor,
20456 breakpoint: Breakpoint,
20457 edit_action: BreakpointPromptEditAction,
20458 block_ids: HashSet<CustomBlockId>,
20459 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20460 _subscriptions: Vec<Subscription>,
20461}
20462
20463impl BreakpointPromptEditor {
20464 const MAX_LINES: u8 = 4;
20465
20466 fn new(
20467 editor: WeakEntity<Editor>,
20468 breakpoint_anchor: Anchor,
20469 breakpoint: Breakpoint,
20470 edit_action: BreakpointPromptEditAction,
20471 window: &mut Window,
20472 cx: &mut Context<Self>,
20473 ) -> Self {
20474 let base_text = match edit_action {
20475 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20476 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20477 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20478 }
20479 .map(|msg| msg.to_string())
20480 .unwrap_or_default();
20481
20482 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20483 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20484
20485 let prompt = cx.new(|cx| {
20486 let mut prompt = Editor::new(
20487 EditorMode::AutoHeight {
20488 max_lines: Self::MAX_LINES as usize,
20489 },
20490 buffer,
20491 None,
20492 window,
20493 cx,
20494 );
20495 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20496 prompt.set_show_cursor_when_unfocused(false, cx);
20497 prompt.set_placeholder_text(
20498 match edit_action {
20499 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20500 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20501 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20502 },
20503 cx,
20504 );
20505
20506 prompt
20507 });
20508
20509 Self {
20510 prompt,
20511 editor,
20512 breakpoint_anchor,
20513 breakpoint,
20514 edit_action,
20515 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20516 block_ids: Default::default(),
20517 _subscriptions: vec![],
20518 }
20519 }
20520
20521 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20522 self.block_ids.extend(block_ids)
20523 }
20524
20525 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20526 if let Some(editor) = self.editor.upgrade() {
20527 let message = self
20528 .prompt
20529 .read(cx)
20530 .buffer
20531 .read(cx)
20532 .as_singleton()
20533 .expect("A multi buffer in breakpoint prompt isn't possible")
20534 .read(cx)
20535 .as_rope()
20536 .to_string();
20537
20538 editor.update(cx, |editor, cx| {
20539 editor.edit_breakpoint_at_anchor(
20540 self.breakpoint_anchor,
20541 self.breakpoint.clone(),
20542 match self.edit_action {
20543 BreakpointPromptEditAction::Log => {
20544 BreakpointEditAction::EditLogMessage(message.into())
20545 }
20546 BreakpointPromptEditAction::Condition => {
20547 BreakpointEditAction::EditCondition(message.into())
20548 }
20549 BreakpointPromptEditAction::HitCondition => {
20550 BreakpointEditAction::EditHitCondition(message.into())
20551 }
20552 },
20553 cx,
20554 );
20555
20556 editor.remove_blocks(self.block_ids.clone(), None, cx);
20557 cx.focus_self(window);
20558 });
20559 }
20560 }
20561
20562 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20563 self.editor
20564 .update(cx, |editor, cx| {
20565 editor.remove_blocks(self.block_ids.clone(), None, cx);
20566 window.focus(&editor.focus_handle);
20567 })
20568 .log_err();
20569 }
20570
20571 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20572 let settings = ThemeSettings::get_global(cx);
20573 let text_style = TextStyle {
20574 color: if self.prompt.read(cx).read_only(cx) {
20575 cx.theme().colors().text_disabled
20576 } else {
20577 cx.theme().colors().text
20578 },
20579 font_family: settings.buffer_font.family.clone(),
20580 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20581 font_size: settings.buffer_font_size(cx).into(),
20582 font_weight: settings.buffer_font.weight,
20583 line_height: relative(settings.buffer_line_height.value()),
20584 ..Default::default()
20585 };
20586 EditorElement::new(
20587 &self.prompt,
20588 EditorStyle {
20589 background: cx.theme().colors().editor_background,
20590 local_player: cx.theme().players().local(),
20591 text: text_style,
20592 ..Default::default()
20593 },
20594 )
20595 }
20596}
20597
20598impl Render for BreakpointPromptEditor {
20599 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20600 let gutter_dimensions = *self.gutter_dimensions.lock();
20601 h_flex()
20602 .key_context("Editor")
20603 .bg(cx.theme().colors().editor_background)
20604 .border_y_1()
20605 .border_color(cx.theme().status().info_border)
20606 .size_full()
20607 .py(window.line_height() / 2.5)
20608 .on_action(cx.listener(Self::confirm))
20609 .on_action(cx.listener(Self::cancel))
20610 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20611 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20612 }
20613}
20614
20615impl Focusable for BreakpointPromptEditor {
20616 fn focus_handle(&self, cx: &App) -> FocusHandle {
20617 self.prompt.focus_handle(cx)
20618 }
20619}
20620
20621fn all_edits_insertions_or_deletions(
20622 edits: &Vec<(Range<Anchor>, String)>,
20623 snapshot: &MultiBufferSnapshot,
20624) -> bool {
20625 let mut all_insertions = true;
20626 let mut all_deletions = true;
20627
20628 for (range, new_text) in edits.iter() {
20629 let range_is_empty = range.to_offset(&snapshot).is_empty();
20630 let text_is_empty = new_text.is_empty();
20631
20632 if range_is_empty != text_is_empty {
20633 if range_is_empty {
20634 all_deletions = false;
20635 } else {
20636 all_insertions = false;
20637 }
20638 } else {
20639 return false;
20640 }
20641
20642 if !all_insertions && !all_deletions {
20643 return false;
20644 }
20645 }
20646 all_insertions || all_deletions
20647}
20648
20649struct MissingEditPredictionKeybindingTooltip;
20650
20651impl Render for MissingEditPredictionKeybindingTooltip {
20652 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20653 ui::tooltip_container(window, cx, |container, _, cx| {
20654 container
20655 .flex_shrink_0()
20656 .max_w_80()
20657 .min_h(rems_from_px(124.))
20658 .justify_between()
20659 .child(
20660 v_flex()
20661 .flex_1()
20662 .text_ui_sm(cx)
20663 .child(Label::new("Conflict with Accept Keybinding"))
20664 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20665 )
20666 .child(
20667 h_flex()
20668 .pb_1()
20669 .gap_1()
20670 .items_end()
20671 .w_full()
20672 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20673 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20674 }))
20675 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20676 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20677 })),
20678 )
20679 })
20680 }
20681}
20682
20683#[derive(Debug, Clone, Copy, PartialEq)]
20684pub struct LineHighlight {
20685 pub background: Background,
20686 pub border: Option<gpui::Hsla>,
20687}
20688
20689impl From<Hsla> for LineHighlight {
20690 fn from(hsla: Hsla) -> Self {
20691 Self {
20692 background: hsla.into(),
20693 border: None,
20694 }
20695 }
20696}
20697
20698impl From<Background> for LineHighlight {
20699 fn from(background: Background) -> Self {
20700 Self {
20701 background,
20702 border: None,
20703 }
20704 }
20705}
20706
20707fn render_diff_hunk_controls(
20708 row: u32,
20709 status: &DiffHunkStatus,
20710 hunk_range: Range<Anchor>,
20711 is_created_file: bool,
20712 line_height: Pixels,
20713 editor: &Entity<Editor>,
20714 _window: &mut Window,
20715 cx: &mut App,
20716) -> AnyElement {
20717 h_flex()
20718 .h(line_height)
20719 .mr_1()
20720 .gap_1()
20721 .px_0p5()
20722 .pb_1()
20723 .border_x_1()
20724 .border_b_1()
20725 .border_color(cx.theme().colors().border_variant)
20726 .rounded_b_lg()
20727 .bg(cx.theme().colors().editor_background)
20728 .gap_1()
20729 .occlude()
20730 .shadow_md()
20731 .child(if status.has_secondary_hunk() {
20732 Button::new(("stage", row as u64), "Stage")
20733 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20734 .tooltip({
20735 let focus_handle = editor.focus_handle(cx);
20736 move |window, cx| {
20737 Tooltip::for_action_in(
20738 "Stage Hunk",
20739 &::git::ToggleStaged,
20740 &focus_handle,
20741 window,
20742 cx,
20743 )
20744 }
20745 })
20746 .on_click({
20747 let editor = editor.clone();
20748 move |_event, _window, cx| {
20749 editor.update(cx, |editor, cx| {
20750 editor.stage_or_unstage_diff_hunks(
20751 true,
20752 vec![hunk_range.start..hunk_range.start],
20753 cx,
20754 );
20755 });
20756 }
20757 })
20758 } else {
20759 Button::new(("unstage", row as u64), "Unstage")
20760 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20761 .tooltip({
20762 let focus_handle = editor.focus_handle(cx);
20763 move |window, cx| {
20764 Tooltip::for_action_in(
20765 "Unstage Hunk",
20766 &::git::ToggleStaged,
20767 &focus_handle,
20768 window,
20769 cx,
20770 )
20771 }
20772 })
20773 .on_click({
20774 let editor = editor.clone();
20775 move |_event, _window, cx| {
20776 editor.update(cx, |editor, cx| {
20777 editor.stage_or_unstage_diff_hunks(
20778 false,
20779 vec![hunk_range.start..hunk_range.start],
20780 cx,
20781 );
20782 });
20783 }
20784 })
20785 })
20786 .child(
20787 Button::new(("restore", row as u64), "Restore")
20788 .tooltip({
20789 let focus_handle = editor.focus_handle(cx);
20790 move |window, cx| {
20791 Tooltip::for_action_in(
20792 "Restore Hunk",
20793 &::git::Restore,
20794 &focus_handle,
20795 window,
20796 cx,
20797 )
20798 }
20799 })
20800 .on_click({
20801 let editor = editor.clone();
20802 move |_event, window, cx| {
20803 editor.update(cx, |editor, cx| {
20804 let snapshot = editor.snapshot(window, cx);
20805 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20806 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20807 });
20808 }
20809 })
20810 .disabled(is_created_file),
20811 )
20812 .when(
20813 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20814 |el| {
20815 el.child(
20816 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20817 .shape(IconButtonShape::Square)
20818 .icon_size(IconSize::Small)
20819 // .disabled(!has_multiple_hunks)
20820 .tooltip({
20821 let focus_handle = editor.focus_handle(cx);
20822 move |window, cx| {
20823 Tooltip::for_action_in(
20824 "Next Hunk",
20825 &GoToHunk,
20826 &focus_handle,
20827 window,
20828 cx,
20829 )
20830 }
20831 })
20832 .on_click({
20833 let editor = editor.clone();
20834 move |_event, window, cx| {
20835 editor.update(cx, |editor, cx| {
20836 let snapshot = editor.snapshot(window, cx);
20837 let position =
20838 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20839 editor.go_to_hunk_before_or_after_position(
20840 &snapshot,
20841 position,
20842 Direction::Next,
20843 window,
20844 cx,
20845 );
20846 editor.expand_selected_diff_hunks(cx);
20847 });
20848 }
20849 }),
20850 )
20851 .child(
20852 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20853 .shape(IconButtonShape::Square)
20854 .icon_size(IconSize::Small)
20855 // .disabled(!has_multiple_hunks)
20856 .tooltip({
20857 let focus_handle = editor.focus_handle(cx);
20858 move |window, cx| {
20859 Tooltip::for_action_in(
20860 "Previous Hunk",
20861 &GoToPreviousHunk,
20862 &focus_handle,
20863 window,
20864 cx,
20865 )
20866 }
20867 })
20868 .on_click({
20869 let editor = editor.clone();
20870 move |_event, window, cx| {
20871 editor.update(cx, |editor, cx| {
20872 let snapshot = editor.snapshot(window, cx);
20873 let point =
20874 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20875 editor.go_to_hunk_before_or_after_position(
20876 &snapshot,
20877 point,
20878 Direction::Prev,
20879 window,
20880 cx,
20881 );
20882 editor.expand_selected_diff_hunks(cx);
20883 });
20884 }
20885 }),
20886 )
20887 },
20888 )
20889 .into_any_element()
20890}