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 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1727 }
1728 }
1729 EditorEvent::Edited { .. } => {
1730 if !vim_enabled(cx) {
1731 let (map, selections) = editor.selections.all_adjusted_display(cx);
1732 let pop_state = editor
1733 .change_list
1734 .last()
1735 .map(|previous| {
1736 previous.len() == selections.len()
1737 && previous.iter().enumerate().all(|(ix, p)| {
1738 p.to_display_point(&map).row()
1739 == selections[ix].head().row()
1740 })
1741 })
1742 .unwrap_or(false);
1743 let new_positions = selections
1744 .into_iter()
1745 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1746 .collect();
1747 editor
1748 .change_list
1749 .push_to_change_list(pop_state, new_positions);
1750 }
1751 }
1752 _ => (),
1753 },
1754 ));
1755
1756 this.end_selection(window, cx);
1757 this.scroll_manager.show_scrollbars(window, cx);
1758 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1759
1760 if mode.is_full() {
1761 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1762 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1763
1764 if this.git_blame_inline_enabled {
1765 this.git_blame_inline_enabled = true;
1766 this.start_git_blame_inline(false, window, cx);
1767 }
1768
1769 this.go_to_active_debug_line(window, cx);
1770
1771 if let Some(buffer) = buffer.read(cx).as_singleton() {
1772 if let Some(project) = this.project.as_ref() {
1773 let handle = project.update(cx, |project, cx| {
1774 project.register_buffer_with_language_servers(&buffer, cx)
1775 });
1776 this.registered_buffers
1777 .insert(buffer.read(cx).remote_id(), handle);
1778 }
1779 }
1780 }
1781
1782 this.report_editor_event("Editor Opened", None, cx);
1783 this
1784 }
1785
1786 pub fn deploy_mouse_context_menu(
1787 &mut self,
1788 position: gpui::Point<Pixels>,
1789 context_menu: Entity<ContextMenu>,
1790 window: &mut Window,
1791 cx: &mut Context<Self>,
1792 ) {
1793 self.mouse_context_menu = Some(MouseContextMenu::new(
1794 self,
1795 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1796 context_menu,
1797 window,
1798 cx,
1799 ));
1800 }
1801
1802 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1803 self.mouse_context_menu
1804 .as_ref()
1805 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1806 }
1807
1808 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1809 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1810 }
1811
1812 fn key_context_internal(
1813 &self,
1814 has_active_edit_prediction: bool,
1815 window: &Window,
1816 cx: &App,
1817 ) -> KeyContext {
1818 let mut key_context = KeyContext::new_with_defaults();
1819 key_context.add("Editor");
1820 let mode = match self.mode {
1821 EditorMode::SingleLine { .. } => "single_line",
1822 EditorMode::AutoHeight { .. } => "auto_height",
1823 EditorMode::Full { .. } => "full",
1824 };
1825
1826 if EditorSettings::jupyter_enabled(cx) {
1827 key_context.add("jupyter");
1828 }
1829
1830 key_context.set("mode", mode);
1831 if self.pending_rename.is_some() {
1832 key_context.add("renaming");
1833 }
1834
1835 match self.context_menu.borrow().as_ref() {
1836 Some(CodeContextMenu::Completions(_)) => {
1837 key_context.add("menu");
1838 key_context.add("showing_completions");
1839 }
1840 Some(CodeContextMenu::CodeActions(_)) => {
1841 key_context.add("menu");
1842 key_context.add("showing_code_actions")
1843 }
1844 None => {}
1845 }
1846
1847 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1848 if !self.focus_handle(cx).contains_focused(window, cx)
1849 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1850 {
1851 for addon in self.addons.values() {
1852 addon.extend_key_context(&mut key_context, cx)
1853 }
1854 }
1855
1856 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1857 if let Some(extension) = singleton_buffer
1858 .read(cx)
1859 .file()
1860 .and_then(|file| file.path().extension()?.to_str())
1861 {
1862 key_context.set("extension", extension.to_string());
1863 }
1864 } else {
1865 key_context.add("multibuffer");
1866 }
1867
1868 if has_active_edit_prediction {
1869 if self.edit_prediction_in_conflict() {
1870 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1871 } else {
1872 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1873 key_context.add("copilot_suggestion");
1874 }
1875 }
1876
1877 if self.selection_mark_mode {
1878 key_context.add("selection_mode");
1879 }
1880
1881 key_context
1882 }
1883
1884 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1885 self.mouse_cursor_hidden = match origin {
1886 HideMouseCursorOrigin::TypingAction => {
1887 matches!(
1888 self.hide_mouse_mode,
1889 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1890 )
1891 }
1892 HideMouseCursorOrigin::MovementAction => {
1893 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1894 }
1895 };
1896 }
1897
1898 pub fn edit_prediction_in_conflict(&self) -> bool {
1899 if !self.show_edit_predictions_in_menu() {
1900 return false;
1901 }
1902
1903 let showing_completions = self
1904 .context_menu
1905 .borrow()
1906 .as_ref()
1907 .map_or(false, |context| {
1908 matches!(context, CodeContextMenu::Completions(_))
1909 });
1910
1911 showing_completions
1912 || self.edit_prediction_requires_modifier()
1913 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1914 // bindings to insert tab characters.
1915 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1916 }
1917
1918 pub fn accept_edit_prediction_keybind(
1919 &self,
1920 window: &Window,
1921 cx: &App,
1922 ) -> AcceptEditPredictionBinding {
1923 let key_context = self.key_context_internal(true, window, cx);
1924 let in_conflict = self.edit_prediction_in_conflict();
1925
1926 AcceptEditPredictionBinding(
1927 window
1928 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1929 .into_iter()
1930 .filter(|binding| {
1931 !in_conflict
1932 || binding
1933 .keystrokes()
1934 .first()
1935 .map_or(false, |keystroke| keystroke.modifiers.modified())
1936 })
1937 .rev()
1938 .min_by_key(|binding| {
1939 binding
1940 .keystrokes()
1941 .first()
1942 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1943 }),
1944 )
1945 }
1946
1947 pub fn new_file(
1948 workspace: &mut Workspace,
1949 _: &workspace::NewFile,
1950 window: &mut Window,
1951 cx: &mut Context<Workspace>,
1952 ) {
1953 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1954 "Failed to create buffer",
1955 window,
1956 cx,
1957 |e, _, _| match e.error_code() {
1958 ErrorCode::RemoteUpgradeRequired => Some(format!(
1959 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1960 e.error_tag("required").unwrap_or("the latest version")
1961 )),
1962 _ => None,
1963 },
1964 );
1965 }
1966
1967 pub fn new_in_workspace(
1968 workspace: &mut Workspace,
1969 window: &mut Window,
1970 cx: &mut Context<Workspace>,
1971 ) -> Task<Result<Entity<Editor>>> {
1972 let project = workspace.project().clone();
1973 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1974
1975 cx.spawn_in(window, async move |workspace, cx| {
1976 let buffer = create.await?;
1977 workspace.update_in(cx, |workspace, window, cx| {
1978 let editor =
1979 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1980 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1981 editor
1982 })
1983 })
1984 }
1985
1986 fn new_file_vertical(
1987 workspace: &mut Workspace,
1988 _: &workspace::NewFileSplitVertical,
1989 window: &mut Window,
1990 cx: &mut Context<Workspace>,
1991 ) {
1992 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1993 }
1994
1995 fn new_file_horizontal(
1996 workspace: &mut Workspace,
1997 _: &workspace::NewFileSplitHorizontal,
1998 window: &mut Window,
1999 cx: &mut Context<Workspace>,
2000 ) {
2001 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2002 }
2003
2004 fn new_file_in_direction(
2005 workspace: &mut Workspace,
2006 direction: SplitDirection,
2007 window: &mut Window,
2008 cx: &mut Context<Workspace>,
2009 ) {
2010 let project = workspace.project().clone();
2011 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2012
2013 cx.spawn_in(window, async move |workspace, cx| {
2014 let buffer = create.await?;
2015 workspace.update_in(cx, move |workspace, window, cx| {
2016 workspace.split_item(
2017 direction,
2018 Box::new(
2019 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2020 ),
2021 window,
2022 cx,
2023 )
2024 })?;
2025 anyhow::Ok(())
2026 })
2027 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2028 match e.error_code() {
2029 ErrorCode::RemoteUpgradeRequired => Some(format!(
2030 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2031 e.error_tag("required").unwrap_or("the latest version")
2032 )),
2033 _ => None,
2034 }
2035 });
2036 }
2037
2038 pub fn leader_peer_id(&self) -> Option<PeerId> {
2039 self.leader_peer_id
2040 }
2041
2042 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2043 &self.buffer
2044 }
2045
2046 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2047 self.workspace.as_ref()?.0.upgrade()
2048 }
2049
2050 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2051 self.buffer().read(cx).title(cx)
2052 }
2053
2054 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2055 let git_blame_gutter_max_author_length = self
2056 .render_git_blame_gutter(cx)
2057 .then(|| {
2058 if let Some(blame) = self.blame.as_ref() {
2059 let max_author_length =
2060 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2061 Some(max_author_length)
2062 } else {
2063 None
2064 }
2065 })
2066 .flatten();
2067
2068 EditorSnapshot {
2069 mode: self.mode,
2070 show_gutter: self.show_gutter,
2071 show_line_numbers: self.show_line_numbers,
2072 show_git_diff_gutter: self.show_git_diff_gutter,
2073 show_code_actions: self.show_code_actions,
2074 show_runnables: self.show_runnables,
2075 show_breakpoints: self.show_breakpoints,
2076 git_blame_gutter_max_author_length,
2077 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2078 scroll_anchor: self.scroll_manager.anchor(),
2079 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2080 placeholder_text: self.placeholder_text.clone(),
2081 is_focused: self.focus_handle.is_focused(window),
2082 current_line_highlight: self
2083 .current_line_highlight
2084 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2085 gutter_hovered: self.gutter_hovered,
2086 }
2087 }
2088
2089 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2090 self.buffer.read(cx).language_at(point, cx)
2091 }
2092
2093 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2094 self.buffer.read(cx).read(cx).file_at(point).cloned()
2095 }
2096
2097 pub fn active_excerpt(
2098 &self,
2099 cx: &App,
2100 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2101 self.buffer
2102 .read(cx)
2103 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2104 }
2105
2106 pub fn mode(&self) -> EditorMode {
2107 self.mode
2108 }
2109
2110 pub fn set_mode(&mut self, mode: EditorMode) {
2111 self.mode = mode;
2112 }
2113
2114 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2115 self.collaboration_hub.as_deref()
2116 }
2117
2118 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2119 self.collaboration_hub = Some(hub);
2120 }
2121
2122 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2123 self.in_project_search = in_project_search;
2124 }
2125
2126 pub fn set_custom_context_menu(
2127 &mut self,
2128 f: impl 'static
2129 + Fn(
2130 &mut Self,
2131 DisplayPoint,
2132 &mut Window,
2133 &mut Context<Self>,
2134 ) -> Option<Entity<ui::ContextMenu>>,
2135 ) {
2136 self.custom_context_menu = Some(Box::new(f))
2137 }
2138
2139 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2140 self.completion_provider = provider;
2141 }
2142
2143 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2144 self.semantics_provider.clone()
2145 }
2146
2147 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2148 self.semantics_provider = provider;
2149 }
2150
2151 pub fn set_edit_prediction_provider<T>(
2152 &mut self,
2153 provider: Option<Entity<T>>,
2154 window: &mut Window,
2155 cx: &mut Context<Self>,
2156 ) where
2157 T: EditPredictionProvider,
2158 {
2159 self.edit_prediction_provider =
2160 provider.map(|provider| RegisteredInlineCompletionProvider {
2161 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2162 if this.focus_handle.is_focused(window) {
2163 this.update_visible_inline_completion(window, cx);
2164 }
2165 }),
2166 provider: Arc::new(provider),
2167 });
2168 self.update_edit_prediction_settings(cx);
2169 self.refresh_inline_completion(false, false, window, cx);
2170 }
2171
2172 pub fn placeholder_text(&self) -> Option<&str> {
2173 self.placeholder_text.as_deref()
2174 }
2175
2176 pub fn set_placeholder_text(
2177 &mut self,
2178 placeholder_text: impl Into<Arc<str>>,
2179 cx: &mut Context<Self>,
2180 ) {
2181 let placeholder_text = Some(placeholder_text.into());
2182 if self.placeholder_text != placeholder_text {
2183 self.placeholder_text = placeholder_text;
2184 cx.notify();
2185 }
2186 }
2187
2188 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2189 self.cursor_shape = cursor_shape;
2190
2191 // Disrupt blink for immediate user feedback that the cursor shape has changed
2192 self.blink_manager.update(cx, BlinkManager::show_cursor);
2193
2194 cx.notify();
2195 }
2196
2197 pub fn set_current_line_highlight(
2198 &mut self,
2199 current_line_highlight: Option<CurrentLineHighlight>,
2200 ) {
2201 self.current_line_highlight = current_line_highlight;
2202 }
2203
2204 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2205 self.collapse_matches = collapse_matches;
2206 }
2207
2208 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2209 let buffers = self.buffer.read(cx).all_buffers();
2210 let Some(project) = self.project.as_ref() else {
2211 return;
2212 };
2213 project.update(cx, |project, cx| {
2214 for buffer in buffers {
2215 self.registered_buffers
2216 .entry(buffer.read(cx).remote_id())
2217 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2218 }
2219 })
2220 }
2221
2222 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2223 if self.collapse_matches {
2224 return range.start..range.start;
2225 }
2226 range.clone()
2227 }
2228
2229 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2230 if self.display_map.read(cx).clip_at_line_ends != clip {
2231 self.display_map
2232 .update(cx, |map, _| map.clip_at_line_ends = clip);
2233 }
2234 }
2235
2236 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2237 self.input_enabled = input_enabled;
2238 }
2239
2240 pub fn set_inline_completions_hidden_for_vim_mode(
2241 &mut self,
2242 hidden: bool,
2243 window: &mut Window,
2244 cx: &mut Context<Self>,
2245 ) {
2246 if hidden != self.inline_completions_hidden_for_vim_mode {
2247 self.inline_completions_hidden_for_vim_mode = hidden;
2248 if hidden {
2249 self.update_visible_inline_completion(window, cx);
2250 } else {
2251 self.refresh_inline_completion(true, false, window, cx);
2252 }
2253 }
2254 }
2255
2256 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2257 self.menu_inline_completions_policy = value;
2258 }
2259
2260 pub fn set_autoindent(&mut self, autoindent: bool) {
2261 if autoindent {
2262 self.autoindent_mode = Some(AutoindentMode::EachLine);
2263 } else {
2264 self.autoindent_mode = None;
2265 }
2266 }
2267
2268 pub fn read_only(&self, cx: &App) -> bool {
2269 self.read_only || self.buffer.read(cx).read_only()
2270 }
2271
2272 pub fn set_read_only(&mut self, read_only: bool) {
2273 self.read_only = read_only;
2274 }
2275
2276 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2277 self.use_autoclose = autoclose;
2278 }
2279
2280 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2281 self.use_auto_surround = auto_surround;
2282 }
2283
2284 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2285 self.auto_replace_emoji_shortcode = auto_replace;
2286 }
2287
2288 pub fn toggle_edit_predictions(
2289 &mut self,
2290 _: &ToggleEditPrediction,
2291 window: &mut Window,
2292 cx: &mut Context<Self>,
2293 ) {
2294 if self.show_inline_completions_override.is_some() {
2295 self.set_show_edit_predictions(None, window, cx);
2296 } else {
2297 let show_edit_predictions = !self.edit_predictions_enabled();
2298 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2299 }
2300 }
2301
2302 pub fn set_show_edit_predictions(
2303 &mut self,
2304 show_edit_predictions: Option<bool>,
2305 window: &mut Window,
2306 cx: &mut Context<Self>,
2307 ) {
2308 self.show_inline_completions_override = show_edit_predictions;
2309 self.update_edit_prediction_settings(cx);
2310
2311 if let Some(false) = show_edit_predictions {
2312 self.discard_inline_completion(false, cx);
2313 } else {
2314 self.refresh_inline_completion(false, true, window, cx);
2315 }
2316 }
2317
2318 fn inline_completions_disabled_in_scope(
2319 &self,
2320 buffer: &Entity<Buffer>,
2321 buffer_position: language::Anchor,
2322 cx: &App,
2323 ) -> bool {
2324 let snapshot = buffer.read(cx).snapshot();
2325 let settings = snapshot.settings_at(buffer_position, cx);
2326
2327 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2328 return false;
2329 };
2330
2331 scope.override_name().map_or(false, |scope_name| {
2332 settings
2333 .edit_predictions_disabled_in
2334 .iter()
2335 .any(|s| s == scope_name)
2336 })
2337 }
2338
2339 pub fn set_use_modal_editing(&mut self, to: bool) {
2340 self.use_modal_editing = to;
2341 }
2342
2343 pub fn use_modal_editing(&self) -> bool {
2344 self.use_modal_editing
2345 }
2346
2347 fn selections_did_change(
2348 &mut self,
2349 local: bool,
2350 old_cursor_position: &Anchor,
2351 show_completions: bool,
2352 window: &mut Window,
2353 cx: &mut Context<Self>,
2354 ) {
2355 window.invalidate_character_coordinates();
2356
2357 // Copy selections to primary selection buffer
2358 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2359 if local {
2360 let selections = self.selections.all::<usize>(cx);
2361 let buffer_handle = self.buffer.read(cx).read(cx);
2362
2363 let mut text = String::new();
2364 for (index, selection) in selections.iter().enumerate() {
2365 let text_for_selection = buffer_handle
2366 .text_for_range(selection.start..selection.end)
2367 .collect::<String>();
2368
2369 text.push_str(&text_for_selection);
2370 if index != selections.len() - 1 {
2371 text.push('\n');
2372 }
2373 }
2374
2375 if !text.is_empty() {
2376 cx.write_to_primary(ClipboardItem::new_string(text));
2377 }
2378 }
2379
2380 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2381 self.buffer.update(cx, |buffer, cx| {
2382 buffer.set_active_selections(
2383 &self.selections.disjoint_anchors(),
2384 self.selections.line_mode,
2385 self.cursor_shape,
2386 cx,
2387 )
2388 });
2389 }
2390 let display_map = self
2391 .display_map
2392 .update(cx, |display_map, cx| display_map.snapshot(cx));
2393 let buffer = &display_map.buffer_snapshot;
2394 self.add_selections_state = None;
2395 self.select_next_state = None;
2396 self.select_prev_state = None;
2397 self.select_syntax_node_history.try_clear();
2398 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2399 self.snippet_stack
2400 .invalidate(&self.selections.disjoint_anchors(), buffer);
2401 self.take_rename(false, window, cx);
2402
2403 let new_cursor_position = self.selections.newest_anchor().head();
2404
2405 self.push_to_nav_history(
2406 *old_cursor_position,
2407 Some(new_cursor_position.to_point(buffer)),
2408 false,
2409 cx,
2410 );
2411
2412 if local {
2413 let new_cursor_position = self.selections.newest_anchor().head();
2414 let mut context_menu = self.context_menu.borrow_mut();
2415 let completion_menu = match context_menu.as_ref() {
2416 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2417 _ => {
2418 *context_menu = None;
2419 None
2420 }
2421 };
2422 if let Some(buffer_id) = new_cursor_position.buffer_id {
2423 if !self.registered_buffers.contains_key(&buffer_id) {
2424 if let Some(project) = self.project.as_ref() {
2425 project.update(cx, |project, cx| {
2426 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2427 return;
2428 };
2429 self.registered_buffers.insert(
2430 buffer_id,
2431 project.register_buffer_with_language_servers(&buffer, cx),
2432 );
2433 })
2434 }
2435 }
2436 }
2437
2438 if let Some(completion_menu) = completion_menu {
2439 let cursor_position = new_cursor_position.to_offset(buffer);
2440 let (word_range, kind) =
2441 buffer.surrounding_word(completion_menu.initial_position, true);
2442 if kind == Some(CharKind::Word)
2443 && word_range.to_inclusive().contains(&cursor_position)
2444 {
2445 let mut completion_menu = completion_menu.clone();
2446 drop(context_menu);
2447
2448 let query = Self::completion_query(buffer, cursor_position);
2449 cx.spawn(async move |this, cx| {
2450 completion_menu
2451 .filter(query.as_deref(), cx.background_executor().clone())
2452 .await;
2453
2454 this.update(cx, |this, cx| {
2455 let mut context_menu = this.context_menu.borrow_mut();
2456 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2457 else {
2458 return;
2459 };
2460
2461 if menu.id > completion_menu.id {
2462 return;
2463 }
2464
2465 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2466 drop(context_menu);
2467 cx.notify();
2468 })
2469 })
2470 .detach();
2471
2472 if show_completions {
2473 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2474 }
2475 } else {
2476 drop(context_menu);
2477 self.hide_context_menu(window, cx);
2478 }
2479 } else {
2480 drop(context_menu);
2481 }
2482
2483 hide_hover(self, cx);
2484
2485 if old_cursor_position.to_display_point(&display_map).row()
2486 != new_cursor_position.to_display_point(&display_map).row()
2487 {
2488 self.available_code_actions.take();
2489 }
2490 self.refresh_code_actions(window, cx);
2491 self.refresh_document_highlights(cx);
2492 self.refresh_selected_text_highlights(window, cx);
2493 refresh_matching_bracket_highlights(self, window, cx);
2494 self.update_visible_inline_completion(window, cx);
2495 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2496 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2497 if self.git_blame_inline_enabled {
2498 self.start_inline_blame_timer(window, cx);
2499 }
2500 }
2501
2502 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2503 cx.emit(EditorEvent::SelectionsChanged { local });
2504
2505 let selections = &self.selections.disjoint;
2506 if selections.len() == 1 {
2507 cx.emit(SearchEvent::ActiveMatchChanged)
2508 }
2509 if local {
2510 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2511 let inmemory_selections = selections
2512 .iter()
2513 .map(|s| {
2514 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2515 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2516 })
2517 .collect();
2518 self.update_restoration_data(cx, |data| {
2519 data.selections = inmemory_selections;
2520 });
2521
2522 if WorkspaceSettings::get(None, cx).restore_on_startup
2523 != RestoreOnStartupBehavior::None
2524 {
2525 if let Some(workspace_id) =
2526 self.workspace.as_ref().and_then(|workspace| workspace.1)
2527 {
2528 let snapshot = self.buffer().read(cx).snapshot(cx);
2529 let selections = selections.clone();
2530 let background_executor = cx.background_executor().clone();
2531 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2532 self.serialize_selections = cx.background_spawn(async move {
2533 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2534 let db_selections = selections
2535 .iter()
2536 .map(|selection| {
2537 (
2538 selection.start.to_offset(&snapshot),
2539 selection.end.to_offset(&snapshot),
2540 )
2541 })
2542 .collect();
2543
2544 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2545 .await
2546 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2547 .log_err();
2548 });
2549 }
2550 }
2551 }
2552 }
2553
2554 cx.notify();
2555 }
2556
2557 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2558 use text::ToOffset as _;
2559 use text::ToPoint as _;
2560
2561 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2562 return;
2563 }
2564
2565 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2566 return;
2567 };
2568
2569 let snapshot = singleton.read(cx).snapshot();
2570 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2571 let display_snapshot = display_map.snapshot(cx);
2572
2573 display_snapshot
2574 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2575 .map(|fold| {
2576 fold.range.start.text_anchor.to_point(&snapshot)
2577 ..fold.range.end.text_anchor.to_point(&snapshot)
2578 })
2579 .collect()
2580 });
2581 self.update_restoration_data(cx, |data| {
2582 data.folds = inmemory_folds;
2583 });
2584
2585 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2586 return;
2587 };
2588 let background_executor = cx.background_executor().clone();
2589 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2590 let db_folds = self.display_map.update(cx, |display_map, cx| {
2591 display_map
2592 .snapshot(cx)
2593 .folds_in_range(0..snapshot.len())
2594 .map(|fold| {
2595 (
2596 fold.range.start.text_anchor.to_offset(&snapshot),
2597 fold.range.end.text_anchor.to_offset(&snapshot),
2598 )
2599 })
2600 .collect()
2601 });
2602 self.serialize_folds = cx.background_spawn(async move {
2603 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2604 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2605 .await
2606 .with_context(|| {
2607 format!(
2608 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2609 )
2610 })
2611 .log_err();
2612 });
2613 }
2614
2615 pub fn sync_selections(
2616 &mut self,
2617 other: Entity<Editor>,
2618 cx: &mut Context<Self>,
2619 ) -> gpui::Subscription {
2620 let other_selections = other.read(cx).selections.disjoint.to_vec();
2621 self.selections.change_with(cx, |selections| {
2622 selections.select_anchors(other_selections);
2623 });
2624
2625 let other_subscription =
2626 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2627 EditorEvent::SelectionsChanged { local: true } => {
2628 let other_selections = other.read(cx).selections.disjoint.to_vec();
2629 if other_selections.is_empty() {
2630 return;
2631 }
2632 this.selections.change_with(cx, |selections| {
2633 selections.select_anchors(other_selections);
2634 });
2635 }
2636 _ => {}
2637 });
2638
2639 let this_subscription =
2640 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2641 EditorEvent::SelectionsChanged { local: true } => {
2642 let these_selections = this.selections.disjoint.to_vec();
2643 if these_selections.is_empty() {
2644 return;
2645 }
2646 other.update(cx, |other_editor, cx| {
2647 other_editor.selections.change_with(cx, |selections| {
2648 selections.select_anchors(these_selections);
2649 })
2650 });
2651 }
2652 _ => {}
2653 });
2654
2655 Subscription::join(other_subscription, this_subscription)
2656 }
2657
2658 pub fn change_selections<R>(
2659 &mut self,
2660 autoscroll: Option<Autoscroll>,
2661 window: &mut Window,
2662 cx: &mut Context<Self>,
2663 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2664 ) -> R {
2665 self.change_selections_inner(autoscroll, true, window, cx, change)
2666 }
2667
2668 fn change_selections_inner<R>(
2669 &mut self,
2670 autoscroll: Option<Autoscroll>,
2671 request_completions: bool,
2672 window: &mut Window,
2673 cx: &mut Context<Self>,
2674 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2675 ) -> R {
2676 let old_cursor_position = self.selections.newest_anchor().head();
2677 self.push_to_selection_history();
2678
2679 let (changed, result) = self.selections.change_with(cx, change);
2680
2681 if changed {
2682 if let Some(autoscroll) = autoscroll {
2683 self.request_autoscroll(autoscroll, cx);
2684 }
2685 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2686
2687 if self.should_open_signature_help_automatically(
2688 &old_cursor_position,
2689 self.signature_help_state.backspace_pressed(),
2690 cx,
2691 ) {
2692 self.show_signature_help(&ShowSignatureHelp, window, cx);
2693 }
2694 self.signature_help_state.set_backspace_pressed(false);
2695 }
2696
2697 result
2698 }
2699
2700 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2701 where
2702 I: IntoIterator<Item = (Range<S>, T)>,
2703 S: ToOffset,
2704 T: Into<Arc<str>>,
2705 {
2706 if self.read_only(cx) {
2707 return;
2708 }
2709
2710 self.buffer
2711 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2712 }
2713
2714 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2715 where
2716 I: IntoIterator<Item = (Range<S>, T)>,
2717 S: ToOffset,
2718 T: Into<Arc<str>>,
2719 {
2720 if self.read_only(cx) {
2721 return;
2722 }
2723
2724 self.buffer.update(cx, |buffer, cx| {
2725 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2726 });
2727 }
2728
2729 pub fn edit_with_block_indent<I, S, T>(
2730 &mut self,
2731 edits: I,
2732 original_indent_columns: Vec<Option<u32>>,
2733 cx: &mut Context<Self>,
2734 ) where
2735 I: IntoIterator<Item = (Range<S>, T)>,
2736 S: ToOffset,
2737 T: Into<Arc<str>>,
2738 {
2739 if self.read_only(cx) {
2740 return;
2741 }
2742
2743 self.buffer.update(cx, |buffer, cx| {
2744 buffer.edit(
2745 edits,
2746 Some(AutoindentMode::Block {
2747 original_indent_columns,
2748 }),
2749 cx,
2750 )
2751 });
2752 }
2753
2754 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2755 self.hide_context_menu(window, cx);
2756
2757 match phase {
2758 SelectPhase::Begin {
2759 position,
2760 add,
2761 click_count,
2762 } => self.begin_selection(position, add, click_count, window, cx),
2763 SelectPhase::BeginColumnar {
2764 position,
2765 goal_column,
2766 reset,
2767 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2768 SelectPhase::Extend {
2769 position,
2770 click_count,
2771 } => self.extend_selection(position, click_count, window, cx),
2772 SelectPhase::Update {
2773 position,
2774 goal_column,
2775 scroll_delta,
2776 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2777 SelectPhase::End => self.end_selection(window, cx),
2778 }
2779 }
2780
2781 fn extend_selection(
2782 &mut self,
2783 position: DisplayPoint,
2784 click_count: usize,
2785 window: &mut Window,
2786 cx: &mut Context<Self>,
2787 ) {
2788 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2789 let tail = self.selections.newest::<usize>(cx).tail();
2790 self.begin_selection(position, false, click_count, window, cx);
2791
2792 let position = position.to_offset(&display_map, Bias::Left);
2793 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2794
2795 let mut pending_selection = self
2796 .selections
2797 .pending_anchor()
2798 .expect("extend_selection not called with pending selection");
2799 if position >= tail {
2800 pending_selection.start = tail_anchor;
2801 } else {
2802 pending_selection.end = tail_anchor;
2803 pending_selection.reversed = true;
2804 }
2805
2806 let mut pending_mode = self.selections.pending_mode().unwrap();
2807 match &mut pending_mode {
2808 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2809 _ => {}
2810 }
2811
2812 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2813 s.set_pending(pending_selection, pending_mode)
2814 });
2815 }
2816
2817 fn begin_selection(
2818 &mut self,
2819 position: DisplayPoint,
2820 add: bool,
2821 click_count: usize,
2822 window: &mut Window,
2823 cx: &mut Context<Self>,
2824 ) {
2825 if !self.focus_handle.is_focused(window) {
2826 self.last_focused_descendant = None;
2827 window.focus(&self.focus_handle);
2828 }
2829
2830 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2831 let buffer = &display_map.buffer_snapshot;
2832 let newest_selection = self.selections.newest_anchor().clone();
2833 let position = display_map.clip_point(position, Bias::Left);
2834
2835 let start;
2836 let end;
2837 let mode;
2838 let mut auto_scroll;
2839 match click_count {
2840 1 => {
2841 start = buffer.anchor_before(position.to_point(&display_map));
2842 end = start;
2843 mode = SelectMode::Character;
2844 auto_scroll = true;
2845 }
2846 2 => {
2847 let range = movement::surrounding_word(&display_map, position);
2848 start = buffer.anchor_before(range.start.to_point(&display_map));
2849 end = buffer.anchor_before(range.end.to_point(&display_map));
2850 mode = SelectMode::Word(start..end);
2851 auto_scroll = true;
2852 }
2853 3 => {
2854 let position = display_map
2855 .clip_point(position, Bias::Left)
2856 .to_point(&display_map);
2857 let line_start = display_map.prev_line_boundary(position).0;
2858 let next_line_start = buffer.clip_point(
2859 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2860 Bias::Left,
2861 );
2862 start = buffer.anchor_before(line_start);
2863 end = buffer.anchor_before(next_line_start);
2864 mode = SelectMode::Line(start..end);
2865 auto_scroll = true;
2866 }
2867 _ => {
2868 start = buffer.anchor_before(0);
2869 end = buffer.anchor_before(buffer.len());
2870 mode = SelectMode::All;
2871 auto_scroll = false;
2872 }
2873 }
2874 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2875
2876 let point_to_delete: Option<usize> = {
2877 let selected_points: Vec<Selection<Point>> =
2878 self.selections.disjoint_in_range(start..end, cx);
2879
2880 if !add || click_count > 1 {
2881 None
2882 } else if !selected_points.is_empty() {
2883 Some(selected_points[0].id)
2884 } else {
2885 let clicked_point_already_selected =
2886 self.selections.disjoint.iter().find(|selection| {
2887 selection.start.to_point(buffer) == start.to_point(buffer)
2888 || selection.end.to_point(buffer) == end.to_point(buffer)
2889 });
2890
2891 clicked_point_already_selected.map(|selection| selection.id)
2892 }
2893 };
2894
2895 let selections_count = self.selections.count();
2896
2897 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2898 if let Some(point_to_delete) = point_to_delete {
2899 s.delete(point_to_delete);
2900
2901 if selections_count == 1 {
2902 s.set_pending_anchor_range(start..end, mode);
2903 }
2904 } else {
2905 if !add {
2906 s.clear_disjoint();
2907 } else if click_count > 1 {
2908 s.delete(newest_selection.id)
2909 }
2910
2911 s.set_pending_anchor_range(start..end, mode);
2912 }
2913 });
2914 }
2915
2916 fn begin_columnar_selection(
2917 &mut self,
2918 position: DisplayPoint,
2919 goal_column: u32,
2920 reset: bool,
2921 window: &mut Window,
2922 cx: &mut Context<Self>,
2923 ) {
2924 if !self.focus_handle.is_focused(window) {
2925 self.last_focused_descendant = None;
2926 window.focus(&self.focus_handle);
2927 }
2928
2929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2930
2931 if reset {
2932 let pointer_position = display_map
2933 .buffer_snapshot
2934 .anchor_before(position.to_point(&display_map));
2935
2936 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2937 s.clear_disjoint();
2938 s.set_pending_anchor_range(
2939 pointer_position..pointer_position,
2940 SelectMode::Character,
2941 );
2942 });
2943 }
2944
2945 let tail = self.selections.newest::<Point>(cx).tail();
2946 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2947
2948 if !reset {
2949 self.select_columns(
2950 tail.to_display_point(&display_map),
2951 position,
2952 goal_column,
2953 &display_map,
2954 window,
2955 cx,
2956 );
2957 }
2958 }
2959
2960 fn update_selection(
2961 &mut self,
2962 position: DisplayPoint,
2963 goal_column: u32,
2964 scroll_delta: gpui::Point<f32>,
2965 window: &mut Window,
2966 cx: &mut Context<Self>,
2967 ) {
2968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2969
2970 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2971 let tail = tail.to_display_point(&display_map);
2972 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2973 } else if let Some(mut pending) = self.selections.pending_anchor() {
2974 let buffer = self.buffer.read(cx).snapshot(cx);
2975 let head;
2976 let tail;
2977 let mode = self.selections.pending_mode().unwrap();
2978 match &mode {
2979 SelectMode::Character => {
2980 head = position.to_point(&display_map);
2981 tail = pending.tail().to_point(&buffer);
2982 }
2983 SelectMode::Word(original_range) => {
2984 let original_display_range = original_range.start.to_display_point(&display_map)
2985 ..original_range.end.to_display_point(&display_map);
2986 let original_buffer_range = original_display_range.start.to_point(&display_map)
2987 ..original_display_range.end.to_point(&display_map);
2988 if movement::is_inside_word(&display_map, position)
2989 || original_display_range.contains(&position)
2990 {
2991 let word_range = movement::surrounding_word(&display_map, position);
2992 if word_range.start < original_display_range.start {
2993 head = word_range.start.to_point(&display_map);
2994 } else {
2995 head = word_range.end.to_point(&display_map);
2996 }
2997 } else {
2998 head = position.to_point(&display_map);
2999 }
3000
3001 if head <= original_buffer_range.start {
3002 tail = original_buffer_range.end;
3003 } else {
3004 tail = original_buffer_range.start;
3005 }
3006 }
3007 SelectMode::Line(original_range) => {
3008 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3009
3010 let position = display_map
3011 .clip_point(position, Bias::Left)
3012 .to_point(&display_map);
3013 let line_start = display_map.prev_line_boundary(position).0;
3014 let next_line_start = buffer.clip_point(
3015 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3016 Bias::Left,
3017 );
3018
3019 if line_start < original_range.start {
3020 head = line_start
3021 } else {
3022 head = next_line_start
3023 }
3024
3025 if head <= original_range.start {
3026 tail = original_range.end;
3027 } else {
3028 tail = original_range.start;
3029 }
3030 }
3031 SelectMode::All => {
3032 return;
3033 }
3034 };
3035
3036 if head < tail {
3037 pending.start = buffer.anchor_before(head);
3038 pending.end = buffer.anchor_before(tail);
3039 pending.reversed = true;
3040 } else {
3041 pending.start = buffer.anchor_before(tail);
3042 pending.end = buffer.anchor_before(head);
3043 pending.reversed = false;
3044 }
3045
3046 self.change_selections(None, window, cx, |s| {
3047 s.set_pending(pending, mode);
3048 });
3049 } else {
3050 log::error!("update_selection dispatched with no pending selection");
3051 return;
3052 }
3053
3054 self.apply_scroll_delta(scroll_delta, window, cx);
3055 cx.notify();
3056 }
3057
3058 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3059 self.columnar_selection_tail.take();
3060 if self.selections.pending_anchor().is_some() {
3061 let selections = self.selections.all::<usize>(cx);
3062 self.change_selections(None, window, cx, |s| {
3063 s.select(selections);
3064 s.clear_pending();
3065 });
3066 }
3067 }
3068
3069 fn select_columns(
3070 &mut self,
3071 tail: DisplayPoint,
3072 head: DisplayPoint,
3073 goal_column: u32,
3074 display_map: &DisplaySnapshot,
3075 window: &mut Window,
3076 cx: &mut Context<Self>,
3077 ) {
3078 let start_row = cmp::min(tail.row(), head.row());
3079 let end_row = cmp::max(tail.row(), head.row());
3080 let start_column = cmp::min(tail.column(), goal_column);
3081 let end_column = cmp::max(tail.column(), goal_column);
3082 let reversed = start_column < tail.column();
3083
3084 let selection_ranges = (start_row.0..=end_row.0)
3085 .map(DisplayRow)
3086 .filter_map(|row| {
3087 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3088 let start = display_map
3089 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3090 .to_point(display_map);
3091 let end = display_map
3092 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3093 .to_point(display_map);
3094 if reversed {
3095 Some(end..start)
3096 } else {
3097 Some(start..end)
3098 }
3099 } else {
3100 None
3101 }
3102 })
3103 .collect::<Vec<_>>();
3104
3105 self.change_selections(None, window, cx, |s| {
3106 s.select_ranges(selection_ranges);
3107 });
3108 cx.notify();
3109 }
3110
3111 pub fn has_pending_nonempty_selection(&self) -> bool {
3112 let pending_nonempty_selection = match self.selections.pending_anchor() {
3113 Some(Selection { start, end, .. }) => start != end,
3114 None => false,
3115 };
3116
3117 pending_nonempty_selection
3118 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3119 }
3120
3121 pub fn has_pending_selection(&self) -> bool {
3122 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3123 }
3124
3125 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3126 self.selection_mark_mode = false;
3127
3128 if self.clear_expanded_diff_hunks(cx) {
3129 cx.notify();
3130 return;
3131 }
3132 if self.dismiss_menus_and_popups(true, window, cx) {
3133 return;
3134 }
3135
3136 if self.mode.is_full()
3137 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3138 {
3139 return;
3140 }
3141
3142 cx.propagate();
3143 }
3144
3145 pub fn dismiss_menus_and_popups(
3146 &mut self,
3147 is_user_requested: bool,
3148 window: &mut Window,
3149 cx: &mut Context<Self>,
3150 ) -> bool {
3151 if self.take_rename(false, window, cx).is_some() {
3152 return true;
3153 }
3154
3155 if hide_hover(self, cx) {
3156 return true;
3157 }
3158
3159 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3160 return true;
3161 }
3162
3163 if self.hide_context_menu(window, cx).is_some() {
3164 return true;
3165 }
3166
3167 if self.mouse_context_menu.take().is_some() {
3168 return true;
3169 }
3170
3171 if is_user_requested && self.discard_inline_completion(true, cx) {
3172 return true;
3173 }
3174
3175 if self.snippet_stack.pop().is_some() {
3176 return true;
3177 }
3178
3179 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3180 self.dismiss_diagnostics(cx);
3181 return true;
3182 }
3183
3184 false
3185 }
3186
3187 fn linked_editing_ranges_for(
3188 &self,
3189 selection: Range<text::Anchor>,
3190 cx: &App,
3191 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3192 if self.linked_edit_ranges.is_empty() {
3193 return None;
3194 }
3195 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3196 selection.end.buffer_id.and_then(|end_buffer_id| {
3197 if selection.start.buffer_id != Some(end_buffer_id) {
3198 return None;
3199 }
3200 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3201 let snapshot = buffer.read(cx).snapshot();
3202 self.linked_edit_ranges
3203 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3204 .map(|ranges| (ranges, snapshot, buffer))
3205 })?;
3206 use text::ToOffset as TO;
3207 // find offset from the start of current range to current cursor position
3208 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3209
3210 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3211 let start_difference = start_offset - start_byte_offset;
3212 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3213 let end_difference = end_offset - start_byte_offset;
3214 // Current range has associated linked ranges.
3215 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3216 for range in linked_ranges.iter() {
3217 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3218 let end_offset = start_offset + end_difference;
3219 let start_offset = start_offset + start_difference;
3220 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3221 continue;
3222 }
3223 if self.selections.disjoint_anchor_ranges().any(|s| {
3224 if s.start.buffer_id != selection.start.buffer_id
3225 || s.end.buffer_id != selection.end.buffer_id
3226 {
3227 return false;
3228 }
3229 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3230 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3231 }) {
3232 continue;
3233 }
3234 let start = buffer_snapshot.anchor_after(start_offset);
3235 let end = buffer_snapshot.anchor_after(end_offset);
3236 linked_edits
3237 .entry(buffer.clone())
3238 .or_default()
3239 .push(start..end);
3240 }
3241 Some(linked_edits)
3242 }
3243
3244 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3245 let text: Arc<str> = text.into();
3246
3247 if self.read_only(cx) {
3248 return;
3249 }
3250
3251 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3252
3253 let selections = self.selections.all_adjusted(cx);
3254 let mut bracket_inserted = false;
3255 let mut edits = Vec::new();
3256 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3257 let mut new_selections = Vec::with_capacity(selections.len());
3258 let mut new_autoclose_regions = Vec::new();
3259 let snapshot = self.buffer.read(cx).read(cx);
3260 let mut clear_linked_edit_ranges = false;
3261
3262 for (selection, autoclose_region) in
3263 self.selections_with_autoclose_regions(selections, &snapshot)
3264 {
3265 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3266 // Determine if the inserted text matches the opening or closing
3267 // bracket of any of this language's bracket pairs.
3268 let mut bracket_pair = None;
3269 let mut is_bracket_pair_start = false;
3270 let mut is_bracket_pair_end = false;
3271 if !text.is_empty() {
3272 let mut bracket_pair_matching_end = None;
3273 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3274 // and they are removing the character that triggered IME popup.
3275 for (pair, enabled) in scope.brackets() {
3276 if !pair.close && !pair.surround {
3277 continue;
3278 }
3279
3280 if enabled && pair.start.ends_with(text.as_ref()) {
3281 let prefix_len = pair.start.len() - text.len();
3282 let preceding_text_matches_prefix = prefix_len == 0
3283 || (selection.start.column >= (prefix_len as u32)
3284 && snapshot.contains_str_at(
3285 Point::new(
3286 selection.start.row,
3287 selection.start.column - (prefix_len as u32),
3288 ),
3289 &pair.start[..prefix_len],
3290 ));
3291 if preceding_text_matches_prefix {
3292 bracket_pair = Some(pair.clone());
3293 is_bracket_pair_start = true;
3294 break;
3295 }
3296 }
3297 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3298 {
3299 // take first bracket pair matching end, but don't break in case a later bracket
3300 // pair matches start
3301 bracket_pair_matching_end = Some(pair.clone());
3302 }
3303 }
3304 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3305 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3306 is_bracket_pair_end = true;
3307 }
3308 }
3309
3310 if let Some(bracket_pair) = bracket_pair {
3311 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3312 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3313 let auto_surround =
3314 self.use_auto_surround && snapshot_settings.use_auto_surround;
3315 if selection.is_empty() {
3316 if is_bracket_pair_start {
3317 // If the inserted text is a suffix of an opening bracket and the
3318 // selection is preceded by the rest of the opening bracket, then
3319 // insert the closing bracket.
3320 let following_text_allows_autoclose = snapshot
3321 .chars_at(selection.start)
3322 .next()
3323 .map_or(true, |c| scope.should_autoclose_before(c));
3324
3325 let preceding_text_allows_autoclose = selection.start.column == 0
3326 || snapshot.reversed_chars_at(selection.start).next().map_or(
3327 true,
3328 |c| {
3329 bracket_pair.start != bracket_pair.end
3330 || !snapshot
3331 .char_classifier_at(selection.start)
3332 .is_word(c)
3333 },
3334 );
3335
3336 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3337 && bracket_pair.start.len() == 1
3338 {
3339 let target = bracket_pair.start.chars().next().unwrap();
3340 let current_line_count = snapshot
3341 .reversed_chars_at(selection.start)
3342 .take_while(|&c| c != '\n')
3343 .filter(|&c| c == target)
3344 .count();
3345 current_line_count % 2 == 1
3346 } else {
3347 false
3348 };
3349
3350 if autoclose
3351 && bracket_pair.close
3352 && following_text_allows_autoclose
3353 && preceding_text_allows_autoclose
3354 && !is_closing_quote
3355 {
3356 let anchor = snapshot.anchor_before(selection.end);
3357 new_selections.push((selection.map(|_| anchor), text.len()));
3358 new_autoclose_regions.push((
3359 anchor,
3360 text.len(),
3361 selection.id,
3362 bracket_pair.clone(),
3363 ));
3364 edits.push((
3365 selection.range(),
3366 format!("{}{}", text, bracket_pair.end).into(),
3367 ));
3368 bracket_inserted = true;
3369 continue;
3370 }
3371 }
3372
3373 if let Some(region) = autoclose_region {
3374 // If the selection is followed by an auto-inserted closing bracket,
3375 // then don't insert that closing bracket again; just move the selection
3376 // past the closing bracket.
3377 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3378 && text.as_ref() == region.pair.end.as_str();
3379 if should_skip {
3380 let anchor = snapshot.anchor_after(selection.end);
3381 new_selections
3382 .push((selection.map(|_| anchor), region.pair.end.len()));
3383 continue;
3384 }
3385 }
3386
3387 let always_treat_brackets_as_autoclosed = snapshot
3388 .language_settings_at(selection.start, cx)
3389 .always_treat_brackets_as_autoclosed;
3390 if always_treat_brackets_as_autoclosed
3391 && is_bracket_pair_end
3392 && snapshot.contains_str_at(selection.end, text.as_ref())
3393 {
3394 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3395 // and the inserted text is a closing bracket and the selection is followed
3396 // by the closing bracket then move the selection past the closing bracket.
3397 let anchor = snapshot.anchor_after(selection.end);
3398 new_selections.push((selection.map(|_| anchor), text.len()));
3399 continue;
3400 }
3401 }
3402 // If an opening bracket is 1 character long and is typed while
3403 // text is selected, then surround that text with the bracket pair.
3404 else if auto_surround
3405 && bracket_pair.surround
3406 && is_bracket_pair_start
3407 && bracket_pair.start.chars().count() == 1
3408 {
3409 edits.push((selection.start..selection.start, text.clone()));
3410 edits.push((
3411 selection.end..selection.end,
3412 bracket_pair.end.as_str().into(),
3413 ));
3414 bracket_inserted = true;
3415 new_selections.push((
3416 Selection {
3417 id: selection.id,
3418 start: snapshot.anchor_after(selection.start),
3419 end: snapshot.anchor_before(selection.end),
3420 reversed: selection.reversed,
3421 goal: selection.goal,
3422 },
3423 0,
3424 ));
3425 continue;
3426 }
3427 }
3428 }
3429
3430 if self.auto_replace_emoji_shortcode
3431 && selection.is_empty()
3432 && text.as_ref().ends_with(':')
3433 {
3434 if let Some(possible_emoji_short_code) =
3435 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3436 {
3437 if !possible_emoji_short_code.is_empty() {
3438 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3439 let emoji_shortcode_start = Point::new(
3440 selection.start.row,
3441 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3442 );
3443
3444 // Remove shortcode from buffer
3445 edits.push((
3446 emoji_shortcode_start..selection.start,
3447 "".to_string().into(),
3448 ));
3449 new_selections.push((
3450 Selection {
3451 id: selection.id,
3452 start: snapshot.anchor_after(emoji_shortcode_start),
3453 end: snapshot.anchor_before(selection.start),
3454 reversed: selection.reversed,
3455 goal: selection.goal,
3456 },
3457 0,
3458 ));
3459
3460 // Insert emoji
3461 let selection_start_anchor = snapshot.anchor_after(selection.start);
3462 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3463 edits.push((selection.start..selection.end, emoji.to_string().into()));
3464
3465 continue;
3466 }
3467 }
3468 }
3469 }
3470
3471 // If not handling any auto-close operation, then just replace the selected
3472 // text with the given input and move the selection to the end of the
3473 // newly inserted text.
3474 let anchor = snapshot.anchor_after(selection.end);
3475 if !self.linked_edit_ranges.is_empty() {
3476 let start_anchor = snapshot.anchor_before(selection.start);
3477
3478 let is_word_char = text.chars().next().map_or(true, |char| {
3479 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3480 classifier.is_word(char)
3481 });
3482
3483 if is_word_char {
3484 if let Some(ranges) = self
3485 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3486 {
3487 for (buffer, edits) in ranges {
3488 linked_edits
3489 .entry(buffer.clone())
3490 .or_default()
3491 .extend(edits.into_iter().map(|range| (range, text.clone())));
3492 }
3493 }
3494 } else {
3495 clear_linked_edit_ranges = true;
3496 }
3497 }
3498
3499 new_selections.push((selection.map(|_| anchor), 0));
3500 edits.push((selection.start..selection.end, text.clone()));
3501 }
3502
3503 drop(snapshot);
3504
3505 self.transact(window, cx, |this, window, cx| {
3506 if clear_linked_edit_ranges {
3507 this.linked_edit_ranges.clear();
3508 }
3509 let initial_buffer_versions =
3510 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3511
3512 this.buffer.update(cx, |buffer, cx| {
3513 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3514 });
3515 for (buffer, edits) in linked_edits {
3516 buffer.update(cx, |buffer, cx| {
3517 let snapshot = buffer.snapshot();
3518 let edits = edits
3519 .into_iter()
3520 .map(|(range, text)| {
3521 use text::ToPoint as TP;
3522 let end_point = TP::to_point(&range.end, &snapshot);
3523 let start_point = TP::to_point(&range.start, &snapshot);
3524 (start_point..end_point, text)
3525 })
3526 .sorted_by_key(|(range, _)| range.start);
3527 buffer.edit(edits, None, cx);
3528 })
3529 }
3530 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3531 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3532 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3533 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3534 .zip(new_selection_deltas)
3535 .map(|(selection, delta)| Selection {
3536 id: selection.id,
3537 start: selection.start + delta,
3538 end: selection.end + delta,
3539 reversed: selection.reversed,
3540 goal: SelectionGoal::None,
3541 })
3542 .collect::<Vec<_>>();
3543
3544 let mut i = 0;
3545 for (position, delta, selection_id, pair) in new_autoclose_regions {
3546 let position = position.to_offset(&map.buffer_snapshot) + delta;
3547 let start = map.buffer_snapshot.anchor_before(position);
3548 let end = map.buffer_snapshot.anchor_after(position);
3549 while let Some(existing_state) = this.autoclose_regions.get(i) {
3550 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3551 Ordering::Less => i += 1,
3552 Ordering::Greater => break,
3553 Ordering::Equal => {
3554 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3555 Ordering::Less => i += 1,
3556 Ordering::Equal => break,
3557 Ordering::Greater => break,
3558 }
3559 }
3560 }
3561 }
3562 this.autoclose_regions.insert(
3563 i,
3564 AutocloseRegion {
3565 selection_id,
3566 range: start..end,
3567 pair,
3568 },
3569 );
3570 }
3571
3572 let had_active_inline_completion = this.has_active_inline_completion();
3573 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3574 s.select(new_selections)
3575 });
3576
3577 if !bracket_inserted {
3578 if let Some(on_type_format_task) =
3579 this.trigger_on_type_formatting(text.to_string(), window, cx)
3580 {
3581 on_type_format_task.detach_and_log_err(cx);
3582 }
3583 }
3584
3585 let editor_settings = EditorSettings::get_global(cx);
3586 if bracket_inserted
3587 && (editor_settings.auto_signature_help
3588 || editor_settings.show_signature_help_after_edits)
3589 {
3590 this.show_signature_help(&ShowSignatureHelp, window, cx);
3591 }
3592
3593 let trigger_in_words =
3594 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3595 if this.hard_wrap.is_some() {
3596 let latest: Range<Point> = this.selections.newest(cx).range();
3597 if latest.is_empty()
3598 && this
3599 .buffer()
3600 .read(cx)
3601 .snapshot(cx)
3602 .line_len(MultiBufferRow(latest.start.row))
3603 == latest.start.column
3604 {
3605 this.rewrap_impl(
3606 RewrapOptions {
3607 override_language_settings: true,
3608 preserve_existing_whitespace: true,
3609 },
3610 cx,
3611 )
3612 }
3613 }
3614 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3615 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3616 this.refresh_inline_completion(true, false, window, cx);
3617 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3618 });
3619 }
3620
3621 fn find_possible_emoji_shortcode_at_position(
3622 snapshot: &MultiBufferSnapshot,
3623 position: Point,
3624 ) -> Option<String> {
3625 let mut chars = Vec::new();
3626 let mut found_colon = false;
3627 for char in snapshot.reversed_chars_at(position).take(100) {
3628 // Found a possible emoji shortcode in the middle of the buffer
3629 if found_colon {
3630 if char.is_whitespace() {
3631 chars.reverse();
3632 return Some(chars.iter().collect());
3633 }
3634 // If the previous character is not a whitespace, we are in the middle of a word
3635 // and we only want to complete the shortcode if the word is made up of other emojis
3636 let mut containing_word = String::new();
3637 for ch in snapshot
3638 .reversed_chars_at(position)
3639 .skip(chars.len() + 1)
3640 .take(100)
3641 {
3642 if ch.is_whitespace() {
3643 break;
3644 }
3645 containing_word.push(ch);
3646 }
3647 let containing_word = containing_word.chars().rev().collect::<String>();
3648 if util::word_consists_of_emojis(containing_word.as_str()) {
3649 chars.reverse();
3650 return Some(chars.iter().collect());
3651 }
3652 }
3653
3654 if char.is_whitespace() || !char.is_ascii() {
3655 return None;
3656 }
3657 if char == ':' {
3658 found_colon = true;
3659 } else {
3660 chars.push(char);
3661 }
3662 }
3663 // Found a possible emoji shortcode at the beginning of the buffer
3664 chars.reverse();
3665 Some(chars.iter().collect())
3666 }
3667
3668 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3669 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3670 self.transact(window, cx, |this, window, cx| {
3671 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3672 let selections = this.selections.all::<usize>(cx);
3673 let multi_buffer = this.buffer.read(cx);
3674 let buffer = multi_buffer.snapshot(cx);
3675 selections
3676 .iter()
3677 .map(|selection| {
3678 let start_point = selection.start.to_point(&buffer);
3679 let mut indent =
3680 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3681 indent.len = cmp::min(indent.len, start_point.column);
3682 let start = selection.start;
3683 let end = selection.end;
3684 let selection_is_empty = start == end;
3685 let language_scope = buffer.language_scope_at(start);
3686 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3687 &language_scope
3688 {
3689 let insert_extra_newline =
3690 insert_extra_newline_brackets(&buffer, start..end, language)
3691 || insert_extra_newline_tree_sitter(&buffer, start..end);
3692
3693 // Comment extension on newline is allowed only for cursor selections
3694 let comment_delimiter = maybe!({
3695 if !selection_is_empty {
3696 return None;
3697 }
3698
3699 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3700 return None;
3701 }
3702
3703 let delimiters = language.line_comment_prefixes();
3704 let max_len_of_delimiter =
3705 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3706 let (snapshot, range) =
3707 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3708
3709 let mut index_of_first_non_whitespace = 0;
3710 let comment_candidate = snapshot
3711 .chars_for_range(range)
3712 .skip_while(|c| {
3713 let should_skip = c.is_whitespace();
3714 if should_skip {
3715 index_of_first_non_whitespace += 1;
3716 }
3717 should_skip
3718 })
3719 .take(max_len_of_delimiter)
3720 .collect::<String>();
3721 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3722 comment_candidate.starts_with(comment_prefix.as_ref())
3723 })?;
3724 let cursor_is_placed_after_comment_marker =
3725 index_of_first_non_whitespace + comment_prefix.len()
3726 <= start_point.column as usize;
3727 if cursor_is_placed_after_comment_marker {
3728 Some(comment_prefix.clone())
3729 } else {
3730 None
3731 }
3732 });
3733 (comment_delimiter, insert_extra_newline)
3734 } else {
3735 (None, false)
3736 };
3737
3738 let capacity_for_delimiter = comment_delimiter
3739 .as_deref()
3740 .map(str::len)
3741 .unwrap_or_default();
3742 let mut new_text =
3743 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3744 new_text.push('\n');
3745 new_text.extend(indent.chars());
3746 if let Some(delimiter) = &comment_delimiter {
3747 new_text.push_str(delimiter);
3748 }
3749 if insert_extra_newline {
3750 new_text = new_text.repeat(2);
3751 }
3752
3753 let anchor = buffer.anchor_after(end);
3754 let new_selection = selection.map(|_| anchor);
3755 (
3756 (start..end, new_text),
3757 (insert_extra_newline, new_selection),
3758 )
3759 })
3760 .unzip()
3761 };
3762
3763 this.edit_with_autoindent(edits, cx);
3764 let buffer = this.buffer.read(cx).snapshot(cx);
3765 let new_selections = selection_fixup_info
3766 .into_iter()
3767 .map(|(extra_newline_inserted, new_selection)| {
3768 let mut cursor = new_selection.end.to_point(&buffer);
3769 if extra_newline_inserted {
3770 cursor.row -= 1;
3771 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3772 }
3773 new_selection.map(|_| cursor)
3774 })
3775 .collect();
3776
3777 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3778 s.select(new_selections)
3779 });
3780 this.refresh_inline_completion(true, false, window, cx);
3781 });
3782 }
3783
3784 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3785 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3786
3787 let buffer = self.buffer.read(cx);
3788 let snapshot = buffer.snapshot(cx);
3789
3790 let mut edits = Vec::new();
3791 let mut rows = Vec::new();
3792
3793 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3794 let cursor = selection.head();
3795 let row = cursor.row;
3796
3797 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3798
3799 let newline = "\n".to_string();
3800 edits.push((start_of_line..start_of_line, newline));
3801
3802 rows.push(row + rows_inserted as u32);
3803 }
3804
3805 self.transact(window, cx, |editor, window, cx| {
3806 editor.edit(edits, cx);
3807
3808 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3809 let mut index = 0;
3810 s.move_cursors_with(|map, _, _| {
3811 let row = rows[index];
3812 index += 1;
3813
3814 let point = Point::new(row, 0);
3815 let boundary = map.next_line_boundary(point).1;
3816 let clipped = map.clip_point(boundary, Bias::Left);
3817
3818 (clipped, SelectionGoal::None)
3819 });
3820 });
3821
3822 let mut indent_edits = Vec::new();
3823 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3824 for row in rows {
3825 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3826 for (row, indent) in indents {
3827 if indent.len == 0 {
3828 continue;
3829 }
3830
3831 let text = match indent.kind {
3832 IndentKind::Space => " ".repeat(indent.len as usize),
3833 IndentKind::Tab => "\t".repeat(indent.len as usize),
3834 };
3835 let point = Point::new(row.0, 0);
3836 indent_edits.push((point..point, text));
3837 }
3838 }
3839 editor.edit(indent_edits, cx);
3840 });
3841 }
3842
3843 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3844 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3845
3846 let buffer = self.buffer.read(cx);
3847 let snapshot = buffer.snapshot(cx);
3848
3849 let mut edits = Vec::new();
3850 let mut rows = Vec::new();
3851 let mut rows_inserted = 0;
3852
3853 for selection in self.selections.all_adjusted(cx) {
3854 let cursor = selection.head();
3855 let row = cursor.row;
3856
3857 let point = Point::new(row + 1, 0);
3858 let start_of_line = snapshot.clip_point(point, Bias::Left);
3859
3860 let newline = "\n".to_string();
3861 edits.push((start_of_line..start_of_line, newline));
3862
3863 rows_inserted += 1;
3864 rows.push(row + rows_inserted);
3865 }
3866
3867 self.transact(window, cx, |editor, window, cx| {
3868 editor.edit(edits, cx);
3869
3870 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3871 let mut index = 0;
3872 s.move_cursors_with(|map, _, _| {
3873 let row = rows[index];
3874 index += 1;
3875
3876 let point = Point::new(row, 0);
3877 let boundary = map.next_line_boundary(point).1;
3878 let clipped = map.clip_point(boundary, Bias::Left);
3879
3880 (clipped, SelectionGoal::None)
3881 });
3882 });
3883
3884 let mut indent_edits = Vec::new();
3885 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3886 for row in rows {
3887 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3888 for (row, indent) in indents {
3889 if indent.len == 0 {
3890 continue;
3891 }
3892
3893 let text = match indent.kind {
3894 IndentKind::Space => " ".repeat(indent.len as usize),
3895 IndentKind::Tab => "\t".repeat(indent.len as usize),
3896 };
3897 let point = Point::new(row.0, 0);
3898 indent_edits.push((point..point, text));
3899 }
3900 }
3901 editor.edit(indent_edits, cx);
3902 });
3903 }
3904
3905 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3906 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3907 original_indent_columns: Vec::new(),
3908 });
3909 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3910 }
3911
3912 fn insert_with_autoindent_mode(
3913 &mut self,
3914 text: &str,
3915 autoindent_mode: Option<AutoindentMode>,
3916 window: &mut Window,
3917 cx: &mut Context<Self>,
3918 ) {
3919 if self.read_only(cx) {
3920 return;
3921 }
3922
3923 let text: Arc<str> = text.into();
3924 self.transact(window, cx, |this, window, cx| {
3925 let old_selections = this.selections.all_adjusted(cx);
3926 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3927 let anchors = {
3928 let snapshot = buffer.read(cx);
3929 old_selections
3930 .iter()
3931 .map(|s| {
3932 let anchor = snapshot.anchor_after(s.head());
3933 s.map(|_| anchor)
3934 })
3935 .collect::<Vec<_>>()
3936 };
3937 buffer.edit(
3938 old_selections
3939 .iter()
3940 .map(|s| (s.start..s.end, text.clone())),
3941 autoindent_mode,
3942 cx,
3943 );
3944 anchors
3945 });
3946
3947 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3948 s.select_anchors(selection_anchors);
3949 });
3950
3951 cx.notify();
3952 });
3953 }
3954
3955 fn trigger_completion_on_input(
3956 &mut self,
3957 text: &str,
3958 trigger_in_words: bool,
3959 window: &mut Window,
3960 cx: &mut Context<Self>,
3961 ) {
3962 let ignore_completion_provider = self
3963 .context_menu
3964 .borrow()
3965 .as_ref()
3966 .map(|menu| match menu {
3967 CodeContextMenu::Completions(completions_menu) => {
3968 completions_menu.ignore_completion_provider
3969 }
3970 CodeContextMenu::CodeActions(_) => false,
3971 })
3972 .unwrap_or(false);
3973
3974 if ignore_completion_provider {
3975 self.show_word_completions(&ShowWordCompletions, window, cx);
3976 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3977 self.show_completions(
3978 &ShowCompletions {
3979 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3980 },
3981 window,
3982 cx,
3983 );
3984 } else {
3985 self.hide_context_menu(window, cx);
3986 }
3987 }
3988
3989 fn is_completion_trigger(
3990 &self,
3991 text: &str,
3992 trigger_in_words: bool,
3993 cx: &mut Context<Self>,
3994 ) -> bool {
3995 let position = self.selections.newest_anchor().head();
3996 let multibuffer = self.buffer.read(cx);
3997 let Some(buffer) = position
3998 .buffer_id
3999 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4000 else {
4001 return false;
4002 };
4003
4004 if let Some(completion_provider) = &self.completion_provider {
4005 completion_provider.is_completion_trigger(
4006 &buffer,
4007 position.text_anchor,
4008 text,
4009 trigger_in_words,
4010 cx,
4011 )
4012 } else {
4013 false
4014 }
4015 }
4016
4017 /// If any empty selections is touching the start of its innermost containing autoclose
4018 /// region, expand it to select the brackets.
4019 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4020 let selections = self.selections.all::<usize>(cx);
4021 let buffer = self.buffer.read(cx).read(cx);
4022 let new_selections = self
4023 .selections_with_autoclose_regions(selections, &buffer)
4024 .map(|(mut selection, region)| {
4025 if !selection.is_empty() {
4026 return selection;
4027 }
4028
4029 if let Some(region) = region {
4030 let mut range = region.range.to_offset(&buffer);
4031 if selection.start == range.start && range.start >= region.pair.start.len() {
4032 range.start -= region.pair.start.len();
4033 if buffer.contains_str_at(range.start, ®ion.pair.start)
4034 && buffer.contains_str_at(range.end, ®ion.pair.end)
4035 {
4036 range.end += region.pair.end.len();
4037 selection.start = range.start;
4038 selection.end = range.end;
4039
4040 return selection;
4041 }
4042 }
4043 }
4044
4045 let always_treat_brackets_as_autoclosed = buffer
4046 .language_settings_at(selection.start, cx)
4047 .always_treat_brackets_as_autoclosed;
4048
4049 if !always_treat_brackets_as_autoclosed {
4050 return selection;
4051 }
4052
4053 if let Some(scope) = buffer.language_scope_at(selection.start) {
4054 for (pair, enabled) in scope.brackets() {
4055 if !enabled || !pair.close {
4056 continue;
4057 }
4058
4059 if buffer.contains_str_at(selection.start, &pair.end) {
4060 let pair_start_len = pair.start.len();
4061 if buffer.contains_str_at(
4062 selection.start.saturating_sub(pair_start_len),
4063 &pair.start,
4064 ) {
4065 selection.start -= pair_start_len;
4066 selection.end += pair.end.len();
4067
4068 return selection;
4069 }
4070 }
4071 }
4072 }
4073
4074 selection
4075 })
4076 .collect();
4077
4078 drop(buffer);
4079 self.change_selections(None, window, cx, |selections| {
4080 selections.select(new_selections)
4081 });
4082 }
4083
4084 /// Iterate the given selections, and for each one, find the smallest surrounding
4085 /// autoclose region. This uses the ordering of the selections and the autoclose
4086 /// regions to avoid repeated comparisons.
4087 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4088 &'a self,
4089 selections: impl IntoIterator<Item = Selection<D>>,
4090 buffer: &'a MultiBufferSnapshot,
4091 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4092 let mut i = 0;
4093 let mut regions = self.autoclose_regions.as_slice();
4094 selections.into_iter().map(move |selection| {
4095 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4096
4097 let mut enclosing = None;
4098 while let Some(pair_state) = regions.get(i) {
4099 if pair_state.range.end.to_offset(buffer) < range.start {
4100 regions = ®ions[i + 1..];
4101 i = 0;
4102 } else if pair_state.range.start.to_offset(buffer) > range.end {
4103 break;
4104 } else {
4105 if pair_state.selection_id == selection.id {
4106 enclosing = Some(pair_state);
4107 }
4108 i += 1;
4109 }
4110 }
4111
4112 (selection, enclosing)
4113 })
4114 }
4115
4116 /// Remove any autoclose regions that no longer contain their selection.
4117 fn invalidate_autoclose_regions(
4118 &mut self,
4119 mut selections: &[Selection<Anchor>],
4120 buffer: &MultiBufferSnapshot,
4121 ) {
4122 self.autoclose_regions.retain(|state| {
4123 let mut i = 0;
4124 while let Some(selection) = selections.get(i) {
4125 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4126 selections = &selections[1..];
4127 continue;
4128 }
4129 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4130 break;
4131 }
4132 if selection.id == state.selection_id {
4133 return true;
4134 } else {
4135 i += 1;
4136 }
4137 }
4138 false
4139 });
4140 }
4141
4142 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4143 let offset = position.to_offset(buffer);
4144 let (word_range, kind) = buffer.surrounding_word(offset, true);
4145 if offset > word_range.start && kind == Some(CharKind::Word) {
4146 Some(
4147 buffer
4148 .text_for_range(word_range.start..offset)
4149 .collect::<String>(),
4150 )
4151 } else {
4152 None
4153 }
4154 }
4155
4156 pub fn toggle_inlay_hints(
4157 &mut self,
4158 _: &ToggleInlayHints,
4159 _: &mut Window,
4160 cx: &mut Context<Self>,
4161 ) {
4162 self.refresh_inlay_hints(
4163 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4164 cx,
4165 );
4166 }
4167
4168 pub fn inlay_hints_enabled(&self) -> bool {
4169 self.inlay_hint_cache.enabled
4170 }
4171
4172 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4173 if self.semantics_provider.is_none() || !self.mode.is_full() {
4174 return;
4175 }
4176
4177 let reason_description = reason.description();
4178 let ignore_debounce = matches!(
4179 reason,
4180 InlayHintRefreshReason::SettingsChange(_)
4181 | InlayHintRefreshReason::Toggle(_)
4182 | InlayHintRefreshReason::ExcerptsRemoved(_)
4183 | InlayHintRefreshReason::ModifiersChanged(_)
4184 );
4185 let (invalidate_cache, required_languages) = match reason {
4186 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4187 match self.inlay_hint_cache.modifiers_override(enabled) {
4188 Some(enabled) => {
4189 if enabled {
4190 (InvalidationStrategy::RefreshRequested, None)
4191 } else {
4192 self.splice_inlays(
4193 &self
4194 .visible_inlay_hints(cx)
4195 .iter()
4196 .map(|inlay| inlay.id)
4197 .collect::<Vec<InlayId>>(),
4198 Vec::new(),
4199 cx,
4200 );
4201 return;
4202 }
4203 }
4204 None => return,
4205 }
4206 }
4207 InlayHintRefreshReason::Toggle(enabled) => {
4208 if self.inlay_hint_cache.toggle(enabled) {
4209 if enabled {
4210 (InvalidationStrategy::RefreshRequested, None)
4211 } else {
4212 self.splice_inlays(
4213 &self
4214 .visible_inlay_hints(cx)
4215 .iter()
4216 .map(|inlay| inlay.id)
4217 .collect::<Vec<InlayId>>(),
4218 Vec::new(),
4219 cx,
4220 );
4221 return;
4222 }
4223 } else {
4224 return;
4225 }
4226 }
4227 InlayHintRefreshReason::SettingsChange(new_settings) => {
4228 match self.inlay_hint_cache.update_settings(
4229 &self.buffer,
4230 new_settings,
4231 self.visible_inlay_hints(cx),
4232 cx,
4233 ) {
4234 ControlFlow::Break(Some(InlaySplice {
4235 to_remove,
4236 to_insert,
4237 })) => {
4238 self.splice_inlays(&to_remove, to_insert, cx);
4239 return;
4240 }
4241 ControlFlow::Break(None) => return,
4242 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4243 }
4244 }
4245 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4246 if let Some(InlaySplice {
4247 to_remove,
4248 to_insert,
4249 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4250 {
4251 self.splice_inlays(&to_remove, to_insert, cx);
4252 }
4253 self.display_map.update(cx, |display_map, _| {
4254 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4255 });
4256 return;
4257 }
4258 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4259 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4260 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4261 }
4262 InlayHintRefreshReason::RefreshRequested => {
4263 (InvalidationStrategy::RefreshRequested, None)
4264 }
4265 };
4266
4267 if let Some(InlaySplice {
4268 to_remove,
4269 to_insert,
4270 }) = self.inlay_hint_cache.spawn_hint_refresh(
4271 reason_description,
4272 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4273 invalidate_cache,
4274 ignore_debounce,
4275 cx,
4276 ) {
4277 self.splice_inlays(&to_remove, to_insert, cx);
4278 }
4279 }
4280
4281 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4282 self.display_map
4283 .read(cx)
4284 .current_inlays()
4285 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4286 .cloned()
4287 .collect()
4288 }
4289
4290 pub fn excerpts_for_inlay_hints_query(
4291 &self,
4292 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4293 cx: &mut Context<Editor>,
4294 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4295 let Some(project) = self.project.as_ref() else {
4296 return HashMap::default();
4297 };
4298 let project = project.read(cx);
4299 let multi_buffer = self.buffer().read(cx);
4300 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4301 let multi_buffer_visible_start = self
4302 .scroll_manager
4303 .anchor()
4304 .anchor
4305 .to_point(&multi_buffer_snapshot);
4306 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4307 multi_buffer_visible_start
4308 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4309 Bias::Left,
4310 );
4311 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4312 multi_buffer_snapshot
4313 .range_to_buffer_ranges(multi_buffer_visible_range)
4314 .into_iter()
4315 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4316 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4317 let buffer_file = project::File::from_dyn(buffer.file())?;
4318 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4319 let worktree_entry = buffer_worktree
4320 .read(cx)
4321 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4322 if worktree_entry.is_ignored {
4323 return None;
4324 }
4325
4326 let language = buffer.language()?;
4327 if let Some(restrict_to_languages) = restrict_to_languages {
4328 if !restrict_to_languages.contains(language) {
4329 return None;
4330 }
4331 }
4332 Some((
4333 excerpt_id,
4334 (
4335 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4336 buffer.version().clone(),
4337 excerpt_visible_range,
4338 ),
4339 ))
4340 })
4341 .collect()
4342 }
4343
4344 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4345 TextLayoutDetails {
4346 text_system: window.text_system().clone(),
4347 editor_style: self.style.clone().unwrap(),
4348 rem_size: window.rem_size(),
4349 scroll_anchor: self.scroll_manager.anchor(),
4350 visible_rows: self.visible_line_count(),
4351 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4352 }
4353 }
4354
4355 pub fn splice_inlays(
4356 &self,
4357 to_remove: &[InlayId],
4358 to_insert: Vec<Inlay>,
4359 cx: &mut Context<Self>,
4360 ) {
4361 self.display_map.update(cx, |display_map, cx| {
4362 display_map.splice_inlays(to_remove, to_insert, cx)
4363 });
4364 cx.notify();
4365 }
4366
4367 fn trigger_on_type_formatting(
4368 &self,
4369 input: String,
4370 window: &mut Window,
4371 cx: &mut Context<Self>,
4372 ) -> Option<Task<Result<()>>> {
4373 if input.len() != 1 {
4374 return None;
4375 }
4376
4377 let project = self.project.as_ref()?;
4378 let position = self.selections.newest_anchor().head();
4379 let (buffer, buffer_position) = self
4380 .buffer
4381 .read(cx)
4382 .text_anchor_for_position(position, cx)?;
4383
4384 let settings = language_settings::language_settings(
4385 buffer
4386 .read(cx)
4387 .language_at(buffer_position)
4388 .map(|l| l.name()),
4389 buffer.read(cx).file(),
4390 cx,
4391 );
4392 if !settings.use_on_type_format {
4393 return None;
4394 }
4395
4396 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4397 // hence we do LSP request & edit on host side only — add formats to host's history.
4398 let push_to_lsp_host_history = true;
4399 // If this is not the host, append its history with new edits.
4400 let push_to_client_history = project.read(cx).is_via_collab();
4401
4402 let on_type_formatting = project.update(cx, |project, cx| {
4403 project.on_type_format(
4404 buffer.clone(),
4405 buffer_position,
4406 input,
4407 push_to_lsp_host_history,
4408 cx,
4409 )
4410 });
4411 Some(cx.spawn_in(window, async move |editor, cx| {
4412 if let Some(transaction) = on_type_formatting.await? {
4413 if push_to_client_history {
4414 buffer
4415 .update(cx, |buffer, _| {
4416 buffer.push_transaction(transaction, Instant::now());
4417 buffer.finalize_last_transaction();
4418 })
4419 .ok();
4420 }
4421 editor.update(cx, |editor, cx| {
4422 editor.refresh_document_highlights(cx);
4423 })?;
4424 }
4425 Ok(())
4426 }))
4427 }
4428
4429 pub fn show_word_completions(
4430 &mut self,
4431 _: &ShowWordCompletions,
4432 window: &mut Window,
4433 cx: &mut Context<Self>,
4434 ) {
4435 self.open_completions_menu(true, None, window, cx);
4436 }
4437
4438 pub fn show_completions(
4439 &mut self,
4440 options: &ShowCompletions,
4441 window: &mut Window,
4442 cx: &mut Context<Self>,
4443 ) {
4444 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4445 }
4446
4447 fn open_completions_menu(
4448 &mut self,
4449 ignore_completion_provider: bool,
4450 trigger: Option<&str>,
4451 window: &mut Window,
4452 cx: &mut Context<Self>,
4453 ) {
4454 if self.pending_rename.is_some() {
4455 return;
4456 }
4457 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4458 return;
4459 }
4460
4461 let position = self.selections.newest_anchor().head();
4462 if position.diff_base_anchor.is_some() {
4463 return;
4464 }
4465 let (buffer, buffer_position) =
4466 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4467 output
4468 } else {
4469 return;
4470 };
4471 let buffer_snapshot = buffer.read(cx).snapshot();
4472 let show_completion_documentation = buffer_snapshot
4473 .settings_at(buffer_position, cx)
4474 .show_completion_documentation;
4475
4476 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4477
4478 let trigger_kind = match trigger {
4479 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4480 CompletionTriggerKind::TRIGGER_CHARACTER
4481 }
4482 _ => CompletionTriggerKind::INVOKED,
4483 };
4484 let completion_context = CompletionContext {
4485 trigger_character: trigger.and_then(|trigger| {
4486 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4487 Some(String::from(trigger))
4488 } else {
4489 None
4490 }
4491 }),
4492 trigger_kind,
4493 };
4494
4495 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4496 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4497 let word_to_exclude = buffer_snapshot
4498 .text_for_range(old_range.clone())
4499 .collect::<String>();
4500 (
4501 buffer_snapshot.anchor_before(old_range.start)
4502 ..buffer_snapshot.anchor_after(old_range.end),
4503 Some(word_to_exclude),
4504 )
4505 } else {
4506 (buffer_position..buffer_position, None)
4507 };
4508
4509 let completion_settings = language_settings(
4510 buffer_snapshot
4511 .language_at(buffer_position)
4512 .map(|language| language.name()),
4513 buffer_snapshot.file(),
4514 cx,
4515 )
4516 .completions;
4517
4518 // The document can be large, so stay in reasonable bounds when searching for words,
4519 // otherwise completion pop-up might be slow to appear.
4520 const WORD_LOOKUP_ROWS: u32 = 5_000;
4521 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4522 let min_word_search = buffer_snapshot.clip_point(
4523 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4524 Bias::Left,
4525 );
4526 let max_word_search = buffer_snapshot.clip_point(
4527 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4528 Bias::Right,
4529 );
4530 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4531 ..buffer_snapshot.point_to_offset(max_word_search);
4532
4533 let provider = self
4534 .completion_provider
4535 .as_ref()
4536 .filter(|_| !ignore_completion_provider);
4537 let skip_digits = query
4538 .as_ref()
4539 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4540
4541 let (mut words, provided_completions) = match provider {
4542 Some(provider) => {
4543 let completions = provider.completions(
4544 position.excerpt_id,
4545 &buffer,
4546 buffer_position,
4547 completion_context,
4548 window,
4549 cx,
4550 );
4551
4552 let words = match completion_settings.words {
4553 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4554 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4555 .background_spawn(async move {
4556 buffer_snapshot.words_in_range(WordsQuery {
4557 fuzzy_contents: None,
4558 range: word_search_range,
4559 skip_digits,
4560 })
4561 }),
4562 };
4563
4564 (words, completions)
4565 }
4566 None => (
4567 cx.background_spawn(async move {
4568 buffer_snapshot.words_in_range(WordsQuery {
4569 fuzzy_contents: None,
4570 range: word_search_range,
4571 skip_digits,
4572 })
4573 }),
4574 Task::ready(Ok(None)),
4575 ),
4576 };
4577
4578 let sort_completions = provider
4579 .as_ref()
4580 .map_or(false, |provider| provider.sort_completions());
4581
4582 let filter_completions = provider
4583 .as_ref()
4584 .map_or(true, |provider| provider.filter_completions());
4585
4586 let id = post_inc(&mut self.next_completion_id);
4587 let task = cx.spawn_in(window, async move |editor, cx| {
4588 async move {
4589 editor.update(cx, |this, _| {
4590 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4591 })?;
4592
4593 let mut completions = Vec::new();
4594 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4595 completions.extend(provided_completions);
4596 if completion_settings.words == WordsCompletionMode::Fallback {
4597 words = Task::ready(BTreeMap::default());
4598 }
4599 }
4600
4601 let mut words = words.await;
4602 if let Some(word_to_exclude) = &word_to_exclude {
4603 words.remove(word_to_exclude);
4604 }
4605 for lsp_completion in &completions {
4606 words.remove(&lsp_completion.new_text);
4607 }
4608 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4609 replace_range: old_range.clone(),
4610 new_text: word.clone(),
4611 label: CodeLabel::plain(word, None),
4612 icon_path: None,
4613 documentation: None,
4614 source: CompletionSource::BufferWord {
4615 word_range,
4616 resolved: false,
4617 },
4618 insert_text_mode: Some(InsertTextMode::AS_IS),
4619 confirm: None,
4620 }));
4621
4622 let menu = if completions.is_empty() {
4623 None
4624 } else {
4625 let mut menu = CompletionsMenu::new(
4626 id,
4627 sort_completions,
4628 show_completion_documentation,
4629 ignore_completion_provider,
4630 position,
4631 buffer.clone(),
4632 completions.into(),
4633 );
4634
4635 menu.filter(
4636 if filter_completions {
4637 query.as_deref()
4638 } else {
4639 None
4640 },
4641 cx.background_executor().clone(),
4642 )
4643 .await;
4644
4645 menu.visible().then_some(menu)
4646 };
4647
4648 editor.update_in(cx, |editor, window, cx| {
4649 match editor.context_menu.borrow().as_ref() {
4650 None => {}
4651 Some(CodeContextMenu::Completions(prev_menu)) => {
4652 if prev_menu.id > id {
4653 return;
4654 }
4655 }
4656 _ => return,
4657 }
4658
4659 if editor.focus_handle.is_focused(window) && menu.is_some() {
4660 let mut menu = menu.unwrap();
4661 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4662
4663 *editor.context_menu.borrow_mut() =
4664 Some(CodeContextMenu::Completions(menu));
4665
4666 if editor.show_edit_predictions_in_menu() {
4667 editor.update_visible_inline_completion(window, cx);
4668 } else {
4669 editor.discard_inline_completion(false, cx);
4670 }
4671
4672 cx.notify();
4673 } else if editor.completion_tasks.len() <= 1 {
4674 // If there are no more completion tasks and the last menu was
4675 // empty, we should hide it.
4676 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4677 // If it was already hidden and we don't show inline
4678 // completions in the menu, we should also show the
4679 // inline-completion when available.
4680 if was_hidden && editor.show_edit_predictions_in_menu() {
4681 editor.update_visible_inline_completion(window, cx);
4682 }
4683 }
4684 })?;
4685
4686 anyhow::Ok(())
4687 }
4688 .log_err()
4689 .await
4690 });
4691
4692 self.completion_tasks.push((id, task));
4693 }
4694
4695 #[cfg(feature = "test-support")]
4696 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4697 let menu = self.context_menu.borrow();
4698 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4699 let completions = menu.completions.borrow();
4700 Some(completions.to_vec())
4701 } else {
4702 None
4703 }
4704 }
4705
4706 pub fn confirm_completion(
4707 &mut self,
4708 action: &ConfirmCompletion,
4709 window: &mut Window,
4710 cx: &mut Context<Self>,
4711 ) -> Option<Task<Result<()>>> {
4712 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4713 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4714 }
4715
4716 pub fn confirm_completion_insert(
4717 &mut self,
4718 _: &ConfirmCompletionInsert,
4719 window: &mut Window,
4720 cx: &mut Context<Self>,
4721 ) -> Option<Task<Result<()>>> {
4722 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4723 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4724 }
4725
4726 pub fn confirm_completion_replace(
4727 &mut self,
4728 _: &ConfirmCompletionReplace,
4729 window: &mut Window,
4730 cx: &mut Context<Self>,
4731 ) -> Option<Task<Result<()>>> {
4732 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4733 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4734 }
4735
4736 pub fn compose_completion(
4737 &mut self,
4738 action: &ComposeCompletion,
4739 window: &mut Window,
4740 cx: &mut Context<Self>,
4741 ) -> Option<Task<Result<()>>> {
4742 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4743 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4744 }
4745
4746 fn do_completion(
4747 &mut self,
4748 item_ix: Option<usize>,
4749 intent: CompletionIntent,
4750 window: &mut Window,
4751 cx: &mut Context<Editor>,
4752 ) -> Option<Task<Result<()>>> {
4753 use language::ToOffset as _;
4754
4755 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4756 else {
4757 return None;
4758 };
4759
4760 let candidate_id = {
4761 let entries = completions_menu.entries.borrow();
4762 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4763 if self.show_edit_predictions_in_menu() {
4764 self.discard_inline_completion(true, cx);
4765 }
4766 mat.candidate_id
4767 };
4768
4769 let buffer_handle = completions_menu.buffer;
4770 let completion = completions_menu
4771 .completions
4772 .borrow()
4773 .get(candidate_id)?
4774 .clone();
4775 cx.stop_propagation();
4776
4777 let snippet;
4778 let new_text;
4779 if completion.is_snippet() {
4780 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4781 new_text = snippet.as_ref().unwrap().text.clone();
4782 } else {
4783 snippet = None;
4784 new_text = completion.new_text.clone();
4785 };
4786
4787 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4788 let buffer = buffer_handle.read(cx);
4789 let snapshot = self.buffer.read(cx).snapshot(cx);
4790 let replace_range_multibuffer = {
4791 let excerpt = snapshot
4792 .excerpt_containing(self.selections.newest_anchor().range())
4793 .unwrap();
4794 let multibuffer_anchor = snapshot
4795 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4796 .unwrap()
4797 ..snapshot
4798 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4799 .unwrap();
4800 multibuffer_anchor.start.to_offset(&snapshot)
4801 ..multibuffer_anchor.end.to_offset(&snapshot)
4802 };
4803 let newest_anchor = self.selections.newest_anchor();
4804 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4805 return None;
4806 }
4807
4808 let old_text = buffer
4809 .text_for_range(replace_range.clone())
4810 .collect::<String>();
4811 let lookbehind = newest_anchor
4812 .start
4813 .text_anchor
4814 .to_offset(buffer)
4815 .saturating_sub(replace_range.start);
4816 let lookahead = replace_range
4817 .end
4818 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4819 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4820 let suffix = &old_text[lookbehind.min(old_text.len())..];
4821
4822 let selections = self.selections.all::<usize>(cx);
4823 let mut ranges = Vec::new();
4824 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4825
4826 for selection in &selections {
4827 let range = if selection.id == newest_anchor.id {
4828 replace_range_multibuffer.clone()
4829 } else {
4830 let mut range = selection.range();
4831
4832 // if prefix is present, don't duplicate it
4833 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4834 range.start = range.start.saturating_sub(lookbehind);
4835
4836 // if suffix is also present, mimic the newest cursor and replace it
4837 if selection.id != newest_anchor.id
4838 && snapshot.contains_str_at(range.end, suffix)
4839 {
4840 range.end += lookahead;
4841 }
4842 }
4843 range
4844 };
4845
4846 ranges.push(range);
4847
4848 if !self.linked_edit_ranges.is_empty() {
4849 let start_anchor = snapshot.anchor_before(selection.head());
4850 let end_anchor = snapshot.anchor_after(selection.tail());
4851 if let Some(ranges) = self
4852 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4853 {
4854 for (buffer, edits) in ranges {
4855 linked_edits
4856 .entry(buffer.clone())
4857 .or_default()
4858 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4859 }
4860 }
4861 }
4862 }
4863
4864 cx.emit(EditorEvent::InputHandled {
4865 utf16_range_to_replace: None,
4866 text: new_text.clone().into(),
4867 });
4868
4869 self.transact(window, cx, |this, window, cx| {
4870 if let Some(mut snippet) = snippet {
4871 snippet.text = new_text.to_string();
4872 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4873 } else {
4874 this.buffer.update(cx, |buffer, cx| {
4875 let auto_indent = match completion.insert_text_mode {
4876 Some(InsertTextMode::AS_IS) => None,
4877 _ => this.autoindent_mode.clone(),
4878 };
4879 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4880 buffer.edit(edits, auto_indent, cx);
4881 });
4882 }
4883 for (buffer, edits) in linked_edits {
4884 buffer.update(cx, |buffer, cx| {
4885 let snapshot = buffer.snapshot();
4886 let edits = edits
4887 .into_iter()
4888 .map(|(range, text)| {
4889 use text::ToPoint as TP;
4890 let end_point = TP::to_point(&range.end, &snapshot);
4891 let start_point = TP::to_point(&range.start, &snapshot);
4892 (start_point..end_point, text)
4893 })
4894 .sorted_by_key(|(range, _)| range.start);
4895 buffer.edit(edits, None, cx);
4896 })
4897 }
4898
4899 this.refresh_inline_completion(true, false, window, cx);
4900 });
4901
4902 let show_new_completions_on_confirm = completion
4903 .confirm
4904 .as_ref()
4905 .map_or(false, |confirm| confirm(intent, window, cx));
4906 if show_new_completions_on_confirm {
4907 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4908 }
4909
4910 let provider = self.completion_provider.as_ref()?;
4911 drop(completion);
4912 let apply_edits = provider.apply_additional_edits_for_completion(
4913 buffer_handle,
4914 completions_menu.completions.clone(),
4915 candidate_id,
4916 true,
4917 cx,
4918 );
4919
4920 let editor_settings = EditorSettings::get_global(cx);
4921 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4922 // After the code completion is finished, users often want to know what signatures are needed.
4923 // so we should automatically call signature_help
4924 self.show_signature_help(&ShowSignatureHelp, window, cx);
4925 }
4926
4927 Some(cx.foreground_executor().spawn(async move {
4928 apply_edits.await?;
4929 Ok(())
4930 }))
4931 }
4932
4933 pub fn toggle_code_actions(
4934 &mut self,
4935 action: &ToggleCodeActions,
4936 window: &mut Window,
4937 cx: &mut Context<Self>,
4938 ) {
4939 let mut context_menu = self.context_menu.borrow_mut();
4940 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4941 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4942 // Toggle if we're selecting the same one
4943 *context_menu = None;
4944 cx.notify();
4945 return;
4946 } else {
4947 // Otherwise, clear it and start a new one
4948 *context_menu = None;
4949 cx.notify();
4950 }
4951 }
4952 drop(context_menu);
4953 let snapshot = self.snapshot(window, cx);
4954 let deployed_from_indicator = action.deployed_from_indicator;
4955 let mut task = self.code_actions_task.take();
4956 let action = action.clone();
4957 cx.spawn_in(window, async move |editor, cx| {
4958 while let Some(prev_task) = task {
4959 prev_task.await.log_err();
4960 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4961 }
4962
4963 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4964 if editor.focus_handle.is_focused(window) {
4965 let multibuffer_point = action
4966 .deployed_from_indicator
4967 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4968 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4969 let (buffer, buffer_row) = snapshot
4970 .buffer_snapshot
4971 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4972 .and_then(|(buffer_snapshot, range)| {
4973 editor
4974 .buffer
4975 .read(cx)
4976 .buffer(buffer_snapshot.remote_id())
4977 .map(|buffer| (buffer, range.start.row))
4978 })?;
4979 let (_, code_actions) = editor
4980 .available_code_actions
4981 .clone()
4982 .and_then(|(location, code_actions)| {
4983 let snapshot = location.buffer.read(cx).snapshot();
4984 let point_range = location.range.to_point(&snapshot);
4985 let point_range = point_range.start.row..=point_range.end.row;
4986 if point_range.contains(&buffer_row) {
4987 Some((location, code_actions))
4988 } else {
4989 None
4990 }
4991 })
4992 .unzip();
4993 let buffer_id = buffer.read(cx).remote_id();
4994 let tasks = editor
4995 .tasks
4996 .get(&(buffer_id, buffer_row))
4997 .map(|t| Arc::new(t.to_owned()));
4998 if tasks.is_none() && code_actions.is_none() {
4999 return None;
5000 }
5001
5002 editor.completion_tasks.clear();
5003 editor.discard_inline_completion(false, cx);
5004 let task_context =
5005 tasks
5006 .as_ref()
5007 .zip(editor.project.clone())
5008 .map(|(tasks, project)| {
5009 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5010 });
5011
5012 let debugger_flag = cx.has_flag::<Debugger>();
5013
5014 Some(cx.spawn_in(window, async move |editor, cx| {
5015 let task_context = match task_context {
5016 Some(task_context) => task_context.await,
5017 None => None,
5018 };
5019 let resolved_tasks =
5020 tasks
5021 .zip(task_context)
5022 .map(|(tasks, task_context)| ResolvedTasks {
5023 templates: tasks.resolve(&task_context).collect(),
5024 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5025 multibuffer_point.row,
5026 tasks.column,
5027 )),
5028 });
5029 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
5030 tasks
5031 .templates
5032 .iter()
5033 .filter(|task| {
5034 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5035 debugger_flag
5036 } else {
5037 true
5038 }
5039 })
5040 .count()
5041 == 1
5042 }) && code_actions
5043 .as_ref()
5044 .map_or(true, |actions| actions.is_empty());
5045 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5046 *editor.context_menu.borrow_mut() =
5047 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5048 buffer,
5049 actions: CodeActionContents::new(
5050 resolved_tasks,
5051 code_actions,
5052 cx,
5053 ),
5054 selected_item: Default::default(),
5055 scroll_handle: UniformListScrollHandle::default(),
5056 deployed_from_indicator,
5057 }));
5058 if spawn_straight_away {
5059 if let Some(task) = editor.confirm_code_action(
5060 &ConfirmCodeAction { item_ix: Some(0) },
5061 window,
5062 cx,
5063 ) {
5064 cx.notify();
5065 return task;
5066 }
5067 }
5068 cx.notify();
5069 Task::ready(Ok(()))
5070 }) {
5071 task.await
5072 } else {
5073 Ok(())
5074 }
5075 }))
5076 } else {
5077 Some(Task::ready(Ok(())))
5078 }
5079 })?;
5080 if let Some(task) = spawned_test_task {
5081 task.await?;
5082 }
5083
5084 Ok::<_, anyhow::Error>(())
5085 })
5086 .detach_and_log_err(cx);
5087 }
5088
5089 pub fn confirm_code_action(
5090 &mut self,
5091 action: &ConfirmCodeAction,
5092 window: &mut Window,
5093 cx: &mut Context<Self>,
5094 ) -> Option<Task<Result<()>>> {
5095 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5096
5097 let actions_menu =
5098 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5099 menu
5100 } else {
5101 return None;
5102 };
5103
5104 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5105 let action = actions_menu.actions.get(action_ix)?;
5106 let title = action.label();
5107 let buffer = actions_menu.buffer;
5108 let workspace = self.workspace()?;
5109
5110 match action {
5111 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5112 match resolved_task.task_type() {
5113 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5114 workspace::tasks::schedule_resolved_task(
5115 workspace,
5116 task_source_kind,
5117 resolved_task,
5118 false,
5119 cx,
5120 );
5121
5122 Some(Task::ready(Ok(())))
5123 }),
5124 task::TaskType::Debug(debug_args) => {
5125 if debug_args.locator.is_some() {
5126 workspace.update(cx, |workspace, cx| {
5127 workspace::tasks::schedule_resolved_task(
5128 workspace,
5129 task_source_kind,
5130 resolved_task,
5131 false,
5132 cx,
5133 );
5134 });
5135
5136 return Some(Task::ready(Ok(())));
5137 }
5138
5139 if let Some(project) = self.project.as_ref() {
5140 project
5141 .update(cx, |project, cx| {
5142 project.start_debug_session(
5143 resolved_task.resolved_debug_adapter_config().unwrap(),
5144 cx,
5145 )
5146 })
5147 .detach_and_log_err(cx);
5148 Some(Task::ready(Ok(())))
5149 } else {
5150 Some(Task::ready(Ok(())))
5151 }
5152 }
5153 }
5154 }
5155 CodeActionsItem::CodeAction {
5156 excerpt_id,
5157 action,
5158 provider,
5159 } => {
5160 let apply_code_action =
5161 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5162 let workspace = workspace.downgrade();
5163 Some(cx.spawn_in(window, async move |editor, cx| {
5164 let project_transaction = apply_code_action.await?;
5165 Self::open_project_transaction(
5166 &editor,
5167 workspace,
5168 project_transaction,
5169 title,
5170 cx,
5171 )
5172 .await
5173 }))
5174 }
5175 }
5176 }
5177
5178 pub async fn open_project_transaction(
5179 this: &WeakEntity<Editor>,
5180 workspace: WeakEntity<Workspace>,
5181 transaction: ProjectTransaction,
5182 title: String,
5183 cx: &mut AsyncWindowContext,
5184 ) -> Result<()> {
5185 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5186 cx.update(|_, cx| {
5187 entries.sort_unstable_by_key(|(buffer, _)| {
5188 buffer.read(cx).file().map(|f| f.path().clone())
5189 });
5190 })?;
5191
5192 // If the project transaction's edits are all contained within this editor, then
5193 // avoid opening a new editor to display them.
5194
5195 if let Some((buffer, transaction)) = entries.first() {
5196 if entries.len() == 1 {
5197 let excerpt = this.update(cx, |editor, cx| {
5198 editor
5199 .buffer()
5200 .read(cx)
5201 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5202 })?;
5203 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5204 if excerpted_buffer == *buffer {
5205 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5206 let excerpt_range = excerpt_range.to_offset(buffer);
5207 buffer
5208 .edited_ranges_for_transaction::<usize>(transaction)
5209 .all(|range| {
5210 excerpt_range.start <= range.start
5211 && excerpt_range.end >= range.end
5212 })
5213 })?;
5214
5215 if all_edits_within_excerpt {
5216 return Ok(());
5217 }
5218 }
5219 }
5220 }
5221 } else {
5222 return Ok(());
5223 }
5224
5225 let mut ranges_to_highlight = Vec::new();
5226 let excerpt_buffer = cx.new(|cx| {
5227 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5228 for (buffer_handle, transaction) in &entries {
5229 let edited_ranges = buffer_handle
5230 .read(cx)
5231 .edited_ranges_for_transaction::<Point>(transaction)
5232 .collect::<Vec<_>>();
5233 let (ranges, _) = multibuffer.set_excerpts_for_path(
5234 PathKey::for_buffer(buffer_handle, cx),
5235 buffer_handle.clone(),
5236 edited_ranges,
5237 DEFAULT_MULTIBUFFER_CONTEXT,
5238 cx,
5239 );
5240
5241 ranges_to_highlight.extend(ranges);
5242 }
5243 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5244 multibuffer
5245 })?;
5246
5247 workspace.update_in(cx, |workspace, window, cx| {
5248 let project = workspace.project().clone();
5249 let editor =
5250 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5251 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5252 editor.update(cx, |editor, cx| {
5253 editor.highlight_background::<Self>(
5254 &ranges_to_highlight,
5255 |theme| theme.editor_highlighted_line_background,
5256 cx,
5257 );
5258 });
5259 })?;
5260
5261 Ok(())
5262 }
5263
5264 pub fn clear_code_action_providers(&mut self) {
5265 self.code_action_providers.clear();
5266 self.available_code_actions.take();
5267 }
5268
5269 pub fn add_code_action_provider(
5270 &mut self,
5271 provider: Rc<dyn CodeActionProvider>,
5272 window: &mut Window,
5273 cx: &mut Context<Self>,
5274 ) {
5275 if self
5276 .code_action_providers
5277 .iter()
5278 .any(|existing_provider| existing_provider.id() == provider.id())
5279 {
5280 return;
5281 }
5282
5283 self.code_action_providers.push(provider);
5284 self.refresh_code_actions(window, cx);
5285 }
5286
5287 pub fn remove_code_action_provider(
5288 &mut self,
5289 id: Arc<str>,
5290 window: &mut Window,
5291 cx: &mut Context<Self>,
5292 ) {
5293 self.code_action_providers
5294 .retain(|provider| provider.id() != id);
5295 self.refresh_code_actions(window, cx);
5296 }
5297
5298 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5299 let newest_selection = self.selections.newest_anchor().clone();
5300 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5301 let buffer = self.buffer.read(cx);
5302 if newest_selection.head().diff_base_anchor.is_some() {
5303 return None;
5304 }
5305 let (start_buffer, start) =
5306 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5307 let (end_buffer, end) =
5308 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5309 if start_buffer != end_buffer {
5310 return None;
5311 }
5312
5313 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5314 cx.background_executor()
5315 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5316 .await;
5317
5318 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5319 let providers = this.code_action_providers.clone();
5320 let tasks = this
5321 .code_action_providers
5322 .iter()
5323 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5324 .collect::<Vec<_>>();
5325 (providers, tasks)
5326 })?;
5327
5328 let mut actions = Vec::new();
5329 for (provider, provider_actions) in
5330 providers.into_iter().zip(future::join_all(tasks).await)
5331 {
5332 if let Some(provider_actions) = provider_actions.log_err() {
5333 actions.extend(provider_actions.into_iter().map(|action| {
5334 AvailableCodeAction {
5335 excerpt_id: newest_selection.start.excerpt_id,
5336 action,
5337 provider: provider.clone(),
5338 }
5339 }));
5340 }
5341 }
5342
5343 this.update(cx, |this, cx| {
5344 this.available_code_actions = if actions.is_empty() {
5345 None
5346 } else {
5347 Some((
5348 Location {
5349 buffer: start_buffer,
5350 range: start..end,
5351 },
5352 actions.into(),
5353 ))
5354 };
5355 cx.notify();
5356 })
5357 }));
5358 None
5359 }
5360
5361 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5362 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5363 self.show_git_blame_inline = false;
5364
5365 self.show_git_blame_inline_delay_task =
5366 Some(cx.spawn_in(window, async move |this, cx| {
5367 cx.background_executor().timer(delay).await;
5368
5369 this.update(cx, |this, cx| {
5370 this.show_git_blame_inline = true;
5371 cx.notify();
5372 })
5373 .log_err();
5374 }));
5375 }
5376 }
5377
5378 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5379 if self.pending_rename.is_some() {
5380 return None;
5381 }
5382
5383 let provider = self.semantics_provider.clone()?;
5384 let buffer = self.buffer.read(cx);
5385 let newest_selection = self.selections.newest_anchor().clone();
5386 let cursor_position = newest_selection.head();
5387 let (cursor_buffer, cursor_buffer_position) =
5388 buffer.text_anchor_for_position(cursor_position, cx)?;
5389 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5390 if cursor_buffer != tail_buffer {
5391 return None;
5392 }
5393 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5394 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5395 cx.background_executor()
5396 .timer(Duration::from_millis(debounce))
5397 .await;
5398
5399 let highlights = if let Some(highlights) = cx
5400 .update(|cx| {
5401 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5402 })
5403 .ok()
5404 .flatten()
5405 {
5406 highlights.await.log_err()
5407 } else {
5408 None
5409 };
5410
5411 if let Some(highlights) = highlights {
5412 this.update(cx, |this, cx| {
5413 if this.pending_rename.is_some() {
5414 return;
5415 }
5416
5417 let buffer_id = cursor_position.buffer_id;
5418 let buffer = this.buffer.read(cx);
5419 if !buffer
5420 .text_anchor_for_position(cursor_position, cx)
5421 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5422 {
5423 return;
5424 }
5425
5426 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5427 let mut write_ranges = Vec::new();
5428 let mut read_ranges = Vec::new();
5429 for highlight in highlights {
5430 for (excerpt_id, excerpt_range) in
5431 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5432 {
5433 let start = highlight
5434 .range
5435 .start
5436 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5437 let end = highlight
5438 .range
5439 .end
5440 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5441 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5442 continue;
5443 }
5444
5445 let range = Anchor {
5446 buffer_id,
5447 excerpt_id,
5448 text_anchor: start,
5449 diff_base_anchor: None,
5450 }..Anchor {
5451 buffer_id,
5452 excerpt_id,
5453 text_anchor: end,
5454 diff_base_anchor: None,
5455 };
5456 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5457 write_ranges.push(range);
5458 } else {
5459 read_ranges.push(range);
5460 }
5461 }
5462 }
5463
5464 this.highlight_background::<DocumentHighlightRead>(
5465 &read_ranges,
5466 |theme| theme.editor_document_highlight_read_background,
5467 cx,
5468 );
5469 this.highlight_background::<DocumentHighlightWrite>(
5470 &write_ranges,
5471 |theme| theme.editor_document_highlight_write_background,
5472 cx,
5473 );
5474 cx.notify();
5475 })
5476 .log_err();
5477 }
5478 }));
5479 None
5480 }
5481
5482 fn prepare_highlight_query_from_selection(
5483 &mut self,
5484 cx: &mut Context<Editor>,
5485 ) -> Option<(String, Range<Anchor>)> {
5486 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5487 return None;
5488 }
5489 if !EditorSettings::get_global(cx).selection_highlight {
5490 return None;
5491 }
5492 if self.selections.count() != 1 || self.selections.line_mode {
5493 return None;
5494 }
5495 let selection = self.selections.newest::<Point>(cx);
5496 if selection.is_empty() || selection.start.row != selection.end.row {
5497 return None;
5498 }
5499 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5500 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5501 let query = multi_buffer_snapshot
5502 .text_for_range(selection_anchor_range.clone())
5503 .collect::<String>();
5504 if query.trim().is_empty() {
5505 return None;
5506 }
5507 Some((query, selection_anchor_range))
5508 }
5509
5510 fn update_selection_occurrence_highlights(
5511 &mut self,
5512 query_text: String,
5513 query_range: Range<Anchor>,
5514 multi_buffer_range_to_query: Range<Point>,
5515 use_debounce: bool,
5516 window: &mut Window,
5517 cx: &mut Context<Editor>,
5518 ) -> Task<()> {
5519 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5520 cx.spawn_in(window, async move |editor, cx| {
5521 if use_debounce {
5522 cx.background_executor()
5523 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5524 .await;
5525 }
5526 let match_task = cx.background_spawn(async move {
5527 let buffer_ranges = multi_buffer_snapshot
5528 .range_to_buffer_ranges(multi_buffer_range_to_query)
5529 .into_iter()
5530 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5531 let mut match_ranges = Vec::new();
5532 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5533 match_ranges.extend(
5534 project::search::SearchQuery::text(
5535 query_text.clone(),
5536 false,
5537 false,
5538 false,
5539 Default::default(),
5540 Default::default(),
5541 false,
5542 None,
5543 )
5544 .unwrap()
5545 .search(&buffer_snapshot, Some(search_range.clone()))
5546 .await
5547 .into_iter()
5548 .filter_map(|match_range| {
5549 let match_start = buffer_snapshot
5550 .anchor_after(search_range.start + match_range.start);
5551 let match_end =
5552 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5553 let match_anchor_range = Anchor::range_in_buffer(
5554 excerpt_id,
5555 buffer_snapshot.remote_id(),
5556 match_start..match_end,
5557 );
5558 (match_anchor_range != query_range).then_some(match_anchor_range)
5559 }),
5560 );
5561 }
5562 match_ranges
5563 });
5564 let match_ranges = match_task.await;
5565 editor
5566 .update_in(cx, |editor, _, cx| {
5567 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5568 if !match_ranges.is_empty() {
5569 editor.highlight_background::<SelectedTextHighlight>(
5570 &match_ranges,
5571 |theme| theme.editor_document_highlight_bracket_background,
5572 cx,
5573 )
5574 }
5575 })
5576 .log_err();
5577 })
5578 }
5579
5580 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5581 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5582 else {
5583 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5584 self.quick_selection_highlight_task.take();
5585 self.debounced_selection_highlight_task.take();
5586 return;
5587 };
5588 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5589 if self
5590 .quick_selection_highlight_task
5591 .as_ref()
5592 .map_or(true, |(prev_anchor_range, _)| {
5593 prev_anchor_range != &query_range
5594 })
5595 {
5596 let multi_buffer_visible_start = self
5597 .scroll_manager
5598 .anchor()
5599 .anchor
5600 .to_point(&multi_buffer_snapshot);
5601 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5602 multi_buffer_visible_start
5603 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5604 Bias::Left,
5605 );
5606 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5607 self.quick_selection_highlight_task = Some((
5608 query_range.clone(),
5609 self.update_selection_occurrence_highlights(
5610 query_text.clone(),
5611 query_range.clone(),
5612 multi_buffer_visible_range,
5613 false,
5614 window,
5615 cx,
5616 ),
5617 ));
5618 }
5619 if self
5620 .debounced_selection_highlight_task
5621 .as_ref()
5622 .map_or(true, |(prev_anchor_range, _)| {
5623 prev_anchor_range != &query_range
5624 })
5625 {
5626 let multi_buffer_start = multi_buffer_snapshot
5627 .anchor_before(0)
5628 .to_point(&multi_buffer_snapshot);
5629 let multi_buffer_end = multi_buffer_snapshot
5630 .anchor_after(multi_buffer_snapshot.len())
5631 .to_point(&multi_buffer_snapshot);
5632 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5633 self.debounced_selection_highlight_task = Some((
5634 query_range.clone(),
5635 self.update_selection_occurrence_highlights(
5636 query_text,
5637 query_range,
5638 multi_buffer_full_range,
5639 true,
5640 window,
5641 cx,
5642 ),
5643 ));
5644 }
5645 }
5646
5647 pub fn refresh_inline_completion(
5648 &mut self,
5649 debounce: bool,
5650 user_requested: bool,
5651 window: &mut Window,
5652 cx: &mut Context<Self>,
5653 ) -> Option<()> {
5654 let provider = self.edit_prediction_provider()?;
5655 let cursor = self.selections.newest_anchor().head();
5656 let (buffer, cursor_buffer_position) =
5657 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5658
5659 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5660 self.discard_inline_completion(false, cx);
5661 return None;
5662 }
5663
5664 if !user_requested
5665 && (!self.should_show_edit_predictions()
5666 || !self.is_focused(window)
5667 || buffer.read(cx).is_empty())
5668 {
5669 self.discard_inline_completion(false, cx);
5670 return None;
5671 }
5672
5673 self.update_visible_inline_completion(window, cx);
5674 provider.refresh(
5675 self.project.clone(),
5676 buffer,
5677 cursor_buffer_position,
5678 debounce,
5679 cx,
5680 );
5681 Some(())
5682 }
5683
5684 fn show_edit_predictions_in_menu(&self) -> bool {
5685 match self.edit_prediction_settings {
5686 EditPredictionSettings::Disabled => false,
5687 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5688 }
5689 }
5690
5691 pub fn edit_predictions_enabled(&self) -> bool {
5692 match self.edit_prediction_settings {
5693 EditPredictionSettings::Disabled => false,
5694 EditPredictionSettings::Enabled { .. } => true,
5695 }
5696 }
5697
5698 fn edit_prediction_requires_modifier(&self) -> bool {
5699 match self.edit_prediction_settings {
5700 EditPredictionSettings::Disabled => false,
5701 EditPredictionSettings::Enabled {
5702 preview_requires_modifier,
5703 ..
5704 } => preview_requires_modifier,
5705 }
5706 }
5707
5708 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5709 if self.edit_prediction_provider.is_none() {
5710 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5711 } else {
5712 let selection = self.selections.newest_anchor();
5713 let cursor = selection.head();
5714
5715 if let Some((buffer, cursor_buffer_position)) =
5716 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5717 {
5718 self.edit_prediction_settings =
5719 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5720 }
5721 }
5722 }
5723
5724 fn edit_prediction_settings_at_position(
5725 &self,
5726 buffer: &Entity<Buffer>,
5727 buffer_position: language::Anchor,
5728 cx: &App,
5729 ) -> EditPredictionSettings {
5730 if !self.mode.is_full()
5731 || !self.show_inline_completions_override.unwrap_or(true)
5732 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5733 {
5734 return EditPredictionSettings::Disabled;
5735 }
5736
5737 let buffer = buffer.read(cx);
5738
5739 let file = buffer.file();
5740
5741 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5742 return EditPredictionSettings::Disabled;
5743 };
5744
5745 let by_provider = matches!(
5746 self.menu_inline_completions_policy,
5747 MenuInlineCompletionsPolicy::ByProvider
5748 );
5749
5750 let show_in_menu = by_provider
5751 && self
5752 .edit_prediction_provider
5753 .as_ref()
5754 .map_or(false, |provider| {
5755 provider.provider.show_completions_in_menu()
5756 });
5757
5758 let preview_requires_modifier =
5759 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5760
5761 EditPredictionSettings::Enabled {
5762 show_in_menu,
5763 preview_requires_modifier,
5764 }
5765 }
5766
5767 fn should_show_edit_predictions(&self) -> bool {
5768 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5769 }
5770
5771 pub fn edit_prediction_preview_is_active(&self) -> bool {
5772 matches!(
5773 self.edit_prediction_preview,
5774 EditPredictionPreview::Active { .. }
5775 )
5776 }
5777
5778 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5779 let cursor = self.selections.newest_anchor().head();
5780 if let Some((buffer, cursor_position)) =
5781 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5782 {
5783 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5784 } else {
5785 false
5786 }
5787 }
5788
5789 fn edit_predictions_enabled_in_buffer(
5790 &self,
5791 buffer: &Entity<Buffer>,
5792 buffer_position: language::Anchor,
5793 cx: &App,
5794 ) -> bool {
5795 maybe!({
5796 if self.read_only(cx) {
5797 return Some(false);
5798 }
5799 let provider = self.edit_prediction_provider()?;
5800 if !provider.is_enabled(&buffer, buffer_position, cx) {
5801 return Some(false);
5802 }
5803 let buffer = buffer.read(cx);
5804 let Some(file) = buffer.file() else {
5805 return Some(true);
5806 };
5807 let settings = all_language_settings(Some(file), cx);
5808 Some(settings.edit_predictions_enabled_for_file(file, cx))
5809 })
5810 .unwrap_or(false)
5811 }
5812
5813 fn cycle_inline_completion(
5814 &mut self,
5815 direction: Direction,
5816 window: &mut Window,
5817 cx: &mut Context<Self>,
5818 ) -> Option<()> {
5819 let provider = self.edit_prediction_provider()?;
5820 let cursor = self.selections.newest_anchor().head();
5821 let (buffer, cursor_buffer_position) =
5822 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5823 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5824 return None;
5825 }
5826
5827 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5828 self.update_visible_inline_completion(window, cx);
5829
5830 Some(())
5831 }
5832
5833 pub fn show_inline_completion(
5834 &mut self,
5835 _: &ShowEditPrediction,
5836 window: &mut Window,
5837 cx: &mut Context<Self>,
5838 ) {
5839 if !self.has_active_inline_completion() {
5840 self.refresh_inline_completion(false, true, window, cx);
5841 return;
5842 }
5843
5844 self.update_visible_inline_completion(window, cx);
5845 }
5846
5847 pub fn display_cursor_names(
5848 &mut self,
5849 _: &DisplayCursorNames,
5850 window: &mut Window,
5851 cx: &mut Context<Self>,
5852 ) {
5853 self.show_cursor_names(window, cx);
5854 }
5855
5856 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5857 self.show_cursor_names = true;
5858 cx.notify();
5859 cx.spawn_in(window, async move |this, cx| {
5860 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5861 this.update(cx, |this, cx| {
5862 this.show_cursor_names = false;
5863 cx.notify()
5864 })
5865 .ok()
5866 })
5867 .detach();
5868 }
5869
5870 pub fn next_edit_prediction(
5871 &mut self,
5872 _: &NextEditPrediction,
5873 window: &mut Window,
5874 cx: &mut Context<Self>,
5875 ) {
5876 if self.has_active_inline_completion() {
5877 self.cycle_inline_completion(Direction::Next, window, cx);
5878 } else {
5879 let is_copilot_disabled = self
5880 .refresh_inline_completion(false, true, window, cx)
5881 .is_none();
5882 if is_copilot_disabled {
5883 cx.propagate();
5884 }
5885 }
5886 }
5887
5888 pub fn previous_edit_prediction(
5889 &mut self,
5890 _: &PreviousEditPrediction,
5891 window: &mut Window,
5892 cx: &mut Context<Self>,
5893 ) {
5894 if self.has_active_inline_completion() {
5895 self.cycle_inline_completion(Direction::Prev, window, cx);
5896 } else {
5897 let is_copilot_disabled = self
5898 .refresh_inline_completion(false, true, window, cx)
5899 .is_none();
5900 if is_copilot_disabled {
5901 cx.propagate();
5902 }
5903 }
5904 }
5905
5906 pub fn accept_edit_prediction(
5907 &mut self,
5908 _: &AcceptEditPrediction,
5909 window: &mut Window,
5910 cx: &mut Context<Self>,
5911 ) {
5912 if self.show_edit_predictions_in_menu() {
5913 self.hide_context_menu(window, cx);
5914 }
5915
5916 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5917 return;
5918 };
5919
5920 self.report_inline_completion_event(
5921 active_inline_completion.completion_id.clone(),
5922 true,
5923 cx,
5924 );
5925
5926 match &active_inline_completion.completion {
5927 InlineCompletion::Move { target, .. } => {
5928 let target = *target;
5929
5930 if let Some(position_map) = &self.last_position_map {
5931 if position_map
5932 .visible_row_range
5933 .contains(&target.to_display_point(&position_map.snapshot).row())
5934 || !self.edit_prediction_requires_modifier()
5935 {
5936 self.unfold_ranges(&[target..target], true, false, cx);
5937 // Note that this is also done in vim's handler of the Tab action.
5938 self.change_selections(
5939 Some(Autoscroll::newest()),
5940 window,
5941 cx,
5942 |selections| {
5943 selections.select_anchor_ranges([target..target]);
5944 },
5945 );
5946 self.clear_row_highlights::<EditPredictionPreview>();
5947
5948 self.edit_prediction_preview
5949 .set_previous_scroll_position(None);
5950 } else {
5951 self.edit_prediction_preview
5952 .set_previous_scroll_position(Some(
5953 position_map.snapshot.scroll_anchor,
5954 ));
5955
5956 self.highlight_rows::<EditPredictionPreview>(
5957 target..target,
5958 cx.theme().colors().editor_highlighted_line_background,
5959 true,
5960 cx,
5961 );
5962 self.request_autoscroll(Autoscroll::fit(), cx);
5963 }
5964 }
5965 }
5966 InlineCompletion::Edit { edits, .. } => {
5967 if let Some(provider) = self.edit_prediction_provider() {
5968 provider.accept(cx);
5969 }
5970
5971 let snapshot = self.buffer.read(cx).snapshot(cx);
5972 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5973
5974 self.buffer.update(cx, |buffer, cx| {
5975 buffer.edit(edits.iter().cloned(), None, cx)
5976 });
5977
5978 self.change_selections(None, window, cx, |s| {
5979 s.select_anchor_ranges([last_edit_end..last_edit_end])
5980 });
5981
5982 self.update_visible_inline_completion(window, cx);
5983 if self.active_inline_completion.is_none() {
5984 self.refresh_inline_completion(true, true, window, cx);
5985 }
5986
5987 cx.notify();
5988 }
5989 }
5990
5991 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5992 }
5993
5994 pub fn accept_partial_inline_completion(
5995 &mut self,
5996 _: &AcceptPartialEditPrediction,
5997 window: &mut Window,
5998 cx: &mut Context<Self>,
5999 ) {
6000 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6001 return;
6002 };
6003 if self.selections.count() != 1 {
6004 return;
6005 }
6006
6007 self.report_inline_completion_event(
6008 active_inline_completion.completion_id.clone(),
6009 true,
6010 cx,
6011 );
6012
6013 match &active_inline_completion.completion {
6014 InlineCompletion::Move { target, .. } => {
6015 let target = *target;
6016 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6017 selections.select_anchor_ranges([target..target]);
6018 });
6019 }
6020 InlineCompletion::Edit { edits, .. } => {
6021 // Find an insertion that starts at the cursor position.
6022 let snapshot = self.buffer.read(cx).snapshot(cx);
6023 let cursor_offset = self.selections.newest::<usize>(cx).head();
6024 let insertion = edits.iter().find_map(|(range, text)| {
6025 let range = range.to_offset(&snapshot);
6026 if range.is_empty() && range.start == cursor_offset {
6027 Some(text)
6028 } else {
6029 None
6030 }
6031 });
6032
6033 if let Some(text) = insertion {
6034 let mut partial_completion = text
6035 .chars()
6036 .by_ref()
6037 .take_while(|c| c.is_alphabetic())
6038 .collect::<String>();
6039 if partial_completion.is_empty() {
6040 partial_completion = text
6041 .chars()
6042 .by_ref()
6043 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6044 .collect::<String>();
6045 }
6046
6047 cx.emit(EditorEvent::InputHandled {
6048 utf16_range_to_replace: None,
6049 text: partial_completion.clone().into(),
6050 });
6051
6052 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6053
6054 self.refresh_inline_completion(true, true, window, cx);
6055 cx.notify();
6056 } else {
6057 self.accept_edit_prediction(&Default::default(), window, cx);
6058 }
6059 }
6060 }
6061 }
6062
6063 fn discard_inline_completion(
6064 &mut self,
6065 should_report_inline_completion_event: bool,
6066 cx: &mut Context<Self>,
6067 ) -> bool {
6068 if should_report_inline_completion_event {
6069 let completion_id = self
6070 .active_inline_completion
6071 .as_ref()
6072 .and_then(|active_completion| active_completion.completion_id.clone());
6073
6074 self.report_inline_completion_event(completion_id, false, cx);
6075 }
6076
6077 if let Some(provider) = self.edit_prediction_provider() {
6078 provider.discard(cx);
6079 }
6080
6081 self.take_active_inline_completion(cx)
6082 }
6083
6084 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6085 let Some(provider) = self.edit_prediction_provider() else {
6086 return;
6087 };
6088
6089 let Some((_, buffer, _)) = self
6090 .buffer
6091 .read(cx)
6092 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6093 else {
6094 return;
6095 };
6096
6097 let extension = buffer
6098 .read(cx)
6099 .file()
6100 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6101
6102 let event_type = match accepted {
6103 true => "Edit Prediction Accepted",
6104 false => "Edit Prediction Discarded",
6105 };
6106 telemetry::event!(
6107 event_type,
6108 provider = provider.name(),
6109 prediction_id = id,
6110 suggestion_accepted = accepted,
6111 file_extension = extension,
6112 );
6113 }
6114
6115 pub fn has_active_inline_completion(&self) -> bool {
6116 self.active_inline_completion.is_some()
6117 }
6118
6119 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6120 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6121 return false;
6122 };
6123
6124 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6125 self.clear_highlights::<InlineCompletionHighlight>(cx);
6126 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6127 true
6128 }
6129
6130 /// Returns true when we're displaying the edit prediction popover below the cursor
6131 /// like we are not previewing and the LSP autocomplete menu is visible
6132 /// or we are in `when_holding_modifier` mode.
6133 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6134 if self.edit_prediction_preview_is_active()
6135 || !self.show_edit_predictions_in_menu()
6136 || !self.edit_predictions_enabled()
6137 {
6138 return false;
6139 }
6140
6141 if self.has_visible_completions_menu() {
6142 return true;
6143 }
6144
6145 has_completion && self.edit_prediction_requires_modifier()
6146 }
6147
6148 fn handle_modifiers_changed(
6149 &mut self,
6150 modifiers: Modifiers,
6151 position_map: &PositionMap,
6152 window: &mut Window,
6153 cx: &mut Context<Self>,
6154 ) {
6155 if self.show_edit_predictions_in_menu() {
6156 self.update_edit_prediction_preview(&modifiers, window, cx);
6157 }
6158
6159 self.update_selection_mode(&modifiers, position_map, window, cx);
6160
6161 let mouse_position = window.mouse_position();
6162 if !position_map.text_hitbox.is_hovered(window) {
6163 return;
6164 }
6165
6166 self.update_hovered_link(
6167 position_map.point_for_position(mouse_position),
6168 &position_map.snapshot,
6169 modifiers,
6170 window,
6171 cx,
6172 )
6173 }
6174
6175 fn update_selection_mode(
6176 &mut self,
6177 modifiers: &Modifiers,
6178 position_map: &PositionMap,
6179 window: &mut Window,
6180 cx: &mut Context<Self>,
6181 ) {
6182 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6183 return;
6184 }
6185
6186 let mouse_position = window.mouse_position();
6187 let point_for_position = position_map.point_for_position(mouse_position);
6188 let position = point_for_position.previous_valid;
6189
6190 self.select(
6191 SelectPhase::BeginColumnar {
6192 position,
6193 reset: false,
6194 goal_column: point_for_position.exact_unclipped.column(),
6195 },
6196 window,
6197 cx,
6198 );
6199 }
6200
6201 fn update_edit_prediction_preview(
6202 &mut self,
6203 modifiers: &Modifiers,
6204 window: &mut Window,
6205 cx: &mut Context<Self>,
6206 ) {
6207 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6208 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6209 return;
6210 };
6211
6212 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6213 if matches!(
6214 self.edit_prediction_preview,
6215 EditPredictionPreview::Inactive { .. }
6216 ) {
6217 self.edit_prediction_preview = EditPredictionPreview::Active {
6218 previous_scroll_position: None,
6219 since: Instant::now(),
6220 };
6221
6222 self.update_visible_inline_completion(window, cx);
6223 cx.notify();
6224 }
6225 } else if let EditPredictionPreview::Active {
6226 previous_scroll_position,
6227 since,
6228 } = self.edit_prediction_preview
6229 {
6230 if let (Some(previous_scroll_position), Some(position_map)) =
6231 (previous_scroll_position, self.last_position_map.as_ref())
6232 {
6233 self.set_scroll_position(
6234 previous_scroll_position
6235 .scroll_position(&position_map.snapshot.display_snapshot),
6236 window,
6237 cx,
6238 );
6239 }
6240
6241 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6242 released_too_fast: since.elapsed() < Duration::from_millis(200),
6243 };
6244 self.clear_row_highlights::<EditPredictionPreview>();
6245 self.update_visible_inline_completion(window, cx);
6246 cx.notify();
6247 }
6248 }
6249
6250 fn update_visible_inline_completion(
6251 &mut self,
6252 _window: &mut Window,
6253 cx: &mut Context<Self>,
6254 ) -> Option<()> {
6255 let selection = self.selections.newest_anchor();
6256 let cursor = selection.head();
6257 let multibuffer = self.buffer.read(cx).snapshot(cx);
6258 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6259 let excerpt_id = cursor.excerpt_id;
6260
6261 let show_in_menu = self.show_edit_predictions_in_menu();
6262 let completions_menu_has_precedence = !show_in_menu
6263 && (self.context_menu.borrow().is_some()
6264 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6265
6266 if completions_menu_has_precedence
6267 || !offset_selection.is_empty()
6268 || self
6269 .active_inline_completion
6270 .as_ref()
6271 .map_or(false, |completion| {
6272 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6273 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6274 !invalidation_range.contains(&offset_selection.head())
6275 })
6276 {
6277 self.discard_inline_completion(false, cx);
6278 return None;
6279 }
6280
6281 self.take_active_inline_completion(cx);
6282 let Some(provider) = self.edit_prediction_provider() else {
6283 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6284 return None;
6285 };
6286
6287 let (buffer, cursor_buffer_position) =
6288 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6289
6290 self.edit_prediction_settings =
6291 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6292
6293 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6294
6295 if self.edit_prediction_indent_conflict {
6296 let cursor_point = cursor.to_point(&multibuffer);
6297
6298 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6299
6300 if let Some((_, indent)) = indents.iter().next() {
6301 if indent.len == cursor_point.column {
6302 self.edit_prediction_indent_conflict = false;
6303 }
6304 }
6305 }
6306
6307 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6308 let edits = inline_completion
6309 .edits
6310 .into_iter()
6311 .flat_map(|(range, new_text)| {
6312 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6313 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6314 Some((start..end, new_text))
6315 })
6316 .collect::<Vec<_>>();
6317 if edits.is_empty() {
6318 return None;
6319 }
6320
6321 let first_edit_start = edits.first().unwrap().0.start;
6322 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6323 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6324
6325 let last_edit_end = edits.last().unwrap().0.end;
6326 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6327 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6328
6329 let cursor_row = cursor.to_point(&multibuffer).row;
6330
6331 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6332
6333 let mut inlay_ids = Vec::new();
6334 let invalidation_row_range;
6335 let move_invalidation_row_range = if cursor_row < edit_start_row {
6336 Some(cursor_row..edit_end_row)
6337 } else if cursor_row > edit_end_row {
6338 Some(edit_start_row..cursor_row)
6339 } else {
6340 None
6341 };
6342 let is_move =
6343 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6344 let completion = if is_move {
6345 invalidation_row_range =
6346 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6347 let target = first_edit_start;
6348 InlineCompletion::Move { target, snapshot }
6349 } else {
6350 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6351 && !self.inline_completions_hidden_for_vim_mode;
6352
6353 if show_completions_in_buffer {
6354 if edits
6355 .iter()
6356 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6357 {
6358 let mut inlays = Vec::new();
6359 for (range, new_text) in &edits {
6360 let inlay = Inlay::inline_completion(
6361 post_inc(&mut self.next_inlay_id),
6362 range.start,
6363 new_text.as_str(),
6364 );
6365 inlay_ids.push(inlay.id);
6366 inlays.push(inlay);
6367 }
6368
6369 self.splice_inlays(&[], inlays, cx);
6370 } else {
6371 let background_color = cx.theme().status().deleted_background;
6372 self.highlight_text::<InlineCompletionHighlight>(
6373 edits.iter().map(|(range, _)| range.clone()).collect(),
6374 HighlightStyle {
6375 background_color: Some(background_color),
6376 ..Default::default()
6377 },
6378 cx,
6379 );
6380 }
6381 }
6382
6383 invalidation_row_range = edit_start_row..edit_end_row;
6384
6385 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6386 if provider.show_tab_accept_marker() {
6387 EditDisplayMode::TabAccept
6388 } else {
6389 EditDisplayMode::Inline
6390 }
6391 } else {
6392 EditDisplayMode::DiffPopover
6393 };
6394
6395 InlineCompletion::Edit {
6396 edits,
6397 edit_preview: inline_completion.edit_preview,
6398 display_mode,
6399 snapshot,
6400 }
6401 };
6402
6403 let invalidation_range = multibuffer
6404 .anchor_before(Point::new(invalidation_row_range.start, 0))
6405 ..multibuffer.anchor_after(Point::new(
6406 invalidation_row_range.end,
6407 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6408 ));
6409
6410 self.stale_inline_completion_in_menu = None;
6411 self.active_inline_completion = Some(InlineCompletionState {
6412 inlay_ids,
6413 completion,
6414 completion_id: inline_completion.id,
6415 invalidation_range,
6416 });
6417
6418 cx.notify();
6419
6420 Some(())
6421 }
6422
6423 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6424 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6425 }
6426
6427 fn render_code_actions_indicator(
6428 &self,
6429 _style: &EditorStyle,
6430 row: DisplayRow,
6431 is_active: bool,
6432 breakpoint: Option<&(Anchor, Breakpoint)>,
6433 cx: &mut Context<Self>,
6434 ) -> Option<IconButton> {
6435 let color = Color::Muted;
6436 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6437 let show_tooltip = !self.context_menu_visible();
6438
6439 if self.available_code_actions.is_some() {
6440 Some(
6441 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6442 .shape(ui::IconButtonShape::Square)
6443 .icon_size(IconSize::XSmall)
6444 .icon_color(color)
6445 .toggle_state(is_active)
6446 .when(show_tooltip, |this| {
6447 this.tooltip({
6448 let focus_handle = self.focus_handle.clone();
6449 move |window, cx| {
6450 Tooltip::for_action_in(
6451 "Toggle Code Actions",
6452 &ToggleCodeActions {
6453 deployed_from_indicator: None,
6454 },
6455 &focus_handle,
6456 window,
6457 cx,
6458 )
6459 }
6460 })
6461 })
6462 .on_click(cx.listener(move |editor, _e, window, cx| {
6463 window.focus(&editor.focus_handle(cx));
6464 editor.toggle_code_actions(
6465 &ToggleCodeActions {
6466 deployed_from_indicator: Some(row),
6467 },
6468 window,
6469 cx,
6470 );
6471 }))
6472 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6473 editor.set_breakpoint_context_menu(
6474 row,
6475 position,
6476 event.down.position,
6477 window,
6478 cx,
6479 );
6480 })),
6481 )
6482 } else {
6483 None
6484 }
6485 }
6486
6487 fn clear_tasks(&mut self) {
6488 self.tasks.clear()
6489 }
6490
6491 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6492 if self.tasks.insert(key, value).is_some() {
6493 // This case should hopefully be rare, but just in case...
6494 log::error!(
6495 "multiple different run targets found on a single line, only the last target will be rendered"
6496 )
6497 }
6498 }
6499
6500 /// Get all display points of breakpoints that will be rendered within editor
6501 ///
6502 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6503 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6504 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6505 fn active_breakpoints(
6506 &self,
6507 range: Range<DisplayRow>,
6508 window: &mut Window,
6509 cx: &mut Context<Self>,
6510 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6511 let mut breakpoint_display_points = HashMap::default();
6512
6513 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6514 return breakpoint_display_points;
6515 };
6516
6517 let snapshot = self.snapshot(window, cx);
6518
6519 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6520 let Some(project) = self.project.as_ref() else {
6521 return breakpoint_display_points;
6522 };
6523
6524 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6525 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6526
6527 for (buffer_snapshot, range, excerpt_id) in
6528 multi_buffer_snapshot.range_to_buffer_ranges(range)
6529 {
6530 let Some(buffer) = project.read_with(cx, |this, cx| {
6531 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6532 }) else {
6533 continue;
6534 };
6535 let breakpoints = breakpoint_store.read(cx).breakpoints(
6536 &buffer,
6537 Some(
6538 buffer_snapshot.anchor_before(range.start)
6539 ..buffer_snapshot.anchor_after(range.end),
6540 ),
6541 buffer_snapshot,
6542 cx,
6543 );
6544 for (anchor, breakpoint) in breakpoints {
6545 let multi_buffer_anchor =
6546 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6547 let position = multi_buffer_anchor
6548 .to_point(&multi_buffer_snapshot)
6549 .to_display_point(&snapshot);
6550
6551 breakpoint_display_points
6552 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6553 }
6554 }
6555
6556 breakpoint_display_points
6557 }
6558
6559 fn breakpoint_context_menu(
6560 &self,
6561 anchor: Anchor,
6562 window: &mut Window,
6563 cx: &mut Context<Self>,
6564 ) -> Entity<ui::ContextMenu> {
6565 let weak_editor = cx.weak_entity();
6566 let focus_handle = self.focus_handle(cx);
6567
6568 let row = self
6569 .buffer
6570 .read(cx)
6571 .snapshot(cx)
6572 .summary_for_anchor::<Point>(&anchor)
6573 .row;
6574
6575 let breakpoint = self
6576 .breakpoint_at_row(row, window, cx)
6577 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6578
6579 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6580 "Edit Log Breakpoint"
6581 } else {
6582 "Set Log Breakpoint"
6583 };
6584
6585 let condition_breakpoint_msg = if breakpoint
6586 .as_ref()
6587 .is_some_and(|bp| bp.1.condition.is_some())
6588 {
6589 "Edit Condition Breakpoint"
6590 } else {
6591 "Set Condition Breakpoint"
6592 };
6593
6594 let hit_condition_breakpoint_msg = if breakpoint
6595 .as_ref()
6596 .is_some_and(|bp| bp.1.hit_condition.is_some())
6597 {
6598 "Edit Hit Condition Breakpoint"
6599 } else {
6600 "Set Hit Condition Breakpoint"
6601 };
6602
6603 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6604 "Unset Breakpoint"
6605 } else {
6606 "Set Breakpoint"
6607 };
6608
6609 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6610 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6611
6612 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6613 BreakpointState::Enabled => Some("Disable"),
6614 BreakpointState::Disabled => Some("Enable"),
6615 });
6616
6617 let (anchor, breakpoint) =
6618 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6619
6620 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6621 menu.on_blur_subscription(Subscription::new(|| {}))
6622 .context(focus_handle)
6623 .when(run_to_cursor, |this| {
6624 let weak_editor = weak_editor.clone();
6625 this.entry("Run to cursor", None, move |window, cx| {
6626 weak_editor
6627 .update(cx, |editor, cx| {
6628 editor.change_selections(None, window, cx, |s| {
6629 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6630 });
6631 })
6632 .ok();
6633
6634 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6635 })
6636 .separator()
6637 })
6638 .when_some(toggle_state_msg, |this, msg| {
6639 this.entry(msg, None, {
6640 let weak_editor = weak_editor.clone();
6641 let breakpoint = breakpoint.clone();
6642 move |_window, cx| {
6643 weak_editor
6644 .update(cx, |this, cx| {
6645 this.edit_breakpoint_at_anchor(
6646 anchor,
6647 breakpoint.as_ref().clone(),
6648 BreakpointEditAction::InvertState,
6649 cx,
6650 );
6651 })
6652 .log_err();
6653 }
6654 })
6655 })
6656 .entry(set_breakpoint_msg, None, {
6657 let weak_editor = weak_editor.clone();
6658 let breakpoint = breakpoint.clone();
6659 move |_window, cx| {
6660 weak_editor
6661 .update(cx, |this, cx| {
6662 this.edit_breakpoint_at_anchor(
6663 anchor,
6664 breakpoint.as_ref().clone(),
6665 BreakpointEditAction::Toggle,
6666 cx,
6667 );
6668 })
6669 .log_err();
6670 }
6671 })
6672 .entry(log_breakpoint_msg, None, {
6673 let breakpoint = breakpoint.clone();
6674 let weak_editor = weak_editor.clone();
6675 move |window, cx| {
6676 weak_editor
6677 .update(cx, |this, cx| {
6678 this.add_edit_breakpoint_block(
6679 anchor,
6680 breakpoint.as_ref(),
6681 BreakpointPromptEditAction::Log,
6682 window,
6683 cx,
6684 );
6685 })
6686 .log_err();
6687 }
6688 })
6689 .entry(condition_breakpoint_msg, None, {
6690 let breakpoint = breakpoint.clone();
6691 let weak_editor = weak_editor.clone();
6692 move |window, cx| {
6693 weak_editor
6694 .update(cx, |this, cx| {
6695 this.add_edit_breakpoint_block(
6696 anchor,
6697 breakpoint.as_ref(),
6698 BreakpointPromptEditAction::Condition,
6699 window,
6700 cx,
6701 );
6702 })
6703 .log_err();
6704 }
6705 })
6706 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6707 weak_editor
6708 .update(cx, |this, cx| {
6709 this.add_edit_breakpoint_block(
6710 anchor,
6711 breakpoint.as_ref(),
6712 BreakpointPromptEditAction::HitCondition,
6713 window,
6714 cx,
6715 );
6716 })
6717 .log_err();
6718 })
6719 })
6720 }
6721
6722 fn render_breakpoint(
6723 &self,
6724 position: Anchor,
6725 row: DisplayRow,
6726 breakpoint: &Breakpoint,
6727 cx: &mut Context<Self>,
6728 ) -> IconButton {
6729 let (color, icon) = {
6730 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6731 (false, false) => ui::IconName::DebugBreakpoint,
6732 (true, false) => ui::IconName::DebugLogBreakpoint,
6733 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6734 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6735 };
6736
6737 let color = if self
6738 .gutter_breakpoint_indicator
6739 .0
6740 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6741 {
6742 Color::Hint
6743 } else {
6744 Color::Debugger
6745 };
6746
6747 (color, icon)
6748 };
6749
6750 let breakpoint = Arc::from(breakpoint.clone());
6751
6752 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6753 .icon_size(IconSize::XSmall)
6754 .size(ui::ButtonSize::None)
6755 .icon_color(color)
6756 .style(ButtonStyle::Transparent)
6757 .on_click(cx.listener({
6758 let breakpoint = breakpoint.clone();
6759
6760 move |editor, event: &ClickEvent, window, cx| {
6761 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6762 BreakpointEditAction::InvertState
6763 } else {
6764 BreakpointEditAction::Toggle
6765 };
6766
6767 window.focus(&editor.focus_handle(cx));
6768 editor.edit_breakpoint_at_anchor(
6769 position,
6770 breakpoint.as_ref().clone(),
6771 edit_action,
6772 cx,
6773 );
6774 }
6775 }))
6776 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6777 editor.set_breakpoint_context_menu(
6778 row,
6779 Some(position),
6780 event.down.position,
6781 window,
6782 cx,
6783 );
6784 }))
6785 }
6786
6787 fn build_tasks_context(
6788 project: &Entity<Project>,
6789 buffer: &Entity<Buffer>,
6790 buffer_row: u32,
6791 tasks: &Arc<RunnableTasks>,
6792 cx: &mut Context<Self>,
6793 ) -> Task<Option<task::TaskContext>> {
6794 let position = Point::new(buffer_row, tasks.column);
6795 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6796 let location = Location {
6797 buffer: buffer.clone(),
6798 range: range_start..range_start,
6799 };
6800 // Fill in the environmental variables from the tree-sitter captures
6801 let mut captured_task_variables = TaskVariables::default();
6802 for (capture_name, value) in tasks.extra_variables.clone() {
6803 captured_task_variables.insert(
6804 task::VariableName::Custom(capture_name.into()),
6805 value.clone(),
6806 );
6807 }
6808 project.update(cx, |project, cx| {
6809 project.task_store().update(cx, |task_store, cx| {
6810 task_store.task_context_for_location(captured_task_variables, location, cx)
6811 })
6812 })
6813 }
6814
6815 pub fn spawn_nearest_task(
6816 &mut self,
6817 action: &SpawnNearestTask,
6818 window: &mut Window,
6819 cx: &mut Context<Self>,
6820 ) {
6821 let Some((workspace, _)) = self.workspace.clone() else {
6822 return;
6823 };
6824 let Some(project) = self.project.clone() else {
6825 return;
6826 };
6827
6828 // Try to find a closest, enclosing node using tree-sitter that has a
6829 // task
6830 let Some((buffer, buffer_row, tasks)) = self
6831 .find_enclosing_node_task(cx)
6832 // Or find the task that's closest in row-distance.
6833 .or_else(|| self.find_closest_task(cx))
6834 else {
6835 return;
6836 };
6837
6838 let reveal_strategy = action.reveal;
6839 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6840 cx.spawn_in(window, async move |_, cx| {
6841 let context = task_context.await?;
6842 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6843
6844 let resolved = resolved_task.resolved.as_mut()?;
6845 resolved.reveal = reveal_strategy;
6846
6847 workspace
6848 .update(cx, |workspace, cx| {
6849 workspace::tasks::schedule_resolved_task(
6850 workspace,
6851 task_source_kind,
6852 resolved_task,
6853 false,
6854 cx,
6855 );
6856 })
6857 .ok()
6858 })
6859 .detach();
6860 }
6861
6862 fn find_closest_task(
6863 &mut self,
6864 cx: &mut Context<Self>,
6865 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6866 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6867
6868 let ((buffer_id, row), tasks) = self
6869 .tasks
6870 .iter()
6871 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6872
6873 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6874 let tasks = Arc::new(tasks.to_owned());
6875 Some((buffer, *row, tasks))
6876 }
6877
6878 fn find_enclosing_node_task(
6879 &mut self,
6880 cx: &mut Context<Self>,
6881 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6882 let snapshot = self.buffer.read(cx).snapshot(cx);
6883 let offset = self.selections.newest::<usize>(cx).head();
6884 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6885 let buffer_id = excerpt.buffer().remote_id();
6886
6887 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6888 let mut cursor = layer.node().walk();
6889
6890 while cursor.goto_first_child_for_byte(offset).is_some() {
6891 if cursor.node().end_byte() == offset {
6892 cursor.goto_next_sibling();
6893 }
6894 }
6895
6896 // Ascend to the smallest ancestor that contains the range and has a task.
6897 loop {
6898 let node = cursor.node();
6899 let node_range = node.byte_range();
6900 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6901
6902 // Check if this node contains our offset
6903 if node_range.start <= offset && node_range.end >= offset {
6904 // If it contains offset, check for task
6905 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6906 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6907 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6908 }
6909 }
6910
6911 if !cursor.goto_parent() {
6912 break;
6913 }
6914 }
6915 None
6916 }
6917
6918 fn render_run_indicator(
6919 &self,
6920 _style: &EditorStyle,
6921 is_active: bool,
6922 row: DisplayRow,
6923 breakpoint: Option<(Anchor, Breakpoint)>,
6924 cx: &mut Context<Self>,
6925 ) -> IconButton {
6926 let color = Color::Muted;
6927 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6928
6929 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6930 .shape(ui::IconButtonShape::Square)
6931 .icon_size(IconSize::XSmall)
6932 .icon_color(color)
6933 .toggle_state(is_active)
6934 .on_click(cx.listener(move |editor, _e, window, cx| {
6935 window.focus(&editor.focus_handle(cx));
6936 editor.toggle_code_actions(
6937 &ToggleCodeActions {
6938 deployed_from_indicator: Some(row),
6939 },
6940 window,
6941 cx,
6942 );
6943 }))
6944 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6945 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6946 }))
6947 }
6948
6949 pub fn context_menu_visible(&self) -> bool {
6950 !self.edit_prediction_preview_is_active()
6951 && self
6952 .context_menu
6953 .borrow()
6954 .as_ref()
6955 .map_or(false, |menu| menu.visible())
6956 }
6957
6958 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6959 self.context_menu
6960 .borrow()
6961 .as_ref()
6962 .map(|menu| menu.origin())
6963 }
6964
6965 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6966 self.context_menu_options = Some(options);
6967 }
6968
6969 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6970 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6971
6972 fn render_edit_prediction_popover(
6973 &mut self,
6974 text_bounds: &Bounds<Pixels>,
6975 content_origin: gpui::Point<Pixels>,
6976 editor_snapshot: &EditorSnapshot,
6977 visible_row_range: Range<DisplayRow>,
6978 scroll_top: f32,
6979 scroll_bottom: f32,
6980 line_layouts: &[LineWithInvisibles],
6981 line_height: Pixels,
6982 scroll_pixel_position: gpui::Point<Pixels>,
6983 newest_selection_head: Option<DisplayPoint>,
6984 editor_width: Pixels,
6985 style: &EditorStyle,
6986 window: &mut Window,
6987 cx: &mut App,
6988 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6989 let active_inline_completion = self.active_inline_completion.as_ref()?;
6990
6991 if self.edit_prediction_visible_in_cursor_popover(true) {
6992 return None;
6993 }
6994
6995 match &active_inline_completion.completion {
6996 InlineCompletion::Move { target, .. } => {
6997 let target_display_point = target.to_display_point(editor_snapshot);
6998
6999 if self.edit_prediction_requires_modifier() {
7000 if !self.edit_prediction_preview_is_active() {
7001 return None;
7002 }
7003
7004 self.render_edit_prediction_modifier_jump_popover(
7005 text_bounds,
7006 content_origin,
7007 visible_row_range,
7008 line_layouts,
7009 line_height,
7010 scroll_pixel_position,
7011 newest_selection_head,
7012 target_display_point,
7013 window,
7014 cx,
7015 )
7016 } else {
7017 self.render_edit_prediction_eager_jump_popover(
7018 text_bounds,
7019 content_origin,
7020 editor_snapshot,
7021 visible_row_range,
7022 scroll_top,
7023 scroll_bottom,
7024 line_height,
7025 scroll_pixel_position,
7026 target_display_point,
7027 editor_width,
7028 window,
7029 cx,
7030 )
7031 }
7032 }
7033 InlineCompletion::Edit {
7034 display_mode: EditDisplayMode::Inline,
7035 ..
7036 } => None,
7037 InlineCompletion::Edit {
7038 display_mode: EditDisplayMode::TabAccept,
7039 edits,
7040 ..
7041 } => {
7042 let range = &edits.first()?.0;
7043 let target_display_point = range.end.to_display_point(editor_snapshot);
7044
7045 self.render_edit_prediction_end_of_line_popover(
7046 "Accept",
7047 editor_snapshot,
7048 visible_row_range,
7049 target_display_point,
7050 line_height,
7051 scroll_pixel_position,
7052 content_origin,
7053 editor_width,
7054 window,
7055 cx,
7056 )
7057 }
7058 InlineCompletion::Edit {
7059 edits,
7060 edit_preview,
7061 display_mode: EditDisplayMode::DiffPopover,
7062 snapshot,
7063 } => self.render_edit_prediction_diff_popover(
7064 text_bounds,
7065 content_origin,
7066 editor_snapshot,
7067 visible_row_range,
7068 line_layouts,
7069 line_height,
7070 scroll_pixel_position,
7071 newest_selection_head,
7072 editor_width,
7073 style,
7074 edits,
7075 edit_preview,
7076 snapshot,
7077 window,
7078 cx,
7079 ),
7080 }
7081 }
7082
7083 fn render_edit_prediction_modifier_jump_popover(
7084 &mut self,
7085 text_bounds: &Bounds<Pixels>,
7086 content_origin: gpui::Point<Pixels>,
7087 visible_row_range: Range<DisplayRow>,
7088 line_layouts: &[LineWithInvisibles],
7089 line_height: Pixels,
7090 scroll_pixel_position: gpui::Point<Pixels>,
7091 newest_selection_head: Option<DisplayPoint>,
7092 target_display_point: DisplayPoint,
7093 window: &mut Window,
7094 cx: &mut App,
7095 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7096 let scrolled_content_origin =
7097 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7098
7099 const SCROLL_PADDING_Y: Pixels = px(12.);
7100
7101 if target_display_point.row() < visible_row_range.start {
7102 return self.render_edit_prediction_scroll_popover(
7103 |_| SCROLL_PADDING_Y,
7104 IconName::ArrowUp,
7105 visible_row_range,
7106 line_layouts,
7107 newest_selection_head,
7108 scrolled_content_origin,
7109 window,
7110 cx,
7111 );
7112 } else if target_display_point.row() >= visible_row_range.end {
7113 return self.render_edit_prediction_scroll_popover(
7114 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7115 IconName::ArrowDown,
7116 visible_row_range,
7117 line_layouts,
7118 newest_selection_head,
7119 scrolled_content_origin,
7120 window,
7121 cx,
7122 );
7123 }
7124
7125 const POLE_WIDTH: Pixels = px(2.);
7126
7127 let line_layout =
7128 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7129 let target_column = target_display_point.column() as usize;
7130
7131 let target_x = line_layout.x_for_index(target_column);
7132 let target_y =
7133 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7134
7135 let flag_on_right = target_x < text_bounds.size.width / 2.;
7136
7137 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7138 border_color.l += 0.001;
7139
7140 let mut element = v_flex()
7141 .items_end()
7142 .when(flag_on_right, |el| el.items_start())
7143 .child(if flag_on_right {
7144 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7145 .rounded_bl(px(0.))
7146 .rounded_tl(px(0.))
7147 .border_l_2()
7148 .border_color(border_color)
7149 } else {
7150 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7151 .rounded_br(px(0.))
7152 .rounded_tr(px(0.))
7153 .border_r_2()
7154 .border_color(border_color)
7155 })
7156 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7157 .into_any();
7158
7159 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7160
7161 let mut origin = scrolled_content_origin + point(target_x, target_y)
7162 - point(
7163 if flag_on_right {
7164 POLE_WIDTH
7165 } else {
7166 size.width - POLE_WIDTH
7167 },
7168 size.height - line_height,
7169 );
7170
7171 origin.x = origin.x.max(content_origin.x);
7172
7173 element.prepaint_at(origin, window, cx);
7174
7175 Some((element, origin))
7176 }
7177
7178 fn render_edit_prediction_scroll_popover(
7179 &mut self,
7180 to_y: impl Fn(Size<Pixels>) -> Pixels,
7181 scroll_icon: IconName,
7182 visible_row_range: Range<DisplayRow>,
7183 line_layouts: &[LineWithInvisibles],
7184 newest_selection_head: Option<DisplayPoint>,
7185 scrolled_content_origin: gpui::Point<Pixels>,
7186 window: &mut Window,
7187 cx: &mut App,
7188 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7189 let mut element = self
7190 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7191 .into_any();
7192
7193 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7194
7195 let cursor = newest_selection_head?;
7196 let cursor_row_layout =
7197 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7198 let cursor_column = cursor.column() as usize;
7199
7200 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7201
7202 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7203
7204 element.prepaint_at(origin, window, cx);
7205 Some((element, origin))
7206 }
7207
7208 fn render_edit_prediction_eager_jump_popover(
7209 &mut self,
7210 text_bounds: &Bounds<Pixels>,
7211 content_origin: gpui::Point<Pixels>,
7212 editor_snapshot: &EditorSnapshot,
7213 visible_row_range: Range<DisplayRow>,
7214 scroll_top: f32,
7215 scroll_bottom: f32,
7216 line_height: Pixels,
7217 scroll_pixel_position: gpui::Point<Pixels>,
7218 target_display_point: DisplayPoint,
7219 editor_width: Pixels,
7220 window: &mut Window,
7221 cx: &mut App,
7222 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7223 if target_display_point.row().as_f32() < scroll_top {
7224 let mut element = self
7225 .render_edit_prediction_line_popover(
7226 "Jump to Edit",
7227 Some(IconName::ArrowUp),
7228 window,
7229 cx,
7230 )?
7231 .into_any();
7232
7233 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7234 let offset = point(
7235 (text_bounds.size.width - size.width) / 2.,
7236 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7237 );
7238
7239 let origin = text_bounds.origin + offset;
7240 element.prepaint_at(origin, window, cx);
7241 Some((element, origin))
7242 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7243 let mut element = self
7244 .render_edit_prediction_line_popover(
7245 "Jump to Edit",
7246 Some(IconName::ArrowDown),
7247 window,
7248 cx,
7249 )?
7250 .into_any();
7251
7252 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7253 let offset = point(
7254 (text_bounds.size.width - size.width) / 2.,
7255 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7256 );
7257
7258 let origin = text_bounds.origin + offset;
7259 element.prepaint_at(origin, window, cx);
7260 Some((element, origin))
7261 } else {
7262 self.render_edit_prediction_end_of_line_popover(
7263 "Jump to Edit",
7264 editor_snapshot,
7265 visible_row_range,
7266 target_display_point,
7267 line_height,
7268 scroll_pixel_position,
7269 content_origin,
7270 editor_width,
7271 window,
7272 cx,
7273 )
7274 }
7275 }
7276
7277 fn render_edit_prediction_end_of_line_popover(
7278 self: &mut Editor,
7279 label: &'static str,
7280 editor_snapshot: &EditorSnapshot,
7281 visible_row_range: Range<DisplayRow>,
7282 target_display_point: DisplayPoint,
7283 line_height: Pixels,
7284 scroll_pixel_position: gpui::Point<Pixels>,
7285 content_origin: gpui::Point<Pixels>,
7286 editor_width: Pixels,
7287 window: &mut Window,
7288 cx: &mut App,
7289 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7290 let target_line_end = DisplayPoint::new(
7291 target_display_point.row(),
7292 editor_snapshot.line_len(target_display_point.row()),
7293 );
7294
7295 let mut element = self
7296 .render_edit_prediction_line_popover(label, None, window, cx)?
7297 .into_any();
7298
7299 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7300
7301 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7302
7303 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7304 let mut origin = start_point
7305 + line_origin
7306 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7307 origin.x = origin.x.max(content_origin.x);
7308
7309 let max_x = content_origin.x + editor_width - size.width;
7310
7311 if origin.x > max_x {
7312 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7313
7314 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7315 origin.y += offset;
7316 IconName::ArrowUp
7317 } else {
7318 origin.y -= offset;
7319 IconName::ArrowDown
7320 };
7321
7322 element = self
7323 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7324 .into_any();
7325
7326 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7327
7328 origin.x = content_origin.x + editor_width - size.width - px(2.);
7329 }
7330
7331 element.prepaint_at(origin, window, cx);
7332 Some((element, origin))
7333 }
7334
7335 fn render_edit_prediction_diff_popover(
7336 self: &Editor,
7337 text_bounds: &Bounds<Pixels>,
7338 content_origin: gpui::Point<Pixels>,
7339 editor_snapshot: &EditorSnapshot,
7340 visible_row_range: Range<DisplayRow>,
7341 line_layouts: &[LineWithInvisibles],
7342 line_height: Pixels,
7343 scroll_pixel_position: gpui::Point<Pixels>,
7344 newest_selection_head: Option<DisplayPoint>,
7345 editor_width: Pixels,
7346 style: &EditorStyle,
7347 edits: &Vec<(Range<Anchor>, String)>,
7348 edit_preview: &Option<language::EditPreview>,
7349 snapshot: &language::BufferSnapshot,
7350 window: &mut Window,
7351 cx: &mut App,
7352 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7353 let edit_start = edits
7354 .first()
7355 .unwrap()
7356 .0
7357 .start
7358 .to_display_point(editor_snapshot);
7359 let edit_end = edits
7360 .last()
7361 .unwrap()
7362 .0
7363 .end
7364 .to_display_point(editor_snapshot);
7365
7366 let is_visible = visible_row_range.contains(&edit_start.row())
7367 || visible_row_range.contains(&edit_end.row());
7368 if !is_visible {
7369 return None;
7370 }
7371
7372 let highlighted_edits =
7373 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7374
7375 let styled_text = highlighted_edits.to_styled_text(&style.text);
7376 let line_count = highlighted_edits.text.lines().count();
7377
7378 const BORDER_WIDTH: Pixels = px(1.);
7379
7380 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7381 let has_keybind = keybind.is_some();
7382
7383 let mut element = h_flex()
7384 .items_start()
7385 .child(
7386 h_flex()
7387 .bg(cx.theme().colors().editor_background)
7388 .border(BORDER_WIDTH)
7389 .shadow_sm()
7390 .border_color(cx.theme().colors().border)
7391 .rounded_l_lg()
7392 .when(line_count > 1, |el| el.rounded_br_lg())
7393 .pr_1()
7394 .child(styled_text),
7395 )
7396 .child(
7397 h_flex()
7398 .h(line_height + BORDER_WIDTH * 2.)
7399 .px_1p5()
7400 .gap_1()
7401 // Workaround: For some reason, there's a gap if we don't do this
7402 .ml(-BORDER_WIDTH)
7403 .shadow(smallvec![gpui::BoxShadow {
7404 color: gpui::black().opacity(0.05),
7405 offset: point(px(1.), px(1.)),
7406 blur_radius: px(2.),
7407 spread_radius: px(0.),
7408 }])
7409 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7410 .border(BORDER_WIDTH)
7411 .border_color(cx.theme().colors().border)
7412 .rounded_r_lg()
7413 .id("edit_prediction_diff_popover_keybind")
7414 .when(!has_keybind, |el| {
7415 let status_colors = cx.theme().status();
7416
7417 el.bg(status_colors.error_background)
7418 .border_color(status_colors.error.opacity(0.6))
7419 .child(Icon::new(IconName::Info).color(Color::Error))
7420 .cursor_default()
7421 .hoverable_tooltip(move |_window, cx| {
7422 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7423 })
7424 })
7425 .children(keybind),
7426 )
7427 .into_any();
7428
7429 let longest_row =
7430 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7431 let longest_line_width = if visible_row_range.contains(&longest_row) {
7432 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7433 } else {
7434 layout_line(
7435 longest_row,
7436 editor_snapshot,
7437 style,
7438 editor_width,
7439 |_| false,
7440 window,
7441 cx,
7442 )
7443 .width
7444 };
7445
7446 let viewport_bounds =
7447 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7448 right: -EditorElement::SCROLLBAR_WIDTH,
7449 ..Default::default()
7450 });
7451
7452 let x_after_longest =
7453 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7454 - scroll_pixel_position.x;
7455
7456 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7457
7458 // Fully visible if it can be displayed within the window (allow overlapping other
7459 // panes). However, this is only allowed if the popover starts within text_bounds.
7460 let can_position_to_the_right = x_after_longest < text_bounds.right()
7461 && x_after_longest + element_bounds.width < viewport_bounds.right();
7462
7463 let mut origin = if can_position_to_the_right {
7464 point(
7465 x_after_longest,
7466 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7467 - scroll_pixel_position.y,
7468 )
7469 } else {
7470 let cursor_row = newest_selection_head.map(|head| head.row());
7471 let above_edit = edit_start
7472 .row()
7473 .0
7474 .checked_sub(line_count as u32)
7475 .map(DisplayRow);
7476 let below_edit = Some(edit_end.row() + 1);
7477 let above_cursor =
7478 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7479 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7480
7481 // Place the edit popover adjacent to the edit if there is a location
7482 // available that is onscreen and does not obscure the cursor. Otherwise,
7483 // place it adjacent to the cursor.
7484 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7485 .into_iter()
7486 .flatten()
7487 .find(|&start_row| {
7488 let end_row = start_row + line_count as u32;
7489 visible_row_range.contains(&start_row)
7490 && visible_row_range.contains(&end_row)
7491 && cursor_row.map_or(true, |cursor_row| {
7492 !((start_row..end_row).contains(&cursor_row))
7493 })
7494 })?;
7495
7496 content_origin
7497 + point(
7498 -scroll_pixel_position.x,
7499 row_target.as_f32() * line_height - scroll_pixel_position.y,
7500 )
7501 };
7502
7503 origin.x -= BORDER_WIDTH;
7504
7505 window.defer_draw(element, origin, 1);
7506
7507 // Do not return an element, since it will already be drawn due to defer_draw.
7508 None
7509 }
7510
7511 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7512 px(30.)
7513 }
7514
7515 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7516 if self.read_only(cx) {
7517 cx.theme().players().read_only()
7518 } else {
7519 self.style.as_ref().unwrap().local_player
7520 }
7521 }
7522
7523 fn render_edit_prediction_accept_keybind(
7524 &self,
7525 window: &mut Window,
7526 cx: &App,
7527 ) -> Option<AnyElement> {
7528 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7529 let accept_keystroke = accept_binding.keystroke()?;
7530
7531 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7532
7533 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7534 Color::Accent
7535 } else {
7536 Color::Muted
7537 };
7538
7539 h_flex()
7540 .px_0p5()
7541 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7542 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7543 .text_size(TextSize::XSmall.rems(cx))
7544 .child(h_flex().children(ui::render_modifiers(
7545 &accept_keystroke.modifiers,
7546 PlatformStyle::platform(),
7547 Some(modifiers_color),
7548 Some(IconSize::XSmall.rems().into()),
7549 true,
7550 )))
7551 .when(is_platform_style_mac, |parent| {
7552 parent.child(accept_keystroke.key.clone())
7553 })
7554 .when(!is_platform_style_mac, |parent| {
7555 parent.child(
7556 Key::new(
7557 util::capitalize(&accept_keystroke.key),
7558 Some(Color::Default),
7559 )
7560 .size(Some(IconSize::XSmall.rems().into())),
7561 )
7562 })
7563 .into_any()
7564 .into()
7565 }
7566
7567 fn render_edit_prediction_line_popover(
7568 &self,
7569 label: impl Into<SharedString>,
7570 icon: Option<IconName>,
7571 window: &mut Window,
7572 cx: &App,
7573 ) -> Option<Stateful<Div>> {
7574 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7575
7576 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7577 let has_keybind = keybind.is_some();
7578
7579 let result = h_flex()
7580 .id("ep-line-popover")
7581 .py_0p5()
7582 .pl_1()
7583 .pr(padding_right)
7584 .gap_1()
7585 .rounded_md()
7586 .border_1()
7587 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7588 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7589 .shadow_sm()
7590 .when(!has_keybind, |el| {
7591 let status_colors = cx.theme().status();
7592
7593 el.bg(status_colors.error_background)
7594 .border_color(status_colors.error.opacity(0.6))
7595 .pl_2()
7596 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7597 .cursor_default()
7598 .hoverable_tooltip(move |_window, cx| {
7599 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7600 })
7601 })
7602 .children(keybind)
7603 .child(
7604 Label::new(label)
7605 .size(LabelSize::Small)
7606 .when(!has_keybind, |el| {
7607 el.color(cx.theme().status().error.into()).strikethrough()
7608 }),
7609 )
7610 .when(!has_keybind, |el| {
7611 el.child(
7612 h_flex().ml_1().child(
7613 Icon::new(IconName::Info)
7614 .size(IconSize::Small)
7615 .color(cx.theme().status().error.into()),
7616 ),
7617 )
7618 })
7619 .when_some(icon, |element, icon| {
7620 element.child(
7621 div()
7622 .mt(px(1.5))
7623 .child(Icon::new(icon).size(IconSize::Small)),
7624 )
7625 });
7626
7627 Some(result)
7628 }
7629
7630 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7631 let accent_color = cx.theme().colors().text_accent;
7632 let editor_bg_color = cx.theme().colors().editor_background;
7633 editor_bg_color.blend(accent_color.opacity(0.1))
7634 }
7635
7636 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7637 let accent_color = cx.theme().colors().text_accent;
7638 let editor_bg_color = cx.theme().colors().editor_background;
7639 editor_bg_color.blend(accent_color.opacity(0.6))
7640 }
7641
7642 fn render_edit_prediction_cursor_popover(
7643 &self,
7644 min_width: Pixels,
7645 max_width: Pixels,
7646 cursor_point: Point,
7647 style: &EditorStyle,
7648 accept_keystroke: Option<&gpui::Keystroke>,
7649 _window: &Window,
7650 cx: &mut Context<Editor>,
7651 ) -> Option<AnyElement> {
7652 let provider = self.edit_prediction_provider.as_ref()?;
7653
7654 if provider.provider.needs_terms_acceptance(cx) {
7655 return Some(
7656 h_flex()
7657 .min_w(min_width)
7658 .flex_1()
7659 .px_2()
7660 .py_1()
7661 .gap_3()
7662 .elevation_2(cx)
7663 .hover(|style| style.bg(cx.theme().colors().element_hover))
7664 .id("accept-terms")
7665 .cursor_pointer()
7666 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7667 .on_click(cx.listener(|this, _event, window, cx| {
7668 cx.stop_propagation();
7669 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7670 window.dispatch_action(
7671 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7672 cx,
7673 );
7674 }))
7675 .child(
7676 h_flex()
7677 .flex_1()
7678 .gap_2()
7679 .child(Icon::new(IconName::ZedPredict))
7680 .child(Label::new("Accept Terms of Service"))
7681 .child(div().w_full())
7682 .child(
7683 Icon::new(IconName::ArrowUpRight)
7684 .color(Color::Muted)
7685 .size(IconSize::Small),
7686 )
7687 .into_any_element(),
7688 )
7689 .into_any(),
7690 );
7691 }
7692
7693 let is_refreshing = provider.provider.is_refreshing(cx);
7694
7695 fn pending_completion_container() -> Div {
7696 h_flex()
7697 .h_full()
7698 .flex_1()
7699 .gap_2()
7700 .child(Icon::new(IconName::ZedPredict))
7701 }
7702
7703 let completion = match &self.active_inline_completion {
7704 Some(prediction) => {
7705 if !self.has_visible_completions_menu() {
7706 const RADIUS: Pixels = px(6.);
7707 const BORDER_WIDTH: Pixels = px(1.);
7708
7709 return Some(
7710 h_flex()
7711 .elevation_2(cx)
7712 .border(BORDER_WIDTH)
7713 .border_color(cx.theme().colors().border)
7714 .when(accept_keystroke.is_none(), |el| {
7715 el.border_color(cx.theme().status().error)
7716 })
7717 .rounded(RADIUS)
7718 .rounded_tl(px(0.))
7719 .overflow_hidden()
7720 .child(div().px_1p5().child(match &prediction.completion {
7721 InlineCompletion::Move { target, snapshot } => {
7722 use text::ToPoint as _;
7723 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7724 {
7725 Icon::new(IconName::ZedPredictDown)
7726 } else {
7727 Icon::new(IconName::ZedPredictUp)
7728 }
7729 }
7730 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7731 }))
7732 .child(
7733 h_flex()
7734 .gap_1()
7735 .py_1()
7736 .px_2()
7737 .rounded_r(RADIUS - BORDER_WIDTH)
7738 .border_l_1()
7739 .border_color(cx.theme().colors().border)
7740 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7741 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7742 el.child(
7743 Label::new("Hold")
7744 .size(LabelSize::Small)
7745 .when(accept_keystroke.is_none(), |el| {
7746 el.strikethrough()
7747 })
7748 .line_height_style(LineHeightStyle::UiLabel),
7749 )
7750 })
7751 .id("edit_prediction_cursor_popover_keybind")
7752 .when(accept_keystroke.is_none(), |el| {
7753 let status_colors = cx.theme().status();
7754
7755 el.bg(status_colors.error_background)
7756 .border_color(status_colors.error.opacity(0.6))
7757 .child(Icon::new(IconName::Info).color(Color::Error))
7758 .cursor_default()
7759 .hoverable_tooltip(move |_window, cx| {
7760 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7761 .into()
7762 })
7763 })
7764 .when_some(
7765 accept_keystroke.as_ref(),
7766 |el, accept_keystroke| {
7767 el.child(h_flex().children(ui::render_modifiers(
7768 &accept_keystroke.modifiers,
7769 PlatformStyle::platform(),
7770 Some(Color::Default),
7771 Some(IconSize::XSmall.rems().into()),
7772 false,
7773 )))
7774 },
7775 ),
7776 )
7777 .into_any(),
7778 );
7779 }
7780
7781 self.render_edit_prediction_cursor_popover_preview(
7782 prediction,
7783 cursor_point,
7784 style,
7785 cx,
7786 )?
7787 }
7788
7789 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7790 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7791 stale_completion,
7792 cursor_point,
7793 style,
7794 cx,
7795 )?,
7796
7797 None => {
7798 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7799 }
7800 },
7801
7802 None => pending_completion_container().child(Label::new("No Prediction")),
7803 };
7804
7805 let completion = if is_refreshing {
7806 completion
7807 .with_animation(
7808 "loading-completion",
7809 Animation::new(Duration::from_secs(2))
7810 .repeat()
7811 .with_easing(pulsating_between(0.4, 0.8)),
7812 |label, delta| label.opacity(delta),
7813 )
7814 .into_any_element()
7815 } else {
7816 completion.into_any_element()
7817 };
7818
7819 let has_completion = self.active_inline_completion.is_some();
7820
7821 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7822 Some(
7823 h_flex()
7824 .min_w(min_width)
7825 .max_w(max_width)
7826 .flex_1()
7827 .elevation_2(cx)
7828 .border_color(cx.theme().colors().border)
7829 .child(
7830 div()
7831 .flex_1()
7832 .py_1()
7833 .px_2()
7834 .overflow_hidden()
7835 .child(completion),
7836 )
7837 .when_some(accept_keystroke, |el, accept_keystroke| {
7838 if !accept_keystroke.modifiers.modified() {
7839 return el;
7840 }
7841
7842 el.child(
7843 h_flex()
7844 .h_full()
7845 .border_l_1()
7846 .rounded_r_lg()
7847 .border_color(cx.theme().colors().border)
7848 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7849 .gap_1()
7850 .py_1()
7851 .px_2()
7852 .child(
7853 h_flex()
7854 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7855 .when(is_platform_style_mac, |parent| parent.gap_1())
7856 .child(h_flex().children(ui::render_modifiers(
7857 &accept_keystroke.modifiers,
7858 PlatformStyle::platform(),
7859 Some(if !has_completion {
7860 Color::Muted
7861 } else {
7862 Color::Default
7863 }),
7864 None,
7865 false,
7866 ))),
7867 )
7868 .child(Label::new("Preview").into_any_element())
7869 .opacity(if has_completion { 1.0 } else { 0.4 }),
7870 )
7871 })
7872 .into_any(),
7873 )
7874 }
7875
7876 fn render_edit_prediction_cursor_popover_preview(
7877 &self,
7878 completion: &InlineCompletionState,
7879 cursor_point: Point,
7880 style: &EditorStyle,
7881 cx: &mut Context<Editor>,
7882 ) -> Option<Div> {
7883 use text::ToPoint as _;
7884
7885 fn render_relative_row_jump(
7886 prefix: impl Into<String>,
7887 current_row: u32,
7888 target_row: u32,
7889 ) -> Div {
7890 let (row_diff, arrow) = if target_row < current_row {
7891 (current_row - target_row, IconName::ArrowUp)
7892 } else {
7893 (target_row - current_row, IconName::ArrowDown)
7894 };
7895
7896 h_flex()
7897 .child(
7898 Label::new(format!("{}{}", prefix.into(), row_diff))
7899 .color(Color::Muted)
7900 .size(LabelSize::Small),
7901 )
7902 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7903 }
7904
7905 match &completion.completion {
7906 InlineCompletion::Move {
7907 target, snapshot, ..
7908 } => Some(
7909 h_flex()
7910 .px_2()
7911 .gap_2()
7912 .flex_1()
7913 .child(
7914 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7915 Icon::new(IconName::ZedPredictDown)
7916 } else {
7917 Icon::new(IconName::ZedPredictUp)
7918 },
7919 )
7920 .child(Label::new("Jump to Edit")),
7921 ),
7922
7923 InlineCompletion::Edit {
7924 edits,
7925 edit_preview,
7926 snapshot,
7927 display_mode: _,
7928 } => {
7929 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7930
7931 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7932 &snapshot,
7933 &edits,
7934 edit_preview.as_ref()?,
7935 true,
7936 cx,
7937 )
7938 .first_line_preview();
7939
7940 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7941 .with_default_highlights(&style.text, highlighted_edits.highlights);
7942
7943 let preview = h_flex()
7944 .gap_1()
7945 .min_w_16()
7946 .child(styled_text)
7947 .when(has_more_lines, |parent| parent.child("…"));
7948
7949 let left = if first_edit_row != cursor_point.row {
7950 render_relative_row_jump("", cursor_point.row, first_edit_row)
7951 .into_any_element()
7952 } else {
7953 Icon::new(IconName::ZedPredict).into_any_element()
7954 };
7955
7956 Some(
7957 h_flex()
7958 .h_full()
7959 .flex_1()
7960 .gap_2()
7961 .pr_1()
7962 .overflow_x_hidden()
7963 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7964 .child(left)
7965 .child(preview),
7966 )
7967 }
7968 }
7969 }
7970
7971 fn render_context_menu(
7972 &self,
7973 style: &EditorStyle,
7974 max_height_in_lines: u32,
7975 window: &mut Window,
7976 cx: &mut Context<Editor>,
7977 ) -> Option<AnyElement> {
7978 let menu = self.context_menu.borrow();
7979 let menu = menu.as_ref()?;
7980 if !menu.visible() {
7981 return None;
7982 };
7983 Some(menu.render(style, max_height_in_lines, window, cx))
7984 }
7985
7986 fn render_context_menu_aside(
7987 &mut self,
7988 max_size: Size<Pixels>,
7989 window: &mut Window,
7990 cx: &mut Context<Editor>,
7991 ) -> Option<AnyElement> {
7992 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7993 if menu.visible() {
7994 menu.render_aside(self, max_size, window, cx)
7995 } else {
7996 None
7997 }
7998 })
7999 }
8000
8001 fn hide_context_menu(
8002 &mut self,
8003 window: &mut Window,
8004 cx: &mut Context<Self>,
8005 ) -> Option<CodeContextMenu> {
8006 cx.notify();
8007 self.completion_tasks.clear();
8008 let context_menu = self.context_menu.borrow_mut().take();
8009 self.stale_inline_completion_in_menu.take();
8010 self.update_visible_inline_completion(window, cx);
8011 context_menu
8012 }
8013
8014 fn show_snippet_choices(
8015 &mut self,
8016 choices: &Vec<String>,
8017 selection: Range<Anchor>,
8018 cx: &mut Context<Self>,
8019 ) {
8020 if selection.start.buffer_id.is_none() {
8021 return;
8022 }
8023 let buffer_id = selection.start.buffer_id.unwrap();
8024 let buffer = self.buffer().read(cx).buffer(buffer_id);
8025 let id = post_inc(&mut self.next_completion_id);
8026
8027 if let Some(buffer) = buffer {
8028 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8029 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
8030 ));
8031 }
8032 }
8033
8034 pub fn insert_snippet(
8035 &mut self,
8036 insertion_ranges: &[Range<usize>],
8037 snippet: Snippet,
8038 window: &mut Window,
8039 cx: &mut Context<Self>,
8040 ) -> Result<()> {
8041 struct Tabstop<T> {
8042 is_end_tabstop: bool,
8043 ranges: Vec<Range<T>>,
8044 choices: Option<Vec<String>>,
8045 }
8046
8047 let tabstops = self.buffer.update(cx, |buffer, cx| {
8048 let snippet_text: Arc<str> = snippet.text.clone().into();
8049 let edits = insertion_ranges
8050 .iter()
8051 .cloned()
8052 .map(|range| (range, snippet_text.clone()));
8053 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8054
8055 let snapshot = &*buffer.read(cx);
8056 let snippet = &snippet;
8057 snippet
8058 .tabstops
8059 .iter()
8060 .map(|tabstop| {
8061 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8062 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8063 });
8064 let mut tabstop_ranges = tabstop
8065 .ranges
8066 .iter()
8067 .flat_map(|tabstop_range| {
8068 let mut delta = 0_isize;
8069 insertion_ranges.iter().map(move |insertion_range| {
8070 let insertion_start = insertion_range.start as isize + delta;
8071 delta +=
8072 snippet.text.len() as isize - insertion_range.len() as isize;
8073
8074 let start = ((insertion_start + tabstop_range.start) as usize)
8075 .min(snapshot.len());
8076 let end = ((insertion_start + tabstop_range.end) as usize)
8077 .min(snapshot.len());
8078 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8079 })
8080 })
8081 .collect::<Vec<_>>();
8082 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8083
8084 Tabstop {
8085 is_end_tabstop,
8086 ranges: tabstop_ranges,
8087 choices: tabstop.choices.clone(),
8088 }
8089 })
8090 .collect::<Vec<_>>()
8091 });
8092 if let Some(tabstop) = tabstops.first() {
8093 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8094 s.select_ranges(tabstop.ranges.iter().cloned());
8095 });
8096
8097 if let Some(choices) = &tabstop.choices {
8098 if let Some(selection) = tabstop.ranges.first() {
8099 self.show_snippet_choices(choices, selection.clone(), cx)
8100 }
8101 }
8102
8103 // If we're already at the last tabstop and it's at the end of the snippet,
8104 // we're done, we don't need to keep the state around.
8105 if !tabstop.is_end_tabstop {
8106 let choices = tabstops
8107 .iter()
8108 .map(|tabstop| tabstop.choices.clone())
8109 .collect();
8110
8111 let ranges = tabstops
8112 .into_iter()
8113 .map(|tabstop| tabstop.ranges)
8114 .collect::<Vec<_>>();
8115
8116 self.snippet_stack.push(SnippetState {
8117 active_index: 0,
8118 ranges,
8119 choices,
8120 });
8121 }
8122
8123 // Check whether the just-entered snippet ends with an auto-closable bracket.
8124 if self.autoclose_regions.is_empty() {
8125 let snapshot = self.buffer.read(cx).snapshot(cx);
8126 for selection in &mut self.selections.all::<Point>(cx) {
8127 let selection_head = selection.head();
8128 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8129 continue;
8130 };
8131
8132 let mut bracket_pair = None;
8133 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8134 let prev_chars = snapshot
8135 .reversed_chars_at(selection_head)
8136 .collect::<String>();
8137 for (pair, enabled) in scope.brackets() {
8138 if enabled
8139 && pair.close
8140 && prev_chars.starts_with(pair.start.as_str())
8141 && next_chars.starts_with(pair.end.as_str())
8142 {
8143 bracket_pair = Some(pair.clone());
8144 break;
8145 }
8146 }
8147 if let Some(pair) = bracket_pair {
8148 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8149 let autoclose_enabled =
8150 self.use_autoclose && snapshot_settings.use_autoclose;
8151 if autoclose_enabled {
8152 let start = snapshot.anchor_after(selection_head);
8153 let end = snapshot.anchor_after(selection_head);
8154 self.autoclose_regions.push(AutocloseRegion {
8155 selection_id: selection.id,
8156 range: start..end,
8157 pair,
8158 });
8159 }
8160 }
8161 }
8162 }
8163 }
8164 Ok(())
8165 }
8166
8167 pub fn move_to_next_snippet_tabstop(
8168 &mut self,
8169 window: &mut Window,
8170 cx: &mut Context<Self>,
8171 ) -> bool {
8172 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8173 }
8174
8175 pub fn move_to_prev_snippet_tabstop(
8176 &mut self,
8177 window: &mut Window,
8178 cx: &mut Context<Self>,
8179 ) -> bool {
8180 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8181 }
8182
8183 pub fn move_to_snippet_tabstop(
8184 &mut self,
8185 bias: Bias,
8186 window: &mut Window,
8187 cx: &mut Context<Self>,
8188 ) -> bool {
8189 if let Some(mut snippet) = self.snippet_stack.pop() {
8190 match bias {
8191 Bias::Left => {
8192 if snippet.active_index > 0 {
8193 snippet.active_index -= 1;
8194 } else {
8195 self.snippet_stack.push(snippet);
8196 return false;
8197 }
8198 }
8199 Bias::Right => {
8200 if snippet.active_index + 1 < snippet.ranges.len() {
8201 snippet.active_index += 1;
8202 } else {
8203 self.snippet_stack.push(snippet);
8204 return false;
8205 }
8206 }
8207 }
8208 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8209 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8210 s.select_anchor_ranges(current_ranges.iter().cloned())
8211 });
8212
8213 if let Some(choices) = &snippet.choices[snippet.active_index] {
8214 if let Some(selection) = current_ranges.first() {
8215 self.show_snippet_choices(&choices, selection.clone(), cx);
8216 }
8217 }
8218
8219 // If snippet state is not at the last tabstop, push it back on the stack
8220 if snippet.active_index + 1 < snippet.ranges.len() {
8221 self.snippet_stack.push(snippet);
8222 }
8223 return true;
8224 }
8225 }
8226
8227 false
8228 }
8229
8230 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8231 self.transact(window, cx, |this, window, cx| {
8232 this.select_all(&SelectAll, window, cx);
8233 this.insert("", window, cx);
8234 });
8235 }
8236
8237 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8238 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8239 self.transact(window, cx, |this, window, cx| {
8240 this.select_autoclose_pair(window, cx);
8241 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8242 if !this.linked_edit_ranges.is_empty() {
8243 let selections = this.selections.all::<MultiBufferPoint>(cx);
8244 let snapshot = this.buffer.read(cx).snapshot(cx);
8245
8246 for selection in selections.iter() {
8247 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8248 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8249 if selection_start.buffer_id != selection_end.buffer_id {
8250 continue;
8251 }
8252 if let Some(ranges) =
8253 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8254 {
8255 for (buffer, entries) in ranges {
8256 linked_ranges.entry(buffer).or_default().extend(entries);
8257 }
8258 }
8259 }
8260 }
8261
8262 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8263 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8264 for selection in &mut selections {
8265 if selection.is_empty() {
8266 let old_head = selection.head();
8267 let mut new_head =
8268 movement::left(&display_map, old_head.to_display_point(&display_map))
8269 .to_point(&display_map);
8270 if let Some((buffer, line_buffer_range)) = display_map
8271 .buffer_snapshot
8272 .buffer_line_for_row(MultiBufferRow(old_head.row))
8273 {
8274 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8275 let indent_len = match indent_size.kind {
8276 IndentKind::Space => {
8277 buffer.settings_at(line_buffer_range.start, cx).tab_size
8278 }
8279 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8280 };
8281 if old_head.column <= indent_size.len && old_head.column > 0 {
8282 let indent_len = indent_len.get();
8283 new_head = cmp::min(
8284 new_head,
8285 MultiBufferPoint::new(
8286 old_head.row,
8287 ((old_head.column - 1) / indent_len) * indent_len,
8288 ),
8289 );
8290 }
8291 }
8292
8293 selection.set_head(new_head, SelectionGoal::None);
8294 }
8295 }
8296
8297 this.signature_help_state.set_backspace_pressed(true);
8298 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8299 s.select(selections)
8300 });
8301 this.insert("", window, cx);
8302 let empty_str: Arc<str> = Arc::from("");
8303 for (buffer, edits) in linked_ranges {
8304 let snapshot = buffer.read(cx).snapshot();
8305 use text::ToPoint as TP;
8306
8307 let edits = edits
8308 .into_iter()
8309 .map(|range| {
8310 let end_point = TP::to_point(&range.end, &snapshot);
8311 let mut start_point = TP::to_point(&range.start, &snapshot);
8312
8313 if end_point == start_point {
8314 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8315 .saturating_sub(1);
8316 start_point =
8317 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8318 };
8319
8320 (start_point..end_point, empty_str.clone())
8321 })
8322 .sorted_by_key(|(range, _)| range.start)
8323 .collect::<Vec<_>>();
8324 buffer.update(cx, |this, cx| {
8325 this.edit(edits, None, cx);
8326 })
8327 }
8328 this.refresh_inline_completion(true, false, window, cx);
8329 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8330 });
8331 }
8332
8333 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8334 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8335 self.transact(window, cx, |this, window, cx| {
8336 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8337 s.move_with(|map, selection| {
8338 if selection.is_empty() {
8339 let cursor = movement::right(map, selection.head());
8340 selection.end = cursor;
8341 selection.reversed = true;
8342 selection.goal = SelectionGoal::None;
8343 }
8344 })
8345 });
8346 this.insert("", window, cx);
8347 this.refresh_inline_completion(true, false, window, cx);
8348 });
8349 }
8350
8351 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8352 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8353 if self.move_to_prev_snippet_tabstop(window, cx) {
8354 return;
8355 }
8356 self.outdent(&Outdent, window, cx);
8357 }
8358
8359 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8360 if self.move_to_next_snippet_tabstop(window, cx) {
8361 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8362 return;
8363 }
8364 if self.read_only(cx) {
8365 return;
8366 }
8367 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8368 let mut selections = self.selections.all_adjusted(cx);
8369 let buffer = self.buffer.read(cx);
8370 let snapshot = buffer.snapshot(cx);
8371 let rows_iter = selections.iter().map(|s| s.head().row);
8372 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8373
8374 let mut edits = Vec::new();
8375 let mut prev_edited_row = 0;
8376 let mut row_delta = 0;
8377 for selection in &mut selections {
8378 if selection.start.row != prev_edited_row {
8379 row_delta = 0;
8380 }
8381 prev_edited_row = selection.end.row;
8382
8383 // If the selection is non-empty, then increase the indentation of the selected lines.
8384 if !selection.is_empty() {
8385 row_delta =
8386 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8387 continue;
8388 }
8389
8390 // If the selection is empty and the cursor is in the leading whitespace before the
8391 // suggested indentation, then auto-indent the line.
8392 let cursor = selection.head();
8393 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8394 if let Some(suggested_indent) =
8395 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8396 {
8397 if cursor.column < suggested_indent.len
8398 && cursor.column <= current_indent.len
8399 && current_indent.len <= suggested_indent.len
8400 {
8401 selection.start = Point::new(cursor.row, suggested_indent.len);
8402 selection.end = selection.start;
8403 if row_delta == 0 {
8404 edits.extend(Buffer::edit_for_indent_size_adjustment(
8405 cursor.row,
8406 current_indent,
8407 suggested_indent,
8408 ));
8409 row_delta = suggested_indent.len - current_indent.len;
8410 }
8411 continue;
8412 }
8413 }
8414
8415 // Otherwise, insert a hard or soft tab.
8416 let settings = buffer.language_settings_at(cursor, cx);
8417 let tab_size = if settings.hard_tabs {
8418 IndentSize::tab()
8419 } else {
8420 let tab_size = settings.tab_size.get();
8421 let indent_remainder = snapshot
8422 .text_for_range(Point::new(cursor.row, 0)..cursor)
8423 .flat_map(str::chars)
8424 .fold(row_delta % tab_size, |counter: u32, c| {
8425 if c == '\t' {
8426 0
8427 } else {
8428 (counter + 1) % tab_size
8429 }
8430 });
8431
8432 let chars_to_next_tab_stop = tab_size - indent_remainder;
8433 IndentSize::spaces(chars_to_next_tab_stop)
8434 };
8435 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8436 selection.end = selection.start;
8437 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8438 row_delta += tab_size.len;
8439 }
8440
8441 self.transact(window, cx, |this, window, cx| {
8442 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8443 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8444 s.select(selections)
8445 });
8446 this.refresh_inline_completion(true, false, window, cx);
8447 });
8448 }
8449
8450 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8451 if self.read_only(cx) {
8452 return;
8453 }
8454 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8455 let mut selections = self.selections.all::<Point>(cx);
8456 let mut prev_edited_row = 0;
8457 let mut row_delta = 0;
8458 let mut edits = Vec::new();
8459 let buffer = self.buffer.read(cx);
8460 let snapshot = buffer.snapshot(cx);
8461 for selection in &mut selections {
8462 if selection.start.row != prev_edited_row {
8463 row_delta = 0;
8464 }
8465 prev_edited_row = selection.end.row;
8466
8467 row_delta =
8468 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8469 }
8470
8471 self.transact(window, cx, |this, window, cx| {
8472 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8473 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8474 s.select(selections)
8475 });
8476 });
8477 }
8478
8479 fn indent_selection(
8480 buffer: &MultiBuffer,
8481 snapshot: &MultiBufferSnapshot,
8482 selection: &mut Selection<Point>,
8483 edits: &mut Vec<(Range<Point>, String)>,
8484 delta_for_start_row: u32,
8485 cx: &App,
8486 ) -> u32 {
8487 let settings = buffer.language_settings_at(selection.start, cx);
8488 let tab_size = settings.tab_size.get();
8489 let indent_kind = if settings.hard_tabs {
8490 IndentKind::Tab
8491 } else {
8492 IndentKind::Space
8493 };
8494 let mut start_row = selection.start.row;
8495 let mut end_row = selection.end.row + 1;
8496
8497 // If a selection ends at the beginning of a line, don't indent
8498 // that last line.
8499 if selection.end.column == 0 && selection.end.row > selection.start.row {
8500 end_row -= 1;
8501 }
8502
8503 // Avoid re-indenting a row that has already been indented by a
8504 // previous selection, but still update this selection's column
8505 // to reflect that indentation.
8506 if delta_for_start_row > 0 {
8507 start_row += 1;
8508 selection.start.column += delta_for_start_row;
8509 if selection.end.row == selection.start.row {
8510 selection.end.column += delta_for_start_row;
8511 }
8512 }
8513
8514 let mut delta_for_end_row = 0;
8515 let has_multiple_rows = start_row + 1 != end_row;
8516 for row in start_row..end_row {
8517 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8518 let indent_delta = match (current_indent.kind, indent_kind) {
8519 (IndentKind::Space, IndentKind::Space) => {
8520 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8521 IndentSize::spaces(columns_to_next_tab_stop)
8522 }
8523 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8524 (_, IndentKind::Tab) => IndentSize::tab(),
8525 };
8526
8527 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8528 0
8529 } else {
8530 selection.start.column
8531 };
8532 let row_start = Point::new(row, start);
8533 edits.push((
8534 row_start..row_start,
8535 indent_delta.chars().collect::<String>(),
8536 ));
8537
8538 // Update this selection's endpoints to reflect the indentation.
8539 if row == selection.start.row {
8540 selection.start.column += indent_delta.len;
8541 }
8542 if row == selection.end.row {
8543 selection.end.column += indent_delta.len;
8544 delta_for_end_row = indent_delta.len;
8545 }
8546 }
8547
8548 if selection.start.row == selection.end.row {
8549 delta_for_start_row + delta_for_end_row
8550 } else {
8551 delta_for_end_row
8552 }
8553 }
8554
8555 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8556 if self.read_only(cx) {
8557 return;
8558 }
8559 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8560 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8561 let selections = self.selections.all::<Point>(cx);
8562 let mut deletion_ranges = Vec::new();
8563 let mut last_outdent = None;
8564 {
8565 let buffer = self.buffer.read(cx);
8566 let snapshot = buffer.snapshot(cx);
8567 for selection in &selections {
8568 let settings = buffer.language_settings_at(selection.start, cx);
8569 let tab_size = settings.tab_size.get();
8570 let mut rows = selection.spanned_rows(false, &display_map);
8571
8572 // Avoid re-outdenting a row that has already been outdented by a
8573 // previous selection.
8574 if let Some(last_row) = last_outdent {
8575 if last_row == rows.start {
8576 rows.start = rows.start.next_row();
8577 }
8578 }
8579 let has_multiple_rows = rows.len() > 1;
8580 for row in rows.iter_rows() {
8581 let indent_size = snapshot.indent_size_for_line(row);
8582 if indent_size.len > 0 {
8583 let deletion_len = match indent_size.kind {
8584 IndentKind::Space => {
8585 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8586 if columns_to_prev_tab_stop == 0 {
8587 tab_size
8588 } else {
8589 columns_to_prev_tab_stop
8590 }
8591 }
8592 IndentKind::Tab => 1,
8593 };
8594 let start = if has_multiple_rows
8595 || deletion_len > selection.start.column
8596 || indent_size.len < selection.start.column
8597 {
8598 0
8599 } else {
8600 selection.start.column - deletion_len
8601 };
8602 deletion_ranges.push(
8603 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8604 );
8605 last_outdent = Some(row);
8606 }
8607 }
8608 }
8609 }
8610
8611 self.transact(window, cx, |this, window, cx| {
8612 this.buffer.update(cx, |buffer, cx| {
8613 let empty_str: Arc<str> = Arc::default();
8614 buffer.edit(
8615 deletion_ranges
8616 .into_iter()
8617 .map(|range| (range, empty_str.clone())),
8618 None,
8619 cx,
8620 );
8621 });
8622 let selections = this.selections.all::<usize>(cx);
8623 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8624 s.select(selections)
8625 });
8626 });
8627 }
8628
8629 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8630 if self.read_only(cx) {
8631 return;
8632 }
8633 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8634 let selections = self
8635 .selections
8636 .all::<usize>(cx)
8637 .into_iter()
8638 .map(|s| s.range());
8639
8640 self.transact(window, cx, |this, window, cx| {
8641 this.buffer.update(cx, |buffer, cx| {
8642 buffer.autoindent_ranges(selections, cx);
8643 });
8644 let selections = this.selections.all::<usize>(cx);
8645 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8646 s.select(selections)
8647 });
8648 });
8649 }
8650
8651 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8652 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8653 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8654 let selections = self.selections.all::<Point>(cx);
8655
8656 let mut new_cursors = Vec::new();
8657 let mut edit_ranges = Vec::new();
8658 let mut selections = selections.iter().peekable();
8659 while let Some(selection) = selections.next() {
8660 let mut rows = selection.spanned_rows(false, &display_map);
8661 let goal_display_column = selection.head().to_display_point(&display_map).column();
8662
8663 // Accumulate contiguous regions of rows that we want to delete.
8664 while let Some(next_selection) = selections.peek() {
8665 let next_rows = next_selection.spanned_rows(false, &display_map);
8666 if next_rows.start <= rows.end {
8667 rows.end = next_rows.end;
8668 selections.next().unwrap();
8669 } else {
8670 break;
8671 }
8672 }
8673
8674 let buffer = &display_map.buffer_snapshot;
8675 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8676 let edit_end;
8677 let cursor_buffer_row;
8678 if buffer.max_point().row >= rows.end.0 {
8679 // If there's a line after the range, delete the \n from the end of the row range
8680 // and position the cursor on the next line.
8681 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8682 cursor_buffer_row = rows.end;
8683 } else {
8684 // If there isn't a line after the range, delete the \n from the line before the
8685 // start of the row range and position the cursor there.
8686 edit_start = edit_start.saturating_sub(1);
8687 edit_end = buffer.len();
8688 cursor_buffer_row = rows.start.previous_row();
8689 }
8690
8691 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8692 *cursor.column_mut() =
8693 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8694
8695 new_cursors.push((
8696 selection.id,
8697 buffer.anchor_after(cursor.to_point(&display_map)),
8698 ));
8699 edit_ranges.push(edit_start..edit_end);
8700 }
8701
8702 self.transact(window, cx, |this, window, cx| {
8703 let buffer = this.buffer.update(cx, |buffer, cx| {
8704 let empty_str: Arc<str> = Arc::default();
8705 buffer.edit(
8706 edit_ranges
8707 .into_iter()
8708 .map(|range| (range, empty_str.clone())),
8709 None,
8710 cx,
8711 );
8712 buffer.snapshot(cx)
8713 });
8714 let new_selections = new_cursors
8715 .into_iter()
8716 .map(|(id, cursor)| {
8717 let cursor = cursor.to_point(&buffer);
8718 Selection {
8719 id,
8720 start: cursor,
8721 end: cursor,
8722 reversed: false,
8723 goal: SelectionGoal::None,
8724 }
8725 })
8726 .collect();
8727
8728 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8729 s.select(new_selections);
8730 });
8731 });
8732 }
8733
8734 pub fn join_lines_impl(
8735 &mut self,
8736 insert_whitespace: bool,
8737 window: &mut Window,
8738 cx: &mut Context<Self>,
8739 ) {
8740 if self.read_only(cx) {
8741 return;
8742 }
8743 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8744 for selection in self.selections.all::<Point>(cx) {
8745 let start = MultiBufferRow(selection.start.row);
8746 // Treat single line selections as if they include the next line. Otherwise this action
8747 // would do nothing for single line selections individual cursors.
8748 let end = if selection.start.row == selection.end.row {
8749 MultiBufferRow(selection.start.row + 1)
8750 } else {
8751 MultiBufferRow(selection.end.row)
8752 };
8753
8754 if let Some(last_row_range) = row_ranges.last_mut() {
8755 if start <= last_row_range.end {
8756 last_row_range.end = end;
8757 continue;
8758 }
8759 }
8760 row_ranges.push(start..end);
8761 }
8762
8763 let snapshot = self.buffer.read(cx).snapshot(cx);
8764 let mut cursor_positions = Vec::new();
8765 for row_range in &row_ranges {
8766 let anchor = snapshot.anchor_before(Point::new(
8767 row_range.end.previous_row().0,
8768 snapshot.line_len(row_range.end.previous_row()),
8769 ));
8770 cursor_positions.push(anchor..anchor);
8771 }
8772
8773 self.transact(window, cx, |this, window, cx| {
8774 for row_range in row_ranges.into_iter().rev() {
8775 for row in row_range.iter_rows().rev() {
8776 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8777 let next_line_row = row.next_row();
8778 let indent = snapshot.indent_size_for_line(next_line_row);
8779 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8780
8781 let replace =
8782 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8783 " "
8784 } else {
8785 ""
8786 };
8787
8788 this.buffer.update(cx, |buffer, cx| {
8789 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8790 });
8791 }
8792 }
8793
8794 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8795 s.select_anchor_ranges(cursor_positions)
8796 });
8797 });
8798 }
8799
8800 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8801 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8802 self.join_lines_impl(true, window, cx);
8803 }
8804
8805 pub fn sort_lines_case_sensitive(
8806 &mut self,
8807 _: &SortLinesCaseSensitive,
8808 window: &mut Window,
8809 cx: &mut Context<Self>,
8810 ) {
8811 self.manipulate_lines(window, cx, |lines| lines.sort())
8812 }
8813
8814 pub fn sort_lines_case_insensitive(
8815 &mut self,
8816 _: &SortLinesCaseInsensitive,
8817 window: &mut Window,
8818 cx: &mut Context<Self>,
8819 ) {
8820 self.manipulate_lines(window, cx, |lines| {
8821 lines.sort_by_key(|line| line.to_lowercase())
8822 })
8823 }
8824
8825 pub fn unique_lines_case_insensitive(
8826 &mut self,
8827 _: &UniqueLinesCaseInsensitive,
8828 window: &mut Window,
8829 cx: &mut Context<Self>,
8830 ) {
8831 self.manipulate_lines(window, cx, |lines| {
8832 let mut seen = HashSet::default();
8833 lines.retain(|line| seen.insert(line.to_lowercase()));
8834 })
8835 }
8836
8837 pub fn unique_lines_case_sensitive(
8838 &mut self,
8839 _: &UniqueLinesCaseSensitive,
8840 window: &mut Window,
8841 cx: &mut Context<Self>,
8842 ) {
8843 self.manipulate_lines(window, cx, |lines| {
8844 let mut seen = HashSet::default();
8845 lines.retain(|line| seen.insert(*line));
8846 })
8847 }
8848
8849 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8850 let Some(project) = self.project.clone() else {
8851 return;
8852 };
8853 self.reload(project, window, cx)
8854 .detach_and_notify_err(window, cx);
8855 }
8856
8857 pub fn restore_file(
8858 &mut self,
8859 _: &::git::RestoreFile,
8860 window: &mut Window,
8861 cx: &mut Context<Self>,
8862 ) {
8863 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8864 let mut buffer_ids = HashSet::default();
8865 let snapshot = self.buffer().read(cx).snapshot(cx);
8866 for selection in self.selections.all::<usize>(cx) {
8867 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8868 }
8869
8870 let buffer = self.buffer().read(cx);
8871 let ranges = buffer_ids
8872 .into_iter()
8873 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8874 .collect::<Vec<_>>();
8875
8876 self.restore_hunks_in_ranges(ranges, window, cx);
8877 }
8878
8879 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8880 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8881 let selections = self
8882 .selections
8883 .all(cx)
8884 .into_iter()
8885 .map(|s| s.range())
8886 .collect();
8887 self.restore_hunks_in_ranges(selections, window, cx);
8888 }
8889
8890 pub fn restore_hunks_in_ranges(
8891 &mut self,
8892 ranges: Vec<Range<Point>>,
8893 window: &mut Window,
8894 cx: &mut Context<Editor>,
8895 ) {
8896 let mut revert_changes = HashMap::default();
8897 let chunk_by = self
8898 .snapshot(window, cx)
8899 .hunks_for_ranges(ranges)
8900 .into_iter()
8901 .chunk_by(|hunk| hunk.buffer_id);
8902 for (buffer_id, hunks) in &chunk_by {
8903 let hunks = hunks.collect::<Vec<_>>();
8904 for hunk in &hunks {
8905 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8906 }
8907 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8908 }
8909 drop(chunk_by);
8910 if !revert_changes.is_empty() {
8911 self.transact(window, cx, |editor, window, cx| {
8912 editor.restore(revert_changes, window, cx);
8913 });
8914 }
8915 }
8916
8917 pub fn open_active_item_in_terminal(
8918 &mut self,
8919 _: &OpenInTerminal,
8920 window: &mut Window,
8921 cx: &mut Context<Self>,
8922 ) {
8923 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8924 let project_path = buffer.read(cx).project_path(cx)?;
8925 let project = self.project.as_ref()?.read(cx);
8926 let entry = project.entry_for_path(&project_path, cx)?;
8927 let parent = match &entry.canonical_path {
8928 Some(canonical_path) => canonical_path.to_path_buf(),
8929 None => project.absolute_path(&project_path, cx)?,
8930 }
8931 .parent()?
8932 .to_path_buf();
8933 Some(parent)
8934 }) {
8935 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8936 }
8937 }
8938
8939 fn set_breakpoint_context_menu(
8940 &mut self,
8941 display_row: DisplayRow,
8942 position: Option<Anchor>,
8943 clicked_point: gpui::Point<Pixels>,
8944 window: &mut Window,
8945 cx: &mut Context<Self>,
8946 ) {
8947 if !cx.has_flag::<Debugger>() {
8948 return;
8949 }
8950 let source = self
8951 .buffer
8952 .read(cx)
8953 .snapshot(cx)
8954 .anchor_before(Point::new(display_row.0, 0u32));
8955
8956 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8957
8958 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8959 self,
8960 source,
8961 clicked_point,
8962 context_menu,
8963 window,
8964 cx,
8965 );
8966 }
8967
8968 fn add_edit_breakpoint_block(
8969 &mut self,
8970 anchor: Anchor,
8971 breakpoint: &Breakpoint,
8972 edit_action: BreakpointPromptEditAction,
8973 window: &mut Window,
8974 cx: &mut Context<Self>,
8975 ) {
8976 let weak_editor = cx.weak_entity();
8977 let bp_prompt = cx.new(|cx| {
8978 BreakpointPromptEditor::new(
8979 weak_editor,
8980 anchor,
8981 breakpoint.clone(),
8982 edit_action,
8983 window,
8984 cx,
8985 )
8986 });
8987
8988 let height = bp_prompt.update(cx, |this, cx| {
8989 this.prompt
8990 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8991 });
8992 let cloned_prompt = bp_prompt.clone();
8993 let blocks = vec![BlockProperties {
8994 style: BlockStyle::Sticky,
8995 placement: BlockPlacement::Above(anchor),
8996 height: Some(height),
8997 render: Arc::new(move |cx| {
8998 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8999 cloned_prompt.clone().into_any_element()
9000 }),
9001 priority: 0,
9002 }];
9003
9004 let focus_handle = bp_prompt.focus_handle(cx);
9005 window.focus(&focus_handle);
9006
9007 let block_ids = self.insert_blocks(blocks, None, cx);
9008 bp_prompt.update(cx, |prompt, _| {
9009 prompt.add_block_ids(block_ids);
9010 });
9011 }
9012
9013 pub(crate) fn breakpoint_at_row(
9014 &self,
9015 row: u32,
9016 window: &mut Window,
9017 cx: &mut Context<Self>,
9018 ) -> Option<(Anchor, Breakpoint)> {
9019 let snapshot = self.snapshot(window, cx);
9020 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9021
9022 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9023 }
9024
9025 pub(crate) fn breakpoint_at_anchor(
9026 &self,
9027 breakpoint_position: Anchor,
9028 snapshot: &EditorSnapshot,
9029 cx: &mut Context<Self>,
9030 ) -> Option<(Anchor, Breakpoint)> {
9031 let project = self.project.clone()?;
9032
9033 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9034 snapshot
9035 .buffer_snapshot
9036 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9037 })?;
9038
9039 let enclosing_excerpt = breakpoint_position.excerpt_id;
9040 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9041 let buffer_snapshot = buffer.read(cx).snapshot();
9042
9043 let row = buffer_snapshot
9044 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9045 .row;
9046
9047 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9048 let anchor_end = snapshot
9049 .buffer_snapshot
9050 .anchor_after(Point::new(row, line_len));
9051
9052 let bp = self
9053 .breakpoint_store
9054 .as_ref()?
9055 .read_with(cx, |breakpoint_store, cx| {
9056 breakpoint_store
9057 .breakpoints(
9058 &buffer,
9059 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9060 &buffer_snapshot,
9061 cx,
9062 )
9063 .next()
9064 .and_then(|(anchor, bp)| {
9065 let breakpoint_row = buffer_snapshot
9066 .summary_for_anchor::<text::PointUtf16>(anchor)
9067 .row;
9068
9069 if breakpoint_row == row {
9070 snapshot
9071 .buffer_snapshot
9072 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9073 .map(|anchor| (anchor, bp.clone()))
9074 } else {
9075 None
9076 }
9077 })
9078 });
9079 bp
9080 }
9081
9082 pub fn edit_log_breakpoint(
9083 &mut self,
9084 _: &EditLogBreakpoint,
9085 window: &mut Window,
9086 cx: &mut Context<Self>,
9087 ) {
9088 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9089 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9090 message: None,
9091 state: BreakpointState::Enabled,
9092 condition: None,
9093 hit_condition: None,
9094 });
9095
9096 self.add_edit_breakpoint_block(
9097 anchor,
9098 &breakpoint,
9099 BreakpointPromptEditAction::Log,
9100 window,
9101 cx,
9102 );
9103 }
9104 }
9105
9106 fn breakpoints_at_cursors(
9107 &self,
9108 window: &mut Window,
9109 cx: &mut Context<Self>,
9110 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9111 let snapshot = self.snapshot(window, cx);
9112 let cursors = self
9113 .selections
9114 .disjoint_anchors()
9115 .into_iter()
9116 .map(|selection| {
9117 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9118
9119 let breakpoint_position = self
9120 .breakpoint_at_row(cursor_position.row, window, cx)
9121 .map(|bp| bp.0)
9122 .unwrap_or_else(|| {
9123 snapshot
9124 .display_snapshot
9125 .buffer_snapshot
9126 .anchor_after(Point::new(cursor_position.row, 0))
9127 });
9128
9129 let breakpoint = self
9130 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9131 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9132
9133 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9134 })
9135 // 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.
9136 .collect::<HashMap<Anchor, _>>();
9137
9138 cursors.into_iter().collect()
9139 }
9140
9141 pub fn enable_breakpoint(
9142 &mut self,
9143 _: &crate::actions::EnableBreakpoint,
9144 window: &mut Window,
9145 cx: &mut Context<Self>,
9146 ) {
9147 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9148 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9149 continue;
9150 };
9151 self.edit_breakpoint_at_anchor(
9152 anchor,
9153 breakpoint,
9154 BreakpointEditAction::InvertState,
9155 cx,
9156 );
9157 }
9158 }
9159
9160 pub fn disable_breakpoint(
9161 &mut self,
9162 _: &crate::actions::DisableBreakpoint,
9163 window: &mut Window,
9164 cx: &mut Context<Self>,
9165 ) {
9166 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9167 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9168 continue;
9169 };
9170 self.edit_breakpoint_at_anchor(
9171 anchor,
9172 breakpoint,
9173 BreakpointEditAction::InvertState,
9174 cx,
9175 );
9176 }
9177 }
9178
9179 pub fn toggle_breakpoint(
9180 &mut self,
9181 _: &crate::actions::ToggleBreakpoint,
9182 window: &mut Window,
9183 cx: &mut Context<Self>,
9184 ) {
9185 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9186 if let Some(breakpoint) = breakpoint {
9187 self.edit_breakpoint_at_anchor(
9188 anchor,
9189 breakpoint,
9190 BreakpointEditAction::Toggle,
9191 cx,
9192 );
9193 } else {
9194 self.edit_breakpoint_at_anchor(
9195 anchor,
9196 Breakpoint::new_standard(),
9197 BreakpointEditAction::Toggle,
9198 cx,
9199 );
9200 }
9201 }
9202 }
9203
9204 pub fn edit_breakpoint_at_anchor(
9205 &mut self,
9206 breakpoint_position: Anchor,
9207 breakpoint: Breakpoint,
9208 edit_action: BreakpointEditAction,
9209 cx: &mut Context<Self>,
9210 ) {
9211 let Some(breakpoint_store) = &self.breakpoint_store else {
9212 return;
9213 };
9214
9215 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9216 if breakpoint_position == Anchor::min() {
9217 self.buffer()
9218 .read(cx)
9219 .excerpt_buffer_ids()
9220 .into_iter()
9221 .next()
9222 } else {
9223 None
9224 }
9225 }) else {
9226 return;
9227 };
9228
9229 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9230 return;
9231 };
9232
9233 breakpoint_store.update(cx, |breakpoint_store, cx| {
9234 breakpoint_store.toggle_breakpoint(
9235 buffer,
9236 (breakpoint_position.text_anchor, breakpoint),
9237 edit_action,
9238 cx,
9239 );
9240 });
9241
9242 cx.notify();
9243 }
9244
9245 #[cfg(any(test, feature = "test-support"))]
9246 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9247 self.breakpoint_store.clone()
9248 }
9249
9250 pub fn prepare_restore_change(
9251 &self,
9252 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9253 hunk: &MultiBufferDiffHunk,
9254 cx: &mut App,
9255 ) -> Option<()> {
9256 if hunk.is_created_file() {
9257 return None;
9258 }
9259 let buffer = self.buffer.read(cx);
9260 let diff = buffer.diff_for(hunk.buffer_id)?;
9261 let buffer = buffer.buffer(hunk.buffer_id)?;
9262 let buffer = buffer.read(cx);
9263 let original_text = diff
9264 .read(cx)
9265 .base_text()
9266 .as_rope()
9267 .slice(hunk.diff_base_byte_range.clone());
9268 let buffer_snapshot = buffer.snapshot();
9269 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9270 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9271 probe
9272 .0
9273 .start
9274 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9275 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9276 }) {
9277 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9278 Some(())
9279 } else {
9280 None
9281 }
9282 }
9283
9284 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9285 self.manipulate_lines(window, cx, |lines| lines.reverse())
9286 }
9287
9288 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9289 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9290 }
9291
9292 fn manipulate_lines<Fn>(
9293 &mut self,
9294 window: &mut Window,
9295 cx: &mut Context<Self>,
9296 mut callback: Fn,
9297 ) where
9298 Fn: FnMut(&mut Vec<&str>),
9299 {
9300 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9301
9302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9303 let buffer = self.buffer.read(cx).snapshot(cx);
9304
9305 let mut edits = Vec::new();
9306
9307 let selections = self.selections.all::<Point>(cx);
9308 let mut selections = selections.iter().peekable();
9309 let mut contiguous_row_selections = Vec::new();
9310 let mut new_selections = Vec::new();
9311 let mut added_lines = 0;
9312 let mut removed_lines = 0;
9313
9314 while let Some(selection) = selections.next() {
9315 let (start_row, end_row) = consume_contiguous_rows(
9316 &mut contiguous_row_selections,
9317 selection,
9318 &display_map,
9319 &mut selections,
9320 );
9321
9322 let start_point = Point::new(start_row.0, 0);
9323 let end_point = Point::new(
9324 end_row.previous_row().0,
9325 buffer.line_len(end_row.previous_row()),
9326 );
9327 let text = buffer
9328 .text_for_range(start_point..end_point)
9329 .collect::<String>();
9330
9331 let mut lines = text.split('\n').collect_vec();
9332
9333 let lines_before = lines.len();
9334 callback(&mut lines);
9335 let lines_after = lines.len();
9336
9337 edits.push((start_point..end_point, lines.join("\n")));
9338
9339 // Selections must change based on added and removed line count
9340 let start_row =
9341 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9342 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9343 new_selections.push(Selection {
9344 id: selection.id,
9345 start: start_row,
9346 end: end_row,
9347 goal: SelectionGoal::None,
9348 reversed: selection.reversed,
9349 });
9350
9351 if lines_after > lines_before {
9352 added_lines += lines_after - lines_before;
9353 } else if lines_before > lines_after {
9354 removed_lines += lines_before - lines_after;
9355 }
9356 }
9357
9358 self.transact(window, cx, |this, window, cx| {
9359 let buffer = this.buffer.update(cx, |buffer, cx| {
9360 buffer.edit(edits, None, cx);
9361 buffer.snapshot(cx)
9362 });
9363
9364 // Recalculate offsets on newly edited buffer
9365 let new_selections = new_selections
9366 .iter()
9367 .map(|s| {
9368 let start_point = Point::new(s.start.0, 0);
9369 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9370 Selection {
9371 id: s.id,
9372 start: buffer.point_to_offset(start_point),
9373 end: buffer.point_to_offset(end_point),
9374 goal: s.goal,
9375 reversed: s.reversed,
9376 }
9377 })
9378 .collect();
9379
9380 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9381 s.select(new_selections);
9382 });
9383
9384 this.request_autoscroll(Autoscroll::fit(), cx);
9385 });
9386 }
9387
9388 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9389 self.manipulate_text(window, cx, |text| {
9390 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9391 if has_upper_case_characters {
9392 text.to_lowercase()
9393 } else {
9394 text.to_uppercase()
9395 }
9396 })
9397 }
9398
9399 pub fn convert_to_upper_case(
9400 &mut self,
9401 _: &ConvertToUpperCase,
9402 window: &mut Window,
9403 cx: &mut Context<Self>,
9404 ) {
9405 self.manipulate_text(window, cx, |text| text.to_uppercase())
9406 }
9407
9408 pub fn convert_to_lower_case(
9409 &mut self,
9410 _: &ConvertToLowerCase,
9411 window: &mut Window,
9412 cx: &mut Context<Self>,
9413 ) {
9414 self.manipulate_text(window, cx, |text| text.to_lowercase())
9415 }
9416
9417 pub fn convert_to_title_case(
9418 &mut self,
9419 _: &ConvertToTitleCase,
9420 window: &mut Window,
9421 cx: &mut Context<Self>,
9422 ) {
9423 self.manipulate_text(window, cx, |text| {
9424 text.split('\n')
9425 .map(|line| line.to_case(Case::Title))
9426 .join("\n")
9427 })
9428 }
9429
9430 pub fn convert_to_snake_case(
9431 &mut self,
9432 _: &ConvertToSnakeCase,
9433 window: &mut Window,
9434 cx: &mut Context<Self>,
9435 ) {
9436 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9437 }
9438
9439 pub fn convert_to_kebab_case(
9440 &mut self,
9441 _: &ConvertToKebabCase,
9442 window: &mut Window,
9443 cx: &mut Context<Self>,
9444 ) {
9445 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9446 }
9447
9448 pub fn convert_to_upper_camel_case(
9449 &mut self,
9450 _: &ConvertToUpperCamelCase,
9451 window: &mut Window,
9452 cx: &mut Context<Self>,
9453 ) {
9454 self.manipulate_text(window, cx, |text| {
9455 text.split('\n')
9456 .map(|line| line.to_case(Case::UpperCamel))
9457 .join("\n")
9458 })
9459 }
9460
9461 pub fn convert_to_lower_camel_case(
9462 &mut self,
9463 _: &ConvertToLowerCamelCase,
9464 window: &mut Window,
9465 cx: &mut Context<Self>,
9466 ) {
9467 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9468 }
9469
9470 pub fn convert_to_opposite_case(
9471 &mut self,
9472 _: &ConvertToOppositeCase,
9473 window: &mut Window,
9474 cx: &mut Context<Self>,
9475 ) {
9476 self.manipulate_text(window, cx, |text| {
9477 text.chars()
9478 .fold(String::with_capacity(text.len()), |mut t, c| {
9479 if c.is_uppercase() {
9480 t.extend(c.to_lowercase());
9481 } else {
9482 t.extend(c.to_uppercase());
9483 }
9484 t
9485 })
9486 })
9487 }
9488
9489 pub fn convert_to_rot13(
9490 &mut self,
9491 _: &ConvertToRot13,
9492 window: &mut Window,
9493 cx: &mut Context<Self>,
9494 ) {
9495 self.manipulate_text(window, cx, |text| {
9496 text.chars()
9497 .map(|c| match c {
9498 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9499 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9500 _ => c,
9501 })
9502 .collect()
9503 })
9504 }
9505
9506 pub fn convert_to_rot47(
9507 &mut self,
9508 _: &ConvertToRot47,
9509 window: &mut Window,
9510 cx: &mut Context<Self>,
9511 ) {
9512 self.manipulate_text(window, cx, |text| {
9513 text.chars()
9514 .map(|c| {
9515 let code_point = c as u32;
9516 if code_point >= 33 && code_point <= 126 {
9517 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9518 }
9519 c
9520 })
9521 .collect()
9522 })
9523 }
9524
9525 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9526 where
9527 Fn: FnMut(&str) -> String,
9528 {
9529 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9530 let buffer = self.buffer.read(cx).snapshot(cx);
9531
9532 let mut new_selections = Vec::new();
9533 let mut edits = Vec::new();
9534 let mut selection_adjustment = 0i32;
9535
9536 for selection in self.selections.all::<usize>(cx) {
9537 let selection_is_empty = selection.is_empty();
9538
9539 let (start, end) = if selection_is_empty {
9540 let word_range = movement::surrounding_word(
9541 &display_map,
9542 selection.start.to_display_point(&display_map),
9543 );
9544 let start = word_range.start.to_offset(&display_map, Bias::Left);
9545 let end = word_range.end.to_offset(&display_map, Bias::Left);
9546 (start, end)
9547 } else {
9548 (selection.start, selection.end)
9549 };
9550
9551 let text = buffer.text_for_range(start..end).collect::<String>();
9552 let old_length = text.len() as i32;
9553 let text = callback(&text);
9554
9555 new_selections.push(Selection {
9556 start: (start as i32 - selection_adjustment) as usize,
9557 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9558 goal: SelectionGoal::None,
9559 ..selection
9560 });
9561
9562 selection_adjustment += old_length - text.len() as i32;
9563
9564 edits.push((start..end, text));
9565 }
9566
9567 self.transact(window, cx, |this, window, cx| {
9568 this.buffer.update(cx, |buffer, cx| {
9569 buffer.edit(edits, None, cx);
9570 });
9571
9572 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9573 s.select(new_selections);
9574 });
9575
9576 this.request_autoscroll(Autoscroll::fit(), cx);
9577 });
9578 }
9579
9580 pub fn duplicate(
9581 &mut self,
9582 upwards: bool,
9583 whole_lines: bool,
9584 window: &mut Window,
9585 cx: &mut Context<Self>,
9586 ) {
9587 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9588
9589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9590 let buffer = &display_map.buffer_snapshot;
9591 let selections = self.selections.all::<Point>(cx);
9592
9593 let mut edits = Vec::new();
9594 let mut selections_iter = selections.iter().peekable();
9595 while let Some(selection) = selections_iter.next() {
9596 let mut rows = selection.spanned_rows(false, &display_map);
9597 // duplicate line-wise
9598 if whole_lines || selection.start == selection.end {
9599 // Avoid duplicating the same lines twice.
9600 while let Some(next_selection) = selections_iter.peek() {
9601 let next_rows = next_selection.spanned_rows(false, &display_map);
9602 if next_rows.start < rows.end {
9603 rows.end = next_rows.end;
9604 selections_iter.next().unwrap();
9605 } else {
9606 break;
9607 }
9608 }
9609
9610 // Copy the text from the selected row region and splice it either at the start
9611 // or end of the region.
9612 let start = Point::new(rows.start.0, 0);
9613 let end = Point::new(
9614 rows.end.previous_row().0,
9615 buffer.line_len(rows.end.previous_row()),
9616 );
9617 let text = buffer
9618 .text_for_range(start..end)
9619 .chain(Some("\n"))
9620 .collect::<String>();
9621 let insert_location = if upwards {
9622 Point::new(rows.end.0, 0)
9623 } else {
9624 start
9625 };
9626 edits.push((insert_location..insert_location, text));
9627 } else {
9628 // duplicate character-wise
9629 let start = selection.start;
9630 let end = selection.end;
9631 let text = buffer.text_for_range(start..end).collect::<String>();
9632 edits.push((selection.end..selection.end, text));
9633 }
9634 }
9635
9636 self.transact(window, cx, |this, _, cx| {
9637 this.buffer.update(cx, |buffer, cx| {
9638 buffer.edit(edits, None, cx);
9639 });
9640
9641 this.request_autoscroll(Autoscroll::fit(), cx);
9642 });
9643 }
9644
9645 pub fn duplicate_line_up(
9646 &mut self,
9647 _: &DuplicateLineUp,
9648 window: &mut Window,
9649 cx: &mut Context<Self>,
9650 ) {
9651 self.duplicate(true, true, window, cx);
9652 }
9653
9654 pub fn duplicate_line_down(
9655 &mut self,
9656 _: &DuplicateLineDown,
9657 window: &mut Window,
9658 cx: &mut Context<Self>,
9659 ) {
9660 self.duplicate(false, true, window, cx);
9661 }
9662
9663 pub fn duplicate_selection(
9664 &mut self,
9665 _: &DuplicateSelection,
9666 window: &mut Window,
9667 cx: &mut Context<Self>,
9668 ) {
9669 self.duplicate(false, false, window, cx);
9670 }
9671
9672 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9673 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9674
9675 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9676 let buffer = self.buffer.read(cx).snapshot(cx);
9677
9678 let mut edits = Vec::new();
9679 let mut unfold_ranges = Vec::new();
9680 let mut refold_creases = Vec::new();
9681
9682 let selections = self.selections.all::<Point>(cx);
9683 let mut selections = selections.iter().peekable();
9684 let mut contiguous_row_selections = Vec::new();
9685 let mut new_selections = Vec::new();
9686
9687 while let Some(selection) = selections.next() {
9688 // Find all the selections that span a contiguous row range
9689 let (start_row, end_row) = consume_contiguous_rows(
9690 &mut contiguous_row_selections,
9691 selection,
9692 &display_map,
9693 &mut selections,
9694 );
9695
9696 // Move the text spanned by the row range to be before the line preceding the row range
9697 if start_row.0 > 0 {
9698 let range_to_move = Point::new(
9699 start_row.previous_row().0,
9700 buffer.line_len(start_row.previous_row()),
9701 )
9702 ..Point::new(
9703 end_row.previous_row().0,
9704 buffer.line_len(end_row.previous_row()),
9705 );
9706 let insertion_point = display_map
9707 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9708 .0;
9709
9710 // Don't move lines across excerpts
9711 if buffer
9712 .excerpt_containing(insertion_point..range_to_move.end)
9713 .is_some()
9714 {
9715 let text = buffer
9716 .text_for_range(range_to_move.clone())
9717 .flat_map(|s| s.chars())
9718 .skip(1)
9719 .chain(['\n'])
9720 .collect::<String>();
9721
9722 edits.push((
9723 buffer.anchor_after(range_to_move.start)
9724 ..buffer.anchor_before(range_to_move.end),
9725 String::new(),
9726 ));
9727 let insertion_anchor = buffer.anchor_after(insertion_point);
9728 edits.push((insertion_anchor..insertion_anchor, text));
9729
9730 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9731
9732 // Move selections up
9733 new_selections.extend(contiguous_row_selections.drain(..).map(
9734 |mut selection| {
9735 selection.start.row -= row_delta;
9736 selection.end.row -= row_delta;
9737 selection
9738 },
9739 ));
9740
9741 // Move folds up
9742 unfold_ranges.push(range_to_move.clone());
9743 for fold in display_map.folds_in_range(
9744 buffer.anchor_before(range_to_move.start)
9745 ..buffer.anchor_after(range_to_move.end),
9746 ) {
9747 let mut start = fold.range.start.to_point(&buffer);
9748 let mut end = fold.range.end.to_point(&buffer);
9749 start.row -= row_delta;
9750 end.row -= row_delta;
9751 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9752 }
9753 }
9754 }
9755
9756 // If we didn't move line(s), preserve the existing selections
9757 new_selections.append(&mut contiguous_row_selections);
9758 }
9759
9760 self.transact(window, cx, |this, window, cx| {
9761 this.unfold_ranges(&unfold_ranges, true, true, cx);
9762 this.buffer.update(cx, |buffer, cx| {
9763 for (range, text) in edits {
9764 buffer.edit([(range, text)], None, cx);
9765 }
9766 });
9767 this.fold_creases(refold_creases, true, window, cx);
9768 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9769 s.select(new_selections);
9770 })
9771 });
9772 }
9773
9774 pub fn move_line_down(
9775 &mut self,
9776 _: &MoveLineDown,
9777 window: &mut Window,
9778 cx: &mut Context<Self>,
9779 ) {
9780 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9781
9782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9783 let buffer = self.buffer.read(cx).snapshot(cx);
9784
9785 let mut edits = Vec::new();
9786 let mut unfold_ranges = Vec::new();
9787 let mut refold_creases = Vec::new();
9788
9789 let selections = self.selections.all::<Point>(cx);
9790 let mut selections = selections.iter().peekable();
9791 let mut contiguous_row_selections = Vec::new();
9792 let mut new_selections = Vec::new();
9793
9794 while let Some(selection) = selections.next() {
9795 // Find all the selections that span a contiguous row range
9796 let (start_row, end_row) = consume_contiguous_rows(
9797 &mut contiguous_row_selections,
9798 selection,
9799 &display_map,
9800 &mut selections,
9801 );
9802
9803 // Move the text spanned by the row range to be after the last line of the row range
9804 if end_row.0 <= buffer.max_point().row {
9805 let range_to_move =
9806 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9807 let insertion_point = display_map
9808 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9809 .0;
9810
9811 // Don't move lines across excerpt boundaries
9812 if buffer
9813 .excerpt_containing(range_to_move.start..insertion_point)
9814 .is_some()
9815 {
9816 let mut text = String::from("\n");
9817 text.extend(buffer.text_for_range(range_to_move.clone()));
9818 text.pop(); // Drop trailing newline
9819 edits.push((
9820 buffer.anchor_after(range_to_move.start)
9821 ..buffer.anchor_before(range_to_move.end),
9822 String::new(),
9823 ));
9824 let insertion_anchor = buffer.anchor_after(insertion_point);
9825 edits.push((insertion_anchor..insertion_anchor, text));
9826
9827 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9828
9829 // Move selections down
9830 new_selections.extend(contiguous_row_selections.drain(..).map(
9831 |mut selection| {
9832 selection.start.row += row_delta;
9833 selection.end.row += row_delta;
9834 selection
9835 },
9836 ));
9837
9838 // Move folds down
9839 unfold_ranges.push(range_to_move.clone());
9840 for fold in display_map.folds_in_range(
9841 buffer.anchor_before(range_to_move.start)
9842 ..buffer.anchor_after(range_to_move.end),
9843 ) {
9844 let mut start = fold.range.start.to_point(&buffer);
9845 let mut end = fold.range.end.to_point(&buffer);
9846 start.row += row_delta;
9847 end.row += row_delta;
9848 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9849 }
9850 }
9851 }
9852
9853 // If we didn't move line(s), preserve the existing selections
9854 new_selections.append(&mut contiguous_row_selections);
9855 }
9856
9857 self.transact(window, cx, |this, window, cx| {
9858 this.unfold_ranges(&unfold_ranges, true, true, cx);
9859 this.buffer.update(cx, |buffer, cx| {
9860 for (range, text) in edits {
9861 buffer.edit([(range, text)], None, cx);
9862 }
9863 });
9864 this.fold_creases(refold_creases, true, window, cx);
9865 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9866 s.select(new_selections)
9867 });
9868 });
9869 }
9870
9871 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9872 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9873 let text_layout_details = &self.text_layout_details(window);
9874 self.transact(window, cx, |this, window, cx| {
9875 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9876 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9877 s.move_with(|display_map, selection| {
9878 if !selection.is_empty() {
9879 return;
9880 }
9881
9882 let mut head = selection.head();
9883 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9884 if head.column() == display_map.line_len(head.row()) {
9885 transpose_offset = display_map
9886 .buffer_snapshot
9887 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9888 }
9889
9890 if transpose_offset == 0 {
9891 return;
9892 }
9893
9894 *head.column_mut() += 1;
9895 head = display_map.clip_point(head, Bias::Right);
9896 let goal = SelectionGoal::HorizontalPosition(
9897 display_map
9898 .x_for_display_point(head, text_layout_details)
9899 .into(),
9900 );
9901 selection.collapse_to(head, goal);
9902
9903 let transpose_start = display_map
9904 .buffer_snapshot
9905 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9906 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9907 let transpose_end = display_map
9908 .buffer_snapshot
9909 .clip_offset(transpose_offset + 1, Bias::Right);
9910 if let Some(ch) =
9911 display_map.buffer_snapshot.chars_at(transpose_start).next()
9912 {
9913 edits.push((transpose_start..transpose_offset, String::new()));
9914 edits.push((transpose_end..transpose_end, ch.to_string()));
9915 }
9916 }
9917 });
9918 edits
9919 });
9920 this.buffer
9921 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9922 let selections = this.selections.all::<usize>(cx);
9923 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9924 s.select(selections);
9925 });
9926 });
9927 }
9928
9929 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9930 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9931 self.rewrap_impl(RewrapOptions::default(), cx)
9932 }
9933
9934 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9935 let buffer = self.buffer.read(cx).snapshot(cx);
9936 let selections = self.selections.all::<Point>(cx);
9937 let mut selections = selections.iter().peekable();
9938
9939 let mut edits = Vec::new();
9940 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9941
9942 while let Some(selection) = selections.next() {
9943 let mut start_row = selection.start.row;
9944 let mut end_row = selection.end.row;
9945
9946 // Skip selections that overlap with a range that has already been rewrapped.
9947 let selection_range = start_row..end_row;
9948 if rewrapped_row_ranges
9949 .iter()
9950 .any(|range| range.overlaps(&selection_range))
9951 {
9952 continue;
9953 }
9954
9955 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9956
9957 // Since not all lines in the selection may be at the same indent
9958 // level, choose the indent size that is the most common between all
9959 // of the lines.
9960 //
9961 // If there is a tie, we use the deepest indent.
9962 let (indent_size, indent_end) = {
9963 let mut indent_size_occurrences = HashMap::default();
9964 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9965
9966 for row in start_row..=end_row {
9967 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9968 rows_by_indent_size.entry(indent).or_default().push(row);
9969 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9970 }
9971
9972 let indent_size = indent_size_occurrences
9973 .into_iter()
9974 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9975 .map(|(indent, _)| indent)
9976 .unwrap_or_default();
9977 let row = rows_by_indent_size[&indent_size][0];
9978 let indent_end = Point::new(row, indent_size.len);
9979
9980 (indent_size, indent_end)
9981 };
9982
9983 let mut line_prefix = indent_size.chars().collect::<String>();
9984
9985 let mut inside_comment = false;
9986 if let Some(comment_prefix) =
9987 buffer
9988 .language_scope_at(selection.head())
9989 .and_then(|language| {
9990 language
9991 .line_comment_prefixes()
9992 .iter()
9993 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9994 .cloned()
9995 })
9996 {
9997 line_prefix.push_str(&comment_prefix);
9998 inside_comment = true;
9999 }
10000
10001 let language_settings = buffer.language_settings_at(selection.head(), cx);
10002 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10003 RewrapBehavior::InComments => inside_comment,
10004 RewrapBehavior::InSelections => !selection.is_empty(),
10005 RewrapBehavior::Anywhere => true,
10006 };
10007
10008 let should_rewrap = options.override_language_settings
10009 || allow_rewrap_based_on_language
10010 || self.hard_wrap.is_some();
10011 if !should_rewrap {
10012 continue;
10013 }
10014
10015 if selection.is_empty() {
10016 'expand_upwards: while start_row > 0 {
10017 let prev_row = start_row - 1;
10018 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10019 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10020 {
10021 start_row = prev_row;
10022 } else {
10023 break 'expand_upwards;
10024 }
10025 }
10026
10027 'expand_downwards: while end_row < buffer.max_point().row {
10028 let next_row = end_row + 1;
10029 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10030 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10031 {
10032 end_row = next_row;
10033 } else {
10034 break 'expand_downwards;
10035 }
10036 }
10037 }
10038
10039 let start = Point::new(start_row, 0);
10040 let start_offset = start.to_offset(&buffer);
10041 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10042 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10043 let Some(lines_without_prefixes) = selection_text
10044 .lines()
10045 .map(|line| {
10046 line.strip_prefix(&line_prefix)
10047 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10048 .ok_or_else(|| {
10049 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10050 })
10051 })
10052 .collect::<Result<Vec<_>, _>>()
10053 .log_err()
10054 else {
10055 continue;
10056 };
10057
10058 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10059 buffer
10060 .language_settings_at(Point::new(start_row, 0), cx)
10061 .preferred_line_length as usize
10062 });
10063 let wrapped_text = wrap_with_prefix(
10064 line_prefix,
10065 lines_without_prefixes.join("\n"),
10066 wrap_column,
10067 tab_size,
10068 options.preserve_existing_whitespace,
10069 );
10070
10071 // TODO: should always use char-based diff while still supporting cursor behavior that
10072 // matches vim.
10073 let mut diff_options = DiffOptions::default();
10074 if options.override_language_settings {
10075 diff_options.max_word_diff_len = 0;
10076 diff_options.max_word_diff_line_count = 0;
10077 } else {
10078 diff_options.max_word_diff_len = usize::MAX;
10079 diff_options.max_word_diff_line_count = usize::MAX;
10080 }
10081
10082 for (old_range, new_text) in
10083 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10084 {
10085 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10086 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10087 edits.push((edit_start..edit_end, new_text));
10088 }
10089
10090 rewrapped_row_ranges.push(start_row..=end_row);
10091 }
10092
10093 self.buffer
10094 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10095 }
10096
10097 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10098 let mut text = String::new();
10099 let buffer = self.buffer.read(cx).snapshot(cx);
10100 let mut selections = self.selections.all::<Point>(cx);
10101 let mut clipboard_selections = Vec::with_capacity(selections.len());
10102 {
10103 let max_point = buffer.max_point();
10104 let mut is_first = true;
10105 for selection in &mut selections {
10106 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10107 if is_entire_line {
10108 selection.start = Point::new(selection.start.row, 0);
10109 if !selection.is_empty() && selection.end.column == 0 {
10110 selection.end = cmp::min(max_point, selection.end);
10111 } else {
10112 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10113 }
10114 selection.goal = SelectionGoal::None;
10115 }
10116 if is_first {
10117 is_first = false;
10118 } else {
10119 text += "\n";
10120 }
10121 let mut len = 0;
10122 for chunk in buffer.text_for_range(selection.start..selection.end) {
10123 text.push_str(chunk);
10124 len += chunk.len();
10125 }
10126 clipboard_selections.push(ClipboardSelection {
10127 len,
10128 is_entire_line,
10129 first_line_indent: buffer
10130 .indent_size_for_line(MultiBufferRow(selection.start.row))
10131 .len,
10132 });
10133 }
10134 }
10135
10136 self.transact(window, cx, |this, window, cx| {
10137 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10138 s.select(selections);
10139 });
10140 this.insert("", window, cx);
10141 });
10142 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10143 }
10144
10145 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10146 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10147 let item = self.cut_common(window, cx);
10148 cx.write_to_clipboard(item);
10149 }
10150
10151 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10152 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10153 self.change_selections(None, window, cx, |s| {
10154 s.move_with(|snapshot, sel| {
10155 if sel.is_empty() {
10156 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10157 }
10158 });
10159 });
10160 let item = self.cut_common(window, cx);
10161 cx.set_global(KillRing(item))
10162 }
10163
10164 pub fn kill_ring_yank(
10165 &mut self,
10166 _: &KillRingYank,
10167 window: &mut Window,
10168 cx: &mut Context<Self>,
10169 ) {
10170 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10171 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10172 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10173 (kill_ring.text().to_string(), kill_ring.metadata_json())
10174 } else {
10175 return;
10176 }
10177 } else {
10178 return;
10179 };
10180 self.do_paste(&text, metadata, false, window, cx);
10181 }
10182
10183 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10184 self.do_copy(true, cx);
10185 }
10186
10187 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10188 self.do_copy(false, cx);
10189 }
10190
10191 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10192 let selections = self.selections.all::<Point>(cx);
10193 let buffer = self.buffer.read(cx).read(cx);
10194 let mut text = String::new();
10195
10196 let mut clipboard_selections = Vec::with_capacity(selections.len());
10197 {
10198 let max_point = buffer.max_point();
10199 let mut is_first = true;
10200 for selection in &selections {
10201 let mut start = selection.start;
10202 let mut end = selection.end;
10203 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10204 if is_entire_line {
10205 start = Point::new(start.row, 0);
10206 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10207 }
10208
10209 let mut trimmed_selections = Vec::new();
10210 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10211 let row = MultiBufferRow(start.row);
10212 let first_indent = buffer.indent_size_for_line(row);
10213 if first_indent.len == 0 || start.column > first_indent.len {
10214 trimmed_selections.push(start..end);
10215 } else {
10216 trimmed_selections.push(
10217 Point::new(row.0, first_indent.len)
10218 ..Point::new(row.0, buffer.line_len(row)),
10219 );
10220 for row in start.row + 1..=end.row {
10221 let mut line_len = buffer.line_len(MultiBufferRow(row));
10222 if row == end.row {
10223 line_len = end.column;
10224 }
10225 if line_len == 0 {
10226 trimmed_selections
10227 .push(Point::new(row, 0)..Point::new(row, line_len));
10228 continue;
10229 }
10230 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10231 if row_indent_size.len >= first_indent.len {
10232 trimmed_selections.push(
10233 Point::new(row, first_indent.len)..Point::new(row, line_len),
10234 );
10235 } else {
10236 trimmed_selections.clear();
10237 trimmed_selections.push(start..end);
10238 break;
10239 }
10240 }
10241 }
10242 } else {
10243 trimmed_selections.push(start..end);
10244 }
10245
10246 for trimmed_range in trimmed_selections {
10247 if is_first {
10248 is_first = false;
10249 } else {
10250 text += "\n";
10251 }
10252 let mut len = 0;
10253 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10254 text.push_str(chunk);
10255 len += chunk.len();
10256 }
10257 clipboard_selections.push(ClipboardSelection {
10258 len,
10259 is_entire_line,
10260 first_line_indent: buffer
10261 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10262 .len,
10263 });
10264 }
10265 }
10266 }
10267
10268 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10269 text,
10270 clipboard_selections,
10271 ));
10272 }
10273
10274 pub fn do_paste(
10275 &mut self,
10276 text: &String,
10277 clipboard_selections: Option<Vec<ClipboardSelection>>,
10278 handle_entire_lines: bool,
10279 window: &mut Window,
10280 cx: &mut Context<Self>,
10281 ) {
10282 if self.read_only(cx) {
10283 return;
10284 }
10285
10286 let clipboard_text = Cow::Borrowed(text);
10287
10288 self.transact(window, cx, |this, window, cx| {
10289 if let Some(mut clipboard_selections) = clipboard_selections {
10290 let old_selections = this.selections.all::<usize>(cx);
10291 let all_selections_were_entire_line =
10292 clipboard_selections.iter().all(|s| s.is_entire_line);
10293 let first_selection_indent_column =
10294 clipboard_selections.first().map(|s| s.first_line_indent);
10295 if clipboard_selections.len() != old_selections.len() {
10296 clipboard_selections.drain(..);
10297 }
10298 let cursor_offset = this.selections.last::<usize>(cx).head();
10299 let mut auto_indent_on_paste = true;
10300
10301 this.buffer.update(cx, |buffer, cx| {
10302 let snapshot = buffer.read(cx);
10303 auto_indent_on_paste = snapshot
10304 .language_settings_at(cursor_offset, cx)
10305 .auto_indent_on_paste;
10306
10307 let mut start_offset = 0;
10308 let mut edits = Vec::new();
10309 let mut original_indent_columns = Vec::new();
10310 for (ix, selection) in old_selections.iter().enumerate() {
10311 let to_insert;
10312 let entire_line;
10313 let original_indent_column;
10314 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10315 let end_offset = start_offset + clipboard_selection.len;
10316 to_insert = &clipboard_text[start_offset..end_offset];
10317 entire_line = clipboard_selection.is_entire_line;
10318 start_offset = end_offset + 1;
10319 original_indent_column = Some(clipboard_selection.first_line_indent);
10320 } else {
10321 to_insert = clipboard_text.as_str();
10322 entire_line = all_selections_were_entire_line;
10323 original_indent_column = first_selection_indent_column
10324 }
10325
10326 // If the corresponding selection was empty when this slice of the
10327 // clipboard text was written, then the entire line containing the
10328 // selection was copied. If this selection is also currently empty,
10329 // then paste the line before the current line of the buffer.
10330 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10331 let column = selection.start.to_point(&snapshot).column as usize;
10332 let line_start = selection.start - column;
10333 line_start..line_start
10334 } else {
10335 selection.range()
10336 };
10337
10338 edits.push((range, to_insert));
10339 original_indent_columns.push(original_indent_column);
10340 }
10341 drop(snapshot);
10342
10343 buffer.edit(
10344 edits,
10345 if auto_indent_on_paste {
10346 Some(AutoindentMode::Block {
10347 original_indent_columns,
10348 })
10349 } else {
10350 None
10351 },
10352 cx,
10353 );
10354 });
10355
10356 let selections = this.selections.all::<usize>(cx);
10357 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10358 s.select(selections)
10359 });
10360 } else {
10361 this.insert(&clipboard_text, window, cx);
10362 }
10363 });
10364 }
10365
10366 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10367 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10368 if let Some(item) = cx.read_from_clipboard() {
10369 let entries = item.entries();
10370
10371 match entries.first() {
10372 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10373 // of all the pasted entries.
10374 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10375 .do_paste(
10376 clipboard_string.text(),
10377 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10378 true,
10379 window,
10380 cx,
10381 ),
10382 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10383 }
10384 }
10385 }
10386
10387 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10388 if self.read_only(cx) {
10389 return;
10390 }
10391
10392 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10393
10394 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10395 if let Some((selections, _)) =
10396 self.selection_history.transaction(transaction_id).cloned()
10397 {
10398 self.change_selections(None, window, cx, |s| {
10399 s.select_anchors(selections.to_vec());
10400 });
10401 } else {
10402 log::error!(
10403 "No entry in selection_history found for undo. \
10404 This may correspond to a bug where undo does not update the selection. \
10405 If this is occurring, please add details to \
10406 https://github.com/zed-industries/zed/issues/22692"
10407 );
10408 }
10409 self.request_autoscroll(Autoscroll::fit(), cx);
10410 self.unmark_text(window, cx);
10411 self.refresh_inline_completion(true, false, window, cx);
10412 cx.emit(EditorEvent::Edited { transaction_id });
10413 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10414 }
10415 }
10416
10417 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10418 if self.read_only(cx) {
10419 return;
10420 }
10421
10422 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10423
10424 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10425 if let Some((_, Some(selections))) =
10426 self.selection_history.transaction(transaction_id).cloned()
10427 {
10428 self.change_selections(None, window, cx, |s| {
10429 s.select_anchors(selections.to_vec());
10430 });
10431 } else {
10432 log::error!(
10433 "No entry in selection_history found for redo. \
10434 This may correspond to a bug where undo does not update the selection. \
10435 If this is occurring, please add details to \
10436 https://github.com/zed-industries/zed/issues/22692"
10437 );
10438 }
10439 self.request_autoscroll(Autoscroll::fit(), cx);
10440 self.unmark_text(window, cx);
10441 self.refresh_inline_completion(true, false, window, cx);
10442 cx.emit(EditorEvent::Edited { transaction_id });
10443 }
10444 }
10445
10446 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10447 self.buffer
10448 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10449 }
10450
10451 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10452 self.buffer
10453 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10454 }
10455
10456 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10457 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10458 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10459 s.move_with(|map, selection| {
10460 let cursor = if selection.is_empty() {
10461 movement::left(map, selection.start)
10462 } else {
10463 selection.start
10464 };
10465 selection.collapse_to(cursor, SelectionGoal::None);
10466 });
10467 })
10468 }
10469
10470 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10471 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10472 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10473 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10474 })
10475 }
10476
10477 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10478 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10479 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10480 s.move_with(|map, selection| {
10481 let cursor = if selection.is_empty() {
10482 movement::right(map, selection.end)
10483 } else {
10484 selection.end
10485 };
10486 selection.collapse_to(cursor, SelectionGoal::None)
10487 });
10488 })
10489 }
10490
10491 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10492 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10493 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10494 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10495 })
10496 }
10497
10498 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10499 if self.take_rename(true, window, cx).is_some() {
10500 return;
10501 }
10502
10503 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10504 cx.propagate();
10505 return;
10506 }
10507
10508 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10509
10510 let text_layout_details = &self.text_layout_details(window);
10511 let selection_count = self.selections.count();
10512 let first_selection = self.selections.first_anchor();
10513
10514 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10515 s.move_with(|map, selection| {
10516 if !selection.is_empty() {
10517 selection.goal = SelectionGoal::None;
10518 }
10519 let (cursor, goal) = movement::up(
10520 map,
10521 selection.start,
10522 selection.goal,
10523 false,
10524 text_layout_details,
10525 );
10526 selection.collapse_to(cursor, goal);
10527 });
10528 });
10529
10530 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10531 {
10532 cx.propagate();
10533 }
10534 }
10535
10536 pub fn move_up_by_lines(
10537 &mut self,
10538 action: &MoveUpByLines,
10539 window: &mut Window,
10540 cx: &mut Context<Self>,
10541 ) {
10542 if self.take_rename(true, window, cx).is_some() {
10543 return;
10544 }
10545
10546 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10547 cx.propagate();
10548 return;
10549 }
10550
10551 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10552
10553 let text_layout_details = &self.text_layout_details(window);
10554
10555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10556 s.move_with(|map, selection| {
10557 if !selection.is_empty() {
10558 selection.goal = SelectionGoal::None;
10559 }
10560 let (cursor, goal) = movement::up_by_rows(
10561 map,
10562 selection.start,
10563 action.lines,
10564 selection.goal,
10565 false,
10566 text_layout_details,
10567 );
10568 selection.collapse_to(cursor, goal);
10569 });
10570 })
10571 }
10572
10573 pub fn move_down_by_lines(
10574 &mut self,
10575 action: &MoveDownByLines,
10576 window: &mut Window,
10577 cx: &mut Context<Self>,
10578 ) {
10579 if self.take_rename(true, window, cx).is_some() {
10580 return;
10581 }
10582
10583 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10584 cx.propagate();
10585 return;
10586 }
10587
10588 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10589
10590 let text_layout_details = &self.text_layout_details(window);
10591
10592 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10593 s.move_with(|map, selection| {
10594 if !selection.is_empty() {
10595 selection.goal = SelectionGoal::None;
10596 }
10597 let (cursor, goal) = movement::down_by_rows(
10598 map,
10599 selection.start,
10600 action.lines,
10601 selection.goal,
10602 false,
10603 text_layout_details,
10604 );
10605 selection.collapse_to(cursor, goal);
10606 });
10607 })
10608 }
10609
10610 pub fn select_down_by_lines(
10611 &mut self,
10612 action: &SelectDownByLines,
10613 window: &mut Window,
10614 cx: &mut Context<Self>,
10615 ) {
10616 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10617 let text_layout_details = &self.text_layout_details(window);
10618 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10619 s.move_heads_with(|map, head, goal| {
10620 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10621 })
10622 })
10623 }
10624
10625 pub fn select_up_by_lines(
10626 &mut self,
10627 action: &SelectUpByLines,
10628 window: &mut Window,
10629 cx: &mut Context<Self>,
10630 ) {
10631 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10632 let text_layout_details = &self.text_layout_details(window);
10633 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10634 s.move_heads_with(|map, head, goal| {
10635 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10636 })
10637 })
10638 }
10639
10640 pub fn select_page_up(
10641 &mut self,
10642 _: &SelectPageUp,
10643 window: &mut Window,
10644 cx: &mut Context<Self>,
10645 ) {
10646 let Some(row_count) = self.visible_row_count() else {
10647 return;
10648 };
10649
10650 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10651
10652 let text_layout_details = &self.text_layout_details(window);
10653
10654 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10655 s.move_heads_with(|map, head, goal| {
10656 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10657 })
10658 })
10659 }
10660
10661 pub fn move_page_up(
10662 &mut self,
10663 action: &MovePageUp,
10664 window: &mut Window,
10665 cx: &mut Context<Self>,
10666 ) {
10667 if self.take_rename(true, window, cx).is_some() {
10668 return;
10669 }
10670
10671 if self
10672 .context_menu
10673 .borrow_mut()
10674 .as_mut()
10675 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10676 .unwrap_or(false)
10677 {
10678 return;
10679 }
10680
10681 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10682 cx.propagate();
10683 return;
10684 }
10685
10686 let Some(row_count) = self.visible_row_count() else {
10687 return;
10688 };
10689
10690 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10691
10692 let autoscroll = if action.center_cursor {
10693 Autoscroll::center()
10694 } else {
10695 Autoscroll::fit()
10696 };
10697
10698 let text_layout_details = &self.text_layout_details(window);
10699
10700 self.change_selections(Some(autoscroll), window, cx, |s| {
10701 s.move_with(|map, selection| {
10702 if !selection.is_empty() {
10703 selection.goal = SelectionGoal::None;
10704 }
10705 let (cursor, goal) = movement::up_by_rows(
10706 map,
10707 selection.end,
10708 row_count,
10709 selection.goal,
10710 false,
10711 text_layout_details,
10712 );
10713 selection.collapse_to(cursor, goal);
10714 });
10715 });
10716 }
10717
10718 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10719 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10720 let text_layout_details = &self.text_layout_details(window);
10721 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10722 s.move_heads_with(|map, head, goal| {
10723 movement::up(map, head, goal, false, text_layout_details)
10724 })
10725 })
10726 }
10727
10728 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10729 self.take_rename(true, window, cx);
10730
10731 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10732 cx.propagate();
10733 return;
10734 }
10735
10736 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10737
10738 let text_layout_details = &self.text_layout_details(window);
10739 let selection_count = self.selections.count();
10740 let first_selection = self.selections.first_anchor();
10741
10742 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10743 s.move_with(|map, selection| {
10744 if !selection.is_empty() {
10745 selection.goal = SelectionGoal::None;
10746 }
10747 let (cursor, goal) = movement::down(
10748 map,
10749 selection.end,
10750 selection.goal,
10751 false,
10752 text_layout_details,
10753 );
10754 selection.collapse_to(cursor, goal);
10755 });
10756 });
10757
10758 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10759 {
10760 cx.propagate();
10761 }
10762 }
10763
10764 pub fn select_page_down(
10765 &mut self,
10766 _: &SelectPageDown,
10767 window: &mut Window,
10768 cx: &mut Context<Self>,
10769 ) {
10770 let Some(row_count) = self.visible_row_count() else {
10771 return;
10772 };
10773
10774 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10775
10776 let text_layout_details = &self.text_layout_details(window);
10777
10778 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10779 s.move_heads_with(|map, head, goal| {
10780 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10781 })
10782 })
10783 }
10784
10785 pub fn move_page_down(
10786 &mut self,
10787 action: &MovePageDown,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) {
10791 if self.take_rename(true, window, cx).is_some() {
10792 return;
10793 }
10794
10795 if self
10796 .context_menu
10797 .borrow_mut()
10798 .as_mut()
10799 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10800 .unwrap_or(false)
10801 {
10802 return;
10803 }
10804
10805 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10806 cx.propagate();
10807 return;
10808 }
10809
10810 let Some(row_count) = self.visible_row_count() else {
10811 return;
10812 };
10813
10814 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10815
10816 let autoscroll = if action.center_cursor {
10817 Autoscroll::center()
10818 } else {
10819 Autoscroll::fit()
10820 };
10821
10822 let text_layout_details = &self.text_layout_details(window);
10823 self.change_selections(Some(autoscroll), window, cx, |s| {
10824 s.move_with(|map, selection| {
10825 if !selection.is_empty() {
10826 selection.goal = SelectionGoal::None;
10827 }
10828 let (cursor, goal) = movement::down_by_rows(
10829 map,
10830 selection.end,
10831 row_count,
10832 selection.goal,
10833 false,
10834 text_layout_details,
10835 );
10836 selection.collapse_to(cursor, goal);
10837 });
10838 });
10839 }
10840
10841 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10842 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10843 let text_layout_details = &self.text_layout_details(window);
10844 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10845 s.move_heads_with(|map, head, goal| {
10846 movement::down(map, head, goal, false, text_layout_details)
10847 })
10848 });
10849 }
10850
10851 pub fn context_menu_first(
10852 &mut self,
10853 _: &ContextMenuFirst,
10854 _window: &mut Window,
10855 cx: &mut Context<Self>,
10856 ) {
10857 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10858 context_menu.select_first(self.completion_provider.as_deref(), cx);
10859 }
10860 }
10861
10862 pub fn context_menu_prev(
10863 &mut self,
10864 _: &ContextMenuPrevious,
10865 _window: &mut Window,
10866 cx: &mut Context<Self>,
10867 ) {
10868 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10869 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10870 }
10871 }
10872
10873 pub fn context_menu_next(
10874 &mut self,
10875 _: &ContextMenuNext,
10876 _window: &mut Window,
10877 cx: &mut Context<Self>,
10878 ) {
10879 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10880 context_menu.select_next(self.completion_provider.as_deref(), cx);
10881 }
10882 }
10883
10884 pub fn context_menu_last(
10885 &mut self,
10886 _: &ContextMenuLast,
10887 _window: &mut Window,
10888 cx: &mut Context<Self>,
10889 ) {
10890 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10891 context_menu.select_last(self.completion_provider.as_deref(), cx);
10892 }
10893 }
10894
10895 pub fn move_to_previous_word_start(
10896 &mut self,
10897 _: &MoveToPreviousWordStart,
10898 window: &mut Window,
10899 cx: &mut Context<Self>,
10900 ) {
10901 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10902 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10903 s.move_cursors_with(|map, head, _| {
10904 (
10905 movement::previous_word_start(map, head),
10906 SelectionGoal::None,
10907 )
10908 });
10909 })
10910 }
10911
10912 pub fn move_to_previous_subword_start(
10913 &mut self,
10914 _: &MoveToPreviousSubwordStart,
10915 window: &mut Window,
10916 cx: &mut Context<Self>,
10917 ) {
10918 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10919 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10920 s.move_cursors_with(|map, head, _| {
10921 (
10922 movement::previous_subword_start(map, head),
10923 SelectionGoal::None,
10924 )
10925 });
10926 })
10927 }
10928
10929 pub fn select_to_previous_word_start(
10930 &mut self,
10931 _: &SelectToPreviousWordStart,
10932 window: &mut Window,
10933 cx: &mut Context<Self>,
10934 ) {
10935 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10937 s.move_heads_with(|map, head, _| {
10938 (
10939 movement::previous_word_start(map, head),
10940 SelectionGoal::None,
10941 )
10942 });
10943 })
10944 }
10945
10946 pub fn select_to_previous_subword_start(
10947 &mut self,
10948 _: &SelectToPreviousSubwordStart,
10949 window: &mut Window,
10950 cx: &mut Context<Self>,
10951 ) {
10952 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10953 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10954 s.move_heads_with(|map, head, _| {
10955 (
10956 movement::previous_subword_start(map, head),
10957 SelectionGoal::None,
10958 )
10959 });
10960 })
10961 }
10962
10963 pub fn delete_to_previous_word_start(
10964 &mut self,
10965 action: &DeleteToPreviousWordStart,
10966 window: &mut Window,
10967 cx: &mut Context<Self>,
10968 ) {
10969 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10970 self.transact(window, cx, |this, window, cx| {
10971 this.select_autoclose_pair(window, cx);
10972 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10973 s.move_with(|map, selection| {
10974 if selection.is_empty() {
10975 let cursor = if action.ignore_newlines {
10976 movement::previous_word_start(map, selection.head())
10977 } else {
10978 movement::previous_word_start_or_newline(map, selection.head())
10979 };
10980 selection.set_head(cursor, SelectionGoal::None);
10981 }
10982 });
10983 });
10984 this.insert("", window, cx);
10985 });
10986 }
10987
10988 pub fn delete_to_previous_subword_start(
10989 &mut self,
10990 _: &DeleteToPreviousSubwordStart,
10991 window: &mut Window,
10992 cx: &mut Context<Self>,
10993 ) {
10994 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10995 self.transact(window, cx, |this, window, cx| {
10996 this.select_autoclose_pair(window, cx);
10997 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10998 s.move_with(|map, selection| {
10999 if selection.is_empty() {
11000 let cursor = movement::previous_subword_start(map, selection.head());
11001 selection.set_head(cursor, SelectionGoal::None);
11002 }
11003 });
11004 });
11005 this.insert("", window, cx);
11006 });
11007 }
11008
11009 pub fn move_to_next_word_end(
11010 &mut self,
11011 _: &MoveToNextWordEnd,
11012 window: &mut Window,
11013 cx: &mut Context<Self>,
11014 ) {
11015 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11016 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11017 s.move_cursors_with(|map, head, _| {
11018 (movement::next_word_end(map, head), SelectionGoal::None)
11019 });
11020 })
11021 }
11022
11023 pub fn move_to_next_subword_end(
11024 &mut self,
11025 _: &MoveToNextSubwordEnd,
11026 window: &mut Window,
11027 cx: &mut Context<Self>,
11028 ) {
11029 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11030 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11031 s.move_cursors_with(|map, head, _| {
11032 (movement::next_subword_end(map, head), SelectionGoal::None)
11033 });
11034 })
11035 }
11036
11037 pub fn select_to_next_word_end(
11038 &mut self,
11039 _: &SelectToNextWordEnd,
11040 window: &mut Window,
11041 cx: &mut Context<Self>,
11042 ) {
11043 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11045 s.move_heads_with(|map, head, _| {
11046 (movement::next_word_end(map, head), SelectionGoal::None)
11047 });
11048 })
11049 }
11050
11051 pub fn select_to_next_subword_end(
11052 &mut self,
11053 _: &SelectToNextSubwordEnd,
11054 window: &mut Window,
11055 cx: &mut Context<Self>,
11056 ) {
11057 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11058 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11059 s.move_heads_with(|map, head, _| {
11060 (movement::next_subword_end(map, head), SelectionGoal::None)
11061 });
11062 })
11063 }
11064
11065 pub fn delete_to_next_word_end(
11066 &mut self,
11067 action: &DeleteToNextWordEnd,
11068 window: &mut Window,
11069 cx: &mut Context<Self>,
11070 ) {
11071 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11072 self.transact(window, cx, |this, window, cx| {
11073 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11074 s.move_with(|map, selection| {
11075 if selection.is_empty() {
11076 let cursor = if action.ignore_newlines {
11077 movement::next_word_end(map, selection.head())
11078 } else {
11079 movement::next_word_end_or_newline(map, selection.head())
11080 };
11081 selection.set_head(cursor, SelectionGoal::None);
11082 }
11083 });
11084 });
11085 this.insert("", window, cx);
11086 });
11087 }
11088
11089 pub fn delete_to_next_subword_end(
11090 &mut self,
11091 _: &DeleteToNextSubwordEnd,
11092 window: &mut Window,
11093 cx: &mut Context<Self>,
11094 ) {
11095 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11096 self.transact(window, cx, |this, window, cx| {
11097 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11098 s.move_with(|map, selection| {
11099 if selection.is_empty() {
11100 let cursor = movement::next_subword_end(map, selection.head());
11101 selection.set_head(cursor, SelectionGoal::None);
11102 }
11103 });
11104 });
11105 this.insert("", window, cx);
11106 });
11107 }
11108
11109 pub fn move_to_beginning_of_line(
11110 &mut self,
11111 action: &MoveToBeginningOfLine,
11112 window: &mut Window,
11113 cx: &mut Context<Self>,
11114 ) {
11115 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11116 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11117 s.move_cursors_with(|map, head, _| {
11118 (
11119 movement::indented_line_beginning(
11120 map,
11121 head,
11122 action.stop_at_soft_wraps,
11123 action.stop_at_indent,
11124 ),
11125 SelectionGoal::None,
11126 )
11127 });
11128 })
11129 }
11130
11131 pub fn select_to_beginning_of_line(
11132 &mut self,
11133 action: &SelectToBeginningOfLine,
11134 window: &mut Window,
11135 cx: &mut Context<Self>,
11136 ) {
11137 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11138 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11139 s.move_heads_with(|map, head, _| {
11140 (
11141 movement::indented_line_beginning(
11142 map,
11143 head,
11144 action.stop_at_soft_wraps,
11145 action.stop_at_indent,
11146 ),
11147 SelectionGoal::None,
11148 )
11149 });
11150 });
11151 }
11152
11153 pub fn delete_to_beginning_of_line(
11154 &mut self,
11155 action: &DeleteToBeginningOfLine,
11156 window: &mut Window,
11157 cx: &mut Context<Self>,
11158 ) {
11159 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11160 self.transact(window, cx, |this, window, cx| {
11161 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11162 s.move_with(|_, selection| {
11163 selection.reversed = true;
11164 });
11165 });
11166
11167 this.select_to_beginning_of_line(
11168 &SelectToBeginningOfLine {
11169 stop_at_soft_wraps: false,
11170 stop_at_indent: action.stop_at_indent,
11171 },
11172 window,
11173 cx,
11174 );
11175 this.backspace(&Backspace, window, cx);
11176 });
11177 }
11178
11179 pub fn move_to_end_of_line(
11180 &mut self,
11181 action: &MoveToEndOfLine,
11182 window: &mut Window,
11183 cx: &mut Context<Self>,
11184 ) {
11185 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11187 s.move_cursors_with(|map, head, _| {
11188 (
11189 movement::line_end(map, head, action.stop_at_soft_wraps),
11190 SelectionGoal::None,
11191 )
11192 });
11193 })
11194 }
11195
11196 pub fn select_to_end_of_line(
11197 &mut self,
11198 action: &SelectToEndOfLine,
11199 window: &mut Window,
11200 cx: &mut Context<Self>,
11201 ) {
11202 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11203 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11204 s.move_heads_with(|map, head, _| {
11205 (
11206 movement::line_end(map, head, action.stop_at_soft_wraps),
11207 SelectionGoal::None,
11208 )
11209 });
11210 })
11211 }
11212
11213 pub fn delete_to_end_of_line(
11214 &mut self,
11215 _: &DeleteToEndOfLine,
11216 window: &mut Window,
11217 cx: &mut Context<Self>,
11218 ) {
11219 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11220 self.transact(window, cx, |this, window, cx| {
11221 this.select_to_end_of_line(
11222 &SelectToEndOfLine {
11223 stop_at_soft_wraps: false,
11224 },
11225 window,
11226 cx,
11227 );
11228 this.delete(&Delete, window, cx);
11229 });
11230 }
11231
11232 pub fn cut_to_end_of_line(
11233 &mut self,
11234 _: &CutToEndOfLine,
11235 window: &mut Window,
11236 cx: &mut Context<Self>,
11237 ) {
11238 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11239 self.transact(window, cx, |this, window, cx| {
11240 this.select_to_end_of_line(
11241 &SelectToEndOfLine {
11242 stop_at_soft_wraps: false,
11243 },
11244 window,
11245 cx,
11246 );
11247 this.cut(&Cut, window, cx);
11248 });
11249 }
11250
11251 pub fn move_to_start_of_paragraph(
11252 &mut self,
11253 _: &MoveToStartOfParagraph,
11254 window: &mut Window,
11255 cx: &mut Context<Self>,
11256 ) {
11257 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11258 cx.propagate();
11259 return;
11260 }
11261 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11262 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11263 s.move_with(|map, selection| {
11264 selection.collapse_to(
11265 movement::start_of_paragraph(map, selection.head(), 1),
11266 SelectionGoal::None,
11267 )
11268 });
11269 })
11270 }
11271
11272 pub fn move_to_end_of_paragraph(
11273 &mut self,
11274 _: &MoveToEndOfParagraph,
11275 window: &mut Window,
11276 cx: &mut Context<Self>,
11277 ) {
11278 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11279 cx.propagate();
11280 return;
11281 }
11282 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11283 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11284 s.move_with(|map, selection| {
11285 selection.collapse_to(
11286 movement::end_of_paragraph(map, selection.head(), 1),
11287 SelectionGoal::None,
11288 )
11289 });
11290 })
11291 }
11292
11293 pub fn select_to_start_of_paragraph(
11294 &mut self,
11295 _: &SelectToStartOfParagraph,
11296 window: &mut Window,
11297 cx: &mut Context<Self>,
11298 ) {
11299 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11300 cx.propagate();
11301 return;
11302 }
11303 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11304 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11305 s.move_heads_with(|map, head, _| {
11306 (
11307 movement::start_of_paragraph(map, head, 1),
11308 SelectionGoal::None,
11309 )
11310 });
11311 })
11312 }
11313
11314 pub fn select_to_end_of_paragraph(
11315 &mut self,
11316 _: &SelectToEndOfParagraph,
11317 window: &mut Window,
11318 cx: &mut Context<Self>,
11319 ) {
11320 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11321 cx.propagate();
11322 return;
11323 }
11324 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11325 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326 s.move_heads_with(|map, head, _| {
11327 (
11328 movement::end_of_paragraph(map, head, 1),
11329 SelectionGoal::None,
11330 )
11331 });
11332 })
11333 }
11334
11335 pub fn move_to_start_of_excerpt(
11336 &mut self,
11337 _: &MoveToStartOfExcerpt,
11338 window: &mut Window,
11339 cx: &mut Context<Self>,
11340 ) {
11341 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11342 cx.propagate();
11343 return;
11344 }
11345 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11346 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11347 s.move_with(|map, selection| {
11348 selection.collapse_to(
11349 movement::start_of_excerpt(
11350 map,
11351 selection.head(),
11352 workspace::searchable::Direction::Prev,
11353 ),
11354 SelectionGoal::None,
11355 )
11356 });
11357 })
11358 }
11359
11360 pub fn move_to_start_of_next_excerpt(
11361 &mut self,
11362 _: &MoveToStartOfNextExcerpt,
11363 window: &mut Window,
11364 cx: &mut Context<Self>,
11365 ) {
11366 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11367 cx.propagate();
11368 return;
11369 }
11370
11371 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11372 s.move_with(|map, selection| {
11373 selection.collapse_to(
11374 movement::start_of_excerpt(
11375 map,
11376 selection.head(),
11377 workspace::searchable::Direction::Next,
11378 ),
11379 SelectionGoal::None,
11380 )
11381 });
11382 })
11383 }
11384
11385 pub fn move_to_end_of_excerpt(
11386 &mut self,
11387 _: &MoveToEndOfExcerpt,
11388 window: &mut Window,
11389 cx: &mut Context<Self>,
11390 ) {
11391 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11392 cx.propagate();
11393 return;
11394 }
11395 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11396 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11397 s.move_with(|map, selection| {
11398 selection.collapse_to(
11399 movement::end_of_excerpt(
11400 map,
11401 selection.head(),
11402 workspace::searchable::Direction::Next,
11403 ),
11404 SelectionGoal::None,
11405 )
11406 });
11407 })
11408 }
11409
11410 pub fn move_to_end_of_previous_excerpt(
11411 &mut self,
11412 _: &MoveToEndOfPreviousExcerpt,
11413 window: &mut Window,
11414 cx: &mut Context<Self>,
11415 ) {
11416 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11417 cx.propagate();
11418 return;
11419 }
11420 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11421 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11422 s.move_with(|map, selection| {
11423 selection.collapse_to(
11424 movement::end_of_excerpt(
11425 map,
11426 selection.head(),
11427 workspace::searchable::Direction::Prev,
11428 ),
11429 SelectionGoal::None,
11430 )
11431 });
11432 })
11433 }
11434
11435 pub fn select_to_start_of_excerpt(
11436 &mut self,
11437 _: &SelectToStartOfExcerpt,
11438 window: &mut Window,
11439 cx: &mut Context<Self>,
11440 ) {
11441 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11442 cx.propagate();
11443 return;
11444 }
11445 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11447 s.move_heads_with(|map, head, _| {
11448 (
11449 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11450 SelectionGoal::None,
11451 )
11452 });
11453 })
11454 }
11455
11456 pub fn select_to_start_of_next_excerpt(
11457 &mut self,
11458 _: &SelectToStartOfNextExcerpt,
11459 window: &mut Window,
11460 cx: &mut Context<Self>,
11461 ) {
11462 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11463 cx.propagate();
11464 return;
11465 }
11466 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11468 s.move_heads_with(|map, head, _| {
11469 (
11470 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11471 SelectionGoal::None,
11472 )
11473 });
11474 })
11475 }
11476
11477 pub fn select_to_end_of_excerpt(
11478 &mut self,
11479 _: &SelectToEndOfExcerpt,
11480 window: &mut Window,
11481 cx: &mut Context<Self>,
11482 ) {
11483 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11484 cx.propagate();
11485 return;
11486 }
11487 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11488 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11489 s.move_heads_with(|map, head, _| {
11490 (
11491 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11492 SelectionGoal::None,
11493 )
11494 });
11495 })
11496 }
11497
11498 pub fn select_to_end_of_previous_excerpt(
11499 &mut self,
11500 _: &SelectToEndOfPreviousExcerpt,
11501 window: &mut Window,
11502 cx: &mut Context<Self>,
11503 ) {
11504 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11505 cx.propagate();
11506 return;
11507 }
11508 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11509 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11510 s.move_heads_with(|map, head, _| {
11511 (
11512 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11513 SelectionGoal::None,
11514 )
11515 });
11516 })
11517 }
11518
11519 pub fn move_to_beginning(
11520 &mut self,
11521 _: &MoveToBeginning,
11522 window: &mut Window,
11523 cx: &mut Context<Self>,
11524 ) {
11525 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11526 cx.propagate();
11527 return;
11528 }
11529 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531 s.select_ranges(vec![0..0]);
11532 });
11533 }
11534
11535 pub fn select_to_beginning(
11536 &mut self,
11537 _: &SelectToBeginning,
11538 window: &mut Window,
11539 cx: &mut Context<Self>,
11540 ) {
11541 let mut selection = self.selections.last::<Point>(cx);
11542 selection.set_head(Point::zero(), SelectionGoal::None);
11543 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11544 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11545 s.select(vec![selection]);
11546 });
11547 }
11548
11549 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11550 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11551 cx.propagate();
11552 return;
11553 }
11554 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11555 let cursor = self.buffer.read(cx).read(cx).len();
11556 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11557 s.select_ranges(vec![cursor..cursor])
11558 });
11559 }
11560
11561 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11562 self.nav_history = nav_history;
11563 }
11564
11565 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11566 self.nav_history.as_ref()
11567 }
11568
11569 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11570 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11571 }
11572
11573 fn push_to_nav_history(
11574 &mut self,
11575 cursor_anchor: Anchor,
11576 new_position: Option<Point>,
11577 is_deactivate: bool,
11578 cx: &mut Context<Self>,
11579 ) {
11580 if let Some(nav_history) = self.nav_history.as_mut() {
11581 let buffer = self.buffer.read(cx).read(cx);
11582 let cursor_position = cursor_anchor.to_point(&buffer);
11583 let scroll_state = self.scroll_manager.anchor();
11584 let scroll_top_row = scroll_state.top_row(&buffer);
11585 drop(buffer);
11586
11587 if let Some(new_position) = new_position {
11588 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11589 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11590 return;
11591 }
11592 }
11593
11594 nav_history.push(
11595 Some(NavigationData {
11596 cursor_anchor,
11597 cursor_position,
11598 scroll_anchor: scroll_state,
11599 scroll_top_row,
11600 }),
11601 cx,
11602 );
11603 cx.emit(EditorEvent::PushedToNavHistory {
11604 anchor: cursor_anchor,
11605 is_deactivate,
11606 })
11607 }
11608 }
11609
11610 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11611 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11612 let buffer = self.buffer.read(cx).snapshot(cx);
11613 let mut selection = self.selections.first::<usize>(cx);
11614 selection.set_head(buffer.len(), SelectionGoal::None);
11615 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11616 s.select(vec![selection]);
11617 });
11618 }
11619
11620 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11621 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11622 let end = self.buffer.read(cx).read(cx).len();
11623 self.change_selections(None, window, cx, |s| {
11624 s.select_ranges(vec![0..end]);
11625 });
11626 }
11627
11628 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11629 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11630 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11631 let mut selections = self.selections.all::<Point>(cx);
11632 let max_point = display_map.buffer_snapshot.max_point();
11633 for selection in &mut selections {
11634 let rows = selection.spanned_rows(true, &display_map);
11635 selection.start = Point::new(rows.start.0, 0);
11636 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11637 selection.reversed = false;
11638 }
11639 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11640 s.select(selections);
11641 });
11642 }
11643
11644 pub fn split_selection_into_lines(
11645 &mut self,
11646 _: &SplitSelectionIntoLines,
11647 window: &mut Window,
11648 cx: &mut Context<Self>,
11649 ) {
11650 let selections = self
11651 .selections
11652 .all::<Point>(cx)
11653 .into_iter()
11654 .map(|selection| selection.start..selection.end)
11655 .collect::<Vec<_>>();
11656 self.unfold_ranges(&selections, true, true, cx);
11657
11658 let mut new_selection_ranges = Vec::new();
11659 {
11660 let buffer = self.buffer.read(cx).read(cx);
11661 for selection in selections {
11662 for row in selection.start.row..selection.end.row {
11663 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11664 new_selection_ranges.push(cursor..cursor);
11665 }
11666
11667 let is_multiline_selection = selection.start.row != selection.end.row;
11668 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11669 // so this action feels more ergonomic when paired with other selection operations
11670 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11671 if !should_skip_last {
11672 new_selection_ranges.push(selection.end..selection.end);
11673 }
11674 }
11675 }
11676 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11677 s.select_ranges(new_selection_ranges);
11678 });
11679 }
11680
11681 pub fn add_selection_above(
11682 &mut self,
11683 _: &AddSelectionAbove,
11684 window: &mut Window,
11685 cx: &mut Context<Self>,
11686 ) {
11687 self.add_selection(true, window, cx);
11688 }
11689
11690 pub fn add_selection_below(
11691 &mut self,
11692 _: &AddSelectionBelow,
11693 window: &mut Window,
11694 cx: &mut Context<Self>,
11695 ) {
11696 self.add_selection(false, window, cx);
11697 }
11698
11699 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11700 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11701
11702 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11703 let mut selections = self.selections.all::<Point>(cx);
11704 let text_layout_details = self.text_layout_details(window);
11705 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11706 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11707 let range = oldest_selection.display_range(&display_map).sorted();
11708
11709 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11710 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11711 let positions = start_x.min(end_x)..start_x.max(end_x);
11712
11713 selections.clear();
11714 let mut stack = Vec::new();
11715 for row in range.start.row().0..=range.end.row().0 {
11716 if let Some(selection) = self.selections.build_columnar_selection(
11717 &display_map,
11718 DisplayRow(row),
11719 &positions,
11720 oldest_selection.reversed,
11721 &text_layout_details,
11722 ) {
11723 stack.push(selection.id);
11724 selections.push(selection);
11725 }
11726 }
11727
11728 if above {
11729 stack.reverse();
11730 }
11731
11732 AddSelectionsState { above, stack }
11733 });
11734
11735 let last_added_selection = *state.stack.last().unwrap();
11736 let mut new_selections = Vec::new();
11737 if above == state.above {
11738 let end_row = if above {
11739 DisplayRow(0)
11740 } else {
11741 display_map.max_point().row()
11742 };
11743
11744 'outer: for selection in selections {
11745 if selection.id == last_added_selection {
11746 let range = selection.display_range(&display_map).sorted();
11747 debug_assert_eq!(range.start.row(), range.end.row());
11748 let mut row = range.start.row();
11749 let positions =
11750 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11751 px(start)..px(end)
11752 } else {
11753 let start_x =
11754 display_map.x_for_display_point(range.start, &text_layout_details);
11755 let end_x =
11756 display_map.x_for_display_point(range.end, &text_layout_details);
11757 start_x.min(end_x)..start_x.max(end_x)
11758 };
11759
11760 while row != end_row {
11761 if above {
11762 row.0 -= 1;
11763 } else {
11764 row.0 += 1;
11765 }
11766
11767 if let Some(new_selection) = self.selections.build_columnar_selection(
11768 &display_map,
11769 row,
11770 &positions,
11771 selection.reversed,
11772 &text_layout_details,
11773 ) {
11774 state.stack.push(new_selection.id);
11775 if above {
11776 new_selections.push(new_selection);
11777 new_selections.push(selection);
11778 } else {
11779 new_selections.push(selection);
11780 new_selections.push(new_selection);
11781 }
11782
11783 continue 'outer;
11784 }
11785 }
11786 }
11787
11788 new_selections.push(selection);
11789 }
11790 } else {
11791 new_selections = selections;
11792 new_selections.retain(|s| s.id != last_added_selection);
11793 state.stack.pop();
11794 }
11795
11796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11797 s.select(new_selections);
11798 });
11799 if state.stack.len() > 1 {
11800 self.add_selections_state = Some(state);
11801 }
11802 }
11803
11804 pub fn select_next_match_internal(
11805 &mut self,
11806 display_map: &DisplaySnapshot,
11807 replace_newest: bool,
11808 autoscroll: Option<Autoscroll>,
11809 window: &mut Window,
11810 cx: &mut Context<Self>,
11811 ) -> Result<()> {
11812 fn select_next_match_ranges(
11813 this: &mut Editor,
11814 range: Range<usize>,
11815 replace_newest: bool,
11816 auto_scroll: Option<Autoscroll>,
11817 window: &mut Window,
11818 cx: &mut Context<Editor>,
11819 ) {
11820 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11821 this.change_selections(auto_scroll, window, cx, |s| {
11822 if replace_newest {
11823 s.delete(s.newest_anchor().id);
11824 }
11825 s.insert_range(range.clone());
11826 });
11827 }
11828
11829 let buffer = &display_map.buffer_snapshot;
11830 let mut selections = self.selections.all::<usize>(cx);
11831 if let Some(mut select_next_state) = self.select_next_state.take() {
11832 let query = &select_next_state.query;
11833 if !select_next_state.done {
11834 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11835 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11836 let mut next_selected_range = None;
11837
11838 let bytes_after_last_selection =
11839 buffer.bytes_in_range(last_selection.end..buffer.len());
11840 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11841 let query_matches = query
11842 .stream_find_iter(bytes_after_last_selection)
11843 .map(|result| (last_selection.end, result))
11844 .chain(
11845 query
11846 .stream_find_iter(bytes_before_first_selection)
11847 .map(|result| (0, result)),
11848 );
11849
11850 for (start_offset, query_match) in query_matches {
11851 let query_match = query_match.unwrap(); // can only fail due to I/O
11852 let offset_range =
11853 start_offset + query_match.start()..start_offset + query_match.end();
11854 let display_range = offset_range.start.to_display_point(display_map)
11855 ..offset_range.end.to_display_point(display_map);
11856
11857 if !select_next_state.wordwise
11858 || (!movement::is_inside_word(display_map, display_range.start)
11859 && !movement::is_inside_word(display_map, display_range.end))
11860 {
11861 // TODO: This is n^2, because we might check all the selections
11862 if !selections
11863 .iter()
11864 .any(|selection| selection.range().overlaps(&offset_range))
11865 {
11866 next_selected_range = Some(offset_range);
11867 break;
11868 }
11869 }
11870 }
11871
11872 if let Some(next_selected_range) = next_selected_range {
11873 select_next_match_ranges(
11874 self,
11875 next_selected_range,
11876 replace_newest,
11877 autoscroll,
11878 window,
11879 cx,
11880 );
11881 } else {
11882 select_next_state.done = true;
11883 }
11884 }
11885
11886 self.select_next_state = Some(select_next_state);
11887 } else {
11888 let mut only_carets = true;
11889 let mut same_text_selected = true;
11890 let mut selected_text = None;
11891
11892 let mut selections_iter = selections.iter().peekable();
11893 while let Some(selection) = selections_iter.next() {
11894 if selection.start != selection.end {
11895 only_carets = false;
11896 }
11897
11898 if same_text_selected {
11899 if selected_text.is_none() {
11900 selected_text =
11901 Some(buffer.text_for_range(selection.range()).collect::<String>());
11902 }
11903
11904 if let Some(next_selection) = selections_iter.peek() {
11905 if next_selection.range().len() == selection.range().len() {
11906 let next_selected_text = buffer
11907 .text_for_range(next_selection.range())
11908 .collect::<String>();
11909 if Some(next_selected_text) != selected_text {
11910 same_text_selected = false;
11911 selected_text = None;
11912 }
11913 } else {
11914 same_text_selected = false;
11915 selected_text = None;
11916 }
11917 }
11918 }
11919 }
11920
11921 if only_carets {
11922 for selection in &mut selections {
11923 let word_range = movement::surrounding_word(
11924 display_map,
11925 selection.start.to_display_point(display_map),
11926 );
11927 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11928 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11929 selection.goal = SelectionGoal::None;
11930 selection.reversed = false;
11931 select_next_match_ranges(
11932 self,
11933 selection.start..selection.end,
11934 replace_newest,
11935 autoscroll,
11936 window,
11937 cx,
11938 );
11939 }
11940
11941 if selections.len() == 1 {
11942 let selection = selections
11943 .last()
11944 .expect("ensured that there's only one selection");
11945 let query = buffer
11946 .text_for_range(selection.start..selection.end)
11947 .collect::<String>();
11948 let is_empty = query.is_empty();
11949 let select_state = SelectNextState {
11950 query: AhoCorasick::new(&[query])?,
11951 wordwise: true,
11952 done: is_empty,
11953 };
11954 self.select_next_state = Some(select_state);
11955 } else {
11956 self.select_next_state = None;
11957 }
11958 } else if let Some(selected_text) = selected_text {
11959 self.select_next_state = Some(SelectNextState {
11960 query: AhoCorasick::new(&[selected_text])?,
11961 wordwise: false,
11962 done: false,
11963 });
11964 self.select_next_match_internal(
11965 display_map,
11966 replace_newest,
11967 autoscroll,
11968 window,
11969 cx,
11970 )?;
11971 }
11972 }
11973 Ok(())
11974 }
11975
11976 pub fn select_all_matches(
11977 &mut self,
11978 _action: &SelectAllMatches,
11979 window: &mut Window,
11980 cx: &mut Context<Self>,
11981 ) -> Result<()> {
11982 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11983
11984 self.push_to_selection_history();
11985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11986
11987 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11988 let Some(select_next_state) = self.select_next_state.as_mut() else {
11989 return Ok(());
11990 };
11991 if select_next_state.done {
11992 return Ok(());
11993 }
11994
11995 let mut new_selections = Vec::new();
11996
11997 let reversed = self.selections.oldest::<usize>(cx).reversed;
11998 let buffer = &display_map.buffer_snapshot;
11999 let query_matches = select_next_state
12000 .query
12001 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12002
12003 for query_match in query_matches.into_iter() {
12004 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12005 let offset_range = if reversed {
12006 query_match.end()..query_match.start()
12007 } else {
12008 query_match.start()..query_match.end()
12009 };
12010 let display_range = offset_range.start.to_display_point(&display_map)
12011 ..offset_range.end.to_display_point(&display_map);
12012
12013 if !select_next_state.wordwise
12014 || (!movement::is_inside_word(&display_map, display_range.start)
12015 && !movement::is_inside_word(&display_map, display_range.end))
12016 {
12017 new_selections.push(offset_range.start..offset_range.end);
12018 }
12019 }
12020
12021 select_next_state.done = true;
12022 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12023 self.change_selections(None, window, cx, |selections| {
12024 selections.select_ranges(new_selections)
12025 });
12026
12027 Ok(())
12028 }
12029
12030 pub fn select_next(
12031 &mut self,
12032 action: &SelectNext,
12033 window: &mut Window,
12034 cx: &mut Context<Self>,
12035 ) -> Result<()> {
12036 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12037 self.push_to_selection_history();
12038 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12039 self.select_next_match_internal(
12040 &display_map,
12041 action.replace_newest,
12042 Some(Autoscroll::newest()),
12043 window,
12044 cx,
12045 )?;
12046 Ok(())
12047 }
12048
12049 pub fn select_previous(
12050 &mut self,
12051 action: &SelectPrevious,
12052 window: &mut Window,
12053 cx: &mut Context<Self>,
12054 ) -> Result<()> {
12055 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12056 self.push_to_selection_history();
12057 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12058 let buffer = &display_map.buffer_snapshot;
12059 let mut selections = self.selections.all::<usize>(cx);
12060 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12061 let query = &select_prev_state.query;
12062 if !select_prev_state.done {
12063 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12064 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12065 let mut next_selected_range = None;
12066 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12067 let bytes_before_last_selection =
12068 buffer.reversed_bytes_in_range(0..last_selection.start);
12069 let bytes_after_first_selection =
12070 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12071 let query_matches = query
12072 .stream_find_iter(bytes_before_last_selection)
12073 .map(|result| (last_selection.start, result))
12074 .chain(
12075 query
12076 .stream_find_iter(bytes_after_first_selection)
12077 .map(|result| (buffer.len(), result)),
12078 );
12079 for (end_offset, query_match) in query_matches {
12080 let query_match = query_match.unwrap(); // can only fail due to I/O
12081 let offset_range =
12082 end_offset - query_match.end()..end_offset - query_match.start();
12083 let display_range = offset_range.start.to_display_point(&display_map)
12084 ..offset_range.end.to_display_point(&display_map);
12085
12086 if !select_prev_state.wordwise
12087 || (!movement::is_inside_word(&display_map, display_range.start)
12088 && !movement::is_inside_word(&display_map, display_range.end))
12089 {
12090 next_selected_range = Some(offset_range);
12091 break;
12092 }
12093 }
12094
12095 if let Some(next_selected_range) = next_selected_range {
12096 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12097 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12098 if action.replace_newest {
12099 s.delete(s.newest_anchor().id);
12100 }
12101 s.insert_range(next_selected_range);
12102 });
12103 } else {
12104 select_prev_state.done = true;
12105 }
12106 }
12107
12108 self.select_prev_state = Some(select_prev_state);
12109 } else {
12110 let mut only_carets = true;
12111 let mut same_text_selected = true;
12112 let mut selected_text = None;
12113
12114 let mut selections_iter = selections.iter().peekable();
12115 while let Some(selection) = selections_iter.next() {
12116 if selection.start != selection.end {
12117 only_carets = false;
12118 }
12119
12120 if same_text_selected {
12121 if selected_text.is_none() {
12122 selected_text =
12123 Some(buffer.text_for_range(selection.range()).collect::<String>());
12124 }
12125
12126 if let Some(next_selection) = selections_iter.peek() {
12127 if next_selection.range().len() == selection.range().len() {
12128 let next_selected_text = buffer
12129 .text_for_range(next_selection.range())
12130 .collect::<String>();
12131 if Some(next_selected_text) != selected_text {
12132 same_text_selected = false;
12133 selected_text = None;
12134 }
12135 } else {
12136 same_text_selected = false;
12137 selected_text = None;
12138 }
12139 }
12140 }
12141 }
12142
12143 if only_carets {
12144 for selection in &mut selections {
12145 let word_range = movement::surrounding_word(
12146 &display_map,
12147 selection.start.to_display_point(&display_map),
12148 );
12149 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12150 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12151 selection.goal = SelectionGoal::None;
12152 selection.reversed = false;
12153 }
12154 if selections.len() == 1 {
12155 let selection = selections
12156 .last()
12157 .expect("ensured that there's only one selection");
12158 let query = buffer
12159 .text_for_range(selection.start..selection.end)
12160 .collect::<String>();
12161 let is_empty = query.is_empty();
12162 let select_state = SelectNextState {
12163 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12164 wordwise: true,
12165 done: is_empty,
12166 };
12167 self.select_prev_state = Some(select_state);
12168 } else {
12169 self.select_prev_state = None;
12170 }
12171
12172 self.unfold_ranges(
12173 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12174 false,
12175 true,
12176 cx,
12177 );
12178 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12179 s.select(selections);
12180 });
12181 } else if let Some(selected_text) = selected_text {
12182 self.select_prev_state = Some(SelectNextState {
12183 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12184 wordwise: false,
12185 done: false,
12186 });
12187 self.select_previous(action, window, cx)?;
12188 }
12189 }
12190 Ok(())
12191 }
12192
12193 pub fn find_next_match(
12194 &mut self,
12195 _: &FindNextMatch,
12196 window: &mut Window,
12197 cx: &mut Context<Self>,
12198 ) -> Result<()> {
12199 let selections = self.selections.disjoint_anchors();
12200 match selections.first() {
12201 Some(first) if selections.len() >= 2 => {
12202 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12203 s.select_ranges([first.range()]);
12204 });
12205 }
12206 _ => self.select_next(
12207 &SelectNext {
12208 replace_newest: true,
12209 },
12210 window,
12211 cx,
12212 )?,
12213 }
12214 Ok(())
12215 }
12216
12217 pub fn find_previous_match(
12218 &mut self,
12219 _: &FindPreviousMatch,
12220 window: &mut Window,
12221 cx: &mut Context<Self>,
12222 ) -> Result<()> {
12223 let selections = self.selections.disjoint_anchors();
12224 match selections.last() {
12225 Some(last) if selections.len() >= 2 => {
12226 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12227 s.select_ranges([last.range()]);
12228 });
12229 }
12230 _ => self.select_previous(
12231 &SelectPrevious {
12232 replace_newest: true,
12233 },
12234 window,
12235 cx,
12236 )?,
12237 }
12238 Ok(())
12239 }
12240
12241 pub fn toggle_comments(
12242 &mut self,
12243 action: &ToggleComments,
12244 window: &mut Window,
12245 cx: &mut Context<Self>,
12246 ) {
12247 if self.read_only(cx) {
12248 return;
12249 }
12250 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12251 let text_layout_details = &self.text_layout_details(window);
12252 self.transact(window, cx, |this, window, cx| {
12253 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12254 let mut edits = Vec::new();
12255 let mut selection_edit_ranges = Vec::new();
12256 let mut last_toggled_row = None;
12257 let snapshot = this.buffer.read(cx).read(cx);
12258 let empty_str: Arc<str> = Arc::default();
12259 let mut suffixes_inserted = Vec::new();
12260 let ignore_indent = action.ignore_indent;
12261
12262 fn comment_prefix_range(
12263 snapshot: &MultiBufferSnapshot,
12264 row: MultiBufferRow,
12265 comment_prefix: &str,
12266 comment_prefix_whitespace: &str,
12267 ignore_indent: bool,
12268 ) -> Range<Point> {
12269 let indent_size = if ignore_indent {
12270 0
12271 } else {
12272 snapshot.indent_size_for_line(row).len
12273 };
12274
12275 let start = Point::new(row.0, indent_size);
12276
12277 let mut line_bytes = snapshot
12278 .bytes_in_range(start..snapshot.max_point())
12279 .flatten()
12280 .copied();
12281
12282 // If this line currently begins with the line comment prefix, then record
12283 // the range containing the prefix.
12284 if line_bytes
12285 .by_ref()
12286 .take(comment_prefix.len())
12287 .eq(comment_prefix.bytes())
12288 {
12289 // Include any whitespace that matches the comment prefix.
12290 let matching_whitespace_len = line_bytes
12291 .zip(comment_prefix_whitespace.bytes())
12292 .take_while(|(a, b)| a == b)
12293 .count() as u32;
12294 let end = Point::new(
12295 start.row,
12296 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12297 );
12298 start..end
12299 } else {
12300 start..start
12301 }
12302 }
12303
12304 fn comment_suffix_range(
12305 snapshot: &MultiBufferSnapshot,
12306 row: MultiBufferRow,
12307 comment_suffix: &str,
12308 comment_suffix_has_leading_space: bool,
12309 ) -> Range<Point> {
12310 let end = Point::new(row.0, snapshot.line_len(row));
12311 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12312
12313 let mut line_end_bytes = snapshot
12314 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12315 .flatten()
12316 .copied();
12317
12318 let leading_space_len = if suffix_start_column > 0
12319 && line_end_bytes.next() == Some(b' ')
12320 && comment_suffix_has_leading_space
12321 {
12322 1
12323 } else {
12324 0
12325 };
12326
12327 // If this line currently begins with the line comment prefix, then record
12328 // the range containing the prefix.
12329 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12330 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12331 start..end
12332 } else {
12333 end..end
12334 }
12335 }
12336
12337 // TODO: Handle selections that cross excerpts
12338 for selection in &mut selections {
12339 let start_column = snapshot
12340 .indent_size_for_line(MultiBufferRow(selection.start.row))
12341 .len;
12342 let language = if let Some(language) =
12343 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12344 {
12345 language
12346 } else {
12347 continue;
12348 };
12349
12350 selection_edit_ranges.clear();
12351
12352 // If multiple selections contain a given row, avoid processing that
12353 // row more than once.
12354 let mut start_row = MultiBufferRow(selection.start.row);
12355 if last_toggled_row == Some(start_row) {
12356 start_row = start_row.next_row();
12357 }
12358 let end_row =
12359 if selection.end.row > selection.start.row && selection.end.column == 0 {
12360 MultiBufferRow(selection.end.row - 1)
12361 } else {
12362 MultiBufferRow(selection.end.row)
12363 };
12364 last_toggled_row = Some(end_row);
12365
12366 if start_row > end_row {
12367 continue;
12368 }
12369
12370 // If the language has line comments, toggle those.
12371 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12372
12373 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12374 if ignore_indent {
12375 full_comment_prefixes = full_comment_prefixes
12376 .into_iter()
12377 .map(|s| Arc::from(s.trim_end()))
12378 .collect();
12379 }
12380
12381 if !full_comment_prefixes.is_empty() {
12382 let first_prefix = full_comment_prefixes
12383 .first()
12384 .expect("prefixes is non-empty");
12385 let prefix_trimmed_lengths = full_comment_prefixes
12386 .iter()
12387 .map(|p| p.trim_end_matches(' ').len())
12388 .collect::<SmallVec<[usize; 4]>>();
12389
12390 let mut all_selection_lines_are_comments = true;
12391
12392 for row in start_row.0..=end_row.0 {
12393 let row = MultiBufferRow(row);
12394 if start_row < end_row && snapshot.is_line_blank(row) {
12395 continue;
12396 }
12397
12398 let prefix_range = full_comment_prefixes
12399 .iter()
12400 .zip(prefix_trimmed_lengths.iter().copied())
12401 .map(|(prefix, trimmed_prefix_len)| {
12402 comment_prefix_range(
12403 snapshot.deref(),
12404 row,
12405 &prefix[..trimmed_prefix_len],
12406 &prefix[trimmed_prefix_len..],
12407 ignore_indent,
12408 )
12409 })
12410 .max_by_key(|range| range.end.column - range.start.column)
12411 .expect("prefixes is non-empty");
12412
12413 if prefix_range.is_empty() {
12414 all_selection_lines_are_comments = false;
12415 }
12416
12417 selection_edit_ranges.push(prefix_range);
12418 }
12419
12420 if all_selection_lines_are_comments {
12421 edits.extend(
12422 selection_edit_ranges
12423 .iter()
12424 .cloned()
12425 .map(|range| (range, empty_str.clone())),
12426 );
12427 } else {
12428 let min_column = selection_edit_ranges
12429 .iter()
12430 .map(|range| range.start.column)
12431 .min()
12432 .unwrap_or(0);
12433 edits.extend(selection_edit_ranges.iter().map(|range| {
12434 let position = Point::new(range.start.row, min_column);
12435 (position..position, first_prefix.clone())
12436 }));
12437 }
12438 } else if let Some((full_comment_prefix, comment_suffix)) =
12439 language.block_comment_delimiters()
12440 {
12441 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12442 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12443 let prefix_range = comment_prefix_range(
12444 snapshot.deref(),
12445 start_row,
12446 comment_prefix,
12447 comment_prefix_whitespace,
12448 ignore_indent,
12449 );
12450 let suffix_range = comment_suffix_range(
12451 snapshot.deref(),
12452 end_row,
12453 comment_suffix.trim_start_matches(' '),
12454 comment_suffix.starts_with(' '),
12455 );
12456
12457 if prefix_range.is_empty() || suffix_range.is_empty() {
12458 edits.push((
12459 prefix_range.start..prefix_range.start,
12460 full_comment_prefix.clone(),
12461 ));
12462 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12463 suffixes_inserted.push((end_row, comment_suffix.len()));
12464 } else {
12465 edits.push((prefix_range, empty_str.clone()));
12466 edits.push((suffix_range, empty_str.clone()));
12467 }
12468 } else {
12469 continue;
12470 }
12471 }
12472
12473 drop(snapshot);
12474 this.buffer.update(cx, |buffer, cx| {
12475 buffer.edit(edits, None, cx);
12476 });
12477
12478 // Adjust selections so that they end before any comment suffixes that
12479 // were inserted.
12480 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12481 let mut selections = this.selections.all::<Point>(cx);
12482 let snapshot = this.buffer.read(cx).read(cx);
12483 for selection in &mut selections {
12484 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12485 match row.cmp(&MultiBufferRow(selection.end.row)) {
12486 Ordering::Less => {
12487 suffixes_inserted.next();
12488 continue;
12489 }
12490 Ordering::Greater => break,
12491 Ordering::Equal => {
12492 if selection.end.column == snapshot.line_len(row) {
12493 if selection.is_empty() {
12494 selection.start.column -= suffix_len as u32;
12495 }
12496 selection.end.column -= suffix_len as u32;
12497 }
12498 break;
12499 }
12500 }
12501 }
12502 }
12503
12504 drop(snapshot);
12505 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12506 s.select(selections)
12507 });
12508
12509 let selections = this.selections.all::<Point>(cx);
12510 let selections_on_single_row = selections.windows(2).all(|selections| {
12511 selections[0].start.row == selections[1].start.row
12512 && selections[0].end.row == selections[1].end.row
12513 && selections[0].start.row == selections[0].end.row
12514 });
12515 let selections_selecting = selections
12516 .iter()
12517 .any(|selection| selection.start != selection.end);
12518 let advance_downwards = action.advance_downwards
12519 && selections_on_single_row
12520 && !selections_selecting
12521 && !matches!(this.mode, EditorMode::SingleLine { .. });
12522
12523 if advance_downwards {
12524 let snapshot = this.buffer.read(cx).snapshot(cx);
12525
12526 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12527 s.move_cursors_with(|display_snapshot, display_point, _| {
12528 let mut point = display_point.to_point(display_snapshot);
12529 point.row += 1;
12530 point = snapshot.clip_point(point, Bias::Left);
12531 let display_point = point.to_display_point(display_snapshot);
12532 let goal = SelectionGoal::HorizontalPosition(
12533 display_snapshot
12534 .x_for_display_point(display_point, text_layout_details)
12535 .into(),
12536 );
12537 (display_point, goal)
12538 })
12539 });
12540 }
12541 });
12542 }
12543
12544 pub fn select_enclosing_symbol(
12545 &mut self,
12546 _: &SelectEnclosingSymbol,
12547 window: &mut Window,
12548 cx: &mut Context<Self>,
12549 ) {
12550 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12551
12552 let buffer = self.buffer.read(cx).snapshot(cx);
12553 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12554
12555 fn update_selection(
12556 selection: &Selection<usize>,
12557 buffer_snap: &MultiBufferSnapshot,
12558 ) -> Option<Selection<usize>> {
12559 let cursor = selection.head();
12560 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12561 for symbol in symbols.iter().rev() {
12562 let start = symbol.range.start.to_offset(buffer_snap);
12563 let end = symbol.range.end.to_offset(buffer_snap);
12564 let new_range = start..end;
12565 if start < selection.start || end > selection.end {
12566 return Some(Selection {
12567 id: selection.id,
12568 start: new_range.start,
12569 end: new_range.end,
12570 goal: SelectionGoal::None,
12571 reversed: selection.reversed,
12572 });
12573 }
12574 }
12575 None
12576 }
12577
12578 let mut selected_larger_symbol = false;
12579 let new_selections = old_selections
12580 .iter()
12581 .map(|selection| match update_selection(selection, &buffer) {
12582 Some(new_selection) => {
12583 if new_selection.range() != selection.range() {
12584 selected_larger_symbol = true;
12585 }
12586 new_selection
12587 }
12588 None => selection.clone(),
12589 })
12590 .collect::<Vec<_>>();
12591
12592 if selected_larger_symbol {
12593 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12594 s.select(new_selections);
12595 });
12596 }
12597 }
12598
12599 pub fn select_larger_syntax_node(
12600 &mut self,
12601 _: &SelectLargerSyntaxNode,
12602 window: &mut Window,
12603 cx: &mut Context<Self>,
12604 ) {
12605 let Some(visible_row_count) = self.visible_row_count() else {
12606 return;
12607 };
12608 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12609 if old_selections.is_empty() {
12610 return;
12611 }
12612
12613 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12614
12615 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12616 let buffer = self.buffer.read(cx).snapshot(cx);
12617
12618 let mut selected_larger_node = false;
12619 let mut new_selections = old_selections
12620 .iter()
12621 .map(|selection| {
12622 let old_range = selection.start..selection.end;
12623
12624 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12625 // manually select word at selection
12626 if ["string_content", "inline"].contains(&node.kind()) {
12627 let word_range = {
12628 let display_point = buffer
12629 .offset_to_point(old_range.start)
12630 .to_display_point(&display_map);
12631 let Range { start, end } =
12632 movement::surrounding_word(&display_map, display_point);
12633 start.to_point(&display_map).to_offset(&buffer)
12634 ..end.to_point(&display_map).to_offset(&buffer)
12635 };
12636 // ignore if word is already selected
12637 if !word_range.is_empty() && old_range != word_range {
12638 let last_word_range = {
12639 let display_point = buffer
12640 .offset_to_point(old_range.end)
12641 .to_display_point(&display_map);
12642 let Range { start, end } =
12643 movement::surrounding_word(&display_map, display_point);
12644 start.to_point(&display_map).to_offset(&buffer)
12645 ..end.to_point(&display_map).to_offset(&buffer)
12646 };
12647 // only select word if start and end point belongs to same word
12648 if word_range == last_word_range {
12649 selected_larger_node = true;
12650 return Selection {
12651 id: selection.id,
12652 start: word_range.start,
12653 end: word_range.end,
12654 goal: SelectionGoal::None,
12655 reversed: selection.reversed,
12656 };
12657 }
12658 }
12659 }
12660 }
12661
12662 let mut new_range = old_range.clone();
12663 let mut new_node = None;
12664 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12665 {
12666 new_node = Some(node);
12667 new_range = match containing_range {
12668 MultiOrSingleBufferOffsetRange::Single(_) => break,
12669 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12670 };
12671 if !display_map.intersects_fold(new_range.start)
12672 && !display_map.intersects_fold(new_range.end)
12673 {
12674 break;
12675 }
12676 }
12677
12678 if let Some(node) = new_node {
12679 // Log the ancestor, to support using this action as a way to explore TreeSitter
12680 // nodes. Parent and grandparent are also logged because this operation will not
12681 // visit nodes that have the same range as their parent.
12682 log::info!("Node: {node:?}");
12683 let parent = node.parent();
12684 log::info!("Parent: {parent:?}");
12685 let grandparent = parent.and_then(|x| x.parent());
12686 log::info!("Grandparent: {grandparent:?}");
12687 }
12688
12689 selected_larger_node |= new_range != old_range;
12690 Selection {
12691 id: selection.id,
12692 start: new_range.start,
12693 end: new_range.end,
12694 goal: SelectionGoal::None,
12695 reversed: selection.reversed,
12696 }
12697 })
12698 .collect::<Vec<_>>();
12699
12700 if !selected_larger_node {
12701 return; // don't put this call in the history
12702 }
12703
12704 // scroll based on transformation done to the last selection created by the user
12705 let (last_old, last_new) = old_selections
12706 .last()
12707 .zip(new_selections.last().cloned())
12708 .expect("old_selections isn't empty");
12709
12710 // revert selection
12711 let is_selection_reversed = {
12712 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12713 new_selections.last_mut().expect("checked above").reversed =
12714 should_newest_selection_be_reversed;
12715 should_newest_selection_be_reversed
12716 };
12717
12718 if selected_larger_node {
12719 self.select_syntax_node_history.disable_clearing = true;
12720 self.change_selections(None, window, cx, |s| {
12721 s.select(new_selections.clone());
12722 });
12723 self.select_syntax_node_history.disable_clearing = false;
12724 }
12725
12726 let start_row = last_new.start.to_display_point(&display_map).row().0;
12727 let end_row = last_new.end.to_display_point(&display_map).row().0;
12728 let selection_height = end_row - start_row + 1;
12729 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12730
12731 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12732 let scroll_behavior = if fits_on_the_screen {
12733 self.request_autoscroll(Autoscroll::fit(), cx);
12734 SelectSyntaxNodeScrollBehavior::FitSelection
12735 } else if is_selection_reversed {
12736 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12737 SelectSyntaxNodeScrollBehavior::CursorTop
12738 } else {
12739 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12740 SelectSyntaxNodeScrollBehavior::CursorBottom
12741 };
12742
12743 self.select_syntax_node_history.push((
12744 old_selections,
12745 scroll_behavior,
12746 is_selection_reversed,
12747 ));
12748 }
12749
12750 pub fn select_smaller_syntax_node(
12751 &mut self,
12752 _: &SelectSmallerSyntaxNode,
12753 window: &mut Window,
12754 cx: &mut Context<Self>,
12755 ) {
12756 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12757
12758 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12759 self.select_syntax_node_history.pop()
12760 {
12761 if let Some(selection) = selections.last_mut() {
12762 selection.reversed = is_selection_reversed;
12763 }
12764
12765 self.select_syntax_node_history.disable_clearing = true;
12766 self.change_selections(None, window, cx, |s| {
12767 s.select(selections.to_vec());
12768 });
12769 self.select_syntax_node_history.disable_clearing = false;
12770
12771 match scroll_behavior {
12772 SelectSyntaxNodeScrollBehavior::CursorTop => {
12773 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12774 }
12775 SelectSyntaxNodeScrollBehavior::FitSelection => {
12776 self.request_autoscroll(Autoscroll::fit(), cx);
12777 }
12778 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12779 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12780 }
12781 }
12782 }
12783 }
12784
12785 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12786 if !EditorSettings::get_global(cx).gutter.runnables {
12787 self.clear_tasks();
12788 return Task::ready(());
12789 }
12790 let project = self.project.as_ref().map(Entity::downgrade);
12791 let task_sources = self.lsp_task_sources(cx);
12792 cx.spawn_in(window, async move |editor, cx| {
12793 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12794 let Some(project) = project.and_then(|p| p.upgrade()) else {
12795 return;
12796 };
12797 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12798 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12799 }) else {
12800 return;
12801 };
12802
12803 let hide_runnables = project
12804 .update(cx, |project, cx| {
12805 // Do not display any test indicators in non-dev server remote projects.
12806 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12807 })
12808 .unwrap_or(true);
12809 if hide_runnables {
12810 return;
12811 }
12812 let new_rows =
12813 cx.background_spawn({
12814 let snapshot = display_snapshot.clone();
12815 async move {
12816 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12817 }
12818 })
12819 .await;
12820 let Ok(lsp_tasks) =
12821 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12822 else {
12823 return;
12824 };
12825 let lsp_tasks = lsp_tasks.await;
12826
12827 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12828 lsp_tasks
12829 .into_iter()
12830 .flat_map(|(kind, tasks)| {
12831 tasks.into_iter().filter_map(move |(location, task)| {
12832 Some((kind.clone(), location?, task))
12833 })
12834 })
12835 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12836 let buffer = location.target.buffer;
12837 let buffer_snapshot = buffer.read(cx).snapshot();
12838 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12839 |(excerpt_id, snapshot, _)| {
12840 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12841 display_snapshot
12842 .buffer_snapshot
12843 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12844 } else {
12845 None
12846 }
12847 },
12848 );
12849 if let Some(offset) = offset {
12850 let task_buffer_range =
12851 location.target.range.to_point(&buffer_snapshot);
12852 let context_buffer_range =
12853 task_buffer_range.to_offset(&buffer_snapshot);
12854 let context_range = BufferOffset(context_buffer_range.start)
12855 ..BufferOffset(context_buffer_range.end);
12856
12857 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12858 .or_insert_with(|| RunnableTasks {
12859 templates: Vec::new(),
12860 offset,
12861 column: task_buffer_range.start.column,
12862 extra_variables: HashMap::default(),
12863 context_range,
12864 })
12865 .templates
12866 .push((kind, task.original_task().clone()));
12867 }
12868
12869 acc
12870 })
12871 }) else {
12872 return;
12873 };
12874
12875 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12876 editor
12877 .update(cx, |editor, _| {
12878 editor.clear_tasks();
12879 for (key, mut value) in rows {
12880 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12881 value.templates.extend(lsp_tasks.templates);
12882 }
12883
12884 editor.insert_tasks(key, value);
12885 }
12886 for (key, value) in lsp_tasks_by_rows {
12887 editor.insert_tasks(key, value);
12888 }
12889 })
12890 .ok();
12891 })
12892 }
12893 fn fetch_runnable_ranges(
12894 snapshot: &DisplaySnapshot,
12895 range: Range<Anchor>,
12896 ) -> Vec<language::RunnableRange> {
12897 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12898 }
12899
12900 fn runnable_rows(
12901 project: Entity<Project>,
12902 snapshot: DisplaySnapshot,
12903 runnable_ranges: Vec<RunnableRange>,
12904 mut cx: AsyncWindowContext,
12905 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12906 runnable_ranges
12907 .into_iter()
12908 .filter_map(|mut runnable| {
12909 let tasks = cx
12910 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12911 .ok()?;
12912 if tasks.is_empty() {
12913 return None;
12914 }
12915
12916 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12917
12918 let row = snapshot
12919 .buffer_snapshot
12920 .buffer_line_for_row(MultiBufferRow(point.row))?
12921 .1
12922 .start
12923 .row;
12924
12925 let context_range =
12926 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12927 Some((
12928 (runnable.buffer_id, row),
12929 RunnableTasks {
12930 templates: tasks,
12931 offset: snapshot
12932 .buffer_snapshot
12933 .anchor_before(runnable.run_range.start),
12934 context_range,
12935 column: point.column,
12936 extra_variables: runnable.extra_captures,
12937 },
12938 ))
12939 })
12940 .collect()
12941 }
12942
12943 fn templates_with_tags(
12944 project: &Entity<Project>,
12945 runnable: &mut Runnable,
12946 cx: &mut App,
12947 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12948 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12949 let (worktree_id, file) = project
12950 .buffer_for_id(runnable.buffer, cx)
12951 .and_then(|buffer| buffer.read(cx).file())
12952 .map(|file| (file.worktree_id(cx), file.clone()))
12953 .unzip();
12954
12955 (
12956 project.task_store().read(cx).task_inventory().cloned(),
12957 worktree_id,
12958 file,
12959 )
12960 });
12961
12962 let mut templates_with_tags = mem::take(&mut runnable.tags)
12963 .into_iter()
12964 .flat_map(|RunnableTag(tag)| {
12965 inventory
12966 .as_ref()
12967 .into_iter()
12968 .flat_map(|inventory| {
12969 inventory.read(cx).list_tasks(
12970 file.clone(),
12971 Some(runnable.language.clone()),
12972 worktree_id,
12973 cx,
12974 )
12975 })
12976 .filter(move |(_, template)| {
12977 template.tags.iter().any(|source_tag| source_tag == &tag)
12978 })
12979 })
12980 .sorted_by_key(|(kind, _)| kind.to_owned())
12981 .collect::<Vec<_>>();
12982 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12983 // Strongest source wins; if we have worktree tag binding, prefer that to
12984 // global and language bindings;
12985 // if we have a global binding, prefer that to language binding.
12986 let first_mismatch = templates_with_tags
12987 .iter()
12988 .position(|(tag_source, _)| tag_source != leading_tag_source);
12989 if let Some(index) = first_mismatch {
12990 templates_with_tags.truncate(index);
12991 }
12992 }
12993
12994 templates_with_tags
12995 }
12996
12997 pub fn move_to_enclosing_bracket(
12998 &mut self,
12999 _: &MoveToEnclosingBracket,
13000 window: &mut Window,
13001 cx: &mut Context<Self>,
13002 ) {
13003 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13004 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13005 s.move_offsets_with(|snapshot, selection| {
13006 let Some(enclosing_bracket_ranges) =
13007 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13008 else {
13009 return;
13010 };
13011
13012 let mut best_length = usize::MAX;
13013 let mut best_inside = false;
13014 let mut best_in_bracket_range = false;
13015 let mut best_destination = None;
13016 for (open, close) in enclosing_bracket_ranges {
13017 let close = close.to_inclusive();
13018 let length = close.end() - open.start;
13019 let inside = selection.start >= open.end && selection.end <= *close.start();
13020 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13021 || close.contains(&selection.head());
13022
13023 // If best is next to a bracket and current isn't, skip
13024 if !in_bracket_range && best_in_bracket_range {
13025 continue;
13026 }
13027
13028 // Prefer smaller lengths unless best is inside and current isn't
13029 if length > best_length && (best_inside || !inside) {
13030 continue;
13031 }
13032
13033 best_length = length;
13034 best_inside = inside;
13035 best_in_bracket_range = in_bracket_range;
13036 best_destination = Some(
13037 if close.contains(&selection.start) && close.contains(&selection.end) {
13038 if inside { open.end } else { open.start }
13039 } else if inside {
13040 *close.start()
13041 } else {
13042 *close.end()
13043 },
13044 );
13045 }
13046
13047 if let Some(destination) = best_destination {
13048 selection.collapse_to(destination, SelectionGoal::None);
13049 }
13050 })
13051 });
13052 }
13053
13054 pub fn undo_selection(
13055 &mut self,
13056 _: &UndoSelection,
13057 window: &mut Window,
13058 cx: &mut Context<Self>,
13059 ) {
13060 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13061 self.end_selection(window, cx);
13062 self.selection_history.mode = SelectionHistoryMode::Undoing;
13063 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13064 self.change_selections(None, window, cx, |s| {
13065 s.select_anchors(entry.selections.to_vec())
13066 });
13067 self.select_next_state = entry.select_next_state;
13068 self.select_prev_state = entry.select_prev_state;
13069 self.add_selections_state = entry.add_selections_state;
13070 self.request_autoscroll(Autoscroll::newest(), cx);
13071 }
13072 self.selection_history.mode = SelectionHistoryMode::Normal;
13073 }
13074
13075 pub fn redo_selection(
13076 &mut self,
13077 _: &RedoSelection,
13078 window: &mut Window,
13079 cx: &mut Context<Self>,
13080 ) {
13081 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13082 self.end_selection(window, cx);
13083 self.selection_history.mode = SelectionHistoryMode::Redoing;
13084 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13085 self.change_selections(None, window, cx, |s| {
13086 s.select_anchors(entry.selections.to_vec())
13087 });
13088 self.select_next_state = entry.select_next_state;
13089 self.select_prev_state = entry.select_prev_state;
13090 self.add_selections_state = entry.add_selections_state;
13091 self.request_autoscroll(Autoscroll::newest(), cx);
13092 }
13093 self.selection_history.mode = SelectionHistoryMode::Normal;
13094 }
13095
13096 pub fn expand_excerpts(
13097 &mut self,
13098 action: &ExpandExcerpts,
13099 _: &mut Window,
13100 cx: &mut Context<Self>,
13101 ) {
13102 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13103 }
13104
13105 pub fn expand_excerpts_down(
13106 &mut self,
13107 action: &ExpandExcerptsDown,
13108 _: &mut Window,
13109 cx: &mut Context<Self>,
13110 ) {
13111 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13112 }
13113
13114 pub fn expand_excerpts_up(
13115 &mut self,
13116 action: &ExpandExcerptsUp,
13117 _: &mut Window,
13118 cx: &mut Context<Self>,
13119 ) {
13120 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13121 }
13122
13123 pub fn expand_excerpts_for_direction(
13124 &mut self,
13125 lines: u32,
13126 direction: ExpandExcerptDirection,
13127
13128 cx: &mut Context<Self>,
13129 ) {
13130 let selections = self.selections.disjoint_anchors();
13131
13132 let lines = if lines == 0 {
13133 EditorSettings::get_global(cx).expand_excerpt_lines
13134 } else {
13135 lines
13136 };
13137
13138 self.buffer.update(cx, |buffer, cx| {
13139 let snapshot = buffer.snapshot(cx);
13140 let mut excerpt_ids = selections
13141 .iter()
13142 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13143 .collect::<Vec<_>>();
13144 excerpt_ids.sort();
13145 excerpt_ids.dedup();
13146 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13147 })
13148 }
13149
13150 pub fn expand_excerpt(
13151 &mut self,
13152 excerpt: ExcerptId,
13153 direction: ExpandExcerptDirection,
13154 window: &mut Window,
13155 cx: &mut Context<Self>,
13156 ) {
13157 let current_scroll_position = self.scroll_position(cx);
13158 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13159 let mut should_scroll_up = false;
13160
13161 if direction == ExpandExcerptDirection::Down {
13162 let multi_buffer = self.buffer.read(cx);
13163 let snapshot = multi_buffer.snapshot(cx);
13164 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13165 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13166 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13167 let buffer_snapshot = buffer.read(cx).snapshot();
13168 let excerpt_end_row =
13169 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13170 let last_row = buffer_snapshot.max_point().row;
13171 let lines_below = last_row.saturating_sub(excerpt_end_row);
13172 should_scroll_up = lines_below >= lines_to_expand;
13173 }
13174 }
13175 }
13176 }
13177
13178 self.buffer.update(cx, |buffer, cx| {
13179 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13180 });
13181
13182 if should_scroll_up {
13183 let new_scroll_position =
13184 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13185 self.set_scroll_position(new_scroll_position, window, cx);
13186 }
13187 }
13188
13189 pub fn go_to_singleton_buffer_point(
13190 &mut self,
13191 point: Point,
13192 window: &mut Window,
13193 cx: &mut Context<Self>,
13194 ) {
13195 self.go_to_singleton_buffer_range(point..point, window, cx);
13196 }
13197
13198 pub fn go_to_singleton_buffer_range(
13199 &mut self,
13200 range: Range<Point>,
13201 window: &mut Window,
13202 cx: &mut Context<Self>,
13203 ) {
13204 let multibuffer = self.buffer().read(cx);
13205 let Some(buffer) = multibuffer.as_singleton() else {
13206 return;
13207 };
13208 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13209 return;
13210 };
13211 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13212 return;
13213 };
13214 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13215 s.select_anchor_ranges([start..end])
13216 });
13217 }
13218
13219 pub fn go_to_diagnostic(
13220 &mut self,
13221 _: &GoToDiagnostic,
13222 window: &mut Window,
13223 cx: &mut Context<Self>,
13224 ) {
13225 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13226 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13227 }
13228
13229 pub fn go_to_prev_diagnostic(
13230 &mut self,
13231 _: &GoToPreviousDiagnostic,
13232 window: &mut Window,
13233 cx: &mut Context<Self>,
13234 ) {
13235 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13236 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13237 }
13238
13239 pub fn go_to_diagnostic_impl(
13240 &mut self,
13241 direction: Direction,
13242 window: &mut Window,
13243 cx: &mut Context<Self>,
13244 ) {
13245 let buffer = self.buffer.read(cx).snapshot(cx);
13246 let selection = self.selections.newest::<usize>(cx);
13247
13248 let mut active_group_id = None;
13249 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13250 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13251 active_group_id = Some(active_group.group_id);
13252 }
13253 }
13254
13255 fn filtered(
13256 snapshot: EditorSnapshot,
13257 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13258 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13259 diagnostics
13260 .filter(|entry| entry.range.start != entry.range.end)
13261 .filter(|entry| !entry.diagnostic.is_unnecessary)
13262 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13263 }
13264
13265 let snapshot = self.snapshot(window, cx);
13266 let before = filtered(
13267 snapshot.clone(),
13268 buffer
13269 .diagnostics_in_range(0..selection.start)
13270 .filter(|entry| entry.range.start <= selection.start),
13271 );
13272 let after = filtered(
13273 snapshot,
13274 buffer
13275 .diagnostics_in_range(selection.start..buffer.len())
13276 .filter(|entry| entry.range.start >= selection.start),
13277 );
13278
13279 let mut found: Option<DiagnosticEntry<usize>> = None;
13280 if direction == Direction::Prev {
13281 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13282 {
13283 for diagnostic in prev_diagnostics.into_iter().rev() {
13284 if diagnostic.range.start != selection.start
13285 || active_group_id
13286 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13287 {
13288 found = Some(diagnostic);
13289 break 'outer;
13290 }
13291 }
13292 }
13293 } else {
13294 for diagnostic in after.chain(before) {
13295 if diagnostic.range.start != selection.start
13296 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13297 {
13298 found = Some(diagnostic);
13299 break;
13300 }
13301 }
13302 }
13303 let Some(next_diagnostic) = found else {
13304 return;
13305 };
13306
13307 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13308 return;
13309 };
13310 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13311 s.select_ranges(vec![
13312 next_diagnostic.range.start..next_diagnostic.range.start,
13313 ])
13314 });
13315 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13316 self.refresh_inline_completion(false, true, window, cx);
13317 }
13318
13319 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13320 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13321 let snapshot = self.snapshot(window, cx);
13322 let selection = self.selections.newest::<Point>(cx);
13323 self.go_to_hunk_before_or_after_position(
13324 &snapshot,
13325 selection.head(),
13326 Direction::Next,
13327 window,
13328 cx,
13329 );
13330 }
13331
13332 pub fn go_to_hunk_before_or_after_position(
13333 &mut self,
13334 snapshot: &EditorSnapshot,
13335 position: Point,
13336 direction: Direction,
13337 window: &mut Window,
13338 cx: &mut Context<Editor>,
13339 ) {
13340 let row = if direction == Direction::Next {
13341 self.hunk_after_position(snapshot, position)
13342 .map(|hunk| hunk.row_range.start)
13343 } else {
13344 self.hunk_before_position(snapshot, position)
13345 };
13346
13347 if let Some(row) = row {
13348 let destination = Point::new(row.0, 0);
13349 let autoscroll = Autoscroll::center();
13350
13351 self.unfold_ranges(&[destination..destination], false, false, cx);
13352 self.change_selections(Some(autoscroll), window, cx, |s| {
13353 s.select_ranges([destination..destination]);
13354 });
13355 }
13356 }
13357
13358 fn hunk_after_position(
13359 &mut self,
13360 snapshot: &EditorSnapshot,
13361 position: Point,
13362 ) -> Option<MultiBufferDiffHunk> {
13363 snapshot
13364 .buffer_snapshot
13365 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13366 .find(|hunk| hunk.row_range.start.0 > position.row)
13367 .or_else(|| {
13368 snapshot
13369 .buffer_snapshot
13370 .diff_hunks_in_range(Point::zero()..position)
13371 .find(|hunk| hunk.row_range.end.0 < position.row)
13372 })
13373 }
13374
13375 fn go_to_prev_hunk(
13376 &mut self,
13377 _: &GoToPreviousHunk,
13378 window: &mut Window,
13379 cx: &mut Context<Self>,
13380 ) {
13381 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13382 let snapshot = self.snapshot(window, cx);
13383 let selection = self.selections.newest::<Point>(cx);
13384 self.go_to_hunk_before_or_after_position(
13385 &snapshot,
13386 selection.head(),
13387 Direction::Prev,
13388 window,
13389 cx,
13390 );
13391 }
13392
13393 fn hunk_before_position(
13394 &mut self,
13395 snapshot: &EditorSnapshot,
13396 position: Point,
13397 ) -> Option<MultiBufferRow> {
13398 snapshot
13399 .buffer_snapshot
13400 .diff_hunk_before(position)
13401 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13402 }
13403
13404 fn go_to_next_change(
13405 &mut self,
13406 _: &GoToNextChange,
13407 window: &mut Window,
13408 cx: &mut Context<Self>,
13409 ) {
13410 if let Some(selections) = self
13411 .change_list
13412 .next_change(1, Direction::Next)
13413 .map(|s| s.to_vec())
13414 {
13415 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13416 let map = s.display_map();
13417 s.select_display_ranges(selections.iter().map(|a| {
13418 let point = a.to_display_point(&map);
13419 point..point
13420 }))
13421 })
13422 }
13423 }
13424
13425 fn go_to_previous_change(
13426 &mut self,
13427 _: &GoToPreviousChange,
13428 window: &mut Window,
13429 cx: &mut Context<Self>,
13430 ) {
13431 if let Some(selections) = self
13432 .change_list
13433 .next_change(1, Direction::Prev)
13434 .map(|s| s.to_vec())
13435 {
13436 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13437 let map = s.display_map();
13438 s.select_display_ranges(selections.iter().map(|a| {
13439 let point = a.to_display_point(&map);
13440 point..point
13441 }))
13442 })
13443 }
13444 }
13445
13446 fn go_to_line<T: 'static>(
13447 &mut self,
13448 position: Anchor,
13449 highlight_color: Option<Hsla>,
13450 window: &mut Window,
13451 cx: &mut Context<Self>,
13452 ) {
13453 let snapshot = self.snapshot(window, cx).display_snapshot;
13454 let position = position.to_point(&snapshot.buffer_snapshot);
13455 let start = snapshot
13456 .buffer_snapshot
13457 .clip_point(Point::new(position.row, 0), Bias::Left);
13458 let end = start + Point::new(1, 0);
13459 let start = snapshot.buffer_snapshot.anchor_before(start);
13460 let end = snapshot.buffer_snapshot.anchor_before(end);
13461
13462 self.highlight_rows::<T>(
13463 start..end,
13464 highlight_color
13465 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13466 false,
13467 cx,
13468 );
13469 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13470 }
13471
13472 pub fn go_to_definition(
13473 &mut self,
13474 _: &GoToDefinition,
13475 window: &mut Window,
13476 cx: &mut Context<Self>,
13477 ) -> Task<Result<Navigated>> {
13478 let definition =
13479 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13480 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13481 cx.spawn_in(window, async move |editor, cx| {
13482 if definition.await? == Navigated::Yes {
13483 return Ok(Navigated::Yes);
13484 }
13485 match fallback_strategy {
13486 GoToDefinitionFallback::None => Ok(Navigated::No),
13487 GoToDefinitionFallback::FindAllReferences => {
13488 match editor.update_in(cx, |editor, window, cx| {
13489 editor.find_all_references(&FindAllReferences, window, cx)
13490 })? {
13491 Some(references) => references.await,
13492 None => Ok(Navigated::No),
13493 }
13494 }
13495 }
13496 })
13497 }
13498
13499 pub fn go_to_declaration(
13500 &mut self,
13501 _: &GoToDeclaration,
13502 window: &mut Window,
13503 cx: &mut Context<Self>,
13504 ) -> Task<Result<Navigated>> {
13505 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13506 }
13507
13508 pub fn go_to_declaration_split(
13509 &mut self,
13510 _: &GoToDeclaration,
13511 window: &mut Window,
13512 cx: &mut Context<Self>,
13513 ) -> Task<Result<Navigated>> {
13514 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13515 }
13516
13517 pub fn go_to_implementation(
13518 &mut self,
13519 _: &GoToImplementation,
13520 window: &mut Window,
13521 cx: &mut Context<Self>,
13522 ) -> Task<Result<Navigated>> {
13523 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13524 }
13525
13526 pub fn go_to_implementation_split(
13527 &mut self,
13528 _: &GoToImplementationSplit,
13529 window: &mut Window,
13530 cx: &mut Context<Self>,
13531 ) -> Task<Result<Navigated>> {
13532 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13533 }
13534
13535 pub fn go_to_type_definition(
13536 &mut self,
13537 _: &GoToTypeDefinition,
13538 window: &mut Window,
13539 cx: &mut Context<Self>,
13540 ) -> Task<Result<Navigated>> {
13541 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13542 }
13543
13544 pub fn go_to_definition_split(
13545 &mut self,
13546 _: &GoToDefinitionSplit,
13547 window: &mut Window,
13548 cx: &mut Context<Self>,
13549 ) -> Task<Result<Navigated>> {
13550 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13551 }
13552
13553 pub fn go_to_type_definition_split(
13554 &mut self,
13555 _: &GoToTypeDefinitionSplit,
13556 window: &mut Window,
13557 cx: &mut Context<Self>,
13558 ) -> Task<Result<Navigated>> {
13559 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13560 }
13561
13562 fn go_to_definition_of_kind(
13563 &mut self,
13564 kind: GotoDefinitionKind,
13565 split: bool,
13566 window: &mut Window,
13567 cx: &mut Context<Self>,
13568 ) -> Task<Result<Navigated>> {
13569 let Some(provider) = self.semantics_provider.clone() else {
13570 return Task::ready(Ok(Navigated::No));
13571 };
13572 let head = self.selections.newest::<usize>(cx).head();
13573 let buffer = self.buffer.read(cx);
13574 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13575 text_anchor
13576 } else {
13577 return Task::ready(Ok(Navigated::No));
13578 };
13579
13580 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13581 return Task::ready(Ok(Navigated::No));
13582 };
13583
13584 cx.spawn_in(window, async move |editor, cx| {
13585 let definitions = definitions.await?;
13586 let navigated = editor
13587 .update_in(cx, |editor, window, cx| {
13588 editor.navigate_to_hover_links(
13589 Some(kind),
13590 definitions
13591 .into_iter()
13592 .filter(|location| {
13593 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13594 })
13595 .map(HoverLink::Text)
13596 .collect::<Vec<_>>(),
13597 split,
13598 window,
13599 cx,
13600 )
13601 })?
13602 .await?;
13603 anyhow::Ok(navigated)
13604 })
13605 }
13606
13607 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13608 let selection = self.selections.newest_anchor();
13609 let head = selection.head();
13610 let tail = selection.tail();
13611
13612 let Some((buffer, start_position)) =
13613 self.buffer.read(cx).text_anchor_for_position(head, cx)
13614 else {
13615 return;
13616 };
13617
13618 let end_position = if head != tail {
13619 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13620 return;
13621 };
13622 Some(pos)
13623 } else {
13624 None
13625 };
13626
13627 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13628 let url = if let Some(end_pos) = end_position {
13629 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13630 } else {
13631 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13632 };
13633
13634 if let Some(url) = url {
13635 editor.update(cx, |_, cx| {
13636 cx.open_url(&url);
13637 })
13638 } else {
13639 Ok(())
13640 }
13641 });
13642
13643 url_finder.detach();
13644 }
13645
13646 pub fn open_selected_filename(
13647 &mut self,
13648 _: &OpenSelectedFilename,
13649 window: &mut Window,
13650 cx: &mut Context<Self>,
13651 ) {
13652 let Some(workspace) = self.workspace() else {
13653 return;
13654 };
13655
13656 let position = self.selections.newest_anchor().head();
13657
13658 let Some((buffer, buffer_position)) =
13659 self.buffer.read(cx).text_anchor_for_position(position, cx)
13660 else {
13661 return;
13662 };
13663
13664 let project = self.project.clone();
13665
13666 cx.spawn_in(window, async move |_, cx| {
13667 let result = find_file(&buffer, project, buffer_position, cx).await;
13668
13669 if let Some((_, path)) = result {
13670 workspace
13671 .update_in(cx, |workspace, window, cx| {
13672 workspace.open_resolved_path(path, window, cx)
13673 })?
13674 .await?;
13675 }
13676 anyhow::Ok(())
13677 })
13678 .detach();
13679 }
13680
13681 pub(crate) fn navigate_to_hover_links(
13682 &mut self,
13683 kind: Option<GotoDefinitionKind>,
13684 mut definitions: Vec<HoverLink>,
13685 split: bool,
13686 window: &mut Window,
13687 cx: &mut Context<Editor>,
13688 ) -> Task<Result<Navigated>> {
13689 // If there is one definition, just open it directly
13690 if definitions.len() == 1 {
13691 let definition = definitions.pop().unwrap();
13692
13693 enum TargetTaskResult {
13694 Location(Option<Location>),
13695 AlreadyNavigated,
13696 }
13697
13698 let target_task = match definition {
13699 HoverLink::Text(link) => {
13700 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13701 }
13702 HoverLink::InlayHint(lsp_location, server_id) => {
13703 let computation =
13704 self.compute_target_location(lsp_location, server_id, window, cx);
13705 cx.background_spawn(async move {
13706 let location = computation.await?;
13707 Ok(TargetTaskResult::Location(location))
13708 })
13709 }
13710 HoverLink::Url(url) => {
13711 cx.open_url(&url);
13712 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13713 }
13714 HoverLink::File(path) => {
13715 if let Some(workspace) = self.workspace() {
13716 cx.spawn_in(window, async move |_, cx| {
13717 workspace
13718 .update_in(cx, |workspace, window, cx| {
13719 workspace.open_resolved_path(path, window, cx)
13720 })?
13721 .await
13722 .map(|_| TargetTaskResult::AlreadyNavigated)
13723 })
13724 } else {
13725 Task::ready(Ok(TargetTaskResult::Location(None)))
13726 }
13727 }
13728 };
13729 cx.spawn_in(window, async move |editor, cx| {
13730 let target = match target_task.await.context("target resolution task")? {
13731 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13732 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13733 TargetTaskResult::Location(Some(target)) => target,
13734 };
13735
13736 editor.update_in(cx, |editor, window, cx| {
13737 let Some(workspace) = editor.workspace() else {
13738 return Navigated::No;
13739 };
13740 let pane = workspace.read(cx).active_pane().clone();
13741
13742 let range = target.range.to_point(target.buffer.read(cx));
13743 let range = editor.range_for_match(&range);
13744 let range = collapse_multiline_range(range);
13745
13746 if !split
13747 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13748 {
13749 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13750 } else {
13751 window.defer(cx, move |window, cx| {
13752 let target_editor: Entity<Self> =
13753 workspace.update(cx, |workspace, cx| {
13754 let pane = if split {
13755 workspace.adjacent_pane(window, cx)
13756 } else {
13757 workspace.active_pane().clone()
13758 };
13759
13760 workspace.open_project_item(
13761 pane,
13762 target.buffer.clone(),
13763 true,
13764 true,
13765 window,
13766 cx,
13767 )
13768 });
13769 target_editor.update(cx, |target_editor, cx| {
13770 // When selecting a definition in a different buffer, disable the nav history
13771 // to avoid creating a history entry at the previous cursor location.
13772 pane.update(cx, |pane, _| pane.disable_history());
13773 target_editor.go_to_singleton_buffer_range(range, window, cx);
13774 pane.update(cx, |pane, _| pane.enable_history());
13775 });
13776 });
13777 }
13778 Navigated::Yes
13779 })
13780 })
13781 } else if !definitions.is_empty() {
13782 cx.spawn_in(window, async move |editor, cx| {
13783 let (title, location_tasks, workspace) = editor
13784 .update_in(cx, |editor, window, cx| {
13785 let tab_kind = match kind {
13786 Some(GotoDefinitionKind::Implementation) => "Implementations",
13787 _ => "Definitions",
13788 };
13789 let title = definitions
13790 .iter()
13791 .find_map(|definition| match definition {
13792 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13793 let buffer = origin.buffer.read(cx);
13794 format!(
13795 "{} for {}",
13796 tab_kind,
13797 buffer
13798 .text_for_range(origin.range.clone())
13799 .collect::<String>()
13800 )
13801 }),
13802 HoverLink::InlayHint(_, _) => None,
13803 HoverLink::Url(_) => None,
13804 HoverLink::File(_) => None,
13805 })
13806 .unwrap_or(tab_kind.to_string());
13807 let location_tasks = definitions
13808 .into_iter()
13809 .map(|definition| match definition {
13810 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13811 HoverLink::InlayHint(lsp_location, server_id) => editor
13812 .compute_target_location(lsp_location, server_id, window, cx),
13813 HoverLink::Url(_) => Task::ready(Ok(None)),
13814 HoverLink::File(_) => Task::ready(Ok(None)),
13815 })
13816 .collect::<Vec<_>>();
13817 (title, location_tasks, editor.workspace().clone())
13818 })
13819 .context("location tasks preparation")?;
13820
13821 let locations = future::join_all(location_tasks)
13822 .await
13823 .into_iter()
13824 .filter_map(|location| location.transpose())
13825 .collect::<Result<_>>()
13826 .context("location tasks")?;
13827
13828 let Some(workspace) = workspace else {
13829 return Ok(Navigated::No);
13830 };
13831 let opened = workspace
13832 .update_in(cx, |workspace, window, cx| {
13833 Self::open_locations_in_multibuffer(
13834 workspace,
13835 locations,
13836 title,
13837 split,
13838 MultibufferSelectionMode::First,
13839 window,
13840 cx,
13841 )
13842 })
13843 .ok();
13844
13845 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13846 })
13847 } else {
13848 Task::ready(Ok(Navigated::No))
13849 }
13850 }
13851
13852 fn compute_target_location(
13853 &self,
13854 lsp_location: lsp::Location,
13855 server_id: LanguageServerId,
13856 window: &mut Window,
13857 cx: &mut Context<Self>,
13858 ) -> Task<anyhow::Result<Option<Location>>> {
13859 let Some(project) = self.project.clone() else {
13860 return Task::ready(Ok(None));
13861 };
13862
13863 cx.spawn_in(window, async move |editor, cx| {
13864 let location_task = editor.update(cx, |_, cx| {
13865 project.update(cx, |project, cx| {
13866 let language_server_name = project
13867 .language_server_statuses(cx)
13868 .find(|(id, _)| server_id == *id)
13869 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13870 language_server_name.map(|language_server_name| {
13871 project.open_local_buffer_via_lsp(
13872 lsp_location.uri.clone(),
13873 server_id,
13874 language_server_name,
13875 cx,
13876 )
13877 })
13878 })
13879 })?;
13880 let location = match location_task {
13881 Some(task) => Some({
13882 let target_buffer_handle = task.await.context("open local buffer")?;
13883 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13884 let target_start = target_buffer
13885 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13886 let target_end = target_buffer
13887 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13888 target_buffer.anchor_after(target_start)
13889 ..target_buffer.anchor_before(target_end)
13890 })?;
13891 Location {
13892 buffer: target_buffer_handle,
13893 range,
13894 }
13895 }),
13896 None => None,
13897 };
13898 Ok(location)
13899 })
13900 }
13901
13902 pub fn find_all_references(
13903 &mut self,
13904 _: &FindAllReferences,
13905 window: &mut Window,
13906 cx: &mut Context<Self>,
13907 ) -> Option<Task<Result<Navigated>>> {
13908 let selection = self.selections.newest::<usize>(cx);
13909 let multi_buffer = self.buffer.read(cx);
13910 let head = selection.head();
13911
13912 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13913 let head_anchor = multi_buffer_snapshot.anchor_at(
13914 head,
13915 if head < selection.tail() {
13916 Bias::Right
13917 } else {
13918 Bias::Left
13919 },
13920 );
13921
13922 match self
13923 .find_all_references_task_sources
13924 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13925 {
13926 Ok(_) => {
13927 log::info!(
13928 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13929 );
13930 return None;
13931 }
13932 Err(i) => {
13933 self.find_all_references_task_sources.insert(i, head_anchor);
13934 }
13935 }
13936
13937 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13938 let workspace = self.workspace()?;
13939 let project = workspace.read(cx).project().clone();
13940 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13941 Some(cx.spawn_in(window, async move |editor, cx| {
13942 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13943 if let Ok(i) = editor
13944 .find_all_references_task_sources
13945 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13946 {
13947 editor.find_all_references_task_sources.remove(i);
13948 }
13949 });
13950
13951 let locations = references.await?;
13952 if locations.is_empty() {
13953 return anyhow::Ok(Navigated::No);
13954 }
13955
13956 workspace.update_in(cx, |workspace, window, cx| {
13957 let title = locations
13958 .first()
13959 .as_ref()
13960 .map(|location| {
13961 let buffer = location.buffer.read(cx);
13962 format!(
13963 "References to `{}`",
13964 buffer
13965 .text_for_range(location.range.clone())
13966 .collect::<String>()
13967 )
13968 })
13969 .unwrap();
13970 Self::open_locations_in_multibuffer(
13971 workspace,
13972 locations,
13973 title,
13974 false,
13975 MultibufferSelectionMode::First,
13976 window,
13977 cx,
13978 );
13979 Navigated::Yes
13980 })
13981 }))
13982 }
13983
13984 /// Opens a multibuffer with the given project locations in it
13985 pub fn open_locations_in_multibuffer(
13986 workspace: &mut Workspace,
13987 mut locations: Vec<Location>,
13988 title: String,
13989 split: bool,
13990 multibuffer_selection_mode: MultibufferSelectionMode,
13991 window: &mut Window,
13992 cx: &mut Context<Workspace>,
13993 ) {
13994 // If there are multiple definitions, open them in a multibuffer
13995 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13996 let mut locations = locations.into_iter().peekable();
13997 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13998 let capability = workspace.project().read(cx).capability();
13999
14000 let excerpt_buffer = cx.new(|cx| {
14001 let mut multibuffer = MultiBuffer::new(capability);
14002 while let Some(location) = locations.next() {
14003 let buffer = location.buffer.read(cx);
14004 let mut ranges_for_buffer = Vec::new();
14005 let range = location.range.to_point(buffer);
14006 ranges_for_buffer.push(range.clone());
14007
14008 while let Some(next_location) = locations.peek() {
14009 if next_location.buffer == location.buffer {
14010 ranges_for_buffer.push(next_location.range.to_point(buffer));
14011 locations.next();
14012 } else {
14013 break;
14014 }
14015 }
14016
14017 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14018 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14019 PathKey::for_buffer(&location.buffer, cx),
14020 location.buffer.clone(),
14021 ranges_for_buffer,
14022 DEFAULT_MULTIBUFFER_CONTEXT,
14023 cx,
14024 );
14025 ranges.extend(new_ranges)
14026 }
14027
14028 multibuffer.with_title(title)
14029 });
14030
14031 let editor = cx.new(|cx| {
14032 Editor::for_multibuffer(
14033 excerpt_buffer,
14034 Some(workspace.project().clone()),
14035 window,
14036 cx,
14037 )
14038 });
14039 editor.update(cx, |editor, cx| {
14040 match multibuffer_selection_mode {
14041 MultibufferSelectionMode::First => {
14042 if let Some(first_range) = ranges.first() {
14043 editor.change_selections(None, window, cx, |selections| {
14044 selections.clear_disjoint();
14045 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14046 });
14047 }
14048 editor.highlight_background::<Self>(
14049 &ranges,
14050 |theme| theme.editor_highlighted_line_background,
14051 cx,
14052 );
14053 }
14054 MultibufferSelectionMode::All => {
14055 editor.change_selections(None, window, cx, |selections| {
14056 selections.clear_disjoint();
14057 selections.select_anchor_ranges(ranges);
14058 });
14059 }
14060 }
14061 editor.register_buffers_with_language_servers(cx);
14062 });
14063
14064 let item = Box::new(editor);
14065 let item_id = item.item_id();
14066
14067 if split {
14068 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14069 } else {
14070 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14071 let (preview_item_id, preview_item_idx) =
14072 workspace.active_pane().update(cx, |pane, _| {
14073 (pane.preview_item_id(), pane.preview_item_idx())
14074 });
14075
14076 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14077
14078 if let Some(preview_item_id) = preview_item_id {
14079 workspace.active_pane().update(cx, |pane, cx| {
14080 pane.remove_item(preview_item_id, false, false, window, cx);
14081 });
14082 }
14083 } else {
14084 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14085 }
14086 }
14087 workspace.active_pane().update(cx, |pane, cx| {
14088 pane.set_preview_item_id(Some(item_id), cx);
14089 });
14090 }
14091
14092 pub fn rename(
14093 &mut self,
14094 _: &Rename,
14095 window: &mut Window,
14096 cx: &mut Context<Self>,
14097 ) -> Option<Task<Result<()>>> {
14098 use language::ToOffset as _;
14099
14100 let provider = self.semantics_provider.clone()?;
14101 let selection = self.selections.newest_anchor().clone();
14102 let (cursor_buffer, cursor_buffer_position) = self
14103 .buffer
14104 .read(cx)
14105 .text_anchor_for_position(selection.head(), cx)?;
14106 let (tail_buffer, cursor_buffer_position_end) = self
14107 .buffer
14108 .read(cx)
14109 .text_anchor_for_position(selection.tail(), cx)?;
14110 if tail_buffer != cursor_buffer {
14111 return None;
14112 }
14113
14114 let snapshot = cursor_buffer.read(cx).snapshot();
14115 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14116 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14117 let prepare_rename = provider
14118 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14119 .unwrap_or_else(|| Task::ready(Ok(None)));
14120 drop(snapshot);
14121
14122 Some(cx.spawn_in(window, async move |this, cx| {
14123 let rename_range = if let Some(range) = prepare_rename.await? {
14124 Some(range)
14125 } else {
14126 this.update(cx, |this, cx| {
14127 let buffer = this.buffer.read(cx).snapshot(cx);
14128 let mut buffer_highlights = this
14129 .document_highlights_for_position(selection.head(), &buffer)
14130 .filter(|highlight| {
14131 highlight.start.excerpt_id == selection.head().excerpt_id
14132 && highlight.end.excerpt_id == selection.head().excerpt_id
14133 });
14134 buffer_highlights
14135 .next()
14136 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14137 })?
14138 };
14139 if let Some(rename_range) = rename_range {
14140 this.update_in(cx, |this, window, cx| {
14141 let snapshot = cursor_buffer.read(cx).snapshot();
14142 let rename_buffer_range = rename_range.to_offset(&snapshot);
14143 let cursor_offset_in_rename_range =
14144 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14145 let cursor_offset_in_rename_range_end =
14146 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14147
14148 this.take_rename(false, window, cx);
14149 let buffer = this.buffer.read(cx).read(cx);
14150 let cursor_offset = selection.head().to_offset(&buffer);
14151 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14152 let rename_end = rename_start + rename_buffer_range.len();
14153 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14154 let mut old_highlight_id = None;
14155 let old_name: Arc<str> = buffer
14156 .chunks(rename_start..rename_end, true)
14157 .map(|chunk| {
14158 if old_highlight_id.is_none() {
14159 old_highlight_id = chunk.syntax_highlight_id;
14160 }
14161 chunk.text
14162 })
14163 .collect::<String>()
14164 .into();
14165
14166 drop(buffer);
14167
14168 // Position the selection in the rename editor so that it matches the current selection.
14169 this.show_local_selections = false;
14170 let rename_editor = cx.new(|cx| {
14171 let mut editor = Editor::single_line(window, cx);
14172 editor.buffer.update(cx, |buffer, cx| {
14173 buffer.edit([(0..0, old_name.clone())], None, cx)
14174 });
14175 let rename_selection_range = match cursor_offset_in_rename_range
14176 .cmp(&cursor_offset_in_rename_range_end)
14177 {
14178 Ordering::Equal => {
14179 editor.select_all(&SelectAll, window, cx);
14180 return editor;
14181 }
14182 Ordering::Less => {
14183 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14184 }
14185 Ordering::Greater => {
14186 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14187 }
14188 };
14189 if rename_selection_range.end > old_name.len() {
14190 editor.select_all(&SelectAll, window, cx);
14191 } else {
14192 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14193 s.select_ranges([rename_selection_range]);
14194 });
14195 }
14196 editor
14197 });
14198 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14199 if e == &EditorEvent::Focused {
14200 cx.emit(EditorEvent::FocusedIn)
14201 }
14202 })
14203 .detach();
14204
14205 let write_highlights =
14206 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14207 let read_highlights =
14208 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14209 let ranges = write_highlights
14210 .iter()
14211 .flat_map(|(_, ranges)| ranges.iter())
14212 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14213 .cloned()
14214 .collect();
14215
14216 this.highlight_text::<Rename>(
14217 ranges,
14218 HighlightStyle {
14219 fade_out: Some(0.6),
14220 ..Default::default()
14221 },
14222 cx,
14223 );
14224 let rename_focus_handle = rename_editor.focus_handle(cx);
14225 window.focus(&rename_focus_handle);
14226 let block_id = this.insert_blocks(
14227 [BlockProperties {
14228 style: BlockStyle::Flex,
14229 placement: BlockPlacement::Below(range.start),
14230 height: Some(1),
14231 render: Arc::new({
14232 let rename_editor = rename_editor.clone();
14233 move |cx: &mut BlockContext| {
14234 let mut text_style = cx.editor_style.text.clone();
14235 if let Some(highlight_style) = old_highlight_id
14236 .and_then(|h| h.style(&cx.editor_style.syntax))
14237 {
14238 text_style = text_style.highlight(highlight_style);
14239 }
14240 div()
14241 .block_mouse_down()
14242 .pl(cx.anchor_x)
14243 .child(EditorElement::new(
14244 &rename_editor,
14245 EditorStyle {
14246 background: cx.theme().system().transparent,
14247 local_player: cx.editor_style.local_player,
14248 text: text_style,
14249 scrollbar_width: cx.editor_style.scrollbar_width,
14250 syntax: cx.editor_style.syntax.clone(),
14251 status: cx.editor_style.status.clone(),
14252 inlay_hints_style: HighlightStyle {
14253 font_weight: Some(FontWeight::BOLD),
14254 ..make_inlay_hints_style(cx.app)
14255 },
14256 inline_completion_styles: make_suggestion_styles(
14257 cx.app,
14258 ),
14259 ..EditorStyle::default()
14260 },
14261 ))
14262 .into_any_element()
14263 }
14264 }),
14265 priority: 0,
14266 }],
14267 Some(Autoscroll::fit()),
14268 cx,
14269 )[0];
14270 this.pending_rename = Some(RenameState {
14271 range,
14272 old_name,
14273 editor: rename_editor,
14274 block_id,
14275 });
14276 })?;
14277 }
14278
14279 Ok(())
14280 }))
14281 }
14282
14283 pub fn confirm_rename(
14284 &mut self,
14285 _: &ConfirmRename,
14286 window: &mut Window,
14287 cx: &mut Context<Self>,
14288 ) -> Option<Task<Result<()>>> {
14289 let rename = self.take_rename(false, window, cx)?;
14290 let workspace = self.workspace()?.downgrade();
14291 let (buffer, start) = self
14292 .buffer
14293 .read(cx)
14294 .text_anchor_for_position(rename.range.start, cx)?;
14295 let (end_buffer, _) = self
14296 .buffer
14297 .read(cx)
14298 .text_anchor_for_position(rename.range.end, cx)?;
14299 if buffer != end_buffer {
14300 return None;
14301 }
14302
14303 let old_name = rename.old_name;
14304 let new_name = rename.editor.read(cx).text(cx);
14305
14306 let rename = self.semantics_provider.as_ref()?.perform_rename(
14307 &buffer,
14308 start,
14309 new_name.clone(),
14310 cx,
14311 )?;
14312
14313 Some(cx.spawn_in(window, async move |editor, cx| {
14314 let project_transaction = rename.await?;
14315 Self::open_project_transaction(
14316 &editor,
14317 workspace,
14318 project_transaction,
14319 format!("Rename: {} → {}", old_name, new_name),
14320 cx,
14321 )
14322 .await?;
14323
14324 editor.update(cx, |editor, cx| {
14325 editor.refresh_document_highlights(cx);
14326 })?;
14327 Ok(())
14328 }))
14329 }
14330
14331 fn take_rename(
14332 &mut self,
14333 moving_cursor: bool,
14334 window: &mut Window,
14335 cx: &mut Context<Self>,
14336 ) -> Option<RenameState> {
14337 let rename = self.pending_rename.take()?;
14338 if rename.editor.focus_handle(cx).is_focused(window) {
14339 window.focus(&self.focus_handle);
14340 }
14341
14342 self.remove_blocks(
14343 [rename.block_id].into_iter().collect(),
14344 Some(Autoscroll::fit()),
14345 cx,
14346 );
14347 self.clear_highlights::<Rename>(cx);
14348 self.show_local_selections = true;
14349
14350 if moving_cursor {
14351 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14352 editor.selections.newest::<usize>(cx).head()
14353 });
14354
14355 // Update the selection to match the position of the selection inside
14356 // the rename editor.
14357 let snapshot = self.buffer.read(cx).read(cx);
14358 let rename_range = rename.range.to_offset(&snapshot);
14359 let cursor_in_editor = snapshot
14360 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14361 .min(rename_range.end);
14362 drop(snapshot);
14363
14364 self.change_selections(None, window, cx, |s| {
14365 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14366 });
14367 } else {
14368 self.refresh_document_highlights(cx);
14369 }
14370
14371 Some(rename)
14372 }
14373
14374 pub fn pending_rename(&self) -> Option<&RenameState> {
14375 self.pending_rename.as_ref()
14376 }
14377
14378 fn format(
14379 &mut self,
14380 _: &Format,
14381 window: &mut Window,
14382 cx: &mut Context<Self>,
14383 ) -> Option<Task<Result<()>>> {
14384 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14385
14386 let project = match &self.project {
14387 Some(project) => project.clone(),
14388 None => return None,
14389 };
14390
14391 Some(self.perform_format(
14392 project,
14393 FormatTrigger::Manual,
14394 FormatTarget::Buffers,
14395 window,
14396 cx,
14397 ))
14398 }
14399
14400 fn format_selections(
14401 &mut self,
14402 _: &FormatSelections,
14403 window: &mut Window,
14404 cx: &mut Context<Self>,
14405 ) -> Option<Task<Result<()>>> {
14406 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14407
14408 let project = match &self.project {
14409 Some(project) => project.clone(),
14410 None => return None,
14411 };
14412
14413 let ranges = self
14414 .selections
14415 .all_adjusted(cx)
14416 .into_iter()
14417 .map(|selection| selection.range())
14418 .collect_vec();
14419
14420 Some(self.perform_format(
14421 project,
14422 FormatTrigger::Manual,
14423 FormatTarget::Ranges(ranges),
14424 window,
14425 cx,
14426 ))
14427 }
14428
14429 fn perform_format(
14430 &mut self,
14431 project: Entity<Project>,
14432 trigger: FormatTrigger,
14433 target: FormatTarget,
14434 window: &mut Window,
14435 cx: &mut Context<Self>,
14436 ) -> Task<Result<()>> {
14437 let buffer = self.buffer.clone();
14438 let (buffers, target) = match target {
14439 FormatTarget::Buffers => {
14440 let mut buffers = buffer.read(cx).all_buffers();
14441 if trigger == FormatTrigger::Save {
14442 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14443 }
14444 (buffers, LspFormatTarget::Buffers)
14445 }
14446 FormatTarget::Ranges(selection_ranges) => {
14447 let multi_buffer = buffer.read(cx);
14448 let snapshot = multi_buffer.read(cx);
14449 let mut buffers = HashSet::default();
14450 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14451 BTreeMap::new();
14452 for selection_range in selection_ranges {
14453 for (buffer, buffer_range, _) in
14454 snapshot.range_to_buffer_ranges(selection_range)
14455 {
14456 let buffer_id = buffer.remote_id();
14457 let start = buffer.anchor_before(buffer_range.start);
14458 let end = buffer.anchor_after(buffer_range.end);
14459 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14460 buffer_id_to_ranges
14461 .entry(buffer_id)
14462 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14463 .or_insert_with(|| vec![start..end]);
14464 }
14465 }
14466 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14467 }
14468 };
14469
14470 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14471 let selections_prev = transaction_id_prev
14472 .and_then(|transaction_id_prev| {
14473 // default to selections as they were after the last edit, if we have them,
14474 // instead of how they are now.
14475 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14476 // will take you back to where you made the last edit, instead of staying where you scrolled
14477 self.selection_history
14478 .transaction(transaction_id_prev)
14479 .map(|t| t.0.clone())
14480 })
14481 .unwrap_or_else(|| {
14482 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14483 self.selections.disjoint_anchors()
14484 });
14485
14486 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14487 let format = project.update(cx, |project, cx| {
14488 project.format(buffers, target, true, trigger, cx)
14489 });
14490
14491 cx.spawn_in(window, async move |editor, cx| {
14492 let transaction = futures::select_biased! {
14493 transaction = format.log_err().fuse() => transaction,
14494 () = timeout => {
14495 log::warn!("timed out waiting for formatting");
14496 None
14497 }
14498 };
14499
14500 buffer
14501 .update(cx, |buffer, cx| {
14502 if let Some(transaction) = transaction {
14503 if !buffer.is_singleton() {
14504 buffer.push_transaction(&transaction.0, cx);
14505 }
14506 }
14507 cx.notify();
14508 })
14509 .ok();
14510
14511 if let Some(transaction_id_now) =
14512 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14513 {
14514 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14515 if has_new_transaction {
14516 _ = editor.update(cx, |editor, _| {
14517 editor
14518 .selection_history
14519 .insert_transaction(transaction_id_now, selections_prev);
14520 });
14521 }
14522 }
14523
14524 Ok(())
14525 })
14526 }
14527
14528 fn organize_imports(
14529 &mut self,
14530 _: &OrganizeImports,
14531 window: &mut Window,
14532 cx: &mut Context<Self>,
14533 ) -> Option<Task<Result<()>>> {
14534 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14535 let project = match &self.project {
14536 Some(project) => project.clone(),
14537 None => return None,
14538 };
14539 Some(self.perform_code_action_kind(
14540 project,
14541 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14542 window,
14543 cx,
14544 ))
14545 }
14546
14547 fn perform_code_action_kind(
14548 &mut self,
14549 project: Entity<Project>,
14550 kind: CodeActionKind,
14551 window: &mut Window,
14552 cx: &mut Context<Self>,
14553 ) -> Task<Result<()>> {
14554 let buffer = self.buffer.clone();
14555 let buffers = buffer.read(cx).all_buffers();
14556 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14557 let apply_action = project.update(cx, |project, cx| {
14558 project.apply_code_action_kind(buffers, kind, true, cx)
14559 });
14560 cx.spawn_in(window, async move |_, cx| {
14561 let transaction = futures::select_biased! {
14562 () = timeout => {
14563 log::warn!("timed out waiting for executing code action");
14564 None
14565 }
14566 transaction = apply_action.log_err().fuse() => transaction,
14567 };
14568 buffer
14569 .update(cx, |buffer, cx| {
14570 // check if we need this
14571 if let Some(transaction) = transaction {
14572 if !buffer.is_singleton() {
14573 buffer.push_transaction(&transaction.0, cx);
14574 }
14575 }
14576 cx.notify();
14577 })
14578 .ok();
14579 Ok(())
14580 })
14581 }
14582
14583 fn restart_language_server(
14584 &mut self,
14585 _: &RestartLanguageServer,
14586 _: &mut Window,
14587 cx: &mut Context<Self>,
14588 ) {
14589 if let Some(project) = self.project.clone() {
14590 self.buffer.update(cx, |multi_buffer, cx| {
14591 project.update(cx, |project, cx| {
14592 project.restart_language_servers_for_buffers(
14593 multi_buffer.all_buffers().into_iter().collect(),
14594 cx,
14595 );
14596 });
14597 })
14598 }
14599 }
14600
14601 fn stop_language_server(
14602 &mut self,
14603 _: &StopLanguageServer,
14604 _: &mut Window,
14605 cx: &mut Context<Self>,
14606 ) {
14607 if let Some(project) = self.project.clone() {
14608 self.buffer.update(cx, |multi_buffer, cx| {
14609 project.update(cx, |project, cx| {
14610 project.stop_language_servers_for_buffers(
14611 multi_buffer.all_buffers().into_iter().collect(),
14612 cx,
14613 );
14614 cx.emit(project::Event::RefreshInlayHints);
14615 });
14616 });
14617 }
14618 }
14619
14620 fn cancel_language_server_work(
14621 workspace: &mut Workspace,
14622 _: &actions::CancelLanguageServerWork,
14623 _: &mut Window,
14624 cx: &mut Context<Workspace>,
14625 ) {
14626 let project = workspace.project();
14627 let buffers = workspace
14628 .active_item(cx)
14629 .and_then(|item| item.act_as::<Editor>(cx))
14630 .map_or(HashSet::default(), |editor| {
14631 editor.read(cx).buffer.read(cx).all_buffers()
14632 });
14633 project.update(cx, |project, cx| {
14634 project.cancel_language_server_work_for_buffers(buffers, cx);
14635 });
14636 }
14637
14638 fn show_character_palette(
14639 &mut self,
14640 _: &ShowCharacterPalette,
14641 window: &mut Window,
14642 _: &mut Context<Self>,
14643 ) {
14644 window.show_character_palette();
14645 }
14646
14647 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14648 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14649 let buffer = self.buffer.read(cx).snapshot(cx);
14650 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14651 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14652 let is_valid = buffer
14653 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14654 .any(|entry| {
14655 entry.diagnostic.is_primary
14656 && !entry.range.is_empty()
14657 && entry.range.start == primary_range_start
14658 && entry.diagnostic.message == active_diagnostics.active_message
14659 });
14660
14661 if !is_valid {
14662 self.dismiss_diagnostics(cx);
14663 }
14664 }
14665 }
14666
14667 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14668 match &self.active_diagnostics {
14669 ActiveDiagnostic::Group(group) => Some(group),
14670 _ => None,
14671 }
14672 }
14673
14674 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14675 self.dismiss_diagnostics(cx);
14676 self.active_diagnostics = ActiveDiagnostic::All;
14677 }
14678
14679 fn activate_diagnostics(
14680 &mut self,
14681 buffer_id: BufferId,
14682 diagnostic: DiagnosticEntry<usize>,
14683 window: &mut Window,
14684 cx: &mut Context<Self>,
14685 ) {
14686 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14687 return;
14688 }
14689 self.dismiss_diagnostics(cx);
14690 let snapshot = self.snapshot(window, cx);
14691 let Some(diagnostic_renderer) = cx
14692 .try_global::<GlobalDiagnosticRenderer>()
14693 .map(|g| g.0.clone())
14694 else {
14695 return;
14696 };
14697 let buffer = self.buffer.read(cx).snapshot(cx);
14698
14699 let diagnostic_group = buffer
14700 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14701 .collect::<Vec<_>>();
14702
14703 let blocks = diagnostic_renderer.render_group(
14704 diagnostic_group,
14705 buffer_id,
14706 snapshot,
14707 cx.weak_entity(),
14708 cx,
14709 );
14710
14711 let blocks = self.display_map.update(cx, |display_map, cx| {
14712 display_map.insert_blocks(blocks, cx).into_iter().collect()
14713 });
14714 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14715 active_range: buffer.anchor_before(diagnostic.range.start)
14716 ..buffer.anchor_after(diagnostic.range.end),
14717 active_message: diagnostic.diagnostic.message.clone(),
14718 group_id: diagnostic.diagnostic.group_id,
14719 blocks,
14720 });
14721 cx.notify();
14722 }
14723
14724 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14725 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14726 return;
14727 };
14728
14729 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14730 if let ActiveDiagnostic::Group(group) = prev {
14731 self.display_map.update(cx, |display_map, cx| {
14732 display_map.remove_blocks(group.blocks, cx);
14733 });
14734 cx.notify();
14735 }
14736 }
14737
14738 /// Disable inline diagnostics rendering for this editor.
14739 pub fn disable_inline_diagnostics(&mut self) {
14740 self.inline_diagnostics_enabled = false;
14741 self.inline_diagnostics_update = Task::ready(());
14742 self.inline_diagnostics.clear();
14743 }
14744
14745 pub fn inline_diagnostics_enabled(&self) -> bool {
14746 self.inline_diagnostics_enabled
14747 }
14748
14749 pub fn show_inline_diagnostics(&self) -> bool {
14750 self.show_inline_diagnostics
14751 }
14752
14753 pub fn toggle_inline_diagnostics(
14754 &mut self,
14755 _: &ToggleInlineDiagnostics,
14756 window: &mut Window,
14757 cx: &mut Context<Editor>,
14758 ) {
14759 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14760 self.refresh_inline_diagnostics(false, window, cx);
14761 }
14762
14763 fn refresh_inline_diagnostics(
14764 &mut self,
14765 debounce: bool,
14766 window: &mut Window,
14767 cx: &mut Context<Self>,
14768 ) {
14769 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14770 self.inline_diagnostics_update = Task::ready(());
14771 self.inline_diagnostics.clear();
14772 return;
14773 }
14774
14775 let debounce_ms = ProjectSettings::get_global(cx)
14776 .diagnostics
14777 .inline
14778 .update_debounce_ms;
14779 let debounce = if debounce && debounce_ms > 0 {
14780 Some(Duration::from_millis(debounce_ms))
14781 } else {
14782 None
14783 };
14784 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14785 let editor = editor.upgrade().unwrap();
14786
14787 if let Some(debounce) = debounce {
14788 cx.background_executor().timer(debounce).await;
14789 }
14790 let Some(snapshot) = editor
14791 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14792 .ok()
14793 else {
14794 return;
14795 };
14796
14797 let new_inline_diagnostics = cx
14798 .background_spawn(async move {
14799 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14800 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14801 let message = diagnostic_entry
14802 .diagnostic
14803 .message
14804 .split_once('\n')
14805 .map(|(line, _)| line)
14806 .map(SharedString::new)
14807 .unwrap_or_else(|| {
14808 SharedString::from(diagnostic_entry.diagnostic.message)
14809 });
14810 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14811 let (Ok(i) | Err(i)) = inline_diagnostics
14812 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14813 inline_diagnostics.insert(
14814 i,
14815 (
14816 start_anchor,
14817 InlineDiagnostic {
14818 message,
14819 group_id: diagnostic_entry.diagnostic.group_id,
14820 start: diagnostic_entry.range.start.to_point(&snapshot),
14821 is_primary: diagnostic_entry.diagnostic.is_primary,
14822 severity: diagnostic_entry.diagnostic.severity,
14823 },
14824 ),
14825 );
14826 }
14827 inline_diagnostics
14828 })
14829 .await;
14830
14831 editor
14832 .update(cx, |editor, cx| {
14833 editor.inline_diagnostics = new_inline_diagnostics;
14834 cx.notify();
14835 })
14836 .ok();
14837 });
14838 }
14839
14840 pub fn set_selections_from_remote(
14841 &mut self,
14842 selections: Vec<Selection<Anchor>>,
14843 pending_selection: Option<Selection<Anchor>>,
14844 window: &mut Window,
14845 cx: &mut Context<Self>,
14846 ) {
14847 let old_cursor_position = self.selections.newest_anchor().head();
14848 self.selections.change_with(cx, |s| {
14849 s.select_anchors(selections);
14850 if let Some(pending_selection) = pending_selection {
14851 s.set_pending(pending_selection, SelectMode::Character);
14852 } else {
14853 s.clear_pending();
14854 }
14855 });
14856 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14857 }
14858
14859 fn push_to_selection_history(&mut self) {
14860 self.selection_history.push(SelectionHistoryEntry {
14861 selections: self.selections.disjoint_anchors(),
14862 select_next_state: self.select_next_state.clone(),
14863 select_prev_state: self.select_prev_state.clone(),
14864 add_selections_state: self.add_selections_state.clone(),
14865 });
14866 }
14867
14868 pub fn transact(
14869 &mut self,
14870 window: &mut Window,
14871 cx: &mut Context<Self>,
14872 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14873 ) -> Option<TransactionId> {
14874 self.start_transaction_at(Instant::now(), window, cx);
14875 update(self, window, cx);
14876 self.end_transaction_at(Instant::now(), cx)
14877 }
14878
14879 pub fn start_transaction_at(
14880 &mut self,
14881 now: Instant,
14882 window: &mut Window,
14883 cx: &mut Context<Self>,
14884 ) {
14885 self.end_selection(window, cx);
14886 if let Some(tx_id) = self
14887 .buffer
14888 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14889 {
14890 self.selection_history
14891 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14892 cx.emit(EditorEvent::TransactionBegun {
14893 transaction_id: tx_id,
14894 })
14895 }
14896 }
14897
14898 pub fn end_transaction_at(
14899 &mut self,
14900 now: Instant,
14901 cx: &mut Context<Self>,
14902 ) -> Option<TransactionId> {
14903 if let Some(transaction_id) = self
14904 .buffer
14905 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14906 {
14907 if let Some((_, end_selections)) =
14908 self.selection_history.transaction_mut(transaction_id)
14909 {
14910 *end_selections = Some(self.selections.disjoint_anchors());
14911 } else {
14912 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14913 }
14914
14915 cx.emit(EditorEvent::Edited { transaction_id });
14916 Some(transaction_id)
14917 } else {
14918 None
14919 }
14920 }
14921
14922 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14923 if self.selection_mark_mode {
14924 self.change_selections(None, window, cx, |s| {
14925 s.move_with(|_, sel| {
14926 sel.collapse_to(sel.head(), SelectionGoal::None);
14927 });
14928 })
14929 }
14930 self.selection_mark_mode = true;
14931 cx.notify();
14932 }
14933
14934 pub fn swap_selection_ends(
14935 &mut self,
14936 _: &actions::SwapSelectionEnds,
14937 window: &mut Window,
14938 cx: &mut Context<Self>,
14939 ) {
14940 self.change_selections(None, window, cx, |s| {
14941 s.move_with(|_, sel| {
14942 if sel.start != sel.end {
14943 sel.reversed = !sel.reversed
14944 }
14945 });
14946 });
14947 self.request_autoscroll(Autoscroll::newest(), cx);
14948 cx.notify();
14949 }
14950
14951 pub fn toggle_fold(
14952 &mut self,
14953 _: &actions::ToggleFold,
14954 window: &mut Window,
14955 cx: &mut Context<Self>,
14956 ) {
14957 if self.is_singleton(cx) {
14958 let selection = self.selections.newest::<Point>(cx);
14959
14960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14961 let range = if selection.is_empty() {
14962 let point = selection.head().to_display_point(&display_map);
14963 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14964 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14965 .to_point(&display_map);
14966 start..end
14967 } else {
14968 selection.range()
14969 };
14970 if display_map.folds_in_range(range).next().is_some() {
14971 self.unfold_lines(&Default::default(), window, cx)
14972 } else {
14973 self.fold(&Default::default(), window, cx)
14974 }
14975 } else {
14976 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14977 let buffer_ids: HashSet<_> = self
14978 .selections
14979 .disjoint_anchor_ranges()
14980 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14981 .collect();
14982
14983 let should_unfold = buffer_ids
14984 .iter()
14985 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14986
14987 for buffer_id in buffer_ids {
14988 if should_unfold {
14989 self.unfold_buffer(buffer_id, cx);
14990 } else {
14991 self.fold_buffer(buffer_id, cx);
14992 }
14993 }
14994 }
14995 }
14996
14997 pub fn toggle_fold_recursive(
14998 &mut self,
14999 _: &actions::ToggleFoldRecursive,
15000 window: &mut Window,
15001 cx: &mut Context<Self>,
15002 ) {
15003 let selection = self.selections.newest::<Point>(cx);
15004
15005 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15006 let range = if selection.is_empty() {
15007 let point = selection.head().to_display_point(&display_map);
15008 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15009 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15010 .to_point(&display_map);
15011 start..end
15012 } else {
15013 selection.range()
15014 };
15015 if display_map.folds_in_range(range).next().is_some() {
15016 self.unfold_recursive(&Default::default(), window, cx)
15017 } else {
15018 self.fold_recursive(&Default::default(), window, cx)
15019 }
15020 }
15021
15022 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15023 if self.is_singleton(cx) {
15024 let mut to_fold = Vec::new();
15025 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15026 let selections = self.selections.all_adjusted(cx);
15027
15028 for selection in selections {
15029 let range = selection.range().sorted();
15030 let buffer_start_row = range.start.row;
15031
15032 if range.start.row != range.end.row {
15033 let mut found = false;
15034 let mut row = range.start.row;
15035 while row <= range.end.row {
15036 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15037 {
15038 found = true;
15039 row = crease.range().end.row + 1;
15040 to_fold.push(crease);
15041 } else {
15042 row += 1
15043 }
15044 }
15045 if found {
15046 continue;
15047 }
15048 }
15049
15050 for row in (0..=range.start.row).rev() {
15051 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15052 if crease.range().end.row >= buffer_start_row {
15053 to_fold.push(crease);
15054 if row <= range.start.row {
15055 break;
15056 }
15057 }
15058 }
15059 }
15060 }
15061
15062 self.fold_creases(to_fold, true, window, cx);
15063 } else {
15064 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15065 let buffer_ids = self
15066 .selections
15067 .disjoint_anchor_ranges()
15068 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15069 .collect::<HashSet<_>>();
15070 for buffer_id in buffer_ids {
15071 self.fold_buffer(buffer_id, cx);
15072 }
15073 }
15074 }
15075
15076 fn fold_at_level(
15077 &mut self,
15078 fold_at: &FoldAtLevel,
15079 window: &mut Window,
15080 cx: &mut Context<Self>,
15081 ) {
15082 if !self.buffer.read(cx).is_singleton() {
15083 return;
15084 }
15085
15086 let fold_at_level = fold_at.0;
15087 let snapshot = self.buffer.read(cx).snapshot(cx);
15088 let mut to_fold = Vec::new();
15089 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15090
15091 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15092 while start_row < end_row {
15093 match self
15094 .snapshot(window, cx)
15095 .crease_for_buffer_row(MultiBufferRow(start_row))
15096 {
15097 Some(crease) => {
15098 let nested_start_row = crease.range().start.row + 1;
15099 let nested_end_row = crease.range().end.row;
15100
15101 if current_level < fold_at_level {
15102 stack.push((nested_start_row, nested_end_row, current_level + 1));
15103 } else if current_level == fold_at_level {
15104 to_fold.push(crease);
15105 }
15106
15107 start_row = nested_end_row + 1;
15108 }
15109 None => start_row += 1,
15110 }
15111 }
15112 }
15113
15114 self.fold_creases(to_fold, true, window, cx);
15115 }
15116
15117 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15118 if self.buffer.read(cx).is_singleton() {
15119 let mut fold_ranges = Vec::new();
15120 let snapshot = self.buffer.read(cx).snapshot(cx);
15121
15122 for row in 0..snapshot.max_row().0 {
15123 if let Some(foldable_range) = self
15124 .snapshot(window, cx)
15125 .crease_for_buffer_row(MultiBufferRow(row))
15126 {
15127 fold_ranges.push(foldable_range);
15128 }
15129 }
15130
15131 self.fold_creases(fold_ranges, true, window, cx);
15132 } else {
15133 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15134 editor
15135 .update_in(cx, |editor, _, cx| {
15136 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15137 editor.fold_buffer(buffer_id, cx);
15138 }
15139 })
15140 .ok();
15141 });
15142 }
15143 }
15144
15145 pub fn fold_function_bodies(
15146 &mut self,
15147 _: &actions::FoldFunctionBodies,
15148 window: &mut Window,
15149 cx: &mut Context<Self>,
15150 ) {
15151 let snapshot = self.buffer.read(cx).snapshot(cx);
15152
15153 let ranges = snapshot
15154 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15155 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15156 .collect::<Vec<_>>();
15157
15158 let creases = ranges
15159 .into_iter()
15160 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15161 .collect();
15162
15163 self.fold_creases(creases, true, window, cx);
15164 }
15165
15166 pub fn fold_recursive(
15167 &mut self,
15168 _: &actions::FoldRecursive,
15169 window: &mut Window,
15170 cx: &mut Context<Self>,
15171 ) {
15172 let mut to_fold = Vec::new();
15173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15174 let selections = self.selections.all_adjusted(cx);
15175
15176 for selection in selections {
15177 let range = selection.range().sorted();
15178 let buffer_start_row = range.start.row;
15179
15180 if range.start.row != range.end.row {
15181 let mut found = false;
15182 for row in range.start.row..=range.end.row {
15183 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15184 found = true;
15185 to_fold.push(crease);
15186 }
15187 }
15188 if found {
15189 continue;
15190 }
15191 }
15192
15193 for row in (0..=range.start.row).rev() {
15194 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15195 if crease.range().end.row >= buffer_start_row {
15196 to_fold.push(crease);
15197 } else {
15198 break;
15199 }
15200 }
15201 }
15202 }
15203
15204 self.fold_creases(to_fold, true, window, cx);
15205 }
15206
15207 pub fn fold_at(
15208 &mut self,
15209 buffer_row: MultiBufferRow,
15210 window: &mut Window,
15211 cx: &mut Context<Self>,
15212 ) {
15213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15214
15215 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15216 let autoscroll = self
15217 .selections
15218 .all::<Point>(cx)
15219 .iter()
15220 .any(|selection| crease.range().overlaps(&selection.range()));
15221
15222 self.fold_creases(vec![crease], autoscroll, window, cx);
15223 }
15224 }
15225
15226 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15227 if self.is_singleton(cx) {
15228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15229 let buffer = &display_map.buffer_snapshot;
15230 let selections = self.selections.all::<Point>(cx);
15231 let ranges = selections
15232 .iter()
15233 .map(|s| {
15234 let range = s.display_range(&display_map).sorted();
15235 let mut start = range.start.to_point(&display_map);
15236 let mut end = range.end.to_point(&display_map);
15237 start.column = 0;
15238 end.column = buffer.line_len(MultiBufferRow(end.row));
15239 start..end
15240 })
15241 .collect::<Vec<_>>();
15242
15243 self.unfold_ranges(&ranges, true, true, cx);
15244 } else {
15245 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15246 let buffer_ids = self
15247 .selections
15248 .disjoint_anchor_ranges()
15249 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15250 .collect::<HashSet<_>>();
15251 for buffer_id in buffer_ids {
15252 self.unfold_buffer(buffer_id, cx);
15253 }
15254 }
15255 }
15256
15257 pub fn unfold_recursive(
15258 &mut self,
15259 _: &UnfoldRecursive,
15260 _window: &mut Window,
15261 cx: &mut Context<Self>,
15262 ) {
15263 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15264 let selections = self.selections.all::<Point>(cx);
15265 let ranges = selections
15266 .iter()
15267 .map(|s| {
15268 let mut range = s.display_range(&display_map).sorted();
15269 *range.start.column_mut() = 0;
15270 *range.end.column_mut() = display_map.line_len(range.end.row());
15271 let start = range.start.to_point(&display_map);
15272 let end = range.end.to_point(&display_map);
15273 start..end
15274 })
15275 .collect::<Vec<_>>();
15276
15277 self.unfold_ranges(&ranges, true, true, cx);
15278 }
15279
15280 pub fn unfold_at(
15281 &mut self,
15282 buffer_row: MultiBufferRow,
15283 _window: &mut Window,
15284 cx: &mut Context<Self>,
15285 ) {
15286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15287
15288 let intersection_range = Point::new(buffer_row.0, 0)
15289 ..Point::new(
15290 buffer_row.0,
15291 display_map.buffer_snapshot.line_len(buffer_row),
15292 );
15293
15294 let autoscroll = self
15295 .selections
15296 .all::<Point>(cx)
15297 .iter()
15298 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15299
15300 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15301 }
15302
15303 pub fn unfold_all(
15304 &mut self,
15305 _: &actions::UnfoldAll,
15306 _window: &mut Window,
15307 cx: &mut Context<Self>,
15308 ) {
15309 if self.buffer.read(cx).is_singleton() {
15310 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15311 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15312 } else {
15313 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15314 editor
15315 .update(cx, |editor, cx| {
15316 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15317 editor.unfold_buffer(buffer_id, cx);
15318 }
15319 })
15320 .ok();
15321 });
15322 }
15323 }
15324
15325 pub fn fold_selected_ranges(
15326 &mut self,
15327 _: &FoldSelectedRanges,
15328 window: &mut Window,
15329 cx: &mut Context<Self>,
15330 ) {
15331 let selections = self.selections.all_adjusted(cx);
15332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15333 let ranges = selections
15334 .into_iter()
15335 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15336 .collect::<Vec<_>>();
15337 self.fold_creases(ranges, true, window, cx);
15338 }
15339
15340 pub fn fold_ranges<T: ToOffset + Clone>(
15341 &mut self,
15342 ranges: Vec<Range<T>>,
15343 auto_scroll: bool,
15344 window: &mut Window,
15345 cx: &mut Context<Self>,
15346 ) {
15347 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15348 let ranges = ranges
15349 .into_iter()
15350 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15351 .collect::<Vec<_>>();
15352 self.fold_creases(ranges, auto_scroll, window, cx);
15353 }
15354
15355 pub fn fold_creases<T: ToOffset + Clone>(
15356 &mut self,
15357 creases: Vec<Crease<T>>,
15358 auto_scroll: bool,
15359 _window: &mut Window,
15360 cx: &mut Context<Self>,
15361 ) {
15362 if creases.is_empty() {
15363 return;
15364 }
15365
15366 let mut buffers_affected = HashSet::default();
15367 let multi_buffer = self.buffer().read(cx);
15368 for crease in &creases {
15369 if let Some((_, buffer, _)) =
15370 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15371 {
15372 buffers_affected.insert(buffer.read(cx).remote_id());
15373 };
15374 }
15375
15376 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15377
15378 if auto_scroll {
15379 self.request_autoscroll(Autoscroll::fit(), cx);
15380 }
15381
15382 cx.notify();
15383
15384 self.scrollbar_marker_state.dirty = true;
15385 self.folds_did_change(cx);
15386 }
15387
15388 /// Removes any folds whose ranges intersect any of the given ranges.
15389 pub fn unfold_ranges<T: ToOffset + Clone>(
15390 &mut self,
15391 ranges: &[Range<T>],
15392 inclusive: bool,
15393 auto_scroll: bool,
15394 cx: &mut Context<Self>,
15395 ) {
15396 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15397 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15398 });
15399 self.folds_did_change(cx);
15400 }
15401
15402 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15403 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15404 return;
15405 }
15406 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15407 self.display_map.update(cx, |display_map, cx| {
15408 display_map.fold_buffers([buffer_id], cx)
15409 });
15410 cx.emit(EditorEvent::BufferFoldToggled {
15411 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15412 folded: true,
15413 });
15414 cx.notify();
15415 }
15416
15417 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15418 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15419 return;
15420 }
15421 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15422 self.display_map.update(cx, |display_map, cx| {
15423 display_map.unfold_buffers([buffer_id], cx);
15424 });
15425 cx.emit(EditorEvent::BufferFoldToggled {
15426 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15427 folded: false,
15428 });
15429 cx.notify();
15430 }
15431
15432 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15433 self.display_map.read(cx).is_buffer_folded(buffer)
15434 }
15435
15436 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15437 self.display_map.read(cx).folded_buffers()
15438 }
15439
15440 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15441 self.display_map.update(cx, |display_map, cx| {
15442 display_map.disable_header_for_buffer(buffer_id, cx);
15443 });
15444 cx.notify();
15445 }
15446
15447 /// Removes any folds with the given ranges.
15448 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15449 &mut self,
15450 ranges: &[Range<T>],
15451 type_id: TypeId,
15452 auto_scroll: bool,
15453 cx: &mut Context<Self>,
15454 ) {
15455 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15456 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15457 });
15458 self.folds_did_change(cx);
15459 }
15460
15461 fn remove_folds_with<T: ToOffset + Clone>(
15462 &mut self,
15463 ranges: &[Range<T>],
15464 auto_scroll: bool,
15465 cx: &mut Context<Self>,
15466 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15467 ) {
15468 if ranges.is_empty() {
15469 return;
15470 }
15471
15472 let mut buffers_affected = HashSet::default();
15473 let multi_buffer = self.buffer().read(cx);
15474 for range in ranges {
15475 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15476 buffers_affected.insert(buffer.read(cx).remote_id());
15477 };
15478 }
15479
15480 self.display_map.update(cx, update);
15481
15482 if auto_scroll {
15483 self.request_autoscroll(Autoscroll::fit(), cx);
15484 }
15485
15486 cx.notify();
15487 self.scrollbar_marker_state.dirty = true;
15488 self.active_indent_guides_state.dirty = true;
15489 }
15490
15491 pub fn update_fold_widths(
15492 &mut self,
15493 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15494 cx: &mut Context<Self>,
15495 ) -> bool {
15496 self.display_map
15497 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15498 }
15499
15500 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15501 self.display_map.read(cx).fold_placeholder.clone()
15502 }
15503
15504 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15505 self.buffer.update(cx, |buffer, cx| {
15506 buffer.set_all_diff_hunks_expanded(cx);
15507 });
15508 }
15509
15510 pub fn expand_all_diff_hunks(
15511 &mut self,
15512 _: &ExpandAllDiffHunks,
15513 _window: &mut Window,
15514 cx: &mut Context<Self>,
15515 ) {
15516 self.buffer.update(cx, |buffer, cx| {
15517 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15518 });
15519 }
15520
15521 pub fn toggle_selected_diff_hunks(
15522 &mut self,
15523 _: &ToggleSelectedDiffHunks,
15524 _window: &mut Window,
15525 cx: &mut Context<Self>,
15526 ) {
15527 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15528 self.toggle_diff_hunks_in_ranges(ranges, cx);
15529 }
15530
15531 pub fn diff_hunks_in_ranges<'a>(
15532 &'a self,
15533 ranges: &'a [Range<Anchor>],
15534 buffer: &'a MultiBufferSnapshot,
15535 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15536 ranges.iter().flat_map(move |range| {
15537 let end_excerpt_id = range.end.excerpt_id;
15538 let range = range.to_point(buffer);
15539 let mut peek_end = range.end;
15540 if range.end.row < buffer.max_row().0 {
15541 peek_end = Point::new(range.end.row + 1, 0);
15542 }
15543 buffer
15544 .diff_hunks_in_range(range.start..peek_end)
15545 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15546 })
15547 }
15548
15549 pub fn has_stageable_diff_hunks_in_ranges(
15550 &self,
15551 ranges: &[Range<Anchor>],
15552 snapshot: &MultiBufferSnapshot,
15553 ) -> bool {
15554 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15555 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15556 }
15557
15558 pub fn toggle_staged_selected_diff_hunks(
15559 &mut self,
15560 _: &::git::ToggleStaged,
15561 _: &mut Window,
15562 cx: &mut Context<Self>,
15563 ) {
15564 let snapshot = self.buffer.read(cx).snapshot(cx);
15565 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15566 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15567 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15568 }
15569
15570 pub fn set_render_diff_hunk_controls(
15571 &mut self,
15572 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15573 cx: &mut Context<Self>,
15574 ) {
15575 self.render_diff_hunk_controls = render_diff_hunk_controls;
15576 cx.notify();
15577 }
15578
15579 pub fn stage_and_next(
15580 &mut self,
15581 _: &::git::StageAndNext,
15582 window: &mut Window,
15583 cx: &mut Context<Self>,
15584 ) {
15585 self.do_stage_or_unstage_and_next(true, window, cx);
15586 }
15587
15588 pub fn unstage_and_next(
15589 &mut self,
15590 _: &::git::UnstageAndNext,
15591 window: &mut Window,
15592 cx: &mut Context<Self>,
15593 ) {
15594 self.do_stage_or_unstage_and_next(false, window, cx);
15595 }
15596
15597 pub fn stage_or_unstage_diff_hunks(
15598 &mut self,
15599 stage: bool,
15600 ranges: Vec<Range<Anchor>>,
15601 cx: &mut Context<Self>,
15602 ) {
15603 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15604 cx.spawn(async move |this, cx| {
15605 task.await?;
15606 this.update(cx, |this, cx| {
15607 let snapshot = this.buffer.read(cx).snapshot(cx);
15608 let chunk_by = this
15609 .diff_hunks_in_ranges(&ranges, &snapshot)
15610 .chunk_by(|hunk| hunk.buffer_id);
15611 for (buffer_id, hunks) in &chunk_by {
15612 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15613 }
15614 })
15615 })
15616 .detach_and_log_err(cx);
15617 }
15618
15619 fn save_buffers_for_ranges_if_needed(
15620 &mut self,
15621 ranges: &[Range<Anchor>],
15622 cx: &mut Context<Editor>,
15623 ) -> Task<Result<()>> {
15624 let multibuffer = self.buffer.read(cx);
15625 let snapshot = multibuffer.read(cx);
15626 let buffer_ids: HashSet<_> = ranges
15627 .iter()
15628 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15629 .collect();
15630 drop(snapshot);
15631
15632 let mut buffers = HashSet::default();
15633 for buffer_id in buffer_ids {
15634 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15635 let buffer = buffer_entity.read(cx);
15636 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15637 {
15638 buffers.insert(buffer_entity);
15639 }
15640 }
15641 }
15642
15643 if let Some(project) = &self.project {
15644 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15645 } else {
15646 Task::ready(Ok(()))
15647 }
15648 }
15649
15650 fn do_stage_or_unstage_and_next(
15651 &mut self,
15652 stage: bool,
15653 window: &mut Window,
15654 cx: &mut Context<Self>,
15655 ) {
15656 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15657
15658 if ranges.iter().any(|range| range.start != range.end) {
15659 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15660 return;
15661 }
15662
15663 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15664 let snapshot = self.snapshot(window, cx);
15665 let position = self.selections.newest::<Point>(cx).head();
15666 let mut row = snapshot
15667 .buffer_snapshot
15668 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15669 .find(|hunk| hunk.row_range.start.0 > position.row)
15670 .map(|hunk| hunk.row_range.start);
15671
15672 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15673 // Outside of the project diff editor, wrap around to the beginning.
15674 if !all_diff_hunks_expanded {
15675 row = row.or_else(|| {
15676 snapshot
15677 .buffer_snapshot
15678 .diff_hunks_in_range(Point::zero()..position)
15679 .find(|hunk| hunk.row_range.end.0 < position.row)
15680 .map(|hunk| hunk.row_range.start)
15681 });
15682 }
15683
15684 if let Some(row) = row {
15685 let destination = Point::new(row.0, 0);
15686 let autoscroll = Autoscroll::center();
15687
15688 self.unfold_ranges(&[destination..destination], false, false, cx);
15689 self.change_selections(Some(autoscroll), window, cx, |s| {
15690 s.select_ranges([destination..destination]);
15691 });
15692 }
15693 }
15694
15695 fn do_stage_or_unstage(
15696 &self,
15697 stage: bool,
15698 buffer_id: BufferId,
15699 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15700 cx: &mut App,
15701 ) -> Option<()> {
15702 let project = self.project.as_ref()?;
15703 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15704 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15705 let buffer_snapshot = buffer.read(cx).snapshot();
15706 let file_exists = buffer_snapshot
15707 .file()
15708 .is_some_and(|file| file.disk_state().exists());
15709 diff.update(cx, |diff, cx| {
15710 diff.stage_or_unstage_hunks(
15711 stage,
15712 &hunks
15713 .map(|hunk| buffer_diff::DiffHunk {
15714 buffer_range: hunk.buffer_range,
15715 diff_base_byte_range: hunk.diff_base_byte_range,
15716 secondary_status: hunk.secondary_status,
15717 range: Point::zero()..Point::zero(), // unused
15718 })
15719 .collect::<Vec<_>>(),
15720 &buffer_snapshot,
15721 file_exists,
15722 cx,
15723 )
15724 });
15725 None
15726 }
15727
15728 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15729 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15730 self.buffer
15731 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15732 }
15733
15734 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15735 self.buffer.update(cx, |buffer, cx| {
15736 let ranges = vec![Anchor::min()..Anchor::max()];
15737 if !buffer.all_diff_hunks_expanded()
15738 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15739 {
15740 buffer.collapse_diff_hunks(ranges, cx);
15741 true
15742 } else {
15743 false
15744 }
15745 })
15746 }
15747
15748 fn toggle_diff_hunks_in_ranges(
15749 &mut self,
15750 ranges: Vec<Range<Anchor>>,
15751 cx: &mut Context<Editor>,
15752 ) {
15753 self.buffer.update(cx, |buffer, cx| {
15754 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15755 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15756 })
15757 }
15758
15759 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15760 self.buffer.update(cx, |buffer, cx| {
15761 let snapshot = buffer.snapshot(cx);
15762 let excerpt_id = range.end.excerpt_id;
15763 let point_range = range.to_point(&snapshot);
15764 let expand = !buffer.single_hunk_is_expanded(range, cx);
15765 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15766 })
15767 }
15768
15769 pub(crate) fn apply_all_diff_hunks(
15770 &mut self,
15771 _: &ApplyAllDiffHunks,
15772 window: &mut Window,
15773 cx: &mut Context<Self>,
15774 ) {
15775 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15776
15777 let buffers = self.buffer.read(cx).all_buffers();
15778 for branch_buffer in buffers {
15779 branch_buffer.update(cx, |branch_buffer, cx| {
15780 branch_buffer.merge_into_base(Vec::new(), cx);
15781 });
15782 }
15783
15784 if let Some(project) = self.project.clone() {
15785 self.save(true, project, window, cx).detach_and_log_err(cx);
15786 }
15787 }
15788
15789 pub(crate) fn apply_selected_diff_hunks(
15790 &mut self,
15791 _: &ApplyDiffHunk,
15792 window: &mut Window,
15793 cx: &mut Context<Self>,
15794 ) {
15795 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15796 let snapshot = self.snapshot(window, cx);
15797 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15798 let mut ranges_by_buffer = HashMap::default();
15799 self.transact(window, cx, |editor, _window, cx| {
15800 for hunk in hunks {
15801 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15802 ranges_by_buffer
15803 .entry(buffer.clone())
15804 .or_insert_with(Vec::new)
15805 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15806 }
15807 }
15808
15809 for (buffer, ranges) in ranges_by_buffer {
15810 buffer.update(cx, |buffer, cx| {
15811 buffer.merge_into_base(ranges, cx);
15812 });
15813 }
15814 });
15815
15816 if let Some(project) = self.project.clone() {
15817 self.save(true, project, window, cx).detach_and_log_err(cx);
15818 }
15819 }
15820
15821 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15822 if hovered != self.gutter_hovered {
15823 self.gutter_hovered = hovered;
15824 cx.notify();
15825 }
15826 }
15827
15828 pub fn insert_blocks(
15829 &mut self,
15830 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15831 autoscroll: Option<Autoscroll>,
15832 cx: &mut Context<Self>,
15833 ) -> Vec<CustomBlockId> {
15834 let blocks = self
15835 .display_map
15836 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15837 if let Some(autoscroll) = autoscroll {
15838 self.request_autoscroll(autoscroll, cx);
15839 }
15840 cx.notify();
15841 blocks
15842 }
15843
15844 pub fn resize_blocks(
15845 &mut self,
15846 heights: HashMap<CustomBlockId, u32>,
15847 autoscroll: Option<Autoscroll>,
15848 cx: &mut Context<Self>,
15849 ) {
15850 self.display_map
15851 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15852 if let Some(autoscroll) = autoscroll {
15853 self.request_autoscroll(autoscroll, cx);
15854 }
15855 cx.notify();
15856 }
15857
15858 pub fn replace_blocks(
15859 &mut self,
15860 renderers: HashMap<CustomBlockId, RenderBlock>,
15861 autoscroll: Option<Autoscroll>,
15862 cx: &mut Context<Self>,
15863 ) {
15864 self.display_map
15865 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15866 if let Some(autoscroll) = autoscroll {
15867 self.request_autoscroll(autoscroll, cx);
15868 }
15869 cx.notify();
15870 }
15871
15872 pub fn remove_blocks(
15873 &mut self,
15874 block_ids: HashSet<CustomBlockId>,
15875 autoscroll: Option<Autoscroll>,
15876 cx: &mut Context<Self>,
15877 ) {
15878 self.display_map.update(cx, |display_map, cx| {
15879 display_map.remove_blocks(block_ids, cx)
15880 });
15881 if let Some(autoscroll) = autoscroll {
15882 self.request_autoscroll(autoscroll, cx);
15883 }
15884 cx.notify();
15885 }
15886
15887 pub fn row_for_block(
15888 &self,
15889 block_id: CustomBlockId,
15890 cx: &mut Context<Self>,
15891 ) -> Option<DisplayRow> {
15892 self.display_map
15893 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15894 }
15895
15896 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15897 self.focused_block = Some(focused_block);
15898 }
15899
15900 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15901 self.focused_block.take()
15902 }
15903
15904 pub fn insert_creases(
15905 &mut self,
15906 creases: impl IntoIterator<Item = Crease<Anchor>>,
15907 cx: &mut Context<Self>,
15908 ) -> Vec<CreaseId> {
15909 self.display_map
15910 .update(cx, |map, cx| map.insert_creases(creases, cx))
15911 }
15912
15913 pub fn remove_creases(
15914 &mut self,
15915 ids: impl IntoIterator<Item = CreaseId>,
15916 cx: &mut Context<Self>,
15917 ) {
15918 self.display_map
15919 .update(cx, |map, cx| map.remove_creases(ids, cx));
15920 }
15921
15922 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15923 self.display_map
15924 .update(cx, |map, cx| map.snapshot(cx))
15925 .longest_row()
15926 }
15927
15928 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15929 self.display_map
15930 .update(cx, |map, cx| map.snapshot(cx))
15931 .max_point()
15932 }
15933
15934 pub fn text(&self, cx: &App) -> String {
15935 self.buffer.read(cx).read(cx).text()
15936 }
15937
15938 pub fn is_empty(&self, cx: &App) -> bool {
15939 self.buffer.read(cx).read(cx).is_empty()
15940 }
15941
15942 pub fn text_option(&self, cx: &App) -> Option<String> {
15943 let text = self.text(cx);
15944 let text = text.trim();
15945
15946 if text.is_empty() {
15947 return None;
15948 }
15949
15950 Some(text.to_string())
15951 }
15952
15953 pub fn set_text(
15954 &mut self,
15955 text: impl Into<Arc<str>>,
15956 window: &mut Window,
15957 cx: &mut Context<Self>,
15958 ) {
15959 self.transact(window, cx, |this, _, cx| {
15960 this.buffer
15961 .read(cx)
15962 .as_singleton()
15963 .expect("you can only call set_text on editors for singleton buffers")
15964 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15965 });
15966 }
15967
15968 pub fn display_text(&self, cx: &mut App) -> String {
15969 self.display_map
15970 .update(cx, |map, cx| map.snapshot(cx))
15971 .text()
15972 }
15973
15974 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15975 let mut wrap_guides = smallvec::smallvec![];
15976
15977 if self.show_wrap_guides == Some(false) {
15978 return wrap_guides;
15979 }
15980
15981 let settings = self.buffer.read(cx).language_settings(cx);
15982 if settings.show_wrap_guides {
15983 match self.soft_wrap_mode(cx) {
15984 SoftWrap::Column(soft_wrap) => {
15985 wrap_guides.push((soft_wrap as usize, true));
15986 }
15987 SoftWrap::Bounded(soft_wrap) => {
15988 wrap_guides.push((soft_wrap as usize, true));
15989 }
15990 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15991 }
15992 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15993 }
15994
15995 wrap_guides
15996 }
15997
15998 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15999 let settings = self.buffer.read(cx).language_settings(cx);
16000 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16001 match mode {
16002 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16003 SoftWrap::None
16004 }
16005 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16006 language_settings::SoftWrap::PreferredLineLength => {
16007 SoftWrap::Column(settings.preferred_line_length)
16008 }
16009 language_settings::SoftWrap::Bounded => {
16010 SoftWrap::Bounded(settings.preferred_line_length)
16011 }
16012 }
16013 }
16014
16015 pub fn set_soft_wrap_mode(
16016 &mut self,
16017 mode: language_settings::SoftWrap,
16018
16019 cx: &mut Context<Self>,
16020 ) {
16021 self.soft_wrap_mode_override = Some(mode);
16022 cx.notify();
16023 }
16024
16025 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16026 self.hard_wrap = hard_wrap;
16027 cx.notify();
16028 }
16029
16030 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16031 self.text_style_refinement = Some(style);
16032 }
16033
16034 /// called by the Element so we know what style we were most recently rendered with.
16035 pub(crate) fn set_style(
16036 &mut self,
16037 style: EditorStyle,
16038 window: &mut Window,
16039 cx: &mut Context<Self>,
16040 ) {
16041 let rem_size = window.rem_size();
16042 self.display_map.update(cx, |map, cx| {
16043 map.set_font(
16044 style.text.font(),
16045 style.text.font_size.to_pixels(rem_size),
16046 cx,
16047 )
16048 });
16049 self.style = Some(style);
16050 }
16051
16052 pub fn style(&self) -> Option<&EditorStyle> {
16053 self.style.as_ref()
16054 }
16055
16056 // Called by the element. This method is not designed to be called outside of the editor
16057 // element's layout code because it does not notify when rewrapping is computed synchronously.
16058 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16059 self.display_map
16060 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16061 }
16062
16063 pub fn set_soft_wrap(&mut self) {
16064 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16065 }
16066
16067 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16068 if self.soft_wrap_mode_override.is_some() {
16069 self.soft_wrap_mode_override.take();
16070 } else {
16071 let soft_wrap = match self.soft_wrap_mode(cx) {
16072 SoftWrap::GitDiff => return,
16073 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16074 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16075 language_settings::SoftWrap::None
16076 }
16077 };
16078 self.soft_wrap_mode_override = Some(soft_wrap);
16079 }
16080 cx.notify();
16081 }
16082
16083 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16084 let Some(workspace) = self.workspace() else {
16085 return;
16086 };
16087 let fs = workspace.read(cx).app_state().fs.clone();
16088 let current_show = TabBarSettings::get_global(cx).show;
16089 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16090 setting.show = Some(!current_show);
16091 });
16092 }
16093
16094 pub fn toggle_indent_guides(
16095 &mut self,
16096 _: &ToggleIndentGuides,
16097 _: &mut Window,
16098 cx: &mut Context<Self>,
16099 ) {
16100 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16101 self.buffer
16102 .read(cx)
16103 .language_settings(cx)
16104 .indent_guides
16105 .enabled
16106 });
16107 self.show_indent_guides = Some(!currently_enabled);
16108 cx.notify();
16109 }
16110
16111 fn should_show_indent_guides(&self) -> Option<bool> {
16112 self.show_indent_guides
16113 }
16114
16115 pub fn toggle_line_numbers(
16116 &mut self,
16117 _: &ToggleLineNumbers,
16118 _: &mut Window,
16119 cx: &mut Context<Self>,
16120 ) {
16121 let mut editor_settings = EditorSettings::get_global(cx).clone();
16122 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16123 EditorSettings::override_global(editor_settings, cx);
16124 }
16125
16126 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16127 if let Some(show_line_numbers) = self.show_line_numbers {
16128 return show_line_numbers;
16129 }
16130 EditorSettings::get_global(cx).gutter.line_numbers
16131 }
16132
16133 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16134 self.use_relative_line_numbers
16135 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16136 }
16137
16138 pub fn toggle_relative_line_numbers(
16139 &mut self,
16140 _: &ToggleRelativeLineNumbers,
16141 _: &mut Window,
16142 cx: &mut Context<Self>,
16143 ) {
16144 let is_relative = self.should_use_relative_line_numbers(cx);
16145 self.set_relative_line_number(Some(!is_relative), cx)
16146 }
16147
16148 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16149 self.use_relative_line_numbers = is_relative;
16150 cx.notify();
16151 }
16152
16153 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16154 self.show_gutter = show_gutter;
16155 cx.notify();
16156 }
16157
16158 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16159 self.show_scrollbars = show_scrollbars;
16160 cx.notify();
16161 }
16162
16163 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16164 self.show_line_numbers = Some(show_line_numbers);
16165 cx.notify();
16166 }
16167
16168 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16169 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16170 cx.notify();
16171 }
16172
16173 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16174 self.show_code_actions = Some(show_code_actions);
16175 cx.notify();
16176 }
16177
16178 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16179 self.show_runnables = Some(show_runnables);
16180 cx.notify();
16181 }
16182
16183 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16184 self.show_breakpoints = Some(show_breakpoints);
16185 cx.notify();
16186 }
16187
16188 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16189 if self.display_map.read(cx).masked != masked {
16190 self.display_map.update(cx, |map, _| map.masked = masked);
16191 }
16192 cx.notify()
16193 }
16194
16195 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16196 self.show_wrap_guides = Some(show_wrap_guides);
16197 cx.notify();
16198 }
16199
16200 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16201 self.show_indent_guides = Some(show_indent_guides);
16202 cx.notify();
16203 }
16204
16205 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16206 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16207 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16208 if let Some(dir) = file.abs_path(cx).parent() {
16209 return Some(dir.to_owned());
16210 }
16211 }
16212
16213 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16214 return Some(project_path.path.to_path_buf());
16215 }
16216 }
16217
16218 None
16219 }
16220
16221 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16222 self.active_excerpt(cx)?
16223 .1
16224 .read(cx)
16225 .file()
16226 .and_then(|f| f.as_local())
16227 }
16228
16229 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16230 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16231 let buffer = buffer.read(cx);
16232 if let Some(project_path) = buffer.project_path(cx) {
16233 let project = self.project.as_ref()?.read(cx);
16234 project.absolute_path(&project_path, cx)
16235 } else {
16236 buffer
16237 .file()
16238 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16239 }
16240 })
16241 }
16242
16243 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16244 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16245 let project_path = buffer.read(cx).project_path(cx)?;
16246 let project = self.project.as_ref()?.read(cx);
16247 let entry = project.entry_for_path(&project_path, cx)?;
16248 let path = entry.path.to_path_buf();
16249 Some(path)
16250 })
16251 }
16252
16253 pub fn reveal_in_finder(
16254 &mut self,
16255 _: &RevealInFileManager,
16256 _window: &mut Window,
16257 cx: &mut Context<Self>,
16258 ) {
16259 if let Some(target) = self.target_file(cx) {
16260 cx.reveal_path(&target.abs_path(cx));
16261 }
16262 }
16263
16264 pub fn copy_path(
16265 &mut self,
16266 _: &zed_actions::workspace::CopyPath,
16267 _window: &mut Window,
16268 cx: &mut Context<Self>,
16269 ) {
16270 if let Some(path) = self.target_file_abs_path(cx) {
16271 if let Some(path) = path.to_str() {
16272 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16273 }
16274 }
16275 }
16276
16277 pub fn copy_relative_path(
16278 &mut self,
16279 _: &zed_actions::workspace::CopyRelativePath,
16280 _window: &mut Window,
16281 cx: &mut Context<Self>,
16282 ) {
16283 if let Some(path) = self.target_file_path(cx) {
16284 if let Some(path) = path.to_str() {
16285 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16286 }
16287 }
16288 }
16289
16290 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16291 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16292 buffer.read(cx).project_path(cx)
16293 } else {
16294 None
16295 }
16296 }
16297
16298 // Returns true if the editor handled a go-to-line request
16299 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16300 maybe!({
16301 let breakpoint_store = self.breakpoint_store.as_ref()?;
16302
16303 let Some((_, _, active_position)) =
16304 breakpoint_store.read(cx).active_position().cloned()
16305 else {
16306 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16307 return None;
16308 };
16309
16310 let snapshot = self
16311 .project
16312 .as_ref()?
16313 .read(cx)
16314 .buffer_for_id(active_position.buffer_id?, cx)?
16315 .read(cx)
16316 .snapshot();
16317
16318 let mut handled = false;
16319 for (id, ExcerptRange { context, .. }) in self
16320 .buffer
16321 .read(cx)
16322 .excerpts_for_buffer(active_position.buffer_id?, cx)
16323 {
16324 if context.start.cmp(&active_position, &snapshot).is_ge()
16325 || context.end.cmp(&active_position, &snapshot).is_lt()
16326 {
16327 continue;
16328 }
16329 let snapshot = self.buffer.read(cx).snapshot(cx);
16330 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16331
16332 handled = true;
16333 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16334 self.go_to_line::<DebugCurrentRowHighlight>(
16335 multibuffer_anchor,
16336 Some(cx.theme().colors().editor_debugger_active_line_background),
16337 window,
16338 cx,
16339 );
16340
16341 cx.notify();
16342 }
16343 handled.then_some(())
16344 })
16345 .is_some()
16346 }
16347
16348 pub fn copy_file_name_without_extension(
16349 &mut self,
16350 _: &CopyFileNameWithoutExtension,
16351 _: &mut Window,
16352 cx: &mut Context<Self>,
16353 ) {
16354 if let Some(file) = self.target_file(cx) {
16355 if let Some(file_stem) = file.path().file_stem() {
16356 if let Some(name) = file_stem.to_str() {
16357 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16358 }
16359 }
16360 }
16361 }
16362
16363 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16364 if let Some(file) = self.target_file(cx) {
16365 if let Some(file_name) = file.path().file_name() {
16366 if let Some(name) = file_name.to_str() {
16367 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16368 }
16369 }
16370 }
16371 }
16372
16373 pub fn toggle_git_blame(
16374 &mut self,
16375 _: &::git::Blame,
16376 window: &mut Window,
16377 cx: &mut Context<Self>,
16378 ) {
16379 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16380
16381 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16382 self.start_git_blame(true, window, cx);
16383 }
16384
16385 cx.notify();
16386 }
16387
16388 pub fn toggle_git_blame_inline(
16389 &mut self,
16390 _: &ToggleGitBlameInline,
16391 window: &mut Window,
16392 cx: &mut Context<Self>,
16393 ) {
16394 self.toggle_git_blame_inline_internal(true, window, cx);
16395 cx.notify();
16396 }
16397
16398 pub fn open_git_blame_commit(
16399 &mut self,
16400 _: &OpenGitBlameCommit,
16401 window: &mut Window,
16402 cx: &mut Context<Self>,
16403 ) {
16404 self.open_git_blame_commit_internal(window, cx);
16405 }
16406
16407 fn open_git_blame_commit_internal(
16408 &mut self,
16409 window: &mut Window,
16410 cx: &mut Context<Self>,
16411 ) -> Option<()> {
16412 let blame = self.blame.as_ref()?;
16413 let snapshot = self.snapshot(window, cx);
16414 let cursor = self.selections.newest::<Point>(cx).head();
16415 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16416 let blame_entry = blame
16417 .update(cx, |blame, cx| {
16418 blame
16419 .blame_for_rows(
16420 &[RowInfo {
16421 buffer_id: Some(buffer.remote_id()),
16422 buffer_row: Some(point.row),
16423 ..Default::default()
16424 }],
16425 cx,
16426 )
16427 .next()
16428 })
16429 .flatten()?;
16430 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16431 let repo = blame.read(cx).repository(cx)?;
16432 let workspace = self.workspace()?.downgrade();
16433 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16434 None
16435 }
16436
16437 pub fn git_blame_inline_enabled(&self) -> bool {
16438 self.git_blame_inline_enabled
16439 }
16440
16441 pub fn toggle_selection_menu(
16442 &mut self,
16443 _: &ToggleSelectionMenu,
16444 _: &mut Window,
16445 cx: &mut Context<Self>,
16446 ) {
16447 self.show_selection_menu = self
16448 .show_selection_menu
16449 .map(|show_selections_menu| !show_selections_menu)
16450 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16451
16452 cx.notify();
16453 }
16454
16455 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16456 self.show_selection_menu
16457 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16458 }
16459
16460 fn start_git_blame(
16461 &mut self,
16462 user_triggered: bool,
16463 window: &mut Window,
16464 cx: &mut Context<Self>,
16465 ) {
16466 if let Some(project) = self.project.as_ref() {
16467 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16468 return;
16469 };
16470
16471 if buffer.read(cx).file().is_none() {
16472 return;
16473 }
16474
16475 let focused = self.focus_handle(cx).contains_focused(window, cx);
16476
16477 let project = project.clone();
16478 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16479 self.blame_subscription =
16480 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16481 self.blame = Some(blame);
16482 }
16483 }
16484
16485 fn toggle_git_blame_inline_internal(
16486 &mut self,
16487 user_triggered: bool,
16488 window: &mut Window,
16489 cx: &mut Context<Self>,
16490 ) {
16491 if self.git_blame_inline_enabled {
16492 self.git_blame_inline_enabled = false;
16493 self.show_git_blame_inline = false;
16494 self.show_git_blame_inline_delay_task.take();
16495 } else {
16496 self.git_blame_inline_enabled = true;
16497 self.start_git_blame_inline(user_triggered, window, cx);
16498 }
16499
16500 cx.notify();
16501 }
16502
16503 fn start_git_blame_inline(
16504 &mut self,
16505 user_triggered: bool,
16506 window: &mut Window,
16507 cx: &mut Context<Self>,
16508 ) {
16509 self.start_git_blame(user_triggered, window, cx);
16510
16511 if ProjectSettings::get_global(cx)
16512 .git
16513 .inline_blame_delay()
16514 .is_some()
16515 {
16516 self.start_inline_blame_timer(window, cx);
16517 } else {
16518 self.show_git_blame_inline = true
16519 }
16520 }
16521
16522 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16523 self.blame.as_ref()
16524 }
16525
16526 pub fn show_git_blame_gutter(&self) -> bool {
16527 self.show_git_blame_gutter
16528 }
16529
16530 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16531 self.show_git_blame_gutter && self.has_blame_entries(cx)
16532 }
16533
16534 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16535 self.show_git_blame_inline
16536 && (self.focus_handle.is_focused(window)
16537 || self
16538 .git_blame_inline_tooltip
16539 .as_ref()
16540 .and_then(|t| t.upgrade())
16541 .is_some())
16542 && !self.newest_selection_head_on_empty_line(cx)
16543 && self.has_blame_entries(cx)
16544 }
16545
16546 fn has_blame_entries(&self, cx: &App) -> bool {
16547 self.blame()
16548 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16549 }
16550
16551 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16552 let cursor_anchor = self.selections.newest_anchor().head();
16553
16554 let snapshot = self.buffer.read(cx).snapshot(cx);
16555 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16556
16557 snapshot.line_len(buffer_row) == 0
16558 }
16559
16560 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16561 let buffer_and_selection = maybe!({
16562 let selection = self.selections.newest::<Point>(cx);
16563 let selection_range = selection.range();
16564
16565 let multi_buffer = self.buffer().read(cx);
16566 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16567 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16568
16569 let (buffer, range, _) = if selection.reversed {
16570 buffer_ranges.first()
16571 } else {
16572 buffer_ranges.last()
16573 }?;
16574
16575 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16576 ..text::ToPoint::to_point(&range.end, &buffer).row;
16577 Some((
16578 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16579 selection,
16580 ))
16581 });
16582
16583 let Some((buffer, selection)) = buffer_and_selection else {
16584 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16585 };
16586
16587 let Some(project) = self.project.as_ref() else {
16588 return Task::ready(Err(anyhow!("editor does not have project")));
16589 };
16590
16591 project.update(cx, |project, cx| {
16592 project.get_permalink_to_line(&buffer, selection, cx)
16593 })
16594 }
16595
16596 pub fn copy_permalink_to_line(
16597 &mut self,
16598 _: &CopyPermalinkToLine,
16599 window: &mut Window,
16600 cx: &mut Context<Self>,
16601 ) {
16602 let permalink_task = self.get_permalink_to_line(cx);
16603 let workspace = self.workspace();
16604
16605 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16606 Ok(permalink) => {
16607 cx.update(|_, cx| {
16608 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16609 })
16610 .ok();
16611 }
16612 Err(err) => {
16613 let message = format!("Failed to copy permalink: {err}");
16614
16615 Err::<(), anyhow::Error>(err).log_err();
16616
16617 if let Some(workspace) = workspace {
16618 workspace
16619 .update_in(cx, |workspace, _, cx| {
16620 struct CopyPermalinkToLine;
16621
16622 workspace.show_toast(
16623 Toast::new(
16624 NotificationId::unique::<CopyPermalinkToLine>(),
16625 message,
16626 ),
16627 cx,
16628 )
16629 })
16630 .ok();
16631 }
16632 }
16633 })
16634 .detach();
16635 }
16636
16637 pub fn copy_file_location(
16638 &mut self,
16639 _: &CopyFileLocation,
16640 _: &mut Window,
16641 cx: &mut Context<Self>,
16642 ) {
16643 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16644 if let Some(file) = self.target_file(cx) {
16645 if let Some(path) = file.path().to_str() {
16646 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16647 }
16648 }
16649 }
16650
16651 pub fn open_permalink_to_line(
16652 &mut self,
16653 _: &OpenPermalinkToLine,
16654 window: &mut Window,
16655 cx: &mut Context<Self>,
16656 ) {
16657 let permalink_task = self.get_permalink_to_line(cx);
16658 let workspace = self.workspace();
16659
16660 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16661 Ok(permalink) => {
16662 cx.update(|_, cx| {
16663 cx.open_url(permalink.as_ref());
16664 })
16665 .ok();
16666 }
16667 Err(err) => {
16668 let message = format!("Failed to open permalink: {err}");
16669
16670 Err::<(), anyhow::Error>(err).log_err();
16671
16672 if let Some(workspace) = workspace {
16673 workspace
16674 .update(cx, |workspace, cx| {
16675 struct OpenPermalinkToLine;
16676
16677 workspace.show_toast(
16678 Toast::new(
16679 NotificationId::unique::<OpenPermalinkToLine>(),
16680 message,
16681 ),
16682 cx,
16683 )
16684 })
16685 .ok();
16686 }
16687 }
16688 })
16689 .detach();
16690 }
16691
16692 pub fn insert_uuid_v4(
16693 &mut self,
16694 _: &InsertUuidV4,
16695 window: &mut Window,
16696 cx: &mut Context<Self>,
16697 ) {
16698 self.insert_uuid(UuidVersion::V4, window, cx);
16699 }
16700
16701 pub fn insert_uuid_v7(
16702 &mut self,
16703 _: &InsertUuidV7,
16704 window: &mut Window,
16705 cx: &mut Context<Self>,
16706 ) {
16707 self.insert_uuid(UuidVersion::V7, window, cx);
16708 }
16709
16710 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16711 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16712 self.transact(window, cx, |this, window, cx| {
16713 let edits = this
16714 .selections
16715 .all::<Point>(cx)
16716 .into_iter()
16717 .map(|selection| {
16718 let uuid = match version {
16719 UuidVersion::V4 => uuid::Uuid::new_v4(),
16720 UuidVersion::V7 => uuid::Uuid::now_v7(),
16721 };
16722
16723 (selection.range(), uuid.to_string())
16724 });
16725 this.edit(edits, cx);
16726 this.refresh_inline_completion(true, false, window, cx);
16727 });
16728 }
16729
16730 pub fn open_selections_in_multibuffer(
16731 &mut self,
16732 _: &OpenSelectionsInMultibuffer,
16733 window: &mut Window,
16734 cx: &mut Context<Self>,
16735 ) {
16736 let multibuffer = self.buffer.read(cx);
16737
16738 let Some(buffer) = multibuffer.as_singleton() else {
16739 return;
16740 };
16741
16742 let Some(workspace) = self.workspace() else {
16743 return;
16744 };
16745
16746 let locations = self
16747 .selections
16748 .disjoint_anchors()
16749 .iter()
16750 .map(|range| Location {
16751 buffer: buffer.clone(),
16752 range: range.start.text_anchor..range.end.text_anchor,
16753 })
16754 .collect::<Vec<_>>();
16755
16756 let title = multibuffer.title(cx).to_string();
16757
16758 cx.spawn_in(window, async move |_, cx| {
16759 workspace.update_in(cx, |workspace, window, cx| {
16760 Self::open_locations_in_multibuffer(
16761 workspace,
16762 locations,
16763 format!("Selections for '{title}'"),
16764 false,
16765 MultibufferSelectionMode::All,
16766 window,
16767 cx,
16768 );
16769 })
16770 })
16771 .detach();
16772 }
16773
16774 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16775 /// last highlight added will be used.
16776 ///
16777 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16778 pub fn highlight_rows<T: 'static>(
16779 &mut self,
16780 range: Range<Anchor>,
16781 color: Hsla,
16782 should_autoscroll: bool,
16783 cx: &mut Context<Self>,
16784 ) {
16785 let snapshot = self.buffer().read(cx).snapshot(cx);
16786 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16787 let ix = row_highlights.binary_search_by(|highlight| {
16788 Ordering::Equal
16789 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16790 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16791 });
16792
16793 if let Err(mut ix) = ix {
16794 let index = post_inc(&mut self.highlight_order);
16795
16796 // If this range intersects with the preceding highlight, then merge it with
16797 // the preceding highlight. Otherwise insert a new highlight.
16798 let mut merged = false;
16799 if ix > 0 {
16800 let prev_highlight = &mut row_highlights[ix - 1];
16801 if prev_highlight
16802 .range
16803 .end
16804 .cmp(&range.start, &snapshot)
16805 .is_ge()
16806 {
16807 ix -= 1;
16808 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16809 prev_highlight.range.end = range.end;
16810 }
16811 merged = true;
16812 prev_highlight.index = index;
16813 prev_highlight.color = color;
16814 prev_highlight.should_autoscroll = should_autoscroll;
16815 }
16816 }
16817
16818 if !merged {
16819 row_highlights.insert(
16820 ix,
16821 RowHighlight {
16822 range: range.clone(),
16823 index,
16824 color,
16825 should_autoscroll,
16826 },
16827 );
16828 }
16829
16830 // If any of the following highlights intersect with this one, merge them.
16831 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16832 let highlight = &row_highlights[ix];
16833 if next_highlight
16834 .range
16835 .start
16836 .cmp(&highlight.range.end, &snapshot)
16837 .is_le()
16838 {
16839 if next_highlight
16840 .range
16841 .end
16842 .cmp(&highlight.range.end, &snapshot)
16843 .is_gt()
16844 {
16845 row_highlights[ix].range.end = next_highlight.range.end;
16846 }
16847 row_highlights.remove(ix + 1);
16848 } else {
16849 break;
16850 }
16851 }
16852 }
16853 }
16854
16855 /// Remove any highlighted row ranges of the given type that intersect the
16856 /// given ranges.
16857 pub fn remove_highlighted_rows<T: 'static>(
16858 &mut self,
16859 ranges_to_remove: Vec<Range<Anchor>>,
16860 cx: &mut Context<Self>,
16861 ) {
16862 let snapshot = self.buffer().read(cx).snapshot(cx);
16863 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16864 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16865 row_highlights.retain(|highlight| {
16866 while let Some(range_to_remove) = ranges_to_remove.peek() {
16867 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16868 Ordering::Less | Ordering::Equal => {
16869 ranges_to_remove.next();
16870 }
16871 Ordering::Greater => {
16872 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16873 Ordering::Less | Ordering::Equal => {
16874 return false;
16875 }
16876 Ordering::Greater => break,
16877 }
16878 }
16879 }
16880 }
16881
16882 true
16883 })
16884 }
16885
16886 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16887 pub fn clear_row_highlights<T: 'static>(&mut self) {
16888 self.highlighted_rows.remove(&TypeId::of::<T>());
16889 }
16890
16891 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16892 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16893 self.highlighted_rows
16894 .get(&TypeId::of::<T>())
16895 .map_or(&[] as &[_], |vec| vec.as_slice())
16896 .iter()
16897 .map(|highlight| (highlight.range.clone(), highlight.color))
16898 }
16899
16900 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16901 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16902 /// Allows to ignore certain kinds of highlights.
16903 pub fn highlighted_display_rows(
16904 &self,
16905 window: &mut Window,
16906 cx: &mut App,
16907 ) -> BTreeMap<DisplayRow, LineHighlight> {
16908 let snapshot = self.snapshot(window, cx);
16909 let mut used_highlight_orders = HashMap::default();
16910 self.highlighted_rows
16911 .iter()
16912 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16913 .fold(
16914 BTreeMap::<DisplayRow, LineHighlight>::new(),
16915 |mut unique_rows, highlight| {
16916 let start = highlight.range.start.to_display_point(&snapshot);
16917 let end = highlight.range.end.to_display_point(&snapshot);
16918 let start_row = start.row().0;
16919 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16920 && end.column() == 0
16921 {
16922 end.row().0.saturating_sub(1)
16923 } else {
16924 end.row().0
16925 };
16926 for row in start_row..=end_row {
16927 let used_index =
16928 used_highlight_orders.entry(row).or_insert(highlight.index);
16929 if highlight.index >= *used_index {
16930 *used_index = highlight.index;
16931 unique_rows.insert(DisplayRow(row), highlight.color.into());
16932 }
16933 }
16934 unique_rows
16935 },
16936 )
16937 }
16938
16939 pub fn highlighted_display_row_for_autoscroll(
16940 &self,
16941 snapshot: &DisplaySnapshot,
16942 ) -> Option<DisplayRow> {
16943 self.highlighted_rows
16944 .values()
16945 .flat_map(|highlighted_rows| highlighted_rows.iter())
16946 .filter_map(|highlight| {
16947 if highlight.should_autoscroll {
16948 Some(highlight.range.start.to_display_point(snapshot).row())
16949 } else {
16950 None
16951 }
16952 })
16953 .min()
16954 }
16955
16956 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16957 self.highlight_background::<SearchWithinRange>(
16958 ranges,
16959 |colors| colors.editor_document_highlight_read_background,
16960 cx,
16961 )
16962 }
16963
16964 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16965 self.breadcrumb_header = Some(new_header);
16966 }
16967
16968 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16969 self.clear_background_highlights::<SearchWithinRange>(cx);
16970 }
16971
16972 pub fn highlight_background<T: 'static>(
16973 &mut self,
16974 ranges: &[Range<Anchor>],
16975 color_fetcher: fn(&ThemeColors) -> Hsla,
16976 cx: &mut Context<Self>,
16977 ) {
16978 self.background_highlights
16979 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16980 self.scrollbar_marker_state.dirty = true;
16981 cx.notify();
16982 }
16983
16984 pub fn clear_background_highlights<T: 'static>(
16985 &mut self,
16986 cx: &mut Context<Self>,
16987 ) -> Option<BackgroundHighlight> {
16988 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16989 if !text_highlights.1.is_empty() {
16990 self.scrollbar_marker_state.dirty = true;
16991 cx.notify();
16992 }
16993 Some(text_highlights)
16994 }
16995
16996 pub fn highlight_gutter<T: 'static>(
16997 &mut self,
16998 ranges: &[Range<Anchor>],
16999 color_fetcher: fn(&App) -> Hsla,
17000 cx: &mut Context<Self>,
17001 ) {
17002 self.gutter_highlights
17003 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17004 cx.notify();
17005 }
17006
17007 pub fn clear_gutter_highlights<T: 'static>(
17008 &mut self,
17009 cx: &mut Context<Self>,
17010 ) -> Option<GutterHighlight> {
17011 cx.notify();
17012 self.gutter_highlights.remove(&TypeId::of::<T>())
17013 }
17014
17015 #[cfg(feature = "test-support")]
17016 pub fn all_text_background_highlights(
17017 &self,
17018 window: &mut Window,
17019 cx: &mut Context<Self>,
17020 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17021 let snapshot = self.snapshot(window, cx);
17022 let buffer = &snapshot.buffer_snapshot;
17023 let start = buffer.anchor_before(0);
17024 let end = buffer.anchor_after(buffer.len());
17025 let theme = cx.theme().colors();
17026 self.background_highlights_in_range(start..end, &snapshot, theme)
17027 }
17028
17029 #[cfg(feature = "test-support")]
17030 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17031 let snapshot = self.buffer().read(cx).snapshot(cx);
17032
17033 let highlights = self
17034 .background_highlights
17035 .get(&TypeId::of::<items::BufferSearchHighlights>());
17036
17037 if let Some((_color, ranges)) = highlights {
17038 ranges
17039 .iter()
17040 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17041 .collect_vec()
17042 } else {
17043 vec![]
17044 }
17045 }
17046
17047 fn document_highlights_for_position<'a>(
17048 &'a self,
17049 position: Anchor,
17050 buffer: &'a MultiBufferSnapshot,
17051 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17052 let read_highlights = self
17053 .background_highlights
17054 .get(&TypeId::of::<DocumentHighlightRead>())
17055 .map(|h| &h.1);
17056 let write_highlights = self
17057 .background_highlights
17058 .get(&TypeId::of::<DocumentHighlightWrite>())
17059 .map(|h| &h.1);
17060 let left_position = position.bias_left(buffer);
17061 let right_position = position.bias_right(buffer);
17062 read_highlights
17063 .into_iter()
17064 .chain(write_highlights)
17065 .flat_map(move |ranges| {
17066 let start_ix = match ranges.binary_search_by(|probe| {
17067 let cmp = probe.end.cmp(&left_position, buffer);
17068 if cmp.is_ge() {
17069 Ordering::Greater
17070 } else {
17071 Ordering::Less
17072 }
17073 }) {
17074 Ok(i) | Err(i) => i,
17075 };
17076
17077 ranges[start_ix..]
17078 .iter()
17079 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17080 })
17081 }
17082
17083 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17084 self.background_highlights
17085 .get(&TypeId::of::<T>())
17086 .map_or(false, |(_, highlights)| !highlights.is_empty())
17087 }
17088
17089 pub fn background_highlights_in_range(
17090 &self,
17091 search_range: Range<Anchor>,
17092 display_snapshot: &DisplaySnapshot,
17093 theme: &ThemeColors,
17094 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17095 let mut results = Vec::new();
17096 for (color_fetcher, ranges) in self.background_highlights.values() {
17097 let color = color_fetcher(theme);
17098 let start_ix = match ranges.binary_search_by(|probe| {
17099 let cmp = probe
17100 .end
17101 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17102 if cmp.is_gt() {
17103 Ordering::Greater
17104 } else {
17105 Ordering::Less
17106 }
17107 }) {
17108 Ok(i) | Err(i) => i,
17109 };
17110 for range in &ranges[start_ix..] {
17111 if range
17112 .start
17113 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17114 .is_ge()
17115 {
17116 break;
17117 }
17118
17119 let start = range.start.to_display_point(display_snapshot);
17120 let end = range.end.to_display_point(display_snapshot);
17121 results.push((start..end, color))
17122 }
17123 }
17124 results
17125 }
17126
17127 pub fn background_highlight_row_ranges<T: 'static>(
17128 &self,
17129 search_range: Range<Anchor>,
17130 display_snapshot: &DisplaySnapshot,
17131 count: usize,
17132 ) -> Vec<RangeInclusive<DisplayPoint>> {
17133 let mut results = Vec::new();
17134 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17135 return vec![];
17136 };
17137
17138 let start_ix = match ranges.binary_search_by(|probe| {
17139 let cmp = probe
17140 .end
17141 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17142 if cmp.is_gt() {
17143 Ordering::Greater
17144 } else {
17145 Ordering::Less
17146 }
17147 }) {
17148 Ok(i) | Err(i) => i,
17149 };
17150 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17151 if let (Some(start_display), Some(end_display)) = (start, end) {
17152 results.push(
17153 start_display.to_display_point(display_snapshot)
17154 ..=end_display.to_display_point(display_snapshot),
17155 );
17156 }
17157 };
17158 let mut start_row: Option<Point> = None;
17159 let mut end_row: Option<Point> = None;
17160 if ranges.len() > count {
17161 return Vec::new();
17162 }
17163 for range in &ranges[start_ix..] {
17164 if range
17165 .start
17166 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17167 .is_ge()
17168 {
17169 break;
17170 }
17171 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17172 if let Some(current_row) = &end_row {
17173 if end.row == current_row.row {
17174 continue;
17175 }
17176 }
17177 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17178 if start_row.is_none() {
17179 assert_eq!(end_row, None);
17180 start_row = Some(start);
17181 end_row = Some(end);
17182 continue;
17183 }
17184 if let Some(current_end) = end_row.as_mut() {
17185 if start.row > current_end.row + 1 {
17186 push_region(start_row, end_row);
17187 start_row = Some(start);
17188 end_row = Some(end);
17189 } else {
17190 // Merge two hunks.
17191 *current_end = end;
17192 }
17193 } else {
17194 unreachable!();
17195 }
17196 }
17197 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17198 push_region(start_row, end_row);
17199 results
17200 }
17201
17202 pub fn gutter_highlights_in_range(
17203 &self,
17204 search_range: Range<Anchor>,
17205 display_snapshot: &DisplaySnapshot,
17206 cx: &App,
17207 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17208 let mut results = Vec::new();
17209 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17210 let color = color_fetcher(cx);
17211 let start_ix = match ranges.binary_search_by(|probe| {
17212 let cmp = probe
17213 .end
17214 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17215 if cmp.is_gt() {
17216 Ordering::Greater
17217 } else {
17218 Ordering::Less
17219 }
17220 }) {
17221 Ok(i) | Err(i) => i,
17222 };
17223 for range in &ranges[start_ix..] {
17224 if range
17225 .start
17226 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17227 .is_ge()
17228 {
17229 break;
17230 }
17231
17232 let start = range.start.to_display_point(display_snapshot);
17233 let end = range.end.to_display_point(display_snapshot);
17234 results.push((start..end, color))
17235 }
17236 }
17237 results
17238 }
17239
17240 /// Get the text ranges corresponding to the redaction query
17241 pub fn redacted_ranges(
17242 &self,
17243 search_range: Range<Anchor>,
17244 display_snapshot: &DisplaySnapshot,
17245 cx: &App,
17246 ) -> Vec<Range<DisplayPoint>> {
17247 display_snapshot
17248 .buffer_snapshot
17249 .redacted_ranges(search_range, |file| {
17250 if let Some(file) = file {
17251 file.is_private()
17252 && EditorSettings::get(
17253 Some(SettingsLocation {
17254 worktree_id: file.worktree_id(cx),
17255 path: file.path().as_ref(),
17256 }),
17257 cx,
17258 )
17259 .redact_private_values
17260 } else {
17261 false
17262 }
17263 })
17264 .map(|range| {
17265 range.start.to_display_point(display_snapshot)
17266 ..range.end.to_display_point(display_snapshot)
17267 })
17268 .collect()
17269 }
17270
17271 pub fn highlight_text<T: 'static>(
17272 &mut self,
17273 ranges: Vec<Range<Anchor>>,
17274 style: HighlightStyle,
17275 cx: &mut Context<Self>,
17276 ) {
17277 self.display_map.update(cx, |map, _| {
17278 map.highlight_text(TypeId::of::<T>(), ranges, style)
17279 });
17280 cx.notify();
17281 }
17282
17283 pub(crate) fn highlight_inlays<T: 'static>(
17284 &mut self,
17285 highlights: Vec<InlayHighlight>,
17286 style: HighlightStyle,
17287 cx: &mut Context<Self>,
17288 ) {
17289 self.display_map.update(cx, |map, _| {
17290 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17291 });
17292 cx.notify();
17293 }
17294
17295 pub fn text_highlights<'a, T: 'static>(
17296 &'a self,
17297 cx: &'a App,
17298 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17299 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17300 }
17301
17302 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17303 let cleared = self
17304 .display_map
17305 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17306 if cleared {
17307 cx.notify();
17308 }
17309 }
17310
17311 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17312 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17313 && self.focus_handle.is_focused(window)
17314 }
17315
17316 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17317 self.show_cursor_when_unfocused = is_enabled;
17318 cx.notify();
17319 }
17320
17321 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17322 cx.notify();
17323 }
17324
17325 fn on_buffer_event(
17326 &mut self,
17327 multibuffer: &Entity<MultiBuffer>,
17328 event: &multi_buffer::Event,
17329 window: &mut Window,
17330 cx: &mut Context<Self>,
17331 ) {
17332 match event {
17333 multi_buffer::Event::Edited {
17334 singleton_buffer_edited,
17335 edited_buffer: buffer_edited,
17336 } => {
17337 self.scrollbar_marker_state.dirty = true;
17338 self.active_indent_guides_state.dirty = true;
17339 self.refresh_active_diagnostics(cx);
17340 self.refresh_code_actions(window, cx);
17341 if self.has_active_inline_completion() {
17342 self.update_visible_inline_completion(window, cx);
17343 }
17344 if let Some(buffer) = buffer_edited {
17345 let buffer_id = buffer.read(cx).remote_id();
17346 if !self.registered_buffers.contains_key(&buffer_id) {
17347 if let Some(project) = self.project.as_ref() {
17348 project.update(cx, |project, cx| {
17349 self.registered_buffers.insert(
17350 buffer_id,
17351 project.register_buffer_with_language_servers(&buffer, cx),
17352 );
17353 })
17354 }
17355 }
17356 }
17357 cx.emit(EditorEvent::BufferEdited);
17358 cx.emit(SearchEvent::MatchesInvalidated);
17359 if *singleton_buffer_edited {
17360 if let Some(project) = &self.project {
17361 #[allow(clippy::mutable_key_type)]
17362 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17363 multibuffer
17364 .all_buffers()
17365 .into_iter()
17366 .filter_map(|buffer| {
17367 buffer.update(cx, |buffer, cx| {
17368 let language = buffer.language()?;
17369 let should_discard = project.update(cx, |project, cx| {
17370 project.is_local()
17371 && !project.has_language_servers_for(buffer, cx)
17372 });
17373 should_discard.not().then_some(language.clone())
17374 })
17375 })
17376 .collect::<HashSet<_>>()
17377 });
17378 if !languages_affected.is_empty() {
17379 self.refresh_inlay_hints(
17380 InlayHintRefreshReason::BufferEdited(languages_affected),
17381 cx,
17382 );
17383 }
17384 }
17385 }
17386
17387 let Some(project) = &self.project else { return };
17388 let (telemetry, is_via_ssh) = {
17389 let project = project.read(cx);
17390 let telemetry = project.client().telemetry().clone();
17391 let is_via_ssh = project.is_via_ssh();
17392 (telemetry, is_via_ssh)
17393 };
17394 refresh_linked_ranges(self, window, cx);
17395 telemetry.log_edit_event("editor", is_via_ssh);
17396 }
17397 multi_buffer::Event::ExcerptsAdded {
17398 buffer,
17399 predecessor,
17400 excerpts,
17401 } => {
17402 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17403 let buffer_id = buffer.read(cx).remote_id();
17404 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17405 if let Some(project) = &self.project {
17406 get_uncommitted_diff_for_buffer(
17407 project,
17408 [buffer.clone()],
17409 self.buffer.clone(),
17410 cx,
17411 )
17412 .detach();
17413 }
17414 }
17415 cx.emit(EditorEvent::ExcerptsAdded {
17416 buffer: buffer.clone(),
17417 predecessor: *predecessor,
17418 excerpts: excerpts.clone(),
17419 });
17420 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17421 }
17422 multi_buffer::Event::ExcerptsRemoved { ids } => {
17423 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17424 let buffer = self.buffer.read(cx);
17425 self.registered_buffers
17426 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17427 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17428 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17429 }
17430 multi_buffer::Event::ExcerptsEdited {
17431 excerpt_ids,
17432 buffer_ids,
17433 } => {
17434 self.display_map.update(cx, |map, cx| {
17435 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17436 });
17437 cx.emit(EditorEvent::ExcerptsEdited {
17438 ids: excerpt_ids.clone(),
17439 })
17440 }
17441 multi_buffer::Event::ExcerptsExpanded { ids } => {
17442 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17443 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17444 }
17445 multi_buffer::Event::Reparsed(buffer_id) => {
17446 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17447 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17448
17449 cx.emit(EditorEvent::Reparsed(*buffer_id));
17450 }
17451 multi_buffer::Event::DiffHunksToggled => {
17452 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17453 }
17454 multi_buffer::Event::LanguageChanged(buffer_id) => {
17455 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17456 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17457 cx.emit(EditorEvent::Reparsed(*buffer_id));
17458 cx.notify();
17459 }
17460 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17461 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17462 multi_buffer::Event::FileHandleChanged
17463 | multi_buffer::Event::Reloaded
17464 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17465 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17466 multi_buffer::Event::DiagnosticsUpdated => {
17467 self.refresh_active_diagnostics(cx);
17468 self.refresh_inline_diagnostics(true, window, cx);
17469 self.scrollbar_marker_state.dirty = true;
17470 cx.notify();
17471 }
17472 _ => {}
17473 };
17474 }
17475
17476 fn on_display_map_changed(
17477 &mut self,
17478 _: Entity<DisplayMap>,
17479 _: &mut Window,
17480 cx: &mut Context<Self>,
17481 ) {
17482 cx.notify();
17483 }
17484
17485 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17486 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17487 self.update_edit_prediction_settings(cx);
17488 self.refresh_inline_completion(true, false, window, cx);
17489 self.refresh_inlay_hints(
17490 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17491 self.selections.newest_anchor().head(),
17492 &self.buffer.read(cx).snapshot(cx),
17493 cx,
17494 )),
17495 cx,
17496 );
17497
17498 let old_cursor_shape = self.cursor_shape;
17499
17500 {
17501 let editor_settings = EditorSettings::get_global(cx);
17502 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17503 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17504 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17505 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17506 }
17507
17508 if old_cursor_shape != self.cursor_shape {
17509 cx.emit(EditorEvent::CursorShapeChanged);
17510 }
17511
17512 let project_settings = ProjectSettings::get_global(cx);
17513 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17514
17515 if self.mode.is_full() {
17516 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17517 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17518 if self.show_inline_diagnostics != show_inline_diagnostics {
17519 self.show_inline_diagnostics = show_inline_diagnostics;
17520 self.refresh_inline_diagnostics(false, window, cx);
17521 }
17522
17523 if self.git_blame_inline_enabled != inline_blame_enabled {
17524 self.toggle_git_blame_inline_internal(false, window, cx);
17525 }
17526 }
17527
17528 cx.notify();
17529 }
17530
17531 pub fn set_searchable(&mut self, searchable: bool) {
17532 self.searchable = searchable;
17533 }
17534
17535 pub fn searchable(&self) -> bool {
17536 self.searchable
17537 }
17538
17539 fn open_proposed_changes_editor(
17540 &mut self,
17541 _: &OpenProposedChangesEditor,
17542 window: &mut Window,
17543 cx: &mut Context<Self>,
17544 ) {
17545 let Some(workspace) = self.workspace() else {
17546 cx.propagate();
17547 return;
17548 };
17549
17550 let selections = self.selections.all::<usize>(cx);
17551 let multi_buffer = self.buffer.read(cx);
17552 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17553 let mut new_selections_by_buffer = HashMap::default();
17554 for selection in selections {
17555 for (buffer, range, _) in
17556 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17557 {
17558 let mut range = range.to_point(buffer);
17559 range.start.column = 0;
17560 range.end.column = buffer.line_len(range.end.row);
17561 new_selections_by_buffer
17562 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17563 .or_insert(Vec::new())
17564 .push(range)
17565 }
17566 }
17567
17568 let proposed_changes_buffers = new_selections_by_buffer
17569 .into_iter()
17570 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17571 .collect::<Vec<_>>();
17572 let proposed_changes_editor = cx.new(|cx| {
17573 ProposedChangesEditor::new(
17574 "Proposed changes",
17575 proposed_changes_buffers,
17576 self.project.clone(),
17577 window,
17578 cx,
17579 )
17580 });
17581
17582 window.defer(cx, move |window, cx| {
17583 workspace.update(cx, |workspace, cx| {
17584 workspace.active_pane().update(cx, |pane, cx| {
17585 pane.add_item(
17586 Box::new(proposed_changes_editor),
17587 true,
17588 true,
17589 None,
17590 window,
17591 cx,
17592 );
17593 });
17594 });
17595 });
17596 }
17597
17598 pub fn open_excerpts_in_split(
17599 &mut self,
17600 _: &OpenExcerptsSplit,
17601 window: &mut Window,
17602 cx: &mut Context<Self>,
17603 ) {
17604 self.open_excerpts_common(None, true, window, cx)
17605 }
17606
17607 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17608 self.open_excerpts_common(None, false, window, cx)
17609 }
17610
17611 fn open_excerpts_common(
17612 &mut self,
17613 jump_data: Option<JumpData>,
17614 split: bool,
17615 window: &mut Window,
17616 cx: &mut Context<Self>,
17617 ) {
17618 let Some(workspace) = self.workspace() else {
17619 cx.propagate();
17620 return;
17621 };
17622
17623 if self.buffer.read(cx).is_singleton() {
17624 cx.propagate();
17625 return;
17626 }
17627
17628 let mut new_selections_by_buffer = HashMap::default();
17629 match &jump_data {
17630 Some(JumpData::MultiBufferPoint {
17631 excerpt_id,
17632 position,
17633 anchor,
17634 line_offset_from_top,
17635 }) => {
17636 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17637 if let Some(buffer) = multi_buffer_snapshot
17638 .buffer_id_for_excerpt(*excerpt_id)
17639 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17640 {
17641 let buffer_snapshot = buffer.read(cx).snapshot();
17642 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17643 language::ToPoint::to_point(anchor, &buffer_snapshot)
17644 } else {
17645 buffer_snapshot.clip_point(*position, Bias::Left)
17646 };
17647 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17648 new_selections_by_buffer.insert(
17649 buffer,
17650 (
17651 vec![jump_to_offset..jump_to_offset],
17652 Some(*line_offset_from_top),
17653 ),
17654 );
17655 }
17656 }
17657 Some(JumpData::MultiBufferRow {
17658 row,
17659 line_offset_from_top,
17660 }) => {
17661 let point = MultiBufferPoint::new(row.0, 0);
17662 if let Some((buffer, buffer_point, _)) =
17663 self.buffer.read(cx).point_to_buffer_point(point, cx)
17664 {
17665 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17666 new_selections_by_buffer
17667 .entry(buffer)
17668 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17669 .0
17670 .push(buffer_offset..buffer_offset)
17671 }
17672 }
17673 None => {
17674 let selections = self.selections.all::<usize>(cx);
17675 let multi_buffer = self.buffer.read(cx);
17676 for selection in selections {
17677 for (snapshot, range, _, anchor) in multi_buffer
17678 .snapshot(cx)
17679 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17680 {
17681 if let Some(anchor) = anchor {
17682 // selection is in a deleted hunk
17683 let Some(buffer_id) = anchor.buffer_id else {
17684 continue;
17685 };
17686 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17687 continue;
17688 };
17689 let offset = text::ToOffset::to_offset(
17690 &anchor.text_anchor,
17691 &buffer_handle.read(cx).snapshot(),
17692 );
17693 let range = offset..offset;
17694 new_selections_by_buffer
17695 .entry(buffer_handle)
17696 .or_insert((Vec::new(), None))
17697 .0
17698 .push(range)
17699 } else {
17700 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17701 else {
17702 continue;
17703 };
17704 new_selections_by_buffer
17705 .entry(buffer_handle)
17706 .or_insert((Vec::new(), None))
17707 .0
17708 .push(range)
17709 }
17710 }
17711 }
17712 }
17713 }
17714
17715 new_selections_by_buffer
17716 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17717
17718 if new_selections_by_buffer.is_empty() {
17719 return;
17720 }
17721
17722 // We defer the pane interaction because we ourselves are a workspace item
17723 // and activating a new item causes the pane to call a method on us reentrantly,
17724 // which panics if we're on the stack.
17725 window.defer(cx, move |window, cx| {
17726 workspace.update(cx, |workspace, cx| {
17727 let pane = if split {
17728 workspace.adjacent_pane(window, cx)
17729 } else {
17730 workspace.active_pane().clone()
17731 };
17732
17733 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17734 let editor = buffer
17735 .read(cx)
17736 .file()
17737 .is_none()
17738 .then(|| {
17739 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17740 // so `workspace.open_project_item` will never find them, always opening a new editor.
17741 // Instead, we try to activate the existing editor in the pane first.
17742 let (editor, pane_item_index) =
17743 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17744 let editor = item.downcast::<Editor>()?;
17745 let singleton_buffer =
17746 editor.read(cx).buffer().read(cx).as_singleton()?;
17747 if singleton_buffer == buffer {
17748 Some((editor, i))
17749 } else {
17750 None
17751 }
17752 })?;
17753 pane.update(cx, |pane, cx| {
17754 pane.activate_item(pane_item_index, true, true, window, cx)
17755 });
17756 Some(editor)
17757 })
17758 .flatten()
17759 .unwrap_or_else(|| {
17760 workspace.open_project_item::<Self>(
17761 pane.clone(),
17762 buffer,
17763 true,
17764 true,
17765 window,
17766 cx,
17767 )
17768 });
17769
17770 editor.update(cx, |editor, cx| {
17771 let autoscroll = match scroll_offset {
17772 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17773 None => Autoscroll::newest(),
17774 };
17775 let nav_history = editor.nav_history.take();
17776 editor.change_selections(Some(autoscroll), window, cx, |s| {
17777 s.select_ranges(ranges);
17778 });
17779 editor.nav_history = nav_history;
17780 });
17781 }
17782 })
17783 });
17784 }
17785
17786 // For now, don't allow opening excerpts in buffers that aren't backed by
17787 // regular project files.
17788 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17789 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17790 }
17791
17792 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17793 let snapshot = self.buffer.read(cx).read(cx);
17794 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17795 Some(
17796 ranges
17797 .iter()
17798 .map(move |range| {
17799 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17800 })
17801 .collect(),
17802 )
17803 }
17804
17805 fn selection_replacement_ranges(
17806 &self,
17807 range: Range<OffsetUtf16>,
17808 cx: &mut App,
17809 ) -> Vec<Range<OffsetUtf16>> {
17810 let selections = self.selections.all::<OffsetUtf16>(cx);
17811 let newest_selection = selections
17812 .iter()
17813 .max_by_key(|selection| selection.id)
17814 .unwrap();
17815 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17816 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17817 let snapshot = self.buffer.read(cx).read(cx);
17818 selections
17819 .into_iter()
17820 .map(|mut selection| {
17821 selection.start.0 =
17822 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17823 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17824 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17825 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17826 })
17827 .collect()
17828 }
17829
17830 fn report_editor_event(
17831 &self,
17832 event_type: &'static str,
17833 file_extension: Option<String>,
17834 cx: &App,
17835 ) {
17836 if cfg!(any(test, feature = "test-support")) {
17837 return;
17838 }
17839
17840 let Some(project) = &self.project else { return };
17841
17842 // If None, we are in a file without an extension
17843 let file = self
17844 .buffer
17845 .read(cx)
17846 .as_singleton()
17847 .and_then(|b| b.read(cx).file());
17848 let file_extension = file_extension.or(file
17849 .as_ref()
17850 .and_then(|file| Path::new(file.file_name(cx)).extension())
17851 .and_then(|e| e.to_str())
17852 .map(|a| a.to_string()));
17853
17854 let vim_mode = vim_enabled(cx);
17855
17856 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17857 let copilot_enabled = edit_predictions_provider
17858 == language::language_settings::EditPredictionProvider::Copilot;
17859 let copilot_enabled_for_language = self
17860 .buffer
17861 .read(cx)
17862 .language_settings(cx)
17863 .show_edit_predictions;
17864
17865 let project = project.read(cx);
17866 telemetry::event!(
17867 event_type,
17868 file_extension,
17869 vim_mode,
17870 copilot_enabled,
17871 copilot_enabled_for_language,
17872 edit_predictions_provider,
17873 is_via_ssh = project.is_via_ssh(),
17874 );
17875 }
17876
17877 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17878 /// with each line being an array of {text, highlight} objects.
17879 fn copy_highlight_json(
17880 &mut self,
17881 _: &CopyHighlightJson,
17882 window: &mut Window,
17883 cx: &mut Context<Self>,
17884 ) {
17885 #[derive(Serialize)]
17886 struct Chunk<'a> {
17887 text: String,
17888 highlight: Option<&'a str>,
17889 }
17890
17891 let snapshot = self.buffer.read(cx).snapshot(cx);
17892 let range = self
17893 .selected_text_range(false, window, cx)
17894 .and_then(|selection| {
17895 if selection.range.is_empty() {
17896 None
17897 } else {
17898 Some(selection.range)
17899 }
17900 })
17901 .unwrap_or_else(|| 0..snapshot.len());
17902
17903 let chunks = snapshot.chunks(range, true);
17904 let mut lines = Vec::new();
17905 let mut line: VecDeque<Chunk> = VecDeque::new();
17906
17907 let Some(style) = self.style.as_ref() else {
17908 return;
17909 };
17910
17911 for chunk in chunks {
17912 let highlight = chunk
17913 .syntax_highlight_id
17914 .and_then(|id| id.name(&style.syntax));
17915 let mut chunk_lines = chunk.text.split('\n').peekable();
17916 while let Some(text) = chunk_lines.next() {
17917 let mut merged_with_last_token = false;
17918 if let Some(last_token) = line.back_mut() {
17919 if last_token.highlight == highlight {
17920 last_token.text.push_str(text);
17921 merged_with_last_token = true;
17922 }
17923 }
17924
17925 if !merged_with_last_token {
17926 line.push_back(Chunk {
17927 text: text.into(),
17928 highlight,
17929 });
17930 }
17931
17932 if chunk_lines.peek().is_some() {
17933 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17934 line.pop_front();
17935 }
17936 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17937 line.pop_back();
17938 }
17939
17940 lines.push(mem::take(&mut line));
17941 }
17942 }
17943 }
17944
17945 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17946 return;
17947 };
17948 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17949 }
17950
17951 pub fn open_context_menu(
17952 &mut self,
17953 _: &OpenContextMenu,
17954 window: &mut Window,
17955 cx: &mut Context<Self>,
17956 ) {
17957 self.request_autoscroll(Autoscroll::newest(), cx);
17958 let position = self.selections.newest_display(cx).start;
17959 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17960 }
17961
17962 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17963 &self.inlay_hint_cache
17964 }
17965
17966 pub fn replay_insert_event(
17967 &mut self,
17968 text: &str,
17969 relative_utf16_range: Option<Range<isize>>,
17970 window: &mut Window,
17971 cx: &mut Context<Self>,
17972 ) {
17973 if !self.input_enabled {
17974 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17975 return;
17976 }
17977 if let Some(relative_utf16_range) = relative_utf16_range {
17978 let selections = self.selections.all::<OffsetUtf16>(cx);
17979 self.change_selections(None, window, cx, |s| {
17980 let new_ranges = selections.into_iter().map(|range| {
17981 let start = OffsetUtf16(
17982 range
17983 .head()
17984 .0
17985 .saturating_add_signed(relative_utf16_range.start),
17986 );
17987 let end = OffsetUtf16(
17988 range
17989 .head()
17990 .0
17991 .saturating_add_signed(relative_utf16_range.end),
17992 );
17993 start..end
17994 });
17995 s.select_ranges(new_ranges);
17996 });
17997 }
17998
17999 self.handle_input(text, window, cx);
18000 }
18001
18002 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18003 let Some(provider) = self.semantics_provider.as_ref() else {
18004 return false;
18005 };
18006
18007 let mut supports = false;
18008 self.buffer().update(cx, |this, cx| {
18009 this.for_each_buffer(|buffer| {
18010 supports |= provider.supports_inlay_hints(buffer, cx);
18011 });
18012 });
18013
18014 supports
18015 }
18016
18017 pub fn is_focused(&self, window: &Window) -> bool {
18018 self.focus_handle.is_focused(window)
18019 }
18020
18021 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18022 cx.emit(EditorEvent::Focused);
18023
18024 if let Some(descendant) = self
18025 .last_focused_descendant
18026 .take()
18027 .and_then(|descendant| descendant.upgrade())
18028 {
18029 window.focus(&descendant);
18030 } else {
18031 if let Some(blame) = self.blame.as_ref() {
18032 blame.update(cx, GitBlame::focus)
18033 }
18034
18035 self.blink_manager.update(cx, BlinkManager::enable);
18036 self.show_cursor_names(window, cx);
18037 self.buffer.update(cx, |buffer, cx| {
18038 buffer.finalize_last_transaction(cx);
18039 if self.leader_peer_id.is_none() {
18040 buffer.set_active_selections(
18041 &self.selections.disjoint_anchors(),
18042 self.selections.line_mode,
18043 self.cursor_shape,
18044 cx,
18045 );
18046 }
18047 });
18048 }
18049 }
18050
18051 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18052 cx.emit(EditorEvent::FocusedIn)
18053 }
18054
18055 fn handle_focus_out(
18056 &mut self,
18057 event: FocusOutEvent,
18058 _window: &mut Window,
18059 cx: &mut Context<Self>,
18060 ) {
18061 if event.blurred != self.focus_handle {
18062 self.last_focused_descendant = Some(event.blurred);
18063 }
18064 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18065 }
18066
18067 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18068 self.blink_manager.update(cx, BlinkManager::disable);
18069 self.buffer
18070 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18071
18072 if let Some(blame) = self.blame.as_ref() {
18073 blame.update(cx, GitBlame::blur)
18074 }
18075 if !self.hover_state.focused(window, cx) {
18076 hide_hover(self, cx);
18077 }
18078 if !self
18079 .context_menu
18080 .borrow()
18081 .as_ref()
18082 .is_some_and(|context_menu| context_menu.focused(window, cx))
18083 {
18084 self.hide_context_menu(window, cx);
18085 }
18086 self.discard_inline_completion(false, cx);
18087 cx.emit(EditorEvent::Blurred);
18088 cx.notify();
18089 }
18090
18091 pub fn register_action<A: Action>(
18092 &mut self,
18093 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18094 ) -> Subscription {
18095 let id = self.next_editor_action_id.post_inc();
18096 let listener = Arc::new(listener);
18097 self.editor_actions.borrow_mut().insert(
18098 id,
18099 Box::new(move |window, _| {
18100 let listener = listener.clone();
18101 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18102 let action = action.downcast_ref().unwrap();
18103 if phase == DispatchPhase::Bubble {
18104 listener(action, window, cx)
18105 }
18106 })
18107 }),
18108 );
18109
18110 let editor_actions = self.editor_actions.clone();
18111 Subscription::new(move || {
18112 editor_actions.borrow_mut().remove(&id);
18113 })
18114 }
18115
18116 pub fn file_header_size(&self) -> u32 {
18117 FILE_HEADER_HEIGHT
18118 }
18119
18120 pub fn restore(
18121 &mut self,
18122 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18123 window: &mut Window,
18124 cx: &mut Context<Self>,
18125 ) {
18126 let workspace = self.workspace();
18127 let project = self.project.as_ref();
18128 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18129 let mut tasks = Vec::new();
18130 for (buffer_id, changes) in revert_changes {
18131 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18132 buffer.update(cx, |buffer, cx| {
18133 buffer.edit(
18134 changes
18135 .into_iter()
18136 .map(|(range, text)| (range, text.to_string())),
18137 None,
18138 cx,
18139 );
18140 });
18141
18142 if let Some(project) =
18143 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18144 {
18145 project.update(cx, |project, cx| {
18146 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18147 })
18148 }
18149 }
18150 }
18151 tasks
18152 });
18153 cx.spawn_in(window, async move |_, cx| {
18154 for (buffer, task) in save_tasks {
18155 let result = task.await;
18156 if result.is_err() {
18157 let Some(path) = buffer
18158 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18159 .ok()
18160 else {
18161 continue;
18162 };
18163 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18164 let Some(task) = cx
18165 .update_window_entity(&workspace, |workspace, window, cx| {
18166 workspace
18167 .open_path_preview(path, None, false, false, false, window, cx)
18168 })
18169 .ok()
18170 else {
18171 continue;
18172 };
18173 task.await.log_err();
18174 }
18175 }
18176 }
18177 })
18178 .detach();
18179 self.change_selections(None, window, cx, |selections| selections.refresh());
18180 }
18181
18182 pub fn to_pixel_point(
18183 &self,
18184 source: multi_buffer::Anchor,
18185 editor_snapshot: &EditorSnapshot,
18186 window: &mut Window,
18187 ) -> Option<gpui::Point<Pixels>> {
18188 let source_point = source.to_display_point(editor_snapshot);
18189 self.display_to_pixel_point(source_point, editor_snapshot, window)
18190 }
18191
18192 pub fn display_to_pixel_point(
18193 &self,
18194 source: DisplayPoint,
18195 editor_snapshot: &EditorSnapshot,
18196 window: &mut Window,
18197 ) -> Option<gpui::Point<Pixels>> {
18198 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18199 let text_layout_details = self.text_layout_details(window);
18200 let scroll_top = text_layout_details
18201 .scroll_anchor
18202 .scroll_position(editor_snapshot)
18203 .y;
18204
18205 if source.row().as_f32() < scroll_top.floor() {
18206 return None;
18207 }
18208 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18209 let source_y = line_height * (source.row().as_f32() - scroll_top);
18210 Some(gpui::Point::new(source_x, source_y))
18211 }
18212
18213 pub fn has_visible_completions_menu(&self) -> bool {
18214 !self.edit_prediction_preview_is_active()
18215 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18216 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18217 })
18218 }
18219
18220 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18221 self.addons
18222 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18223 }
18224
18225 pub fn unregister_addon<T: Addon>(&mut self) {
18226 self.addons.remove(&std::any::TypeId::of::<T>());
18227 }
18228
18229 pub fn addon<T: Addon>(&self) -> Option<&T> {
18230 let type_id = std::any::TypeId::of::<T>();
18231 self.addons
18232 .get(&type_id)
18233 .and_then(|item| item.to_any().downcast_ref::<T>())
18234 }
18235
18236 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18237 let text_layout_details = self.text_layout_details(window);
18238 let style = &text_layout_details.editor_style;
18239 let font_id = window.text_system().resolve_font(&style.text.font());
18240 let font_size = style.text.font_size.to_pixels(window.rem_size());
18241 let line_height = style.text.line_height_in_pixels(window.rem_size());
18242 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18243
18244 gpui::Size::new(em_width, line_height)
18245 }
18246
18247 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18248 self.load_diff_task.clone()
18249 }
18250
18251 fn read_metadata_from_db(
18252 &mut self,
18253 item_id: u64,
18254 workspace_id: WorkspaceId,
18255 window: &mut Window,
18256 cx: &mut Context<Editor>,
18257 ) {
18258 if self.is_singleton(cx)
18259 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18260 {
18261 let buffer_snapshot = OnceCell::new();
18262
18263 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18264 if !folds.is_empty() {
18265 let snapshot =
18266 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18267 self.fold_ranges(
18268 folds
18269 .into_iter()
18270 .map(|(start, end)| {
18271 snapshot.clip_offset(start, Bias::Left)
18272 ..snapshot.clip_offset(end, Bias::Right)
18273 })
18274 .collect(),
18275 false,
18276 window,
18277 cx,
18278 );
18279 }
18280 }
18281
18282 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18283 if !selections.is_empty() {
18284 let snapshot =
18285 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18286 self.change_selections(None, window, cx, |s| {
18287 s.select_ranges(selections.into_iter().map(|(start, end)| {
18288 snapshot.clip_offset(start, Bias::Left)
18289 ..snapshot.clip_offset(end, Bias::Right)
18290 }));
18291 });
18292 }
18293 };
18294 }
18295
18296 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18297 }
18298}
18299
18300fn vim_enabled(cx: &App) -> bool {
18301 cx.global::<SettingsStore>()
18302 .raw_user_settings()
18303 .get("vim_mode")
18304 == Some(&serde_json::Value::Bool(true))
18305}
18306
18307// Consider user intent and default settings
18308fn choose_completion_range(
18309 completion: &Completion,
18310 intent: CompletionIntent,
18311 buffer: &Entity<Buffer>,
18312 cx: &mut Context<Editor>,
18313) -> Range<usize> {
18314 fn should_replace(
18315 completion: &Completion,
18316 insert_range: &Range<text::Anchor>,
18317 intent: CompletionIntent,
18318 completion_mode_setting: LspInsertMode,
18319 buffer: &Buffer,
18320 ) -> bool {
18321 // specific actions take precedence over settings
18322 match intent {
18323 CompletionIntent::CompleteWithInsert => return false,
18324 CompletionIntent::CompleteWithReplace => return true,
18325 CompletionIntent::Complete | CompletionIntent::Compose => {}
18326 }
18327
18328 match completion_mode_setting {
18329 LspInsertMode::Insert => false,
18330 LspInsertMode::Replace => true,
18331 LspInsertMode::ReplaceSubsequence => {
18332 let mut text_to_replace = buffer.chars_for_range(
18333 buffer.anchor_before(completion.replace_range.start)
18334 ..buffer.anchor_after(completion.replace_range.end),
18335 );
18336 let mut completion_text = completion.new_text.chars();
18337
18338 // is `text_to_replace` a subsequence of `completion_text`
18339 text_to_replace
18340 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18341 }
18342 LspInsertMode::ReplaceSuffix => {
18343 let range_after_cursor = insert_range.end..completion.replace_range.end;
18344
18345 let text_after_cursor = buffer
18346 .text_for_range(
18347 buffer.anchor_before(range_after_cursor.start)
18348 ..buffer.anchor_after(range_after_cursor.end),
18349 )
18350 .collect::<String>();
18351 completion.new_text.ends_with(&text_after_cursor)
18352 }
18353 }
18354 }
18355
18356 let buffer = buffer.read(cx);
18357
18358 if let CompletionSource::Lsp {
18359 insert_range: Some(insert_range),
18360 ..
18361 } = &completion.source
18362 {
18363 let completion_mode_setting =
18364 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18365 .completions
18366 .lsp_insert_mode;
18367
18368 if !should_replace(
18369 completion,
18370 &insert_range,
18371 intent,
18372 completion_mode_setting,
18373 buffer,
18374 ) {
18375 return insert_range.to_offset(buffer);
18376 }
18377 }
18378
18379 completion.replace_range.to_offset(buffer)
18380}
18381
18382fn insert_extra_newline_brackets(
18383 buffer: &MultiBufferSnapshot,
18384 range: Range<usize>,
18385 language: &language::LanguageScope,
18386) -> bool {
18387 let leading_whitespace_len = buffer
18388 .reversed_chars_at(range.start)
18389 .take_while(|c| c.is_whitespace() && *c != '\n')
18390 .map(|c| c.len_utf8())
18391 .sum::<usize>();
18392 let trailing_whitespace_len = buffer
18393 .chars_at(range.end)
18394 .take_while(|c| c.is_whitespace() && *c != '\n')
18395 .map(|c| c.len_utf8())
18396 .sum::<usize>();
18397 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18398
18399 language.brackets().any(|(pair, enabled)| {
18400 let pair_start = pair.start.trim_end();
18401 let pair_end = pair.end.trim_start();
18402
18403 enabled
18404 && pair.newline
18405 && buffer.contains_str_at(range.end, pair_end)
18406 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18407 })
18408}
18409
18410fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18411 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18412 [(buffer, range, _)] => (*buffer, range.clone()),
18413 _ => return false,
18414 };
18415 let pair = {
18416 let mut result: Option<BracketMatch> = None;
18417
18418 for pair in buffer
18419 .all_bracket_ranges(range.clone())
18420 .filter(move |pair| {
18421 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18422 })
18423 {
18424 let len = pair.close_range.end - pair.open_range.start;
18425
18426 if let Some(existing) = &result {
18427 let existing_len = existing.close_range.end - existing.open_range.start;
18428 if len > existing_len {
18429 continue;
18430 }
18431 }
18432
18433 result = Some(pair);
18434 }
18435
18436 result
18437 };
18438 let Some(pair) = pair else {
18439 return false;
18440 };
18441 pair.newline_only
18442 && buffer
18443 .chars_for_range(pair.open_range.end..range.start)
18444 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18445 .all(|c| c.is_whitespace() && c != '\n')
18446}
18447
18448fn get_uncommitted_diff_for_buffer(
18449 project: &Entity<Project>,
18450 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18451 buffer: Entity<MultiBuffer>,
18452 cx: &mut App,
18453) -> Task<()> {
18454 let mut tasks = Vec::new();
18455 project.update(cx, |project, cx| {
18456 for buffer in buffers {
18457 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18458 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18459 }
18460 }
18461 });
18462 cx.spawn(async move |cx| {
18463 let diffs = future::join_all(tasks).await;
18464 buffer
18465 .update(cx, |buffer, cx| {
18466 for diff in diffs.into_iter().flatten() {
18467 buffer.add_diff(diff, cx);
18468 }
18469 })
18470 .ok();
18471 })
18472}
18473
18474fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18475 let tab_size = tab_size.get() as usize;
18476 let mut width = offset;
18477
18478 for ch in text.chars() {
18479 width += if ch == '\t' {
18480 tab_size - (width % tab_size)
18481 } else {
18482 1
18483 };
18484 }
18485
18486 width - offset
18487}
18488
18489#[cfg(test)]
18490mod tests {
18491 use super::*;
18492
18493 #[test]
18494 fn test_string_size_with_expanded_tabs() {
18495 let nz = |val| NonZeroU32::new(val).unwrap();
18496 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18497 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18498 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18499 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18500 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18501 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18502 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18503 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18504 }
18505}
18506
18507/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18508struct WordBreakingTokenizer<'a> {
18509 input: &'a str,
18510}
18511
18512impl<'a> WordBreakingTokenizer<'a> {
18513 fn new(input: &'a str) -> Self {
18514 Self { input }
18515 }
18516}
18517
18518fn is_char_ideographic(ch: char) -> bool {
18519 use unicode_script::Script::*;
18520 use unicode_script::UnicodeScript;
18521 matches!(ch.script(), Han | Tangut | Yi)
18522}
18523
18524fn is_grapheme_ideographic(text: &str) -> bool {
18525 text.chars().any(is_char_ideographic)
18526}
18527
18528fn is_grapheme_whitespace(text: &str) -> bool {
18529 text.chars().any(|x| x.is_whitespace())
18530}
18531
18532fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18533 text.chars().next().map_or(false, |ch| {
18534 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18535 })
18536}
18537
18538#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18539enum WordBreakToken<'a> {
18540 Word { token: &'a str, grapheme_len: usize },
18541 InlineWhitespace { token: &'a str, grapheme_len: usize },
18542 Newline,
18543}
18544
18545impl<'a> Iterator for WordBreakingTokenizer<'a> {
18546 /// Yields a span, the count of graphemes in the token, and whether it was
18547 /// whitespace. Note that it also breaks at word boundaries.
18548 type Item = WordBreakToken<'a>;
18549
18550 fn next(&mut self) -> Option<Self::Item> {
18551 use unicode_segmentation::UnicodeSegmentation;
18552 if self.input.is_empty() {
18553 return None;
18554 }
18555
18556 let mut iter = self.input.graphemes(true).peekable();
18557 let mut offset = 0;
18558 let mut grapheme_len = 0;
18559 if let Some(first_grapheme) = iter.next() {
18560 let is_newline = first_grapheme == "\n";
18561 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18562 offset += first_grapheme.len();
18563 grapheme_len += 1;
18564 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18565 if let Some(grapheme) = iter.peek().copied() {
18566 if should_stay_with_preceding_ideograph(grapheme) {
18567 offset += grapheme.len();
18568 grapheme_len += 1;
18569 }
18570 }
18571 } else {
18572 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18573 let mut next_word_bound = words.peek().copied();
18574 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18575 next_word_bound = words.next();
18576 }
18577 while let Some(grapheme) = iter.peek().copied() {
18578 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18579 break;
18580 };
18581 if is_grapheme_whitespace(grapheme) != is_whitespace
18582 || (grapheme == "\n") != is_newline
18583 {
18584 break;
18585 };
18586 offset += grapheme.len();
18587 grapheme_len += 1;
18588 iter.next();
18589 }
18590 }
18591 let token = &self.input[..offset];
18592 self.input = &self.input[offset..];
18593 if token == "\n" {
18594 Some(WordBreakToken::Newline)
18595 } else if is_whitespace {
18596 Some(WordBreakToken::InlineWhitespace {
18597 token,
18598 grapheme_len,
18599 })
18600 } else {
18601 Some(WordBreakToken::Word {
18602 token,
18603 grapheme_len,
18604 })
18605 }
18606 } else {
18607 None
18608 }
18609 }
18610}
18611
18612#[test]
18613fn test_word_breaking_tokenizer() {
18614 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18615 ("", &[]),
18616 (" ", &[whitespace(" ", 2)]),
18617 ("Ʒ", &[word("Ʒ", 1)]),
18618 ("Ǽ", &[word("Ǽ", 1)]),
18619 ("⋑", &[word("⋑", 1)]),
18620 ("⋑⋑", &[word("⋑⋑", 2)]),
18621 (
18622 "原理,进而",
18623 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18624 ),
18625 (
18626 "hello world",
18627 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18628 ),
18629 (
18630 "hello, world",
18631 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18632 ),
18633 (
18634 " hello world",
18635 &[
18636 whitespace(" ", 2),
18637 word("hello", 5),
18638 whitespace(" ", 1),
18639 word("world", 5),
18640 ],
18641 ),
18642 (
18643 "这是什么 \n 钢笔",
18644 &[
18645 word("这", 1),
18646 word("是", 1),
18647 word("什", 1),
18648 word("么", 1),
18649 whitespace(" ", 1),
18650 newline(),
18651 whitespace(" ", 1),
18652 word("钢", 1),
18653 word("笔", 1),
18654 ],
18655 ),
18656 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18657 ];
18658
18659 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18660 WordBreakToken::Word {
18661 token,
18662 grapheme_len,
18663 }
18664 }
18665
18666 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18667 WordBreakToken::InlineWhitespace {
18668 token,
18669 grapheme_len,
18670 }
18671 }
18672
18673 fn newline() -> WordBreakToken<'static> {
18674 WordBreakToken::Newline
18675 }
18676
18677 for (input, result) in tests {
18678 assert_eq!(
18679 WordBreakingTokenizer::new(input)
18680 .collect::<Vec<_>>()
18681 .as_slice(),
18682 *result,
18683 );
18684 }
18685}
18686
18687fn wrap_with_prefix(
18688 line_prefix: String,
18689 unwrapped_text: String,
18690 wrap_column: usize,
18691 tab_size: NonZeroU32,
18692 preserve_existing_whitespace: bool,
18693) -> String {
18694 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18695 let mut wrapped_text = String::new();
18696 let mut current_line = line_prefix.clone();
18697
18698 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18699 let mut current_line_len = line_prefix_len;
18700 let mut in_whitespace = false;
18701 for token in tokenizer {
18702 let have_preceding_whitespace = in_whitespace;
18703 match token {
18704 WordBreakToken::Word {
18705 token,
18706 grapheme_len,
18707 } => {
18708 in_whitespace = false;
18709 if current_line_len + grapheme_len > wrap_column
18710 && current_line_len != line_prefix_len
18711 {
18712 wrapped_text.push_str(current_line.trim_end());
18713 wrapped_text.push('\n');
18714 current_line.truncate(line_prefix.len());
18715 current_line_len = line_prefix_len;
18716 }
18717 current_line.push_str(token);
18718 current_line_len += grapheme_len;
18719 }
18720 WordBreakToken::InlineWhitespace {
18721 mut token,
18722 mut grapheme_len,
18723 } => {
18724 in_whitespace = true;
18725 if have_preceding_whitespace && !preserve_existing_whitespace {
18726 continue;
18727 }
18728 if !preserve_existing_whitespace {
18729 token = " ";
18730 grapheme_len = 1;
18731 }
18732 if current_line_len + grapheme_len > wrap_column {
18733 wrapped_text.push_str(current_line.trim_end());
18734 wrapped_text.push('\n');
18735 current_line.truncate(line_prefix.len());
18736 current_line_len = line_prefix_len;
18737 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18738 current_line.push_str(token);
18739 current_line_len += grapheme_len;
18740 }
18741 }
18742 WordBreakToken::Newline => {
18743 in_whitespace = true;
18744 if preserve_existing_whitespace {
18745 wrapped_text.push_str(current_line.trim_end());
18746 wrapped_text.push('\n');
18747 current_line.truncate(line_prefix.len());
18748 current_line_len = line_prefix_len;
18749 } else if have_preceding_whitespace {
18750 continue;
18751 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18752 {
18753 wrapped_text.push_str(current_line.trim_end());
18754 wrapped_text.push('\n');
18755 current_line.truncate(line_prefix.len());
18756 current_line_len = line_prefix_len;
18757 } else if current_line_len != line_prefix_len {
18758 current_line.push(' ');
18759 current_line_len += 1;
18760 }
18761 }
18762 }
18763 }
18764
18765 if !current_line.is_empty() {
18766 wrapped_text.push_str(¤t_line);
18767 }
18768 wrapped_text
18769}
18770
18771#[test]
18772fn test_wrap_with_prefix() {
18773 assert_eq!(
18774 wrap_with_prefix(
18775 "# ".to_string(),
18776 "abcdefg".to_string(),
18777 4,
18778 NonZeroU32::new(4).unwrap(),
18779 false,
18780 ),
18781 "# abcdefg"
18782 );
18783 assert_eq!(
18784 wrap_with_prefix(
18785 "".to_string(),
18786 "\thello world".to_string(),
18787 8,
18788 NonZeroU32::new(4).unwrap(),
18789 false,
18790 ),
18791 "hello\nworld"
18792 );
18793 assert_eq!(
18794 wrap_with_prefix(
18795 "// ".to_string(),
18796 "xx \nyy zz aa bb cc".to_string(),
18797 12,
18798 NonZeroU32::new(4).unwrap(),
18799 false,
18800 ),
18801 "// xx yy zz\n// aa bb cc"
18802 );
18803 assert_eq!(
18804 wrap_with_prefix(
18805 String::new(),
18806 "这是什么 \n 钢笔".to_string(),
18807 3,
18808 NonZeroU32::new(4).unwrap(),
18809 false,
18810 ),
18811 "这是什\n么 钢\n笔"
18812 );
18813}
18814
18815pub trait CollaborationHub {
18816 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18817 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18818 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18819}
18820
18821impl CollaborationHub for Entity<Project> {
18822 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18823 self.read(cx).collaborators()
18824 }
18825
18826 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18827 self.read(cx).user_store().read(cx).participant_indices()
18828 }
18829
18830 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18831 let this = self.read(cx);
18832 let user_ids = this.collaborators().values().map(|c| c.user_id);
18833 this.user_store().read_with(cx, |user_store, cx| {
18834 user_store.participant_names(user_ids, cx)
18835 })
18836 }
18837}
18838
18839pub trait SemanticsProvider {
18840 fn hover(
18841 &self,
18842 buffer: &Entity<Buffer>,
18843 position: text::Anchor,
18844 cx: &mut App,
18845 ) -> Option<Task<Vec<project::Hover>>>;
18846
18847 fn inlay_hints(
18848 &self,
18849 buffer_handle: Entity<Buffer>,
18850 range: Range<text::Anchor>,
18851 cx: &mut App,
18852 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18853
18854 fn resolve_inlay_hint(
18855 &self,
18856 hint: InlayHint,
18857 buffer_handle: Entity<Buffer>,
18858 server_id: LanguageServerId,
18859 cx: &mut App,
18860 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18861
18862 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18863
18864 fn document_highlights(
18865 &self,
18866 buffer: &Entity<Buffer>,
18867 position: text::Anchor,
18868 cx: &mut App,
18869 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18870
18871 fn definitions(
18872 &self,
18873 buffer: &Entity<Buffer>,
18874 position: text::Anchor,
18875 kind: GotoDefinitionKind,
18876 cx: &mut App,
18877 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18878
18879 fn range_for_rename(
18880 &self,
18881 buffer: &Entity<Buffer>,
18882 position: text::Anchor,
18883 cx: &mut App,
18884 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18885
18886 fn perform_rename(
18887 &self,
18888 buffer: &Entity<Buffer>,
18889 position: text::Anchor,
18890 new_name: String,
18891 cx: &mut App,
18892 ) -> Option<Task<Result<ProjectTransaction>>>;
18893}
18894
18895pub trait CompletionProvider {
18896 fn completions(
18897 &self,
18898 excerpt_id: ExcerptId,
18899 buffer: &Entity<Buffer>,
18900 buffer_position: text::Anchor,
18901 trigger: CompletionContext,
18902 window: &mut Window,
18903 cx: &mut Context<Editor>,
18904 ) -> Task<Result<Option<Vec<Completion>>>>;
18905
18906 fn resolve_completions(
18907 &self,
18908 buffer: Entity<Buffer>,
18909 completion_indices: Vec<usize>,
18910 completions: Rc<RefCell<Box<[Completion]>>>,
18911 cx: &mut Context<Editor>,
18912 ) -> Task<Result<bool>>;
18913
18914 fn apply_additional_edits_for_completion(
18915 &self,
18916 _buffer: Entity<Buffer>,
18917 _completions: Rc<RefCell<Box<[Completion]>>>,
18918 _completion_index: usize,
18919 _push_to_history: bool,
18920 _cx: &mut Context<Editor>,
18921 ) -> Task<Result<Option<language::Transaction>>> {
18922 Task::ready(Ok(None))
18923 }
18924
18925 fn is_completion_trigger(
18926 &self,
18927 buffer: &Entity<Buffer>,
18928 position: language::Anchor,
18929 text: &str,
18930 trigger_in_words: bool,
18931 cx: &mut Context<Editor>,
18932 ) -> bool;
18933
18934 fn sort_completions(&self) -> bool {
18935 true
18936 }
18937
18938 fn filter_completions(&self) -> bool {
18939 true
18940 }
18941}
18942
18943pub trait CodeActionProvider {
18944 fn id(&self) -> Arc<str>;
18945
18946 fn code_actions(
18947 &self,
18948 buffer: &Entity<Buffer>,
18949 range: Range<text::Anchor>,
18950 window: &mut Window,
18951 cx: &mut App,
18952 ) -> Task<Result<Vec<CodeAction>>>;
18953
18954 fn apply_code_action(
18955 &self,
18956 buffer_handle: Entity<Buffer>,
18957 action: CodeAction,
18958 excerpt_id: ExcerptId,
18959 push_to_history: bool,
18960 window: &mut Window,
18961 cx: &mut App,
18962 ) -> Task<Result<ProjectTransaction>>;
18963}
18964
18965impl CodeActionProvider for Entity<Project> {
18966 fn id(&self) -> Arc<str> {
18967 "project".into()
18968 }
18969
18970 fn code_actions(
18971 &self,
18972 buffer: &Entity<Buffer>,
18973 range: Range<text::Anchor>,
18974 _window: &mut Window,
18975 cx: &mut App,
18976 ) -> Task<Result<Vec<CodeAction>>> {
18977 self.update(cx, |project, cx| {
18978 let code_lens = project.code_lens(buffer, range.clone(), cx);
18979 let code_actions = project.code_actions(buffer, range, None, cx);
18980 cx.background_spawn(async move {
18981 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18982 Ok(code_lens
18983 .context("code lens fetch")?
18984 .into_iter()
18985 .chain(code_actions.context("code action fetch")?)
18986 .collect())
18987 })
18988 })
18989 }
18990
18991 fn apply_code_action(
18992 &self,
18993 buffer_handle: Entity<Buffer>,
18994 action: CodeAction,
18995 _excerpt_id: ExcerptId,
18996 push_to_history: bool,
18997 _window: &mut Window,
18998 cx: &mut App,
18999 ) -> Task<Result<ProjectTransaction>> {
19000 self.update(cx, |project, cx| {
19001 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19002 })
19003 }
19004}
19005
19006fn snippet_completions(
19007 project: &Project,
19008 buffer: &Entity<Buffer>,
19009 buffer_position: text::Anchor,
19010 cx: &mut App,
19011) -> Task<Result<Vec<Completion>>> {
19012 let languages = buffer.read(cx).languages_at(buffer_position);
19013 let snippet_store = project.snippets().read(cx);
19014
19015 let scopes: Vec<_> = languages
19016 .iter()
19017 .filter_map(|language| {
19018 let language_name = language.lsp_id();
19019 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19020
19021 if snippets.is_empty() {
19022 None
19023 } else {
19024 Some((language.default_scope(), snippets))
19025 }
19026 })
19027 .collect();
19028
19029 if scopes.is_empty() {
19030 return Task::ready(Ok(vec![]));
19031 }
19032
19033 let snapshot = buffer.read(cx).text_snapshot();
19034 let chars: String = snapshot
19035 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19036 .collect();
19037 let executor = cx.background_executor().clone();
19038
19039 cx.background_spawn(async move {
19040 let mut all_results: Vec<Completion> = Vec::new();
19041 for (scope, snippets) in scopes.into_iter() {
19042 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19043 let mut last_word = chars
19044 .chars()
19045 .take_while(|c| classifier.is_word(*c))
19046 .collect::<String>();
19047 last_word = last_word.chars().rev().collect();
19048
19049 if last_word.is_empty() {
19050 return Ok(vec![]);
19051 }
19052
19053 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19054 let to_lsp = |point: &text::Anchor| {
19055 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19056 point_to_lsp(end)
19057 };
19058 let lsp_end = to_lsp(&buffer_position);
19059
19060 let candidates = snippets
19061 .iter()
19062 .enumerate()
19063 .flat_map(|(ix, snippet)| {
19064 snippet
19065 .prefix
19066 .iter()
19067 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19068 })
19069 .collect::<Vec<StringMatchCandidate>>();
19070
19071 let mut matches = fuzzy::match_strings(
19072 &candidates,
19073 &last_word,
19074 last_word.chars().any(|c| c.is_uppercase()),
19075 100,
19076 &Default::default(),
19077 executor.clone(),
19078 )
19079 .await;
19080
19081 // Remove all candidates where the query's start does not match the start of any word in the candidate
19082 if let Some(query_start) = last_word.chars().next() {
19083 matches.retain(|string_match| {
19084 split_words(&string_match.string).any(|word| {
19085 // Check that the first codepoint of the word as lowercase matches the first
19086 // codepoint of the query as lowercase
19087 word.chars()
19088 .flat_map(|codepoint| codepoint.to_lowercase())
19089 .zip(query_start.to_lowercase())
19090 .all(|(word_cp, query_cp)| word_cp == query_cp)
19091 })
19092 });
19093 }
19094
19095 let matched_strings = matches
19096 .into_iter()
19097 .map(|m| m.string)
19098 .collect::<HashSet<_>>();
19099
19100 let mut result: Vec<Completion> = snippets
19101 .iter()
19102 .filter_map(|snippet| {
19103 let matching_prefix = snippet
19104 .prefix
19105 .iter()
19106 .find(|prefix| matched_strings.contains(*prefix))?;
19107 let start = as_offset - last_word.len();
19108 let start = snapshot.anchor_before(start);
19109 let range = start..buffer_position;
19110 let lsp_start = to_lsp(&start);
19111 let lsp_range = lsp::Range {
19112 start: lsp_start,
19113 end: lsp_end,
19114 };
19115 Some(Completion {
19116 replace_range: range,
19117 new_text: snippet.body.clone(),
19118 source: CompletionSource::Lsp {
19119 insert_range: None,
19120 server_id: LanguageServerId(usize::MAX),
19121 resolved: true,
19122 lsp_completion: Box::new(lsp::CompletionItem {
19123 label: snippet.prefix.first().unwrap().clone(),
19124 kind: Some(CompletionItemKind::SNIPPET),
19125 label_details: snippet.description.as_ref().map(|description| {
19126 lsp::CompletionItemLabelDetails {
19127 detail: Some(description.clone()),
19128 description: None,
19129 }
19130 }),
19131 insert_text_format: Some(InsertTextFormat::SNIPPET),
19132 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19133 lsp::InsertReplaceEdit {
19134 new_text: snippet.body.clone(),
19135 insert: lsp_range,
19136 replace: lsp_range,
19137 },
19138 )),
19139 filter_text: Some(snippet.body.clone()),
19140 sort_text: Some(char::MAX.to_string()),
19141 ..lsp::CompletionItem::default()
19142 }),
19143 lsp_defaults: None,
19144 },
19145 label: CodeLabel {
19146 text: matching_prefix.clone(),
19147 runs: Vec::new(),
19148 filter_range: 0..matching_prefix.len(),
19149 },
19150 icon_path: None,
19151 documentation: snippet.description.clone().map(|description| {
19152 CompletionDocumentation::SingleLine(description.into())
19153 }),
19154 insert_text_mode: None,
19155 confirm: None,
19156 })
19157 })
19158 .collect();
19159
19160 all_results.append(&mut result);
19161 }
19162
19163 Ok(all_results)
19164 })
19165}
19166
19167impl CompletionProvider for Entity<Project> {
19168 fn completions(
19169 &self,
19170 _excerpt_id: ExcerptId,
19171 buffer: &Entity<Buffer>,
19172 buffer_position: text::Anchor,
19173 options: CompletionContext,
19174 _window: &mut Window,
19175 cx: &mut Context<Editor>,
19176 ) -> Task<Result<Option<Vec<Completion>>>> {
19177 self.update(cx, |project, cx| {
19178 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19179 let project_completions = project.completions(buffer, buffer_position, options, cx);
19180 cx.background_spawn(async move {
19181 let snippets_completions = snippets.await?;
19182 match project_completions.await? {
19183 Some(mut completions) => {
19184 completions.extend(snippets_completions);
19185 Ok(Some(completions))
19186 }
19187 None => {
19188 if snippets_completions.is_empty() {
19189 Ok(None)
19190 } else {
19191 Ok(Some(snippets_completions))
19192 }
19193 }
19194 }
19195 })
19196 })
19197 }
19198
19199 fn resolve_completions(
19200 &self,
19201 buffer: Entity<Buffer>,
19202 completion_indices: Vec<usize>,
19203 completions: Rc<RefCell<Box<[Completion]>>>,
19204 cx: &mut Context<Editor>,
19205 ) -> Task<Result<bool>> {
19206 self.update(cx, |project, cx| {
19207 project.lsp_store().update(cx, |lsp_store, cx| {
19208 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19209 })
19210 })
19211 }
19212
19213 fn apply_additional_edits_for_completion(
19214 &self,
19215 buffer: Entity<Buffer>,
19216 completions: Rc<RefCell<Box<[Completion]>>>,
19217 completion_index: usize,
19218 push_to_history: bool,
19219 cx: &mut Context<Editor>,
19220 ) -> Task<Result<Option<language::Transaction>>> {
19221 self.update(cx, |project, cx| {
19222 project.lsp_store().update(cx, |lsp_store, cx| {
19223 lsp_store.apply_additional_edits_for_completion(
19224 buffer,
19225 completions,
19226 completion_index,
19227 push_to_history,
19228 cx,
19229 )
19230 })
19231 })
19232 }
19233
19234 fn is_completion_trigger(
19235 &self,
19236 buffer: &Entity<Buffer>,
19237 position: language::Anchor,
19238 text: &str,
19239 trigger_in_words: bool,
19240 cx: &mut Context<Editor>,
19241 ) -> bool {
19242 let mut chars = text.chars();
19243 let char = if let Some(char) = chars.next() {
19244 char
19245 } else {
19246 return false;
19247 };
19248 if chars.next().is_some() {
19249 return false;
19250 }
19251
19252 let buffer = buffer.read(cx);
19253 let snapshot = buffer.snapshot();
19254 if !snapshot.settings_at(position, cx).show_completions_on_input {
19255 return false;
19256 }
19257 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19258 if trigger_in_words && classifier.is_word(char) {
19259 return true;
19260 }
19261
19262 buffer.completion_triggers().contains(text)
19263 }
19264}
19265
19266impl SemanticsProvider for Entity<Project> {
19267 fn hover(
19268 &self,
19269 buffer: &Entity<Buffer>,
19270 position: text::Anchor,
19271 cx: &mut App,
19272 ) -> Option<Task<Vec<project::Hover>>> {
19273 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19274 }
19275
19276 fn document_highlights(
19277 &self,
19278 buffer: &Entity<Buffer>,
19279 position: text::Anchor,
19280 cx: &mut App,
19281 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19282 Some(self.update(cx, |project, cx| {
19283 project.document_highlights(buffer, position, cx)
19284 }))
19285 }
19286
19287 fn definitions(
19288 &self,
19289 buffer: &Entity<Buffer>,
19290 position: text::Anchor,
19291 kind: GotoDefinitionKind,
19292 cx: &mut App,
19293 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19294 Some(self.update(cx, |project, cx| match kind {
19295 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19296 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19297 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19298 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19299 }))
19300 }
19301
19302 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19303 // TODO: make this work for remote projects
19304 self.update(cx, |this, cx| {
19305 buffer.update(cx, |buffer, cx| {
19306 this.any_language_server_supports_inlay_hints(buffer, cx)
19307 })
19308 })
19309 }
19310
19311 fn inlay_hints(
19312 &self,
19313 buffer_handle: Entity<Buffer>,
19314 range: Range<text::Anchor>,
19315 cx: &mut App,
19316 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19317 Some(self.update(cx, |project, cx| {
19318 project.inlay_hints(buffer_handle, range, cx)
19319 }))
19320 }
19321
19322 fn resolve_inlay_hint(
19323 &self,
19324 hint: InlayHint,
19325 buffer_handle: Entity<Buffer>,
19326 server_id: LanguageServerId,
19327 cx: &mut App,
19328 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19329 Some(self.update(cx, |project, cx| {
19330 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19331 }))
19332 }
19333
19334 fn range_for_rename(
19335 &self,
19336 buffer: &Entity<Buffer>,
19337 position: text::Anchor,
19338 cx: &mut App,
19339 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19340 Some(self.update(cx, |project, cx| {
19341 let buffer = buffer.clone();
19342 let task = project.prepare_rename(buffer.clone(), position, cx);
19343 cx.spawn(async move |_, cx| {
19344 Ok(match task.await? {
19345 PrepareRenameResponse::Success(range) => Some(range),
19346 PrepareRenameResponse::InvalidPosition => None,
19347 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19348 // Fallback on using TreeSitter info to determine identifier range
19349 buffer.update(cx, |buffer, _| {
19350 let snapshot = buffer.snapshot();
19351 let (range, kind) = snapshot.surrounding_word(position);
19352 if kind != Some(CharKind::Word) {
19353 return None;
19354 }
19355 Some(
19356 snapshot.anchor_before(range.start)
19357 ..snapshot.anchor_after(range.end),
19358 )
19359 })?
19360 }
19361 })
19362 })
19363 }))
19364 }
19365
19366 fn perform_rename(
19367 &self,
19368 buffer: &Entity<Buffer>,
19369 position: text::Anchor,
19370 new_name: String,
19371 cx: &mut App,
19372 ) -> Option<Task<Result<ProjectTransaction>>> {
19373 Some(self.update(cx, |project, cx| {
19374 project.perform_rename(buffer.clone(), position, new_name, cx)
19375 }))
19376 }
19377}
19378
19379fn inlay_hint_settings(
19380 location: Anchor,
19381 snapshot: &MultiBufferSnapshot,
19382 cx: &mut Context<Editor>,
19383) -> InlayHintSettings {
19384 let file = snapshot.file_at(location);
19385 let language = snapshot.language_at(location).map(|l| l.name());
19386 language_settings(language, file, cx).inlay_hints
19387}
19388
19389fn consume_contiguous_rows(
19390 contiguous_row_selections: &mut Vec<Selection<Point>>,
19391 selection: &Selection<Point>,
19392 display_map: &DisplaySnapshot,
19393 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19394) -> (MultiBufferRow, MultiBufferRow) {
19395 contiguous_row_selections.push(selection.clone());
19396 let start_row = MultiBufferRow(selection.start.row);
19397 let mut end_row = ending_row(selection, display_map);
19398
19399 while let Some(next_selection) = selections.peek() {
19400 if next_selection.start.row <= end_row.0 {
19401 end_row = ending_row(next_selection, display_map);
19402 contiguous_row_selections.push(selections.next().unwrap().clone());
19403 } else {
19404 break;
19405 }
19406 }
19407 (start_row, end_row)
19408}
19409
19410fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19411 if next_selection.end.column > 0 || next_selection.is_empty() {
19412 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19413 } else {
19414 MultiBufferRow(next_selection.end.row)
19415 }
19416}
19417
19418impl EditorSnapshot {
19419 pub fn remote_selections_in_range<'a>(
19420 &'a self,
19421 range: &'a Range<Anchor>,
19422 collaboration_hub: &dyn CollaborationHub,
19423 cx: &'a App,
19424 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19425 let participant_names = collaboration_hub.user_names(cx);
19426 let participant_indices = collaboration_hub.user_participant_indices(cx);
19427 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19428 let collaborators_by_replica_id = collaborators_by_peer_id
19429 .iter()
19430 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19431 .collect::<HashMap<_, _>>();
19432 self.buffer_snapshot
19433 .selections_in_range(range, false)
19434 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19435 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19436 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19437 let user_name = participant_names.get(&collaborator.user_id).cloned();
19438 Some(RemoteSelection {
19439 replica_id,
19440 selection,
19441 cursor_shape,
19442 line_mode,
19443 participant_index,
19444 peer_id: collaborator.peer_id,
19445 user_name,
19446 })
19447 })
19448 }
19449
19450 pub fn hunks_for_ranges(
19451 &self,
19452 ranges: impl IntoIterator<Item = Range<Point>>,
19453 ) -> Vec<MultiBufferDiffHunk> {
19454 let mut hunks = Vec::new();
19455 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19456 HashMap::default();
19457 for query_range in ranges {
19458 let query_rows =
19459 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19460 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19461 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19462 ) {
19463 // Include deleted hunks that are adjacent to the query range, because
19464 // otherwise they would be missed.
19465 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19466 if hunk.status().is_deleted() {
19467 intersects_range |= hunk.row_range.start == query_rows.end;
19468 intersects_range |= hunk.row_range.end == query_rows.start;
19469 }
19470 if intersects_range {
19471 if !processed_buffer_rows
19472 .entry(hunk.buffer_id)
19473 .or_default()
19474 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19475 {
19476 continue;
19477 }
19478 hunks.push(hunk);
19479 }
19480 }
19481 }
19482
19483 hunks
19484 }
19485
19486 fn display_diff_hunks_for_rows<'a>(
19487 &'a self,
19488 display_rows: Range<DisplayRow>,
19489 folded_buffers: &'a HashSet<BufferId>,
19490 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19491 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19492 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19493
19494 self.buffer_snapshot
19495 .diff_hunks_in_range(buffer_start..buffer_end)
19496 .filter_map(|hunk| {
19497 if folded_buffers.contains(&hunk.buffer_id) {
19498 return None;
19499 }
19500
19501 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19502 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19503
19504 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19505 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19506
19507 let display_hunk = if hunk_display_start.column() != 0 {
19508 DisplayDiffHunk::Folded {
19509 display_row: hunk_display_start.row(),
19510 }
19511 } else {
19512 let mut end_row = hunk_display_end.row();
19513 if hunk_display_end.column() > 0 {
19514 end_row.0 += 1;
19515 }
19516 let is_created_file = hunk.is_created_file();
19517 DisplayDiffHunk::Unfolded {
19518 status: hunk.status(),
19519 diff_base_byte_range: hunk.diff_base_byte_range,
19520 display_row_range: hunk_display_start.row()..end_row,
19521 multi_buffer_range: Anchor::range_in_buffer(
19522 hunk.excerpt_id,
19523 hunk.buffer_id,
19524 hunk.buffer_range,
19525 ),
19526 is_created_file,
19527 }
19528 };
19529
19530 Some(display_hunk)
19531 })
19532 }
19533
19534 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19535 self.display_snapshot.buffer_snapshot.language_at(position)
19536 }
19537
19538 pub fn is_focused(&self) -> bool {
19539 self.is_focused
19540 }
19541
19542 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19543 self.placeholder_text.as_ref()
19544 }
19545
19546 pub fn scroll_position(&self) -> gpui::Point<f32> {
19547 self.scroll_anchor.scroll_position(&self.display_snapshot)
19548 }
19549
19550 fn gutter_dimensions(
19551 &self,
19552 font_id: FontId,
19553 font_size: Pixels,
19554 max_line_number_width: Pixels,
19555 cx: &App,
19556 ) -> Option<GutterDimensions> {
19557 if !self.show_gutter {
19558 return None;
19559 }
19560
19561 let descent = cx.text_system().descent(font_id, font_size);
19562 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19563 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19564
19565 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19566 matches!(
19567 ProjectSettings::get_global(cx).git.git_gutter,
19568 Some(GitGutterSetting::TrackedFiles)
19569 )
19570 });
19571 let gutter_settings = EditorSettings::get_global(cx).gutter;
19572 let show_line_numbers = self
19573 .show_line_numbers
19574 .unwrap_or(gutter_settings.line_numbers);
19575 let line_gutter_width = if show_line_numbers {
19576 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19577 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19578 max_line_number_width.max(min_width_for_number_on_gutter)
19579 } else {
19580 0.0.into()
19581 };
19582
19583 let show_code_actions = self
19584 .show_code_actions
19585 .unwrap_or(gutter_settings.code_actions);
19586
19587 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19588 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19589
19590 let git_blame_entries_width =
19591 self.git_blame_gutter_max_author_length
19592 .map(|max_author_length| {
19593 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19594 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19595
19596 /// The number of characters to dedicate to gaps and margins.
19597 const SPACING_WIDTH: usize = 4;
19598
19599 let max_char_count = max_author_length.min(renderer.max_author_length())
19600 + ::git::SHORT_SHA_LENGTH
19601 + MAX_RELATIVE_TIMESTAMP.len()
19602 + SPACING_WIDTH;
19603
19604 em_advance * max_char_count
19605 });
19606
19607 let is_singleton = self.buffer_snapshot.is_singleton();
19608
19609 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19610 left_padding += if !is_singleton {
19611 em_width * 4.0
19612 } else if show_code_actions || show_runnables || show_breakpoints {
19613 em_width * 3.0
19614 } else if show_git_gutter && show_line_numbers {
19615 em_width * 2.0
19616 } else if show_git_gutter || show_line_numbers {
19617 em_width
19618 } else {
19619 px(0.)
19620 };
19621
19622 let shows_folds = is_singleton && gutter_settings.folds;
19623
19624 let right_padding = if shows_folds && show_line_numbers {
19625 em_width * 4.0
19626 } else if shows_folds || (!is_singleton && show_line_numbers) {
19627 em_width * 3.0
19628 } else if show_line_numbers {
19629 em_width
19630 } else {
19631 px(0.)
19632 };
19633
19634 Some(GutterDimensions {
19635 left_padding,
19636 right_padding,
19637 width: line_gutter_width + left_padding + right_padding,
19638 margin: -descent,
19639 git_blame_entries_width,
19640 })
19641 }
19642
19643 pub fn render_crease_toggle(
19644 &self,
19645 buffer_row: MultiBufferRow,
19646 row_contains_cursor: bool,
19647 editor: Entity<Editor>,
19648 window: &mut Window,
19649 cx: &mut App,
19650 ) -> Option<AnyElement> {
19651 let folded = self.is_line_folded(buffer_row);
19652 let mut is_foldable = false;
19653
19654 if let Some(crease) = self
19655 .crease_snapshot
19656 .query_row(buffer_row, &self.buffer_snapshot)
19657 {
19658 is_foldable = true;
19659 match crease {
19660 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19661 if let Some(render_toggle) = render_toggle {
19662 let toggle_callback =
19663 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19664 if folded {
19665 editor.update(cx, |editor, cx| {
19666 editor.fold_at(buffer_row, window, cx)
19667 });
19668 } else {
19669 editor.update(cx, |editor, cx| {
19670 editor.unfold_at(buffer_row, window, cx)
19671 });
19672 }
19673 });
19674 return Some((render_toggle)(
19675 buffer_row,
19676 folded,
19677 toggle_callback,
19678 window,
19679 cx,
19680 ));
19681 }
19682 }
19683 }
19684 }
19685
19686 is_foldable |= self.starts_indent(buffer_row);
19687
19688 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19689 Some(
19690 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19691 .toggle_state(folded)
19692 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19693 if folded {
19694 this.unfold_at(buffer_row, window, cx);
19695 } else {
19696 this.fold_at(buffer_row, window, cx);
19697 }
19698 }))
19699 .into_any_element(),
19700 )
19701 } else {
19702 None
19703 }
19704 }
19705
19706 pub fn render_crease_trailer(
19707 &self,
19708 buffer_row: MultiBufferRow,
19709 window: &mut Window,
19710 cx: &mut App,
19711 ) -> Option<AnyElement> {
19712 let folded = self.is_line_folded(buffer_row);
19713 if let Crease::Inline { render_trailer, .. } = self
19714 .crease_snapshot
19715 .query_row(buffer_row, &self.buffer_snapshot)?
19716 {
19717 let render_trailer = render_trailer.as_ref()?;
19718 Some(render_trailer(buffer_row, folded, window, cx))
19719 } else {
19720 None
19721 }
19722 }
19723}
19724
19725impl Deref for EditorSnapshot {
19726 type Target = DisplaySnapshot;
19727
19728 fn deref(&self) -> &Self::Target {
19729 &self.display_snapshot
19730 }
19731}
19732
19733#[derive(Clone, Debug, PartialEq, Eq)]
19734pub enum EditorEvent {
19735 InputIgnored {
19736 text: Arc<str>,
19737 },
19738 InputHandled {
19739 utf16_range_to_replace: Option<Range<isize>>,
19740 text: Arc<str>,
19741 },
19742 ExcerptsAdded {
19743 buffer: Entity<Buffer>,
19744 predecessor: ExcerptId,
19745 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19746 },
19747 ExcerptsRemoved {
19748 ids: Vec<ExcerptId>,
19749 },
19750 BufferFoldToggled {
19751 ids: Vec<ExcerptId>,
19752 folded: bool,
19753 },
19754 ExcerptsEdited {
19755 ids: Vec<ExcerptId>,
19756 },
19757 ExcerptsExpanded {
19758 ids: Vec<ExcerptId>,
19759 },
19760 BufferEdited,
19761 Edited {
19762 transaction_id: clock::Lamport,
19763 },
19764 Reparsed(BufferId),
19765 Focused,
19766 FocusedIn,
19767 Blurred,
19768 DirtyChanged,
19769 Saved,
19770 TitleChanged,
19771 DiffBaseChanged,
19772 SelectionsChanged {
19773 local: bool,
19774 },
19775 ScrollPositionChanged {
19776 local: bool,
19777 autoscroll: bool,
19778 },
19779 Closed,
19780 TransactionUndone {
19781 transaction_id: clock::Lamport,
19782 },
19783 TransactionBegun {
19784 transaction_id: clock::Lamport,
19785 },
19786 Reloaded,
19787 CursorShapeChanged,
19788 PushedToNavHistory {
19789 anchor: Anchor,
19790 is_deactivate: bool,
19791 },
19792}
19793
19794impl EventEmitter<EditorEvent> for Editor {}
19795
19796impl Focusable for Editor {
19797 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19798 self.focus_handle.clone()
19799 }
19800}
19801
19802impl Render for Editor {
19803 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19804 let settings = ThemeSettings::get_global(cx);
19805
19806 let mut text_style = match self.mode {
19807 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19808 color: cx.theme().colors().editor_foreground,
19809 font_family: settings.ui_font.family.clone(),
19810 font_features: settings.ui_font.features.clone(),
19811 font_fallbacks: settings.ui_font.fallbacks.clone(),
19812 font_size: rems(0.875).into(),
19813 font_weight: settings.ui_font.weight,
19814 line_height: relative(settings.buffer_line_height.value()),
19815 ..Default::default()
19816 },
19817 EditorMode::Full { .. } => TextStyle {
19818 color: cx.theme().colors().editor_foreground,
19819 font_family: settings.buffer_font.family.clone(),
19820 font_features: settings.buffer_font.features.clone(),
19821 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19822 font_size: settings.buffer_font_size(cx).into(),
19823 font_weight: settings.buffer_font.weight,
19824 line_height: relative(settings.buffer_line_height.value()),
19825 ..Default::default()
19826 },
19827 };
19828 if let Some(text_style_refinement) = &self.text_style_refinement {
19829 text_style.refine(text_style_refinement)
19830 }
19831
19832 let background = match self.mode {
19833 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19834 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19835 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19836 };
19837
19838 EditorElement::new(
19839 &cx.entity(),
19840 EditorStyle {
19841 background,
19842 local_player: cx.theme().players().local(),
19843 text: text_style,
19844 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19845 syntax: cx.theme().syntax().clone(),
19846 status: cx.theme().status().clone(),
19847 inlay_hints_style: make_inlay_hints_style(cx),
19848 inline_completion_styles: make_suggestion_styles(cx),
19849 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19850 },
19851 )
19852 }
19853}
19854
19855impl EntityInputHandler for Editor {
19856 fn text_for_range(
19857 &mut self,
19858 range_utf16: Range<usize>,
19859 adjusted_range: &mut Option<Range<usize>>,
19860 _: &mut Window,
19861 cx: &mut Context<Self>,
19862 ) -> Option<String> {
19863 let snapshot = self.buffer.read(cx).read(cx);
19864 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19865 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19866 if (start.0..end.0) != range_utf16 {
19867 adjusted_range.replace(start.0..end.0);
19868 }
19869 Some(snapshot.text_for_range(start..end).collect())
19870 }
19871
19872 fn selected_text_range(
19873 &mut self,
19874 ignore_disabled_input: bool,
19875 _: &mut Window,
19876 cx: &mut Context<Self>,
19877 ) -> Option<UTF16Selection> {
19878 // Prevent the IME menu from appearing when holding down an alphabetic key
19879 // while input is disabled.
19880 if !ignore_disabled_input && !self.input_enabled {
19881 return None;
19882 }
19883
19884 let selection = self.selections.newest::<OffsetUtf16>(cx);
19885 let range = selection.range();
19886
19887 Some(UTF16Selection {
19888 range: range.start.0..range.end.0,
19889 reversed: selection.reversed,
19890 })
19891 }
19892
19893 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19894 let snapshot = self.buffer.read(cx).read(cx);
19895 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19896 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19897 }
19898
19899 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19900 self.clear_highlights::<InputComposition>(cx);
19901 self.ime_transaction.take();
19902 }
19903
19904 fn replace_text_in_range(
19905 &mut self,
19906 range_utf16: Option<Range<usize>>,
19907 text: &str,
19908 window: &mut Window,
19909 cx: &mut Context<Self>,
19910 ) {
19911 if !self.input_enabled {
19912 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19913 return;
19914 }
19915
19916 self.transact(window, cx, |this, window, cx| {
19917 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19918 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19919 Some(this.selection_replacement_ranges(range_utf16, cx))
19920 } else {
19921 this.marked_text_ranges(cx)
19922 };
19923
19924 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19925 let newest_selection_id = this.selections.newest_anchor().id;
19926 this.selections
19927 .all::<OffsetUtf16>(cx)
19928 .iter()
19929 .zip(ranges_to_replace.iter())
19930 .find_map(|(selection, range)| {
19931 if selection.id == newest_selection_id {
19932 Some(
19933 (range.start.0 as isize - selection.head().0 as isize)
19934 ..(range.end.0 as isize - selection.head().0 as isize),
19935 )
19936 } else {
19937 None
19938 }
19939 })
19940 });
19941
19942 cx.emit(EditorEvent::InputHandled {
19943 utf16_range_to_replace: range_to_replace,
19944 text: text.into(),
19945 });
19946
19947 if let Some(new_selected_ranges) = new_selected_ranges {
19948 this.change_selections(None, window, cx, |selections| {
19949 selections.select_ranges(new_selected_ranges)
19950 });
19951 this.backspace(&Default::default(), window, cx);
19952 }
19953
19954 this.handle_input(text, window, cx);
19955 });
19956
19957 if let Some(transaction) = self.ime_transaction {
19958 self.buffer.update(cx, |buffer, cx| {
19959 buffer.group_until_transaction(transaction, cx);
19960 });
19961 }
19962
19963 self.unmark_text(window, cx);
19964 }
19965
19966 fn replace_and_mark_text_in_range(
19967 &mut self,
19968 range_utf16: Option<Range<usize>>,
19969 text: &str,
19970 new_selected_range_utf16: Option<Range<usize>>,
19971 window: &mut Window,
19972 cx: &mut Context<Self>,
19973 ) {
19974 if !self.input_enabled {
19975 return;
19976 }
19977
19978 let transaction = self.transact(window, cx, |this, window, cx| {
19979 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19980 let snapshot = this.buffer.read(cx).read(cx);
19981 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19982 for marked_range in &mut marked_ranges {
19983 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19984 marked_range.start.0 += relative_range_utf16.start;
19985 marked_range.start =
19986 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19987 marked_range.end =
19988 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19989 }
19990 }
19991 Some(marked_ranges)
19992 } else if let Some(range_utf16) = range_utf16 {
19993 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19994 Some(this.selection_replacement_ranges(range_utf16, cx))
19995 } else {
19996 None
19997 };
19998
19999 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20000 let newest_selection_id = this.selections.newest_anchor().id;
20001 this.selections
20002 .all::<OffsetUtf16>(cx)
20003 .iter()
20004 .zip(ranges_to_replace.iter())
20005 .find_map(|(selection, range)| {
20006 if selection.id == newest_selection_id {
20007 Some(
20008 (range.start.0 as isize - selection.head().0 as isize)
20009 ..(range.end.0 as isize - selection.head().0 as isize),
20010 )
20011 } else {
20012 None
20013 }
20014 })
20015 });
20016
20017 cx.emit(EditorEvent::InputHandled {
20018 utf16_range_to_replace: range_to_replace,
20019 text: text.into(),
20020 });
20021
20022 if let Some(ranges) = ranges_to_replace {
20023 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20024 }
20025
20026 let marked_ranges = {
20027 let snapshot = this.buffer.read(cx).read(cx);
20028 this.selections
20029 .disjoint_anchors()
20030 .iter()
20031 .map(|selection| {
20032 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20033 })
20034 .collect::<Vec<_>>()
20035 };
20036
20037 if text.is_empty() {
20038 this.unmark_text(window, cx);
20039 } else {
20040 this.highlight_text::<InputComposition>(
20041 marked_ranges.clone(),
20042 HighlightStyle {
20043 underline: Some(UnderlineStyle {
20044 thickness: px(1.),
20045 color: None,
20046 wavy: false,
20047 }),
20048 ..Default::default()
20049 },
20050 cx,
20051 );
20052 }
20053
20054 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20055 let use_autoclose = this.use_autoclose;
20056 let use_auto_surround = this.use_auto_surround;
20057 this.set_use_autoclose(false);
20058 this.set_use_auto_surround(false);
20059 this.handle_input(text, window, cx);
20060 this.set_use_autoclose(use_autoclose);
20061 this.set_use_auto_surround(use_auto_surround);
20062
20063 if let Some(new_selected_range) = new_selected_range_utf16 {
20064 let snapshot = this.buffer.read(cx).read(cx);
20065 let new_selected_ranges = marked_ranges
20066 .into_iter()
20067 .map(|marked_range| {
20068 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20069 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20070 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20071 snapshot.clip_offset_utf16(new_start, Bias::Left)
20072 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20073 })
20074 .collect::<Vec<_>>();
20075
20076 drop(snapshot);
20077 this.change_selections(None, window, cx, |selections| {
20078 selections.select_ranges(new_selected_ranges)
20079 });
20080 }
20081 });
20082
20083 self.ime_transaction = self.ime_transaction.or(transaction);
20084 if let Some(transaction) = self.ime_transaction {
20085 self.buffer.update(cx, |buffer, cx| {
20086 buffer.group_until_transaction(transaction, cx);
20087 });
20088 }
20089
20090 if self.text_highlights::<InputComposition>(cx).is_none() {
20091 self.ime_transaction.take();
20092 }
20093 }
20094
20095 fn bounds_for_range(
20096 &mut self,
20097 range_utf16: Range<usize>,
20098 element_bounds: gpui::Bounds<Pixels>,
20099 window: &mut Window,
20100 cx: &mut Context<Self>,
20101 ) -> Option<gpui::Bounds<Pixels>> {
20102 let text_layout_details = self.text_layout_details(window);
20103 let gpui::Size {
20104 width: em_width,
20105 height: line_height,
20106 } = self.character_size(window);
20107
20108 let snapshot = self.snapshot(window, cx);
20109 let scroll_position = snapshot.scroll_position();
20110 let scroll_left = scroll_position.x * em_width;
20111
20112 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20113 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20114 + self.gutter_dimensions.width
20115 + self.gutter_dimensions.margin;
20116 let y = line_height * (start.row().as_f32() - scroll_position.y);
20117
20118 Some(Bounds {
20119 origin: element_bounds.origin + point(x, y),
20120 size: size(em_width, line_height),
20121 })
20122 }
20123
20124 fn character_index_for_point(
20125 &mut self,
20126 point: gpui::Point<Pixels>,
20127 _window: &mut Window,
20128 _cx: &mut Context<Self>,
20129 ) -> Option<usize> {
20130 let position_map = self.last_position_map.as_ref()?;
20131 if !position_map.text_hitbox.contains(&point) {
20132 return None;
20133 }
20134 let display_point = position_map.point_for_position(point).previous_valid;
20135 let anchor = position_map
20136 .snapshot
20137 .display_point_to_anchor(display_point, Bias::Left);
20138 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20139 Some(utf16_offset.0)
20140 }
20141}
20142
20143trait SelectionExt {
20144 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20145 fn spanned_rows(
20146 &self,
20147 include_end_if_at_line_start: bool,
20148 map: &DisplaySnapshot,
20149 ) -> Range<MultiBufferRow>;
20150}
20151
20152impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20153 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20154 let start = self
20155 .start
20156 .to_point(&map.buffer_snapshot)
20157 .to_display_point(map);
20158 let end = self
20159 .end
20160 .to_point(&map.buffer_snapshot)
20161 .to_display_point(map);
20162 if self.reversed {
20163 end..start
20164 } else {
20165 start..end
20166 }
20167 }
20168
20169 fn spanned_rows(
20170 &self,
20171 include_end_if_at_line_start: bool,
20172 map: &DisplaySnapshot,
20173 ) -> Range<MultiBufferRow> {
20174 let start = self.start.to_point(&map.buffer_snapshot);
20175 let mut end = self.end.to_point(&map.buffer_snapshot);
20176 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20177 end.row -= 1;
20178 }
20179
20180 let buffer_start = map.prev_line_boundary(start).0;
20181 let buffer_end = map.next_line_boundary(end).0;
20182 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20183 }
20184}
20185
20186impl<T: InvalidationRegion> InvalidationStack<T> {
20187 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20188 where
20189 S: Clone + ToOffset,
20190 {
20191 while let Some(region) = self.last() {
20192 let all_selections_inside_invalidation_ranges =
20193 if selections.len() == region.ranges().len() {
20194 selections
20195 .iter()
20196 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20197 .all(|(selection, invalidation_range)| {
20198 let head = selection.head().to_offset(buffer);
20199 invalidation_range.start <= head && invalidation_range.end >= head
20200 })
20201 } else {
20202 false
20203 };
20204
20205 if all_selections_inside_invalidation_ranges {
20206 break;
20207 } else {
20208 self.pop();
20209 }
20210 }
20211 }
20212}
20213
20214impl<T> Default for InvalidationStack<T> {
20215 fn default() -> Self {
20216 Self(Default::default())
20217 }
20218}
20219
20220impl<T> Deref for InvalidationStack<T> {
20221 type Target = Vec<T>;
20222
20223 fn deref(&self) -> &Self::Target {
20224 &self.0
20225 }
20226}
20227
20228impl<T> DerefMut for InvalidationStack<T> {
20229 fn deref_mut(&mut self) -> &mut Self::Target {
20230 &mut self.0
20231 }
20232}
20233
20234impl InvalidationRegion for SnippetState {
20235 fn ranges(&self) -> &[Range<Anchor>] {
20236 &self.ranges[self.active_index]
20237 }
20238}
20239
20240fn inline_completion_edit_text(
20241 current_snapshot: &BufferSnapshot,
20242 edits: &[(Range<Anchor>, String)],
20243 edit_preview: &EditPreview,
20244 include_deletions: bool,
20245 cx: &App,
20246) -> HighlightedText {
20247 let edits = edits
20248 .iter()
20249 .map(|(anchor, text)| {
20250 (
20251 anchor.start.text_anchor..anchor.end.text_anchor,
20252 text.clone(),
20253 )
20254 })
20255 .collect::<Vec<_>>();
20256
20257 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20258}
20259
20260pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20261 match severity {
20262 DiagnosticSeverity::ERROR => colors.error,
20263 DiagnosticSeverity::WARNING => colors.warning,
20264 DiagnosticSeverity::INFORMATION => colors.info,
20265 DiagnosticSeverity::HINT => colors.info,
20266 _ => colors.ignored,
20267 }
20268}
20269
20270pub fn styled_runs_for_code_label<'a>(
20271 label: &'a CodeLabel,
20272 syntax_theme: &'a theme::SyntaxTheme,
20273) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20274 let fade_out = HighlightStyle {
20275 fade_out: Some(0.35),
20276 ..Default::default()
20277 };
20278
20279 let mut prev_end = label.filter_range.end;
20280 label
20281 .runs
20282 .iter()
20283 .enumerate()
20284 .flat_map(move |(ix, (range, highlight_id))| {
20285 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20286 style
20287 } else {
20288 return Default::default();
20289 };
20290 let mut muted_style = style;
20291 muted_style.highlight(fade_out);
20292
20293 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20294 if range.start >= label.filter_range.end {
20295 if range.start > prev_end {
20296 runs.push((prev_end..range.start, fade_out));
20297 }
20298 runs.push((range.clone(), muted_style));
20299 } else if range.end <= label.filter_range.end {
20300 runs.push((range.clone(), style));
20301 } else {
20302 runs.push((range.start..label.filter_range.end, style));
20303 runs.push((label.filter_range.end..range.end, muted_style));
20304 }
20305 prev_end = cmp::max(prev_end, range.end);
20306
20307 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20308 runs.push((prev_end..label.text.len(), fade_out));
20309 }
20310
20311 runs
20312 })
20313}
20314
20315pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20316 let mut prev_index = 0;
20317 let mut prev_codepoint: Option<char> = None;
20318 text.char_indices()
20319 .chain([(text.len(), '\0')])
20320 .filter_map(move |(index, codepoint)| {
20321 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20322 let is_boundary = index == text.len()
20323 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20324 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20325 if is_boundary {
20326 let chunk = &text[prev_index..index];
20327 prev_index = index;
20328 Some(chunk)
20329 } else {
20330 None
20331 }
20332 })
20333}
20334
20335pub trait RangeToAnchorExt: Sized {
20336 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20337
20338 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20339 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20340 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20341 }
20342}
20343
20344impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20345 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20346 let start_offset = self.start.to_offset(snapshot);
20347 let end_offset = self.end.to_offset(snapshot);
20348 if start_offset == end_offset {
20349 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20350 } else {
20351 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20352 }
20353 }
20354}
20355
20356pub trait RowExt {
20357 fn as_f32(&self) -> f32;
20358
20359 fn next_row(&self) -> Self;
20360
20361 fn previous_row(&self) -> Self;
20362
20363 fn minus(&self, other: Self) -> u32;
20364}
20365
20366impl RowExt for DisplayRow {
20367 fn as_f32(&self) -> f32 {
20368 self.0 as f32
20369 }
20370
20371 fn next_row(&self) -> Self {
20372 Self(self.0 + 1)
20373 }
20374
20375 fn previous_row(&self) -> Self {
20376 Self(self.0.saturating_sub(1))
20377 }
20378
20379 fn minus(&self, other: Self) -> u32 {
20380 self.0 - other.0
20381 }
20382}
20383
20384impl RowExt for MultiBufferRow {
20385 fn as_f32(&self) -> f32 {
20386 self.0 as f32
20387 }
20388
20389 fn next_row(&self) -> Self {
20390 Self(self.0 + 1)
20391 }
20392
20393 fn previous_row(&self) -> Self {
20394 Self(self.0.saturating_sub(1))
20395 }
20396
20397 fn minus(&self, other: Self) -> u32 {
20398 self.0 - other.0
20399 }
20400}
20401
20402trait RowRangeExt {
20403 type Row;
20404
20405 fn len(&self) -> usize;
20406
20407 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20408}
20409
20410impl RowRangeExt for Range<MultiBufferRow> {
20411 type Row = MultiBufferRow;
20412
20413 fn len(&self) -> usize {
20414 (self.end.0 - self.start.0) as usize
20415 }
20416
20417 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20418 (self.start.0..self.end.0).map(MultiBufferRow)
20419 }
20420}
20421
20422impl RowRangeExt for Range<DisplayRow> {
20423 type Row = DisplayRow;
20424
20425 fn len(&self) -> usize {
20426 (self.end.0 - self.start.0) as usize
20427 }
20428
20429 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20430 (self.start.0..self.end.0).map(DisplayRow)
20431 }
20432}
20433
20434/// If select range has more than one line, we
20435/// just point the cursor to range.start.
20436fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20437 if range.start.row == range.end.row {
20438 range
20439 } else {
20440 range.start..range.start
20441 }
20442}
20443pub struct KillRing(ClipboardItem);
20444impl Global for KillRing {}
20445
20446const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20447
20448enum BreakpointPromptEditAction {
20449 Log,
20450 Condition,
20451 HitCondition,
20452}
20453
20454struct BreakpointPromptEditor {
20455 pub(crate) prompt: Entity<Editor>,
20456 editor: WeakEntity<Editor>,
20457 breakpoint_anchor: Anchor,
20458 breakpoint: Breakpoint,
20459 edit_action: BreakpointPromptEditAction,
20460 block_ids: HashSet<CustomBlockId>,
20461 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20462 _subscriptions: Vec<Subscription>,
20463}
20464
20465impl BreakpointPromptEditor {
20466 const MAX_LINES: u8 = 4;
20467
20468 fn new(
20469 editor: WeakEntity<Editor>,
20470 breakpoint_anchor: Anchor,
20471 breakpoint: Breakpoint,
20472 edit_action: BreakpointPromptEditAction,
20473 window: &mut Window,
20474 cx: &mut Context<Self>,
20475 ) -> Self {
20476 let base_text = match edit_action {
20477 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20478 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20479 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20480 }
20481 .map(|msg| msg.to_string())
20482 .unwrap_or_default();
20483
20484 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20485 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20486
20487 let prompt = cx.new(|cx| {
20488 let mut prompt = Editor::new(
20489 EditorMode::AutoHeight {
20490 max_lines: Self::MAX_LINES as usize,
20491 },
20492 buffer,
20493 None,
20494 window,
20495 cx,
20496 );
20497 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20498 prompt.set_show_cursor_when_unfocused(false, cx);
20499 prompt.set_placeholder_text(
20500 match edit_action {
20501 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20502 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20503 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20504 },
20505 cx,
20506 );
20507
20508 prompt
20509 });
20510
20511 Self {
20512 prompt,
20513 editor,
20514 breakpoint_anchor,
20515 breakpoint,
20516 edit_action,
20517 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20518 block_ids: Default::default(),
20519 _subscriptions: vec![],
20520 }
20521 }
20522
20523 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20524 self.block_ids.extend(block_ids)
20525 }
20526
20527 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20528 if let Some(editor) = self.editor.upgrade() {
20529 let message = self
20530 .prompt
20531 .read(cx)
20532 .buffer
20533 .read(cx)
20534 .as_singleton()
20535 .expect("A multi buffer in breakpoint prompt isn't possible")
20536 .read(cx)
20537 .as_rope()
20538 .to_string();
20539
20540 editor.update(cx, |editor, cx| {
20541 editor.edit_breakpoint_at_anchor(
20542 self.breakpoint_anchor,
20543 self.breakpoint.clone(),
20544 match self.edit_action {
20545 BreakpointPromptEditAction::Log => {
20546 BreakpointEditAction::EditLogMessage(message.into())
20547 }
20548 BreakpointPromptEditAction::Condition => {
20549 BreakpointEditAction::EditCondition(message.into())
20550 }
20551 BreakpointPromptEditAction::HitCondition => {
20552 BreakpointEditAction::EditHitCondition(message.into())
20553 }
20554 },
20555 cx,
20556 );
20557
20558 editor.remove_blocks(self.block_ids.clone(), None, cx);
20559 cx.focus_self(window);
20560 });
20561 }
20562 }
20563
20564 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20565 self.editor
20566 .update(cx, |editor, cx| {
20567 editor.remove_blocks(self.block_ids.clone(), None, cx);
20568 window.focus(&editor.focus_handle);
20569 })
20570 .log_err();
20571 }
20572
20573 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20574 let settings = ThemeSettings::get_global(cx);
20575 let text_style = TextStyle {
20576 color: if self.prompt.read(cx).read_only(cx) {
20577 cx.theme().colors().text_disabled
20578 } else {
20579 cx.theme().colors().text
20580 },
20581 font_family: settings.buffer_font.family.clone(),
20582 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20583 font_size: settings.buffer_font_size(cx).into(),
20584 font_weight: settings.buffer_font.weight,
20585 line_height: relative(settings.buffer_line_height.value()),
20586 ..Default::default()
20587 };
20588 EditorElement::new(
20589 &self.prompt,
20590 EditorStyle {
20591 background: cx.theme().colors().editor_background,
20592 local_player: cx.theme().players().local(),
20593 text: text_style,
20594 ..Default::default()
20595 },
20596 )
20597 }
20598}
20599
20600impl Render for BreakpointPromptEditor {
20601 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20602 let gutter_dimensions = *self.gutter_dimensions.lock();
20603 h_flex()
20604 .key_context("Editor")
20605 .bg(cx.theme().colors().editor_background)
20606 .border_y_1()
20607 .border_color(cx.theme().status().info_border)
20608 .size_full()
20609 .py(window.line_height() / 2.5)
20610 .on_action(cx.listener(Self::confirm))
20611 .on_action(cx.listener(Self::cancel))
20612 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20613 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20614 }
20615}
20616
20617impl Focusable for BreakpointPromptEditor {
20618 fn focus_handle(&self, cx: &App) -> FocusHandle {
20619 self.prompt.focus_handle(cx)
20620 }
20621}
20622
20623fn all_edits_insertions_or_deletions(
20624 edits: &Vec<(Range<Anchor>, String)>,
20625 snapshot: &MultiBufferSnapshot,
20626) -> bool {
20627 let mut all_insertions = true;
20628 let mut all_deletions = true;
20629
20630 for (range, new_text) in edits.iter() {
20631 let range_is_empty = range.to_offset(&snapshot).is_empty();
20632 let text_is_empty = new_text.is_empty();
20633
20634 if range_is_empty != text_is_empty {
20635 if range_is_empty {
20636 all_deletions = false;
20637 } else {
20638 all_insertions = false;
20639 }
20640 } else {
20641 return false;
20642 }
20643
20644 if !all_insertions && !all_deletions {
20645 return false;
20646 }
20647 }
20648 all_insertions || all_deletions
20649}
20650
20651struct MissingEditPredictionKeybindingTooltip;
20652
20653impl Render for MissingEditPredictionKeybindingTooltip {
20654 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20655 ui::tooltip_container(window, cx, |container, _, cx| {
20656 container
20657 .flex_shrink_0()
20658 .max_w_80()
20659 .min_h(rems_from_px(124.))
20660 .justify_between()
20661 .child(
20662 v_flex()
20663 .flex_1()
20664 .text_ui_sm(cx)
20665 .child(Label::new("Conflict with Accept Keybinding"))
20666 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20667 )
20668 .child(
20669 h_flex()
20670 .pb_1()
20671 .gap_1()
20672 .items_end()
20673 .w_full()
20674 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20675 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20676 }))
20677 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20678 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20679 })),
20680 )
20681 })
20682 }
20683}
20684
20685#[derive(Debug, Clone, Copy, PartialEq)]
20686pub struct LineHighlight {
20687 pub background: Background,
20688 pub border: Option<gpui::Hsla>,
20689}
20690
20691impl From<Hsla> for LineHighlight {
20692 fn from(hsla: Hsla) -> Self {
20693 Self {
20694 background: hsla.into(),
20695 border: None,
20696 }
20697 }
20698}
20699
20700impl From<Background> for LineHighlight {
20701 fn from(background: Background) -> Self {
20702 Self {
20703 background,
20704 border: None,
20705 }
20706 }
20707}
20708
20709fn render_diff_hunk_controls(
20710 row: u32,
20711 status: &DiffHunkStatus,
20712 hunk_range: Range<Anchor>,
20713 is_created_file: bool,
20714 line_height: Pixels,
20715 editor: &Entity<Editor>,
20716 _window: &mut Window,
20717 cx: &mut App,
20718) -> AnyElement {
20719 h_flex()
20720 .h(line_height)
20721 .mr_1()
20722 .gap_1()
20723 .px_0p5()
20724 .pb_1()
20725 .border_x_1()
20726 .border_b_1()
20727 .border_color(cx.theme().colors().border_variant)
20728 .rounded_b_lg()
20729 .bg(cx.theme().colors().editor_background)
20730 .gap_1()
20731 .occlude()
20732 .shadow_md()
20733 .child(if status.has_secondary_hunk() {
20734 Button::new(("stage", row as u64), "Stage")
20735 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20736 .tooltip({
20737 let focus_handle = editor.focus_handle(cx);
20738 move |window, cx| {
20739 Tooltip::for_action_in(
20740 "Stage Hunk",
20741 &::git::ToggleStaged,
20742 &focus_handle,
20743 window,
20744 cx,
20745 )
20746 }
20747 })
20748 .on_click({
20749 let editor = editor.clone();
20750 move |_event, _window, cx| {
20751 editor.update(cx, |editor, cx| {
20752 editor.stage_or_unstage_diff_hunks(
20753 true,
20754 vec![hunk_range.start..hunk_range.start],
20755 cx,
20756 );
20757 });
20758 }
20759 })
20760 } else {
20761 Button::new(("unstage", row as u64), "Unstage")
20762 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20763 .tooltip({
20764 let focus_handle = editor.focus_handle(cx);
20765 move |window, cx| {
20766 Tooltip::for_action_in(
20767 "Unstage Hunk",
20768 &::git::ToggleStaged,
20769 &focus_handle,
20770 window,
20771 cx,
20772 )
20773 }
20774 })
20775 .on_click({
20776 let editor = editor.clone();
20777 move |_event, _window, cx| {
20778 editor.update(cx, |editor, cx| {
20779 editor.stage_or_unstage_diff_hunks(
20780 false,
20781 vec![hunk_range.start..hunk_range.start],
20782 cx,
20783 );
20784 });
20785 }
20786 })
20787 })
20788 .child(
20789 Button::new(("restore", row as u64), "Restore")
20790 .tooltip({
20791 let focus_handle = editor.focus_handle(cx);
20792 move |window, cx| {
20793 Tooltip::for_action_in(
20794 "Restore Hunk",
20795 &::git::Restore,
20796 &focus_handle,
20797 window,
20798 cx,
20799 )
20800 }
20801 })
20802 .on_click({
20803 let editor = editor.clone();
20804 move |_event, window, cx| {
20805 editor.update(cx, |editor, cx| {
20806 let snapshot = editor.snapshot(window, cx);
20807 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20808 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20809 });
20810 }
20811 })
20812 .disabled(is_created_file),
20813 )
20814 .when(
20815 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20816 |el| {
20817 el.child(
20818 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20819 .shape(IconButtonShape::Square)
20820 .icon_size(IconSize::Small)
20821 // .disabled(!has_multiple_hunks)
20822 .tooltip({
20823 let focus_handle = editor.focus_handle(cx);
20824 move |window, cx| {
20825 Tooltip::for_action_in(
20826 "Next Hunk",
20827 &GoToHunk,
20828 &focus_handle,
20829 window,
20830 cx,
20831 )
20832 }
20833 })
20834 .on_click({
20835 let editor = editor.clone();
20836 move |_event, window, cx| {
20837 editor.update(cx, |editor, cx| {
20838 let snapshot = editor.snapshot(window, cx);
20839 let position =
20840 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20841 editor.go_to_hunk_before_or_after_position(
20842 &snapshot,
20843 position,
20844 Direction::Next,
20845 window,
20846 cx,
20847 );
20848 editor.expand_selected_diff_hunks(cx);
20849 });
20850 }
20851 }),
20852 )
20853 .child(
20854 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20855 .shape(IconButtonShape::Square)
20856 .icon_size(IconSize::Small)
20857 // .disabled(!has_multiple_hunks)
20858 .tooltip({
20859 let focus_handle = editor.focus_handle(cx);
20860 move |window, cx| {
20861 Tooltip::for_action_in(
20862 "Previous Hunk",
20863 &GoToPreviousHunk,
20864 &focus_handle,
20865 window,
20866 cx,
20867 )
20868 }
20869 })
20870 .on_click({
20871 let editor = editor.clone();
20872 move |_event, window, cx| {
20873 editor.update(cx, |editor, cx| {
20874 let snapshot = editor.snapshot(window, cx);
20875 let point =
20876 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20877 editor.go_to_hunk_before_or_after_position(
20878 &snapshot,
20879 point,
20880 Direction::Prev,
20881 window,
20882 cx,
20883 );
20884 editor.expand_selected_diff_hunks(cx);
20885 });
20886 }
20887 }),
20888 )
20889 },
20890 )
20891 .into_any_element()
20892}