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 code_completion_tests;
44#[cfg(test)]
45mod editor_tests;
46#[cfg(test)]
47mod inline_completion_tests;
48mod signature_help;
49#[cfg(any(test, feature = "test-support"))]
50pub mod test;
51
52pub(crate) use actions::*;
53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{Context as _, Result, anyhow};
56use blink_manager::BlinkManager;
57use buffer_diff::DiffHunkStatus;
58use client::{Collaborator, ParticipantIndex};
59use clock::{AGENT_REPLICA_ID, ReplicaId};
60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
61use convert_case::{Case, Casing};
62use display_map::*;
63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
64pub use editor_settings::{
65 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
66 ShowScrollbar,
67};
68use editor_settings::{GoToDefinitionFallback, Minimap as MinimapSettings};
69pub use editor_settings_controls::*;
70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
71pub use element::{
72 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
73};
74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
75use futures::{
76 FutureExt,
77 future::{self, Shared, join},
78};
79use fuzzy::StringMatchCandidate;
80
81use ::git::blame::BlameEntry;
82use ::git::{Restore, blame::ParsedCommitMessage};
83use code_context_menus::{
84 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
85 CompletionsMenu, ContextMenuOrigin,
86};
87use git::blame::{GitBlame, GlobalBlameRenderer};
88use gpui::{
89 Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
90 AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
91 DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
92 Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
93 MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
94 SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
95 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
96 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
97};
98use highlight_matching_bracket::refresh_matching_bracket_highlights;
99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
100pub use hover_popover::hover_markdown_style;
101use hover_popover::{HoverState, hide_hover};
102use indent_guides::ActiveIndentGuidesState;
103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
104pub use inline_completion::Direction;
105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
106pub use items::MAX_TAB_TITLE_LEN;
107use itertools::Itertools;
108use language::{
109 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
110 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
111 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
112 TransactionId, TreeSitterOptions, WordsQuery,
113 language_settings::{
114 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
115 all_language_settings, language_settings,
116 },
117 point_from_lsp, text_diff_with_options,
118};
119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
120use linked_editing_ranges::refresh_linked_ranges;
121use markdown::Markdown;
122use mouse_context_menu::MouseContextMenu;
123use persistence::DB;
124use project::{
125 ProjectPath,
126 debugger::{
127 breakpoint_store::{
128 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
129 },
130 session::{Session, SessionEvent},
131 },
132 project_settings::DiagnosticSeverity,
133};
134
135pub use git::blame::BlameRenderer;
136pub use proposed_changes_editor::{
137 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
138};
139use smallvec::smallvec;
140use std::{cell::OnceCell, iter::Peekable, ops::Not};
141use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
142
143pub use lsp::CompletionContext;
144use lsp::{
145 CodeActionKind, CompletionItemKind, CompletionTriggerKind, InsertTextFormat, InsertTextMode,
146 LanguageServerId, LanguageServerName,
147};
148
149use language::BufferSnapshot;
150pub use lsp_ext::lsp_tasks;
151use movement::TextLayoutDetails;
152pub use multi_buffer::{
153 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
154 RowInfo, ToOffset, ToPoint,
155};
156use multi_buffer::{
157 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
158 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
159};
160use parking_lot::Mutex;
161use project::{
162 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
163 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
164 TaskSourceKind,
165 debugger::breakpoint_store::Breakpoint,
166 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
167 project_settings::{GitGutterSetting, ProjectSettings},
168};
169use rand::prelude::*;
170use rpc::{ErrorExt, proto::*};
171use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
172use selections_collection::{
173 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
174};
175use serde::{Deserialize, Serialize};
176use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
177use smallvec::SmallVec;
178use snippet::Snippet;
179use std::sync::Arc;
180use std::{
181 any::TypeId,
182 borrow::Cow,
183 cell::RefCell,
184 cmp::{self, Ordering, Reverse},
185 mem,
186 num::NonZeroU32,
187 ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
188 path::{Path, PathBuf},
189 rc::Rc,
190 time::{Duration, Instant},
191};
192pub use sum_tree::Bias;
193use sum_tree::TreeMap;
194use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
195use theme::{
196 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
197 observe_buffer_font_size_adjustment,
198};
199use ui::{
200 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
201 IconSize, Key, Tooltip, h_flex, prelude::*,
202};
203use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
204use workspace::{
205 CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
206 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
207 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
208 item::{ItemHandle, PreviewTabsSettings},
209 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
210 searchable::SearchEvent,
211};
212
213use crate::hover_links::{find_url, find_url_from_range};
214use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
215
216pub const FILE_HEADER_HEIGHT: u32 = 2;
217pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
218pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
219const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
220const MAX_LINE_LEN: usize = 1024;
221const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
222const MAX_SELECTION_HISTORY_LEN: usize = 1024;
223pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
224#[doc(hidden)]
225pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
226const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
227
228pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
229pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
230pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
231
232pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
233pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
234pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
235pub(crate) const MINIMAP_FONT_SIZE: AbsoluteLength = AbsoluteLength::Pixels(px(2.));
236
237pub type RenderDiffHunkControlsFn = Arc<
238 dyn Fn(
239 u32,
240 &DiffHunkStatus,
241 Range<Anchor>,
242 bool,
243 Pixels,
244 &Entity<Editor>,
245 &mut Window,
246 &mut App,
247 ) -> AnyElement,
248>;
249
250const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
251 alt: true,
252 shift: true,
253 control: false,
254 platform: false,
255 function: false,
256};
257
258struct InlineValueCache {
259 enabled: bool,
260 inlays: Vec<InlayId>,
261 refresh_task: Task<Option<()>>,
262}
263
264impl InlineValueCache {
265 fn new(enabled: bool) -> Self {
266 Self {
267 enabled,
268 inlays: Vec::new(),
269 refresh_task: Task::ready(None),
270 }
271 }
272}
273
274#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
275pub enum InlayId {
276 InlineCompletion(usize),
277 Hint(usize),
278 DebuggerValue(usize),
279}
280
281impl InlayId {
282 fn id(&self) -> usize {
283 match self {
284 Self::InlineCompletion(id) => *id,
285 Self::Hint(id) => *id,
286 Self::DebuggerValue(id) => *id,
287 }
288 }
289}
290
291pub enum ActiveDebugLine {}
292enum DocumentHighlightRead {}
293enum DocumentHighlightWrite {}
294enum InputComposition {}
295enum SelectedTextHighlight {}
296
297pub enum ConflictsOuter {}
298pub enum ConflictsOurs {}
299pub enum ConflictsTheirs {}
300pub enum ConflictsOursMarker {}
301pub enum ConflictsTheirsMarker {}
302
303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
304pub enum Navigated {
305 Yes,
306 No,
307}
308
309impl Navigated {
310 pub fn from_bool(yes: bool) -> Navigated {
311 if yes { Navigated::Yes } else { Navigated::No }
312 }
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
316enum DisplayDiffHunk {
317 Folded {
318 display_row: DisplayRow,
319 },
320 Unfolded {
321 is_created_file: bool,
322 diff_base_byte_range: Range<usize>,
323 display_row_range: Range<DisplayRow>,
324 multi_buffer_range: Range<Anchor>,
325 status: DiffHunkStatus,
326 },
327}
328
329pub enum HideMouseCursorOrigin {
330 TypingAction,
331 MovementAction,
332}
333
334pub fn init_settings(cx: &mut App) {
335 EditorSettings::register(cx);
336}
337
338pub fn init(cx: &mut App) {
339 init_settings(cx);
340
341 cx.set_global(GlobalBlameRenderer(Arc::new(())));
342
343 workspace::register_project_item::<Editor>(cx);
344 workspace::FollowableViewRegistry::register::<Editor>(cx);
345 workspace::register_serializable_item::<Editor>(cx);
346
347 cx.observe_new(
348 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
349 workspace.register_action(Editor::new_file);
350 workspace.register_action(Editor::new_file_vertical);
351 workspace.register_action(Editor::new_file_horizontal);
352 workspace.register_action(Editor::cancel_language_server_work);
353 },
354 )
355 .detach();
356
357 cx.on_action(move |_: &workspace::NewFile, cx| {
358 let app_state = workspace::AppState::global(cx);
359 if let Some(app_state) = app_state.upgrade() {
360 workspace::open_new(
361 Default::default(),
362 app_state,
363 cx,
364 |workspace, window, cx| {
365 Editor::new_file(workspace, &Default::default(), window, cx)
366 },
367 )
368 .detach();
369 }
370 });
371 cx.on_action(move |_: &workspace::NewWindow, cx| {
372 let app_state = workspace::AppState::global(cx);
373 if let Some(app_state) = app_state.upgrade() {
374 workspace::open_new(
375 Default::default(),
376 app_state,
377 cx,
378 |workspace, window, cx| {
379 cx.activate(true);
380 Editor::new_file(workspace, &Default::default(), window, cx)
381 },
382 )
383 .detach();
384 }
385 });
386}
387
388pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
389 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
390}
391
392pub trait DiagnosticRenderer {
393 fn render_group(
394 &self,
395 diagnostic_group: Vec<DiagnosticEntry<Point>>,
396 buffer_id: BufferId,
397 snapshot: EditorSnapshot,
398 editor: WeakEntity<Editor>,
399 cx: &mut App,
400 ) -> Vec<BlockProperties<Anchor>>;
401
402 fn render_hover(
403 &self,
404 diagnostic_group: Vec<DiagnosticEntry<Point>>,
405 range: Range<Point>,
406 buffer_id: BufferId,
407 cx: &mut App,
408 ) -> Option<Entity<markdown::Markdown>>;
409
410 fn open_link(
411 &self,
412 editor: &mut Editor,
413 link: SharedString,
414 window: &mut Window,
415 cx: &mut Context<Editor>,
416 );
417}
418
419pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
420
421impl GlobalDiagnosticRenderer {
422 fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
423 cx.try_global::<Self>().map(|g| g.0.clone())
424 }
425}
426
427impl gpui::Global for GlobalDiagnosticRenderer {}
428pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
429 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
430}
431
432pub struct SearchWithinRange;
433
434trait InvalidationRegion {
435 fn ranges(&self) -> &[Range<Anchor>];
436}
437
438#[derive(Clone, Debug, PartialEq)]
439pub enum SelectPhase {
440 Begin {
441 position: DisplayPoint,
442 add: bool,
443 click_count: usize,
444 },
445 BeginColumnar {
446 position: DisplayPoint,
447 reset: bool,
448 goal_column: u32,
449 },
450 Extend {
451 position: DisplayPoint,
452 click_count: usize,
453 },
454 Update {
455 position: DisplayPoint,
456 goal_column: u32,
457 scroll_delta: gpui::Point<f32>,
458 },
459 End,
460}
461
462#[derive(Clone, Debug)]
463pub enum SelectMode {
464 Character,
465 Word(Range<Anchor>),
466 Line(Range<Anchor>),
467 All,
468}
469
470#[derive(Clone, PartialEq, Eq, Debug)]
471pub enum EditorMode {
472 SingleLine {
473 auto_width: bool,
474 },
475 AutoHeight {
476 max_lines: usize,
477 },
478 Full {
479 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
480 scale_ui_elements_with_buffer_font_size: bool,
481 /// When set to `true`, the editor will render a background for the active line.
482 show_active_line_background: bool,
483 /// When set to `true`, the editor's height will be determined by its content.
484 sized_by_content: bool,
485 },
486 Minimap {
487 parent: WeakEntity<Editor>,
488 },
489}
490
491impl EditorMode {
492 pub fn full() -> Self {
493 Self::Full {
494 scale_ui_elements_with_buffer_font_size: true,
495 show_active_line_background: true,
496 sized_by_content: false,
497 }
498 }
499
500 pub fn is_full(&self) -> bool {
501 matches!(self, Self::Full { .. })
502 }
503
504 fn is_minimap(&self) -> bool {
505 matches!(self, Self::Minimap { .. })
506 }
507}
508
509#[derive(Copy, Clone, Debug)]
510pub enum SoftWrap {
511 /// Prefer not to wrap at all.
512 ///
513 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
514 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
515 GitDiff,
516 /// Prefer a single line generally, unless an overly long line is encountered.
517 None,
518 /// Soft wrap lines that exceed the editor width.
519 EditorWidth,
520 /// Soft wrap lines at the preferred line length.
521 Column(u32),
522 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
523 Bounded(u32),
524}
525
526#[derive(Clone)]
527pub struct EditorStyle {
528 pub background: Hsla,
529 pub local_player: PlayerColor,
530 pub text: TextStyle,
531 pub scrollbar_width: Pixels,
532 pub syntax: Arc<SyntaxTheme>,
533 pub status: StatusColors,
534 pub inlay_hints_style: HighlightStyle,
535 pub inline_completion_styles: InlineCompletionStyles,
536 pub unnecessary_code_fade: f32,
537 pub show_underlines: bool,
538}
539
540impl Default for EditorStyle {
541 fn default() -> Self {
542 Self {
543 background: Hsla::default(),
544 local_player: PlayerColor::default(),
545 text: TextStyle::default(),
546 scrollbar_width: Pixels::default(),
547 syntax: Default::default(),
548 // HACK: Status colors don't have a real default.
549 // We should look into removing the status colors from the editor
550 // style and retrieve them directly from the theme.
551 status: StatusColors::dark(),
552 inlay_hints_style: HighlightStyle::default(),
553 inline_completion_styles: InlineCompletionStyles {
554 insertion: HighlightStyle::default(),
555 whitespace: HighlightStyle::default(),
556 },
557 unnecessary_code_fade: Default::default(),
558 show_underlines: true,
559 }
560 }
561}
562
563pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
564 let show_background = language_settings::language_settings(None, None, cx)
565 .inlay_hints
566 .show_background;
567
568 HighlightStyle {
569 color: Some(cx.theme().status().hint),
570 background_color: show_background.then(|| cx.theme().status().hint_background),
571 ..HighlightStyle::default()
572 }
573}
574
575pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
576 InlineCompletionStyles {
577 insertion: HighlightStyle {
578 color: Some(cx.theme().status().predictive),
579 ..HighlightStyle::default()
580 },
581 whitespace: HighlightStyle {
582 background_color: Some(cx.theme().status().created_background),
583 ..HighlightStyle::default()
584 },
585 }
586}
587
588type CompletionId = usize;
589
590pub(crate) enum EditDisplayMode {
591 TabAccept,
592 DiffPopover,
593 Inline,
594}
595
596enum InlineCompletion {
597 Edit {
598 edits: Vec<(Range<Anchor>, String)>,
599 edit_preview: Option<EditPreview>,
600 display_mode: EditDisplayMode,
601 snapshot: BufferSnapshot,
602 },
603 Move {
604 target: Anchor,
605 snapshot: BufferSnapshot,
606 },
607}
608
609struct InlineCompletionState {
610 inlay_ids: Vec<InlayId>,
611 completion: InlineCompletion,
612 completion_id: Option<SharedString>,
613 invalidation_range: Range<Anchor>,
614}
615
616enum EditPredictionSettings {
617 Disabled,
618 Enabled {
619 show_in_menu: bool,
620 preview_requires_modifier: bool,
621 },
622}
623
624enum InlineCompletionHighlight {}
625
626#[derive(Debug, Clone)]
627struct InlineDiagnostic {
628 message: SharedString,
629 group_id: usize,
630 is_primary: bool,
631 start: Point,
632 severity: lsp::DiagnosticSeverity,
633}
634
635pub enum MenuInlineCompletionsPolicy {
636 Never,
637 ByProvider,
638}
639
640pub enum EditPredictionPreview {
641 /// Modifier is not pressed
642 Inactive { released_too_fast: bool },
643 /// Modifier pressed
644 Active {
645 since: Instant,
646 previous_scroll_position: Option<ScrollAnchor>,
647 },
648}
649
650impl EditPredictionPreview {
651 pub fn released_too_fast(&self) -> bool {
652 match self {
653 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
654 EditPredictionPreview::Active { .. } => false,
655 }
656 }
657
658 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
659 if let EditPredictionPreview::Active {
660 previous_scroll_position,
661 ..
662 } = self
663 {
664 *previous_scroll_position = scroll_position;
665 }
666 }
667}
668
669pub struct ContextMenuOptions {
670 pub min_entries_visible: usize,
671 pub max_entries_visible: usize,
672 pub placement: Option<ContextMenuPlacement>,
673}
674
675#[derive(Debug, Clone, PartialEq, Eq)]
676pub enum ContextMenuPlacement {
677 Above,
678 Below,
679}
680
681#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
682struct EditorActionId(usize);
683
684impl EditorActionId {
685 pub fn post_inc(&mut self) -> Self {
686 let answer = self.0;
687
688 *self = Self(answer + 1);
689
690 Self(answer)
691 }
692}
693
694// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
695// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
696
697type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
698type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
699
700#[derive(Default)]
701struct ScrollbarMarkerState {
702 scrollbar_size: Size<Pixels>,
703 dirty: bool,
704 markers: Arc<[PaintQuad]>,
705 pending_refresh: Option<Task<Result<()>>>,
706}
707
708impl ScrollbarMarkerState {
709 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
710 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
711 }
712}
713
714#[derive(Clone, Copy, PartialEq, Eq)]
715pub enum MinimapVisibility {
716 Disabled,
717 Enabled(bool),
718}
719
720impl MinimapVisibility {
721 fn for_mode(mode: &EditorMode, cx: &App) -> Self {
722 if mode.is_full() {
723 Self::Enabled(EditorSettings::get_global(cx).minimap.minimap_enabled())
724 } else {
725 Self::Disabled
726 }
727 }
728
729 fn disabled(&self) -> bool {
730 match *self {
731 Self::Disabled => true,
732 _ => false,
733 }
734 }
735
736 fn visible(&self) -> bool {
737 match *self {
738 Self::Enabled(visible) => visible,
739 _ => false,
740 }
741 }
742
743 fn toggle_visibility(&self) -> Self {
744 match *self {
745 Self::Enabled(visible) => Self::Enabled(!visible),
746 Self::Disabled => Self::Disabled,
747 }
748 }
749}
750
751#[derive(Clone, Debug)]
752struct RunnableTasks {
753 templates: Vec<(TaskSourceKind, TaskTemplate)>,
754 offset: multi_buffer::Anchor,
755 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
756 column: u32,
757 // Values of all named captures, including those starting with '_'
758 extra_variables: HashMap<String, String>,
759 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
760 context_range: Range<BufferOffset>,
761}
762
763impl RunnableTasks {
764 fn resolve<'a>(
765 &'a self,
766 cx: &'a task::TaskContext,
767 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
768 self.templates.iter().filter_map(|(kind, template)| {
769 template
770 .resolve_task(&kind.to_id_base(), cx)
771 .map(|task| (kind.clone(), task))
772 })
773 }
774}
775
776#[derive(Clone)]
777struct ResolvedTasks {
778 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
779 position: Anchor,
780}
781
782#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
783struct BufferOffset(usize);
784
785// Addons allow storing per-editor state in other crates (e.g. Vim)
786pub trait Addon: 'static {
787 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
788
789 fn render_buffer_header_controls(
790 &self,
791 _: &ExcerptInfo,
792 _: &Window,
793 _: &App,
794 ) -> Option<AnyElement> {
795 None
796 }
797
798 fn to_any(&self) -> &dyn std::any::Any;
799
800 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
801 None
802 }
803}
804
805/// A set of caret positions, registered when the editor was edited.
806pub struct ChangeList {
807 changes: Vec<Vec<Anchor>>,
808 /// Currently "selected" change.
809 position: Option<usize>,
810}
811
812impl ChangeList {
813 pub fn new() -> Self {
814 Self {
815 changes: Vec::new(),
816 position: None,
817 }
818 }
819
820 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
821 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
822 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
823 if self.changes.is_empty() {
824 return None;
825 }
826
827 let prev = self.position.unwrap_or(self.changes.len());
828 let next = if direction == Direction::Prev {
829 prev.saturating_sub(count)
830 } else {
831 (prev + count).min(self.changes.len() - 1)
832 };
833 self.position = Some(next);
834 self.changes.get(next).map(|anchors| anchors.as_slice())
835 }
836
837 /// Adds a new change to the list, resetting the change list position.
838 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
839 self.position.take();
840 if pop_state {
841 self.changes.pop();
842 }
843 self.changes.push(new_positions.clone());
844 }
845
846 pub fn last(&self) -> Option<&[Anchor]> {
847 self.changes.last().map(|anchors| anchors.as_slice())
848 }
849}
850
851#[derive(Clone)]
852struct InlineBlamePopoverState {
853 scroll_handle: ScrollHandle,
854 commit_message: Option<ParsedCommitMessage>,
855 markdown: Entity<Markdown>,
856}
857
858struct InlineBlamePopover {
859 position: gpui::Point<Pixels>,
860 show_task: Option<Task<()>>,
861 hide_task: Option<Task<()>>,
862 popover_bounds: Option<Bounds<Pixels>>,
863 popover_state: InlineBlamePopoverState,
864}
865
866/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
867/// a breakpoint on them.
868#[derive(Clone, Copy, Debug)]
869struct PhantomBreakpointIndicator {
870 display_row: DisplayRow,
871 /// There's a small debounce between hovering over the line and showing the indicator.
872 /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
873 is_active: bool,
874 collides_with_existing_breakpoint: bool,
875}
876/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
877///
878/// See the [module level documentation](self) for more information.
879pub struct Editor {
880 focus_handle: FocusHandle,
881 last_focused_descendant: Option<WeakFocusHandle>,
882 /// The text buffer being edited
883 buffer: Entity<MultiBuffer>,
884 /// Map of how text in the buffer should be displayed.
885 /// Handles soft wraps, folds, fake inlay text insertions, etc.
886 pub display_map: Entity<DisplayMap>,
887 pub selections: SelectionsCollection,
888 pub scroll_manager: ScrollManager,
889 /// When inline assist editors are linked, they all render cursors because
890 /// typing enters text into each of them, even the ones that aren't focused.
891 pub(crate) show_cursor_when_unfocused: bool,
892 columnar_selection_tail: Option<Anchor>,
893 add_selections_state: Option<AddSelectionsState>,
894 select_next_state: Option<SelectNextState>,
895 select_prev_state: Option<SelectNextState>,
896 selection_history: SelectionHistory,
897 autoclose_regions: Vec<AutocloseRegion>,
898 snippet_stack: InvalidationStack<SnippetState>,
899 select_syntax_node_history: SelectSyntaxNodeHistory,
900 ime_transaction: Option<TransactionId>,
901 pub diagnostics_max_severity: DiagnosticSeverity,
902 active_diagnostics: ActiveDiagnostic,
903 show_inline_diagnostics: bool,
904 inline_diagnostics_update: Task<()>,
905 inline_diagnostics_enabled: bool,
906 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
907 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
908 hard_wrap: Option<usize>,
909
910 // TODO: make this a access method
911 pub project: Option<Entity<Project>>,
912 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
913 completion_provider: Option<Box<dyn CompletionProvider>>,
914 collaboration_hub: Option<Box<dyn CollaborationHub>>,
915 blink_manager: Entity<BlinkManager>,
916 show_cursor_names: bool,
917 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
918 pub show_local_selections: bool,
919 mode: EditorMode,
920 show_breadcrumbs: bool,
921 show_gutter: bool,
922 show_scrollbars: bool,
923 minimap_visibility: MinimapVisibility,
924 disable_expand_excerpt_buttons: bool,
925 show_line_numbers: Option<bool>,
926 use_relative_line_numbers: Option<bool>,
927 show_git_diff_gutter: Option<bool>,
928 show_code_actions: Option<bool>,
929 show_runnables: Option<bool>,
930 show_breakpoints: Option<bool>,
931 show_wrap_guides: Option<bool>,
932 show_indent_guides: Option<bool>,
933 placeholder_text: Option<Arc<str>>,
934 highlight_order: usize,
935 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
936 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
937 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
938 scrollbar_marker_state: ScrollbarMarkerState,
939 active_indent_guides_state: ActiveIndentGuidesState,
940 nav_history: Option<ItemNavHistory>,
941 context_menu: RefCell<Option<CodeContextMenu>>,
942 context_menu_options: Option<ContextMenuOptions>,
943 mouse_context_menu: Option<MouseContextMenu>,
944 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
945 inline_blame_popover: Option<InlineBlamePopover>,
946 signature_help_state: SignatureHelpState,
947 auto_signature_help: Option<bool>,
948 find_all_references_task_sources: Vec<Anchor>,
949 next_completion_id: CompletionId,
950 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
951 code_actions_task: Option<Task<Result<()>>>,
952 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
953 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
954 document_highlights_task: Option<Task<()>>,
955 linked_editing_range_task: Option<Task<Option<()>>>,
956 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
957 pending_rename: Option<RenameState>,
958 searchable: bool,
959 cursor_shape: CursorShape,
960 current_line_highlight: Option<CurrentLineHighlight>,
961 collapse_matches: bool,
962 autoindent_mode: Option<AutoindentMode>,
963 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
964 input_enabled: bool,
965 use_modal_editing: bool,
966 read_only: bool,
967 leader_id: Option<CollaboratorId>,
968 remote_id: Option<ViewId>,
969 pub hover_state: HoverState,
970 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
971 gutter_hovered: bool,
972 hovered_link_state: Option<HoveredLinkState>,
973 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
974 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
975 active_inline_completion: Option<InlineCompletionState>,
976 /// Used to prevent flickering as the user types while the menu is open
977 stale_inline_completion_in_menu: Option<InlineCompletionState>,
978 edit_prediction_settings: EditPredictionSettings,
979 inline_completions_hidden_for_vim_mode: bool,
980 show_inline_completions_override: Option<bool>,
981 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
982 edit_prediction_preview: EditPredictionPreview,
983 edit_prediction_indent_conflict: bool,
984 edit_prediction_requires_modifier_in_indent_conflict: bool,
985 inlay_hint_cache: InlayHintCache,
986 next_inlay_id: usize,
987 _subscriptions: Vec<Subscription>,
988 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
989 gutter_dimensions: GutterDimensions,
990 style: Option<EditorStyle>,
991 text_style_refinement: Option<TextStyleRefinement>,
992 next_editor_action_id: EditorActionId,
993 editor_actions:
994 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
995 use_autoclose: bool,
996 use_auto_surround: bool,
997 auto_replace_emoji_shortcode: bool,
998 jsx_tag_auto_close_enabled_in_any_buffer: bool,
999 show_git_blame_gutter: bool,
1000 show_git_blame_inline: bool,
1001 show_git_blame_inline_delay_task: Option<Task<()>>,
1002 git_blame_inline_enabled: bool,
1003 render_diff_hunk_controls: RenderDiffHunkControlsFn,
1004 serialize_dirty_buffers: bool,
1005 show_selection_menu: Option<bool>,
1006 blame: Option<Entity<GitBlame>>,
1007 blame_subscription: Option<Subscription>,
1008 custom_context_menu: Option<
1009 Box<
1010 dyn 'static
1011 + Fn(
1012 &mut Self,
1013 DisplayPoint,
1014 &mut Window,
1015 &mut Context<Self>,
1016 ) -> Option<Entity<ui::ContextMenu>>,
1017 >,
1018 >,
1019 last_bounds: Option<Bounds<Pixels>>,
1020 last_position_map: Option<Rc<PositionMap>>,
1021 expect_bounds_change: Option<Bounds<Pixels>>,
1022 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
1023 tasks_update_task: Option<Task<()>>,
1024 breakpoint_store: Option<Entity<BreakpointStore>>,
1025 gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
1026 in_project_search: bool,
1027 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
1028 breadcrumb_header: Option<String>,
1029 focused_block: Option<FocusedBlock>,
1030 next_scroll_position: NextScrollCursorCenterTopBottom,
1031 addons: HashMap<TypeId, Box<dyn Addon>>,
1032 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
1033 load_diff_task: Option<Shared<Task<()>>>,
1034 /// Whether we are temporarily displaying a diff other than git's
1035 temporary_diff_override: bool,
1036 selection_mark_mode: bool,
1037 toggle_fold_multiple_buffers: Task<()>,
1038 _scroll_cursor_center_top_bottom_task: Task<()>,
1039 serialize_selections: Task<()>,
1040 serialize_folds: Task<()>,
1041 mouse_cursor_hidden: bool,
1042 minimap: Option<Entity<Self>>,
1043 hide_mouse_mode: HideMouseMode,
1044 pub change_list: ChangeList,
1045 inline_value_cache: InlineValueCache,
1046}
1047
1048#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
1049enum NextScrollCursorCenterTopBottom {
1050 #[default]
1051 Center,
1052 Top,
1053 Bottom,
1054}
1055
1056impl NextScrollCursorCenterTopBottom {
1057 fn next(&self) -> Self {
1058 match self {
1059 Self::Center => Self::Top,
1060 Self::Top => Self::Bottom,
1061 Self::Bottom => Self::Center,
1062 }
1063 }
1064}
1065
1066#[derive(Clone)]
1067pub struct EditorSnapshot {
1068 pub mode: EditorMode,
1069 show_gutter: bool,
1070 show_line_numbers: Option<bool>,
1071 show_git_diff_gutter: Option<bool>,
1072 show_runnables: Option<bool>,
1073 show_breakpoints: Option<bool>,
1074 git_blame_gutter_max_author_length: Option<usize>,
1075 pub display_snapshot: DisplaySnapshot,
1076 pub placeholder_text: Option<Arc<str>>,
1077 is_focused: bool,
1078 scroll_anchor: ScrollAnchor,
1079 ongoing_scroll: OngoingScroll,
1080 current_line_highlight: CurrentLineHighlight,
1081 gutter_hovered: bool,
1082}
1083
1084#[derive(Default, Debug, Clone, Copy)]
1085pub struct GutterDimensions {
1086 pub left_padding: Pixels,
1087 pub right_padding: Pixels,
1088 pub width: Pixels,
1089 pub margin: Pixels,
1090 pub git_blame_entries_width: Option<Pixels>,
1091}
1092
1093impl GutterDimensions {
1094 fn default_with_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Self {
1095 Self {
1096 margin: Self::default_gutter_margin(font_id, font_size, cx),
1097 ..Default::default()
1098 }
1099 }
1100
1101 fn default_gutter_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Pixels {
1102 -cx.text_system().descent(font_id, font_size)
1103 }
1104 /// The full width of the space taken up by the gutter.
1105 pub fn full_width(&self) -> Pixels {
1106 self.margin + self.width
1107 }
1108
1109 /// The width of the space reserved for the fold indicators,
1110 /// use alongside 'justify_end' and `gutter_width` to
1111 /// right align content with the line numbers
1112 pub fn fold_area_width(&self) -> Pixels {
1113 self.margin + self.right_padding
1114 }
1115}
1116
1117#[derive(Debug)]
1118pub struct RemoteSelection {
1119 pub replica_id: ReplicaId,
1120 pub selection: Selection<Anchor>,
1121 pub cursor_shape: CursorShape,
1122 pub collaborator_id: CollaboratorId,
1123 pub line_mode: bool,
1124 pub user_name: Option<SharedString>,
1125 pub color: PlayerColor,
1126}
1127
1128#[derive(Clone, Debug)]
1129struct SelectionHistoryEntry {
1130 selections: Arc<[Selection<Anchor>]>,
1131 select_next_state: Option<SelectNextState>,
1132 select_prev_state: Option<SelectNextState>,
1133 add_selections_state: Option<AddSelectionsState>,
1134}
1135
1136enum SelectionHistoryMode {
1137 Normal,
1138 Undoing,
1139 Redoing,
1140}
1141
1142#[derive(Clone, PartialEq, Eq, Hash)]
1143struct HoveredCursor {
1144 replica_id: u16,
1145 selection_id: usize,
1146}
1147
1148impl Default for SelectionHistoryMode {
1149 fn default() -> Self {
1150 Self::Normal
1151 }
1152}
1153
1154#[derive(Default)]
1155struct SelectionHistory {
1156 #[allow(clippy::type_complexity)]
1157 selections_by_transaction:
1158 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1159 mode: SelectionHistoryMode,
1160 undo_stack: VecDeque<SelectionHistoryEntry>,
1161 redo_stack: VecDeque<SelectionHistoryEntry>,
1162}
1163
1164impl SelectionHistory {
1165 fn insert_transaction(
1166 &mut self,
1167 transaction_id: TransactionId,
1168 selections: Arc<[Selection<Anchor>]>,
1169 ) {
1170 self.selections_by_transaction
1171 .insert(transaction_id, (selections, None));
1172 }
1173
1174 #[allow(clippy::type_complexity)]
1175 fn transaction(
1176 &self,
1177 transaction_id: TransactionId,
1178 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1179 self.selections_by_transaction.get(&transaction_id)
1180 }
1181
1182 #[allow(clippy::type_complexity)]
1183 fn transaction_mut(
1184 &mut self,
1185 transaction_id: TransactionId,
1186 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1187 self.selections_by_transaction.get_mut(&transaction_id)
1188 }
1189
1190 fn push(&mut self, entry: SelectionHistoryEntry) {
1191 if !entry.selections.is_empty() {
1192 match self.mode {
1193 SelectionHistoryMode::Normal => {
1194 self.push_undo(entry);
1195 self.redo_stack.clear();
1196 }
1197 SelectionHistoryMode::Undoing => self.push_redo(entry),
1198 SelectionHistoryMode::Redoing => self.push_undo(entry),
1199 }
1200 }
1201 }
1202
1203 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1204 if self
1205 .undo_stack
1206 .back()
1207 .map_or(true, |e| e.selections != entry.selections)
1208 {
1209 self.undo_stack.push_back(entry);
1210 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1211 self.undo_stack.pop_front();
1212 }
1213 }
1214 }
1215
1216 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1217 if self
1218 .redo_stack
1219 .back()
1220 .map_or(true, |e| e.selections != entry.selections)
1221 {
1222 self.redo_stack.push_back(entry);
1223 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1224 self.redo_stack.pop_front();
1225 }
1226 }
1227 }
1228}
1229
1230#[derive(Clone, Copy)]
1231pub struct RowHighlightOptions {
1232 pub autoscroll: bool,
1233 pub include_gutter: bool,
1234}
1235
1236impl Default for RowHighlightOptions {
1237 fn default() -> Self {
1238 Self {
1239 autoscroll: Default::default(),
1240 include_gutter: true,
1241 }
1242 }
1243}
1244
1245struct RowHighlight {
1246 index: usize,
1247 range: Range<Anchor>,
1248 color: Hsla,
1249 options: RowHighlightOptions,
1250 type_id: TypeId,
1251}
1252
1253#[derive(Clone, Debug)]
1254struct AddSelectionsState {
1255 above: bool,
1256 stack: Vec<usize>,
1257}
1258
1259#[derive(Clone)]
1260struct SelectNextState {
1261 query: AhoCorasick,
1262 wordwise: bool,
1263 done: bool,
1264}
1265
1266impl std::fmt::Debug for SelectNextState {
1267 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1268 f.debug_struct(std::any::type_name::<Self>())
1269 .field("wordwise", &self.wordwise)
1270 .field("done", &self.done)
1271 .finish()
1272 }
1273}
1274
1275#[derive(Debug)]
1276struct AutocloseRegion {
1277 selection_id: usize,
1278 range: Range<Anchor>,
1279 pair: BracketPair,
1280}
1281
1282#[derive(Debug)]
1283struct SnippetState {
1284 ranges: Vec<Vec<Range<Anchor>>>,
1285 active_index: usize,
1286 choices: Vec<Option<Vec<String>>>,
1287}
1288
1289#[doc(hidden)]
1290pub struct RenameState {
1291 pub range: Range<Anchor>,
1292 pub old_name: Arc<str>,
1293 pub editor: Entity<Editor>,
1294 block_id: CustomBlockId,
1295}
1296
1297struct InvalidationStack<T>(Vec<T>);
1298
1299struct RegisteredInlineCompletionProvider {
1300 provider: Arc<dyn InlineCompletionProviderHandle>,
1301 _subscription: Subscription,
1302}
1303
1304#[derive(Debug, PartialEq, Eq)]
1305pub struct ActiveDiagnosticGroup {
1306 pub active_range: Range<Anchor>,
1307 pub active_message: String,
1308 pub group_id: usize,
1309 pub blocks: HashSet<CustomBlockId>,
1310}
1311
1312#[derive(Debug, PartialEq, Eq)]
1313#[allow(clippy::large_enum_variant)]
1314pub(crate) enum ActiveDiagnostic {
1315 None,
1316 All,
1317 Group(ActiveDiagnosticGroup),
1318}
1319
1320#[derive(Serialize, Deserialize, Clone, Debug)]
1321pub struct ClipboardSelection {
1322 /// The number of bytes in this selection.
1323 pub len: usize,
1324 /// Whether this was a full-line selection.
1325 pub is_entire_line: bool,
1326 /// The indentation of the first line when this content was originally copied.
1327 pub first_line_indent: u32,
1328}
1329
1330// selections, scroll behavior, was newest selection reversed
1331type SelectSyntaxNodeHistoryState = (
1332 Box<[Selection<usize>]>,
1333 SelectSyntaxNodeScrollBehavior,
1334 bool,
1335);
1336
1337#[derive(Default)]
1338struct SelectSyntaxNodeHistory {
1339 stack: Vec<SelectSyntaxNodeHistoryState>,
1340 // disable temporarily to allow changing selections without losing the stack
1341 pub disable_clearing: bool,
1342}
1343
1344impl SelectSyntaxNodeHistory {
1345 pub fn try_clear(&mut self) {
1346 if !self.disable_clearing {
1347 self.stack.clear();
1348 }
1349 }
1350
1351 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1352 self.stack.push(selection);
1353 }
1354
1355 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1356 self.stack.pop()
1357 }
1358}
1359
1360enum SelectSyntaxNodeScrollBehavior {
1361 CursorTop,
1362 FitSelection,
1363 CursorBottom,
1364}
1365
1366#[derive(Debug)]
1367pub(crate) struct NavigationData {
1368 cursor_anchor: Anchor,
1369 cursor_position: Point,
1370 scroll_anchor: ScrollAnchor,
1371 scroll_top_row: u32,
1372}
1373
1374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1375pub enum GotoDefinitionKind {
1376 Symbol,
1377 Declaration,
1378 Type,
1379 Implementation,
1380}
1381
1382#[derive(Debug, Clone)]
1383enum InlayHintRefreshReason {
1384 ModifiersChanged(bool),
1385 Toggle(bool),
1386 SettingsChange(InlayHintSettings),
1387 NewLinesShown,
1388 BufferEdited(HashSet<Arc<Language>>),
1389 RefreshRequested,
1390 ExcerptsRemoved(Vec<ExcerptId>),
1391}
1392
1393impl InlayHintRefreshReason {
1394 fn description(&self) -> &'static str {
1395 match self {
1396 Self::ModifiersChanged(_) => "modifiers changed",
1397 Self::Toggle(_) => "toggle",
1398 Self::SettingsChange(_) => "settings change",
1399 Self::NewLinesShown => "new lines shown",
1400 Self::BufferEdited(_) => "buffer edited",
1401 Self::RefreshRequested => "refresh requested",
1402 Self::ExcerptsRemoved(_) => "excerpts removed",
1403 }
1404 }
1405}
1406
1407pub enum FormatTarget {
1408 Buffers,
1409 Ranges(Vec<Range<MultiBufferPoint>>),
1410}
1411
1412pub(crate) struct FocusedBlock {
1413 id: BlockId,
1414 focus_handle: WeakFocusHandle,
1415}
1416
1417#[derive(Clone)]
1418enum JumpData {
1419 MultiBufferRow {
1420 row: MultiBufferRow,
1421 line_offset_from_top: u32,
1422 },
1423 MultiBufferPoint {
1424 excerpt_id: ExcerptId,
1425 position: Point,
1426 anchor: text::Anchor,
1427 line_offset_from_top: u32,
1428 },
1429}
1430
1431pub enum MultibufferSelectionMode {
1432 First,
1433 All,
1434}
1435
1436#[derive(Clone, Copy, Debug, Default)]
1437pub struct RewrapOptions {
1438 pub override_language_settings: bool,
1439 pub preserve_existing_whitespace: bool,
1440}
1441
1442impl Editor {
1443 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1444 let buffer = cx.new(|cx| Buffer::local("", cx));
1445 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1446 Self::new(
1447 EditorMode::SingleLine { auto_width: false },
1448 buffer,
1449 None,
1450 window,
1451 cx,
1452 )
1453 }
1454
1455 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1456 let buffer = cx.new(|cx| Buffer::local("", cx));
1457 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1458 Self::new(EditorMode::full(), buffer, None, window, cx)
1459 }
1460
1461 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1462 let buffer = cx.new(|cx| Buffer::local("", cx));
1463 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1464 Self::new(
1465 EditorMode::SingleLine { auto_width: true },
1466 buffer,
1467 None,
1468 window,
1469 cx,
1470 )
1471 }
1472
1473 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1474 let buffer = cx.new(|cx| Buffer::local("", cx));
1475 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1476 Self::new(
1477 EditorMode::AutoHeight { max_lines },
1478 buffer,
1479 None,
1480 window,
1481 cx,
1482 )
1483 }
1484
1485 pub fn for_buffer(
1486 buffer: Entity<Buffer>,
1487 project: Option<Entity<Project>>,
1488 window: &mut Window,
1489 cx: &mut Context<Self>,
1490 ) -> Self {
1491 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1492 Self::new(EditorMode::full(), buffer, project, window, cx)
1493 }
1494
1495 pub fn for_multibuffer(
1496 buffer: Entity<MultiBuffer>,
1497 project: Option<Entity<Project>>,
1498 window: &mut Window,
1499 cx: &mut Context<Self>,
1500 ) -> Self {
1501 Self::new(EditorMode::full(), buffer, project, window, cx)
1502 }
1503
1504 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1505 let mut clone = Self::new(
1506 self.mode.clone(),
1507 self.buffer.clone(),
1508 self.project.clone(),
1509 window,
1510 cx,
1511 );
1512 self.display_map.update(cx, |display_map, cx| {
1513 let snapshot = display_map.snapshot(cx);
1514 clone.display_map.update(cx, |display_map, cx| {
1515 display_map.set_state(&snapshot, cx);
1516 });
1517 });
1518 clone.folds_did_change(cx);
1519 clone.selections.clone_state(&self.selections);
1520 clone.scroll_manager.clone_state(&self.scroll_manager);
1521 clone.searchable = self.searchable;
1522 clone.read_only = self.read_only;
1523 clone
1524 }
1525
1526 pub fn new(
1527 mode: EditorMode,
1528 buffer: Entity<MultiBuffer>,
1529 project: Option<Entity<Project>>,
1530 window: &mut Window,
1531 cx: &mut Context<Self>,
1532 ) -> Self {
1533 Editor::new_internal(mode, buffer, project, None, window, cx)
1534 }
1535
1536 fn new_internal(
1537 mode: EditorMode,
1538 buffer: Entity<MultiBuffer>,
1539 project: Option<Entity<Project>>,
1540 display_map: Option<Entity<DisplayMap>>,
1541 window: &mut Window,
1542 cx: &mut Context<Self>,
1543 ) -> Self {
1544 debug_assert!(
1545 display_map.is_none() || mode.is_minimap(),
1546 "Providing a display map for a new editor is only intended for the minimap and might have unindended side effects otherwise!"
1547 );
1548
1549 let full_mode = mode.is_full();
1550 let diagnostics_max_severity = if full_mode {
1551 EditorSettings::get_global(cx)
1552 .diagnostics_max_severity
1553 .unwrap_or(DiagnosticSeverity::Hint)
1554 } else {
1555 DiagnosticSeverity::Off
1556 };
1557 let style = window.text_style();
1558 let font_size = style.font_size.to_pixels(window.rem_size());
1559 let editor = cx.entity().downgrade();
1560 let fold_placeholder = FoldPlaceholder {
1561 constrain_width: true,
1562 render: Arc::new(move |fold_id, fold_range, cx| {
1563 let editor = editor.clone();
1564 div()
1565 .id(fold_id)
1566 .bg(cx.theme().colors().ghost_element_background)
1567 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1568 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1569 .rounded_xs()
1570 .size_full()
1571 .cursor_pointer()
1572 .child("⋯")
1573 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1574 .on_click(move |_, _window, cx| {
1575 editor
1576 .update(cx, |editor, cx| {
1577 editor.unfold_ranges(
1578 &[fold_range.start..fold_range.end],
1579 true,
1580 false,
1581 cx,
1582 );
1583 cx.stop_propagation();
1584 })
1585 .ok();
1586 })
1587 .into_any()
1588 }),
1589 merge_adjacent: true,
1590 ..FoldPlaceholder::default()
1591 };
1592 let display_map = display_map.unwrap_or_else(|| {
1593 cx.new(|cx| {
1594 DisplayMap::new(
1595 buffer.clone(),
1596 style.font(),
1597 font_size,
1598 None,
1599 FILE_HEADER_HEIGHT,
1600 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1601 fold_placeholder,
1602 diagnostics_max_severity,
1603 cx,
1604 )
1605 })
1606 });
1607
1608 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1609
1610 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1611
1612 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1613 .then(|| language_settings::SoftWrap::None);
1614
1615 let mut project_subscriptions = Vec::new();
1616 if mode.is_full() {
1617 if let Some(project) = project.as_ref() {
1618 project_subscriptions.push(cx.subscribe_in(
1619 project,
1620 window,
1621 |editor, _, event, window, cx| match event {
1622 project::Event::RefreshCodeLens => {
1623 // we always query lens with actions, without storing them, always refreshing them
1624 }
1625 project::Event::RefreshInlayHints => {
1626 editor
1627 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1628 }
1629 project::Event::SnippetEdit(id, snippet_edits) => {
1630 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1631 let focus_handle = editor.focus_handle(cx);
1632 if focus_handle.is_focused(window) {
1633 let snapshot = buffer.read(cx).snapshot();
1634 for (range, snippet) in snippet_edits {
1635 let editor_range =
1636 language::range_from_lsp(*range).to_offset(&snapshot);
1637 editor
1638 .insert_snippet(
1639 &[editor_range],
1640 snippet.clone(),
1641 window,
1642 cx,
1643 )
1644 .ok();
1645 }
1646 }
1647 }
1648 }
1649 _ => {}
1650 },
1651 ));
1652 if let Some(task_inventory) = project
1653 .read(cx)
1654 .task_store()
1655 .read(cx)
1656 .task_inventory()
1657 .cloned()
1658 {
1659 project_subscriptions.push(cx.observe_in(
1660 &task_inventory,
1661 window,
1662 |editor, _, window, cx| {
1663 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1664 },
1665 ));
1666 };
1667
1668 project_subscriptions.push(cx.subscribe_in(
1669 &project.read(cx).breakpoint_store(),
1670 window,
1671 |editor, _, event, window, cx| match event {
1672 BreakpointStoreEvent::ClearDebugLines => {
1673 editor.clear_row_highlights::<ActiveDebugLine>();
1674 editor.refresh_inline_values(cx);
1675 }
1676 BreakpointStoreEvent::SetDebugLine => {
1677 if editor.go_to_active_debug_line(window, cx) {
1678 cx.stop_propagation();
1679 }
1680
1681 editor.refresh_inline_values(cx);
1682 }
1683 _ => {}
1684 },
1685 ));
1686 }
1687 }
1688
1689 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1690
1691 let inlay_hint_settings =
1692 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1693 let focus_handle = cx.focus_handle();
1694 cx.on_focus(&focus_handle, window, Self::handle_focus)
1695 .detach();
1696 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1697 .detach();
1698 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1699 .detach();
1700 cx.on_blur(&focus_handle, window, Self::handle_blur)
1701 .detach();
1702
1703 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1704 Some(false)
1705 } else {
1706 None
1707 };
1708
1709 let breakpoint_store = match (&mode, project.as_ref()) {
1710 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1711 _ => None,
1712 };
1713
1714 let mut code_action_providers = Vec::new();
1715 let mut load_uncommitted_diff = None;
1716 if let Some(project) = project.clone() {
1717 load_uncommitted_diff = Some(
1718 update_uncommitted_diff_for_buffer(
1719 cx.entity(),
1720 &project,
1721 buffer.read(cx).all_buffers(),
1722 buffer.clone(),
1723 cx,
1724 )
1725 .shared(),
1726 );
1727 code_action_providers.push(Rc::new(project) as Rc<_>);
1728 }
1729
1730 let mut this = Self {
1731 focus_handle,
1732 show_cursor_when_unfocused: false,
1733 last_focused_descendant: None,
1734 buffer: buffer.clone(),
1735 display_map: display_map.clone(),
1736 selections,
1737 scroll_manager: ScrollManager::new(cx),
1738 columnar_selection_tail: None,
1739 add_selections_state: None,
1740 select_next_state: None,
1741 select_prev_state: None,
1742 selection_history: SelectionHistory::default(),
1743 autoclose_regions: Vec::new(),
1744 snippet_stack: InvalidationStack::default(),
1745 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1746 ime_transaction: None,
1747 active_diagnostics: ActiveDiagnostic::None,
1748 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1749 inline_diagnostics_update: Task::ready(()),
1750 inline_diagnostics: Vec::new(),
1751 soft_wrap_mode_override,
1752 diagnostics_max_severity,
1753 hard_wrap: None,
1754 completion_provider: project.clone().map(|project| Box::new(project) as _),
1755 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1756 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1757 project,
1758 blink_manager: blink_manager.clone(),
1759 show_local_selections: true,
1760 show_scrollbars: full_mode,
1761 minimap_visibility: MinimapVisibility::for_mode(&mode, cx),
1762 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1763 show_gutter: mode.is_full(),
1764 show_line_numbers: None,
1765 use_relative_line_numbers: None,
1766 disable_expand_excerpt_buttons: false,
1767 show_git_diff_gutter: None,
1768 show_code_actions: None,
1769 show_runnables: None,
1770 show_breakpoints: None,
1771 show_wrap_guides: None,
1772 show_indent_guides,
1773 placeholder_text: None,
1774 highlight_order: 0,
1775 highlighted_rows: HashMap::default(),
1776 background_highlights: TreeMap::default(),
1777 gutter_highlights: TreeMap::default(),
1778 scrollbar_marker_state: ScrollbarMarkerState::default(),
1779 active_indent_guides_state: ActiveIndentGuidesState::default(),
1780 nav_history: None,
1781 context_menu: RefCell::new(None),
1782 context_menu_options: None,
1783 mouse_context_menu: None,
1784 completion_tasks: Vec::new(),
1785 inline_blame_popover: None,
1786 signature_help_state: SignatureHelpState::default(),
1787 auto_signature_help: None,
1788 find_all_references_task_sources: Vec::new(),
1789 next_completion_id: 0,
1790 next_inlay_id: 0,
1791 code_action_providers,
1792 available_code_actions: None,
1793 code_actions_task: None,
1794 quick_selection_highlight_task: None,
1795 debounced_selection_highlight_task: None,
1796 document_highlights_task: None,
1797 linked_editing_range_task: None,
1798 pending_rename: None,
1799 searchable: true,
1800 cursor_shape: EditorSettings::get_global(cx)
1801 .cursor_shape
1802 .unwrap_or_default(),
1803 current_line_highlight: None,
1804 autoindent_mode: Some(AutoindentMode::EachLine),
1805 collapse_matches: false,
1806 workspace: None,
1807 input_enabled: true,
1808 use_modal_editing: mode.is_full(),
1809 read_only: mode.is_minimap(),
1810 use_autoclose: true,
1811 use_auto_surround: true,
1812 auto_replace_emoji_shortcode: false,
1813 jsx_tag_auto_close_enabled_in_any_buffer: false,
1814 leader_id: None,
1815 remote_id: None,
1816 hover_state: HoverState::default(),
1817 pending_mouse_down: None,
1818 hovered_link_state: None,
1819 edit_prediction_provider: None,
1820 active_inline_completion: None,
1821 stale_inline_completion_in_menu: None,
1822 edit_prediction_preview: EditPredictionPreview::Inactive {
1823 released_too_fast: false,
1824 },
1825 inline_diagnostics_enabled: mode.is_full(),
1826 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1827 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1828
1829 gutter_hovered: false,
1830 pixel_position_of_newest_cursor: None,
1831 last_bounds: None,
1832 last_position_map: None,
1833 expect_bounds_change: None,
1834 gutter_dimensions: GutterDimensions::default(),
1835 style: None,
1836 show_cursor_names: false,
1837 hovered_cursors: HashMap::default(),
1838 next_editor_action_id: EditorActionId::default(),
1839 editor_actions: Rc::default(),
1840 inline_completions_hidden_for_vim_mode: false,
1841 show_inline_completions_override: None,
1842 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1843 edit_prediction_settings: EditPredictionSettings::Disabled,
1844 edit_prediction_indent_conflict: false,
1845 edit_prediction_requires_modifier_in_indent_conflict: true,
1846 custom_context_menu: None,
1847 show_git_blame_gutter: false,
1848 show_git_blame_inline: false,
1849 show_selection_menu: None,
1850 show_git_blame_inline_delay_task: None,
1851 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1852 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1853 serialize_dirty_buffers: !mode.is_minimap()
1854 && ProjectSettings::get_global(cx)
1855 .session
1856 .restore_unsaved_buffers,
1857 blame: None,
1858 blame_subscription: None,
1859 tasks: BTreeMap::default(),
1860
1861 breakpoint_store,
1862 gutter_breakpoint_indicator: (None, None),
1863 _subscriptions: vec![
1864 cx.observe(&buffer, Self::on_buffer_changed),
1865 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1866 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1867 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1868 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1869 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1870 cx.observe_window_activation(window, |editor, window, cx| {
1871 let active = window.is_window_active();
1872 editor.blink_manager.update(cx, |blink_manager, cx| {
1873 if active {
1874 blink_manager.enable(cx);
1875 } else {
1876 blink_manager.disable(cx);
1877 }
1878 });
1879 }),
1880 ],
1881 tasks_update_task: None,
1882 linked_edit_ranges: Default::default(),
1883 in_project_search: false,
1884 previous_search_ranges: None,
1885 breadcrumb_header: None,
1886 focused_block: None,
1887 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1888 addons: HashMap::default(),
1889 registered_buffers: HashMap::default(),
1890 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1891 selection_mark_mode: false,
1892 toggle_fold_multiple_buffers: Task::ready(()),
1893 serialize_selections: Task::ready(()),
1894 serialize_folds: Task::ready(()),
1895 text_style_refinement: None,
1896 load_diff_task: load_uncommitted_diff,
1897 temporary_diff_override: false,
1898 mouse_cursor_hidden: false,
1899 minimap: None,
1900 hide_mouse_mode: EditorSettings::get_global(cx)
1901 .hide_mouse
1902 .unwrap_or_default(),
1903 change_list: ChangeList::new(),
1904 mode,
1905 };
1906 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1907 this._subscriptions
1908 .push(cx.observe(breakpoints, |_, _, cx| {
1909 cx.notify();
1910 }));
1911 }
1912 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1913 this._subscriptions.extend(project_subscriptions);
1914
1915 this._subscriptions.push(cx.subscribe_in(
1916 &cx.entity(),
1917 window,
1918 |editor, _, e: &EditorEvent, window, cx| match e {
1919 EditorEvent::ScrollPositionChanged { local, .. } => {
1920 if *local {
1921 let new_anchor = editor.scroll_manager.anchor();
1922 let snapshot = editor.snapshot(window, cx);
1923 editor.update_restoration_data(cx, move |data| {
1924 data.scroll_position = (
1925 new_anchor.top_row(&snapshot.buffer_snapshot),
1926 new_anchor.offset,
1927 );
1928 });
1929 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1930 editor.inline_blame_popover.take();
1931 }
1932 }
1933 EditorEvent::Edited { .. } => {
1934 if !vim_enabled(cx) {
1935 let (map, selections) = editor.selections.all_adjusted_display(cx);
1936 let pop_state = editor
1937 .change_list
1938 .last()
1939 .map(|previous| {
1940 previous.len() == selections.len()
1941 && previous.iter().enumerate().all(|(ix, p)| {
1942 p.to_display_point(&map).row()
1943 == selections[ix].head().row()
1944 })
1945 })
1946 .unwrap_or(false);
1947 let new_positions = selections
1948 .into_iter()
1949 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1950 .collect();
1951 editor
1952 .change_list
1953 .push_to_change_list(pop_state, new_positions);
1954 }
1955 }
1956 _ => (),
1957 },
1958 ));
1959
1960 if let Some(dap_store) = this
1961 .project
1962 .as_ref()
1963 .map(|project| project.read(cx).dap_store())
1964 {
1965 let weak_editor = cx.weak_entity();
1966
1967 this._subscriptions
1968 .push(
1969 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1970 let session_entity = cx.entity();
1971 weak_editor
1972 .update(cx, |editor, cx| {
1973 editor._subscriptions.push(
1974 cx.subscribe(&session_entity, Self::on_debug_session_event),
1975 );
1976 })
1977 .ok();
1978 }),
1979 );
1980
1981 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1982 this._subscriptions
1983 .push(cx.subscribe(&session, Self::on_debug_session_event));
1984 }
1985 }
1986
1987 this.end_selection(window, cx);
1988 this.scroll_manager.show_scrollbars(window, cx);
1989 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1990
1991 if full_mode {
1992 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1993 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1994
1995 if this.git_blame_inline_enabled {
1996 this.start_git_blame_inline(false, window, cx);
1997 }
1998
1999 this.go_to_active_debug_line(window, cx);
2000
2001 if let Some(buffer) = buffer.read(cx).as_singleton() {
2002 if let Some(project) = this.project.as_ref() {
2003 let handle = project.update(cx, |project, cx| {
2004 project.register_buffer_with_language_servers(&buffer, cx)
2005 });
2006 this.registered_buffers
2007 .insert(buffer.read(cx).remote_id(), handle);
2008 }
2009 }
2010
2011 this.minimap = this.create_minimap(EditorSettings::get_global(cx).minimap, window, cx);
2012 }
2013
2014 this.report_editor_event("Editor Opened", None, cx);
2015 this
2016 }
2017
2018 pub fn deploy_mouse_context_menu(
2019 &mut self,
2020 position: gpui::Point<Pixels>,
2021 context_menu: Entity<ContextMenu>,
2022 window: &mut Window,
2023 cx: &mut Context<Self>,
2024 ) {
2025 self.mouse_context_menu = Some(MouseContextMenu::new(
2026 self,
2027 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
2028 context_menu,
2029 window,
2030 cx,
2031 ));
2032 }
2033
2034 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
2035 self.mouse_context_menu
2036 .as_ref()
2037 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
2038 }
2039
2040 pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
2041 self.key_context_internal(self.has_active_inline_completion(), window, cx)
2042 }
2043
2044 fn key_context_internal(
2045 &self,
2046 has_active_edit_prediction: bool,
2047 window: &Window,
2048 cx: &App,
2049 ) -> KeyContext {
2050 let mut key_context = KeyContext::new_with_defaults();
2051 key_context.add("Editor");
2052 let mode = match self.mode {
2053 EditorMode::SingleLine { .. } => "single_line",
2054 EditorMode::AutoHeight { .. } => "auto_height",
2055 EditorMode::Minimap { .. } => "minimap",
2056 EditorMode::Full { .. } => "full",
2057 };
2058
2059 if EditorSettings::jupyter_enabled(cx) {
2060 key_context.add("jupyter");
2061 }
2062
2063 key_context.set("mode", mode);
2064 if self.pending_rename.is_some() {
2065 key_context.add("renaming");
2066 }
2067
2068 match self.context_menu.borrow().as_ref() {
2069 Some(CodeContextMenu::Completions(_)) => {
2070 key_context.add("menu");
2071 key_context.add("showing_completions");
2072 }
2073 Some(CodeContextMenu::CodeActions(_)) => {
2074 key_context.add("menu");
2075 key_context.add("showing_code_actions")
2076 }
2077 None => {}
2078 }
2079
2080 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2081 if !self.focus_handle(cx).contains_focused(window, cx)
2082 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
2083 {
2084 for addon in self.addons.values() {
2085 addon.extend_key_context(&mut key_context, cx)
2086 }
2087 }
2088
2089 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
2090 if let Some(extension) = singleton_buffer
2091 .read(cx)
2092 .file()
2093 .and_then(|file| file.path().extension()?.to_str())
2094 {
2095 key_context.set("extension", extension.to_string());
2096 }
2097 } else {
2098 key_context.add("multibuffer");
2099 }
2100
2101 if has_active_edit_prediction {
2102 if self.edit_prediction_in_conflict() {
2103 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
2104 } else {
2105 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
2106 key_context.add("copilot_suggestion");
2107 }
2108 }
2109
2110 if self.selection_mark_mode {
2111 key_context.add("selection_mode");
2112 }
2113
2114 key_context
2115 }
2116
2117 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
2118 self.mouse_cursor_hidden = match origin {
2119 HideMouseCursorOrigin::TypingAction => {
2120 matches!(
2121 self.hide_mouse_mode,
2122 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
2123 )
2124 }
2125 HideMouseCursorOrigin::MovementAction => {
2126 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
2127 }
2128 };
2129 }
2130
2131 pub fn edit_prediction_in_conflict(&self) -> bool {
2132 if !self.show_edit_predictions_in_menu() {
2133 return false;
2134 }
2135
2136 let showing_completions = self
2137 .context_menu
2138 .borrow()
2139 .as_ref()
2140 .map_or(false, |context| {
2141 matches!(context, CodeContextMenu::Completions(_))
2142 });
2143
2144 showing_completions
2145 || self.edit_prediction_requires_modifier()
2146 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2147 // bindings to insert tab characters.
2148 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2149 }
2150
2151 pub fn accept_edit_prediction_keybind(
2152 &self,
2153 window: &Window,
2154 cx: &App,
2155 ) -> AcceptEditPredictionBinding {
2156 let key_context = self.key_context_internal(true, window, cx);
2157 let in_conflict = self.edit_prediction_in_conflict();
2158
2159 AcceptEditPredictionBinding(
2160 window
2161 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2162 .into_iter()
2163 .filter(|binding| {
2164 !in_conflict
2165 || binding
2166 .keystrokes()
2167 .first()
2168 .map_or(false, |keystroke| keystroke.modifiers.modified())
2169 })
2170 .rev()
2171 .min_by_key(|binding| {
2172 binding
2173 .keystrokes()
2174 .first()
2175 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2176 }),
2177 )
2178 }
2179
2180 pub fn new_file(
2181 workspace: &mut Workspace,
2182 _: &workspace::NewFile,
2183 window: &mut Window,
2184 cx: &mut Context<Workspace>,
2185 ) {
2186 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2187 "Failed to create buffer",
2188 window,
2189 cx,
2190 |e, _, _| match e.error_code() {
2191 ErrorCode::RemoteUpgradeRequired => Some(format!(
2192 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2193 e.error_tag("required").unwrap_or("the latest version")
2194 )),
2195 _ => None,
2196 },
2197 );
2198 }
2199
2200 pub fn new_in_workspace(
2201 workspace: &mut Workspace,
2202 window: &mut Window,
2203 cx: &mut Context<Workspace>,
2204 ) -> Task<Result<Entity<Editor>>> {
2205 let project = workspace.project().clone();
2206 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2207
2208 cx.spawn_in(window, async move |workspace, cx| {
2209 let buffer = create.await?;
2210 workspace.update_in(cx, |workspace, window, cx| {
2211 let editor =
2212 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2213 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2214 editor
2215 })
2216 })
2217 }
2218
2219 fn new_file_vertical(
2220 workspace: &mut Workspace,
2221 _: &workspace::NewFileSplitVertical,
2222 window: &mut Window,
2223 cx: &mut Context<Workspace>,
2224 ) {
2225 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2226 }
2227
2228 fn new_file_horizontal(
2229 workspace: &mut Workspace,
2230 _: &workspace::NewFileSplitHorizontal,
2231 window: &mut Window,
2232 cx: &mut Context<Workspace>,
2233 ) {
2234 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2235 }
2236
2237 fn new_file_in_direction(
2238 workspace: &mut Workspace,
2239 direction: SplitDirection,
2240 window: &mut Window,
2241 cx: &mut Context<Workspace>,
2242 ) {
2243 let project = workspace.project().clone();
2244 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2245
2246 cx.spawn_in(window, async move |workspace, cx| {
2247 let buffer = create.await?;
2248 workspace.update_in(cx, move |workspace, window, cx| {
2249 workspace.split_item(
2250 direction,
2251 Box::new(
2252 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2253 ),
2254 window,
2255 cx,
2256 )
2257 })?;
2258 anyhow::Ok(())
2259 })
2260 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2261 match e.error_code() {
2262 ErrorCode::RemoteUpgradeRequired => Some(format!(
2263 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2264 e.error_tag("required").unwrap_or("the latest version")
2265 )),
2266 _ => None,
2267 }
2268 });
2269 }
2270
2271 pub fn leader_id(&self) -> Option<CollaboratorId> {
2272 self.leader_id
2273 }
2274
2275 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2276 &self.buffer
2277 }
2278
2279 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2280 self.workspace.as_ref()?.0.upgrade()
2281 }
2282
2283 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2284 self.buffer().read(cx).title(cx)
2285 }
2286
2287 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2288 let git_blame_gutter_max_author_length = self
2289 .render_git_blame_gutter(cx)
2290 .then(|| {
2291 if let Some(blame) = self.blame.as_ref() {
2292 let max_author_length =
2293 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2294 Some(max_author_length)
2295 } else {
2296 None
2297 }
2298 })
2299 .flatten();
2300
2301 EditorSnapshot {
2302 mode: self.mode.clone(),
2303 show_gutter: self.show_gutter,
2304 show_line_numbers: self.show_line_numbers,
2305 show_git_diff_gutter: self.show_git_diff_gutter,
2306 show_runnables: self.show_runnables,
2307 show_breakpoints: self.show_breakpoints,
2308 git_blame_gutter_max_author_length,
2309 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2310 scroll_anchor: self.scroll_manager.anchor(),
2311 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2312 placeholder_text: self.placeholder_text.clone(),
2313 is_focused: self.focus_handle.is_focused(window),
2314 current_line_highlight: self
2315 .current_line_highlight
2316 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2317 gutter_hovered: self.gutter_hovered,
2318 }
2319 }
2320
2321 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2322 self.buffer.read(cx).language_at(point, cx)
2323 }
2324
2325 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2326 self.buffer.read(cx).read(cx).file_at(point).cloned()
2327 }
2328
2329 pub fn active_excerpt(
2330 &self,
2331 cx: &App,
2332 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2333 self.buffer
2334 .read(cx)
2335 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2336 }
2337
2338 pub fn mode(&self) -> &EditorMode {
2339 &self.mode
2340 }
2341
2342 pub fn set_mode(&mut self, mode: EditorMode) {
2343 self.mode = mode;
2344 }
2345
2346 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2347 self.collaboration_hub.as_deref()
2348 }
2349
2350 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2351 self.collaboration_hub = Some(hub);
2352 }
2353
2354 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2355 self.in_project_search = in_project_search;
2356 }
2357
2358 pub fn set_custom_context_menu(
2359 &mut self,
2360 f: impl 'static
2361 + Fn(
2362 &mut Self,
2363 DisplayPoint,
2364 &mut Window,
2365 &mut Context<Self>,
2366 ) -> Option<Entity<ui::ContextMenu>>,
2367 ) {
2368 self.custom_context_menu = Some(Box::new(f))
2369 }
2370
2371 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2372 self.completion_provider = provider;
2373 }
2374
2375 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2376 self.semantics_provider.clone()
2377 }
2378
2379 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2380 self.semantics_provider = provider;
2381 }
2382
2383 pub fn set_edit_prediction_provider<T>(
2384 &mut self,
2385 provider: Option<Entity<T>>,
2386 window: &mut Window,
2387 cx: &mut Context<Self>,
2388 ) where
2389 T: EditPredictionProvider,
2390 {
2391 self.edit_prediction_provider =
2392 provider.map(|provider| RegisteredInlineCompletionProvider {
2393 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2394 if this.focus_handle.is_focused(window) {
2395 this.update_visible_inline_completion(window, cx);
2396 }
2397 }),
2398 provider: Arc::new(provider),
2399 });
2400 self.update_edit_prediction_settings(cx);
2401 self.refresh_inline_completion(false, false, window, cx);
2402 }
2403
2404 pub fn placeholder_text(&self) -> Option<&str> {
2405 self.placeholder_text.as_deref()
2406 }
2407
2408 pub fn set_placeholder_text(
2409 &mut self,
2410 placeholder_text: impl Into<Arc<str>>,
2411 cx: &mut Context<Self>,
2412 ) {
2413 let placeholder_text = Some(placeholder_text.into());
2414 if self.placeholder_text != placeholder_text {
2415 self.placeholder_text = placeholder_text;
2416 cx.notify();
2417 }
2418 }
2419
2420 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2421 self.cursor_shape = cursor_shape;
2422
2423 // Disrupt blink for immediate user feedback that the cursor shape has changed
2424 self.blink_manager.update(cx, BlinkManager::show_cursor);
2425
2426 cx.notify();
2427 }
2428
2429 pub fn set_current_line_highlight(
2430 &mut self,
2431 current_line_highlight: Option<CurrentLineHighlight>,
2432 ) {
2433 self.current_line_highlight = current_line_highlight;
2434 }
2435
2436 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2437 self.collapse_matches = collapse_matches;
2438 }
2439
2440 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2441 let buffers = self.buffer.read(cx).all_buffers();
2442 let Some(project) = self.project.as_ref() else {
2443 return;
2444 };
2445 project.update(cx, |project, cx| {
2446 for buffer in buffers {
2447 self.registered_buffers
2448 .entry(buffer.read(cx).remote_id())
2449 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2450 }
2451 })
2452 }
2453
2454 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2455 if self.collapse_matches {
2456 return range.start..range.start;
2457 }
2458 range.clone()
2459 }
2460
2461 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2462 if self.display_map.read(cx).clip_at_line_ends != clip {
2463 self.display_map
2464 .update(cx, |map, _| map.clip_at_line_ends = clip);
2465 }
2466 }
2467
2468 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2469 self.input_enabled = input_enabled;
2470 }
2471
2472 pub fn set_inline_completions_hidden_for_vim_mode(
2473 &mut self,
2474 hidden: bool,
2475 window: &mut Window,
2476 cx: &mut Context<Self>,
2477 ) {
2478 if hidden != self.inline_completions_hidden_for_vim_mode {
2479 self.inline_completions_hidden_for_vim_mode = hidden;
2480 if hidden {
2481 self.update_visible_inline_completion(window, cx);
2482 } else {
2483 self.refresh_inline_completion(true, false, window, cx);
2484 }
2485 }
2486 }
2487
2488 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2489 self.menu_inline_completions_policy = value;
2490 }
2491
2492 pub fn set_autoindent(&mut self, autoindent: bool) {
2493 if autoindent {
2494 self.autoindent_mode = Some(AutoindentMode::EachLine);
2495 } else {
2496 self.autoindent_mode = None;
2497 }
2498 }
2499
2500 pub fn read_only(&self, cx: &App) -> bool {
2501 self.read_only || self.buffer.read(cx).read_only()
2502 }
2503
2504 pub fn set_read_only(&mut self, read_only: bool) {
2505 self.read_only = read_only;
2506 }
2507
2508 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2509 self.use_autoclose = autoclose;
2510 }
2511
2512 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2513 self.use_auto_surround = auto_surround;
2514 }
2515
2516 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2517 self.auto_replace_emoji_shortcode = auto_replace;
2518 }
2519
2520 pub fn toggle_edit_predictions(
2521 &mut self,
2522 _: &ToggleEditPrediction,
2523 window: &mut Window,
2524 cx: &mut Context<Self>,
2525 ) {
2526 if self.show_inline_completions_override.is_some() {
2527 self.set_show_edit_predictions(None, window, cx);
2528 } else {
2529 let show_edit_predictions = !self.edit_predictions_enabled();
2530 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2531 }
2532 }
2533
2534 pub fn set_show_edit_predictions(
2535 &mut self,
2536 show_edit_predictions: Option<bool>,
2537 window: &mut Window,
2538 cx: &mut Context<Self>,
2539 ) {
2540 self.show_inline_completions_override = show_edit_predictions;
2541 self.update_edit_prediction_settings(cx);
2542
2543 if let Some(false) = show_edit_predictions {
2544 self.discard_inline_completion(false, cx);
2545 } else {
2546 self.refresh_inline_completion(false, true, window, cx);
2547 }
2548 }
2549
2550 fn inline_completions_disabled_in_scope(
2551 &self,
2552 buffer: &Entity<Buffer>,
2553 buffer_position: language::Anchor,
2554 cx: &App,
2555 ) -> bool {
2556 let snapshot = buffer.read(cx).snapshot();
2557 let settings = snapshot.settings_at(buffer_position, cx);
2558
2559 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2560 return false;
2561 };
2562
2563 scope.override_name().map_or(false, |scope_name| {
2564 settings
2565 .edit_predictions_disabled_in
2566 .iter()
2567 .any(|s| s == scope_name)
2568 })
2569 }
2570
2571 pub fn set_use_modal_editing(&mut self, to: bool) {
2572 self.use_modal_editing = to;
2573 }
2574
2575 pub fn use_modal_editing(&self) -> bool {
2576 self.use_modal_editing
2577 }
2578
2579 fn selections_did_change(
2580 &mut self,
2581 local: bool,
2582 old_cursor_position: &Anchor,
2583 show_completions: bool,
2584 window: &mut Window,
2585 cx: &mut Context<Self>,
2586 ) {
2587 window.invalidate_character_coordinates();
2588
2589 // Copy selections to primary selection buffer
2590 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2591 if local {
2592 let selections = self.selections.all::<usize>(cx);
2593 let buffer_handle = self.buffer.read(cx).read(cx);
2594
2595 let mut text = String::new();
2596 for (index, selection) in selections.iter().enumerate() {
2597 let text_for_selection = buffer_handle
2598 .text_for_range(selection.start..selection.end)
2599 .collect::<String>();
2600
2601 text.push_str(&text_for_selection);
2602 if index != selections.len() - 1 {
2603 text.push('\n');
2604 }
2605 }
2606
2607 if !text.is_empty() {
2608 cx.write_to_primary(ClipboardItem::new_string(text));
2609 }
2610 }
2611
2612 if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
2613 self.buffer.update(cx, |buffer, cx| {
2614 buffer.set_active_selections(
2615 &self.selections.disjoint_anchors(),
2616 self.selections.line_mode,
2617 self.cursor_shape,
2618 cx,
2619 )
2620 });
2621 }
2622 let display_map = self
2623 .display_map
2624 .update(cx, |display_map, cx| display_map.snapshot(cx));
2625 let buffer = &display_map.buffer_snapshot;
2626 self.add_selections_state = None;
2627 self.select_next_state = None;
2628 self.select_prev_state = None;
2629 self.select_syntax_node_history.try_clear();
2630 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2631 self.snippet_stack
2632 .invalidate(&self.selections.disjoint_anchors(), buffer);
2633 self.take_rename(false, window, cx);
2634
2635 let new_cursor_position = self.selections.newest_anchor().head();
2636
2637 self.push_to_nav_history(
2638 *old_cursor_position,
2639 Some(new_cursor_position.to_point(buffer)),
2640 false,
2641 cx,
2642 );
2643
2644 if local {
2645 let new_cursor_position = self.selections.newest_anchor().head();
2646 let mut context_menu = self.context_menu.borrow_mut();
2647 let completion_menu = match context_menu.as_ref() {
2648 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2649 _ => {
2650 *context_menu = None;
2651 None
2652 }
2653 };
2654 if let Some(buffer_id) = new_cursor_position.buffer_id {
2655 if !self.registered_buffers.contains_key(&buffer_id) {
2656 if let Some(project) = self.project.as_ref() {
2657 project.update(cx, |project, cx| {
2658 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2659 return;
2660 };
2661 self.registered_buffers.insert(
2662 buffer_id,
2663 project.register_buffer_with_language_servers(&buffer, cx),
2664 );
2665 })
2666 }
2667 }
2668 }
2669
2670 if let Some(completion_menu) = completion_menu {
2671 let cursor_position = new_cursor_position.to_offset(buffer);
2672 let (word_range, kind) =
2673 buffer.surrounding_word(completion_menu.initial_position, true);
2674 if kind == Some(CharKind::Word)
2675 && word_range.to_inclusive().contains(&cursor_position)
2676 {
2677 let mut completion_menu = completion_menu.clone();
2678 drop(context_menu);
2679
2680 let query = Self::completion_query(buffer, cursor_position);
2681 cx.spawn(async move |this, cx| {
2682 completion_menu
2683 .filter(query.as_deref(), cx.background_executor().clone())
2684 .await;
2685
2686 this.update(cx, |this, cx| {
2687 let mut context_menu = this.context_menu.borrow_mut();
2688 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2689 else {
2690 return;
2691 };
2692
2693 if menu.id > completion_menu.id {
2694 return;
2695 }
2696
2697 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2698 drop(context_menu);
2699 cx.notify();
2700 })
2701 })
2702 .detach();
2703
2704 if show_completions {
2705 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2706 }
2707 } else {
2708 drop(context_menu);
2709 self.hide_context_menu(window, cx);
2710 }
2711 } else {
2712 drop(context_menu);
2713 }
2714
2715 hide_hover(self, cx);
2716
2717 if old_cursor_position.to_display_point(&display_map).row()
2718 != new_cursor_position.to_display_point(&display_map).row()
2719 {
2720 self.available_code_actions.take();
2721 }
2722 self.refresh_code_actions(window, cx);
2723 self.refresh_document_highlights(cx);
2724 self.refresh_selected_text_highlights(false, window, cx);
2725 refresh_matching_bracket_highlights(self, window, cx);
2726 self.update_visible_inline_completion(window, cx);
2727 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2728 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2729 self.inline_blame_popover.take();
2730 if self.git_blame_inline_enabled {
2731 self.start_inline_blame_timer(window, cx);
2732 }
2733 }
2734
2735 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2736 cx.emit(EditorEvent::SelectionsChanged { local });
2737
2738 let selections = &self.selections.disjoint;
2739 if selections.len() == 1 {
2740 cx.emit(SearchEvent::ActiveMatchChanged)
2741 }
2742 if local {
2743 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2744 let inmemory_selections = selections
2745 .iter()
2746 .map(|s| {
2747 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2748 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2749 })
2750 .collect();
2751 self.update_restoration_data(cx, |data| {
2752 data.selections = inmemory_selections;
2753 });
2754
2755 if WorkspaceSettings::get(None, cx).restore_on_startup
2756 != RestoreOnStartupBehavior::None
2757 {
2758 if let Some(workspace_id) =
2759 self.workspace.as_ref().and_then(|workspace| workspace.1)
2760 {
2761 let snapshot = self.buffer().read(cx).snapshot(cx);
2762 let selections = selections.clone();
2763 let background_executor = cx.background_executor().clone();
2764 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2765 self.serialize_selections = cx.background_spawn(async move {
2766 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2767 let db_selections = selections
2768 .iter()
2769 .map(|selection| {
2770 (
2771 selection.start.to_offset(&snapshot),
2772 selection.end.to_offset(&snapshot),
2773 )
2774 })
2775 .collect();
2776
2777 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2778 .await
2779 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2780 .log_err();
2781 });
2782 }
2783 }
2784 }
2785 }
2786
2787 cx.notify();
2788 }
2789
2790 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2791 use text::ToOffset as _;
2792 use text::ToPoint as _;
2793
2794 if self.mode.is_minimap()
2795 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2796 {
2797 return;
2798 }
2799
2800 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2801 return;
2802 };
2803
2804 let snapshot = singleton.read(cx).snapshot();
2805 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2806 let display_snapshot = display_map.snapshot(cx);
2807
2808 display_snapshot
2809 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2810 .map(|fold| {
2811 fold.range.start.text_anchor.to_point(&snapshot)
2812 ..fold.range.end.text_anchor.to_point(&snapshot)
2813 })
2814 .collect()
2815 });
2816 self.update_restoration_data(cx, |data| {
2817 data.folds = inmemory_folds;
2818 });
2819
2820 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2821 return;
2822 };
2823 let background_executor = cx.background_executor().clone();
2824 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2825 let db_folds = self.display_map.update(cx, |display_map, cx| {
2826 display_map
2827 .snapshot(cx)
2828 .folds_in_range(0..snapshot.len())
2829 .map(|fold| {
2830 (
2831 fold.range.start.text_anchor.to_offset(&snapshot),
2832 fold.range.end.text_anchor.to_offset(&snapshot),
2833 )
2834 })
2835 .collect()
2836 });
2837 self.serialize_folds = cx.background_spawn(async move {
2838 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2839 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2840 .await
2841 .with_context(|| {
2842 format!(
2843 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2844 )
2845 })
2846 .log_err();
2847 });
2848 }
2849
2850 pub fn sync_selections(
2851 &mut self,
2852 other: Entity<Editor>,
2853 cx: &mut Context<Self>,
2854 ) -> gpui::Subscription {
2855 let other_selections = other.read(cx).selections.disjoint.to_vec();
2856 self.selections.change_with(cx, |selections| {
2857 selections.select_anchors(other_selections);
2858 });
2859
2860 let other_subscription =
2861 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2862 EditorEvent::SelectionsChanged { local: true } => {
2863 let other_selections = other.read(cx).selections.disjoint.to_vec();
2864 if other_selections.is_empty() {
2865 return;
2866 }
2867 this.selections.change_with(cx, |selections| {
2868 selections.select_anchors(other_selections);
2869 });
2870 }
2871 _ => {}
2872 });
2873
2874 let this_subscription =
2875 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2876 EditorEvent::SelectionsChanged { local: true } => {
2877 let these_selections = this.selections.disjoint.to_vec();
2878 if these_selections.is_empty() {
2879 return;
2880 }
2881 other.update(cx, |other_editor, cx| {
2882 other_editor.selections.change_with(cx, |selections| {
2883 selections.select_anchors(these_selections);
2884 })
2885 });
2886 }
2887 _ => {}
2888 });
2889
2890 Subscription::join(other_subscription, this_subscription)
2891 }
2892
2893 pub fn change_selections<R>(
2894 &mut self,
2895 autoscroll: Option<Autoscroll>,
2896 window: &mut Window,
2897 cx: &mut Context<Self>,
2898 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2899 ) -> R {
2900 self.change_selections_inner(autoscroll, true, window, cx, change)
2901 }
2902
2903 fn change_selections_inner<R>(
2904 &mut self,
2905 autoscroll: Option<Autoscroll>,
2906 request_completions: bool,
2907 window: &mut Window,
2908 cx: &mut Context<Self>,
2909 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2910 ) -> R {
2911 let old_cursor_position = self.selections.newest_anchor().head();
2912 self.push_to_selection_history();
2913
2914 let (changed, result) = self.selections.change_with(cx, change);
2915
2916 if changed {
2917 if let Some(autoscroll) = autoscroll {
2918 self.request_autoscroll(autoscroll, cx);
2919 }
2920 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2921
2922 if self.should_open_signature_help_automatically(
2923 &old_cursor_position,
2924 self.signature_help_state.backspace_pressed(),
2925 cx,
2926 ) {
2927 self.show_signature_help(&ShowSignatureHelp, window, cx);
2928 }
2929 self.signature_help_state.set_backspace_pressed(false);
2930 }
2931
2932 result
2933 }
2934
2935 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2936 where
2937 I: IntoIterator<Item = (Range<S>, T)>,
2938 S: ToOffset,
2939 T: Into<Arc<str>>,
2940 {
2941 if self.read_only(cx) {
2942 return;
2943 }
2944
2945 self.buffer
2946 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2947 }
2948
2949 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2950 where
2951 I: IntoIterator<Item = (Range<S>, T)>,
2952 S: ToOffset,
2953 T: Into<Arc<str>>,
2954 {
2955 if self.read_only(cx) {
2956 return;
2957 }
2958
2959 self.buffer.update(cx, |buffer, cx| {
2960 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2961 });
2962 }
2963
2964 pub fn edit_with_block_indent<I, S, T>(
2965 &mut self,
2966 edits: I,
2967 original_indent_columns: Vec<Option<u32>>,
2968 cx: &mut Context<Self>,
2969 ) where
2970 I: IntoIterator<Item = (Range<S>, T)>,
2971 S: ToOffset,
2972 T: Into<Arc<str>>,
2973 {
2974 if self.read_only(cx) {
2975 return;
2976 }
2977
2978 self.buffer.update(cx, |buffer, cx| {
2979 buffer.edit(
2980 edits,
2981 Some(AutoindentMode::Block {
2982 original_indent_columns,
2983 }),
2984 cx,
2985 )
2986 });
2987 }
2988
2989 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2990 self.hide_context_menu(window, cx);
2991
2992 match phase {
2993 SelectPhase::Begin {
2994 position,
2995 add,
2996 click_count,
2997 } => self.begin_selection(position, add, click_count, window, cx),
2998 SelectPhase::BeginColumnar {
2999 position,
3000 goal_column,
3001 reset,
3002 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
3003 SelectPhase::Extend {
3004 position,
3005 click_count,
3006 } => self.extend_selection(position, click_count, window, cx),
3007 SelectPhase::Update {
3008 position,
3009 goal_column,
3010 scroll_delta,
3011 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
3012 SelectPhase::End => self.end_selection(window, cx),
3013 }
3014 }
3015
3016 fn extend_selection(
3017 &mut self,
3018 position: DisplayPoint,
3019 click_count: usize,
3020 window: &mut Window,
3021 cx: &mut Context<Self>,
3022 ) {
3023 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3024 let tail = self.selections.newest::<usize>(cx).tail();
3025 self.begin_selection(position, false, click_count, window, cx);
3026
3027 let position = position.to_offset(&display_map, Bias::Left);
3028 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
3029
3030 let mut pending_selection = self
3031 .selections
3032 .pending_anchor()
3033 .expect("extend_selection not called with pending selection");
3034 if position >= tail {
3035 pending_selection.start = tail_anchor;
3036 } else {
3037 pending_selection.end = tail_anchor;
3038 pending_selection.reversed = true;
3039 }
3040
3041 let mut pending_mode = self.selections.pending_mode().unwrap();
3042 match &mut pending_mode {
3043 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
3044 _ => {}
3045 }
3046
3047 let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
3048
3049 self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
3050 s.set_pending(pending_selection, pending_mode)
3051 });
3052 }
3053
3054 fn begin_selection(
3055 &mut self,
3056 position: DisplayPoint,
3057 add: bool,
3058 click_count: usize,
3059 window: &mut Window,
3060 cx: &mut Context<Self>,
3061 ) {
3062 if !self.focus_handle.is_focused(window) {
3063 self.last_focused_descendant = None;
3064 window.focus(&self.focus_handle);
3065 }
3066
3067 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3068 let buffer = &display_map.buffer_snapshot;
3069 let position = display_map.clip_point(position, Bias::Left);
3070
3071 let start;
3072 let end;
3073 let mode;
3074 let mut auto_scroll;
3075 match click_count {
3076 1 => {
3077 start = buffer.anchor_before(position.to_point(&display_map));
3078 end = start;
3079 mode = SelectMode::Character;
3080 auto_scroll = true;
3081 }
3082 2 => {
3083 let range = movement::surrounding_word(&display_map, position);
3084 start = buffer.anchor_before(range.start.to_point(&display_map));
3085 end = buffer.anchor_before(range.end.to_point(&display_map));
3086 mode = SelectMode::Word(start..end);
3087 auto_scroll = true;
3088 }
3089 3 => {
3090 let position = display_map
3091 .clip_point(position, Bias::Left)
3092 .to_point(&display_map);
3093 let line_start = display_map.prev_line_boundary(position).0;
3094 let next_line_start = buffer.clip_point(
3095 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3096 Bias::Left,
3097 );
3098 start = buffer.anchor_before(line_start);
3099 end = buffer.anchor_before(next_line_start);
3100 mode = SelectMode::Line(start..end);
3101 auto_scroll = true;
3102 }
3103 _ => {
3104 start = buffer.anchor_before(0);
3105 end = buffer.anchor_before(buffer.len());
3106 mode = SelectMode::All;
3107 auto_scroll = false;
3108 }
3109 }
3110 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3111
3112 let point_to_delete: Option<usize> = {
3113 let selected_points: Vec<Selection<Point>> =
3114 self.selections.disjoint_in_range(start..end, cx);
3115
3116 if !add || click_count > 1 {
3117 None
3118 } else if !selected_points.is_empty() {
3119 Some(selected_points[0].id)
3120 } else {
3121 let clicked_point_already_selected =
3122 self.selections.disjoint.iter().find(|selection| {
3123 selection.start.to_point(buffer) == start.to_point(buffer)
3124 || selection.end.to_point(buffer) == end.to_point(buffer)
3125 });
3126
3127 clicked_point_already_selected.map(|selection| selection.id)
3128 }
3129 };
3130
3131 let selections_count = self.selections.count();
3132
3133 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3134 if let Some(point_to_delete) = point_to_delete {
3135 s.delete(point_to_delete);
3136
3137 if selections_count == 1 {
3138 s.set_pending_anchor_range(start..end, mode);
3139 }
3140 } else {
3141 if !add {
3142 s.clear_disjoint();
3143 }
3144
3145 s.set_pending_anchor_range(start..end, mode);
3146 }
3147 });
3148 }
3149
3150 fn begin_columnar_selection(
3151 &mut self,
3152 position: DisplayPoint,
3153 goal_column: u32,
3154 reset: bool,
3155 window: &mut Window,
3156 cx: &mut Context<Self>,
3157 ) {
3158 if !self.focus_handle.is_focused(window) {
3159 self.last_focused_descendant = None;
3160 window.focus(&self.focus_handle);
3161 }
3162
3163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3164
3165 if reset {
3166 let pointer_position = display_map
3167 .buffer_snapshot
3168 .anchor_before(position.to_point(&display_map));
3169
3170 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3171 s.clear_disjoint();
3172 s.set_pending_anchor_range(
3173 pointer_position..pointer_position,
3174 SelectMode::Character,
3175 );
3176 });
3177 }
3178
3179 let tail = self.selections.newest::<Point>(cx).tail();
3180 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3181
3182 if !reset {
3183 self.select_columns(
3184 tail.to_display_point(&display_map),
3185 position,
3186 goal_column,
3187 &display_map,
3188 window,
3189 cx,
3190 );
3191 }
3192 }
3193
3194 fn update_selection(
3195 &mut self,
3196 position: DisplayPoint,
3197 goal_column: u32,
3198 scroll_delta: gpui::Point<f32>,
3199 window: &mut Window,
3200 cx: &mut Context<Self>,
3201 ) {
3202 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3203
3204 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3205 let tail = tail.to_display_point(&display_map);
3206 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3207 } else if let Some(mut pending) = self.selections.pending_anchor() {
3208 let buffer = self.buffer.read(cx).snapshot(cx);
3209 let head;
3210 let tail;
3211 let mode = self.selections.pending_mode().unwrap();
3212 match &mode {
3213 SelectMode::Character => {
3214 head = position.to_point(&display_map);
3215 tail = pending.tail().to_point(&buffer);
3216 }
3217 SelectMode::Word(original_range) => {
3218 let original_display_range = original_range.start.to_display_point(&display_map)
3219 ..original_range.end.to_display_point(&display_map);
3220 let original_buffer_range = original_display_range.start.to_point(&display_map)
3221 ..original_display_range.end.to_point(&display_map);
3222 if movement::is_inside_word(&display_map, position)
3223 || original_display_range.contains(&position)
3224 {
3225 let word_range = movement::surrounding_word(&display_map, position);
3226 if word_range.start < original_display_range.start {
3227 head = word_range.start.to_point(&display_map);
3228 } else {
3229 head = word_range.end.to_point(&display_map);
3230 }
3231 } else {
3232 head = position.to_point(&display_map);
3233 }
3234
3235 if head <= original_buffer_range.start {
3236 tail = original_buffer_range.end;
3237 } else {
3238 tail = original_buffer_range.start;
3239 }
3240 }
3241 SelectMode::Line(original_range) => {
3242 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3243
3244 let position = display_map
3245 .clip_point(position, Bias::Left)
3246 .to_point(&display_map);
3247 let line_start = display_map.prev_line_boundary(position).0;
3248 let next_line_start = buffer.clip_point(
3249 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3250 Bias::Left,
3251 );
3252
3253 if line_start < original_range.start {
3254 head = line_start
3255 } else {
3256 head = next_line_start
3257 }
3258
3259 if head <= original_range.start {
3260 tail = original_range.end;
3261 } else {
3262 tail = original_range.start;
3263 }
3264 }
3265 SelectMode::All => {
3266 return;
3267 }
3268 };
3269
3270 if head < tail {
3271 pending.start = buffer.anchor_before(head);
3272 pending.end = buffer.anchor_before(tail);
3273 pending.reversed = true;
3274 } else {
3275 pending.start = buffer.anchor_before(tail);
3276 pending.end = buffer.anchor_before(head);
3277 pending.reversed = false;
3278 }
3279
3280 self.change_selections(None, window, cx, |s| {
3281 s.set_pending(pending, mode);
3282 });
3283 } else {
3284 log::error!("update_selection dispatched with no pending selection");
3285 return;
3286 }
3287
3288 self.apply_scroll_delta(scroll_delta, window, cx);
3289 cx.notify();
3290 }
3291
3292 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3293 self.columnar_selection_tail.take();
3294 if self.selections.pending_anchor().is_some() {
3295 let selections = self.selections.all::<usize>(cx);
3296 self.change_selections(None, window, cx, |s| {
3297 s.select(selections);
3298 s.clear_pending();
3299 });
3300 }
3301 }
3302
3303 fn select_columns(
3304 &mut self,
3305 tail: DisplayPoint,
3306 head: DisplayPoint,
3307 goal_column: u32,
3308 display_map: &DisplaySnapshot,
3309 window: &mut Window,
3310 cx: &mut Context<Self>,
3311 ) {
3312 let start_row = cmp::min(tail.row(), head.row());
3313 let end_row = cmp::max(tail.row(), head.row());
3314 let start_column = cmp::min(tail.column(), goal_column);
3315 let end_column = cmp::max(tail.column(), goal_column);
3316 let reversed = start_column < tail.column();
3317
3318 let selection_ranges = (start_row.0..=end_row.0)
3319 .map(DisplayRow)
3320 .filter_map(|row| {
3321 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3322 let start = display_map
3323 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3324 .to_point(display_map);
3325 let end = display_map
3326 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3327 .to_point(display_map);
3328 if reversed {
3329 Some(end..start)
3330 } else {
3331 Some(start..end)
3332 }
3333 } else {
3334 None
3335 }
3336 })
3337 .collect::<Vec<_>>();
3338
3339 self.change_selections(None, window, cx, |s| {
3340 s.select_ranges(selection_ranges);
3341 });
3342 cx.notify();
3343 }
3344
3345 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3346 self.selections
3347 .all_adjusted(cx)
3348 .iter()
3349 .any(|selection| !selection.is_empty())
3350 }
3351
3352 pub fn has_pending_nonempty_selection(&self) -> bool {
3353 let pending_nonempty_selection = match self.selections.pending_anchor() {
3354 Some(Selection { start, end, .. }) => start != end,
3355 None => false,
3356 };
3357
3358 pending_nonempty_selection
3359 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3360 }
3361
3362 pub fn has_pending_selection(&self) -> bool {
3363 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3364 }
3365
3366 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3367 self.selection_mark_mode = false;
3368
3369 if self.clear_expanded_diff_hunks(cx) {
3370 cx.notify();
3371 return;
3372 }
3373 if self.dismiss_menus_and_popups(true, window, cx) {
3374 return;
3375 }
3376
3377 if self.mode.is_full()
3378 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3379 {
3380 return;
3381 }
3382
3383 cx.propagate();
3384 }
3385
3386 pub fn dismiss_menus_and_popups(
3387 &mut self,
3388 is_user_requested: bool,
3389 window: &mut Window,
3390 cx: &mut Context<Self>,
3391 ) -> bool {
3392 if self.take_rename(false, window, cx).is_some() {
3393 return true;
3394 }
3395
3396 if hide_hover(self, cx) {
3397 return true;
3398 }
3399
3400 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3401 return true;
3402 }
3403
3404 if self.hide_context_menu(window, cx).is_some() {
3405 return true;
3406 }
3407
3408 if self.mouse_context_menu.take().is_some() {
3409 return true;
3410 }
3411
3412 if is_user_requested && self.discard_inline_completion(true, cx) {
3413 return true;
3414 }
3415
3416 if self.snippet_stack.pop().is_some() {
3417 return true;
3418 }
3419
3420 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3421 self.dismiss_diagnostics(cx);
3422 return true;
3423 }
3424
3425 false
3426 }
3427
3428 fn linked_editing_ranges_for(
3429 &self,
3430 selection: Range<text::Anchor>,
3431 cx: &App,
3432 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3433 if self.linked_edit_ranges.is_empty() {
3434 return None;
3435 }
3436 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3437 selection.end.buffer_id.and_then(|end_buffer_id| {
3438 if selection.start.buffer_id != Some(end_buffer_id) {
3439 return None;
3440 }
3441 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3442 let snapshot = buffer.read(cx).snapshot();
3443 self.linked_edit_ranges
3444 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3445 .map(|ranges| (ranges, snapshot, buffer))
3446 })?;
3447 use text::ToOffset as TO;
3448 // find offset from the start of current range to current cursor position
3449 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3450
3451 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3452 let start_difference = start_offset - start_byte_offset;
3453 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3454 let end_difference = end_offset - start_byte_offset;
3455 // Current range has associated linked ranges.
3456 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3457 for range in linked_ranges.iter() {
3458 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3459 let end_offset = start_offset + end_difference;
3460 let start_offset = start_offset + start_difference;
3461 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3462 continue;
3463 }
3464 if self.selections.disjoint_anchor_ranges().any(|s| {
3465 if s.start.buffer_id != selection.start.buffer_id
3466 || s.end.buffer_id != selection.end.buffer_id
3467 {
3468 return false;
3469 }
3470 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3471 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3472 }) {
3473 continue;
3474 }
3475 let start = buffer_snapshot.anchor_after(start_offset);
3476 let end = buffer_snapshot.anchor_after(end_offset);
3477 linked_edits
3478 .entry(buffer.clone())
3479 .or_default()
3480 .push(start..end);
3481 }
3482 Some(linked_edits)
3483 }
3484
3485 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3486 let text: Arc<str> = text.into();
3487
3488 if self.read_only(cx) {
3489 return;
3490 }
3491
3492 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3493
3494 let selections = self.selections.all_adjusted(cx);
3495 let mut bracket_inserted = false;
3496 let mut edits = Vec::new();
3497 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3498 let mut new_selections = Vec::with_capacity(selections.len());
3499 let mut new_autoclose_regions = Vec::new();
3500 let snapshot = self.buffer.read(cx).read(cx);
3501 let mut clear_linked_edit_ranges = false;
3502
3503 for (selection, autoclose_region) in
3504 self.selections_with_autoclose_regions(selections, &snapshot)
3505 {
3506 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3507 // Determine if the inserted text matches the opening or closing
3508 // bracket of any of this language's bracket pairs.
3509 let mut bracket_pair = None;
3510 let mut is_bracket_pair_start = false;
3511 let mut is_bracket_pair_end = false;
3512 if !text.is_empty() {
3513 let mut bracket_pair_matching_end = None;
3514 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3515 // and they are removing the character that triggered IME popup.
3516 for (pair, enabled) in scope.brackets() {
3517 if !pair.close && !pair.surround {
3518 continue;
3519 }
3520
3521 if enabled && pair.start.ends_with(text.as_ref()) {
3522 let prefix_len = pair.start.len() - text.len();
3523 let preceding_text_matches_prefix = prefix_len == 0
3524 || (selection.start.column >= (prefix_len as u32)
3525 && snapshot.contains_str_at(
3526 Point::new(
3527 selection.start.row,
3528 selection.start.column - (prefix_len as u32),
3529 ),
3530 &pair.start[..prefix_len],
3531 ));
3532 if preceding_text_matches_prefix {
3533 bracket_pair = Some(pair.clone());
3534 is_bracket_pair_start = true;
3535 break;
3536 }
3537 }
3538 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3539 {
3540 // take first bracket pair matching end, but don't break in case a later bracket
3541 // pair matches start
3542 bracket_pair_matching_end = Some(pair.clone());
3543 }
3544 }
3545 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3546 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3547 is_bracket_pair_end = true;
3548 }
3549 }
3550
3551 if let Some(bracket_pair) = bracket_pair {
3552 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3553 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3554 let auto_surround =
3555 self.use_auto_surround && snapshot_settings.use_auto_surround;
3556 if selection.is_empty() {
3557 if is_bracket_pair_start {
3558 // If the inserted text is a suffix of an opening bracket and the
3559 // selection is preceded by the rest of the opening bracket, then
3560 // insert the closing bracket.
3561 let following_text_allows_autoclose = snapshot
3562 .chars_at(selection.start)
3563 .next()
3564 .map_or(true, |c| scope.should_autoclose_before(c));
3565
3566 let preceding_text_allows_autoclose = selection.start.column == 0
3567 || snapshot.reversed_chars_at(selection.start).next().map_or(
3568 true,
3569 |c| {
3570 bracket_pair.start != bracket_pair.end
3571 || !snapshot
3572 .char_classifier_at(selection.start)
3573 .is_word(c)
3574 },
3575 );
3576
3577 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3578 && bracket_pair.start.len() == 1
3579 {
3580 let target = bracket_pair.start.chars().next().unwrap();
3581 let current_line_count = snapshot
3582 .reversed_chars_at(selection.start)
3583 .take_while(|&c| c != '\n')
3584 .filter(|&c| c == target)
3585 .count();
3586 current_line_count % 2 == 1
3587 } else {
3588 false
3589 };
3590
3591 if autoclose
3592 && bracket_pair.close
3593 && following_text_allows_autoclose
3594 && preceding_text_allows_autoclose
3595 && !is_closing_quote
3596 {
3597 let anchor = snapshot.anchor_before(selection.end);
3598 new_selections.push((selection.map(|_| anchor), text.len()));
3599 new_autoclose_regions.push((
3600 anchor,
3601 text.len(),
3602 selection.id,
3603 bracket_pair.clone(),
3604 ));
3605 edits.push((
3606 selection.range(),
3607 format!("{}{}", text, bracket_pair.end).into(),
3608 ));
3609 bracket_inserted = true;
3610 continue;
3611 }
3612 }
3613
3614 if let Some(region) = autoclose_region {
3615 // If the selection is followed by an auto-inserted closing bracket,
3616 // then don't insert that closing bracket again; just move the selection
3617 // past the closing bracket.
3618 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3619 && text.as_ref() == region.pair.end.as_str();
3620 if should_skip {
3621 let anchor = snapshot.anchor_after(selection.end);
3622 new_selections
3623 .push((selection.map(|_| anchor), region.pair.end.len()));
3624 continue;
3625 }
3626 }
3627
3628 let always_treat_brackets_as_autoclosed = snapshot
3629 .language_settings_at(selection.start, cx)
3630 .always_treat_brackets_as_autoclosed;
3631 if always_treat_brackets_as_autoclosed
3632 && is_bracket_pair_end
3633 && snapshot.contains_str_at(selection.end, text.as_ref())
3634 {
3635 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3636 // and the inserted text is a closing bracket and the selection is followed
3637 // by the closing bracket then move the selection past the closing bracket.
3638 let anchor = snapshot.anchor_after(selection.end);
3639 new_selections.push((selection.map(|_| anchor), text.len()));
3640 continue;
3641 }
3642 }
3643 // If an opening bracket is 1 character long and is typed while
3644 // text is selected, then surround that text with the bracket pair.
3645 else if auto_surround
3646 && bracket_pair.surround
3647 && is_bracket_pair_start
3648 && bracket_pair.start.chars().count() == 1
3649 {
3650 edits.push((selection.start..selection.start, text.clone()));
3651 edits.push((
3652 selection.end..selection.end,
3653 bracket_pair.end.as_str().into(),
3654 ));
3655 bracket_inserted = true;
3656 new_selections.push((
3657 Selection {
3658 id: selection.id,
3659 start: snapshot.anchor_after(selection.start),
3660 end: snapshot.anchor_before(selection.end),
3661 reversed: selection.reversed,
3662 goal: selection.goal,
3663 },
3664 0,
3665 ));
3666 continue;
3667 }
3668 }
3669 }
3670
3671 if self.auto_replace_emoji_shortcode
3672 && selection.is_empty()
3673 && text.as_ref().ends_with(':')
3674 {
3675 if let Some(possible_emoji_short_code) =
3676 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3677 {
3678 if !possible_emoji_short_code.is_empty() {
3679 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3680 let emoji_shortcode_start = Point::new(
3681 selection.start.row,
3682 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3683 );
3684
3685 // Remove shortcode from buffer
3686 edits.push((
3687 emoji_shortcode_start..selection.start,
3688 "".to_string().into(),
3689 ));
3690 new_selections.push((
3691 Selection {
3692 id: selection.id,
3693 start: snapshot.anchor_after(emoji_shortcode_start),
3694 end: snapshot.anchor_before(selection.start),
3695 reversed: selection.reversed,
3696 goal: selection.goal,
3697 },
3698 0,
3699 ));
3700
3701 // Insert emoji
3702 let selection_start_anchor = snapshot.anchor_after(selection.start);
3703 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3704 edits.push((selection.start..selection.end, emoji.to_string().into()));
3705
3706 continue;
3707 }
3708 }
3709 }
3710 }
3711
3712 // If not handling any auto-close operation, then just replace the selected
3713 // text with the given input and move the selection to the end of the
3714 // newly inserted text.
3715 let anchor = snapshot.anchor_after(selection.end);
3716 if !self.linked_edit_ranges.is_empty() {
3717 let start_anchor = snapshot.anchor_before(selection.start);
3718
3719 let is_word_char = text.chars().next().map_or(true, |char| {
3720 let classifier = snapshot
3721 .char_classifier_at(start_anchor.to_offset(&snapshot))
3722 .ignore_punctuation(true);
3723 classifier.is_word(char)
3724 });
3725
3726 if is_word_char {
3727 if let Some(ranges) = self
3728 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3729 {
3730 for (buffer, edits) in ranges {
3731 linked_edits
3732 .entry(buffer.clone())
3733 .or_default()
3734 .extend(edits.into_iter().map(|range| (range, text.clone())));
3735 }
3736 }
3737 } else {
3738 clear_linked_edit_ranges = true;
3739 }
3740 }
3741
3742 new_selections.push((selection.map(|_| anchor), 0));
3743 edits.push((selection.start..selection.end, text.clone()));
3744 }
3745
3746 drop(snapshot);
3747
3748 self.transact(window, cx, |this, window, cx| {
3749 if clear_linked_edit_ranges {
3750 this.linked_edit_ranges.clear();
3751 }
3752 let initial_buffer_versions =
3753 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3754
3755 this.buffer.update(cx, |buffer, cx| {
3756 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3757 });
3758 for (buffer, edits) in linked_edits {
3759 buffer.update(cx, |buffer, cx| {
3760 let snapshot = buffer.snapshot();
3761 let edits = edits
3762 .into_iter()
3763 .map(|(range, text)| {
3764 use text::ToPoint as TP;
3765 let end_point = TP::to_point(&range.end, &snapshot);
3766 let start_point = TP::to_point(&range.start, &snapshot);
3767 (start_point..end_point, text)
3768 })
3769 .sorted_by_key(|(range, _)| range.start);
3770 buffer.edit(edits, None, cx);
3771 })
3772 }
3773 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3774 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3775 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3776 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3777 .zip(new_selection_deltas)
3778 .map(|(selection, delta)| Selection {
3779 id: selection.id,
3780 start: selection.start + delta,
3781 end: selection.end + delta,
3782 reversed: selection.reversed,
3783 goal: SelectionGoal::None,
3784 })
3785 .collect::<Vec<_>>();
3786
3787 let mut i = 0;
3788 for (position, delta, selection_id, pair) in new_autoclose_regions {
3789 let position = position.to_offset(&map.buffer_snapshot) + delta;
3790 let start = map.buffer_snapshot.anchor_before(position);
3791 let end = map.buffer_snapshot.anchor_after(position);
3792 while let Some(existing_state) = this.autoclose_regions.get(i) {
3793 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3794 Ordering::Less => i += 1,
3795 Ordering::Greater => break,
3796 Ordering::Equal => {
3797 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3798 Ordering::Less => i += 1,
3799 Ordering::Equal => break,
3800 Ordering::Greater => break,
3801 }
3802 }
3803 }
3804 }
3805 this.autoclose_regions.insert(
3806 i,
3807 AutocloseRegion {
3808 selection_id,
3809 range: start..end,
3810 pair,
3811 },
3812 );
3813 }
3814
3815 let had_active_inline_completion = this.has_active_inline_completion();
3816 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3817 s.select(new_selections)
3818 });
3819
3820 if !bracket_inserted {
3821 if let Some(on_type_format_task) =
3822 this.trigger_on_type_formatting(text.to_string(), window, cx)
3823 {
3824 on_type_format_task.detach_and_log_err(cx);
3825 }
3826 }
3827
3828 let editor_settings = EditorSettings::get_global(cx);
3829 if bracket_inserted
3830 && (editor_settings.auto_signature_help
3831 || editor_settings.show_signature_help_after_edits)
3832 {
3833 this.show_signature_help(&ShowSignatureHelp, window, cx);
3834 }
3835
3836 let trigger_in_words =
3837 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3838 if this.hard_wrap.is_some() {
3839 let latest: Range<Point> = this.selections.newest(cx).range();
3840 if latest.is_empty()
3841 && this
3842 .buffer()
3843 .read(cx)
3844 .snapshot(cx)
3845 .line_len(MultiBufferRow(latest.start.row))
3846 == latest.start.column
3847 {
3848 this.rewrap_impl(
3849 RewrapOptions {
3850 override_language_settings: true,
3851 preserve_existing_whitespace: true,
3852 },
3853 cx,
3854 )
3855 }
3856 }
3857 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3858 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3859 this.refresh_inline_completion(true, false, window, cx);
3860 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3861 });
3862 }
3863
3864 fn find_possible_emoji_shortcode_at_position(
3865 snapshot: &MultiBufferSnapshot,
3866 position: Point,
3867 ) -> Option<String> {
3868 let mut chars = Vec::new();
3869 let mut found_colon = false;
3870 for char in snapshot.reversed_chars_at(position).take(100) {
3871 // Found a possible emoji shortcode in the middle of the buffer
3872 if found_colon {
3873 if char.is_whitespace() {
3874 chars.reverse();
3875 return Some(chars.iter().collect());
3876 }
3877 // If the previous character is not a whitespace, we are in the middle of a word
3878 // and we only want to complete the shortcode if the word is made up of other emojis
3879 let mut containing_word = String::new();
3880 for ch in snapshot
3881 .reversed_chars_at(position)
3882 .skip(chars.len() + 1)
3883 .take(100)
3884 {
3885 if ch.is_whitespace() {
3886 break;
3887 }
3888 containing_word.push(ch);
3889 }
3890 let containing_word = containing_word.chars().rev().collect::<String>();
3891 if util::word_consists_of_emojis(containing_word.as_str()) {
3892 chars.reverse();
3893 return Some(chars.iter().collect());
3894 }
3895 }
3896
3897 if char.is_whitespace() || !char.is_ascii() {
3898 return None;
3899 }
3900 if char == ':' {
3901 found_colon = true;
3902 } else {
3903 chars.push(char);
3904 }
3905 }
3906 // Found a possible emoji shortcode at the beginning of the buffer
3907 chars.reverse();
3908 Some(chars.iter().collect())
3909 }
3910
3911 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3912 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3913 self.transact(window, cx, |this, window, cx| {
3914 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3915 let selections = this.selections.all::<usize>(cx);
3916 let multi_buffer = this.buffer.read(cx);
3917 let buffer = multi_buffer.snapshot(cx);
3918 selections
3919 .iter()
3920 .map(|selection| {
3921 let start_point = selection.start.to_point(&buffer);
3922 let mut indent =
3923 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3924 indent.len = cmp::min(indent.len, start_point.column);
3925 let start = selection.start;
3926 let end = selection.end;
3927 let selection_is_empty = start == end;
3928 let language_scope = buffer.language_scope_at(start);
3929 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3930 &language_scope
3931 {
3932 let insert_extra_newline =
3933 insert_extra_newline_brackets(&buffer, start..end, language)
3934 || insert_extra_newline_tree_sitter(&buffer, start..end);
3935
3936 // Comment extension on newline is allowed only for cursor selections
3937 let comment_delimiter = maybe!({
3938 if !selection_is_empty {
3939 return None;
3940 }
3941
3942 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3943 return None;
3944 }
3945
3946 let delimiters = language.line_comment_prefixes();
3947 let max_len_of_delimiter =
3948 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3949 let (snapshot, range) =
3950 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3951
3952 let mut index_of_first_non_whitespace = 0;
3953 let comment_candidate = snapshot
3954 .chars_for_range(range)
3955 .skip_while(|c| {
3956 let should_skip = c.is_whitespace();
3957 if should_skip {
3958 index_of_first_non_whitespace += 1;
3959 }
3960 should_skip
3961 })
3962 .take(max_len_of_delimiter)
3963 .collect::<String>();
3964 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3965 comment_candidate.starts_with(comment_prefix.as_ref())
3966 })?;
3967 let cursor_is_placed_after_comment_marker =
3968 index_of_first_non_whitespace + comment_prefix.len()
3969 <= start_point.column as usize;
3970 if cursor_is_placed_after_comment_marker {
3971 Some(comment_prefix.clone())
3972 } else {
3973 None
3974 }
3975 });
3976 (comment_delimiter, insert_extra_newline)
3977 } else {
3978 (None, false)
3979 };
3980
3981 let capacity_for_delimiter = comment_delimiter
3982 .as_deref()
3983 .map(str::len)
3984 .unwrap_or_default();
3985 let mut new_text =
3986 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3987 new_text.push('\n');
3988 new_text.extend(indent.chars());
3989 if let Some(delimiter) = &comment_delimiter {
3990 new_text.push_str(delimiter);
3991 }
3992 if insert_extra_newline {
3993 new_text = new_text.repeat(2);
3994 }
3995
3996 let anchor = buffer.anchor_after(end);
3997 let new_selection = selection.map(|_| anchor);
3998 (
3999 (start..end, new_text),
4000 (insert_extra_newline, new_selection),
4001 )
4002 })
4003 .unzip()
4004 };
4005
4006 this.edit_with_autoindent(edits, cx);
4007 let buffer = this.buffer.read(cx).snapshot(cx);
4008 let new_selections = selection_fixup_info
4009 .into_iter()
4010 .map(|(extra_newline_inserted, new_selection)| {
4011 let mut cursor = new_selection.end.to_point(&buffer);
4012 if extra_newline_inserted {
4013 cursor.row -= 1;
4014 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
4015 }
4016 new_selection.map(|_| cursor)
4017 })
4018 .collect();
4019
4020 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4021 s.select(new_selections)
4022 });
4023 this.refresh_inline_completion(true, false, window, cx);
4024 });
4025 }
4026
4027 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
4028 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4029
4030 let buffer = self.buffer.read(cx);
4031 let snapshot = buffer.snapshot(cx);
4032
4033 let mut edits = Vec::new();
4034 let mut rows = Vec::new();
4035
4036 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
4037 let cursor = selection.head();
4038 let row = cursor.row;
4039
4040 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
4041
4042 let newline = "\n".to_string();
4043 edits.push((start_of_line..start_of_line, newline));
4044
4045 rows.push(row + rows_inserted as u32);
4046 }
4047
4048 self.transact(window, cx, |editor, window, cx| {
4049 editor.edit(edits, cx);
4050
4051 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4052 let mut index = 0;
4053 s.move_cursors_with(|map, _, _| {
4054 let row = rows[index];
4055 index += 1;
4056
4057 let point = Point::new(row, 0);
4058 let boundary = map.next_line_boundary(point).1;
4059 let clipped = map.clip_point(boundary, Bias::Left);
4060
4061 (clipped, SelectionGoal::None)
4062 });
4063 });
4064
4065 let mut indent_edits = Vec::new();
4066 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4067 for row in rows {
4068 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4069 for (row, indent) in indents {
4070 if indent.len == 0 {
4071 continue;
4072 }
4073
4074 let text = match indent.kind {
4075 IndentKind::Space => " ".repeat(indent.len as usize),
4076 IndentKind::Tab => "\t".repeat(indent.len as usize),
4077 };
4078 let point = Point::new(row.0, 0);
4079 indent_edits.push((point..point, text));
4080 }
4081 }
4082 editor.edit(indent_edits, cx);
4083 });
4084 }
4085
4086 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
4087 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4088
4089 let buffer = self.buffer.read(cx);
4090 let snapshot = buffer.snapshot(cx);
4091
4092 let mut edits = Vec::new();
4093 let mut rows = Vec::new();
4094 let mut rows_inserted = 0;
4095
4096 for selection in self.selections.all_adjusted(cx) {
4097 let cursor = selection.head();
4098 let row = cursor.row;
4099
4100 let point = Point::new(row + 1, 0);
4101 let start_of_line = snapshot.clip_point(point, Bias::Left);
4102
4103 let newline = "\n".to_string();
4104 edits.push((start_of_line..start_of_line, newline));
4105
4106 rows_inserted += 1;
4107 rows.push(row + rows_inserted);
4108 }
4109
4110 self.transact(window, cx, |editor, window, cx| {
4111 editor.edit(edits, cx);
4112
4113 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4114 let mut index = 0;
4115 s.move_cursors_with(|map, _, _| {
4116 let row = rows[index];
4117 index += 1;
4118
4119 let point = Point::new(row, 0);
4120 let boundary = map.next_line_boundary(point).1;
4121 let clipped = map.clip_point(boundary, Bias::Left);
4122
4123 (clipped, SelectionGoal::None)
4124 });
4125 });
4126
4127 let mut indent_edits = Vec::new();
4128 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4129 for row in rows {
4130 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4131 for (row, indent) in indents {
4132 if indent.len == 0 {
4133 continue;
4134 }
4135
4136 let text = match indent.kind {
4137 IndentKind::Space => " ".repeat(indent.len as usize),
4138 IndentKind::Tab => "\t".repeat(indent.len as usize),
4139 };
4140 let point = Point::new(row.0, 0);
4141 indent_edits.push((point..point, text));
4142 }
4143 }
4144 editor.edit(indent_edits, cx);
4145 });
4146 }
4147
4148 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4149 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4150 original_indent_columns: Vec::new(),
4151 });
4152 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4153 }
4154
4155 fn insert_with_autoindent_mode(
4156 &mut self,
4157 text: &str,
4158 autoindent_mode: Option<AutoindentMode>,
4159 window: &mut Window,
4160 cx: &mut Context<Self>,
4161 ) {
4162 if self.read_only(cx) {
4163 return;
4164 }
4165
4166 let text: Arc<str> = text.into();
4167 self.transact(window, cx, |this, window, cx| {
4168 let old_selections = this.selections.all_adjusted(cx);
4169 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4170 let anchors = {
4171 let snapshot = buffer.read(cx);
4172 old_selections
4173 .iter()
4174 .map(|s| {
4175 let anchor = snapshot.anchor_after(s.head());
4176 s.map(|_| anchor)
4177 })
4178 .collect::<Vec<_>>()
4179 };
4180 buffer.edit(
4181 old_selections
4182 .iter()
4183 .map(|s| (s.start..s.end, text.clone())),
4184 autoindent_mode,
4185 cx,
4186 );
4187 anchors
4188 });
4189
4190 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4191 s.select_anchors(selection_anchors);
4192 });
4193
4194 cx.notify();
4195 });
4196 }
4197
4198 fn trigger_completion_on_input(
4199 &mut self,
4200 text: &str,
4201 trigger_in_words: bool,
4202 window: &mut Window,
4203 cx: &mut Context<Self>,
4204 ) {
4205 let ignore_completion_provider = self
4206 .context_menu
4207 .borrow()
4208 .as_ref()
4209 .map(|menu| match menu {
4210 CodeContextMenu::Completions(completions_menu) => {
4211 completions_menu.ignore_completion_provider
4212 }
4213 CodeContextMenu::CodeActions(_) => false,
4214 })
4215 .unwrap_or(false);
4216
4217 if ignore_completion_provider {
4218 self.show_word_completions(&ShowWordCompletions, window, cx);
4219 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4220 self.show_completions(
4221 &ShowCompletions {
4222 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4223 },
4224 window,
4225 cx,
4226 );
4227 } else {
4228 self.hide_context_menu(window, cx);
4229 }
4230 }
4231
4232 fn is_completion_trigger(
4233 &self,
4234 text: &str,
4235 trigger_in_words: bool,
4236 cx: &mut Context<Self>,
4237 ) -> bool {
4238 let position = self.selections.newest_anchor().head();
4239 let multibuffer = self.buffer.read(cx);
4240 let Some(buffer) = position
4241 .buffer_id
4242 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4243 else {
4244 return false;
4245 };
4246
4247 if let Some(completion_provider) = &self.completion_provider {
4248 completion_provider.is_completion_trigger(
4249 &buffer,
4250 position.text_anchor,
4251 text,
4252 trigger_in_words,
4253 cx,
4254 )
4255 } else {
4256 false
4257 }
4258 }
4259
4260 /// If any empty selections is touching the start of its innermost containing autoclose
4261 /// region, expand it to select the brackets.
4262 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4263 let selections = self.selections.all::<usize>(cx);
4264 let buffer = self.buffer.read(cx).read(cx);
4265 let new_selections = self
4266 .selections_with_autoclose_regions(selections, &buffer)
4267 .map(|(mut selection, region)| {
4268 if !selection.is_empty() {
4269 return selection;
4270 }
4271
4272 if let Some(region) = region {
4273 let mut range = region.range.to_offset(&buffer);
4274 if selection.start == range.start && range.start >= region.pair.start.len() {
4275 range.start -= region.pair.start.len();
4276 if buffer.contains_str_at(range.start, ®ion.pair.start)
4277 && buffer.contains_str_at(range.end, ®ion.pair.end)
4278 {
4279 range.end += region.pair.end.len();
4280 selection.start = range.start;
4281 selection.end = range.end;
4282
4283 return selection;
4284 }
4285 }
4286 }
4287
4288 let always_treat_brackets_as_autoclosed = buffer
4289 .language_settings_at(selection.start, cx)
4290 .always_treat_brackets_as_autoclosed;
4291
4292 if !always_treat_brackets_as_autoclosed {
4293 return selection;
4294 }
4295
4296 if let Some(scope) = buffer.language_scope_at(selection.start) {
4297 for (pair, enabled) in scope.brackets() {
4298 if !enabled || !pair.close {
4299 continue;
4300 }
4301
4302 if buffer.contains_str_at(selection.start, &pair.end) {
4303 let pair_start_len = pair.start.len();
4304 if buffer.contains_str_at(
4305 selection.start.saturating_sub(pair_start_len),
4306 &pair.start,
4307 ) {
4308 selection.start -= pair_start_len;
4309 selection.end += pair.end.len();
4310
4311 return selection;
4312 }
4313 }
4314 }
4315 }
4316
4317 selection
4318 })
4319 .collect();
4320
4321 drop(buffer);
4322 self.change_selections(None, window, cx, |selections| {
4323 selections.select(new_selections)
4324 });
4325 }
4326
4327 /// Iterate the given selections, and for each one, find the smallest surrounding
4328 /// autoclose region. This uses the ordering of the selections and the autoclose
4329 /// regions to avoid repeated comparisons.
4330 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4331 &'a self,
4332 selections: impl IntoIterator<Item = Selection<D>>,
4333 buffer: &'a MultiBufferSnapshot,
4334 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4335 let mut i = 0;
4336 let mut regions = self.autoclose_regions.as_slice();
4337 selections.into_iter().map(move |selection| {
4338 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4339
4340 let mut enclosing = None;
4341 while let Some(pair_state) = regions.get(i) {
4342 if pair_state.range.end.to_offset(buffer) < range.start {
4343 regions = ®ions[i + 1..];
4344 i = 0;
4345 } else if pair_state.range.start.to_offset(buffer) > range.end {
4346 break;
4347 } else {
4348 if pair_state.selection_id == selection.id {
4349 enclosing = Some(pair_state);
4350 }
4351 i += 1;
4352 }
4353 }
4354
4355 (selection, enclosing)
4356 })
4357 }
4358
4359 /// Remove any autoclose regions that no longer contain their selection.
4360 fn invalidate_autoclose_regions(
4361 &mut self,
4362 mut selections: &[Selection<Anchor>],
4363 buffer: &MultiBufferSnapshot,
4364 ) {
4365 self.autoclose_regions.retain(|state| {
4366 let mut i = 0;
4367 while let Some(selection) = selections.get(i) {
4368 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4369 selections = &selections[1..];
4370 continue;
4371 }
4372 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4373 break;
4374 }
4375 if selection.id == state.selection_id {
4376 return true;
4377 } else {
4378 i += 1;
4379 }
4380 }
4381 false
4382 });
4383 }
4384
4385 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4386 let offset = position.to_offset(buffer);
4387 let (word_range, kind) = buffer.surrounding_word(offset, true);
4388 if offset > word_range.start && kind == Some(CharKind::Word) {
4389 Some(
4390 buffer
4391 .text_for_range(word_range.start..offset)
4392 .collect::<String>(),
4393 )
4394 } else {
4395 None
4396 }
4397 }
4398
4399 pub fn toggle_inline_values(
4400 &mut self,
4401 _: &ToggleInlineValues,
4402 _: &mut Window,
4403 cx: &mut Context<Self>,
4404 ) {
4405 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4406
4407 self.refresh_inline_values(cx);
4408 }
4409
4410 pub fn toggle_inlay_hints(
4411 &mut self,
4412 _: &ToggleInlayHints,
4413 _: &mut Window,
4414 cx: &mut Context<Self>,
4415 ) {
4416 self.refresh_inlay_hints(
4417 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4418 cx,
4419 );
4420 }
4421
4422 pub fn inlay_hints_enabled(&self) -> bool {
4423 self.inlay_hint_cache.enabled
4424 }
4425
4426 pub fn inline_values_enabled(&self) -> bool {
4427 self.inline_value_cache.enabled
4428 }
4429
4430 #[cfg(any(test, feature = "test-support"))]
4431 pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
4432 self.display_map
4433 .read(cx)
4434 .current_inlays()
4435 .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
4436 .cloned()
4437 .collect()
4438 }
4439
4440 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4441 if self.semantics_provider.is_none() || !self.mode.is_full() {
4442 return;
4443 }
4444
4445 let reason_description = reason.description();
4446 let ignore_debounce = matches!(
4447 reason,
4448 InlayHintRefreshReason::SettingsChange(_)
4449 | InlayHintRefreshReason::Toggle(_)
4450 | InlayHintRefreshReason::ExcerptsRemoved(_)
4451 | InlayHintRefreshReason::ModifiersChanged(_)
4452 );
4453 let (invalidate_cache, required_languages) = match reason {
4454 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4455 match self.inlay_hint_cache.modifiers_override(enabled) {
4456 Some(enabled) => {
4457 if enabled {
4458 (InvalidationStrategy::RefreshRequested, None)
4459 } else {
4460 self.splice_inlays(
4461 &self
4462 .visible_inlay_hints(cx)
4463 .iter()
4464 .map(|inlay| inlay.id)
4465 .collect::<Vec<InlayId>>(),
4466 Vec::new(),
4467 cx,
4468 );
4469 return;
4470 }
4471 }
4472 None => return,
4473 }
4474 }
4475 InlayHintRefreshReason::Toggle(enabled) => {
4476 if self.inlay_hint_cache.toggle(enabled) {
4477 if enabled {
4478 (InvalidationStrategy::RefreshRequested, None)
4479 } else {
4480 self.splice_inlays(
4481 &self
4482 .visible_inlay_hints(cx)
4483 .iter()
4484 .map(|inlay| inlay.id)
4485 .collect::<Vec<InlayId>>(),
4486 Vec::new(),
4487 cx,
4488 );
4489 return;
4490 }
4491 } else {
4492 return;
4493 }
4494 }
4495 InlayHintRefreshReason::SettingsChange(new_settings) => {
4496 match self.inlay_hint_cache.update_settings(
4497 &self.buffer,
4498 new_settings,
4499 self.visible_inlay_hints(cx),
4500 cx,
4501 ) {
4502 ControlFlow::Break(Some(InlaySplice {
4503 to_remove,
4504 to_insert,
4505 })) => {
4506 self.splice_inlays(&to_remove, to_insert, cx);
4507 return;
4508 }
4509 ControlFlow::Break(None) => return,
4510 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4511 }
4512 }
4513 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4514 if let Some(InlaySplice {
4515 to_remove,
4516 to_insert,
4517 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4518 {
4519 self.splice_inlays(&to_remove, to_insert, cx);
4520 }
4521 self.display_map.update(cx, |display_map, _| {
4522 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4523 });
4524 return;
4525 }
4526 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4527 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4528 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4529 }
4530 InlayHintRefreshReason::RefreshRequested => {
4531 (InvalidationStrategy::RefreshRequested, None)
4532 }
4533 };
4534
4535 if let Some(InlaySplice {
4536 to_remove,
4537 to_insert,
4538 }) = self.inlay_hint_cache.spawn_hint_refresh(
4539 reason_description,
4540 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4541 invalidate_cache,
4542 ignore_debounce,
4543 cx,
4544 ) {
4545 self.splice_inlays(&to_remove, to_insert, cx);
4546 }
4547 }
4548
4549 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4550 self.display_map
4551 .read(cx)
4552 .current_inlays()
4553 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4554 .cloned()
4555 .collect()
4556 }
4557
4558 pub fn excerpts_for_inlay_hints_query(
4559 &self,
4560 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4561 cx: &mut Context<Editor>,
4562 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4563 let Some(project) = self.project.as_ref() else {
4564 return HashMap::default();
4565 };
4566 let project = project.read(cx);
4567 let multi_buffer = self.buffer().read(cx);
4568 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4569 let multi_buffer_visible_start = self
4570 .scroll_manager
4571 .anchor()
4572 .anchor
4573 .to_point(&multi_buffer_snapshot);
4574 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4575 multi_buffer_visible_start
4576 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4577 Bias::Left,
4578 );
4579 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4580 multi_buffer_snapshot
4581 .range_to_buffer_ranges(multi_buffer_visible_range)
4582 .into_iter()
4583 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4584 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4585 let buffer_file = project::File::from_dyn(buffer.file())?;
4586 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4587 let worktree_entry = buffer_worktree
4588 .read(cx)
4589 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4590 if worktree_entry.is_ignored {
4591 return None;
4592 }
4593
4594 let language = buffer.language()?;
4595 if let Some(restrict_to_languages) = restrict_to_languages {
4596 if !restrict_to_languages.contains(language) {
4597 return None;
4598 }
4599 }
4600 Some((
4601 excerpt_id,
4602 (
4603 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4604 buffer.version().clone(),
4605 excerpt_visible_range,
4606 ),
4607 ))
4608 })
4609 .collect()
4610 }
4611
4612 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4613 TextLayoutDetails {
4614 text_system: window.text_system().clone(),
4615 editor_style: self.style.clone().unwrap(),
4616 rem_size: window.rem_size(),
4617 scroll_anchor: self.scroll_manager.anchor(),
4618 visible_rows: self.visible_line_count(),
4619 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4620 }
4621 }
4622
4623 pub fn splice_inlays(
4624 &self,
4625 to_remove: &[InlayId],
4626 to_insert: Vec<Inlay>,
4627 cx: &mut Context<Self>,
4628 ) {
4629 self.display_map.update(cx, |display_map, cx| {
4630 display_map.splice_inlays(to_remove, to_insert, cx)
4631 });
4632 cx.notify();
4633 }
4634
4635 fn trigger_on_type_formatting(
4636 &self,
4637 input: String,
4638 window: &mut Window,
4639 cx: &mut Context<Self>,
4640 ) -> Option<Task<Result<()>>> {
4641 if input.len() != 1 {
4642 return None;
4643 }
4644
4645 let project = self.project.as_ref()?;
4646 let position = self.selections.newest_anchor().head();
4647 let (buffer, buffer_position) = self
4648 .buffer
4649 .read(cx)
4650 .text_anchor_for_position(position, cx)?;
4651
4652 let settings = language_settings::language_settings(
4653 buffer
4654 .read(cx)
4655 .language_at(buffer_position)
4656 .map(|l| l.name()),
4657 buffer.read(cx).file(),
4658 cx,
4659 );
4660 if !settings.use_on_type_format {
4661 return None;
4662 }
4663
4664 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4665 // hence we do LSP request & edit on host side only — add formats to host's history.
4666 let push_to_lsp_host_history = true;
4667 // If this is not the host, append its history with new edits.
4668 let push_to_client_history = project.read(cx).is_via_collab();
4669
4670 let on_type_formatting = project.update(cx, |project, cx| {
4671 project.on_type_format(
4672 buffer.clone(),
4673 buffer_position,
4674 input,
4675 push_to_lsp_host_history,
4676 cx,
4677 )
4678 });
4679 Some(cx.spawn_in(window, async move |editor, cx| {
4680 if let Some(transaction) = on_type_formatting.await? {
4681 if push_to_client_history {
4682 buffer
4683 .update(cx, |buffer, _| {
4684 buffer.push_transaction(transaction, Instant::now());
4685 buffer.finalize_last_transaction();
4686 })
4687 .ok();
4688 }
4689 editor.update(cx, |editor, cx| {
4690 editor.refresh_document_highlights(cx);
4691 })?;
4692 }
4693 Ok(())
4694 }))
4695 }
4696
4697 pub fn show_word_completions(
4698 &mut self,
4699 _: &ShowWordCompletions,
4700 window: &mut Window,
4701 cx: &mut Context<Self>,
4702 ) {
4703 self.open_completions_menu(true, None, window, cx);
4704 }
4705
4706 pub fn show_completions(
4707 &mut self,
4708 options: &ShowCompletions,
4709 window: &mut Window,
4710 cx: &mut Context<Self>,
4711 ) {
4712 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4713 }
4714
4715 fn open_completions_menu(
4716 &mut self,
4717 ignore_completion_provider: bool,
4718 trigger: Option<&str>,
4719 window: &mut Window,
4720 cx: &mut Context<Self>,
4721 ) {
4722 if self.pending_rename.is_some() {
4723 return;
4724 }
4725 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4726 return;
4727 }
4728
4729 let position = self.selections.newest_anchor().head();
4730 if position.diff_base_anchor.is_some() {
4731 return;
4732 }
4733 let (buffer, buffer_position) =
4734 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4735 output
4736 } else {
4737 return;
4738 };
4739 let buffer_snapshot = buffer.read(cx).snapshot();
4740 let show_completion_documentation = buffer_snapshot
4741 .settings_at(buffer_position, cx)
4742 .show_completion_documentation;
4743
4744 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4745
4746 let trigger_kind = match trigger {
4747 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4748 CompletionTriggerKind::TRIGGER_CHARACTER
4749 }
4750 _ => CompletionTriggerKind::INVOKED,
4751 };
4752 let completion_context = CompletionContext {
4753 trigger_character: trigger.and_then(|trigger| {
4754 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4755 Some(String::from(trigger))
4756 } else {
4757 None
4758 }
4759 }),
4760 trigger_kind,
4761 };
4762
4763 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4764 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4765 let word_to_exclude = buffer_snapshot
4766 .text_for_range(old_range.clone())
4767 .collect::<String>();
4768 (
4769 buffer_snapshot.anchor_before(old_range.start)
4770 ..buffer_snapshot.anchor_after(old_range.end),
4771 Some(word_to_exclude),
4772 )
4773 } else {
4774 (buffer_position..buffer_position, None)
4775 };
4776
4777 let completion_settings = language_settings(
4778 buffer_snapshot
4779 .language_at(buffer_position)
4780 .map(|language| language.name()),
4781 buffer_snapshot.file(),
4782 cx,
4783 )
4784 .completions;
4785
4786 // The document can be large, so stay in reasonable bounds when searching for words,
4787 // otherwise completion pop-up might be slow to appear.
4788 const WORD_LOOKUP_ROWS: u32 = 5_000;
4789 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4790 let min_word_search = buffer_snapshot.clip_point(
4791 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4792 Bias::Left,
4793 );
4794 let max_word_search = buffer_snapshot.clip_point(
4795 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4796 Bias::Right,
4797 );
4798 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4799 ..buffer_snapshot.point_to_offset(max_word_search);
4800
4801 let provider = self
4802 .completion_provider
4803 .as_ref()
4804 .filter(|_| !ignore_completion_provider);
4805 let skip_digits = query
4806 .as_ref()
4807 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4808
4809 let (mut words, provided_completions) = match provider {
4810 Some(provider) => {
4811 let completions = provider.completions(
4812 position.excerpt_id,
4813 &buffer,
4814 buffer_position,
4815 completion_context,
4816 window,
4817 cx,
4818 );
4819
4820 let words = match completion_settings.words {
4821 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4822 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4823 .background_spawn(async move {
4824 buffer_snapshot.words_in_range(WordsQuery {
4825 fuzzy_contents: None,
4826 range: word_search_range,
4827 skip_digits,
4828 })
4829 }),
4830 };
4831
4832 (words, completions)
4833 }
4834 None => (
4835 cx.background_spawn(async move {
4836 buffer_snapshot.words_in_range(WordsQuery {
4837 fuzzy_contents: None,
4838 range: word_search_range,
4839 skip_digits,
4840 })
4841 }),
4842 Task::ready(Ok(None)),
4843 ),
4844 };
4845
4846 let sort_completions = provider
4847 .as_ref()
4848 .map_or(false, |provider| provider.sort_completions());
4849
4850 let filter_completions = provider
4851 .as_ref()
4852 .map_or(true, |provider| provider.filter_completions());
4853
4854 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4855
4856 let id = post_inc(&mut self.next_completion_id);
4857 let task = cx.spawn_in(window, async move |editor, cx| {
4858 async move {
4859 editor.update(cx, |this, _| {
4860 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4861 })?;
4862
4863 let mut completions = Vec::new();
4864 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4865 completions.extend(provided_completions);
4866 if completion_settings.words == WordsCompletionMode::Fallback {
4867 words = Task::ready(BTreeMap::default());
4868 }
4869 }
4870
4871 let mut words = words.await;
4872 if let Some(word_to_exclude) = &word_to_exclude {
4873 words.remove(word_to_exclude);
4874 }
4875 for lsp_completion in &completions {
4876 words.remove(&lsp_completion.new_text);
4877 }
4878 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4879 replace_range: old_range.clone(),
4880 new_text: word.clone(),
4881 label: CodeLabel::plain(word, None),
4882 icon_path: None,
4883 documentation: None,
4884 source: CompletionSource::BufferWord {
4885 word_range,
4886 resolved: false,
4887 },
4888 insert_text_mode: Some(InsertTextMode::AS_IS),
4889 confirm: None,
4890 }));
4891
4892 let menu = if completions.is_empty() {
4893 None
4894 } else {
4895 let mut menu = CompletionsMenu::new(
4896 id,
4897 sort_completions,
4898 show_completion_documentation,
4899 ignore_completion_provider,
4900 position,
4901 buffer.clone(),
4902 completions.into(),
4903 snippet_sort_order,
4904 );
4905
4906 menu.filter(
4907 if filter_completions {
4908 query.as_deref()
4909 } else {
4910 None
4911 },
4912 cx.background_executor().clone(),
4913 )
4914 .await;
4915
4916 menu.visible().then_some(menu)
4917 };
4918
4919 editor.update_in(cx, |editor, window, cx| {
4920 match editor.context_menu.borrow().as_ref() {
4921 None => {}
4922 Some(CodeContextMenu::Completions(prev_menu)) => {
4923 if prev_menu.id > id {
4924 return;
4925 }
4926 }
4927 _ => return,
4928 }
4929
4930 if editor.focus_handle.is_focused(window) && menu.is_some() {
4931 let mut menu = menu.unwrap();
4932 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4933
4934 *editor.context_menu.borrow_mut() =
4935 Some(CodeContextMenu::Completions(menu));
4936
4937 if editor.show_edit_predictions_in_menu() {
4938 editor.update_visible_inline_completion(window, cx);
4939 } else {
4940 editor.discard_inline_completion(false, cx);
4941 }
4942
4943 cx.notify();
4944 } else if editor.completion_tasks.len() <= 1 {
4945 // If there are no more completion tasks and the last menu was
4946 // empty, we should hide it.
4947 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4948 // If it was already hidden and we don't show inline
4949 // completions in the menu, we should also show the
4950 // inline-completion when available.
4951 if was_hidden && editor.show_edit_predictions_in_menu() {
4952 editor.update_visible_inline_completion(window, cx);
4953 }
4954 }
4955 })?;
4956
4957 anyhow::Ok(())
4958 }
4959 .log_err()
4960 .await
4961 });
4962
4963 self.completion_tasks.push((id, task));
4964 }
4965
4966 #[cfg(feature = "test-support")]
4967 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4968 let menu = self.context_menu.borrow();
4969 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4970 let completions = menu.completions.borrow();
4971 Some(completions.to_vec())
4972 } else {
4973 None
4974 }
4975 }
4976
4977 pub fn confirm_completion(
4978 &mut self,
4979 action: &ConfirmCompletion,
4980 window: &mut Window,
4981 cx: &mut Context<Self>,
4982 ) -> Option<Task<Result<()>>> {
4983 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4984 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4985 }
4986
4987 pub fn confirm_completion_insert(
4988 &mut self,
4989 _: &ConfirmCompletionInsert,
4990 window: &mut Window,
4991 cx: &mut Context<Self>,
4992 ) -> Option<Task<Result<()>>> {
4993 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4994 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4995 }
4996
4997 pub fn confirm_completion_replace(
4998 &mut self,
4999 _: &ConfirmCompletionReplace,
5000 window: &mut Window,
5001 cx: &mut Context<Self>,
5002 ) -> Option<Task<Result<()>>> {
5003 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5004 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
5005 }
5006
5007 pub fn compose_completion(
5008 &mut self,
5009 action: &ComposeCompletion,
5010 window: &mut Window,
5011 cx: &mut Context<Self>,
5012 ) -> Option<Task<Result<()>>> {
5013 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5014 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
5015 }
5016
5017 fn do_completion(
5018 &mut self,
5019 item_ix: Option<usize>,
5020 intent: CompletionIntent,
5021 window: &mut Window,
5022 cx: &mut Context<Editor>,
5023 ) -> Option<Task<Result<()>>> {
5024 use language::ToOffset as _;
5025
5026 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
5027 else {
5028 return None;
5029 };
5030
5031 let candidate_id = {
5032 let entries = completions_menu.entries.borrow();
5033 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
5034 if self.show_edit_predictions_in_menu() {
5035 self.discard_inline_completion(true, cx);
5036 }
5037 mat.candidate_id
5038 };
5039
5040 let buffer_handle = completions_menu.buffer;
5041 let completion = completions_menu
5042 .completions
5043 .borrow()
5044 .get(candidate_id)?
5045 .clone();
5046 cx.stop_propagation();
5047
5048 let snapshot = self.buffer.read(cx).snapshot(cx);
5049 let newest_anchor = self.selections.newest_anchor();
5050
5051 let snippet;
5052 let new_text;
5053 if completion.is_snippet() {
5054 let mut snippet_source = completion.new_text.clone();
5055 if let Some(scope) = snapshot.language_scope_at(newest_anchor.head()) {
5056 if scope.prefers_label_for_snippet_in_completion() {
5057 if let Some(label) = completion.label() {
5058 if matches!(
5059 completion.kind(),
5060 Some(CompletionItemKind::FUNCTION) | Some(CompletionItemKind::METHOD)
5061 ) {
5062 snippet_source = label;
5063 }
5064 }
5065 }
5066 }
5067 snippet = Some(Snippet::parse(&snippet_source).log_err()?);
5068 new_text = snippet.as_ref().unwrap().text.clone();
5069 } else {
5070 snippet = None;
5071 new_text = completion.new_text.clone();
5072 };
5073
5074 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
5075 let buffer = buffer_handle.read(cx);
5076 let replace_range_multibuffer = {
5077 let excerpt = snapshot.excerpt_containing(newest_anchor.range()).unwrap();
5078 let multibuffer_anchor = snapshot
5079 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
5080 .unwrap()
5081 ..snapshot
5082 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
5083 .unwrap();
5084 multibuffer_anchor.start.to_offset(&snapshot)
5085 ..multibuffer_anchor.end.to_offset(&snapshot)
5086 };
5087 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
5088 return None;
5089 }
5090
5091 let old_text = buffer
5092 .text_for_range(replace_range.clone())
5093 .collect::<String>();
5094 let lookbehind = newest_anchor
5095 .start
5096 .text_anchor
5097 .to_offset(buffer)
5098 .saturating_sub(replace_range.start);
5099 let lookahead = replace_range
5100 .end
5101 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
5102 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
5103 let suffix = &old_text[lookbehind.min(old_text.len())..];
5104
5105 let selections = self.selections.all::<usize>(cx);
5106 let mut ranges = Vec::new();
5107 let mut linked_edits = HashMap::<_, Vec<_>>::default();
5108
5109 for selection in &selections {
5110 let range = if selection.id == newest_anchor.id {
5111 replace_range_multibuffer.clone()
5112 } else {
5113 let mut range = selection.range();
5114
5115 // if prefix is present, don't duplicate it
5116 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
5117 range.start = range.start.saturating_sub(lookbehind);
5118
5119 // if suffix is also present, mimic the newest cursor and replace it
5120 if selection.id != newest_anchor.id
5121 && snapshot.contains_str_at(range.end, suffix)
5122 {
5123 range.end += lookahead;
5124 }
5125 }
5126 range
5127 };
5128
5129 ranges.push(range.clone());
5130
5131 if !self.linked_edit_ranges.is_empty() {
5132 let start_anchor = snapshot.anchor_before(range.start);
5133 let end_anchor = snapshot.anchor_after(range.end);
5134 if let Some(ranges) = self
5135 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5136 {
5137 for (buffer, edits) in ranges {
5138 linked_edits
5139 .entry(buffer.clone())
5140 .or_default()
5141 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5142 }
5143 }
5144 }
5145 }
5146
5147 cx.emit(EditorEvent::InputHandled {
5148 utf16_range_to_replace: None,
5149 text: new_text.clone().into(),
5150 });
5151
5152 self.transact(window, cx, |this, window, cx| {
5153 if let Some(mut snippet) = snippet {
5154 snippet.text = new_text.to_string();
5155 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5156 } else {
5157 this.buffer.update(cx, |buffer, cx| {
5158 let auto_indent = match completion.insert_text_mode {
5159 Some(InsertTextMode::AS_IS) => None,
5160 _ => this.autoindent_mode.clone(),
5161 };
5162 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5163 buffer.edit(edits, auto_indent, cx);
5164 });
5165 }
5166 for (buffer, edits) in linked_edits {
5167 buffer.update(cx, |buffer, cx| {
5168 let snapshot = buffer.snapshot();
5169 let edits = edits
5170 .into_iter()
5171 .map(|(range, text)| {
5172 use text::ToPoint as TP;
5173 let end_point = TP::to_point(&range.end, &snapshot);
5174 let start_point = TP::to_point(&range.start, &snapshot);
5175 (start_point..end_point, text)
5176 })
5177 .sorted_by_key(|(range, _)| range.start);
5178 buffer.edit(edits, None, cx);
5179 })
5180 }
5181
5182 this.refresh_inline_completion(true, false, window, cx);
5183 });
5184
5185 let show_new_completions_on_confirm = completion
5186 .confirm
5187 .as_ref()
5188 .map_or(false, |confirm| confirm(intent, window, cx));
5189 if show_new_completions_on_confirm {
5190 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5191 }
5192
5193 let provider = self.completion_provider.as_ref()?;
5194 drop(completion);
5195 let apply_edits = provider.apply_additional_edits_for_completion(
5196 buffer_handle,
5197 completions_menu.completions.clone(),
5198 candidate_id,
5199 true,
5200 cx,
5201 );
5202
5203 let editor_settings = EditorSettings::get_global(cx);
5204 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5205 // After the code completion is finished, users often want to know what signatures are needed.
5206 // so we should automatically call signature_help
5207 self.show_signature_help(&ShowSignatureHelp, window, cx);
5208 }
5209
5210 Some(cx.foreground_executor().spawn(async move {
5211 apply_edits.await?;
5212 Ok(())
5213 }))
5214 }
5215
5216 pub fn toggle_code_actions(
5217 &mut self,
5218 action: &ToggleCodeActions,
5219 window: &mut Window,
5220 cx: &mut Context<Self>,
5221 ) {
5222 let quick_launch = action.quick_launch;
5223 let mut context_menu = self.context_menu.borrow_mut();
5224 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5225 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5226 // Toggle if we're selecting the same one
5227 *context_menu = None;
5228 cx.notify();
5229 return;
5230 } else {
5231 // Otherwise, clear it and start a new one
5232 *context_menu = None;
5233 cx.notify();
5234 }
5235 }
5236 drop(context_menu);
5237 let snapshot = self.snapshot(window, cx);
5238 let deployed_from_indicator = action.deployed_from_indicator;
5239 let mut task = self.code_actions_task.take();
5240 let action = action.clone();
5241 cx.spawn_in(window, async move |editor, cx| {
5242 while let Some(prev_task) = task {
5243 prev_task.await.log_err();
5244 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5245 }
5246
5247 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5248 if editor.focus_handle.is_focused(window) {
5249 let multibuffer_point = action
5250 .deployed_from_indicator
5251 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5252 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5253 let (buffer, buffer_row) = snapshot
5254 .buffer_snapshot
5255 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5256 .and_then(|(buffer_snapshot, range)| {
5257 editor
5258 .buffer
5259 .read(cx)
5260 .buffer(buffer_snapshot.remote_id())
5261 .map(|buffer| (buffer, range.start.row))
5262 })?;
5263 let (_, code_actions) = editor
5264 .available_code_actions
5265 .clone()
5266 .and_then(|(location, code_actions)| {
5267 let snapshot = location.buffer.read(cx).snapshot();
5268 let point_range = location.range.to_point(&snapshot);
5269 let point_range = point_range.start.row..=point_range.end.row;
5270 if point_range.contains(&buffer_row) {
5271 Some((location, code_actions))
5272 } else {
5273 None
5274 }
5275 })
5276 .unzip();
5277 let buffer_id = buffer.read(cx).remote_id();
5278 let tasks = editor
5279 .tasks
5280 .get(&(buffer_id, buffer_row))
5281 .map(|t| Arc::new(t.to_owned()));
5282 if tasks.is_none() && code_actions.is_none() {
5283 return None;
5284 }
5285
5286 editor.completion_tasks.clear();
5287 editor.discard_inline_completion(false, cx);
5288 let task_context =
5289 tasks
5290 .as_ref()
5291 .zip(editor.project.clone())
5292 .map(|(tasks, project)| {
5293 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5294 });
5295
5296 Some(cx.spawn_in(window, async move |editor, cx| {
5297 let task_context = match task_context {
5298 Some(task_context) => task_context.await,
5299 None => None,
5300 };
5301 let resolved_tasks =
5302 tasks
5303 .zip(task_context.clone())
5304 .map(|(tasks, task_context)| ResolvedTasks {
5305 templates: tasks.resolve(&task_context).collect(),
5306 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5307 multibuffer_point.row,
5308 tasks.column,
5309 )),
5310 });
5311 let debug_scenarios = editor.update(cx, |editor, cx| {
5312 if cx.has_flag::<DebuggerFeatureFlag>() {
5313 maybe!({
5314 let project = editor.project.as_ref()?;
5315 let dap_store = project.read(cx).dap_store();
5316 let mut scenarios = vec![];
5317 let resolved_tasks = resolved_tasks.as_ref()?;
5318 let buffer = buffer.read(cx);
5319 let language = buffer.language()?;
5320 let file = buffer.file();
5321 let debug_adapter =
5322 language_settings(language.name().into(), file, cx)
5323 .debuggers
5324 .first()
5325 .map(SharedString::from)
5326 .or_else(|| {
5327 language
5328 .config()
5329 .debuggers
5330 .first()
5331 .map(SharedString::from)
5332 })?;
5333
5334 dap_store.update(cx, |this, cx| {
5335 for (_, task) in &resolved_tasks.templates {
5336 if let Some(scenario) = this
5337 .debug_scenario_for_build_task(
5338 task.original_task().clone(),
5339 debug_adapter.clone().into(),
5340 task.display_label().to_owned().into(),
5341 cx,
5342 )
5343 {
5344 scenarios.push(scenario);
5345 }
5346 }
5347 });
5348 Some(scenarios)
5349 })
5350 .unwrap_or_default()
5351 } else {
5352 vec![]
5353 }
5354 })?;
5355 let spawn_straight_away = quick_launch
5356 && resolved_tasks
5357 .as_ref()
5358 .map_or(false, |tasks| tasks.templates.len() == 1)
5359 && code_actions
5360 .as_ref()
5361 .map_or(true, |actions| actions.is_empty())
5362 && debug_scenarios.is_empty();
5363 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5364 *editor.context_menu.borrow_mut() =
5365 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5366 buffer,
5367 actions: CodeActionContents::new(
5368 resolved_tasks,
5369 code_actions,
5370 debug_scenarios,
5371 task_context.unwrap_or_default(),
5372 ),
5373 selected_item: Default::default(),
5374 scroll_handle: UniformListScrollHandle::default(),
5375 deployed_from_indicator,
5376 }));
5377 if spawn_straight_away {
5378 if let Some(task) = editor.confirm_code_action(
5379 &ConfirmCodeAction { item_ix: Some(0) },
5380 window,
5381 cx,
5382 ) {
5383 cx.notify();
5384 return task;
5385 }
5386 }
5387 cx.notify();
5388 Task::ready(Ok(()))
5389 }) {
5390 task.await
5391 } else {
5392 Ok(())
5393 }
5394 }))
5395 } else {
5396 Some(Task::ready(Ok(())))
5397 }
5398 })?;
5399 if let Some(task) = spawned_test_task {
5400 task.await?;
5401 }
5402
5403 Ok::<_, anyhow::Error>(())
5404 })
5405 .detach_and_log_err(cx);
5406 }
5407
5408 pub fn confirm_code_action(
5409 &mut self,
5410 action: &ConfirmCodeAction,
5411 window: &mut Window,
5412 cx: &mut Context<Self>,
5413 ) -> Option<Task<Result<()>>> {
5414 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5415
5416 let actions_menu =
5417 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5418 menu
5419 } else {
5420 return None;
5421 };
5422
5423 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5424 let action = actions_menu.actions.get(action_ix)?;
5425 let title = action.label();
5426 let buffer = actions_menu.buffer;
5427 let workspace = self.workspace()?;
5428
5429 match action {
5430 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5431 workspace.update(cx, |workspace, cx| {
5432 workspace.schedule_resolved_task(
5433 task_source_kind,
5434 resolved_task,
5435 false,
5436 window,
5437 cx,
5438 );
5439
5440 Some(Task::ready(Ok(())))
5441 })
5442 }
5443 CodeActionsItem::CodeAction {
5444 excerpt_id,
5445 action,
5446 provider,
5447 } => {
5448 let apply_code_action =
5449 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5450 let workspace = workspace.downgrade();
5451 Some(cx.spawn_in(window, async move |editor, cx| {
5452 let project_transaction = apply_code_action.await?;
5453 Self::open_project_transaction(
5454 &editor,
5455 workspace,
5456 project_transaction,
5457 title,
5458 cx,
5459 )
5460 .await
5461 }))
5462 }
5463 CodeActionsItem::DebugScenario(scenario) => {
5464 let context = actions_menu.actions.context.clone();
5465
5466 workspace.update(cx, |workspace, cx| {
5467 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5468 });
5469 Some(Task::ready(Ok(())))
5470 }
5471 }
5472 }
5473
5474 pub async fn open_project_transaction(
5475 this: &WeakEntity<Editor>,
5476 workspace: WeakEntity<Workspace>,
5477 transaction: ProjectTransaction,
5478 title: String,
5479 cx: &mut AsyncWindowContext,
5480 ) -> Result<()> {
5481 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5482 cx.update(|_, cx| {
5483 entries.sort_unstable_by_key(|(buffer, _)| {
5484 buffer.read(cx).file().map(|f| f.path().clone())
5485 });
5486 })?;
5487
5488 // If the project transaction's edits are all contained within this editor, then
5489 // avoid opening a new editor to display them.
5490
5491 if let Some((buffer, transaction)) = entries.first() {
5492 if entries.len() == 1 {
5493 let excerpt = this.update(cx, |editor, cx| {
5494 editor
5495 .buffer()
5496 .read(cx)
5497 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5498 })?;
5499 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5500 if excerpted_buffer == *buffer {
5501 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5502 let excerpt_range = excerpt_range.to_offset(buffer);
5503 buffer
5504 .edited_ranges_for_transaction::<usize>(transaction)
5505 .all(|range| {
5506 excerpt_range.start <= range.start
5507 && excerpt_range.end >= range.end
5508 })
5509 })?;
5510
5511 if all_edits_within_excerpt {
5512 return Ok(());
5513 }
5514 }
5515 }
5516 }
5517 } else {
5518 return Ok(());
5519 }
5520
5521 let mut ranges_to_highlight = Vec::new();
5522 let excerpt_buffer = cx.new(|cx| {
5523 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5524 for (buffer_handle, transaction) in &entries {
5525 let edited_ranges = buffer_handle
5526 .read(cx)
5527 .edited_ranges_for_transaction::<Point>(transaction)
5528 .collect::<Vec<_>>();
5529 let (ranges, _) = multibuffer.set_excerpts_for_path(
5530 PathKey::for_buffer(buffer_handle, cx),
5531 buffer_handle.clone(),
5532 edited_ranges,
5533 DEFAULT_MULTIBUFFER_CONTEXT,
5534 cx,
5535 );
5536
5537 ranges_to_highlight.extend(ranges);
5538 }
5539 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5540 multibuffer
5541 })?;
5542
5543 workspace.update_in(cx, |workspace, window, cx| {
5544 let project = workspace.project().clone();
5545 let editor =
5546 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5547 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5548 editor.update(cx, |editor, cx| {
5549 editor.highlight_background::<Self>(
5550 &ranges_to_highlight,
5551 |theme| theme.editor_highlighted_line_background,
5552 cx,
5553 );
5554 });
5555 })?;
5556
5557 Ok(())
5558 }
5559
5560 pub fn clear_code_action_providers(&mut self) {
5561 self.code_action_providers.clear();
5562 self.available_code_actions.take();
5563 }
5564
5565 pub fn add_code_action_provider(
5566 &mut self,
5567 provider: Rc<dyn CodeActionProvider>,
5568 window: &mut Window,
5569 cx: &mut Context<Self>,
5570 ) {
5571 if self
5572 .code_action_providers
5573 .iter()
5574 .any(|existing_provider| existing_provider.id() == provider.id())
5575 {
5576 return;
5577 }
5578
5579 self.code_action_providers.push(provider);
5580 self.refresh_code_actions(window, cx);
5581 }
5582
5583 pub fn remove_code_action_provider(
5584 &mut self,
5585 id: Arc<str>,
5586 window: &mut Window,
5587 cx: &mut Context<Self>,
5588 ) {
5589 self.code_action_providers
5590 .retain(|provider| provider.id() != id);
5591 self.refresh_code_actions(window, cx);
5592 }
5593
5594 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5595 let newest_selection = self.selections.newest_anchor().clone();
5596 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5597 let buffer = self.buffer.read(cx);
5598 if newest_selection.head().diff_base_anchor.is_some() {
5599 return None;
5600 }
5601 let (start_buffer, start) =
5602 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5603 let (end_buffer, end) =
5604 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5605 if start_buffer != end_buffer {
5606 return None;
5607 }
5608
5609 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5610 cx.background_executor()
5611 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5612 .await;
5613
5614 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5615 let providers = this.code_action_providers.clone();
5616 let tasks = this
5617 .code_action_providers
5618 .iter()
5619 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5620 .collect::<Vec<_>>();
5621 (providers, tasks)
5622 })?;
5623
5624 let mut actions = Vec::new();
5625 for (provider, provider_actions) in
5626 providers.into_iter().zip(future::join_all(tasks).await)
5627 {
5628 if let Some(provider_actions) = provider_actions.log_err() {
5629 actions.extend(provider_actions.into_iter().map(|action| {
5630 AvailableCodeAction {
5631 excerpt_id: newest_selection.start.excerpt_id,
5632 action,
5633 provider: provider.clone(),
5634 }
5635 }));
5636 }
5637 }
5638
5639 this.update(cx, |this, cx| {
5640 this.available_code_actions = if actions.is_empty() {
5641 None
5642 } else {
5643 Some((
5644 Location {
5645 buffer: start_buffer,
5646 range: start..end,
5647 },
5648 actions.into(),
5649 ))
5650 };
5651 cx.notify();
5652 })
5653 }));
5654 None
5655 }
5656
5657 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5658 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5659 self.show_git_blame_inline = false;
5660
5661 self.show_git_blame_inline_delay_task =
5662 Some(cx.spawn_in(window, async move |this, cx| {
5663 cx.background_executor().timer(delay).await;
5664
5665 this.update(cx, |this, cx| {
5666 this.show_git_blame_inline = true;
5667 cx.notify();
5668 })
5669 .log_err();
5670 }));
5671 }
5672 }
5673
5674 fn show_blame_popover(
5675 &mut self,
5676 blame_entry: &BlameEntry,
5677 position: gpui::Point<Pixels>,
5678 cx: &mut Context<Self>,
5679 ) {
5680 if let Some(state) = &mut self.inline_blame_popover {
5681 state.hide_task.take();
5682 cx.notify();
5683 } else {
5684 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5685 let show_task = cx.spawn(async move |editor, cx| {
5686 cx.background_executor()
5687 .timer(std::time::Duration::from_millis(delay))
5688 .await;
5689 editor
5690 .update(cx, |editor, cx| {
5691 if let Some(state) = &mut editor.inline_blame_popover {
5692 state.show_task = None;
5693 cx.notify();
5694 }
5695 })
5696 .ok();
5697 });
5698 let Some(blame) = self.blame.as_ref() else {
5699 return;
5700 };
5701 let blame = blame.read(cx);
5702 let details = blame.details_for_entry(&blame_entry);
5703 let markdown = cx.new(|cx| {
5704 Markdown::new(
5705 details
5706 .as_ref()
5707 .map(|message| message.message.clone())
5708 .unwrap_or_default(),
5709 None,
5710 None,
5711 cx,
5712 )
5713 });
5714 self.inline_blame_popover = Some(InlineBlamePopover {
5715 position,
5716 show_task: Some(show_task),
5717 hide_task: None,
5718 popover_bounds: None,
5719 popover_state: InlineBlamePopoverState {
5720 scroll_handle: ScrollHandle::new(),
5721 commit_message: details,
5722 markdown,
5723 },
5724 });
5725 }
5726 }
5727
5728 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5729 if let Some(state) = &mut self.inline_blame_popover {
5730 if state.show_task.is_some() {
5731 self.inline_blame_popover.take();
5732 cx.notify();
5733 } else {
5734 let hide_task = cx.spawn(async move |editor, cx| {
5735 cx.background_executor()
5736 .timer(std::time::Duration::from_millis(100))
5737 .await;
5738 editor
5739 .update(cx, |editor, cx| {
5740 editor.inline_blame_popover.take();
5741 cx.notify();
5742 })
5743 .ok();
5744 });
5745 state.hide_task = Some(hide_task);
5746 }
5747 }
5748 }
5749
5750 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5751 if self.pending_rename.is_some() {
5752 return None;
5753 }
5754
5755 let provider = self.semantics_provider.clone()?;
5756 let buffer = self.buffer.read(cx);
5757 let newest_selection = self.selections.newest_anchor().clone();
5758 let cursor_position = newest_selection.head();
5759 let (cursor_buffer, cursor_buffer_position) =
5760 buffer.text_anchor_for_position(cursor_position, cx)?;
5761 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5762 if cursor_buffer != tail_buffer {
5763 return None;
5764 }
5765 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5766 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5767 cx.background_executor()
5768 .timer(Duration::from_millis(debounce))
5769 .await;
5770
5771 let highlights = if let Some(highlights) = cx
5772 .update(|cx| {
5773 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5774 })
5775 .ok()
5776 .flatten()
5777 {
5778 highlights.await.log_err()
5779 } else {
5780 None
5781 };
5782
5783 if let Some(highlights) = highlights {
5784 this.update(cx, |this, cx| {
5785 if this.pending_rename.is_some() {
5786 return;
5787 }
5788
5789 let buffer_id = cursor_position.buffer_id;
5790 let buffer = this.buffer.read(cx);
5791 if !buffer
5792 .text_anchor_for_position(cursor_position, cx)
5793 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5794 {
5795 return;
5796 }
5797
5798 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5799 let mut write_ranges = Vec::new();
5800 let mut read_ranges = Vec::new();
5801 for highlight in highlights {
5802 for (excerpt_id, excerpt_range) in
5803 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5804 {
5805 let start = highlight
5806 .range
5807 .start
5808 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5809 let end = highlight
5810 .range
5811 .end
5812 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5813 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5814 continue;
5815 }
5816
5817 let range = Anchor {
5818 buffer_id,
5819 excerpt_id,
5820 text_anchor: start,
5821 diff_base_anchor: None,
5822 }..Anchor {
5823 buffer_id,
5824 excerpt_id,
5825 text_anchor: end,
5826 diff_base_anchor: None,
5827 };
5828 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5829 write_ranges.push(range);
5830 } else {
5831 read_ranges.push(range);
5832 }
5833 }
5834 }
5835
5836 this.highlight_background::<DocumentHighlightRead>(
5837 &read_ranges,
5838 |theme| theme.editor_document_highlight_read_background,
5839 cx,
5840 );
5841 this.highlight_background::<DocumentHighlightWrite>(
5842 &write_ranges,
5843 |theme| theme.editor_document_highlight_write_background,
5844 cx,
5845 );
5846 cx.notify();
5847 })
5848 .log_err();
5849 }
5850 }));
5851 None
5852 }
5853
5854 fn prepare_highlight_query_from_selection(
5855 &mut self,
5856 cx: &mut Context<Editor>,
5857 ) -> Option<(String, Range<Anchor>)> {
5858 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5859 return None;
5860 }
5861 if !EditorSettings::get_global(cx).selection_highlight {
5862 return None;
5863 }
5864 if self.selections.count() != 1 || self.selections.line_mode {
5865 return None;
5866 }
5867 let selection = self.selections.newest::<Point>(cx);
5868 if selection.is_empty() || selection.start.row != selection.end.row {
5869 return None;
5870 }
5871 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5872 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5873 let query = multi_buffer_snapshot
5874 .text_for_range(selection_anchor_range.clone())
5875 .collect::<String>();
5876 if query.trim().is_empty() {
5877 return None;
5878 }
5879 Some((query, selection_anchor_range))
5880 }
5881
5882 fn update_selection_occurrence_highlights(
5883 &mut self,
5884 query_text: String,
5885 query_range: Range<Anchor>,
5886 multi_buffer_range_to_query: Range<Point>,
5887 use_debounce: bool,
5888 window: &mut Window,
5889 cx: &mut Context<Editor>,
5890 ) -> Task<()> {
5891 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5892 cx.spawn_in(window, async move |editor, cx| {
5893 if use_debounce {
5894 cx.background_executor()
5895 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5896 .await;
5897 }
5898 let match_task = cx.background_spawn(async move {
5899 let buffer_ranges = multi_buffer_snapshot
5900 .range_to_buffer_ranges(multi_buffer_range_to_query)
5901 .into_iter()
5902 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5903 let mut match_ranges = Vec::new();
5904 let Ok(regex) = project::search::SearchQuery::text(
5905 query_text.clone(),
5906 false,
5907 false,
5908 false,
5909 Default::default(),
5910 Default::default(),
5911 false,
5912 None,
5913 ) else {
5914 return Vec::default();
5915 };
5916 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5917 match_ranges.extend(
5918 regex
5919 .search(&buffer_snapshot, Some(search_range.clone()))
5920 .await
5921 .into_iter()
5922 .filter_map(|match_range| {
5923 let match_start = buffer_snapshot
5924 .anchor_after(search_range.start + match_range.start);
5925 let match_end = buffer_snapshot
5926 .anchor_before(search_range.start + match_range.end);
5927 let match_anchor_range = Anchor::range_in_buffer(
5928 excerpt_id,
5929 buffer_snapshot.remote_id(),
5930 match_start..match_end,
5931 );
5932 (match_anchor_range != query_range).then_some(match_anchor_range)
5933 }),
5934 );
5935 }
5936 match_ranges
5937 });
5938 let match_ranges = match_task.await;
5939 editor
5940 .update_in(cx, |editor, _, cx| {
5941 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5942 if !match_ranges.is_empty() {
5943 editor.highlight_background::<SelectedTextHighlight>(
5944 &match_ranges,
5945 |theme| theme.editor_document_highlight_bracket_background,
5946 cx,
5947 )
5948 }
5949 })
5950 .log_err();
5951 })
5952 }
5953
5954 fn refresh_selected_text_highlights(
5955 &mut self,
5956 on_buffer_edit: bool,
5957 window: &mut Window,
5958 cx: &mut Context<Editor>,
5959 ) {
5960 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5961 else {
5962 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5963 self.quick_selection_highlight_task.take();
5964 self.debounced_selection_highlight_task.take();
5965 return;
5966 };
5967 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5968 if on_buffer_edit
5969 || self
5970 .quick_selection_highlight_task
5971 .as_ref()
5972 .map_or(true, |(prev_anchor_range, _)| {
5973 prev_anchor_range != &query_range
5974 })
5975 {
5976 let multi_buffer_visible_start = self
5977 .scroll_manager
5978 .anchor()
5979 .anchor
5980 .to_point(&multi_buffer_snapshot);
5981 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5982 multi_buffer_visible_start
5983 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5984 Bias::Left,
5985 );
5986 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5987 self.quick_selection_highlight_task = Some((
5988 query_range.clone(),
5989 self.update_selection_occurrence_highlights(
5990 query_text.clone(),
5991 query_range.clone(),
5992 multi_buffer_visible_range,
5993 false,
5994 window,
5995 cx,
5996 ),
5997 ));
5998 }
5999 if on_buffer_edit
6000 || self
6001 .debounced_selection_highlight_task
6002 .as_ref()
6003 .map_or(true, |(prev_anchor_range, _)| {
6004 prev_anchor_range != &query_range
6005 })
6006 {
6007 let multi_buffer_start = multi_buffer_snapshot
6008 .anchor_before(0)
6009 .to_point(&multi_buffer_snapshot);
6010 let multi_buffer_end = multi_buffer_snapshot
6011 .anchor_after(multi_buffer_snapshot.len())
6012 .to_point(&multi_buffer_snapshot);
6013 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
6014 self.debounced_selection_highlight_task = Some((
6015 query_range.clone(),
6016 self.update_selection_occurrence_highlights(
6017 query_text,
6018 query_range,
6019 multi_buffer_full_range,
6020 true,
6021 window,
6022 cx,
6023 ),
6024 ));
6025 }
6026 }
6027
6028 pub fn refresh_inline_completion(
6029 &mut self,
6030 debounce: bool,
6031 user_requested: bool,
6032 window: &mut Window,
6033 cx: &mut Context<Self>,
6034 ) -> Option<()> {
6035 let provider = self.edit_prediction_provider()?;
6036 let cursor = self.selections.newest_anchor().head();
6037 let (buffer, cursor_buffer_position) =
6038 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6039
6040 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
6041 self.discard_inline_completion(false, cx);
6042 return None;
6043 }
6044
6045 if !user_requested
6046 && (!self.should_show_edit_predictions()
6047 || !self.is_focused(window)
6048 || buffer.read(cx).is_empty())
6049 {
6050 self.discard_inline_completion(false, cx);
6051 return None;
6052 }
6053
6054 self.update_visible_inline_completion(window, cx);
6055 provider.refresh(
6056 self.project.clone(),
6057 buffer,
6058 cursor_buffer_position,
6059 debounce,
6060 cx,
6061 );
6062 Some(())
6063 }
6064
6065 fn show_edit_predictions_in_menu(&self) -> bool {
6066 match self.edit_prediction_settings {
6067 EditPredictionSettings::Disabled => false,
6068 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
6069 }
6070 }
6071
6072 pub fn edit_predictions_enabled(&self) -> bool {
6073 match self.edit_prediction_settings {
6074 EditPredictionSettings::Disabled => false,
6075 EditPredictionSettings::Enabled { .. } => true,
6076 }
6077 }
6078
6079 fn edit_prediction_requires_modifier(&self) -> bool {
6080 match self.edit_prediction_settings {
6081 EditPredictionSettings::Disabled => false,
6082 EditPredictionSettings::Enabled {
6083 preview_requires_modifier,
6084 ..
6085 } => preview_requires_modifier,
6086 }
6087 }
6088
6089 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
6090 if self.edit_prediction_provider.is_none() {
6091 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6092 } else {
6093 let selection = self.selections.newest_anchor();
6094 let cursor = selection.head();
6095
6096 if let Some((buffer, cursor_buffer_position)) =
6097 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6098 {
6099 self.edit_prediction_settings =
6100 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6101 }
6102 }
6103 }
6104
6105 fn edit_prediction_settings_at_position(
6106 &self,
6107 buffer: &Entity<Buffer>,
6108 buffer_position: language::Anchor,
6109 cx: &App,
6110 ) -> EditPredictionSettings {
6111 if !self.mode.is_full()
6112 || !self.show_inline_completions_override.unwrap_or(true)
6113 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
6114 {
6115 return EditPredictionSettings::Disabled;
6116 }
6117
6118 let buffer = buffer.read(cx);
6119
6120 let file = buffer.file();
6121
6122 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
6123 return EditPredictionSettings::Disabled;
6124 };
6125
6126 let by_provider = matches!(
6127 self.menu_inline_completions_policy,
6128 MenuInlineCompletionsPolicy::ByProvider
6129 );
6130
6131 let show_in_menu = by_provider
6132 && self
6133 .edit_prediction_provider
6134 .as_ref()
6135 .map_or(false, |provider| {
6136 provider.provider.show_completions_in_menu()
6137 });
6138
6139 let preview_requires_modifier =
6140 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6141
6142 EditPredictionSettings::Enabled {
6143 show_in_menu,
6144 preview_requires_modifier,
6145 }
6146 }
6147
6148 fn should_show_edit_predictions(&self) -> bool {
6149 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6150 }
6151
6152 pub fn edit_prediction_preview_is_active(&self) -> bool {
6153 matches!(
6154 self.edit_prediction_preview,
6155 EditPredictionPreview::Active { .. }
6156 )
6157 }
6158
6159 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6160 let cursor = self.selections.newest_anchor().head();
6161 if let Some((buffer, cursor_position)) =
6162 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6163 {
6164 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6165 } else {
6166 false
6167 }
6168 }
6169
6170 pub fn supports_minimap(&self, cx: &App) -> bool {
6171 !self.minimap_visibility.disabled() && self.is_singleton(cx)
6172 }
6173
6174 fn edit_predictions_enabled_in_buffer(
6175 &self,
6176 buffer: &Entity<Buffer>,
6177 buffer_position: language::Anchor,
6178 cx: &App,
6179 ) -> bool {
6180 maybe!({
6181 if self.read_only(cx) {
6182 return Some(false);
6183 }
6184 let provider = self.edit_prediction_provider()?;
6185 if !provider.is_enabled(&buffer, buffer_position, cx) {
6186 return Some(false);
6187 }
6188 let buffer = buffer.read(cx);
6189 let Some(file) = buffer.file() else {
6190 return Some(true);
6191 };
6192 let settings = all_language_settings(Some(file), cx);
6193 Some(settings.edit_predictions_enabled_for_file(file, cx))
6194 })
6195 .unwrap_or(false)
6196 }
6197
6198 fn cycle_inline_completion(
6199 &mut self,
6200 direction: Direction,
6201 window: &mut Window,
6202 cx: &mut Context<Self>,
6203 ) -> Option<()> {
6204 let provider = self.edit_prediction_provider()?;
6205 let cursor = self.selections.newest_anchor().head();
6206 let (buffer, cursor_buffer_position) =
6207 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6208 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6209 return None;
6210 }
6211
6212 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6213 self.update_visible_inline_completion(window, cx);
6214
6215 Some(())
6216 }
6217
6218 pub fn show_inline_completion(
6219 &mut self,
6220 _: &ShowEditPrediction,
6221 window: &mut Window,
6222 cx: &mut Context<Self>,
6223 ) {
6224 if !self.has_active_inline_completion() {
6225 self.refresh_inline_completion(false, true, window, cx);
6226 return;
6227 }
6228
6229 self.update_visible_inline_completion(window, cx);
6230 }
6231
6232 pub fn display_cursor_names(
6233 &mut self,
6234 _: &DisplayCursorNames,
6235 window: &mut Window,
6236 cx: &mut Context<Self>,
6237 ) {
6238 self.show_cursor_names(window, cx);
6239 }
6240
6241 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6242 self.show_cursor_names = true;
6243 cx.notify();
6244 cx.spawn_in(window, async move |this, cx| {
6245 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6246 this.update(cx, |this, cx| {
6247 this.show_cursor_names = false;
6248 cx.notify()
6249 })
6250 .ok()
6251 })
6252 .detach();
6253 }
6254
6255 pub fn next_edit_prediction(
6256 &mut self,
6257 _: &NextEditPrediction,
6258 window: &mut Window,
6259 cx: &mut Context<Self>,
6260 ) {
6261 if self.has_active_inline_completion() {
6262 self.cycle_inline_completion(Direction::Next, window, cx);
6263 } else {
6264 let is_copilot_disabled = self
6265 .refresh_inline_completion(false, true, window, cx)
6266 .is_none();
6267 if is_copilot_disabled {
6268 cx.propagate();
6269 }
6270 }
6271 }
6272
6273 pub fn previous_edit_prediction(
6274 &mut self,
6275 _: &PreviousEditPrediction,
6276 window: &mut Window,
6277 cx: &mut Context<Self>,
6278 ) {
6279 if self.has_active_inline_completion() {
6280 self.cycle_inline_completion(Direction::Prev, window, cx);
6281 } else {
6282 let is_copilot_disabled = self
6283 .refresh_inline_completion(false, true, window, cx)
6284 .is_none();
6285 if is_copilot_disabled {
6286 cx.propagate();
6287 }
6288 }
6289 }
6290
6291 pub fn accept_edit_prediction(
6292 &mut self,
6293 _: &AcceptEditPrediction,
6294 window: &mut Window,
6295 cx: &mut Context<Self>,
6296 ) {
6297 if self.show_edit_predictions_in_menu() {
6298 self.hide_context_menu(window, cx);
6299 }
6300
6301 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6302 return;
6303 };
6304
6305 self.report_inline_completion_event(
6306 active_inline_completion.completion_id.clone(),
6307 true,
6308 cx,
6309 );
6310
6311 match &active_inline_completion.completion {
6312 InlineCompletion::Move { target, .. } => {
6313 let target = *target;
6314
6315 if let Some(position_map) = &self.last_position_map {
6316 if position_map
6317 .visible_row_range
6318 .contains(&target.to_display_point(&position_map.snapshot).row())
6319 || !self.edit_prediction_requires_modifier()
6320 {
6321 self.unfold_ranges(&[target..target], true, false, cx);
6322 // Note that this is also done in vim's handler of the Tab action.
6323 self.change_selections(
6324 Some(Autoscroll::newest()),
6325 window,
6326 cx,
6327 |selections| {
6328 selections.select_anchor_ranges([target..target]);
6329 },
6330 );
6331 self.clear_row_highlights::<EditPredictionPreview>();
6332
6333 self.edit_prediction_preview
6334 .set_previous_scroll_position(None);
6335 } else {
6336 self.edit_prediction_preview
6337 .set_previous_scroll_position(Some(
6338 position_map.snapshot.scroll_anchor,
6339 ));
6340
6341 self.highlight_rows::<EditPredictionPreview>(
6342 target..target,
6343 cx.theme().colors().editor_highlighted_line_background,
6344 RowHighlightOptions {
6345 autoscroll: true,
6346 ..Default::default()
6347 },
6348 cx,
6349 );
6350 self.request_autoscroll(Autoscroll::fit(), cx);
6351 }
6352 }
6353 }
6354 InlineCompletion::Edit { edits, .. } => {
6355 if let Some(provider) = self.edit_prediction_provider() {
6356 provider.accept(cx);
6357 }
6358
6359 let snapshot = self.buffer.read(cx).snapshot(cx);
6360 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6361
6362 self.buffer.update(cx, |buffer, cx| {
6363 buffer.edit(edits.iter().cloned(), None, cx)
6364 });
6365
6366 self.change_selections(None, window, cx, |s| {
6367 s.select_anchor_ranges([last_edit_end..last_edit_end])
6368 });
6369
6370 self.update_visible_inline_completion(window, cx);
6371 if self.active_inline_completion.is_none() {
6372 self.refresh_inline_completion(true, true, window, cx);
6373 }
6374
6375 cx.notify();
6376 }
6377 }
6378
6379 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6380 }
6381
6382 pub fn accept_partial_inline_completion(
6383 &mut self,
6384 _: &AcceptPartialEditPrediction,
6385 window: &mut Window,
6386 cx: &mut Context<Self>,
6387 ) {
6388 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6389 return;
6390 };
6391 if self.selections.count() != 1 {
6392 return;
6393 }
6394
6395 self.report_inline_completion_event(
6396 active_inline_completion.completion_id.clone(),
6397 true,
6398 cx,
6399 );
6400
6401 match &active_inline_completion.completion {
6402 InlineCompletion::Move { target, .. } => {
6403 let target = *target;
6404 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6405 selections.select_anchor_ranges([target..target]);
6406 });
6407 }
6408 InlineCompletion::Edit { edits, .. } => {
6409 // Find an insertion that starts at the cursor position.
6410 let snapshot = self.buffer.read(cx).snapshot(cx);
6411 let cursor_offset = self.selections.newest::<usize>(cx).head();
6412 let insertion = edits.iter().find_map(|(range, text)| {
6413 let range = range.to_offset(&snapshot);
6414 if range.is_empty() && range.start == cursor_offset {
6415 Some(text)
6416 } else {
6417 None
6418 }
6419 });
6420
6421 if let Some(text) = insertion {
6422 let mut partial_completion = text
6423 .chars()
6424 .by_ref()
6425 .take_while(|c| c.is_alphabetic())
6426 .collect::<String>();
6427 if partial_completion.is_empty() {
6428 partial_completion = text
6429 .chars()
6430 .by_ref()
6431 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6432 .collect::<String>();
6433 }
6434
6435 cx.emit(EditorEvent::InputHandled {
6436 utf16_range_to_replace: None,
6437 text: partial_completion.clone().into(),
6438 });
6439
6440 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6441
6442 self.refresh_inline_completion(true, true, window, cx);
6443 cx.notify();
6444 } else {
6445 self.accept_edit_prediction(&Default::default(), window, cx);
6446 }
6447 }
6448 }
6449 }
6450
6451 fn discard_inline_completion(
6452 &mut self,
6453 should_report_inline_completion_event: bool,
6454 cx: &mut Context<Self>,
6455 ) -> bool {
6456 if should_report_inline_completion_event {
6457 let completion_id = self
6458 .active_inline_completion
6459 .as_ref()
6460 .and_then(|active_completion| active_completion.completion_id.clone());
6461
6462 self.report_inline_completion_event(completion_id, false, cx);
6463 }
6464
6465 if let Some(provider) = self.edit_prediction_provider() {
6466 provider.discard(cx);
6467 }
6468
6469 self.take_active_inline_completion(cx)
6470 }
6471
6472 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6473 let Some(provider) = self.edit_prediction_provider() else {
6474 return;
6475 };
6476
6477 let Some((_, buffer, _)) = self
6478 .buffer
6479 .read(cx)
6480 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6481 else {
6482 return;
6483 };
6484
6485 let extension = buffer
6486 .read(cx)
6487 .file()
6488 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6489
6490 let event_type = match accepted {
6491 true => "Edit Prediction Accepted",
6492 false => "Edit Prediction Discarded",
6493 };
6494 telemetry::event!(
6495 event_type,
6496 provider = provider.name(),
6497 prediction_id = id,
6498 suggestion_accepted = accepted,
6499 file_extension = extension,
6500 );
6501 }
6502
6503 pub fn has_active_inline_completion(&self) -> bool {
6504 self.active_inline_completion.is_some()
6505 }
6506
6507 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6508 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6509 return false;
6510 };
6511
6512 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6513 self.clear_highlights::<InlineCompletionHighlight>(cx);
6514 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6515 true
6516 }
6517
6518 /// Returns true when we're displaying the edit prediction popover below the cursor
6519 /// like we are not previewing and the LSP autocomplete menu is visible
6520 /// or we are in `when_holding_modifier` mode.
6521 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6522 if self.edit_prediction_preview_is_active()
6523 || !self.show_edit_predictions_in_menu()
6524 || !self.edit_predictions_enabled()
6525 {
6526 return false;
6527 }
6528
6529 if self.has_visible_completions_menu() {
6530 return true;
6531 }
6532
6533 has_completion && self.edit_prediction_requires_modifier()
6534 }
6535
6536 fn handle_modifiers_changed(
6537 &mut self,
6538 modifiers: Modifiers,
6539 position_map: &PositionMap,
6540 window: &mut Window,
6541 cx: &mut Context<Self>,
6542 ) {
6543 if self.show_edit_predictions_in_menu() {
6544 self.update_edit_prediction_preview(&modifiers, window, cx);
6545 }
6546
6547 self.update_selection_mode(&modifiers, position_map, window, cx);
6548
6549 let mouse_position = window.mouse_position();
6550 if !position_map.text_hitbox.is_hovered(window) {
6551 return;
6552 }
6553
6554 self.update_hovered_link(
6555 position_map.point_for_position(mouse_position),
6556 &position_map.snapshot,
6557 modifiers,
6558 window,
6559 cx,
6560 )
6561 }
6562
6563 fn update_selection_mode(
6564 &mut self,
6565 modifiers: &Modifiers,
6566 position_map: &PositionMap,
6567 window: &mut Window,
6568 cx: &mut Context<Self>,
6569 ) {
6570 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6571 return;
6572 }
6573
6574 let mouse_position = window.mouse_position();
6575 let point_for_position = position_map.point_for_position(mouse_position);
6576 let position = point_for_position.previous_valid;
6577
6578 self.select(
6579 SelectPhase::BeginColumnar {
6580 position,
6581 reset: false,
6582 goal_column: point_for_position.exact_unclipped.column(),
6583 },
6584 window,
6585 cx,
6586 );
6587 }
6588
6589 fn update_edit_prediction_preview(
6590 &mut self,
6591 modifiers: &Modifiers,
6592 window: &mut Window,
6593 cx: &mut Context<Self>,
6594 ) {
6595 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6596 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6597 return;
6598 };
6599
6600 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6601 if matches!(
6602 self.edit_prediction_preview,
6603 EditPredictionPreview::Inactive { .. }
6604 ) {
6605 self.edit_prediction_preview = EditPredictionPreview::Active {
6606 previous_scroll_position: None,
6607 since: Instant::now(),
6608 };
6609
6610 self.update_visible_inline_completion(window, cx);
6611 cx.notify();
6612 }
6613 } else if let EditPredictionPreview::Active {
6614 previous_scroll_position,
6615 since,
6616 } = self.edit_prediction_preview
6617 {
6618 if let (Some(previous_scroll_position), Some(position_map)) =
6619 (previous_scroll_position, self.last_position_map.as_ref())
6620 {
6621 self.set_scroll_position(
6622 previous_scroll_position
6623 .scroll_position(&position_map.snapshot.display_snapshot),
6624 window,
6625 cx,
6626 );
6627 }
6628
6629 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6630 released_too_fast: since.elapsed() < Duration::from_millis(200),
6631 };
6632 self.clear_row_highlights::<EditPredictionPreview>();
6633 self.update_visible_inline_completion(window, cx);
6634 cx.notify();
6635 }
6636 }
6637
6638 fn update_visible_inline_completion(
6639 &mut self,
6640 _window: &mut Window,
6641 cx: &mut Context<Self>,
6642 ) -> Option<()> {
6643 let selection = self.selections.newest_anchor();
6644 let cursor = selection.head();
6645 let multibuffer = self.buffer.read(cx).snapshot(cx);
6646 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6647 let excerpt_id = cursor.excerpt_id;
6648
6649 let show_in_menu = self.show_edit_predictions_in_menu();
6650 let completions_menu_has_precedence = !show_in_menu
6651 && (self.context_menu.borrow().is_some()
6652 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6653
6654 if completions_menu_has_precedence
6655 || !offset_selection.is_empty()
6656 || self
6657 .active_inline_completion
6658 .as_ref()
6659 .map_or(false, |completion| {
6660 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6661 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6662 !invalidation_range.contains(&offset_selection.head())
6663 })
6664 {
6665 self.discard_inline_completion(false, cx);
6666 return None;
6667 }
6668
6669 self.take_active_inline_completion(cx);
6670 let Some(provider) = self.edit_prediction_provider() else {
6671 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6672 return None;
6673 };
6674
6675 let (buffer, cursor_buffer_position) =
6676 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6677
6678 self.edit_prediction_settings =
6679 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6680
6681 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6682
6683 if self.edit_prediction_indent_conflict {
6684 let cursor_point = cursor.to_point(&multibuffer);
6685
6686 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6687
6688 if let Some((_, indent)) = indents.iter().next() {
6689 if indent.len == cursor_point.column {
6690 self.edit_prediction_indent_conflict = false;
6691 }
6692 }
6693 }
6694
6695 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6696 let edits = inline_completion
6697 .edits
6698 .into_iter()
6699 .flat_map(|(range, new_text)| {
6700 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6701 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6702 Some((start..end, new_text))
6703 })
6704 .collect::<Vec<_>>();
6705 if edits.is_empty() {
6706 return None;
6707 }
6708
6709 let first_edit_start = edits.first().unwrap().0.start;
6710 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6711 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6712
6713 let last_edit_end = edits.last().unwrap().0.end;
6714 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6715 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6716
6717 let cursor_row = cursor.to_point(&multibuffer).row;
6718
6719 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6720
6721 let mut inlay_ids = Vec::new();
6722 let invalidation_row_range;
6723 let move_invalidation_row_range = if cursor_row < edit_start_row {
6724 Some(cursor_row..edit_end_row)
6725 } else if cursor_row > edit_end_row {
6726 Some(edit_start_row..cursor_row)
6727 } else {
6728 None
6729 };
6730 let is_move =
6731 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6732 let completion = if is_move {
6733 invalidation_row_range =
6734 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6735 let target = first_edit_start;
6736 InlineCompletion::Move { target, snapshot }
6737 } else {
6738 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6739 && !self.inline_completions_hidden_for_vim_mode;
6740
6741 if show_completions_in_buffer {
6742 if edits
6743 .iter()
6744 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6745 {
6746 let mut inlays = Vec::new();
6747 for (range, new_text) in &edits {
6748 let inlay = Inlay::inline_completion(
6749 post_inc(&mut self.next_inlay_id),
6750 range.start,
6751 new_text.as_str(),
6752 );
6753 inlay_ids.push(inlay.id);
6754 inlays.push(inlay);
6755 }
6756
6757 self.splice_inlays(&[], inlays, cx);
6758 } else {
6759 let background_color = cx.theme().status().deleted_background;
6760 self.highlight_text::<InlineCompletionHighlight>(
6761 edits.iter().map(|(range, _)| range.clone()).collect(),
6762 HighlightStyle {
6763 background_color: Some(background_color),
6764 ..Default::default()
6765 },
6766 cx,
6767 );
6768 }
6769 }
6770
6771 invalidation_row_range = edit_start_row..edit_end_row;
6772
6773 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6774 if provider.show_tab_accept_marker() {
6775 EditDisplayMode::TabAccept
6776 } else {
6777 EditDisplayMode::Inline
6778 }
6779 } else {
6780 EditDisplayMode::DiffPopover
6781 };
6782
6783 InlineCompletion::Edit {
6784 edits,
6785 edit_preview: inline_completion.edit_preview,
6786 display_mode,
6787 snapshot,
6788 }
6789 };
6790
6791 let invalidation_range = multibuffer
6792 .anchor_before(Point::new(invalidation_row_range.start, 0))
6793 ..multibuffer.anchor_after(Point::new(
6794 invalidation_row_range.end,
6795 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6796 ));
6797
6798 self.stale_inline_completion_in_menu = None;
6799 self.active_inline_completion = Some(InlineCompletionState {
6800 inlay_ids,
6801 completion,
6802 completion_id: inline_completion.id,
6803 invalidation_range,
6804 });
6805
6806 cx.notify();
6807
6808 Some(())
6809 }
6810
6811 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6812 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6813 }
6814
6815 fn clear_tasks(&mut self) {
6816 self.tasks.clear()
6817 }
6818
6819 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6820 if self.tasks.insert(key, value).is_some() {
6821 // This case should hopefully be rare, but just in case...
6822 log::error!(
6823 "multiple different run targets found on a single line, only the last target will be rendered"
6824 )
6825 }
6826 }
6827
6828 /// Get all display points of breakpoints that will be rendered within editor
6829 ///
6830 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6831 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6832 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6833 fn active_breakpoints(
6834 &self,
6835 range: Range<DisplayRow>,
6836 window: &mut Window,
6837 cx: &mut Context<Self>,
6838 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6839 let mut breakpoint_display_points = HashMap::default();
6840
6841 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6842 return breakpoint_display_points;
6843 };
6844
6845 let snapshot = self.snapshot(window, cx);
6846
6847 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6848 let Some(project) = self.project.as_ref() else {
6849 return breakpoint_display_points;
6850 };
6851
6852 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6853 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6854
6855 for (buffer_snapshot, range, excerpt_id) in
6856 multi_buffer_snapshot.range_to_buffer_ranges(range)
6857 {
6858 let Some(buffer) = project.read_with(cx, |this, cx| {
6859 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6860 }) else {
6861 continue;
6862 };
6863 let breakpoints = breakpoint_store.read(cx).breakpoints(
6864 &buffer,
6865 Some(
6866 buffer_snapshot.anchor_before(range.start)
6867 ..buffer_snapshot.anchor_after(range.end),
6868 ),
6869 buffer_snapshot,
6870 cx,
6871 );
6872 for (anchor, breakpoint) in breakpoints {
6873 let multi_buffer_anchor =
6874 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6875 let position = multi_buffer_anchor
6876 .to_point(&multi_buffer_snapshot)
6877 .to_display_point(&snapshot);
6878
6879 breakpoint_display_points
6880 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6881 }
6882 }
6883
6884 breakpoint_display_points
6885 }
6886
6887 fn breakpoint_context_menu(
6888 &self,
6889 anchor: Anchor,
6890 window: &mut Window,
6891 cx: &mut Context<Self>,
6892 ) -> Entity<ui::ContextMenu> {
6893 let weak_editor = cx.weak_entity();
6894 let focus_handle = self.focus_handle(cx);
6895
6896 let row = self
6897 .buffer
6898 .read(cx)
6899 .snapshot(cx)
6900 .summary_for_anchor::<Point>(&anchor)
6901 .row;
6902
6903 let breakpoint = self
6904 .breakpoint_at_row(row, window, cx)
6905 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6906
6907 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6908 "Edit Log Breakpoint"
6909 } else {
6910 "Set Log Breakpoint"
6911 };
6912
6913 let condition_breakpoint_msg = if breakpoint
6914 .as_ref()
6915 .is_some_and(|bp| bp.1.condition.is_some())
6916 {
6917 "Edit Condition Breakpoint"
6918 } else {
6919 "Set Condition Breakpoint"
6920 };
6921
6922 let hit_condition_breakpoint_msg = if breakpoint
6923 .as_ref()
6924 .is_some_and(|bp| bp.1.hit_condition.is_some())
6925 {
6926 "Edit Hit Condition Breakpoint"
6927 } else {
6928 "Set Hit Condition Breakpoint"
6929 };
6930
6931 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6932 "Unset Breakpoint"
6933 } else {
6934 "Set Breakpoint"
6935 };
6936
6937 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6938 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6939
6940 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6941 BreakpointState::Enabled => Some("Disable"),
6942 BreakpointState::Disabled => Some("Enable"),
6943 });
6944
6945 let (anchor, breakpoint) =
6946 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6947
6948 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6949 menu.on_blur_subscription(Subscription::new(|| {}))
6950 .context(focus_handle)
6951 .when(run_to_cursor, |this| {
6952 let weak_editor = weak_editor.clone();
6953 this.entry("Run to cursor", None, move |window, cx| {
6954 weak_editor
6955 .update(cx, |editor, cx| {
6956 editor.change_selections(None, window, cx, |s| {
6957 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6958 });
6959 })
6960 .ok();
6961
6962 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6963 })
6964 .separator()
6965 })
6966 .when_some(toggle_state_msg, |this, msg| {
6967 this.entry(msg, None, {
6968 let weak_editor = weak_editor.clone();
6969 let breakpoint = breakpoint.clone();
6970 move |_window, cx| {
6971 weak_editor
6972 .update(cx, |this, cx| {
6973 this.edit_breakpoint_at_anchor(
6974 anchor,
6975 breakpoint.as_ref().clone(),
6976 BreakpointEditAction::InvertState,
6977 cx,
6978 );
6979 })
6980 .log_err();
6981 }
6982 })
6983 })
6984 .entry(set_breakpoint_msg, None, {
6985 let weak_editor = weak_editor.clone();
6986 let breakpoint = breakpoint.clone();
6987 move |_window, cx| {
6988 weak_editor
6989 .update(cx, |this, cx| {
6990 this.edit_breakpoint_at_anchor(
6991 anchor,
6992 breakpoint.as_ref().clone(),
6993 BreakpointEditAction::Toggle,
6994 cx,
6995 );
6996 })
6997 .log_err();
6998 }
6999 })
7000 .entry(log_breakpoint_msg, None, {
7001 let breakpoint = breakpoint.clone();
7002 let weak_editor = weak_editor.clone();
7003 move |window, cx| {
7004 weak_editor
7005 .update(cx, |this, cx| {
7006 this.add_edit_breakpoint_block(
7007 anchor,
7008 breakpoint.as_ref(),
7009 BreakpointPromptEditAction::Log,
7010 window,
7011 cx,
7012 );
7013 })
7014 .log_err();
7015 }
7016 })
7017 .entry(condition_breakpoint_msg, None, {
7018 let breakpoint = breakpoint.clone();
7019 let weak_editor = weak_editor.clone();
7020 move |window, cx| {
7021 weak_editor
7022 .update(cx, |this, cx| {
7023 this.add_edit_breakpoint_block(
7024 anchor,
7025 breakpoint.as_ref(),
7026 BreakpointPromptEditAction::Condition,
7027 window,
7028 cx,
7029 );
7030 })
7031 .log_err();
7032 }
7033 })
7034 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
7035 weak_editor
7036 .update(cx, |this, cx| {
7037 this.add_edit_breakpoint_block(
7038 anchor,
7039 breakpoint.as_ref(),
7040 BreakpointPromptEditAction::HitCondition,
7041 window,
7042 cx,
7043 );
7044 })
7045 .log_err();
7046 })
7047 })
7048 }
7049
7050 fn render_breakpoint(
7051 &self,
7052 position: Anchor,
7053 row: DisplayRow,
7054 breakpoint: &Breakpoint,
7055 cx: &mut Context<Self>,
7056 ) -> IconButton {
7057 // Is it a breakpoint that shows up when hovering over gutter?
7058 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
7059 (false, false),
7060 |PhantomBreakpointIndicator {
7061 is_active,
7062 display_row,
7063 collides_with_existing_breakpoint,
7064 }| {
7065 (
7066 is_active && display_row == row,
7067 collides_with_existing_breakpoint,
7068 )
7069 },
7070 );
7071
7072 let (color, icon) = {
7073 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7074 (false, false) => ui::IconName::DebugBreakpoint,
7075 (true, false) => ui::IconName::DebugLogBreakpoint,
7076 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7077 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7078 };
7079
7080 let color = if is_phantom {
7081 Color::Hint
7082 } else {
7083 Color::Debugger
7084 };
7085
7086 (color, icon)
7087 };
7088
7089 let breakpoint = Arc::from(breakpoint.clone());
7090
7091 let alt_as_text = gpui::Keystroke {
7092 modifiers: Modifiers::secondary_key(),
7093 ..Default::default()
7094 };
7095 let primary_action_text = if breakpoint.is_disabled() {
7096 "enable"
7097 } else if is_phantom && !collides_with_existing {
7098 "set"
7099 } else {
7100 "unset"
7101 };
7102 let mut primary_text = format!("Click to {primary_action_text}");
7103 if collides_with_existing && !breakpoint.is_disabled() {
7104 use std::fmt::Write;
7105 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7106 }
7107 let primary_text = SharedString::from(primary_text);
7108 let focus_handle = self.focus_handle.clone();
7109 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7110 .icon_size(IconSize::XSmall)
7111 .size(ui::ButtonSize::None)
7112 .icon_color(color)
7113 .style(ButtonStyle::Transparent)
7114 .on_click(cx.listener({
7115 let breakpoint = breakpoint.clone();
7116
7117 move |editor, event: &ClickEvent, window, cx| {
7118 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7119 BreakpointEditAction::InvertState
7120 } else {
7121 BreakpointEditAction::Toggle
7122 };
7123
7124 window.focus(&editor.focus_handle(cx));
7125 editor.edit_breakpoint_at_anchor(
7126 position,
7127 breakpoint.as_ref().clone(),
7128 edit_action,
7129 cx,
7130 );
7131 }
7132 }))
7133 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7134 editor.set_breakpoint_context_menu(
7135 row,
7136 Some(position),
7137 event.down.position,
7138 window,
7139 cx,
7140 );
7141 }))
7142 .tooltip(move |window, cx| {
7143 Tooltip::with_meta_in(
7144 primary_text.clone(),
7145 None,
7146 "Right-click for more options",
7147 &focus_handle,
7148 window,
7149 cx,
7150 )
7151 })
7152 }
7153
7154 fn build_tasks_context(
7155 project: &Entity<Project>,
7156 buffer: &Entity<Buffer>,
7157 buffer_row: u32,
7158 tasks: &Arc<RunnableTasks>,
7159 cx: &mut Context<Self>,
7160 ) -> Task<Option<task::TaskContext>> {
7161 let position = Point::new(buffer_row, tasks.column);
7162 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7163 let location = Location {
7164 buffer: buffer.clone(),
7165 range: range_start..range_start,
7166 };
7167 // Fill in the environmental variables from the tree-sitter captures
7168 let mut captured_task_variables = TaskVariables::default();
7169 for (capture_name, value) in tasks.extra_variables.clone() {
7170 captured_task_variables.insert(
7171 task::VariableName::Custom(capture_name.into()),
7172 value.clone(),
7173 );
7174 }
7175 project.update(cx, |project, cx| {
7176 project.task_store().update(cx, |task_store, cx| {
7177 task_store.task_context_for_location(captured_task_variables, location, cx)
7178 })
7179 })
7180 }
7181
7182 pub fn spawn_nearest_task(
7183 &mut self,
7184 action: &SpawnNearestTask,
7185 window: &mut Window,
7186 cx: &mut Context<Self>,
7187 ) {
7188 let Some((workspace, _)) = self.workspace.clone() else {
7189 return;
7190 };
7191 let Some(project) = self.project.clone() else {
7192 return;
7193 };
7194
7195 // Try to find a closest, enclosing node using tree-sitter that has a
7196 // task
7197 let Some((buffer, buffer_row, tasks)) = self
7198 .find_enclosing_node_task(cx)
7199 // Or find the task that's closest in row-distance.
7200 .or_else(|| self.find_closest_task(cx))
7201 else {
7202 return;
7203 };
7204
7205 let reveal_strategy = action.reveal;
7206 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7207 cx.spawn_in(window, async move |_, cx| {
7208 let context = task_context.await?;
7209 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7210
7211 let resolved = &mut resolved_task.resolved;
7212 resolved.reveal = reveal_strategy;
7213
7214 workspace
7215 .update_in(cx, |workspace, window, cx| {
7216 workspace.schedule_resolved_task(
7217 task_source_kind,
7218 resolved_task,
7219 false,
7220 window,
7221 cx,
7222 );
7223 })
7224 .ok()
7225 })
7226 .detach();
7227 }
7228
7229 fn find_closest_task(
7230 &mut self,
7231 cx: &mut Context<Self>,
7232 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7233 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7234
7235 let ((buffer_id, row), tasks) = self
7236 .tasks
7237 .iter()
7238 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7239
7240 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7241 let tasks = Arc::new(tasks.to_owned());
7242 Some((buffer, *row, tasks))
7243 }
7244
7245 fn find_enclosing_node_task(
7246 &mut self,
7247 cx: &mut Context<Self>,
7248 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7249 let snapshot = self.buffer.read(cx).snapshot(cx);
7250 let offset = self.selections.newest::<usize>(cx).head();
7251 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7252 let buffer_id = excerpt.buffer().remote_id();
7253
7254 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7255 let mut cursor = layer.node().walk();
7256
7257 while cursor.goto_first_child_for_byte(offset).is_some() {
7258 if cursor.node().end_byte() == offset {
7259 cursor.goto_next_sibling();
7260 }
7261 }
7262
7263 // Ascend to the smallest ancestor that contains the range and has a task.
7264 loop {
7265 let node = cursor.node();
7266 let node_range = node.byte_range();
7267 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7268
7269 // Check if this node contains our offset
7270 if node_range.start <= offset && node_range.end >= offset {
7271 // If it contains offset, check for task
7272 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7273 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7274 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7275 }
7276 }
7277
7278 if !cursor.goto_parent() {
7279 break;
7280 }
7281 }
7282 None
7283 }
7284
7285 fn render_run_indicator(
7286 &self,
7287 _style: &EditorStyle,
7288 is_active: bool,
7289 row: DisplayRow,
7290 breakpoint: Option<(Anchor, Breakpoint)>,
7291 cx: &mut Context<Self>,
7292 ) -> IconButton {
7293 let color = Color::Muted;
7294 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7295
7296 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7297 .shape(ui::IconButtonShape::Square)
7298 .icon_size(IconSize::XSmall)
7299 .icon_color(color)
7300 .toggle_state(is_active)
7301 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7302 let quick_launch = e.down.button == MouseButton::Left;
7303 window.focus(&editor.focus_handle(cx));
7304 editor.toggle_code_actions(
7305 &ToggleCodeActions {
7306 deployed_from_indicator: Some(row),
7307 quick_launch,
7308 },
7309 window,
7310 cx,
7311 );
7312 }))
7313 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7314 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7315 }))
7316 }
7317
7318 pub fn context_menu_visible(&self) -> bool {
7319 !self.edit_prediction_preview_is_active()
7320 && self
7321 .context_menu
7322 .borrow()
7323 .as_ref()
7324 .map_or(false, |menu| menu.visible())
7325 }
7326
7327 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7328 self.context_menu
7329 .borrow()
7330 .as_ref()
7331 .map(|menu| menu.origin())
7332 }
7333
7334 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7335 self.context_menu_options = Some(options);
7336 }
7337
7338 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7339 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7340
7341 fn render_edit_prediction_popover(
7342 &mut self,
7343 text_bounds: &Bounds<Pixels>,
7344 content_origin: gpui::Point<Pixels>,
7345 right_margin: Pixels,
7346 editor_snapshot: &EditorSnapshot,
7347 visible_row_range: Range<DisplayRow>,
7348 scroll_top: f32,
7349 scroll_bottom: f32,
7350 line_layouts: &[LineWithInvisibles],
7351 line_height: Pixels,
7352 scroll_pixel_position: gpui::Point<Pixels>,
7353 newest_selection_head: Option<DisplayPoint>,
7354 editor_width: Pixels,
7355 style: &EditorStyle,
7356 window: &mut Window,
7357 cx: &mut App,
7358 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7359 if self.mode().is_minimap() {
7360 return None;
7361 }
7362 let active_inline_completion = self.active_inline_completion.as_ref()?;
7363
7364 if self.edit_prediction_visible_in_cursor_popover(true) {
7365 return None;
7366 }
7367
7368 match &active_inline_completion.completion {
7369 InlineCompletion::Move { target, .. } => {
7370 let target_display_point = target.to_display_point(editor_snapshot);
7371
7372 if self.edit_prediction_requires_modifier() {
7373 if !self.edit_prediction_preview_is_active() {
7374 return None;
7375 }
7376
7377 self.render_edit_prediction_modifier_jump_popover(
7378 text_bounds,
7379 content_origin,
7380 visible_row_range,
7381 line_layouts,
7382 line_height,
7383 scroll_pixel_position,
7384 newest_selection_head,
7385 target_display_point,
7386 window,
7387 cx,
7388 )
7389 } else {
7390 self.render_edit_prediction_eager_jump_popover(
7391 text_bounds,
7392 content_origin,
7393 editor_snapshot,
7394 visible_row_range,
7395 scroll_top,
7396 scroll_bottom,
7397 line_height,
7398 scroll_pixel_position,
7399 target_display_point,
7400 editor_width,
7401 window,
7402 cx,
7403 )
7404 }
7405 }
7406 InlineCompletion::Edit {
7407 display_mode: EditDisplayMode::Inline,
7408 ..
7409 } => None,
7410 InlineCompletion::Edit {
7411 display_mode: EditDisplayMode::TabAccept,
7412 edits,
7413 ..
7414 } => {
7415 let range = &edits.first()?.0;
7416 let target_display_point = range.end.to_display_point(editor_snapshot);
7417
7418 self.render_edit_prediction_end_of_line_popover(
7419 "Accept",
7420 editor_snapshot,
7421 visible_row_range,
7422 target_display_point,
7423 line_height,
7424 scroll_pixel_position,
7425 content_origin,
7426 editor_width,
7427 window,
7428 cx,
7429 )
7430 }
7431 InlineCompletion::Edit {
7432 edits,
7433 edit_preview,
7434 display_mode: EditDisplayMode::DiffPopover,
7435 snapshot,
7436 } => self.render_edit_prediction_diff_popover(
7437 text_bounds,
7438 content_origin,
7439 right_margin,
7440 editor_snapshot,
7441 visible_row_range,
7442 line_layouts,
7443 line_height,
7444 scroll_pixel_position,
7445 newest_selection_head,
7446 editor_width,
7447 style,
7448 edits,
7449 edit_preview,
7450 snapshot,
7451 window,
7452 cx,
7453 ),
7454 }
7455 }
7456
7457 fn render_edit_prediction_modifier_jump_popover(
7458 &mut self,
7459 text_bounds: &Bounds<Pixels>,
7460 content_origin: gpui::Point<Pixels>,
7461 visible_row_range: Range<DisplayRow>,
7462 line_layouts: &[LineWithInvisibles],
7463 line_height: Pixels,
7464 scroll_pixel_position: gpui::Point<Pixels>,
7465 newest_selection_head: Option<DisplayPoint>,
7466 target_display_point: DisplayPoint,
7467 window: &mut Window,
7468 cx: &mut App,
7469 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7470 let scrolled_content_origin =
7471 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7472
7473 const SCROLL_PADDING_Y: Pixels = px(12.);
7474
7475 if target_display_point.row() < visible_row_range.start {
7476 return self.render_edit_prediction_scroll_popover(
7477 |_| SCROLL_PADDING_Y,
7478 IconName::ArrowUp,
7479 visible_row_range,
7480 line_layouts,
7481 newest_selection_head,
7482 scrolled_content_origin,
7483 window,
7484 cx,
7485 );
7486 } else if target_display_point.row() >= visible_row_range.end {
7487 return self.render_edit_prediction_scroll_popover(
7488 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7489 IconName::ArrowDown,
7490 visible_row_range,
7491 line_layouts,
7492 newest_selection_head,
7493 scrolled_content_origin,
7494 window,
7495 cx,
7496 );
7497 }
7498
7499 const POLE_WIDTH: Pixels = px(2.);
7500
7501 let line_layout =
7502 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7503 let target_column = target_display_point.column() as usize;
7504
7505 let target_x = line_layout.x_for_index(target_column);
7506 let target_y =
7507 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7508
7509 let flag_on_right = target_x < text_bounds.size.width / 2.;
7510
7511 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7512 border_color.l += 0.001;
7513
7514 let mut element = v_flex()
7515 .items_end()
7516 .when(flag_on_right, |el| el.items_start())
7517 .child(if flag_on_right {
7518 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7519 .rounded_bl(px(0.))
7520 .rounded_tl(px(0.))
7521 .border_l_2()
7522 .border_color(border_color)
7523 } else {
7524 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7525 .rounded_br(px(0.))
7526 .rounded_tr(px(0.))
7527 .border_r_2()
7528 .border_color(border_color)
7529 })
7530 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7531 .into_any();
7532
7533 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7534
7535 let mut origin = scrolled_content_origin + point(target_x, target_y)
7536 - point(
7537 if flag_on_right {
7538 POLE_WIDTH
7539 } else {
7540 size.width - POLE_WIDTH
7541 },
7542 size.height - line_height,
7543 );
7544
7545 origin.x = origin.x.max(content_origin.x);
7546
7547 element.prepaint_at(origin, window, cx);
7548
7549 Some((element, origin))
7550 }
7551
7552 fn render_edit_prediction_scroll_popover(
7553 &mut self,
7554 to_y: impl Fn(Size<Pixels>) -> Pixels,
7555 scroll_icon: IconName,
7556 visible_row_range: Range<DisplayRow>,
7557 line_layouts: &[LineWithInvisibles],
7558 newest_selection_head: Option<DisplayPoint>,
7559 scrolled_content_origin: gpui::Point<Pixels>,
7560 window: &mut Window,
7561 cx: &mut App,
7562 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7563 let mut element = self
7564 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7565 .into_any();
7566
7567 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7568
7569 let cursor = newest_selection_head?;
7570 let cursor_row_layout =
7571 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7572 let cursor_column = cursor.column() as usize;
7573
7574 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7575
7576 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7577
7578 element.prepaint_at(origin, window, cx);
7579 Some((element, origin))
7580 }
7581
7582 fn render_edit_prediction_eager_jump_popover(
7583 &mut self,
7584 text_bounds: &Bounds<Pixels>,
7585 content_origin: gpui::Point<Pixels>,
7586 editor_snapshot: &EditorSnapshot,
7587 visible_row_range: Range<DisplayRow>,
7588 scroll_top: f32,
7589 scroll_bottom: f32,
7590 line_height: Pixels,
7591 scroll_pixel_position: gpui::Point<Pixels>,
7592 target_display_point: DisplayPoint,
7593 editor_width: Pixels,
7594 window: &mut Window,
7595 cx: &mut App,
7596 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7597 if target_display_point.row().as_f32() < scroll_top {
7598 let mut element = self
7599 .render_edit_prediction_line_popover(
7600 "Jump to Edit",
7601 Some(IconName::ArrowUp),
7602 window,
7603 cx,
7604 )?
7605 .into_any();
7606
7607 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7608 let offset = point(
7609 (text_bounds.size.width - size.width) / 2.,
7610 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7611 );
7612
7613 let origin = text_bounds.origin + offset;
7614 element.prepaint_at(origin, window, cx);
7615 Some((element, origin))
7616 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7617 let mut element = self
7618 .render_edit_prediction_line_popover(
7619 "Jump to Edit",
7620 Some(IconName::ArrowDown),
7621 window,
7622 cx,
7623 )?
7624 .into_any();
7625
7626 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7627 let offset = point(
7628 (text_bounds.size.width - size.width) / 2.,
7629 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7630 );
7631
7632 let origin = text_bounds.origin + offset;
7633 element.prepaint_at(origin, window, cx);
7634 Some((element, origin))
7635 } else {
7636 self.render_edit_prediction_end_of_line_popover(
7637 "Jump to Edit",
7638 editor_snapshot,
7639 visible_row_range,
7640 target_display_point,
7641 line_height,
7642 scroll_pixel_position,
7643 content_origin,
7644 editor_width,
7645 window,
7646 cx,
7647 )
7648 }
7649 }
7650
7651 fn render_edit_prediction_end_of_line_popover(
7652 self: &mut Editor,
7653 label: &'static str,
7654 editor_snapshot: &EditorSnapshot,
7655 visible_row_range: Range<DisplayRow>,
7656 target_display_point: DisplayPoint,
7657 line_height: Pixels,
7658 scroll_pixel_position: gpui::Point<Pixels>,
7659 content_origin: gpui::Point<Pixels>,
7660 editor_width: Pixels,
7661 window: &mut Window,
7662 cx: &mut App,
7663 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7664 let target_line_end = DisplayPoint::new(
7665 target_display_point.row(),
7666 editor_snapshot.line_len(target_display_point.row()),
7667 );
7668
7669 let mut element = self
7670 .render_edit_prediction_line_popover(label, None, window, cx)?
7671 .into_any();
7672
7673 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7674
7675 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7676
7677 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7678 let mut origin = start_point
7679 + line_origin
7680 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7681 origin.x = origin.x.max(content_origin.x);
7682
7683 let max_x = content_origin.x + editor_width - size.width;
7684
7685 if origin.x > max_x {
7686 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7687
7688 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7689 origin.y += offset;
7690 IconName::ArrowUp
7691 } else {
7692 origin.y -= offset;
7693 IconName::ArrowDown
7694 };
7695
7696 element = self
7697 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7698 .into_any();
7699
7700 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7701
7702 origin.x = content_origin.x + editor_width - size.width - px(2.);
7703 }
7704
7705 element.prepaint_at(origin, window, cx);
7706 Some((element, origin))
7707 }
7708
7709 fn render_edit_prediction_diff_popover(
7710 self: &Editor,
7711 text_bounds: &Bounds<Pixels>,
7712 content_origin: gpui::Point<Pixels>,
7713 right_margin: Pixels,
7714 editor_snapshot: &EditorSnapshot,
7715 visible_row_range: Range<DisplayRow>,
7716 line_layouts: &[LineWithInvisibles],
7717 line_height: Pixels,
7718 scroll_pixel_position: gpui::Point<Pixels>,
7719 newest_selection_head: Option<DisplayPoint>,
7720 editor_width: Pixels,
7721 style: &EditorStyle,
7722 edits: &Vec<(Range<Anchor>, String)>,
7723 edit_preview: &Option<language::EditPreview>,
7724 snapshot: &language::BufferSnapshot,
7725 window: &mut Window,
7726 cx: &mut App,
7727 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7728 let edit_start = edits
7729 .first()
7730 .unwrap()
7731 .0
7732 .start
7733 .to_display_point(editor_snapshot);
7734 let edit_end = edits
7735 .last()
7736 .unwrap()
7737 .0
7738 .end
7739 .to_display_point(editor_snapshot);
7740
7741 let is_visible = visible_row_range.contains(&edit_start.row())
7742 || visible_row_range.contains(&edit_end.row());
7743 if !is_visible {
7744 return None;
7745 }
7746
7747 let highlighted_edits =
7748 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7749
7750 let styled_text = highlighted_edits.to_styled_text(&style.text);
7751 let line_count = highlighted_edits.text.lines().count();
7752
7753 const BORDER_WIDTH: Pixels = px(1.);
7754
7755 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7756 let has_keybind = keybind.is_some();
7757
7758 let mut element = h_flex()
7759 .items_start()
7760 .child(
7761 h_flex()
7762 .bg(cx.theme().colors().editor_background)
7763 .border(BORDER_WIDTH)
7764 .shadow_sm()
7765 .border_color(cx.theme().colors().border)
7766 .rounded_l_lg()
7767 .when(line_count > 1, |el| el.rounded_br_lg())
7768 .pr_1()
7769 .child(styled_text),
7770 )
7771 .child(
7772 h_flex()
7773 .h(line_height + BORDER_WIDTH * 2.)
7774 .px_1p5()
7775 .gap_1()
7776 // Workaround: For some reason, there's a gap if we don't do this
7777 .ml(-BORDER_WIDTH)
7778 .shadow(smallvec![gpui::BoxShadow {
7779 color: gpui::black().opacity(0.05),
7780 offset: point(px(1.), px(1.)),
7781 blur_radius: px(2.),
7782 spread_radius: px(0.),
7783 }])
7784 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7785 .border(BORDER_WIDTH)
7786 .border_color(cx.theme().colors().border)
7787 .rounded_r_lg()
7788 .id("edit_prediction_diff_popover_keybind")
7789 .when(!has_keybind, |el| {
7790 let status_colors = cx.theme().status();
7791
7792 el.bg(status_colors.error_background)
7793 .border_color(status_colors.error.opacity(0.6))
7794 .child(Icon::new(IconName::Info).color(Color::Error))
7795 .cursor_default()
7796 .hoverable_tooltip(move |_window, cx| {
7797 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7798 })
7799 })
7800 .children(keybind),
7801 )
7802 .into_any();
7803
7804 let longest_row =
7805 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7806 let longest_line_width = if visible_row_range.contains(&longest_row) {
7807 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7808 } else {
7809 layout_line(
7810 longest_row,
7811 editor_snapshot,
7812 style,
7813 editor_width,
7814 |_| false,
7815 window,
7816 cx,
7817 )
7818 .width
7819 };
7820
7821 let viewport_bounds =
7822 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7823 right: -right_margin,
7824 ..Default::default()
7825 });
7826
7827 let x_after_longest =
7828 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7829 - scroll_pixel_position.x;
7830
7831 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7832
7833 // Fully visible if it can be displayed within the window (allow overlapping other
7834 // panes). However, this is only allowed if the popover starts within text_bounds.
7835 let can_position_to_the_right = x_after_longest < text_bounds.right()
7836 && x_after_longest + element_bounds.width < viewport_bounds.right();
7837
7838 let mut origin = if can_position_to_the_right {
7839 point(
7840 x_after_longest,
7841 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7842 - scroll_pixel_position.y,
7843 )
7844 } else {
7845 let cursor_row = newest_selection_head.map(|head| head.row());
7846 let above_edit = edit_start
7847 .row()
7848 .0
7849 .checked_sub(line_count as u32)
7850 .map(DisplayRow);
7851 let below_edit = Some(edit_end.row() + 1);
7852 let above_cursor =
7853 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7854 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7855
7856 // Place the edit popover adjacent to the edit if there is a location
7857 // available that is onscreen and does not obscure the cursor. Otherwise,
7858 // place it adjacent to the cursor.
7859 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7860 .into_iter()
7861 .flatten()
7862 .find(|&start_row| {
7863 let end_row = start_row + line_count as u32;
7864 visible_row_range.contains(&start_row)
7865 && visible_row_range.contains(&end_row)
7866 && cursor_row.map_or(true, |cursor_row| {
7867 !((start_row..end_row).contains(&cursor_row))
7868 })
7869 })?;
7870
7871 content_origin
7872 + point(
7873 -scroll_pixel_position.x,
7874 row_target.as_f32() * line_height - scroll_pixel_position.y,
7875 )
7876 };
7877
7878 origin.x -= BORDER_WIDTH;
7879
7880 window.defer_draw(element, origin, 1);
7881
7882 // Do not return an element, since it will already be drawn due to defer_draw.
7883 None
7884 }
7885
7886 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7887 px(30.)
7888 }
7889
7890 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7891 if self.read_only(cx) {
7892 cx.theme().players().read_only()
7893 } else {
7894 self.style.as_ref().unwrap().local_player
7895 }
7896 }
7897
7898 fn render_edit_prediction_accept_keybind(
7899 &self,
7900 window: &mut Window,
7901 cx: &App,
7902 ) -> Option<AnyElement> {
7903 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7904 let accept_keystroke = accept_binding.keystroke()?;
7905
7906 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7907
7908 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7909 Color::Accent
7910 } else {
7911 Color::Muted
7912 };
7913
7914 h_flex()
7915 .px_0p5()
7916 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7917 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7918 .text_size(TextSize::XSmall.rems(cx))
7919 .child(h_flex().children(ui::render_modifiers(
7920 &accept_keystroke.modifiers,
7921 PlatformStyle::platform(),
7922 Some(modifiers_color),
7923 Some(IconSize::XSmall.rems().into()),
7924 true,
7925 )))
7926 .when(is_platform_style_mac, |parent| {
7927 parent.child(accept_keystroke.key.clone())
7928 })
7929 .when(!is_platform_style_mac, |parent| {
7930 parent.child(
7931 Key::new(
7932 util::capitalize(&accept_keystroke.key),
7933 Some(Color::Default),
7934 )
7935 .size(Some(IconSize::XSmall.rems().into())),
7936 )
7937 })
7938 .into_any()
7939 .into()
7940 }
7941
7942 fn render_edit_prediction_line_popover(
7943 &self,
7944 label: impl Into<SharedString>,
7945 icon: Option<IconName>,
7946 window: &mut Window,
7947 cx: &App,
7948 ) -> Option<Stateful<Div>> {
7949 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7950
7951 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7952 let has_keybind = keybind.is_some();
7953
7954 let result = h_flex()
7955 .id("ep-line-popover")
7956 .py_0p5()
7957 .pl_1()
7958 .pr(padding_right)
7959 .gap_1()
7960 .rounded_md()
7961 .border_1()
7962 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7963 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7964 .shadow_sm()
7965 .when(!has_keybind, |el| {
7966 let status_colors = cx.theme().status();
7967
7968 el.bg(status_colors.error_background)
7969 .border_color(status_colors.error.opacity(0.6))
7970 .pl_2()
7971 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7972 .cursor_default()
7973 .hoverable_tooltip(move |_window, cx| {
7974 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7975 })
7976 })
7977 .children(keybind)
7978 .child(
7979 Label::new(label)
7980 .size(LabelSize::Small)
7981 .when(!has_keybind, |el| {
7982 el.color(cx.theme().status().error.into()).strikethrough()
7983 }),
7984 )
7985 .when(!has_keybind, |el| {
7986 el.child(
7987 h_flex().ml_1().child(
7988 Icon::new(IconName::Info)
7989 .size(IconSize::Small)
7990 .color(cx.theme().status().error.into()),
7991 ),
7992 )
7993 })
7994 .when_some(icon, |element, icon| {
7995 element.child(
7996 div()
7997 .mt(px(1.5))
7998 .child(Icon::new(icon).size(IconSize::Small)),
7999 )
8000 });
8001
8002 Some(result)
8003 }
8004
8005 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
8006 let accent_color = cx.theme().colors().text_accent;
8007 let editor_bg_color = cx.theme().colors().editor_background;
8008 editor_bg_color.blend(accent_color.opacity(0.1))
8009 }
8010
8011 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
8012 let accent_color = cx.theme().colors().text_accent;
8013 let editor_bg_color = cx.theme().colors().editor_background;
8014 editor_bg_color.blend(accent_color.opacity(0.6))
8015 }
8016
8017 fn render_edit_prediction_cursor_popover(
8018 &self,
8019 min_width: Pixels,
8020 max_width: Pixels,
8021 cursor_point: Point,
8022 style: &EditorStyle,
8023 accept_keystroke: Option<&gpui::Keystroke>,
8024 _window: &Window,
8025 cx: &mut Context<Editor>,
8026 ) -> Option<AnyElement> {
8027 let provider = self.edit_prediction_provider.as_ref()?;
8028
8029 if provider.provider.needs_terms_acceptance(cx) {
8030 return Some(
8031 h_flex()
8032 .min_w(min_width)
8033 .flex_1()
8034 .px_2()
8035 .py_1()
8036 .gap_3()
8037 .elevation_2(cx)
8038 .hover(|style| style.bg(cx.theme().colors().element_hover))
8039 .id("accept-terms")
8040 .cursor_pointer()
8041 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
8042 .on_click(cx.listener(|this, _event, window, cx| {
8043 cx.stop_propagation();
8044 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
8045 window.dispatch_action(
8046 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
8047 cx,
8048 );
8049 }))
8050 .child(
8051 h_flex()
8052 .flex_1()
8053 .gap_2()
8054 .child(Icon::new(IconName::ZedPredict))
8055 .child(Label::new("Accept Terms of Service"))
8056 .child(div().w_full())
8057 .child(
8058 Icon::new(IconName::ArrowUpRight)
8059 .color(Color::Muted)
8060 .size(IconSize::Small),
8061 )
8062 .into_any_element(),
8063 )
8064 .into_any(),
8065 );
8066 }
8067
8068 let is_refreshing = provider.provider.is_refreshing(cx);
8069
8070 fn pending_completion_container() -> Div {
8071 h_flex()
8072 .h_full()
8073 .flex_1()
8074 .gap_2()
8075 .child(Icon::new(IconName::ZedPredict))
8076 }
8077
8078 let completion = match &self.active_inline_completion {
8079 Some(prediction) => {
8080 if !self.has_visible_completions_menu() {
8081 const RADIUS: Pixels = px(6.);
8082 const BORDER_WIDTH: Pixels = px(1.);
8083
8084 return Some(
8085 h_flex()
8086 .elevation_2(cx)
8087 .border(BORDER_WIDTH)
8088 .border_color(cx.theme().colors().border)
8089 .when(accept_keystroke.is_none(), |el| {
8090 el.border_color(cx.theme().status().error)
8091 })
8092 .rounded(RADIUS)
8093 .rounded_tl(px(0.))
8094 .overflow_hidden()
8095 .child(div().px_1p5().child(match &prediction.completion {
8096 InlineCompletion::Move { target, snapshot } => {
8097 use text::ToPoint as _;
8098 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8099 {
8100 Icon::new(IconName::ZedPredictDown)
8101 } else {
8102 Icon::new(IconName::ZedPredictUp)
8103 }
8104 }
8105 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8106 }))
8107 .child(
8108 h_flex()
8109 .gap_1()
8110 .py_1()
8111 .px_2()
8112 .rounded_r(RADIUS - BORDER_WIDTH)
8113 .border_l_1()
8114 .border_color(cx.theme().colors().border)
8115 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8116 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8117 el.child(
8118 Label::new("Hold")
8119 .size(LabelSize::Small)
8120 .when(accept_keystroke.is_none(), |el| {
8121 el.strikethrough()
8122 })
8123 .line_height_style(LineHeightStyle::UiLabel),
8124 )
8125 })
8126 .id("edit_prediction_cursor_popover_keybind")
8127 .when(accept_keystroke.is_none(), |el| {
8128 let status_colors = cx.theme().status();
8129
8130 el.bg(status_colors.error_background)
8131 .border_color(status_colors.error.opacity(0.6))
8132 .child(Icon::new(IconName::Info).color(Color::Error))
8133 .cursor_default()
8134 .hoverable_tooltip(move |_window, cx| {
8135 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8136 .into()
8137 })
8138 })
8139 .when_some(
8140 accept_keystroke.as_ref(),
8141 |el, accept_keystroke| {
8142 el.child(h_flex().children(ui::render_modifiers(
8143 &accept_keystroke.modifiers,
8144 PlatformStyle::platform(),
8145 Some(Color::Default),
8146 Some(IconSize::XSmall.rems().into()),
8147 false,
8148 )))
8149 },
8150 ),
8151 )
8152 .into_any(),
8153 );
8154 }
8155
8156 self.render_edit_prediction_cursor_popover_preview(
8157 prediction,
8158 cursor_point,
8159 style,
8160 cx,
8161 )?
8162 }
8163
8164 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8165 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8166 stale_completion,
8167 cursor_point,
8168 style,
8169 cx,
8170 )?,
8171
8172 None => {
8173 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8174 }
8175 },
8176
8177 None => pending_completion_container().child(Label::new("No Prediction")),
8178 };
8179
8180 let completion = if is_refreshing {
8181 completion
8182 .with_animation(
8183 "loading-completion",
8184 Animation::new(Duration::from_secs(2))
8185 .repeat()
8186 .with_easing(pulsating_between(0.4, 0.8)),
8187 |label, delta| label.opacity(delta),
8188 )
8189 .into_any_element()
8190 } else {
8191 completion.into_any_element()
8192 };
8193
8194 let has_completion = self.active_inline_completion.is_some();
8195
8196 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8197 Some(
8198 h_flex()
8199 .min_w(min_width)
8200 .max_w(max_width)
8201 .flex_1()
8202 .elevation_2(cx)
8203 .border_color(cx.theme().colors().border)
8204 .child(
8205 div()
8206 .flex_1()
8207 .py_1()
8208 .px_2()
8209 .overflow_hidden()
8210 .child(completion),
8211 )
8212 .when_some(accept_keystroke, |el, accept_keystroke| {
8213 if !accept_keystroke.modifiers.modified() {
8214 return el;
8215 }
8216
8217 el.child(
8218 h_flex()
8219 .h_full()
8220 .border_l_1()
8221 .rounded_r_lg()
8222 .border_color(cx.theme().colors().border)
8223 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8224 .gap_1()
8225 .py_1()
8226 .px_2()
8227 .child(
8228 h_flex()
8229 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8230 .when(is_platform_style_mac, |parent| parent.gap_1())
8231 .child(h_flex().children(ui::render_modifiers(
8232 &accept_keystroke.modifiers,
8233 PlatformStyle::platform(),
8234 Some(if !has_completion {
8235 Color::Muted
8236 } else {
8237 Color::Default
8238 }),
8239 None,
8240 false,
8241 ))),
8242 )
8243 .child(Label::new("Preview").into_any_element())
8244 .opacity(if has_completion { 1.0 } else { 0.4 }),
8245 )
8246 })
8247 .into_any(),
8248 )
8249 }
8250
8251 fn render_edit_prediction_cursor_popover_preview(
8252 &self,
8253 completion: &InlineCompletionState,
8254 cursor_point: Point,
8255 style: &EditorStyle,
8256 cx: &mut Context<Editor>,
8257 ) -> Option<Div> {
8258 use text::ToPoint as _;
8259
8260 fn render_relative_row_jump(
8261 prefix: impl Into<String>,
8262 current_row: u32,
8263 target_row: u32,
8264 ) -> Div {
8265 let (row_diff, arrow) = if target_row < current_row {
8266 (current_row - target_row, IconName::ArrowUp)
8267 } else {
8268 (target_row - current_row, IconName::ArrowDown)
8269 };
8270
8271 h_flex()
8272 .child(
8273 Label::new(format!("{}{}", prefix.into(), row_diff))
8274 .color(Color::Muted)
8275 .size(LabelSize::Small),
8276 )
8277 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8278 }
8279
8280 match &completion.completion {
8281 InlineCompletion::Move {
8282 target, snapshot, ..
8283 } => Some(
8284 h_flex()
8285 .px_2()
8286 .gap_2()
8287 .flex_1()
8288 .child(
8289 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8290 Icon::new(IconName::ZedPredictDown)
8291 } else {
8292 Icon::new(IconName::ZedPredictUp)
8293 },
8294 )
8295 .child(Label::new("Jump to Edit")),
8296 ),
8297
8298 InlineCompletion::Edit {
8299 edits,
8300 edit_preview,
8301 snapshot,
8302 display_mode: _,
8303 } => {
8304 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8305
8306 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8307 &snapshot,
8308 &edits,
8309 edit_preview.as_ref()?,
8310 true,
8311 cx,
8312 )
8313 .first_line_preview();
8314
8315 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8316 .with_default_highlights(&style.text, highlighted_edits.highlights);
8317
8318 let preview = h_flex()
8319 .gap_1()
8320 .min_w_16()
8321 .child(styled_text)
8322 .when(has_more_lines, |parent| parent.child("…"));
8323
8324 let left = if first_edit_row != cursor_point.row {
8325 render_relative_row_jump("", cursor_point.row, first_edit_row)
8326 .into_any_element()
8327 } else {
8328 Icon::new(IconName::ZedPredict).into_any_element()
8329 };
8330
8331 Some(
8332 h_flex()
8333 .h_full()
8334 .flex_1()
8335 .gap_2()
8336 .pr_1()
8337 .overflow_x_hidden()
8338 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8339 .child(left)
8340 .child(preview),
8341 )
8342 }
8343 }
8344 }
8345
8346 fn render_context_menu(
8347 &self,
8348 style: &EditorStyle,
8349 max_height_in_lines: u32,
8350 window: &mut Window,
8351 cx: &mut Context<Editor>,
8352 ) -> Option<AnyElement> {
8353 let menu = self.context_menu.borrow();
8354 let menu = menu.as_ref()?;
8355 if !menu.visible() {
8356 return None;
8357 };
8358 Some(menu.render(style, max_height_in_lines, window, cx))
8359 }
8360
8361 fn render_context_menu_aside(
8362 &mut self,
8363 max_size: Size<Pixels>,
8364 window: &mut Window,
8365 cx: &mut Context<Editor>,
8366 ) -> Option<AnyElement> {
8367 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8368 if menu.visible() {
8369 menu.render_aside(self, max_size, window, cx)
8370 } else {
8371 None
8372 }
8373 })
8374 }
8375
8376 fn hide_context_menu(
8377 &mut self,
8378 window: &mut Window,
8379 cx: &mut Context<Self>,
8380 ) -> Option<CodeContextMenu> {
8381 cx.notify();
8382 self.completion_tasks.clear();
8383 let context_menu = self.context_menu.borrow_mut().take();
8384 self.stale_inline_completion_in_menu.take();
8385 self.update_visible_inline_completion(window, cx);
8386 context_menu
8387 }
8388
8389 fn show_snippet_choices(
8390 &mut self,
8391 choices: &Vec<String>,
8392 selection: Range<Anchor>,
8393 cx: &mut Context<Self>,
8394 ) {
8395 if selection.start.buffer_id.is_none() {
8396 return;
8397 }
8398 let buffer_id = selection.start.buffer_id.unwrap();
8399 let buffer = self.buffer().read(cx).buffer(buffer_id);
8400 let id = post_inc(&mut self.next_completion_id);
8401 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8402
8403 if let Some(buffer) = buffer {
8404 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8405 CompletionsMenu::new_snippet_choices(
8406 id,
8407 true,
8408 choices,
8409 selection,
8410 buffer,
8411 snippet_sort_order,
8412 ),
8413 ));
8414 }
8415 }
8416
8417 pub fn insert_snippet(
8418 &mut self,
8419 insertion_ranges: &[Range<usize>],
8420 snippet: Snippet,
8421 window: &mut Window,
8422 cx: &mut Context<Self>,
8423 ) -> Result<()> {
8424 struct Tabstop<T> {
8425 is_end_tabstop: bool,
8426 ranges: Vec<Range<T>>,
8427 choices: Option<Vec<String>>,
8428 }
8429
8430 let tabstops = self.buffer.update(cx, |buffer, cx| {
8431 let snippet_text: Arc<str> = snippet.text.clone().into();
8432 let edits = insertion_ranges
8433 .iter()
8434 .cloned()
8435 .map(|range| (range, snippet_text.clone()));
8436 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8437
8438 let snapshot = &*buffer.read(cx);
8439 let snippet = &snippet;
8440 snippet
8441 .tabstops
8442 .iter()
8443 .map(|tabstop| {
8444 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8445 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8446 });
8447 let mut tabstop_ranges = tabstop
8448 .ranges
8449 .iter()
8450 .flat_map(|tabstop_range| {
8451 let mut delta = 0_isize;
8452 insertion_ranges.iter().map(move |insertion_range| {
8453 let insertion_start = insertion_range.start as isize + delta;
8454 delta +=
8455 snippet.text.len() as isize - insertion_range.len() as isize;
8456
8457 let start = ((insertion_start + tabstop_range.start) as usize)
8458 .min(snapshot.len());
8459 let end = ((insertion_start + tabstop_range.end) as usize)
8460 .min(snapshot.len());
8461 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8462 })
8463 })
8464 .collect::<Vec<_>>();
8465 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8466
8467 Tabstop {
8468 is_end_tabstop,
8469 ranges: tabstop_ranges,
8470 choices: tabstop.choices.clone(),
8471 }
8472 })
8473 .collect::<Vec<_>>()
8474 });
8475 if let Some(tabstop) = tabstops.first() {
8476 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8477 s.select_ranges(tabstop.ranges.iter().cloned());
8478 });
8479
8480 if let Some(choices) = &tabstop.choices {
8481 if let Some(selection) = tabstop.ranges.first() {
8482 self.show_snippet_choices(choices, selection.clone(), cx)
8483 }
8484 }
8485
8486 // If we're already at the last tabstop and it's at the end of the snippet,
8487 // we're done, we don't need to keep the state around.
8488 if !tabstop.is_end_tabstop {
8489 let choices = tabstops
8490 .iter()
8491 .map(|tabstop| tabstop.choices.clone())
8492 .collect();
8493
8494 let ranges = tabstops
8495 .into_iter()
8496 .map(|tabstop| tabstop.ranges)
8497 .collect::<Vec<_>>();
8498
8499 self.snippet_stack.push(SnippetState {
8500 active_index: 0,
8501 ranges,
8502 choices,
8503 });
8504 }
8505
8506 // Check whether the just-entered snippet ends with an auto-closable bracket.
8507 if self.autoclose_regions.is_empty() {
8508 let snapshot = self.buffer.read(cx).snapshot(cx);
8509 for selection in &mut self.selections.all::<Point>(cx) {
8510 let selection_head = selection.head();
8511 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8512 continue;
8513 };
8514
8515 let mut bracket_pair = None;
8516 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8517 let prev_chars = snapshot
8518 .reversed_chars_at(selection_head)
8519 .collect::<String>();
8520 for (pair, enabled) in scope.brackets() {
8521 if enabled
8522 && pair.close
8523 && prev_chars.starts_with(pair.start.as_str())
8524 && next_chars.starts_with(pair.end.as_str())
8525 {
8526 bracket_pair = Some(pair.clone());
8527 break;
8528 }
8529 }
8530 if let Some(pair) = bracket_pair {
8531 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8532 let autoclose_enabled =
8533 self.use_autoclose && snapshot_settings.use_autoclose;
8534 if autoclose_enabled {
8535 let start = snapshot.anchor_after(selection_head);
8536 let end = snapshot.anchor_after(selection_head);
8537 self.autoclose_regions.push(AutocloseRegion {
8538 selection_id: selection.id,
8539 range: start..end,
8540 pair,
8541 });
8542 }
8543 }
8544 }
8545 }
8546 }
8547 Ok(())
8548 }
8549
8550 pub fn move_to_next_snippet_tabstop(
8551 &mut self,
8552 window: &mut Window,
8553 cx: &mut Context<Self>,
8554 ) -> bool {
8555 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8556 }
8557
8558 pub fn move_to_prev_snippet_tabstop(
8559 &mut self,
8560 window: &mut Window,
8561 cx: &mut Context<Self>,
8562 ) -> bool {
8563 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8564 }
8565
8566 pub fn move_to_snippet_tabstop(
8567 &mut self,
8568 bias: Bias,
8569 window: &mut Window,
8570 cx: &mut Context<Self>,
8571 ) -> bool {
8572 if let Some(mut snippet) = self.snippet_stack.pop() {
8573 match bias {
8574 Bias::Left => {
8575 if snippet.active_index > 0 {
8576 snippet.active_index -= 1;
8577 } else {
8578 self.snippet_stack.push(snippet);
8579 return false;
8580 }
8581 }
8582 Bias::Right => {
8583 if snippet.active_index + 1 < snippet.ranges.len() {
8584 snippet.active_index += 1;
8585 } else {
8586 self.snippet_stack.push(snippet);
8587 return false;
8588 }
8589 }
8590 }
8591 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8592 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8593 s.select_anchor_ranges(current_ranges.iter().cloned())
8594 });
8595
8596 if let Some(choices) = &snippet.choices[snippet.active_index] {
8597 if let Some(selection) = current_ranges.first() {
8598 self.show_snippet_choices(&choices, selection.clone(), cx);
8599 }
8600 }
8601
8602 // If snippet state is not at the last tabstop, push it back on the stack
8603 if snippet.active_index + 1 < snippet.ranges.len() {
8604 self.snippet_stack.push(snippet);
8605 }
8606 return true;
8607 }
8608 }
8609
8610 false
8611 }
8612
8613 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8614 self.transact(window, cx, |this, window, cx| {
8615 this.select_all(&SelectAll, window, cx);
8616 this.insert("", window, cx);
8617 });
8618 }
8619
8620 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8621 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8622 self.transact(window, cx, |this, window, cx| {
8623 this.select_autoclose_pair(window, cx);
8624 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8625 if !this.linked_edit_ranges.is_empty() {
8626 let selections = this.selections.all::<MultiBufferPoint>(cx);
8627 let snapshot = this.buffer.read(cx).snapshot(cx);
8628
8629 for selection in selections.iter() {
8630 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8631 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8632 if selection_start.buffer_id != selection_end.buffer_id {
8633 continue;
8634 }
8635 if let Some(ranges) =
8636 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8637 {
8638 for (buffer, entries) in ranges {
8639 linked_ranges.entry(buffer).or_default().extend(entries);
8640 }
8641 }
8642 }
8643 }
8644
8645 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8646 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8647 for selection in &mut selections {
8648 if selection.is_empty() {
8649 let old_head = selection.head();
8650 let mut new_head =
8651 movement::left(&display_map, old_head.to_display_point(&display_map))
8652 .to_point(&display_map);
8653 if let Some((buffer, line_buffer_range)) = display_map
8654 .buffer_snapshot
8655 .buffer_line_for_row(MultiBufferRow(old_head.row))
8656 {
8657 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8658 let indent_len = match indent_size.kind {
8659 IndentKind::Space => {
8660 buffer.settings_at(line_buffer_range.start, cx).tab_size
8661 }
8662 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8663 };
8664 if old_head.column <= indent_size.len && old_head.column > 0 {
8665 let indent_len = indent_len.get();
8666 new_head = cmp::min(
8667 new_head,
8668 MultiBufferPoint::new(
8669 old_head.row,
8670 ((old_head.column - 1) / indent_len) * indent_len,
8671 ),
8672 );
8673 }
8674 }
8675
8676 selection.set_head(new_head, SelectionGoal::None);
8677 }
8678 }
8679
8680 this.signature_help_state.set_backspace_pressed(true);
8681 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8682 s.select(selections)
8683 });
8684 this.insert("", window, cx);
8685 let empty_str: Arc<str> = Arc::from("");
8686 for (buffer, edits) in linked_ranges {
8687 let snapshot = buffer.read(cx).snapshot();
8688 use text::ToPoint as TP;
8689
8690 let edits = edits
8691 .into_iter()
8692 .map(|range| {
8693 let end_point = TP::to_point(&range.end, &snapshot);
8694 let mut start_point = TP::to_point(&range.start, &snapshot);
8695
8696 if end_point == start_point {
8697 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8698 .saturating_sub(1);
8699 start_point =
8700 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8701 };
8702
8703 (start_point..end_point, empty_str.clone())
8704 })
8705 .sorted_by_key(|(range, _)| range.start)
8706 .collect::<Vec<_>>();
8707 buffer.update(cx, |this, cx| {
8708 this.edit(edits, None, cx);
8709 })
8710 }
8711 this.refresh_inline_completion(true, false, window, cx);
8712 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8713 });
8714 }
8715
8716 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8717 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8718 self.transact(window, cx, |this, window, cx| {
8719 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8720 s.move_with(|map, selection| {
8721 if selection.is_empty() {
8722 let cursor = movement::right(map, selection.head());
8723 selection.end = cursor;
8724 selection.reversed = true;
8725 selection.goal = SelectionGoal::None;
8726 }
8727 })
8728 });
8729 this.insert("", window, cx);
8730 this.refresh_inline_completion(true, false, window, cx);
8731 });
8732 }
8733
8734 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8735 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8736 if self.move_to_prev_snippet_tabstop(window, cx) {
8737 return;
8738 }
8739 self.outdent(&Outdent, window, cx);
8740 }
8741
8742 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8743 if self.move_to_next_snippet_tabstop(window, cx) {
8744 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8745 return;
8746 }
8747 if self.read_only(cx) {
8748 return;
8749 }
8750 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8751 let mut selections = self.selections.all_adjusted(cx);
8752 let buffer = self.buffer.read(cx);
8753 let snapshot = buffer.snapshot(cx);
8754 let rows_iter = selections.iter().map(|s| s.head().row);
8755 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8756
8757 let has_some_cursor_in_whitespace = selections
8758 .iter()
8759 .filter(|selection| selection.is_empty())
8760 .any(|selection| {
8761 let cursor = selection.head();
8762 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8763 cursor.column < current_indent.len
8764 });
8765
8766 let mut edits = Vec::new();
8767 let mut prev_edited_row = 0;
8768 let mut row_delta = 0;
8769 for selection in &mut selections {
8770 if selection.start.row != prev_edited_row {
8771 row_delta = 0;
8772 }
8773 prev_edited_row = selection.end.row;
8774
8775 // If the selection is non-empty, then increase the indentation of the selected lines.
8776 if !selection.is_empty() {
8777 row_delta =
8778 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8779 continue;
8780 }
8781
8782 // If the selection is empty and the cursor is in the leading whitespace before the
8783 // suggested indentation, then auto-indent the line.
8784 let cursor = selection.head();
8785 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8786 if let Some(suggested_indent) =
8787 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8788 {
8789 // If there exist any empty selection in the leading whitespace, then skip
8790 // indent for selections at the boundary.
8791 if has_some_cursor_in_whitespace
8792 && cursor.column == current_indent.len
8793 && current_indent.len == suggested_indent.len
8794 {
8795 continue;
8796 }
8797
8798 if cursor.column < suggested_indent.len
8799 && cursor.column <= current_indent.len
8800 && current_indent.len <= suggested_indent.len
8801 {
8802 selection.start = Point::new(cursor.row, suggested_indent.len);
8803 selection.end = selection.start;
8804 if row_delta == 0 {
8805 edits.extend(Buffer::edit_for_indent_size_adjustment(
8806 cursor.row,
8807 current_indent,
8808 suggested_indent,
8809 ));
8810 row_delta = suggested_indent.len - current_indent.len;
8811 }
8812 continue;
8813 }
8814 }
8815
8816 // Otherwise, insert a hard or soft tab.
8817 let settings = buffer.language_settings_at(cursor, cx);
8818 let tab_size = if settings.hard_tabs {
8819 IndentSize::tab()
8820 } else {
8821 let tab_size = settings.tab_size.get();
8822 let indent_remainder = snapshot
8823 .text_for_range(Point::new(cursor.row, 0)..cursor)
8824 .flat_map(str::chars)
8825 .fold(row_delta % tab_size, |counter: u32, c| {
8826 if c == '\t' {
8827 0
8828 } else {
8829 (counter + 1) % tab_size
8830 }
8831 });
8832
8833 let chars_to_next_tab_stop = tab_size - indent_remainder;
8834 IndentSize::spaces(chars_to_next_tab_stop)
8835 };
8836 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8837 selection.end = selection.start;
8838 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8839 row_delta += tab_size.len;
8840 }
8841
8842 self.transact(window, cx, |this, window, cx| {
8843 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8844 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8845 s.select(selections)
8846 });
8847 this.refresh_inline_completion(true, false, window, cx);
8848 });
8849 }
8850
8851 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8852 if self.read_only(cx) {
8853 return;
8854 }
8855 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8856 let mut selections = self.selections.all::<Point>(cx);
8857 let mut prev_edited_row = 0;
8858 let mut row_delta = 0;
8859 let mut edits = Vec::new();
8860 let buffer = self.buffer.read(cx);
8861 let snapshot = buffer.snapshot(cx);
8862 for selection in &mut selections {
8863 if selection.start.row != prev_edited_row {
8864 row_delta = 0;
8865 }
8866 prev_edited_row = selection.end.row;
8867
8868 row_delta =
8869 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8870 }
8871
8872 self.transact(window, cx, |this, window, cx| {
8873 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8874 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8875 s.select(selections)
8876 });
8877 });
8878 }
8879
8880 fn indent_selection(
8881 buffer: &MultiBuffer,
8882 snapshot: &MultiBufferSnapshot,
8883 selection: &mut Selection<Point>,
8884 edits: &mut Vec<(Range<Point>, String)>,
8885 delta_for_start_row: u32,
8886 cx: &App,
8887 ) -> u32 {
8888 let settings = buffer.language_settings_at(selection.start, cx);
8889 let tab_size = settings.tab_size.get();
8890 let indent_kind = if settings.hard_tabs {
8891 IndentKind::Tab
8892 } else {
8893 IndentKind::Space
8894 };
8895 let mut start_row = selection.start.row;
8896 let mut end_row = selection.end.row + 1;
8897
8898 // If a selection ends at the beginning of a line, don't indent
8899 // that last line.
8900 if selection.end.column == 0 && selection.end.row > selection.start.row {
8901 end_row -= 1;
8902 }
8903
8904 // Avoid re-indenting a row that has already been indented by a
8905 // previous selection, but still update this selection's column
8906 // to reflect that indentation.
8907 if delta_for_start_row > 0 {
8908 start_row += 1;
8909 selection.start.column += delta_for_start_row;
8910 if selection.end.row == selection.start.row {
8911 selection.end.column += delta_for_start_row;
8912 }
8913 }
8914
8915 let mut delta_for_end_row = 0;
8916 let has_multiple_rows = start_row + 1 != end_row;
8917 for row in start_row..end_row {
8918 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8919 let indent_delta = match (current_indent.kind, indent_kind) {
8920 (IndentKind::Space, IndentKind::Space) => {
8921 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8922 IndentSize::spaces(columns_to_next_tab_stop)
8923 }
8924 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8925 (_, IndentKind::Tab) => IndentSize::tab(),
8926 };
8927
8928 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8929 0
8930 } else {
8931 selection.start.column
8932 };
8933 let row_start = Point::new(row, start);
8934 edits.push((
8935 row_start..row_start,
8936 indent_delta.chars().collect::<String>(),
8937 ));
8938
8939 // Update this selection's endpoints to reflect the indentation.
8940 if row == selection.start.row {
8941 selection.start.column += indent_delta.len;
8942 }
8943 if row == selection.end.row {
8944 selection.end.column += indent_delta.len;
8945 delta_for_end_row = indent_delta.len;
8946 }
8947 }
8948
8949 if selection.start.row == selection.end.row {
8950 delta_for_start_row + delta_for_end_row
8951 } else {
8952 delta_for_end_row
8953 }
8954 }
8955
8956 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8957 if self.read_only(cx) {
8958 return;
8959 }
8960 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8961 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8962 let selections = self.selections.all::<Point>(cx);
8963 let mut deletion_ranges = Vec::new();
8964 let mut last_outdent = None;
8965 {
8966 let buffer = self.buffer.read(cx);
8967 let snapshot = buffer.snapshot(cx);
8968 for selection in &selections {
8969 let settings = buffer.language_settings_at(selection.start, cx);
8970 let tab_size = settings.tab_size.get();
8971 let mut rows = selection.spanned_rows(false, &display_map);
8972
8973 // Avoid re-outdenting a row that has already been outdented by a
8974 // previous selection.
8975 if let Some(last_row) = last_outdent {
8976 if last_row == rows.start {
8977 rows.start = rows.start.next_row();
8978 }
8979 }
8980 let has_multiple_rows = rows.len() > 1;
8981 for row in rows.iter_rows() {
8982 let indent_size = snapshot.indent_size_for_line(row);
8983 if indent_size.len > 0 {
8984 let deletion_len = match indent_size.kind {
8985 IndentKind::Space => {
8986 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8987 if columns_to_prev_tab_stop == 0 {
8988 tab_size
8989 } else {
8990 columns_to_prev_tab_stop
8991 }
8992 }
8993 IndentKind::Tab => 1,
8994 };
8995 let start = if has_multiple_rows
8996 || deletion_len > selection.start.column
8997 || indent_size.len < selection.start.column
8998 {
8999 0
9000 } else {
9001 selection.start.column - deletion_len
9002 };
9003 deletion_ranges.push(
9004 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
9005 );
9006 last_outdent = Some(row);
9007 }
9008 }
9009 }
9010 }
9011
9012 self.transact(window, cx, |this, window, cx| {
9013 this.buffer.update(cx, |buffer, cx| {
9014 let empty_str: Arc<str> = Arc::default();
9015 buffer.edit(
9016 deletion_ranges
9017 .into_iter()
9018 .map(|range| (range, empty_str.clone())),
9019 None,
9020 cx,
9021 );
9022 });
9023 let selections = this.selections.all::<usize>(cx);
9024 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9025 s.select(selections)
9026 });
9027 });
9028 }
9029
9030 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
9031 if self.read_only(cx) {
9032 return;
9033 }
9034 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9035 let selections = self
9036 .selections
9037 .all::<usize>(cx)
9038 .into_iter()
9039 .map(|s| s.range());
9040
9041 self.transact(window, cx, |this, window, cx| {
9042 this.buffer.update(cx, |buffer, cx| {
9043 buffer.autoindent_ranges(selections, cx);
9044 });
9045 let selections = this.selections.all::<usize>(cx);
9046 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9047 s.select(selections)
9048 });
9049 });
9050 }
9051
9052 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
9053 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9054 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9055 let selections = self.selections.all::<Point>(cx);
9056
9057 let mut new_cursors = Vec::new();
9058 let mut edit_ranges = Vec::new();
9059 let mut selections = selections.iter().peekable();
9060 while let Some(selection) = selections.next() {
9061 let mut rows = selection.spanned_rows(false, &display_map);
9062 let goal_display_column = selection.head().to_display_point(&display_map).column();
9063
9064 // Accumulate contiguous regions of rows that we want to delete.
9065 while let Some(next_selection) = selections.peek() {
9066 let next_rows = next_selection.spanned_rows(false, &display_map);
9067 if next_rows.start <= rows.end {
9068 rows.end = next_rows.end;
9069 selections.next().unwrap();
9070 } else {
9071 break;
9072 }
9073 }
9074
9075 let buffer = &display_map.buffer_snapshot;
9076 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9077 let edit_end;
9078 let cursor_buffer_row;
9079 if buffer.max_point().row >= rows.end.0 {
9080 // If there's a line after the range, delete the \n from the end of the row range
9081 // and position the cursor on the next line.
9082 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9083 cursor_buffer_row = rows.end;
9084 } else {
9085 // If there isn't a line after the range, delete the \n from the line before the
9086 // start of the row range and position the cursor there.
9087 edit_start = edit_start.saturating_sub(1);
9088 edit_end = buffer.len();
9089 cursor_buffer_row = rows.start.previous_row();
9090 }
9091
9092 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9093 *cursor.column_mut() =
9094 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9095
9096 new_cursors.push((
9097 selection.id,
9098 buffer.anchor_after(cursor.to_point(&display_map)),
9099 ));
9100 edit_ranges.push(edit_start..edit_end);
9101 }
9102
9103 self.transact(window, cx, |this, window, cx| {
9104 let buffer = this.buffer.update(cx, |buffer, cx| {
9105 let empty_str: Arc<str> = Arc::default();
9106 buffer.edit(
9107 edit_ranges
9108 .into_iter()
9109 .map(|range| (range, empty_str.clone())),
9110 None,
9111 cx,
9112 );
9113 buffer.snapshot(cx)
9114 });
9115 let new_selections = new_cursors
9116 .into_iter()
9117 .map(|(id, cursor)| {
9118 let cursor = cursor.to_point(&buffer);
9119 Selection {
9120 id,
9121 start: cursor,
9122 end: cursor,
9123 reversed: false,
9124 goal: SelectionGoal::None,
9125 }
9126 })
9127 .collect();
9128
9129 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9130 s.select(new_selections);
9131 });
9132 });
9133 }
9134
9135 pub fn join_lines_impl(
9136 &mut self,
9137 insert_whitespace: bool,
9138 window: &mut Window,
9139 cx: &mut Context<Self>,
9140 ) {
9141 if self.read_only(cx) {
9142 return;
9143 }
9144 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9145 for selection in self.selections.all::<Point>(cx) {
9146 let start = MultiBufferRow(selection.start.row);
9147 // Treat single line selections as if they include the next line. Otherwise this action
9148 // would do nothing for single line selections individual cursors.
9149 let end = if selection.start.row == selection.end.row {
9150 MultiBufferRow(selection.start.row + 1)
9151 } else {
9152 MultiBufferRow(selection.end.row)
9153 };
9154
9155 if let Some(last_row_range) = row_ranges.last_mut() {
9156 if start <= last_row_range.end {
9157 last_row_range.end = end;
9158 continue;
9159 }
9160 }
9161 row_ranges.push(start..end);
9162 }
9163
9164 let snapshot = self.buffer.read(cx).snapshot(cx);
9165 let mut cursor_positions = Vec::new();
9166 for row_range in &row_ranges {
9167 let anchor = snapshot.anchor_before(Point::new(
9168 row_range.end.previous_row().0,
9169 snapshot.line_len(row_range.end.previous_row()),
9170 ));
9171 cursor_positions.push(anchor..anchor);
9172 }
9173
9174 self.transact(window, cx, |this, window, cx| {
9175 for row_range in row_ranges.into_iter().rev() {
9176 for row in row_range.iter_rows().rev() {
9177 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9178 let next_line_row = row.next_row();
9179 let indent = snapshot.indent_size_for_line(next_line_row);
9180 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9181
9182 let replace =
9183 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9184 " "
9185 } else {
9186 ""
9187 };
9188
9189 this.buffer.update(cx, |buffer, cx| {
9190 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9191 });
9192 }
9193 }
9194
9195 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9196 s.select_anchor_ranges(cursor_positions)
9197 });
9198 });
9199 }
9200
9201 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9202 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9203 self.join_lines_impl(true, window, cx);
9204 }
9205
9206 pub fn sort_lines_case_sensitive(
9207 &mut self,
9208 _: &SortLinesCaseSensitive,
9209 window: &mut Window,
9210 cx: &mut Context<Self>,
9211 ) {
9212 self.manipulate_lines(window, cx, |lines| lines.sort())
9213 }
9214
9215 pub fn sort_lines_case_insensitive(
9216 &mut self,
9217 _: &SortLinesCaseInsensitive,
9218 window: &mut Window,
9219 cx: &mut Context<Self>,
9220 ) {
9221 self.manipulate_lines(window, cx, |lines| {
9222 lines.sort_by_key(|line| line.to_lowercase())
9223 })
9224 }
9225
9226 pub fn unique_lines_case_insensitive(
9227 &mut self,
9228 _: &UniqueLinesCaseInsensitive,
9229 window: &mut Window,
9230 cx: &mut Context<Self>,
9231 ) {
9232 self.manipulate_lines(window, cx, |lines| {
9233 let mut seen = HashSet::default();
9234 lines.retain(|line| seen.insert(line.to_lowercase()));
9235 })
9236 }
9237
9238 pub fn unique_lines_case_sensitive(
9239 &mut self,
9240 _: &UniqueLinesCaseSensitive,
9241 window: &mut Window,
9242 cx: &mut Context<Self>,
9243 ) {
9244 self.manipulate_lines(window, cx, |lines| {
9245 let mut seen = HashSet::default();
9246 lines.retain(|line| seen.insert(*line));
9247 })
9248 }
9249
9250 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9251 let Some(project) = self.project.clone() else {
9252 return;
9253 };
9254 self.reload(project, window, cx)
9255 .detach_and_notify_err(window, cx);
9256 }
9257
9258 pub fn restore_file(
9259 &mut self,
9260 _: &::git::RestoreFile,
9261 window: &mut Window,
9262 cx: &mut Context<Self>,
9263 ) {
9264 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9265 let mut buffer_ids = HashSet::default();
9266 let snapshot = self.buffer().read(cx).snapshot(cx);
9267 for selection in self.selections.all::<usize>(cx) {
9268 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9269 }
9270
9271 let buffer = self.buffer().read(cx);
9272 let ranges = buffer_ids
9273 .into_iter()
9274 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9275 .collect::<Vec<_>>();
9276
9277 self.restore_hunks_in_ranges(ranges, window, cx);
9278 }
9279
9280 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9281 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9282 let selections = self
9283 .selections
9284 .all(cx)
9285 .into_iter()
9286 .map(|s| s.range())
9287 .collect();
9288 self.restore_hunks_in_ranges(selections, window, cx);
9289 }
9290
9291 pub fn restore_hunks_in_ranges(
9292 &mut self,
9293 ranges: Vec<Range<Point>>,
9294 window: &mut Window,
9295 cx: &mut Context<Editor>,
9296 ) {
9297 let mut revert_changes = HashMap::default();
9298 let chunk_by = self
9299 .snapshot(window, cx)
9300 .hunks_for_ranges(ranges)
9301 .into_iter()
9302 .chunk_by(|hunk| hunk.buffer_id);
9303 for (buffer_id, hunks) in &chunk_by {
9304 let hunks = hunks.collect::<Vec<_>>();
9305 for hunk in &hunks {
9306 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9307 }
9308 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9309 }
9310 drop(chunk_by);
9311 if !revert_changes.is_empty() {
9312 self.transact(window, cx, |editor, window, cx| {
9313 editor.restore(revert_changes, window, cx);
9314 });
9315 }
9316 }
9317
9318 pub fn open_active_item_in_terminal(
9319 &mut self,
9320 _: &OpenInTerminal,
9321 window: &mut Window,
9322 cx: &mut Context<Self>,
9323 ) {
9324 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9325 let project_path = buffer.read(cx).project_path(cx)?;
9326 let project = self.project.as_ref()?.read(cx);
9327 let entry = project.entry_for_path(&project_path, cx)?;
9328 let parent = match &entry.canonical_path {
9329 Some(canonical_path) => canonical_path.to_path_buf(),
9330 None => project.absolute_path(&project_path, cx)?,
9331 }
9332 .parent()?
9333 .to_path_buf();
9334 Some(parent)
9335 }) {
9336 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9337 }
9338 }
9339
9340 fn set_breakpoint_context_menu(
9341 &mut self,
9342 display_row: DisplayRow,
9343 position: Option<Anchor>,
9344 clicked_point: gpui::Point<Pixels>,
9345 window: &mut Window,
9346 cx: &mut Context<Self>,
9347 ) {
9348 if !cx.has_flag::<DebuggerFeatureFlag>() {
9349 return;
9350 }
9351 let source = self
9352 .buffer
9353 .read(cx)
9354 .snapshot(cx)
9355 .anchor_before(Point::new(display_row.0, 0u32));
9356
9357 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9358
9359 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9360 self,
9361 source,
9362 clicked_point,
9363 context_menu,
9364 window,
9365 cx,
9366 );
9367 }
9368
9369 fn add_edit_breakpoint_block(
9370 &mut self,
9371 anchor: Anchor,
9372 breakpoint: &Breakpoint,
9373 edit_action: BreakpointPromptEditAction,
9374 window: &mut Window,
9375 cx: &mut Context<Self>,
9376 ) {
9377 let weak_editor = cx.weak_entity();
9378 let bp_prompt = cx.new(|cx| {
9379 BreakpointPromptEditor::new(
9380 weak_editor,
9381 anchor,
9382 breakpoint.clone(),
9383 edit_action,
9384 window,
9385 cx,
9386 )
9387 });
9388
9389 let height = bp_prompt.update(cx, |this, cx| {
9390 this.prompt
9391 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9392 });
9393 let cloned_prompt = bp_prompt.clone();
9394 let blocks = vec![BlockProperties {
9395 style: BlockStyle::Sticky,
9396 placement: BlockPlacement::Above(anchor),
9397 height: Some(height),
9398 render: Arc::new(move |cx| {
9399 *cloned_prompt.read(cx).editor_margins.lock() = *cx.margins;
9400 cloned_prompt.clone().into_any_element()
9401 }),
9402 priority: 0,
9403 render_in_minimap: true,
9404 }];
9405
9406 let focus_handle = bp_prompt.focus_handle(cx);
9407 window.focus(&focus_handle);
9408
9409 let block_ids = self.insert_blocks(blocks, None, cx);
9410 bp_prompt.update(cx, |prompt, _| {
9411 prompt.add_block_ids(block_ids);
9412 });
9413 }
9414
9415 pub(crate) fn breakpoint_at_row(
9416 &self,
9417 row: u32,
9418 window: &mut Window,
9419 cx: &mut Context<Self>,
9420 ) -> Option<(Anchor, Breakpoint)> {
9421 let snapshot = self.snapshot(window, cx);
9422 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9423
9424 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9425 }
9426
9427 pub(crate) fn breakpoint_at_anchor(
9428 &self,
9429 breakpoint_position: Anchor,
9430 snapshot: &EditorSnapshot,
9431 cx: &mut Context<Self>,
9432 ) -> Option<(Anchor, Breakpoint)> {
9433 let project = self.project.clone()?;
9434
9435 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9436 snapshot
9437 .buffer_snapshot
9438 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9439 })?;
9440
9441 let enclosing_excerpt = breakpoint_position.excerpt_id;
9442 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9443 let buffer_snapshot = buffer.read(cx).snapshot();
9444
9445 let row = buffer_snapshot
9446 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9447 .row;
9448
9449 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9450 let anchor_end = snapshot
9451 .buffer_snapshot
9452 .anchor_after(Point::new(row, line_len));
9453
9454 let bp = self
9455 .breakpoint_store
9456 .as_ref()?
9457 .read_with(cx, |breakpoint_store, cx| {
9458 breakpoint_store
9459 .breakpoints(
9460 &buffer,
9461 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9462 &buffer_snapshot,
9463 cx,
9464 )
9465 .next()
9466 .and_then(|(anchor, bp)| {
9467 let breakpoint_row = buffer_snapshot
9468 .summary_for_anchor::<text::PointUtf16>(anchor)
9469 .row;
9470
9471 if breakpoint_row == row {
9472 snapshot
9473 .buffer_snapshot
9474 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9475 .map(|anchor| (anchor, bp.clone()))
9476 } else {
9477 None
9478 }
9479 })
9480 });
9481 bp
9482 }
9483
9484 pub fn edit_log_breakpoint(
9485 &mut self,
9486 _: &EditLogBreakpoint,
9487 window: &mut Window,
9488 cx: &mut Context<Self>,
9489 ) {
9490 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9491 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9492 message: None,
9493 state: BreakpointState::Enabled,
9494 condition: None,
9495 hit_condition: None,
9496 });
9497
9498 self.add_edit_breakpoint_block(
9499 anchor,
9500 &breakpoint,
9501 BreakpointPromptEditAction::Log,
9502 window,
9503 cx,
9504 );
9505 }
9506 }
9507
9508 fn breakpoints_at_cursors(
9509 &self,
9510 window: &mut Window,
9511 cx: &mut Context<Self>,
9512 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9513 let snapshot = self.snapshot(window, cx);
9514 let cursors = self
9515 .selections
9516 .disjoint_anchors()
9517 .into_iter()
9518 .map(|selection| {
9519 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9520
9521 let breakpoint_position = self
9522 .breakpoint_at_row(cursor_position.row, window, cx)
9523 .map(|bp| bp.0)
9524 .unwrap_or_else(|| {
9525 snapshot
9526 .display_snapshot
9527 .buffer_snapshot
9528 .anchor_after(Point::new(cursor_position.row, 0))
9529 });
9530
9531 let breakpoint = self
9532 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9533 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9534
9535 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9536 })
9537 // 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.
9538 .collect::<HashMap<Anchor, _>>();
9539
9540 cursors.into_iter().collect()
9541 }
9542
9543 pub fn enable_breakpoint(
9544 &mut self,
9545 _: &crate::actions::EnableBreakpoint,
9546 window: &mut Window,
9547 cx: &mut Context<Self>,
9548 ) {
9549 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9550 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9551 continue;
9552 };
9553 self.edit_breakpoint_at_anchor(
9554 anchor,
9555 breakpoint,
9556 BreakpointEditAction::InvertState,
9557 cx,
9558 );
9559 }
9560 }
9561
9562 pub fn disable_breakpoint(
9563 &mut self,
9564 _: &crate::actions::DisableBreakpoint,
9565 window: &mut Window,
9566 cx: &mut Context<Self>,
9567 ) {
9568 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9569 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9570 continue;
9571 };
9572 self.edit_breakpoint_at_anchor(
9573 anchor,
9574 breakpoint,
9575 BreakpointEditAction::InvertState,
9576 cx,
9577 );
9578 }
9579 }
9580
9581 pub fn toggle_breakpoint(
9582 &mut self,
9583 _: &crate::actions::ToggleBreakpoint,
9584 window: &mut Window,
9585 cx: &mut Context<Self>,
9586 ) {
9587 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9588 if let Some(breakpoint) = breakpoint {
9589 self.edit_breakpoint_at_anchor(
9590 anchor,
9591 breakpoint,
9592 BreakpointEditAction::Toggle,
9593 cx,
9594 );
9595 } else {
9596 self.edit_breakpoint_at_anchor(
9597 anchor,
9598 Breakpoint::new_standard(),
9599 BreakpointEditAction::Toggle,
9600 cx,
9601 );
9602 }
9603 }
9604 }
9605
9606 pub fn edit_breakpoint_at_anchor(
9607 &mut self,
9608 breakpoint_position: Anchor,
9609 breakpoint: Breakpoint,
9610 edit_action: BreakpointEditAction,
9611 cx: &mut Context<Self>,
9612 ) {
9613 let Some(breakpoint_store) = &self.breakpoint_store else {
9614 return;
9615 };
9616
9617 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9618 if breakpoint_position == Anchor::min() {
9619 self.buffer()
9620 .read(cx)
9621 .excerpt_buffer_ids()
9622 .into_iter()
9623 .next()
9624 } else {
9625 None
9626 }
9627 }) else {
9628 return;
9629 };
9630
9631 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9632 return;
9633 };
9634
9635 breakpoint_store.update(cx, |breakpoint_store, cx| {
9636 breakpoint_store.toggle_breakpoint(
9637 buffer,
9638 (breakpoint_position.text_anchor, breakpoint),
9639 edit_action,
9640 cx,
9641 );
9642 });
9643
9644 cx.notify();
9645 }
9646
9647 #[cfg(any(test, feature = "test-support"))]
9648 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9649 self.breakpoint_store.clone()
9650 }
9651
9652 pub fn prepare_restore_change(
9653 &self,
9654 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9655 hunk: &MultiBufferDiffHunk,
9656 cx: &mut App,
9657 ) -> Option<()> {
9658 if hunk.is_created_file() {
9659 return None;
9660 }
9661 let buffer = self.buffer.read(cx);
9662 let diff = buffer.diff_for(hunk.buffer_id)?;
9663 let buffer = buffer.buffer(hunk.buffer_id)?;
9664 let buffer = buffer.read(cx);
9665 let original_text = diff
9666 .read(cx)
9667 .base_text()
9668 .as_rope()
9669 .slice(hunk.diff_base_byte_range.clone());
9670 let buffer_snapshot = buffer.snapshot();
9671 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9672 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9673 probe
9674 .0
9675 .start
9676 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9677 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9678 }) {
9679 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9680 Some(())
9681 } else {
9682 None
9683 }
9684 }
9685
9686 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9687 self.manipulate_lines(window, cx, |lines| lines.reverse())
9688 }
9689
9690 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9691 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9692 }
9693
9694 fn manipulate_lines<Fn>(
9695 &mut self,
9696 window: &mut Window,
9697 cx: &mut Context<Self>,
9698 mut callback: Fn,
9699 ) where
9700 Fn: FnMut(&mut Vec<&str>),
9701 {
9702 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9703
9704 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9705 let buffer = self.buffer.read(cx).snapshot(cx);
9706
9707 let mut edits = Vec::new();
9708
9709 let selections = self.selections.all::<Point>(cx);
9710 let mut selections = selections.iter().peekable();
9711 let mut contiguous_row_selections = Vec::new();
9712 let mut new_selections = Vec::new();
9713 let mut added_lines = 0;
9714 let mut removed_lines = 0;
9715
9716 while let Some(selection) = selections.next() {
9717 let (start_row, end_row) = consume_contiguous_rows(
9718 &mut contiguous_row_selections,
9719 selection,
9720 &display_map,
9721 &mut selections,
9722 );
9723
9724 let start_point = Point::new(start_row.0, 0);
9725 let end_point = Point::new(
9726 end_row.previous_row().0,
9727 buffer.line_len(end_row.previous_row()),
9728 );
9729 let text = buffer
9730 .text_for_range(start_point..end_point)
9731 .collect::<String>();
9732
9733 let mut lines = text.split('\n').collect_vec();
9734
9735 let lines_before = lines.len();
9736 callback(&mut lines);
9737 let lines_after = lines.len();
9738
9739 edits.push((start_point..end_point, lines.join("\n")));
9740
9741 // Selections must change based on added and removed line count
9742 let start_row =
9743 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9744 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9745 new_selections.push(Selection {
9746 id: selection.id,
9747 start: start_row,
9748 end: end_row,
9749 goal: SelectionGoal::None,
9750 reversed: selection.reversed,
9751 });
9752
9753 if lines_after > lines_before {
9754 added_lines += lines_after - lines_before;
9755 } else if lines_before > lines_after {
9756 removed_lines += lines_before - lines_after;
9757 }
9758 }
9759
9760 self.transact(window, cx, |this, window, cx| {
9761 let buffer = this.buffer.update(cx, |buffer, cx| {
9762 buffer.edit(edits, None, cx);
9763 buffer.snapshot(cx)
9764 });
9765
9766 // Recalculate offsets on newly edited buffer
9767 let new_selections = new_selections
9768 .iter()
9769 .map(|s| {
9770 let start_point = Point::new(s.start.0, 0);
9771 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9772 Selection {
9773 id: s.id,
9774 start: buffer.point_to_offset(start_point),
9775 end: buffer.point_to_offset(end_point),
9776 goal: s.goal,
9777 reversed: s.reversed,
9778 }
9779 })
9780 .collect();
9781
9782 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9783 s.select(new_selections);
9784 });
9785
9786 this.request_autoscroll(Autoscroll::fit(), cx);
9787 });
9788 }
9789
9790 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9791 self.manipulate_text(window, cx, |text| {
9792 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9793 if has_upper_case_characters {
9794 text.to_lowercase()
9795 } else {
9796 text.to_uppercase()
9797 }
9798 })
9799 }
9800
9801 pub fn convert_to_upper_case(
9802 &mut self,
9803 _: &ConvertToUpperCase,
9804 window: &mut Window,
9805 cx: &mut Context<Self>,
9806 ) {
9807 self.manipulate_text(window, cx, |text| text.to_uppercase())
9808 }
9809
9810 pub fn convert_to_lower_case(
9811 &mut self,
9812 _: &ConvertToLowerCase,
9813 window: &mut Window,
9814 cx: &mut Context<Self>,
9815 ) {
9816 self.manipulate_text(window, cx, |text| text.to_lowercase())
9817 }
9818
9819 pub fn convert_to_title_case(
9820 &mut self,
9821 _: &ConvertToTitleCase,
9822 window: &mut Window,
9823 cx: &mut Context<Self>,
9824 ) {
9825 self.manipulate_text(window, cx, |text| {
9826 text.split('\n')
9827 .map(|line| line.to_case(Case::Title))
9828 .join("\n")
9829 })
9830 }
9831
9832 pub fn convert_to_snake_case(
9833 &mut self,
9834 _: &ConvertToSnakeCase,
9835 window: &mut Window,
9836 cx: &mut Context<Self>,
9837 ) {
9838 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9839 }
9840
9841 pub fn convert_to_kebab_case(
9842 &mut self,
9843 _: &ConvertToKebabCase,
9844 window: &mut Window,
9845 cx: &mut Context<Self>,
9846 ) {
9847 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9848 }
9849
9850 pub fn convert_to_upper_camel_case(
9851 &mut self,
9852 _: &ConvertToUpperCamelCase,
9853 window: &mut Window,
9854 cx: &mut Context<Self>,
9855 ) {
9856 self.manipulate_text(window, cx, |text| {
9857 text.split('\n')
9858 .map(|line| line.to_case(Case::UpperCamel))
9859 .join("\n")
9860 })
9861 }
9862
9863 pub fn convert_to_lower_camel_case(
9864 &mut self,
9865 _: &ConvertToLowerCamelCase,
9866 window: &mut Window,
9867 cx: &mut Context<Self>,
9868 ) {
9869 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9870 }
9871
9872 pub fn convert_to_opposite_case(
9873 &mut self,
9874 _: &ConvertToOppositeCase,
9875 window: &mut Window,
9876 cx: &mut Context<Self>,
9877 ) {
9878 self.manipulate_text(window, cx, |text| {
9879 text.chars()
9880 .fold(String::with_capacity(text.len()), |mut t, c| {
9881 if c.is_uppercase() {
9882 t.extend(c.to_lowercase());
9883 } else {
9884 t.extend(c.to_uppercase());
9885 }
9886 t
9887 })
9888 })
9889 }
9890
9891 pub fn convert_to_rot13(
9892 &mut self,
9893 _: &ConvertToRot13,
9894 window: &mut Window,
9895 cx: &mut Context<Self>,
9896 ) {
9897 self.manipulate_text(window, cx, |text| {
9898 text.chars()
9899 .map(|c| match c {
9900 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9901 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9902 _ => c,
9903 })
9904 .collect()
9905 })
9906 }
9907
9908 pub fn convert_to_rot47(
9909 &mut self,
9910 _: &ConvertToRot47,
9911 window: &mut Window,
9912 cx: &mut Context<Self>,
9913 ) {
9914 self.manipulate_text(window, cx, |text| {
9915 text.chars()
9916 .map(|c| {
9917 let code_point = c as u32;
9918 if code_point >= 33 && code_point <= 126 {
9919 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9920 }
9921 c
9922 })
9923 .collect()
9924 })
9925 }
9926
9927 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9928 where
9929 Fn: FnMut(&str) -> String,
9930 {
9931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9932 let buffer = self.buffer.read(cx).snapshot(cx);
9933
9934 let mut new_selections = Vec::new();
9935 let mut edits = Vec::new();
9936 let mut selection_adjustment = 0i32;
9937
9938 for selection in self.selections.all::<usize>(cx) {
9939 let selection_is_empty = selection.is_empty();
9940
9941 let (start, end) = if selection_is_empty {
9942 let word_range = movement::surrounding_word(
9943 &display_map,
9944 selection.start.to_display_point(&display_map),
9945 );
9946 let start = word_range.start.to_offset(&display_map, Bias::Left);
9947 let end = word_range.end.to_offset(&display_map, Bias::Left);
9948 (start, end)
9949 } else {
9950 (selection.start, selection.end)
9951 };
9952
9953 let text = buffer.text_for_range(start..end).collect::<String>();
9954 let old_length = text.len() as i32;
9955 let text = callback(&text);
9956
9957 new_selections.push(Selection {
9958 start: (start as i32 - selection_adjustment) as usize,
9959 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9960 goal: SelectionGoal::None,
9961 ..selection
9962 });
9963
9964 selection_adjustment += old_length - text.len() as i32;
9965
9966 edits.push((start..end, text));
9967 }
9968
9969 self.transact(window, cx, |this, window, cx| {
9970 this.buffer.update(cx, |buffer, cx| {
9971 buffer.edit(edits, None, cx);
9972 });
9973
9974 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9975 s.select(new_selections);
9976 });
9977
9978 this.request_autoscroll(Autoscroll::fit(), cx);
9979 });
9980 }
9981
9982 pub fn duplicate(
9983 &mut self,
9984 upwards: bool,
9985 whole_lines: bool,
9986 window: &mut Window,
9987 cx: &mut Context<Self>,
9988 ) {
9989 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9990
9991 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9992 let buffer = &display_map.buffer_snapshot;
9993 let selections = self.selections.all::<Point>(cx);
9994
9995 let mut edits = Vec::new();
9996 let mut selections_iter = selections.iter().peekable();
9997 while let Some(selection) = selections_iter.next() {
9998 let mut rows = selection.spanned_rows(false, &display_map);
9999 // duplicate line-wise
10000 if whole_lines || selection.start == selection.end {
10001 // Avoid duplicating the same lines twice.
10002 while let Some(next_selection) = selections_iter.peek() {
10003 let next_rows = next_selection.spanned_rows(false, &display_map);
10004 if next_rows.start < rows.end {
10005 rows.end = next_rows.end;
10006 selections_iter.next().unwrap();
10007 } else {
10008 break;
10009 }
10010 }
10011
10012 // Copy the text from the selected row region and splice it either at the start
10013 // or end of the region.
10014 let start = Point::new(rows.start.0, 0);
10015 let end = Point::new(
10016 rows.end.previous_row().0,
10017 buffer.line_len(rows.end.previous_row()),
10018 );
10019 let text = buffer
10020 .text_for_range(start..end)
10021 .chain(Some("\n"))
10022 .collect::<String>();
10023 let insert_location = if upwards {
10024 Point::new(rows.end.0, 0)
10025 } else {
10026 start
10027 };
10028 edits.push((insert_location..insert_location, text));
10029 } else {
10030 // duplicate character-wise
10031 let start = selection.start;
10032 let end = selection.end;
10033 let text = buffer.text_for_range(start..end).collect::<String>();
10034 edits.push((selection.end..selection.end, text));
10035 }
10036 }
10037
10038 self.transact(window, cx, |this, _, cx| {
10039 this.buffer.update(cx, |buffer, cx| {
10040 buffer.edit(edits, None, cx);
10041 });
10042
10043 this.request_autoscroll(Autoscroll::fit(), cx);
10044 });
10045 }
10046
10047 pub fn duplicate_line_up(
10048 &mut self,
10049 _: &DuplicateLineUp,
10050 window: &mut Window,
10051 cx: &mut Context<Self>,
10052 ) {
10053 self.duplicate(true, true, window, cx);
10054 }
10055
10056 pub fn duplicate_line_down(
10057 &mut self,
10058 _: &DuplicateLineDown,
10059 window: &mut Window,
10060 cx: &mut Context<Self>,
10061 ) {
10062 self.duplicate(false, true, window, cx);
10063 }
10064
10065 pub fn duplicate_selection(
10066 &mut self,
10067 _: &DuplicateSelection,
10068 window: &mut Window,
10069 cx: &mut Context<Self>,
10070 ) {
10071 self.duplicate(false, false, window, cx);
10072 }
10073
10074 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10075 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10076
10077 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10078 let buffer = self.buffer.read(cx).snapshot(cx);
10079
10080 let mut edits = Vec::new();
10081 let mut unfold_ranges = Vec::new();
10082 let mut refold_creases = Vec::new();
10083
10084 let selections = self.selections.all::<Point>(cx);
10085 let mut selections = selections.iter().peekable();
10086 let mut contiguous_row_selections = Vec::new();
10087 let mut new_selections = Vec::new();
10088
10089 while let Some(selection) = selections.next() {
10090 // Find all the selections that span a contiguous row range
10091 let (start_row, end_row) = consume_contiguous_rows(
10092 &mut contiguous_row_selections,
10093 selection,
10094 &display_map,
10095 &mut selections,
10096 );
10097
10098 // Move the text spanned by the row range to be before the line preceding the row range
10099 if start_row.0 > 0 {
10100 let range_to_move = Point::new(
10101 start_row.previous_row().0,
10102 buffer.line_len(start_row.previous_row()),
10103 )
10104 ..Point::new(
10105 end_row.previous_row().0,
10106 buffer.line_len(end_row.previous_row()),
10107 );
10108 let insertion_point = display_map
10109 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10110 .0;
10111
10112 // Don't move lines across excerpts
10113 if buffer
10114 .excerpt_containing(insertion_point..range_to_move.end)
10115 .is_some()
10116 {
10117 let text = buffer
10118 .text_for_range(range_to_move.clone())
10119 .flat_map(|s| s.chars())
10120 .skip(1)
10121 .chain(['\n'])
10122 .collect::<String>();
10123
10124 edits.push((
10125 buffer.anchor_after(range_to_move.start)
10126 ..buffer.anchor_before(range_to_move.end),
10127 String::new(),
10128 ));
10129 let insertion_anchor = buffer.anchor_after(insertion_point);
10130 edits.push((insertion_anchor..insertion_anchor, text));
10131
10132 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10133
10134 // Move selections up
10135 new_selections.extend(contiguous_row_selections.drain(..).map(
10136 |mut selection| {
10137 selection.start.row -= row_delta;
10138 selection.end.row -= row_delta;
10139 selection
10140 },
10141 ));
10142
10143 // Move folds up
10144 unfold_ranges.push(range_to_move.clone());
10145 for fold in display_map.folds_in_range(
10146 buffer.anchor_before(range_to_move.start)
10147 ..buffer.anchor_after(range_to_move.end),
10148 ) {
10149 let mut start = fold.range.start.to_point(&buffer);
10150 let mut end = fold.range.end.to_point(&buffer);
10151 start.row -= row_delta;
10152 end.row -= row_delta;
10153 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10154 }
10155 }
10156 }
10157
10158 // If we didn't move line(s), preserve the existing selections
10159 new_selections.append(&mut contiguous_row_selections);
10160 }
10161
10162 self.transact(window, cx, |this, window, cx| {
10163 this.unfold_ranges(&unfold_ranges, true, true, cx);
10164 this.buffer.update(cx, |buffer, cx| {
10165 for (range, text) in edits {
10166 buffer.edit([(range, text)], None, cx);
10167 }
10168 });
10169 this.fold_creases(refold_creases, true, window, cx);
10170 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10171 s.select(new_selections);
10172 })
10173 });
10174 }
10175
10176 pub fn move_line_down(
10177 &mut self,
10178 _: &MoveLineDown,
10179 window: &mut Window,
10180 cx: &mut Context<Self>,
10181 ) {
10182 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10183
10184 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10185 let buffer = self.buffer.read(cx).snapshot(cx);
10186
10187 let mut edits = Vec::new();
10188 let mut unfold_ranges = Vec::new();
10189 let mut refold_creases = Vec::new();
10190
10191 let selections = self.selections.all::<Point>(cx);
10192 let mut selections = selections.iter().peekable();
10193 let mut contiguous_row_selections = Vec::new();
10194 let mut new_selections = Vec::new();
10195
10196 while let Some(selection) = selections.next() {
10197 // Find all the selections that span a contiguous row range
10198 let (start_row, end_row) = consume_contiguous_rows(
10199 &mut contiguous_row_selections,
10200 selection,
10201 &display_map,
10202 &mut selections,
10203 );
10204
10205 // Move the text spanned by the row range to be after the last line of the row range
10206 if end_row.0 <= buffer.max_point().row {
10207 let range_to_move =
10208 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10209 let insertion_point = display_map
10210 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10211 .0;
10212
10213 // Don't move lines across excerpt boundaries
10214 if buffer
10215 .excerpt_containing(range_to_move.start..insertion_point)
10216 .is_some()
10217 {
10218 let mut text = String::from("\n");
10219 text.extend(buffer.text_for_range(range_to_move.clone()));
10220 text.pop(); // Drop trailing newline
10221 edits.push((
10222 buffer.anchor_after(range_to_move.start)
10223 ..buffer.anchor_before(range_to_move.end),
10224 String::new(),
10225 ));
10226 let insertion_anchor = buffer.anchor_after(insertion_point);
10227 edits.push((insertion_anchor..insertion_anchor, text));
10228
10229 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10230
10231 // Move selections down
10232 new_selections.extend(contiguous_row_selections.drain(..).map(
10233 |mut selection| {
10234 selection.start.row += row_delta;
10235 selection.end.row += row_delta;
10236 selection
10237 },
10238 ));
10239
10240 // Move folds down
10241 unfold_ranges.push(range_to_move.clone());
10242 for fold in display_map.folds_in_range(
10243 buffer.anchor_before(range_to_move.start)
10244 ..buffer.anchor_after(range_to_move.end),
10245 ) {
10246 let mut start = fold.range.start.to_point(&buffer);
10247 let mut end = fold.range.end.to_point(&buffer);
10248 start.row += row_delta;
10249 end.row += row_delta;
10250 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10251 }
10252 }
10253 }
10254
10255 // If we didn't move line(s), preserve the existing selections
10256 new_selections.append(&mut contiguous_row_selections);
10257 }
10258
10259 self.transact(window, cx, |this, window, cx| {
10260 this.unfold_ranges(&unfold_ranges, true, true, cx);
10261 this.buffer.update(cx, |buffer, cx| {
10262 for (range, text) in edits {
10263 buffer.edit([(range, text)], None, cx);
10264 }
10265 });
10266 this.fold_creases(refold_creases, true, window, cx);
10267 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10268 s.select(new_selections)
10269 });
10270 });
10271 }
10272
10273 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10274 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10275 let text_layout_details = &self.text_layout_details(window);
10276 self.transact(window, cx, |this, window, cx| {
10277 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10278 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10279 s.move_with(|display_map, selection| {
10280 if !selection.is_empty() {
10281 return;
10282 }
10283
10284 let mut head = selection.head();
10285 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10286 if head.column() == display_map.line_len(head.row()) {
10287 transpose_offset = display_map
10288 .buffer_snapshot
10289 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10290 }
10291
10292 if transpose_offset == 0 {
10293 return;
10294 }
10295
10296 *head.column_mut() += 1;
10297 head = display_map.clip_point(head, Bias::Right);
10298 let goal = SelectionGoal::HorizontalPosition(
10299 display_map
10300 .x_for_display_point(head, text_layout_details)
10301 .into(),
10302 );
10303 selection.collapse_to(head, goal);
10304
10305 let transpose_start = display_map
10306 .buffer_snapshot
10307 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10308 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10309 let transpose_end = display_map
10310 .buffer_snapshot
10311 .clip_offset(transpose_offset + 1, Bias::Right);
10312 if let Some(ch) =
10313 display_map.buffer_snapshot.chars_at(transpose_start).next()
10314 {
10315 edits.push((transpose_start..transpose_offset, String::new()));
10316 edits.push((transpose_end..transpose_end, ch.to_string()));
10317 }
10318 }
10319 });
10320 edits
10321 });
10322 this.buffer
10323 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10324 let selections = this.selections.all::<usize>(cx);
10325 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10326 s.select(selections);
10327 });
10328 });
10329 }
10330
10331 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10332 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10333 self.rewrap_impl(RewrapOptions::default(), cx)
10334 }
10335
10336 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10337 let buffer = self.buffer.read(cx).snapshot(cx);
10338 let selections = self.selections.all::<Point>(cx);
10339 let mut selections = selections.iter().peekable();
10340
10341 let mut edits = Vec::new();
10342 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10343
10344 while let Some(selection) = selections.next() {
10345 let mut start_row = selection.start.row;
10346 let mut end_row = selection.end.row;
10347
10348 // Skip selections that overlap with a range that has already been rewrapped.
10349 let selection_range = start_row..end_row;
10350 if rewrapped_row_ranges
10351 .iter()
10352 .any(|range| range.overlaps(&selection_range))
10353 {
10354 continue;
10355 }
10356
10357 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10358
10359 // Since not all lines in the selection may be at the same indent
10360 // level, choose the indent size that is the most common between all
10361 // of the lines.
10362 //
10363 // If there is a tie, we use the deepest indent.
10364 let (indent_size, indent_end) = {
10365 let mut indent_size_occurrences = HashMap::default();
10366 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10367
10368 for row in start_row..=end_row {
10369 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10370 rows_by_indent_size.entry(indent).or_default().push(row);
10371 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10372 }
10373
10374 let indent_size = indent_size_occurrences
10375 .into_iter()
10376 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10377 .map(|(indent, _)| indent)
10378 .unwrap_or_default();
10379 let row = rows_by_indent_size[&indent_size][0];
10380 let indent_end = Point::new(row, indent_size.len);
10381
10382 (indent_size, indent_end)
10383 };
10384
10385 let mut line_prefix = indent_size.chars().collect::<String>();
10386
10387 let mut inside_comment = false;
10388 if let Some(comment_prefix) =
10389 buffer
10390 .language_scope_at(selection.head())
10391 .and_then(|language| {
10392 language
10393 .line_comment_prefixes()
10394 .iter()
10395 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10396 .cloned()
10397 })
10398 {
10399 line_prefix.push_str(&comment_prefix);
10400 inside_comment = true;
10401 }
10402
10403 let language_settings = buffer.language_settings_at(selection.head(), cx);
10404 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10405 RewrapBehavior::InComments => inside_comment,
10406 RewrapBehavior::InSelections => !selection.is_empty(),
10407 RewrapBehavior::Anywhere => true,
10408 };
10409
10410 let should_rewrap = options.override_language_settings
10411 || allow_rewrap_based_on_language
10412 || self.hard_wrap.is_some();
10413 if !should_rewrap {
10414 continue;
10415 }
10416
10417 if selection.is_empty() {
10418 'expand_upwards: while start_row > 0 {
10419 let prev_row = start_row - 1;
10420 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10421 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10422 {
10423 start_row = prev_row;
10424 } else {
10425 break 'expand_upwards;
10426 }
10427 }
10428
10429 'expand_downwards: while end_row < buffer.max_point().row {
10430 let next_row = end_row + 1;
10431 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10432 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10433 {
10434 end_row = next_row;
10435 } else {
10436 break 'expand_downwards;
10437 }
10438 }
10439 }
10440
10441 let start = Point::new(start_row, 0);
10442 let start_offset = start.to_offset(&buffer);
10443 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10444 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10445 let Some(lines_without_prefixes) = selection_text
10446 .lines()
10447 .map(|line| {
10448 line.strip_prefix(&line_prefix)
10449 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10450 .ok_or_else(|| {
10451 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10452 })
10453 })
10454 .collect::<Result<Vec<_>, _>>()
10455 .log_err()
10456 else {
10457 continue;
10458 };
10459
10460 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10461 buffer
10462 .language_settings_at(Point::new(start_row, 0), cx)
10463 .preferred_line_length as usize
10464 });
10465 let wrapped_text = wrap_with_prefix(
10466 line_prefix,
10467 lines_without_prefixes.join("\n"),
10468 wrap_column,
10469 tab_size,
10470 options.preserve_existing_whitespace,
10471 );
10472
10473 // TODO: should always use char-based diff while still supporting cursor behavior that
10474 // matches vim.
10475 let mut diff_options = DiffOptions::default();
10476 if options.override_language_settings {
10477 diff_options.max_word_diff_len = 0;
10478 diff_options.max_word_diff_line_count = 0;
10479 } else {
10480 diff_options.max_word_diff_len = usize::MAX;
10481 diff_options.max_word_diff_line_count = usize::MAX;
10482 }
10483
10484 for (old_range, new_text) in
10485 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10486 {
10487 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10488 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10489 edits.push((edit_start..edit_end, new_text));
10490 }
10491
10492 rewrapped_row_ranges.push(start_row..=end_row);
10493 }
10494
10495 self.buffer
10496 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10497 }
10498
10499 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10500 let mut text = String::new();
10501 let buffer = self.buffer.read(cx).snapshot(cx);
10502 let mut selections = self.selections.all::<Point>(cx);
10503 let mut clipboard_selections = Vec::with_capacity(selections.len());
10504 {
10505 let max_point = buffer.max_point();
10506 let mut is_first = true;
10507 for selection in &mut selections {
10508 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10509 if is_entire_line {
10510 selection.start = Point::new(selection.start.row, 0);
10511 if !selection.is_empty() && selection.end.column == 0 {
10512 selection.end = cmp::min(max_point, selection.end);
10513 } else {
10514 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10515 }
10516 selection.goal = SelectionGoal::None;
10517 }
10518 if is_first {
10519 is_first = false;
10520 } else {
10521 text += "\n";
10522 }
10523 let mut len = 0;
10524 for chunk in buffer.text_for_range(selection.start..selection.end) {
10525 text.push_str(chunk);
10526 len += chunk.len();
10527 }
10528 clipboard_selections.push(ClipboardSelection {
10529 len,
10530 is_entire_line,
10531 first_line_indent: buffer
10532 .indent_size_for_line(MultiBufferRow(selection.start.row))
10533 .len,
10534 });
10535 }
10536 }
10537
10538 self.transact(window, cx, |this, window, cx| {
10539 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10540 s.select(selections);
10541 });
10542 this.insert("", window, cx);
10543 });
10544 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10545 }
10546
10547 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10548 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10549 let item = self.cut_common(window, cx);
10550 cx.write_to_clipboard(item);
10551 }
10552
10553 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10554 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10555 self.change_selections(None, window, cx, |s| {
10556 s.move_with(|snapshot, sel| {
10557 if sel.is_empty() {
10558 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10559 }
10560 });
10561 });
10562 let item = self.cut_common(window, cx);
10563 cx.set_global(KillRing(item))
10564 }
10565
10566 pub fn kill_ring_yank(
10567 &mut self,
10568 _: &KillRingYank,
10569 window: &mut Window,
10570 cx: &mut Context<Self>,
10571 ) {
10572 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10573 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10574 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10575 (kill_ring.text().to_string(), kill_ring.metadata_json())
10576 } else {
10577 return;
10578 }
10579 } else {
10580 return;
10581 };
10582 self.do_paste(&text, metadata, false, window, cx);
10583 }
10584
10585 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10586 self.do_copy(true, cx);
10587 }
10588
10589 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10590 self.do_copy(false, cx);
10591 }
10592
10593 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10594 let selections = self.selections.all::<Point>(cx);
10595 let buffer = self.buffer.read(cx).read(cx);
10596 let mut text = String::new();
10597
10598 let mut clipboard_selections = Vec::with_capacity(selections.len());
10599 {
10600 let max_point = buffer.max_point();
10601 let mut is_first = true;
10602 for selection in &selections {
10603 let mut start = selection.start;
10604 let mut end = selection.end;
10605 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10606 if is_entire_line {
10607 start = Point::new(start.row, 0);
10608 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10609 }
10610
10611 let mut trimmed_selections = Vec::new();
10612 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10613 let row = MultiBufferRow(start.row);
10614 let first_indent = buffer.indent_size_for_line(row);
10615 if first_indent.len == 0 || start.column > first_indent.len {
10616 trimmed_selections.push(start..end);
10617 } else {
10618 trimmed_selections.push(
10619 Point::new(row.0, first_indent.len)
10620 ..Point::new(row.0, buffer.line_len(row)),
10621 );
10622 for row in start.row + 1..=end.row {
10623 let mut line_len = buffer.line_len(MultiBufferRow(row));
10624 if row == end.row {
10625 line_len = end.column;
10626 }
10627 if line_len == 0 {
10628 trimmed_selections
10629 .push(Point::new(row, 0)..Point::new(row, line_len));
10630 continue;
10631 }
10632 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10633 if row_indent_size.len >= first_indent.len {
10634 trimmed_selections.push(
10635 Point::new(row, first_indent.len)..Point::new(row, line_len),
10636 );
10637 } else {
10638 trimmed_selections.clear();
10639 trimmed_selections.push(start..end);
10640 break;
10641 }
10642 }
10643 }
10644 } else {
10645 trimmed_selections.push(start..end);
10646 }
10647
10648 for trimmed_range in trimmed_selections {
10649 if is_first {
10650 is_first = false;
10651 } else {
10652 text += "\n";
10653 }
10654 let mut len = 0;
10655 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10656 text.push_str(chunk);
10657 len += chunk.len();
10658 }
10659 clipboard_selections.push(ClipboardSelection {
10660 len,
10661 is_entire_line,
10662 first_line_indent: buffer
10663 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10664 .len,
10665 });
10666 }
10667 }
10668 }
10669
10670 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10671 text,
10672 clipboard_selections,
10673 ));
10674 }
10675
10676 pub fn do_paste(
10677 &mut self,
10678 text: &String,
10679 clipboard_selections: Option<Vec<ClipboardSelection>>,
10680 handle_entire_lines: bool,
10681 window: &mut Window,
10682 cx: &mut Context<Self>,
10683 ) {
10684 if self.read_only(cx) {
10685 return;
10686 }
10687
10688 let clipboard_text = Cow::Borrowed(text);
10689
10690 self.transact(window, cx, |this, window, cx| {
10691 if let Some(mut clipboard_selections) = clipboard_selections {
10692 let old_selections = this.selections.all::<usize>(cx);
10693 let all_selections_were_entire_line =
10694 clipboard_selections.iter().all(|s| s.is_entire_line);
10695 let first_selection_indent_column =
10696 clipboard_selections.first().map(|s| s.first_line_indent);
10697 if clipboard_selections.len() != old_selections.len() {
10698 clipboard_selections.drain(..);
10699 }
10700 let cursor_offset = this.selections.last::<usize>(cx).head();
10701 let mut auto_indent_on_paste = true;
10702
10703 this.buffer.update(cx, |buffer, cx| {
10704 let snapshot = buffer.read(cx);
10705 auto_indent_on_paste = snapshot
10706 .language_settings_at(cursor_offset, cx)
10707 .auto_indent_on_paste;
10708
10709 let mut start_offset = 0;
10710 let mut edits = Vec::new();
10711 let mut original_indent_columns = Vec::new();
10712 for (ix, selection) in old_selections.iter().enumerate() {
10713 let to_insert;
10714 let entire_line;
10715 let original_indent_column;
10716 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10717 let end_offset = start_offset + clipboard_selection.len;
10718 to_insert = &clipboard_text[start_offset..end_offset];
10719 entire_line = clipboard_selection.is_entire_line;
10720 start_offset = end_offset + 1;
10721 original_indent_column = Some(clipboard_selection.first_line_indent);
10722 } else {
10723 to_insert = clipboard_text.as_str();
10724 entire_line = all_selections_were_entire_line;
10725 original_indent_column = first_selection_indent_column
10726 }
10727
10728 // If the corresponding selection was empty when this slice of the
10729 // clipboard text was written, then the entire line containing the
10730 // selection was copied. If this selection is also currently empty,
10731 // then paste the line before the current line of the buffer.
10732 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10733 let column = selection.start.to_point(&snapshot).column as usize;
10734 let line_start = selection.start - column;
10735 line_start..line_start
10736 } else {
10737 selection.range()
10738 };
10739
10740 edits.push((range, to_insert));
10741 original_indent_columns.push(original_indent_column);
10742 }
10743 drop(snapshot);
10744
10745 buffer.edit(
10746 edits,
10747 if auto_indent_on_paste {
10748 Some(AutoindentMode::Block {
10749 original_indent_columns,
10750 })
10751 } else {
10752 None
10753 },
10754 cx,
10755 );
10756 });
10757
10758 let selections = this.selections.all::<usize>(cx);
10759 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10760 s.select(selections)
10761 });
10762 } else {
10763 this.insert(&clipboard_text, window, cx);
10764 }
10765 });
10766 }
10767
10768 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10769 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10770 if let Some(item) = cx.read_from_clipboard() {
10771 let entries = item.entries();
10772
10773 match entries.first() {
10774 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10775 // of all the pasted entries.
10776 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10777 .do_paste(
10778 clipboard_string.text(),
10779 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10780 true,
10781 window,
10782 cx,
10783 ),
10784 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10785 }
10786 }
10787 }
10788
10789 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10790 if self.read_only(cx) {
10791 return;
10792 }
10793
10794 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10795
10796 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10797 if let Some((selections, _)) =
10798 self.selection_history.transaction(transaction_id).cloned()
10799 {
10800 self.change_selections(None, window, cx, |s| {
10801 s.select_anchors(selections.to_vec());
10802 });
10803 } else {
10804 log::error!(
10805 "No entry in selection_history found for undo. \
10806 This may correspond to a bug where undo does not update the selection. \
10807 If this is occurring, please add details to \
10808 https://github.com/zed-industries/zed/issues/22692"
10809 );
10810 }
10811 self.request_autoscroll(Autoscroll::fit(), cx);
10812 self.unmark_text(window, cx);
10813 self.refresh_inline_completion(true, false, window, cx);
10814 cx.emit(EditorEvent::Edited { transaction_id });
10815 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10816 }
10817 }
10818
10819 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10820 if self.read_only(cx) {
10821 return;
10822 }
10823
10824 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10825
10826 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10827 if let Some((_, Some(selections))) =
10828 self.selection_history.transaction(transaction_id).cloned()
10829 {
10830 self.change_selections(None, window, cx, |s| {
10831 s.select_anchors(selections.to_vec());
10832 });
10833 } else {
10834 log::error!(
10835 "No entry in selection_history found for redo. \
10836 This may correspond to a bug where undo does not update the selection. \
10837 If this is occurring, please add details to \
10838 https://github.com/zed-industries/zed/issues/22692"
10839 );
10840 }
10841 self.request_autoscroll(Autoscroll::fit(), cx);
10842 self.unmark_text(window, cx);
10843 self.refresh_inline_completion(true, false, window, cx);
10844 cx.emit(EditorEvent::Edited { transaction_id });
10845 }
10846 }
10847
10848 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10849 self.buffer
10850 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10851 }
10852
10853 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10854 self.buffer
10855 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10856 }
10857
10858 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10859 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10860 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10861 s.move_with(|map, selection| {
10862 let cursor = if selection.is_empty() {
10863 movement::left(map, selection.start)
10864 } else {
10865 selection.start
10866 };
10867 selection.collapse_to(cursor, SelectionGoal::None);
10868 });
10869 })
10870 }
10871
10872 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10873 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10874 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10876 })
10877 }
10878
10879 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10880 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10881 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10882 s.move_with(|map, selection| {
10883 let cursor = if selection.is_empty() {
10884 movement::right(map, selection.end)
10885 } else {
10886 selection.end
10887 };
10888 selection.collapse_to(cursor, SelectionGoal::None)
10889 });
10890 })
10891 }
10892
10893 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10894 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10895 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10896 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10897 })
10898 }
10899
10900 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10901 if self.take_rename(true, window, cx).is_some() {
10902 return;
10903 }
10904
10905 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10906 cx.propagate();
10907 return;
10908 }
10909
10910 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10911
10912 let text_layout_details = &self.text_layout_details(window);
10913 let selection_count = self.selections.count();
10914 let first_selection = self.selections.first_anchor();
10915
10916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10917 s.move_with(|map, selection| {
10918 if !selection.is_empty() {
10919 selection.goal = SelectionGoal::None;
10920 }
10921 let (cursor, goal) = movement::up(
10922 map,
10923 selection.start,
10924 selection.goal,
10925 false,
10926 text_layout_details,
10927 );
10928 selection.collapse_to(cursor, goal);
10929 });
10930 });
10931
10932 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10933 {
10934 cx.propagate();
10935 }
10936 }
10937
10938 pub fn move_up_by_lines(
10939 &mut self,
10940 action: &MoveUpByLines,
10941 window: &mut Window,
10942 cx: &mut Context<Self>,
10943 ) {
10944 if self.take_rename(true, window, cx).is_some() {
10945 return;
10946 }
10947
10948 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10949 cx.propagate();
10950 return;
10951 }
10952
10953 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10954
10955 let text_layout_details = &self.text_layout_details(window);
10956
10957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10958 s.move_with(|map, selection| {
10959 if !selection.is_empty() {
10960 selection.goal = SelectionGoal::None;
10961 }
10962 let (cursor, goal) = movement::up_by_rows(
10963 map,
10964 selection.start,
10965 action.lines,
10966 selection.goal,
10967 false,
10968 text_layout_details,
10969 );
10970 selection.collapse_to(cursor, goal);
10971 });
10972 })
10973 }
10974
10975 pub fn move_down_by_lines(
10976 &mut self,
10977 action: &MoveDownByLines,
10978 window: &mut Window,
10979 cx: &mut Context<Self>,
10980 ) {
10981 if self.take_rename(true, window, cx).is_some() {
10982 return;
10983 }
10984
10985 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10986 cx.propagate();
10987 return;
10988 }
10989
10990 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10991
10992 let text_layout_details = &self.text_layout_details(window);
10993
10994 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10995 s.move_with(|map, selection| {
10996 if !selection.is_empty() {
10997 selection.goal = SelectionGoal::None;
10998 }
10999 let (cursor, goal) = movement::down_by_rows(
11000 map,
11001 selection.start,
11002 action.lines,
11003 selection.goal,
11004 false,
11005 text_layout_details,
11006 );
11007 selection.collapse_to(cursor, goal);
11008 });
11009 })
11010 }
11011
11012 pub fn select_down_by_lines(
11013 &mut self,
11014 action: &SelectDownByLines,
11015 window: &mut Window,
11016 cx: &mut Context<Self>,
11017 ) {
11018 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11019 let text_layout_details = &self.text_layout_details(window);
11020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11021 s.move_heads_with(|map, head, goal| {
11022 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
11023 })
11024 })
11025 }
11026
11027 pub fn select_up_by_lines(
11028 &mut self,
11029 action: &SelectUpByLines,
11030 window: &mut Window,
11031 cx: &mut Context<Self>,
11032 ) {
11033 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11034 let text_layout_details = &self.text_layout_details(window);
11035 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11036 s.move_heads_with(|map, head, goal| {
11037 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
11038 })
11039 })
11040 }
11041
11042 pub fn select_page_up(
11043 &mut self,
11044 _: &SelectPageUp,
11045 window: &mut Window,
11046 cx: &mut Context<Self>,
11047 ) {
11048 let Some(row_count) = self.visible_row_count() else {
11049 return;
11050 };
11051
11052 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11053
11054 let text_layout_details = &self.text_layout_details(window);
11055
11056 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11057 s.move_heads_with(|map, head, goal| {
11058 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
11059 })
11060 })
11061 }
11062
11063 pub fn move_page_up(
11064 &mut self,
11065 action: &MovePageUp,
11066 window: &mut Window,
11067 cx: &mut Context<Self>,
11068 ) {
11069 if self.take_rename(true, window, cx).is_some() {
11070 return;
11071 }
11072
11073 if self
11074 .context_menu
11075 .borrow_mut()
11076 .as_mut()
11077 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11078 .unwrap_or(false)
11079 {
11080 return;
11081 }
11082
11083 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11084 cx.propagate();
11085 return;
11086 }
11087
11088 let Some(row_count) = self.visible_row_count() else {
11089 return;
11090 };
11091
11092 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11093
11094 let autoscroll = if action.center_cursor {
11095 Autoscroll::center()
11096 } else {
11097 Autoscroll::fit()
11098 };
11099
11100 let text_layout_details = &self.text_layout_details(window);
11101
11102 self.change_selections(Some(autoscroll), window, cx, |s| {
11103 s.move_with(|map, selection| {
11104 if !selection.is_empty() {
11105 selection.goal = SelectionGoal::None;
11106 }
11107 let (cursor, goal) = movement::up_by_rows(
11108 map,
11109 selection.end,
11110 row_count,
11111 selection.goal,
11112 false,
11113 text_layout_details,
11114 );
11115 selection.collapse_to(cursor, goal);
11116 });
11117 });
11118 }
11119
11120 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11121 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11122 let text_layout_details = &self.text_layout_details(window);
11123 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11124 s.move_heads_with(|map, head, goal| {
11125 movement::up(map, head, goal, false, text_layout_details)
11126 })
11127 })
11128 }
11129
11130 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11131 self.take_rename(true, window, cx);
11132
11133 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11134 cx.propagate();
11135 return;
11136 }
11137
11138 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11139
11140 let text_layout_details = &self.text_layout_details(window);
11141 let selection_count = self.selections.count();
11142 let first_selection = self.selections.first_anchor();
11143
11144 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11145 s.move_with(|map, selection| {
11146 if !selection.is_empty() {
11147 selection.goal = SelectionGoal::None;
11148 }
11149 let (cursor, goal) = movement::down(
11150 map,
11151 selection.end,
11152 selection.goal,
11153 false,
11154 text_layout_details,
11155 );
11156 selection.collapse_to(cursor, goal);
11157 });
11158 });
11159
11160 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11161 {
11162 cx.propagate();
11163 }
11164 }
11165
11166 pub fn select_page_down(
11167 &mut self,
11168 _: &SelectPageDown,
11169 window: &mut Window,
11170 cx: &mut Context<Self>,
11171 ) {
11172 let Some(row_count) = self.visible_row_count() else {
11173 return;
11174 };
11175
11176 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11177
11178 let text_layout_details = &self.text_layout_details(window);
11179
11180 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11181 s.move_heads_with(|map, head, goal| {
11182 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11183 })
11184 })
11185 }
11186
11187 pub fn move_page_down(
11188 &mut self,
11189 action: &MovePageDown,
11190 window: &mut Window,
11191 cx: &mut Context<Self>,
11192 ) {
11193 if self.take_rename(true, window, cx).is_some() {
11194 return;
11195 }
11196
11197 if self
11198 .context_menu
11199 .borrow_mut()
11200 .as_mut()
11201 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11202 .unwrap_or(false)
11203 {
11204 return;
11205 }
11206
11207 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11208 cx.propagate();
11209 return;
11210 }
11211
11212 let Some(row_count) = self.visible_row_count() else {
11213 return;
11214 };
11215
11216 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11217
11218 let autoscroll = if action.center_cursor {
11219 Autoscroll::center()
11220 } else {
11221 Autoscroll::fit()
11222 };
11223
11224 let text_layout_details = &self.text_layout_details(window);
11225 self.change_selections(Some(autoscroll), window, cx, |s| {
11226 s.move_with(|map, selection| {
11227 if !selection.is_empty() {
11228 selection.goal = SelectionGoal::None;
11229 }
11230 let (cursor, goal) = movement::down_by_rows(
11231 map,
11232 selection.end,
11233 row_count,
11234 selection.goal,
11235 false,
11236 text_layout_details,
11237 );
11238 selection.collapse_to(cursor, goal);
11239 });
11240 });
11241 }
11242
11243 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11244 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11245 let text_layout_details = &self.text_layout_details(window);
11246 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247 s.move_heads_with(|map, head, goal| {
11248 movement::down(map, head, goal, false, text_layout_details)
11249 })
11250 });
11251 }
11252
11253 pub fn context_menu_first(
11254 &mut self,
11255 _: &ContextMenuFirst,
11256 _window: &mut Window,
11257 cx: &mut Context<Self>,
11258 ) {
11259 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11260 context_menu.select_first(self.completion_provider.as_deref(), cx);
11261 }
11262 }
11263
11264 pub fn context_menu_prev(
11265 &mut self,
11266 _: &ContextMenuPrevious,
11267 _window: &mut Window,
11268 cx: &mut Context<Self>,
11269 ) {
11270 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11271 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11272 }
11273 }
11274
11275 pub fn context_menu_next(
11276 &mut self,
11277 _: &ContextMenuNext,
11278 _window: &mut Window,
11279 cx: &mut Context<Self>,
11280 ) {
11281 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11282 context_menu.select_next(self.completion_provider.as_deref(), cx);
11283 }
11284 }
11285
11286 pub fn context_menu_last(
11287 &mut self,
11288 _: &ContextMenuLast,
11289 _window: &mut Window,
11290 cx: &mut Context<Self>,
11291 ) {
11292 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11293 context_menu.select_last(self.completion_provider.as_deref(), cx);
11294 }
11295 }
11296
11297 pub fn move_to_previous_word_start(
11298 &mut self,
11299 _: &MoveToPreviousWordStart,
11300 window: &mut Window,
11301 cx: &mut Context<Self>,
11302 ) {
11303 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11304 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11305 s.move_cursors_with(|map, head, _| {
11306 (
11307 movement::previous_word_start(map, head),
11308 SelectionGoal::None,
11309 )
11310 });
11311 })
11312 }
11313
11314 pub fn move_to_previous_subword_start(
11315 &mut self,
11316 _: &MoveToPreviousSubwordStart,
11317 window: &mut Window,
11318 cx: &mut Context<Self>,
11319 ) {
11320 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11321 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11322 s.move_cursors_with(|map, head, _| {
11323 (
11324 movement::previous_subword_start(map, head),
11325 SelectionGoal::None,
11326 )
11327 });
11328 })
11329 }
11330
11331 pub fn select_to_previous_word_start(
11332 &mut self,
11333 _: &SelectToPreviousWordStart,
11334 window: &mut Window,
11335 cx: &mut Context<Self>,
11336 ) {
11337 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11338 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11339 s.move_heads_with(|map, head, _| {
11340 (
11341 movement::previous_word_start(map, head),
11342 SelectionGoal::None,
11343 )
11344 });
11345 })
11346 }
11347
11348 pub fn select_to_previous_subword_start(
11349 &mut self,
11350 _: &SelectToPreviousSubwordStart,
11351 window: &mut Window,
11352 cx: &mut Context<Self>,
11353 ) {
11354 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11355 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11356 s.move_heads_with(|map, head, _| {
11357 (
11358 movement::previous_subword_start(map, head),
11359 SelectionGoal::None,
11360 )
11361 });
11362 })
11363 }
11364
11365 pub fn delete_to_previous_word_start(
11366 &mut self,
11367 action: &DeleteToPreviousWordStart,
11368 window: &mut Window,
11369 cx: &mut Context<Self>,
11370 ) {
11371 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11372 self.transact(window, cx, |this, window, cx| {
11373 this.select_autoclose_pair(window, cx);
11374 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11375 s.move_with(|map, selection| {
11376 if selection.is_empty() {
11377 let cursor = if action.ignore_newlines {
11378 movement::previous_word_start(map, selection.head())
11379 } else {
11380 movement::previous_word_start_or_newline(map, selection.head())
11381 };
11382 selection.set_head(cursor, SelectionGoal::None);
11383 }
11384 });
11385 });
11386 this.insert("", window, cx);
11387 });
11388 }
11389
11390 pub fn delete_to_previous_subword_start(
11391 &mut self,
11392 _: &DeleteToPreviousSubwordStart,
11393 window: &mut Window,
11394 cx: &mut Context<Self>,
11395 ) {
11396 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11397 self.transact(window, cx, |this, window, cx| {
11398 this.select_autoclose_pair(window, cx);
11399 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11400 s.move_with(|map, selection| {
11401 if selection.is_empty() {
11402 let cursor = movement::previous_subword_start(map, selection.head());
11403 selection.set_head(cursor, SelectionGoal::None);
11404 }
11405 });
11406 });
11407 this.insert("", window, cx);
11408 });
11409 }
11410
11411 pub fn move_to_next_word_end(
11412 &mut self,
11413 _: &MoveToNextWordEnd,
11414 window: &mut Window,
11415 cx: &mut Context<Self>,
11416 ) {
11417 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11418 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11419 s.move_cursors_with(|map, head, _| {
11420 (movement::next_word_end(map, head), SelectionGoal::None)
11421 });
11422 })
11423 }
11424
11425 pub fn move_to_next_subword_end(
11426 &mut self,
11427 _: &MoveToNextSubwordEnd,
11428 window: &mut Window,
11429 cx: &mut Context<Self>,
11430 ) {
11431 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11432 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11433 s.move_cursors_with(|map, head, _| {
11434 (movement::next_subword_end(map, head), SelectionGoal::None)
11435 });
11436 })
11437 }
11438
11439 pub fn select_to_next_word_end(
11440 &mut self,
11441 _: &SelectToNextWordEnd,
11442 window: &mut Window,
11443 cx: &mut Context<Self>,
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 (movement::next_word_end(map, head), SelectionGoal::None)
11449 });
11450 })
11451 }
11452
11453 pub fn select_to_next_subword_end(
11454 &mut self,
11455 _: &SelectToNextSubwordEnd,
11456 window: &mut Window,
11457 cx: &mut Context<Self>,
11458 ) {
11459 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11460 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11461 s.move_heads_with(|map, head, _| {
11462 (movement::next_subword_end(map, head), SelectionGoal::None)
11463 });
11464 })
11465 }
11466
11467 pub fn delete_to_next_word_end(
11468 &mut self,
11469 action: &DeleteToNextWordEnd,
11470 window: &mut Window,
11471 cx: &mut Context<Self>,
11472 ) {
11473 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11474 self.transact(window, cx, |this, window, cx| {
11475 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11476 s.move_with(|map, selection| {
11477 if selection.is_empty() {
11478 let cursor = if action.ignore_newlines {
11479 movement::next_word_end(map, selection.head())
11480 } else {
11481 movement::next_word_end_or_newline(map, selection.head())
11482 };
11483 selection.set_head(cursor, SelectionGoal::None);
11484 }
11485 });
11486 });
11487 this.insert("", window, cx);
11488 });
11489 }
11490
11491 pub fn delete_to_next_subword_end(
11492 &mut self,
11493 _: &DeleteToNextSubwordEnd,
11494 window: &mut Window,
11495 cx: &mut Context<Self>,
11496 ) {
11497 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11498 self.transact(window, cx, |this, window, cx| {
11499 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11500 s.move_with(|map, selection| {
11501 if selection.is_empty() {
11502 let cursor = movement::next_subword_end(map, selection.head());
11503 selection.set_head(cursor, SelectionGoal::None);
11504 }
11505 });
11506 });
11507 this.insert("", window, cx);
11508 });
11509 }
11510
11511 pub fn move_to_beginning_of_line(
11512 &mut self,
11513 action: &MoveToBeginningOfLine,
11514 window: &mut Window,
11515 cx: &mut Context<Self>,
11516 ) {
11517 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11519 s.move_cursors_with(|map, head, _| {
11520 (
11521 movement::indented_line_beginning(
11522 map,
11523 head,
11524 action.stop_at_soft_wraps,
11525 action.stop_at_indent,
11526 ),
11527 SelectionGoal::None,
11528 )
11529 });
11530 })
11531 }
11532
11533 pub fn select_to_beginning_of_line(
11534 &mut self,
11535 action: &SelectToBeginningOfLine,
11536 window: &mut Window,
11537 cx: &mut Context<Self>,
11538 ) {
11539 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11540 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11541 s.move_heads_with(|map, head, _| {
11542 (
11543 movement::indented_line_beginning(
11544 map,
11545 head,
11546 action.stop_at_soft_wraps,
11547 action.stop_at_indent,
11548 ),
11549 SelectionGoal::None,
11550 )
11551 });
11552 });
11553 }
11554
11555 pub fn delete_to_beginning_of_line(
11556 &mut self,
11557 action: &DeleteToBeginningOfLine,
11558 window: &mut Window,
11559 cx: &mut Context<Self>,
11560 ) {
11561 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11562 self.transact(window, cx, |this, window, cx| {
11563 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11564 s.move_with(|_, selection| {
11565 selection.reversed = true;
11566 });
11567 });
11568
11569 this.select_to_beginning_of_line(
11570 &SelectToBeginningOfLine {
11571 stop_at_soft_wraps: false,
11572 stop_at_indent: action.stop_at_indent,
11573 },
11574 window,
11575 cx,
11576 );
11577 this.backspace(&Backspace, window, cx);
11578 });
11579 }
11580
11581 pub fn move_to_end_of_line(
11582 &mut self,
11583 action: &MoveToEndOfLine,
11584 window: &mut Window,
11585 cx: &mut Context<Self>,
11586 ) {
11587 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11588 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11589 s.move_cursors_with(|map, head, _| {
11590 (
11591 movement::line_end(map, head, action.stop_at_soft_wraps),
11592 SelectionGoal::None,
11593 )
11594 });
11595 })
11596 }
11597
11598 pub fn select_to_end_of_line(
11599 &mut self,
11600 action: &SelectToEndOfLine,
11601 window: &mut Window,
11602 cx: &mut Context<Self>,
11603 ) {
11604 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11605 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11606 s.move_heads_with(|map, head, _| {
11607 (
11608 movement::line_end(map, head, action.stop_at_soft_wraps),
11609 SelectionGoal::None,
11610 )
11611 });
11612 })
11613 }
11614
11615 pub fn delete_to_end_of_line(
11616 &mut self,
11617 _: &DeleteToEndOfLine,
11618 window: &mut Window,
11619 cx: &mut Context<Self>,
11620 ) {
11621 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11622 self.transact(window, cx, |this, window, cx| {
11623 this.select_to_end_of_line(
11624 &SelectToEndOfLine {
11625 stop_at_soft_wraps: false,
11626 },
11627 window,
11628 cx,
11629 );
11630 this.delete(&Delete, window, cx);
11631 });
11632 }
11633
11634 pub fn cut_to_end_of_line(
11635 &mut self,
11636 _: &CutToEndOfLine,
11637 window: &mut Window,
11638 cx: &mut Context<Self>,
11639 ) {
11640 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11641 self.transact(window, cx, |this, window, cx| {
11642 this.select_to_end_of_line(
11643 &SelectToEndOfLine {
11644 stop_at_soft_wraps: false,
11645 },
11646 window,
11647 cx,
11648 );
11649 this.cut(&Cut, window, cx);
11650 });
11651 }
11652
11653 pub fn move_to_start_of_paragraph(
11654 &mut self,
11655 _: &MoveToStartOfParagraph,
11656 window: &mut Window,
11657 cx: &mut Context<Self>,
11658 ) {
11659 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11660 cx.propagate();
11661 return;
11662 }
11663 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11664 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11665 s.move_with(|map, selection| {
11666 selection.collapse_to(
11667 movement::start_of_paragraph(map, selection.head(), 1),
11668 SelectionGoal::None,
11669 )
11670 });
11671 })
11672 }
11673
11674 pub fn move_to_end_of_paragraph(
11675 &mut self,
11676 _: &MoveToEndOfParagraph,
11677 window: &mut Window,
11678 cx: &mut Context<Self>,
11679 ) {
11680 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11681 cx.propagate();
11682 return;
11683 }
11684 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11685 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11686 s.move_with(|map, selection| {
11687 selection.collapse_to(
11688 movement::end_of_paragraph(map, selection.head(), 1),
11689 SelectionGoal::None,
11690 )
11691 });
11692 })
11693 }
11694
11695 pub fn select_to_start_of_paragraph(
11696 &mut self,
11697 _: &SelectToStartOfParagraph,
11698 window: &mut Window,
11699 cx: &mut Context<Self>,
11700 ) {
11701 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11702 cx.propagate();
11703 return;
11704 }
11705 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11706 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11707 s.move_heads_with(|map, head, _| {
11708 (
11709 movement::start_of_paragraph(map, head, 1),
11710 SelectionGoal::None,
11711 )
11712 });
11713 })
11714 }
11715
11716 pub fn select_to_end_of_paragraph(
11717 &mut self,
11718 _: &SelectToEndOfParagraph,
11719 window: &mut Window,
11720 cx: &mut Context<Self>,
11721 ) {
11722 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11723 cx.propagate();
11724 return;
11725 }
11726 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11727 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11728 s.move_heads_with(|map, head, _| {
11729 (
11730 movement::end_of_paragraph(map, head, 1),
11731 SelectionGoal::None,
11732 )
11733 });
11734 })
11735 }
11736
11737 pub fn move_to_start_of_excerpt(
11738 &mut self,
11739 _: &MoveToStartOfExcerpt,
11740 window: &mut Window,
11741 cx: &mut Context<Self>,
11742 ) {
11743 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11744 cx.propagate();
11745 return;
11746 }
11747 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11748 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11749 s.move_with(|map, selection| {
11750 selection.collapse_to(
11751 movement::start_of_excerpt(
11752 map,
11753 selection.head(),
11754 workspace::searchable::Direction::Prev,
11755 ),
11756 SelectionGoal::None,
11757 )
11758 });
11759 })
11760 }
11761
11762 pub fn move_to_start_of_next_excerpt(
11763 &mut self,
11764 _: &MoveToStartOfNextExcerpt,
11765 window: &mut Window,
11766 cx: &mut Context<Self>,
11767 ) {
11768 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11769 cx.propagate();
11770 return;
11771 }
11772
11773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11774 s.move_with(|map, selection| {
11775 selection.collapse_to(
11776 movement::start_of_excerpt(
11777 map,
11778 selection.head(),
11779 workspace::searchable::Direction::Next,
11780 ),
11781 SelectionGoal::None,
11782 )
11783 });
11784 })
11785 }
11786
11787 pub fn move_to_end_of_excerpt(
11788 &mut self,
11789 _: &MoveToEndOfExcerpt,
11790 window: &mut Window,
11791 cx: &mut Context<Self>,
11792 ) {
11793 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11794 cx.propagate();
11795 return;
11796 }
11797 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11798 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11799 s.move_with(|map, selection| {
11800 selection.collapse_to(
11801 movement::end_of_excerpt(
11802 map,
11803 selection.head(),
11804 workspace::searchable::Direction::Next,
11805 ),
11806 SelectionGoal::None,
11807 )
11808 });
11809 })
11810 }
11811
11812 pub fn move_to_end_of_previous_excerpt(
11813 &mut self,
11814 _: &MoveToEndOfPreviousExcerpt,
11815 window: &mut Window,
11816 cx: &mut Context<Self>,
11817 ) {
11818 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11819 cx.propagate();
11820 return;
11821 }
11822 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11823 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11824 s.move_with(|map, selection| {
11825 selection.collapse_to(
11826 movement::end_of_excerpt(
11827 map,
11828 selection.head(),
11829 workspace::searchable::Direction::Prev,
11830 ),
11831 SelectionGoal::None,
11832 )
11833 });
11834 })
11835 }
11836
11837 pub fn select_to_start_of_excerpt(
11838 &mut self,
11839 _: &SelectToStartOfExcerpt,
11840 window: &mut Window,
11841 cx: &mut Context<Self>,
11842 ) {
11843 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11844 cx.propagate();
11845 return;
11846 }
11847 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11848 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11849 s.move_heads_with(|map, head, _| {
11850 (
11851 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11852 SelectionGoal::None,
11853 )
11854 });
11855 })
11856 }
11857
11858 pub fn select_to_start_of_next_excerpt(
11859 &mut self,
11860 _: &SelectToStartOfNextExcerpt,
11861 window: &mut Window,
11862 cx: &mut Context<Self>,
11863 ) {
11864 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11865 cx.propagate();
11866 return;
11867 }
11868 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11869 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11870 s.move_heads_with(|map, head, _| {
11871 (
11872 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11873 SelectionGoal::None,
11874 )
11875 });
11876 })
11877 }
11878
11879 pub fn select_to_end_of_excerpt(
11880 &mut self,
11881 _: &SelectToEndOfExcerpt,
11882 window: &mut Window,
11883 cx: &mut Context<Self>,
11884 ) {
11885 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11886 cx.propagate();
11887 return;
11888 }
11889 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11890 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11891 s.move_heads_with(|map, head, _| {
11892 (
11893 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11894 SelectionGoal::None,
11895 )
11896 });
11897 })
11898 }
11899
11900 pub fn select_to_end_of_previous_excerpt(
11901 &mut self,
11902 _: &SelectToEndOfPreviousExcerpt,
11903 window: &mut Window,
11904 cx: &mut Context<Self>,
11905 ) {
11906 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11907 cx.propagate();
11908 return;
11909 }
11910 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11911 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11912 s.move_heads_with(|map, head, _| {
11913 (
11914 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11915 SelectionGoal::None,
11916 )
11917 });
11918 })
11919 }
11920
11921 pub fn move_to_beginning(
11922 &mut self,
11923 _: &MoveToBeginning,
11924 window: &mut Window,
11925 cx: &mut Context<Self>,
11926 ) {
11927 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11928 cx.propagate();
11929 return;
11930 }
11931 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11932 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11933 s.select_ranges(vec![0..0]);
11934 });
11935 }
11936
11937 pub fn select_to_beginning(
11938 &mut self,
11939 _: &SelectToBeginning,
11940 window: &mut Window,
11941 cx: &mut Context<Self>,
11942 ) {
11943 let mut selection = self.selections.last::<Point>(cx);
11944 selection.set_head(Point::zero(), SelectionGoal::None);
11945 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11947 s.select(vec![selection]);
11948 });
11949 }
11950
11951 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11952 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11953 cx.propagate();
11954 return;
11955 }
11956 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11957 let cursor = self.buffer.read(cx).read(cx).len();
11958 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11959 s.select_ranges(vec![cursor..cursor])
11960 });
11961 }
11962
11963 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11964 self.nav_history = nav_history;
11965 }
11966
11967 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11968 self.nav_history.as_ref()
11969 }
11970
11971 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11972 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11973 }
11974
11975 fn push_to_nav_history(
11976 &mut self,
11977 cursor_anchor: Anchor,
11978 new_position: Option<Point>,
11979 is_deactivate: bool,
11980 cx: &mut Context<Self>,
11981 ) {
11982 if let Some(nav_history) = self.nav_history.as_mut() {
11983 let buffer = self.buffer.read(cx).read(cx);
11984 let cursor_position = cursor_anchor.to_point(&buffer);
11985 let scroll_state = self.scroll_manager.anchor();
11986 let scroll_top_row = scroll_state.top_row(&buffer);
11987 drop(buffer);
11988
11989 if let Some(new_position) = new_position {
11990 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11991 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11992 return;
11993 }
11994 }
11995
11996 nav_history.push(
11997 Some(NavigationData {
11998 cursor_anchor,
11999 cursor_position,
12000 scroll_anchor: scroll_state,
12001 scroll_top_row,
12002 }),
12003 cx,
12004 );
12005 cx.emit(EditorEvent::PushedToNavHistory {
12006 anchor: cursor_anchor,
12007 is_deactivate,
12008 })
12009 }
12010 }
12011
12012 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
12013 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12014 let buffer = self.buffer.read(cx).snapshot(cx);
12015 let mut selection = self.selections.first::<usize>(cx);
12016 selection.set_head(buffer.len(), SelectionGoal::None);
12017 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12018 s.select(vec![selection]);
12019 });
12020 }
12021
12022 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
12023 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12024 let end = self.buffer.read(cx).read(cx).len();
12025 self.change_selections(None, window, cx, |s| {
12026 s.select_ranges(vec![0..end]);
12027 });
12028 }
12029
12030 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
12031 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12032 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12033 let mut selections = self.selections.all::<Point>(cx);
12034 let max_point = display_map.buffer_snapshot.max_point();
12035 for selection in &mut selections {
12036 let rows = selection.spanned_rows(true, &display_map);
12037 selection.start = Point::new(rows.start.0, 0);
12038 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
12039 selection.reversed = false;
12040 }
12041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12042 s.select(selections);
12043 });
12044 }
12045
12046 pub fn split_selection_into_lines(
12047 &mut self,
12048 _: &SplitSelectionIntoLines,
12049 window: &mut Window,
12050 cx: &mut Context<Self>,
12051 ) {
12052 let selections = self
12053 .selections
12054 .all::<Point>(cx)
12055 .into_iter()
12056 .map(|selection| selection.start..selection.end)
12057 .collect::<Vec<_>>();
12058 self.unfold_ranges(&selections, true, true, cx);
12059
12060 let mut new_selection_ranges = Vec::new();
12061 {
12062 let buffer = self.buffer.read(cx).read(cx);
12063 for selection in selections {
12064 for row in selection.start.row..selection.end.row {
12065 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12066 new_selection_ranges.push(cursor..cursor);
12067 }
12068
12069 let is_multiline_selection = selection.start.row != selection.end.row;
12070 // Don't insert last one if it's a multi-line selection ending at the start of a line,
12071 // so this action feels more ergonomic when paired with other selection operations
12072 let should_skip_last = is_multiline_selection && selection.end.column == 0;
12073 if !should_skip_last {
12074 new_selection_ranges.push(selection.end..selection.end);
12075 }
12076 }
12077 }
12078 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12079 s.select_ranges(new_selection_ranges);
12080 });
12081 }
12082
12083 pub fn add_selection_above(
12084 &mut self,
12085 _: &AddSelectionAbove,
12086 window: &mut Window,
12087 cx: &mut Context<Self>,
12088 ) {
12089 self.add_selection(true, window, cx);
12090 }
12091
12092 pub fn add_selection_below(
12093 &mut self,
12094 _: &AddSelectionBelow,
12095 window: &mut Window,
12096 cx: &mut Context<Self>,
12097 ) {
12098 self.add_selection(false, window, cx);
12099 }
12100
12101 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12102 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12103
12104 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12105 let mut selections = self.selections.all::<Point>(cx);
12106 let text_layout_details = self.text_layout_details(window);
12107 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12108 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12109 let range = oldest_selection.display_range(&display_map).sorted();
12110
12111 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12112 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12113 let positions = start_x.min(end_x)..start_x.max(end_x);
12114
12115 selections.clear();
12116 let mut stack = Vec::new();
12117 for row in range.start.row().0..=range.end.row().0 {
12118 if let Some(selection) = self.selections.build_columnar_selection(
12119 &display_map,
12120 DisplayRow(row),
12121 &positions,
12122 oldest_selection.reversed,
12123 &text_layout_details,
12124 ) {
12125 stack.push(selection.id);
12126 selections.push(selection);
12127 }
12128 }
12129
12130 if above {
12131 stack.reverse();
12132 }
12133
12134 AddSelectionsState { above, stack }
12135 });
12136
12137 let last_added_selection = *state.stack.last().unwrap();
12138 let mut new_selections = Vec::new();
12139 if above == state.above {
12140 let end_row = if above {
12141 DisplayRow(0)
12142 } else {
12143 display_map.max_point().row()
12144 };
12145
12146 'outer: for selection in selections {
12147 if selection.id == last_added_selection {
12148 let range = selection.display_range(&display_map).sorted();
12149 debug_assert_eq!(range.start.row(), range.end.row());
12150 let mut row = range.start.row();
12151 let positions =
12152 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12153 px(start)..px(end)
12154 } else {
12155 let start_x =
12156 display_map.x_for_display_point(range.start, &text_layout_details);
12157 let end_x =
12158 display_map.x_for_display_point(range.end, &text_layout_details);
12159 start_x.min(end_x)..start_x.max(end_x)
12160 };
12161
12162 while row != end_row {
12163 if above {
12164 row.0 -= 1;
12165 } else {
12166 row.0 += 1;
12167 }
12168
12169 if let Some(new_selection) = self.selections.build_columnar_selection(
12170 &display_map,
12171 row,
12172 &positions,
12173 selection.reversed,
12174 &text_layout_details,
12175 ) {
12176 state.stack.push(new_selection.id);
12177 if above {
12178 new_selections.push(new_selection);
12179 new_selections.push(selection);
12180 } else {
12181 new_selections.push(selection);
12182 new_selections.push(new_selection);
12183 }
12184
12185 continue 'outer;
12186 }
12187 }
12188 }
12189
12190 new_selections.push(selection);
12191 }
12192 } else {
12193 new_selections = selections;
12194 new_selections.retain(|s| s.id != last_added_selection);
12195 state.stack.pop();
12196 }
12197
12198 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12199 s.select(new_selections);
12200 });
12201 if state.stack.len() > 1 {
12202 self.add_selections_state = Some(state);
12203 }
12204 }
12205
12206 fn select_match_ranges(
12207 &mut self,
12208 range: Range<usize>,
12209 reversed: bool,
12210 replace_newest: bool,
12211 auto_scroll: Option<Autoscroll>,
12212 window: &mut Window,
12213 cx: &mut Context<Editor>,
12214 ) {
12215 self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12216 self.change_selections(auto_scroll, window, cx, |s| {
12217 if replace_newest {
12218 s.delete(s.newest_anchor().id);
12219 }
12220 if reversed {
12221 s.insert_range(range.end..range.start);
12222 } else {
12223 s.insert_range(range);
12224 }
12225 });
12226 }
12227
12228 pub fn select_next_match_internal(
12229 &mut self,
12230 display_map: &DisplaySnapshot,
12231 replace_newest: bool,
12232 autoscroll: Option<Autoscroll>,
12233 window: &mut Window,
12234 cx: &mut Context<Self>,
12235 ) -> Result<()> {
12236 let buffer = &display_map.buffer_snapshot;
12237 let mut selections = self.selections.all::<usize>(cx);
12238 if let Some(mut select_next_state) = self.select_next_state.take() {
12239 let query = &select_next_state.query;
12240 if !select_next_state.done {
12241 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12242 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12243 let mut next_selected_range = None;
12244
12245 let bytes_after_last_selection =
12246 buffer.bytes_in_range(last_selection.end..buffer.len());
12247 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12248 let query_matches = query
12249 .stream_find_iter(bytes_after_last_selection)
12250 .map(|result| (last_selection.end, result))
12251 .chain(
12252 query
12253 .stream_find_iter(bytes_before_first_selection)
12254 .map(|result| (0, result)),
12255 );
12256
12257 for (start_offset, query_match) in query_matches {
12258 let query_match = query_match.unwrap(); // can only fail due to I/O
12259 let offset_range =
12260 start_offset + query_match.start()..start_offset + query_match.end();
12261 let display_range = offset_range.start.to_display_point(display_map)
12262 ..offset_range.end.to_display_point(display_map);
12263
12264 if !select_next_state.wordwise
12265 || (!movement::is_inside_word(display_map, display_range.start)
12266 && !movement::is_inside_word(display_map, display_range.end))
12267 {
12268 // TODO: This is n^2, because we might check all the selections
12269 if !selections
12270 .iter()
12271 .any(|selection| selection.range().overlaps(&offset_range))
12272 {
12273 next_selected_range = Some(offset_range);
12274 break;
12275 }
12276 }
12277 }
12278
12279 if let Some(next_selected_range) = next_selected_range {
12280 self.select_match_ranges(
12281 next_selected_range,
12282 last_selection.reversed,
12283 replace_newest,
12284 autoscroll,
12285 window,
12286 cx,
12287 );
12288 } else {
12289 select_next_state.done = true;
12290 }
12291 }
12292
12293 self.select_next_state = Some(select_next_state);
12294 } else {
12295 let mut only_carets = true;
12296 let mut same_text_selected = true;
12297 let mut selected_text = None;
12298
12299 let mut selections_iter = selections.iter().peekable();
12300 while let Some(selection) = selections_iter.next() {
12301 if selection.start != selection.end {
12302 only_carets = false;
12303 }
12304
12305 if same_text_selected {
12306 if selected_text.is_none() {
12307 selected_text =
12308 Some(buffer.text_for_range(selection.range()).collect::<String>());
12309 }
12310
12311 if let Some(next_selection) = selections_iter.peek() {
12312 if next_selection.range().len() == selection.range().len() {
12313 let next_selected_text = buffer
12314 .text_for_range(next_selection.range())
12315 .collect::<String>();
12316 if Some(next_selected_text) != selected_text {
12317 same_text_selected = false;
12318 selected_text = None;
12319 }
12320 } else {
12321 same_text_selected = false;
12322 selected_text = None;
12323 }
12324 }
12325 }
12326 }
12327
12328 if only_carets {
12329 for selection in &mut selections {
12330 let word_range = movement::surrounding_word(
12331 display_map,
12332 selection.start.to_display_point(display_map),
12333 );
12334 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12335 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12336 selection.goal = SelectionGoal::None;
12337 selection.reversed = false;
12338 self.select_match_ranges(
12339 selection.start..selection.end,
12340 selection.reversed,
12341 replace_newest,
12342 autoscroll,
12343 window,
12344 cx,
12345 );
12346 }
12347
12348 if selections.len() == 1 {
12349 let selection = selections
12350 .last()
12351 .expect("ensured that there's only one selection");
12352 let query = buffer
12353 .text_for_range(selection.start..selection.end)
12354 .collect::<String>();
12355 let is_empty = query.is_empty();
12356 let select_state = SelectNextState {
12357 query: AhoCorasick::new(&[query])?,
12358 wordwise: true,
12359 done: is_empty,
12360 };
12361 self.select_next_state = Some(select_state);
12362 } else {
12363 self.select_next_state = None;
12364 }
12365 } else if let Some(selected_text) = selected_text {
12366 self.select_next_state = Some(SelectNextState {
12367 query: AhoCorasick::new(&[selected_text])?,
12368 wordwise: false,
12369 done: false,
12370 });
12371 self.select_next_match_internal(
12372 display_map,
12373 replace_newest,
12374 autoscroll,
12375 window,
12376 cx,
12377 )?;
12378 }
12379 }
12380 Ok(())
12381 }
12382
12383 pub fn select_all_matches(
12384 &mut self,
12385 _action: &SelectAllMatches,
12386 window: &mut Window,
12387 cx: &mut Context<Self>,
12388 ) -> Result<()> {
12389 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12390
12391 self.push_to_selection_history();
12392 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12393
12394 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12395 let Some(select_next_state) = self.select_next_state.as_mut() else {
12396 return Ok(());
12397 };
12398 if select_next_state.done {
12399 return Ok(());
12400 }
12401
12402 let mut new_selections = Vec::new();
12403
12404 let reversed = self.selections.oldest::<usize>(cx).reversed;
12405 let buffer = &display_map.buffer_snapshot;
12406 let query_matches = select_next_state
12407 .query
12408 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12409
12410 for query_match in query_matches.into_iter() {
12411 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12412 let offset_range = if reversed {
12413 query_match.end()..query_match.start()
12414 } else {
12415 query_match.start()..query_match.end()
12416 };
12417 let display_range = offset_range.start.to_display_point(&display_map)
12418 ..offset_range.end.to_display_point(&display_map);
12419
12420 if !select_next_state.wordwise
12421 || (!movement::is_inside_word(&display_map, display_range.start)
12422 && !movement::is_inside_word(&display_map, display_range.end))
12423 {
12424 new_selections.push(offset_range.start..offset_range.end);
12425 }
12426 }
12427
12428 select_next_state.done = true;
12429 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12430 self.change_selections(None, window, cx, |selections| {
12431 selections.select_ranges(new_selections)
12432 });
12433
12434 Ok(())
12435 }
12436
12437 pub fn select_next(
12438 &mut self,
12439 action: &SelectNext,
12440 window: &mut Window,
12441 cx: &mut Context<Self>,
12442 ) -> Result<()> {
12443 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12444 self.push_to_selection_history();
12445 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12446 self.select_next_match_internal(
12447 &display_map,
12448 action.replace_newest,
12449 Some(Autoscroll::newest()),
12450 window,
12451 cx,
12452 )?;
12453 Ok(())
12454 }
12455
12456 pub fn select_previous(
12457 &mut self,
12458 action: &SelectPrevious,
12459 window: &mut Window,
12460 cx: &mut Context<Self>,
12461 ) -> Result<()> {
12462 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12463 self.push_to_selection_history();
12464 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12465 let buffer = &display_map.buffer_snapshot;
12466 let mut selections = self.selections.all::<usize>(cx);
12467 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12468 let query = &select_prev_state.query;
12469 if !select_prev_state.done {
12470 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12471 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12472 let mut next_selected_range = None;
12473 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12474 let bytes_before_last_selection =
12475 buffer.reversed_bytes_in_range(0..last_selection.start);
12476 let bytes_after_first_selection =
12477 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12478 let query_matches = query
12479 .stream_find_iter(bytes_before_last_selection)
12480 .map(|result| (last_selection.start, result))
12481 .chain(
12482 query
12483 .stream_find_iter(bytes_after_first_selection)
12484 .map(|result| (buffer.len(), result)),
12485 );
12486 for (end_offset, query_match) in query_matches {
12487 let query_match = query_match.unwrap(); // can only fail due to I/O
12488 let offset_range =
12489 end_offset - query_match.end()..end_offset - query_match.start();
12490 let display_range = offset_range.start.to_display_point(&display_map)
12491 ..offset_range.end.to_display_point(&display_map);
12492
12493 if !select_prev_state.wordwise
12494 || (!movement::is_inside_word(&display_map, display_range.start)
12495 && !movement::is_inside_word(&display_map, display_range.end))
12496 {
12497 next_selected_range = Some(offset_range);
12498 break;
12499 }
12500 }
12501
12502 if let Some(next_selected_range) = next_selected_range {
12503 self.select_match_ranges(
12504 next_selected_range,
12505 last_selection.reversed,
12506 action.replace_newest,
12507 Some(Autoscroll::newest()),
12508 window,
12509 cx,
12510 );
12511 } else {
12512 select_prev_state.done = true;
12513 }
12514 }
12515
12516 self.select_prev_state = Some(select_prev_state);
12517 } else {
12518 let mut only_carets = true;
12519 let mut same_text_selected = true;
12520 let mut selected_text = None;
12521
12522 let mut selections_iter = selections.iter().peekable();
12523 while let Some(selection) = selections_iter.next() {
12524 if selection.start != selection.end {
12525 only_carets = false;
12526 }
12527
12528 if same_text_selected {
12529 if selected_text.is_none() {
12530 selected_text =
12531 Some(buffer.text_for_range(selection.range()).collect::<String>());
12532 }
12533
12534 if let Some(next_selection) = selections_iter.peek() {
12535 if next_selection.range().len() == selection.range().len() {
12536 let next_selected_text = buffer
12537 .text_for_range(next_selection.range())
12538 .collect::<String>();
12539 if Some(next_selected_text) != selected_text {
12540 same_text_selected = false;
12541 selected_text = None;
12542 }
12543 } else {
12544 same_text_selected = false;
12545 selected_text = None;
12546 }
12547 }
12548 }
12549 }
12550
12551 if only_carets {
12552 for selection in &mut selections {
12553 let word_range = movement::surrounding_word(
12554 &display_map,
12555 selection.start.to_display_point(&display_map),
12556 );
12557 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12558 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12559 selection.goal = SelectionGoal::None;
12560 selection.reversed = false;
12561 self.select_match_ranges(
12562 selection.start..selection.end,
12563 selection.reversed,
12564 action.replace_newest,
12565 Some(Autoscroll::newest()),
12566 window,
12567 cx,
12568 );
12569 }
12570 if selections.len() == 1 {
12571 let selection = selections
12572 .last()
12573 .expect("ensured that there's only one selection");
12574 let query = buffer
12575 .text_for_range(selection.start..selection.end)
12576 .collect::<String>();
12577 let is_empty = query.is_empty();
12578 let select_state = SelectNextState {
12579 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12580 wordwise: true,
12581 done: is_empty,
12582 };
12583 self.select_prev_state = Some(select_state);
12584 } else {
12585 self.select_prev_state = None;
12586 }
12587 } else if let Some(selected_text) = selected_text {
12588 self.select_prev_state = Some(SelectNextState {
12589 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12590 wordwise: false,
12591 done: false,
12592 });
12593 self.select_previous(action, window, cx)?;
12594 }
12595 }
12596 Ok(())
12597 }
12598
12599 pub fn find_next_match(
12600 &mut self,
12601 _: &FindNextMatch,
12602 window: &mut Window,
12603 cx: &mut Context<Self>,
12604 ) -> Result<()> {
12605 let selections = self.selections.disjoint_anchors();
12606 match selections.first() {
12607 Some(first) if selections.len() >= 2 => {
12608 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12609 s.select_ranges([first.range()]);
12610 });
12611 }
12612 _ => self.select_next(
12613 &SelectNext {
12614 replace_newest: true,
12615 },
12616 window,
12617 cx,
12618 )?,
12619 }
12620 Ok(())
12621 }
12622
12623 pub fn find_previous_match(
12624 &mut self,
12625 _: &FindPreviousMatch,
12626 window: &mut Window,
12627 cx: &mut Context<Self>,
12628 ) -> Result<()> {
12629 let selections = self.selections.disjoint_anchors();
12630 match selections.last() {
12631 Some(last) if selections.len() >= 2 => {
12632 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12633 s.select_ranges([last.range()]);
12634 });
12635 }
12636 _ => self.select_previous(
12637 &SelectPrevious {
12638 replace_newest: true,
12639 },
12640 window,
12641 cx,
12642 )?,
12643 }
12644 Ok(())
12645 }
12646
12647 pub fn toggle_comments(
12648 &mut self,
12649 action: &ToggleComments,
12650 window: &mut Window,
12651 cx: &mut Context<Self>,
12652 ) {
12653 if self.read_only(cx) {
12654 return;
12655 }
12656 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12657 let text_layout_details = &self.text_layout_details(window);
12658 self.transact(window, cx, |this, window, cx| {
12659 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12660 let mut edits = Vec::new();
12661 let mut selection_edit_ranges = Vec::new();
12662 let mut last_toggled_row = None;
12663 let snapshot = this.buffer.read(cx).read(cx);
12664 let empty_str: Arc<str> = Arc::default();
12665 let mut suffixes_inserted = Vec::new();
12666 let ignore_indent = action.ignore_indent;
12667
12668 fn comment_prefix_range(
12669 snapshot: &MultiBufferSnapshot,
12670 row: MultiBufferRow,
12671 comment_prefix: &str,
12672 comment_prefix_whitespace: &str,
12673 ignore_indent: bool,
12674 ) -> Range<Point> {
12675 let indent_size = if ignore_indent {
12676 0
12677 } else {
12678 snapshot.indent_size_for_line(row).len
12679 };
12680
12681 let start = Point::new(row.0, indent_size);
12682
12683 let mut line_bytes = snapshot
12684 .bytes_in_range(start..snapshot.max_point())
12685 .flatten()
12686 .copied();
12687
12688 // If this line currently begins with the line comment prefix, then record
12689 // the range containing the prefix.
12690 if line_bytes
12691 .by_ref()
12692 .take(comment_prefix.len())
12693 .eq(comment_prefix.bytes())
12694 {
12695 // Include any whitespace that matches the comment prefix.
12696 let matching_whitespace_len = line_bytes
12697 .zip(comment_prefix_whitespace.bytes())
12698 .take_while(|(a, b)| a == b)
12699 .count() as u32;
12700 let end = Point::new(
12701 start.row,
12702 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12703 );
12704 start..end
12705 } else {
12706 start..start
12707 }
12708 }
12709
12710 fn comment_suffix_range(
12711 snapshot: &MultiBufferSnapshot,
12712 row: MultiBufferRow,
12713 comment_suffix: &str,
12714 comment_suffix_has_leading_space: bool,
12715 ) -> Range<Point> {
12716 let end = Point::new(row.0, snapshot.line_len(row));
12717 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12718
12719 let mut line_end_bytes = snapshot
12720 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12721 .flatten()
12722 .copied();
12723
12724 let leading_space_len = if suffix_start_column > 0
12725 && line_end_bytes.next() == Some(b' ')
12726 && comment_suffix_has_leading_space
12727 {
12728 1
12729 } else {
12730 0
12731 };
12732
12733 // If this line currently begins with the line comment prefix, then record
12734 // the range containing the prefix.
12735 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12736 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12737 start..end
12738 } else {
12739 end..end
12740 }
12741 }
12742
12743 // TODO: Handle selections that cross excerpts
12744 for selection in &mut selections {
12745 let start_column = snapshot
12746 .indent_size_for_line(MultiBufferRow(selection.start.row))
12747 .len;
12748 let language = if let Some(language) =
12749 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12750 {
12751 language
12752 } else {
12753 continue;
12754 };
12755
12756 selection_edit_ranges.clear();
12757
12758 // If multiple selections contain a given row, avoid processing that
12759 // row more than once.
12760 let mut start_row = MultiBufferRow(selection.start.row);
12761 if last_toggled_row == Some(start_row) {
12762 start_row = start_row.next_row();
12763 }
12764 let end_row =
12765 if selection.end.row > selection.start.row && selection.end.column == 0 {
12766 MultiBufferRow(selection.end.row - 1)
12767 } else {
12768 MultiBufferRow(selection.end.row)
12769 };
12770 last_toggled_row = Some(end_row);
12771
12772 if start_row > end_row {
12773 continue;
12774 }
12775
12776 // If the language has line comments, toggle those.
12777 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12778
12779 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12780 if ignore_indent {
12781 full_comment_prefixes = full_comment_prefixes
12782 .into_iter()
12783 .map(|s| Arc::from(s.trim_end()))
12784 .collect();
12785 }
12786
12787 if !full_comment_prefixes.is_empty() {
12788 let first_prefix = full_comment_prefixes
12789 .first()
12790 .expect("prefixes is non-empty");
12791 let prefix_trimmed_lengths = full_comment_prefixes
12792 .iter()
12793 .map(|p| p.trim_end_matches(' ').len())
12794 .collect::<SmallVec<[usize; 4]>>();
12795
12796 let mut all_selection_lines_are_comments = true;
12797
12798 for row in start_row.0..=end_row.0 {
12799 let row = MultiBufferRow(row);
12800 if start_row < end_row && snapshot.is_line_blank(row) {
12801 continue;
12802 }
12803
12804 let prefix_range = full_comment_prefixes
12805 .iter()
12806 .zip(prefix_trimmed_lengths.iter().copied())
12807 .map(|(prefix, trimmed_prefix_len)| {
12808 comment_prefix_range(
12809 snapshot.deref(),
12810 row,
12811 &prefix[..trimmed_prefix_len],
12812 &prefix[trimmed_prefix_len..],
12813 ignore_indent,
12814 )
12815 })
12816 .max_by_key(|range| range.end.column - range.start.column)
12817 .expect("prefixes is non-empty");
12818
12819 if prefix_range.is_empty() {
12820 all_selection_lines_are_comments = false;
12821 }
12822
12823 selection_edit_ranges.push(prefix_range);
12824 }
12825
12826 if all_selection_lines_are_comments {
12827 edits.extend(
12828 selection_edit_ranges
12829 .iter()
12830 .cloned()
12831 .map(|range| (range, empty_str.clone())),
12832 );
12833 } else {
12834 let min_column = selection_edit_ranges
12835 .iter()
12836 .map(|range| range.start.column)
12837 .min()
12838 .unwrap_or(0);
12839 edits.extend(selection_edit_ranges.iter().map(|range| {
12840 let position = Point::new(range.start.row, min_column);
12841 (position..position, first_prefix.clone())
12842 }));
12843 }
12844 } else if let Some((full_comment_prefix, comment_suffix)) =
12845 language.block_comment_delimiters()
12846 {
12847 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12848 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12849 let prefix_range = comment_prefix_range(
12850 snapshot.deref(),
12851 start_row,
12852 comment_prefix,
12853 comment_prefix_whitespace,
12854 ignore_indent,
12855 );
12856 let suffix_range = comment_suffix_range(
12857 snapshot.deref(),
12858 end_row,
12859 comment_suffix.trim_start_matches(' '),
12860 comment_suffix.starts_with(' '),
12861 );
12862
12863 if prefix_range.is_empty() || suffix_range.is_empty() {
12864 edits.push((
12865 prefix_range.start..prefix_range.start,
12866 full_comment_prefix.clone(),
12867 ));
12868 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12869 suffixes_inserted.push((end_row, comment_suffix.len()));
12870 } else {
12871 edits.push((prefix_range, empty_str.clone()));
12872 edits.push((suffix_range, empty_str.clone()));
12873 }
12874 } else {
12875 continue;
12876 }
12877 }
12878
12879 drop(snapshot);
12880 this.buffer.update(cx, |buffer, cx| {
12881 buffer.edit(edits, None, cx);
12882 });
12883
12884 // Adjust selections so that they end before any comment suffixes that
12885 // were inserted.
12886 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12887 let mut selections = this.selections.all::<Point>(cx);
12888 let snapshot = this.buffer.read(cx).read(cx);
12889 for selection in &mut selections {
12890 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12891 match row.cmp(&MultiBufferRow(selection.end.row)) {
12892 Ordering::Less => {
12893 suffixes_inserted.next();
12894 continue;
12895 }
12896 Ordering::Greater => break,
12897 Ordering::Equal => {
12898 if selection.end.column == snapshot.line_len(row) {
12899 if selection.is_empty() {
12900 selection.start.column -= suffix_len as u32;
12901 }
12902 selection.end.column -= suffix_len as u32;
12903 }
12904 break;
12905 }
12906 }
12907 }
12908 }
12909
12910 drop(snapshot);
12911 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12912 s.select(selections)
12913 });
12914
12915 let selections = this.selections.all::<Point>(cx);
12916 let selections_on_single_row = selections.windows(2).all(|selections| {
12917 selections[0].start.row == selections[1].start.row
12918 && selections[0].end.row == selections[1].end.row
12919 && selections[0].start.row == selections[0].end.row
12920 });
12921 let selections_selecting = selections
12922 .iter()
12923 .any(|selection| selection.start != selection.end);
12924 let advance_downwards = action.advance_downwards
12925 && selections_on_single_row
12926 && !selections_selecting
12927 && !matches!(this.mode, EditorMode::SingleLine { .. });
12928
12929 if advance_downwards {
12930 let snapshot = this.buffer.read(cx).snapshot(cx);
12931
12932 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12933 s.move_cursors_with(|display_snapshot, display_point, _| {
12934 let mut point = display_point.to_point(display_snapshot);
12935 point.row += 1;
12936 point = snapshot.clip_point(point, Bias::Left);
12937 let display_point = point.to_display_point(display_snapshot);
12938 let goal = SelectionGoal::HorizontalPosition(
12939 display_snapshot
12940 .x_for_display_point(display_point, text_layout_details)
12941 .into(),
12942 );
12943 (display_point, goal)
12944 })
12945 });
12946 }
12947 });
12948 }
12949
12950 pub fn select_enclosing_symbol(
12951 &mut self,
12952 _: &SelectEnclosingSymbol,
12953 window: &mut Window,
12954 cx: &mut Context<Self>,
12955 ) {
12956 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12957
12958 let buffer = self.buffer.read(cx).snapshot(cx);
12959 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12960
12961 fn update_selection(
12962 selection: &Selection<usize>,
12963 buffer_snap: &MultiBufferSnapshot,
12964 ) -> Option<Selection<usize>> {
12965 let cursor = selection.head();
12966 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12967 for symbol in symbols.iter().rev() {
12968 let start = symbol.range.start.to_offset(buffer_snap);
12969 let end = symbol.range.end.to_offset(buffer_snap);
12970 let new_range = start..end;
12971 if start < selection.start || end > selection.end {
12972 return Some(Selection {
12973 id: selection.id,
12974 start: new_range.start,
12975 end: new_range.end,
12976 goal: SelectionGoal::None,
12977 reversed: selection.reversed,
12978 });
12979 }
12980 }
12981 None
12982 }
12983
12984 let mut selected_larger_symbol = false;
12985 let new_selections = old_selections
12986 .iter()
12987 .map(|selection| match update_selection(selection, &buffer) {
12988 Some(new_selection) => {
12989 if new_selection.range() != selection.range() {
12990 selected_larger_symbol = true;
12991 }
12992 new_selection
12993 }
12994 None => selection.clone(),
12995 })
12996 .collect::<Vec<_>>();
12997
12998 if selected_larger_symbol {
12999 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13000 s.select(new_selections);
13001 });
13002 }
13003 }
13004
13005 pub fn select_larger_syntax_node(
13006 &mut self,
13007 _: &SelectLargerSyntaxNode,
13008 window: &mut Window,
13009 cx: &mut Context<Self>,
13010 ) {
13011 let Some(visible_row_count) = self.visible_row_count() else {
13012 return;
13013 };
13014 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
13015 if old_selections.is_empty() {
13016 return;
13017 }
13018
13019 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13020
13021 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13022 let buffer = self.buffer.read(cx).snapshot(cx);
13023
13024 let mut selected_larger_node = false;
13025 let mut new_selections = old_selections
13026 .iter()
13027 .map(|selection| {
13028 let old_range = selection.start..selection.end;
13029
13030 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
13031 // manually select word at selection
13032 if ["string_content", "inline"].contains(&node.kind()) {
13033 let word_range = {
13034 let display_point = buffer
13035 .offset_to_point(old_range.start)
13036 .to_display_point(&display_map);
13037 let Range { start, end } =
13038 movement::surrounding_word(&display_map, display_point);
13039 start.to_point(&display_map).to_offset(&buffer)
13040 ..end.to_point(&display_map).to_offset(&buffer)
13041 };
13042 // ignore if word is already selected
13043 if !word_range.is_empty() && old_range != word_range {
13044 let last_word_range = {
13045 let display_point = buffer
13046 .offset_to_point(old_range.end)
13047 .to_display_point(&display_map);
13048 let Range { start, end } =
13049 movement::surrounding_word(&display_map, display_point);
13050 start.to_point(&display_map).to_offset(&buffer)
13051 ..end.to_point(&display_map).to_offset(&buffer)
13052 };
13053 // only select word if start and end point belongs to same word
13054 if word_range == last_word_range {
13055 selected_larger_node = true;
13056 return Selection {
13057 id: selection.id,
13058 start: word_range.start,
13059 end: word_range.end,
13060 goal: SelectionGoal::None,
13061 reversed: selection.reversed,
13062 };
13063 }
13064 }
13065 }
13066 }
13067
13068 let mut new_range = old_range.clone();
13069 while let Some((_node, containing_range)) =
13070 buffer.syntax_ancestor(new_range.clone())
13071 {
13072 new_range = match containing_range {
13073 MultiOrSingleBufferOffsetRange::Single(_) => break,
13074 MultiOrSingleBufferOffsetRange::Multi(range) => range,
13075 };
13076 if !display_map.intersects_fold(new_range.start)
13077 && !display_map.intersects_fold(new_range.end)
13078 {
13079 break;
13080 }
13081 }
13082
13083 selected_larger_node |= new_range != old_range;
13084 Selection {
13085 id: selection.id,
13086 start: new_range.start,
13087 end: new_range.end,
13088 goal: SelectionGoal::None,
13089 reversed: selection.reversed,
13090 }
13091 })
13092 .collect::<Vec<_>>();
13093
13094 if !selected_larger_node {
13095 return; // don't put this call in the history
13096 }
13097
13098 // scroll based on transformation done to the last selection created by the user
13099 let (last_old, last_new) = old_selections
13100 .last()
13101 .zip(new_selections.last().cloned())
13102 .expect("old_selections isn't empty");
13103
13104 // revert selection
13105 let is_selection_reversed = {
13106 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13107 new_selections.last_mut().expect("checked above").reversed =
13108 should_newest_selection_be_reversed;
13109 should_newest_selection_be_reversed
13110 };
13111
13112 if selected_larger_node {
13113 self.select_syntax_node_history.disable_clearing = true;
13114 self.change_selections(None, window, cx, |s| {
13115 s.select(new_selections.clone());
13116 });
13117 self.select_syntax_node_history.disable_clearing = false;
13118 }
13119
13120 let start_row = last_new.start.to_display_point(&display_map).row().0;
13121 let end_row = last_new.end.to_display_point(&display_map).row().0;
13122 let selection_height = end_row - start_row + 1;
13123 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13124
13125 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13126 let scroll_behavior = if fits_on_the_screen {
13127 self.request_autoscroll(Autoscroll::fit(), cx);
13128 SelectSyntaxNodeScrollBehavior::FitSelection
13129 } else if is_selection_reversed {
13130 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13131 SelectSyntaxNodeScrollBehavior::CursorTop
13132 } else {
13133 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13134 SelectSyntaxNodeScrollBehavior::CursorBottom
13135 };
13136
13137 self.select_syntax_node_history.push((
13138 old_selections,
13139 scroll_behavior,
13140 is_selection_reversed,
13141 ));
13142 }
13143
13144 pub fn select_smaller_syntax_node(
13145 &mut self,
13146 _: &SelectSmallerSyntaxNode,
13147 window: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) {
13150 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13151
13152 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13153 self.select_syntax_node_history.pop()
13154 {
13155 if let Some(selection) = selections.last_mut() {
13156 selection.reversed = is_selection_reversed;
13157 }
13158
13159 self.select_syntax_node_history.disable_clearing = true;
13160 self.change_selections(None, window, cx, |s| {
13161 s.select(selections.to_vec());
13162 });
13163 self.select_syntax_node_history.disable_clearing = false;
13164
13165 match scroll_behavior {
13166 SelectSyntaxNodeScrollBehavior::CursorTop => {
13167 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13168 }
13169 SelectSyntaxNodeScrollBehavior::FitSelection => {
13170 self.request_autoscroll(Autoscroll::fit(), cx);
13171 }
13172 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13173 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13174 }
13175 }
13176 }
13177 }
13178
13179 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13180 if !EditorSettings::get_global(cx).gutter.runnables {
13181 self.clear_tasks();
13182 return Task::ready(());
13183 }
13184 let project = self.project.as_ref().map(Entity::downgrade);
13185 let task_sources = self.lsp_task_sources(cx);
13186 cx.spawn_in(window, async move |editor, cx| {
13187 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13188 let Some(project) = project.and_then(|p| p.upgrade()) else {
13189 return;
13190 };
13191 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13192 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13193 }) else {
13194 return;
13195 };
13196
13197 let hide_runnables = project
13198 .update(cx, |project, cx| {
13199 // Do not display any test indicators in non-dev server remote projects.
13200 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13201 })
13202 .unwrap_or(true);
13203 if hide_runnables {
13204 return;
13205 }
13206 let new_rows =
13207 cx.background_spawn({
13208 let snapshot = display_snapshot.clone();
13209 async move {
13210 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13211 }
13212 })
13213 .await;
13214 let Ok(lsp_tasks) =
13215 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13216 else {
13217 return;
13218 };
13219 let lsp_tasks = lsp_tasks.await;
13220
13221 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13222 lsp_tasks
13223 .into_iter()
13224 .flat_map(|(kind, tasks)| {
13225 tasks.into_iter().filter_map(move |(location, task)| {
13226 Some((kind.clone(), location?, task))
13227 })
13228 })
13229 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13230 let buffer = location.target.buffer;
13231 let buffer_snapshot = buffer.read(cx).snapshot();
13232 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13233 |(excerpt_id, snapshot, _)| {
13234 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13235 display_snapshot
13236 .buffer_snapshot
13237 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13238 } else {
13239 None
13240 }
13241 },
13242 );
13243 if let Some(offset) = offset {
13244 let task_buffer_range =
13245 location.target.range.to_point(&buffer_snapshot);
13246 let context_buffer_range =
13247 task_buffer_range.to_offset(&buffer_snapshot);
13248 let context_range = BufferOffset(context_buffer_range.start)
13249 ..BufferOffset(context_buffer_range.end);
13250
13251 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13252 .or_insert_with(|| RunnableTasks {
13253 templates: Vec::new(),
13254 offset,
13255 column: task_buffer_range.start.column,
13256 extra_variables: HashMap::default(),
13257 context_range,
13258 })
13259 .templates
13260 .push((kind, task.original_task().clone()));
13261 }
13262
13263 acc
13264 })
13265 }) else {
13266 return;
13267 };
13268
13269 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13270 editor
13271 .update(cx, |editor, _| {
13272 editor.clear_tasks();
13273 for (key, mut value) in rows {
13274 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13275 value.templates.extend(lsp_tasks.templates);
13276 }
13277
13278 editor.insert_tasks(key, value);
13279 }
13280 for (key, value) in lsp_tasks_by_rows {
13281 editor.insert_tasks(key, value);
13282 }
13283 })
13284 .ok();
13285 })
13286 }
13287 fn fetch_runnable_ranges(
13288 snapshot: &DisplaySnapshot,
13289 range: Range<Anchor>,
13290 ) -> Vec<language::RunnableRange> {
13291 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13292 }
13293
13294 fn runnable_rows(
13295 project: Entity<Project>,
13296 snapshot: DisplaySnapshot,
13297 runnable_ranges: Vec<RunnableRange>,
13298 mut cx: AsyncWindowContext,
13299 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13300 runnable_ranges
13301 .into_iter()
13302 .filter_map(|mut runnable| {
13303 let tasks = cx
13304 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13305 .ok()?;
13306 if tasks.is_empty() {
13307 return None;
13308 }
13309
13310 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13311
13312 let row = snapshot
13313 .buffer_snapshot
13314 .buffer_line_for_row(MultiBufferRow(point.row))?
13315 .1
13316 .start
13317 .row;
13318
13319 let context_range =
13320 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13321 Some((
13322 (runnable.buffer_id, row),
13323 RunnableTasks {
13324 templates: tasks,
13325 offset: snapshot
13326 .buffer_snapshot
13327 .anchor_before(runnable.run_range.start),
13328 context_range,
13329 column: point.column,
13330 extra_variables: runnable.extra_captures,
13331 },
13332 ))
13333 })
13334 .collect()
13335 }
13336
13337 fn templates_with_tags(
13338 project: &Entity<Project>,
13339 runnable: &mut Runnable,
13340 cx: &mut App,
13341 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13342 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13343 let (worktree_id, file) = project
13344 .buffer_for_id(runnable.buffer, cx)
13345 .and_then(|buffer| buffer.read(cx).file())
13346 .map(|file| (file.worktree_id(cx), file.clone()))
13347 .unzip();
13348
13349 (
13350 project.task_store().read(cx).task_inventory().cloned(),
13351 worktree_id,
13352 file,
13353 )
13354 });
13355
13356 let mut templates_with_tags = mem::take(&mut runnable.tags)
13357 .into_iter()
13358 .flat_map(|RunnableTag(tag)| {
13359 inventory
13360 .as_ref()
13361 .into_iter()
13362 .flat_map(|inventory| {
13363 inventory.read(cx).list_tasks(
13364 file.clone(),
13365 Some(runnable.language.clone()),
13366 worktree_id,
13367 cx,
13368 )
13369 })
13370 .filter(move |(_, template)| {
13371 template.tags.iter().any(|source_tag| source_tag == &tag)
13372 })
13373 })
13374 .sorted_by_key(|(kind, _)| kind.to_owned())
13375 .collect::<Vec<_>>();
13376 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13377 // Strongest source wins; if we have worktree tag binding, prefer that to
13378 // global and language bindings;
13379 // if we have a global binding, prefer that to language binding.
13380 let first_mismatch = templates_with_tags
13381 .iter()
13382 .position(|(tag_source, _)| tag_source != leading_tag_source);
13383 if let Some(index) = first_mismatch {
13384 templates_with_tags.truncate(index);
13385 }
13386 }
13387
13388 templates_with_tags
13389 }
13390
13391 pub fn move_to_enclosing_bracket(
13392 &mut self,
13393 _: &MoveToEnclosingBracket,
13394 window: &mut Window,
13395 cx: &mut Context<Self>,
13396 ) {
13397 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13398 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13399 s.move_offsets_with(|snapshot, selection| {
13400 let Some(enclosing_bracket_ranges) =
13401 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13402 else {
13403 return;
13404 };
13405
13406 let mut best_length = usize::MAX;
13407 let mut best_inside = false;
13408 let mut best_in_bracket_range = false;
13409 let mut best_destination = None;
13410 for (open, close) in enclosing_bracket_ranges {
13411 let close = close.to_inclusive();
13412 let length = close.end() - open.start;
13413 let inside = selection.start >= open.end && selection.end <= *close.start();
13414 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13415 || close.contains(&selection.head());
13416
13417 // If best is next to a bracket and current isn't, skip
13418 if !in_bracket_range && best_in_bracket_range {
13419 continue;
13420 }
13421
13422 // Prefer smaller lengths unless best is inside and current isn't
13423 if length > best_length && (best_inside || !inside) {
13424 continue;
13425 }
13426
13427 best_length = length;
13428 best_inside = inside;
13429 best_in_bracket_range = in_bracket_range;
13430 best_destination = Some(
13431 if close.contains(&selection.start) && close.contains(&selection.end) {
13432 if inside { open.end } else { open.start }
13433 } else if inside {
13434 *close.start()
13435 } else {
13436 *close.end()
13437 },
13438 );
13439 }
13440
13441 if let Some(destination) = best_destination {
13442 selection.collapse_to(destination, SelectionGoal::None);
13443 }
13444 })
13445 });
13446 }
13447
13448 pub fn undo_selection(
13449 &mut self,
13450 _: &UndoSelection,
13451 window: &mut Window,
13452 cx: &mut Context<Self>,
13453 ) {
13454 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13455 self.end_selection(window, cx);
13456 self.selection_history.mode = SelectionHistoryMode::Undoing;
13457 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13458 self.change_selections(None, window, cx, |s| {
13459 s.select_anchors(entry.selections.to_vec())
13460 });
13461 self.select_next_state = entry.select_next_state;
13462 self.select_prev_state = entry.select_prev_state;
13463 self.add_selections_state = entry.add_selections_state;
13464 self.request_autoscroll(Autoscroll::newest(), cx);
13465 }
13466 self.selection_history.mode = SelectionHistoryMode::Normal;
13467 }
13468
13469 pub fn redo_selection(
13470 &mut self,
13471 _: &RedoSelection,
13472 window: &mut Window,
13473 cx: &mut Context<Self>,
13474 ) {
13475 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13476 self.end_selection(window, cx);
13477 self.selection_history.mode = SelectionHistoryMode::Redoing;
13478 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13479 self.change_selections(None, window, cx, |s| {
13480 s.select_anchors(entry.selections.to_vec())
13481 });
13482 self.select_next_state = entry.select_next_state;
13483 self.select_prev_state = entry.select_prev_state;
13484 self.add_selections_state = entry.add_selections_state;
13485 self.request_autoscroll(Autoscroll::newest(), cx);
13486 }
13487 self.selection_history.mode = SelectionHistoryMode::Normal;
13488 }
13489
13490 pub fn expand_excerpts(
13491 &mut self,
13492 action: &ExpandExcerpts,
13493 _: &mut Window,
13494 cx: &mut Context<Self>,
13495 ) {
13496 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13497 }
13498
13499 pub fn expand_excerpts_down(
13500 &mut self,
13501 action: &ExpandExcerptsDown,
13502 _: &mut Window,
13503 cx: &mut Context<Self>,
13504 ) {
13505 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13506 }
13507
13508 pub fn expand_excerpts_up(
13509 &mut self,
13510 action: &ExpandExcerptsUp,
13511 _: &mut Window,
13512 cx: &mut Context<Self>,
13513 ) {
13514 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13515 }
13516
13517 pub fn expand_excerpts_for_direction(
13518 &mut self,
13519 lines: u32,
13520 direction: ExpandExcerptDirection,
13521
13522 cx: &mut Context<Self>,
13523 ) {
13524 let selections = self.selections.disjoint_anchors();
13525
13526 let lines = if lines == 0 {
13527 EditorSettings::get_global(cx).expand_excerpt_lines
13528 } else {
13529 lines
13530 };
13531
13532 self.buffer.update(cx, |buffer, cx| {
13533 let snapshot = buffer.snapshot(cx);
13534 let mut excerpt_ids = selections
13535 .iter()
13536 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13537 .collect::<Vec<_>>();
13538 excerpt_ids.sort();
13539 excerpt_ids.dedup();
13540 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13541 })
13542 }
13543
13544 pub fn expand_excerpt(
13545 &mut self,
13546 excerpt: ExcerptId,
13547 direction: ExpandExcerptDirection,
13548 window: &mut Window,
13549 cx: &mut Context<Self>,
13550 ) {
13551 let current_scroll_position = self.scroll_position(cx);
13552 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13553 let mut should_scroll_up = false;
13554
13555 if direction == ExpandExcerptDirection::Down {
13556 let multi_buffer = self.buffer.read(cx);
13557 let snapshot = multi_buffer.snapshot(cx);
13558 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13559 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13560 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13561 let buffer_snapshot = buffer.read(cx).snapshot();
13562 let excerpt_end_row =
13563 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13564 let last_row = buffer_snapshot.max_point().row;
13565 let lines_below = last_row.saturating_sub(excerpt_end_row);
13566 should_scroll_up = lines_below >= lines_to_expand;
13567 }
13568 }
13569 }
13570 }
13571
13572 self.buffer.update(cx, |buffer, cx| {
13573 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13574 });
13575
13576 if should_scroll_up {
13577 let new_scroll_position =
13578 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13579 self.set_scroll_position(new_scroll_position, window, cx);
13580 }
13581 }
13582
13583 pub fn go_to_singleton_buffer_point(
13584 &mut self,
13585 point: Point,
13586 window: &mut Window,
13587 cx: &mut Context<Self>,
13588 ) {
13589 self.go_to_singleton_buffer_range(point..point, window, cx);
13590 }
13591
13592 pub fn go_to_singleton_buffer_range(
13593 &mut self,
13594 range: Range<Point>,
13595 window: &mut Window,
13596 cx: &mut Context<Self>,
13597 ) {
13598 let multibuffer = self.buffer().read(cx);
13599 let Some(buffer) = multibuffer.as_singleton() else {
13600 return;
13601 };
13602 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13603 return;
13604 };
13605 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13606 return;
13607 };
13608 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13609 s.select_anchor_ranges([start..end])
13610 });
13611 }
13612
13613 pub fn go_to_diagnostic(
13614 &mut self,
13615 _: &GoToDiagnostic,
13616 window: &mut Window,
13617 cx: &mut Context<Self>,
13618 ) {
13619 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13620 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13621 }
13622
13623 pub fn go_to_prev_diagnostic(
13624 &mut self,
13625 _: &GoToPreviousDiagnostic,
13626 window: &mut Window,
13627 cx: &mut Context<Self>,
13628 ) {
13629 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13630 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13631 }
13632
13633 pub fn go_to_diagnostic_impl(
13634 &mut self,
13635 direction: Direction,
13636 window: &mut Window,
13637 cx: &mut Context<Self>,
13638 ) {
13639 let buffer = self.buffer.read(cx).snapshot(cx);
13640 let selection = self.selections.newest::<usize>(cx);
13641
13642 let mut active_group_id = None;
13643 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13644 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13645 active_group_id = Some(active_group.group_id);
13646 }
13647 }
13648
13649 fn filtered(
13650 snapshot: EditorSnapshot,
13651 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13652 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13653 diagnostics
13654 .filter(|entry| entry.range.start != entry.range.end)
13655 .filter(|entry| !entry.diagnostic.is_unnecessary)
13656 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13657 }
13658
13659 let snapshot = self.snapshot(window, cx);
13660 let before = filtered(
13661 snapshot.clone(),
13662 buffer
13663 .diagnostics_in_range(0..selection.start)
13664 .filter(|entry| entry.range.start <= selection.start),
13665 );
13666 let after = filtered(
13667 snapshot,
13668 buffer
13669 .diagnostics_in_range(selection.start..buffer.len())
13670 .filter(|entry| entry.range.start >= selection.start),
13671 );
13672
13673 let mut found: Option<DiagnosticEntry<usize>> = None;
13674 if direction == Direction::Prev {
13675 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13676 {
13677 for diagnostic in prev_diagnostics.into_iter().rev() {
13678 if diagnostic.range.start != selection.start
13679 || active_group_id
13680 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13681 {
13682 found = Some(diagnostic);
13683 break 'outer;
13684 }
13685 }
13686 }
13687 } else {
13688 for diagnostic in after.chain(before) {
13689 if diagnostic.range.start != selection.start
13690 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13691 {
13692 found = Some(diagnostic);
13693 break;
13694 }
13695 }
13696 }
13697 let Some(next_diagnostic) = found else {
13698 return;
13699 };
13700
13701 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13702 return;
13703 };
13704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13705 s.select_ranges(vec![
13706 next_diagnostic.range.start..next_diagnostic.range.start,
13707 ])
13708 });
13709 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13710 self.refresh_inline_completion(false, true, window, cx);
13711 }
13712
13713 pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13714 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13715 let snapshot = self.snapshot(window, cx);
13716 let selection = self.selections.newest::<Point>(cx);
13717 self.go_to_hunk_before_or_after_position(
13718 &snapshot,
13719 selection.head(),
13720 Direction::Next,
13721 window,
13722 cx,
13723 );
13724 }
13725
13726 pub fn go_to_hunk_before_or_after_position(
13727 &mut self,
13728 snapshot: &EditorSnapshot,
13729 position: Point,
13730 direction: Direction,
13731 window: &mut Window,
13732 cx: &mut Context<Editor>,
13733 ) {
13734 let row = if direction == Direction::Next {
13735 self.hunk_after_position(snapshot, position)
13736 .map(|hunk| hunk.row_range.start)
13737 } else {
13738 self.hunk_before_position(snapshot, position)
13739 };
13740
13741 if let Some(row) = row {
13742 let destination = Point::new(row.0, 0);
13743 let autoscroll = Autoscroll::center();
13744
13745 self.unfold_ranges(&[destination..destination], false, false, cx);
13746 self.change_selections(Some(autoscroll), window, cx, |s| {
13747 s.select_ranges([destination..destination]);
13748 });
13749 }
13750 }
13751
13752 fn hunk_after_position(
13753 &mut self,
13754 snapshot: &EditorSnapshot,
13755 position: Point,
13756 ) -> Option<MultiBufferDiffHunk> {
13757 snapshot
13758 .buffer_snapshot
13759 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13760 .find(|hunk| hunk.row_range.start.0 > position.row)
13761 .or_else(|| {
13762 snapshot
13763 .buffer_snapshot
13764 .diff_hunks_in_range(Point::zero()..position)
13765 .find(|hunk| hunk.row_range.end.0 < position.row)
13766 })
13767 }
13768
13769 fn go_to_prev_hunk(
13770 &mut self,
13771 _: &GoToPreviousHunk,
13772 window: &mut Window,
13773 cx: &mut Context<Self>,
13774 ) {
13775 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13776 let snapshot = self.snapshot(window, cx);
13777 let selection = self.selections.newest::<Point>(cx);
13778 self.go_to_hunk_before_or_after_position(
13779 &snapshot,
13780 selection.head(),
13781 Direction::Prev,
13782 window,
13783 cx,
13784 );
13785 }
13786
13787 fn hunk_before_position(
13788 &mut self,
13789 snapshot: &EditorSnapshot,
13790 position: Point,
13791 ) -> Option<MultiBufferRow> {
13792 snapshot
13793 .buffer_snapshot
13794 .diff_hunk_before(position)
13795 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13796 }
13797
13798 fn go_to_next_change(
13799 &mut self,
13800 _: &GoToNextChange,
13801 window: &mut Window,
13802 cx: &mut Context<Self>,
13803 ) {
13804 if let Some(selections) = self
13805 .change_list
13806 .next_change(1, Direction::Next)
13807 .map(|s| s.to_vec())
13808 {
13809 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13810 let map = s.display_map();
13811 s.select_display_ranges(selections.iter().map(|a| {
13812 let point = a.to_display_point(&map);
13813 point..point
13814 }))
13815 })
13816 }
13817 }
13818
13819 fn go_to_previous_change(
13820 &mut self,
13821 _: &GoToPreviousChange,
13822 window: &mut Window,
13823 cx: &mut Context<Self>,
13824 ) {
13825 if let Some(selections) = self
13826 .change_list
13827 .next_change(1, Direction::Prev)
13828 .map(|s| s.to_vec())
13829 {
13830 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13831 let map = s.display_map();
13832 s.select_display_ranges(selections.iter().map(|a| {
13833 let point = a.to_display_point(&map);
13834 point..point
13835 }))
13836 })
13837 }
13838 }
13839
13840 fn go_to_line<T: 'static>(
13841 &mut self,
13842 position: Anchor,
13843 highlight_color: Option<Hsla>,
13844 window: &mut Window,
13845 cx: &mut Context<Self>,
13846 ) {
13847 let snapshot = self.snapshot(window, cx).display_snapshot;
13848 let position = position.to_point(&snapshot.buffer_snapshot);
13849 let start = snapshot
13850 .buffer_snapshot
13851 .clip_point(Point::new(position.row, 0), Bias::Left);
13852 let end = start + Point::new(1, 0);
13853 let start = snapshot.buffer_snapshot.anchor_before(start);
13854 let end = snapshot.buffer_snapshot.anchor_before(end);
13855
13856 self.highlight_rows::<T>(
13857 start..end,
13858 highlight_color
13859 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13860 Default::default(),
13861 cx,
13862 );
13863 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13864 }
13865
13866 pub fn go_to_definition(
13867 &mut self,
13868 _: &GoToDefinition,
13869 window: &mut Window,
13870 cx: &mut Context<Self>,
13871 ) -> Task<Result<Navigated>> {
13872 let definition =
13873 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13874 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13875 cx.spawn_in(window, async move |editor, cx| {
13876 if definition.await? == Navigated::Yes {
13877 return Ok(Navigated::Yes);
13878 }
13879 match fallback_strategy {
13880 GoToDefinitionFallback::None => Ok(Navigated::No),
13881 GoToDefinitionFallback::FindAllReferences => {
13882 match editor.update_in(cx, |editor, window, cx| {
13883 editor.find_all_references(&FindAllReferences, window, cx)
13884 })? {
13885 Some(references) => references.await,
13886 None => Ok(Navigated::No),
13887 }
13888 }
13889 }
13890 })
13891 }
13892
13893 pub fn go_to_declaration(
13894 &mut self,
13895 _: &GoToDeclaration,
13896 window: &mut Window,
13897 cx: &mut Context<Self>,
13898 ) -> Task<Result<Navigated>> {
13899 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13900 }
13901
13902 pub fn go_to_declaration_split(
13903 &mut self,
13904 _: &GoToDeclaration,
13905 window: &mut Window,
13906 cx: &mut Context<Self>,
13907 ) -> Task<Result<Navigated>> {
13908 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13909 }
13910
13911 pub fn go_to_implementation(
13912 &mut self,
13913 _: &GoToImplementation,
13914 window: &mut Window,
13915 cx: &mut Context<Self>,
13916 ) -> Task<Result<Navigated>> {
13917 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13918 }
13919
13920 pub fn go_to_implementation_split(
13921 &mut self,
13922 _: &GoToImplementationSplit,
13923 window: &mut Window,
13924 cx: &mut Context<Self>,
13925 ) -> Task<Result<Navigated>> {
13926 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13927 }
13928
13929 pub fn go_to_type_definition(
13930 &mut self,
13931 _: &GoToTypeDefinition,
13932 window: &mut Window,
13933 cx: &mut Context<Self>,
13934 ) -> Task<Result<Navigated>> {
13935 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13936 }
13937
13938 pub fn go_to_definition_split(
13939 &mut self,
13940 _: &GoToDefinitionSplit,
13941 window: &mut Window,
13942 cx: &mut Context<Self>,
13943 ) -> Task<Result<Navigated>> {
13944 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13945 }
13946
13947 pub fn go_to_type_definition_split(
13948 &mut self,
13949 _: &GoToTypeDefinitionSplit,
13950 window: &mut Window,
13951 cx: &mut Context<Self>,
13952 ) -> Task<Result<Navigated>> {
13953 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13954 }
13955
13956 fn go_to_definition_of_kind(
13957 &mut self,
13958 kind: GotoDefinitionKind,
13959 split: bool,
13960 window: &mut Window,
13961 cx: &mut Context<Self>,
13962 ) -> Task<Result<Navigated>> {
13963 let Some(provider) = self.semantics_provider.clone() else {
13964 return Task::ready(Ok(Navigated::No));
13965 };
13966 let head = self.selections.newest::<usize>(cx).head();
13967 let buffer = self.buffer.read(cx);
13968 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13969 text_anchor
13970 } else {
13971 return Task::ready(Ok(Navigated::No));
13972 };
13973
13974 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13975 return Task::ready(Ok(Navigated::No));
13976 };
13977
13978 cx.spawn_in(window, async move |editor, cx| {
13979 let definitions = definitions.await?;
13980 let navigated = editor
13981 .update_in(cx, |editor, window, cx| {
13982 editor.navigate_to_hover_links(
13983 Some(kind),
13984 definitions
13985 .into_iter()
13986 .filter(|location| {
13987 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13988 })
13989 .map(HoverLink::Text)
13990 .collect::<Vec<_>>(),
13991 split,
13992 window,
13993 cx,
13994 )
13995 })?
13996 .await?;
13997 anyhow::Ok(navigated)
13998 })
13999 }
14000
14001 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
14002 let selection = self.selections.newest_anchor();
14003 let head = selection.head();
14004 let tail = selection.tail();
14005
14006 let Some((buffer, start_position)) =
14007 self.buffer.read(cx).text_anchor_for_position(head, cx)
14008 else {
14009 return;
14010 };
14011
14012 let end_position = if head != tail {
14013 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
14014 return;
14015 };
14016 Some(pos)
14017 } else {
14018 None
14019 };
14020
14021 let url_finder = cx.spawn_in(window, async move |editor, cx| {
14022 let url = if let Some(end_pos) = end_position {
14023 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
14024 } else {
14025 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
14026 };
14027
14028 if let Some(url) = url {
14029 editor.update(cx, |_, cx| {
14030 cx.open_url(&url);
14031 })
14032 } else {
14033 Ok(())
14034 }
14035 });
14036
14037 url_finder.detach();
14038 }
14039
14040 pub fn open_selected_filename(
14041 &mut self,
14042 _: &OpenSelectedFilename,
14043 window: &mut Window,
14044 cx: &mut Context<Self>,
14045 ) {
14046 let Some(workspace) = self.workspace() else {
14047 return;
14048 };
14049
14050 let position = self.selections.newest_anchor().head();
14051
14052 let Some((buffer, buffer_position)) =
14053 self.buffer.read(cx).text_anchor_for_position(position, cx)
14054 else {
14055 return;
14056 };
14057
14058 let project = self.project.clone();
14059
14060 cx.spawn_in(window, async move |_, cx| {
14061 let result = find_file(&buffer, project, buffer_position, cx).await;
14062
14063 if let Some((_, path)) = result {
14064 workspace
14065 .update_in(cx, |workspace, window, cx| {
14066 workspace.open_resolved_path(path, window, cx)
14067 })?
14068 .await?;
14069 }
14070 anyhow::Ok(())
14071 })
14072 .detach();
14073 }
14074
14075 pub(crate) fn navigate_to_hover_links(
14076 &mut self,
14077 kind: Option<GotoDefinitionKind>,
14078 mut definitions: Vec<HoverLink>,
14079 split: bool,
14080 window: &mut Window,
14081 cx: &mut Context<Editor>,
14082 ) -> Task<Result<Navigated>> {
14083 // If there is one definition, just open it directly
14084 if definitions.len() == 1 {
14085 let definition = definitions.pop().unwrap();
14086
14087 enum TargetTaskResult {
14088 Location(Option<Location>),
14089 AlreadyNavigated,
14090 }
14091
14092 let target_task = match definition {
14093 HoverLink::Text(link) => {
14094 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14095 }
14096 HoverLink::InlayHint(lsp_location, server_id) => {
14097 let computation =
14098 self.compute_target_location(lsp_location, server_id, window, cx);
14099 cx.background_spawn(async move {
14100 let location = computation.await?;
14101 Ok(TargetTaskResult::Location(location))
14102 })
14103 }
14104 HoverLink::Url(url) => {
14105 cx.open_url(&url);
14106 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14107 }
14108 HoverLink::File(path) => {
14109 if let Some(workspace) = self.workspace() {
14110 cx.spawn_in(window, async move |_, cx| {
14111 workspace
14112 .update_in(cx, |workspace, window, cx| {
14113 workspace.open_resolved_path(path, window, cx)
14114 })?
14115 .await
14116 .map(|_| TargetTaskResult::AlreadyNavigated)
14117 })
14118 } else {
14119 Task::ready(Ok(TargetTaskResult::Location(None)))
14120 }
14121 }
14122 };
14123 cx.spawn_in(window, async move |editor, cx| {
14124 let target = match target_task.await.context("target resolution task")? {
14125 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14126 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14127 TargetTaskResult::Location(Some(target)) => target,
14128 };
14129
14130 editor.update_in(cx, |editor, window, cx| {
14131 let Some(workspace) = editor.workspace() else {
14132 return Navigated::No;
14133 };
14134 let pane = workspace.read(cx).active_pane().clone();
14135
14136 let range = target.range.to_point(target.buffer.read(cx));
14137 let range = editor.range_for_match(&range);
14138 let range = collapse_multiline_range(range);
14139
14140 if !split
14141 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14142 {
14143 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14144 } else {
14145 window.defer(cx, move |window, cx| {
14146 let target_editor: Entity<Self> =
14147 workspace.update(cx, |workspace, cx| {
14148 let pane = if split {
14149 workspace.adjacent_pane(window, cx)
14150 } else {
14151 workspace.active_pane().clone()
14152 };
14153
14154 workspace.open_project_item(
14155 pane,
14156 target.buffer.clone(),
14157 true,
14158 true,
14159 window,
14160 cx,
14161 )
14162 });
14163 target_editor.update(cx, |target_editor, cx| {
14164 // When selecting a definition in a different buffer, disable the nav history
14165 // to avoid creating a history entry at the previous cursor location.
14166 pane.update(cx, |pane, _| pane.disable_history());
14167 target_editor.go_to_singleton_buffer_range(range, window, cx);
14168 pane.update(cx, |pane, _| pane.enable_history());
14169 });
14170 });
14171 }
14172 Navigated::Yes
14173 })
14174 })
14175 } else if !definitions.is_empty() {
14176 cx.spawn_in(window, async move |editor, cx| {
14177 let (title, location_tasks, workspace) = editor
14178 .update_in(cx, |editor, window, cx| {
14179 let tab_kind = match kind {
14180 Some(GotoDefinitionKind::Implementation) => "Implementations",
14181 _ => "Definitions",
14182 };
14183 let title = definitions
14184 .iter()
14185 .find_map(|definition| match definition {
14186 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14187 let buffer = origin.buffer.read(cx);
14188 format!(
14189 "{} for {}",
14190 tab_kind,
14191 buffer
14192 .text_for_range(origin.range.clone())
14193 .collect::<String>()
14194 )
14195 }),
14196 HoverLink::InlayHint(_, _) => None,
14197 HoverLink::Url(_) => None,
14198 HoverLink::File(_) => None,
14199 })
14200 .unwrap_or(tab_kind.to_string());
14201 let location_tasks = definitions
14202 .into_iter()
14203 .map(|definition| match definition {
14204 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14205 HoverLink::InlayHint(lsp_location, server_id) => editor
14206 .compute_target_location(lsp_location, server_id, window, cx),
14207 HoverLink::Url(_) => Task::ready(Ok(None)),
14208 HoverLink::File(_) => Task::ready(Ok(None)),
14209 })
14210 .collect::<Vec<_>>();
14211 (title, location_tasks, editor.workspace().clone())
14212 })
14213 .context("location tasks preparation")?;
14214
14215 let locations = future::join_all(location_tasks)
14216 .await
14217 .into_iter()
14218 .filter_map(|location| location.transpose())
14219 .collect::<Result<_>>()
14220 .context("location tasks")?;
14221
14222 let Some(workspace) = workspace else {
14223 return Ok(Navigated::No);
14224 };
14225 let opened = workspace
14226 .update_in(cx, |workspace, window, cx| {
14227 Self::open_locations_in_multibuffer(
14228 workspace,
14229 locations,
14230 title,
14231 split,
14232 MultibufferSelectionMode::First,
14233 window,
14234 cx,
14235 )
14236 })
14237 .ok();
14238
14239 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14240 })
14241 } else {
14242 Task::ready(Ok(Navigated::No))
14243 }
14244 }
14245
14246 fn compute_target_location(
14247 &self,
14248 lsp_location: lsp::Location,
14249 server_id: LanguageServerId,
14250 window: &mut Window,
14251 cx: &mut Context<Self>,
14252 ) -> Task<anyhow::Result<Option<Location>>> {
14253 let Some(project) = self.project.clone() else {
14254 return Task::ready(Ok(None));
14255 };
14256
14257 cx.spawn_in(window, async move |editor, cx| {
14258 let location_task = editor.update(cx, |_, cx| {
14259 project.update(cx, |project, cx| {
14260 let language_server_name = project
14261 .language_server_statuses(cx)
14262 .find(|(id, _)| server_id == *id)
14263 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14264 language_server_name.map(|language_server_name| {
14265 project.open_local_buffer_via_lsp(
14266 lsp_location.uri.clone(),
14267 server_id,
14268 language_server_name,
14269 cx,
14270 )
14271 })
14272 })
14273 })?;
14274 let location = match location_task {
14275 Some(task) => Some({
14276 let target_buffer_handle = task.await.context("open local buffer")?;
14277 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14278 let target_start = target_buffer
14279 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14280 let target_end = target_buffer
14281 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14282 target_buffer.anchor_after(target_start)
14283 ..target_buffer.anchor_before(target_end)
14284 })?;
14285 Location {
14286 buffer: target_buffer_handle,
14287 range,
14288 }
14289 }),
14290 None => None,
14291 };
14292 Ok(location)
14293 })
14294 }
14295
14296 pub fn find_all_references(
14297 &mut self,
14298 _: &FindAllReferences,
14299 window: &mut Window,
14300 cx: &mut Context<Self>,
14301 ) -> Option<Task<Result<Navigated>>> {
14302 let selection = self.selections.newest::<usize>(cx);
14303 let multi_buffer = self.buffer.read(cx);
14304 let head = selection.head();
14305
14306 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14307 let head_anchor = multi_buffer_snapshot.anchor_at(
14308 head,
14309 if head < selection.tail() {
14310 Bias::Right
14311 } else {
14312 Bias::Left
14313 },
14314 );
14315
14316 match self
14317 .find_all_references_task_sources
14318 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14319 {
14320 Ok(_) => {
14321 log::info!(
14322 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14323 );
14324 return None;
14325 }
14326 Err(i) => {
14327 self.find_all_references_task_sources.insert(i, head_anchor);
14328 }
14329 }
14330
14331 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14332 let workspace = self.workspace()?;
14333 let project = workspace.read(cx).project().clone();
14334 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14335 Some(cx.spawn_in(window, async move |editor, cx| {
14336 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14337 if let Ok(i) = editor
14338 .find_all_references_task_sources
14339 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14340 {
14341 editor.find_all_references_task_sources.remove(i);
14342 }
14343 });
14344
14345 let locations = references.await?;
14346 if locations.is_empty() {
14347 return anyhow::Ok(Navigated::No);
14348 }
14349
14350 workspace.update_in(cx, |workspace, window, cx| {
14351 let title = locations
14352 .first()
14353 .as_ref()
14354 .map(|location| {
14355 let buffer = location.buffer.read(cx);
14356 format!(
14357 "References to `{}`",
14358 buffer
14359 .text_for_range(location.range.clone())
14360 .collect::<String>()
14361 )
14362 })
14363 .unwrap();
14364 Self::open_locations_in_multibuffer(
14365 workspace,
14366 locations,
14367 title,
14368 false,
14369 MultibufferSelectionMode::First,
14370 window,
14371 cx,
14372 );
14373 Navigated::Yes
14374 })
14375 }))
14376 }
14377
14378 /// Opens a multibuffer with the given project locations in it
14379 pub fn open_locations_in_multibuffer(
14380 workspace: &mut Workspace,
14381 mut locations: Vec<Location>,
14382 title: String,
14383 split: bool,
14384 multibuffer_selection_mode: MultibufferSelectionMode,
14385 window: &mut Window,
14386 cx: &mut Context<Workspace>,
14387 ) {
14388 // If there are multiple definitions, open them in a multibuffer
14389 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14390 let mut locations = locations.into_iter().peekable();
14391 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14392 let capability = workspace.project().read(cx).capability();
14393
14394 let excerpt_buffer = cx.new(|cx| {
14395 let mut multibuffer = MultiBuffer::new(capability);
14396 while let Some(location) = locations.next() {
14397 let buffer = location.buffer.read(cx);
14398 let mut ranges_for_buffer = Vec::new();
14399 let range = location.range.to_point(buffer);
14400 ranges_for_buffer.push(range.clone());
14401
14402 while let Some(next_location) = locations.peek() {
14403 if next_location.buffer == location.buffer {
14404 ranges_for_buffer.push(next_location.range.to_point(buffer));
14405 locations.next();
14406 } else {
14407 break;
14408 }
14409 }
14410
14411 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14412 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14413 PathKey::for_buffer(&location.buffer, cx),
14414 location.buffer.clone(),
14415 ranges_for_buffer,
14416 DEFAULT_MULTIBUFFER_CONTEXT,
14417 cx,
14418 );
14419 ranges.extend(new_ranges)
14420 }
14421
14422 multibuffer.with_title(title)
14423 });
14424
14425 let editor = cx.new(|cx| {
14426 Editor::for_multibuffer(
14427 excerpt_buffer,
14428 Some(workspace.project().clone()),
14429 window,
14430 cx,
14431 )
14432 });
14433 editor.update(cx, |editor, cx| {
14434 match multibuffer_selection_mode {
14435 MultibufferSelectionMode::First => {
14436 if let Some(first_range) = ranges.first() {
14437 editor.change_selections(None, window, cx, |selections| {
14438 selections.clear_disjoint();
14439 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14440 });
14441 }
14442 editor.highlight_background::<Self>(
14443 &ranges,
14444 |theme| theme.editor_highlighted_line_background,
14445 cx,
14446 );
14447 }
14448 MultibufferSelectionMode::All => {
14449 editor.change_selections(None, window, cx, |selections| {
14450 selections.clear_disjoint();
14451 selections.select_anchor_ranges(ranges);
14452 });
14453 }
14454 }
14455 editor.register_buffers_with_language_servers(cx);
14456 });
14457
14458 let item = Box::new(editor);
14459 let item_id = item.item_id();
14460
14461 if split {
14462 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14463 } else {
14464 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14465 let (preview_item_id, preview_item_idx) =
14466 workspace.active_pane().update(cx, |pane, _| {
14467 (pane.preview_item_id(), pane.preview_item_idx())
14468 });
14469
14470 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14471
14472 if let Some(preview_item_id) = preview_item_id {
14473 workspace.active_pane().update(cx, |pane, cx| {
14474 pane.remove_item(preview_item_id, false, false, window, cx);
14475 });
14476 }
14477 } else {
14478 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14479 }
14480 }
14481 workspace.active_pane().update(cx, |pane, cx| {
14482 pane.set_preview_item_id(Some(item_id), cx);
14483 });
14484 }
14485
14486 pub fn rename(
14487 &mut self,
14488 _: &Rename,
14489 window: &mut Window,
14490 cx: &mut Context<Self>,
14491 ) -> Option<Task<Result<()>>> {
14492 use language::ToOffset as _;
14493
14494 let provider = self.semantics_provider.clone()?;
14495 let selection = self.selections.newest_anchor().clone();
14496 let (cursor_buffer, cursor_buffer_position) = self
14497 .buffer
14498 .read(cx)
14499 .text_anchor_for_position(selection.head(), cx)?;
14500 let (tail_buffer, cursor_buffer_position_end) = self
14501 .buffer
14502 .read(cx)
14503 .text_anchor_for_position(selection.tail(), cx)?;
14504 if tail_buffer != cursor_buffer {
14505 return None;
14506 }
14507
14508 let snapshot = cursor_buffer.read(cx).snapshot();
14509 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14510 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14511 let prepare_rename = provider
14512 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14513 .unwrap_or_else(|| Task::ready(Ok(None)));
14514 drop(snapshot);
14515
14516 Some(cx.spawn_in(window, async move |this, cx| {
14517 let rename_range = if let Some(range) = prepare_rename.await? {
14518 Some(range)
14519 } else {
14520 this.update(cx, |this, cx| {
14521 let buffer = this.buffer.read(cx).snapshot(cx);
14522 let mut buffer_highlights = this
14523 .document_highlights_for_position(selection.head(), &buffer)
14524 .filter(|highlight| {
14525 highlight.start.excerpt_id == selection.head().excerpt_id
14526 && highlight.end.excerpt_id == selection.head().excerpt_id
14527 });
14528 buffer_highlights
14529 .next()
14530 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14531 })?
14532 };
14533 if let Some(rename_range) = rename_range {
14534 this.update_in(cx, |this, window, cx| {
14535 let snapshot = cursor_buffer.read(cx).snapshot();
14536 let rename_buffer_range = rename_range.to_offset(&snapshot);
14537 let cursor_offset_in_rename_range =
14538 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14539 let cursor_offset_in_rename_range_end =
14540 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14541
14542 this.take_rename(false, window, cx);
14543 let buffer = this.buffer.read(cx).read(cx);
14544 let cursor_offset = selection.head().to_offset(&buffer);
14545 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14546 let rename_end = rename_start + rename_buffer_range.len();
14547 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14548 let mut old_highlight_id = None;
14549 let old_name: Arc<str> = buffer
14550 .chunks(rename_start..rename_end, true)
14551 .map(|chunk| {
14552 if old_highlight_id.is_none() {
14553 old_highlight_id = chunk.syntax_highlight_id;
14554 }
14555 chunk.text
14556 })
14557 .collect::<String>()
14558 .into();
14559
14560 drop(buffer);
14561
14562 // Position the selection in the rename editor so that it matches the current selection.
14563 this.show_local_selections = false;
14564 let rename_editor = cx.new(|cx| {
14565 let mut editor = Editor::single_line(window, cx);
14566 editor.buffer.update(cx, |buffer, cx| {
14567 buffer.edit([(0..0, old_name.clone())], None, cx)
14568 });
14569 let rename_selection_range = match cursor_offset_in_rename_range
14570 .cmp(&cursor_offset_in_rename_range_end)
14571 {
14572 Ordering::Equal => {
14573 editor.select_all(&SelectAll, window, cx);
14574 return editor;
14575 }
14576 Ordering::Less => {
14577 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14578 }
14579 Ordering::Greater => {
14580 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14581 }
14582 };
14583 if rename_selection_range.end > old_name.len() {
14584 editor.select_all(&SelectAll, window, cx);
14585 } else {
14586 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14587 s.select_ranges([rename_selection_range]);
14588 });
14589 }
14590 editor
14591 });
14592 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14593 if e == &EditorEvent::Focused {
14594 cx.emit(EditorEvent::FocusedIn)
14595 }
14596 })
14597 .detach();
14598
14599 let write_highlights =
14600 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14601 let read_highlights =
14602 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14603 let ranges = write_highlights
14604 .iter()
14605 .flat_map(|(_, ranges)| ranges.iter())
14606 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14607 .cloned()
14608 .collect();
14609
14610 this.highlight_text::<Rename>(
14611 ranges,
14612 HighlightStyle {
14613 fade_out: Some(0.6),
14614 ..Default::default()
14615 },
14616 cx,
14617 );
14618 let rename_focus_handle = rename_editor.focus_handle(cx);
14619 window.focus(&rename_focus_handle);
14620 let block_id = this.insert_blocks(
14621 [BlockProperties {
14622 style: BlockStyle::Flex,
14623 placement: BlockPlacement::Below(range.start),
14624 height: Some(1),
14625 render: Arc::new({
14626 let rename_editor = rename_editor.clone();
14627 move |cx: &mut BlockContext| {
14628 let mut text_style = cx.editor_style.text.clone();
14629 if let Some(highlight_style) = old_highlight_id
14630 .and_then(|h| h.style(&cx.editor_style.syntax))
14631 {
14632 text_style = text_style.highlight(highlight_style);
14633 }
14634 div()
14635 .block_mouse_down()
14636 .pl(cx.anchor_x)
14637 .child(EditorElement::new(
14638 &rename_editor,
14639 EditorStyle {
14640 background: cx.theme().system().transparent,
14641 local_player: cx.editor_style.local_player,
14642 text: text_style,
14643 scrollbar_width: cx.editor_style.scrollbar_width,
14644 syntax: cx.editor_style.syntax.clone(),
14645 status: cx.editor_style.status.clone(),
14646 inlay_hints_style: HighlightStyle {
14647 font_weight: Some(FontWeight::BOLD),
14648 ..make_inlay_hints_style(cx.app)
14649 },
14650 inline_completion_styles: make_suggestion_styles(
14651 cx.app,
14652 ),
14653 ..EditorStyle::default()
14654 },
14655 ))
14656 .into_any_element()
14657 }
14658 }),
14659 priority: 0,
14660 render_in_minimap: true,
14661 }],
14662 Some(Autoscroll::fit()),
14663 cx,
14664 )[0];
14665 this.pending_rename = Some(RenameState {
14666 range,
14667 old_name,
14668 editor: rename_editor,
14669 block_id,
14670 });
14671 })?;
14672 }
14673
14674 Ok(())
14675 }))
14676 }
14677
14678 pub fn confirm_rename(
14679 &mut self,
14680 _: &ConfirmRename,
14681 window: &mut Window,
14682 cx: &mut Context<Self>,
14683 ) -> Option<Task<Result<()>>> {
14684 let rename = self.take_rename(false, window, cx)?;
14685 let workspace = self.workspace()?.downgrade();
14686 let (buffer, start) = self
14687 .buffer
14688 .read(cx)
14689 .text_anchor_for_position(rename.range.start, cx)?;
14690 let (end_buffer, _) = self
14691 .buffer
14692 .read(cx)
14693 .text_anchor_for_position(rename.range.end, cx)?;
14694 if buffer != end_buffer {
14695 return None;
14696 }
14697
14698 let old_name = rename.old_name;
14699 let new_name = rename.editor.read(cx).text(cx);
14700
14701 let rename = self.semantics_provider.as_ref()?.perform_rename(
14702 &buffer,
14703 start,
14704 new_name.clone(),
14705 cx,
14706 )?;
14707
14708 Some(cx.spawn_in(window, async move |editor, cx| {
14709 let project_transaction = rename.await?;
14710 Self::open_project_transaction(
14711 &editor,
14712 workspace,
14713 project_transaction,
14714 format!("Rename: {} → {}", old_name, new_name),
14715 cx,
14716 )
14717 .await?;
14718
14719 editor.update(cx, |editor, cx| {
14720 editor.refresh_document_highlights(cx);
14721 })?;
14722 Ok(())
14723 }))
14724 }
14725
14726 fn take_rename(
14727 &mut self,
14728 moving_cursor: bool,
14729 window: &mut Window,
14730 cx: &mut Context<Self>,
14731 ) -> Option<RenameState> {
14732 let rename = self.pending_rename.take()?;
14733 if rename.editor.focus_handle(cx).is_focused(window) {
14734 window.focus(&self.focus_handle);
14735 }
14736
14737 self.remove_blocks(
14738 [rename.block_id].into_iter().collect(),
14739 Some(Autoscroll::fit()),
14740 cx,
14741 );
14742 self.clear_highlights::<Rename>(cx);
14743 self.show_local_selections = true;
14744
14745 if moving_cursor {
14746 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14747 editor.selections.newest::<usize>(cx).head()
14748 });
14749
14750 // Update the selection to match the position of the selection inside
14751 // the rename editor.
14752 let snapshot = self.buffer.read(cx).read(cx);
14753 let rename_range = rename.range.to_offset(&snapshot);
14754 let cursor_in_editor = snapshot
14755 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14756 .min(rename_range.end);
14757 drop(snapshot);
14758
14759 self.change_selections(None, window, cx, |s| {
14760 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14761 });
14762 } else {
14763 self.refresh_document_highlights(cx);
14764 }
14765
14766 Some(rename)
14767 }
14768
14769 pub fn pending_rename(&self) -> Option<&RenameState> {
14770 self.pending_rename.as_ref()
14771 }
14772
14773 fn format(
14774 &mut self,
14775 _: &Format,
14776 window: &mut Window,
14777 cx: &mut Context<Self>,
14778 ) -> Option<Task<Result<()>>> {
14779 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14780
14781 let project = match &self.project {
14782 Some(project) => project.clone(),
14783 None => return None,
14784 };
14785
14786 Some(self.perform_format(
14787 project,
14788 FormatTrigger::Manual,
14789 FormatTarget::Buffers,
14790 window,
14791 cx,
14792 ))
14793 }
14794
14795 fn format_selections(
14796 &mut self,
14797 _: &FormatSelections,
14798 window: &mut Window,
14799 cx: &mut Context<Self>,
14800 ) -> Option<Task<Result<()>>> {
14801 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14802
14803 let project = match &self.project {
14804 Some(project) => project.clone(),
14805 None => return None,
14806 };
14807
14808 let ranges = self
14809 .selections
14810 .all_adjusted(cx)
14811 .into_iter()
14812 .map(|selection| selection.range())
14813 .collect_vec();
14814
14815 Some(self.perform_format(
14816 project,
14817 FormatTrigger::Manual,
14818 FormatTarget::Ranges(ranges),
14819 window,
14820 cx,
14821 ))
14822 }
14823
14824 fn perform_format(
14825 &mut self,
14826 project: Entity<Project>,
14827 trigger: FormatTrigger,
14828 target: FormatTarget,
14829 window: &mut Window,
14830 cx: &mut Context<Self>,
14831 ) -> Task<Result<()>> {
14832 let buffer = self.buffer.clone();
14833 let (buffers, target) = match target {
14834 FormatTarget::Buffers => {
14835 let mut buffers = buffer.read(cx).all_buffers();
14836 if trigger == FormatTrigger::Save {
14837 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14838 }
14839 (buffers, LspFormatTarget::Buffers)
14840 }
14841 FormatTarget::Ranges(selection_ranges) => {
14842 let multi_buffer = buffer.read(cx);
14843 let snapshot = multi_buffer.read(cx);
14844 let mut buffers = HashSet::default();
14845 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14846 BTreeMap::new();
14847 for selection_range in selection_ranges {
14848 for (buffer, buffer_range, _) in
14849 snapshot.range_to_buffer_ranges(selection_range)
14850 {
14851 let buffer_id = buffer.remote_id();
14852 let start = buffer.anchor_before(buffer_range.start);
14853 let end = buffer.anchor_after(buffer_range.end);
14854 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14855 buffer_id_to_ranges
14856 .entry(buffer_id)
14857 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14858 .or_insert_with(|| vec![start..end]);
14859 }
14860 }
14861 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14862 }
14863 };
14864
14865 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14866 let selections_prev = transaction_id_prev
14867 .and_then(|transaction_id_prev| {
14868 // default to selections as they were after the last edit, if we have them,
14869 // instead of how they are now.
14870 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14871 // will take you back to where you made the last edit, instead of staying where you scrolled
14872 self.selection_history
14873 .transaction(transaction_id_prev)
14874 .map(|t| t.0.clone())
14875 })
14876 .unwrap_or_else(|| {
14877 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14878 self.selections.disjoint_anchors()
14879 });
14880
14881 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14882 let format = project.update(cx, |project, cx| {
14883 project.format(buffers, target, true, trigger, cx)
14884 });
14885
14886 cx.spawn_in(window, async move |editor, cx| {
14887 let transaction = futures::select_biased! {
14888 transaction = format.log_err().fuse() => transaction,
14889 () = timeout => {
14890 log::warn!("timed out waiting for formatting");
14891 None
14892 }
14893 };
14894
14895 buffer
14896 .update(cx, |buffer, cx| {
14897 if let Some(transaction) = transaction {
14898 if !buffer.is_singleton() {
14899 buffer.push_transaction(&transaction.0, cx);
14900 }
14901 }
14902 cx.notify();
14903 })
14904 .ok();
14905
14906 if let Some(transaction_id_now) =
14907 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14908 {
14909 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14910 if has_new_transaction {
14911 _ = editor.update(cx, |editor, _| {
14912 editor
14913 .selection_history
14914 .insert_transaction(transaction_id_now, selections_prev);
14915 });
14916 }
14917 }
14918
14919 Ok(())
14920 })
14921 }
14922
14923 fn organize_imports(
14924 &mut self,
14925 _: &OrganizeImports,
14926 window: &mut Window,
14927 cx: &mut Context<Self>,
14928 ) -> Option<Task<Result<()>>> {
14929 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14930 let project = match &self.project {
14931 Some(project) => project.clone(),
14932 None => return None,
14933 };
14934 Some(self.perform_code_action_kind(
14935 project,
14936 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14937 window,
14938 cx,
14939 ))
14940 }
14941
14942 fn perform_code_action_kind(
14943 &mut self,
14944 project: Entity<Project>,
14945 kind: CodeActionKind,
14946 window: &mut Window,
14947 cx: &mut Context<Self>,
14948 ) -> Task<Result<()>> {
14949 let buffer = self.buffer.clone();
14950 let buffers = buffer.read(cx).all_buffers();
14951 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14952 let apply_action = project.update(cx, |project, cx| {
14953 project.apply_code_action_kind(buffers, kind, true, cx)
14954 });
14955 cx.spawn_in(window, async move |_, cx| {
14956 let transaction = futures::select_biased! {
14957 () = timeout => {
14958 log::warn!("timed out waiting for executing code action");
14959 None
14960 }
14961 transaction = apply_action.log_err().fuse() => transaction,
14962 };
14963 buffer
14964 .update(cx, |buffer, cx| {
14965 // check if we need this
14966 if let Some(transaction) = transaction {
14967 if !buffer.is_singleton() {
14968 buffer.push_transaction(&transaction.0, cx);
14969 }
14970 }
14971 cx.notify();
14972 })
14973 .ok();
14974 Ok(())
14975 })
14976 }
14977
14978 fn restart_language_server(
14979 &mut self,
14980 _: &RestartLanguageServer,
14981 _: &mut Window,
14982 cx: &mut Context<Self>,
14983 ) {
14984 if let Some(project) = self.project.clone() {
14985 self.buffer.update(cx, |multi_buffer, cx| {
14986 project.update(cx, |project, cx| {
14987 project.restart_language_servers_for_buffers(
14988 multi_buffer.all_buffers().into_iter().collect(),
14989 cx,
14990 );
14991 });
14992 })
14993 }
14994 }
14995
14996 fn stop_language_server(
14997 &mut self,
14998 _: &StopLanguageServer,
14999 _: &mut Window,
15000 cx: &mut Context<Self>,
15001 ) {
15002 if let Some(project) = self.project.clone() {
15003 self.buffer.update(cx, |multi_buffer, cx| {
15004 project.update(cx, |project, cx| {
15005 project.stop_language_servers_for_buffers(
15006 multi_buffer.all_buffers().into_iter().collect(),
15007 cx,
15008 );
15009 cx.emit(project::Event::RefreshInlayHints);
15010 });
15011 });
15012 }
15013 }
15014
15015 fn cancel_language_server_work(
15016 workspace: &mut Workspace,
15017 _: &actions::CancelLanguageServerWork,
15018 _: &mut Window,
15019 cx: &mut Context<Workspace>,
15020 ) {
15021 let project = workspace.project();
15022 let buffers = workspace
15023 .active_item(cx)
15024 .and_then(|item| item.act_as::<Editor>(cx))
15025 .map_or(HashSet::default(), |editor| {
15026 editor.read(cx).buffer.read(cx).all_buffers()
15027 });
15028 project.update(cx, |project, cx| {
15029 project.cancel_language_server_work_for_buffers(buffers, cx);
15030 });
15031 }
15032
15033 fn show_character_palette(
15034 &mut self,
15035 _: &ShowCharacterPalette,
15036 window: &mut Window,
15037 _: &mut Context<Self>,
15038 ) {
15039 window.show_character_palette();
15040 }
15041
15042 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
15043 if self.mode.is_minimap() {
15044 return;
15045 }
15046
15047 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
15048 let buffer = self.buffer.read(cx).snapshot(cx);
15049 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
15050 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
15051 let is_valid = buffer
15052 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
15053 .any(|entry| {
15054 entry.diagnostic.is_primary
15055 && !entry.range.is_empty()
15056 && entry.range.start == primary_range_start
15057 && entry.diagnostic.message == active_diagnostics.active_message
15058 });
15059
15060 if !is_valid {
15061 self.dismiss_diagnostics(cx);
15062 }
15063 }
15064 }
15065
15066 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15067 match &self.active_diagnostics {
15068 ActiveDiagnostic::Group(group) => Some(group),
15069 _ => None,
15070 }
15071 }
15072
15073 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15074 self.dismiss_diagnostics(cx);
15075 self.active_diagnostics = ActiveDiagnostic::All;
15076 }
15077
15078 fn activate_diagnostics(
15079 &mut self,
15080 buffer_id: BufferId,
15081 diagnostic: DiagnosticEntry<usize>,
15082 window: &mut Window,
15083 cx: &mut Context<Self>,
15084 ) {
15085 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15086 return;
15087 }
15088 self.dismiss_diagnostics(cx);
15089 let snapshot = self.snapshot(window, cx);
15090 let buffer = self.buffer.read(cx).snapshot(cx);
15091 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15092 return;
15093 };
15094
15095 let diagnostic_group = buffer
15096 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15097 .collect::<Vec<_>>();
15098
15099 let blocks =
15100 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15101
15102 let blocks = self.display_map.update(cx, |display_map, cx| {
15103 display_map.insert_blocks(blocks, cx).into_iter().collect()
15104 });
15105 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15106 active_range: buffer.anchor_before(diagnostic.range.start)
15107 ..buffer.anchor_after(diagnostic.range.end),
15108 active_message: diagnostic.diagnostic.message.clone(),
15109 group_id: diagnostic.diagnostic.group_id,
15110 blocks,
15111 });
15112 cx.notify();
15113 }
15114
15115 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15116 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15117 return;
15118 };
15119
15120 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15121 if let ActiveDiagnostic::Group(group) = prev {
15122 self.display_map.update(cx, |display_map, cx| {
15123 display_map.remove_blocks(group.blocks, cx);
15124 });
15125 cx.notify();
15126 }
15127 }
15128
15129 /// Disable inline diagnostics rendering for this editor.
15130 pub fn disable_inline_diagnostics(&mut self) {
15131 self.inline_diagnostics_enabled = false;
15132 self.inline_diagnostics_update = Task::ready(());
15133 self.inline_diagnostics.clear();
15134 }
15135
15136 pub fn diagnostics_enabled(&self) -> bool {
15137 self.mode.is_full()
15138 }
15139
15140 pub fn inline_diagnostics_enabled(&self) -> bool {
15141 self.diagnostics_enabled() && self.inline_diagnostics_enabled
15142 }
15143
15144 pub fn show_inline_diagnostics(&self) -> bool {
15145 self.show_inline_diagnostics
15146 }
15147
15148 pub fn toggle_inline_diagnostics(
15149 &mut self,
15150 _: &ToggleInlineDiagnostics,
15151 window: &mut Window,
15152 cx: &mut Context<Editor>,
15153 ) {
15154 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15155 self.refresh_inline_diagnostics(false, window, cx);
15156 }
15157
15158 pub fn set_max_diagnostics_severity(&mut self, severity: DiagnosticSeverity, cx: &mut App) {
15159 self.diagnostics_max_severity = severity;
15160 self.display_map.update(cx, |display_map, _| {
15161 display_map.diagnostics_max_severity = self.diagnostics_max_severity;
15162 });
15163 }
15164
15165 pub fn toggle_diagnostics(
15166 &mut self,
15167 _: &ToggleDiagnostics,
15168 window: &mut Window,
15169 cx: &mut Context<Editor>,
15170 ) {
15171 if !self.diagnostics_enabled() {
15172 return;
15173 }
15174
15175 let new_severity = if self.diagnostics_max_severity == DiagnosticSeverity::Off {
15176 EditorSettings::get_global(cx)
15177 .diagnostics_max_severity
15178 .filter(|severity| severity != &DiagnosticSeverity::Off)
15179 .unwrap_or(DiagnosticSeverity::Hint)
15180 } else {
15181 DiagnosticSeverity::Off
15182 };
15183 self.set_max_diagnostics_severity(new_severity, cx);
15184 if self.diagnostics_max_severity == DiagnosticSeverity::Off {
15185 self.active_diagnostics = ActiveDiagnostic::None;
15186 self.inline_diagnostics_update = Task::ready(());
15187 self.inline_diagnostics.clear();
15188 } else {
15189 self.refresh_inline_diagnostics(false, window, cx);
15190 }
15191
15192 cx.notify();
15193 }
15194
15195 pub fn toggle_minimap(
15196 &mut self,
15197 _: &ToggleMinimap,
15198 window: &mut Window,
15199 cx: &mut Context<Editor>,
15200 ) {
15201 if self.supports_minimap(cx) {
15202 self.set_minimap_visibility(self.minimap_visibility.toggle_visibility(), window, cx);
15203 }
15204 }
15205
15206 fn refresh_inline_diagnostics(
15207 &mut self,
15208 debounce: bool,
15209 window: &mut Window,
15210 cx: &mut Context<Self>,
15211 ) {
15212 let max_severity = ProjectSettings::get_global(cx)
15213 .diagnostics
15214 .inline
15215 .max_severity
15216 .unwrap_or(self.diagnostics_max_severity);
15217
15218 if self.mode.is_minimap()
15219 || !self.inline_diagnostics_enabled()
15220 || !self.show_inline_diagnostics
15221 || max_severity == DiagnosticSeverity::Off
15222 {
15223 self.inline_diagnostics_update = Task::ready(());
15224 self.inline_diagnostics.clear();
15225 return;
15226 }
15227
15228 let debounce_ms = ProjectSettings::get_global(cx)
15229 .diagnostics
15230 .inline
15231 .update_debounce_ms;
15232 let debounce = if debounce && debounce_ms > 0 {
15233 Some(Duration::from_millis(debounce_ms))
15234 } else {
15235 None
15236 };
15237 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15238 let editor = editor.upgrade().unwrap();
15239
15240 if let Some(debounce) = debounce {
15241 cx.background_executor().timer(debounce).await;
15242 }
15243 let Some(snapshot) = editor
15244 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15245 .ok()
15246 else {
15247 return;
15248 };
15249
15250 let new_inline_diagnostics = cx
15251 .background_spawn(async move {
15252 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15253 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15254 let message = diagnostic_entry
15255 .diagnostic
15256 .message
15257 .split_once('\n')
15258 .map(|(line, _)| line)
15259 .map(SharedString::new)
15260 .unwrap_or_else(|| {
15261 SharedString::from(diagnostic_entry.diagnostic.message)
15262 });
15263 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15264 let (Ok(i) | Err(i)) = inline_diagnostics
15265 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15266 inline_diagnostics.insert(
15267 i,
15268 (
15269 start_anchor,
15270 InlineDiagnostic {
15271 message,
15272 group_id: diagnostic_entry.diagnostic.group_id,
15273 start: diagnostic_entry.range.start.to_point(&snapshot),
15274 is_primary: diagnostic_entry.diagnostic.is_primary,
15275 severity: diagnostic_entry.diagnostic.severity,
15276 },
15277 ),
15278 );
15279 }
15280 inline_diagnostics
15281 })
15282 .await;
15283
15284 editor
15285 .update(cx, |editor, cx| {
15286 editor.inline_diagnostics = new_inline_diagnostics;
15287 cx.notify();
15288 })
15289 .ok();
15290 });
15291 }
15292
15293 pub fn set_selections_from_remote(
15294 &mut self,
15295 selections: Vec<Selection<Anchor>>,
15296 pending_selection: Option<Selection<Anchor>>,
15297 window: &mut Window,
15298 cx: &mut Context<Self>,
15299 ) {
15300 let old_cursor_position = self.selections.newest_anchor().head();
15301 self.selections.change_with(cx, |s| {
15302 s.select_anchors(selections);
15303 if let Some(pending_selection) = pending_selection {
15304 s.set_pending(pending_selection, SelectMode::Character);
15305 } else {
15306 s.clear_pending();
15307 }
15308 });
15309 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15310 }
15311
15312 fn push_to_selection_history(&mut self) {
15313 self.selection_history.push(SelectionHistoryEntry {
15314 selections: self.selections.disjoint_anchors(),
15315 select_next_state: self.select_next_state.clone(),
15316 select_prev_state: self.select_prev_state.clone(),
15317 add_selections_state: self.add_selections_state.clone(),
15318 });
15319 }
15320
15321 pub fn transact(
15322 &mut self,
15323 window: &mut Window,
15324 cx: &mut Context<Self>,
15325 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15326 ) -> Option<TransactionId> {
15327 self.start_transaction_at(Instant::now(), window, cx);
15328 update(self, window, cx);
15329 self.end_transaction_at(Instant::now(), cx)
15330 }
15331
15332 pub fn start_transaction_at(
15333 &mut self,
15334 now: Instant,
15335 window: &mut Window,
15336 cx: &mut Context<Self>,
15337 ) {
15338 self.end_selection(window, cx);
15339 if let Some(tx_id) = self
15340 .buffer
15341 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15342 {
15343 self.selection_history
15344 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15345 cx.emit(EditorEvent::TransactionBegun {
15346 transaction_id: tx_id,
15347 })
15348 }
15349 }
15350
15351 pub fn end_transaction_at(
15352 &mut self,
15353 now: Instant,
15354 cx: &mut Context<Self>,
15355 ) -> Option<TransactionId> {
15356 if let Some(transaction_id) = self
15357 .buffer
15358 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15359 {
15360 if let Some((_, end_selections)) =
15361 self.selection_history.transaction_mut(transaction_id)
15362 {
15363 *end_selections = Some(self.selections.disjoint_anchors());
15364 } else {
15365 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15366 }
15367
15368 cx.emit(EditorEvent::Edited { transaction_id });
15369 Some(transaction_id)
15370 } else {
15371 None
15372 }
15373 }
15374
15375 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15376 if self.selection_mark_mode {
15377 self.change_selections(None, window, cx, |s| {
15378 s.move_with(|_, sel| {
15379 sel.collapse_to(sel.head(), SelectionGoal::None);
15380 });
15381 })
15382 }
15383 self.selection_mark_mode = true;
15384 cx.notify();
15385 }
15386
15387 pub fn swap_selection_ends(
15388 &mut self,
15389 _: &actions::SwapSelectionEnds,
15390 window: &mut Window,
15391 cx: &mut Context<Self>,
15392 ) {
15393 self.change_selections(None, window, cx, |s| {
15394 s.move_with(|_, sel| {
15395 if sel.start != sel.end {
15396 sel.reversed = !sel.reversed
15397 }
15398 });
15399 });
15400 self.request_autoscroll(Autoscroll::newest(), cx);
15401 cx.notify();
15402 }
15403
15404 pub fn toggle_fold(
15405 &mut self,
15406 _: &actions::ToggleFold,
15407 window: &mut Window,
15408 cx: &mut Context<Self>,
15409 ) {
15410 if self.is_singleton(cx) {
15411 let selection = self.selections.newest::<Point>(cx);
15412
15413 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15414 let range = if selection.is_empty() {
15415 let point = selection.head().to_display_point(&display_map);
15416 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15417 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15418 .to_point(&display_map);
15419 start..end
15420 } else {
15421 selection.range()
15422 };
15423 if display_map.folds_in_range(range).next().is_some() {
15424 self.unfold_lines(&Default::default(), window, cx)
15425 } else {
15426 self.fold(&Default::default(), window, cx)
15427 }
15428 } else {
15429 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15430 let buffer_ids: HashSet<_> = self
15431 .selections
15432 .disjoint_anchor_ranges()
15433 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15434 .collect();
15435
15436 let should_unfold = buffer_ids
15437 .iter()
15438 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15439
15440 for buffer_id in buffer_ids {
15441 if should_unfold {
15442 self.unfold_buffer(buffer_id, cx);
15443 } else {
15444 self.fold_buffer(buffer_id, cx);
15445 }
15446 }
15447 }
15448 }
15449
15450 pub fn toggle_fold_recursive(
15451 &mut self,
15452 _: &actions::ToggleFoldRecursive,
15453 window: &mut Window,
15454 cx: &mut Context<Self>,
15455 ) {
15456 let selection = self.selections.newest::<Point>(cx);
15457
15458 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15459 let range = if selection.is_empty() {
15460 let point = selection.head().to_display_point(&display_map);
15461 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15462 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15463 .to_point(&display_map);
15464 start..end
15465 } else {
15466 selection.range()
15467 };
15468 if display_map.folds_in_range(range).next().is_some() {
15469 self.unfold_recursive(&Default::default(), window, cx)
15470 } else {
15471 self.fold_recursive(&Default::default(), window, cx)
15472 }
15473 }
15474
15475 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15476 if self.is_singleton(cx) {
15477 let mut to_fold = Vec::new();
15478 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15479 let selections = self.selections.all_adjusted(cx);
15480
15481 for selection in selections {
15482 let range = selection.range().sorted();
15483 let buffer_start_row = range.start.row;
15484
15485 if range.start.row != range.end.row {
15486 let mut found = false;
15487 let mut row = range.start.row;
15488 while row <= range.end.row {
15489 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15490 {
15491 found = true;
15492 row = crease.range().end.row + 1;
15493 to_fold.push(crease);
15494 } else {
15495 row += 1
15496 }
15497 }
15498 if found {
15499 continue;
15500 }
15501 }
15502
15503 for row in (0..=range.start.row).rev() {
15504 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15505 if crease.range().end.row >= buffer_start_row {
15506 to_fold.push(crease);
15507 if row <= range.start.row {
15508 break;
15509 }
15510 }
15511 }
15512 }
15513 }
15514
15515 self.fold_creases(to_fold, true, window, cx);
15516 } else {
15517 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15518 let buffer_ids = self
15519 .selections
15520 .disjoint_anchor_ranges()
15521 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15522 .collect::<HashSet<_>>();
15523 for buffer_id in buffer_ids {
15524 self.fold_buffer(buffer_id, cx);
15525 }
15526 }
15527 }
15528
15529 fn fold_at_level(
15530 &mut self,
15531 fold_at: &FoldAtLevel,
15532 window: &mut Window,
15533 cx: &mut Context<Self>,
15534 ) {
15535 if !self.buffer.read(cx).is_singleton() {
15536 return;
15537 }
15538
15539 let fold_at_level = fold_at.0;
15540 let snapshot = self.buffer.read(cx).snapshot(cx);
15541 let mut to_fold = Vec::new();
15542 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15543
15544 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15545 while start_row < end_row {
15546 match self
15547 .snapshot(window, cx)
15548 .crease_for_buffer_row(MultiBufferRow(start_row))
15549 {
15550 Some(crease) => {
15551 let nested_start_row = crease.range().start.row + 1;
15552 let nested_end_row = crease.range().end.row;
15553
15554 if current_level < fold_at_level {
15555 stack.push((nested_start_row, nested_end_row, current_level + 1));
15556 } else if current_level == fold_at_level {
15557 to_fold.push(crease);
15558 }
15559
15560 start_row = nested_end_row + 1;
15561 }
15562 None => start_row += 1,
15563 }
15564 }
15565 }
15566
15567 self.fold_creases(to_fold, true, window, cx);
15568 }
15569
15570 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15571 if self.buffer.read(cx).is_singleton() {
15572 let mut fold_ranges = Vec::new();
15573 let snapshot = self.buffer.read(cx).snapshot(cx);
15574
15575 for row in 0..snapshot.max_row().0 {
15576 if let Some(foldable_range) = self
15577 .snapshot(window, cx)
15578 .crease_for_buffer_row(MultiBufferRow(row))
15579 {
15580 fold_ranges.push(foldable_range);
15581 }
15582 }
15583
15584 self.fold_creases(fold_ranges, true, window, cx);
15585 } else {
15586 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15587 editor
15588 .update_in(cx, |editor, _, cx| {
15589 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15590 editor.fold_buffer(buffer_id, cx);
15591 }
15592 })
15593 .ok();
15594 });
15595 }
15596 }
15597
15598 pub fn fold_function_bodies(
15599 &mut self,
15600 _: &actions::FoldFunctionBodies,
15601 window: &mut Window,
15602 cx: &mut Context<Self>,
15603 ) {
15604 let snapshot = self.buffer.read(cx).snapshot(cx);
15605
15606 let ranges = snapshot
15607 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15608 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15609 .collect::<Vec<_>>();
15610
15611 let creases = ranges
15612 .into_iter()
15613 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15614 .collect();
15615
15616 self.fold_creases(creases, true, window, cx);
15617 }
15618
15619 pub fn fold_recursive(
15620 &mut self,
15621 _: &actions::FoldRecursive,
15622 window: &mut Window,
15623 cx: &mut Context<Self>,
15624 ) {
15625 let mut to_fold = Vec::new();
15626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15627 let selections = self.selections.all_adjusted(cx);
15628
15629 for selection in selections {
15630 let range = selection.range().sorted();
15631 let buffer_start_row = range.start.row;
15632
15633 if range.start.row != range.end.row {
15634 let mut found = false;
15635 for row in range.start.row..=range.end.row {
15636 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15637 found = true;
15638 to_fold.push(crease);
15639 }
15640 }
15641 if found {
15642 continue;
15643 }
15644 }
15645
15646 for row in (0..=range.start.row).rev() {
15647 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15648 if crease.range().end.row >= buffer_start_row {
15649 to_fold.push(crease);
15650 } else {
15651 break;
15652 }
15653 }
15654 }
15655 }
15656
15657 self.fold_creases(to_fold, true, window, cx);
15658 }
15659
15660 pub fn fold_at(
15661 &mut self,
15662 buffer_row: MultiBufferRow,
15663 window: &mut Window,
15664 cx: &mut Context<Self>,
15665 ) {
15666 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15667
15668 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15669 let autoscroll = self
15670 .selections
15671 .all::<Point>(cx)
15672 .iter()
15673 .any(|selection| crease.range().overlaps(&selection.range()));
15674
15675 self.fold_creases(vec![crease], autoscroll, window, cx);
15676 }
15677 }
15678
15679 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15680 if self.is_singleton(cx) {
15681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15682 let buffer = &display_map.buffer_snapshot;
15683 let selections = self.selections.all::<Point>(cx);
15684 let ranges = selections
15685 .iter()
15686 .map(|s| {
15687 let range = s.display_range(&display_map).sorted();
15688 let mut start = range.start.to_point(&display_map);
15689 let mut end = range.end.to_point(&display_map);
15690 start.column = 0;
15691 end.column = buffer.line_len(MultiBufferRow(end.row));
15692 start..end
15693 })
15694 .collect::<Vec<_>>();
15695
15696 self.unfold_ranges(&ranges, true, true, cx);
15697 } else {
15698 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15699 let buffer_ids = self
15700 .selections
15701 .disjoint_anchor_ranges()
15702 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15703 .collect::<HashSet<_>>();
15704 for buffer_id in buffer_ids {
15705 self.unfold_buffer(buffer_id, cx);
15706 }
15707 }
15708 }
15709
15710 pub fn unfold_recursive(
15711 &mut self,
15712 _: &UnfoldRecursive,
15713 _window: &mut Window,
15714 cx: &mut Context<Self>,
15715 ) {
15716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15717 let selections = self.selections.all::<Point>(cx);
15718 let ranges = selections
15719 .iter()
15720 .map(|s| {
15721 let mut range = s.display_range(&display_map).sorted();
15722 *range.start.column_mut() = 0;
15723 *range.end.column_mut() = display_map.line_len(range.end.row());
15724 let start = range.start.to_point(&display_map);
15725 let end = range.end.to_point(&display_map);
15726 start..end
15727 })
15728 .collect::<Vec<_>>();
15729
15730 self.unfold_ranges(&ranges, true, true, cx);
15731 }
15732
15733 pub fn unfold_at(
15734 &mut self,
15735 buffer_row: MultiBufferRow,
15736 _window: &mut Window,
15737 cx: &mut Context<Self>,
15738 ) {
15739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15740
15741 let intersection_range = Point::new(buffer_row.0, 0)
15742 ..Point::new(
15743 buffer_row.0,
15744 display_map.buffer_snapshot.line_len(buffer_row),
15745 );
15746
15747 let autoscroll = self
15748 .selections
15749 .all::<Point>(cx)
15750 .iter()
15751 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15752
15753 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15754 }
15755
15756 pub fn unfold_all(
15757 &mut self,
15758 _: &actions::UnfoldAll,
15759 _window: &mut Window,
15760 cx: &mut Context<Self>,
15761 ) {
15762 if self.buffer.read(cx).is_singleton() {
15763 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15764 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15765 } else {
15766 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15767 editor
15768 .update(cx, |editor, cx| {
15769 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15770 editor.unfold_buffer(buffer_id, cx);
15771 }
15772 })
15773 .ok();
15774 });
15775 }
15776 }
15777
15778 pub fn fold_selected_ranges(
15779 &mut self,
15780 _: &FoldSelectedRanges,
15781 window: &mut Window,
15782 cx: &mut Context<Self>,
15783 ) {
15784 let selections = self.selections.all_adjusted(cx);
15785 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15786 let ranges = selections
15787 .into_iter()
15788 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15789 .collect::<Vec<_>>();
15790 self.fold_creases(ranges, true, window, cx);
15791 }
15792
15793 pub fn fold_ranges<T: ToOffset + Clone>(
15794 &mut self,
15795 ranges: Vec<Range<T>>,
15796 auto_scroll: bool,
15797 window: &mut Window,
15798 cx: &mut Context<Self>,
15799 ) {
15800 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15801 let ranges = ranges
15802 .into_iter()
15803 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15804 .collect::<Vec<_>>();
15805 self.fold_creases(ranges, auto_scroll, window, cx);
15806 }
15807
15808 pub fn fold_creases<T: ToOffset + Clone>(
15809 &mut self,
15810 creases: Vec<Crease<T>>,
15811 auto_scroll: bool,
15812 _window: &mut Window,
15813 cx: &mut Context<Self>,
15814 ) {
15815 if creases.is_empty() {
15816 return;
15817 }
15818
15819 let mut buffers_affected = HashSet::default();
15820 let multi_buffer = self.buffer().read(cx);
15821 for crease in &creases {
15822 if let Some((_, buffer, _)) =
15823 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15824 {
15825 buffers_affected.insert(buffer.read(cx).remote_id());
15826 };
15827 }
15828
15829 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15830
15831 if auto_scroll {
15832 self.request_autoscroll(Autoscroll::fit(), cx);
15833 }
15834
15835 cx.notify();
15836
15837 self.scrollbar_marker_state.dirty = true;
15838 self.folds_did_change(cx);
15839 }
15840
15841 /// Removes any folds whose ranges intersect any of the given ranges.
15842 pub fn unfold_ranges<T: ToOffset + Clone>(
15843 &mut self,
15844 ranges: &[Range<T>],
15845 inclusive: bool,
15846 auto_scroll: bool,
15847 cx: &mut Context<Self>,
15848 ) {
15849 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15850 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15851 });
15852 self.folds_did_change(cx);
15853 }
15854
15855 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15856 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15857 return;
15858 }
15859 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15860 self.display_map.update(cx, |display_map, cx| {
15861 display_map.fold_buffers([buffer_id], cx)
15862 });
15863 cx.emit(EditorEvent::BufferFoldToggled {
15864 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15865 folded: true,
15866 });
15867 cx.notify();
15868 }
15869
15870 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15871 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15872 return;
15873 }
15874 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15875 self.display_map.update(cx, |display_map, cx| {
15876 display_map.unfold_buffers([buffer_id], cx);
15877 });
15878 cx.emit(EditorEvent::BufferFoldToggled {
15879 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15880 folded: false,
15881 });
15882 cx.notify();
15883 }
15884
15885 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15886 self.display_map.read(cx).is_buffer_folded(buffer)
15887 }
15888
15889 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15890 self.display_map.read(cx).folded_buffers()
15891 }
15892
15893 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15894 self.display_map.update(cx, |display_map, cx| {
15895 display_map.disable_header_for_buffer(buffer_id, cx);
15896 });
15897 cx.notify();
15898 }
15899
15900 /// Removes any folds with the given ranges.
15901 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15902 &mut self,
15903 ranges: &[Range<T>],
15904 type_id: TypeId,
15905 auto_scroll: bool,
15906 cx: &mut Context<Self>,
15907 ) {
15908 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15909 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15910 });
15911 self.folds_did_change(cx);
15912 }
15913
15914 fn remove_folds_with<T: ToOffset + Clone>(
15915 &mut self,
15916 ranges: &[Range<T>],
15917 auto_scroll: bool,
15918 cx: &mut Context<Self>,
15919 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15920 ) {
15921 if ranges.is_empty() {
15922 return;
15923 }
15924
15925 let mut buffers_affected = HashSet::default();
15926 let multi_buffer = self.buffer().read(cx);
15927 for range in ranges {
15928 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15929 buffers_affected.insert(buffer.read(cx).remote_id());
15930 };
15931 }
15932
15933 self.display_map.update(cx, update);
15934
15935 if auto_scroll {
15936 self.request_autoscroll(Autoscroll::fit(), cx);
15937 }
15938
15939 cx.notify();
15940 self.scrollbar_marker_state.dirty = true;
15941 self.active_indent_guides_state.dirty = true;
15942 }
15943
15944 pub fn update_fold_widths(
15945 &mut self,
15946 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15947 cx: &mut Context<Self>,
15948 ) -> bool {
15949 self.display_map
15950 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15951 }
15952
15953 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15954 self.display_map.read(cx).fold_placeholder.clone()
15955 }
15956
15957 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15958 self.buffer.update(cx, |buffer, cx| {
15959 buffer.set_all_diff_hunks_expanded(cx);
15960 });
15961 }
15962
15963 pub fn expand_all_diff_hunks(
15964 &mut self,
15965 _: &ExpandAllDiffHunks,
15966 _window: &mut Window,
15967 cx: &mut Context<Self>,
15968 ) {
15969 self.buffer.update(cx, |buffer, cx| {
15970 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15971 });
15972 }
15973
15974 pub fn toggle_selected_diff_hunks(
15975 &mut self,
15976 _: &ToggleSelectedDiffHunks,
15977 _window: &mut Window,
15978 cx: &mut Context<Self>,
15979 ) {
15980 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15981 self.toggle_diff_hunks_in_ranges(ranges, cx);
15982 }
15983
15984 pub fn diff_hunks_in_ranges<'a>(
15985 &'a self,
15986 ranges: &'a [Range<Anchor>],
15987 buffer: &'a MultiBufferSnapshot,
15988 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15989 ranges.iter().flat_map(move |range| {
15990 let end_excerpt_id = range.end.excerpt_id;
15991 let range = range.to_point(buffer);
15992 let mut peek_end = range.end;
15993 if range.end.row < buffer.max_row().0 {
15994 peek_end = Point::new(range.end.row + 1, 0);
15995 }
15996 buffer
15997 .diff_hunks_in_range(range.start..peek_end)
15998 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15999 })
16000 }
16001
16002 pub fn has_stageable_diff_hunks_in_ranges(
16003 &self,
16004 ranges: &[Range<Anchor>],
16005 snapshot: &MultiBufferSnapshot,
16006 ) -> bool {
16007 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
16008 hunks.any(|hunk| hunk.status().has_secondary_hunk())
16009 }
16010
16011 pub fn toggle_staged_selected_diff_hunks(
16012 &mut self,
16013 _: &::git::ToggleStaged,
16014 _: &mut Window,
16015 cx: &mut Context<Self>,
16016 ) {
16017 let snapshot = self.buffer.read(cx).snapshot(cx);
16018 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16019 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
16020 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16021 }
16022
16023 pub fn set_render_diff_hunk_controls(
16024 &mut self,
16025 render_diff_hunk_controls: RenderDiffHunkControlsFn,
16026 cx: &mut Context<Self>,
16027 ) {
16028 self.render_diff_hunk_controls = render_diff_hunk_controls;
16029 cx.notify();
16030 }
16031
16032 pub fn stage_and_next(
16033 &mut self,
16034 _: &::git::StageAndNext,
16035 window: &mut Window,
16036 cx: &mut Context<Self>,
16037 ) {
16038 self.do_stage_or_unstage_and_next(true, window, cx);
16039 }
16040
16041 pub fn unstage_and_next(
16042 &mut self,
16043 _: &::git::UnstageAndNext,
16044 window: &mut Window,
16045 cx: &mut Context<Self>,
16046 ) {
16047 self.do_stage_or_unstage_and_next(false, window, cx);
16048 }
16049
16050 pub fn stage_or_unstage_diff_hunks(
16051 &mut self,
16052 stage: bool,
16053 ranges: Vec<Range<Anchor>>,
16054 cx: &mut Context<Self>,
16055 ) {
16056 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
16057 cx.spawn(async move |this, cx| {
16058 task.await?;
16059 this.update(cx, |this, cx| {
16060 let snapshot = this.buffer.read(cx).snapshot(cx);
16061 let chunk_by = this
16062 .diff_hunks_in_ranges(&ranges, &snapshot)
16063 .chunk_by(|hunk| hunk.buffer_id);
16064 for (buffer_id, hunks) in &chunk_by {
16065 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
16066 }
16067 })
16068 })
16069 .detach_and_log_err(cx);
16070 }
16071
16072 fn save_buffers_for_ranges_if_needed(
16073 &mut self,
16074 ranges: &[Range<Anchor>],
16075 cx: &mut Context<Editor>,
16076 ) -> Task<Result<()>> {
16077 let multibuffer = self.buffer.read(cx);
16078 let snapshot = multibuffer.read(cx);
16079 let buffer_ids: HashSet<_> = ranges
16080 .iter()
16081 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
16082 .collect();
16083 drop(snapshot);
16084
16085 let mut buffers = HashSet::default();
16086 for buffer_id in buffer_ids {
16087 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
16088 let buffer = buffer_entity.read(cx);
16089 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
16090 {
16091 buffers.insert(buffer_entity);
16092 }
16093 }
16094 }
16095
16096 if let Some(project) = &self.project {
16097 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
16098 } else {
16099 Task::ready(Ok(()))
16100 }
16101 }
16102
16103 fn do_stage_or_unstage_and_next(
16104 &mut self,
16105 stage: bool,
16106 window: &mut Window,
16107 cx: &mut Context<Self>,
16108 ) {
16109 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
16110
16111 if ranges.iter().any(|range| range.start != range.end) {
16112 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16113 return;
16114 }
16115
16116 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16117 let snapshot = self.snapshot(window, cx);
16118 let position = self.selections.newest::<Point>(cx).head();
16119 let mut row = snapshot
16120 .buffer_snapshot
16121 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
16122 .find(|hunk| hunk.row_range.start.0 > position.row)
16123 .map(|hunk| hunk.row_range.start);
16124
16125 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16126 // Outside of the project diff editor, wrap around to the beginning.
16127 if !all_diff_hunks_expanded {
16128 row = row.or_else(|| {
16129 snapshot
16130 .buffer_snapshot
16131 .diff_hunks_in_range(Point::zero()..position)
16132 .find(|hunk| hunk.row_range.end.0 < position.row)
16133 .map(|hunk| hunk.row_range.start)
16134 });
16135 }
16136
16137 if let Some(row) = row {
16138 let destination = Point::new(row.0, 0);
16139 let autoscroll = Autoscroll::center();
16140
16141 self.unfold_ranges(&[destination..destination], false, false, cx);
16142 self.change_selections(Some(autoscroll), window, cx, |s| {
16143 s.select_ranges([destination..destination]);
16144 });
16145 }
16146 }
16147
16148 fn do_stage_or_unstage(
16149 &self,
16150 stage: bool,
16151 buffer_id: BufferId,
16152 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16153 cx: &mut App,
16154 ) -> Option<()> {
16155 let project = self.project.as_ref()?;
16156 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16157 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16158 let buffer_snapshot = buffer.read(cx).snapshot();
16159 let file_exists = buffer_snapshot
16160 .file()
16161 .is_some_and(|file| file.disk_state().exists());
16162 diff.update(cx, |diff, cx| {
16163 diff.stage_or_unstage_hunks(
16164 stage,
16165 &hunks
16166 .map(|hunk| buffer_diff::DiffHunk {
16167 buffer_range: hunk.buffer_range,
16168 diff_base_byte_range: hunk.diff_base_byte_range,
16169 secondary_status: hunk.secondary_status,
16170 range: Point::zero()..Point::zero(), // unused
16171 })
16172 .collect::<Vec<_>>(),
16173 &buffer_snapshot,
16174 file_exists,
16175 cx,
16176 )
16177 });
16178 None
16179 }
16180
16181 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16182 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16183 self.buffer
16184 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16185 }
16186
16187 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16188 self.buffer.update(cx, |buffer, cx| {
16189 let ranges = vec![Anchor::min()..Anchor::max()];
16190 if !buffer.all_diff_hunks_expanded()
16191 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16192 {
16193 buffer.collapse_diff_hunks(ranges, cx);
16194 true
16195 } else {
16196 false
16197 }
16198 })
16199 }
16200
16201 fn toggle_diff_hunks_in_ranges(
16202 &mut self,
16203 ranges: Vec<Range<Anchor>>,
16204 cx: &mut Context<Editor>,
16205 ) {
16206 self.buffer.update(cx, |buffer, cx| {
16207 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16208 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16209 })
16210 }
16211
16212 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16213 self.buffer.update(cx, |buffer, cx| {
16214 let snapshot = buffer.snapshot(cx);
16215 let excerpt_id = range.end.excerpt_id;
16216 let point_range = range.to_point(&snapshot);
16217 let expand = !buffer.single_hunk_is_expanded(range, cx);
16218 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16219 })
16220 }
16221
16222 pub(crate) fn apply_all_diff_hunks(
16223 &mut self,
16224 _: &ApplyAllDiffHunks,
16225 window: &mut Window,
16226 cx: &mut Context<Self>,
16227 ) {
16228 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16229
16230 let buffers = self.buffer.read(cx).all_buffers();
16231 for branch_buffer in buffers {
16232 branch_buffer.update(cx, |branch_buffer, cx| {
16233 branch_buffer.merge_into_base(Vec::new(), cx);
16234 });
16235 }
16236
16237 if let Some(project) = self.project.clone() {
16238 self.save(true, project, window, cx).detach_and_log_err(cx);
16239 }
16240 }
16241
16242 pub(crate) fn apply_selected_diff_hunks(
16243 &mut self,
16244 _: &ApplyDiffHunk,
16245 window: &mut Window,
16246 cx: &mut Context<Self>,
16247 ) {
16248 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16249 let snapshot = self.snapshot(window, cx);
16250 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16251 let mut ranges_by_buffer = HashMap::default();
16252 self.transact(window, cx, |editor, _window, cx| {
16253 for hunk in hunks {
16254 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16255 ranges_by_buffer
16256 .entry(buffer.clone())
16257 .or_insert_with(Vec::new)
16258 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16259 }
16260 }
16261
16262 for (buffer, ranges) in ranges_by_buffer {
16263 buffer.update(cx, |buffer, cx| {
16264 buffer.merge_into_base(ranges, cx);
16265 });
16266 }
16267 });
16268
16269 if let Some(project) = self.project.clone() {
16270 self.save(true, project, window, cx).detach_and_log_err(cx);
16271 }
16272 }
16273
16274 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16275 if hovered != self.gutter_hovered {
16276 self.gutter_hovered = hovered;
16277 cx.notify();
16278 }
16279 }
16280
16281 pub fn insert_blocks(
16282 &mut self,
16283 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16284 autoscroll: Option<Autoscroll>,
16285 cx: &mut Context<Self>,
16286 ) -> Vec<CustomBlockId> {
16287 let blocks = self
16288 .display_map
16289 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16290 if let Some(autoscroll) = autoscroll {
16291 self.request_autoscroll(autoscroll, cx);
16292 }
16293 cx.notify();
16294 blocks
16295 }
16296
16297 pub fn resize_blocks(
16298 &mut self,
16299 heights: HashMap<CustomBlockId, u32>,
16300 autoscroll: Option<Autoscroll>,
16301 cx: &mut Context<Self>,
16302 ) {
16303 self.display_map
16304 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16305 if let Some(autoscroll) = autoscroll {
16306 self.request_autoscroll(autoscroll, cx);
16307 }
16308 cx.notify();
16309 }
16310
16311 pub fn replace_blocks(
16312 &mut self,
16313 renderers: HashMap<CustomBlockId, RenderBlock>,
16314 autoscroll: Option<Autoscroll>,
16315 cx: &mut Context<Self>,
16316 ) {
16317 self.display_map
16318 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16319 if let Some(autoscroll) = autoscroll {
16320 self.request_autoscroll(autoscroll, cx);
16321 }
16322 cx.notify();
16323 }
16324
16325 pub fn remove_blocks(
16326 &mut self,
16327 block_ids: HashSet<CustomBlockId>,
16328 autoscroll: Option<Autoscroll>,
16329 cx: &mut Context<Self>,
16330 ) {
16331 self.display_map.update(cx, |display_map, cx| {
16332 display_map.remove_blocks(block_ids, cx)
16333 });
16334 if let Some(autoscroll) = autoscroll {
16335 self.request_autoscroll(autoscroll, cx);
16336 }
16337 cx.notify();
16338 }
16339
16340 pub fn row_for_block(
16341 &self,
16342 block_id: CustomBlockId,
16343 cx: &mut Context<Self>,
16344 ) -> Option<DisplayRow> {
16345 self.display_map
16346 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16347 }
16348
16349 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16350 self.focused_block = Some(focused_block);
16351 }
16352
16353 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16354 self.focused_block.take()
16355 }
16356
16357 pub fn insert_creases(
16358 &mut self,
16359 creases: impl IntoIterator<Item = Crease<Anchor>>,
16360 cx: &mut Context<Self>,
16361 ) -> Vec<CreaseId> {
16362 self.display_map
16363 .update(cx, |map, cx| map.insert_creases(creases, cx))
16364 }
16365
16366 pub fn remove_creases(
16367 &mut self,
16368 ids: impl IntoIterator<Item = CreaseId>,
16369 cx: &mut Context<Self>,
16370 ) -> Vec<(CreaseId, Range<Anchor>)> {
16371 self.display_map
16372 .update(cx, |map, cx| map.remove_creases(ids, cx))
16373 }
16374
16375 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16376 self.display_map
16377 .update(cx, |map, cx| map.snapshot(cx))
16378 .longest_row()
16379 }
16380
16381 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16382 self.display_map
16383 .update(cx, |map, cx| map.snapshot(cx))
16384 .max_point()
16385 }
16386
16387 pub fn text(&self, cx: &App) -> String {
16388 self.buffer.read(cx).read(cx).text()
16389 }
16390
16391 pub fn is_empty(&self, cx: &App) -> bool {
16392 self.buffer.read(cx).read(cx).is_empty()
16393 }
16394
16395 pub fn text_option(&self, cx: &App) -> Option<String> {
16396 let text = self.text(cx);
16397 let text = text.trim();
16398
16399 if text.is_empty() {
16400 return None;
16401 }
16402
16403 Some(text.to_string())
16404 }
16405
16406 pub fn set_text(
16407 &mut self,
16408 text: impl Into<Arc<str>>,
16409 window: &mut Window,
16410 cx: &mut Context<Self>,
16411 ) {
16412 self.transact(window, cx, |this, _, cx| {
16413 this.buffer
16414 .read(cx)
16415 .as_singleton()
16416 .expect("you can only call set_text on editors for singleton buffers")
16417 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16418 });
16419 }
16420
16421 pub fn display_text(&self, cx: &mut App) -> String {
16422 self.display_map
16423 .update(cx, |map, cx| map.snapshot(cx))
16424 .text()
16425 }
16426
16427 fn create_minimap(
16428 &self,
16429 minimap_settings: MinimapSettings,
16430 window: &mut Window,
16431 cx: &mut Context<Self>,
16432 ) -> Option<Entity<Self>> {
16433 (minimap_settings.minimap_enabled() && self.is_singleton(cx))
16434 .then(|| self.initialize_new_minimap(minimap_settings, window, cx))
16435 }
16436
16437 fn initialize_new_minimap(
16438 &self,
16439 minimap_settings: MinimapSettings,
16440 window: &mut Window,
16441 cx: &mut Context<Self>,
16442 ) -> Entity<Self> {
16443 const MINIMAP_FONT_WEIGHT: gpui::FontWeight = gpui::FontWeight::BLACK;
16444
16445 let mut minimap = Editor::new_internal(
16446 EditorMode::Minimap {
16447 parent: cx.weak_entity(),
16448 },
16449 self.buffer.clone(),
16450 self.project.clone(),
16451 Some(self.display_map.clone()),
16452 window,
16453 cx,
16454 );
16455 minimap.scroll_manager.clone_state(&self.scroll_manager);
16456 minimap.set_text_style_refinement(TextStyleRefinement {
16457 font_size: Some(MINIMAP_FONT_SIZE),
16458 font_weight: Some(MINIMAP_FONT_WEIGHT),
16459 ..Default::default()
16460 });
16461 minimap.update_minimap_configuration(minimap_settings, cx);
16462 cx.new(|_| minimap)
16463 }
16464
16465 fn update_minimap_configuration(&mut self, minimap_settings: MinimapSettings, cx: &App) {
16466 let current_line_highlight = minimap_settings
16467 .current_line_highlight
16468 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight);
16469 self.set_current_line_highlight(Some(current_line_highlight));
16470 }
16471
16472 pub fn minimap(&self) -> Option<&Entity<Self>> {
16473 self.minimap
16474 .as_ref()
16475 .filter(|_| self.minimap_visibility.visible())
16476 }
16477
16478 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16479 let mut wrap_guides = smallvec::smallvec![];
16480
16481 if self.show_wrap_guides == Some(false) {
16482 return wrap_guides;
16483 }
16484
16485 let settings = self.buffer.read(cx).language_settings(cx);
16486 if settings.show_wrap_guides {
16487 match self.soft_wrap_mode(cx) {
16488 SoftWrap::Column(soft_wrap) => {
16489 wrap_guides.push((soft_wrap as usize, true));
16490 }
16491 SoftWrap::Bounded(soft_wrap) => {
16492 wrap_guides.push((soft_wrap as usize, true));
16493 }
16494 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16495 }
16496 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16497 }
16498
16499 wrap_guides
16500 }
16501
16502 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16503 let settings = self.buffer.read(cx).language_settings(cx);
16504 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16505 match mode {
16506 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16507 SoftWrap::None
16508 }
16509 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16510 language_settings::SoftWrap::PreferredLineLength => {
16511 SoftWrap::Column(settings.preferred_line_length)
16512 }
16513 language_settings::SoftWrap::Bounded => {
16514 SoftWrap::Bounded(settings.preferred_line_length)
16515 }
16516 }
16517 }
16518
16519 pub fn set_soft_wrap_mode(
16520 &mut self,
16521 mode: language_settings::SoftWrap,
16522
16523 cx: &mut Context<Self>,
16524 ) {
16525 self.soft_wrap_mode_override = Some(mode);
16526 cx.notify();
16527 }
16528
16529 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16530 self.hard_wrap = hard_wrap;
16531 cx.notify();
16532 }
16533
16534 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16535 self.text_style_refinement = Some(style);
16536 }
16537
16538 /// called by the Element so we know what style we were most recently rendered with.
16539 pub(crate) fn set_style(
16540 &mut self,
16541 style: EditorStyle,
16542 window: &mut Window,
16543 cx: &mut Context<Self>,
16544 ) {
16545 // We intentionally do not inform the display map about the minimap style
16546 // so that wrapping is not recalculated and stays consistent for the editor
16547 // and its linked minimap.
16548 if !self.mode.is_minimap() {
16549 let rem_size = window.rem_size();
16550 self.display_map.update(cx, |map, cx| {
16551 map.set_font(
16552 style.text.font(),
16553 style.text.font_size.to_pixels(rem_size),
16554 cx,
16555 )
16556 });
16557 }
16558 self.style = Some(style);
16559 }
16560
16561 pub fn style(&self) -> Option<&EditorStyle> {
16562 self.style.as_ref()
16563 }
16564
16565 // Called by the element. This method is not designed to be called outside of the editor
16566 // element's layout code because it does not notify when rewrapping is computed synchronously.
16567 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16568 self.display_map
16569 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16570 }
16571
16572 pub fn set_soft_wrap(&mut self) {
16573 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16574 }
16575
16576 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16577 if self.soft_wrap_mode_override.is_some() {
16578 self.soft_wrap_mode_override.take();
16579 } else {
16580 let soft_wrap = match self.soft_wrap_mode(cx) {
16581 SoftWrap::GitDiff => return,
16582 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16583 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16584 language_settings::SoftWrap::None
16585 }
16586 };
16587 self.soft_wrap_mode_override = Some(soft_wrap);
16588 }
16589 cx.notify();
16590 }
16591
16592 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16593 let Some(workspace) = self.workspace() else {
16594 return;
16595 };
16596 let fs = workspace.read(cx).app_state().fs.clone();
16597 let current_show = TabBarSettings::get_global(cx).show;
16598 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16599 setting.show = Some(!current_show);
16600 });
16601 }
16602
16603 pub fn toggle_indent_guides(
16604 &mut self,
16605 _: &ToggleIndentGuides,
16606 _: &mut Window,
16607 cx: &mut Context<Self>,
16608 ) {
16609 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16610 self.buffer
16611 .read(cx)
16612 .language_settings(cx)
16613 .indent_guides
16614 .enabled
16615 });
16616 self.show_indent_guides = Some(!currently_enabled);
16617 cx.notify();
16618 }
16619
16620 fn should_show_indent_guides(&self) -> Option<bool> {
16621 self.show_indent_guides
16622 }
16623
16624 pub fn toggle_line_numbers(
16625 &mut self,
16626 _: &ToggleLineNumbers,
16627 _: &mut Window,
16628 cx: &mut Context<Self>,
16629 ) {
16630 let mut editor_settings = EditorSettings::get_global(cx).clone();
16631 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16632 EditorSettings::override_global(editor_settings, cx);
16633 }
16634
16635 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16636 if let Some(show_line_numbers) = self.show_line_numbers {
16637 return show_line_numbers;
16638 }
16639 EditorSettings::get_global(cx).gutter.line_numbers
16640 }
16641
16642 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16643 self.use_relative_line_numbers
16644 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16645 }
16646
16647 pub fn toggle_relative_line_numbers(
16648 &mut self,
16649 _: &ToggleRelativeLineNumbers,
16650 _: &mut Window,
16651 cx: &mut Context<Self>,
16652 ) {
16653 let is_relative = self.should_use_relative_line_numbers(cx);
16654 self.set_relative_line_number(Some(!is_relative), cx)
16655 }
16656
16657 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16658 self.use_relative_line_numbers = is_relative;
16659 cx.notify();
16660 }
16661
16662 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16663 self.show_gutter = show_gutter;
16664 cx.notify();
16665 }
16666
16667 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16668 self.show_scrollbars = show_scrollbars;
16669 cx.notify();
16670 }
16671
16672 pub fn set_minimap_visibility(
16673 &mut self,
16674 minimap_visibility: MinimapVisibility,
16675 window: &mut Window,
16676 cx: &mut Context<Self>,
16677 ) {
16678 if self.minimap_visibility != minimap_visibility {
16679 if minimap_visibility.visible() && self.minimap.is_none() {
16680 let minimap_settings = EditorSettings::get_global(cx).minimap;
16681 self.minimap =
16682 self.create_minimap(minimap_settings.with_show_override(), window, cx);
16683 }
16684 self.minimap_visibility = minimap_visibility;
16685 cx.notify();
16686 }
16687 }
16688
16689 pub fn disable_scrollbars_and_minimap(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16690 self.set_show_scrollbars(false, cx);
16691 self.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
16692 }
16693
16694 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16695 self.show_line_numbers = Some(show_line_numbers);
16696 cx.notify();
16697 }
16698
16699 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16700 self.disable_expand_excerpt_buttons = true;
16701 cx.notify();
16702 }
16703
16704 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16705 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16706 cx.notify();
16707 }
16708
16709 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16710 self.show_code_actions = Some(show_code_actions);
16711 cx.notify();
16712 }
16713
16714 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16715 self.show_runnables = Some(show_runnables);
16716 cx.notify();
16717 }
16718
16719 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16720 self.show_breakpoints = Some(show_breakpoints);
16721 cx.notify();
16722 }
16723
16724 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16725 if self.display_map.read(cx).masked != masked {
16726 self.display_map.update(cx, |map, _| map.masked = masked);
16727 }
16728 cx.notify()
16729 }
16730
16731 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16732 self.show_wrap_guides = Some(show_wrap_guides);
16733 cx.notify();
16734 }
16735
16736 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16737 self.show_indent_guides = Some(show_indent_guides);
16738 cx.notify();
16739 }
16740
16741 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16742 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16743 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16744 if let Some(dir) = file.abs_path(cx).parent() {
16745 return Some(dir.to_owned());
16746 }
16747 }
16748
16749 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16750 return Some(project_path.path.to_path_buf());
16751 }
16752 }
16753
16754 None
16755 }
16756
16757 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16758 self.active_excerpt(cx)?
16759 .1
16760 .read(cx)
16761 .file()
16762 .and_then(|f| f.as_local())
16763 }
16764
16765 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16766 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16767 let buffer = buffer.read(cx);
16768 if let Some(project_path) = buffer.project_path(cx) {
16769 let project = self.project.as_ref()?.read(cx);
16770 project.absolute_path(&project_path, cx)
16771 } else {
16772 buffer
16773 .file()
16774 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16775 }
16776 })
16777 }
16778
16779 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16780 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16781 let project_path = buffer.read(cx).project_path(cx)?;
16782 let project = self.project.as_ref()?.read(cx);
16783 let entry = project.entry_for_path(&project_path, cx)?;
16784 let path = entry.path.to_path_buf();
16785 Some(path)
16786 })
16787 }
16788
16789 pub fn reveal_in_finder(
16790 &mut self,
16791 _: &RevealInFileManager,
16792 _window: &mut Window,
16793 cx: &mut Context<Self>,
16794 ) {
16795 if let Some(target) = self.target_file(cx) {
16796 cx.reveal_path(&target.abs_path(cx));
16797 }
16798 }
16799
16800 pub fn copy_path(
16801 &mut self,
16802 _: &zed_actions::workspace::CopyPath,
16803 _window: &mut Window,
16804 cx: &mut Context<Self>,
16805 ) {
16806 if let Some(path) = self.target_file_abs_path(cx) {
16807 if let Some(path) = path.to_str() {
16808 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16809 }
16810 }
16811 }
16812
16813 pub fn copy_relative_path(
16814 &mut self,
16815 _: &zed_actions::workspace::CopyRelativePath,
16816 _window: &mut Window,
16817 cx: &mut Context<Self>,
16818 ) {
16819 if let Some(path) = self.target_file_path(cx) {
16820 if let Some(path) = path.to_str() {
16821 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16822 }
16823 }
16824 }
16825
16826 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16827 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16828 buffer.read(cx).project_path(cx)
16829 } else {
16830 None
16831 }
16832 }
16833
16834 // Returns true if the editor handled a go-to-line request
16835 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16836 maybe!({
16837 let breakpoint_store = self.breakpoint_store.as_ref()?;
16838
16839 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16840 else {
16841 self.clear_row_highlights::<ActiveDebugLine>();
16842 return None;
16843 };
16844
16845 let position = active_stack_frame.position;
16846 let buffer_id = position.buffer_id?;
16847 let snapshot = self
16848 .project
16849 .as_ref()?
16850 .read(cx)
16851 .buffer_for_id(buffer_id, cx)?
16852 .read(cx)
16853 .snapshot();
16854
16855 let mut handled = false;
16856 for (id, ExcerptRange { context, .. }) in
16857 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16858 {
16859 if context.start.cmp(&position, &snapshot).is_ge()
16860 || context.end.cmp(&position, &snapshot).is_lt()
16861 {
16862 continue;
16863 }
16864 let snapshot = self.buffer.read(cx).snapshot(cx);
16865 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16866
16867 handled = true;
16868 self.clear_row_highlights::<ActiveDebugLine>();
16869 self.go_to_line::<ActiveDebugLine>(
16870 multibuffer_anchor,
16871 Some(cx.theme().colors().editor_debugger_active_line_background),
16872 window,
16873 cx,
16874 );
16875
16876 cx.notify();
16877 }
16878
16879 handled.then_some(())
16880 })
16881 .is_some()
16882 }
16883
16884 pub fn copy_file_name_without_extension(
16885 &mut self,
16886 _: &CopyFileNameWithoutExtension,
16887 _: &mut Window,
16888 cx: &mut Context<Self>,
16889 ) {
16890 if let Some(file) = self.target_file(cx) {
16891 if let Some(file_stem) = file.path().file_stem() {
16892 if let Some(name) = file_stem.to_str() {
16893 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16894 }
16895 }
16896 }
16897 }
16898
16899 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16900 if let Some(file) = self.target_file(cx) {
16901 if let Some(file_name) = file.path().file_name() {
16902 if let Some(name) = file_name.to_str() {
16903 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16904 }
16905 }
16906 }
16907 }
16908
16909 pub fn toggle_git_blame(
16910 &mut self,
16911 _: &::git::Blame,
16912 window: &mut Window,
16913 cx: &mut Context<Self>,
16914 ) {
16915 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16916
16917 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16918 self.start_git_blame(true, window, cx);
16919 }
16920
16921 cx.notify();
16922 }
16923
16924 pub fn toggle_git_blame_inline(
16925 &mut self,
16926 _: &ToggleGitBlameInline,
16927 window: &mut Window,
16928 cx: &mut Context<Self>,
16929 ) {
16930 self.toggle_git_blame_inline_internal(true, window, cx);
16931 cx.notify();
16932 }
16933
16934 pub fn open_git_blame_commit(
16935 &mut self,
16936 _: &OpenGitBlameCommit,
16937 window: &mut Window,
16938 cx: &mut Context<Self>,
16939 ) {
16940 self.open_git_blame_commit_internal(window, cx);
16941 }
16942
16943 fn open_git_blame_commit_internal(
16944 &mut self,
16945 window: &mut Window,
16946 cx: &mut Context<Self>,
16947 ) -> Option<()> {
16948 let blame = self.blame.as_ref()?;
16949 let snapshot = self.snapshot(window, cx);
16950 let cursor = self.selections.newest::<Point>(cx).head();
16951 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16952 let blame_entry = blame
16953 .update(cx, |blame, cx| {
16954 blame
16955 .blame_for_rows(
16956 &[RowInfo {
16957 buffer_id: Some(buffer.remote_id()),
16958 buffer_row: Some(point.row),
16959 ..Default::default()
16960 }],
16961 cx,
16962 )
16963 .next()
16964 })
16965 .flatten()?;
16966 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16967 let repo = blame.read(cx).repository(cx)?;
16968 let workspace = self.workspace()?.downgrade();
16969 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16970 None
16971 }
16972
16973 pub fn git_blame_inline_enabled(&self) -> bool {
16974 self.git_blame_inline_enabled
16975 }
16976
16977 pub fn toggle_selection_menu(
16978 &mut self,
16979 _: &ToggleSelectionMenu,
16980 _: &mut Window,
16981 cx: &mut Context<Self>,
16982 ) {
16983 self.show_selection_menu = self
16984 .show_selection_menu
16985 .map(|show_selections_menu| !show_selections_menu)
16986 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16987
16988 cx.notify();
16989 }
16990
16991 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16992 self.show_selection_menu
16993 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16994 }
16995
16996 fn start_git_blame(
16997 &mut self,
16998 user_triggered: bool,
16999 window: &mut Window,
17000 cx: &mut Context<Self>,
17001 ) {
17002 if let Some(project) = self.project.as_ref() {
17003 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
17004 return;
17005 };
17006
17007 if buffer.read(cx).file().is_none() {
17008 return;
17009 }
17010
17011 let focused = self.focus_handle(cx).contains_focused(window, cx);
17012
17013 let project = project.clone();
17014 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
17015 self.blame_subscription =
17016 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
17017 self.blame = Some(blame);
17018 }
17019 }
17020
17021 fn toggle_git_blame_inline_internal(
17022 &mut self,
17023 user_triggered: bool,
17024 window: &mut Window,
17025 cx: &mut Context<Self>,
17026 ) {
17027 if self.git_blame_inline_enabled {
17028 self.git_blame_inline_enabled = false;
17029 self.show_git_blame_inline = false;
17030 self.show_git_blame_inline_delay_task.take();
17031 } else {
17032 self.git_blame_inline_enabled = true;
17033 self.start_git_blame_inline(user_triggered, window, cx);
17034 }
17035
17036 cx.notify();
17037 }
17038
17039 fn start_git_blame_inline(
17040 &mut self,
17041 user_triggered: bool,
17042 window: &mut Window,
17043 cx: &mut Context<Self>,
17044 ) {
17045 self.start_git_blame(user_triggered, window, cx);
17046
17047 if ProjectSettings::get_global(cx)
17048 .git
17049 .inline_blame_delay()
17050 .is_some()
17051 {
17052 self.start_inline_blame_timer(window, cx);
17053 } else {
17054 self.show_git_blame_inline = true
17055 }
17056 }
17057
17058 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
17059 self.blame.as_ref()
17060 }
17061
17062 pub fn show_git_blame_gutter(&self) -> bool {
17063 self.show_git_blame_gutter
17064 }
17065
17066 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
17067 !self.mode().is_minimap() && self.show_git_blame_gutter && self.has_blame_entries(cx)
17068 }
17069
17070 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
17071 self.show_git_blame_inline
17072 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
17073 && !self.newest_selection_head_on_empty_line(cx)
17074 && self.has_blame_entries(cx)
17075 }
17076
17077 fn has_blame_entries(&self, cx: &App) -> bool {
17078 self.blame()
17079 .map_or(false, |blame| blame.read(cx).has_generated_entries())
17080 }
17081
17082 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
17083 let cursor_anchor = self.selections.newest_anchor().head();
17084
17085 let snapshot = self.buffer.read(cx).snapshot(cx);
17086 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
17087
17088 snapshot.line_len(buffer_row) == 0
17089 }
17090
17091 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
17092 let buffer_and_selection = maybe!({
17093 let selection = self.selections.newest::<Point>(cx);
17094 let selection_range = selection.range();
17095
17096 let multi_buffer = self.buffer().read(cx);
17097 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17098 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
17099
17100 let (buffer, range, _) = if selection.reversed {
17101 buffer_ranges.first()
17102 } else {
17103 buffer_ranges.last()
17104 }?;
17105
17106 let selection = text::ToPoint::to_point(&range.start, &buffer).row
17107 ..text::ToPoint::to_point(&range.end, &buffer).row;
17108 Some((
17109 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
17110 selection,
17111 ))
17112 });
17113
17114 let Some((buffer, selection)) = buffer_and_selection else {
17115 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
17116 };
17117
17118 let Some(project) = self.project.as_ref() else {
17119 return Task::ready(Err(anyhow!("editor does not have project")));
17120 };
17121
17122 project.update(cx, |project, cx| {
17123 project.get_permalink_to_line(&buffer, selection, cx)
17124 })
17125 }
17126
17127 pub fn copy_permalink_to_line(
17128 &mut self,
17129 _: &CopyPermalinkToLine,
17130 window: &mut Window,
17131 cx: &mut Context<Self>,
17132 ) {
17133 let permalink_task = self.get_permalink_to_line(cx);
17134 let workspace = self.workspace();
17135
17136 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17137 Ok(permalink) => {
17138 cx.update(|_, cx| {
17139 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
17140 })
17141 .ok();
17142 }
17143 Err(err) => {
17144 let message = format!("Failed to copy permalink: {err}");
17145
17146 Err::<(), anyhow::Error>(err).log_err();
17147
17148 if let Some(workspace) = workspace {
17149 workspace
17150 .update_in(cx, |workspace, _, cx| {
17151 struct CopyPermalinkToLine;
17152
17153 workspace.show_toast(
17154 Toast::new(
17155 NotificationId::unique::<CopyPermalinkToLine>(),
17156 message,
17157 ),
17158 cx,
17159 )
17160 })
17161 .ok();
17162 }
17163 }
17164 })
17165 .detach();
17166 }
17167
17168 pub fn copy_file_location(
17169 &mut self,
17170 _: &CopyFileLocation,
17171 _: &mut Window,
17172 cx: &mut Context<Self>,
17173 ) {
17174 let selection = self.selections.newest::<Point>(cx).start.row + 1;
17175 if let Some(file) = self.target_file(cx) {
17176 if let Some(path) = file.path().to_str() {
17177 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
17178 }
17179 }
17180 }
17181
17182 pub fn open_permalink_to_line(
17183 &mut self,
17184 _: &OpenPermalinkToLine,
17185 window: &mut Window,
17186 cx: &mut Context<Self>,
17187 ) {
17188 let permalink_task = self.get_permalink_to_line(cx);
17189 let workspace = self.workspace();
17190
17191 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17192 Ok(permalink) => {
17193 cx.update(|_, cx| {
17194 cx.open_url(permalink.as_ref());
17195 })
17196 .ok();
17197 }
17198 Err(err) => {
17199 let message = format!("Failed to open permalink: {err}");
17200
17201 Err::<(), anyhow::Error>(err).log_err();
17202
17203 if let Some(workspace) = workspace {
17204 workspace
17205 .update(cx, |workspace, cx| {
17206 struct OpenPermalinkToLine;
17207
17208 workspace.show_toast(
17209 Toast::new(
17210 NotificationId::unique::<OpenPermalinkToLine>(),
17211 message,
17212 ),
17213 cx,
17214 )
17215 })
17216 .ok();
17217 }
17218 }
17219 })
17220 .detach();
17221 }
17222
17223 pub fn insert_uuid_v4(
17224 &mut self,
17225 _: &InsertUuidV4,
17226 window: &mut Window,
17227 cx: &mut Context<Self>,
17228 ) {
17229 self.insert_uuid(UuidVersion::V4, window, cx);
17230 }
17231
17232 pub fn insert_uuid_v7(
17233 &mut self,
17234 _: &InsertUuidV7,
17235 window: &mut Window,
17236 cx: &mut Context<Self>,
17237 ) {
17238 self.insert_uuid(UuidVersion::V7, window, cx);
17239 }
17240
17241 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17242 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17243 self.transact(window, cx, |this, window, cx| {
17244 let edits = this
17245 .selections
17246 .all::<Point>(cx)
17247 .into_iter()
17248 .map(|selection| {
17249 let uuid = match version {
17250 UuidVersion::V4 => uuid::Uuid::new_v4(),
17251 UuidVersion::V7 => uuid::Uuid::now_v7(),
17252 };
17253
17254 (selection.range(), uuid.to_string())
17255 });
17256 this.edit(edits, cx);
17257 this.refresh_inline_completion(true, false, window, cx);
17258 });
17259 }
17260
17261 pub fn open_selections_in_multibuffer(
17262 &mut self,
17263 _: &OpenSelectionsInMultibuffer,
17264 window: &mut Window,
17265 cx: &mut Context<Self>,
17266 ) {
17267 let multibuffer = self.buffer.read(cx);
17268
17269 let Some(buffer) = multibuffer.as_singleton() else {
17270 return;
17271 };
17272
17273 let Some(workspace) = self.workspace() else {
17274 return;
17275 };
17276
17277 let locations = self
17278 .selections
17279 .disjoint_anchors()
17280 .iter()
17281 .map(|range| Location {
17282 buffer: buffer.clone(),
17283 range: range.start.text_anchor..range.end.text_anchor,
17284 })
17285 .collect::<Vec<_>>();
17286
17287 let title = multibuffer.title(cx).to_string();
17288
17289 cx.spawn_in(window, async move |_, cx| {
17290 workspace.update_in(cx, |workspace, window, cx| {
17291 Self::open_locations_in_multibuffer(
17292 workspace,
17293 locations,
17294 format!("Selections for '{title}'"),
17295 false,
17296 MultibufferSelectionMode::All,
17297 window,
17298 cx,
17299 );
17300 })
17301 })
17302 .detach();
17303 }
17304
17305 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17306 /// last highlight added will be used.
17307 ///
17308 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17309 pub fn highlight_rows<T: 'static>(
17310 &mut self,
17311 range: Range<Anchor>,
17312 color: Hsla,
17313 options: RowHighlightOptions,
17314 cx: &mut Context<Self>,
17315 ) {
17316 let snapshot = self.buffer().read(cx).snapshot(cx);
17317 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17318 let ix = row_highlights.binary_search_by(|highlight| {
17319 Ordering::Equal
17320 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17321 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17322 });
17323
17324 if let Err(mut ix) = ix {
17325 let index = post_inc(&mut self.highlight_order);
17326
17327 // If this range intersects with the preceding highlight, then merge it with
17328 // the preceding highlight. Otherwise insert a new highlight.
17329 let mut merged = false;
17330 if ix > 0 {
17331 let prev_highlight = &mut row_highlights[ix - 1];
17332 if prev_highlight
17333 .range
17334 .end
17335 .cmp(&range.start, &snapshot)
17336 .is_ge()
17337 {
17338 ix -= 1;
17339 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17340 prev_highlight.range.end = range.end;
17341 }
17342 merged = true;
17343 prev_highlight.index = index;
17344 prev_highlight.color = color;
17345 prev_highlight.options = options;
17346 }
17347 }
17348
17349 if !merged {
17350 row_highlights.insert(
17351 ix,
17352 RowHighlight {
17353 range: range.clone(),
17354 index,
17355 color,
17356 options,
17357 type_id: TypeId::of::<T>(),
17358 },
17359 );
17360 }
17361
17362 // If any of the following highlights intersect with this one, merge them.
17363 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17364 let highlight = &row_highlights[ix];
17365 if next_highlight
17366 .range
17367 .start
17368 .cmp(&highlight.range.end, &snapshot)
17369 .is_le()
17370 {
17371 if next_highlight
17372 .range
17373 .end
17374 .cmp(&highlight.range.end, &snapshot)
17375 .is_gt()
17376 {
17377 row_highlights[ix].range.end = next_highlight.range.end;
17378 }
17379 row_highlights.remove(ix + 1);
17380 } else {
17381 break;
17382 }
17383 }
17384 }
17385 }
17386
17387 /// Remove any highlighted row ranges of the given type that intersect the
17388 /// given ranges.
17389 pub fn remove_highlighted_rows<T: 'static>(
17390 &mut self,
17391 ranges_to_remove: Vec<Range<Anchor>>,
17392 cx: &mut Context<Self>,
17393 ) {
17394 let snapshot = self.buffer().read(cx).snapshot(cx);
17395 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17396 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17397 row_highlights.retain(|highlight| {
17398 while let Some(range_to_remove) = ranges_to_remove.peek() {
17399 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17400 Ordering::Less | Ordering::Equal => {
17401 ranges_to_remove.next();
17402 }
17403 Ordering::Greater => {
17404 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17405 Ordering::Less | Ordering::Equal => {
17406 return false;
17407 }
17408 Ordering::Greater => break,
17409 }
17410 }
17411 }
17412 }
17413
17414 true
17415 })
17416 }
17417
17418 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17419 pub fn clear_row_highlights<T: 'static>(&mut self) {
17420 self.highlighted_rows.remove(&TypeId::of::<T>());
17421 }
17422
17423 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17424 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17425 self.highlighted_rows
17426 .get(&TypeId::of::<T>())
17427 .map_or(&[] as &[_], |vec| vec.as_slice())
17428 .iter()
17429 .map(|highlight| (highlight.range.clone(), highlight.color))
17430 }
17431
17432 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17433 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17434 /// Allows to ignore certain kinds of highlights.
17435 pub fn highlighted_display_rows(
17436 &self,
17437 window: &mut Window,
17438 cx: &mut App,
17439 ) -> BTreeMap<DisplayRow, LineHighlight> {
17440 let snapshot = self.snapshot(window, cx);
17441 let mut used_highlight_orders = HashMap::default();
17442 self.highlighted_rows
17443 .iter()
17444 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17445 .fold(
17446 BTreeMap::<DisplayRow, LineHighlight>::new(),
17447 |mut unique_rows, highlight| {
17448 let start = highlight.range.start.to_display_point(&snapshot);
17449 let end = highlight.range.end.to_display_point(&snapshot);
17450 let start_row = start.row().0;
17451 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17452 && end.column() == 0
17453 {
17454 end.row().0.saturating_sub(1)
17455 } else {
17456 end.row().0
17457 };
17458 for row in start_row..=end_row {
17459 let used_index =
17460 used_highlight_orders.entry(row).or_insert(highlight.index);
17461 if highlight.index >= *used_index {
17462 *used_index = highlight.index;
17463 unique_rows.insert(
17464 DisplayRow(row),
17465 LineHighlight {
17466 include_gutter: highlight.options.include_gutter,
17467 border: None,
17468 background: highlight.color.into(),
17469 type_id: Some(highlight.type_id),
17470 },
17471 );
17472 }
17473 }
17474 unique_rows
17475 },
17476 )
17477 }
17478
17479 pub fn highlighted_display_row_for_autoscroll(
17480 &self,
17481 snapshot: &DisplaySnapshot,
17482 ) -> Option<DisplayRow> {
17483 self.highlighted_rows
17484 .values()
17485 .flat_map(|highlighted_rows| highlighted_rows.iter())
17486 .filter_map(|highlight| {
17487 if highlight.options.autoscroll {
17488 Some(highlight.range.start.to_display_point(snapshot).row())
17489 } else {
17490 None
17491 }
17492 })
17493 .min()
17494 }
17495
17496 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17497 self.highlight_background::<SearchWithinRange>(
17498 ranges,
17499 |colors| colors.editor_document_highlight_read_background,
17500 cx,
17501 )
17502 }
17503
17504 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17505 self.breadcrumb_header = Some(new_header);
17506 }
17507
17508 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17509 self.clear_background_highlights::<SearchWithinRange>(cx);
17510 }
17511
17512 pub fn highlight_background<T: 'static>(
17513 &mut self,
17514 ranges: &[Range<Anchor>],
17515 color_fetcher: fn(&ThemeColors) -> Hsla,
17516 cx: &mut Context<Self>,
17517 ) {
17518 self.background_highlights
17519 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17520 self.scrollbar_marker_state.dirty = true;
17521 cx.notify();
17522 }
17523
17524 pub fn clear_background_highlights<T: 'static>(
17525 &mut self,
17526 cx: &mut Context<Self>,
17527 ) -> Option<BackgroundHighlight> {
17528 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17529 if !text_highlights.1.is_empty() {
17530 self.scrollbar_marker_state.dirty = true;
17531 cx.notify();
17532 }
17533 Some(text_highlights)
17534 }
17535
17536 pub fn highlight_gutter<T: 'static>(
17537 &mut self,
17538 ranges: &[Range<Anchor>],
17539 color_fetcher: fn(&App) -> Hsla,
17540 cx: &mut Context<Self>,
17541 ) {
17542 self.gutter_highlights
17543 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17544 cx.notify();
17545 }
17546
17547 pub fn clear_gutter_highlights<T: 'static>(
17548 &mut self,
17549 cx: &mut Context<Self>,
17550 ) -> Option<GutterHighlight> {
17551 cx.notify();
17552 self.gutter_highlights.remove(&TypeId::of::<T>())
17553 }
17554
17555 #[cfg(feature = "test-support")]
17556 pub fn all_text_background_highlights(
17557 &self,
17558 window: &mut Window,
17559 cx: &mut Context<Self>,
17560 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17561 let snapshot = self.snapshot(window, cx);
17562 let buffer = &snapshot.buffer_snapshot;
17563 let start = buffer.anchor_before(0);
17564 let end = buffer.anchor_after(buffer.len());
17565 let theme = cx.theme().colors();
17566 self.background_highlights_in_range(start..end, &snapshot, theme)
17567 }
17568
17569 #[cfg(feature = "test-support")]
17570 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17571 let snapshot = self.buffer().read(cx).snapshot(cx);
17572
17573 let highlights = self
17574 .background_highlights
17575 .get(&TypeId::of::<items::BufferSearchHighlights>());
17576
17577 if let Some((_color, ranges)) = highlights {
17578 ranges
17579 .iter()
17580 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17581 .collect_vec()
17582 } else {
17583 vec![]
17584 }
17585 }
17586
17587 fn document_highlights_for_position<'a>(
17588 &'a self,
17589 position: Anchor,
17590 buffer: &'a MultiBufferSnapshot,
17591 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17592 let read_highlights = self
17593 .background_highlights
17594 .get(&TypeId::of::<DocumentHighlightRead>())
17595 .map(|h| &h.1);
17596 let write_highlights = self
17597 .background_highlights
17598 .get(&TypeId::of::<DocumentHighlightWrite>())
17599 .map(|h| &h.1);
17600 let left_position = position.bias_left(buffer);
17601 let right_position = position.bias_right(buffer);
17602 read_highlights
17603 .into_iter()
17604 .chain(write_highlights)
17605 .flat_map(move |ranges| {
17606 let start_ix = match ranges.binary_search_by(|probe| {
17607 let cmp = probe.end.cmp(&left_position, buffer);
17608 if cmp.is_ge() {
17609 Ordering::Greater
17610 } else {
17611 Ordering::Less
17612 }
17613 }) {
17614 Ok(i) | Err(i) => i,
17615 };
17616
17617 ranges[start_ix..]
17618 .iter()
17619 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17620 })
17621 }
17622
17623 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17624 self.background_highlights
17625 .get(&TypeId::of::<T>())
17626 .map_or(false, |(_, highlights)| !highlights.is_empty())
17627 }
17628
17629 pub fn background_highlights_in_range(
17630 &self,
17631 search_range: Range<Anchor>,
17632 display_snapshot: &DisplaySnapshot,
17633 theme: &ThemeColors,
17634 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17635 let mut results = Vec::new();
17636 for (color_fetcher, ranges) in self.background_highlights.values() {
17637 let color = color_fetcher(theme);
17638 let start_ix = match ranges.binary_search_by(|probe| {
17639 let cmp = probe
17640 .end
17641 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17642 if cmp.is_gt() {
17643 Ordering::Greater
17644 } else {
17645 Ordering::Less
17646 }
17647 }) {
17648 Ok(i) | Err(i) => i,
17649 };
17650 for range in &ranges[start_ix..] {
17651 if range
17652 .start
17653 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17654 .is_ge()
17655 {
17656 break;
17657 }
17658
17659 let start = range.start.to_display_point(display_snapshot);
17660 let end = range.end.to_display_point(display_snapshot);
17661 results.push((start..end, color))
17662 }
17663 }
17664 results
17665 }
17666
17667 pub fn background_highlight_row_ranges<T: 'static>(
17668 &self,
17669 search_range: Range<Anchor>,
17670 display_snapshot: &DisplaySnapshot,
17671 count: usize,
17672 ) -> Vec<RangeInclusive<DisplayPoint>> {
17673 let mut results = Vec::new();
17674 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17675 return vec![];
17676 };
17677
17678 let start_ix = match ranges.binary_search_by(|probe| {
17679 let cmp = probe
17680 .end
17681 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17682 if cmp.is_gt() {
17683 Ordering::Greater
17684 } else {
17685 Ordering::Less
17686 }
17687 }) {
17688 Ok(i) | Err(i) => i,
17689 };
17690 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17691 if let (Some(start_display), Some(end_display)) = (start, end) {
17692 results.push(
17693 start_display.to_display_point(display_snapshot)
17694 ..=end_display.to_display_point(display_snapshot),
17695 );
17696 }
17697 };
17698 let mut start_row: Option<Point> = None;
17699 let mut end_row: Option<Point> = None;
17700 if ranges.len() > count {
17701 return Vec::new();
17702 }
17703 for range in &ranges[start_ix..] {
17704 if range
17705 .start
17706 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17707 .is_ge()
17708 {
17709 break;
17710 }
17711 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17712 if let Some(current_row) = &end_row {
17713 if end.row == current_row.row {
17714 continue;
17715 }
17716 }
17717 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17718 if start_row.is_none() {
17719 assert_eq!(end_row, None);
17720 start_row = Some(start);
17721 end_row = Some(end);
17722 continue;
17723 }
17724 if let Some(current_end) = end_row.as_mut() {
17725 if start.row > current_end.row + 1 {
17726 push_region(start_row, end_row);
17727 start_row = Some(start);
17728 end_row = Some(end);
17729 } else {
17730 // Merge two hunks.
17731 *current_end = end;
17732 }
17733 } else {
17734 unreachable!();
17735 }
17736 }
17737 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17738 push_region(start_row, end_row);
17739 results
17740 }
17741
17742 pub fn gutter_highlights_in_range(
17743 &self,
17744 search_range: Range<Anchor>,
17745 display_snapshot: &DisplaySnapshot,
17746 cx: &App,
17747 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17748 let mut results = Vec::new();
17749 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17750 let color = color_fetcher(cx);
17751 let start_ix = match ranges.binary_search_by(|probe| {
17752 let cmp = probe
17753 .end
17754 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17755 if cmp.is_gt() {
17756 Ordering::Greater
17757 } else {
17758 Ordering::Less
17759 }
17760 }) {
17761 Ok(i) | Err(i) => i,
17762 };
17763 for range in &ranges[start_ix..] {
17764 if range
17765 .start
17766 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17767 .is_ge()
17768 {
17769 break;
17770 }
17771
17772 let start = range.start.to_display_point(display_snapshot);
17773 let end = range.end.to_display_point(display_snapshot);
17774 results.push((start..end, color))
17775 }
17776 }
17777 results
17778 }
17779
17780 /// Get the text ranges corresponding to the redaction query
17781 pub fn redacted_ranges(
17782 &self,
17783 search_range: Range<Anchor>,
17784 display_snapshot: &DisplaySnapshot,
17785 cx: &App,
17786 ) -> Vec<Range<DisplayPoint>> {
17787 display_snapshot
17788 .buffer_snapshot
17789 .redacted_ranges(search_range, |file| {
17790 if let Some(file) = file {
17791 file.is_private()
17792 && EditorSettings::get(
17793 Some(SettingsLocation {
17794 worktree_id: file.worktree_id(cx),
17795 path: file.path().as_ref(),
17796 }),
17797 cx,
17798 )
17799 .redact_private_values
17800 } else {
17801 false
17802 }
17803 })
17804 .map(|range| {
17805 range.start.to_display_point(display_snapshot)
17806 ..range.end.to_display_point(display_snapshot)
17807 })
17808 .collect()
17809 }
17810
17811 pub fn highlight_text<T: 'static>(
17812 &mut self,
17813 ranges: Vec<Range<Anchor>>,
17814 style: HighlightStyle,
17815 cx: &mut Context<Self>,
17816 ) {
17817 self.display_map.update(cx, |map, _| {
17818 map.highlight_text(TypeId::of::<T>(), ranges, style)
17819 });
17820 cx.notify();
17821 }
17822
17823 pub(crate) fn highlight_inlays<T: 'static>(
17824 &mut self,
17825 highlights: Vec<InlayHighlight>,
17826 style: HighlightStyle,
17827 cx: &mut Context<Self>,
17828 ) {
17829 self.display_map.update(cx, |map, _| {
17830 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17831 });
17832 cx.notify();
17833 }
17834
17835 pub fn text_highlights<'a, T: 'static>(
17836 &'a self,
17837 cx: &'a App,
17838 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17839 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17840 }
17841
17842 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17843 let cleared = self
17844 .display_map
17845 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17846 if cleared {
17847 cx.notify();
17848 }
17849 }
17850
17851 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17852 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17853 && self.focus_handle.is_focused(window)
17854 }
17855
17856 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17857 self.show_cursor_when_unfocused = is_enabled;
17858 cx.notify();
17859 }
17860
17861 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17862 cx.notify();
17863 }
17864
17865 fn on_debug_session_event(
17866 &mut self,
17867 _session: Entity<Session>,
17868 event: &SessionEvent,
17869 cx: &mut Context<Self>,
17870 ) {
17871 match event {
17872 SessionEvent::InvalidateInlineValue => {
17873 self.refresh_inline_values(cx);
17874 }
17875 _ => {}
17876 }
17877 }
17878
17879 pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17880 let Some(project) = self.project.clone() else {
17881 return;
17882 };
17883 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17884 return;
17885 };
17886 if !self.inline_value_cache.enabled {
17887 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17888 self.splice_inlays(&inlays, Vec::new(), cx);
17889 return;
17890 }
17891
17892 let current_execution_position = self
17893 .highlighted_rows
17894 .get(&TypeId::of::<ActiveDebugLine>())
17895 .and_then(|lines| lines.last().map(|line| line.range.start));
17896
17897 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17898 let snapshot = editor
17899 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17900 .ok()?;
17901
17902 let inline_values = editor
17903 .update(cx, |_, cx| {
17904 let Some(current_execution_position) = current_execution_position else {
17905 return Some(Task::ready(Ok(Vec::new())));
17906 };
17907
17908 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17909 // anchor is in the same buffer
17910 let range =
17911 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17912 project.inline_values(buffer, range, cx)
17913 })
17914 .ok()
17915 .flatten()?
17916 .await
17917 .context("refreshing debugger inlays")
17918 .log_err()?;
17919
17920 let (excerpt_id, buffer_id) = snapshot
17921 .excerpts()
17922 .next()
17923 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17924 editor
17925 .update(cx, |editor, cx| {
17926 let new_inlays = inline_values
17927 .into_iter()
17928 .map(|debugger_value| {
17929 Inlay::debugger_hint(
17930 post_inc(&mut editor.next_inlay_id),
17931 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17932 debugger_value.text(),
17933 )
17934 })
17935 .collect::<Vec<_>>();
17936 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17937 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17938
17939 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17940 })
17941 .ok()?;
17942 Some(())
17943 });
17944 }
17945
17946 fn on_buffer_event(
17947 &mut self,
17948 multibuffer: &Entity<MultiBuffer>,
17949 event: &multi_buffer::Event,
17950 window: &mut Window,
17951 cx: &mut Context<Self>,
17952 ) {
17953 match event {
17954 multi_buffer::Event::Edited {
17955 singleton_buffer_edited,
17956 edited_buffer: buffer_edited,
17957 } => {
17958 self.scrollbar_marker_state.dirty = true;
17959 self.active_indent_guides_state.dirty = true;
17960 self.refresh_active_diagnostics(cx);
17961 self.refresh_code_actions(window, cx);
17962 self.refresh_selected_text_highlights(true, window, cx);
17963 refresh_matching_bracket_highlights(self, window, cx);
17964 if self.has_active_inline_completion() {
17965 self.update_visible_inline_completion(window, cx);
17966 }
17967 if let Some(buffer) = buffer_edited {
17968 let buffer_id = buffer.read(cx).remote_id();
17969 if !self.registered_buffers.contains_key(&buffer_id) {
17970 if let Some(project) = self.project.as_ref() {
17971 project.update(cx, |project, cx| {
17972 self.registered_buffers.insert(
17973 buffer_id,
17974 project.register_buffer_with_language_servers(&buffer, cx),
17975 );
17976 })
17977 }
17978 }
17979 }
17980 cx.emit(EditorEvent::BufferEdited);
17981 cx.emit(SearchEvent::MatchesInvalidated);
17982 if *singleton_buffer_edited {
17983 if let Some(project) = &self.project {
17984 #[allow(clippy::mutable_key_type)]
17985 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17986 multibuffer
17987 .all_buffers()
17988 .into_iter()
17989 .filter_map(|buffer| {
17990 buffer.update(cx, |buffer, cx| {
17991 let language = buffer.language()?;
17992 let should_discard = project.update(cx, |project, cx| {
17993 project.is_local()
17994 && !project.has_language_servers_for(buffer, cx)
17995 });
17996 should_discard.not().then_some(language.clone())
17997 })
17998 })
17999 .collect::<HashSet<_>>()
18000 });
18001 if !languages_affected.is_empty() {
18002 self.refresh_inlay_hints(
18003 InlayHintRefreshReason::BufferEdited(languages_affected),
18004 cx,
18005 );
18006 }
18007 }
18008 }
18009
18010 let Some(project) = &self.project else { return };
18011 let (telemetry, is_via_ssh) = {
18012 let project = project.read(cx);
18013 let telemetry = project.client().telemetry().clone();
18014 let is_via_ssh = project.is_via_ssh();
18015 (telemetry, is_via_ssh)
18016 };
18017 refresh_linked_ranges(self, window, cx);
18018 telemetry.log_edit_event("editor", is_via_ssh);
18019 }
18020 multi_buffer::Event::ExcerptsAdded {
18021 buffer,
18022 predecessor,
18023 excerpts,
18024 } => {
18025 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18026 let buffer_id = buffer.read(cx).remote_id();
18027 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
18028 if let Some(project) = &self.project {
18029 update_uncommitted_diff_for_buffer(
18030 cx.entity(),
18031 project,
18032 [buffer.clone()],
18033 self.buffer.clone(),
18034 cx,
18035 )
18036 .detach();
18037 }
18038 }
18039 cx.emit(EditorEvent::ExcerptsAdded {
18040 buffer: buffer.clone(),
18041 predecessor: *predecessor,
18042 excerpts: excerpts.clone(),
18043 });
18044 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
18045 }
18046 multi_buffer::Event::ExcerptsRemoved {
18047 ids,
18048 removed_buffer_ids,
18049 } => {
18050 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
18051 let buffer = self.buffer.read(cx);
18052 self.registered_buffers
18053 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
18054 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18055 cx.emit(EditorEvent::ExcerptsRemoved {
18056 ids: ids.clone(),
18057 removed_buffer_ids: removed_buffer_ids.clone(),
18058 })
18059 }
18060 multi_buffer::Event::ExcerptsEdited {
18061 excerpt_ids,
18062 buffer_ids,
18063 } => {
18064 self.display_map.update(cx, |map, cx| {
18065 map.unfold_buffers(buffer_ids.iter().copied(), cx)
18066 });
18067 cx.emit(EditorEvent::ExcerptsEdited {
18068 ids: excerpt_ids.clone(),
18069 })
18070 }
18071 multi_buffer::Event::ExcerptsExpanded { ids } => {
18072 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
18073 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
18074 }
18075 multi_buffer::Event::Reparsed(buffer_id) => {
18076 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18077 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18078
18079 cx.emit(EditorEvent::Reparsed(*buffer_id));
18080 }
18081 multi_buffer::Event::DiffHunksToggled => {
18082 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18083 }
18084 multi_buffer::Event::LanguageChanged(buffer_id) => {
18085 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
18086 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18087 cx.emit(EditorEvent::Reparsed(*buffer_id));
18088 cx.notify();
18089 }
18090 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
18091 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
18092 multi_buffer::Event::FileHandleChanged
18093 | multi_buffer::Event::Reloaded
18094 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
18095 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
18096 multi_buffer::Event::DiagnosticsUpdated => {
18097 self.refresh_active_diagnostics(cx);
18098 self.refresh_inline_diagnostics(true, window, cx);
18099 self.scrollbar_marker_state.dirty = true;
18100 cx.notify();
18101 }
18102 _ => {}
18103 };
18104 }
18105
18106 pub fn start_temporary_diff_override(&mut self) {
18107 self.load_diff_task.take();
18108 self.temporary_diff_override = true;
18109 }
18110
18111 pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
18112 self.temporary_diff_override = false;
18113 self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
18114 self.buffer.update(cx, |buffer, cx| {
18115 buffer.set_all_diff_hunks_collapsed(cx);
18116 });
18117
18118 if let Some(project) = self.project.clone() {
18119 self.load_diff_task = Some(
18120 update_uncommitted_diff_for_buffer(
18121 cx.entity(),
18122 &project,
18123 self.buffer.read(cx).all_buffers(),
18124 self.buffer.clone(),
18125 cx,
18126 )
18127 .shared(),
18128 );
18129 }
18130 }
18131
18132 fn on_display_map_changed(
18133 &mut self,
18134 _: Entity<DisplayMap>,
18135 _: &mut Window,
18136 cx: &mut Context<Self>,
18137 ) {
18138 cx.notify();
18139 }
18140
18141 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18142 let new_severity = if self.diagnostics_enabled() {
18143 EditorSettings::get_global(cx)
18144 .diagnostics_max_severity
18145 .unwrap_or(DiagnosticSeverity::Hint)
18146 } else {
18147 DiagnosticSeverity::Off
18148 };
18149 self.set_max_diagnostics_severity(new_severity, cx);
18150 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18151 self.update_edit_prediction_settings(cx);
18152 self.refresh_inline_completion(true, false, window, cx);
18153 self.refresh_inlay_hints(
18154 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
18155 self.selections.newest_anchor().head(),
18156 &self.buffer.read(cx).snapshot(cx),
18157 cx,
18158 )),
18159 cx,
18160 );
18161
18162 let old_cursor_shape = self.cursor_shape;
18163
18164 {
18165 let editor_settings = EditorSettings::get_global(cx);
18166 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
18167 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
18168 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
18169 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
18170 }
18171
18172 if old_cursor_shape != self.cursor_shape {
18173 cx.emit(EditorEvent::CursorShapeChanged);
18174 }
18175
18176 let project_settings = ProjectSettings::get_global(cx);
18177 self.serialize_dirty_buffers =
18178 !self.mode.is_minimap() && project_settings.session.restore_unsaved_buffers;
18179
18180 if self.mode.is_full() {
18181 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
18182 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
18183 if self.show_inline_diagnostics != show_inline_diagnostics {
18184 self.show_inline_diagnostics = show_inline_diagnostics;
18185 self.refresh_inline_diagnostics(false, window, cx);
18186 }
18187
18188 if self.git_blame_inline_enabled != inline_blame_enabled {
18189 self.toggle_git_blame_inline_internal(false, window, cx);
18190 }
18191
18192 let minimap_settings = EditorSettings::get_global(cx).minimap;
18193 if self.minimap_visibility.visible() != minimap_settings.minimap_enabled() {
18194 self.set_minimap_visibility(
18195 self.minimap_visibility.toggle_visibility(),
18196 window,
18197 cx,
18198 );
18199 } else if let Some(minimap_entity) = self.minimap.as_ref() {
18200 minimap_entity.update(cx, |minimap_editor, cx| {
18201 minimap_editor.update_minimap_configuration(minimap_settings, cx)
18202 })
18203 }
18204 }
18205
18206 cx.notify();
18207 }
18208
18209 pub fn set_searchable(&mut self, searchable: bool) {
18210 self.searchable = searchable;
18211 }
18212
18213 pub fn searchable(&self) -> bool {
18214 self.searchable
18215 }
18216
18217 fn open_proposed_changes_editor(
18218 &mut self,
18219 _: &OpenProposedChangesEditor,
18220 window: &mut Window,
18221 cx: &mut Context<Self>,
18222 ) {
18223 let Some(workspace) = self.workspace() else {
18224 cx.propagate();
18225 return;
18226 };
18227
18228 let selections = self.selections.all::<usize>(cx);
18229 let multi_buffer = self.buffer.read(cx);
18230 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18231 let mut new_selections_by_buffer = HashMap::default();
18232 for selection in selections {
18233 for (buffer, range, _) in
18234 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18235 {
18236 let mut range = range.to_point(buffer);
18237 range.start.column = 0;
18238 range.end.column = buffer.line_len(range.end.row);
18239 new_selections_by_buffer
18240 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18241 .or_insert(Vec::new())
18242 .push(range)
18243 }
18244 }
18245
18246 let proposed_changes_buffers = new_selections_by_buffer
18247 .into_iter()
18248 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18249 .collect::<Vec<_>>();
18250 let proposed_changes_editor = cx.new(|cx| {
18251 ProposedChangesEditor::new(
18252 "Proposed changes",
18253 proposed_changes_buffers,
18254 self.project.clone(),
18255 window,
18256 cx,
18257 )
18258 });
18259
18260 window.defer(cx, move |window, cx| {
18261 workspace.update(cx, |workspace, cx| {
18262 workspace.active_pane().update(cx, |pane, cx| {
18263 pane.add_item(
18264 Box::new(proposed_changes_editor),
18265 true,
18266 true,
18267 None,
18268 window,
18269 cx,
18270 );
18271 });
18272 });
18273 });
18274 }
18275
18276 pub fn open_excerpts_in_split(
18277 &mut self,
18278 _: &OpenExcerptsSplit,
18279 window: &mut Window,
18280 cx: &mut Context<Self>,
18281 ) {
18282 self.open_excerpts_common(None, true, window, cx)
18283 }
18284
18285 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18286 self.open_excerpts_common(None, false, window, cx)
18287 }
18288
18289 fn open_excerpts_common(
18290 &mut self,
18291 jump_data: Option<JumpData>,
18292 split: bool,
18293 window: &mut Window,
18294 cx: &mut Context<Self>,
18295 ) {
18296 let Some(workspace) = self.workspace() else {
18297 cx.propagate();
18298 return;
18299 };
18300
18301 if self.buffer.read(cx).is_singleton() {
18302 cx.propagate();
18303 return;
18304 }
18305
18306 let mut new_selections_by_buffer = HashMap::default();
18307 match &jump_data {
18308 Some(JumpData::MultiBufferPoint {
18309 excerpt_id,
18310 position,
18311 anchor,
18312 line_offset_from_top,
18313 }) => {
18314 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18315 if let Some(buffer) = multi_buffer_snapshot
18316 .buffer_id_for_excerpt(*excerpt_id)
18317 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18318 {
18319 let buffer_snapshot = buffer.read(cx).snapshot();
18320 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18321 language::ToPoint::to_point(anchor, &buffer_snapshot)
18322 } else {
18323 buffer_snapshot.clip_point(*position, Bias::Left)
18324 };
18325 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18326 new_selections_by_buffer.insert(
18327 buffer,
18328 (
18329 vec![jump_to_offset..jump_to_offset],
18330 Some(*line_offset_from_top),
18331 ),
18332 );
18333 }
18334 }
18335 Some(JumpData::MultiBufferRow {
18336 row,
18337 line_offset_from_top,
18338 }) => {
18339 let point = MultiBufferPoint::new(row.0, 0);
18340 if let Some((buffer, buffer_point, _)) =
18341 self.buffer.read(cx).point_to_buffer_point(point, cx)
18342 {
18343 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18344 new_selections_by_buffer
18345 .entry(buffer)
18346 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18347 .0
18348 .push(buffer_offset..buffer_offset)
18349 }
18350 }
18351 None => {
18352 let selections = self.selections.all::<usize>(cx);
18353 let multi_buffer = self.buffer.read(cx);
18354 for selection in selections {
18355 for (snapshot, range, _, anchor) in multi_buffer
18356 .snapshot(cx)
18357 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18358 {
18359 if let Some(anchor) = anchor {
18360 // selection is in a deleted hunk
18361 let Some(buffer_id) = anchor.buffer_id else {
18362 continue;
18363 };
18364 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18365 continue;
18366 };
18367 let offset = text::ToOffset::to_offset(
18368 &anchor.text_anchor,
18369 &buffer_handle.read(cx).snapshot(),
18370 );
18371 let range = offset..offset;
18372 new_selections_by_buffer
18373 .entry(buffer_handle)
18374 .or_insert((Vec::new(), None))
18375 .0
18376 .push(range)
18377 } else {
18378 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18379 else {
18380 continue;
18381 };
18382 new_selections_by_buffer
18383 .entry(buffer_handle)
18384 .or_insert((Vec::new(), None))
18385 .0
18386 .push(range)
18387 }
18388 }
18389 }
18390 }
18391 }
18392
18393 new_selections_by_buffer
18394 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18395
18396 if new_selections_by_buffer.is_empty() {
18397 return;
18398 }
18399
18400 // We defer the pane interaction because we ourselves are a workspace item
18401 // and activating a new item causes the pane to call a method on us reentrantly,
18402 // which panics if we're on the stack.
18403 window.defer(cx, move |window, cx| {
18404 workspace.update(cx, |workspace, cx| {
18405 let pane = if split {
18406 workspace.adjacent_pane(window, cx)
18407 } else {
18408 workspace.active_pane().clone()
18409 };
18410
18411 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18412 let editor = buffer
18413 .read(cx)
18414 .file()
18415 .is_none()
18416 .then(|| {
18417 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18418 // so `workspace.open_project_item` will never find them, always opening a new editor.
18419 // Instead, we try to activate the existing editor in the pane first.
18420 let (editor, pane_item_index) =
18421 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18422 let editor = item.downcast::<Editor>()?;
18423 let singleton_buffer =
18424 editor.read(cx).buffer().read(cx).as_singleton()?;
18425 if singleton_buffer == buffer {
18426 Some((editor, i))
18427 } else {
18428 None
18429 }
18430 })?;
18431 pane.update(cx, |pane, cx| {
18432 pane.activate_item(pane_item_index, true, true, window, cx)
18433 });
18434 Some(editor)
18435 })
18436 .flatten()
18437 .unwrap_or_else(|| {
18438 workspace.open_project_item::<Self>(
18439 pane.clone(),
18440 buffer,
18441 true,
18442 true,
18443 window,
18444 cx,
18445 )
18446 });
18447
18448 editor.update(cx, |editor, cx| {
18449 let autoscroll = match scroll_offset {
18450 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18451 None => Autoscroll::newest(),
18452 };
18453 let nav_history = editor.nav_history.take();
18454 editor.change_selections(Some(autoscroll), window, cx, |s| {
18455 s.select_ranges(ranges);
18456 });
18457 editor.nav_history = nav_history;
18458 });
18459 }
18460 })
18461 });
18462 }
18463
18464 // For now, don't allow opening excerpts in buffers that aren't backed by
18465 // regular project files.
18466 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18467 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18468 }
18469
18470 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18471 let snapshot = self.buffer.read(cx).read(cx);
18472 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18473 Some(
18474 ranges
18475 .iter()
18476 .map(move |range| {
18477 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18478 })
18479 .collect(),
18480 )
18481 }
18482
18483 fn selection_replacement_ranges(
18484 &self,
18485 range: Range<OffsetUtf16>,
18486 cx: &mut App,
18487 ) -> Vec<Range<OffsetUtf16>> {
18488 let selections = self.selections.all::<OffsetUtf16>(cx);
18489 let newest_selection = selections
18490 .iter()
18491 .max_by_key(|selection| selection.id)
18492 .unwrap();
18493 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18494 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18495 let snapshot = self.buffer.read(cx).read(cx);
18496 selections
18497 .into_iter()
18498 .map(|mut selection| {
18499 selection.start.0 =
18500 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18501 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18502 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18503 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18504 })
18505 .collect()
18506 }
18507
18508 fn report_editor_event(
18509 &self,
18510 event_type: &'static str,
18511 file_extension: Option<String>,
18512 cx: &App,
18513 ) {
18514 if cfg!(any(test, feature = "test-support")) {
18515 return;
18516 }
18517
18518 let Some(project) = &self.project else { return };
18519
18520 // If None, we are in a file without an extension
18521 let file = self
18522 .buffer
18523 .read(cx)
18524 .as_singleton()
18525 .and_then(|b| b.read(cx).file());
18526 let file_extension = file_extension.or(file
18527 .as_ref()
18528 .and_then(|file| Path::new(file.file_name(cx)).extension())
18529 .and_then(|e| e.to_str())
18530 .map(|a| a.to_string()));
18531
18532 let vim_mode = vim_enabled(cx);
18533
18534 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18535 let copilot_enabled = edit_predictions_provider
18536 == language::language_settings::EditPredictionProvider::Copilot;
18537 let copilot_enabled_for_language = self
18538 .buffer
18539 .read(cx)
18540 .language_settings(cx)
18541 .show_edit_predictions;
18542
18543 let project = project.read(cx);
18544 telemetry::event!(
18545 event_type,
18546 file_extension,
18547 vim_mode,
18548 copilot_enabled,
18549 copilot_enabled_for_language,
18550 edit_predictions_provider,
18551 is_via_ssh = project.is_via_ssh(),
18552 );
18553 }
18554
18555 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18556 /// with each line being an array of {text, highlight} objects.
18557 fn copy_highlight_json(
18558 &mut self,
18559 _: &CopyHighlightJson,
18560 window: &mut Window,
18561 cx: &mut Context<Self>,
18562 ) {
18563 #[derive(Serialize)]
18564 struct Chunk<'a> {
18565 text: String,
18566 highlight: Option<&'a str>,
18567 }
18568
18569 let snapshot = self.buffer.read(cx).snapshot(cx);
18570 let range = self
18571 .selected_text_range(false, window, cx)
18572 .and_then(|selection| {
18573 if selection.range.is_empty() {
18574 None
18575 } else {
18576 Some(selection.range)
18577 }
18578 })
18579 .unwrap_or_else(|| 0..snapshot.len());
18580
18581 let chunks = snapshot.chunks(range, true);
18582 let mut lines = Vec::new();
18583 let mut line: VecDeque<Chunk> = VecDeque::new();
18584
18585 let Some(style) = self.style.as_ref() else {
18586 return;
18587 };
18588
18589 for chunk in chunks {
18590 let highlight = chunk
18591 .syntax_highlight_id
18592 .and_then(|id| id.name(&style.syntax));
18593 let mut chunk_lines = chunk.text.split('\n').peekable();
18594 while let Some(text) = chunk_lines.next() {
18595 let mut merged_with_last_token = false;
18596 if let Some(last_token) = line.back_mut() {
18597 if last_token.highlight == highlight {
18598 last_token.text.push_str(text);
18599 merged_with_last_token = true;
18600 }
18601 }
18602
18603 if !merged_with_last_token {
18604 line.push_back(Chunk {
18605 text: text.into(),
18606 highlight,
18607 });
18608 }
18609
18610 if chunk_lines.peek().is_some() {
18611 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18612 line.pop_front();
18613 }
18614 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18615 line.pop_back();
18616 }
18617
18618 lines.push(mem::take(&mut line));
18619 }
18620 }
18621 }
18622
18623 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18624 return;
18625 };
18626 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18627 }
18628
18629 pub fn open_context_menu(
18630 &mut self,
18631 _: &OpenContextMenu,
18632 window: &mut Window,
18633 cx: &mut Context<Self>,
18634 ) {
18635 self.request_autoscroll(Autoscroll::newest(), cx);
18636 let position = self.selections.newest_display(cx).start;
18637 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18638 }
18639
18640 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18641 &self.inlay_hint_cache
18642 }
18643
18644 pub fn replay_insert_event(
18645 &mut self,
18646 text: &str,
18647 relative_utf16_range: Option<Range<isize>>,
18648 window: &mut Window,
18649 cx: &mut Context<Self>,
18650 ) {
18651 if !self.input_enabled {
18652 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18653 return;
18654 }
18655 if let Some(relative_utf16_range) = relative_utf16_range {
18656 let selections = self.selections.all::<OffsetUtf16>(cx);
18657 self.change_selections(None, window, cx, |s| {
18658 let new_ranges = selections.into_iter().map(|range| {
18659 let start = OffsetUtf16(
18660 range
18661 .head()
18662 .0
18663 .saturating_add_signed(relative_utf16_range.start),
18664 );
18665 let end = OffsetUtf16(
18666 range
18667 .head()
18668 .0
18669 .saturating_add_signed(relative_utf16_range.end),
18670 );
18671 start..end
18672 });
18673 s.select_ranges(new_ranges);
18674 });
18675 }
18676
18677 self.handle_input(text, window, cx);
18678 }
18679
18680 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18681 let Some(provider) = self.semantics_provider.as_ref() else {
18682 return false;
18683 };
18684
18685 let mut supports = false;
18686 self.buffer().update(cx, |this, cx| {
18687 this.for_each_buffer(|buffer| {
18688 supports |= provider.supports_inlay_hints(buffer, cx);
18689 });
18690 });
18691
18692 supports
18693 }
18694
18695 pub fn is_focused(&self, window: &Window) -> bool {
18696 self.focus_handle.is_focused(window)
18697 }
18698
18699 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18700 cx.emit(EditorEvent::Focused);
18701
18702 if let Some(descendant) = self
18703 .last_focused_descendant
18704 .take()
18705 .and_then(|descendant| descendant.upgrade())
18706 {
18707 window.focus(&descendant);
18708 } else {
18709 if let Some(blame) = self.blame.as_ref() {
18710 blame.update(cx, GitBlame::focus)
18711 }
18712
18713 self.blink_manager.update(cx, BlinkManager::enable);
18714 self.show_cursor_names(window, cx);
18715 self.buffer.update(cx, |buffer, cx| {
18716 buffer.finalize_last_transaction(cx);
18717 if self.leader_id.is_none() {
18718 buffer.set_active_selections(
18719 &self.selections.disjoint_anchors(),
18720 self.selections.line_mode,
18721 self.cursor_shape,
18722 cx,
18723 );
18724 }
18725 });
18726 }
18727 }
18728
18729 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18730 cx.emit(EditorEvent::FocusedIn)
18731 }
18732
18733 fn handle_focus_out(
18734 &mut self,
18735 event: FocusOutEvent,
18736 _window: &mut Window,
18737 cx: &mut Context<Self>,
18738 ) {
18739 if event.blurred != self.focus_handle {
18740 self.last_focused_descendant = Some(event.blurred);
18741 }
18742 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18743 }
18744
18745 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18746 self.blink_manager.update(cx, BlinkManager::disable);
18747 self.buffer
18748 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18749
18750 if let Some(blame) = self.blame.as_ref() {
18751 blame.update(cx, GitBlame::blur)
18752 }
18753 if !self.hover_state.focused(window, cx) {
18754 hide_hover(self, cx);
18755 }
18756 if !self
18757 .context_menu
18758 .borrow()
18759 .as_ref()
18760 .is_some_and(|context_menu| context_menu.focused(window, cx))
18761 {
18762 self.hide_context_menu(window, cx);
18763 }
18764 self.discard_inline_completion(false, cx);
18765 cx.emit(EditorEvent::Blurred);
18766 cx.notify();
18767 }
18768
18769 pub fn register_action<A: Action>(
18770 &mut self,
18771 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18772 ) -> Subscription {
18773 let id = self.next_editor_action_id.post_inc();
18774 let listener = Arc::new(listener);
18775 self.editor_actions.borrow_mut().insert(
18776 id,
18777 Box::new(move |window, _| {
18778 let listener = listener.clone();
18779 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18780 let action = action.downcast_ref().unwrap();
18781 if phase == DispatchPhase::Bubble {
18782 listener(action, window, cx)
18783 }
18784 })
18785 }),
18786 );
18787
18788 let editor_actions = self.editor_actions.clone();
18789 Subscription::new(move || {
18790 editor_actions.borrow_mut().remove(&id);
18791 })
18792 }
18793
18794 pub fn file_header_size(&self) -> u32 {
18795 FILE_HEADER_HEIGHT
18796 }
18797
18798 pub fn restore(
18799 &mut self,
18800 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18801 window: &mut Window,
18802 cx: &mut Context<Self>,
18803 ) {
18804 let workspace = self.workspace();
18805 let project = self.project.as_ref();
18806 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18807 let mut tasks = Vec::new();
18808 for (buffer_id, changes) in revert_changes {
18809 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18810 buffer.update(cx, |buffer, cx| {
18811 buffer.edit(
18812 changes
18813 .into_iter()
18814 .map(|(range, text)| (range, text.to_string())),
18815 None,
18816 cx,
18817 );
18818 });
18819
18820 if let Some(project) =
18821 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18822 {
18823 project.update(cx, |project, cx| {
18824 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18825 })
18826 }
18827 }
18828 }
18829 tasks
18830 });
18831 cx.spawn_in(window, async move |_, cx| {
18832 for (buffer, task) in save_tasks {
18833 let result = task.await;
18834 if result.is_err() {
18835 let Some(path) = buffer
18836 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18837 .ok()
18838 else {
18839 continue;
18840 };
18841 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18842 let Some(task) = cx
18843 .update_window_entity(&workspace, |workspace, window, cx| {
18844 workspace
18845 .open_path_preview(path, None, false, false, false, window, cx)
18846 })
18847 .ok()
18848 else {
18849 continue;
18850 };
18851 task.await.log_err();
18852 }
18853 }
18854 }
18855 })
18856 .detach();
18857 self.change_selections(None, window, cx, |selections| selections.refresh());
18858 }
18859
18860 pub fn to_pixel_point(
18861 &self,
18862 source: multi_buffer::Anchor,
18863 editor_snapshot: &EditorSnapshot,
18864 window: &mut Window,
18865 ) -> Option<gpui::Point<Pixels>> {
18866 let source_point = source.to_display_point(editor_snapshot);
18867 self.display_to_pixel_point(source_point, editor_snapshot, window)
18868 }
18869
18870 pub fn display_to_pixel_point(
18871 &self,
18872 source: DisplayPoint,
18873 editor_snapshot: &EditorSnapshot,
18874 window: &mut Window,
18875 ) -> Option<gpui::Point<Pixels>> {
18876 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18877 let text_layout_details = self.text_layout_details(window);
18878 let scroll_top = text_layout_details
18879 .scroll_anchor
18880 .scroll_position(editor_snapshot)
18881 .y;
18882
18883 if source.row().as_f32() < scroll_top.floor() {
18884 return None;
18885 }
18886 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18887 let source_y = line_height * (source.row().as_f32() - scroll_top);
18888 Some(gpui::Point::new(source_x, source_y))
18889 }
18890
18891 pub fn has_visible_completions_menu(&self) -> bool {
18892 !self.edit_prediction_preview_is_active()
18893 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18894 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18895 })
18896 }
18897
18898 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18899 if self.mode.is_minimap() {
18900 return;
18901 }
18902 self.addons
18903 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18904 }
18905
18906 pub fn unregister_addon<T: Addon>(&mut self) {
18907 self.addons.remove(&std::any::TypeId::of::<T>());
18908 }
18909
18910 pub fn addon<T: Addon>(&self) -> Option<&T> {
18911 let type_id = std::any::TypeId::of::<T>();
18912 self.addons
18913 .get(&type_id)
18914 .and_then(|item| item.to_any().downcast_ref::<T>())
18915 }
18916
18917 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18918 let type_id = std::any::TypeId::of::<T>();
18919 self.addons
18920 .get_mut(&type_id)
18921 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18922 }
18923
18924 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18925 let text_layout_details = self.text_layout_details(window);
18926 let style = &text_layout_details.editor_style;
18927 let font_id = window.text_system().resolve_font(&style.text.font());
18928 let font_size = style.text.font_size.to_pixels(window.rem_size());
18929 let line_height = style.text.line_height_in_pixels(window.rem_size());
18930 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18931
18932 gpui::Size::new(em_width, line_height)
18933 }
18934
18935 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18936 self.load_diff_task.clone()
18937 }
18938
18939 fn read_metadata_from_db(
18940 &mut self,
18941 item_id: u64,
18942 workspace_id: WorkspaceId,
18943 window: &mut Window,
18944 cx: &mut Context<Editor>,
18945 ) {
18946 if self.is_singleton(cx)
18947 && !self.mode.is_minimap()
18948 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18949 {
18950 let buffer_snapshot = OnceCell::new();
18951
18952 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18953 if !folds.is_empty() {
18954 let snapshot =
18955 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18956 self.fold_ranges(
18957 folds
18958 .into_iter()
18959 .map(|(start, end)| {
18960 snapshot.clip_offset(start, Bias::Left)
18961 ..snapshot.clip_offset(end, Bias::Right)
18962 })
18963 .collect(),
18964 false,
18965 window,
18966 cx,
18967 );
18968 }
18969 }
18970
18971 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18972 if !selections.is_empty() {
18973 let snapshot =
18974 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18975 self.change_selections(None, window, cx, |s| {
18976 s.select_ranges(selections.into_iter().map(|(start, end)| {
18977 snapshot.clip_offset(start, Bias::Left)
18978 ..snapshot.clip_offset(end, Bias::Right)
18979 }));
18980 });
18981 }
18982 };
18983 }
18984
18985 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18986 }
18987}
18988
18989fn vim_enabled(cx: &App) -> bool {
18990 cx.global::<SettingsStore>()
18991 .raw_user_settings()
18992 .get("vim_mode")
18993 == Some(&serde_json::Value::Bool(true))
18994}
18995
18996// Consider user intent and default settings
18997fn choose_completion_range(
18998 completion: &Completion,
18999 intent: CompletionIntent,
19000 buffer: &Entity<Buffer>,
19001 cx: &mut Context<Editor>,
19002) -> Range<usize> {
19003 fn should_replace(
19004 completion: &Completion,
19005 insert_range: &Range<text::Anchor>,
19006 intent: CompletionIntent,
19007 completion_mode_setting: LspInsertMode,
19008 buffer: &Buffer,
19009 ) -> bool {
19010 // specific actions take precedence over settings
19011 match intent {
19012 CompletionIntent::CompleteWithInsert => return false,
19013 CompletionIntent::CompleteWithReplace => return true,
19014 CompletionIntent::Complete | CompletionIntent::Compose => {}
19015 }
19016
19017 match completion_mode_setting {
19018 LspInsertMode::Insert => false,
19019 LspInsertMode::Replace => true,
19020 LspInsertMode::ReplaceSubsequence => {
19021 let mut text_to_replace = buffer.chars_for_range(
19022 buffer.anchor_before(completion.replace_range.start)
19023 ..buffer.anchor_after(completion.replace_range.end),
19024 );
19025 let mut completion_text = completion.new_text.chars();
19026
19027 // is `text_to_replace` a subsequence of `completion_text`
19028 text_to_replace
19029 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
19030 }
19031 LspInsertMode::ReplaceSuffix => {
19032 let range_after_cursor = insert_range.end..completion.replace_range.end;
19033
19034 let text_after_cursor = buffer
19035 .text_for_range(
19036 buffer.anchor_before(range_after_cursor.start)
19037 ..buffer.anchor_after(range_after_cursor.end),
19038 )
19039 .collect::<String>();
19040 completion.new_text.ends_with(&text_after_cursor)
19041 }
19042 }
19043 }
19044
19045 let buffer = buffer.read(cx);
19046
19047 if let CompletionSource::Lsp {
19048 insert_range: Some(insert_range),
19049 ..
19050 } = &completion.source
19051 {
19052 let completion_mode_setting =
19053 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
19054 .completions
19055 .lsp_insert_mode;
19056
19057 if !should_replace(
19058 completion,
19059 &insert_range,
19060 intent,
19061 completion_mode_setting,
19062 buffer,
19063 ) {
19064 return insert_range.to_offset(buffer);
19065 }
19066 }
19067
19068 completion.replace_range.to_offset(buffer)
19069}
19070
19071fn insert_extra_newline_brackets(
19072 buffer: &MultiBufferSnapshot,
19073 range: Range<usize>,
19074 language: &language::LanguageScope,
19075) -> bool {
19076 let leading_whitespace_len = buffer
19077 .reversed_chars_at(range.start)
19078 .take_while(|c| c.is_whitespace() && *c != '\n')
19079 .map(|c| c.len_utf8())
19080 .sum::<usize>();
19081 let trailing_whitespace_len = buffer
19082 .chars_at(range.end)
19083 .take_while(|c| c.is_whitespace() && *c != '\n')
19084 .map(|c| c.len_utf8())
19085 .sum::<usize>();
19086 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
19087
19088 language.brackets().any(|(pair, enabled)| {
19089 let pair_start = pair.start.trim_end();
19090 let pair_end = pair.end.trim_start();
19091
19092 enabled
19093 && pair.newline
19094 && buffer.contains_str_at(range.end, pair_end)
19095 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
19096 })
19097}
19098
19099fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
19100 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
19101 [(buffer, range, _)] => (*buffer, range.clone()),
19102 _ => return false,
19103 };
19104 let pair = {
19105 let mut result: Option<BracketMatch> = None;
19106
19107 for pair in buffer
19108 .all_bracket_ranges(range.clone())
19109 .filter(move |pair| {
19110 pair.open_range.start <= range.start && pair.close_range.end >= range.end
19111 })
19112 {
19113 let len = pair.close_range.end - pair.open_range.start;
19114
19115 if let Some(existing) = &result {
19116 let existing_len = existing.close_range.end - existing.open_range.start;
19117 if len > existing_len {
19118 continue;
19119 }
19120 }
19121
19122 result = Some(pair);
19123 }
19124
19125 result
19126 };
19127 let Some(pair) = pair else {
19128 return false;
19129 };
19130 pair.newline_only
19131 && buffer
19132 .chars_for_range(pair.open_range.end..range.start)
19133 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
19134 .all(|c| c.is_whitespace() && c != '\n')
19135}
19136
19137fn update_uncommitted_diff_for_buffer(
19138 editor: Entity<Editor>,
19139 project: &Entity<Project>,
19140 buffers: impl IntoIterator<Item = Entity<Buffer>>,
19141 buffer: Entity<MultiBuffer>,
19142 cx: &mut App,
19143) -> Task<()> {
19144 let mut tasks = Vec::new();
19145 project.update(cx, |project, cx| {
19146 for buffer in buffers {
19147 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
19148 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
19149 }
19150 }
19151 });
19152 cx.spawn(async move |cx| {
19153 let diffs = future::join_all(tasks).await;
19154 if editor
19155 .read_with(cx, |editor, _cx| editor.temporary_diff_override)
19156 .unwrap_or(false)
19157 {
19158 return;
19159 }
19160
19161 buffer
19162 .update(cx, |buffer, cx| {
19163 for diff in diffs.into_iter().flatten() {
19164 buffer.add_diff(diff, cx);
19165 }
19166 })
19167 .ok();
19168 })
19169}
19170
19171fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
19172 let tab_size = tab_size.get() as usize;
19173 let mut width = offset;
19174
19175 for ch in text.chars() {
19176 width += if ch == '\t' {
19177 tab_size - (width % tab_size)
19178 } else {
19179 1
19180 };
19181 }
19182
19183 width - offset
19184}
19185
19186#[cfg(test)]
19187mod tests {
19188 use super::*;
19189
19190 #[test]
19191 fn test_string_size_with_expanded_tabs() {
19192 let nz = |val| NonZeroU32::new(val).unwrap();
19193 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
19194 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
19195 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
19196 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
19197 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
19198 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
19199 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
19200 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
19201 }
19202}
19203
19204/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
19205struct WordBreakingTokenizer<'a> {
19206 input: &'a str,
19207}
19208
19209impl<'a> WordBreakingTokenizer<'a> {
19210 fn new(input: &'a str) -> Self {
19211 Self { input }
19212 }
19213}
19214
19215fn is_char_ideographic(ch: char) -> bool {
19216 use unicode_script::Script::*;
19217 use unicode_script::UnicodeScript;
19218 matches!(ch.script(), Han | Tangut | Yi)
19219}
19220
19221fn is_grapheme_ideographic(text: &str) -> bool {
19222 text.chars().any(is_char_ideographic)
19223}
19224
19225fn is_grapheme_whitespace(text: &str) -> bool {
19226 text.chars().any(|x| x.is_whitespace())
19227}
19228
19229fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19230 text.chars().next().map_or(false, |ch| {
19231 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19232 })
19233}
19234
19235#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19236enum WordBreakToken<'a> {
19237 Word { token: &'a str, grapheme_len: usize },
19238 InlineWhitespace { token: &'a str, grapheme_len: usize },
19239 Newline,
19240}
19241
19242impl<'a> Iterator for WordBreakingTokenizer<'a> {
19243 /// Yields a span, the count of graphemes in the token, and whether it was
19244 /// whitespace. Note that it also breaks at word boundaries.
19245 type Item = WordBreakToken<'a>;
19246
19247 fn next(&mut self) -> Option<Self::Item> {
19248 use unicode_segmentation::UnicodeSegmentation;
19249 if self.input.is_empty() {
19250 return None;
19251 }
19252
19253 let mut iter = self.input.graphemes(true).peekable();
19254 let mut offset = 0;
19255 let mut grapheme_len = 0;
19256 if let Some(first_grapheme) = iter.next() {
19257 let is_newline = first_grapheme == "\n";
19258 let is_whitespace = is_grapheme_whitespace(first_grapheme);
19259 offset += first_grapheme.len();
19260 grapheme_len += 1;
19261 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19262 if let Some(grapheme) = iter.peek().copied() {
19263 if should_stay_with_preceding_ideograph(grapheme) {
19264 offset += grapheme.len();
19265 grapheme_len += 1;
19266 }
19267 }
19268 } else {
19269 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19270 let mut next_word_bound = words.peek().copied();
19271 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19272 next_word_bound = words.next();
19273 }
19274 while let Some(grapheme) = iter.peek().copied() {
19275 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19276 break;
19277 };
19278 if is_grapheme_whitespace(grapheme) != is_whitespace
19279 || (grapheme == "\n") != is_newline
19280 {
19281 break;
19282 };
19283 offset += grapheme.len();
19284 grapheme_len += 1;
19285 iter.next();
19286 }
19287 }
19288 let token = &self.input[..offset];
19289 self.input = &self.input[offset..];
19290 if token == "\n" {
19291 Some(WordBreakToken::Newline)
19292 } else if is_whitespace {
19293 Some(WordBreakToken::InlineWhitespace {
19294 token,
19295 grapheme_len,
19296 })
19297 } else {
19298 Some(WordBreakToken::Word {
19299 token,
19300 grapheme_len,
19301 })
19302 }
19303 } else {
19304 None
19305 }
19306 }
19307}
19308
19309#[test]
19310fn test_word_breaking_tokenizer() {
19311 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19312 ("", &[]),
19313 (" ", &[whitespace(" ", 2)]),
19314 ("Ʒ", &[word("Ʒ", 1)]),
19315 ("Ǽ", &[word("Ǽ", 1)]),
19316 ("⋑", &[word("⋑", 1)]),
19317 ("⋑⋑", &[word("⋑⋑", 2)]),
19318 (
19319 "原理,进而",
19320 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19321 ),
19322 (
19323 "hello world",
19324 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19325 ),
19326 (
19327 "hello, world",
19328 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19329 ),
19330 (
19331 " hello world",
19332 &[
19333 whitespace(" ", 2),
19334 word("hello", 5),
19335 whitespace(" ", 1),
19336 word("world", 5),
19337 ],
19338 ),
19339 (
19340 "这是什么 \n 钢笔",
19341 &[
19342 word("这", 1),
19343 word("是", 1),
19344 word("什", 1),
19345 word("么", 1),
19346 whitespace(" ", 1),
19347 newline(),
19348 whitespace(" ", 1),
19349 word("钢", 1),
19350 word("笔", 1),
19351 ],
19352 ),
19353 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19354 ];
19355
19356 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19357 WordBreakToken::Word {
19358 token,
19359 grapheme_len,
19360 }
19361 }
19362
19363 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19364 WordBreakToken::InlineWhitespace {
19365 token,
19366 grapheme_len,
19367 }
19368 }
19369
19370 fn newline() -> WordBreakToken<'static> {
19371 WordBreakToken::Newline
19372 }
19373
19374 for (input, result) in tests {
19375 assert_eq!(
19376 WordBreakingTokenizer::new(input)
19377 .collect::<Vec<_>>()
19378 .as_slice(),
19379 *result,
19380 );
19381 }
19382}
19383
19384fn wrap_with_prefix(
19385 line_prefix: String,
19386 unwrapped_text: String,
19387 wrap_column: usize,
19388 tab_size: NonZeroU32,
19389 preserve_existing_whitespace: bool,
19390) -> String {
19391 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19392 let mut wrapped_text = String::new();
19393 let mut current_line = line_prefix.clone();
19394
19395 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19396 let mut current_line_len = line_prefix_len;
19397 let mut in_whitespace = false;
19398 for token in tokenizer {
19399 let have_preceding_whitespace = in_whitespace;
19400 match token {
19401 WordBreakToken::Word {
19402 token,
19403 grapheme_len,
19404 } => {
19405 in_whitespace = false;
19406 if current_line_len + grapheme_len > wrap_column
19407 && current_line_len != line_prefix_len
19408 {
19409 wrapped_text.push_str(current_line.trim_end());
19410 wrapped_text.push('\n');
19411 current_line.truncate(line_prefix.len());
19412 current_line_len = line_prefix_len;
19413 }
19414 current_line.push_str(token);
19415 current_line_len += grapheme_len;
19416 }
19417 WordBreakToken::InlineWhitespace {
19418 mut token,
19419 mut grapheme_len,
19420 } => {
19421 in_whitespace = true;
19422 if have_preceding_whitespace && !preserve_existing_whitespace {
19423 continue;
19424 }
19425 if !preserve_existing_whitespace {
19426 token = " ";
19427 grapheme_len = 1;
19428 }
19429 if current_line_len + grapheme_len > wrap_column {
19430 wrapped_text.push_str(current_line.trim_end());
19431 wrapped_text.push('\n');
19432 current_line.truncate(line_prefix.len());
19433 current_line_len = line_prefix_len;
19434 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19435 current_line.push_str(token);
19436 current_line_len += grapheme_len;
19437 }
19438 }
19439 WordBreakToken::Newline => {
19440 in_whitespace = true;
19441 if preserve_existing_whitespace {
19442 wrapped_text.push_str(current_line.trim_end());
19443 wrapped_text.push('\n');
19444 current_line.truncate(line_prefix.len());
19445 current_line_len = line_prefix_len;
19446 } else if have_preceding_whitespace {
19447 continue;
19448 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19449 {
19450 wrapped_text.push_str(current_line.trim_end());
19451 wrapped_text.push('\n');
19452 current_line.truncate(line_prefix.len());
19453 current_line_len = line_prefix_len;
19454 } else if current_line_len != line_prefix_len {
19455 current_line.push(' ');
19456 current_line_len += 1;
19457 }
19458 }
19459 }
19460 }
19461
19462 if !current_line.is_empty() {
19463 wrapped_text.push_str(¤t_line);
19464 }
19465 wrapped_text
19466}
19467
19468#[test]
19469fn test_wrap_with_prefix() {
19470 assert_eq!(
19471 wrap_with_prefix(
19472 "# ".to_string(),
19473 "abcdefg".to_string(),
19474 4,
19475 NonZeroU32::new(4).unwrap(),
19476 false,
19477 ),
19478 "# abcdefg"
19479 );
19480 assert_eq!(
19481 wrap_with_prefix(
19482 "".to_string(),
19483 "\thello world".to_string(),
19484 8,
19485 NonZeroU32::new(4).unwrap(),
19486 false,
19487 ),
19488 "hello\nworld"
19489 );
19490 assert_eq!(
19491 wrap_with_prefix(
19492 "// ".to_string(),
19493 "xx \nyy zz aa bb cc".to_string(),
19494 12,
19495 NonZeroU32::new(4).unwrap(),
19496 false,
19497 ),
19498 "// xx yy zz\n// aa bb cc"
19499 );
19500 assert_eq!(
19501 wrap_with_prefix(
19502 String::new(),
19503 "这是什么 \n 钢笔".to_string(),
19504 3,
19505 NonZeroU32::new(4).unwrap(),
19506 false,
19507 ),
19508 "这是什\n么 钢\n笔"
19509 );
19510}
19511
19512pub trait CollaborationHub {
19513 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19514 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19515 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19516}
19517
19518impl CollaborationHub for Entity<Project> {
19519 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19520 self.read(cx).collaborators()
19521 }
19522
19523 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19524 self.read(cx).user_store().read(cx).participant_indices()
19525 }
19526
19527 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19528 let this = self.read(cx);
19529 let user_ids = this.collaborators().values().map(|c| c.user_id);
19530 this.user_store().read_with(cx, |user_store, cx| {
19531 user_store.participant_names(user_ids, cx)
19532 })
19533 }
19534}
19535
19536pub trait SemanticsProvider {
19537 fn hover(
19538 &self,
19539 buffer: &Entity<Buffer>,
19540 position: text::Anchor,
19541 cx: &mut App,
19542 ) -> Option<Task<Vec<project::Hover>>>;
19543
19544 fn inline_values(
19545 &self,
19546 buffer_handle: Entity<Buffer>,
19547 range: Range<text::Anchor>,
19548 cx: &mut App,
19549 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19550
19551 fn inlay_hints(
19552 &self,
19553 buffer_handle: Entity<Buffer>,
19554 range: Range<text::Anchor>,
19555 cx: &mut App,
19556 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19557
19558 fn resolve_inlay_hint(
19559 &self,
19560 hint: InlayHint,
19561 buffer_handle: Entity<Buffer>,
19562 server_id: LanguageServerId,
19563 cx: &mut App,
19564 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19565
19566 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19567
19568 fn document_highlights(
19569 &self,
19570 buffer: &Entity<Buffer>,
19571 position: text::Anchor,
19572 cx: &mut App,
19573 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19574
19575 fn definitions(
19576 &self,
19577 buffer: &Entity<Buffer>,
19578 position: text::Anchor,
19579 kind: GotoDefinitionKind,
19580 cx: &mut App,
19581 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19582
19583 fn range_for_rename(
19584 &self,
19585 buffer: &Entity<Buffer>,
19586 position: text::Anchor,
19587 cx: &mut App,
19588 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19589
19590 fn perform_rename(
19591 &self,
19592 buffer: &Entity<Buffer>,
19593 position: text::Anchor,
19594 new_name: String,
19595 cx: &mut App,
19596 ) -> Option<Task<Result<ProjectTransaction>>>;
19597}
19598
19599pub trait CompletionProvider {
19600 fn completions(
19601 &self,
19602 excerpt_id: ExcerptId,
19603 buffer: &Entity<Buffer>,
19604 buffer_position: text::Anchor,
19605 trigger: CompletionContext,
19606 window: &mut Window,
19607 cx: &mut Context<Editor>,
19608 ) -> Task<Result<Option<Vec<Completion>>>>;
19609
19610 fn resolve_completions(
19611 &self,
19612 buffer: Entity<Buffer>,
19613 completion_indices: Vec<usize>,
19614 completions: Rc<RefCell<Box<[Completion]>>>,
19615 cx: &mut Context<Editor>,
19616 ) -> Task<Result<bool>>;
19617
19618 fn apply_additional_edits_for_completion(
19619 &self,
19620 _buffer: Entity<Buffer>,
19621 _completions: Rc<RefCell<Box<[Completion]>>>,
19622 _completion_index: usize,
19623 _push_to_history: bool,
19624 _cx: &mut Context<Editor>,
19625 ) -> Task<Result<Option<language::Transaction>>> {
19626 Task::ready(Ok(None))
19627 }
19628
19629 fn is_completion_trigger(
19630 &self,
19631 buffer: &Entity<Buffer>,
19632 position: language::Anchor,
19633 text: &str,
19634 trigger_in_words: bool,
19635 cx: &mut Context<Editor>,
19636 ) -> bool;
19637
19638 fn sort_completions(&self) -> bool {
19639 true
19640 }
19641
19642 fn filter_completions(&self) -> bool {
19643 true
19644 }
19645}
19646
19647pub trait CodeActionProvider {
19648 fn id(&self) -> Arc<str>;
19649
19650 fn code_actions(
19651 &self,
19652 buffer: &Entity<Buffer>,
19653 range: Range<text::Anchor>,
19654 window: &mut Window,
19655 cx: &mut App,
19656 ) -> Task<Result<Vec<CodeAction>>>;
19657
19658 fn apply_code_action(
19659 &self,
19660 buffer_handle: Entity<Buffer>,
19661 action: CodeAction,
19662 excerpt_id: ExcerptId,
19663 push_to_history: bool,
19664 window: &mut Window,
19665 cx: &mut App,
19666 ) -> Task<Result<ProjectTransaction>>;
19667}
19668
19669impl CodeActionProvider for Entity<Project> {
19670 fn id(&self) -> Arc<str> {
19671 "project".into()
19672 }
19673
19674 fn code_actions(
19675 &self,
19676 buffer: &Entity<Buffer>,
19677 range: Range<text::Anchor>,
19678 _window: &mut Window,
19679 cx: &mut App,
19680 ) -> Task<Result<Vec<CodeAction>>> {
19681 self.update(cx, |project, cx| {
19682 let code_lens = project.code_lens(buffer, range.clone(), cx);
19683 let code_actions = project.code_actions(buffer, range, None, cx);
19684 cx.background_spawn(async move {
19685 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19686 Ok(code_lens
19687 .context("code lens fetch")?
19688 .into_iter()
19689 .chain(code_actions.context("code action fetch")?)
19690 .collect())
19691 })
19692 })
19693 }
19694
19695 fn apply_code_action(
19696 &self,
19697 buffer_handle: Entity<Buffer>,
19698 action: CodeAction,
19699 _excerpt_id: ExcerptId,
19700 push_to_history: bool,
19701 _window: &mut Window,
19702 cx: &mut App,
19703 ) -> Task<Result<ProjectTransaction>> {
19704 self.update(cx, |project, cx| {
19705 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19706 })
19707 }
19708}
19709
19710fn snippet_completions(
19711 project: &Project,
19712 buffer: &Entity<Buffer>,
19713 buffer_position: text::Anchor,
19714 cx: &mut App,
19715) -> Task<Result<Vec<Completion>>> {
19716 let languages = buffer.read(cx).languages_at(buffer_position);
19717 let snippet_store = project.snippets().read(cx);
19718
19719 let scopes: Vec<_> = languages
19720 .iter()
19721 .filter_map(|language| {
19722 let language_name = language.lsp_id();
19723 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19724
19725 if snippets.is_empty() {
19726 None
19727 } else {
19728 Some((language.default_scope(), snippets))
19729 }
19730 })
19731 .collect();
19732
19733 if scopes.is_empty() {
19734 return Task::ready(Ok(vec![]));
19735 }
19736
19737 let snapshot = buffer.read(cx).text_snapshot();
19738 let chars: String = snapshot
19739 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19740 .collect();
19741 let executor = cx.background_executor().clone();
19742
19743 cx.background_spawn(async move {
19744 let mut all_results: Vec<Completion> = Vec::new();
19745 for (scope, snippets) in scopes.into_iter() {
19746 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19747 let mut last_word = chars
19748 .chars()
19749 .take_while(|c| classifier.is_word(*c))
19750 .collect::<String>();
19751 last_word = last_word.chars().rev().collect();
19752
19753 if last_word.is_empty() {
19754 return Ok(vec![]);
19755 }
19756
19757 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19758 let to_lsp = |point: &text::Anchor| {
19759 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19760 point_to_lsp(end)
19761 };
19762 let lsp_end = to_lsp(&buffer_position);
19763
19764 let candidates = snippets
19765 .iter()
19766 .enumerate()
19767 .flat_map(|(ix, snippet)| {
19768 snippet
19769 .prefix
19770 .iter()
19771 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19772 })
19773 .collect::<Vec<StringMatchCandidate>>();
19774
19775 let mut matches = fuzzy::match_strings(
19776 &candidates,
19777 &last_word,
19778 last_word.chars().any(|c| c.is_uppercase()),
19779 100,
19780 &Default::default(),
19781 executor.clone(),
19782 )
19783 .await;
19784
19785 // Remove all candidates where the query's start does not match the start of any word in the candidate
19786 if let Some(query_start) = last_word.chars().next() {
19787 matches.retain(|string_match| {
19788 split_words(&string_match.string).any(|word| {
19789 // Check that the first codepoint of the word as lowercase matches the first
19790 // codepoint of the query as lowercase
19791 word.chars()
19792 .flat_map(|codepoint| codepoint.to_lowercase())
19793 .zip(query_start.to_lowercase())
19794 .all(|(word_cp, query_cp)| word_cp == query_cp)
19795 })
19796 });
19797 }
19798
19799 let matched_strings = matches
19800 .into_iter()
19801 .map(|m| m.string)
19802 .collect::<HashSet<_>>();
19803
19804 let mut result: Vec<Completion> = snippets
19805 .iter()
19806 .filter_map(|snippet| {
19807 let matching_prefix = snippet
19808 .prefix
19809 .iter()
19810 .find(|prefix| matched_strings.contains(*prefix))?;
19811 let start = as_offset - last_word.len();
19812 let start = snapshot.anchor_before(start);
19813 let range = start..buffer_position;
19814 let lsp_start = to_lsp(&start);
19815 let lsp_range = lsp::Range {
19816 start: lsp_start,
19817 end: lsp_end,
19818 };
19819 Some(Completion {
19820 replace_range: range,
19821 new_text: snippet.body.clone(),
19822 source: CompletionSource::Lsp {
19823 insert_range: None,
19824 server_id: LanguageServerId(usize::MAX),
19825 resolved: true,
19826 lsp_completion: Box::new(lsp::CompletionItem {
19827 label: snippet.prefix.first().unwrap().clone(),
19828 kind: Some(CompletionItemKind::SNIPPET),
19829 label_details: snippet.description.as_ref().map(|description| {
19830 lsp::CompletionItemLabelDetails {
19831 detail: Some(description.clone()),
19832 description: None,
19833 }
19834 }),
19835 insert_text_format: Some(InsertTextFormat::SNIPPET),
19836 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19837 lsp::InsertReplaceEdit {
19838 new_text: snippet.body.clone(),
19839 insert: lsp_range,
19840 replace: lsp_range,
19841 },
19842 )),
19843 filter_text: Some(snippet.body.clone()),
19844 sort_text: Some(char::MAX.to_string()),
19845 ..lsp::CompletionItem::default()
19846 }),
19847 lsp_defaults: None,
19848 },
19849 label: CodeLabel {
19850 text: matching_prefix.clone(),
19851 runs: Vec::new(),
19852 filter_range: 0..matching_prefix.len(),
19853 },
19854 icon_path: None,
19855 documentation: snippet.description.clone().map(|description| {
19856 CompletionDocumentation::SingleLine(description.into())
19857 }),
19858 insert_text_mode: None,
19859 confirm: None,
19860 })
19861 })
19862 .collect();
19863
19864 all_results.append(&mut result);
19865 }
19866
19867 Ok(all_results)
19868 })
19869}
19870
19871impl CompletionProvider for Entity<Project> {
19872 fn completions(
19873 &self,
19874 _excerpt_id: ExcerptId,
19875 buffer: &Entity<Buffer>,
19876 buffer_position: text::Anchor,
19877 options: CompletionContext,
19878 _window: &mut Window,
19879 cx: &mut Context<Editor>,
19880 ) -> Task<Result<Option<Vec<Completion>>>> {
19881 self.update(cx, |project, cx| {
19882 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19883 let project_completions = project.completions(buffer, buffer_position, options, cx);
19884 cx.background_spawn(async move {
19885 let snippets_completions = snippets.await?;
19886 match project_completions.await? {
19887 Some(mut completions) => {
19888 completions.extend(snippets_completions);
19889 Ok(Some(completions))
19890 }
19891 None => {
19892 if snippets_completions.is_empty() {
19893 Ok(None)
19894 } else {
19895 Ok(Some(snippets_completions))
19896 }
19897 }
19898 }
19899 })
19900 })
19901 }
19902
19903 fn resolve_completions(
19904 &self,
19905 buffer: Entity<Buffer>,
19906 completion_indices: Vec<usize>,
19907 completions: Rc<RefCell<Box<[Completion]>>>,
19908 cx: &mut Context<Editor>,
19909 ) -> Task<Result<bool>> {
19910 self.update(cx, |project, cx| {
19911 project.lsp_store().update(cx, |lsp_store, cx| {
19912 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19913 })
19914 })
19915 }
19916
19917 fn apply_additional_edits_for_completion(
19918 &self,
19919 buffer: Entity<Buffer>,
19920 completions: Rc<RefCell<Box<[Completion]>>>,
19921 completion_index: usize,
19922 push_to_history: bool,
19923 cx: &mut Context<Editor>,
19924 ) -> Task<Result<Option<language::Transaction>>> {
19925 self.update(cx, |project, cx| {
19926 project.lsp_store().update(cx, |lsp_store, cx| {
19927 lsp_store.apply_additional_edits_for_completion(
19928 buffer,
19929 completions,
19930 completion_index,
19931 push_to_history,
19932 cx,
19933 )
19934 })
19935 })
19936 }
19937
19938 fn is_completion_trigger(
19939 &self,
19940 buffer: &Entity<Buffer>,
19941 position: language::Anchor,
19942 text: &str,
19943 trigger_in_words: bool,
19944 cx: &mut Context<Editor>,
19945 ) -> bool {
19946 let mut chars = text.chars();
19947 let char = if let Some(char) = chars.next() {
19948 char
19949 } else {
19950 return false;
19951 };
19952 if chars.next().is_some() {
19953 return false;
19954 }
19955
19956 let buffer = buffer.read(cx);
19957 let snapshot = buffer.snapshot();
19958 if !snapshot.settings_at(position, cx).show_completions_on_input {
19959 return false;
19960 }
19961 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19962 if trigger_in_words && classifier.is_word(char) {
19963 return true;
19964 }
19965
19966 buffer.completion_triggers().contains(text)
19967 }
19968}
19969
19970impl SemanticsProvider for Entity<Project> {
19971 fn hover(
19972 &self,
19973 buffer: &Entity<Buffer>,
19974 position: text::Anchor,
19975 cx: &mut App,
19976 ) -> Option<Task<Vec<project::Hover>>> {
19977 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19978 }
19979
19980 fn document_highlights(
19981 &self,
19982 buffer: &Entity<Buffer>,
19983 position: text::Anchor,
19984 cx: &mut App,
19985 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19986 Some(self.update(cx, |project, cx| {
19987 project.document_highlights(buffer, position, cx)
19988 }))
19989 }
19990
19991 fn definitions(
19992 &self,
19993 buffer: &Entity<Buffer>,
19994 position: text::Anchor,
19995 kind: GotoDefinitionKind,
19996 cx: &mut App,
19997 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19998 Some(self.update(cx, |project, cx| match kind {
19999 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
20000 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
20001 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
20002 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
20003 }))
20004 }
20005
20006 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
20007 // TODO: make this work for remote projects
20008 self.update(cx, |project, cx| {
20009 if project
20010 .active_debug_session(cx)
20011 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
20012 {
20013 return true;
20014 }
20015
20016 buffer.update(cx, |buffer, cx| {
20017 project.any_language_server_supports_inlay_hints(buffer, cx)
20018 })
20019 })
20020 }
20021
20022 fn inline_values(
20023 &self,
20024 buffer_handle: Entity<Buffer>,
20025 range: Range<text::Anchor>,
20026 cx: &mut App,
20027 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
20028 self.update(cx, |project, cx| {
20029 let (session, active_stack_frame) = project.active_debug_session(cx)?;
20030
20031 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
20032 })
20033 }
20034
20035 fn inlay_hints(
20036 &self,
20037 buffer_handle: Entity<Buffer>,
20038 range: Range<text::Anchor>,
20039 cx: &mut App,
20040 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
20041 Some(self.update(cx, |project, cx| {
20042 project.inlay_hints(buffer_handle, range, cx)
20043 }))
20044 }
20045
20046 fn resolve_inlay_hint(
20047 &self,
20048 hint: InlayHint,
20049 buffer_handle: Entity<Buffer>,
20050 server_id: LanguageServerId,
20051 cx: &mut App,
20052 ) -> Option<Task<anyhow::Result<InlayHint>>> {
20053 Some(self.update(cx, |project, cx| {
20054 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
20055 }))
20056 }
20057
20058 fn range_for_rename(
20059 &self,
20060 buffer: &Entity<Buffer>,
20061 position: text::Anchor,
20062 cx: &mut App,
20063 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
20064 Some(self.update(cx, |project, cx| {
20065 let buffer = buffer.clone();
20066 let task = project.prepare_rename(buffer.clone(), position, cx);
20067 cx.spawn(async move |_, cx| {
20068 Ok(match task.await? {
20069 PrepareRenameResponse::Success(range) => Some(range),
20070 PrepareRenameResponse::InvalidPosition => None,
20071 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
20072 // Fallback on using TreeSitter info to determine identifier range
20073 buffer.update(cx, |buffer, _| {
20074 let snapshot = buffer.snapshot();
20075 let (range, kind) = snapshot.surrounding_word(position);
20076 if kind != Some(CharKind::Word) {
20077 return None;
20078 }
20079 Some(
20080 snapshot.anchor_before(range.start)
20081 ..snapshot.anchor_after(range.end),
20082 )
20083 })?
20084 }
20085 })
20086 })
20087 }))
20088 }
20089
20090 fn perform_rename(
20091 &self,
20092 buffer: &Entity<Buffer>,
20093 position: text::Anchor,
20094 new_name: String,
20095 cx: &mut App,
20096 ) -> Option<Task<Result<ProjectTransaction>>> {
20097 Some(self.update(cx, |project, cx| {
20098 project.perform_rename(buffer.clone(), position, new_name, cx)
20099 }))
20100 }
20101}
20102
20103fn inlay_hint_settings(
20104 location: Anchor,
20105 snapshot: &MultiBufferSnapshot,
20106 cx: &mut Context<Editor>,
20107) -> InlayHintSettings {
20108 let file = snapshot.file_at(location);
20109 let language = snapshot.language_at(location).map(|l| l.name());
20110 language_settings(language, file, cx).inlay_hints
20111}
20112
20113fn consume_contiguous_rows(
20114 contiguous_row_selections: &mut Vec<Selection<Point>>,
20115 selection: &Selection<Point>,
20116 display_map: &DisplaySnapshot,
20117 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
20118) -> (MultiBufferRow, MultiBufferRow) {
20119 contiguous_row_selections.push(selection.clone());
20120 let start_row = MultiBufferRow(selection.start.row);
20121 let mut end_row = ending_row(selection, display_map);
20122
20123 while let Some(next_selection) = selections.peek() {
20124 if next_selection.start.row <= end_row.0 {
20125 end_row = ending_row(next_selection, display_map);
20126 contiguous_row_selections.push(selections.next().unwrap().clone());
20127 } else {
20128 break;
20129 }
20130 }
20131 (start_row, end_row)
20132}
20133
20134fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
20135 if next_selection.end.column > 0 || next_selection.is_empty() {
20136 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
20137 } else {
20138 MultiBufferRow(next_selection.end.row)
20139 }
20140}
20141
20142impl EditorSnapshot {
20143 pub fn remote_selections_in_range<'a>(
20144 &'a self,
20145 range: &'a Range<Anchor>,
20146 collaboration_hub: &dyn CollaborationHub,
20147 cx: &'a App,
20148 ) -> impl 'a + Iterator<Item = RemoteSelection> {
20149 let participant_names = collaboration_hub.user_names(cx);
20150 let participant_indices = collaboration_hub.user_participant_indices(cx);
20151 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
20152 let collaborators_by_replica_id = collaborators_by_peer_id
20153 .iter()
20154 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
20155 .collect::<HashMap<_, _>>();
20156 self.buffer_snapshot
20157 .selections_in_range(range, false)
20158 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
20159 if replica_id == AGENT_REPLICA_ID {
20160 Some(RemoteSelection {
20161 replica_id,
20162 selection,
20163 cursor_shape,
20164 line_mode,
20165 collaborator_id: CollaboratorId::Agent,
20166 user_name: Some("Agent".into()),
20167 color: cx.theme().players().agent(),
20168 })
20169 } else {
20170 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
20171 let participant_index = participant_indices.get(&collaborator.user_id).copied();
20172 let user_name = participant_names.get(&collaborator.user_id).cloned();
20173 Some(RemoteSelection {
20174 replica_id,
20175 selection,
20176 cursor_shape,
20177 line_mode,
20178 collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
20179 user_name,
20180 color: if let Some(index) = participant_index {
20181 cx.theme().players().color_for_participant(index.0)
20182 } else {
20183 cx.theme().players().absent()
20184 },
20185 })
20186 }
20187 })
20188 }
20189
20190 pub fn hunks_for_ranges(
20191 &self,
20192 ranges: impl IntoIterator<Item = Range<Point>>,
20193 ) -> Vec<MultiBufferDiffHunk> {
20194 let mut hunks = Vec::new();
20195 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
20196 HashMap::default();
20197 for query_range in ranges {
20198 let query_rows =
20199 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
20200 for hunk in self.buffer_snapshot.diff_hunks_in_range(
20201 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
20202 ) {
20203 // Include deleted hunks that are adjacent to the query range, because
20204 // otherwise they would be missed.
20205 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
20206 if hunk.status().is_deleted() {
20207 intersects_range |= hunk.row_range.start == query_rows.end;
20208 intersects_range |= hunk.row_range.end == query_rows.start;
20209 }
20210 if intersects_range {
20211 if !processed_buffer_rows
20212 .entry(hunk.buffer_id)
20213 .or_default()
20214 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
20215 {
20216 continue;
20217 }
20218 hunks.push(hunk);
20219 }
20220 }
20221 }
20222
20223 hunks
20224 }
20225
20226 fn display_diff_hunks_for_rows<'a>(
20227 &'a self,
20228 display_rows: Range<DisplayRow>,
20229 folded_buffers: &'a HashSet<BufferId>,
20230 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20231 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20232 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20233
20234 self.buffer_snapshot
20235 .diff_hunks_in_range(buffer_start..buffer_end)
20236 .filter_map(|hunk| {
20237 if folded_buffers.contains(&hunk.buffer_id) {
20238 return None;
20239 }
20240
20241 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20242 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20243
20244 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20245 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20246
20247 let display_hunk = if hunk_display_start.column() != 0 {
20248 DisplayDiffHunk::Folded {
20249 display_row: hunk_display_start.row(),
20250 }
20251 } else {
20252 let mut end_row = hunk_display_end.row();
20253 if hunk_display_end.column() > 0 {
20254 end_row.0 += 1;
20255 }
20256 let is_created_file = hunk.is_created_file();
20257 DisplayDiffHunk::Unfolded {
20258 status: hunk.status(),
20259 diff_base_byte_range: hunk.diff_base_byte_range,
20260 display_row_range: hunk_display_start.row()..end_row,
20261 multi_buffer_range: Anchor::range_in_buffer(
20262 hunk.excerpt_id,
20263 hunk.buffer_id,
20264 hunk.buffer_range,
20265 ),
20266 is_created_file,
20267 }
20268 };
20269
20270 Some(display_hunk)
20271 })
20272 }
20273
20274 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20275 self.display_snapshot.buffer_snapshot.language_at(position)
20276 }
20277
20278 pub fn is_focused(&self) -> bool {
20279 self.is_focused
20280 }
20281
20282 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20283 self.placeholder_text.as_ref()
20284 }
20285
20286 pub fn scroll_position(&self) -> gpui::Point<f32> {
20287 self.scroll_anchor.scroll_position(&self.display_snapshot)
20288 }
20289
20290 fn gutter_dimensions(
20291 &self,
20292 font_id: FontId,
20293 font_size: Pixels,
20294 max_line_number_width: Pixels,
20295 cx: &App,
20296 ) -> Option<GutterDimensions> {
20297 if !self.show_gutter {
20298 return None;
20299 }
20300
20301 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20302 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20303
20304 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20305 matches!(
20306 ProjectSettings::get_global(cx).git.git_gutter,
20307 Some(GitGutterSetting::TrackedFiles)
20308 )
20309 });
20310 let gutter_settings = EditorSettings::get_global(cx).gutter;
20311 let show_line_numbers = self
20312 .show_line_numbers
20313 .unwrap_or(gutter_settings.line_numbers);
20314 let line_gutter_width = if show_line_numbers {
20315 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20316 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20317 max_line_number_width.max(min_width_for_number_on_gutter)
20318 } else {
20319 0.0.into()
20320 };
20321
20322 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20323 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20324
20325 let git_blame_entries_width =
20326 self.git_blame_gutter_max_author_length
20327 .map(|max_author_length| {
20328 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20329 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20330
20331 /// The number of characters to dedicate to gaps and margins.
20332 const SPACING_WIDTH: usize = 4;
20333
20334 let max_char_count = max_author_length.min(renderer.max_author_length())
20335 + ::git::SHORT_SHA_LENGTH
20336 + MAX_RELATIVE_TIMESTAMP.len()
20337 + SPACING_WIDTH;
20338
20339 em_advance * max_char_count
20340 });
20341
20342 let is_singleton = self.buffer_snapshot.is_singleton();
20343
20344 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20345 left_padding += if !is_singleton {
20346 em_width * 4.0
20347 } else if show_runnables || show_breakpoints {
20348 em_width * 3.0
20349 } else if show_git_gutter && show_line_numbers {
20350 em_width * 2.0
20351 } else if show_git_gutter || show_line_numbers {
20352 em_width
20353 } else {
20354 px(0.)
20355 };
20356
20357 let shows_folds = is_singleton && gutter_settings.folds;
20358
20359 let right_padding = if shows_folds && show_line_numbers {
20360 em_width * 4.0
20361 } else if shows_folds || (!is_singleton && show_line_numbers) {
20362 em_width * 3.0
20363 } else if show_line_numbers {
20364 em_width
20365 } else {
20366 px(0.)
20367 };
20368
20369 Some(GutterDimensions {
20370 left_padding,
20371 right_padding,
20372 width: line_gutter_width + left_padding + right_padding,
20373 margin: GutterDimensions::default_gutter_margin(font_id, font_size, cx),
20374 git_blame_entries_width,
20375 })
20376 }
20377
20378 pub fn render_crease_toggle(
20379 &self,
20380 buffer_row: MultiBufferRow,
20381 row_contains_cursor: bool,
20382 editor: Entity<Editor>,
20383 window: &mut Window,
20384 cx: &mut App,
20385 ) -> Option<AnyElement> {
20386 let folded = self.is_line_folded(buffer_row);
20387 let mut is_foldable = false;
20388
20389 if let Some(crease) = self
20390 .crease_snapshot
20391 .query_row(buffer_row, &self.buffer_snapshot)
20392 {
20393 is_foldable = true;
20394 match crease {
20395 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20396 if let Some(render_toggle) = render_toggle {
20397 let toggle_callback =
20398 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20399 if folded {
20400 editor.update(cx, |editor, cx| {
20401 editor.fold_at(buffer_row, window, cx)
20402 });
20403 } else {
20404 editor.update(cx, |editor, cx| {
20405 editor.unfold_at(buffer_row, window, cx)
20406 });
20407 }
20408 });
20409 return Some((render_toggle)(
20410 buffer_row,
20411 folded,
20412 toggle_callback,
20413 window,
20414 cx,
20415 ));
20416 }
20417 }
20418 }
20419 }
20420
20421 is_foldable |= self.starts_indent(buffer_row);
20422
20423 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20424 Some(
20425 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20426 .toggle_state(folded)
20427 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20428 if folded {
20429 this.unfold_at(buffer_row, window, cx);
20430 } else {
20431 this.fold_at(buffer_row, window, cx);
20432 }
20433 }))
20434 .into_any_element(),
20435 )
20436 } else {
20437 None
20438 }
20439 }
20440
20441 pub fn render_crease_trailer(
20442 &self,
20443 buffer_row: MultiBufferRow,
20444 window: &mut Window,
20445 cx: &mut App,
20446 ) -> Option<AnyElement> {
20447 let folded = self.is_line_folded(buffer_row);
20448 if let Crease::Inline { render_trailer, .. } = self
20449 .crease_snapshot
20450 .query_row(buffer_row, &self.buffer_snapshot)?
20451 {
20452 let render_trailer = render_trailer.as_ref()?;
20453 Some(render_trailer(buffer_row, folded, window, cx))
20454 } else {
20455 None
20456 }
20457 }
20458}
20459
20460impl Deref for EditorSnapshot {
20461 type Target = DisplaySnapshot;
20462
20463 fn deref(&self) -> &Self::Target {
20464 &self.display_snapshot
20465 }
20466}
20467
20468#[derive(Clone, Debug, PartialEq, Eq)]
20469pub enum EditorEvent {
20470 InputIgnored {
20471 text: Arc<str>,
20472 },
20473 InputHandled {
20474 utf16_range_to_replace: Option<Range<isize>>,
20475 text: Arc<str>,
20476 },
20477 ExcerptsAdded {
20478 buffer: Entity<Buffer>,
20479 predecessor: ExcerptId,
20480 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20481 },
20482 ExcerptsRemoved {
20483 ids: Vec<ExcerptId>,
20484 removed_buffer_ids: Vec<BufferId>,
20485 },
20486 BufferFoldToggled {
20487 ids: Vec<ExcerptId>,
20488 folded: bool,
20489 },
20490 ExcerptsEdited {
20491 ids: Vec<ExcerptId>,
20492 },
20493 ExcerptsExpanded {
20494 ids: Vec<ExcerptId>,
20495 },
20496 BufferEdited,
20497 Edited {
20498 transaction_id: clock::Lamport,
20499 },
20500 Reparsed(BufferId),
20501 Focused,
20502 FocusedIn,
20503 Blurred,
20504 DirtyChanged,
20505 Saved,
20506 TitleChanged,
20507 DiffBaseChanged,
20508 SelectionsChanged {
20509 local: bool,
20510 },
20511 ScrollPositionChanged {
20512 local: bool,
20513 autoscroll: bool,
20514 },
20515 Closed,
20516 TransactionUndone {
20517 transaction_id: clock::Lamport,
20518 },
20519 TransactionBegun {
20520 transaction_id: clock::Lamport,
20521 },
20522 Reloaded,
20523 CursorShapeChanged,
20524 PushedToNavHistory {
20525 anchor: Anchor,
20526 is_deactivate: bool,
20527 },
20528}
20529
20530impl EventEmitter<EditorEvent> for Editor {}
20531
20532impl Focusable for Editor {
20533 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20534 self.focus_handle.clone()
20535 }
20536}
20537
20538impl Render for Editor {
20539 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20540 let settings = ThemeSettings::get_global(cx);
20541
20542 let mut text_style = match self.mode {
20543 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20544 color: cx.theme().colors().editor_foreground,
20545 font_family: settings.ui_font.family.clone(),
20546 font_features: settings.ui_font.features.clone(),
20547 font_fallbacks: settings.ui_font.fallbacks.clone(),
20548 font_size: rems(0.875).into(),
20549 font_weight: settings.ui_font.weight,
20550 line_height: relative(settings.buffer_line_height.value()),
20551 ..Default::default()
20552 },
20553 EditorMode::Full { .. } | EditorMode::Minimap { .. } => TextStyle {
20554 color: cx.theme().colors().editor_foreground,
20555 font_family: settings.buffer_font.family.clone(),
20556 font_features: settings.buffer_font.features.clone(),
20557 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20558 font_size: settings.buffer_font_size(cx).into(),
20559 font_weight: settings.buffer_font.weight,
20560 line_height: relative(settings.buffer_line_height.value()),
20561 ..Default::default()
20562 },
20563 };
20564 if let Some(text_style_refinement) = &self.text_style_refinement {
20565 text_style.refine(text_style_refinement)
20566 }
20567
20568 let background = match self.mode {
20569 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20570 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20571 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20572 EditorMode::Minimap { .. } => cx.theme().colors().editor_background.opacity(0.7),
20573 };
20574
20575 EditorElement::new(
20576 &cx.entity(),
20577 EditorStyle {
20578 background,
20579 local_player: cx.theme().players().local(),
20580 text: text_style,
20581 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20582 syntax: cx.theme().syntax().clone(),
20583 status: cx.theme().status().clone(),
20584 inlay_hints_style: make_inlay_hints_style(cx),
20585 inline_completion_styles: make_suggestion_styles(cx),
20586 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20587 show_underlines: !self.mode.is_minimap(),
20588 },
20589 )
20590 }
20591}
20592
20593impl EntityInputHandler for Editor {
20594 fn text_for_range(
20595 &mut self,
20596 range_utf16: Range<usize>,
20597 adjusted_range: &mut Option<Range<usize>>,
20598 _: &mut Window,
20599 cx: &mut Context<Self>,
20600 ) -> Option<String> {
20601 let snapshot = self.buffer.read(cx).read(cx);
20602 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20603 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20604 if (start.0..end.0) != range_utf16 {
20605 adjusted_range.replace(start.0..end.0);
20606 }
20607 Some(snapshot.text_for_range(start..end).collect())
20608 }
20609
20610 fn selected_text_range(
20611 &mut self,
20612 ignore_disabled_input: bool,
20613 _: &mut Window,
20614 cx: &mut Context<Self>,
20615 ) -> Option<UTF16Selection> {
20616 // Prevent the IME menu from appearing when holding down an alphabetic key
20617 // while input is disabled.
20618 if !ignore_disabled_input && !self.input_enabled {
20619 return None;
20620 }
20621
20622 let selection = self.selections.newest::<OffsetUtf16>(cx);
20623 let range = selection.range();
20624
20625 Some(UTF16Selection {
20626 range: range.start.0..range.end.0,
20627 reversed: selection.reversed,
20628 })
20629 }
20630
20631 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20632 let snapshot = self.buffer.read(cx).read(cx);
20633 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20634 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20635 }
20636
20637 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20638 self.clear_highlights::<InputComposition>(cx);
20639 self.ime_transaction.take();
20640 }
20641
20642 fn replace_text_in_range(
20643 &mut self,
20644 range_utf16: Option<Range<usize>>,
20645 text: &str,
20646 window: &mut Window,
20647 cx: &mut Context<Self>,
20648 ) {
20649 if !self.input_enabled {
20650 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20651 return;
20652 }
20653
20654 self.transact(window, cx, |this, window, cx| {
20655 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20656 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20657 Some(this.selection_replacement_ranges(range_utf16, cx))
20658 } else {
20659 this.marked_text_ranges(cx)
20660 };
20661
20662 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20663 let newest_selection_id = this.selections.newest_anchor().id;
20664 this.selections
20665 .all::<OffsetUtf16>(cx)
20666 .iter()
20667 .zip(ranges_to_replace.iter())
20668 .find_map(|(selection, range)| {
20669 if selection.id == newest_selection_id {
20670 Some(
20671 (range.start.0 as isize - selection.head().0 as isize)
20672 ..(range.end.0 as isize - selection.head().0 as isize),
20673 )
20674 } else {
20675 None
20676 }
20677 })
20678 });
20679
20680 cx.emit(EditorEvent::InputHandled {
20681 utf16_range_to_replace: range_to_replace,
20682 text: text.into(),
20683 });
20684
20685 if let Some(new_selected_ranges) = new_selected_ranges {
20686 this.change_selections(None, window, cx, |selections| {
20687 selections.select_ranges(new_selected_ranges)
20688 });
20689 this.backspace(&Default::default(), window, cx);
20690 }
20691
20692 this.handle_input(text, window, cx);
20693 });
20694
20695 if let Some(transaction) = self.ime_transaction {
20696 self.buffer.update(cx, |buffer, cx| {
20697 buffer.group_until_transaction(transaction, cx);
20698 });
20699 }
20700
20701 self.unmark_text(window, cx);
20702 }
20703
20704 fn replace_and_mark_text_in_range(
20705 &mut self,
20706 range_utf16: Option<Range<usize>>,
20707 text: &str,
20708 new_selected_range_utf16: Option<Range<usize>>,
20709 window: &mut Window,
20710 cx: &mut Context<Self>,
20711 ) {
20712 if !self.input_enabled {
20713 return;
20714 }
20715
20716 let transaction = self.transact(window, cx, |this, window, cx| {
20717 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20718 let snapshot = this.buffer.read(cx).read(cx);
20719 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20720 for marked_range in &mut marked_ranges {
20721 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20722 marked_range.start.0 += relative_range_utf16.start;
20723 marked_range.start =
20724 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20725 marked_range.end =
20726 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20727 }
20728 }
20729 Some(marked_ranges)
20730 } else if let Some(range_utf16) = range_utf16 {
20731 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20732 Some(this.selection_replacement_ranges(range_utf16, cx))
20733 } else {
20734 None
20735 };
20736
20737 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20738 let newest_selection_id = this.selections.newest_anchor().id;
20739 this.selections
20740 .all::<OffsetUtf16>(cx)
20741 .iter()
20742 .zip(ranges_to_replace.iter())
20743 .find_map(|(selection, range)| {
20744 if selection.id == newest_selection_id {
20745 Some(
20746 (range.start.0 as isize - selection.head().0 as isize)
20747 ..(range.end.0 as isize - selection.head().0 as isize),
20748 )
20749 } else {
20750 None
20751 }
20752 })
20753 });
20754
20755 cx.emit(EditorEvent::InputHandled {
20756 utf16_range_to_replace: range_to_replace,
20757 text: text.into(),
20758 });
20759
20760 if let Some(ranges) = ranges_to_replace {
20761 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20762 }
20763
20764 let marked_ranges = {
20765 let snapshot = this.buffer.read(cx).read(cx);
20766 this.selections
20767 .disjoint_anchors()
20768 .iter()
20769 .map(|selection| {
20770 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20771 })
20772 .collect::<Vec<_>>()
20773 };
20774
20775 if text.is_empty() {
20776 this.unmark_text(window, cx);
20777 } else {
20778 this.highlight_text::<InputComposition>(
20779 marked_ranges.clone(),
20780 HighlightStyle {
20781 underline: Some(UnderlineStyle {
20782 thickness: px(1.),
20783 color: None,
20784 wavy: false,
20785 }),
20786 ..Default::default()
20787 },
20788 cx,
20789 );
20790 }
20791
20792 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20793 let use_autoclose = this.use_autoclose;
20794 let use_auto_surround = this.use_auto_surround;
20795 this.set_use_autoclose(false);
20796 this.set_use_auto_surround(false);
20797 this.handle_input(text, window, cx);
20798 this.set_use_autoclose(use_autoclose);
20799 this.set_use_auto_surround(use_auto_surround);
20800
20801 if let Some(new_selected_range) = new_selected_range_utf16 {
20802 let snapshot = this.buffer.read(cx).read(cx);
20803 let new_selected_ranges = marked_ranges
20804 .into_iter()
20805 .map(|marked_range| {
20806 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20807 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20808 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20809 snapshot.clip_offset_utf16(new_start, Bias::Left)
20810 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20811 })
20812 .collect::<Vec<_>>();
20813
20814 drop(snapshot);
20815 this.change_selections(None, window, cx, |selections| {
20816 selections.select_ranges(new_selected_ranges)
20817 });
20818 }
20819 });
20820
20821 self.ime_transaction = self.ime_transaction.or(transaction);
20822 if let Some(transaction) = self.ime_transaction {
20823 self.buffer.update(cx, |buffer, cx| {
20824 buffer.group_until_transaction(transaction, cx);
20825 });
20826 }
20827
20828 if self.text_highlights::<InputComposition>(cx).is_none() {
20829 self.ime_transaction.take();
20830 }
20831 }
20832
20833 fn bounds_for_range(
20834 &mut self,
20835 range_utf16: Range<usize>,
20836 element_bounds: gpui::Bounds<Pixels>,
20837 window: &mut Window,
20838 cx: &mut Context<Self>,
20839 ) -> Option<gpui::Bounds<Pixels>> {
20840 let text_layout_details = self.text_layout_details(window);
20841 let gpui::Size {
20842 width: em_width,
20843 height: line_height,
20844 } = self.character_size(window);
20845
20846 let snapshot = self.snapshot(window, cx);
20847 let scroll_position = snapshot.scroll_position();
20848 let scroll_left = scroll_position.x * em_width;
20849
20850 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20851 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20852 + self.gutter_dimensions.width
20853 + self.gutter_dimensions.margin;
20854 let y = line_height * (start.row().as_f32() - scroll_position.y);
20855
20856 Some(Bounds {
20857 origin: element_bounds.origin + point(x, y),
20858 size: size(em_width, line_height),
20859 })
20860 }
20861
20862 fn character_index_for_point(
20863 &mut self,
20864 point: gpui::Point<Pixels>,
20865 _window: &mut Window,
20866 _cx: &mut Context<Self>,
20867 ) -> Option<usize> {
20868 let position_map = self.last_position_map.as_ref()?;
20869 if !position_map.text_hitbox.contains(&point) {
20870 return None;
20871 }
20872 let display_point = position_map.point_for_position(point).previous_valid;
20873 let anchor = position_map
20874 .snapshot
20875 .display_point_to_anchor(display_point, Bias::Left);
20876 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20877 Some(utf16_offset.0)
20878 }
20879}
20880
20881trait SelectionExt {
20882 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20883 fn spanned_rows(
20884 &self,
20885 include_end_if_at_line_start: bool,
20886 map: &DisplaySnapshot,
20887 ) -> Range<MultiBufferRow>;
20888}
20889
20890impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20891 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20892 let start = self
20893 .start
20894 .to_point(&map.buffer_snapshot)
20895 .to_display_point(map);
20896 let end = self
20897 .end
20898 .to_point(&map.buffer_snapshot)
20899 .to_display_point(map);
20900 if self.reversed {
20901 end..start
20902 } else {
20903 start..end
20904 }
20905 }
20906
20907 fn spanned_rows(
20908 &self,
20909 include_end_if_at_line_start: bool,
20910 map: &DisplaySnapshot,
20911 ) -> Range<MultiBufferRow> {
20912 let start = self.start.to_point(&map.buffer_snapshot);
20913 let mut end = self.end.to_point(&map.buffer_snapshot);
20914 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20915 end.row -= 1;
20916 }
20917
20918 let buffer_start = map.prev_line_boundary(start).0;
20919 let buffer_end = map.next_line_boundary(end).0;
20920 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20921 }
20922}
20923
20924impl<T: InvalidationRegion> InvalidationStack<T> {
20925 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20926 where
20927 S: Clone + ToOffset,
20928 {
20929 while let Some(region) = self.last() {
20930 let all_selections_inside_invalidation_ranges =
20931 if selections.len() == region.ranges().len() {
20932 selections
20933 .iter()
20934 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20935 .all(|(selection, invalidation_range)| {
20936 let head = selection.head().to_offset(buffer);
20937 invalidation_range.start <= head && invalidation_range.end >= head
20938 })
20939 } else {
20940 false
20941 };
20942
20943 if all_selections_inside_invalidation_ranges {
20944 break;
20945 } else {
20946 self.pop();
20947 }
20948 }
20949 }
20950}
20951
20952impl<T> Default for InvalidationStack<T> {
20953 fn default() -> Self {
20954 Self(Default::default())
20955 }
20956}
20957
20958impl<T> Deref for InvalidationStack<T> {
20959 type Target = Vec<T>;
20960
20961 fn deref(&self) -> &Self::Target {
20962 &self.0
20963 }
20964}
20965
20966impl<T> DerefMut for InvalidationStack<T> {
20967 fn deref_mut(&mut self) -> &mut Self::Target {
20968 &mut self.0
20969 }
20970}
20971
20972impl InvalidationRegion for SnippetState {
20973 fn ranges(&self) -> &[Range<Anchor>] {
20974 &self.ranges[self.active_index]
20975 }
20976}
20977
20978fn inline_completion_edit_text(
20979 current_snapshot: &BufferSnapshot,
20980 edits: &[(Range<Anchor>, String)],
20981 edit_preview: &EditPreview,
20982 include_deletions: bool,
20983 cx: &App,
20984) -> HighlightedText {
20985 let edits = edits
20986 .iter()
20987 .map(|(anchor, text)| {
20988 (
20989 anchor.start.text_anchor..anchor.end.text_anchor,
20990 text.clone(),
20991 )
20992 })
20993 .collect::<Vec<_>>();
20994
20995 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20996}
20997
20998pub fn diagnostic_style(severity: lsp::DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20999 match severity {
21000 lsp::DiagnosticSeverity::ERROR => colors.error,
21001 lsp::DiagnosticSeverity::WARNING => colors.warning,
21002 lsp::DiagnosticSeverity::INFORMATION => colors.info,
21003 lsp::DiagnosticSeverity::HINT => colors.info,
21004 _ => colors.ignored,
21005 }
21006}
21007
21008pub fn styled_runs_for_code_label<'a>(
21009 label: &'a CodeLabel,
21010 syntax_theme: &'a theme::SyntaxTheme,
21011) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
21012 let fade_out = HighlightStyle {
21013 fade_out: Some(0.35),
21014 ..Default::default()
21015 };
21016
21017 let mut prev_end = label.filter_range.end;
21018 label
21019 .runs
21020 .iter()
21021 .enumerate()
21022 .flat_map(move |(ix, (range, highlight_id))| {
21023 let style = if let Some(style) = highlight_id.style(syntax_theme) {
21024 style
21025 } else {
21026 return Default::default();
21027 };
21028 let mut muted_style = style;
21029 muted_style.highlight(fade_out);
21030
21031 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
21032 if range.start >= label.filter_range.end {
21033 if range.start > prev_end {
21034 runs.push((prev_end..range.start, fade_out));
21035 }
21036 runs.push((range.clone(), muted_style));
21037 } else if range.end <= label.filter_range.end {
21038 runs.push((range.clone(), style));
21039 } else {
21040 runs.push((range.start..label.filter_range.end, style));
21041 runs.push((label.filter_range.end..range.end, muted_style));
21042 }
21043 prev_end = cmp::max(prev_end, range.end);
21044
21045 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
21046 runs.push((prev_end..label.text.len(), fade_out));
21047 }
21048
21049 runs
21050 })
21051}
21052
21053pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
21054 let mut prev_index = 0;
21055 let mut prev_codepoint: Option<char> = None;
21056 text.char_indices()
21057 .chain([(text.len(), '\0')])
21058 .filter_map(move |(index, codepoint)| {
21059 let prev_codepoint = prev_codepoint.replace(codepoint)?;
21060 let is_boundary = index == text.len()
21061 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
21062 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
21063 if is_boundary {
21064 let chunk = &text[prev_index..index];
21065 prev_index = index;
21066 Some(chunk)
21067 } else {
21068 None
21069 }
21070 })
21071}
21072
21073pub trait RangeToAnchorExt: Sized {
21074 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
21075
21076 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
21077 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
21078 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
21079 }
21080}
21081
21082impl<T: ToOffset> RangeToAnchorExt for Range<T> {
21083 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
21084 let start_offset = self.start.to_offset(snapshot);
21085 let end_offset = self.end.to_offset(snapshot);
21086 if start_offset == end_offset {
21087 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
21088 } else {
21089 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
21090 }
21091 }
21092}
21093
21094pub trait RowExt {
21095 fn as_f32(&self) -> f32;
21096
21097 fn next_row(&self) -> Self;
21098
21099 fn previous_row(&self) -> Self;
21100
21101 fn minus(&self, other: Self) -> u32;
21102}
21103
21104impl RowExt for DisplayRow {
21105 fn as_f32(&self) -> f32 {
21106 self.0 as f32
21107 }
21108
21109 fn next_row(&self) -> Self {
21110 Self(self.0 + 1)
21111 }
21112
21113 fn previous_row(&self) -> Self {
21114 Self(self.0.saturating_sub(1))
21115 }
21116
21117 fn minus(&self, other: Self) -> u32 {
21118 self.0 - other.0
21119 }
21120}
21121
21122impl RowExt for MultiBufferRow {
21123 fn as_f32(&self) -> f32 {
21124 self.0 as f32
21125 }
21126
21127 fn next_row(&self) -> Self {
21128 Self(self.0 + 1)
21129 }
21130
21131 fn previous_row(&self) -> Self {
21132 Self(self.0.saturating_sub(1))
21133 }
21134
21135 fn minus(&self, other: Self) -> u32 {
21136 self.0 - other.0
21137 }
21138}
21139
21140trait RowRangeExt {
21141 type Row;
21142
21143 fn len(&self) -> usize;
21144
21145 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
21146}
21147
21148impl RowRangeExt for Range<MultiBufferRow> {
21149 type Row = MultiBufferRow;
21150
21151 fn len(&self) -> usize {
21152 (self.end.0 - self.start.0) as usize
21153 }
21154
21155 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
21156 (self.start.0..self.end.0).map(MultiBufferRow)
21157 }
21158}
21159
21160impl RowRangeExt for Range<DisplayRow> {
21161 type Row = DisplayRow;
21162
21163 fn len(&self) -> usize {
21164 (self.end.0 - self.start.0) as usize
21165 }
21166
21167 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
21168 (self.start.0..self.end.0).map(DisplayRow)
21169 }
21170}
21171
21172/// If select range has more than one line, we
21173/// just point the cursor to range.start.
21174fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
21175 if range.start.row == range.end.row {
21176 range
21177 } else {
21178 range.start..range.start
21179 }
21180}
21181pub struct KillRing(ClipboardItem);
21182impl Global for KillRing {}
21183
21184const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
21185
21186enum BreakpointPromptEditAction {
21187 Log,
21188 Condition,
21189 HitCondition,
21190}
21191
21192struct BreakpointPromptEditor {
21193 pub(crate) prompt: Entity<Editor>,
21194 editor: WeakEntity<Editor>,
21195 breakpoint_anchor: Anchor,
21196 breakpoint: Breakpoint,
21197 edit_action: BreakpointPromptEditAction,
21198 block_ids: HashSet<CustomBlockId>,
21199 editor_margins: Arc<Mutex<EditorMargins>>,
21200 _subscriptions: Vec<Subscription>,
21201}
21202
21203impl BreakpointPromptEditor {
21204 const MAX_LINES: u8 = 4;
21205
21206 fn new(
21207 editor: WeakEntity<Editor>,
21208 breakpoint_anchor: Anchor,
21209 breakpoint: Breakpoint,
21210 edit_action: BreakpointPromptEditAction,
21211 window: &mut Window,
21212 cx: &mut Context<Self>,
21213 ) -> Self {
21214 let base_text = match edit_action {
21215 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
21216 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
21217 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
21218 }
21219 .map(|msg| msg.to_string())
21220 .unwrap_or_default();
21221
21222 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
21223 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
21224
21225 let prompt = cx.new(|cx| {
21226 let mut prompt = Editor::new(
21227 EditorMode::AutoHeight {
21228 max_lines: Self::MAX_LINES as usize,
21229 },
21230 buffer,
21231 None,
21232 window,
21233 cx,
21234 );
21235 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21236 prompt.set_show_cursor_when_unfocused(false, cx);
21237 prompt.set_placeholder_text(
21238 match edit_action {
21239 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21240 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21241 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21242 },
21243 cx,
21244 );
21245
21246 prompt
21247 });
21248
21249 Self {
21250 prompt,
21251 editor,
21252 breakpoint_anchor,
21253 breakpoint,
21254 edit_action,
21255 editor_margins: Arc::new(Mutex::new(EditorMargins::default())),
21256 block_ids: Default::default(),
21257 _subscriptions: vec![],
21258 }
21259 }
21260
21261 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21262 self.block_ids.extend(block_ids)
21263 }
21264
21265 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21266 if let Some(editor) = self.editor.upgrade() {
21267 let message = self
21268 .prompt
21269 .read(cx)
21270 .buffer
21271 .read(cx)
21272 .as_singleton()
21273 .expect("A multi buffer in breakpoint prompt isn't possible")
21274 .read(cx)
21275 .as_rope()
21276 .to_string();
21277
21278 editor.update(cx, |editor, cx| {
21279 editor.edit_breakpoint_at_anchor(
21280 self.breakpoint_anchor,
21281 self.breakpoint.clone(),
21282 match self.edit_action {
21283 BreakpointPromptEditAction::Log => {
21284 BreakpointEditAction::EditLogMessage(message.into())
21285 }
21286 BreakpointPromptEditAction::Condition => {
21287 BreakpointEditAction::EditCondition(message.into())
21288 }
21289 BreakpointPromptEditAction::HitCondition => {
21290 BreakpointEditAction::EditHitCondition(message.into())
21291 }
21292 },
21293 cx,
21294 );
21295
21296 editor.remove_blocks(self.block_ids.clone(), None, cx);
21297 cx.focus_self(window);
21298 });
21299 }
21300 }
21301
21302 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21303 self.editor
21304 .update(cx, |editor, cx| {
21305 editor.remove_blocks(self.block_ids.clone(), None, cx);
21306 window.focus(&editor.focus_handle);
21307 })
21308 .log_err();
21309 }
21310
21311 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21312 let settings = ThemeSettings::get_global(cx);
21313 let text_style = TextStyle {
21314 color: if self.prompt.read(cx).read_only(cx) {
21315 cx.theme().colors().text_disabled
21316 } else {
21317 cx.theme().colors().text
21318 },
21319 font_family: settings.buffer_font.family.clone(),
21320 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21321 font_size: settings.buffer_font_size(cx).into(),
21322 font_weight: settings.buffer_font.weight,
21323 line_height: relative(settings.buffer_line_height.value()),
21324 ..Default::default()
21325 };
21326 EditorElement::new(
21327 &self.prompt,
21328 EditorStyle {
21329 background: cx.theme().colors().editor_background,
21330 local_player: cx.theme().players().local(),
21331 text: text_style,
21332 ..Default::default()
21333 },
21334 )
21335 }
21336}
21337
21338impl Render for BreakpointPromptEditor {
21339 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21340 let editor_margins = *self.editor_margins.lock();
21341 let gutter_dimensions = editor_margins.gutter;
21342 h_flex()
21343 .key_context("Editor")
21344 .bg(cx.theme().colors().editor_background)
21345 .border_y_1()
21346 .border_color(cx.theme().status().info_border)
21347 .size_full()
21348 .py(window.line_height() / 2.5)
21349 .on_action(cx.listener(Self::confirm))
21350 .on_action(cx.listener(Self::cancel))
21351 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21352 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21353 }
21354}
21355
21356impl Focusable for BreakpointPromptEditor {
21357 fn focus_handle(&self, cx: &App) -> FocusHandle {
21358 self.prompt.focus_handle(cx)
21359 }
21360}
21361
21362fn all_edits_insertions_or_deletions(
21363 edits: &Vec<(Range<Anchor>, String)>,
21364 snapshot: &MultiBufferSnapshot,
21365) -> bool {
21366 let mut all_insertions = true;
21367 let mut all_deletions = true;
21368
21369 for (range, new_text) in edits.iter() {
21370 let range_is_empty = range.to_offset(&snapshot).is_empty();
21371 let text_is_empty = new_text.is_empty();
21372
21373 if range_is_empty != text_is_empty {
21374 if range_is_empty {
21375 all_deletions = false;
21376 } else {
21377 all_insertions = false;
21378 }
21379 } else {
21380 return false;
21381 }
21382
21383 if !all_insertions && !all_deletions {
21384 return false;
21385 }
21386 }
21387 all_insertions || all_deletions
21388}
21389
21390struct MissingEditPredictionKeybindingTooltip;
21391
21392impl Render for MissingEditPredictionKeybindingTooltip {
21393 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21394 ui::tooltip_container(window, cx, |container, _, cx| {
21395 container
21396 .flex_shrink_0()
21397 .max_w_80()
21398 .min_h(rems_from_px(124.))
21399 .justify_between()
21400 .child(
21401 v_flex()
21402 .flex_1()
21403 .text_ui_sm(cx)
21404 .child(Label::new("Conflict with Accept Keybinding"))
21405 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21406 )
21407 .child(
21408 h_flex()
21409 .pb_1()
21410 .gap_1()
21411 .items_end()
21412 .w_full()
21413 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21414 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21415 }))
21416 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21417 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21418 })),
21419 )
21420 })
21421 }
21422}
21423
21424#[derive(Debug, Clone, Copy, PartialEq)]
21425pub struct LineHighlight {
21426 pub background: Background,
21427 pub border: Option<gpui::Hsla>,
21428 pub include_gutter: bool,
21429 pub type_id: Option<TypeId>,
21430}
21431
21432fn render_diff_hunk_controls(
21433 row: u32,
21434 status: &DiffHunkStatus,
21435 hunk_range: Range<Anchor>,
21436 is_created_file: bool,
21437 line_height: Pixels,
21438 editor: &Entity<Editor>,
21439 _window: &mut Window,
21440 cx: &mut App,
21441) -> AnyElement {
21442 h_flex()
21443 .h(line_height)
21444 .mr_1()
21445 .gap_1()
21446 .px_0p5()
21447 .pb_1()
21448 .border_x_1()
21449 .border_b_1()
21450 .border_color(cx.theme().colors().border_variant)
21451 .rounded_b_lg()
21452 .bg(cx.theme().colors().editor_background)
21453 .gap_1()
21454 .occlude()
21455 .shadow_md()
21456 .child(if status.has_secondary_hunk() {
21457 Button::new(("stage", row as u64), "Stage")
21458 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21459 .tooltip({
21460 let focus_handle = editor.focus_handle(cx);
21461 move |window, cx| {
21462 Tooltip::for_action_in(
21463 "Stage Hunk",
21464 &::git::ToggleStaged,
21465 &focus_handle,
21466 window,
21467 cx,
21468 )
21469 }
21470 })
21471 .on_click({
21472 let editor = editor.clone();
21473 move |_event, _window, cx| {
21474 editor.update(cx, |editor, cx| {
21475 editor.stage_or_unstage_diff_hunks(
21476 true,
21477 vec![hunk_range.start..hunk_range.start],
21478 cx,
21479 );
21480 });
21481 }
21482 })
21483 } else {
21484 Button::new(("unstage", row as u64), "Unstage")
21485 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21486 .tooltip({
21487 let focus_handle = editor.focus_handle(cx);
21488 move |window, cx| {
21489 Tooltip::for_action_in(
21490 "Unstage Hunk",
21491 &::git::ToggleStaged,
21492 &focus_handle,
21493 window,
21494 cx,
21495 )
21496 }
21497 })
21498 .on_click({
21499 let editor = editor.clone();
21500 move |_event, _window, cx| {
21501 editor.update(cx, |editor, cx| {
21502 editor.stage_or_unstage_diff_hunks(
21503 false,
21504 vec![hunk_range.start..hunk_range.start],
21505 cx,
21506 );
21507 });
21508 }
21509 })
21510 })
21511 .child(
21512 Button::new(("restore", row as u64), "Restore")
21513 .tooltip({
21514 let focus_handle = editor.focus_handle(cx);
21515 move |window, cx| {
21516 Tooltip::for_action_in(
21517 "Restore Hunk",
21518 &::git::Restore,
21519 &focus_handle,
21520 window,
21521 cx,
21522 )
21523 }
21524 })
21525 .on_click({
21526 let editor = editor.clone();
21527 move |_event, window, cx| {
21528 editor.update(cx, |editor, cx| {
21529 let snapshot = editor.snapshot(window, cx);
21530 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21531 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21532 });
21533 }
21534 })
21535 .disabled(is_created_file),
21536 )
21537 .when(
21538 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21539 |el| {
21540 el.child(
21541 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21542 .shape(IconButtonShape::Square)
21543 .icon_size(IconSize::Small)
21544 // .disabled(!has_multiple_hunks)
21545 .tooltip({
21546 let focus_handle = editor.focus_handle(cx);
21547 move |window, cx| {
21548 Tooltip::for_action_in(
21549 "Next Hunk",
21550 &GoToHunk,
21551 &focus_handle,
21552 window,
21553 cx,
21554 )
21555 }
21556 })
21557 .on_click({
21558 let editor = editor.clone();
21559 move |_event, window, cx| {
21560 editor.update(cx, |editor, cx| {
21561 let snapshot = editor.snapshot(window, cx);
21562 let position =
21563 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21564 editor.go_to_hunk_before_or_after_position(
21565 &snapshot,
21566 position,
21567 Direction::Next,
21568 window,
21569 cx,
21570 );
21571 editor.expand_selected_diff_hunks(cx);
21572 });
21573 }
21574 }),
21575 )
21576 .child(
21577 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21578 .shape(IconButtonShape::Square)
21579 .icon_size(IconSize::Small)
21580 // .disabled(!has_multiple_hunks)
21581 .tooltip({
21582 let focus_handle = editor.focus_handle(cx);
21583 move |window, cx| {
21584 Tooltip::for_action_in(
21585 "Previous Hunk",
21586 &GoToPreviousHunk,
21587 &focus_handle,
21588 window,
21589 cx,
21590 )
21591 }
21592 })
21593 .on_click({
21594 let editor = editor.clone();
21595 move |_event, window, cx| {
21596 editor.update(cx, |editor, cx| {
21597 let snapshot = editor.snapshot(window, cx);
21598 let point =
21599 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21600 editor.go_to_hunk_before_or_after_position(
21601 &snapshot,
21602 point,
21603 Direction::Prev,
21604 window,
21605 cx,
21606 );
21607 editor.expand_selected_diff_hunks(cx);
21608 });
21609 }
21610 }),
21611 )
21612 },
21613 )
21614 .into_any_element()
21615}