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};
64use editor_settings::GoToDefinitionFallback;
65pub use editor_settings::{
66 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
67 ShowScrollbar,
68};
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};
133
134pub use git::blame::BlameRenderer;
135pub use proposed_changes_editor::{
136 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
137};
138use smallvec::smallvec;
139use std::{cell::OnceCell, iter::Peekable};
140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
141
142pub use lsp::CompletionContext;
143use lsp::{
144 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
145 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
146};
147
148use language::BufferSnapshot;
149pub use lsp_ext::lsp_tasks;
150use movement::TextLayoutDetails;
151pub use multi_buffer::{
152 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
153 RowInfo, ToOffset, ToPoint,
154};
155use multi_buffer::{
156 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
157 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
158};
159use parking_lot::Mutex;
160use project::{
161 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
162 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
163 TaskSourceKind,
164 debugger::breakpoint_store::Breakpoint,
165 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
166 project_settings::{GitGutterSetting, ProjectSettings},
167};
168use rand::prelude::*;
169use rpc::{ErrorExt, proto::*};
170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
171use selections_collection::{
172 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
173};
174use serde::{Deserialize, Serialize};
175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
176use smallvec::SmallVec;
177use snippet::Snippet;
178use std::sync::Arc;
179use std::{
180 any::TypeId,
181 borrow::Cow,
182 cell::RefCell,
183 cmp::{self, Ordering, Reverse},
184 mem,
185 num::NonZeroU32,
186 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
187 path::{Path, PathBuf},
188 rc::Rc,
189 time::{Duration, Instant},
190};
191pub use sum_tree::Bias;
192use sum_tree::TreeMap;
193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
194use theme::{
195 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
196 observe_buffer_font_size_adjustment,
197};
198use ui::{
199 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
200 IconSize, Key, Tooltip, h_flex, prelude::*,
201};
202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
203use workspace::{
204 CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
205 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
206 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
207 item::{ItemHandle, PreviewTabsSettings},
208 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
209 searchable::SearchEvent,
210};
211
212use crate::hover_links::{find_url, find_url_from_range};
213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
214
215pub const FILE_HEADER_HEIGHT: u32 = 2;
216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
219const MAX_LINE_LEN: usize = 1024;
220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
223#[doc(hidden)]
224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
226
227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
230
231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
234
235pub type RenderDiffHunkControlsFn = Arc<
236 dyn Fn(
237 u32,
238 &DiffHunkStatus,
239 Range<Anchor>,
240 bool,
241 Pixels,
242 &Entity<Editor>,
243 &mut Window,
244 &mut App,
245 ) -> AnyElement,
246>;
247
248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
249 alt: true,
250 shift: true,
251 control: false,
252 platform: false,
253 function: false,
254};
255
256struct InlineValueCache {
257 enabled: bool,
258 inlays: Vec<InlayId>,
259 refresh_task: Task<Option<()>>,
260}
261
262impl InlineValueCache {
263 fn new(enabled: bool) -> Self {
264 Self {
265 enabled,
266 inlays: Vec::new(),
267 refresh_task: Task::ready(None),
268 }
269 }
270}
271
272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
273pub enum InlayId {
274 InlineCompletion(usize),
275 Hint(usize),
276 DebuggerValue(usize),
277}
278
279impl InlayId {
280 fn id(&self) -> usize {
281 match self {
282 Self::InlineCompletion(id) => *id,
283 Self::Hint(id) => *id,
284 Self::DebuggerValue(id) => *id,
285 }
286 }
287}
288
289pub enum ActiveDebugLine {}
290enum DocumentHighlightRead {}
291enum DocumentHighlightWrite {}
292enum InputComposition {}
293enum SelectedTextHighlight {}
294
295pub enum ConflictsOuter {}
296pub enum ConflictsOurs {}
297pub enum ConflictsTheirs {}
298pub enum ConflictsOursMarker {}
299pub enum ConflictsTheirsMarker {}
300
301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
302pub enum Navigated {
303 Yes,
304 No,
305}
306
307impl Navigated {
308 pub fn from_bool(yes: bool) -> Navigated {
309 if yes { Navigated::Yes } else { Navigated::No }
310 }
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
314enum DisplayDiffHunk {
315 Folded {
316 display_row: DisplayRow,
317 },
318 Unfolded {
319 is_created_file: bool,
320 diff_base_byte_range: Range<usize>,
321 display_row_range: Range<DisplayRow>,
322 multi_buffer_range: Range<Anchor>,
323 status: DiffHunkStatus,
324 },
325}
326
327pub enum HideMouseCursorOrigin {
328 TypingAction,
329 MovementAction,
330}
331
332pub fn init_settings(cx: &mut App) {
333 EditorSettings::register(cx);
334}
335
336pub fn init(cx: &mut App) {
337 init_settings(cx);
338
339 cx.set_global(GlobalBlameRenderer(Arc::new(())));
340
341 workspace::register_project_item::<Editor>(cx);
342 workspace::FollowableViewRegistry::register::<Editor>(cx);
343 workspace::register_serializable_item::<Editor>(cx);
344
345 cx.observe_new(
346 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
347 workspace.register_action(Editor::new_file);
348 workspace.register_action(Editor::new_file_vertical);
349 workspace.register_action(Editor::new_file_horizontal);
350 workspace.register_action(Editor::cancel_language_server_work);
351 },
352 )
353 .detach();
354
355 cx.on_action(move |_: &workspace::NewFile, cx| {
356 let app_state = workspace::AppState::global(cx);
357 if let Some(app_state) = app_state.upgrade() {
358 workspace::open_new(
359 Default::default(),
360 app_state,
361 cx,
362 |workspace, window, cx| {
363 Editor::new_file(workspace, &Default::default(), window, cx)
364 },
365 )
366 .detach();
367 }
368 });
369 cx.on_action(move |_: &workspace::NewWindow, cx| {
370 let app_state = workspace::AppState::global(cx);
371 if let Some(app_state) = app_state.upgrade() {
372 workspace::open_new(
373 Default::default(),
374 app_state,
375 cx,
376 |workspace, window, cx| {
377 cx.activate(true);
378 Editor::new_file(workspace, &Default::default(), window, cx)
379 },
380 )
381 .detach();
382 }
383 });
384}
385
386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
387 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
388}
389
390pub trait DiagnosticRenderer {
391 fn render_group(
392 &self,
393 diagnostic_group: Vec<DiagnosticEntry<Point>>,
394 buffer_id: BufferId,
395 snapshot: EditorSnapshot,
396 editor: WeakEntity<Editor>,
397 cx: &mut App,
398 ) -> Vec<BlockProperties<Anchor>>;
399
400 fn render_hover(
401 &self,
402 diagnostic_group: Vec<DiagnosticEntry<Point>>,
403 range: Range<Point>,
404 buffer_id: BufferId,
405 cx: &mut App,
406 ) -> Option<Entity<markdown::Markdown>>;
407
408 fn open_link(
409 &self,
410 editor: &mut Editor,
411 link: SharedString,
412 window: &mut Window,
413 cx: &mut Context<Editor>,
414 );
415}
416
417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
418
419impl GlobalDiagnosticRenderer {
420 fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
421 cx.try_global::<Self>().map(|g| g.0.clone())
422 }
423}
424
425impl gpui::Global for GlobalDiagnosticRenderer {}
426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
427 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
428}
429
430pub struct SearchWithinRange;
431
432trait InvalidationRegion {
433 fn ranges(&self) -> &[Range<Anchor>];
434}
435
436#[derive(Clone, Debug, PartialEq)]
437pub enum SelectPhase {
438 Begin {
439 position: DisplayPoint,
440 add: bool,
441 click_count: usize,
442 },
443 BeginColumnar {
444 position: DisplayPoint,
445 reset: bool,
446 goal_column: u32,
447 },
448 Extend {
449 position: DisplayPoint,
450 click_count: usize,
451 },
452 Update {
453 position: DisplayPoint,
454 goal_column: u32,
455 scroll_delta: gpui::Point<f32>,
456 },
457 End,
458}
459
460#[derive(Clone, Debug)]
461pub enum SelectMode {
462 Character,
463 Word(Range<Anchor>),
464 Line(Range<Anchor>),
465 All,
466}
467
468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
469pub enum EditorMode {
470 SingleLine {
471 auto_width: bool,
472 },
473 AutoHeight {
474 max_lines: usize,
475 },
476 Full {
477 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
478 scale_ui_elements_with_buffer_font_size: bool,
479 /// When set to `true`, the editor will render a background for the active line.
480 show_active_line_background: bool,
481 /// When set to `true`, the editor's height will be determined by its content.
482 sized_by_content: bool,
483 },
484}
485
486impl EditorMode {
487 pub fn full() -> Self {
488 Self::Full {
489 scale_ui_elements_with_buffer_font_size: true,
490 show_active_line_background: true,
491 sized_by_content: false,
492 }
493 }
494
495 pub fn is_full(&self) -> bool {
496 matches!(self, Self::Full { .. })
497 }
498}
499
500#[derive(Copy, Clone, Debug)]
501pub enum SoftWrap {
502 /// Prefer not to wrap at all.
503 ///
504 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
505 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
506 GitDiff,
507 /// Prefer a single line generally, unless an overly long line is encountered.
508 None,
509 /// Soft wrap lines that exceed the editor width.
510 EditorWidth,
511 /// Soft wrap lines at the preferred line length.
512 Column(u32),
513 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
514 Bounded(u32),
515}
516
517#[derive(Clone)]
518pub struct EditorStyle {
519 pub background: Hsla,
520 pub horizontal_padding: Pixels,
521 pub local_player: PlayerColor,
522 pub text: TextStyle,
523 pub scrollbar_width: Pixels,
524 pub syntax: Arc<SyntaxTheme>,
525 pub status: StatusColors,
526 pub inlay_hints_style: HighlightStyle,
527 pub inline_completion_styles: InlineCompletionStyles,
528 pub unnecessary_code_fade: f32,
529}
530
531impl Default for EditorStyle {
532 fn default() -> Self {
533 Self {
534 background: Hsla::default(),
535 horizontal_padding: Pixels::default(),
536 local_player: PlayerColor::default(),
537 text: TextStyle::default(),
538 scrollbar_width: Pixels::default(),
539 syntax: Default::default(),
540 // HACK: Status colors don't have a real default.
541 // We should look into removing the status colors from the editor
542 // style and retrieve them directly from the theme.
543 status: StatusColors::dark(),
544 inlay_hints_style: HighlightStyle::default(),
545 inline_completion_styles: InlineCompletionStyles {
546 insertion: HighlightStyle::default(),
547 whitespace: HighlightStyle::default(),
548 },
549 unnecessary_code_fade: Default::default(),
550 }
551 }
552}
553
554pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
555 let show_background = language_settings::language_settings(None, None, cx)
556 .inlay_hints
557 .show_background;
558
559 HighlightStyle {
560 color: Some(cx.theme().status().hint),
561 background_color: show_background.then(|| cx.theme().status().hint_background),
562 ..HighlightStyle::default()
563 }
564}
565
566pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
567 InlineCompletionStyles {
568 insertion: HighlightStyle {
569 color: Some(cx.theme().status().predictive),
570 ..HighlightStyle::default()
571 },
572 whitespace: HighlightStyle {
573 background_color: Some(cx.theme().status().created_background),
574 ..HighlightStyle::default()
575 },
576 }
577}
578
579type CompletionId = usize;
580
581pub(crate) enum EditDisplayMode {
582 TabAccept,
583 DiffPopover,
584 Inline,
585}
586
587enum InlineCompletion {
588 Edit {
589 edits: Vec<(Range<Anchor>, String)>,
590 edit_preview: Option<EditPreview>,
591 display_mode: EditDisplayMode,
592 snapshot: BufferSnapshot,
593 },
594 Move {
595 target: Anchor,
596 snapshot: BufferSnapshot,
597 },
598}
599
600struct InlineCompletionState {
601 inlay_ids: Vec<InlayId>,
602 completion: InlineCompletion,
603 completion_id: Option<SharedString>,
604 invalidation_range: Range<Anchor>,
605}
606
607enum EditPredictionSettings {
608 Disabled,
609 Enabled {
610 show_in_menu: bool,
611 preview_requires_modifier: bool,
612 },
613}
614
615enum InlineCompletionHighlight {}
616
617#[derive(Debug, Clone)]
618struct InlineDiagnostic {
619 message: SharedString,
620 group_id: usize,
621 is_primary: bool,
622 start: Point,
623 severity: DiagnosticSeverity,
624}
625
626pub enum MenuInlineCompletionsPolicy {
627 Never,
628 ByProvider,
629}
630
631pub enum EditPredictionPreview {
632 /// Modifier is not pressed
633 Inactive { released_too_fast: bool },
634 /// Modifier pressed
635 Active {
636 since: Instant,
637 previous_scroll_position: Option<ScrollAnchor>,
638 },
639}
640
641impl EditPredictionPreview {
642 pub fn released_too_fast(&self) -> bool {
643 match self {
644 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
645 EditPredictionPreview::Active { .. } => false,
646 }
647 }
648
649 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
650 if let EditPredictionPreview::Active {
651 previous_scroll_position,
652 ..
653 } = self
654 {
655 *previous_scroll_position = scroll_position;
656 }
657 }
658}
659
660pub struct ContextMenuOptions {
661 pub min_entries_visible: usize,
662 pub max_entries_visible: usize,
663 pub placement: Option<ContextMenuPlacement>,
664}
665
666#[derive(Debug, Clone, PartialEq, Eq)]
667pub enum ContextMenuPlacement {
668 Above,
669 Below,
670}
671
672#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
673struct EditorActionId(usize);
674
675impl EditorActionId {
676 pub fn post_inc(&mut self) -> Self {
677 let answer = self.0;
678
679 *self = Self(answer + 1);
680
681 Self(answer)
682 }
683}
684
685// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
686// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
687
688type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
689type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
690
691#[derive(Default)]
692struct ScrollbarMarkerState {
693 scrollbar_size: Size<Pixels>,
694 dirty: bool,
695 markers: Arc<[PaintQuad]>,
696 pending_refresh: Option<Task<Result<()>>>,
697}
698
699impl ScrollbarMarkerState {
700 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
701 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
702 }
703}
704
705#[derive(Clone, Debug)]
706struct RunnableTasks {
707 templates: Vec<(TaskSourceKind, TaskTemplate)>,
708 offset: multi_buffer::Anchor,
709 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
710 column: u32,
711 // Values of all named captures, including those starting with '_'
712 extra_variables: HashMap<String, String>,
713 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
714 context_range: Range<BufferOffset>,
715}
716
717impl RunnableTasks {
718 fn resolve<'a>(
719 &'a self,
720 cx: &'a task::TaskContext,
721 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
722 self.templates.iter().filter_map(|(kind, template)| {
723 template
724 .resolve_task(&kind.to_id_base(), cx)
725 .map(|task| (kind.clone(), task))
726 })
727 }
728}
729
730#[derive(Clone)]
731struct ResolvedTasks {
732 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
733 position: Anchor,
734}
735
736#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
737struct BufferOffset(usize);
738
739// Addons allow storing per-editor state in other crates (e.g. Vim)
740pub trait Addon: 'static {
741 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
742
743 fn render_buffer_header_controls(
744 &self,
745 _: &ExcerptInfo,
746 _: &Window,
747 _: &App,
748 ) -> Option<AnyElement> {
749 None
750 }
751
752 fn to_any(&self) -> &dyn std::any::Any;
753
754 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
755 None
756 }
757}
758
759/// A set of caret positions, registered when the editor was edited.
760pub struct ChangeList {
761 changes: Vec<Vec<Anchor>>,
762 /// Currently "selected" change.
763 position: Option<usize>,
764}
765
766impl ChangeList {
767 pub fn new() -> Self {
768 Self {
769 changes: Vec::new(),
770 position: None,
771 }
772 }
773
774 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
775 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
776 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
777 if self.changes.is_empty() {
778 return None;
779 }
780
781 let prev = self.position.unwrap_or(self.changes.len());
782 let next = if direction == Direction::Prev {
783 prev.saturating_sub(count)
784 } else {
785 (prev + count).min(self.changes.len() - 1)
786 };
787 self.position = Some(next);
788 self.changes.get(next).map(|anchors| anchors.as_slice())
789 }
790
791 /// Adds a new change to the list, resetting the change list position.
792 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
793 self.position.take();
794 if pop_state {
795 self.changes.pop();
796 }
797 self.changes.push(new_positions.clone());
798 }
799
800 pub fn last(&self) -> Option<&[Anchor]> {
801 self.changes.last().map(|anchors| anchors.as_slice())
802 }
803}
804
805#[derive(Clone)]
806struct InlineBlamePopoverState {
807 scroll_handle: ScrollHandle,
808 commit_message: Option<ParsedCommitMessage>,
809 markdown: Entity<Markdown>,
810}
811
812struct InlineBlamePopover {
813 position: gpui::Point<Pixels>,
814 show_task: Option<Task<()>>,
815 hide_task: Option<Task<()>>,
816 popover_bounds: Option<Bounds<Pixels>>,
817 popover_state: InlineBlamePopoverState,
818}
819
820/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
821/// a breakpoint on them.
822#[derive(Clone, Copy, Debug)]
823struct PhantomBreakpointIndicator {
824 display_row: DisplayRow,
825 /// There's a small debounce between hovering over the line and showing the indicator.
826 /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
827 is_active: bool,
828 collides_with_existing_breakpoint: bool,
829}
830/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
831///
832/// See the [module level documentation](self) for more information.
833pub struct Editor {
834 focus_handle: FocusHandle,
835 last_focused_descendant: Option<WeakFocusHandle>,
836 /// The text buffer being edited
837 buffer: Entity<MultiBuffer>,
838 /// Map of how text in the buffer should be displayed.
839 /// Handles soft wraps, folds, fake inlay text insertions, etc.
840 pub display_map: Entity<DisplayMap>,
841 pub selections: SelectionsCollection,
842 pub scroll_manager: ScrollManager,
843 /// When inline assist editors are linked, they all render cursors because
844 /// typing enters text into each of them, even the ones that aren't focused.
845 pub(crate) show_cursor_when_unfocused: bool,
846 columnar_selection_tail: Option<Anchor>,
847 add_selections_state: Option<AddSelectionsState>,
848 select_next_state: Option<SelectNextState>,
849 select_prev_state: Option<SelectNextState>,
850 selection_history: SelectionHistory,
851 autoclose_regions: Vec<AutocloseRegion>,
852 snippet_stack: InvalidationStack<SnippetState>,
853 select_syntax_node_history: SelectSyntaxNodeHistory,
854 ime_transaction: Option<TransactionId>,
855 active_diagnostics: ActiveDiagnostic,
856 show_inline_diagnostics: bool,
857 inline_diagnostics_update: Task<()>,
858 inline_diagnostics_enabled: bool,
859 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
860 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
861 hard_wrap: Option<usize>,
862
863 // TODO: make this a access method
864 pub project: Option<Entity<Project>>,
865 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
866 completion_provider: Option<Box<dyn CompletionProvider>>,
867 collaboration_hub: Option<Box<dyn CollaborationHub>>,
868 blink_manager: Entity<BlinkManager>,
869 show_cursor_names: bool,
870 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
871 pub show_local_selections: bool,
872 mode: EditorMode,
873 show_breadcrumbs: bool,
874 show_gutter: bool,
875 show_scrollbars: bool,
876 disable_expand_excerpt_buttons: bool,
877 show_line_numbers: Option<bool>,
878 use_relative_line_numbers: Option<bool>,
879 show_git_diff_gutter: Option<bool>,
880 show_code_actions: Option<bool>,
881 show_runnables: Option<bool>,
882 show_breakpoints: Option<bool>,
883 show_wrap_guides: Option<bool>,
884 show_indent_guides: Option<bool>,
885 placeholder_text: Option<Arc<str>>,
886 highlight_order: usize,
887 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
888 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
889 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
890 scrollbar_marker_state: ScrollbarMarkerState,
891 active_indent_guides_state: ActiveIndentGuidesState,
892 nav_history: Option<ItemNavHistory>,
893 context_menu: RefCell<Option<CodeContextMenu>>,
894 context_menu_options: Option<ContextMenuOptions>,
895 mouse_context_menu: Option<MouseContextMenu>,
896 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
897 inline_blame_popover: Option<InlineBlamePopover>,
898 signature_help_state: SignatureHelpState,
899 auto_signature_help: Option<bool>,
900 find_all_references_task_sources: Vec<Anchor>,
901 next_completion_id: CompletionId,
902 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
903 code_actions_task: Option<Task<Result<()>>>,
904 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
905 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
906 document_highlights_task: Option<Task<()>>,
907 linked_editing_range_task: Option<Task<Option<()>>>,
908 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
909 pending_rename: Option<RenameState>,
910 searchable: bool,
911 cursor_shape: CursorShape,
912 current_line_highlight: Option<CurrentLineHighlight>,
913 collapse_matches: bool,
914 autoindent_mode: Option<AutoindentMode>,
915 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
916 input_enabled: bool,
917 use_modal_editing: bool,
918 read_only: bool,
919 leader_id: Option<CollaboratorId>,
920 remote_id: Option<ViewId>,
921 pub hover_state: HoverState,
922 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
923 gutter_hovered: bool,
924 hovered_link_state: Option<HoveredLinkState>,
925 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
926 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
927 active_inline_completion: Option<InlineCompletionState>,
928 /// Used to prevent flickering as the user types while the menu is open
929 stale_inline_completion_in_menu: Option<InlineCompletionState>,
930 edit_prediction_settings: EditPredictionSettings,
931 inline_completions_hidden_for_vim_mode: bool,
932 show_inline_completions_override: Option<bool>,
933 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
934 edit_prediction_preview: EditPredictionPreview,
935 edit_prediction_indent_conflict: bool,
936 edit_prediction_requires_modifier_in_indent_conflict: bool,
937 inlay_hint_cache: InlayHintCache,
938 next_inlay_id: usize,
939 _subscriptions: Vec<Subscription>,
940 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
941 gutter_dimensions: GutterDimensions,
942 style: Option<EditorStyle>,
943 text_style_refinement: Option<TextStyleRefinement>,
944 next_editor_action_id: EditorActionId,
945 editor_actions:
946 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
947 use_autoclose: bool,
948 use_auto_surround: bool,
949 auto_replace_emoji_shortcode: bool,
950 jsx_tag_auto_close_enabled_in_any_buffer: bool,
951 show_git_blame_gutter: bool,
952 show_git_blame_inline: bool,
953 show_git_blame_inline_delay_task: Option<Task<()>>,
954 git_blame_inline_enabled: bool,
955 render_diff_hunk_controls: RenderDiffHunkControlsFn,
956 serialize_dirty_buffers: bool,
957 show_selection_menu: Option<bool>,
958 blame: Option<Entity<GitBlame>>,
959 blame_subscription: Option<Subscription>,
960 custom_context_menu: Option<
961 Box<
962 dyn 'static
963 + Fn(
964 &mut Self,
965 DisplayPoint,
966 &mut Window,
967 &mut Context<Self>,
968 ) -> Option<Entity<ui::ContextMenu>>,
969 >,
970 >,
971 last_bounds: Option<Bounds<Pixels>>,
972 last_position_map: Option<Rc<PositionMap>>,
973 expect_bounds_change: Option<Bounds<Pixels>>,
974 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
975 tasks_update_task: Option<Task<()>>,
976 breakpoint_store: Option<Entity<BreakpointStore>>,
977 gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
978 in_project_search: bool,
979 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
980 breadcrumb_header: Option<String>,
981 focused_block: Option<FocusedBlock>,
982 next_scroll_position: NextScrollCursorCenterTopBottom,
983 addons: HashMap<TypeId, Box<dyn Addon>>,
984 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
985 load_diff_task: Option<Shared<Task<()>>>,
986 /// Whether we are temporarily displaying a diff other than git's
987 temporary_diff_override: bool,
988 selection_mark_mode: bool,
989 toggle_fold_multiple_buffers: Task<()>,
990 _scroll_cursor_center_top_bottom_task: Task<()>,
991 serialize_selections: Task<()>,
992 serialize_folds: Task<()>,
993 mouse_cursor_hidden: bool,
994 hide_mouse_mode: HideMouseMode,
995 pub change_list: ChangeList,
996 inline_value_cache: InlineValueCache,
997}
998
999#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
1000enum NextScrollCursorCenterTopBottom {
1001 #[default]
1002 Center,
1003 Top,
1004 Bottom,
1005}
1006
1007impl NextScrollCursorCenterTopBottom {
1008 fn next(&self) -> Self {
1009 match self {
1010 Self::Center => Self::Top,
1011 Self::Top => Self::Bottom,
1012 Self::Bottom => Self::Center,
1013 }
1014 }
1015}
1016
1017#[derive(Clone)]
1018pub struct EditorSnapshot {
1019 pub mode: EditorMode,
1020 show_gutter: bool,
1021 show_line_numbers: Option<bool>,
1022 show_git_diff_gutter: Option<bool>,
1023 show_code_actions: Option<bool>,
1024 show_runnables: Option<bool>,
1025 show_breakpoints: Option<bool>,
1026 git_blame_gutter_max_author_length: Option<usize>,
1027 pub display_snapshot: DisplaySnapshot,
1028 pub placeholder_text: Option<Arc<str>>,
1029 is_focused: bool,
1030 scroll_anchor: ScrollAnchor,
1031 ongoing_scroll: OngoingScroll,
1032 current_line_highlight: CurrentLineHighlight,
1033 gutter_hovered: bool,
1034}
1035
1036#[derive(Default, Debug, Clone, Copy)]
1037pub struct GutterDimensions {
1038 pub left_padding: Pixels,
1039 pub right_padding: Pixels,
1040 pub width: Pixels,
1041 pub margin: Pixels,
1042 pub git_blame_entries_width: Option<Pixels>,
1043}
1044
1045impl GutterDimensions {
1046 /// The full width of the space taken up by the gutter.
1047 pub fn full_width(&self) -> Pixels {
1048 self.margin + self.width
1049 }
1050
1051 /// The width of the space reserved for the fold indicators,
1052 /// use alongside 'justify_end' and `gutter_width` to
1053 /// right align content with the line numbers
1054 pub fn fold_area_width(&self) -> Pixels {
1055 self.margin + self.right_padding
1056 }
1057}
1058
1059#[derive(Debug)]
1060pub struct RemoteSelection {
1061 pub replica_id: ReplicaId,
1062 pub selection: Selection<Anchor>,
1063 pub cursor_shape: CursorShape,
1064 pub collaborator_id: CollaboratorId,
1065 pub line_mode: bool,
1066 pub user_name: Option<SharedString>,
1067 pub color: PlayerColor,
1068}
1069
1070#[derive(Clone, Debug)]
1071struct SelectionHistoryEntry {
1072 selections: Arc<[Selection<Anchor>]>,
1073 select_next_state: Option<SelectNextState>,
1074 select_prev_state: Option<SelectNextState>,
1075 add_selections_state: Option<AddSelectionsState>,
1076}
1077
1078enum SelectionHistoryMode {
1079 Normal,
1080 Undoing,
1081 Redoing,
1082}
1083
1084#[derive(Clone, PartialEq, Eq, Hash)]
1085struct HoveredCursor {
1086 replica_id: u16,
1087 selection_id: usize,
1088}
1089
1090impl Default for SelectionHistoryMode {
1091 fn default() -> Self {
1092 Self::Normal
1093 }
1094}
1095
1096#[derive(Default)]
1097struct SelectionHistory {
1098 #[allow(clippy::type_complexity)]
1099 selections_by_transaction:
1100 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1101 mode: SelectionHistoryMode,
1102 undo_stack: VecDeque<SelectionHistoryEntry>,
1103 redo_stack: VecDeque<SelectionHistoryEntry>,
1104}
1105
1106impl SelectionHistory {
1107 fn insert_transaction(
1108 &mut self,
1109 transaction_id: TransactionId,
1110 selections: Arc<[Selection<Anchor>]>,
1111 ) {
1112 self.selections_by_transaction
1113 .insert(transaction_id, (selections, None));
1114 }
1115
1116 #[allow(clippy::type_complexity)]
1117 fn transaction(
1118 &self,
1119 transaction_id: TransactionId,
1120 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1121 self.selections_by_transaction.get(&transaction_id)
1122 }
1123
1124 #[allow(clippy::type_complexity)]
1125 fn transaction_mut(
1126 &mut self,
1127 transaction_id: TransactionId,
1128 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1129 self.selections_by_transaction.get_mut(&transaction_id)
1130 }
1131
1132 fn push(&mut self, entry: SelectionHistoryEntry) {
1133 if !entry.selections.is_empty() {
1134 match self.mode {
1135 SelectionHistoryMode::Normal => {
1136 self.push_undo(entry);
1137 self.redo_stack.clear();
1138 }
1139 SelectionHistoryMode::Undoing => self.push_redo(entry),
1140 SelectionHistoryMode::Redoing => self.push_undo(entry),
1141 }
1142 }
1143 }
1144
1145 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1146 if self
1147 .undo_stack
1148 .back()
1149 .map_or(true, |e| e.selections != entry.selections)
1150 {
1151 self.undo_stack.push_back(entry);
1152 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1153 self.undo_stack.pop_front();
1154 }
1155 }
1156 }
1157
1158 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1159 if self
1160 .redo_stack
1161 .back()
1162 .map_or(true, |e| e.selections != entry.selections)
1163 {
1164 self.redo_stack.push_back(entry);
1165 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1166 self.redo_stack.pop_front();
1167 }
1168 }
1169 }
1170}
1171
1172#[derive(Clone, Copy)]
1173pub struct RowHighlightOptions {
1174 pub autoscroll: bool,
1175 pub include_gutter: bool,
1176}
1177
1178impl Default for RowHighlightOptions {
1179 fn default() -> Self {
1180 Self {
1181 autoscroll: Default::default(),
1182 include_gutter: true,
1183 }
1184 }
1185}
1186
1187struct RowHighlight {
1188 index: usize,
1189 range: Range<Anchor>,
1190 color: Hsla,
1191 options: RowHighlightOptions,
1192 type_id: TypeId,
1193}
1194
1195#[derive(Clone, Debug)]
1196struct AddSelectionsState {
1197 above: bool,
1198 stack: Vec<usize>,
1199}
1200
1201#[derive(Clone)]
1202struct SelectNextState {
1203 query: AhoCorasick,
1204 wordwise: bool,
1205 done: bool,
1206}
1207
1208impl std::fmt::Debug for SelectNextState {
1209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1210 f.debug_struct(std::any::type_name::<Self>())
1211 .field("wordwise", &self.wordwise)
1212 .field("done", &self.done)
1213 .finish()
1214 }
1215}
1216
1217#[derive(Debug)]
1218struct AutocloseRegion {
1219 selection_id: usize,
1220 range: Range<Anchor>,
1221 pair: BracketPair,
1222}
1223
1224#[derive(Debug)]
1225struct SnippetState {
1226 ranges: Vec<Vec<Range<Anchor>>>,
1227 active_index: usize,
1228 choices: Vec<Option<Vec<String>>>,
1229}
1230
1231#[doc(hidden)]
1232pub struct RenameState {
1233 pub range: Range<Anchor>,
1234 pub old_name: Arc<str>,
1235 pub editor: Entity<Editor>,
1236 block_id: CustomBlockId,
1237}
1238
1239struct InvalidationStack<T>(Vec<T>);
1240
1241struct RegisteredInlineCompletionProvider {
1242 provider: Arc<dyn InlineCompletionProviderHandle>,
1243 _subscription: Subscription,
1244}
1245
1246#[derive(Debug, PartialEq, Eq)]
1247pub struct ActiveDiagnosticGroup {
1248 pub active_range: Range<Anchor>,
1249 pub active_message: String,
1250 pub group_id: usize,
1251 pub blocks: HashSet<CustomBlockId>,
1252}
1253
1254#[derive(Debug, PartialEq, Eq)]
1255#[allow(clippy::large_enum_variant)]
1256pub(crate) enum ActiveDiagnostic {
1257 None,
1258 All,
1259 Group(ActiveDiagnosticGroup),
1260}
1261
1262#[derive(Serialize, Deserialize, Clone, Debug)]
1263pub struct ClipboardSelection {
1264 /// The number of bytes in this selection.
1265 pub len: usize,
1266 /// Whether this was a full-line selection.
1267 pub is_entire_line: bool,
1268 /// The indentation of the first line when this content was originally copied.
1269 pub first_line_indent: u32,
1270}
1271
1272// selections, scroll behavior, was newest selection reversed
1273type SelectSyntaxNodeHistoryState = (
1274 Box<[Selection<usize>]>,
1275 SelectSyntaxNodeScrollBehavior,
1276 bool,
1277);
1278
1279#[derive(Default)]
1280struct SelectSyntaxNodeHistory {
1281 stack: Vec<SelectSyntaxNodeHistoryState>,
1282 // disable temporarily to allow changing selections without losing the stack
1283 pub disable_clearing: bool,
1284}
1285
1286impl SelectSyntaxNodeHistory {
1287 pub fn try_clear(&mut self) {
1288 if !self.disable_clearing {
1289 self.stack.clear();
1290 }
1291 }
1292
1293 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1294 self.stack.push(selection);
1295 }
1296
1297 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1298 self.stack.pop()
1299 }
1300}
1301
1302enum SelectSyntaxNodeScrollBehavior {
1303 CursorTop,
1304 FitSelection,
1305 CursorBottom,
1306}
1307
1308#[derive(Debug)]
1309pub(crate) struct NavigationData {
1310 cursor_anchor: Anchor,
1311 cursor_position: Point,
1312 scroll_anchor: ScrollAnchor,
1313 scroll_top_row: u32,
1314}
1315
1316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1317pub enum GotoDefinitionKind {
1318 Symbol,
1319 Declaration,
1320 Type,
1321 Implementation,
1322}
1323
1324#[derive(Debug, Clone)]
1325enum InlayHintRefreshReason {
1326 ModifiersChanged(bool),
1327 Toggle(bool),
1328 SettingsChange(InlayHintSettings),
1329 NewLinesShown,
1330 BufferEdited(HashSet<Arc<Language>>),
1331 RefreshRequested,
1332 ExcerptsRemoved(Vec<ExcerptId>),
1333}
1334
1335impl InlayHintRefreshReason {
1336 fn description(&self) -> &'static str {
1337 match self {
1338 Self::ModifiersChanged(_) => "modifiers changed",
1339 Self::Toggle(_) => "toggle",
1340 Self::SettingsChange(_) => "settings change",
1341 Self::NewLinesShown => "new lines shown",
1342 Self::BufferEdited(_) => "buffer edited",
1343 Self::RefreshRequested => "refresh requested",
1344 Self::ExcerptsRemoved(_) => "excerpts removed",
1345 }
1346 }
1347}
1348
1349pub enum FormatTarget {
1350 Buffers,
1351 Ranges(Vec<Range<MultiBufferPoint>>),
1352}
1353
1354pub(crate) struct FocusedBlock {
1355 id: BlockId,
1356 focus_handle: WeakFocusHandle,
1357}
1358
1359#[derive(Clone)]
1360enum JumpData {
1361 MultiBufferRow {
1362 row: MultiBufferRow,
1363 line_offset_from_top: u32,
1364 },
1365 MultiBufferPoint {
1366 excerpt_id: ExcerptId,
1367 position: Point,
1368 anchor: text::Anchor,
1369 line_offset_from_top: u32,
1370 },
1371}
1372
1373pub enum MultibufferSelectionMode {
1374 First,
1375 All,
1376}
1377
1378#[derive(Clone, Copy, Debug, Default)]
1379pub struct RewrapOptions {
1380 pub override_language_settings: bool,
1381 pub preserve_existing_whitespace: bool,
1382}
1383
1384impl Editor {
1385 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1386 let buffer = cx.new(|cx| Buffer::local("", cx));
1387 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1388 Self::new(
1389 EditorMode::SingleLine { auto_width: false },
1390 buffer,
1391 None,
1392 window,
1393 cx,
1394 )
1395 }
1396
1397 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1398 let buffer = cx.new(|cx| Buffer::local("", cx));
1399 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1400 Self::new(EditorMode::full(), buffer, None, window, cx)
1401 }
1402
1403 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1404 let buffer = cx.new(|cx| Buffer::local("", cx));
1405 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1406 Self::new(
1407 EditorMode::SingleLine { auto_width: true },
1408 buffer,
1409 None,
1410 window,
1411 cx,
1412 )
1413 }
1414
1415 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1416 let buffer = cx.new(|cx| Buffer::local("", cx));
1417 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1418 Self::new(
1419 EditorMode::AutoHeight { max_lines },
1420 buffer,
1421 None,
1422 window,
1423 cx,
1424 )
1425 }
1426
1427 pub fn for_buffer(
1428 buffer: Entity<Buffer>,
1429 project: Option<Entity<Project>>,
1430 window: &mut Window,
1431 cx: &mut Context<Self>,
1432 ) -> Self {
1433 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1434 Self::new(EditorMode::full(), buffer, project, window, cx)
1435 }
1436
1437 pub fn for_multibuffer(
1438 buffer: Entity<MultiBuffer>,
1439 project: Option<Entity<Project>>,
1440 window: &mut Window,
1441 cx: &mut Context<Self>,
1442 ) -> Self {
1443 Self::new(EditorMode::full(), buffer, project, window, cx)
1444 }
1445
1446 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1447 let mut clone = Self::new(
1448 self.mode,
1449 self.buffer.clone(),
1450 self.project.clone(),
1451 window,
1452 cx,
1453 );
1454 self.display_map.update(cx, |display_map, cx| {
1455 let snapshot = display_map.snapshot(cx);
1456 clone.display_map.update(cx, |display_map, cx| {
1457 display_map.set_state(&snapshot, cx);
1458 });
1459 });
1460 clone.folds_did_change(cx);
1461 clone.selections.clone_state(&self.selections);
1462 clone.scroll_manager.clone_state(&self.scroll_manager);
1463 clone.searchable = self.searchable;
1464 clone.read_only = self.read_only;
1465 clone
1466 }
1467
1468 pub fn new(
1469 mode: EditorMode,
1470 buffer: Entity<MultiBuffer>,
1471 project: Option<Entity<Project>>,
1472 window: &mut Window,
1473 cx: &mut Context<Self>,
1474 ) -> Self {
1475 let style = window.text_style();
1476 let font_size = style.font_size.to_pixels(window.rem_size());
1477 let editor = cx.entity().downgrade();
1478 let fold_placeholder = FoldPlaceholder {
1479 constrain_width: true,
1480 render: Arc::new(move |fold_id, fold_range, cx| {
1481 let editor = editor.clone();
1482 div()
1483 .id(fold_id)
1484 .bg(cx.theme().colors().ghost_element_background)
1485 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1486 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1487 .rounded_xs()
1488 .size_full()
1489 .cursor_pointer()
1490 .child("⋯")
1491 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1492 .on_click(move |_, _window, cx| {
1493 editor
1494 .update(cx, |editor, cx| {
1495 editor.unfold_ranges(
1496 &[fold_range.start..fold_range.end],
1497 true,
1498 false,
1499 cx,
1500 );
1501 cx.stop_propagation();
1502 })
1503 .ok();
1504 })
1505 .into_any()
1506 }),
1507 merge_adjacent: true,
1508 ..Default::default()
1509 };
1510 let display_map = cx.new(|cx| {
1511 DisplayMap::new(
1512 buffer.clone(),
1513 style.font(),
1514 font_size,
1515 None,
1516 FILE_HEADER_HEIGHT,
1517 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1518 fold_placeholder,
1519 cx,
1520 )
1521 });
1522
1523 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1524
1525 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1526
1527 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1528 .then(|| language_settings::SoftWrap::None);
1529
1530 let mut project_subscriptions = Vec::new();
1531 if mode.is_full() {
1532 if let Some(project) = project.as_ref() {
1533 project_subscriptions.push(cx.subscribe_in(
1534 project,
1535 window,
1536 |editor, _, event, window, cx| match event {
1537 project::Event::RefreshCodeLens => {
1538 // we always query lens with actions, without storing them, always refreshing them
1539 }
1540 project::Event::RefreshInlayHints => {
1541 editor
1542 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1543 }
1544 project::Event::SnippetEdit(id, snippet_edits) => {
1545 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1546 let focus_handle = editor.focus_handle(cx);
1547 if focus_handle.is_focused(window) {
1548 let snapshot = buffer.read(cx).snapshot();
1549 for (range, snippet) in snippet_edits {
1550 let editor_range =
1551 language::range_from_lsp(*range).to_offset(&snapshot);
1552 editor
1553 .insert_snippet(
1554 &[editor_range],
1555 snippet.clone(),
1556 window,
1557 cx,
1558 )
1559 .ok();
1560 }
1561 }
1562 }
1563 }
1564 _ => {}
1565 },
1566 ));
1567 if let Some(task_inventory) = project
1568 .read(cx)
1569 .task_store()
1570 .read(cx)
1571 .task_inventory()
1572 .cloned()
1573 {
1574 project_subscriptions.push(cx.observe_in(
1575 &task_inventory,
1576 window,
1577 |editor, _, window, cx| {
1578 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1579 },
1580 ));
1581 };
1582
1583 project_subscriptions.push(cx.subscribe_in(
1584 &project.read(cx).breakpoint_store(),
1585 window,
1586 |editor, _, event, window, cx| match event {
1587 BreakpointStoreEvent::ClearDebugLines => {
1588 editor.clear_row_highlights::<ActiveDebugLine>();
1589 editor.refresh_inline_values(cx);
1590 }
1591 BreakpointStoreEvent::SetDebugLine => {
1592 if editor.go_to_active_debug_line(window, cx) {
1593 cx.stop_propagation();
1594 }
1595
1596 editor.refresh_inline_values(cx);
1597 }
1598 _ => {}
1599 },
1600 ));
1601 }
1602 }
1603
1604 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1605
1606 let inlay_hint_settings =
1607 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1608 let focus_handle = cx.focus_handle();
1609 cx.on_focus(&focus_handle, window, Self::handle_focus)
1610 .detach();
1611 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1612 .detach();
1613 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1614 .detach();
1615 cx.on_blur(&focus_handle, window, Self::handle_blur)
1616 .detach();
1617
1618 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1619 Some(false)
1620 } else {
1621 None
1622 };
1623
1624 let breakpoint_store = match (mode, project.as_ref()) {
1625 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1626 _ => None,
1627 };
1628
1629 let mut code_action_providers = Vec::new();
1630 let mut load_uncommitted_diff = None;
1631 if let Some(project) = project.clone() {
1632 load_uncommitted_diff = Some(
1633 update_uncommitted_diff_for_buffer(
1634 cx.entity(),
1635 &project,
1636 buffer.read(cx).all_buffers(),
1637 buffer.clone(),
1638 cx,
1639 )
1640 .shared(),
1641 );
1642 code_action_providers.push(Rc::new(project) as Rc<_>);
1643 }
1644
1645 let mut this = Self {
1646 focus_handle,
1647 show_cursor_when_unfocused: false,
1648 last_focused_descendant: None,
1649 buffer: buffer.clone(),
1650 display_map: display_map.clone(),
1651 selections,
1652 scroll_manager: ScrollManager::new(cx),
1653 columnar_selection_tail: None,
1654 add_selections_state: None,
1655 select_next_state: None,
1656 select_prev_state: None,
1657 selection_history: Default::default(),
1658 autoclose_regions: Default::default(),
1659 snippet_stack: Default::default(),
1660 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1661 ime_transaction: Default::default(),
1662 active_diagnostics: ActiveDiagnostic::None,
1663 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1664 inline_diagnostics_update: Task::ready(()),
1665 inline_diagnostics: Vec::new(),
1666 soft_wrap_mode_override,
1667 hard_wrap: None,
1668 completion_provider: project.clone().map(|project| Box::new(project) as _),
1669 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1670 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1671 project,
1672 blink_manager: blink_manager.clone(),
1673 show_local_selections: true,
1674 show_scrollbars: true,
1675 mode,
1676 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1677 show_gutter: mode.is_full(),
1678 show_line_numbers: None,
1679 use_relative_line_numbers: None,
1680 disable_expand_excerpt_buttons: false,
1681 show_git_diff_gutter: None,
1682 show_code_actions: None,
1683 show_runnables: None,
1684 show_breakpoints: None,
1685 show_wrap_guides: None,
1686 show_indent_guides,
1687 placeholder_text: None,
1688 highlight_order: 0,
1689 highlighted_rows: HashMap::default(),
1690 background_highlights: Default::default(),
1691 gutter_highlights: TreeMap::default(),
1692 scrollbar_marker_state: ScrollbarMarkerState::default(),
1693 active_indent_guides_state: ActiveIndentGuidesState::default(),
1694 nav_history: None,
1695 context_menu: RefCell::new(None),
1696 context_menu_options: None,
1697 mouse_context_menu: None,
1698 completion_tasks: Default::default(),
1699 inline_blame_popover: Default::default(),
1700 signature_help_state: SignatureHelpState::default(),
1701 auto_signature_help: None,
1702 find_all_references_task_sources: Vec::new(),
1703 next_completion_id: 0,
1704 next_inlay_id: 0,
1705 code_action_providers,
1706 available_code_actions: Default::default(),
1707 code_actions_task: Default::default(),
1708 quick_selection_highlight_task: Default::default(),
1709 debounced_selection_highlight_task: Default::default(),
1710 document_highlights_task: Default::default(),
1711 linked_editing_range_task: Default::default(),
1712 pending_rename: Default::default(),
1713 searchable: true,
1714 cursor_shape: EditorSettings::get_global(cx)
1715 .cursor_shape
1716 .unwrap_or_default(),
1717 current_line_highlight: None,
1718 autoindent_mode: Some(AutoindentMode::EachLine),
1719 collapse_matches: false,
1720 workspace: None,
1721 input_enabled: true,
1722 use_modal_editing: mode.is_full(),
1723 read_only: false,
1724 use_autoclose: true,
1725 use_auto_surround: true,
1726 auto_replace_emoji_shortcode: false,
1727 jsx_tag_auto_close_enabled_in_any_buffer: false,
1728 leader_id: None,
1729 remote_id: None,
1730 hover_state: Default::default(),
1731 pending_mouse_down: None,
1732 hovered_link_state: Default::default(),
1733 edit_prediction_provider: None,
1734 active_inline_completion: None,
1735 stale_inline_completion_in_menu: None,
1736 edit_prediction_preview: EditPredictionPreview::Inactive {
1737 released_too_fast: false,
1738 },
1739 inline_diagnostics_enabled: mode.is_full(),
1740 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1741 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1742
1743 gutter_hovered: false,
1744 pixel_position_of_newest_cursor: None,
1745 last_bounds: None,
1746 last_position_map: None,
1747 expect_bounds_change: None,
1748 gutter_dimensions: GutterDimensions::default(),
1749 style: None,
1750 show_cursor_names: false,
1751 hovered_cursors: Default::default(),
1752 next_editor_action_id: EditorActionId::default(),
1753 editor_actions: Rc::default(),
1754 inline_completions_hidden_for_vim_mode: false,
1755 show_inline_completions_override: None,
1756 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1757 edit_prediction_settings: EditPredictionSettings::Disabled,
1758 edit_prediction_indent_conflict: false,
1759 edit_prediction_requires_modifier_in_indent_conflict: true,
1760 custom_context_menu: None,
1761 show_git_blame_gutter: false,
1762 show_git_blame_inline: false,
1763 show_selection_menu: None,
1764 show_git_blame_inline_delay_task: None,
1765 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1766 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1767 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1768 .session
1769 .restore_unsaved_buffers,
1770 blame: None,
1771 blame_subscription: None,
1772 tasks: Default::default(),
1773
1774 breakpoint_store,
1775 gutter_breakpoint_indicator: (None, None),
1776 _subscriptions: vec![
1777 cx.observe(&buffer, Self::on_buffer_changed),
1778 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1779 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1780 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1781 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1782 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1783 cx.observe_window_activation(window, |editor, window, cx| {
1784 let active = window.is_window_active();
1785 editor.blink_manager.update(cx, |blink_manager, cx| {
1786 if active {
1787 blink_manager.enable(cx);
1788 } else {
1789 blink_manager.disable(cx);
1790 }
1791 });
1792 }),
1793 ],
1794 tasks_update_task: None,
1795 linked_edit_ranges: Default::default(),
1796 in_project_search: false,
1797 previous_search_ranges: None,
1798 breadcrumb_header: None,
1799 focused_block: None,
1800 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1801 addons: HashMap::default(),
1802 registered_buffers: HashMap::default(),
1803 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1804 selection_mark_mode: false,
1805 toggle_fold_multiple_buffers: Task::ready(()),
1806 serialize_selections: Task::ready(()),
1807 serialize_folds: Task::ready(()),
1808 text_style_refinement: None,
1809 load_diff_task: load_uncommitted_diff,
1810 temporary_diff_override: false,
1811 mouse_cursor_hidden: false,
1812 hide_mouse_mode: EditorSettings::get_global(cx)
1813 .hide_mouse
1814 .unwrap_or_default(),
1815 change_list: ChangeList::new(),
1816 };
1817 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1818 this._subscriptions
1819 .push(cx.observe(breakpoints, |_, _, cx| {
1820 cx.notify();
1821 }));
1822 }
1823 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1824 this._subscriptions.extend(project_subscriptions);
1825
1826 this._subscriptions.push(cx.subscribe_in(
1827 &cx.entity(),
1828 window,
1829 |editor, _, e: &EditorEvent, window, cx| match e {
1830 EditorEvent::ScrollPositionChanged { local, .. } => {
1831 if *local {
1832 let new_anchor = editor.scroll_manager.anchor();
1833 let snapshot = editor.snapshot(window, cx);
1834 editor.update_restoration_data(cx, move |data| {
1835 data.scroll_position = (
1836 new_anchor.top_row(&snapshot.buffer_snapshot),
1837 new_anchor.offset,
1838 );
1839 });
1840 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1841 editor.inline_blame_popover.take();
1842 }
1843 }
1844 EditorEvent::Edited { .. } => {
1845 if !vim_enabled(cx) {
1846 let (map, selections) = editor.selections.all_adjusted_display(cx);
1847 let pop_state = editor
1848 .change_list
1849 .last()
1850 .map(|previous| {
1851 previous.len() == selections.len()
1852 && previous.iter().enumerate().all(|(ix, p)| {
1853 p.to_display_point(&map).row()
1854 == selections[ix].head().row()
1855 })
1856 })
1857 .unwrap_or(false);
1858 let new_positions = selections
1859 .into_iter()
1860 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1861 .collect();
1862 editor
1863 .change_list
1864 .push_to_change_list(pop_state, new_positions);
1865 }
1866 }
1867 _ => (),
1868 },
1869 ));
1870
1871 if let Some(dap_store) = this
1872 .project
1873 .as_ref()
1874 .map(|project| project.read(cx).dap_store())
1875 {
1876 let weak_editor = cx.weak_entity();
1877
1878 this._subscriptions
1879 .push(
1880 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1881 let session_entity = cx.entity();
1882 weak_editor
1883 .update(cx, |editor, cx| {
1884 editor._subscriptions.push(
1885 cx.subscribe(&session_entity, Self::on_debug_session_event),
1886 );
1887 })
1888 .ok();
1889 }),
1890 );
1891
1892 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1893 this._subscriptions
1894 .push(cx.subscribe(&session, Self::on_debug_session_event));
1895 }
1896 }
1897
1898 this.end_selection(window, cx);
1899 this.scroll_manager.show_scrollbars(window, cx);
1900 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1901
1902 if mode.is_full() {
1903 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1904 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1905
1906 if this.git_blame_inline_enabled {
1907 this.git_blame_inline_enabled = true;
1908 this.start_git_blame_inline(false, window, cx);
1909 }
1910
1911 this.go_to_active_debug_line(window, cx);
1912
1913 if let Some(buffer) = buffer.read(cx).as_singleton() {
1914 if let Some(project) = this.project.as_ref() {
1915 let handle = project.update(cx, |project, cx| {
1916 project.register_buffer_with_language_servers(&buffer, cx)
1917 });
1918 this.registered_buffers
1919 .insert(buffer.read(cx).remote_id(), handle);
1920 }
1921 }
1922 }
1923
1924 this.report_editor_event("Editor Opened", None, cx);
1925 this
1926 }
1927
1928 pub fn deploy_mouse_context_menu(
1929 &mut self,
1930 position: gpui::Point<Pixels>,
1931 context_menu: Entity<ContextMenu>,
1932 window: &mut Window,
1933 cx: &mut Context<Self>,
1934 ) {
1935 self.mouse_context_menu = Some(MouseContextMenu::new(
1936 self,
1937 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1938 context_menu,
1939 window,
1940 cx,
1941 ));
1942 }
1943
1944 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1945 self.mouse_context_menu
1946 .as_ref()
1947 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1948 }
1949
1950 pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1951 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1952 }
1953
1954 fn key_context_internal(
1955 &self,
1956 has_active_edit_prediction: bool,
1957 window: &Window,
1958 cx: &App,
1959 ) -> KeyContext {
1960 let mut key_context = KeyContext::new_with_defaults();
1961 key_context.add("Editor");
1962 let mode = match self.mode {
1963 EditorMode::SingleLine { .. } => "single_line",
1964 EditorMode::AutoHeight { .. } => "auto_height",
1965 EditorMode::Full { .. } => "full",
1966 };
1967
1968 if EditorSettings::jupyter_enabled(cx) {
1969 key_context.add("jupyter");
1970 }
1971
1972 key_context.set("mode", mode);
1973 if self.pending_rename.is_some() {
1974 key_context.add("renaming");
1975 }
1976
1977 match self.context_menu.borrow().as_ref() {
1978 Some(CodeContextMenu::Completions(_)) => {
1979 key_context.add("menu");
1980 key_context.add("showing_completions");
1981 }
1982 Some(CodeContextMenu::CodeActions(_)) => {
1983 key_context.add("menu");
1984 key_context.add("showing_code_actions")
1985 }
1986 None => {}
1987 }
1988
1989 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1990 if !self.focus_handle(cx).contains_focused(window, cx)
1991 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1992 {
1993 for addon in self.addons.values() {
1994 addon.extend_key_context(&mut key_context, cx)
1995 }
1996 }
1997
1998 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1999 if let Some(extension) = singleton_buffer
2000 .read(cx)
2001 .file()
2002 .and_then(|file| file.path().extension()?.to_str())
2003 {
2004 key_context.set("extension", extension.to_string());
2005 }
2006 } else {
2007 key_context.add("multibuffer");
2008 }
2009
2010 if has_active_edit_prediction {
2011 if self.edit_prediction_in_conflict() {
2012 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
2013 } else {
2014 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
2015 key_context.add("copilot_suggestion");
2016 }
2017 }
2018
2019 if self.selection_mark_mode {
2020 key_context.add("selection_mode");
2021 }
2022
2023 key_context
2024 }
2025
2026 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
2027 self.mouse_cursor_hidden = match origin {
2028 HideMouseCursorOrigin::TypingAction => {
2029 matches!(
2030 self.hide_mouse_mode,
2031 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
2032 )
2033 }
2034 HideMouseCursorOrigin::MovementAction => {
2035 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
2036 }
2037 };
2038 }
2039
2040 pub fn edit_prediction_in_conflict(&self) -> bool {
2041 if !self.show_edit_predictions_in_menu() {
2042 return false;
2043 }
2044
2045 let showing_completions = self
2046 .context_menu
2047 .borrow()
2048 .as_ref()
2049 .map_or(false, |context| {
2050 matches!(context, CodeContextMenu::Completions(_))
2051 });
2052
2053 showing_completions
2054 || self.edit_prediction_requires_modifier()
2055 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2056 // bindings to insert tab characters.
2057 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2058 }
2059
2060 pub fn accept_edit_prediction_keybind(
2061 &self,
2062 window: &Window,
2063 cx: &App,
2064 ) -> AcceptEditPredictionBinding {
2065 let key_context = self.key_context_internal(true, window, cx);
2066 let in_conflict = self.edit_prediction_in_conflict();
2067
2068 AcceptEditPredictionBinding(
2069 window
2070 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2071 .into_iter()
2072 .filter(|binding| {
2073 !in_conflict
2074 || binding
2075 .keystrokes()
2076 .first()
2077 .map_or(false, |keystroke| keystroke.modifiers.modified())
2078 })
2079 .rev()
2080 .min_by_key(|binding| {
2081 binding
2082 .keystrokes()
2083 .first()
2084 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2085 }),
2086 )
2087 }
2088
2089 pub fn new_file(
2090 workspace: &mut Workspace,
2091 _: &workspace::NewFile,
2092 window: &mut Window,
2093 cx: &mut Context<Workspace>,
2094 ) {
2095 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2096 "Failed to create buffer",
2097 window,
2098 cx,
2099 |e, _, _| match e.error_code() {
2100 ErrorCode::RemoteUpgradeRequired => Some(format!(
2101 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2102 e.error_tag("required").unwrap_or("the latest version")
2103 )),
2104 _ => None,
2105 },
2106 );
2107 }
2108
2109 pub fn new_in_workspace(
2110 workspace: &mut Workspace,
2111 window: &mut Window,
2112 cx: &mut Context<Workspace>,
2113 ) -> Task<Result<Entity<Editor>>> {
2114 let project = workspace.project().clone();
2115 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2116
2117 cx.spawn_in(window, async move |workspace, cx| {
2118 let buffer = create.await?;
2119 workspace.update_in(cx, |workspace, window, cx| {
2120 let editor =
2121 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2122 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2123 editor
2124 })
2125 })
2126 }
2127
2128 fn new_file_vertical(
2129 workspace: &mut Workspace,
2130 _: &workspace::NewFileSplitVertical,
2131 window: &mut Window,
2132 cx: &mut Context<Workspace>,
2133 ) {
2134 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2135 }
2136
2137 fn new_file_horizontal(
2138 workspace: &mut Workspace,
2139 _: &workspace::NewFileSplitHorizontal,
2140 window: &mut Window,
2141 cx: &mut Context<Workspace>,
2142 ) {
2143 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2144 }
2145
2146 fn new_file_in_direction(
2147 workspace: &mut Workspace,
2148 direction: SplitDirection,
2149 window: &mut Window,
2150 cx: &mut Context<Workspace>,
2151 ) {
2152 let project = workspace.project().clone();
2153 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2154
2155 cx.spawn_in(window, async move |workspace, cx| {
2156 let buffer = create.await?;
2157 workspace.update_in(cx, move |workspace, window, cx| {
2158 workspace.split_item(
2159 direction,
2160 Box::new(
2161 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2162 ),
2163 window,
2164 cx,
2165 )
2166 })?;
2167 anyhow::Ok(())
2168 })
2169 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2170 match e.error_code() {
2171 ErrorCode::RemoteUpgradeRequired => Some(format!(
2172 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2173 e.error_tag("required").unwrap_or("the latest version")
2174 )),
2175 _ => None,
2176 }
2177 });
2178 }
2179
2180 pub fn leader_id(&self) -> Option<CollaboratorId> {
2181 self.leader_id
2182 }
2183
2184 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2185 &self.buffer
2186 }
2187
2188 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2189 self.workspace.as_ref()?.0.upgrade()
2190 }
2191
2192 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2193 self.buffer().read(cx).title(cx)
2194 }
2195
2196 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2197 let git_blame_gutter_max_author_length = self
2198 .render_git_blame_gutter(cx)
2199 .then(|| {
2200 if let Some(blame) = self.blame.as_ref() {
2201 let max_author_length =
2202 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2203 Some(max_author_length)
2204 } else {
2205 None
2206 }
2207 })
2208 .flatten();
2209
2210 EditorSnapshot {
2211 mode: self.mode,
2212 show_gutter: self.show_gutter,
2213 show_line_numbers: self.show_line_numbers,
2214 show_git_diff_gutter: self.show_git_diff_gutter,
2215 show_code_actions: self.show_code_actions,
2216 show_runnables: self.show_runnables,
2217 show_breakpoints: self.show_breakpoints,
2218 git_blame_gutter_max_author_length,
2219 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2220 scroll_anchor: self.scroll_manager.anchor(),
2221 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2222 placeholder_text: self.placeholder_text.clone(),
2223 is_focused: self.focus_handle.is_focused(window),
2224 current_line_highlight: self
2225 .current_line_highlight
2226 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2227 gutter_hovered: self.gutter_hovered,
2228 }
2229 }
2230
2231 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2232 self.buffer.read(cx).language_at(point, cx)
2233 }
2234
2235 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2236 self.buffer.read(cx).read(cx).file_at(point).cloned()
2237 }
2238
2239 pub fn active_excerpt(
2240 &self,
2241 cx: &App,
2242 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2243 self.buffer
2244 .read(cx)
2245 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2246 }
2247
2248 pub fn mode(&self) -> EditorMode {
2249 self.mode
2250 }
2251
2252 pub fn set_mode(&mut self, mode: EditorMode) {
2253 self.mode = mode;
2254 }
2255
2256 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2257 self.collaboration_hub.as_deref()
2258 }
2259
2260 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2261 self.collaboration_hub = Some(hub);
2262 }
2263
2264 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2265 self.in_project_search = in_project_search;
2266 }
2267
2268 pub fn set_custom_context_menu(
2269 &mut self,
2270 f: impl 'static
2271 + Fn(
2272 &mut Self,
2273 DisplayPoint,
2274 &mut Window,
2275 &mut Context<Self>,
2276 ) -> Option<Entity<ui::ContextMenu>>,
2277 ) {
2278 self.custom_context_menu = Some(Box::new(f))
2279 }
2280
2281 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2282 self.completion_provider = provider;
2283 }
2284
2285 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2286 self.semantics_provider.clone()
2287 }
2288
2289 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2290 self.semantics_provider = provider;
2291 }
2292
2293 pub fn set_edit_prediction_provider<T>(
2294 &mut self,
2295 provider: Option<Entity<T>>,
2296 window: &mut Window,
2297 cx: &mut Context<Self>,
2298 ) where
2299 T: EditPredictionProvider,
2300 {
2301 self.edit_prediction_provider =
2302 provider.map(|provider| RegisteredInlineCompletionProvider {
2303 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2304 if this.focus_handle.is_focused(window) {
2305 this.update_visible_inline_completion(window, cx);
2306 }
2307 }),
2308 provider: Arc::new(provider),
2309 });
2310 self.update_edit_prediction_settings(cx);
2311 self.refresh_inline_completion(false, false, window, cx);
2312 }
2313
2314 pub fn placeholder_text(&self) -> Option<&str> {
2315 self.placeholder_text.as_deref()
2316 }
2317
2318 pub fn set_placeholder_text(
2319 &mut self,
2320 placeholder_text: impl Into<Arc<str>>,
2321 cx: &mut Context<Self>,
2322 ) {
2323 let placeholder_text = Some(placeholder_text.into());
2324 if self.placeholder_text != placeholder_text {
2325 self.placeholder_text = placeholder_text;
2326 cx.notify();
2327 }
2328 }
2329
2330 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2331 self.cursor_shape = cursor_shape;
2332
2333 // Disrupt blink for immediate user feedback that the cursor shape has changed
2334 self.blink_manager.update(cx, BlinkManager::show_cursor);
2335
2336 cx.notify();
2337 }
2338
2339 pub fn set_current_line_highlight(
2340 &mut self,
2341 current_line_highlight: Option<CurrentLineHighlight>,
2342 ) {
2343 self.current_line_highlight = current_line_highlight;
2344 }
2345
2346 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2347 self.collapse_matches = collapse_matches;
2348 }
2349
2350 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2351 let buffers = self.buffer.read(cx).all_buffers();
2352 let Some(project) = self.project.as_ref() else {
2353 return;
2354 };
2355 project.update(cx, |project, cx| {
2356 for buffer in buffers {
2357 self.registered_buffers
2358 .entry(buffer.read(cx).remote_id())
2359 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2360 }
2361 })
2362 }
2363
2364 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2365 if self.collapse_matches {
2366 return range.start..range.start;
2367 }
2368 range.clone()
2369 }
2370
2371 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2372 if self.display_map.read(cx).clip_at_line_ends != clip {
2373 self.display_map
2374 .update(cx, |map, _| map.clip_at_line_ends = clip);
2375 }
2376 }
2377
2378 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2379 self.input_enabled = input_enabled;
2380 }
2381
2382 pub fn set_inline_completions_hidden_for_vim_mode(
2383 &mut self,
2384 hidden: bool,
2385 window: &mut Window,
2386 cx: &mut Context<Self>,
2387 ) {
2388 if hidden != self.inline_completions_hidden_for_vim_mode {
2389 self.inline_completions_hidden_for_vim_mode = hidden;
2390 if hidden {
2391 self.update_visible_inline_completion(window, cx);
2392 } else {
2393 self.refresh_inline_completion(true, false, window, cx);
2394 }
2395 }
2396 }
2397
2398 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2399 self.menu_inline_completions_policy = value;
2400 }
2401
2402 pub fn set_autoindent(&mut self, autoindent: bool) {
2403 if autoindent {
2404 self.autoindent_mode = Some(AutoindentMode::EachLine);
2405 } else {
2406 self.autoindent_mode = None;
2407 }
2408 }
2409
2410 pub fn read_only(&self, cx: &App) -> bool {
2411 self.read_only || self.buffer.read(cx).read_only()
2412 }
2413
2414 pub fn set_read_only(&mut self, read_only: bool) {
2415 self.read_only = read_only;
2416 }
2417
2418 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2419 self.use_autoclose = autoclose;
2420 }
2421
2422 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2423 self.use_auto_surround = auto_surround;
2424 }
2425
2426 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2427 self.auto_replace_emoji_shortcode = auto_replace;
2428 }
2429
2430 pub fn toggle_edit_predictions(
2431 &mut self,
2432 _: &ToggleEditPrediction,
2433 window: &mut Window,
2434 cx: &mut Context<Self>,
2435 ) {
2436 if self.show_inline_completions_override.is_some() {
2437 self.set_show_edit_predictions(None, window, cx);
2438 } else {
2439 let show_edit_predictions = !self.edit_predictions_enabled();
2440 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2441 }
2442 }
2443
2444 pub fn set_show_edit_predictions(
2445 &mut self,
2446 show_edit_predictions: Option<bool>,
2447 window: &mut Window,
2448 cx: &mut Context<Self>,
2449 ) {
2450 self.show_inline_completions_override = show_edit_predictions;
2451 self.update_edit_prediction_settings(cx);
2452
2453 if let Some(false) = show_edit_predictions {
2454 self.discard_inline_completion(false, cx);
2455 } else {
2456 self.refresh_inline_completion(false, true, window, cx);
2457 }
2458 }
2459
2460 fn inline_completions_disabled_in_scope(
2461 &self,
2462 buffer: &Entity<Buffer>,
2463 buffer_position: language::Anchor,
2464 cx: &App,
2465 ) -> bool {
2466 let snapshot = buffer.read(cx).snapshot();
2467 let settings = snapshot.settings_at(buffer_position, cx);
2468
2469 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2470 return false;
2471 };
2472
2473 scope.override_name().map_or(false, |scope_name| {
2474 settings
2475 .edit_predictions_disabled_in
2476 .iter()
2477 .any(|s| s == scope_name)
2478 })
2479 }
2480
2481 pub fn set_use_modal_editing(&mut self, to: bool) {
2482 self.use_modal_editing = to;
2483 }
2484
2485 pub fn use_modal_editing(&self) -> bool {
2486 self.use_modal_editing
2487 }
2488
2489 fn selections_did_change(
2490 &mut self,
2491 local: bool,
2492 old_cursor_position: &Anchor,
2493 show_completions: bool,
2494 window: &mut Window,
2495 cx: &mut Context<Self>,
2496 ) {
2497 window.invalidate_character_coordinates();
2498
2499 // Copy selections to primary selection buffer
2500 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2501 if local {
2502 let selections = self.selections.all::<usize>(cx);
2503 let buffer_handle = self.buffer.read(cx).read(cx);
2504
2505 let mut text = String::new();
2506 for (index, selection) in selections.iter().enumerate() {
2507 let text_for_selection = buffer_handle
2508 .text_for_range(selection.start..selection.end)
2509 .collect::<String>();
2510
2511 text.push_str(&text_for_selection);
2512 if index != selections.len() - 1 {
2513 text.push('\n');
2514 }
2515 }
2516
2517 if !text.is_empty() {
2518 cx.write_to_primary(ClipboardItem::new_string(text));
2519 }
2520 }
2521
2522 if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
2523 self.buffer.update(cx, |buffer, cx| {
2524 buffer.set_active_selections(
2525 &self.selections.disjoint_anchors(),
2526 self.selections.line_mode,
2527 self.cursor_shape,
2528 cx,
2529 )
2530 });
2531 }
2532 let display_map = self
2533 .display_map
2534 .update(cx, |display_map, cx| display_map.snapshot(cx));
2535 let buffer = &display_map.buffer_snapshot;
2536 self.add_selections_state = None;
2537 self.select_next_state = None;
2538 self.select_prev_state = None;
2539 self.select_syntax_node_history.try_clear();
2540 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2541 self.snippet_stack
2542 .invalidate(&self.selections.disjoint_anchors(), buffer);
2543 self.take_rename(false, window, cx);
2544
2545 let new_cursor_position = self.selections.newest_anchor().head();
2546
2547 self.push_to_nav_history(
2548 *old_cursor_position,
2549 Some(new_cursor_position.to_point(buffer)),
2550 false,
2551 cx,
2552 );
2553
2554 if local {
2555 let new_cursor_position = self.selections.newest_anchor().head();
2556 let mut context_menu = self.context_menu.borrow_mut();
2557 let completion_menu = match context_menu.as_ref() {
2558 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2559 _ => {
2560 *context_menu = None;
2561 None
2562 }
2563 };
2564 if let Some(buffer_id) = new_cursor_position.buffer_id {
2565 if !self.registered_buffers.contains_key(&buffer_id) {
2566 if let Some(project) = self.project.as_ref() {
2567 project.update(cx, |project, cx| {
2568 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2569 return;
2570 };
2571 self.registered_buffers.insert(
2572 buffer_id,
2573 project.register_buffer_with_language_servers(&buffer, cx),
2574 );
2575 })
2576 }
2577 }
2578 }
2579
2580 if let Some(completion_menu) = completion_menu {
2581 let cursor_position = new_cursor_position.to_offset(buffer);
2582 let (word_range, kind) =
2583 buffer.surrounding_word(completion_menu.initial_position, true);
2584 if kind == Some(CharKind::Word)
2585 && word_range.to_inclusive().contains(&cursor_position)
2586 {
2587 let mut completion_menu = completion_menu.clone();
2588 drop(context_menu);
2589
2590 let query = Self::completion_query(buffer, cursor_position);
2591 cx.spawn(async move |this, cx| {
2592 completion_menu
2593 .filter(query.as_deref(), cx.background_executor().clone())
2594 .await;
2595
2596 this.update(cx, |this, cx| {
2597 let mut context_menu = this.context_menu.borrow_mut();
2598 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2599 else {
2600 return;
2601 };
2602
2603 if menu.id > completion_menu.id {
2604 return;
2605 }
2606
2607 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2608 drop(context_menu);
2609 cx.notify();
2610 })
2611 })
2612 .detach();
2613
2614 if show_completions {
2615 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2616 }
2617 } else {
2618 drop(context_menu);
2619 self.hide_context_menu(window, cx);
2620 }
2621 } else {
2622 drop(context_menu);
2623 }
2624
2625 hide_hover(self, cx);
2626
2627 if old_cursor_position.to_display_point(&display_map).row()
2628 != new_cursor_position.to_display_point(&display_map).row()
2629 {
2630 self.available_code_actions.take();
2631 }
2632 self.refresh_code_actions(window, cx);
2633 self.refresh_document_highlights(cx);
2634 self.refresh_selected_text_highlights(false, window, cx);
2635 refresh_matching_bracket_highlights(self, window, cx);
2636 self.update_visible_inline_completion(window, cx);
2637 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2638 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2639 self.inline_blame_popover.take();
2640 if self.git_blame_inline_enabled {
2641 self.start_inline_blame_timer(window, cx);
2642 }
2643 }
2644
2645 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2646 cx.emit(EditorEvent::SelectionsChanged { local });
2647
2648 let selections = &self.selections.disjoint;
2649 if selections.len() == 1 {
2650 cx.emit(SearchEvent::ActiveMatchChanged)
2651 }
2652 if local {
2653 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2654 let inmemory_selections = selections
2655 .iter()
2656 .map(|s| {
2657 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2658 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2659 })
2660 .collect();
2661 self.update_restoration_data(cx, |data| {
2662 data.selections = inmemory_selections;
2663 });
2664
2665 if WorkspaceSettings::get(None, cx).restore_on_startup
2666 != RestoreOnStartupBehavior::None
2667 {
2668 if let Some(workspace_id) =
2669 self.workspace.as_ref().and_then(|workspace| workspace.1)
2670 {
2671 let snapshot = self.buffer().read(cx).snapshot(cx);
2672 let selections = selections.clone();
2673 let background_executor = cx.background_executor().clone();
2674 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2675 self.serialize_selections = cx.background_spawn(async move {
2676 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2677 let db_selections = selections
2678 .iter()
2679 .map(|selection| {
2680 (
2681 selection.start.to_offset(&snapshot),
2682 selection.end.to_offset(&snapshot),
2683 )
2684 })
2685 .collect();
2686
2687 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2688 .await
2689 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2690 .log_err();
2691 });
2692 }
2693 }
2694 }
2695 }
2696
2697 cx.notify();
2698 }
2699
2700 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2701 use text::ToOffset as _;
2702 use text::ToPoint as _;
2703
2704 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2705 return;
2706 }
2707
2708 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2709 return;
2710 };
2711
2712 let snapshot = singleton.read(cx).snapshot();
2713 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2714 let display_snapshot = display_map.snapshot(cx);
2715
2716 display_snapshot
2717 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2718 .map(|fold| {
2719 fold.range.start.text_anchor.to_point(&snapshot)
2720 ..fold.range.end.text_anchor.to_point(&snapshot)
2721 })
2722 .collect()
2723 });
2724 self.update_restoration_data(cx, |data| {
2725 data.folds = inmemory_folds;
2726 });
2727
2728 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2729 return;
2730 };
2731 let background_executor = cx.background_executor().clone();
2732 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2733 let db_folds = self.display_map.update(cx, |display_map, cx| {
2734 display_map
2735 .snapshot(cx)
2736 .folds_in_range(0..snapshot.len())
2737 .map(|fold| {
2738 (
2739 fold.range.start.text_anchor.to_offset(&snapshot),
2740 fold.range.end.text_anchor.to_offset(&snapshot),
2741 )
2742 })
2743 .collect()
2744 });
2745 self.serialize_folds = cx.background_spawn(async move {
2746 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2747 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2748 .await
2749 .with_context(|| {
2750 format!(
2751 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2752 )
2753 })
2754 .log_err();
2755 });
2756 }
2757
2758 pub fn sync_selections(
2759 &mut self,
2760 other: Entity<Editor>,
2761 cx: &mut Context<Self>,
2762 ) -> gpui::Subscription {
2763 let other_selections = other.read(cx).selections.disjoint.to_vec();
2764 self.selections.change_with(cx, |selections| {
2765 selections.select_anchors(other_selections);
2766 });
2767
2768 let other_subscription =
2769 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2770 EditorEvent::SelectionsChanged { local: true } => {
2771 let other_selections = other.read(cx).selections.disjoint.to_vec();
2772 if other_selections.is_empty() {
2773 return;
2774 }
2775 this.selections.change_with(cx, |selections| {
2776 selections.select_anchors(other_selections);
2777 });
2778 }
2779 _ => {}
2780 });
2781
2782 let this_subscription =
2783 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2784 EditorEvent::SelectionsChanged { local: true } => {
2785 let these_selections = this.selections.disjoint.to_vec();
2786 if these_selections.is_empty() {
2787 return;
2788 }
2789 other.update(cx, |other_editor, cx| {
2790 other_editor.selections.change_with(cx, |selections| {
2791 selections.select_anchors(these_selections);
2792 })
2793 });
2794 }
2795 _ => {}
2796 });
2797
2798 Subscription::join(other_subscription, this_subscription)
2799 }
2800
2801 pub fn change_selections<R>(
2802 &mut self,
2803 autoscroll: Option<Autoscroll>,
2804 window: &mut Window,
2805 cx: &mut Context<Self>,
2806 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2807 ) -> R {
2808 self.change_selections_inner(autoscroll, true, window, cx, change)
2809 }
2810
2811 fn change_selections_inner<R>(
2812 &mut self,
2813 autoscroll: Option<Autoscroll>,
2814 request_completions: bool,
2815 window: &mut Window,
2816 cx: &mut Context<Self>,
2817 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2818 ) -> R {
2819 let old_cursor_position = self.selections.newest_anchor().head();
2820 self.push_to_selection_history();
2821
2822 let (changed, result) = self.selections.change_with(cx, change);
2823
2824 if changed {
2825 if let Some(autoscroll) = autoscroll {
2826 self.request_autoscroll(autoscroll, cx);
2827 }
2828 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2829
2830 if self.should_open_signature_help_automatically(
2831 &old_cursor_position,
2832 self.signature_help_state.backspace_pressed(),
2833 cx,
2834 ) {
2835 self.show_signature_help(&ShowSignatureHelp, window, cx);
2836 }
2837 self.signature_help_state.set_backspace_pressed(false);
2838 }
2839
2840 result
2841 }
2842
2843 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2844 where
2845 I: IntoIterator<Item = (Range<S>, T)>,
2846 S: ToOffset,
2847 T: Into<Arc<str>>,
2848 {
2849 if self.read_only(cx) {
2850 return;
2851 }
2852
2853 self.buffer
2854 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2855 }
2856
2857 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2858 where
2859 I: IntoIterator<Item = (Range<S>, T)>,
2860 S: ToOffset,
2861 T: Into<Arc<str>>,
2862 {
2863 if self.read_only(cx) {
2864 return;
2865 }
2866
2867 self.buffer.update(cx, |buffer, cx| {
2868 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2869 });
2870 }
2871
2872 pub fn edit_with_block_indent<I, S, T>(
2873 &mut self,
2874 edits: I,
2875 original_indent_columns: Vec<Option<u32>>,
2876 cx: &mut Context<Self>,
2877 ) where
2878 I: IntoIterator<Item = (Range<S>, T)>,
2879 S: ToOffset,
2880 T: Into<Arc<str>>,
2881 {
2882 if self.read_only(cx) {
2883 return;
2884 }
2885
2886 self.buffer.update(cx, |buffer, cx| {
2887 buffer.edit(
2888 edits,
2889 Some(AutoindentMode::Block {
2890 original_indent_columns,
2891 }),
2892 cx,
2893 )
2894 });
2895 }
2896
2897 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2898 self.hide_context_menu(window, cx);
2899
2900 match phase {
2901 SelectPhase::Begin {
2902 position,
2903 add,
2904 click_count,
2905 } => self.begin_selection(position, add, click_count, window, cx),
2906 SelectPhase::BeginColumnar {
2907 position,
2908 goal_column,
2909 reset,
2910 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2911 SelectPhase::Extend {
2912 position,
2913 click_count,
2914 } => self.extend_selection(position, click_count, window, cx),
2915 SelectPhase::Update {
2916 position,
2917 goal_column,
2918 scroll_delta,
2919 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2920 SelectPhase::End => self.end_selection(window, cx),
2921 }
2922 }
2923
2924 fn extend_selection(
2925 &mut self,
2926 position: DisplayPoint,
2927 click_count: usize,
2928 window: &mut Window,
2929 cx: &mut Context<Self>,
2930 ) {
2931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2932 let tail = self.selections.newest::<usize>(cx).tail();
2933 self.begin_selection(position, false, click_count, window, cx);
2934
2935 let position = position.to_offset(&display_map, Bias::Left);
2936 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2937
2938 let mut pending_selection = self
2939 .selections
2940 .pending_anchor()
2941 .expect("extend_selection not called with pending selection");
2942 if position >= tail {
2943 pending_selection.start = tail_anchor;
2944 } else {
2945 pending_selection.end = tail_anchor;
2946 pending_selection.reversed = true;
2947 }
2948
2949 let mut pending_mode = self.selections.pending_mode().unwrap();
2950 match &mut pending_mode {
2951 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2952 _ => {}
2953 }
2954
2955 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2956 s.set_pending(pending_selection, pending_mode)
2957 });
2958 }
2959
2960 fn begin_selection(
2961 &mut self,
2962 position: DisplayPoint,
2963 add: bool,
2964 click_count: usize,
2965 window: &mut Window,
2966 cx: &mut Context<Self>,
2967 ) {
2968 if !self.focus_handle.is_focused(window) {
2969 self.last_focused_descendant = None;
2970 window.focus(&self.focus_handle);
2971 }
2972
2973 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2974 let buffer = &display_map.buffer_snapshot;
2975 let newest_selection = self.selections.newest_anchor().clone();
2976 let position = display_map.clip_point(position, Bias::Left);
2977
2978 let start;
2979 let end;
2980 let mode;
2981 let mut auto_scroll;
2982 match click_count {
2983 1 => {
2984 start = buffer.anchor_before(position.to_point(&display_map));
2985 end = start;
2986 mode = SelectMode::Character;
2987 auto_scroll = true;
2988 }
2989 2 => {
2990 let range = movement::surrounding_word(&display_map, position);
2991 start = buffer.anchor_before(range.start.to_point(&display_map));
2992 end = buffer.anchor_before(range.end.to_point(&display_map));
2993 mode = SelectMode::Word(start..end);
2994 auto_scroll = true;
2995 }
2996 3 => {
2997 let position = display_map
2998 .clip_point(position, Bias::Left)
2999 .to_point(&display_map);
3000 let line_start = display_map.prev_line_boundary(position).0;
3001 let next_line_start = buffer.clip_point(
3002 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3003 Bias::Left,
3004 );
3005 start = buffer.anchor_before(line_start);
3006 end = buffer.anchor_before(next_line_start);
3007 mode = SelectMode::Line(start..end);
3008 auto_scroll = true;
3009 }
3010 _ => {
3011 start = buffer.anchor_before(0);
3012 end = buffer.anchor_before(buffer.len());
3013 mode = SelectMode::All;
3014 auto_scroll = false;
3015 }
3016 }
3017 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3018
3019 let point_to_delete: Option<usize> = {
3020 let selected_points: Vec<Selection<Point>> =
3021 self.selections.disjoint_in_range(start..end, cx);
3022
3023 if !add || click_count > 1 {
3024 None
3025 } else if !selected_points.is_empty() {
3026 Some(selected_points[0].id)
3027 } else {
3028 let clicked_point_already_selected =
3029 self.selections.disjoint.iter().find(|selection| {
3030 selection.start.to_point(buffer) == start.to_point(buffer)
3031 || selection.end.to_point(buffer) == end.to_point(buffer)
3032 });
3033
3034 clicked_point_already_selected.map(|selection| selection.id)
3035 }
3036 };
3037
3038 let selections_count = self.selections.count();
3039
3040 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3041 if let Some(point_to_delete) = point_to_delete {
3042 s.delete(point_to_delete);
3043
3044 if selections_count == 1 {
3045 s.set_pending_anchor_range(start..end, mode);
3046 }
3047 } else {
3048 if !add {
3049 s.clear_disjoint();
3050 } else if click_count > 1 {
3051 s.delete(newest_selection.id)
3052 }
3053
3054 s.set_pending_anchor_range(start..end, mode);
3055 }
3056 });
3057 }
3058
3059 fn begin_columnar_selection(
3060 &mut self,
3061 position: DisplayPoint,
3062 goal_column: u32,
3063 reset: bool,
3064 window: &mut Window,
3065 cx: &mut Context<Self>,
3066 ) {
3067 if !self.focus_handle.is_focused(window) {
3068 self.last_focused_descendant = None;
3069 window.focus(&self.focus_handle);
3070 }
3071
3072 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3073
3074 if reset {
3075 let pointer_position = display_map
3076 .buffer_snapshot
3077 .anchor_before(position.to_point(&display_map));
3078
3079 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3080 s.clear_disjoint();
3081 s.set_pending_anchor_range(
3082 pointer_position..pointer_position,
3083 SelectMode::Character,
3084 );
3085 });
3086 }
3087
3088 let tail = self.selections.newest::<Point>(cx).tail();
3089 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3090
3091 if !reset {
3092 self.select_columns(
3093 tail.to_display_point(&display_map),
3094 position,
3095 goal_column,
3096 &display_map,
3097 window,
3098 cx,
3099 );
3100 }
3101 }
3102
3103 fn update_selection(
3104 &mut self,
3105 position: DisplayPoint,
3106 goal_column: u32,
3107 scroll_delta: gpui::Point<f32>,
3108 window: &mut Window,
3109 cx: &mut Context<Self>,
3110 ) {
3111 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3112
3113 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3114 let tail = tail.to_display_point(&display_map);
3115 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3116 } else if let Some(mut pending) = self.selections.pending_anchor() {
3117 let buffer = self.buffer.read(cx).snapshot(cx);
3118 let head;
3119 let tail;
3120 let mode = self.selections.pending_mode().unwrap();
3121 match &mode {
3122 SelectMode::Character => {
3123 head = position.to_point(&display_map);
3124 tail = pending.tail().to_point(&buffer);
3125 }
3126 SelectMode::Word(original_range) => {
3127 let original_display_range = original_range.start.to_display_point(&display_map)
3128 ..original_range.end.to_display_point(&display_map);
3129 let original_buffer_range = original_display_range.start.to_point(&display_map)
3130 ..original_display_range.end.to_point(&display_map);
3131 if movement::is_inside_word(&display_map, position)
3132 || original_display_range.contains(&position)
3133 {
3134 let word_range = movement::surrounding_word(&display_map, position);
3135 if word_range.start < original_display_range.start {
3136 head = word_range.start.to_point(&display_map);
3137 } else {
3138 head = word_range.end.to_point(&display_map);
3139 }
3140 } else {
3141 head = position.to_point(&display_map);
3142 }
3143
3144 if head <= original_buffer_range.start {
3145 tail = original_buffer_range.end;
3146 } else {
3147 tail = original_buffer_range.start;
3148 }
3149 }
3150 SelectMode::Line(original_range) => {
3151 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3152
3153 let position = display_map
3154 .clip_point(position, Bias::Left)
3155 .to_point(&display_map);
3156 let line_start = display_map.prev_line_boundary(position).0;
3157 let next_line_start = buffer.clip_point(
3158 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3159 Bias::Left,
3160 );
3161
3162 if line_start < original_range.start {
3163 head = line_start
3164 } else {
3165 head = next_line_start
3166 }
3167
3168 if head <= original_range.start {
3169 tail = original_range.end;
3170 } else {
3171 tail = original_range.start;
3172 }
3173 }
3174 SelectMode::All => {
3175 return;
3176 }
3177 };
3178
3179 if head < tail {
3180 pending.start = buffer.anchor_before(head);
3181 pending.end = buffer.anchor_before(tail);
3182 pending.reversed = true;
3183 } else {
3184 pending.start = buffer.anchor_before(tail);
3185 pending.end = buffer.anchor_before(head);
3186 pending.reversed = false;
3187 }
3188
3189 self.change_selections(None, window, cx, |s| {
3190 s.set_pending(pending, mode);
3191 });
3192 } else {
3193 log::error!("update_selection dispatched with no pending selection");
3194 return;
3195 }
3196
3197 self.apply_scroll_delta(scroll_delta, window, cx);
3198 cx.notify();
3199 }
3200
3201 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3202 self.columnar_selection_tail.take();
3203 if self.selections.pending_anchor().is_some() {
3204 let selections = self.selections.all::<usize>(cx);
3205 self.change_selections(None, window, cx, |s| {
3206 s.select(selections);
3207 s.clear_pending();
3208 });
3209 }
3210 }
3211
3212 fn select_columns(
3213 &mut self,
3214 tail: DisplayPoint,
3215 head: DisplayPoint,
3216 goal_column: u32,
3217 display_map: &DisplaySnapshot,
3218 window: &mut Window,
3219 cx: &mut Context<Self>,
3220 ) {
3221 let start_row = cmp::min(tail.row(), head.row());
3222 let end_row = cmp::max(tail.row(), head.row());
3223 let start_column = cmp::min(tail.column(), goal_column);
3224 let end_column = cmp::max(tail.column(), goal_column);
3225 let reversed = start_column < tail.column();
3226
3227 let selection_ranges = (start_row.0..=end_row.0)
3228 .map(DisplayRow)
3229 .filter_map(|row| {
3230 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3231 let start = display_map
3232 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3233 .to_point(display_map);
3234 let end = display_map
3235 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3236 .to_point(display_map);
3237 if reversed {
3238 Some(end..start)
3239 } else {
3240 Some(start..end)
3241 }
3242 } else {
3243 None
3244 }
3245 })
3246 .collect::<Vec<_>>();
3247
3248 self.change_selections(None, window, cx, |s| {
3249 s.select_ranges(selection_ranges);
3250 });
3251 cx.notify();
3252 }
3253
3254 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3255 self.selections
3256 .all_adjusted(cx)
3257 .iter()
3258 .any(|selection| !selection.is_empty())
3259 }
3260
3261 pub fn has_pending_nonempty_selection(&self) -> bool {
3262 let pending_nonempty_selection = match self.selections.pending_anchor() {
3263 Some(Selection { start, end, .. }) => start != end,
3264 None => false,
3265 };
3266
3267 pending_nonempty_selection
3268 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3269 }
3270
3271 pub fn has_pending_selection(&self) -> bool {
3272 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3273 }
3274
3275 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3276 self.selection_mark_mode = false;
3277
3278 if self.clear_expanded_diff_hunks(cx) {
3279 cx.notify();
3280 return;
3281 }
3282 if self.dismiss_menus_and_popups(true, window, cx) {
3283 return;
3284 }
3285
3286 if self.mode.is_full()
3287 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3288 {
3289 return;
3290 }
3291
3292 cx.propagate();
3293 }
3294
3295 pub fn dismiss_menus_and_popups(
3296 &mut self,
3297 is_user_requested: bool,
3298 window: &mut Window,
3299 cx: &mut Context<Self>,
3300 ) -> bool {
3301 if self.take_rename(false, window, cx).is_some() {
3302 return true;
3303 }
3304
3305 if hide_hover(self, cx) {
3306 return true;
3307 }
3308
3309 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3310 return true;
3311 }
3312
3313 if self.hide_context_menu(window, cx).is_some() {
3314 return true;
3315 }
3316
3317 if self.mouse_context_menu.take().is_some() {
3318 return true;
3319 }
3320
3321 if is_user_requested && self.discard_inline_completion(true, cx) {
3322 return true;
3323 }
3324
3325 if self.snippet_stack.pop().is_some() {
3326 return true;
3327 }
3328
3329 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3330 self.dismiss_diagnostics(cx);
3331 return true;
3332 }
3333
3334 false
3335 }
3336
3337 fn linked_editing_ranges_for(
3338 &self,
3339 selection: Range<text::Anchor>,
3340 cx: &App,
3341 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3342 if self.linked_edit_ranges.is_empty() {
3343 return None;
3344 }
3345 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3346 selection.end.buffer_id.and_then(|end_buffer_id| {
3347 if selection.start.buffer_id != Some(end_buffer_id) {
3348 return None;
3349 }
3350 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3351 let snapshot = buffer.read(cx).snapshot();
3352 self.linked_edit_ranges
3353 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3354 .map(|ranges| (ranges, snapshot, buffer))
3355 })?;
3356 use text::ToOffset as TO;
3357 // find offset from the start of current range to current cursor position
3358 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3359
3360 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3361 let start_difference = start_offset - start_byte_offset;
3362 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3363 let end_difference = end_offset - start_byte_offset;
3364 // Current range has associated linked ranges.
3365 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3366 for range in linked_ranges.iter() {
3367 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3368 let end_offset = start_offset + end_difference;
3369 let start_offset = start_offset + start_difference;
3370 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3371 continue;
3372 }
3373 if self.selections.disjoint_anchor_ranges().any(|s| {
3374 if s.start.buffer_id != selection.start.buffer_id
3375 || s.end.buffer_id != selection.end.buffer_id
3376 {
3377 return false;
3378 }
3379 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3380 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3381 }) {
3382 continue;
3383 }
3384 let start = buffer_snapshot.anchor_after(start_offset);
3385 let end = buffer_snapshot.anchor_after(end_offset);
3386 linked_edits
3387 .entry(buffer.clone())
3388 .or_default()
3389 .push(start..end);
3390 }
3391 Some(linked_edits)
3392 }
3393
3394 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3395 let text: Arc<str> = text.into();
3396
3397 if self.read_only(cx) {
3398 return;
3399 }
3400
3401 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3402
3403 let selections = self.selections.all_adjusted(cx);
3404 let mut bracket_inserted = false;
3405 let mut edits = Vec::new();
3406 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3407 let mut new_selections = Vec::with_capacity(selections.len());
3408 let mut new_autoclose_regions = Vec::new();
3409 let snapshot = self.buffer.read(cx).read(cx);
3410 let mut clear_linked_edit_ranges = false;
3411
3412 for (selection, autoclose_region) in
3413 self.selections_with_autoclose_regions(selections, &snapshot)
3414 {
3415 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3416 // Determine if the inserted text matches the opening or closing
3417 // bracket of any of this language's bracket pairs.
3418 let mut bracket_pair = None;
3419 let mut is_bracket_pair_start = false;
3420 let mut is_bracket_pair_end = false;
3421 if !text.is_empty() {
3422 let mut bracket_pair_matching_end = None;
3423 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3424 // and they are removing the character that triggered IME popup.
3425 for (pair, enabled) in scope.brackets() {
3426 if !pair.close && !pair.surround {
3427 continue;
3428 }
3429
3430 if enabled && pair.start.ends_with(text.as_ref()) {
3431 let prefix_len = pair.start.len() - text.len();
3432 let preceding_text_matches_prefix = prefix_len == 0
3433 || (selection.start.column >= (prefix_len as u32)
3434 && snapshot.contains_str_at(
3435 Point::new(
3436 selection.start.row,
3437 selection.start.column - (prefix_len as u32),
3438 ),
3439 &pair.start[..prefix_len],
3440 ));
3441 if preceding_text_matches_prefix {
3442 bracket_pair = Some(pair.clone());
3443 is_bracket_pair_start = true;
3444 break;
3445 }
3446 }
3447 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3448 {
3449 // take first bracket pair matching end, but don't break in case a later bracket
3450 // pair matches start
3451 bracket_pair_matching_end = Some(pair.clone());
3452 }
3453 }
3454 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3455 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3456 is_bracket_pair_end = true;
3457 }
3458 }
3459
3460 if let Some(bracket_pair) = bracket_pair {
3461 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3462 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3463 let auto_surround =
3464 self.use_auto_surround && snapshot_settings.use_auto_surround;
3465 if selection.is_empty() {
3466 if is_bracket_pair_start {
3467 // If the inserted text is a suffix of an opening bracket and the
3468 // selection is preceded by the rest of the opening bracket, then
3469 // insert the closing bracket.
3470 let following_text_allows_autoclose = snapshot
3471 .chars_at(selection.start)
3472 .next()
3473 .map_or(true, |c| scope.should_autoclose_before(c));
3474
3475 let preceding_text_allows_autoclose = selection.start.column == 0
3476 || snapshot.reversed_chars_at(selection.start).next().map_or(
3477 true,
3478 |c| {
3479 bracket_pair.start != bracket_pair.end
3480 || !snapshot
3481 .char_classifier_at(selection.start)
3482 .is_word(c)
3483 },
3484 );
3485
3486 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3487 && bracket_pair.start.len() == 1
3488 {
3489 let target = bracket_pair.start.chars().next().unwrap();
3490 let current_line_count = snapshot
3491 .reversed_chars_at(selection.start)
3492 .take_while(|&c| c != '\n')
3493 .filter(|&c| c == target)
3494 .count();
3495 current_line_count % 2 == 1
3496 } else {
3497 false
3498 };
3499
3500 if autoclose
3501 && bracket_pair.close
3502 && following_text_allows_autoclose
3503 && preceding_text_allows_autoclose
3504 && !is_closing_quote
3505 {
3506 let anchor = snapshot.anchor_before(selection.end);
3507 new_selections.push((selection.map(|_| anchor), text.len()));
3508 new_autoclose_regions.push((
3509 anchor,
3510 text.len(),
3511 selection.id,
3512 bracket_pair.clone(),
3513 ));
3514 edits.push((
3515 selection.range(),
3516 format!("{}{}", text, bracket_pair.end).into(),
3517 ));
3518 bracket_inserted = true;
3519 continue;
3520 }
3521 }
3522
3523 if let Some(region) = autoclose_region {
3524 // If the selection is followed by an auto-inserted closing bracket,
3525 // then don't insert that closing bracket again; just move the selection
3526 // past the closing bracket.
3527 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3528 && text.as_ref() == region.pair.end.as_str();
3529 if should_skip {
3530 let anchor = snapshot.anchor_after(selection.end);
3531 new_selections
3532 .push((selection.map(|_| anchor), region.pair.end.len()));
3533 continue;
3534 }
3535 }
3536
3537 let always_treat_brackets_as_autoclosed = snapshot
3538 .language_settings_at(selection.start, cx)
3539 .always_treat_brackets_as_autoclosed;
3540 if always_treat_brackets_as_autoclosed
3541 && is_bracket_pair_end
3542 && snapshot.contains_str_at(selection.end, text.as_ref())
3543 {
3544 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3545 // and the inserted text is a closing bracket and the selection is followed
3546 // by the closing bracket then move the selection past the closing bracket.
3547 let anchor = snapshot.anchor_after(selection.end);
3548 new_selections.push((selection.map(|_| anchor), text.len()));
3549 continue;
3550 }
3551 }
3552 // If an opening bracket is 1 character long and is typed while
3553 // text is selected, then surround that text with the bracket pair.
3554 else if auto_surround
3555 && bracket_pair.surround
3556 && is_bracket_pair_start
3557 && bracket_pair.start.chars().count() == 1
3558 {
3559 edits.push((selection.start..selection.start, text.clone()));
3560 edits.push((
3561 selection.end..selection.end,
3562 bracket_pair.end.as_str().into(),
3563 ));
3564 bracket_inserted = true;
3565 new_selections.push((
3566 Selection {
3567 id: selection.id,
3568 start: snapshot.anchor_after(selection.start),
3569 end: snapshot.anchor_before(selection.end),
3570 reversed: selection.reversed,
3571 goal: selection.goal,
3572 },
3573 0,
3574 ));
3575 continue;
3576 }
3577 }
3578 }
3579
3580 if self.auto_replace_emoji_shortcode
3581 && selection.is_empty()
3582 && text.as_ref().ends_with(':')
3583 {
3584 if let Some(possible_emoji_short_code) =
3585 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3586 {
3587 if !possible_emoji_short_code.is_empty() {
3588 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3589 let emoji_shortcode_start = Point::new(
3590 selection.start.row,
3591 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3592 );
3593
3594 // Remove shortcode from buffer
3595 edits.push((
3596 emoji_shortcode_start..selection.start,
3597 "".to_string().into(),
3598 ));
3599 new_selections.push((
3600 Selection {
3601 id: selection.id,
3602 start: snapshot.anchor_after(emoji_shortcode_start),
3603 end: snapshot.anchor_before(selection.start),
3604 reversed: selection.reversed,
3605 goal: selection.goal,
3606 },
3607 0,
3608 ));
3609
3610 // Insert emoji
3611 let selection_start_anchor = snapshot.anchor_after(selection.start);
3612 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3613 edits.push((selection.start..selection.end, emoji.to_string().into()));
3614
3615 continue;
3616 }
3617 }
3618 }
3619 }
3620
3621 // If not handling any auto-close operation, then just replace the selected
3622 // text with the given input and move the selection to the end of the
3623 // newly inserted text.
3624 let anchor = snapshot.anchor_after(selection.end);
3625 if !self.linked_edit_ranges.is_empty() {
3626 let start_anchor = snapshot.anchor_before(selection.start);
3627
3628 let is_word_char = text.chars().next().map_or(true, |char| {
3629 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3630 classifier.is_word(char)
3631 });
3632
3633 if is_word_char {
3634 if let Some(ranges) = self
3635 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3636 {
3637 for (buffer, edits) in ranges {
3638 linked_edits
3639 .entry(buffer.clone())
3640 .or_default()
3641 .extend(edits.into_iter().map(|range| (range, text.clone())));
3642 }
3643 }
3644 } else {
3645 clear_linked_edit_ranges = true;
3646 }
3647 }
3648
3649 new_selections.push((selection.map(|_| anchor), 0));
3650 edits.push((selection.start..selection.end, text.clone()));
3651 }
3652
3653 drop(snapshot);
3654
3655 self.transact(window, cx, |this, window, cx| {
3656 if clear_linked_edit_ranges {
3657 this.linked_edit_ranges.clear();
3658 }
3659 let initial_buffer_versions =
3660 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3661
3662 this.buffer.update(cx, |buffer, cx| {
3663 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3664 });
3665 for (buffer, edits) in linked_edits {
3666 buffer.update(cx, |buffer, cx| {
3667 let snapshot = buffer.snapshot();
3668 let edits = edits
3669 .into_iter()
3670 .map(|(range, text)| {
3671 use text::ToPoint as TP;
3672 let end_point = TP::to_point(&range.end, &snapshot);
3673 let start_point = TP::to_point(&range.start, &snapshot);
3674 (start_point..end_point, text)
3675 })
3676 .sorted_by_key(|(range, _)| range.start);
3677 buffer.edit(edits, None, cx);
3678 })
3679 }
3680 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3681 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3682 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3683 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3684 .zip(new_selection_deltas)
3685 .map(|(selection, delta)| Selection {
3686 id: selection.id,
3687 start: selection.start + delta,
3688 end: selection.end + delta,
3689 reversed: selection.reversed,
3690 goal: SelectionGoal::None,
3691 })
3692 .collect::<Vec<_>>();
3693
3694 let mut i = 0;
3695 for (position, delta, selection_id, pair) in new_autoclose_regions {
3696 let position = position.to_offset(&map.buffer_snapshot) + delta;
3697 let start = map.buffer_snapshot.anchor_before(position);
3698 let end = map.buffer_snapshot.anchor_after(position);
3699 while let Some(existing_state) = this.autoclose_regions.get(i) {
3700 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3701 Ordering::Less => i += 1,
3702 Ordering::Greater => break,
3703 Ordering::Equal => {
3704 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3705 Ordering::Less => i += 1,
3706 Ordering::Equal => break,
3707 Ordering::Greater => break,
3708 }
3709 }
3710 }
3711 }
3712 this.autoclose_regions.insert(
3713 i,
3714 AutocloseRegion {
3715 selection_id,
3716 range: start..end,
3717 pair,
3718 },
3719 );
3720 }
3721
3722 let had_active_inline_completion = this.has_active_inline_completion();
3723 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3724 s.select(new_selections)
3725 });
3726
3727 if !bracket_inserted {
3728 if let Some(on_type_format_task) =
3729 this.trigger_on_type_formatting(text.to_string(), window, cx)
3730 {
3731 on_type_format_task.detach_and_log_err(cx);
3732 }
3733 }
3734
3735 let editor_settings = EditorSettings::get_global(cx);
3736 if bracket_inserted
3737 && (editor_settings.auto_signature_help
3738 || editor_settings.show_signature_help_after_edits)
3739 {
3740 this.show_signature_help(&ShowSignatureHelp, window, cx);
3741 }
3742
3743 let trigger_in_words =
3744 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3745 if this.hard_wrap.is_some() {
3746 let latest: Range<Point> = this.selections.newest(cx).range();
3747 if latest.is_empty()
3748 && this
3749 .buffer()
3750 .read(cx)
3751 .snapshot(cx)
3752 .line_len(MultiBufferRow(latest.start.row))
3753 == latest.start.column
3754 {
3755 this.rewrap_impl(
3756 RewrapOptions {
3757 override_language_settings: true,
3758 preserve_existing_whitespace: true,
3759 },
3760 cx,
3761 )
3762 }
3763 }
3764 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3765 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3766 this.refresh_inline_completion(true, false, window, cx);
3767 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3768 });
3769 }
3770
3771 fn find_possible_emoji_shortcode_at_position(
3772 snapshot: &MultiBufferSnapshot,
3773 position: Point,
3774 ) -> Option<String> {
3775 let mut chars = Vec::new();
3776 let mut found_colon = false;
3777 for char in snapshot.reversed_chars_at(position).take(100) {
3778 // Found a possible emoji shortcode in the middle of the buffer
3779 if found_colon {
3780 if char.is_whitespace() {
3781 chars.reverse();
3782 return Some(chars.iter().collect());
3783 }
3784 // If the previous character is not a whitespace, we are in the middle of a word
3785 // and we only want to complete the shortcode if the word is made up of other emojis
3786 let mut containing_word = String::new();
3787 for ch in snapshot
3788 .reversed_chars_at(position)
3789 .skip(chars.len() + 1)
3790 .take(100)
3791 {
3792 if ch.is_whitespace() {
3793 break;
3794 }
3795 containing_word.push(ch);
3796 }
3797 let containing_word = containing_word.chars().rev().collect::<String>();
3798 if util::word_consists_of_emojis(containing_word.as_str()) {
3799 chars.reverse();
3800 return Some(chars.iter().collect());
3801 }
3802 }
3803
3804 if char.is_whitespace() || !char.is_ascii() {
3805 return None;
3806 }
3807 if char == ':' {
3808 found_colon = true;
3809 } else {
3810 chars.push(char);
3811 }
3812 }
3813 // Found a possible emoji shortcode at the beginning of the buffer
3814 chars.reverse();
3815 Some(chars.iter().collect())
3816 }
3817
3818 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3819 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3820 self.transact(window, cx, |this, window, cx| {
3821 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3822 let selections = this.selections.all::<usize>(cx);
3823 let multi_buffer = this.buffer.read(cx);
3824 let buffer = multi_buffer.snapshot(cx);
3825 selections
3826 .iter()
3827 .map(|selection| {
3828 let start_point = selection.start.to_point(&buffer);
3829 let mut indent =
3830 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3831 indent.len = cmp::min(indent.len, start_point.column);
3832 let start = selection.start;
3833 let end = selection.end;
3834 let selection_is_empty = start == end;
3835 let language_scope = buffer.language_scope_at(start);
3836 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3837 &language_scope
3838 {
3839 let insert_extra_newline =
3840 insert_extra_newline_brackets(&buffer, start..end, language)
3841 || insert_extra_newline_tree_sitter(&buffer, start..end);
3842
3843 // Comment extension on newline is allowed only for cursor selections
3844 let comment_delimiter = maybe!({
3845 if !selection_is_empty {
3846 return None;
3847 }
3848
3849 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3850 return None;
3851 }
3852
3853 let delimiters = language.line_comment_prefixes();
3854 let max_len_of_delimiter =
3855 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3856 let (snapshot, range) =
3857 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3858
3859 let mut index_of_first_non_whitespace = 0;
3860 let comment_candidate = snapshot
3861 .chars_for_range(range)
3862 .skip_while(|c| {
3863 let should_skip = c.is_whitespace();
3864 if should_skip {
3865 index_of_first_non_whitespace += 1;
3866 }
3867 should_skip
3868 })
3869 .take(max_len_of_delimiter)
3870 .collect::<String>();
3871 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3872 comment_candidate.starts_with(comment_prefix.as_ref())
3873 })?;
3874 let cursor_is_placed_after_comment_marker =
3875 index_of_first_non_whitespace + comment_prefix.len()
3876 <= start_point.column as usize;
3877 if cursor_is_placed_after_comment_marker {
3878 Some(comment_prefix.clone())
3879 } else {
3880 None
3881 }
3882 });
3883 (comment_delimiter, insert_extra_newline)
3884 } else {
3885 (None, false)
3886 };
3887
3888 let capacity_for_delimiter = comment_delimiter
3889 .as_deref()
3890 .map(str::len)
3891 .unwrap_or_default();
3892 let mut new_text =
3893 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3894 new_text.push('\n');
3895 new_text.extend(indent.chars());
3896 if let Some(delimiter) = &comment_delimiter {
3897 new_text.push_str(delimiter);
3898 }
3899 if insert_extra_newline {
3900 new_text = new_text.repeat(2);
3901 }
3902
3903 let anchor = buffer.anchor_after(end);
3904 let new_selection = selection.map(|_| anchor);
3905 (
3906 (start..end, new_text),
3907 (insert_extra_newline, new_selection),
3908 )
3909 })
3910 .unzip()
3911 };
3912
3913 this.edit_with_autoindent(edits, cx);
3914 let buffer = this.buffer.read(cx).snapshot(cx);
3915 let new_selections = selection_fixup_info
3916 .into_iter()
3917 .map(|(extra_newline_inserted, new_selection)| {
3918 let mut cursor = new_selection.end.to_point(&buffer);
3919 if extra_newline_inserted {
3920 cursor.row -= 1;
3921 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3922 }
3923 new_selection.map(|_| cursor)
3924 })
3925 .collect();
3926
3927 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3928 s.select(new_selections)
3929 });
3930 this.refresh_inline_completion(true, false, window, cx);
3931 });
3932 }
3933
3934 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3935 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3936
3937 let buffer = self.buffer.read(cx);
3938 let snapshot = buffer.snapshot(cx);
3939
3940 let mut edits = Vec::new();
3941 let mut rows = Vec::new();
3942
3943 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3944 let cursor = selection.head();
3945 let row = cursor.row;
3946
3947 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3948
3949 let newline = "\n".to_string();
3950 edits.push((start_of_line..start_of_line, newline));
3951
3952 rows.push(row + rows_inserted as u32);
3953 }
3954
3955 self.transact(window, cx, |editor, window, cx| {
3956 editor.edit(edits, cx);
3957
3958 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3959 let mut index = 0;
3960 s.move_cursors_with(|map, _, _| {
3961 let row = rows[index];
3962 index += 1;
3963
3964 let point = Point::new(row, 0);
3965 let boundary = map.next_line_boundary(point).1;
3966 let clipped = map.clip_point(boundary, Bias::Left);
3967
3968 (clipped, SelectionGoal::None)
3969 });
3970 });
3971
3972 let mut indent_edits = Vec::new();
3973 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3974 for row in rows {
3975 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3976 for (row, indent) in indents {
3977 if indent.len == 0 {
3978 continue;
3979 }
3980
3981 let text = match indent.kind {
3982 IndentKind::Space => " ".repeat(indent.len as usize),
3983 IndentKind::Tab => "\t".repeat(indent.len as usize),
3984 };
3985 let point = Point::new(row.0, 0);
3986 indent_edits.push((point..point, text));
3987 }
3988 }
3989 editor.edit(indent_edits, cx);
3990 });
3991 }
3992
3993 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3994 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3995
3996 let buffer = self.buffer.read(cx);
3997 let snapshot = buffer.snapshot(cx);
3998
3999 let mut edits = Vec::new();
4000 let mut rows = Vec::new();
4001 let mut rows_inserted = 0;
4002
4003 for selection in self.selections.all_adjusted(cx) {
4004 let cursor = selection.head();
4005 let row = cursor.row;
4006
4007 let point = Point::new(row + 1, 0);
4008 let start_of_line = snapshot.clip_point(point, Bias::Left);
4009
4010 let newline = "\n".to_string();
4011 edits.push((start_of_line..start_of_line, newline));
4012
4013 rows_inserted += 1;
4014 rows.push(row + rows_inserted);
4015 }
4016
4017 self.transact(window, cx, |editor, window, cx| {
4018 editor.edit(edits, cx);
4019
4020 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4021 let mut index = 0;
4022 s.move_cursors_with(|map, _, _| {
4023 let row = rows[index];
4024 index += 1;
4025
4026 let point = Point::new(row, 0);
4027 let boundary = map.next_line_boundary(point).1;
4028 let clipped = map.clip_point(boundary, Bias::Left);
4029
4030 (clipped, SelectionGoal::None)
4031 });
4032 });
4033
4034 let mut indent_edits = Vec::new();
4035 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4036 for row in rows {
4037 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4038 for (row, indent) in indents {
4039 if indent.len == 0 {
4040 continue;
4041 }
4042
4043 let text = match indent.kind {
4044 IndentKind::Space => " ".repeat(indent.len as usize),
4045 IndentKind::Tab => "\t".repeat(indent.len as usize),
4046 };
4047 let point = Point::new(row.0, 0);
4048 indent_edits.push((point..point, text));
4049 }
4050 }
4051 editor.edit(indent_edits, cx);
4052 });
4053 }
4054
4055 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4056 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4057 original_indent_columns: Vec::new(),
4058 });
4059 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4060 }
4061
4062 fn insert_with_autoindent_mode(
4063 &mut self,
4064 text: &str,
4065 autoindent_mode: Option<AutoindentMode>,
4066 window: &mut Window,
4067 cx: &mut Context<Self>,
4068 ) {
4069 if self.read_only(cx) {
4070 return;
4071 }
4072
4073 let text: Arc<str> = text.into();
4074 self.transact(window, cx, |this, window, cx| {
4075 let old_selections = this.selections.all_adjusted(cx);
4076 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4077 let anchors = {
4078 let snapshot = buffer.read(cx);
4079 old_selections
4080 .iter()
4081 .map(|s| {
4082 let anchor = snapshot.anchor_after(s.head());
4083 s.map(|_| anchor)
4084 })
4085 .collect::<Vec<_>>()
4086 };
4087 buffer.edit(
4088 old_selections
4089 .iter()
4090 .map(|s| (s.start..s.end, text.clone())),
4091 autoindent_mode,
4092 cx,
4093 );
4094 anchors
4095 });
4096
4097 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4098 s.select_anchors(selection_anchors);
4099 });
4100
4101 cx.notify();
4102 });
4103 }
4104
4105 fn trigger_completion_on_input(
4106 &mut self,
4107 text: &str,
4108 trigger_in_words: bool,
4109 window: &mut Window,
4110 cx: &mut Context<Self>,
4111 ) {
4112 let ignore_completion_provider = self
4113 .context_menu
4114 .borrow()
4115 .as_ref()
4116 .map(|menu| match menu {
4117 CodeContextMenu::Completions(completions_menu) => {
4118 completions_menu.ignore_completion_provider
4119 }
4120 CodeContextMenu::CodeActions(_) => false,
4121 })
4122 .unwrap_or(false);
4123
4124 if ignore_completion_provider {
4125 self.show_word_completions(&ShowWordCompletions, window, cx);
4126 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4127 self.show_completions(
4128 &ShowCompletions {
4129 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4130 },
4131 window,
4132 cx,
4133 );
4134 } else {
4135 self.hide_context_menu(window, cx);
4136 }
4137 }
4138
4139 fn is_completion_trigger(
4140 &self,
4141 text: &str,
4142 trigger_in_words: bool,
4143 cx: &mut Context<Self>,
4144 ) -> bool {
4145 let position = self.selections.newest_anchor().head();
4146 let multibuffer = self.buffer.read(cx);
4147 let Some(buffer) = position
4148 .buffer_id
4149 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4150 else {
4151 return false;
4152 };
4153
4154 if let Some(completion_provider) = &self.completion_provider {
4155 completion_provider.is_completion_trigger(
4156 &buffer,
4157 position.text_anchor,
4158 text,
4159 trigger_in_words,
4160 cx,
4161 )
4162 } else {
4163 false
4164 }
4165 }
4166
4167 /// If any empty selections is touching the start of its innermost containing autoclose
4168 /// region, expand it to select the brackets.
4169 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4170 let selections = self.selections.all::<usize>(cx);
4171 let buffer = self.buffer.read(cx).read(cx);
4172 let new_selections = self
4173 .selections_with_autoclose_regions(selections, &buffer)
4174 .map(|(mut selection, region)| {
4175 if !selection.is_empty() {
4176 return selection;
4177 }
4178
4179 if let Some(region) = region {
4180 let mut range = region.range.to_offset(&buffer);
4181 if selection.start == range.start && range.start >= region.pair.start.len() {
4182 range.start -= region.pair.start.len();
4183 if buffer.contains_str_at(range.start, ®ion.pair.start)
4184 && buffer.contains_str_at(range.end, ®ion.pair.end)
4185 {
4186 range.end += region.pair.end.len();
4187 selection.start = range.start;
4188 selection.end = range.end;
4189
4190 return selection;
4191 }
4192 }
4193 }
4194
4195 let always_treat_brackets_as_autoclosed = buffer
4196 .language_settings_at(selection.start, cx)
4197 .always_treat_brackets_as_autoclosed;
4198
4199 if !always_treat_brackets_as_autoclosed {
4200 return selection;
4201 }
4202
4203 if let Some(scope) = buffer.language_scope_at(selection.start) {
4204 for (pair, enabled) in scope.brackets() {
4205 if !enabled || !pair.close {
4206 continue;
4207 }
4208
4209 if buffer.contains_str_at(selection.start, &pair.end) {
4210 let pair_start_len = pair.start.len();
4211 if buffer.contains_str_at(
4212 selection.start.saturating_sub(pair_start_len),
4213 &pair.start,
4214 ) {
4215 selection.start -= pair_start_len;
4216 selection.end += pair.end.len();
4217
4218 return selection;
4219 }
4220 }
4221 }
4222 }
4223
4224 selection
4225 })
4226 .collect();
4227
4228 drop(buffer);
4229 self.change_selections(None, window, cx, |selections| {
4230 selections.select(new_selections)
4231 });
4232 }
4233
4234 /// Iterate the given selections, and for each one, find the smallest surrounding
4235 /// autoclose region. This uses the ordering of the selections and the autoclose
4236 /// regions to avoid repeated comparisons.
4237 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4238 &'a self,
4239 selections: impl IntoIterator<Item = Selection<D>>,
4240 buffer: &'a MultiBufferSnapshot,
4241 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4242 let mut i = 0;
4243 let mut regions = self.autoclose_regions.as_slice();
4244 selections.into_iter().map(move |selection| {
4245 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4246
4247 let mut enclosing = None;
4248 while let Some(pair_state) = regions.get(i) {
4249 if pair_state.range.end.to_offset(buffer) < range.start {
4250 regions = ®ions[i + 1..];
4251 i = 0;
4252 } else if pair_state.range.start.to_offset(buffer) > range.end {
4253 break;
4254 } else {
4255 if pair_state.selection_id == selection.id {
4256 enclosing = Some(pair_state);
4257 }
4258 i += 1;
4259 }
4260 }
4261
4262 (selection, enclosing)
4263 })
4264 }
4265
4266 /// Remove any autoclose regions that no longer contain their selection.
4267 fn invalidate_autoclose_regions(
4268 &mut self,
4269 mut selections: &[Selection<Anchor>],
4270 buffer: &MultiBufferSnapshot,
4271 ) {
4272 self.autoclose_regions.retain(|state| {
4273 let mut i = 0;
4274 while let Some(selection) = selections.get(i) {
4275 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4276 selections = &selections[1..];
4277 continue;
4278 }
4279 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4280 break;
4281 }
4282 if selection.id == state.selection_id {
4283 return true;
4284 } else {
4285 i += 1;
4286 }
4287 }
4288 false
4289 });
4290 }
4291
4292 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4293 let offset = position.to_offset(buffer);
4294 let (word_range, kind) = buffer.surrounding_word(offset, true);
4295 if offset > word_range.start && kind == Some(CharKind::Word) {
4296 Some(
4297 buffer
4298 .text_for_range(word_range.start..offset)
4299 .collect::<String>(),
4300 )
4301 } else {
4302 None
4303 }
4304 }
4305
4306 pub fn toggle_inline_values(
4307 &mut self,
4308 _: &ToggleInlineValues,
4309 _: &mut Window,
4310 cx: &mut Context<Self>,
4311 ) {
4312 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4313
4314 self.refresh_inline_values(cx);
4315 }
4316
4317 pub fn toggle_inlay_hints(
4318 &mut self,
4319 _: &ToggleInlayHints,
4320 _: &mut Window,
4321 cx: &mut Context<Self>,
4322 ) {
4323 self.refresh_inlay_hints(
4324 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4325 cx,
4326 );
4327 }
4328
4329 pub fn inlay_hints_enabled(&self) -> bool {
4330 self.inlay_hint_cache.enabled
4331 }
4332
4333 pub fn inline_values_enabled(&self) -> bool {
4334 self.inline_value_cache.enabled
4335 }
4336
4337 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4338 if self.semantics_provider.is_none() || !self.mode.is_full() {
4339 return;
4340 }
4341
4342 let reason_description = reason.description();
4343 let ignore_debounce = matches!(
4344 reason,
4345 InlayHintRefreshReason::SettingsChange(_)
4346 | InlayHintRefreshReason::Toggle(_)
4347 | InlayHintRefreshReason::ExcerptsRemoved(_)
4348 | InlayHintRefreshReason::ModifiersChanged(_)
4349 );
4350 let (invalidate_cache, required_languages) = match reason {
4351 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4352 match self.inlay_hint_cache.modifiers_override(enabled) {
4353 Some(enabled) => {
4354 if enabled {
4355 (InvalidationStrategy::RefreshRequested, None)
4356 } else {
4357 self.splice_inlays(
4358 &self
4359 .visible_inlay_hints(cx)
4360 .iter()
4361 .map(|inlay| inlay.id)
4362 .collect::<Vec<InlayId>>(),
4363 Vec::new(),
4364 cx,
4365 );
4366 return;
4367 }
4368 }
4369 None => return,
4370 }
4371 }
4372 InlayHintRefreshReason::Toggle(enabled) => {
4373 if self.inlay_hint_cache.toggle(enabled) {
4374 if enabled {
4375 (InvalidationStrategy::RefreshRequested, None)
4376 } else {
4377 self.splice_inlays(
4378 &self
4379 .visible_inlay_hints(cx)
4380 .iter()
4381 .map(|inlay| inlay.id)
4382 .collect::<Vec<InlayId>>(),
4383 Vec::new(),
4384 cx,
4385 );
4386 return;
4387 }
4388 } else {
4389 return;
4390 }
4391 }
4392 InlayHintRefreshReason::SettingsChange(new_settings) => {
4393 match self.inlay_hint_cache.update_settings(
4394 &self.buffer,
4395 new_settings,
4396 self.visible_inlay_hints(cx),
4397 cx,
4398 ) {
4399 ControlFlow::Break(Some(InlaySplice {
4400 to_remove,
4401 to_insert,
4402 })) => {
4403 self.splice_inlays(&to_remove, to_insert, cx);
4404 return;
4405 }
4406 ControlFlow::Break(None) => return,
4407 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4408 }
4409 }
4410 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4411 if let Some(InlaySplice {
4412 to_remove,
4413 to_insert,
4414 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4415 {
4416 self.splice_inlays(&to_remove, to_insert, cx);
4417 }
4418 self.display_map.update(cx, |display_map, _| {
4419 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4420 });
4421 return;
4422 }
4423 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4424 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4425 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4426 }
4427 InlayHintRefreshReason::RefreshRequested => {
4428 (InvalidationStrategy::RefreshRequested, None)
4429 }
4430 };
4431
4432 if let Some(InlaySplice {
4433 to_remove,
4434 to_insert,
4435 }) = self.inlay_hint_cache.spawn_hint_refresh(
4436 reason_description,
4437 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4438 invalidate_cache,
4439 ignore_debounce,
4440 cx,
4441 ) {
4442 self.splice_inlays(&to_remove, to_insert, cx);
4443 }
4444 }
4445
4446 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4447 self.display_map
4448 .read(cx)
4449 .current_inlays()
4450 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4451 .cloned()
4452 .collect()
4453 }
4454
4455 pub fn excerpts_for_inlay_hints_query(
4456 &self,
4457 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4458 cx: &mut Context<Editor>,
4459 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4460 let Some(project) = self.project.as_ref() else {
4461 return HashMap::default();
4462 };
4463 let project = project.read(cx);
4464 let multi_buffer = self.buffer().read(cx);
4465 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4466 let multi_buffer_visible_start = self
4467 .scroll_manager
4468 .anchor()
4469 .anchor
4470 .to_point(&multi_buffer_snapshot);
4471 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4472 multi_buffer_visible_start
4473 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4474 Bias::Left,
4475 );
4476 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4477 multi_buffer_snapshot
4478 .range_to_buffer_ranges(multi_buffer_visible_range)
4479 .into_iter()
4480 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4481 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4482 let buffer_file = project::File::from_dyn(buffer.file())?;
4483 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4484 let worktree_entry = buffer_worktree
4485 .read(cx)
4486 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4487 if worktree_entry.is_ignored {
4488 return None;
4489 }
4490
4491 let language = buffer.language()?;
4492 if let Some(restrict_to_languages) = restrict_to_languages {
4493 if !restrict_to_languages.contains(language) {
4494 return None;
4495 }
4496 }
4497 Some((
4498 excerpt_id,
4499 (
4500 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4501 buffer.version().clone(),
4502 excerpt_visible_range,
4503 ),
4504 ))
4505 })
4506 .collect()
4507 }
4508
4509 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4510 TextLayoutDetails {
4511 text_system: window.text_system().clone(),
4512 editor_style: self.style.clone().unwrap(),
4513 rem_size: window.rem_size(),
4514 scroll_anchor: self.scroll_manager.anchor(),
4515 visible_rows: self.visible_line_count(),
4516 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4517 }
4518 }
4519
4520 pub fn splice_inlays(
4521 &self,
4522 to_remove: &[InlayId],
4523 to_insert: Vec<Inlay>,
4524 cx: &mut Context<Self>,
4525 ) {
4526 self.display_map.update(cx, |display_map, cx| {
4527 display_map.splice_inlays(to_remove, to_insert, cx)
4528 });
4529 cx.notify();
4530 }
4531
4532 fn trigger_on_type_formatting(
4533 &self,
4534 input: String,
4535 window: &mut Window,
4536 cx: &mut Context<Self>,
4537 ) -> Option<Task<Result<()>>> {
4538 if input.len() != 1 {
4539 return None;
4540 }
4541
4542 let project = self.project.as_ref()?;
4543 let position = self.selections.newest_anchor().head();
4544 let (buffer, buffer_position) = self
4545 .buffer
4546 .read(cx)
4547 .text_anchor_for_position(position, cx)?;
4548
4549 let settings = language_settings::language_settings(
4550 buffer
4551 .read(cx)
4552 .language_at(buffer_position)
4553 .map(|l| l.name()),
4554 buffer.read(cx).file(),
4555 cx,
4556 );
4557 if !settings.use_on_type_format {
4558 return None;
4559 }
4560
4561 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4562 // hence we do LSP request & edit on host side only — add formats to host's history.
4563 let push_to_lsp_host_history = true;
4564 // If this is not the host, append its history with new edits.
4565 let push_to_client_history = project.read(cx).is_via_collab();
4566
4567 let on_type_formatting = project.update(cx, |project, cx| {
4568 project.on_type_format(
4569 buffer.clone(),
4570 buffer_position,
4571 input,
4572 push_to_lsp_host_history,
4573 cx,
4574 )
4575 });
4576 Some(cx.spawn_in(window, async move |editor, cx| {
4577 if let Some(transaction) = on_type_formatting.await? {
4578 if push_to_client_history {
4579 buffer
4580 .update(cx, |buffer, _| {
4581 buffer.push_transaction(transaction, Instant::now());
4582 buffer.finalize_last_transaction();
4583 })
4584 .ok();
4585 }
4586 editor.update(cx, |editor, cx| {
4587 editor.refresh_document_highlights(cx);
4588 })?;
4589 }
4590 Ok(())
4591 }))
4592 }
4593
4594 pub fn show_word_completions(
4595 &mut self,
4596 _: &ShowWordCompletions,
4597 window: &mut Window,
4598 cx: &mut Context<Self>,
4599 ) {
4600 self.open_completions_menu(true, None, window, cx);
4601 }
4602
4603 pub fn show_completions(
4604 &mut self,
4605 options: &ShowCompletions,
4606 window: &mut Window,
4607 cx: &mut Context<Self>,
4608 ) {
4609 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4610 }
4611
4612 fn open_completions_menu(
4613 &mut self,
4614 ignore_completion_provider: bool,
4615 trigger: Option<&str>,
4616 window: &mut Window,
4617 cx: &mut Context<Self>,
4618 ) {
4619 if self.pending_rename.is_some() {
4620 return;
4621 }
4622 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4623 return;
4624 }
4625
4626 let position = self.selections.newest_anchor().head();
4627 if position.diff_base_anchor.is_some() {
4628 return;
4629 }
4630 let (buffer, buffer_position) =
4631 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4632 output
4633 } else {
4634 return;
4635 };
4636 let buffer_snapshot = buffer.read(cx).snapshot();
4637 let show_completion_documentation = buffer_snapshot
4638 .settings_at(buffer_position, cx)
4639 .show_completion_documentation;
4640
4641 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4642
4643 let trigger_kind = match trigger {
4644 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4645 CompletionTriggerKind::TRIGGER_CHARACTER
4646 }
4647 _ => CompletionTriggerKind::INVOKED,
4648 };
4649 let completion_context = CompletionContext {
4650 trigger_character: trigger.and_then(|trigger| {
4651 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4652 Some(String::from(trigger))
4653 } else {
4654 None
4655 }
4656 }),
4657 trigger_kind,
4658 };
4659
4660 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4661 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4662 let word_to_exclude = buffer_snapshot
4663 .text_for_range(old_range.clone())
4664 .collect::<String>();
4665 (
4666 buffer_snapshot.anchor_before(old_range.start)
4667 ..buffer_snapshot.anchor_after(old_range.end),
4668 Some(word_to_exclude),
4669 )
4670 } else {
4671 (buffer_position..buffer_position, None)
4672 };
4673
4674 let completion_settings = language_settings(
4675 buffer_snapshot
4676 .language_at(buffer_position)
4677 .map(|language| language.name()),
4678 buffer_snapshot.file(),
4679 cx,
4680 )
4681 .completions;
4682
4683 // The document can be large, so stay in reasonable bounds when searching for words,
4684 // otherwise completion pop-up might be slow to appear.
4685 const WORD_LOOKUP_ROWS: u32 = 5_000;
4686 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4687 let min_word_search = buffer_snapshot.clip_point(
4688 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4689 Bias::Left,
4690 );
4691 let max_word_search = buffer_snapshot.clip_point(
4692 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4693 Bias::Right,
4694 );
4695 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4696 ..buffer_snapshot.point_to_offset(max_word_search);
4697
4698 let provider = self
4699 .completion_provider
4700 .as_ref()
4701 .filter(|_| !ignore_completion_provider);
4702 let skip_digits = query
4703 .as_ref()
4704 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4705
4706 let (mut words, provided_completions) = match provider {
4707 Some(provider) => {
4708 let completions = provider.completions(
4709 position.excerpt_id,
4710 &buffer,
4711 buffer_position,
4712 completion_context,
4713 window,
4714 cx,
4715 );
4716
4717 let words = match completion_settings.words {
4718 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4719 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4720 .background_spawn(async move {
4721 buffer_snapshot.words_in_range(WordsQuery {
4722 fuzzy_contents: None,
4723 range: word_search_range,
4724 skip_digits,
4725 })
4726 }),
4727 };
4728
4729 (words, completions)
4730 }
4731 None => (
4732 cx.background_spawn(async move {
4733 buffer_snapshot.words_in_range(WordsQuery {
4734 fuzzy_contents: None,
4735 range: word_search_range,
4736 skip_digits,
4737 })
4738 }),
4739 Task::ready(Ok(None)),
4740 ),
4741 };
4742
4743 let sort_completions = provider
4744 .as_ref()
4745 .map_or(false, |provider| provider.sort_completions());
4746
4747 let filter_completions = provider
4748 .as_ref()
4749 .map_or(true, |provider| provider.filter_completions());
4750
4751 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4752
4753 let id = post_inc(&mut self.next_completion_id);
4754 let task = cx.spawn_in(window, async move |editor, cx| {
4755 async move {
4756 editor.update(cx, |this, _| {
4757 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4758 })?;
4759
4760 let mut completions = Vec::new();
4761 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4762 completions.extend(provided_completions);
4763 if completion_settings.words == WordsCompletionMode::Fallback {
4764 words = Task::ready(BTreeMap::default());
4765 }
4766 }
4767
4768 let mut words = words.await;
4769 if let Some(word_to_exclude) = &word_to_exclude {
4770 words.remove(word_to_exclude);
4771 }
4772 for lsp_completion in &completions {
4773 words.remove(&lsp_completion.new_text);
4774 }
4775 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4776 replace_range: old_range.clone(),
4777 new_text: word.clone(),
4778 label: CodeLabel::plain(word, None),
4779 icon_path: None,
4780 documentation: None,
4781 source: CompletionSource::BufferWord {
4782 word_range,
4783 resolved: false,
4784 },
4785 insert_text_mode: Some(InsertTextMode::AS_IS),
4786 confirm: None,
4787 }));
4788
4789 let menu = if completions.is_empty() {
4790 None
4791 } else {
4792 let mut menu = CompletionsMenu::new(
4793 id,
4794 sort_completions,
4795 show_completion_documentation,
4796 ignore_completion_provider,
4797 position,
4798 buffer.clone(),
4799 completions.into(),
4800 snippet_sort_order,
4801 );
4802
4803 menu.filter(
4804 if filter_completions {
4805 query.as_deref()
4806 } else {
4807 None
4808 },
4809 cx.background_executor().clone(),
4810 )
4811 .await;
4812
4813 menu.visible().then_some(menu)
4814 };
4815
4816 editor.update_in(cx, |editor, window, cx| {
4817 match editor.context_menu.borrow().as_ref() {
4818 None => {}
4819 Some(CodeContextMenu::Completions(prev_menu)) => {
4820 if prev_menu.id > id {
4821 return;
4822 }
4823 }
4824 _ => return,
4825 }
4826
4827 if editor.focus_handle.is_focused(window) && menu.is_some() {
4828 let mut menu = menu.unwrap();
4829 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4830
4831 *editor.context_menu.borrow_mut() =
4832 Some(CodeContextMenu::Completions(menu));
4833
4834 if editor.show_edit_predictions_in_menu() {
4835 editor.update_visible_inline_completion(window, cx);
4836 } else {
4837 editor.discard_inline_completion(false, cx);
4838 }
4839
4840 cx.notify();
4841 } else if editor.completion_tasks.len() <= 1 {
4842 // If there are no more completion tasks and the last menu was
4843 // empty, we should hide it.
4844 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4845 // If it was already hidden and we don't show inline
4846 // completions in the menu, we should also show the
4847 // inline-completion when available.
4848 if was_hidden && editor.show_edit_predictions_in_menu() {
4849 editor.update_visible_inline_completion(window, cx);
4850 }
4851 }
4852 })?;
4853
4854 anyhow::Ok(())
4855 }
4856 .log_err()
4857 .await
4858 });
4859
4860 self.completion_tasks.push((id, task));
4861 }
4862
4863 #[cfg(feature = "test-support")]
4864 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4865 let menu = self.context_menu.borrow();
4866 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4867 let completions = menu.completions.borrow();
4868 Some(completions.to_vec())
4869 } else {
4870 None
4871 }
4872 }
4873
4874 pub fn confirm_completion(
4875 &mut self,
4876 action: &ConfirmCompletion,
4877 window: &mut Window,
4878 cx: &mut Context<Self>,
4879 ) -> Option<Task<Result<()>>> {
4880 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4881 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4882 }
4883
4884 pub fn confirm_completion_insert(
4885 &mut self,
4886 _: &ConfirmCompletionInsert,
4887 window: &mut Window,
4888 cx: &mut Context<Self>,
4889 ) -> Option<Task<Result<()>>> {
4890 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4891 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4892 }
4893
4894 pub fn confirm_completion_replace(
4895 &mut self,
4896 _: &ConfirmCompletionReplace,
4897 window: &mut Window,
4898 cx: &mut Context<Self>,
4899 ) -> Option<Task<Result<()>>> {
4900 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4901 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4902 }
4903
4904 pub fn compose_completion(
4905 &mut self,
4906 action: &ComposeCompletion,
4907 window: &mut Window,
4908 cx: &mut Context<Self>,
4909 ) -> Option<Task<Result<()>>> {
4910 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4911 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4912 }
4913
4914 fn do_completion(
4915 &mut self,
4916 item_ix: Option<usize>,
4917 intent: CompletionIntent,
4918 window: &mut Window,
4919 cx: &mut Context<Editor>,
4920 ) -> Option<Task<Result<()>>> {
4921 use language::ToOffset as _;
4922
4923 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4924 else {
4925 return None;
4926 };
4927
4928 let candidate_id = {
4929 let entries = completions_menu.entries.borrow();
4930 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4931 if self.show_edit_predictions_in_menu() {
4932 self.discard_inline_completion(true, cx);
4933 }
4934 mat.candidate_id
4935 };
4936
4937 let buffer_handle = completions_menu.buffer;
4938 let completion = completions_menu
4939 .completions
4940 .borrow()
4941 .get(candidate_id)?
4942 .clone();
4943 cx.stop_propagation();
4944
4945 let snippet;
4946 let new_text;
4947 if completion.is_snippet() {
4948 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4949 new_text = snippet.as_ref().unwrap().text.clone();
4950 } else {
4951 snippet = None;
4952 new_text = completion.new_text.clone();
4953 };
4954
4955 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4956 let buffer = buffer_handle.read(cx);
4957 let snapshot = self.buffer.read(cx).snapshot(cx);
4958 let replace_range_multibuffer = {
4959 let excerpt = snapshot
4960 .excerpt_containing(self.selections.newest_anchor().range())
4961 .unwrap();
4962 let multibuffer_anchor = snapshot
4963 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4964 .unwrap()
4965 ..snapshot
4966 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4967 .unwrap();
4968 multibuffer_anchor.start.to_offset(&snapshot)
4969 ..multibuffer_anchor.end.to_offset(&snapshot)
4970 };
4971 let newest_anchor = self.selections.newest_anchor();
4972 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4973 return None;
4974 }
4975
4976 let old_text = buffer
4977 .text_for_range(replace_range.clone())
4978 .collect::<String>();
4979 let lookbehind = newest_anchor
4980 .start
4981 .text_anchor
4982 .to_offset(buffer)
4983 .saturating_sub(replace_range.start);
4984 let lookahead = replace_range
4985 .end
4986 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4987 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4988 let suffix = &old_text[lookbehind.min(old_text.len())..];
4989
4990 let selections = self.selections.all::<usize>(cx);
4991 let mut ranges = Vec::new();
4992 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4993
4994 for selection in &selections {
4995 let range = if selection.id == newest_anchor.id {
4996 replace_range_multibuffer.clone()
4997 } else {
4998 let mut range = selection.range();
4999
5000 // if prefix is present, don't duplicate it
5001 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
5002 range.start = range.start.saturating_sub(lookbehind);
5003
5004 // if suffix is also present, mimic the newest cursor and replace it
5005 if selection.id != newest_anchor.id
5006 && snapshot.contains_str_at(range.end, suffix)
5007 {
5008 range.end += lookahead;
5009 }
5010 }
5011 range
5012 };
5013
5014 ranges.push(range.clone());
5015
5016 if !self.linked_edit_ranges.is_empty() {
5017 let start_anchor = snapshot.anchor_before(range.start);
5018 let end_anchor = snapshot.anchor_after(range.end);
5019 if let Some(ranges) = self
5020 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5021 {
5022 for (buffer, edits) in ranges {
5023 linked_edits
5024 .entry(buffer.clone())
5025 .or_default()
5026 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5027 }
5028 }
5029 }
5030 }
5031
5032 cx.emit(EditorEvent::InputHandled {
5033 utf16_range_to_replace: None,
5034 text: new_text.clone().into(),
5035 });
5036
5037 self.transact(window, cx, |this, window, cx| {
5038 if let Some(mut snippet) = snippet {
5039 snippet.text = new_text.to_string();
5040 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5041 } else {
5042 this.buffer.update(cx, |buffer, cx| {
5043 let auto_indent = match completion.insert_text_mode {
5044 Some(InsertTextMode::AS_IS) => None,
5045 _ => this.autoindent_mode.clone(),
5046 };
5047 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5048 buffer.edit(edits, auto_indent, cx);
5049 });
5050 }
5051 for (buffer, edits) in linked_edits {
5052 buffer.update(cx, |buffer, cx| {
5053 let snapshot = buffer.snapshot();
5054 let edits = edits
5055 .into_iter()
5056 .map(|(range, text)| {
5057 use text::ToPoint as TP;
5058 let end_point = TP::to_point(&range.end, &snapshot);
5059 let start_point = TP::to_point(&range.start, &snapshot);
5060 (start_point..end_point, text)
5061 })
5062 .sorted_by_key(|(range, _)| range.start);
5063 buffer.edit(edits, None, cx);
5064 })
5065 }
5066
5067 this.refresh_inline_completion(true, false, window, cx);
5068 });
5069
5070 let show_new_completions_on_confirm = completion
5071 .confirm
5072 .as_ref()
5073 .map_or(false, |confirm| confirm(intent, window, cx));
5074 if show_new_completions_on_confirm {
5075 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5076 }
5077
5078 let provider = self.completion_provider.as_ref()?;
5079 drop(completion);
5080 let apply_edits = provider.apply_additional_edits_for_completion(
5081 buffer_handle,
5082 completions_menu.completions.clone(),
5083 candidate_id,
5084 true,
5085 cx,
5086 );
5087
5088 let editor_settings = EditorSettings::get_global(cx);
5089 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5090 // After the code completion is finished, users often want to know what signatures are needed.
5091 // so we should automatically call signature_help
5092 self.show_signature_help(&ShowSignatureHelp, window, cx);
5093 }
5094
5095 Some(cx.foreground_executor().spawn(async move {
5096 apply_edits.await?;
5097 Ok(())
5098 }))
5099 }
5100
5101 pub fn toggle_code_actions(
5102 &mut self,
5103 action: &ToggleCodeActions,
5104 window: &mut Window,
5105 cx: &mut Context<Self>,
5106 ) {
5107 let quick_launch = action.quick_launch;
5108 let mut context_menu = self.context_menu.borrow_mut();
5109 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5110 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5111 // Toggle if we're selecting the same one
5112 *context_menu = None;
5113 cx.notify();
5114 return;
5115 } else {
5116 // Otherwise, clear it and start a new one
5117 *context_menu = None;
5118 cx.notify();
5119 }
5120 }
5121 drop(context_menu);
5122 let snapshot = self.snapshot(window, cx);
5123 let deployed_from_indicator = action.deployed_from_indicator;
5124 let mut task = self.code_actions_task.take();
5125 let action = action.clone();
5126 cx.spawn_in(window, async move |editor, cx| {
5127 while let Some(prev_task) = task {
5128 prev_task.await.log_err();
5129 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5130 }
5131
5132 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5133 if editor.focus_handle.is_focused(window) {
5134 let multibuffer_point = action
5135 .deployed_from_indicator
5136 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5137 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5138 let (buffer, buffer_row) = snapshot
5139 .buffer_snapshot
5140 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5141 .and_then(|(buffer_snapshot, range)| {
5142 editor
5143 .buffer
5144 .read(cx)
5145 .buffer(buffer_snapshot.remote_id())
5146 .map(|buffer| (buffer, range.start.row))
5147 })?;
5148 let (_, code_actions) = editor
5149 .available_code_actions
5150 .clone()
5151 .and_then(|(location, code_actions)| {
5152 let snapshot = location.buffer.read(cx).snapshot();
5153 let point_range = location.range.to_point(&snapshot);
5154 let point_range = point_range.start.row..=point_range.end.row;
5155 if point_range.contains(&buffer_row) {
5156 Some((location, code_actions))
5157 } else {
5158 None
5159 }
5160 })
5161 .unzip();
5162 let buffer_id = buffer.read(cx).remote_id();
5163 let tasks = editor
5164 .tasks
5165 .get(&(buffer_id, buffer_row))
5166 .map(|t| Arc::new(t.to_owned()));
5167 if tasks.is_none() && code_actions.is_none() {
5168 return None;
5169 }
5170
5171 editor.completion_tasks.clear();
5172 editor.discard_inline_completion(false, cx);
5173 let task_context =
5174 tasks
5175 .as_ref()
5176 .zip(editor.project.clone())
5177 .map(|(tasks, project)| {
5178 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5179 });
5180
5181 Some(cx.spawn_in(window, async move |editor, cx| {
5182 let task_context = match task_context {
5183 Some(task_context) => task_context.await,
5184 None => None,
5185 };
5186 let resolved_tasks =
5187 tasks
5188 .zip(task_context.clone())
5189 .map(|(tasks, task_context)| ResolvedTasks {
5190 templates: tasks.resolve(&task_context).collect(),
5191 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5192 multibuffer_point.row,
5193 tasks.column,
5194 )),
5195 });
5196 let spawn_straight_away = quick_launch
5197 && resolved_tasks
5198 .as_ref()
5199 .map_or(false, |tasks| tasks.templates.len() == 1)
5200 && code_actions
5201 .as_ref()
5202 .map_or(true, |actions| actions.is_empty());
5203 let debug_scenarios = editor.update(cx, |editor, cx| {
5204 if cx.has_flag::<DebuggerFeatureFlag>() {
5205 maybe!({
5206 let project = editor.project.as_ref()?;
5207 let dap_store = project.read(cx).dap_store();
5208 let mut scenarios = vec![];
5209 let resolved_tasks = resolved_tasks.as_ref()?;
5210 let debug_adapter: SharedString = buffer
5211 .read(cx)
5212 .language()?
5213 .context_provider()?
5214 .debug_adapter()?
5215 .into();
5216 dap_store.update(cx, |this, cx| {
5217 for (_, task) in &resolved_tasks.templates {
5218 if let Some(scenario) = this
5219 .debug_scenario_for_build_task(
5220 task.resolved.clone(),
5221 SharedString::from(
5222 task.original_task().label.clone(),
5223 ),
5224 debug_adapter.clone(),
5225 cx,
5226 )
5227 {
5228 scenarios.push(scenario);
5229 }
5230 }
5231 });
5232 Some(scenarios)
5233 })
5234 .unwrap_or_default()
5235 } else {
5236 vec![]
5237 }
5238 })?;
5239 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5240 *editor.context_menu.borrow_mut() =
5241 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5242 buffer,
5243 actions: CodeActionContents::new(
5244 resolved_tasks,
5245 code_actions,
5246 debug_scenarios,
5247 task_context.unwrap_or_default(),
5248 ),
5249 selected_item: Default::default(),
5250 scroll_handle: UniformListScrollHandle::default(),
5251 deployed_from_indicator,
5252 }));
5253 if spawn_straight_away {
5254 if let Some(task) = editor.confirm_code_action(
5255 &ConfirmCodeAction { item_ix: Some(0) },
5256 window,
5257 cx,
5258 ) {
5259 cx.notify();
5260 return task;
5261 }
5262 }
5263 cx.notify();
5264 Task::ready(Ok(()))
5265 }) {
5266 task.await
5267 } else {
5268 Ok(())
5269 }
5270 }))
5271 } else {
5272 Some(Task::ready(Ok(())))
5273 }
5274 })?;
5275 if let Some(task) = spawned_test_task {
5276 task.await?;
5277 }
5278
5279 Ok::<_, anyhow::Error>(())
5280 })
5281 .detach_and_log_err(cx);
5282 }
5283
5284 pub fn confirm_code_action(
5285 &mut self,
5286 action: &ConfirmCodeAction,
5287 window: &mut Window,
5288 cx: &mut Context<Self>,
5289 ) -> Option<Task<Result<()>>> {
5290 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5291
5292 let actions_menu =
5293 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5294 menu
5295 } else {
5296 return None;
5297 };
5298
5299 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5300 let action = actions_menu.actions.get(action_ix)?;
5301 let title = action.label();
5302 let buffer = actions_menu.buffer;
5303 let workspace = self.workspace()?;
5304
5305 match action {
5306 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5307 workspace.update(cx, |workspace, cx| {
5308 workspace.schedule_resolved_task(
5309 task_source_kind,
5310 resolved_task,
5311 false,
5312 window,
5313 cx,
5314 );
5315
5316 Some(Task::ready(Ok(())))
5317 })
5318 }
5319 CodeActionsItem::CodeAction {
5320 excerpt_id,
5321 action,
5322 provider,
5323 } => {
5324 let apply_code_action =
5325 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5326 let workspace = workspace.downgrade();
5327 Some(cx.spawn_in(window, async move |editor, cx| {
5328 let project_transaction = apply_code_action.await?;
5329 Self::open_project_transaction(
5330 &editor,
5331 workspace,
5332 project_transaction,
5333 title,
5334 cx,
5335 )
5336 .await
5337 }))
5338 }
5339 CodeActionsItem::DebugScenario(scenario) => {
5340 let context = actions_menu.actions.context.clone();
5341
5342 workspace.update(cx, |workspace, cx| {
5343 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5344 });
5345 Some(Task::ready(Ok(())))
5346 }
5347 }
5348 }
5349
5350 pub async fn open_project_transaction(
5351 this: &WeakEntity<Editor>,
5352 workspace: WeakEntity<Workspace>,
5353 transaction: ProjectTransaction,
5354 title: String,
5355 cx: &mut AsyncWindowContext,
5356 ) -> Result<()> {
5357 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5358 cx.update(|_, cx| {
5359 entries.sort_unstable_by_key(|(buffer, _)| {
5360 buffer.read(cx).file().map(|f| f.path().clone())
5361 });
5362 })?;
5363
5364 // If the project transaction's edits are all contained within this editor, then
5365 // avoid opening a new editor to display them.
5366
5367 if let Some((buffer, transaction)) = entries.first() {
5368 if entries.len() == 1 {
5369 let excerpt = this.update(cx, |editor, cx| {
5370 editor
5371 .buffer()
5372 .read(cx)
5373 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5374 })?;
5375 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5376 if excerpted_buffer == *buffer {
5377 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5378 let excerpt_range = excerpt_range.to_offset(buffer);
5379 buffer
5380 .edited_ranges_for_transaction::<usize>(transaction)
5381 .all(|range| {
5382 excerpt_range.start <= range.start
5383 && excerpt_range.end >= range.end
5384 })
5385 })?;
5386
5387 if all_edits_within_excerpt {
5388 return Ok(());
5389 }
5390 }
5391 }
5392 }
5393 } else {
5394 return Ok(());
5395 }
5396
5397 let mut ranges_to_highlight = Vec::new();
5398 let excerpt_buffer = cx.new(|cx| {
5399 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5400 for (buffer_handle, transaction) in &entries {
5401 let edited_ranges = buffer_handle
5402 .read(cx)
5403 .edited_ranges_for_transaction::<Point>(transaction)
5404 .collect::<Vec<_>>();
5405 let (ranges, _) = multibuffer.set_excerpts_for_path(
5406 PathKey::for_buffer(buffer_handle, cx),
5407 buffer_handle.clone(),
5408 edited_ranges,
5409 DEFAULT_MULTIBUFFER_CONTEXT,
5410 cx,
5411 );
5412
5413 ranges_to_highlight.extend(ranges);
5414 }
5415 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5416 multibuffer
5417 })?;
5418
5419 workspace.update_in(cx, |workspace, window, cx| {
5420 let project = workspace.project().clone();
5421 let editor =
5422 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5423 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5424 editor.update(cx, |editor, cx| {
5425 editor.highlight_background::<Self>(
5426 &ranges_to_highlight,
5427 |theme| theme.editor_highlighted_line_background,
5428 cx,
5429 );
5430 });
5431 })?;
5432
5433 Ok(())
5434 }
5435
5436 pub fn clear_code_action_providers(&mut self) {
5437 self.code_action_providers.clear();
5438 self.available_code_actions.take();
5439 }
5440
5441 pub fn add_code_action_provider(
5442 &mut self,
5443 provider: Rc<dyn CodeActionProvider>,
5444 window: &mut Window,
5445 cx: &mut Context<Self>,
5446 ) {
5447 if self
5448 .code_action_providers
5449 .iter()
5450 .any(|existing_provider| existing_provider.id() == provider.id())
5451 {
5452 return;
5453 }
5454
5455 self.code_action_providers.push(provider);
5456 self.refresh_code_actions(window, cx);
5457 }
5458
5459 pub fn remove_code_action_provider(
5460 &mut self,
5461 id: Arc<str>,
5462 window: &mut Window,
5463 cx: &mut Context<Self>,
5464 ) {
5465 self.code_action_providers
5466 .retain(|provider| provider.id() != id);
5467 self.refresh_code_actions(window, cx);
5468 }
5469
5470 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5471 let newest_selection = self.selections.newest_anchor().clone();
5472 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5473 let buffer = self.buffer.read(cx);
5474 if newest_selection.head().diff_base_anchor.is_some() {
5475 return None;
5476 }
5477 let (start_buffer, start) =
5478 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5479 let (end_buffer, end) =
5480 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5481 if start_buffer != end_buffer {
5482 return None;
5483 }
5484
5485 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5486 cx.background_executor()
5487 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5488 .await;
5489
5490 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5491 let providers = this.code_action_providers.clone();
5492 let tasks = this
5493 .code_action_providers
5494 .iter()
5495 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5496 .collect::<Vec<_>>();
5497 (providers, tasks)
5498 })?;
5499
5500 let mut actions = Vec::new();
5501 for (provider, provider_actions) in
5502 providers.into_iter().zip(future::join_all(tasks).await)
5503 {
5504 if let Some(provider_actions) = provider_actions.log_err() {
5505 actions.extend(provider_actions.into_iter().map(|action| {
5506 AvailableCodeAction {
5507 excerpt_id: newest_selection.start.excerpt_id,
5508 action,
5509 provider: provider.clone(),
5510 }
5511 }));
5512 }
5513 }
5514
5515 this.update(cx, |this, cx| {
5516 this.available_code_actions = if actions.is_empty() {
5517 None
5518 } else {
5519 Some((
5520 Location {
5521 buffer: start_buffer,
5522 range: start..end,
5523 },
5524 actions.into(),
5525 ))
5526 };
5527 cx.notify();
5528 })
5529 }));
5530 None
5531 }
5532
5533 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5534 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5535 self.show_git_blame_inline = false;
5536
5537 self.show_git_blame_inline_delay_task =
5538 Some(cx.spawn_in(window, async move |this, cx| {
5539 cx.background_executor().timer(delay).await;
5540
5541 this.update(cx, |this, cx| {
5542 this.show_git_blame_inline = true;
5543 cx.notify();
5544 })
5545 .log_err();
5546 }));
5547 }
5548 }
5549
5550 fn show_blame_popover(
5551 &mut self,
5552 blame_entry: &BlameEntry,
5553 position: gpui::Point<Pixels>,
5554 cx: &mut Context<Self>,
5555 ) {
5556 if let Some(state) = &mut self.inline_blame_popover {
5557 state.hide_task.take();
5558 cx.notify();
5559 } else {
5560 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5561 let show_task = cx.spawn(async move |editor, cx| {
5562 cx.background_executor()
5563 .timer(std::time::Duration::from_millis(delay))
5564 .await;
5565 editor
5566 .update(cx, |editor, cx| {
5567 if let Some(state) = &mut editor.inline_blame_popover {
5568 state.show_task = None;
5569 cx.notify();
5570 }
5571 })
5572 .ok();
5573 });
5574 let Some(blame) = self.blame.as_ref() else {
5575 return;
5576 };
5577 let blame = blame.read(cx);
5578 let details = blame.details_for_entry(&blame_entry);
5579 let markdown = cx.new(|cx| {
5580 Markdown::new(
5581 details
5582 .as_ref()
5583 .map(|message| message.message.clone())
5584 .unwrap_or_default(),
5585 None,
5586 None,
5587 cx,
5588 )
5589 });
5590 self.inline_blame_popover = Some(InlineBlamePopover {
5591 position,
5592 show_task: Some(show_task),
5593 hide_task: None,
5594 popover_bounds: None,
5595 popover_state: InlineBlamePopoverState {
5596 scroll_handle: ScrollHandle::new(),
5597 commit_message: details,
5598 markdown,
5599 },
5600 });
5601 }
5602 }
5603
5604 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5605 if let Some(state) = &mut self.inline_blame_popover {
5606 if state.show_task.is_some() {
5607 self.inline_blame_popover.take();
5608 cx.notify();
5609 } else {
5610 let hide_task = cx.spawn(async move |editor, cx| {
5611 cx.background_executor()
5612 .timer(std::time::Duration::from_millis(100))
5613 .await;
5614 editor
5615 .update(cx, |editor, cx| {
5616 editor.inline_blame_popover.take();
5617 cx.notify();
5618 })
5619 .ok();
5620 });
5621 state.hide_task = Some(hide_task);
5622 }
5623 }
5624 }
5625
5626 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5627 if self.pending_rename.is_some() {
5628 return None;
5629 }
5630
5631 let provider = self.semantics_provider.clone()?;
5632 let buffer = self.buffer.read(cx);
5633 let newest_selection = self.selections.newest_anchor().clone();
5634 let cursor_position = newest_selection.head();
5635 let (cursor_buffer, cursor_buffer_position) =
5636 buffer.text_anchor_for_position(cursor_position, cx)?;
5637 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5638 if cursor_buffer != tail_buffer {
5639 return None;
5640 }
5641 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5642 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5643 cx.background_executor()
5644 .timer(Duration::from_millis(debounce))
5645 .await;
5646
5647 let highlights = if let Some(highlights) = cx
5648 .update(|cx| {
5649 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5650 })
5651 .ok()
5652 .flatten()
5653 {
5654 highlights.await.log_err()
5655 } else {
5656 None
5657 };
5658
5659 if let Some(highlights) = highlights {
5660 this.update(cx, |this, cx| {
5661 if this.pending_rename.is_some() {
5662 return;
5663 }
5664
5665 let buffer_id = cursor_position.buffer_id;
5666 let buffer = this.buffer.read(cx);
5667 if !buffer
5668 .text_anchor_for_position(cursor_position, cx)
5669 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5670 {
5671 return;
5672 }
5673
5674 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5675 let mut write_ranges = Vec::new();
5676 let mut read_ranges = Vec::new();
5677 for highlight in highlights {
5678 for (excerpt_id, excerpt_range) in
5679 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5680 {
5681 let start = highlight
5682 .range
5683 .start
5684 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5685 let end = highlight
5686 .range
5687 .end
5688 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5689 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5690 continue;
5691 }
5692
5693 let range = Anchor {
5694 buffer_id,
5695 excerpt_id,
5696 text_anchor: start,
5697 diff_base_anchor: None,
5698 }..Anchor {
5699 buffer_id,
5700 excerpt_id,
5701 text_anchor: end,
5702 diff_base_anchor: None,
5703 };
5704 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5705 write_ranges.push(range);
5706 } else {
5707 read_ranges.push(range);
5708 }
5709 }
5710 }
5711
5712 this.highlight_background::<DocumentHighlightRead>(
5713 &read_ranges,
5714 |theme| theme.editor_document_highlight_read_background,
5715 cx,
5716 );
5717 this.highlight_background::<DocumentHighlightWrite>(
5718 &write_ranges,
5719 |theme| theme.editor_document_highlight_write_background,
5720 cx,
5721 );
5722 cx.notify();
5723 })
5724 .log_err();
5725 }
5726 }));
5727 None
5728 }
5729
5730 fn prepare_highlight_query_from_selection(
5731 &mut self,
5732 cx: &mut Context<Editor>,
5733 ) -> Option<(String, Range<Anchor>)> {
5734 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5735 return None;
5736 }
5737 if !EditorSettings::get_global(cx).selection_highlight {
5738 return None;
5739 }
5740 if self.selections.count() != 1 || self.selections.line_mode {
5741 return None;
5742 }
5743 let selection = self.selections.newest::<Point>(cx);
5744 if selection.is_empty() || selection.start.row != selection.end.row {
5745 return None;
5746 }
5747 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5748 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5749 let query = multi_buffer_snapshot
5750 .text_for_range(selection_anchor_range.clone())
5751 .collect::<String>();
5752 if query.trim().is_empty() {
5753 return None;
5754 }
5755 Some((query, selection_anchor_range))
5756 }
5757
5758 fn update_selection_occurrence_highlights(
5759 &mut self,
5760 query_text: String,
5761 query_range: Range<Anchor>,
5762 multi_buffer_range_to_query: Range<Point>,
5763 use_debounce: bool,
5764 window: &mut Window,
5765 cx: &mut Context<Editor>,
5766 ) -> Task<()> {
5767 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5768 cx.spawn_in(window, async move |editor, cx| {
5769 if use_debounce {
5770 cx.background_executor()
5771 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5772 .await;
5773 }
5774 let match_task = cx.background_spawn(async move {
5775 let buffer_ranges = multi_buffer_snapshot
5776 .range_to_buffer_ranges(multi_buffer_range_to_query)
5777 .into_iter()
5778 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5779 let mut match_ranges = Vec::new();
5780 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5781 match_ranges.extend(
5782 project::search::SearchQuery::text(
5783 query_text.clone(),
5784 false,
5785 false,
5786 false,
5787 Default::default(),
5788 Default::default(),
5789 false,
5790 None,
5791 )
5792 .unwrap()
5793 .search(&buffer_snapshot, Some(search_range.clone()))
5794 .await
5795 .into_iter()
5796 .filter_map(|match_range| {
5797 let match_start = buffer_snapshot
5798 .anchor_after(search_range.start + match_range.start);
5799 let match_end =
5800 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5801 let match_anchor_range = Anchor::range_in_buffer(
5802 excerpt_id,
5803 buffer_snapshot.remote_id(),
5804 match_start..match_end,
5805 );
5806 (match_anchor_range != query_range).then_some(match_anchor_range)
5807 }),
5808 );
5809 }
5810 match_ranges
5811 });
5812 let match_ranges = match_task.await;
5813 editor
5814 .update_in(cx, |editor, _, cx| {
5815 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5816 if !match_ranges.is_empty() {
5817 editor.highlight_background::<SelectedTextHighlight>(
5818 &match_ranges,
5819 |theme| theme.editor_document_highlight_bracket_background,
5820 cx,
5821 )
5822 }
5823 })
5824 .log_err();
5825 })
5826 }
5827
5828 fn refresh_selected_text_highlights(
5829 &mut self,
5830 on_buffer_edit: bool,
5831 window: &mut Window,
5832 cx: &mut Context<Editor>,
5833 ) {
5834 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5835 else {
5836 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5837 self.quick_selection_highlight_task.take();
5838 self.debounced_selection_highlight_task.take();
5839 return;
5840 };
5841 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5842 if on_buffer_edit
5843 || self
5844 .quick_selection_highlight_task
5845 .as_ref()
5846 .map_or(true, |(prev_anchor_range, _)| {
5847 prev_anchor_range != &query_range
5848 })
5849 {
5850 let multi_buffer_visible_start = self
5851 .scroll_manager
5852 .anchor()
5853 .anchor
5854 .to_point(&multi_buffer_snapshot);
5855 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5856 multi_buffer_visible_start
5857 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5858 Bias::Left,
5859 );
5860 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5861 self.quick_selection_highlight_task = Some((
5862 query_range.clone(),
5863 self.update_selection_occurrence_highlights(
5864 query_text.clone(),
5865 query_range.clone(),
5866 multi_buffer_visible_range,
5867 false,
5868 window,
5869 cx,
5870 ),
5871 ));
5872 }
5873 if on_buffer_edit
5874 || self
5875 .debounced_selection_highlight_task
5876 .as_ref()
5877 .map_or(true, |(prev_anchor_range, _)| {
5878 prev_anchor_range != &query_range
5879 })
5880 {
5881 let multi_buffer_start = multi_buffer_snapshot
5882 .anchor_before(0)
5883 .to_point(&multi_buffer_snapshot);
5884 let multi_buffer_end = multi_buffer_snapshot
5885 .anchor_after(multi_buffer_snapshot.len())
5886 .to_point(&multi_buffer_snapshot);
5887 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5888 self.debounced_selection_highlight_task = Some((
5889 query_range.clone(),
5890 self.update_selection_occurrence_highlights(
5891 query_text,
5892 query_range,
5893 multi_buffer_full_range,
5894 true,
5895 window,
5896 cx,
5897 ),
5898 ));
5899 }
5900 }
5901
5902 pub fn refresh_inline_completion(
5903 &mut self,
5904 debounce: bool,
5905 user_requested: bool,
5906 window: &mut Window,
5907 cx: &mut Context<Self>,
5908 ) -> Option<()> {
5909 let provider = self.edit_prediction_provider()?;
5910 let cursor = self.selections.newest_anchor().head();
5911 let (buffer, cursor_buffer_position) =
5912 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5913
5914 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5915 self.discard_inline_completion(false, cx);
5916 return None;
5917 }
5918
5919 if !user_requested
5920 && (!self.should_show_edit_predictions()
5921 || !self.is_focused(window)
5922 || buffer.read(cx).is_empty())
5923 {
5924 self.discard_inline_completion(false, cx);
5925 return None;
5926 }
5927
5928 self.update_visible_inline_completion(window, cx);
5929 provider.refresh(
5930 self.project.clone(),
5931 buffer,
5932 cursor_buffer_position,
5933 debounce,
5934 cx,
5935 );
5936 Some(())
5937 }
5938
5939 fn show_edit_predictions_in_menu(&self) -> bool {
5940 match self.edit_prediction_settings {
5941 EditPredictionSettings::Disabled => false,
5942 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5943 }
5944 }
5945
5946 pub fn edit_predictions_enabled(&self) -> bool {
5947 match self.edit_prediction_settings {
5948 EditPredictionSettings::Disabled => false,
5949 EditPredictionSettings::Enabled { .. } => true,
5950 }
5951 }
5952
5953 fn edit_prediction_requires_modifier(&self) -> bool {
5954 match self.edit_prediction_settings {
5955 EditPredictionSettings::Disabled => false,
5956 EditPredictionSettings::Enabled {
5957 preview_requires_modifier,
5958 ..
5959 } => preview_requires_modifier,
5960 }
5961 }
5962
5963 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5964 if self.edit_prediction_provider.is_none() {
5965 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5966 } else {
5967 let selection = self.selections.newest_anchor();
5968 let cursor = selection.head();
5969
5970 if let Some((buffer, cursor_buffer_position)) =
5971 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5972 {
5973 self.edit_prediction_settings =
5974 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5975 }
5976 }
5977 }
5978
5979 fn edit_prediction_settings_at_position(
5980 &self,
5981 buffer: &Entity<Buffer>,
5982 buffer_position: language::Anchor,
5983 cx: &App,
5984 ) -> EditPredictionSettings {
5985 if !self.mode.is_full()
5986 || !self.show_inline_completions_override.unwrap_or(true)
5987 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5988 {
5989 return EditPredictionSettings::Disabled;
5990 }
5991
5992 let buffer = buffer.read(cx);
5993
5994 let file = buffer.file();
5995
5996 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5997 return EditPredictionSettings::Disabled;
5998 };
5999
6000 let by_provider = matches!(
6001 self.menu_inline_completions_policy,
6002 MenuInlineCompletionsPolicy::ByProvider
6003 );
6004
6005 let show_in_menu = by_provider
6006 && self
6007 .edit_prediction_provider
6008 .as_ref()
6009 .map_or(false, |provider| {
6010 provider.provider.show_completions_in_menu()
6011 });
6012
6013 let preview_requires_modifier =
6014 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6015
6016 EditPredictionSettings::Enabled {
6017 show_in_menu,
6018 preview_requires_modifier,
6019 }
6020 }
6021
6022 fn should_show_edit_predictions(&self) -> bool {
6023 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6024 }
6025
6026 pub fn edit_prediction_preview_is_active(&self) -> bool {
6027 matches!(
6028 self.edit_prediction_preview,
6029 EditPredictionPreview::Active { .. }
6030 )
6031 }
6032
6033 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6034 let cursor = self.selections.newest_anchor().head();
6035 if let Some((buffer, cursor_position)) =
6036 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6037 {
6038 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6039 } else {
6040 false
6041 }
6042 }
6043
6044 fn edit_predictions_enabled_in_buffer(
6045 &self,
6046 buffer: &Entity<Buffer>,
6047 buffer_position: language::Anchor,
6048 cx: &App,
6049 ) -> bool {
6050 maybe!({
6051 if self.read_only(cx) {
6052 return Some(false);
6053 }
6054 let provider = self.edit_prediction_provider()?;
6055 if !provider.is_enabled(&buffer, buffer_position, cx) {
6056 return Some(false);
6057 }
6058 let buffer = buffer.read(cx);
6059 let Some(file) = buffer.file() else {
6060 return Some(true);
6061 };
6062 let settings = all_language_settings(Some(file), cx);
6063 Some(settings.edit_predictions_enabled_for_file(file, cx))
6064 })
6065 .unwrap_or(false)
6066 }
6067
6068 fn cycle_inline_completion(
6069 &mut self,
6070 direction: Direction,
6071 window: &mut Window,
6072 cx: &mut Context<Self>,
6073 ) -> Option<()> {
6074 let provider = self.edit_prediction_provider()?;
6075 let cursor = self.selections.newest_anchor().head();
6076 let (buffer, cursor_buffer_position) =
6077 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6078 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6079 return None;
6080 }
6081
6082 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6083 self.update_visible_inline_completion(window, cx);
6084
6085 Some(())
6086 }
6087
6088 pub fn show_inline_completion(
6089 &mut self,
6090 _: &ShowEditPrediction,
6091 window: &mut Window,
6092 cx: &mut Context<Self>,
6093 ) {
6094 if !self.has_active_inline_completion() {
6095 self.refresh_inline_completion(false, true, window, cx);
6096 return;
6097 }
6098
6099 self.update_visible_inline_completion(window, cx);
6100 }
6101
6102 pub fn display_cursor_names(
6103 &mut self,
6104 _: &DisplayCursorNames,
6105 window: &mut Window,
6106 cx: &mut Context<Self>,
6107 ) {
6108 self.show_cursor_names(window, cx);
6109 }
6110
6111 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6112 self.show_cursor_names = true;
6113 cx.notify();
6114 cx.spawn_in(window, async move |this, cx| {
6115 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6116 this.update(cx, |this, cx| {
6117 this.show_cursor_names = false;
6118 cx.notify()
6119 })
6120 .ok()
6121 })
6122 .detach();
6123 }
6124
6125 pub fn next_edit_prediction(
6126 &mut self,
6127 _: &NextEditPrediction,
6128 window: &mut Window,
6129 cx: &mut Context<Self>,
6130 ) {
6131 if self.has_active_inline_completion() {
6132 self.cycle_inline_completion(Direction::Next, window, cx);
6133 } else {
6134 let is_copilot_disabled = self
6135 .refresh_inline_completion(false, true, window, cx)
6136 .is_none();
6137 if is_copilot_disabled {
6138 cx.propagate();
6139 }
6140 }
6141 }
6142
6143 pub fn previous_edit_prediction(
6144 &mut self,
6145 _: &PreviousEditPrediction,
6146 window: &mut Window,
6147 cx: &mut Context<Self>,
6148 ) {
6149 if self.has_active_inline_completion() {
6150 self.cycle_inline_completion(Direction::Prev, window, cx);
6151 } else {
6152 let is_copilot_disabled = self
6153 .refresh_inline_completion(false, true, window, cx)
6154 .is_none();
6155 if is_copilot_disabled {
6156 cx.propagate();
6157 }
6158 }
6159 }
6160
6161 pub fn accept_edit_prediction(
6162 &mut self,
6163 _: &AcceptEditPrediction,
6164 window: &mut Window,
6165 cx: &mut Context<Self>,
6166 ) {
6167 if self.show_edit_predictions_in_menu() {
6168 self.hide_context_menu(window, cx);
6169 }
6170
6171 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6172 return;
6173 };
6174
6175 self.report_inline_completion_event(
6176 active_inline_completion.completion_id.clone(),
6177 true,
6178 cx,
6179 );
6180
6181 match &active_inline_completion.completion {
6182 InlineCompletion::Move { target, .. } => {
6183 let target = *target;
6184
6185 if let Some(position_map) = &self.last_position_map {
6186 if position_map
6187 .visible_row_range
6188 .contains(&target.to_display_point(&position_map.snapshot).row())
6189 || !self.edit_prediction_requires_modifier()
6190 {
6191 self.unfold_ranges(&[target..target], true, false, cx);
6192 // Note that this is also done in vim's handler of the Tab action.
6193 self.change_selections(
6194 Some(Autoscroll::newest()),
6195 window,
6196 cx,
6197 |selections| {
6198 selections.select_anchor_ranges([target..target]);
6199 },
6200 );
6201 self.clear_row_highlights::<EditPredictionPreview>();
6202
6203 self.edit_prediction_preview
6204 .set_previous_scroll_position(None);
6205 } else {
6206 self.edit_prediction_preview
6207 .set_previous_scroll_position(Some(
6208 position_map.snapshot.scroll_anchor,
6209 ));
6210
6211 self.highlight_rows::<EditPredictionPreview>(
6212 target..target,
6213 cx.theme().colors().editor_highlighted_line_background,
6214 RowHighlightOptions {
6215 autoscroll: true,
6216 ..Default::default()
6217 },
6218 cx,
6219 );
6220 self.request_autoscroll(Autoscroll::fit(), cx);
6221 }
6222 }
6223 }
6224 InlineCompletion::Edit { edits, .. } => {
6225 if let Some(provider) = self.edit_prediction_provider() {
6226 provider.accept(cx);
6227 }
6228
6229 let snapshot = self.buffer.read(cx).snapshot(cx);
6230 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6231
6232 self.buffer.update(cx, |buffer, cx| {
6233 buffer.edit(edits.iter().cloned(), None, cx)
6234 });
6235
6236 self.change_selections(None, window, cx, |s| {
6237 s.select_anchor_ranges([last_edit_end..last_edit_end])
6238 });
6239
6240 self.update_visible_inline_completion(window, cx);
6241 if self.active_inline_completion.is_none() {
6242 self.refresh_inline_completion(true, true, window, cx);
6243 }
6244
6245 cx.notify();
6246 }
6247 }
6248
6249 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6250 }
6251
6252 pub fn accept_partial_inline_completion(
6253 &mut self,
6254 _: &AcceptPartialEditPrediction,
6255 window: &mut Window,
6256 cx: &mut Context<Self>,
6257 ) {
6258 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6259 return;
6260 };
6261 if self.selections.count() != 1 {
6262 return;
6263 }
6264
6265 self.report_inline_completion_event(
6266 active_inline_completion.completion_id.clone(),
6267 true,
6268 cx,
6269 );
6270
6271 match &active_inline_completion.completion {
6272 InlineCompletion::Move { target, .. } => {
6273 let target = *target;
6274 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6275 selections.select_anchor_ranges([target..target]);
6276 });
6277 }
6278 InlineCompletion::Edit { edits, .. } => {
6279 // Find an insertion that starts at the cursor position.
6280 let snapshot = self.buffer.read(cx).snapshot(cx);
6281 let cursor_offset = self.selections.newest::<usize>(cx).head();
6282 let insertion = edits.iter().find_map(|(range, text)| {
6283 let range = range.to_offset(&snapshot);
6284 if range.is_empty() && range.start == cursor_offset {
6285 Some(text)
6286 } else {
6287 None
6288 }
6289 });
6290
6291 if let Some(text) = insertion {
6292 let mut partial_completion = text
6293 .chars()
6294 .by_ref()
6295 .take_while(|c| c.is_alphabetic())
6296 .collect::<String>();
6297 if partial_completion.is_empty() {
6298 partial_completion = text
6299 .chars()
6300 .by_ref()
6301 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6302 .collect::<String>();
6303 }
6304
6305 cx.emit(EditorEvent::InputHandled {
6306 utf16_range_to_replace: None,
6307 text: partial_completion.clone().into(),
6308 });
6309
6310 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6311
6312 self.refresh_inline_completion(true, true, window, cx);
6313 cx.notify();
6314 } else {
6315 self.accept_edit_prediction(&Default::default(), window, cx);
6316 }
6317 }
6318 }
6319 }
6320
6321 fn discard_inline_completion(
6322 &mut self,
6323 should_report_inline_completion_event: bool,
6324 cx: &mut Context<Self>,
6325 ) -> bool {
6326 if should_report_inline_completion_event {
6327 let completion_id = self
6328 .active_inline_completion
6329 .as_ref()
6330 .and_then(|active_completion| active_completion.completion_id.clone());
6331
6332 self.report_inline_completion_event(completion_id, false, cx);
6333 }
6334
6335 if let Some(provider) = self.edit_prediction_provider() {
6336 provider.discard(cx);
6337 }
6338
6339 self.take_active_inline_completion(cx)
6340 }
6341
6342 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6343 let Some(provider) = self.edit_prediction_provider() else {
6344 return;
6345 };
6346
6347 let Some((_, buffer, _)) = self
6348 .buffer
6349 .read(cx)
6350 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6351 else {
6352 return;
6353 };
6354
6355 let extension = buffer
6356 .read(cx)
6357 .file()
6358 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6359
6360 let event_type = match accepted {
6361 true => "Edit Prediction Accepted",
6362 false => "Edit Prediction Discarded",
6363 };
6364 telemetry::event!(
6365 event_type,
6366 provider = provider.name(),
6367 prediction_id = id,
6368 suggestion_accepted = accepted,
6369 file_extension = extension,
6370 );
6371 }
6372
6373 pub fn has_active_inline_completion(&self) -> bool {
6374 self.active_inline_completion.is_some()
6375 }
6376
6377 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6378 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6379 return false;
6380 };
6381
6382 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6383 self.clear_highlights::<InlineCompletionHighlight>(cx);
6384 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6385 true
6386 }
6387
6388 /// Returns true when we're displaying the edit prediction popover below the cursor
6389 /// like we are not previewing and the LSP autocomplete menu is visible
6390 /// or we are in `when_holding_modifier` mode.
6391 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6392 if self.edit_prediction_preview_is_active()
6393 || !self.show_edit_predictions_in_menu()
6394 || !self.edit_predictions_enabled()
6395 {
6396 return false;
6397 }
6398
6399 if self.has_visible_completions_menu() {
6400 return true;
6401 }
6402
6403 has_completion && self.edit_prediction_requires_modifier()
6404 }
6405
6406 fn handle_modifiers_changed(
6407 &mut self,
6408 modifiers: Modifiers,
6409 position_map: &PositionMap,
6410 window: &mut Window,
6411 cx: &mut Context<Self>,
6412 ) {
6413 if self.show_edit_predictions_in_menu() {
6414 self.update_edit_prediction_preview(&modifiers, window, cx);
6415 }
6416
6417 self.update_selection_mode(&modifiers, position_map, window, cx);
6418
6419 let mouse_position = window.mouse_position();
6420 if !position_map.text_hitbox.is_hovered(window) {
6421 return;
6422 }
6423
6424 self.update_hovered_link(
6425 position_map.point_for_position(mouse_position),
6426 &position_map.snapshot,
6427 modifiers,
6428 window,
6429 cx,
6430 )
6431 }
6432
6433 fn update_selection_mode(
6434 &mut self,
6435 modifiers: &Modifiers,
6436 position_map: &PositionMap,
6437 window: &mut Window,
6438 cx: &mut Context<Self>,
6439 ) {
6440 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6441 return;
6442 }
6443
6444 let mouse_position = window.mouse_position();
6445 let point_for_position = position_map.point_for_position(mouse_position);
6446 let position = point_for_position.previous_valid;
6447
6448 self.select(
6449 SelectPhase::BeginColumnar {
6450 position,
6451 reset: false,
6452 goal_column: point_for_position.exact_unclipped.column(),
6453 },
6454 window,
6455 cx,
6456 );
6457 }
6458
6459 fn update_edit_prediction_preview(
6460 &mut self,
6461 modifiers: &Modifiers,
6462 window: &mut Window,
6463 cx: &mut Context<Self>,
6464 ) {
6465 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6466 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6467 return;
6468 };
6469
6470 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6471 if matches!(
6472 self.edit_prediction_preview,
6473 EditPredictionPreview::Inactive { .. }
6474 ) {
6475 self.edit_prediction_preview = EditPredictionPreview::Active {
6476 previous_scroll_position: None,
6477 since: Instant::now(),
6478 };
6479
6480 self.update_visible_inline_completion(window, cx);
6481 cx.notify();
6482 }
6483 } else if let EditPredictionPreview::Active {
6484 previous_scroll_position,
6485 since,
6486 } = self.edit_prediction_preview
6487 {
6488 if let (Some(previous_scroll_position), Some(position_map)) =
6489 (previous_scroll_position, self.last_position_map.as_ref())
6490 {
6491 self.set_scroll_position(
6492 previous_scroll_position
6493 .scroll_position(&position_map.snapshot.display_snapshot),
6494 window,
6495 cx,
6496 );
6497 }
6498
6499 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6500 released_too_fast: since.elapsed() < Duration::from_millis(200),
6501 };
6502 self.clear_row_highlights::<EditPredictionPreview>();
6503 self.update_visible_inline_completion(window, cx);
6504 cx.notify();
6505 }
6506 }
6507
6508 fn update_visible_inline_completion(
6509 &mut self,
6510 _window: &mut Window,
6511 cx: &mut Context<Self>,
6512 ) -> Option<()> {
6513 let selection = self.selections.newest_anchor();
6514 let cursor = selection.head();
6515 let multibuffer = self.buffer.read(cx).snapshot(cx);
6516 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6517 let excerpt_id = cursor.excerpt_id;
6518
6519 let show_in_menu = self.show_edit_predictions_in_menu();
6520 let completions_menu_has_precedence = !show_in_menu
6521 && (self.context_menu.borrow().is_some()
6522 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6523
6524 if completions_menu_has_precedence
6525 || !offset_selection.is_empty()
6526 || self
6527 .active_inline_completion
6528 .as_ref()
6529 .map_or(false, |completion| {
6530 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6531 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6532 !invalidation_range.contains(&offset_selection.head())
6533 })
6534 {
6535 self.discard_inline_completion(false, cx);
6536 return None;
6537 }
6538
6539 self.take_active_inline_completion(cx);
6540 let Some(provider) = self.edit_prediction_provider() else {
6541 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6542 return None;
6543 };
6544
6545 let (buffer, cursor_buffer_position) =
6546 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6547
6548 self.edit_prediction_settings =
6549 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6550
6551 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6552
6553 if self.edit_prediction_indent_conflict {
6554 let cursor_point = cursor.to_point(&multibuffer);
6555
6556 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6557
6558 if let Some((_, indent)) = indents.iter().next() {
6559 if indent.len == cursor_point.column {
6560 self.edit_prediction_indent_conflict = false;
6561 }
6562 }
6563 }
6564
6565 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6566 let edits = inline_completion
6567 .edits
6568 .into_iter()
6569 .flat_map(|(range, new_text)| {
6570 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6571 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6572 Some((start..end, new_text))
6573 })
6574 .collect::<Vec<_>>();
6575 if edits.is_empty() {
6576 return None;
6577 }
6578
6579 let first_edit_start = edits.first().unwrap().0.start;
6580 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6581 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6582
6583 let last_edit_end = edits.last().unwrap().0.end;
6584 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6585 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6586
6587 let cursor_row = cursor.to_point(&multibuffer).row;
6588
6589 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6590
6591 let mut inlay_ids = Vec::new();
6592 let invalidation_row_range;
6593 let move_invalidation_row_range = if cursor_row < edit_start_row {
6594 Some(cursor_row..edit_end_row)
6595 } else if cursor_row > edit_end_row {
6596 Some(edit_start_row..cursor_row)
6597 } else {
6598 None
6599 };
6600 let is_move =
6601 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6602 let completion = if is_move {
6603 invalidation_row_range =
6604 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6605 let target = first_edit_start;
6606 InlineCompletion::Move { target, snapshot }
6607 } else {
6608 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6609 && !self.inline_completions_hidden_for_vim_mode;
6610
6611 if show_completions_in_buffer {
6612 if edits
6613 .iter()
6614 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6615 {
6616 let mut inlays = Vec::new();
6617 for (range, new_text) in &edits {
6618 let inlay = Inlay::inline_completion(
6619 post_inc(&mut self.next_inlay_id),
6620 range.start,
6621 new_text.as_str(),
6622 );
6623 inlay_ids.push(inlay.id);
6624 inlays.push(inlay);
6625 }
6626
6627 self.splice_inlays(&[], inlays, cx);
6628 } else {
6629 let background_color = cx.theme().status().deleted_background;
6630 self.highlight_text::<InlineCompletionHighlight>(
6631 edits.iter().map(|(range, _)| range.clone()).collect(),
6632 HighlightStyle {
6633 background_color: Some(background_color),
6634 ..Default::default()
6635 },
6636 cx,
6637 );
6638 }
6639 }
6640
6641 invalidation_row_range = edit_start_row..edit_end_row;
6642
6643 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6644 if provider.show_tab_accept_marker() {
6645 EditDisplayMode::TabAccept
6646 } else {
6647 EditDisplayMode::Inline
6648 }
6649 } else {
6650 EditDisplayMode::DiffPopover
6651 };
6652
6653 InlineCompletion::Edit {
6654 edits,
6655 edit_preview: inline_completion.edit_preview,
6656 display_mode,
6657 snapshot,
6658 }
6659 };
6660
6661 let invalidation_range = multibuffer
6662 .anchor_before(Point::new(invalidation_row_range.start, 0))
6663 ..multibuffer.anchor_after(Point::new(
6664 invalidation_row_range.end,
6665 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6666 ));
6667
6668 self.stale_inline_completion_in_menu = None;
6669 self.active_inline_completion = Some(InlineCompletionState {
6670 inlay_ids,
6671 completion,
6672 completion_id: inline_completion.id,
6673 invalidation_range,
6674 });
6675
6676 cx.notify();
6677
6678 Some(())
6679 }
6680
6681 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6682 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6683 }
6684
6685 fn render_code_actions_indicator(
6686 &self,
6687 _style: &EditorStyle,
6688 row: DisplayRow,
6689 is_active: bool,
6690 breakpoint: Option<&(Anchor, Breakpoint)>,
6691 cx: &mut Context<Self>,
6692 ) -> Option<IconButton> {
6693 let color = Color::Muted;
6694 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6695 let show_tooltip = !self.context_menu_visible();
6696
6697 if self.available_code_actions.is_some() {
6698 Some(
6699 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6700 .shape(ui::IconButtonShape::Square)
6701 .icon_size(IconSize::XSmall)
6702 .icon_color(color)
6703 .toggle_state(is_active)
6704 .when(show_tooltip, |this| {
6705 this.tooltip({
6706 let focus_handle = self.focus_handle.clone();
6707 move |window, cx| {
6708 Tooltip::for_action_in(
6709 "Toggle Code Actions",
6710 &ToggleCodeActions {
6711 deployed_from_indicator: None,
6712 quick_launch: false,
6713 },
6714 &focus_handle,
6715 window,
6716 cx,
6717 )
6718 }
6719 })
6720 })
6721 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
6722 let quick_launch = e.down.button == MouseButton::Left;
6723 window.focus(&editor.focus_handle(cx));
6724 editor.toggle_code_actions(
6725 &ToggleCodeActions {
6726 deployed_from_indicator: Some(row),
6727 quick_launch,
6728 },
6729 window,
6730 cx,
6731 );
6732 }))
6733 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6734 editor.set_breakpoint_context_menu(
6735 row,
6736 position,
6737 event.down.position,
6738 window,
6739 cx,
6740 );
6741 })),
6742 )
6743 } else {
6744 None
6745 }
6746 }
6747
6748 fn clear_tasks(&mut self) {
6749 self.tasks.clear()
6750 }
6751
6752 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6753 if self.tasks.insert(key, value).is_some() {
6754 // This case should hopefully be rare, but just in case...
6755 log::error!(
6756 "multiple different run targets found on a single line, only the last target will be rendered"
6757 )
6758 }
6759 }
6760
6761 /// Get all display points of breakpoints that will be rendered within editor
6762 ///
6763 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6764 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6765 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6766 fn active_breakpoints(
6767 &self,
6768 range: Range<DisplayRow>,
6769 window: &mut Window,
6770 cx: &mut Context<Self>,
6771 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6772 let mut breakpoint_display_points = HashMap::default();
6773
6774 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6775 return breakpoint_display_points;
6776 };
6777
6778 let snapshot = self.snapshot(window, cx);
6779
6780 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6781 let Some(project) = self.project.as_ref() else {
6782 return breakpoint_display_points;
6783 };
6784
6785 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6786 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6787
6788 for (buffer_snapshot, range, excerpt_id) in
6789 multi_buffer_snapshot.range_to_buffer_ranges(range)
6790 {
6791 let Some(buffer) = project.read_with(cx, |this, cx| {
6792 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6793 }) else {
6794 continue;
6795 };
6796 let breakpoints = breakpoint_store.read(cx).breakpoints(
6797 &buffer,
6798 Some(
6799 buffer_snapshot.anchor_before(range.start)
6800 ..buffer_snapshot.anchor_after(range.end),
6801 ),
6802 buffer_snapshot,
6803 cx,
6804 );
6805 for (anchor, breakpoint) in breakpoints {
6806 let multi_buffer_anchor =
6807 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6808 let position = multi_buffer_anchor
6809 .to_point(&multi_buffer_snapshot)
6810 .to_display_point(&snapshot);
6811
6812 breakpoint_display_points
6813 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6814 }
6815 }
6816
6817 breakpoint_display_points
6818 }
6819
6820 fn breakpoint_context_menu(
6821 &self,
6822 anchor: Anchor,
6823 window: &mut Window,
6824 cx: &mut Context<Self>,
6825 ) -> Entity<ui::ContextMenu> {
6826 let weak_editor = cx.weak_entity();
6827 let focus_handle = self.focus_handle(cx);
6828
6829 let row = self
6830 .buffer
6831 .read(cx)
6832 .snapshot(cx)
6833 .summary_for_anchor::<Point>(&anchor)
6834 .row;
6835
6836 let breakpoint = self
6837 .breakpoint_at_row(row, window, cx)
6838 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6839
6840 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6841 "Edit Log Breakpoint"
6842 } else {
6843 "Set Log Breakpoint"
6844 };
6845
6846 let condition_breakpoint_msg = if breakpoint
6847 .as_ref()
6848 .is_some_and(|bp| bp.1.condition.is_some())
6849 {
6850 "Edit Condition Breakpoint"
6851 } else {
6852 "Set Condition Breakpoint"
6853 };
6854
6855 let hit_condition_breakpoint_msg = if breakpoint
6856 .as_ref()
6857 .is_some_and(|bp| bp.1.hit_condition.is_some())
6858 {
6859 "Edit Hit Condition Breakpoint"
6860 } else {
6861 "Set Hit Condition Breakpoint"
6862 };
6863
6864 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6865 "Unset Breakpoint"
6866 } else {
6867 "Set Breakpoint"
6868 };
6869
6870 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6871 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6872
6873 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6874 BreakpointState::Enabled => Some("Disable"),
6875 BreakpointState::Disabled => Some("Enable"),
6876 });
6877
6878 let (anchor, breakpoint) =
6879 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6880
6881 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6882 menu.on_blur_subscription(Subscription::new(|| {}))
6883 .context(focus_handle)
6884 .when(run_to_cursor, |this| {
6885 let weak_editor = weak_editor.clone();
6886 this.entry("Run to cursor", None, move |window, cx| {
6887 weak_editor
6888 .update(cx, |editor, cx| {
6889 editor.change_selections(None, window, cx, |s| {
6890 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6891 });
6892 })
6893 .ok();
6894
6895 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6896 })
6897 .separator()
6898 })
6899 .when_some(toggle_state_msg, |this, msg| {
6900 this.entry(msg, None, {
6901 let weak_editor = weak_editor.clone();
6902 let breakpoint = breakpoint.clone();
6903 move |_window, cx| {
6904 weak_editor
6905 .update(cx, |this, cx| {
6906 this.edit_breakpoint_at_anchor(
6907 anchor,
6908 breakpoint.as_ref().clone(),
6909 BreakpointEditAction::InvertState,
6910 cx,
6911 );
6912 })
6913 .log_err();
6914 }
6915 })
6916 })
6917 .entry(set_breakpoint_msg, None, {
6918 let weak_editor = weak_editor.clone();
6919 let breakpoint = breakpoint.clone();
6920 move |_window, cx| {
6921 weak_editor
6922 .update(cx, |this, cx| {
6923 this.edit_breakpoint_at_anchor(
6924 anchor,
6925 breakpoint.as_ref().clone(),
6926 BreakpointEditAction::Toggle,
6927 cx,
6928 );
6929 })
6930 .log_err();
6931 }
6932 })
6933 .entry(log_breakpoint_msg, None, {
6934 let breakpoint = breakpoint.clone();
6935 let weak_editor = weak_editor.clone();
6936 move |window, cx| {
6937 weak_editor
6938 .update(cx, |this, cx| {
6939 this.add_edit_breakpoint_block(
6940 anchor,
6941 breakpoint.as_ref(),
6942 BreakpointPromptEditAction::Log,
6943 window,
6944 cx,
6945 );
6946 })
6947 .log_err();
6948 }
6949 })
6950 .entry(condition_breakpoint_msg, None, {
6951 let breakpoint = breakpoint.clone();
6952 let weak_editor = weak_editor.clone();
6953 move |window, cx| {
6954 weak_editor
6955 .update(cx, |this, cx| {
6956 this.add_edit_breakpoint_block(
6957 anchor,
6958 breakpoint.as_ref(),
6959 BreakpointPromptEditAction::Condition,
6960 window,
6961 cx,
6962 );
6963 })
6964 .log_err();
6965 }
6966 })
6967 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6968 weak_editor
6969 .update(cx, |this, cx| {
6970 this.add_edit_breakpoint_block(
6971 anchor,
6972 breakpoint.as_ref(),
6973 BreakpointPromptEditAction::HitCondition,
6974 window,
6975 cx,
6976 );
6977 })
6978 .log_err();
6979 })
6980 })
6981 }
6982
6983 fn render_breakpoint(
6984 &self,
6985 position: Anchor,
6986 row: DisplayRow,
6987 breakpoint: &Breakpoint,
6988 cx: &mut Context<Self>,
6989 ) -> IconButton {
6990 // Is it a breakpoint that shows up when hovering over gutter?
6991 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
6992 (false, false),
6993 |PhantomBreakpointIndicator {
6994 is_active,
6995 display_row,
6996 collides_with_existing_breakpoint,
6997 }| {
6998 (
6999 is_active && display_row == row,
7000 collides_with_existing_breakpoint,
7001 )
7002 },
7003 );
7004
7005 let (color, icon) = {
7006 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7007 (false, false) => ui::IconName::DebugBreakpoint,
7008 (true, false) => ui::IconName::DebugLogBreakpoint,
7009 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7010 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7011 };
7012
7013 let color = if is_phantom {
7014 Color::Hint
7015 } else {
7016 Color::Debugger
7017 };
7018
7019 (color, icon)
7020 };
7021
7022 let breakpoint = Arc::from(breakpoint.clone());
7023
7024 let alt_as_text = gpui::Keystroke {
7025 modifiers: Modifiers::secondary_key(),
7026 ..Default::default()
7027 };
7028 let primary_action_text = if breakpoint.is_disabled() {
7029 "enable"
7030 } else if is_phantom && !collides_with_existing {
7031 "set"
7032 } else {
7033 "unset"
7034 };
7035 let mut primary_text = format!("Click to {primary_action_text}");
7036 if collides_with_existing && !breakpoint.is_disabled() {
7037 use std::fmt::Write;
7038 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7039 }
7040 let primary_text = SharedString::from(primary_text);
7041 let focus_handle = self.focus_handle.clone();
7042 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7043 .icon_size(IconSize::XSmall)
7044 .size(ui::ButtonSize::None)
7045 .icon_color(color)
7046 .style(ButtonStyle::Transparent)
7047 .on_click(cx.listener({
7048 let breakpoint = breakpoint.clone();
7049
7050 move |editor, event: &ClickEvent, window, cx| {
7051 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7052 BreakpointEditAction::InvertState
7053 } else {
7054 BreakpointEditAction::Toggle
7055 };
7056
7057 window.focus(&editor.focus_handle(cx));
7058 editor.edit_breakpoint_at_anchor(
7059 position,
7060 breakpoint.as_ref().clone(),
7061 edit_action,
7062 cx,
7063 );
7064 }
7065 }))
7066 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7067 editor.set_breakpoint_context_menu(
7068 row,
7069 Some(position),
7070 event.down.position,
7071 window,
7072 cx,
7073 );
7074 }))
7075 .tooltip(move |window, cx| {
7076 Tooltip::with_meta_in(
7077 primary_text.clone(),
7078 None,
7079 "Right-click for more options",
7080 &focus_handle,
7081 window,
7082 cx,
7083 )
7084 })
7085 }
7086
7087 fn build_tasks_context(
7088 project: &Entity<Project>,
7089 buffer: &Entity<Buffer>,
7090 buffer_row: u32,
7091 tasks: &Arc<RunnableTasks>,
7092 cx: &mut Context<Self>,
7093 ) -> Task<Option<task::TaskContext>> {
7094 let position = Point::new(buffer_row, tasks.column);
7095 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7096 let location = Location {
7097 buffer: buffer.clone(),
7098 range: range_start..range_start,
7099 };
7100 // Fill in the environmental variables from the tree-sitter captures
7101 let mut captured_task_variables = TaskVariables::default();
7102 for (capture_name, value) in tasks.extra_variables.clone() {
7103 captured_task_variables.insert(
7104 task::VariableName::Custom(capture_name.into()),
7105 value.clone(),
7106 );
7107 }
7108 project.update(cx, |project, cx| {
7109 project.task_store().update(cx, |task_store, cx| {
7110 task_store.task_context_for_location(captured_task_variables, location, cx)
7111 })
7112 })
7113 }
7114
7115 pub fn spawn_nearest_task(
7116 &mut self,
7117 action: &SpawnNearestTask,
7118 window: &mut Window,
7119 cx: &mut Context<Self>,
7120 ) {
7121 let Some((workspace, _)) = self.workspace.clone() else {
7122 return;
7123 };
7124 let Some(project) = self.project.clone() else {
7125 return;
7126 };
7127
7128 // Try to find a closest, enclosing node using tree-sitter that has a
7129 // task
7130 let Some((buffer, buffer_row, tasks)) = self
7131 .find_enclosing_node_task(cx)
7132 // Or find the task that's closest in row-distance.
7133 .or_else(|| self.find_closest_task(cx))
7134 else {
7135 return;
7136 };
7137
7138 let reveal_strategy = action.reveal;
7139 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7140 cx.spawn_in(window, async move |_, cx| {
7141 let context = task_context.await?;
7142 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7143
7144 let resolved = &mut resolved_task.resolved;
7145 resolved.reveal = reveal_strategy;
7146
7147 workspace
7148 .update_in(cx, |workspace, window, cx| {
7149 workspace.schedule_resolved_task(
7150 task_source_kind,
7151 resolved_task,
7152 false,
7153 window,
7154 cx,
7155 );
7156 })
7157 .ok()
7158 })
7159 .detach();
7160 }
7161
7162 fn find_closest_task(
7163 &mut self,
7164 cx: &mut Context<Self>,
7165 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7166 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7167
7168 let ((buffer_id, row), tasks) = self
7169 .tasks
7170 .iter()
7171 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7172
7173 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7174 let tasks = Arc::new(tasks.to_owned());
7175 Some((buffer, *row, tasks))
7176 }
7177
7178 fn find_enclosing_node_task(
7179 &mut self,
7180 cx: &mut Context<Self>,
7181 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7182 let snapshot = self.buffer.read(cx).snapshot(cx);
7183 let offset = self.selections.newest::<usize>(cx).head();
7184 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7185 let buffer_id = excerpt.buffer().remote_id();
7186
7187 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7188 let mut cursor = layer.node().walk();
7189
7190 while cursor.goto_first_child_for_byte(offset).is_some() {
7191 if cursor.node().end_byte() == offset {
7192 cursor.goto_next_sibling();
7193 }
7194 }
7195
7196 // Ascend to the smallest ancestor that contains the range and has a task.
7197 loop {
7198 let node = cursor.node();
7199 let node_range = node.byte_range();
7200 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7201
7202 // Check if this node contains our offset
7203 if node_range.start <= offset && node_range.end >= offset {
7204 // If it contains offset, check for task
7205 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7206 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7207 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7208 }
7209 }
7210
7211 if !cursor.goto_parent() {
7212 break;
7213 }
7214 }
7215 None
7216 }
7217
7218 fn render_run_indicator(
7219 &self,
7220 _style: &EditorStyle,
7221 is_active: bool,
7222 row: DisplayRow,
7223 breakpoint: Option<(Anchor, Breakpoint)>,
7224 cx: &mut Context<Self>,
7225 ) -> IconButton {
7226 let color = Color::Muted;
7227 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7228
7229 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7230 .shape(ui::IconButtonShape::Square)
7231 .icon_size(IconSize::XSmall)
7232 .icon_color(color)
7233 .toggle_state(is_active)
7234 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7235 let quick_launch = e.down.button == MouseButton::Left;
7236 window.focus(&editor.focus_handle(cx));
7237 editor.toggle_code_actions(
7238 &ToggleCodeActions {
7239 deployed_from_indicator: Some(row),
7240 quick_launch,
7241 },
7242 window,
7243 cx,
7244 );
7245 }))
7246 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7247 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7248 }))
7249 }
7250
7251 pub fn context_menu_visible(&self) -> bool {
7252 !self.edit_prediction_preview_is_active()
7253 && self
7254 .context_menu
7255 .borrow()
7256 .as_ref()
7257 .map_or(false, |menu| menu.visible())
7258 }
7259
7260 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7261 self.context_menu
7262 .borrow()
7263 .as_ref()
7264 .map(|menu| menu.origin())
7265 }
7266
7267 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7268 self.context_menu_options = Some(options);
7269 }
7270
7271 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7272 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7273
7274 fn render_edit_prediction_popover(
7275 &mut self,
7276 text_bounds: &Bounds<Pixels>,
7277 content_origin: gpui::Point<Pixels>,
7278 editor_snapshot: &EditorSnapshot,
7279 visible_row_range: Range<DisplayRow>,
7280 scroll_top: f32,
7281 scroll_bottom: f32,
7282 line_layouts: &[LineWithInvisibles],
7283 line_height: Pixels,
7284 scroll_pixel_position: gpui::Point<Pixels>,
7285 newest_selection_head: Option<DisplayPoint>,
7286 editor_width: Pixels,
7287 style: &EditorStyle,
7288 window: &mut Window,
7289 cx: &mut App,
7290 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7291 let active_inline_completion = self.active_inline_completion.as_ref()?;
7292
7293 if self.edit_prediction_visible_in_cursor_popover(true) {
7294 return None;
7295 }
7296
7297 match &active_inline_completion.completion {
7298 InlineCompletion::Move { target, .. } => {
7299 let target_display_point = target.to_display_point(editor_snapshot);
7300
7301 if self.edit_prediction_requires_modifier() {
7302 if !self.edit_prediction_preview_is_active() {
7303 return None;
7304 }
7305
7306 self.render_edit_prediction_modifier_jump_popover(
7307 text_bounds,
7308 content_origin,
7309 visible_row_range,
7310 line_layouts,
7311 line_height,
7312 scroll_pixel_position,
7313 newest_selection_head,
7314 target_display_point,
7315 window,
7316 cx,
7317 )
7318 } else {
7319 self.render_edit_prediction_eager_jump_popover(
7320 text_bounds,
7321 content_origin,
7322 editor_snapshot,
7323 visible_row_range,
7324 scroll_top,
7325 scroll_bottom,
7326 line_height,
7327 scroll_pixel_position,
7328 target_display_point,
7329 editor_width,
7330 window,
7331 cx,
7332 )
7333 }
7334 }
7335 InlineCompletion::Edit {
7336 display_mode: EditDisplayMode::Inline,
7337 ..
7338 } => None,
7339 InlineCompletion::Edit {
7340 display_mode: EditDisplayMode::TabAccept,
7341 edits,
7342 ..
7343 } => {
7344 let range = &edits.first()?.0;
7345 let target_display_point = range.end.to_display_point(editor_snapshot);
7346
7347 self.render_edit_prediction_end_of_line_popover(
7348 "Accept",
7349 editor_snapshot,
7350 visible_row_range,
7351 target_display_point,
7352 line_height,
7353 scroll_pixel_position,
7354 content_origin,
7355 editor_width,
7356 window,
7357 cx,
7358 )
7359 }
7360 InlineCompletion::Edit {
7361 edits,
7362 edit_preview,
7363 display_mode: EditDisplayMode::DiffPopover,
7364 snapshot,
7365 } => self.render_edit_prediction_diff_popover(
7366 text_bounds,
7367 content_origin,
7368 editor_snapshot,
7369 visible_row_range,
7370 line_layouts,
7371 line_height,
7372 scroll_pixel_position,
7373 newest_selection_head,
7374 editor_width,
7375 style,
7376 edits,
7377 edit_preview,
7378 snapshot,
7379 window,
7380 cx,
7381 ),
7382 }
7383 }
7384
7385 fn render_edit_prediction_modifier_jump_popover(
7386 &mut self,
7387 text_bounds: &Bounds<Pixels>,
7388 content_origin: gpui::Point<Pixels>,
7389 visible_row_range: Range<DisplayRow>,
7390 line_layouts: &[LineWithInvisibles],
7391 line_height: Pixels,
7392 scroll_pixel_position: gpui::Point<Pixels>,
7393 newest_selection_head: Option<DisplayPoint>,
7394 target_display_point: DisplayPoint,
7395 window: &mut Window,
7396 cx: &mut App,
7397 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7398 let scrolled_content_origin =
7399 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7400
7401 const SCROLL_PADDING_Y: Pixels = px(12.);
7402
7403 if target_display_point.row() < visible_row_range.start {
7404 return self.render_edit_prediction_scroll_popover(
7405 |_| SCROLL_PADDING_Y,
7406 IconName::ArrowUp,
7407 visible_row_range,
7408 line_layouts,
7409 newest_selection_head,
7410 scrolled_content_origin,
7411 window,
7412 cx,
7413 );
7414 } else if target_display_point.row() >= visible_row_range.end {
7415 return self.render_edit_prediction_scroll_popover(
7416 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7417 IconName::ArrowDown,
7418 visible_row_range,
7419 line_layouts,
7420 newest_selection_head,
7421 scrolled_content_origin,
7422 window,
7423 cx,
7424 );
7425 }
7426
7427 const POLE_WIDTH: Pixels = px(2.);
7428
7429 let line_layout =
7430 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7431 let target_column = target_display_point.column() as usize;
7432
7433 let target_x = line_layout.x_for_index(target_column);
7434 let target_y =
7435 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7436
7437 let flag_on_right = target_x < text_bounds.size.width / 2.;
7438
7439 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7440 border_color.l += 0.001;
7441
7442 let mut element = v_flex()
7443 .items_end()
7444 .when(flag_on_right, |el| el.items_start())
7445 .child(if flag_on_right {
7446 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7447 .rounded_bl(px(0.))
7448 .rounded_tl(px(0.))
7449 .border_l_2()
7450 .border_color(border_color)
7451 } else {
7452 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7453 .rounded_br(px(0.))
7454 .rounded_tr(px(0.))
7455 .border_r_2()
7456 .border_color(border_color)
7457 })
7458 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7459 .into_any();
7460
7461 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7462
7463 let mut origin = scrolled_content_origin + point(target_x, target_y)
7464 - point(
7465 if flag_on_right {
7466 POLE_WIDTH
7467 } else {
7468 size.width - POLE_WIDTH
7469 },
7470 size.height - line_height,
7471 );
7472
7473 origin.x = origin.x.max(content_origin.x);
7474
7475 element.prepaint_at(origin, window, cx);
7476
7477 Some((element, origin))
7478 }
7479
7480 fn render_edit_prediction_scroll_popover(
7481 &mut self,
7482 to_y: impl Fn(Size<Pixels>) -> Pixels,
7483 scroll_icon: IconName,
7484 visible_row_range: Range<DisplayRow>,
7485 line_layouts: &[LineWithInvisibles],
7486 newest_selection_head: Option<DisplayPoint>,
7487 scrolled_content_origin: gpui::Point<Pixels>,
7488 window: &mut Window,
7489 cx: &mut App,
7490 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7491 let mut element = self
7492 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7493 .into_any();
7494
7495 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7496
7497 let cursor = newest_selection_head?;
7498 let cursor_row_layout =
7499 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7500 let cursor_column = cursor.column() as usize;
7501
7502 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7503
7504 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7505
7506 element.prepaint_at(origin, window, cx);
7507 Some((element, origin))
7508 }
7509
7510 fn render_edit_prediction_eager_jump_popover(
7511 &mut self,
7512 text_bounds: &Bounds<Pixels>,
7513 content_origin: gpui::Point<Pixels>,
7514 editor_snapshot: &EditorSnapshot,
7515 visible_row_range: Range<DisplayRow>,
7516 scroll_top: f32,
7517 scroll_bottom: f32,
7518 line_height: Pixels,
7519 scroll_pixel_position: gpui::Point<Pixels>,
7520 target_display_point: DisplayPoint,
7521 editor_width: Pixels,
7522 window: &mut Window,
7523 cx: &mut App,
7524 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7525 if target_display_point.row().as_f32() < scroll_top {
7526 let mut element = self
7527 .render_edit_prediction_line_popover(
7528 "Jump to Edit",
7529 Some(IconName::ArrowUp),
7530 window,
7531 cx,
7532 )?
7533 .into_any();
7534
7535 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7536 let offset = point(
7537 (text_bounds.size.width - size.width) / 2.,
7538 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7539 );
7540
7541 let origin = text_bounds.origin + offset;
7542 element.prepaint_at(origin, window, cx);
7543 Some((element, origin))
7544 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7545 let mut element = self
7546 .render_edit_prediction_line_popover(
7547 "Jump to Edit",
7548 Some(IconName::ArrowDown),
7549 window,
7550 cx,
7551 )?
7552 .into_any();
7553
7554 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7555 let offset = point(
7556 (text_bounds.size.width - size.width) / 2.,
7557 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7558 );
7559
7560 let origin = text_bounds.origin + offset;
7561 element.prepaint_at(origin, window, cx);
7562 Some((element, origin))
7563 } else {
7564 self.render_edit_prediction_end_of_line_popover(
7565 "Jump to Edit",
7566 editor_snapshot,
7567 visible_row_range,
7568 target_display_point,
7569 line_height,
7570 scroll_pixel_position,
7571 content_origin,
7572 editor_width,
7573 window,
7574 cx,
7575 )
7576 }
7577 }
7578
7579 fn render_edit_prediction_end_of_line_popover(
7580 self: &mut Editor,
7581 label: &'static str,
7582 editor_snapshot: &EditorSnapshot,
7583 visible_row_range: Range<DisplayRow>,
7584 target_display_point: DisplayPoint,
7585 line_height: Pixels,
7586 scroll_pixel_position: gpui::Point<Pixels>,
7587 content_origin: gpui::Point<Pixels>,
7588 editor_width: Pixels,
7589 window: &mut Window,
7590 cx: &mut App,
7591 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7592 let target_line_end = DisplayPoint::new(
7593 target_display_point.row(),
7594 editor_snapshot.line_len(target_display_point.row()),
7595 );
7596
7597 let mut element = self
7598 .render_edit_prediction_line_popover(label, None, window, cx)?
7599 .into_any();
7600
7601 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7602
7603 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7604
7605 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7606 let mut origin = start_point
7607 + line_origin
7608 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7609 origin.x = origin.x.max(content_origin.x);
7610
7611 let max_x = content_origin.x + editor_width - size.width;
7612
7613 if origin.x > max_x {
7614 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7615
7616 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7617 origin.y += offset;
7618 IconName::ArrowUp
7619 } else {
7620 origin.y -= offset;
7621 IconName::ArrowDown
7622 };
7623
7624 element = self
7625 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7626 .into_any();
7627
7628 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7629
7630 origin.x = content_origin.x + editor_width - size.width - px(2.);
7631 }
7632
7633 element.prepaint_at(origin, window, cx);
7634 Some((element, origin))
7635 }
7636
7637 fn render_edit_prediction_diff_popover(
7638 self: &Editor,
7639 text_bounds: &Bounds<Pixels>,
7640 content_origin: gpui::Point<Pixels>,
7641 editor_snapshot: &EditorSnapshot,
7642 visible_row_range: Range<DisplayRow>,
7643 line_layouts: &[LineWithInvisibles],
7644 line_height: Pixels,
7645 scroll_pixel_position: gpui::Point<Pixels>,
7646 newest_selection_head: Option<DisplayPoint>,
7647 editor_width: Pixels,
7648 style: &EditorStyle,
7649 edits: &Vec<(Range<Anchor>, String)>,
7650 edit_preview: &Option<language::EditPreview>,
7651 snapshot: &language::BufferSnapshot,
7652 window: &mut Window,
7653 cx: &mut App,
7654 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7655 let edit_start = edits
7656 .first()
7657 .unwrap()
7658 .0
7659 .start
7660 .to_display_point(editor_snapshot);
7661 let edit_end = edits
7662 .last()
7663 .unwrap()
7664 .0
7665 .end
7666 .to_display_point(editor_snapshot);
7667
7668 let is_visible = visible_row_range.contains(&edit_start.row())
7669 || visible_row_range.contains(&edit_end.row());
7670 if !is_visible {
7671 return None;
7672 }
7673
7674 let highlighted_edits =
7675 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7676
7677 let styled_text = highlighted_edits.to_styled_text(&style.text);
7678 let line_count = highlighted_edits.text.lines().count();
7679
7680 const BORDER_WIDTH: Pixels = px(1.);
7681
7682 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7683 let has_keybind = keybind.is_some();
7684
7685 let mut element = h_flex()
7686 .items_start()
7687 .child(
7688 h_flex()
7689 .bg(cx.theme().colors().editor_background)
7690 .border(BORDER_WIDTH)
7691 .shadow_sm()
7692 .border_color(cx.theme().colors().border)
7693 .rounded_l_lg()
7694 .when(line_count > 1, |el| el.rounded_br_lg())
7695 .pr_1()
7696 .child(styled_text),
7697 )
7698 .child(
7699 h_flex()
7700 .h(line_height + BORDER_WIDTH * 2.)
7701 .px_1p5()
7702 .gap_1()
7703 // Workaround: For some reason, there's a gap if we don't do this
7704 .ml(-BORDER_WIDTH)
7705 .shadow(smallvec![gpui::BoxShadow {
7706 color: gpui::black().opacity(0.05),
7707 offset: point(px(1.), px(1.)),
7708 blur_radius: px(2.),
7709 spread_radius: px(0.),
7710 }])
7711 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7712 .border(BORDER_WIDTH)
7713 .border_color(cx.theme().colors().border)
7714 .rounded_r_lg()
7715 .id("edit_prediction_diff_popover_keybind")
7716 .when(!has_keybind, |el| {
7717 let status_colors = cx.theme().status();
7718
7719 el.bg(status_colors.error_background)
7720 .border_color(status_colors.error.opacity(0.6))
7721 .child(Icon::new(IconName::Info).color(Color::Error))
7722 .cursor_default()
7723 .hoverable_tooltip(move |_window, cx| {
7724 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7725 })
7726 })
7727 .children(keybind),
7728 )
7729 .into_any();
7730
7731 let longest_row =
7732 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7733 let longest_line_width = if visible_row_range.contains(&longest_row) {
7734 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7735 } else {
7736 layout_line(
7737 longest_row,
7738 editor_snapshot,
7739 style,
7740 editor_width,
7741 |_| false,
7742 window,
7743 cx,
7744 )
7745 .width
7746 };
7747
7748 let viewport_bounds =
7749 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7750 right: -EditorElement::SCROLLBAR_WIDTH,
7751 ..Default::default()
7752 });
7753
7754 let x_after_longest =
7755 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7756 - scroll_pixel_position.x;
7757
7758 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7759
7760 // Fully visible if it can be displayed within the window (allow overlapping other
7761 // panes). However, this is only allowed if the popover starts within text_bounds.
7762 let can_position_to_the_right = x_after_longest < text_bounds.right()
7763 && x_after_longest + element_bounds.width < viewport_bounds.right();
7764
7765 let mut origin = if can_position_to_the_right {
7766 point(
7767 x_after_longest,
7768 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7769 - scroll_pixel_position.y,
7770 )
7771 } else {
7772 let cursor_row = newest_selection_head.map(|head| head.row());
7773 let above_edit = edit_start
7774 .row()
7775 .0
7776 .checked_sub(line_count as u32)
7777 .map(DisplayRow);
7778 let below_edit = Some(edit_end.row() + 1);
7779 let above_cursor =
7780 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7781 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7782
7783 // Place the edit popover adjacent to the edit if there is a location
7784 // available that is onscreen and does not obscure the cursor. Otherwise,
7785 // place it adjacent to the cursor.
7786 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7787 .into_iter()
7788 .flatten()
7789 .find(|&start_row| {
7790 let end_row = start_row + line_count as u32;
7791 visible_row_range.contains(&start_row)
7792 && visible_row_range.contains(&end_row)
7793 && cursor_row.map_or(true, |cursor_row| {
7794 !((start_row..end_row).contains(&cursor_row))
7795 })
7796 })?;
7797
7798 content_origin
7799 + point(
7800 -scroll_pixel_position.x,
7801 row_target.as_f32() * line_height - scroll_pixel_position.y,
7802 )
7803 };
7804
7805 origin.x -= BORDER_WIDTH;
7806
7807 window.defer_draw(element, origin, 1);
7808
7809 // Do not return an element, since it will already be drawn due to defer_draw.
7810 None
7811 }
7812
7813 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7814 px(30.)
7815 }
7816
7817 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7818 if self.read_only(cx) {
7819 cx.theme().players().read_only()
7820 } else {
7821 self.style.as_ref().unwrap().local_player
7822 }
7823 }
7824
7825 fn render_edit_prediction_accept_keybind(
7826 &self,
7827 window: &mut Window,
7828 cx: &App,
7829 ) -> Option<AnyElement> {
7830 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7831 let accept_keystroke = accept_binding.keystroke()?;
7832
7833 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7834
7835 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7836 Color::Accent
7837 } else {
7838 Color::Muted
7839 };
7840
7841 h_flex()
7842 .px_0p5()
7843 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7844 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7845 .text_size(TextSize::XSmall.rems(cx))
7846 .child(h_flex().children(ui::render_modifiers(
7847 &accept_keystroke.modifiers,
7848 PlatformStyle::platform(),
7849 Some(modifiers_color),
7850 Some(IconSize::XSmall.rems().into()),
7851 true,
7852 )))
7853 .when(is_platform_style_mac, |parent| {
7854 parent.child(accept_keystroke.key.clone())
7855 })
7856 .when(!is_platform_style_mac, |parent| {
7857 parent.child(
7858 Key::new(
7859 util::capitalize(&accept_keystroke.key),
7860 Some(Color::Default),
7861 )
7862 .size(Some(IconSize::XSmall.rems().into())),
7863 )
7864 })
7865 .into_any()
7866 .into()
7867 }
7868
7869 fn render_edit_prediction_line_popover(
7870 &self,
7871 label: impl Into<SharedString>,
7872 icon: Option<IconName>,
7873 window: &mut Window,
7874 cx: &App,
7875 ) -> Option<Stateful<Div>> {
7876 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7877
7878 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7879 let has_keybind = keybind.is_some();
7880
7881 let result = h_flex()
7882 .id("ep-line-popover")
7883 .py_0p5()
7884 .pl_1()
7885 .pr(padding_right)
7886 .gap_1()
7887 .rounded_md()
7888 .border_1()
7889 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7890 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7891 .shadow_sm()
7892 .when(!has_keybind, |el| {
7893 let status_colors = cx.theme().status();
7894
7895 el.bg(status_colors.error_background)
7896 .border_color(status_colors.error.opacity(0.6))
7897 .pl_2()
7898 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7899 .cursor_default()
7900 .hoverable_tooltip(move |_window, cx| {
7901 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7902 })
7903 })
7904 .children(keybind)
7905 .child(
7906 Label::new(label)
7907 .size(LabelSize::Small)
7908 .when(!has_keybind, |el| {
7909 el.color(cx.theme().status().error.into()).strikethrough()
7910 }),
7911 )
7912 .when(!has_keybind, |el| {
7913 el.child(
7914 h_flex().ml_1().child(
7915 Icon::new(IconName::Info)
7916 .size(IconSize::Small)
7917 .color(cx.theme().status().error.into()),
7918 ),
7919 )
7920 })
7921 .when_some(icon, |element, icon| {
7922 element.child(
7923 div()
7924 .mt(px(1.5))
7925 .child(Icon::new(icon).size(IconSize::Small)),
7926 )
7927 });
7928
7929 Some(result)
7930 }
7931
7932 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7933 let accent_color = cx.theme().colors().text_accent;
7934 let editor_bg_color = cx.theme().colors().editor_background;
7935 editor_bg_color.blend(accent_color.opacity(0.1))
7936 }
7937
7938 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7939 let accent_color = cx.theme().colors().text_accent;
7940 let editor_bg_color = cx.theme().colors().editor_background;
7941 editor_bg_color.blend(accent_color.opacity(0.6))
7942 }
7943
7944 fn render_edit_prediction_cursor_popover(
7945 &self,
7946 min_width: Pixels,
7947 max_width: Pixels,
7948 cursor_point: Point,
7949 style: &EditorStyle,
7950 accept_keystroke: Option<&gpui::Keystroke>,
7951 _window: &Window,
7952 cx: &mut Context<Editor>,
7953 ) -> Option<AnyElement> {
7954 let provider = self.edit_prediction_provider.as_ref()?;
7955
7956 if provider.provider.needs_terms_acceptance(cx) {
7957 return Some(
7958 h_flex()
7959 .min_w(min_width)
7960 .flex_1()
7961 .px_2()
7962 .py_1()
7963 .gap_3()
7964 .elevation_2(cx)
7965 .hover(|style| style.bg(cx.theme().colors().element_hover))
7966 .id("accept-terms")
7967 .cursor_pointer()
7968 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7969 .on_click(cx.listener(|this, _event, window, cx| {
7970 cx.stop_propagation();
7971 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7972 window.dispatch_action(
7973 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7974 cx,
7975 );
7976 }))
7977 .child(
7978 h_flex()
7979 .flex_1()
7980 .gap_2()
7981 .child(Icon::new(IconName::ZedPredict))
7982 .child(Label::new("Accept Terms of Service"))
7983 .child(div().w_full())
7984 .child(
7985 Icon::new(IconName::ArrowUpRight)
7986 .color(Color::Muted)
7987 .size(IconSize::Small),
7988 )
7989 .into_any_element(),
7990 )
7991 .into_any(),
7992 );
7993 }
7994
7995 let is_refreshing = provider.provider.is_refreshing(cx);
7996
7997 fn pending_completion_container() -> Div {
7998 h_flex()
7999 .h_full()
8000 .flex_1()
8001 .gap_2()
8002 .child(Icon::new(IconName::ZedPredict))
8003 }
8004
8005 let completion = match &self.active_inline_completion {
8006 Some(prediction) => {
8007 if !self.has_visible_completions_menu() {
8008 const RADIUS: Pixels = px(6.);
8009 const BORDER_WIDTH: Pixels = px(1.);
8010
8011 return Some(
8012 h_flex()
8013 .elevation_2(cx)
8014 .border(BORDER_WIDTH)
8015 .border_color(cx.theme().colors().border)
8016 .when(accept_keystroke.is_none(), |el| {
8017 el.border_color(cx.theme().status().error)
8018 })
8019 .rounded(RADIUS)
8020 .rounded_tl(px(0.))
8021 .overflow_hidden()
8022 .child(div().px_1p5().child(match &prediction.completion {
8023 InlineCompletion::Move { target, snapshot } => {
8024 use text::ToPoint as _;
8025 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8026 {
8027 Icon::new(IconName::ZedPredictDown)
8028 } else {
8029 Icon::new(IconName::ZedPredictUp)
8030 }
8031 }
8032 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8033 }))
8034 .child(
8035 h_flex()
8036 .gap_1()
8037 .py_1()
8038 .px_2()
8039 .rounded_r(RADIUS - BORDER_WIDTH)
8040 .border_l_1()
8041 .border_color(cx.theme().colors().border)
8042 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8043 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8044 el.child(
8045 Label::new("Hold")
8046 .size(LabelSize::Small)
8047 .when(accept_keystroke.is_none(), |el| {
8048 el.strikethrough()
8049 })
8050 .line_height_style(LineHeightStyle::UiLabel),
8051 )
8052 })
8053 .id("edit_prediction_cursor_popover_keybind")
8054 .when(accept_keystroke.is_none(), |el| {
8055 let status_colors = cx.theme().status();
8056
8057 el.bg(status_colors.error_background)
8058 .border_color(status_colors.error.opacity(0.6))
8059 .child(Icon::new(IconName::Info).color(Color::Error))
8060 .cursor_default()
8061 .hoverable_tooltip(move |_window, cx| {
8062 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8063 .into()
8064 })
8065 })
8066 .when_some(
8067 accept_keystroke.as_ref(),
8068 |el, accept_keystroke| {
8069 el.child(h_flex().children(ui::render_modifiers(
8070 &accept_keystroke.modifiers,
8071 PlatformStyle::platform(),
8072 Some(Color::Default),
8073 Some(IconSize::XSmall.rems().into()),
8074 false,
8075 )))
8076 },
8077 ),
8078 )
8079 .into_any(),
8080 );
8081 }
8082
8083 self.render_edit_prediction_cursor_popover_preview(
8084 prediction,
8085 cursor_point,
8086 style,
8087 cx,
8088 )?
8089 }
8090
8091 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8092 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8093 stale_completion,
8094 cursor_point,
8095 style,
8096 cx,
8097 )?,
8098
8099 None => {
8100 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8101 }
8102 },
8103
8104 None => pending_completion_container().child(Label::new("No Prediction")),
8105 };
8106
8107 let completion = if is_refreshing {
8108 completion
8109 .with_animation(
8110 "loading-completion",
8111 Animation::new(Duration::from_secs(2))
8112 .repeat()
8113 .with_easing(pulsating_between(0.4, 0.8)),
8114 |label, delta| label.opacity(delta),
8115 )
8116 .into_any_element()
8117 } else {
8118 completion.into_any_element()
8119 };
8120
8121 let has_completion = self.active_inline_completion.is_some();
8122
8123 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8124 Some(
8125 h_flex()
8126 .min_w(min_width)
8127 .max_w(max_width)
8128 .flex_1()
8129 .elevation_2(cx)
8130 .border_color(cx.theme().colors().border)
8131 .child(
8132 div()
8133 .flex_1()
8134 .py_1()
8135 .px_2()
8136 .overflow_hidden()
8137 .child(completion),
8138 )
8139 .when_some(accept_keystroke, |el, accept_keystroke| {
8140 if !accept_keystroke.modifiers.modified() {
8141 return el;
8142 }
8143
8144 el.child(
8145 h_flex()
8146 .h_full()
8147 .border_l_1()
8148 .rounded_r_lg()
8149 .border_color(cx.theme().colors().border)
8150 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8151 .gap_1()
8152 .py_1()
8153 .px_2()
8154 .child(
8155 h_flex()
8156 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8157 .when(is_platform_style_mac, |parent| parent.gap_1())
8158 .child(h_flex().children(ui::render_modifiers(
8159 &accept_keystroke.modifiers,
8160 PlatformStyle::platform(),
8161 Some(if !has_completion {
8162 Color::Muted
8163 } else {
8164 Color::Default
8165 }),
8166 None,
8167 false,
8168 ))),
8169 )
8170 .child(Label::new("Preview").into_any_element())
8171 .opacity(if has_completion { 1.0 } else { 0.4 }),
8172 )
8173 })
8174 .into_any(),
8175 )
8176 }
8177
8178 fn render_edit_prediction_cursor_popover_preview(
8179 &self,
8180 completion: &InlineCompletionState,
8181 cursor_point: Point,
8182 style: &EditorStyle,
8183 cx: &mut Context<Editor>,
8184 ) -> Option<Div> {
8185 use text::ToPoint as _;
8186
8187 fn render_relative_row_jump(
8188 prefix: impl Into<String>,
8189 current_row: u32,
8190 target_row: u32,
8191 ) -> Div {
8192 let (row_diff, arrow) = if target_row < current_row {
8193 (current_row - target_row, IconName::ArrowUp)
8194 } else {
8195 (target_row - current_row, IconName::ArrowDown)
8196 };
8197
8198 h_flex()
8199 .child(
8200 Label::new(format!("{}{}", prefix.into(), row_diff))
8201 .color(Color::Muted)
8202 .size(LabelSize::Small),
8203 )
8204 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8205 }
8206
8207 match &completion.completion {
8208 InlineCompletion::Move {
8209 target, snapshot, ..
8210 } => Some(
8211 h_flex()
8212 .px_2()
8213 .gap_2()
8214 .flex_1()
8215 .child(
8216 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8217 Icon::new(IconName::ZedPredictDown)
8218 } else {
8219 Icon::new(IconName::ZedPredictUp)
8220 },
8221 )
8222 .child(Label::new("Jump to Edit")),
8223 ),
8224
8225 InlineCompletion::Edit {
8226 edits,
8227 edit_preview,
8228 snapshot,
8229 display_mode: _,
8230 } => {
8231 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8232
8233 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8234 &snapshot,
8235 &edits,
8236 edit_preview.as_ref()?,
8237 true,
8238 cx,
8239 )
8240 .first_line_preview();
8241
8242 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8243 .with_default_highlights(&style.text, highlighted_edits.highlights);
8244
8245 let preview = h_flex()
8246 .gap_1()
8247 .min_w_16()
8248 .child(styled_text)
8249 .when(has_more_lines, |parent| parent.child("…"));
8250
8251 let left = if first_edit_row != cursor_point.row {
8252 render_relative_row_jump("", cursor_point.row, first_edit_row)
8253 .into_any_element()
8254 } else {
8255 Icon::new(IconName::ZedPredict).into_any_element()
8256 };
8257
8258 Some(
8259 h_flex()
8260 .h_full()
8261 .flex_1()
8262 .gap_2()
8263 .pr_1()
8264 .overflow_x_hidden()
8265 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8266 .child(left)
8267 .child(preview),
8268 )
8269 }
8270 }
8271 }
8272
8273 fn render_context_menu(
8274 &self,
8275 style: &EditorStyle,
8276 max_height_in_lines: u32,
8277 window: &mut Window,
8278 cx: &mut Context<Editor>,
8279 ) -> Option<AnyElement> {
8280 let menu = self.context_menu.borrow();
8281 let menu = menu.as_ref()?;
8282 if !menu.visible() {
8283 return None;
8284 };
8285 Some(menu.render(style, max_height_in_lines, window, cx))
8286 }
8287
8288 fn render_context_menu_aside(
8289 &mut self,
8290 max_size: Size<Pixels>,
8291 window: &mut Window,
8292 cx: &mut Context<Editor>,
8293 ) -> Option<AnyElement> {
8294 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8295 if menu.visible() {
8296 menu.render_aside(self, max_size, window, cx)
8297 } else {
8298 None
8299 }
8300 })
8301 }
8302
8303 fn hide_context_menu(
8304 &mut self,
8305 window: &mut Window,
8306 cx: &mut Context<Self>,
8307 ) -> Option<CodeContextMenu> {
8308 cx.notify();
8309 self.completion_tasks.clear();
8310 let context_menu = self.context_menu.borrow_mut().take();
8311 self.stale_inline_completion_in_menu.take();
8312 self.update_visible_inline_completion(window, cx);
8313 context_menu
8314 }
8315
8316 fn show_snippet_choices(
8317 &mut self,
8318 choices: &Vec<String>,
8319 selection: Range<Anchor>,
8320 cx: &mut Context<Self>,
8321 ) {
8322 if selection.start.buffer_id.is_none() {
8323 return;
8324 }
8325 let buffer_id = selection.start.buffer_id.unwrap();
8326 let buffer = self.buffer().read(cx).buffer(buffer_id);
8327 let id = post_inc(&mut self.next_completion_id);
8328 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8329
8330 if let Some(buffer) = buffer {
8331 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8332 CompletionsMenu::new_snippet_choices(
8333 id,
8334 true,
8335 choices,
8336 selection,
8337 buffer,
8338 snippet_sort_order,
8339 ),
8340 ));
8341 }
8342 }
8343
8344 pub fn insert_snippet(
8345 &mut self,
8346 insertion_ranges: &[Range<usize>],
8347 snippet: Snippet,
8348 window: &mut Window,
8349 cx: &mut Context<Self>,
8350 ) -> Result<()> {
8351 struct Tabstop<T> {
8352 is_end_tabstop: bool,
8353 ranges: Vec<Range<T>>,
8354 choices: Option<Vec<String>>,
8355 }
8356
8357 let tabstops = self.buffer.update(cx, |buffer, cx| {
8358 let snippet_text: Arc<str> = snippet.text.clone().into();
8359 let edits = insertion_ranges
8360 .iter()
8361 .cloned()
8362 .map(|range| (range, snippet_text.clone()));
8363 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8364
8365 let snapshot = &*buffer.read(cx);
8366 let snippet = &snippet;
8367 snippet
8368 .tabstops
8369 .iter()
8370 .map(|tabstop| {
8371 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8372 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8373 });
8374 let mut tabstop_ranges = tabstop
8375 .ranges
8376 .iter()
8377 .flat_map(|tabstop_range| {
8378 let mut delta = 0_isize;
8379 insertion_ranges.iter().map(move |insertion_range| {
8380 let insertion_start = insertion_range.start as isize + delta;
8381 delta +=
8382 snippet.text.len() as isize - insertion_range.len() as isize;
8383
8384 let start = ((insertion_start + tabstop_range.start) as usize)
8385 .min(snapshot.len());
8386 let end = ((insertion_start + tabstop_range.end) as usize)
8387 .min(snapshot.len());
8388 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8389 })
8390 })
8391 .collect::<Vec<_>>();
8392 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8393
8394 Tabstop {
8395 is_end_tabstop,
8396 ranges: tabstop_ranges,
8397 choices: tabstop.choices.clone(),
8398 }
8399 })
8400 .collect::<Vec<_>>()
8401 });
8402 if let Some(tabstop) = tabstops.first() {
8403 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8404 s.select_ranges(tabstop.ranges.iter().cloned());
8405 });
8406
8407 if let Some(choices) = &tabstop.choices {
8408 if let Some(selection) = tabstop.ranges.first() {
8409 self.show_snippet_choices(choices, selection.clone(), cx)
8410 }
8411 }
8412
8413 // If we're already at the last tabstop and it's at the end of the snippet,
8414 // we're done, we don't need to keep the state around.
8415 if !tabstop.is_end_tabstop {
8416 let choices = tabstops
8417 .iter()
8418 .map(|tabstop| tabstop.choices.clone())
8419 .collect();
8420
8421 let ranges = tabstops
8422 .into_iter()
8423 .map(|tabstop| tabstop.ranges)
8424 .collect::<Vec<_>>();
8425
8426 self.snippet_stack.push(SnippetState {
8427 active_index: 0,
8428 ranges,
8429 choices,
8430 });
8431 }
8432
8433 // Check whether the just-entered snippet ends with an auto-closable bracket.
8434 if self.autoclose_regions.is_empty() {
8435 let snapshot = self.buffer.read(cx).snapshot(cx);
8436 for selection in &mut self.selections.all::<Point>(cx) {
8437 let selection_head = selection.head();
8438 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8439 continue;
8440 };
8441
8442 let mut bracket_pair = None;
8443 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8444 let prev_chars = snapshot
8445 .reversed_chars_at(selection_head)
8446 .collect::<String>();
8447 for (pair, enabled) in scope.brackets() {
8448 if enabled
8449 && pair.close
8450 && prev_chars.starts_with(pair.start.as_str())
8451 && next_chars.starts_with(pair.end.as_str())
8452 {
8453 bracket_pair = Some(pair.clone());
8454 break;
8455 }
8456 }
8457 if let Some(pair) = bracket_pair {
8458 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8459 let autoclose_enabled =
8460 self.use_autoclose && snapshot_settings.use_autoclose;
8461 if autoclose_enabled {
8462 let start = snapshot.anchor_after(selection_head);
8463 let end = snapshot.anchor_after(selection_head);
8464 self.autoclose_regions.push(AutocloseRegion {
8465 selection_id: selection.id,
8466 range: start..end,
8467 pair,
8468 });
8469 }
8470 }
8471 }
8472 }
8473 }
8474 Ok(())
8475 }
8476
8477 pub fn move_to_next_snippet_tabstop(
8478 &mut self,
8479 window: &mut Window,
8480 cx: &mut Context<Self>,
8481 ) -> bool {
8482 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8483 }
8484
8485 pub fn move_to_prev_snippet_tabstop(
8486 &mut self,
8487 window: &mut Window,
8488 cx: &mut Context<Self>,
8489 ) -> bool {
8490 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8491 }
8492
8493 pub fn move_to_snippet_tabstop(
8494 &mut self,
8495 bias: Bias,
8496 window: &mut Window,
8497 cx: &mut Context<Self>,
8498 ) -> bool {
8499 if let Some(mut snippet) = self.snippet_stack.pop() {
8500 match bias {
8501 Bias::Left => {
8502 if snippet.active_index > 0 {
8503 snippet.active_index -= 1;
8504 } else {
8505 self.snippet_stack.push(snippet);
8506 return false;
8507 }
8508 }
8509 Bias::Right => {
8510 if snippet.active_index + 1 < snippet.ranges.len() {
8511 snippet.active_index += 1;
8512 } else {
8513 self.snippet_stack.push(snippet);
8514 return false;
8515 }
8516 }
8517 }
8518 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8519 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8520 s.select_anchor_ranges(current_ranges.iter().cloned())
8521 });
8522
8523 if let Some(choices) = &snippet.choices[snippet.active_index] {
8524 if let Some(selection) = current_ranges.first() {
8525 self.show_snippet_choices(&choices, selection.clone(), cx);
8526 }
8527 }
8528
8529 // If snippet state is not at the last tabstop, push it back on the stack
8530 if snippet.active_index + 1 < snippet.ranges.len() {
8531 self.snippet_stack.push(snippet);
8532 }
8533 return true;
8534 }
8535 }
8536
8537 false
8538 }
8539
8540 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8541 self.transact(window, cx, |this, window, cx| {
8542 this.select_all(&SelectAll, window, cx);
8543 this.insert("", window, cx);
8544 });
8545 }
8546
8547 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8548 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8549 self.transact(window, cx, |this, window, cx| {
8550 this.select_autoclose_pair(window, cx);
8551 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8552 if !this.linked_edit_ranges.is_empty() {
8553 let selections = this.selections.all::<MultiBufferPoint>(cx);
8554 let snapshot = this.buffer.read(cx).snapshot(cx);
8555
8556 for selection in selections.iter() {
8557 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8558 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8559 if selection_start.buffer_id != selection_end.buffer_id {
8560 continue;
8561 }
8562 if let Some(ranges) =
8563 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8564 {
8565 for (buffer, entries) in ranges {
8566 linked_ranges.entry(buffer).or_default().extend(entries);
8567 }
8568 }
8569 }
8570 }
8571
8572 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8573 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8574 for selection in &mut selections {
8575 if selection.is_empty() {
8576 let old_head = selection.head();
8577 let mut new_head =
8578 movement::left(&display_map, old_head.to_display_point(&display_map))
8579 .to_point(&display_map);
8580 if let Some((buffer, line_buffer_range)) = display_map
8581 .buffer_snapshot
8582 .buffer_line_for_row(MultiBufferRow(old_head.row))
8583 {
8584 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8585 let indent_len = match indent_size.kind {
8586 IndentKind::Space => {
8587 buffer.settings_at(line_buffer_range.start, cx).tab_size
8588 }
8589 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8590 };
8591 if old_head.column <= indent_size.len && old_head.column > 0 {
8592 let indent_len = indent_len.get();
8593 new_head = cmp::min(
8594 new_head,
8595 MultiBufferPoint::new(
8596 old_head.row,
8597 ((old_head.column - 1) / indent_len) * indent_len,
8598 ),
8599 );
8600 }
8601 }
8602
8603 selection.set_head(new_head, SelectionGoal::None);
8604 }
8605 }
8606
8607 this.signature_help_state.set_backspace_pressed(true);
8608 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8609 s.select(selections)
8610 });
8611 this.insert("", window, cx);
8612 let empty_str: Arc<str> = Arc::from("");
8613 for (buffer, edits) in linked_ranges {
8614 let snapshot = buffer.read(cx).snapshot();
8615 use text::ToPoint as TP;
8616
8617 let edits = edits
8618 .into_iter()
8619 .map(|range| {
8620 let end_point = TP::to_point(&range.end, &snapshot);
8621 let mut start_point = TP::to_point(&range.start, &snapshot);
8622
8623 if end_point == start_point {
8624 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8625 .saturating_sub(1);
8626 start_point =
8627 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8628 };
8629
8630 (start_point..end_point, empty_str.clone())
8631 })
8632 .sorted_by_key(|(range, _)| range.start)
8633 .collect::<Vec<_>>();
8634 buffer.update(cx, |this, cx| {
8635 this.edit(edits, None, cx);
8636 })
8637 }
8638 this.refresh_inline_completion(true, false, window, cx);
8639 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8640 });
8641 }
8642
8643 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8644 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8645 self.transact(window, cx, |this, window, cx| {
8646 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8647 s.move_with(|map, selection| {
8648 if selection.is_empty() {
8649 let cursor = movement::right(map, selection.head());
8650 selection.end = cursor;
8651 selection.reversed = true;
8652 selection.goal = SelectionGoal::None;
8653 }
8654 })
8655 });
8656 this.insert("", window, cx);
8657 this.refresh_inline_completion(true, false, window, cx);
8658 });
8659 }
8660
8661 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8662 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8663 if self.move_to_prev_snippet_tabstop(window, cx) {
8664 return;
8665 }
8666 self.outdent(&Outdent, window, cx);
8667 }
8668
8669 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8670 if self.move_to_next_snippet_tabstop(window, cx) {
8671 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8672 return;
8673 }
8674 if self.read_only(cx) {
8675 return;
8676 }
8677 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8678 let mut selections = self.selections.all_adjusted(cx);
8679 let buffer = self.buffer.read(cx);
8680 let snapshot = buffer.snapshot(cx);
8681 let rows_iter = selections.iter().map(|s| s.head().row);
8682 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8683
8684 let has_some_cursor_in_whitespace = selections
8685 .iter()
8686 .filter(|selection| selection.is_empty())
8687 .any(|selection| {
8688 let cursor = selection.head();
8689 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8690 cursor.column < current_indent.len
8691 });
8692
8693 let mut edits = Vec::new();
8694 let mut prev_edited_row = 0;
8695 let mut row_delta = 0;
8696 for selection in &mut selections {
8697 if selection.start.row != prev_edited_row {
8698 row_delta = 0;
8699 }
8700 prev_edited_row = selection.end.row;
8701
8702 // If the selection is non-empty, then increase the indentation of the selected lines.
8703 if !selection.is_empty() {
8704 row_delta =
8705 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8706 continue;
8707 }
8708
8709 // If the selection is empty and the cursor is in the leading whitespace before the
8710 // suggested indentation, then auto-indent the line.
8711 let cursor = selection.head();
8712 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8713 if let Some(suggested_indent) =
8714 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8715 {
8716 // If there exist any empty selection in the leading whitespace, then skip
8717 // indent for selections at the boundary.
8718 if has_some_cursor_in_whitespace
8719 && cursor.column == current_indent.len
8720 && current_indent.len == suggested_indent.len
8721 {
8722 continue;
8723 }
8724
8725 if cursor.column < suggested_indent.len
8726 && cursor.column <= current_indent.len
8727 && current_indent.len <= suggested_indent.len
8728 {
8729 selection.start = Point::new(cursor.row, suggested_indent.len);
8730 selection.end = selection.start;
8731 if row_delta == 0 {
8732 edits.extend(Buffer::edit_for_indent_size_adjustment(
8733 cursor.row,
8734 current_indent,
8735 suggested_indent,
8736 ));
8737 row_delta = suggested_indent.len - current_indent.len;
8738 }
8739 continue;
8740 }
8741 }
8742
8743 // Otherwise, insert a hard or soft tab.
8744 let settings = buffer.language_settings_at(cursor, cx);
8745 let tab_size = if settings.hard_tabs {
8746 IndentSize::tab()
8747 } else {
8748 let tab_size = settings.tab_size.get();
8749 let indent_remainder = snapshot
8750 .text_for_range(Point::new(cursor.row, 0)..cursor)
8751 .flat_map(str::chars)
8752 .fold(row_delta % tab_size, |counter: u32, c| {
8753 if c == '\t' {
8754 0
8755 } else {
8756 (counter + 1) % tab_size
8757 }
8758 });
8759
8760 let chars_to_next_tab_stop = tab_size - indent_remainder;
8761 IndentSize::spaces(chars_to_next_tab_stop)
8762 };
8763 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8764 selection.end = selection.start;
8765 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8766 row_delta += tab_size.len;
8767 }
8768
8769 self.transact(window, cx, |this, window, cx| {
8770 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8771 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8772 s.select(selections)
8773 });
8774 this.refresh_inline_completion(true, false, window, cx);
8775 });
8776 }
8777
8778 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8779 if self.read_only(cx) {
8780 return;
8781 }
8782 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8783 let mut selections = self.selections.all::<Point>(cx);
8784 let mut prev_edited_row = 0;
8785 let mut row_delta = 0;
8786 let mut edits = Vec::new();
8787 let buffer = self.buffer.read(cx);
8788 let snapshot = buffer.snapshot(cx);
8789 for selection in &mut selections {
8790 if selection.start.row != prev_edited_row {
8791 row_delta = 0;
8792 }
8793 prev_edited_row = selection.end.row;
8794
8795 row_delta =
8796 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8797 }
8798
8799 self.transact(window, cx, |this, window, cx| {
8800 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8801 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8802 s.select(selections)
8803 });
8804 });
8805 }
8806
8807 fn indent_selection(
8808 buffer: &MultiBuffer,
8809 snapshot: &MultiBufferSnapshot,
8810 selection: &mut Selection<Point>,
8811 edits: &mut Vec<(Range<Point>, String)>,
8812 delta_for_start_row: u32,
8813 cx: &App,
8814 ) -> u32 {
8815 let settings = buffer.language_settings_at(selection.start, cx);
8816 let tab_size = settings.tab_size.get();
8817 let indent_kind = if settings.hard_tabs {
8818 IndentKind::Tab
8819 } else {
8820 IndentKind::Space
8821 };
8822 let mut start_row = selection.start.row;
8823 let mut end_row = selection.end.row + 1;
8824
8825 // If a selection ends at the beginning of a line, don't indent
8826 // that last line.
8827 if selection.end.column == 0 && selection.end.row > selection.start.row {
8828 end_row -= 1;
8829 }
8830
8831 // Avoid re-indenting a row that has already been indented by a
8832 // previous selection, but still update this selection's column
8833 // to reflect that indentation.
8834 if delta_for_start_row > 0 {
8835 start_row += 1;
8836 selection.start.column += delta_for_start_row;
8837 if selection.end.row == selection.start.row {
8838 selection.end.column += delta_for_start_row;
8839 }
8840 }
8841
8842 let mut delta_for_end_row = 0;
8843 let has_multiple_rows = start_row + 1 != end_row;
8844 for row in start_row..end_row {
8845 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8846 let indent_delta = match (current_indent.kind, indent_kind) {
8847 (IndentKind::Space, IndentKind::Space) => {
8848 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8849 IndentSize::spaces(columns_to_next_tab_stop)
8850 }
8851 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8852 (_, IndentKind::Tab) => IndentSize::tab(),
8853 };
8854
8855 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8856 0
8857 } else {
8858 selection.start.column
8859 };
8860 let row_start = Point::new(row, start);
8861 edits.push((
8862 row_start..row_start,
8863 indent_delta.chars().collect::<String>(),
8864 ));
8865
8866 // Update this selection's endpoints to reflect the indentation.
8867 if row == selection.start.row {
8868 selection.start.column += indent_delta.len;
8869 }
8870 if row == selection.end.row {
8871 selection.end.column += indent_delta.len;
8872 delta_for_end_row = indent_delta.len;
8873 }
8874 }
8875
8876 if selection.start.row == selection.end.row {
8877 delta_for_start_row + delta_for_end_row
8878 } else {
8879 delta_for_end_row
8880 }
8881 }
8882
8883 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8884 if self.read_only(cx) {
8885 return;
8886 }
8887 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8888 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8889 let selections = self.selections.all::<Point>(cx);
8890 let mut deletion_ranges = Vec::new();
8891 let mut last_outdent = None;
8892 {
8893 let buffer = self.buffer.read(cx);
8894 let snapshot = buffer.snapshot(cx);
8895 for selection in &selections {
8896 let settings = buffer.language_settings_at(selection.start, cx);
8897 let tab_size = settings.tab_size.get();
8898 let mut rows = selection.spanned_rows(false, &display_map);
8899
8900 // Avoid re-outdenting a row that has already been outdented by a
8901 // previous selection.
8902 if let Some(last_row) = last_outdent {
8903 if last_row == rows.start {
8904 rows.start = rows.start.next_row();
8905 }
8906 }
8907 let has_multiple_rows = rows.len() > 1;
8908 for row in rows.iter_rows() {
8909 let indent_size = snapshot.indent_size_for_line(row);
8910 if indent_size.len > 0 {
8911 let deletion_len = match indent_size.kind {
8912 IndentKind::Space => {
8913 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8914 if columns_to_prev_tab_stop == 0 {
8915 tab_size
8916 } else {
8917 columns_to_prev_tab_stop
8918 }
8919 }
8920 IndentKind::Tab => 1,
8921 };
8922 let start = if has_multiple_rows
8923 || deletion_len > selection.start.column
8924 || indent_size.len < selection.start.column
8925 {
8926 0
8927 } else {
8928 selection.start.column - deletion_len
8929 };
8930 deletion_ranges.push(
8931 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8932 );
8933 last_outdent = Some(row);
8934 }
8935 }
8936 }
8937 }
8938
8939 self.transact(window, cx, |this, window, cx| {
8940 this.buffer.update(cx, |buffer, cx| {
8941 let empty_str: Arc<str> = Arc::default();
8942 buffer.edit(
8943 deletion_ranges
8944 .into_iter()
8945 .map(|range| (range, empty_str.clone())),
8946 None,
8947 cx,
8948 );
8949 });
8950 let selections = this.selections.all::<usize>(cx);
8951 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8952 s.select(selections)
8953 });
8954 });
8955 }
8956
8957 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8958 if self.read_only(cx) {
8959 return;
8960 }
8961 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8962 let selections = self
8963 .selections
8964 .all::<usize>(cx)
8965 .into_iter()
8966 .map(|s| s.range());
8967
8968 self.transact(window, cx, |this, window, cx| {
8969 this.buffer.update(cx, |buffer, cx| {
8970 buffer.autoindent_ranges(selections, cx);
8971 });
8972 let selections = this.selections.all::<usize>(cx);
8973 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8974 s.select(selections)
8975 });
8976 });
8977 }
8978
8979 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8980 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8981 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8982 let selections = self.selections.all::<Point>(cx);
8983
8984 let mut new_cursors = Vec::new();
8985 let mut edit_ranges = Vec::new();
8986 let mut selections = selections.iter().peekable();
8987 while let Some(selection) = selections.next() {
8988 let mut rows = selection.spanned_rows(false, &display_map);
8989 let goal_display_column = selection.head().to_display_point(&display_map).column();
8990
8991 // Accumulate contiguous regions of rows that we want to delete.
8992 while let Some(next_selection) = selections.peek() {
8993 let next_rows = next_selection.spanned_rows(false, &display_map);
8994 if next_rows.start <= rows.end {
8995 rows.end = next_rows.end;
8996 selections.next().unwrap();
8997 } else {
8998 break;
8999 }
9000 }
9001
9002 let buffer = &display_map.buffer_snapshot;
9003 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9004 let edit_end;
9005 let cursor_buffer_row;
9006 if buffer.max_point().row >= rows.end.0 {
9007 // If there's a line after the range, delete the \n from the end of the row range
9008 // and position the cursor on the next line.
9009 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9010 cursor_buffer_row = rows.end;
9011 } else {
9012 // If there isn't a line after the range, delete the \n from the line before the
9013 // start of the row range and position the cursor there.
9014 edit_start = edit_start.saturating_sub(1);
9015 edit_end = buffer.len();
9016 cursor_buffer_row = rows.start.previous_row();
9017 }
9018
9019 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9020 *cursor.column_mut() =
9021 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9022
9023 new_cursors.push((
9024 selection.id,
9025 buffer.anchor_after(cursor.to_point(&display_map)),
9026 ));
9027 edit_ranges.push(edit_start..edit_end);
9028 }
9029
9030 self.transact(window, cx, |this, window, cx| {
9031 let buffer = this.buffer.update(cx, |buffer, cx| {
9032 let empty_str: Arc<str> = Arc::default();
9033 buffer.edit(
9034 edit_ranges
9035 .into_iter()
9036 .map(|range| (range, empty_str.clone())),
9037 None,
9038 cx,
9039 );
9040 buffer.snapshot(cx)
9041 });
9042 let new_selections = new_cursors
9043 .into_iter()
9044 .map(|(id, cursor)| {
9045 let cursor = cursor.to_point(&buffer);
9046 Selection {
9047 id,
9048 start: cursor,
9049 end: cursor,
9050 reversed: false,
9051 goal: SelectionGoal::None,
9052 }
9053 })
9054 .collect();
9055
9056 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9057 s.select(new_selections);
9058 });
9059 });
9060 }
9061
9062 pub fn join_lines_impl(
9063 &mut self,
9064 insert_whitespace: bool,
9065 window: &mut Window,
9066 cx: &mut Context<Self>,
9067 ) {
9068 if self.read_only(cx) {
9069 return;
9070 }
9071 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9072 for selection in self.selections.all::<Point>(cx) {
9073 let start = MultiBufferRow(selection.start.row);
9074 // Treat single line selections as if they include the next line. Otherwise this action
9075 // would do nothing for single line selections individual cursors.
9076 let end = if selection.start.row == selection.end.row {
9077 MultiBufferRow(selection.start.row + 1)
9078 } else {
9079 MultiBufferRow(selection.end.row)
9080 };
9081
9082 if let Some(last_row_range) = row_ranges.last_mut() {
9083 if start <= last_row_range.end {
9084 last_row_range.end = end;
9085 continue;
9086 }
9087 }
9088 row_ranges.push(start..end);
9089 }
9090
9091 let snapshot = self.buffer.read(cx).snapshot(cx);
9092 let mut cursor_positions = Vec::new();
9093 for row_range in &row_ranges {
9094 let anchor = snapshot.anchor_before(Point::new(
9095 row_range.end.previous_row().0,
9096 snapshot.line_len(row_range.end.previous_row()),
9097 ));
9098 cursor_positions.push(anchor..anchor);
9099 }
9100
9101 self.transact(window, cx, |this, window, cx| {
9102 for row_range in row_ranges.into_iter().rev() {
9103 for row in row_range.iter_rows().rev() {
9104 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9105 let next_line_row = row.next_row();
9106 let indent = snapshot.indent_size_for_line(next_line_row);
9107 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9108
9109 let replace =
9110 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9111 " "
9112 } else {
9113 ""
9114 };
9115
9116 this.buffer.update(cx, |buffer, cx| {
9117 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9118 });
9119 }
9120 }
9121
9122 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9123 s.select_anchor_ranges(cursor_positions)
9124 });
9125 });
9126 }
9127
9128 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9129 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9130 self.join_lines_impl(true, window, cx);
9131 }
9132
9133 pub fn sort_lines_case_sensitive(
9134 &mut self,
9135 _: &SortLinesCaseSensitive,
9136 window: &mut Window,
9137 cx: &mut Context<Self>,
9138 ) {
9139 self.manipulate_lines(window, cx, |lines| lines.sort())
9140 }
9141
9142 pub fn sort_lines_case_insensitive(
9143 &mut self,
9144 _: &SortLinesCaseInsensitive,
9145 window: &mut Window,
9146 cx: &mut Context<Self>,
9147 ) {
9148 self.manipulate_lines(window, cx, |lines| {
9149 lines.sort_by_key(|line| line.to_lowercase())
9150 })
9151 }
9152
9153 pub fn unique_lines_case_insensitive(
9154 &mut self,
9155 _: &UniqueLinesCaseInsensitive,
9156 window: &mut Window,
9157 cx: &mut Context<Self>,
9158 ) {
9159 self.manipulate_lines(window, cx, |lines| {
9160 let mut seen = HashSet::default();
9161 lines.retain(|line| seen.insert(line.to_lowercase()));
9162 })
9163 }
9164
9165 pub fn unique_lines_case_sensitive(
9166 &mut self,
9167 _: &UniqueLinesCaseSensitive,
9168 window: &mut Window,
9169 cx: &mut Context<Self>,
9170 ) {
9171 self.manipulate_lines(window, cx, |lines| {
9172 let mut seen = HashSet::default();
9173 lines.retain(|line| seen.insert(*line));
9174 })
9175 }
9176
9177 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9178 let Some(project) = self.project.clone() else {
9179 return;
9180 };
9181 self.reload(project, window, cx)
9182 .detach_and_notify_err(window, cx);
9183 }
9184
9185 pub fn restore_file(
9186 &mut self,
9187 _: &::git::RestoreFile,
9188 window: &mut Window,
9189 cx: &mut Context<Self>,
9190 ) {
9191 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9192 let mut buffer_ids = HashSet::default();
9193 let snapshot = self.buffer().read(cx).snapshot(cx);
9194 for selection in self.selections.all::<usize>(cx) {
9195 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9196 }
9197
9198 let buffer = self.buffer().read(cx);
9199 let ranges = buffer_ids
9200 .into_iter()
9201 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9202 .collect::<Vec<_>>();
9203
9204 self.restore_hunks_in_ranges(ranges, window, cx);
9205 }
9206
9207 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9208 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9209 let selections = self
9210 .selections
9211 .all(cx)
9212 .into_iter()
9213 .map(|s| s.range())
9214 .collect();
9215 self.restore_hunks_in_ranges(selections, window, cx);
9216 }
9217
9218 pub fn restore_hunks_in_ranges(
9219 &mut self,
9220 ranges: Vec<Range<Point>>,
9221 window: &mut Window,
9222 cx: &mut Context<Editor>,
9223 ) {
9224 let mut revert_changes = HashMap::default();
9225 let chunk_by = self
9226 .snapshot(window, cx)
9227 .hunks_for_ranges(ranges)
9228 .into_iter()
9229 .chunk_by(|hunk| hunk.buffer_id);
9230 for (buffer_id, hunks) in &chunk_by {
9231 let hunks = hunks.collect::<Vec<_>>();
9232 for hunk in &hunks {
9233 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9234 }
9235 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9236 }
9237 drop(chunk_by);
9238 if !revert_changes.is_empty() {
9239 self.transact(window, cx, |editor, window, cx| {
9240 editor.restore(revert_changes, window, cx);
9241 });
9242 }
9243 }
9244
9245 pub fn open_active_item_in_terminal(
9246 &mut self,
9247 _: &OpenInTerminal,
9248 window: &mut Window,
9249 cx: &mut Context<Self>,
9250 ) {
9251 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9252 let project_path = buffer.read(cx).project_path(cx)?;
9253 let project = self.project.as_ref()?.read(cx);
9254 let entry = project.entry_for_path(&project_path, cx)?;
9255 let parent = match &entry.canonical_path {
9256 Some(canonical_path) => canonical_path.to_path_buf(),
9257 None => project.absolute_path(&project_path, cx)?,
9258 }
9259 .parent()?
9260 .to_path_buf();
9261 Some(parent)
9262 }) {
9263 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9264 }
9265 }
9266
9267 fn set_breakpoint_context_menu(
9268 &mut self,
9269 display_row: DisplayRow,
9270 position: Option<Anchor>,
9271 clicked_point: gpui::Point<Pixels>,
9272 window: &mut Window,
9273 cx: &mut Context<Self>,
9274 ) {
9275 if !cx.has_flag::<DebuggerFeatureFlag>() {
9276 return;
9277 }
9278 let source = self
9279 .buffer
9280 .read(cx)
9281 .snapshot(cx)
9282 .anchor_before(Point::new(display_row.0, 0u32));
9283
9284 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9285
9286 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9287 self,
9288 source,
9289 clicked_point,
9290 context_menu,
9291 window,
9292 cx,
9293 );
9294 }
9295
9296 fn add_edit_breakpoint_block(
9297 &mut self,
9298 anchor: Anchor,
9299 breakpoint: &Breakpoint,
9300 edit_action: BreakpointPromptEditAction,
9301 window: &mut Window,
9302 cx: &mut Context<Self>,
9303 ) {
9304 let weak_editor = cx.weak_entity();
9305 let bp_prompt = cx.new(|cx| {
9306 BreakpointPromptEditor::new(
9307 weak_editor,
9308 anchor,
9309 breakpoint.clone(),
9310 edit_action,
9311 window,
9312 cx,
9313 )
9314 });
9315
9316 let height = bp_prompt.update(cx, |this, cx| {
9317 this.prompt
9318 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9319 });
9320 let cloned_prompt = bp_prompt.clone();
9321 let blocks = vec![BlockProperties {
9322 style: BlockStyle::Sticky,
9323 placement: BlockPlacement::Above(anchor),
9324 height: Some(height),
9325 render: Arc::new(move |cx| {
9326 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9327 cloned_prompt.clone().into_any_element()
9328 }),
9329 priority: 0,
9330 }];
9331
9332 let focus_handle = bp_prompt.focus_handle(cx);
9333 window.focus(&focus_handle);
9334
9335 let block_ids = self.insert_blocks(blocks, None, cx);
9336 bp_prompt.update(cx, |prompt, _| {
9337 prompt.add_block_ids(block_ids);
9338 });
9339 }
9340
9341 pub(crate) fn breakpoint_at_row(
9342 &self,
9343 row: u32,
9344 window: &mut Window,
9345 cx: &mut Context<Self>,
9346 ) -> Option<(Anchor, Breakpoint)> {
9347 let snapshot = self.snapshot(window, cx);
9348 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9349
9350 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9351 }
9352
9353 pub(crate) fn breakpoint_at_anchor(
9354 &self,
9355 breakpoint_position: Anchor,
9356 snapshot: &EditorSnapshot,
9357 cx: &mut Context<Self>,
9358 ) -> Option<(Anchor, Breakpoint)> {
9359 let project = self.project.clone()?;
9360
9361 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9362 snapshot
9363 .buffer_snapshot
9364 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9365 })?;
9366
9367 let enclosing_excerpt = breakpoint_position.excerpt_id;
9368 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9369 let buffer_snapshot = buffer.read(cx).snapshot();
9370
9371 let row = buffer_snapshot
9372 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9373 .row;
9374
9375 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9376 let anchor_end = snapshot
9377 .buffer_snapshot
9378 .anchor_after(Point::new(row, line_len));
9379
9380 let bp = self
9381 .breakpoint_store
9382 .as_ref()?
9383 .read_with(cx, |breakpoint_store, cx| {
9384 breakpoint_store
9385 .breakpoints(
9386 &buffer,
9387 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9388 &buffer_snapshot,
9389 cx,
9390 )
9391 .next()
9392 .and_then(|(anchor, bp)| {
9393 let breakpoint_row = buffer_snapshot
9394 .summary_for_anchor::<text::PointUtf16>(anchor)
9395 .row;
9396
9397 if breakpoint_row == row {
9398 snapshot
9399 .buffer_snapshot
9400 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9401 .map(|anchor| (anchor, bp.clone()))
9402 } else {
9403 None
9404 }
9405 })
9406 });
9407 bp
9408 }
9409
9410 pub fn edit_log_breakpoint(
9411 &mut self,
9412 _: &EditLogBreakpoint,
9413 window: &mut Window,
9414 cx: &mut Context<Self>,
9415 ) {
9416 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9417 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9418 message: None,
9419 state: BreakpointState::Enabled,
9420 condition: None,
9421 hit_condition: None,
9422 });
9423
9424 self.add_edit_breakpoint_block(
9425 anchor,
9426 &breakpoint,
9427 BreakpointPromptEditAction::Log,
9428 window,
9429 cx,
9430 );
9431 }
9432 }
9433
9434 fn breakpoints_at_cursors(
9435 &self,
9436 window: &mut Window,
9437 cx: &mut Context<Self>,
9438 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9439 let snapshot = self.snapshot(window, cx);
9440 let cursors = self
9441 .selections
9442 .disjoint_anchors()
9443 .into_iter()
9444 .map(|selection| {
9445 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9446
9447 let breakpoint_position = self
9448 .breakpoint_at_row(cursor_position.row, window, cx)
9449 .map(|bp| bp.0)
9450 .unwrap_or_else(|| {
9451 snapshot
9452 .display_snapshot
9453 .buffer_snapshot
9454 .anchor_after(Point::new(cursor_position.row, 0))
9455 });
9456
9457 let breakpoint = self
9458 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9459 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9460
9461 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9462 })
9463 // 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.
9464 .collect::<HashMap<Anchor, _>>();
9465
9466 cursors.into_iter().collect()
9467 }
9468
9469 pub fn enable_breakpoint(
9470 &mut self,
9471 _: &crate::actions::EnableBreakpoint,
9472 window: &mut Window,
9473 cx: &mut Context<Self>,
9474 ) {
9475 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9476 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9477 continue;
9478 };
9479 self.edit_breakpoint_at_anchor(
9480 anchor,
9481 breakpoint,
9482 BreakpointEditAction::InvertState,
9483 cx,
9484 );
9485 }
9486 }
9487
9488 pub fn disable_breakpoint(
9489 &mut self,
9490 _: &crate::actions::DisableBreakpoint,
9491 window: &mut Window,
9492 cx: &mut Context<Self>,
9493 ) {
9494 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9495 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9496 continue;
9497 };
9498 self.edit_breakpoint_at_anchor(
9499 anchor,
9500 breakpoint,
9501 BreakpointEditAction::InvertState,
9502 cx,
9503 );
9504 }
9505 }
9506
9507 pub fn toggle_breakpoint(
9508 &mut self,
9509 _: &crate::actions::ToggleBreakpoint,
9510 window: &mut Window,
9511 cx: &mut Context<Self>,
9512 ) {
9513 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9514 if let Some(breakpoint) = breakpoint {
9515 self.edit_breakpoint_at_anchor(
9516 anchor,
9517 breakpoint,
9518 BreakpointEditAction::Toggle,
9519 cx,
9520 );
9521 } else {
9522 self.edit_breakpoint_at_anchor(
9523 anchor,
9524 Breakpoint::new_standard(),
9525 BreakpointEditAction::Toggle,
9526 cx,
9527 );
9528 }
9529 }
9530 }
9531
9532 pub fn edit_breakpoint_at_anchor(
9533 &mut self,
9534 breakpoint_position: Anchor,
9535 breakpoint: Breakpoint,
9536 edit_action: BreakpointEditAction,
9537 cx: &mut Context<Self>,
9538 ) {
9539 let Some(breakpoint_store) = &self.breakpoint_store else {
9540 return;
9541 };
9542
9543 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9544 if breakpoint_position == Anchor::min() {
9545 self.buffer()
9546 .read(cx)
9547 .excerpt_buffer_ids()
9548 .into_iter()
9549 .next()
9550 } else {
9551 None
9552 }
9553 }) else {
9554 return;
9555 };
9556
9557 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9558 return;
9559 };
9560
9561 breakpoint_store.update(cx, |breakpoint_store, cx| {
9562 breakpoint_store.toggle_breakpoint(
9563 buffer,
9564 (breakpoint_position.text_anchor, breakpoint),
9565 edit_action,
9566 cx,
9567 );
9568 });
9569
9570 cx.notify();
9571 }
9572
9573 #[cfg(any(test, feature = "test-support"))]
9574 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9575 self.breakpoint_store.clone()
9576 }
9577
9578 pub fn prepare_restore_change(
9579 &self,
9580 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9581 hunk: &MultiBufferDiffHunk,
9582 cx: &mut App,
9583 ) -> Option<()> {
9584 if hunk.is_created_file() {
9585 return None;
9586 }
9587 let buffer = self.buffer.read(cx);
9588 let diff = buffer.diff_for(hunk.buffer_id)?;
9589 let buffer = buffer.buffer(hunk.buffer_id)?;
9590 let buffer = buffer.read(cx);
9591 let original_text = diff
9592 .read(cx)
9593 .base_text()
9594 .as_rope()
9595 .slice(hunk.diff_base_byte_range.clone());
9596 let buffer_snapshot = buffer.snapshot();
9597 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9598 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9599 probe
9600 .0
9601 .start
9602 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9603 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9604 }) {
9605 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9606 Some(())
9607 } else {
9608 None
9609 }
9610 }
9611
9612 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9613 self.manipulate_lines(window, cx, |lines| lines.reverse())
9614 }
9615
9616 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9617 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9618 }
9619
9620 fn manipulate_lines<Fn>(
9621 &mut self,
9622 window: &mut Window,
9623 cx: &mut Context<Self>,
9624 mut callback: Fn,
9625 ) where
9626 Fn: FnMut(&mut Vec<&str>),
9627 {
9628 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9629
9630 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9631 let buffer = self.buffer.read(cx).snapshot(cx);
9632
9633 let mut edits = Vec::new();
9634
9635 let selections = self.selections.all::<Point>(cx);
9636 let mut selections = selections.iter().peekable();
9637 let mut contiguous_row_selections = Vec::new();
9638 let mut new_selections = Vec::new();
9639 let mut added_lines = 0;
9640 let mut removed_lines = 0;
9641
9642 while let Some(selection) = selections.next() {
9643 let (start_row, end_row) = consume_contiguous_rows(
9644 &mut contiguous_row_selections,
9645 selection,
9646 &display_map,
9647 &mut selections,
9648 );
9649
9650 let start_point = Point::new(start_row.0, 0);
9651 let end_point = Point::new(
9652 end_row.previous_row().0,
9653 buffer.line_len(end_row.previous_row()),
9654 );
9655 let text = buffer
9656 .text_for_range(start_point..end_point)
9657 .collect::<String>();
9658
9659 let mut lines = text.split('\n').collect_vec();
9660
9661 let lines_before = lines.len();
9662 callback(&mut lines);
9663 let lines_after = lines.len();
9664
9665 edits.push((start_point..end_point, lines.join("\n")));
9666
9667 // Selections must change based on added and removed line count
9668 let start_row =
9669 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9670 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9671 new_selections.push(Selection {
9672 id: selection.id,
9673 start: start_row,
9674 end: end_row,
9675 goal: SelectionGoal::None,
9676 reversed: selection.reversed,
9677 });
9678
9679 if lines_after > lines_before {
9680 added_lines += lines_after - lines_before;
9681 } else if lines_before > lines_after {
9682 removed_lines += lines_before - lines_after;
9683 }
9684 }
9685
9686 self.transact(window, cx, |this, window, cx| {
9687 let buffer = this.buffer.update(cx, |buffer, cx| {
9688 buffer.edit(edits, None, cx);
9689 buffer.snapshot(cx)
9690 });
9691
9692 // Recalculate offsets on newly edited buffer
9693 let new_selections = new_selections
9694 .iter()
9695 .map(|s| {
9696 let start_point = Point::new(s.start.0, 0);
9697 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9698 Selection {
9699 id: s.id,
9700 start: buffer.point_to_offset(start_point),
9701 end: buffer.point_to_offset(end_point),
9702 goal: s.goal,
9703 reversed: s.reversed,
9704 }
9705 })
9706 .collect();
9707
9708 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9709 s.select(new_selections);
9710 });
9711
9712 this.request_autoscroll(Autoscroll::fit(), cx);
9713 });
9714 }
9715
9716 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9717 self.manipulate_text(window, cx, |text| {
9718 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9719 if has_upper_case_characters {
9720 text.to_lowercase()
9721 } else {
9722 text.to_uppercase()
9723 }
9724 })
9725 }
9726
9727 pub fn convert_to_upper_case(
9728 &mut self,
9729 _: &ConvertToUpperCase,
9730 window: &mut Window,
9731 cx: &mut Context<Self>,
9732 ) {
9733 self.manipulate_text(window, cx, |text| text.to_uppercase())
9734 }
9735
9736 pub fn convert_to_lower_case(
9737 &mut self,
9738 _: &ConvertToLowerCase,
9739 window: &mut Window,
9740 cx: &mut Context<Self>,
9741 ) {
9742 self.manipulate_text(window, cx, |text| text.to_lowercase())
9743 }
9744
9745 pub fn convert_to_title_case(
9746 &mut self,
9747 _: &ConvertToTitleCase,
9748 window: &mut Window,
9749 cx: &mut Context<Self>,
9750 ) {
9751 self.manipulate_text(window, cx, |text| {
9752 text.split('\n')
9753 .map(|line| line.to_case(Case::Title))
9754 .join("\n")
9755 })
9756 }
9757
9758 pub fn convert_to_snake_case(
9759 &mut self,
9760 _: &ConvertToSnakeCase,
9761 window: &mut Window,
9762 cx: &mut Context<Self>,
9763 ) {
9764 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9765 }
9766
9767 pub fn convert_to_kebab_case(
9768 &mut self,
9769 _: &ConvertToKebabCase,
9770 window: &mut Window,
9771 cx: &mut Context<Self>,
9772 ) {
9773 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9774 }
9775
9776 pub fn convert_to_upper_camel_case(
9777 &mut self,
9778 _: &ConvertToUpperCamelCase,
9779 window: &mut Window,
9780 cx: &mut Context<Self>,
9781 ) {
9782 self.manipulate_text(window, cx, |text| {
9783 text.split('\n')
9784 .map(|line| line.to_case(Case::UpperCamel))
9785 .join("\n")
9786 })
9787 }
9788
9789 pub fn convert_to_lower_camel_case(
9790 &mut self,
9791 _: &ConvertToLowerCamelCase,
9792 window: &mut Window,
9793 cx: &mut Context<Self>,
9794 ) {
9795 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9796 }
9797
9798 pub fn convert_to_opposite_case(
9799 &mut self,
9800 _: &ConvertToOppositeCase,
9801 window: &mut Window,
9802 cx: &mut Context<Self>,
9803 ) {
9804 self.manipulate_text(window, cx, |text| {
9805 text.chars()
9806 .fold(String::with_capacity(text.len()), |mut t, c| {
9807 if c.is_uppercase() {
9808 t.extend(c.to_lowercase());
9809 } else {
9810 t.extend(c.to_uppercase());
9811 }
9812 t
9813 })
9814 })
9815 }
9816
9817 pub fn convert_to_rot13(
9818 &mut self,
9819 _: &ConvertToRot13,
9820 window: &mut Window,
9821 cx: &mut Context<Self>,
9822 ) {
9823 self.manipulate_text(window, cx, |text| {
9824 text.chars()
9825 .map(|c| match c {
9826 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9827 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9828 _ => c,
9829 })
9830 .collect()
9831 })
9832 }
9833
9834 pub fn convert_to_rot47(
9835 &mut self,
9836 _: &ConvertToRot47,
9837 window: &mut Window,
9838 cx: &mut Context<Self>,
9839 ) {
9840 self.manipulate_text(window, cx, |text| {
9841 text.chars()
9842 .map(|c| {
9843 let code_point = c as u32;
9844 if code_point >= 33 && code_point <= 126 {
9845 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9846 }
9847 c
9848 })
9849 .collect()
9850 })
9851 }
9852
9853 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9854 where
9855 Fn: FnMut(&str) -> String,
9856 {
9857 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9858 let buffer = self.buffer.read(cx).snapshot(cx);
9859
9860 let mut new_selections = Vec::new();
9861 let mut edits = Vec::new();
9862 let mut selection_adjustment = 0i32;
9863
9864 for selection in self.selections.all::<usize>(cx) {
9865 let selection_is_empty = selection.is_empty();
9866
9867 let (start, end) = if selection_is_empty {
9868 let word_range = movement::surrounding_word(
9869 &display_map,
9870 selection.start.to_display_point(&display_map),
9871 );
9872 let start = word_range.start.to_offset(&display_map, Bias::Left);
9873 let end = word_range.end.to_offset(&display_map, Bias::Left);
9874 (start, end)
9875 } else {
9876 (selection.start, selection.end)
9877 };
9878
9879 let text = buffer.text_for_range(start..end).collect::<String>();
9880 let old_length = text.len() as i32;
9881 let text = callback(&text);
9882
9883 new_selections.push(Selection {
9884 start: (start as i32 - selection_adjustment) as usize,
9885 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9886 goal: SelectionGoal::None,
9887 ..selection
9888 });
9889
9890 selection_adjustment += old_length - text.len() as i32;
9891
9892 edits.push((start..end, text));
9893 }
9894
9895 self.transact(window, cx, |this, window, cx| {
9896 this.buffer.update(cx, |buffer, cx| {
9897 buffer.edit(edits, None, cx);
9898 });
9899
9900 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9901 s.select(new_selections);
9902 });
9903
9904 this.request_autoscroll(Autoscroll::fit(), cx);
9905 });
9906 }
9907
9908 pub fn duplicate(
9909 &mut self,
9910 upwards: bool,
9911 whole_lines: bool,
9912 window: &mut Window,
9913 cx: &mut Context<Self>,
9914 ) {
9915 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9916
9917 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9918 let buffer = &display_map.buffer_snapshot;
9919 let selections = self.selections.all::<Point>(cx);
9920
9921 let mut edits = Vec::new();
9922 let mut selections_iter = selections.iter().peekable();
9923 while let Some(selection) = selections_iter.next() {
9924 let mut rows = selection.spanned_rows(false, &display_map);
9925 // duplicate line-wise
9926 if whole_lines || selection.start == selection.end {
9927 // Avoid duplicating the same lines twice.
9928 while let Some(next_selection) = selections_iter.peek() {
9929 let next_rows = next_selection.spanned_rows(false, &display_map);
9930 if next_rows.start < rows.end {
9931 rows.end = next_rows.end;
9932 selections_iter.next().unwrap();
9933 } else {
9934 break;
9935 }
9936 }
9937
9938 // Copy the text from the selected row region and splice it either at the start
9939 // or end of the region.
9940 let start = Point::new(rows.start.0, 0);
9941 let end = Point::new(
9942 rows.end.previous_row().0,
9943 buffer.line_len(rows.end.previous_row()),
9944 );
9945 let text = buffer
9946 .text_for_range(start..end)
9947 .chain(Some("\n"))
9948 .collect::<String>();
9949 let insert_location = if upwards {
9950 Point::new(rows.end.0, 0)
9951 } else {
9952 start
9953 };
9954 edits.push((insert_location..insert_location, text));
9955 } else {
9956 // duplicate character-wise
9957 let start = selection.start;
9958 let end = selection.end;
9959 let text = buffer.text_for_range(start..end).collect::<String>();
9960 edits.push((selection.end..selection.end, text));
9961 }
9962 }
9963
9964 self.transact(window, cx, |this, _, cx| {
9965 this.buffer.update(cx, |buffer, cx| {
9966 buffer.edit(edits, None, cx);
9967 });
9968
9969 this.request_autoscroll(Autoscroll::fit(), cx);
9970 });
9971 }
9972
9973 pub fn duplicate_line_up(
9974 &mut self,
9975 _: &DuplicateLineUp,
9976 window: &mut Window,
9977 cx: &mut Context<Self>,
9978 ) {
9979 self.duplicate(true, true, window, cx);
9980 }
9981
9982 pub fn duplicate_line_down(
9983 &mut self,
9984 _: &DuplicateLineDown,
9985 window: &mut Window,
9986 cx: &mut Context<Self>,
9987 ) {
9988 self.duplicate(false, true, window, cx);
9989 }
9990
9991 pub fn duplicate_selection(
9992 &mut self,
9993 _: &DuplicateSelection,
9994 window: &mut Window,
9995 cx: &mut Context<Self>,
9996 ) {
9997 self.duplicate(false, false, window, cx);
9998 }
9999
10000 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10001 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10002
10003 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10004 let buffer = self.buffer.read(cx).snapshot(cx);
10005
10006 let mut edits = Vec::new();
10007 let mut unfold_ranges = Vec::new();
10008 let mut refold_creases = Vec::new();
10009
10010 let selections = self.selections.all::<Point>(cx);
10011 let mut selections = selections.iter().peekable();
10012 let mut contiguous_row_selections = Vec::new();
10013 let mut new_selections = Vec::new();
10014
10015 while let Some(selection) = selections.next() {
10016 // Find all the selections that span a contiguous row range
10017 let (start_row, end_row) = consume_contiguous_rows(
10018 &mut contiguous_row_selections,
10019 selection,
10020 &display_map,
10021 &mut selections,
10022 );
10023
10024 // Move the text spanned by the row range to be before the line preceding the row range
10025 if start_row.0 > 0 {
10026 let range_to_move = Point::new(
10027 start_row.previous_row().0,
10028 buffer.line_len(start_row.previous_row()),
10029 )
10030 ..Point::new(
10031 end_row.previous_row().0,
10032 buffer.line_len(end_row.previous_row()),
10033 );
10034 let insertion_point = display_map
10035 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10036 .0;
10037
10038 // Don't move lines across excerpts
10039 if buffer
10040 .excerpt_containing(insertion_point..range_to_move.end)
10041 .is_some()
10042 {
10043 let text = buffer
10044 .text_for_range(range_to_move.clone())
10045 .flat_map(|s| s.chars())
10046 .skip(1)
10047 .chain(['\n'])
10048 .collect::<String>();
10049
10050 edits.push((
10051 buffer.anchor_after(range_to_move.start)
10052 ..buffer.anchor_before(range_to_move.end),
10053 String::new(),
10054 ));
10055 let insertion_anchor = buffer.anchor_after(insertion_point);
10056 edits.push((insertion_anchor..insertion_anchor, text));
10057
10058 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10059
10060 // Move selections up
10061 new_selections.extend(contiguous_row_selections.drain(..).map(
10062 |mut selection| {
10063 selection.start.row -= row_delta;
10064 selection.end.row -= row_delta;
10065 selection
10066 },
10067 ));
10068
10069 // Move folds up
10070 unfold_ranges.push(range_to_move.clone());
10071 for fold in display_map.folds_in_range(
10072 buffer.anchor_before(range_to_move.start)
10073 ..buffer.anchor_after(range_to_move.end),
10074 ) {
10075 let mut start = fold.range.start.to_point(&buffer);
10076 let mut end = fold.range.end.to_point(&buffer);
10077 start.row -= row_delta;
10078 end.row -= row_delta;
10079 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10080 }
10081 }
10082 }
10083
10084 // If we didn't move line(s), preserve the existing selections
10085 new_selections.append(&mut contiguous_row_selections);
10086 }
10087
10088 self.transact(window, cx, |this, window, cx| {
10089 this.unfold_ranges(&unfold_ranges, true, true, cx);
10090 this.buffer.update(cx, |buffer, cx| {
10091 for (range, text) in edits {
10092 buffer.edit([(range, text)], None, cx);
10093 }
10094 });
10095 this.fold_creases(refold_creases, true, window, cx);
10096 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10097 s.select(new_selections);
10098 })
10099 });
10100 }
10101
10102 pub fn move_line_down(
10103 &mut self,
10104 _: &MoveLineDown,
10105 window: &mut Window,
10106 cx: &mut Context<Self>,
10107 ) {
10108 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10109
10110 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10111 let buffer = self.buffer.read(cx).snapshot(cx);
10112
10113 let mut edits = Vec::new();
10114 let mut unfold_ranges = Vec::new();
10115 let mut refold_creases = Vec::new();
10116
10117 let selections = self.selections.all::<Point>(cx);
10118 let mut selections = selections.iter().peekable();
10119 let mut contiguous_row_selections = Vec::new();
10120 let mut new_selections = Vec::new();
10121
10122 while let Some(selection) = selections.next() {
10123 // Find all the selections that span a contiguous row range
10124 let (start_row, end_row) = consume_contiguous_rows(
10125 &mut contiguous_row_selections,
10126 selection,
10127 &display_map,
10128 &mut selections,
10129 );
10130
10131 // Move the text spanned by the row range to be after the last line of the row range
10132 if end_row.0 <= buffer.max_point().row {
10133 let range_to_move =
10134 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10135 let insertion_point = display_map
10136 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10137 .0;
10138
10139 // Don't move lines across excerpt boundaries
10140 if buffer
10141 .excerpt_containing(range_to_move.start..insertion_point)
10142 .is_some()
10143 {
10144 let mut text = String::from("\n");
10145 text.extend(buffer.text_for_range(range_to_move.clone()));
10146 text.pop(); // Drop trailing newline
10147 edits.push((
10148 buffer.anchor_after(range_to_move.start)
10149 ..buffer.anchor_before(range_to_move.end),
10150 String::new(),
10151 ));
10152 let insertion_anchor = buffer.anchor_after(insertion_point);
10153 edits.push((insertion_anchor..insertion_anchor, text));
10154
10155 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10156
10157 // Move selections down
10158 new_selections.extend(contiguous_row_selections.drain(..).map(
10159 |mut selection| {
10160 selection.start.row += row_delta;
10161 selection.end.row += row_delta;
10162 selection
10163 },
10164 ));
10165
10166 // Move folds down
10167 unfold_ranges.push(range_to_move.clone());
10168 for fold in display_map.folds_in_range(
10169 buffer.anchor_before(range_to_move.start)
10170 ..buffer.anchor_after(range_to_move.end),
10171 ) {
10172 let mut start = fold.range.start.to_point(&buffer);
10173 let mut end = fold.range.end.to_point(&buffer);
10174 start.row += row_delta;
10175 end.row += row_delta;
10176 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10177 }
10178 }
10179 }
10180
10181 // If we didn't move line(s), preserve the existing selections
10182 new_selections.append(&mut contiguous_row_selections);
10183 }
10184
10185 self.transact(window, cx, |this, window, cx| {
10186 this.unfold_ranges(&unfold_ranges, true, true, cx);
10187 this.buffer.update(cx, |buffer, cx| {
10188 for (range, text) in edits {
10189 buffer.edit([(range, text)], None, cx);
10190 }
10191 });
10192 this.fold_creases(refold_creases, true, window, cx);
10193 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10194 s.select(new_selections)
10195 });
10196 });
10197 }
10198
10199 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10200 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10201 let text_layout_details = &self.text_layout_details(window);
10202 self.transact(window, cx, |this, window, cx| {
10203 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10204 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10205 s.move_with(|display_map, selection| {
10206 if !selection.is_empty() {
10207 return;
10208 }
10209
10210 let mut head = selection.head();
10211 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10212 if head.column() == display_map.line_len(head.row()) {
10213 transpose_offset = display_map
10214 .buffer_snapshot
10215 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10216 }
10217
10218 if transpose_offset == 0 {
10219 return;
10220 }
10221
10222 *head.column_mut() += 1;
10223 head = display_map.clip_point(head, Bias::Right);
10224 let goal = SelectionGoal::HorizontalPosition(
10225 display_map
10226 .x_for_display_point(head, text_layout_details)
10227 .into(),
10228 );
10229 selection.collapse_to(head, goal);
10230
10231 let transpose_start = display_map
10232 .buffer_snapshot
10233 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10234 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10235 let transpose_end = display_map
10236 .buffer_snapshot
10237 .clip_offset(transpose_offset + 1, Bias::Right);
10238 if let Some(ch) =
10239 display_map.buffer_snapshot.chars_at(transpose_start).next()
10240 {
10241 edits.push((transpose_start..transpose_offset, String::new()));
10242 edits.push((transpose_end..transpose_end, ch.to_string()));
10243 }
10244 }
10245 });
10246 edits
10247 });
10248 this.buffer
10249 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10250 let selections = this.selections.all::<usize>(cx);
10251 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252 s.select(selections);
10253 });
10254 });
10255 }
10256
10257 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10258 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10259 self.rewrap_impl(RewrapOptions::default(), cx)
10260 }
10261
10262 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10263 let buffer = self.buffer.read(cx).snapshot(cx);
10264 let selections = self.selections.all::<Point>(cx);
10265 let mut selections = selections.iter().peekable();
10266
10267 let mut edits = Vec::new();
10268 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10269
10270 while let Some(selection) = selections.next() {
10271 let mut start_row = selection.start.row;
10272 let mut end_row = selection.end.row;
10273
10274 // Skip selections that overlap with a range that has already been rewrapped.
10275 let selection_range = start_row..end_row;
10276 if rewrapped_row_ranges
10277 .iter()
10278 .any(|range| range.overlaps(&selection_range))
10279 {
10280 continue;
10281 }
10282
10283 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10284
10285 // Since not all lines in the selection may be at the same indent
10286 // level, choose the indent size that is the most common between all
10287 // of the lines.
10288 //
10289 // If there is a tie, we use the deepest indent.
10290 let (indent_size, indent_end) = {
10291 let mut indent_size_occurrences = HashMap::default();
10292 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10293
10294 for row in start_row..=end_row {
10295 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10296 rows_by_indent_size.entry(indent).or_default().push(row);
10297 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10298 }
10299
10300 let indent_size = indent_size_occurrences
10301 .into_iter()
10302 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10303 .map(|(indent, _)| indent)
10304 .unwrap_or_default();
10305 let row = rows_by_indent_size[&indent_size][0];
10306 let indent_end = Point::new(row, indent_size.len);
10307
10308 (indent_size, indent_end)
10309 };
10310
10311 let mut line_prefix = indent_size.chars().collect::<String>();
10312
10313 let mut inside_comment = false;
10314 if let Some(comment_prefix) =
10315 buffer
10316 .language_scope_at(selection.head())
10317 .and_then(|language| {
10318 language
10319 .line_comment_prefixes()
10320 .iter()
10321 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10322 .cloned()
10323 })
10324 {
10325 line_prefix.push_str(&comment_prefix);
10326 inside_comment = true;
10327 }
10328
10329 let language_settings = buffer.language_settings_at(selection.head(), cx);
10330 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10331 RewrapBehavior::InComments => inside_comment,
10332 RewrapBehavior::InSelections => !selection.is_empty(),
10333 RewrapBehavior::Anywhere => true,
10334 };
10335
10336 let should_rewrap = options.override_language_settings
10337 || allow_rewrap_based_on_language
10338 || self.hard_wrap.is_some();
10339 if !should_rewrap {
10340 continue;
10341 }
10342
10343 if selection.is_empty() {
10344 'expand_upwards: while start_row > 0 {
10345 let prev_row = start_row - 1;
10346 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10347 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10348 {
10349 start_row = prev_row;
10350 } else {
10351 break 'expand_upwards;
10352 }
10353 }
10354
10355 'expand_downwards: while end_row < buffer.max_point().row {
10356 let next_row = end_row + 1;
10357 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10358 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10359 {
10360 end_row = next_row;
10361 } else {
10362 break 'expand_downwards;
10363 }
10364 }
10365 }
10366
10367 let start = Point::new(start_row, 0);
10368 let start_offset = start.to_offset(&buffer);
10369 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10370 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10371 let Some(lines_without_prefixes) = selection_text
10372 .lines()
10373 .map(|line| {
10374 line.strip_prefix(&line_prefix)
10375 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10376 .ok_or_else(|| {
10377 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10378 })
10379 })
10380 .collect::<Result<Vec<_>, _>>()
10381 .log_err()
10382 else {
10383 continue;
10384 };
10385
10386 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10387 buffer
10388 .language_settings_at(Point::new(start_row, 0), cx)
10389 .preferred_line_length as usize
10390 });
10391 let wrapped_text = wrap_with_prefix(
10392 line_prefix,
10393 lines_without_prefixes.join("\n"),
10394 wrap_column,
10395 tab_size,
10396 options.preserve_existing_whitespace,
10397 );
10398
10399 // TODO: should always use char-based diff while still supporting cursor behavior that
10400 // matches vim.
10401 let mut diff_options = DiffOptions::default();
10402 if options.override_language_settings {
10403 diff_options.max_word_diff_len = 0;
10404 diff_options.max_word_diff_line_count = 0;
10405 } else {
10406 diff_options.max_word_diff_len = usize::MAX;
10407 diff_options.max_word_diff_line_count = usize::MAX;
10408 }
10409
10410 for (old_range, new_text) in
10411 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10412 {
10413 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10414 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10415 edits.push((edit_start..edit_end, new_text));
10416 }
10417
10418 rewrapped_row_ranges.push(start_row..=end_row);
10419 }
10420
10421 self.buffer
10422 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10423 }
10424
10425 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10426 let mut text = String::new();
10427 let buffer = self.buffer.read(cx).snapshot(cx);
10428 let mut selections = self.selections.all::<Point>(cx);
10429 let mut clipboard_selections = Vec::with_capacity(selections.len());
10430 {
10431 let max_point = buffer.max_point();
10432 let mut is_first = true;
10433 for selection in &mut selections {
10434 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10435 if is_entire_line {
10436 selection.start = Point::new(selection.start.row, 0);
10437 if !selection.is_empty() && selection.end.column == 0 {
10438 selection.end = cmp::min(max_point, selection.end);
10439 } else {
10440 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10441 }
10442 selection.goal = SelectionGoal::None;
10443 }
10444 if is_first {
10445 is_first = false;
10446 } else {
10447 text += "\n";
10448 }
10449 let mut len = 0;
10450 for chunk in buffer.text_for_range(selection.start..selection.end) {
10451 text.push_str(chunk);
10452 len += chunk.len();
10453 }
10454 clipboard_selections.push(ClipboardSelection {
10455 len,
10456 is_entire_line,
10457 first_line_indent: buffer
10458 .indent_size_for_line(MultiBufferRow(selection.start.row))
10459 .len,
10460 });
10461 }
10462 }
10463
10464 self.transact(window, cx, |this, window, cx| {
10465 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10466 s.select(selections);
10467 });
10468 this.insert("", window, cx);
10469 });
10470 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10471 }
10472
10473 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10474 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10475 let item = self.cut_common(window, cx);
10476 cx.write_to_clipboard(item);
10477 }
10478
10479 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10480 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10481 self.change_selections(None, window, cx, |s| {
10482 s.move_with(|snapshot, sel| {
10483 if sel.is_empty() {
10484 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10485 }
10486 });
10487 });
10488 let item = self.cut_common(window, cx);
10489 cx.set_global(KillRing(item))
10490 }
10491
10492 pub fn kill_ring_yank(
10493 &mut self,
10494 _: &KillRingYank,
10495 window: &mut Window,
10496 cx: &mut Context<Self>,
10497 ) {
10498 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10499 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10500 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10501 (kill_ring.text().to_string(), kill_ring.metadata_json())
10502 } else {
10503 return;
10504 }
10505 } else {
10506 return;
10507 };
10508 self.do_paste(&text, metadata, false, window, cx);
10509 }
10510
10511 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10512 self.do_copy(true, cx);
10513 }
10514
10515 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10516 self.do_copy(false, cx);
10517 }
10518
10519 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10520 let selections = self.selections.all::<Point>(cx);
10521 let buffer = self.buffer.read(cx).read(cx);
10522 let mut text = String::new();
10523
10524 let mut clipboard_selections = Vec::with_capacity(selections.len());
10525 {
10526 let max_point = buffer.max_point();
10527 let mut is_first = true;
10528 for selection in &selections {
10529 let mut start = selection.start;
10530 let mut end = selection.end;
10531 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10532 if is_entire_line {
10533 start = Point::new(start.row, 0);
10534 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10535 }
10536
10537 let mut trimmed_selections = Vec::new();
10538 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10539 let row = MultiBufferRow(start.row);
10540 let first_indent = buffer.indent_size_for_line(row);
10541 if first_indent.len == 0 || start.column > first_indent.len {
10542 trimmed_selections.push(start..end);
10543 } else {
10544 trimmed_selections.push(
10545 Point::new(row.0, first_indent.len)
10546 ..Point::new(row.0, buffer.line_len(row)),
10547 );
10548 for row in start.row + 1..=end.row {
10549 let mut line_len = buffer.line_len(MultiBufferRow(row));
10550 if row == end.row {
10551 line_len = end.column;
10552 }
10553 if line_len == 0 {
10554 trimmed_selections
10555 .push(Point::new(row, 0)..Point::new(row, line_len));
10556 continue;
10557 }
10558 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10559 if row_indent_size.len >= first_indent.len {
10560 trimmed_selections.push(
10561 Point::new(row, first_indent.len)..Point::new(row, line_len),
10562 );
10563 } else {
10564 trimmed_selections.clear();
10565 trimmed_selections.push(start..end);
10566 break;
10567 }
10568 }
10569 }
10570 } else {
10571 trimmed_selections.push(start..end);
10572 }
10573
10574 for trimmed_range in trimmed_selections {
10575 if is_first {
10576 is_first = false;
10577 } else {
10578 text += "\n";
10579 }
10580 let mut len = 0;
10581 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10582 text.push_str(chunk);
10583 len += chunk.len();
10584 }
10585 clipboard_selections.push(ClipboardSelection {
10586 len,
10587 is_entire_line,
10588 first_line_indent: buffer
10589 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10590 .len,
10591 });
10592 }
10593 }
10594 }
10595
10596 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10597 text,
10598 clipboard_selections,
10599 ));
10600 }
10601
10602 pub fn do_paste(
10603 &mut self,
10604 text: &String,
10605 clipboard_selections: Option<Vec<ClipboardSelection>>,
10606 handle_entire_lines: bool,
10607 window: &mut Window,
10608 cx: &mut Context<Self>,
10609 ) {
10610 if self.read_only(cx) {
10611 return;
10612 }
10613
10614 let clipboard_text = Cow::Borrowed(text);
10615
10616 self.transact(window, cx, |this, window, cx| {
10617 if let Some(mut clipboard_selections) = clipboard_selections {
10618 let old_selections = this.selections.all::<usize>(cx);
10619 let all_selections_were_entire_line =
10620 clipboard_selections.iter().all(|s| s.is_entire_line);
10621 let first_selection_indent_column =
10622 clipboard_selections.first().map(|s| s.first_line_indent);
10623 if clipboard_selections.len() != old_selections.len() {
10624 clipboard_selections.drain(..);
10625 }
10626 let cursor_offset = this.selections.last::<usize>(cx).head();
10627 let mut auto_indent_on_paste = true;
10628
10629 this.buffer.update(cx, |buffer, cx| {
10630 let snapshot = buffer.read(cx);
10631 auto_indent_on_paste = snapshot
10632 .language_settings_at(cursor_offset, cx)
10633 .auto_indent_on_paste;
10634
10635 let mut start_offset = 0;
10636 let mut edits = Vec::new();
10637 let mut original_indent_columns = Vec::new();
10638 for (ix, selection) in old_selections.iter().enumerate() {
10639 let to_insert;
10640 let entire_line;
10641 let original_indent_column;
10642 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10643 let end_offset = start_offset + clipboard_selection.len;
10644 to_insert = &clipboard_text[start_offset..end_offset];
10645 entire_line = clipboard_selection.is_entire_line;
10646 start_offset = end_offset + 1;
10647 original_indent_column = Some(clipboard_selection.first_line_indent);
10648 } else {
10649 to_insert = clipboard_text.as_str();
10650 entire_line = all_selections_were_entire_line;
10651 original_indent_column = first_selection_indent_column
10652 }
10653
10654 // If the corresponding selection was empty when this slice of the
10655 // clipboard text was written, then the entire line containing the
10656 // selection was copied. If this selection is also currently empty,
10657 // then paste the line before the current line of the buffer.
10658 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10659 let column = selection.start.to_point(&snapshot).column as usize;
10660 let line_start = selection.start - column;
10661 line_start..line_start
10662 } else {
10663 selection.range()
10664 };
10665
10666 edits.push((range, to_insert));
10667 original_indent_columns.push(original_indent_column);
10668 }
10669 drop(snapshot);
10670
10671 buffer.edit(
10672 edits,
10673 if auto_indent_on_paste {
10674 Some(AutoindentMode::Block {
10675 original_indent_columns,
10676 })
10677 } else {
10678 None
10679 },
10680 cx,
10681 );
10682 });
10683
10684 let selections = this.selections.all::<usize>(cx);
10685 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686 s.select(selections)
10687 });
10688 } else {
10689 this.insert(&clipboard_text, window, cx);
10690 }
10691 });
10692 }
10693
10694 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10695 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10696 if let Some(item) = cx.read_from_clipboard() {
10697 let entries = item.entries();
10698
10699 match entries.first() {
10700 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10701 // of all the pasted entries.
10702 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10703 .do_paste(
10704 clipboard_string.text(),
10705 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10706 true,
10707 window,
10708 cx,
10709 ),
10710 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10711 }
10712 }
10713 }
10714
10715 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10716 if self.read_only(cx) {
10717 return;
10718 }
10719
10720 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10721
10722 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10723 if let Some((selections, _)) =
10724 self.selection_history.transaction(transaction_id).cloned()
10725 {
10726 self.change_selections(None, window, cx, |s| {
10727 s.select_anchors(selections.to_vec());
10728 });
10729 } else {
10730 log::error!(
10731 "No entry in selection_history found for undo. \
10732 This may correspond to a bug where undo does not update the selection. \
10733 If this is occurring, please add details to \
10734 https://github.com/zed-industries/zed/issues/22692"
10735 );
10736 }
10737 self.request_autoscroll(Autoscroll::fit(), cx);
10738 self.unmark_text(window, cx);
10739 self.refresh_inline_completion(true, false, window, cx);
10740 cx.emit(EditorEvent::Edited { transaction_id });
10741 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10742 }
10743 }
10744
10745 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10746 if self.read_only(cx) {
10747 return;
10748 }
10749
10750 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10751
10752 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10753 if let Some((_, Some(selections))) =
10754 self.selection_history.transaction(transaction_id).cloned()
10755 {
10756 self.change_selections(None, window, cx, |s| {
10757 s.select_anchors(selections.to_vec());
10758 });
10759 } else {
10760 log::error!(
10761 "No entry in selection_history found for redo. \
10762 This may correspond to a bug where undo does not update the selection. \
10763 If this is occurring, please add details to \
10764 https://github.com/zed-industries/zed/issues/22692"
10765 );
10766 }
10767 self.request_autoscroll(Autoscroll::fit(), cx);
10768 self.unmark_text(window, cx);
10769 self.refresh_inline_completion(true, false, window, cx);
10770 cx.emit(EditorEvent::Edited { transaction_id });
10771 }
10772 }
10773
10774 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10775 self.buffer
10776 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10777 }
10778
10779 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10780 self.buffer
10781 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10782 }
10783
10784 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10785 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10786 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10787 s.move_with(|map, selection| {
10788 let cursor = if selection.is_empty() {
10789 movement::left(map, selection.start)
10790 } else {
10791 selection.start
10792 };
10793 selection.collapse_to(cursor, SelectionGoal::None);
10794 });
10795 })
10796 }
10797
10798 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10799 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10800 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10801 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10802 })
10803 }
10804
10805 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10806 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10807 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10808 s.move_with(|map, selection| {
10809 let cursor = if selection.is_empty() {
10810 movement::right(map, selection.end)
10811 } else {
10812 selection.end
10813 };
10814 selection.collapse_to(cursor, SelectionGoal::None)
10815 });
10816 })
10817 }
10818
10819 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10820 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10822 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10823 })
10824 }
10825
10826 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10827 if self.take_rename(true, window, cx).is_some() {
10828 return;
10829 }
10830
10831 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10832 cx.propagate();
10833 return;
10834 }
10835
10836 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10837
10838 let text_layout_details = &self.text_layout_details(window);
10839 let selection_count = self.selections.count();
10840 let first_selection = self.selections.first_anchor();
10841
10842 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10843 s.move_with(|map, selection| {
10844 if !selection.is_empty() {
10845 selection.goal = SelectionGoal::None;
10846 }
10847 let (cursor, goal) = movement::up(
10848 map,
10849 selection.start,
10850 selection.goal,
10851 false,
10852 text_layout_details,
10853 );
10854 selection.collapse_to(cursor, goal);
10855 });
10856 });
10857
10858 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10859 {
10860 cx.propagate();
10861 }
10862 }
10863
10864 pub fn move_up_by_lines(
10865 &mut self,
10866 action: &MoveUpByLines,
10867 window: &mut Window,
10868 cx: &mut Context<Self>,
10869 ) {
10870 if self.take_rename(true, window, cx).is_some() {
10871 return;
10872 }
10873
10874 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10875 cx.propagate();
10876 return;
10877 }
10878
10879 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10880
10881 let text_layout_details = &self.text_layout_details(window);
10882
10883 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10884 s.move_with(|map, selection| {
10885 if !selection.is_empty() {
10886 selection.goal = SelectionGoal::None;
10887 }
10888 let (cursor, goal) = movement::up_by_rows(
10889 map,
10890 selection.start,
10891 action.lines,
10892 selection.goal,
10893 false,
10894 text_layout_details,
10895 );
10896 selection.collapse_to(cursor, goal);
10897 });
10898 })
10899 }
10900
10901 pub fn move_down_by_lines(
10902 &mut self,
10903 action: &MoveDownByLines,
10904 window: &mut Window,
10905 cx: &mut Context<Self>,
10906 ) {
10907 if self.take_rename(true, window, cx).is_some() {
10908 return;
10909 }
10910
10911 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10912 cx.propagate();
10913 return;
10914 }
10915
10916 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10917
10918 let text_layout_details = &self.text_layout_details(window);
10919
10920 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10921 s.move_with(|map, selection| {
10922 if !selection.is_empty() {
10923 selection.goal = SelectionGoal::None;
10924 }
10925 let (cursor, goal) = movement::down_by_rows(
10926 map,
10927 selection.start,
10928 action.lines,
10929 selection.goal,
10930 false,
10931 text_layout_details,
10932 );
10933 selection.collapse_to(cursor, goal);
10934 });
10935 })
10936 }
10937
10938 pub fn select_down_by_lines(
10939 &mut self,
10940 action: &SelectDownByLines,
10941 window: &mut Window,
10942 cx: &mut Context<Self>,
10943 ) {
10944 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10945 let text_layout_details = &self.text_layout_details(window);
10946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947 s.move_heads_with(|map, head, goal| {
10948 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10949 })
10950 })
10951 }
10952
10953 pub fn select_up_by_lines(
10954 &mut self,
10955 action: &SelectUpByLines,
10956 window: &mut Window,
10957 cx: &mut Context<Self>,
10958 ) {
10959 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10960 let text_layout_details = &self.text_layout_details(window);
10961 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10962 s.move_heads_with(|map, head, goal| {
10963 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10964 })
10965 })
10966 }
10967
10968 pub fn select_page_up(
10969 &mut self,
10970 _: &SelectPageUp,
10971 window: &mut Window,
10972 cx: &mut Context<Self>,
10973 ) {
10974 let Some(row_count) = self.visible_row_count() else {
10975 return;
10976 };
10977
10978 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10979
10980 let text_layout_details = &self.text_layout_details(window);
10981
10982 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10983 s.move_heads_with(|map, head, goal| {
10984 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10985 })
10986 })
10987 }
10988
10989 pub fn move_page_up(
10990 &mut self,
10991 action: &MovePageUp,
10992 window: &mut Window,
10993 cx: &mut Context<Self>,
10994 ) {
10995 if self.take_rename(true, window, cx).is_some() {
10996 return;
10997 }
10998
10999 if self
11000 .context_menu
11001 .borrow_mut()
11002 .as_mut()
11003 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11004 .unwrap_or(false)
11005 {
11006 return;
11007 }
11008
11009 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11010 cx.propagate();
11011 return;
11012 }
11013
11014 let Some(row_count) = self.visible_row_count() else {
11015 return;
11016 };
11017
11018 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11019
11020 let autoscroll = if action.center_cursor {
11021 Autoscroll::center()
11022 } else {
11023 Autoscroll::fit()
11024 };
11025
11026 let text_layout_details = &self.text_layout_details(window);
11027
11028 self.change_selections(Some(autoscroll), window, cx, |s| {
11029 s.move_with(|map, selection| {
11030 if !selection.is_empty() {
11031 selection.goal = SelectionGoal::None;
11032 }
11033 let (cursor, goal) = movement::up_by_rows(
11034 map,
11035 selection.end,
11036 row_count,
11037 selection.goal,
11038 false,
11039 text_layout_details,
11040 );
11041 selection.collapse_to(cursor, goal);
11042 });
11043 });
11044 }
11045
11046 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11047 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11048 let text_layout_details = &self.text_layout_details(window);
11049 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11050 s.move_heads_with(|map, head, goal| {
11051 movement::up(map, head, goal, false, text_layout_details)
11052 })
11053 })
11054 }
11055
11056 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11057 self.take_rename(true, window, cx);
11058
11059 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11060 cx.propagate();
11061 return;
11062 }
11063
11064 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11065
11066 let text_layout_details = &self.text_layout_details(window);
11067 let selection_count = self.selections.count();
11068 let first_selection = self.selections.first_anchor();
11069
11070 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11071 s.move_with(|map, selection| {
11072 if !selection.is_empty() {
11073 selection.goal = SelectionGoal::None;
11074 }
11075 let (cursor, goal) = movement::down(
11076 map,
11077 selection.end,
11078 selection.goal,
11079 false,
11080 text_layout_details,
11081 );
11082 selection.collapse_to(cursor, goal);
11083 });
11084 });
11085
11086 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11087 {
11088 cx.propagate();
11089 }
11090 }
11091
11092 pub fn select_page_down(
11093 &mut self,
11094 _: &SelectPageDown,
11095 window: &mut Window,
11096 cx: &mut Context<Self>,
11097 ) {
11098 let Some(row_count) = self.visible_row_count() else {
11099 return;
11100 };
11101
11102 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11103
11104 let text_layout_details = &self.text_layout_details(window);
11105
11106 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11107 s.move_heads_with(|map, head, goal| {
11108 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11109 })
11110 })
11111 }
11112
11113 pub fn move_page_down(
11114 &mut self,
11115 action: &MovePageDown,
11116 window: &mut Window,
11117 cx: &mut Context<Self>,
11118 ) {
11119 if self.take_rename(true, window, cx).is_some() {
11120 return;
11121 }
11122
11123 if self
11124 .context_menu
11125 .borrow_mut()
11126 .as_mut()
11127 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11128 .unwrap_or(false)
11129 {
11130 return;
11131 }
11132
11133 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11134 cx.propagate();
11135 return;
11136 }
11137
11138 let Some(row_count) = self.visible_row_count() else {
11139 return;
11140 };
11141
11142 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11143
11144 let autoscroll = if action.center_cursor {
11145 Autoscroll::center()
11146 } else {
11147 Autoscroll::fit()
11148 };
11149
11150 let text_layout_details = &self.text_layout_details(window);
11151 self.change_selections(Some(autoscroll), window, cx, |s| {
11152 s.move_with(|map, selection| {
11153 if !selection.is_empty() {
11154 selection.goal = SelectionGoal::None;
11155 }
11156 let (cursor, goal) = movement::down_by_rows(
11157 map,
11158 selection.end,
11159 row_count,
11160 selection.goal,
11161 false,
11162 text_layout_details,
11163 );
11164 selection.collapse_to(cursor, goal);
11165 });
11166 });
11167 }
11168
11169 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11170 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11171 let text_layout_details = &self.text_layout_details(window);
11172 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11173 s.move_heads_with(|map, head, goal| {
11174 movement::down(map, head, goal, false, text_layout_details)
11175 })
11176 });
11177 }
11178
11179 pub fn context_menu_first(
11180 &mut self,
11181 _: &ContextMenuFirst,
11182 _window: &mut Window,
11183 cx: &mut Context<Self>,
11184 ) {
11185 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11186 context_menu.select_first(self.completion_provider.as_deref(), cx);
11187 }
11188 }
11189
11190 pub fn context_menu_prev(
11191 &mut self,
11192 _: &ContextMenuPrevious,
11193 _window: &mut Window,
11194 cx: &mut Context<Self>,
11195 ) {
11196 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11197 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11198 }
11199 }
11200
11201 pub fn context_menu_next(
11202 &mut self,
11203 _: &ContextMenuNext,
11204 _window: &mut Window,
11205 cx: &mut Context<Self>,
11206 ) {
11207 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11208 context_menu.select_next(self.completion_provider.as_deref(), cx);
11209 }
11210 }
11211
11212 pub fn context_menu_last(
11213 &mut self,
11214 _: &ContextMenuLast,
11215 _window: &mut Window,
11216 cx: &mut Context<Self>,
11217 ) {
11218 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11219 context_menu.select_last(self.completion_provider.as_deref(), cx);
11220 }
11221 }
11222
11223 pub fn move_to_previous_word_start(
11224 &mut self,
11225 _: &MoveToPreviousWordStart,
11226 window: &mut Window,
11227 cx: &mut Context<Self>,
11228 ) {
11229 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11230 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11231 s.move_cursors_with(|map, head, _| {
11232 (
11233 movement::previous_word_start(map, head),
11234 SelectionGoal::None,
11235 )
11236 });
11237 })
11238 }
11239
11240 pub fn move_to_previous_subword_start(
11241 &mut self,
11242 _: &MoveToPreviousSubwordStart,
11243 window: &mut Window,
11244 cx: &mut Context<Self>,
11245 ) {
11246 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11247 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11248 s.move_cursors_with(|map, head, _| {
11249 (
11250 movement::previous_subword_start(map, head),
11251 SelectionGoal::None,
11252 )
11253 });
11254 })
11255 }
11256
11257 pub fn select_to_previous_word_start(
11258 &mut self,
11259 _: &SelectToPreviousWordStart,
11260 window: &mut Window,
11261 cx: &mut Context<Self>,
11262 ) {
11263 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11264 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11265 s.move_heads_with(|map, head, _| {
11266 (
11267 movement::previous_word_start(map, head),
11268 SelectionGoal::None,
11269 )
11270 });
11271 })
11272 }
11273
11274 pub fn select_to_previous_subword_start(
11275 &mut self,
11276 _: &SelectToPreviousSubwordStart,
11277 window: &mut Window,
11278 cx: &mut Context<Self>,
11279 ) {
11280 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11282 s.move_heads_with(|map, head, _| {
11283 (
11284 movement::previous_subword_start(map, head),
11285 SelectionGoal::None,
11286 )
11287 });
11288 })
11289 }
11290
11291 pub fn delete_to_previous_word_start(
11292 &mut self,
11293 action: &DeleteToPreviousWordStart,
11294 window: &mut Window,
11295 cx: &mut Context<Self>,
11296 ) {
11297 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11298 self.transact(window, cx, |this, window, cx| {
11299 this.select_autoclose_pair(window, cx);
11300 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11301 s.move_with(|map, selection| {
11302 if selection.is_empty() {
11303 let cursor = if action.ignore_newlines {
11304 movement::previous_word_start(map, selection.head())
11305 } else {
11306 movement::previous_word_start_or_newline(map, selection.head())
11307 };
11308 selection.set_head(cursor, SelectionGoal::None);
11309 }
11310 });
11311 });
11312 this.insert("", window, cx);
11313 });
11314 }
11315
11316 pub fn delete_to_previous_subword_start(
11317 &mut self,
11318 _: &DeleteToPreviousSubwordStart,
11319 window: &mut Window,
11320 cx: &mut Context<Self>,
11321 ) {
11322 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11323 self.transact(window, cx, |this, window, cx| {
11324 this.select_autoclose_pair(window, cx);
11325 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326 s.move_with(|map, selection| {
11327 if selection.is_empty() {
11328 let cursor = movement::previous_subword_start(map, selection.head());
11329 selection.set_head(cursor, SelectionGoal::None);
11330 }
11331 });
11332 });
11333 this.insert("", window, cx);
11334 });
11335 }
11336
11337 pub fn move_to_next_word_end(
11338 &mut self,
11339 _: &MoveToNextWordEnd,
11340 window: &mut Window,
11341 cx: &mut Context<Self>,
11342 ) {
11343 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11344 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11345 s.move_cursors_with(|map, head, _| {
11346 (movement::next_word_end(map, head), SelectionGoal::None)
11347 });
11348 })
11349 }
11350
11351 pub fn move_to_next_subword_end(
11352 &mut self,
11353 _: &MoveToNextSubwordEnd,
11354 window: &mut Window,
11355 cx: &mut Context<Self>,
11356 ) {
11357 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11358 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11359 s.move_cursors_with(|map, head, _| {
11360 (movement::next_subword_end(map, head), SelectionGoal::None)
11361 });
11362 })
11363 }
11364
11365 pub fn select_to_next_word_end(
11366 &mut self,
11367 _: &SelectToNextWordEnd,
11368 window: &mut Window,
11369 cx: &mut Context<Self>,
11370 ) {
11371 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11373 s.move_heads_with(|map, head, _| {
11374 (movement::next_word_end(map, head), SelectionGoal::None)
11375 });
11376 })
11377 }
11378
11379 pub fn select_to_next_subword_end(
11380 &mut self,
11381 _: &SelectToNextSubwordEnd,
11382 window: &mut Window,
11383 cx: &mut Context<Self>,
11384 ) {
11385 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11386 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11387 s.move_heads_with(|map, head, _| {
11388 (movement::next_subword_end(map, head), SelectionGoal::None)
11389 });
11390 })
11391 }
11392
11393 pub fn delete_to_next_word_end(
11394 &mut self,
11395 action: &DeleteToNextWordEnd,
11396 window: &mut Window,
11397 cx: &mut Context<Self>,
11398 ) {
11399 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11400 self.transact(window, cx, |this, window, cx| {
11401 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11402 s.move_with(|map, selection| {
11403 if selection.is_empty() {
11404 let cursor = if action.ignore_newlines {
11405 movement::next_word_end(map, selection.head())
11406 } else {
11407 movement::next_word_end_or_newline(map, selection.head())
11408 };
11409 selection.set_head(cursor, SelectionGoal::None);
11410 }
11411 });
11412 });
11413 this.insert("", window, cx);
11414 });
11415 }
11416
11417 pub fn delete_to_next_subword_end(
11418 &mut self,
11419 _: &DeleteToNextSubwordEnd,
11420 window: &mut Window,
11421 cx: &mut Context<Self>,
11422 ) {
11423 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11424 self.transact(window, cx, |this, window, cx| {
11425 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11426 s.move_with(|map, selection| {
11427 if selection.is_empty() {
11428 let cursor = movement::next_subword_end(map, selection.head());
11429 selection.set_head(cursor, SelectionGoal::None);
11430 }
11431 });
11432 });
11433 this.insert("", window, cx);
11434 });
11435 }
11436
11437 pub fn move_to_beginning_of_line(
11438 &mut self,
11439 action: &MoveToBeginningOfLine,
11440 window: &mut Window,
11441 cx: &mut Context<Self>,
11442 ) {
11443 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11445 s.move_cursors_with(|map, head, _| {
11446 (
11447 movement::indented_line_beginning(
11448 map,
11449 head,
11450 action.stop_at_soft_wraps,
11451 action.stop_at_indent,
11452 ),
11453 SelectionGoal::None,
11454 )
11455 });
11456 })
11457 }
11458
11459 pub fn select_to_beginning_of_line(
11460 &mut self,
11461 action: &SelectToBeginningOfLine,
11462 window: &mut Window,
11463 cx: &mut Context<Self>,
11464 ) {
11465 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11466 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11467 s.move_heads_with(|map, head, _| {
11468 (
11469 movement::indented_line_beginning(
11470 map,
11471 head,
11472 action.stop_at_soft_wraps,
11473 action.stop_at_indent,
11474 ),
11475 SelectionGoal::None,
11476 )
11477 });
11478 });
11479 }
11480
11481 pub fn delete_to_beginning_of_line(
11482 &mut self,
11483 action: &DeleteToBeginningOfLine,
11484 window: &mut Window,
11485 cx: &mut Context<Self>,
11486 ) {
11487 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11488 self.transact(window, cx, |this, window, cx| {
11489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11490 s.move_with(|_, selection| {
11491 selection.reversed = true;
11492 });
11493 });
11494
11495 this.select_to_beginning_of_line(
11496 &SelectToBeginningOfLine {
11497 stop_at_soft_wraps: false,
11498 stop_at_indent: action.stop_at_indent,
11499 },
11500 window,
11501 cx,
11502 );
11503 this.backspace(&Backspace, window, cx);
11504 });
11505 }
11506
11507 pub fn move_to_end_of_line(
11508 &mut self,
11509 action: &MoveToEndOfLine,
11510 window: &mut Window,
11511 cx: &mut Context<Self>,
11512 ) {
11513 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11514 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11515 s.move_cursors_with(|map, head, _| {
11516 (
11517 movement::line_end(map, head, action.stop_at_soft_wraps),
11518 SelectionGoal::None,
11519 )
11520 });
11521 })
11522 }
11523
11524 pub fn select_to_end_of_line(
11525 &mut self,
11526 action: &SelectToEndOfLine,
11527 window: &mut Window,
11528 cx: &mut Context<Self>,
11529 ) {
11530 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11531 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11532 s.move_heads_with(|map, head, _| {
11533 (
11534 movement::line_end(map, head, action.stop_at_soft_wraps),
11535 SelectionGoal::None,
11536 )
11537 });
11538 })
11539 }
11540
11541 pub fn delete_to_end_of_line(
11542 &mut self,
11543 _: &DeleteToEndOfLine,
11544 window: &mut Window,
11545 cx: &mut Context<Self>,
11546 ) {
11547 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11548 self.transact(window, cx, |this, window, cx| {
11549 this.select_to_end_of_line(
11550 &SelectToEndOfLine {
11551 stop_at_soft_wraps: false,
11552 },
11553 window,
11554 cx,
11555 );
11556 this.delete(&Delete, window, cx);
11557 });
11558 }
11559
11560 pub fn cut_to_end_of_line(
11561 &mut self,
11562 _: &CutToEndOfLine,
11563 window: &mut Window,
11564 cx: &mut Context<Self>,
11565 ) {
11566 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11567 self.transact(window, cx, |this, window, cx| {
11568 this.select_to_end_of_line(
11569 &SelectToEndOfLine {
11570 stop_at_soft_wraps: false,
11571 },
11572 window,
11573 cx,
11574 );
11575 this.cut(&Cut, window, cx);
11576 });
11577 }
11578
11579 pub fn move_to_start_of_paragraph(
11580 &mut self,
11581 _: &MoveToStartOfParagraph,
11582 window: &mut Window,
11583 cx: &mut Context<Self>,
11584 ) {
11585 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11586 cx.propagate();
11587 return;
11588 }
11589 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11590 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11591 s.move_with(|map, selection| {
11592 selection.collapse_to(
11593 movement::start_of_paragraph(map, selection.head(), 1),
11594 SelectionGoal::None,
11595 )
11596 });
11597 })
11598 }
11599
11600 pub fn move_to_end_of_paragraph(
11601 &mut self,
11602 _: &MoveToEndOfParagraph,
11603 window: &mut Window,
11604 cx: &mut Context<Self>,
11605 ) {
11606 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11607 cx.propagate();
11608 return;
11609 }
11610 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11611 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11612 s.move_with(|map, selection| {
11613 selection.collapse_to(
11614 movement::end_of_paragraph(map, selection.head(), 1),
11615 SelectionGoal::None,
11616 )
11617 });
11618 })
11619 }
11620
11621 pub fn select_to_start_of_paragraph(
11622 &mut self,
11623 _: &SelectToStartOfParagraph,
11624 window: &mut Window,
11625 cx: &mut Context<Self>,
11626 ) {
11627 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11628 cx.propagate();
11629 return;
11630 }
11631 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11632 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11633 s.move_heads_with(|map, head, _| {
11634 (
11635 movement::start_of_paragraph(map, head, 1),
11636 SelectionGoal::None,
11637 )
11638 });
11639 })
11640 }
11641
11642 pub fn select_to_end_of_paragraph(
11643 &mut self,
11644 _: &SelectToEndOfParagraph,
11645 window: &mut Window,
11646 cx: &mut Context<Self>,
11647 ) {
11648 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11649 cx.propagate();
11650 return;
11651 }
11652 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11653 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11654 s.move_heads_with(|map, head, _| {
11655 (
11656 movement::end_of_paragraph(map, head, 1),
11657 SelectionGoal::None,
11658 )
11659 });
11660 })
11661 }
11662
11663 pub fn move_to_start_of_excerpt(
11664 &mut self,
11665 _: &MoveToStartOfExcerpt,
11666 window: &mut Window,
11667 cx: &mut Context<Self>,
11668 ) {
11669 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11670 cx.propagate();
11671 return;
11672 }
11673 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11674 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11675 s.move_with(|map, selection| {
11676 selection.collapse_to(
11677 movement::start_of_excerpt(
11678 map,
11679 selection.head(),
11680 workspace::searchable::Direction::Prev,
11681 ),
11682 SelectionGoal::None,
11683 )
11684 });
11685 })
11686 }
11687
11688 pub fn move_to_start_of_next_excerpt(
11689 &mut self,
11690 _: &MoveToStartOfNextExcerpt,
11691 window: &mut Window,
11692 cx: &mut Context<Self>,
11693 ) {
11694 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11695 cx.propagate();
11696 return;
11697 }
11698
11699 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11700 s.move_with(|map, selection| {
11701 selection.collapse_to(
11702 movement::start_of_excerpt(
11703 map,
11704 selection.head(),
11705 workspace::searchable::Direction::Next,
11706 ),
11707 SelectionGoal::None,
11708 )
11709 });
11710 })
11711 }
11712
11713 pub fn move_to_end_of_excerpt(
11714 &mut self,
11715 _: &MoveToEndOfExcerpt,
11716 window: &mut Window,
11717 cx: &mut Context<Self>,
11718 ) {
11719 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11720 cx.propagate();
11721 return;
11722 }
11723 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11724 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11725 s.move_with(|map, selection| {
11726 selection.collapse_to(
11727 movement::end_of_excerpt(
11728 map,
11729 selection.head(),
11730 workspace::searchable::Direction::Next,
11731 ),
11732 SelectionGoal::None,
11733 )
11734 });
11735 })
11736 }
11737
11738 pub fn move_to_end_of_previous_excerpt(
11739 &mut self,
11740 _: &MoveToEndOfPreviousExcerpt,
11741 window: &mut Window,
11742 cx: &mut Context<Self>,
11743 ) {
11744 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11745 cx.propagate();
11746 return;
11747 }
11748 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11749 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11750 s.move_with(|map, selection| {
11751 selection.collapse_to(
11752 movement::end_of_excerpt(
11753 map,
11754 selection.head(),
11755 workspace::searchable::Direction::Prev,
11756 ),
11757 SelectionGoal::None,
11758 )
11759 });
11760 })
11761 }
11762
11763 pub fn select_to_start_of_excerpt(
11764 &mut self,
11765 _: &SelectToStartOfExcerpt,
11766 window: &mut Window,
11767 cx: &mut Context<Self>,
11768 ) {
11769 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11770 cx.propagate();
11771 return;
11772 }
11773 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11774 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11775 s.move_heads_with(|map, head, _| {
11776 (
11777 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11778 SelectionGoal::None,
11779 )
11780 });
11781 })
11782 }
11783
11784 pub fn select_to_start_of_next_excerpt(
11785 &mut self,
11786 _: &SelectToStartOfNextExcerpt,
11787 window: &mut Window,
11788 cx: &mut Context<Self>,
11789 ) {
11790 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11791 cx.propagate();
11792 return;
11793 }
11794 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11795 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11796 s.move_heads_with(|map, head, _| {
11797 (
11798 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11799 SelectionGoal::None,
11800 )
11801 });
11802 })
11803 }
11804
11805 pub fn select_to_end_of_excerpt(
11806 &mut self,
11807 _: &SelectToEndOfExcerpt,
11808 window: &mut Window,
11809 cx: &mut Context<Self>,
11810 ) {
11811 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11812 cx.propagate();
11813 return;
11814 }
11815 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11816 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11817 s.move_heads_with(|map, head, _| {
11818 (
11819 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11820 SelectionGoal::None,
11821 )
11822 });
11823 })
11824 }
11825
11826 pub fn select_to_end_of_previous_excerpt(
11827 &mut self,
11828 _: &SelectToEndOfPreviousExcerpt,
11829 window: &mut Window,
11830 cx: &mut Context<Self>,
11831 ) {
11832 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11833 cx.propagate();
11834 return;
11835 }
11836 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11838 s.move_heads_with(|map, head, _| {
11839 (
11840 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11841 SelectionGoal::None,
11842 )
11843 });
11844 })
11845 }
11846
11847 pub fn move_to_beginning(
11848 &mut self,
11849 _: &MoveToBeginning,
11850 window: &mut Window,
11851 cx: &mut Context<Self>,
11852 ) {
11853 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11854 cx.propagate();
11855 return;
11856 }
11857 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11858 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11859 s.select_ranges(vec![0..0]);
11860 });
11861 }
11862
11863 pub fn select_to_beginning(
11864 &mut self,
11865 _: &SelectToBeginning,
11866 window: &mut Window,
11867 cx: &mut Context<Self>,
11868 ) {
11869 let mut selection = self.selections.last::<Point>(cx);
11870 selection.set_head(Point::zero(), SelectionGoal::None);
11871 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11872 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11873 s.select(vec![selection]);
11874 });
11875 }
11876
11877 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11878 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11879 cx.propagate();
11880 return;
11881 }
11882 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11883 let cursor = self.buffer.read(cx).read(cx).len();
11884 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11885 s.select_ranges(vec![cursor..cursor])
11886 });
11887 }
11888
11889 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11890 self.nav_history = nav_history;
11891 }
11892
11893 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11894 self.nav_history.as_ref()
11895 }
11896
11897 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11898 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11899 }
11900
11901 fn push_to_nav_history(
11902 &mut self,
11903 cursor_anchor: Anchor,
11904 new_position: Option<Point>,
11905 is_deactivate: bool,
11906 cx: &mut Context<Self>,
11907 ) {
11908 if let Some(nav_history) = self.nav_history.as_mut() {
11909 let buffer = self.buffer.read(cx).read(cx);
11910 let cursor_position = cursor_anchor.to_point(&buffer);
11911 let scroll_state = self.scroll_manager.anchor();
11912 let scroll_top_row = scroll_state.top_row(&buffer);
11913 drop(buffer);
11914
11915 if let Some(new_position) = new_position {
11916 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11917 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11918 return;
11919 }
11920 }
11921
11922 nav_history.push(
11923 Some(NavigationData {
11924 cursor_anchor,
11925 cursor_position,
11926 scroll_anchor: scroll_state,
11927 scroll_top_row,
11928 }),
11929 cx,
11930 );
11931 cx.emit(EditorEvent::PushedToNavHistory {
11932 anchor: cursor_anchor,
11933 is_deactivate,
11934 })
11935 }
11936 }
11937
11938 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11939 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11940 let buffer = self.buffer.read(cx).snapshot(cx);
11941 let mut selection = self.selections.first::<usize>(cx);
11942 selection.set_head(buffer.len(), SelectionGoal::None);
11943 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11944 s.select(vec![selection]);
11945 });
11946 }
11947
11948 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11949 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11950 let end = self.buffer.read(cx).read(cx).len();
11951 self.change_selections(None, window, cx, |s| {
11952 s.select_ranges(vec![0..end]);
11953 });
11954 }
11955
11956 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11957 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11958 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11959 let mut selections = self.selections.all::<Point>(cx);
11960 let max_point = display_map.buffer_snapshot.max_point();
11961 for selection in &mut selections {
11962 let rows = selection.spanned_rows(true, &display_map);
11963 selection.start = Point::new(rows.start.0, 0);
11964 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11965 selection.reversed = false;
11966 }
11967 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11968 s.select(selections);
11969 });
11970 }
11971
11972 pub fn split_selection_into_lines(
11973 &mut self,
11974 _: &SplitSelectionIntoLines,
11975 window: &mut Window,
11976 cx: &mut Context<Self>,
11977 ) {
11978 let selections = self
11979 .selections
11980 .all::<Point>(cx)
11981 .into_iter()
11982 .map(|selection| selection.start..selection.end)
11983 .collect::<Vec<_>>();
11984 self.unfold_ranges(&selections, true, true, cx);
11985
11986 let mut new_selection_ranges = Vec::new();
11987 {
11988 let buffer = self.buffer.read(cx).read(cx);
11989 for selection in selections {
11990 for row in selection.start.row..selection.end.row {
11991 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11992 new_selection_ranges.push(cursor..cursor);
11993 }
11994
11995 let is_multiline_selection = selection.start.row != selection.end.row;
11996 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11997 // so this action feels more ergonomic when paired with other selection operations
11998 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11999 if !should_skip_last {
12000 new_selection_ranges.push(selection.end..selection.end);
12001 }
12002 }
12003 }
12004 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12005 s.select_ranges(new_selection_ranges);
12006 });
12007 }
12008
12009 pub fn add_selection_above(
12010 &mut self,
12011 _: &AddSelectionAbove,
12012 window: &mut Window,
12013 cx: &mut Context<Self>,
12014 ) {
12015 self.add_selection(true, window, cx);
12016 }
12017
12018 pub fn add_selection_below(
12019 &mut self,
12020 _: &AddSelectionBelow,
12021 window: &mut Window,
12022 cx: &mut Context<Self>,
12023 ) {
12024 self.add_selection(false, window, cx);
12025 }
12026
12027 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12028 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12029
12030 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12031 let mut selections = self.selections.all::<Point>(cx);
12032 let text_layout_details = self.text_layout_details(window);
12033 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12034 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12035 let range = oldest_selection.display_range(&display_map).sorted();
12036
12037 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12038 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12039 let positions = start_x.min(end_x)..start_x.max(end_x);
12040
12041 selections.clear();
12042 let mut stack = Vec::new();
12043 for row in range.start.row().0..=range.end.row().0 {
12044 if let Some(selection) = self.selections.build_columnar_selection(
12045 &display_map,
12046 DisplayRow(row),
12047 &positions,
12048 oldest_selection.reversed,
12049 &text_layout_details,
12050 ) {
12051 stack.push(selection.id);
12052 selections.push(selection);
12053 }
12054 }
12055
12056 if above {
12057 stack.reverse();
12058 }
12059
12060 AddSelectionsState { above, stack }
12061 });
12062
12063 let last_added_selection = *state.stack.last().unwrap();
12064 let mut new_selections = Vec::new();
12065 if above == state.above {
12066 let end_row = if above {
12067 DisplayRow(0)
12068 } else {
12069 display_map.max_point().row()
12070 };
12071
12072 'outer: for selection in selections {
12073 if selection.id == last_added_selection {
12074 let range = selection.display_range(&display_map).sorted();
12075 debug_assert_eq!(range.start.row(), range.end.row());
12076 let mut row = range.start.row();
12077 let positions =
12078 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12079 px(start)..px(end)
12080 } else {
12081 let start_x =
12082 display_map.x_for_display_point(range.start, &text_layout_details);
12083 let end_x =
12084 display_map.x_for_display_point(range.end, &text_layout_details);
12085 start_x.min(end_x)..start_x.max(end_x)
12086 };
12087
12088 while row != end_row {
12089 if above {
12090 row.0 -= 1;
12091 } else {
12092 row.0 += 1;
12093 }
12094
12095 if let Some(new_selection) = self.selections.build_columnar_selection(
12096 &display_map,
12097 row,
12098 &positions,
12099 selection.reversed,
12100 &text_layout_details,
12101 ) {
12102 state.stack.push(new_selection.id);
12103 if above {
12104 new_selections.push(new_selection);
12105 new_selections.push(selection);
12106 } else {
12107 new_selections.push(selection);
12108 new_selections.push(new_selection);
12109 }
12110
12111 continue 'outer;
12112 }
12113 }
12114 }
12115
12116 new_selections.push(selection);
12117 }
12118 } else {
12119 new_selections = selections;
12120 new_selections.retain(|s| s.id != last_added_selection);
12121 state.stack.pop();
12122 }
12123
12124 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12125 s.select(new_selections);
12126 });
12127 if state.stack.len() > 1 {
12128 self.add_selections_state = Some(state);
12129 }
12130 }
12131
12132 pub fn select_next_match_internal(
12133 &mut self,
12134 display_map: &DisplaySnapshot,
12135 replace_newest: bool,
12136 autoscroll: Option<Autoscroll>,
12137 window: &mut Window,
12138 cx: &mut Context<Self>,
12139 ) -> Result<()> {
12140 fn select_next_match_ranges(
12141 this: &mut Editor,
12142 range: Range<usize>,
12143 reversed: bool,
12144 replace_newest: bool,
12145 auto_scroll: Option<Autoscroll>,
12146 window: &mut Window,
12147 cx: &mut Context<Editor>,
12148 ) {
12149 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12150 this.change_selections(auto_scroll, window, cx, |s| {
12151 if replace_newest {
12152 s.delete(s.newest_anchor().id);
12153 }
12154 if reversed {
12155 s.insert_range(range.end..range.start);
12156 } else {
12157 s.insert_range(range);
12158 }
12159 });
12160 }
12161
12162 let buffer = &display_map.buffer_snapshot;
12163 let mut selections = self.selections.all::<usize>(cx);
12164 if let Some(mut select_next_state) = self.select_next_state.take() {
12165 let query = &select_next_state.query;
12166 if !select_next_state.done {
12167 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12168 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12169 let mut next_selected_range = None;
12170
12171 let bytes_after_last_selection =
12172 buffer.bytes_in_range(last_selection.end..buffer.len());
12173 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12174 let query_matches = query
12175 .stream_find_iter(bytes_after_last_selection)
12176 .map(|result| (last_selection.end, result))
12177 .chain(
12178 query
12179 .stream_find_iter(bytes_before_first_selection)
12180 .map(|result| (0, result)),
12181 );
12182
12183 for (start_offset, query_match) in query_matches {
12184 let query_match = query_match.unwrap(); // can only fail due to I/O
12185 let offset_range =
12186 start_offset + query_match.start()..start_offset + query_match.end();
12187 let display_range = offset_range.start.to_display_point(display_map)
12188 ..offset_range.end.to_display_point(display_map);
12189
12190 if !select_next_state.wordwise
12191 || (!movement::is_inside_word(display_map, display_range.start)
12192 && !movement::is_inside_word(display_map, display_range.end))
12193 {
12194 // TODO: This is n^2, because we might check all the selections
12195 if !selections
12196 .iter()
12197 .any(|selection| selection.range().overlaps(&offset_range))
12198 {
12199 next_selected_range = Some(offset_range);
12200 break;
12201 }
12202 }
12203 }
12204
12205 if let Some(next_selected_range) = next_selected_range {
12206 select_next_match_ranges(
12207 self,
12208 next_selected_range,
12209 last_selection.reversed,
12210 replace_newest,
12211 autoscroll,
12212 window,
12213 cx,
12214 );
12215 } else {
12216 select_next_state.done = true;
12217 }
12218 }
12219
12220 self.select_next_state = Some(select_next_state);
12221 } else {
12222 let mut only_carets = true;
12223 let mut same_text_selected = true;
12224 let mut selected_text = None;
12225
12226 let mut selections_iter = selections.iter().peekable();
12227 while let Some(selection) = selections_iter.next() {
12228 if selection.start != selection.end {
12229 only_carets = false;
12230 }
12231
12232 if same_text_selected {
12233 if selected_text.is_none() {
12234 selected_text =
12235 Some(buffer.text_for_range(selection.range()).collect::<String>());
12236 }
12237
12238 if let Some(next_selection) = selections_iter.peek() {
12239 if next_selection.range().len() == selection.range().len() {
12240 let next_selected_text = buffer
12241 .text_for_range(next_selection.range())
12242 .collect::<String>();
12243 if Some(next_selected_text) != selected_text {
12244 same_text_selected = false;
12245 selected_text = None;
12246 }
12247 } else {
12248 same_text_selected = false;
12249 selected_text = None;
12250 }
12251 }
12252 }
12253 }
12254
12255 if only_carets {
12256 for selection in &mut selections {
12257 let word_range = movement::surrounding_word(
12258 display_map,
12259 selection.start.to_display_point(display_map),
12260 );
12261 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12262 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12263 selection.goal = SelectionGoal::None;
12264 selection.reversed = false;
12265 select_next_match_ranges(
12266 self,
12267 selection.start..selection.end,
12268 selection.reversed,
12269 replace_newest,
12270 autoscroll,
12271 window,
12272 cx,
12273 );
12274 }
12275
12276 if selections.len() == 1 {
12277 let selection = selections
12278 .last()
12279 .expect("ensured that there's only one selection");
12280 let query = buffer
12281 .text_for_range(selection.start..selection.end)
12282 .collect::<String>();
12283 let is_empty = query.is_empty();
12284 let select_state = SelectNextState {
12285 query: AhoCorasick::new(&[query])?,
12286 wordwise: true,
12287 done: is_empty,
12288 };
12289 self.select_next_state = Some(select_state);
12290 } else {
12291 self.select_next_state = None;
12292 }
12293 } else if let Some(selected_text) = selected_text {
12294 self.select_next_state = Some(SelectNextState {
12295 query: AhoCorasick::new(&[selected_text])?,
12296 wordwise: false,
12297 done: false,
12298 });
12299 self.select_next_match_internal(
12300 display_map,
12301 replace_newest,
12302 autoscroll,
12303 window,
12304 cx,
12305 )?;
12306 }
12307 }
12308 Ok(())
12309 }
12310
12311 pub fn select_all_matches(
12312 &mut self,
12313 _action: &SelectAllMatches,
12314 window: &mut Window,
12315 cx: &mut Context<Self>,
12316 ) -> Result<()> {
12317 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12318
12319 self.push_to_selection_history();
12320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12321
12322 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12323 let Some(select_next_state) = self.select_next_state.as_mut() else {
12324 return Ok(());
12325 };
12326 if select_next_state.done {
12327 return Ok(());
12328 }
12329
12330 let mut new_selections = Vec::new();
12331
12332 let reversed = self.selections.oldest::<usize>(cx).reversed;
12333 let buffer = &display_map.buffer_snapshot;
12334 let query_matches = select_next_state
12335 .query
12336 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12337
12338 for query_match in query_matches.into_iter() {
12339 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12340 let offset_range = if reversed {
12341 query_match.end()..query_match.start()
12342 } else {
12343 query_match.start()..query_match.end()
12344 };
12345 let display_range = offset_range.start.to_display_point(&display_map)
12346 ..offset_range.end.to_display_point(&display_map);
12347
12348 if !select_next_state.wordwise
12349 || (!movement::is_inside_word(&display_map, display_range.start)
12350 && !movement::is_inside_word(&display_map, display_range.end))
12351 {
12352 new_selections.push(offset_range.start..offset_range.end);
12353 }
12354 }
12355
12356 select_next_state.done = true;
12357 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12358 self.change_selections(None, window, cx, |selections| {
12359 selections.select_ranges(new_selections)
12360 });
12361
12362 Ok(())
12363 }
12364
12365 pub fn select_next(
12366 &mut self,
12367 action: &SelectNext,
12368 window: &mut Window,
12369 cx: &mut Context<Self>,
12370 ) -> Result<()> {
12371 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12372 self.push_to_selection_history();
12373 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12374 self.select_next_match_internal(
12375 &display_map,
12376 action.replace_newest,
12377 Some(Autoscroll::newest()),
12378 window,
12379 cx,
12380 )?;
12381 Ok(())
12382 }
12383
12384 pub fn select_previous(
12385 &mut self,
12386 action: &SelectPrevious,
12387 window: &mut Window,
12388 cx: &mut Context<Self>,
12389 ) -> Result<()> {
12390 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12391 self.push_to_selection_history();
12392 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12393 let buffer = &display_map.buffer_snapshot;
12394 let mut selections = self.selections.all::<usize>(cx);
12395 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12396 let query = &select_prev_state.query;
12397 if !select_prev_state.done {
12398 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12399 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12400 let mut next_selected_range = None;
12401 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12402 let bytes_before_last_selection =
12403 buffer.reversed_bytes_in_range(0..last_selection.start);
12404 let bytes_after_first_selection =
12405 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12406 let query_matches = query
12407 .stream_find_iter(bytes_before_last_selection)
12408 .map(|result| (last_selection.start, result))
12409 .chain(
12410 query
12411 .stream_find_iter(bytes_after_first_selection)
12412 .map(|result| (buffer.len(), result)),
12413 );
12414 for (end_offset, query_match) in query_matches {
12415 let query_match = query_match.unwrap(); // can only fail due to I/O
12416 let offset_range =
12417 end_offset - query_match.end()..end_offset - query_match.start();
12418 let display_range = offset_range.start.to_display_point(&display_map)
12419 ..offset_range.end.to_display_point(&display_map);
12420
12421 if !select_prev_state.wordwise
12422 || (!movement::is_inside_word(&display_map, display_range.start)
12423 && !movement::is_inside_word(&display_map, display_range.end))
12424 {
12425 next_selected_range = Some(offset_range);
12426 break;
12427 }
12428 }
12429
12430 if let Some(next_selected_range) = next_selected_range {
12431 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12432 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12433 if action.replace_newest {
12434 s.delete(s.newest_anchor().id);
12435 }
12436 if last_selection.reversed {
12437 s.insert_range(next_selected_range.end..next_selected_range.start);
12438 } else {
12439 s.insert_range(next_selected_range);
12440 }
12441 });
12442 } else {
12443 select_prev_state.done = true;
12444 }
12445 }
12446
12447 self.select_prev_state = Some(select_prev_state);
12448 } else {
12449 let mut only_carets = true;
12450 let mut same_text_selected = true;
12451 let mut selected_text = None;
12452
12453 let mut selections_iter = selections.iter().peekable();
12454 while let Some(selection) = selections_iter.next() {
12455 if selection.start != selection.end {
12456 only_carets = false;
12457 }
12458
12459 if same_text_selected {
12460 if selected_text.is_none() {
12461 selected_text =
12462 Some(buffer.text_for_range(selection.range()).collect::<String>());
12463 }
12464
12465 if let Some(next_selection) = selections_iter.peek() {
12466 if next_selection.range().len() == selection.range().len() {
12467 let next_selected_text = buffer
12468 .text_for_range(next_selection.range())
12469 .collect::<String>();
12470 if Some(next_selected_text) != selected_text {
12471 same_text_selected = false;
12472 selected_text = None;
12473 }
12474 } else {
12475 same_text_selected = false;
12476 selected_text = None;
12477 }
12478 }
12479 }
12480 }
12481
12482 if only_carets {
12483 for selection in &mut selections {
12484 let word_range = movement::surrounding_word(
12485 &display_map,
12486 selection.start.to_display_point(&display_map),
12487 );
12488 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12489 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12490 selection.goal = SelectionGoal::None;
12491 selection.reversed = false;
12492 }
12493 if selections.len() == 1 {
12494 let selection = selections
12495 .last()
12496 .expect("ensured that there's only one selection");
12497 let query = buffer
12498 .text_for_range(selection.start..selection.end)
12499 .collect::<String>();
12500 let is_empty = query.is_empty();
12501 let select_state = SelectNextState {
12502 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12503 wordwise: true,
12504 done: is_empty,
12505 };
12506 self.select_prev_state = Some(select_state);
12507 } else {
12508 self.select_prev_state = None;
12509 }
12510
12511 self.unfold_ranges(
12512 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12513 false,
12514 true,
12515 cx,
12516 );
12517 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12518 s.select(selections);
12519 });
12520 } else if let Some(selected_text) = selected_text {
12521 self.select_prev_state = Some(SelectNextState {
12522 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12523 wordwise: false,
12524 done: false,
12525 });
12526 self.select_previous(action, window, cx)?;
12527 }
12528 }
12529 Ok(())
12530 }
12531
12532 pub fn find_next_match(
12533 &mut self,
12534 _: &FindNextMatch,
12535 window: &mut Window,
12536 cx: &mut Context<Self>,
12537 ) -> Result<()> {
12538 let selections = self.selections.disjoint_anchors();
12539 match selections.first() {
12540 Some(first) if selections.len() >= 2 => {
12541 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12542 s.select_ranges([first.range()]);
12543 });
12544 }
12545 _ => self.select_next(
12546 &SelectNext {
12547 replace_newest: true,
12548 },
12549 window,
12550 cx,
12551 )?,
12552 }
12553 Ok(())
12554 }
12555
12556 pub fn find_previous_match(
12557 &mut self,
12558 _: &FindPreviousMatch,
12559 window: &mut Window,
12560 cx: &mut Context<Self>,
12561 ) -> Result<()> {
12562 let selections = self.selections.disjoint_anchors();
12563 match selections.last() {
12564 Some(last) if selections.len() >= 2 => {
12565 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12566 s.select_ranges([last.range()]);
12567 });
12568 }
12569 _ => self.select_previous(
12570 &SelectPrevious {
12571 replace_newest: true,
12572 },
12573 window,
12574 cx,
12575 )?,
12576 }
12577 Ok(())
12578 }
12579
12580 pub fn toggle_comments(
12581 &mut self,
12582 action: &ToggleComments,
12583 window: &mut Window,
12584 cx: &mut Context<Self>,
12585 ) {
12586 if self.read_only(cx) {
12587 return;
12588 }
12589 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12590 let text_layout_details = &self.text_layout_details(window);
12591 self.transact(window, cx, |this, window, cx| {
12592 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12593 let mut edits = Vec::new();
12594 let mut selection_edit_ranges = Vec::new();
12595 let mut last_toggled_row = None;
12596 let snapshot = this.buffer.read(cx).read(cx);
12597 let empty_str: Arc<str> = Arc::default();
12598 let mut suffixes_inserted = Vec::new();
12599 let ignore_indent = action.ignore_indent;
12600
12601 fn comment_prefix_range(
12602 snapshot: &MultiBufferSnapshot,
12603 row: MultiBufferRow,
12604 comment_prefix: &str,
12605 comment_prefix_whitespace: &str,
12606 ignore_indent: bool,
12607 ) -> Range<Point> {
12608 let indent_size = if ignore_indent {
12609 0
12610 } else {
12611 snapshot.indent_size_for_line(row).len
12612 };
12613
12614 let start = Point::new(row.0, indent_size);
12615
12616 let mut line_bytes = snapshot
12617 .bytes_in_range(start..snapshot.max_point())
12618 .flatten()
12619 .copied();
12620
12621 // If this line currently begins with the line comment prefix, then record
12622 // the range containing the prefix.
12623 if line_bytes
12624 .by_ref()
12625 .take(comment_prefix.len())
12626 .eq(comment_prefix.bytes())
12627 {
12628 // Include any whitespace that matches the comment prefix.
12629 let matching_whitespace_len = line_bytes
12630 .zip(comment_prefix_whitespace.bytes())
12631 .take_while(|(a, b)| a == b)
12632 .count() as u32;
12633 let end = Point::new(
12634 start.row,
12635 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12636 );
12637 start..end
12638 } else {
12639 start..start
12640 }
12641 }
12642
12643 fn comment_suffix_range(
12644 snapshot: &MultiBufferSnapshot,
12645 row: MultiBufferRow,
12646 comment_suffix: &str,
12647 comment_suffix_has_leading_space: bool,
12648 ) -> Range<Point> {
12649 let end = Point::new(row.0, snapshot.line_len(row));
12650 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12651
12652 let mut line_end_bytes = snapshot
12653 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12654 .flatten()
12655 .copied();
12656
12657 let leading_space_len = if suffix_start_column > 0
12658 && line_end_bytes.next() == Some(b' ')
12659 && comment_suffix_has_leading_space
12660 {
12661 1
12662 } else {
12663 0
12664 };
12665
12666 // If this line currently begins with the line comment prefix, then record
12667 // the range containing the prefix.
12668 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12669 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12670 start..end
12671 } else {
12672 end..end
12673 }
12674 }
12675
12676 // TODO: Handle selections that cross excerpts
12677 for selection in &mut selections {
12678 let start_column = snapshot
12679 .indent_size_for_line(MultiBufferRow(selection.start.row))
12680 .len;
12681 let language = if let Some(language) =
12682 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12683 {
12684 language
12685 } else {
12686 continue;
12687 };
12688
12689 selection_edit_ranges.clear();
12690
12691 // If multiple selections contain a given row, avoid processing that
12692 // row more than once.
12693 let mut start_row = MultiBufferRow(selection.start.row);
12694 if last_toggled_row == Some(start_row) {
12695 start_row = start_row.next_row();
12696 }
12697 let end_row =
12698 if selection.end.row > selection.start.row && selection.end.column == 0 {
12699 MultiBufferRow(selection.end.row - 1)
12700 } else {
12701 MultiBufferRow(selection.end.row)
12702 };
12703 last_toggled_row = Some(end_row);
12704
12705 if start_row > end_row {
12706 continue;
12707 }
12708
12709 // If the language has line comments, toggle those.
12710 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12711
12712 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12713 if ignore_indent {
12714 full_comment_prefixes = full_comment_prefixes
12715 .into_iter()
12716 .map(|s| Arc::from(s.trim_end()))
12717 .collect();
12718 }
12719
12720 if !full_comment_prefixes.is_empty() {
12721 let first_prefix = full_comment_prefixes
12722 .first()
12723 .expect("prefixes is non-empty");
12724 let prefix_trimmed_lengths = full_comment_prefixes
12725 .iter()
12726 .map(|p| p.trim_end_matches(' ').len())
12727 .collect::<SmallVec<[usize; 4]>>();
12728
12729 let mut all_selection_lines_are_comments = true;
12730
12731 for row in start_row.0..=end_row.0 {
12732 let row = MultiBufferRow(row);
12733 if start_row < end_row && snapshot.is_line_blank(row) {
12734 continue;
12735 }
12736
12737 let prefix_range = full_comment_prefixes
12738 .iter()
12739 .zip(prefix_trimmed_lengths.iter().copied())
12740 .map(|(prefix, trimmed_prefix_len)| {
12741 comment_prefix_range(
12742 snapshot.deref(),
12743 row,
12744 &prefix[..trimmed_prefix_len],
12745 &prefix[trimmed_prefix_len..],
12746 ignore_indent,
12747 )
12748 })
12749 .max_by_key(|range| range.end.column - range.start.column)
12750 .expect("prefixes is non-empty");
12751
12752 if prefix_range.is_empty() {
12753 all_selection_lines_are_comments = false;
12754 }
12755
12756 selection_edit_ranges.push(prefix_range);
12757 }
12758
12759 if all_selection_lines_are_comments {
12760 edits.extend(
12761 selection_edit_ranges
12762 .iter()
12763 .cloned()
12764 .map(|range| (range, empty_str.clone())),
12765 );
12766 } else {
12767 let min_column = selection_edit_ranges
12768 .iter()
12769 .map(|range| range.start.column)
12770 .min()
12771 .unwrap_or(0);
12772 edits.extend(selection_edit_ranges.iter().map(|range| {
12773 let position = Point::new(range.start.row, min_column);
12774 (position..position, first_prefix.clone())
12775 }));
12776 }
12777 } else if let Some((full_comment_prefix, comment_suffix)) =
12778 language.block_comment_delimiters()
12779 {
12780 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12781 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12782 let prefix_range = comment_prefix_range(
12783 snapshot.deref(),
12784 start_row,
12785 comment_prefix,
12786 comment_prefix_whitespace,
12787 ignore_indent,
12788 );
12789 let suffix_range = comment_suffix_range(
12790 snapshot.deref(),
12791 end_row,
12792 comment_suffix.trim_start_matches(' '),
12793 comment_suffix.starts_with(' '),
12794 );
12795
12796 if prefix_range.is_empty() || suffix_range.is_empty() {
12797 edits.push((
12798 prefix_range.start..prefix_range.start,
12799 full_comment_prefix.clone(),
12800 ));
12801 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12802 suffixes_inserted.push((end_row, comment_suffix.len()));
12803 } else {
12804 edits.push((prefix_range, empty_str.clone()));
12805 edits.push((suffix_range, empty_str.clone()));
12806 }
12807 } else {
12808 continue;
12809 }
12810 }
12811
12812 drop(snapshot);
12813 this.buffer.update(cx, |buffer, cx| {
12814 buffer.edit(edits, None, cx);
12815 });
12816
12817 // Adjust selections so that they end before any comment suffixes that
12818 // were inserted.
12819 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12820 let mut selections = this.selections.all::<Point>(cx);
12821 let snapshot = this.buffer.read(cx).read(cx);
12822 for selection in &mut selections {
12823 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12824 match row.cmp(&MultiBufferRow(selection.end.row)) {
12825 Ordering::Less => {
12826 suffixes_inserted.next();
12827 continue;
12828 }
12829 Ordering::Greater => break,
12830 Ordering::Equal => {
12831 if selection.end.column == snapshot.line_len(row) {
12832 if selection.is_empty() {
12833 selection.start.column -= suffix_len as u32;
12834 }
12835 selection.end.column -= suffix_len as u32;
12836 }
12837 break;
12838 }
12839 }
12840 }
12841 }
12842
12843 drop(snapshot);
12844 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12845 s.select(selections)
12846 });
12847
12848 let selections = this.selections.all::<Point>(cx);
12849 let selections_on_single_row = selections.windows(2).all(|selections| {
12850 selections[0].start.row == selections[1].start.row
12851 && selections[0].end.row == selections[1].end.row
12852 && selections[0].start.row == selections[0].end.row
12853 });
12854 let selections_selecting = selections
12855 .iter()
12856 .any(|selection| selection.start != selection.end);
12857 let advance_downwards = action.advance_downwards
12858 && selections_on_single_row
12859 && !selections_selecting
12860 && !matches!(this.mode, EditorMode::SingleLine { .. });
12861
12862 if advance_downwards {
12863 let snapshot = this.buffer.read(cx).snapshot(cx);
12864
12865 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12866 s.move_cursors_with(|display_snapshot, display_point, _| {
12867 let mut point = display_point.to_point(display_snapshot);
12868 point.row += 1;
12869 point = snapshot.clip_point(point, Bias::Left);
12870 let display_point = point.to_display_point(display_snapshot);
12871 let goal = SelectionGoal::HorizontalPosition(
12872 display_snapshot
12873 .x_for_display_point(display_point, text_layout_details)
12874 .into(),
12875 );
12876 (display_point, goal)
12877 })
12878 });
12879 }
12880 });
12881 }
12882
12883 pub fn select_enclosing_symbol(
12884 &mut self,
12885 _: &SelectEnclosingSymbol,
12886 window: &mut Window,
12887 cx: &mut Context<Self>,
12888 ) {
12889 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12890
12891 let buffer = self.buffer.read(cx).snapshot(cx);
12892 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12893
12894 fn update_selection(
12895 selection: &Selection<usize>,
12896 buffer_snap: &MultiBufferSnapshot,
12897 ) -> Option<Selection<usize>> {
12898 let cursor = selection.head();
12899 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12900 for symbol in symbols.iter().rev() {
12901 let start = symbol.range.start.to_offset(buffer_snap);
12902 let end = symbol.range.end.to_offset(buffer_snap);
12903 let new_range = start..end;
12904 if start < selection.start || end > selection.end {
12905 return Some(Selection {
12906 id: selection.id,
12907 start: new_range.start,
12908 end: new_range.end,
12909 goal: SelectionGoal::None,
12910 reversed: selection.reversed,
12911 });
12912 }
12913 }
12914 None
12915 }
12916
12917 let mut selected_larger_symbol = false;
12918 let new_selections = old_selections
12919 .iter()
12920 .map(|selection| match update_selection(selection, &buffer) {
12921 Some(new_selection) => {
12922 if new_selection.range() != selection.range() {
12923 selected_larger_symbol = true;
12924 }
12925 new_selection
12926 }
12927 None => selection.clone(),
12928 })
12929 .collect::<Vec<_>>();
12930
12931 if selected_larger_symbol {
12932 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12933 s.select(new_selections);
12934 });
12935 }
12936 }
12937
12938 pub fn select_larger_syntax_node(
12939 &mut self,
12940 _: &SelectLargerSyntaxNode,
12941 window: &mut Window,
12942 cx: &mut Context<Self>,
12943 ) {
12944 let Some(visible_row_count) = self.visible_row_count() else {
12945 return;
12946 };
12947 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12948 if old_selections.is_empty() {
12949 return;
12950 }
12951
12952 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12953
12954 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12955 let buffer = self.buffer.read(cx).snapshot(cx);
12956
12957 let mut selected_larger_node = false;
12958 let mut new_selections = old_selections
12959 .iter()
12960 .map(|selection| {
12961 let old_range = selection.start..selection.end;
12962
12963 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12964 // manually select word at selection
12965 if ["string_content", "inline"].contains(&node.kind()) {
12966 let word_range = {
12967 let display_point = buffer
12968 .offset_to_point(old_range.start)
12969 .to_display_point(&display_map);
12970 let Range { start, end } =
12971 movement::surrounding_word(&display_map, display_point);
12972 start.to_point(&display_map).to_offset(&buffer)
12973 ..end.to_point(&display_map).to_offset(&buffer)
12974 };
12975 // ignore if word is already selected
12976 if !word_range.is_empty() && old_range != word_range {
12977 let last_word_range = {
12978 let display_point = buffer
12979 .offset_to_point(old_range.end)
12980 .to_display_point(&display_map);
12981 let Range { start, end } =
12982 movement::surrounding_word(&display_map, display_point);
12983 start.to_point(&display_map).to_offset(&buffer)
12984 ..end.to_point(&display_map).to_offset(&buffer)
12985 };
12986 // only select word if start and end point belongs to same word
12987 if word_range == last_word_range {
12988 selected_larger_node = true;
12989 return Selection {
12990 id: selection.id,
12991 start: word_range.start,
12992 end: word_range.end,
12993 goal: SelectionGoal::None,
12994 reversed: selection.reversed,
12995 };
12996 }
12997 }
12998 }
12999 }
13000
13001 let mut new_range = old_range.clone();
13002 let mut new_node = None;
13003 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
13004 {
13005 new_node = Some(node);
13006 new_range = match containing_range {
13007 MultiOrSingleBufferOffsetRange::Single(_) => break,
13008 MultiOrSingleBufferOffsetRange::Multi(range) => range,
13009 };
13010 if !display_map.intersects_fold(new_range.start)
13011 && !display_map.intersects_fold(new_range.end)
13012 {
13013 break;
13014 }
13015 }
13016
13017 if let Some(node) = new_node {
13018 // Log the ancestor, to support using this action as a way to explore TreeSitter
13019 // nodes. Parent and grandparent are also logged because this operation will not
13020 // visit nodes that have the same range as their parent.
13021 log::info!("Node: {node:?}");
13022 let parent = node.parent();
13023 log::info!("Parent: {parent:?}");
13024 let grandparent = parent.and_then(|x| x.parent());
13025 log::info!("Grandparent: {grandparent:?}");
13026 }
13027
13028 selected_larger_node |= new_range != old_range;
13029 Selection {
13030 id: selection.id,
13031 start: new_range.start,
13032 end: new_range.end,
13033 goal: SelectionGoal::None,
13034 reversed: selection.reversed,
13035 }
13036 })
13037 .collect::<Vec<_>>();
13038
13039 if !selected_larger_node {
13040 return; // don't put this call in the history
13041 }
13042
13043 // scroll based on transformation done to the last selection created by the user
13044 let (last_old, last_new) = old_selections
13045 .last()
13046 .zip(new_selections.last().cloned())
13047 .expect("old_selections isn't empty");
13048
13049 // revert selection
13050 let is_selection_reversed = {
13051 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13052 new_selections.last_mut().expect("checked above").reversed =
13053 should_newest_selection_be_reversed;
13054 should_newest_selection_be_reversed
13055 };
13056
13057 if selected_larger_node {
13058 self.select_syntax_node_history.disable_clearing = true;
13059 self.change_selections(None, window, cx, |s| {
13060 s.select(new_selections.clone());
13061 });
13062 self.select_syntax_node_history.disable_clearing = false;
13063 }
13064
13065 let start_row = last_new.start.to_display_point(&display_map).row().0;
13066 let end_row = last_new.end.to_display_point(&display_map).row().0;
13067 let selection_height = end_row - start_row + 1;
13068 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13069
13070 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13071 let scroll_behavior = if fits_on_the_screen {
13072 self.request_autoscroll(Autoscroll::fit(), cx);
13073 SelectSyntaxNodeScrollBehavior::FitSelection
13074 } else if is_selection_reversed {
13075 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13076 SelectSyntaxNodeScrollBehavior::CursorTop
13077 } else {
13078 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13079 SelectSyntaxNodeScrollBehavior::CursorBottom
13080 };
13081
13082 self.select_syntax_node_history.push((
13083 old_selections,
13084 scroll_behavior,
13085 is_selection_reversed,
13086 ));
13087 }
13088
13089 pub fn select_smaller_syntax_node(
13090 &mut self,
13091 _: &SelectSmallerSyntaxNode,
13092 window: &mut Window,
13093 cx: &mut Context<Self>,
13094 ) {
13095 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13096
13097 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13098 self.select_syntax_node_history.pop()
13099 {
13100 if let Some(selection) = selections.last_mut() {
13101 selection.reversed = is_selection_reversed;
13102 }
13103
13104 self.select_syntax_node_history.disable_clearing = true;
13105 self.change_selections(None, window, cx, |s| {
13106 s.select(selections.to_vec());
13107 });
13108 self.select_syntax_node_history.disable_clearing = false;
13109
13110 match scroll_behavior {
13111 SelectSyntaxNodeScrollBehavior::CursorTop => {
13112 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13113 }
13114 SelectSyntaxNodeScrollBehavior::FitSelection => {
13115 self.request_autoscroll(Autoscroll::fit(), cx);
13116 }
13117 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13118 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13119 }
13120 }
13121 }
13122 }
13123
13124 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13125 if !EditorSettings::get_global(cx).gutter.runnables {
13126 self.clear_tasks();
13127 return Task::ready(());
13128 }
13129 let project = self.project.as_ref().map(Entity::downgrade);
13130 let task_sources = self.lsp_task_sources(cx);
13131 cx.spawn_in(window, async move |editor, cx| {
13132 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13133 let Some(project) = project.and_then(|p| p.upgrade()) else {
13134 return;
13135 };
13136 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13137 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13138 }) else {
13139 return;
13140 };
13141
13142 let hide_runnables = project
13143 .update(cx, |project, cx| {
13144 // Do not display any test indicators in non-dev server remote projects.
13145 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13146 })
13147 .unwrap_or(true);
13148 if hide_runnables {
13149 return;
13150 }
13151 let new_rows =
13152 cx.background_spawn({
13153 let snapshot = display_snapshot.clone();
13154 async move {
13155 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13156 }
13157 })
13158 .await;
13159 let Ok(lsp_tasks) =
13160 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13161 else {
13162 return;
13163 };
13164 let lsp_tasks = lsp_tasks.await;
13165
13166 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13167 lsp_tasks
13168 .into_iter()
13169 .flat_map(|(kind, tasks)| {
13170 tasks.into_iter().filter_map(move |(location, task)| {
13171 Some((kind.clone(), location?, task))
13172 })
13173 })
13174 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13175 let buffer = location.target.buffer;
13176 let buffer_snapshot = buffer.read(cx).snapshot();
13177 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13178 |(excerpt_id, snapshot, _)| {
13179 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13180 display_snapshot
13181 .buffer_snapshot
13182 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13183 } else {
13184 None
13185 }
13186 },
13187 );
13188 if let Some(offset) = offset {
13189 let task_buffer_range =
13190 location.target.range.to_point(&buffer_snapshot);
13191 let context_buffer_range =
13192 task_buffer_range.to_offset(&buffer_snapshot);
13193 let context_range = BufferOffset(context_buffer_range.start)
13194 ..BufferOffset(context_buffer_range.end);
13195
13196 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13197 .or_insert_with(|| RunnableTasks {
13198 templates: Vec::new(),
13199 offset,
13200 column: task_buffer_range.start.column,
13201 extra_variables: HashMap::default(),
13202 context_range,
13203 })
13204 .templates
13205 .push((kind, task.original_task().clone()));
13206 }
13207
13208 acc
13209 })
13210 }) else {
13211 return;
13212 };
13213
13214 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13215 editor
13216 .update(cx, |editor, _| {
13217 editor.clear_tasks();
13218 for (key, mut value) in rows {
13219 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13220 value.templates.extend(lsp_tasks.templates);
13221 }
13222
13223 editor.insert_tasks(key, value);
13224 }
13225 for (key, value) in lsp_tasks_by_rows {
13226 editor.insert_tasks(key, value);
13227 }
13228 })
13229 .ok();
13230 })
13231 }
13232 fn fetch_runnable_ranges(
13233 snapshot: &DisplaySnapshot,
13234 range: Range<Anchor>,
13235 ) -> Vec<language::RunnableRange> {
13236 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13237 }
13238
13239 fn runnable_rows(
13240 project: Entity<Project>,
13241 snapshot: DisplaySnapshot,
13242 runnable_ranges: Vec<RunnableRange>,
13243 mut cx: AsyncWindowContext,
13244 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13245 runnable_ranges
13246 .into_iter()
13247 .filter_map(|mut runnable| {
13248 let tasks = cx
13249 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13250 .ok()?;
13251 if tasks.is_empty() {
13252 return None;
13253 }
13254
13255 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13256
13257 let row = snapshot
13258 .buffer_snapshot
13259 .buffer_line_for_row(MultiBufferRow(point.row))?
13260 .1
13261 .start
13262 .row;
13263
13264 let context_range =
13265 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13266 Some((
13267 (runnable.buffer_id, row),
13268 RunnableTasks {
13269 templates: tasks,
13270 offset: snapshot
13271 .buffer_snapshot
13272 .anchor_before(runnable.run_range.start),
13273 context_range,
13274 column: point.column,
13275 extra_variables: runnable.extra_captures,
13276 },
13277 ))
13278 })
13279 .collect()
13280 }
13281
13282 fn templates_with_tags(
13283 project: &Entity<Project>,
13284 runnable: &mut Runnable,
13285 cx: &mut App,
13286 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13287 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13288 let (worktree_id, file) = project
13289 .buffer_for_id(runnable.buffer, cx)
13290 .and_then(|buffer| buffer.read(cx).file())
13291 .map(|file| (file.worktree_id(cx), file.clone()))
13292 .unzip();
13293
13294 (
13295 project.task_store().read(cx).task_inventory().cloned(),
13296 worktree_id,
13297 file,
13298 )
13299 });
13300
13301 let mut templates_with_tags = mem::take(&mut runnable.tags)
13302 .into_iter()
13303 .flat_map(|RunnableTag(tag)| {
13304 inventory
13305 .as_ref()
13306 .into_iter()
13307 .flat_map(|inventory| {
13308 inventory.read(cx).list_tasks(
13309 file.clone(),
13310 Some(runnable.language.clone()),
13311 worktree_id,
13312 cx,
13313 )
13314 })
13315 .filter(move |(_, template)| {
13316 template.tags.iter().any(|source_tag| source_tag == &tag)
13317 })
13318 })
13319 .sorted_by_key(|(kind, _)| kind.to_owned())
13320 .collect::<Vec<_>>();
13321 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13322 // Strongest source wins; if we have worktree tag binding, prefer that to
13323 // global and language bindings;
13324 // if we have a global binding, prefer that to language binding.
13325 let first_mismatch = templates_with_tags
13326 .iter()
13327 .position(|(tag_source, _)| tag_source != leading_tag_source);
13328 if let Some(index) = first_mismatch {
13329 templates_with_tags.truncate(index);
13330 }
13331 }
13332
13333 templates_with_tags
13334 }
13335
13336 pub fn move_to_enclosing_bracket(
13337 &mut self,
13338 _: &MoveToEnclosingBracket,
13339 window: &mut Window,
13340 cx: &mut Context<Self>,
13341 ) {
13342 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13343 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13344 s.move_offsets_with(|snapshot, selection| {
13345 let Some(enclosing_bracket_ranges) =
13346 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13347 else {
13348 return;
13349 };
13350
13351 let mut best_length = usize::MAX;
13352 let mut best_inside = false;
13353 let mut best_in_bracket_range = false;
13354 let mut best_destination = None;
13355 for (open, close) in enclosing_bracket_ranges {
13356 let close = close.to_inclusive();
13357 let length = close.end() - open.start;
13358 let inside = selection.start >= open.end && selection.end <= *close.start();
13359 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13360 || close.contains(&selection.head());
13361
13362 // If best is next to a bracket and current isn't, skip
13363 if !in_bracket_range && best_in_bracket_range {
13364 continue;
13365 }
13366
13367 // Prefer smaller lengths unless best is inside and current isn't
13368 if length > best_length && (best_inside || !inside) {
13369 continue;
13370 }
13371
13372 best_length = length;
13373 best_inside = inside;
13374 best_in_bracket_range = in_bracket_range;
13375 best_destination = Some(
13376 if close.contains(&selection.start) && close.contains(&selection.end) {
13377 if inside { open.end } else { open.start }
13378 } else if inside {
13379 *close.start()
13380 } else {
13381 *close.end()
13382 },
13383 );
13384 }
13385
13386 if let Some(destination) = best_destination {
13387 selection.collapse_to(destination, SelectionGoal::None);
13388 }
13389 })
13390 });
13391 }
13392
13393 pub fn undo_selection(
13394 &mut self,
13395 _: &UndoSelection,
13396 window: &mut Window,
13397 cx: &mut Context<Self>,
13398 ) {
13399 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13400 self.end_selection(window, cx);
13401 self.selection_history.mode = SelectionHistoryMode::Undoing;
13402 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13403 self.change_selections(None, window, cx, |s| {
13404 s.select_anchors(entry.selections.to_vec())
13405 });
13406 self.select_next_state = entry.select_next_state;
13407 self.select_prev_state = entry.select_prev_state;
13408 self.add_selections_state = entry.add_selections_state;
13409 self.request_autoscroll(Autoscroll::newest(), cx);
13410 }
13411 self.selection_history.mode = SelectionHistoryMode::Normal;
13412 }
13413
13414 pub fn redo_selection(
13415 &mut self,
13416 _: &RedoSelection,
13417 window: &mut Window,
13418 cx: &mut Context<Self>,
13419 ) {
13420 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13421 self.end_selection(window, cx);
13422 self.selection_history.mode = SelectionHistoryMode::Redoing;
13423 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13424 self.change_selections(None, window, cx, |s| {
13425 s.select_anchors(entry.selections.to_vec())
13426 });
13427 self.select_next_state = entry.select_next_state;
13428 self.select_prev_state = entry.select_prev_state;
13429 self.add_selections_state = entry.add_selections_state;
13430 self.request_autoscroll(Autoscroll::newest(), cx);
13431 }
13432 self.selection_history.mode = SelectionHistoryMode::Normal;
13433 }
13434
13435 pub fn expand_excerpts(
13436 &mut self,
13437 action: &ExpandExcerpts,
13438 _: &mut Window,
13439 cx: &mut Context<Self>,
13440 ) {
13441 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13442 }
13443
13444 pub fn expand_excerpts_down(
13445 &mut self,
13446 action: &ExpandExcerptsDown,
13447 _: &mut Window,
13448 cx: &mut Context<Self>,
13449 ) {
13450 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13451 }
13452
13453 pub fn expand_excerpts_up(
13454 &mut self,
13455 action: &ExpandExcerptsUp,
13456 _: &mut Window,
13457 cx: &mut Context<Self>,
13458 ) {
13459 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13460 }
13461
13462 pub fn expand_excerpts_for_direction(
13463 &mut self,
13464 lines: u32,
13465 direction: ExpandExcerptDirection,
13466
13467 cx: &mut Context<Self>,
13468 ) {
13469 let selections = self.selections.disjoint_anchors();
13470
13471 let lines = if lines == 0 {
13472 EditorSettings::get_global(cx).expand_excerpt_lines
13473 } else {
13474 lines
13475 };
13476
13477 self.buffer.update(cx, |buffer, cx| {
13478 let snapshot = buffer.snapshot(cx);
13479 let mut excerpt_ids = selections
13480 .iter()
13481 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13482 .collect::<Vec<_>>();
13483 excerpt_ids.sort();
13484 excerpt_ids.dedup();
13485 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13486 })
13487 }
13488
13489 pub fn expand_excerpt(
13490 &mut self,
13491 excerpt: ExcerptId,
13492 direction: ExpandExcerptDirection,
13493 window: &mut Window,
13494 cx: &mut Context<Self>,
13495 ) {
13496 let current_scroll_position = self.scroll_position(cx);
13497 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13498 let mut should_scroll_up = false;
13499
13500 if direction == ExpandExcerptDirection::Down {
13501 let multi_buffer = self.buffer.read(cx);
13502 let snapshot = multi_buffer.snapshot(cx);
13503 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13504 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13505 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13506 let buffer_snapshot = buffer.read(cx).snapshot();
13507 let excerpt_end_row =
13508 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13509 let last_row = buffer_snapshot.max_point().row;
13510 let lines_below = last_row.saturating_sub(excerpt_end_row);
13511 should_scroll_up = lines_below >= lines_to_expand;
13512 }
13513 }
13514 }
13515 }
13516
13517 self.buffer.update(cx, |buffer, cx| {
13518 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13519 });
13520
13521 if should_scroll_up {
13522 let new_scroll_position =
13523 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13524 self.set_scroll_position(new_scroll_position, window, cx);
13525 }
13526 }
13527
13528 pub fn go_to_singleton_buffer_point(
13529 &mut self,
13530 point: Point,
13531 window: &mut Window,
13532 cx: &mut Context<Self>,
13533 ) {
13534 self.go_to_singleton_buffer_range(point..point, window, cx);
13535 }
13536
13537 pub fn go_to_singleton_buffer_range(
13538 &mut self,
13539 range: Range<Point>,
13540 window: &mut Window,
13541 cx: &mut Context<Self>,
13542 ) {
13543 let multibuffer = self.buffer().read(cx);
13544 let Some(buffer) = multibuffer.as_singleton() else {
13545 return;
13546 };
13547 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13548 return;
13549 };
13550 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13551 return;
13552 };
13553 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13554 s.select_anchor_ranges([start..end])
13555 });
13556 }
13557
13558 pub fn go_to_diagnostic(
13559 &mut self,
13560 _: &GoToDiagnostic,
13561 window: &mut Window,
13562 cx: &mut Context<Self>,
13563 ) {
13564 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13565 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13566 }
13567
13568 pub fn go_to_prev_diagnostic(
13569 &mut self,
13570 _: &GoToPreviousDiagnostic,
13571 window: &mut Window,
13572 cx: &mut Context<Self>,
13573 ) {
13574 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13575 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13576 }
13577
13578 pub fn go_to_diagnostic_impl(
13579 &mut self,
13580 direction: Direction,
13581 window: &mut Window,
13582 cx: &mut Context<Self>,
13583 ) {
13584 let buffer = self.buffer.read(cx).snapshot(cx);
13585 let selection = self.selections.newest::<usize>(cx);
13586
13587 let mut active_group_id = None;
13588 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13589 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13590 active_group_id = Some(active_group.group_id);
13591 }
13592 }
13593
13594 fn filtered(
13595 snapshot: EditorSnapshot,
13596 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13597 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13598 diagnostics
13599 .filter(|entry| entry.range.start != entry.range.end)
13600 .filter(|entry| !entry.diagnostic.is_unnecessary)
13601 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13602 }
13603
13604 let snapshot = self.snapshot(window, cx);
13605 let before = filtered(
13606 snapshot.clone(),
13607 buffer
13608 .diagnostics_in_range(0..selection.start)
13609 .filter(|entry| entry.range.start <= selection.start),
13610 );
13611 let after = filtered(
13612 snapshot,
13613 buffer
13614 .diagnostics_in_range(selection.start..buffer.len())
13615 .filter(|entry| entry.range.start >= selection.start),
13616 );
13617
13618 let mut found: Option<DiagnosticEntry<usize>> = None;
13619 if direction == Direction::Prev {
13620 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13621 {
13622 for diagnostic in prev_diagnostics.into_iter().rev() {
13623 if diagnostic.range.start != selection.start
13624 || active_group_id
13625 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13626 {
13627 found = Some(diagnostic);
13628 break 'outer;
13629 }
13630 }
13631 }
13632 } else {
13633 for diagnostic in after.chain(before) {
13634 if diagnostic.range.start != selection.start
13635 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13636 {
13637 found = Some(diagnostic);
13638 break;
13639 }
13640 }
13641 }
13642 let Some(next_diagnostic) = found else {
13643 return;
13644 };
13645
13646 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13647 return;
13648 };
13649 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13650 s.select_ranges(vec![
13651 next_diagnostic.range.start..next_diagnostic.range.start,
13652 ])
13653 });
13654 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13655 self.refresh_inline_completion(false, true, window, cx);
13656 }
13657
13658 pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13659 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13660 let snapshot = self.snapshot(window, cx);
13661 let selection = self.selections.newest::<Point>(cx);
13662 self.go_to_hunk_before_or_after_position(
13663 &snapshot,
13664 selection.head(),
13665 Direction::Next,
13666 window,
13667 cx,
13668 );
13669 }
13670
13671 pub fn go_to_hunk_before_or_after_position(
13672 &mut self,
13673 snapshot: &EditorSnapshot,
13674 position: Point,
13675 direction: Direction,
13676 window: &mut Window,
13677 cx: &mut Context<Editor>,
13678 ) {
13679 let row = if direction == Direction::Next {
13680 self.hunk_after_position(snapshot, position)
13681 .map(|hunk| hunk.row_range.start)
13682 } else {
13683 self.hunk_before_position(snapshot, position)
13684 };
13685
13686 if let Some(row) = row {
13687 let destination = Point::new(row.0, 0);
13688 let autoscroll = Autoscroll::center();
13689
13690 self.unfold_ranges(&[destination..destination], false, false, cx);
13691 self.change_selections(Some(autoscroll), window, cx, |s| {
13692 s.select_ranges([destination..destination]);
13693 });
13694 }
13695 }
13696
13697 fn hunk_after_position(
13698 &mut self,
13699 snapshot: &EditorSnapshot,
13700 position: Point,
13701 ) -> Option<MultiBufferDiffHunk> {
13702 snapshot
13703 .buffer_snapshot
13704 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13705 .find(|hunk| hunk.row_range.start.0 > position.row)
13706 .or_else(|| {
13707 snapshot
13708 .buffer_snapshot
13709 .diff_hunks_in_range(Point::zero()..position)
13710 .find(|hunk| hunk.row_range.end.0 < position.row)
13711 })
13712 }
13713
13714 fn go_to_prev_hunk(
13715 &mut self,
13716 _: &GoToPreviousHunk,
13717 window: &mut Window,
13718 cx: &mut Context<Self>,
13719 ) {
13720 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13721 let snapshot = self.snapshot(window, cx);
13722 let selection = self.selections.newest::<Point>(cx);
13723 self.go_to_hunk_before_or_after_position(
13724 &snapshot,
13725 selection.head(),
13726 Direction::Prev,
13727 window,
13728 cx,
13729 );
13730 }
13731
13732 fn hunk_before_position(
13733 &mut self,
13734 snapshot: &EditorSnapshot,
13735 position: Point,
13736 ) -> Option<MultiBufferRow> {
13737 snapshot
13738 .buffer_snapshot
13739 .diff_hunk_before(position)
13740 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13741 }
13742
13743 fn go_to_next_change(
13744 &mut self,
13745 _: &GoToNextChange,
13746 window: &mut Window,
13747 cx: &mut Context<Self>,
13748 ) {
13749 if let Some(selections) = self
13750 .change_list
13751 .next_change(1, Direction::Next)
13752 .map(|s| s.to_vec())
13753 {
13754 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13755 let map = s.display_map();
13756 s.select_display_ranges(selections.iter().map(|a| {
13757 let point = a.to_display_point(&map);
13758 point..point
13759 }))
13760 })
13761 }
13762 }
13763
13764 fn go_to_previous_change(
13765 &mut self,
13766 _: &GoToPreviousChange,
13767 window: &mut Window,
13768 cx: &mut Context<Self>,
13769 ) {
13770 if let Some(selections) = self
13771 .change_list
13772 .next_change(1, Direction::Prev)
13773 .map(|s| s.to_vec())
13774 {
13775 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13776 let map = s.display_map();
13777 s.select_display_ranges(selections.iter().map(|a| {
13778 let point = a.to_display_point(&map);
13779 point..point
13780 }))
13781 })
13782 }
13783 }
13784
13785 fn go_to_line<T: 'static>(
13786 &mut self,
13787 position: Anchor,
13788 highlight_color: Option<Hsla>,
13789 window: &mut Window,
13790 cx: &mut Context<Self>,
13791 ) {
13792 let snapshot = self.snapshot(window, cx).display_snapshot;
13793 let position = position.to_point(&snapshot.buffer_snapshot);
13794 let start = snapshot
13795 .buffer_snapshot
13796 .clip_point(Point::new(position.row, 0), Bias::Left);
13797 let end = start + Point::new(1, 0);
13798 let start = snapshot.buffer_snapshot.anchor_before(start);
13799 let end = snapshot.buffer_snapshot.anchor_before(end);
13800
13801 self.highlight_rows::<T>(
13802 start..end,
13803 highlight_color
13804 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13805 Default::default(),
13806 cx,
13807 );
13808 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13809 }
13810
13811 pub fn go_to_definition(
13812 &mut self,
13813 _: &GoToDefinition,
13814 window: &mut Window,
13815 cx: &mut Context<Self>,
13816 ) -> Task<Result<Navigated>> {
13817 let definition =
13818 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13819 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13820 cx.spawn_in(window, async move |editor, cx| {
13821 if definition.await? == Navigated::Yes {
13822 return Ok(Navigated::Yes);
13823 }
13824 match fallback_strategy {
13825 GoToDefinitionFallback::None => Ok(Navigated::No),
13826 GoToDefinitionFallback::FindAllReferences => {
13827 match editor.update_in(cx, |editor, window, cx| {
13828 editor.find_all_references(&FindAllReferences, window, cx)
13829 })? {
13830 Some(references) => references.await,
13831 None => Ok(Navigated::No),
13832 }
13833 }
13834 }
13835 })
13836 }
13837
13838 pub fn go_to_declaration(
13839 &mut self,
13840 _: &GoToDeclaration,
13841 window: &mut Window,
13842 cx: &mut Context<Self>,
13843 ) -> Task<Result<Navigated>> {
13844 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13845 }
13846
13847 pub fn go_to_declaration_split(
13848 &mut self,
13849 _: &GoToDeclaration,
13850 window: &mut Window,
13851 cx: &mut Context<Self>,
13852 ) -> Task<Result<Navigated>> {
13853 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13854 }
13855
13856 pub fn go_to_implementation(
13857 &mut self,
13858 _: &GoToImplementation,
13859 window: &mut Window,
13860 cx: &mut Context<Self>,
13861 ) -> Task<Result<Navigated>> {
13862 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13863 }
13864
13865 pub fn go_to_implementation_split(
13866 &mut self,
13867 _: &GoToImplementationSplit,
13868 window: &mut Window,
13869 cx: &mut Context<Self>,
13870 ) -> Task<Result<Navigated>> {
13871 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13872 }
13873
13874 pub fn go_to_type_definition(
13875 &mut self,
13876 _: &GoToTypeDefinition,
13877 window: &mut Window,
13878 cx: &mut Context<Self>,
13879 ) -> Task<Result<Navigated>> {
13880 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13881 }
13882
13883 pub fn go_to_definition_split(
13884 &mut self,
13885 _: &GoToDefinitionSplit,
13886 window: &mut Window,
13887 cx: &mut Context<Self>,
13888 ) -> Task<Result<Navigated>> {
13889 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13890 }
13891
13892 pub fn go_to_type_definition_split(
13893 &mut self,
13894 _: &GoToTypeDefinitionSplit,
13895 window: &mut Window,
13896 cx: &mut Context<Self>,
13897 ) -> Task<Result<Navigated>> {
13898 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13899 }
13900
13901 fn go_to_definition_of_kind(
13902 &mut self,
13903 kind: GotoDefinitionKind,
13904 split: bool,
13905 window: &mut Window,
13906 cx: &mut Context<Self>,
13907 ) -> Task<Result<Navigated>> {
13908 let Some(provider) = self.semantics_provider.clone() else {
13909 return Task::ready(Ok(Navigated::No));
13910 };
13911 let head = self.selections.newest::<usize>(cx).head();
13912 let buffer = self.buffer.read(cx);
13913 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13914 text_anchor
13915 } else {
13916 return Task::ready(Ok(Navigated::No));
13917 };
13918
13919 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13920 return Task::ready(Ok(Navigated::No));
13921 };
13922
13923 cx.spawn_in(window, async move |editor, cx| {
13924 let definitions = definitions.await?;
13925 let navigated = editor
13926 .update_in(cx, |editor, window, cx| {
13927 editor.navigate_to_hover_links(
13928 Some(kind),
13929 definitions
13930 .into_iter()
13931 .filter(|location| {
13932 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13933 })
13934 .map(HoverLink::Text)
13935 .collect::<Vec<_>>(),
13936 split,
13937 window,
13938 cx,
13939 )
13940 })?
13941 .await?;
13942 anyhow::Ok(navigated)
13943 })
13944 }
13945
13946 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13947 let selection = self.selections.newest_anchor();
13948 let head = selection.head();
13949 let tail = selection.tail();
13950
13951 let Some((buffer, start_position)) =
13952 self.buffer.read(cx).text_anchor_for_position(head, cx)
13953 else {
13954 return;
13955 };
13956
13957 let end_position = if head != tail {
13958 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13959 return;
13960 };
13961 Some(pos)
13962 } else {
13963 None
13964 };
13965
13966 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13967 let url = if let Some(end_pos) = end_position {
13968 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13969 } else {
13970 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13971 };
13972
13973 if let Some(url) = url {
13974 editor.update(cx, |_, cx| {
13975 cx.open_url(&url);
13976 })
13977 } else {
13978 Ok(())
13979 }
13980 });
13981
13982 url_finder.detach();
13983 }
13984
13985 pub fn open_selected_filename(
13986 &mut self,
13987 _: &OpenSelectedFilename,
13988 window: &mut Window,
13989 cx: &mut Context<Self>,
13990 ) {
13991 let Some(workspace) = self.workspace() else {
13992 return;
13993 };
13994
13995 let position = self.selections.newest_anchor().head();
13996
13997 let Some((buffer, buffer_position)) =
13998 self.buffer.read(cx).text_anchor_for_position(position, cx)
13999 else {
14000 return;
14001 };
14002
14003 let project = self.project.clone();
14004
14005 cx.spawn_in(window, async move |_, cx| {
14006 let result = find_file(&buffer, project, buffer_position, cx).await;
14007
14008 if let Some((_, path)) = result {
14009 workspace
14010 .update_in(cx, |workspace, window, cx| {
14011 workspace.open_resolved_path(path, window, cx)
14012 })?
14013 .await?;
14014 }
14015 anyhow::Ok(())
14016 })
14017 .detach();
14018 }
14019
14020 pub(crate) fn navigate_to_hover_links(
14021 &mut self,
14022 kind: Option<GotoDefinitionKind>,
14023 mut definitions: Vec<HoverLink>,
14024 split: bool,
14025 window: &mut Window,
14026 cx: &mut Context<Editor>,
14027 ) -> Task<Result<Navigated>> {
14028 // If there is one definition, just open it directly
14029 if definitions.len() == 1 {
14030 let definition = definitions.pop().unwrap();
14031
14032 enum TargetTaskResult {
14033 Location(Option<Location>),
14034 AlreadyNavigated,
14035 }
14036
14037 let target_task = match definition {
14038 HoverLink::Text(link) => {
14039 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14040 }
14041 HoverLink::InlayHint(lsp_location, server_id) => {
14042 let computation =
14043 self.compute_target_location(lsp_location, server_id, window, cx);
14044 cx.background_spawn(async move {
14045 let location = computation.await?;
14046 Ok(TargetTaskResult::Location(location))
14047 })
14048 }
14049 HoverLink::Url(url) => {
14050 cx.open_url(&url);
14051 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14052 }
14053 HoverLink::File(path) => {
14054 if let Some(workspace) = self.workspace() {
14055 cx.spawn_in(window, async move |_, cx| {
14056 workspace
14057 .update_in(cx, |workspace, window, cx| {
14058 workspace.open_resolved_path(path, window, cx)
14059 })?
14060 .await
14061 .map(|_| TargetTaskResult::AlreadyNavigated)
14062 })
14063 } else {
14064 Task::ready(Ok(TargetTaskResult::Location(None)))
14065 }
14066 }
14067 };
14068 cx.spawn_in(window, async move |editor, cx| {
14069 let target = match target_task.await.context("target resolution task")? {
14070 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14071 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14072 TargetTaskResult::Location(Some(target)) => target,
14073 };
14074
14075 editor.update_in(cx, |editor, window, cx| {
14076 let Some(workspace) = editor.workspace() else {
14077 return Navigated::No;
14078 };
14079 let pane = workspace.read(cx).active_pane().clone();
14080
14081 let range = target.range.to_point(target.buffer.read(cx));
14082 let range = editor.range_for_match(&range);
14083 let range = collapse_multiline_range(range);
14084
14085 if !split
14086 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14087 {
14088 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14089 } else {
14090 window.defer(cx, move |window, cx| {
14091 let target_editor: Entity<Self> =
14092 workspace.update(cx, |workspace, cx| {
14093 let pane = if split {
14094 workspace.adjacent_pane(window, cx)
14095 } else {
14096 workspace.active_pane().clone()
14097 };
14098
14099 workspace.open_project_item(
14100 pane,
14101 target.buffer.clone(),
14102 true,
14103 true,
14104 window,
14105 cx,
14106 )
14107 });
14108 target_editor.update(cx, |target_editor, cx| {
14109 // When selecting a definition in a different buffer, disable the nav history
14110 // to avoid creating a history entry at the previous cursor location.
14111 pane.update(cx, |pane, _| pane.disable_history());
14112 target_editor.go_to_singleton_buffer_range(range, window, cx);
14113 pane.update(cx, |pane, _| pane.enable_history());
14114 });
14115 });
14116 }
14117 Navigated::Yes
14118 })
14119 })
14120 } else if !definitions.is_empty() {
14121 cx.spawn_in(window, async move |editor, cx| {
14122 let (title, location_tasks, workspace) = editor
14123 .update_in(cx, |editor, window, cx| {
14124 let tab_kind = match kind {
14125 Some(GotoDefinitionKind::Implementation) => "Implementations",
14126 _ => "Definitions",
14127 };
14128 let title = definitions
14129 .iter()
14130 .find_map(|definition| match definition {
14131 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14132 let buffer = origin.buffer.read(cx);
14133 format!(
14134 "{} for {}",
14135 tab_kind,
14136 buffer
14137 .text_for_range(origin.range.clone())
14138 .collect::<String>()
14139 )
14140 }),
14141 HoverLink::InlayHint(_, _) => None,
14142 HoverLink::Url(_) => None,
14143 HoverLink::File(_) => None,
14144 })
14145 .unwrap_or(tab_kind.to_string());
14146 let location_tasks = definitions
14147 .into_iter()
14148 .map(|definition| match definition {
14149 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14150 HoverLink::InlayHint(lsp_location, server_id) => editor
14151 .compute_target_location(lsp_location, server_id, window, cx),
14152 HoverLink::Url(_) => Task::ready(Ok(None)),
14153 HoverLink::File(_) => Task::ready(Ok(None)),
14154 })
14155 .collect::<Vec<_>>();
14156 (title, location_tasks, editor.workspace().clone())
14157 })
14158 .context("location tasks preparation")?;
14159
14160 let locations = future::join_all(location_tasks)
14161 .await
14162 .into_iter()
14163 .filter_map(|location| location.transpose())
14164 .collect::<Result<_>>()
14165 .context("location tasks")?;
14166
14167 let Some(workspace) = workspace else {
14168 return Ok(Navigated::No);
14169 };
14170 let opened = workspace
14171 .update_in(cx, |workspace, window, cx| {
14172 Self::open_locations_in_multibuffer(
14173 workspace,
14174 locations,
14175 title,
14176 split,
14177 MultibufferSelectionMode::First,
14178 window,
14179 cx,
14180 )
14181 })
14182 .ok();
14183
14184 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14185 })
14186 } else {
14187 Task::ready(Ok(Navigated::No))
14188 }
14189 }
14190
14191 fn compute_target_location(
14192 &self,
14193 lsp_location: lsp::Location,
14194 server_id: LanguageServerId,
14195 window: &mut Window,
14196 cx: &mut Context<Self>,
14197 ) -> Task<anyhow::Result<Option<Location>>> {
14198 let Some(project) = self.project.clone() else {
14199 return Task::ready(Ok(None));
14200 };
14201
14202 cx.spawn_in(window, async move |editor, cx| {
14203 let location_task = editor.update(cx, |_, cx| {
14204 project.update(cx, |project, cx| {
14205 let language_server_name = project
14206 .language_server_statuses(cx)
14207 .find(|(id, _)| server_id == *id)
14208 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14209 language_server_name.map(|language_server_name| {
14210 project.open_local_buffer_via_lsp(
14211 lsp_location.uri.clone(),
14212 server_id,
14213 language_server_name,
14214 cx,
14215 )
14216 })
14217 })
14218 })?;
14219 let location = match location_task {
14220 Some(task) => Some({
14221 let target_buffer_handle = task.await.context("open local buffer")?;
14222 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14223 let target_start = target_buffer
14224 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14225 let target_end = target_buffer
14226 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14227 target_buffer.anchor_after(target_start)
14228 ..target_buffer.anchor_before(target_end)
14229 })?;
14230 Location {
14231 buffer: target_buffer_handle,
14232 range,
14233 }
14234 }),
14235 None => None,
14236 };
14237 Ok(location)
14238 })
14239 }
14240
14241 pub fn find_all_references(
14242 &mut self,
14243 _: &FindAllReferences,
14244 window: &mut Window,
14245 cx: &mut Context<Self>,
14246 ) -> Option<Task<Result<Navigated>>> {
14247 let selection = self.selections.newest::<usize>(cx);
14248 let multi_buffer = self.buffer.read(cx);
14249 let head = selection.head();
14250
14251 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14252 let head_anchor = multi_buffer_snapshot.anchor_at(
14253 head,
14254 if head < selection.tail() {
14255 Bias::Right
14256 } else {
14257 Bias::Left
14258 },
14259 );
14260
14261 match self
14262 .find_all_references_task_sources
14263 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14264 {
14265 Ok(_) => {
14266 log::info!(
14267 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14268 );
14269 return None;
14270 }
14271 Err(i) => {
14272 self.find_all_references_task_sources.insert(i, head_anchor);
14273 }
14274 }
14275
14276 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14277 let workspace = self.workspace()?;
14278 let project = workspace.read(cx).project().clone();
14279 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14280 Some(cx.spawn_in(window, async move |editor, cx| {
14281 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14282 if let Ok(i) = editor
14283 .find_all_references_task_sources
14284 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14285 {
14286 editor.find_all_references_task_sources.remove(i);
14287 }
14288 });
14289
14290 let locations = references.await?;
14291 if locations.is_empty() {
14292 return anyhow::Ok(Navigated::No);
14293 }
14294
14295 workspace.update_in(cx, |workspace, window, cx| {
14296 let title = locations
14297 .first()
14298 .as_ref()
14299 .map(|location| {
14300 let buffer = location.buffer.read(cx);
14301 format!(
14302 "References to `{}`",
14303 buffer
14304 .text_for_range(location.range.clone())
14305 .collect::<String>()
14306 )
14307 })
14308 .unwrap();
14309 Self::open_locations_in_multibuffer(
14310 workspace,
14311 locations,
14312 title,
14313 false,
14314 MultibufferSelectionMode::First,
14315 window,
14316 cx,
14317 );
14318 Navigated::Yes
14319 })
14320 }))
14321 }
14322
14323 /// Opens a multibuffer with the given project locations in it
14324 pub fn open_locations_in_multibuffer(
14325 workspace: &mut Workspace,
14326 mut locations: Vec<Location>,
14327 title: String,
14328 split: bool,
14329 multibuffer_selection_mode: MultibufferSelectionMode,
14330 window: &mut Window,
14331 cx: &mut Context<Workspace>,
14332 ) {
14333 // If there are multiple definitions, open them in a multibuffer
14334 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14335 let mut locations = locations.into_iter().peekable();
14336 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14337 let capability = workspace.project().read(cx).capability();
14338
14339 let excerpt_buffer = cx.new(|cx| {
14340 let mut multibuffer = MultiBuffer::new(capability);
14341 while let Some(location) = locations.next() {
14342 let buffer = location.buffer.read(cx);
14343 let mut ranges_for_buffer = Vec::new();
14344 let range = location.range.to_point(buffer);
14345 ranges_for_buffer.push(range.clone());
14346
14347 while let Some(next_location) = locations.peek() {
14348 if next_location.buffer == location.buffer {
14349 ranges_for_buffer.push(next_location.range.to_point(buffer));
14350 locations.next();
14351 } else {
14352 break;
14353 }
14354 }
14355
14356 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14357 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14358 PathKey::for_buffer(&location.buffer, cx),
14359 location.buffer.clone(),
14360 ranges_for_buffer,
14361 DEFAULT_MULTIBUFFER_CONTEXT,
14362 cx,
14363 );
14364 ranges.extend(new_ranges)
14365 }
14366
14367 multibuffer.with_title(title)
14368 });
14369
14370 let editor = cx.new(|cx| {
14371 Editor::for_multibuffer(
14372 excerpt_buffer,
14373 Some(workspace.project().clone()),
14374 window,
14375 cx,
14376 )
14377 });
14378 editor.update(cx, |editor, cx| {
14379 match multibuffer_selection_mode {
14380 MultibufferSelectionMode::First => {
14381 if let Some(first_range) = ranges.first() {
14382 editor.change_selections(None, window, cx, |selections| {
14383 selections.clear_disjoint();
14384 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14385 });
14386 }
14387 editor.highlight_background::<Self>(
14388 &ranges,
14389 |theme| theme.editor_highlighted_line_background,
14390 cx,
14391 );
14392 }
14393 MultibufferSelectionMode::All => {
14394 editor.change_selections(None, window, cx, |selections| {
14395 selections.clear_disjoint();
14396 selections.select_anchor_ranges(ranges);
14397 });
14398 }
14399 }
14400 editor.register_buffers_with_language_servers(cx);
14401 });
14402
14403 let item = Box::new(editor);
14404 let item_id = item.item_id();
14405
14406 if split {
14407 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14408 } else {
14409 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14410 let (preview_item_id, preview_item_idx) =
14411 workspace.active_pane().update(cx, |pane, _| {
14412 (pane.preview_item_id(), pane.preview_item_idx())
14413 });
14414
14415 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14416
14417 if let Some(preview_item_id) = preview_item_id {
14418 workspace.active_pane().update(cx, |pane, cx| {
14419 pane.remove_item(preview_item_id, false, false, window, cx);
14420 });
14421 }
14422 } else {
14423 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14424 }
14425 }
14426 workspace.active_pane().update(cx, |pane, cx| {
14427 pane.set_preview_item_id(Some(item_id), cx);
14428 });
14429 }
14430
14431 pub fn rename(
14432 &mut self,
14433 _: &Rename,
14434 window: &mut Window,
14435 cx: &mut Context<Self>,
14436 ) -> Option<Task<Result<()>>> {
14437 use language::ToOffset as _;
14438
14439 let provider = self.semantics_provider.clone()?;
14440 let selection = self.selections.newest_anchor().clone();
14441 let (cursor_buffer, cursor_buffer_position) = self
14442 .buffer
14443 .read(cx)
14444 .text_anchor_for_position(selection.head(), cx)?;
14445 let (tail_buffer, cursor_buffer_position_end) = self
14446 .buffer
14447 .read(cx)
14448 .text_anchor_for_position(selection.tail(), cx)?;
14449 if tail_buffer != cursor_buffer {
14450 return None;
14451 }
14452
14453 let snapshot = cursor_buffer.read(cx).snapshot();
14454 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14455 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14456 let prepare_rename = provider
14457 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14458 .unwrap_or_else(|| Task::ready(Ok(None)));
14459 drop(snapshot);
14460
14461 Some(cx.spawn_in(window, async move |this, cx| {
14462 let rename_range = if let Some(range) = prepare_rename.await? {
14463 Some(range)
14464 } else {
14465 this.update(cx, |this, cx| {
14466 let buffer = this.buffer.read(cx).snapshot(cx);
14467 let mut buffer_highlights = this
14468 .document_highlights_for_position(selection.head(), &buffer)
14469 .filter(|highlight| {
14470 highlight.start.excerpt_id == selection.head().excerpt_id
14471 && highlight.end.excerpt_id == selection.head().excerpt_id
14472 });
14473 buffer_highlights
14474 .next()
14475 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14476 })?
14477 };
14478 if let Some(rename_range) = rename_range {
14479 this.update_in(cx, |this, window, cx| {
14480 let snapshot = cursor_buffer.read(cx).snapshot();
14481 let rename_buffer_range = rename_range.to_offset(&snapshot);
14482 let cursor_offset_in_rename_range =
14483 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14484 let cursor_offset_in_rename_range_end =
14485 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14486
14487 this.take_rename(false, window, cx);
14488 let buffer = this.buffer.read(cx).read(cx);
14489 let cursor_offset = selection.head().to_offset(&buffer);
14490 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14491 let rename_end = rename_start + rename_buffer_range.len();
14492 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14493 let mut old_highlight_id = None;
14494 let old_name: Arc<str> = buffer
14495 .chunks(rename_start..rename_end, true)
14496 .map(|chunk| {
14497 if old_highlight_id.is_none() {
14498 old_highlight_id = chunk.syntax_highlight_id;
14499 }
14500 chunk.text
14501 })
14502 .collect::<String>()
14503 .into();
14504
14505 drop(buffer);
14506
14507 // Position the selection in the rename editor so that it matches the current selection.
14508 this.show_local_selections = false;
14509 let rename_editor = cx.new(|cx| {
14510 let mut editor = Editor::single_line(window, cx);
14511 editor.buffer.update(cx, |buffer, cx| {
14512 buffer.edit([(0..0, old_name.clone())], None, cx)
14513 });
14514 let rename_selection_range = match cursor_offset_in_rename_range
14515 .cmp(&cursor_offset_in_rename_range_end)
14516 {
14517 Ordering::Equal => {
14518 editor.select_all(&SelectAll, window, cx);
14519 return editor;
14520 }
14521 Ordering::Less => {
14522 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14523 }
14524 Ordering::Greater => {
14525 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14526 }
14527 };
14528 if rename_selection_range.end > old_name.len() {
14529 editor.select_all(&SelectAll, window, cx);
14530 } else {
14531 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14532 s.select_ranges([rename_selection_range]);
14533 });
14534 }
14535 editor
14536 });
14537 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14538 if e == &EditorEvent::Focused {
14539 cx.emit(EditorEvent::FocusedIn)
14540 }
14541 })
14542 .detach();
14543
14544 let write_highlights =
14545 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14546 let read_highlights =
14547 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14548 let ranges = write_highlights
14549 .iter()
14550 .flat_map(|(_, ranges)| ranges.iter())
14551 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14552 .cloned()
14553 .collect();
14554
14555 this.highlight_text::<Rename>(
14556 ranges,
14557 HighlightStyle {
14558 fade_out: Some(0.6),
14559 ..Default::default()
14560 },
14561 cx,
14562 );
14563 let rename_focus_handle = rename_editor.focus_handle(cx);
14564 window.focus(&rename_focus_handle);
14565 let block_id = this.insert_blocks(
14566 [BlockProperties {
14567 style: BlockStyle::Flex,
14568 placement: BlockPlacement::Below(range.start),
14569 height: Some(1),
14570 render: Arc::new({
14571 let rename_editor = rename_editor.clone();
14572 move |cx: &mut BlockContext| {
14573 let mut text_style = cx.editor_style.text.clone();
14574 if let Some(highlight_style) = old_highlight_id
14575 .and_then(|h| h.style(&cx.editor_style.syntax))
14576 {
14577 text_style = text_style.highlight(highlight_style);
14578 }
14579 div()
14580 .block_mouse_down()
14581 .pl(cx.anchor_x)
14582 .child(EditorElement::new(
14583 &rename_editor,
14584 EditorStyle {
14585 background: cx.theme().system().transparent,
14586 local_player: cx.editor_style.local_player,
14587 text: text_style,
14588 scrollbar_width: cx.editor_style.scrollbar_width,
14589 syntax: cx.editor_style.syntax.clone(),
14590 status: cx.editor_style.status.clone(),
14591 inlay_hints_style: HighlightStyle {
14592 font_weight: Some(FontWeight::BOLD),
14593 ..make_inlay_hints_style(cx.app)
14594 },
14595 inline_completion_styles: make_suggestion_styles(
14596 cx.app,
14597 ),
14598 ..EditorStyle::default()
14599 },
14600 ))
14601 .into_any_element()
14602 }
14603 }),
14604 priority: 0,
14605 }],
14606 Some(Autoscroll::fit()),
14607 cx,
14608 )[0];
14609 this.pending_rename = Some(RenameState {
14610 range,
14611 old_name,
14612 editor: rename_editor,
14613 block_id,
14614 });
14615 })?;
14616 }
14617
14618 Ok(())
14619 }))
14620 }
14621
14622 pub fn confirm_rename(
14623 &mut self,
14624 _: &ConfirmRename,
14625 window: &mut Window,
14626 cx: &mut Context<Self>,
14627 ) -> Option<Task<Result<()>>> {
14628 let rename = self.take_rename(false, window, cx)?;
14629 let workspace = self.workspace()?.downgrade();
14630 let (buffer, start) = self
14631 .buffer
14632 .read(cx)
14633 .text_anchor_for_position(rename.range.start, cx)?;
14634 let (end_buffer, _) = self
14635 .buffer
14636 .read(cx)
14637 .text_anchor_for_position(rename.range.end, cx)?;
14638 if buffer != end_buffer {
14639 return None;
14640 }
14641
14642 let old_name = rename.old_name;
14643 let new_name = rename.editor.read(cx).text(cx);
14644
14645 let rename = self.semantics_provider.as_ref()?.perform_rename(
14646 &buffer,
14647 start,
14648 new_name.clone(),
14649 cx,
14650 )?;
14651
14652 Some(cx.spawn_in(window, async move |editor, cx| {
14653 let project_transaction = rename.await?;
14654 Self::open_project_transaction(
14655 &editor,
14656 workspace,
14657 project_transaction,
14658 format!("Rename: {} → {}", old_name, new_name),
14659 cx,
14660 )
14661 .await?;
14662
14663 editor.update(cx, |editor, cx| {
14664 editor.refresh_document_highlights(cx);
14665 })?;
14666 Ok(())
14667 }))
14668 }
14669
14670 fn take_rename(
14671 &mut self,
14672 moving_cursor: bool,
14673 window: &mut Window,
14674 cx: &mut Context<Self>,
14675 ) -> Option<RenameState> {
14676 let rename = self.pending_rename.take()?;
14677 if rename.editor.focus_handle(cx).is_focused(window) {
14678 window.focus(&self.focus_handle);
14679 }
14680
14681 self.remove_blocks(
14682 [rename.block_id].into_iter().collect(),
14683 Some(Autoscroll::fit()),
14684 cx,
14685 );
14686 self.clear_highlights::<Rename>(cx);
14687 self.show_local_selections = true;
14688
14689 if moving_cursor {
14690 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14691 editor.selections.newest::<usize>(cx).head()
14692 });
14693
14694 // Update the selection to match the position of the selection inside
14695 // the rename editor.
14696 let snapshot = self.buffer.read(cx).read(cx);
14697 let rename_range = rename.range.to_offset(&snapshot);
14698 let cursor_in_editor = snapshot
14699 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14700 .min(rename_range.end);
14701 drop(snapshot);
14702
14703 self.change_selections(None, window, cx, |s| {
14704 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14705 });
14706 } else {
14707 self.refresh_document_highlights(cx);
14708 }
14709
14710 Some(rename)
14711 }
14712
14713 pub fn pending_rename(&self) -> Option<&RenameState> {
14714 self.pending_rename.as_ref()
14715 }
14716
14717 fn format(
14718 &mut self,
14719 _: &Format,
14720 window: &mut Window,
14721 cx: &mut Context<Self>,
14722 ) -> Option<Task<Result<()>>> {
14723 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14724
14725 let project = match &self.project {
14726 Some(project) => project.clone(),
14727 None => return None,
14728 };
14729
14730 Some(self.perform_format(
14731 project,
14732 FormatTrigger::Manual,
14733 FormatTarget::Buffers,
14734 window,
14735 cx,
14736 ))
14737 }
14738
14739 fn format_selections(
14740 &mut self,
14741 _: &FormatSelections,
14742 window: &mut Window,
14743 cx: &mut Context<Self>,
14744 ) -> Option<Task<Result<()>>> {
14745 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14746
14747 let project = match &self.project {
14748 Some(project) => project.clone(),
14749 None => return None,
14750 };
14751
14752 let ranges = self
14753 .selections
14754 .all_adjusted(cx)
14755 .into_iter()
14756 .map(|selection| selection.range())
14757 .collect_vec();
14758
14759 Some(self.perform_format(
14760 project,
14761 FormatTrigger::Manual,
14762 FormatTarget::Ranges(ranges),
14763 window,
14764 cx,
14765 ))
14766 }
14767
14768 fn perform_format(
14769 &mut self,
14770 project: Entity<Project>,
14771 trigger: FormatTrigger,
14772 target: FormatTarget,
14773 window: &mut Window,
14774 cx: &mut Context<Self>,
14775 ) -> Task<Result<()>> {
14776 let buffer = self.buffer.clone();
14777 let (buffers, target) = match target {
14778 FormatTarget::Buffers => {
14779 let mut buffers = buffer.read(cx).all_buffers();
14780 if trigger == FormatTrigger::Save {
14781 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14782 }
14783 (buffers, LspFormatTarget::Buffers)
14784 }
14785 FormatTarget::Ranges(selection_ranges) => {
14786 let multi_buffer = buffer.read(cx);
14787 let snapshot = multi_buffer.read(cx);
14788 let mut buffers = HashSet::default();
14789 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14790 BTreeMap::new();
14791 for selection_range in selection_ranges {
14792 for (buffer, buffer_range, _) in
14793 snapshot.range_to_buffer_ranges(selection_range)
14794 {
14795 let buffer_id = buffer.remote_id();
14796 let start = buffer.anchor_before(buffer_range.start);
14797 let end = buffer.anchor_after(buffer_range.end);
14798 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14799 buffer_id_to_ranges
14800 .entry(buffer_id)
14801 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14802 .or_insert_with(|| vec![start..end]);
14803 }
14804 }
14805 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14806 }
14807 };
14808
14809 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14810 let selections_prev = transaction_id_prev
14811 .and_then(|transaction_id_prev| {
14812 // default to selections as they were after the last edit, if we have them,
14813 // instead of how they are now.
14814 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14815 // will take you back to where you made the last edit, instead of staying where you scrolled
14816 self.selection_history
14817 .transaction(transaction_id_prev)
14818 .map(|t| t.0.clone())
14819 })
14820 .unwrap_or_else(|| {
14821 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14822 self.selections.disjoint_anchors()
14823 });
14824
14825 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14826 let format = project.update(cx, |project, cx| {
14827 project.format(buffers, target, true, trigger, cx)
14828 });
14829
14830 cx.spawn_in(window, async move |editor, cx| {
14831 let transaction = futures::select_biased! {
14832 transaction = format.log_err().fuse() => transaction,
14833 () = timeout => {
14834 log::warn!("timed out waiting for formatting");
14835 None
14836 }
14837 };
14838
14839 buffer
14840 .update(cx, |buffer, cx| {
14841 if let Some(transaction) = transaction {
14842 if !buffer.is_singleton() {
14843 buffer.push_transaction(&transaction.0, cx);
14844 }
14845 }
14846 cx.notify();
14847 })
14848 .ok();
14849
14850 if let Some(transaction_id_now) =
14851 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14852 {
14853 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14854 if has_new_transaction {
14855 _ = editor.update(cx, |editor, _| {
14856 editor
14857 .selection_history
14858 .insert_transaction(transaction_id_now, selections_prev);
14859 });
14860 }
14861 }
14862
14863 Ok(())
14864 })
14865 }
14866
14867 fn organize_imports(
14868 &mut self,
14869 _: &OrganizeImports,
14870 window: &mut Window,
14871 cx: &mut Context<Self>,
14872 ) -> Option<Task<Result<()>>> {
14873 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14874 let project = match &self.project {
14875 Some(project) => project.clone(),
14876 None => return None,
14877 };
14878 Some(self.perform_code_action_kind(
14879 project,
14880 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14881 window,
14882 cx,
14883 ))
14884 }
14885
14886 fn perform_code_action_kind(
14887 &mut self,
14888 project: Entity<Project>,
14889 kind: CodeActionKind,
14890 window: &mut Window,
14891 cx: &mut Context<Self>,
14892 ) -> Task<Result<()>> {
14893 let buffer = self.buffer.clone();
14894 let buffers = buffer.read(cx).all_buffers();
14895 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14896 let apply_action = project.update(cx, |project, cx| {
14897 project.apply_code_action_kind(buffers, kind, true, cx)
14898 });
14899 cx.spawn_in(window, async move |_, cx| {
14900 let transaction = futures::select_biased! {
14901 () = timeout => {
14902 log::warn!("timed out waiting for executing code action");
14903 None
14904 }
14905 transaction = apply_action.log_err().fuse() => transaction,
14906 };
14907 buffer
14908 .update(cx, |buffer, cx| {
14909 // check if we need this
14910 if let Some(transaction) = transaction {
14911 if !buffer.is_singleton() {
14912 buffer.push_transaction(&transaction.0, cx);
14913 }
14914 }
14915 cx.notify();
14916 })
14917 .ok();
14918 Ok(())
14919 })
14920 }
14921
14922 fn restart_language_server(
14923 &mut self,
14924 _: &RestartLanguageServer,
14925 _: &mut Window,
14926 cx: &mut Context<Self>,
14927 ) {
14928 if let Some(project) = self.project.clone() {
14929 self.buffer.update(cx, |multi_buffer, cx| {
14930 project.update(cx, |project, cx| {
14931 project.restart_language_servers_for_buffers(
14932 multi_buffer.all_buffers().into_iter().collect(),
14933 cx,
14934 );
14935 });
14936 })
14937 }
14938 }
14939
14940 fn stop_language_server(
14941 &mut self,
14942 _: &StopLanguageServer,
14943 _: &mut Window,
14944 cx: &mut Context<Self>,
14945 ) {
14946 if let Some(project) = self.project.clone() {
14947 self.buffer.update(cx, |multi_buffer, cx| {
14948 project.update(cx, |project, cx| {
14949 project.stop_language_servers_for_buffers(
14950 multi_buffer.all_buffers().into_iter().collect(),
14951 cx,
14952 );
14953 cx.emit(project::Event::RefreshInlayHints);
14954 });
14955 });
14956 }
14957 }
14958
14959 fn cancel_language_server_work(
14960 workspace: &mut Workspace,
14961 _: &actions::CancelLanguageServerWork,
14962 _: &mut Window,
14963 cx: &mut Context<Workspace>,
14964 ) {
14965 let project = workspace.project();
14966 let buffers = workspace
14967 .active_item(cx)
14968 .and_then(|item| item.act_as::<Editor>(cx))
14969 .map_or(HashSet::default(), |editor| {
14970 editor.read(cx).buffer.read(cx).all_buffers()
14971 });
14972 project.update(cx, |project, cx| {
14973 project.cancel_language_server_work_for_buffers(buffers, cx);
14974 });
14975 }
14976
14977 fn show_character_palette(
14978 &mut self,
14979 _: &ShowCharacterPalette,
14980 window: &mut Window,
14981 _: &mut Context<Self>,
14982 ) {
14983 window.show_character_palette();
14984 }
14985
14986 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14987 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14988 let buffer = self.buffer.read(cx).snapshot(cx);
14989 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14990 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14991 let is_valid = buffer
14992 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14993 .any(|entry| {
14994 entry.diagnostic.is_primary
14995 && !entry.range.is_empty()
14996 && entry.range.start == primary_range_start
14997 && entry.diagnostic.message == active_diagnostics.active_message
14998 });
14999
15000 if !is_valid {
15001 self.dismiss_diagnostics(cx);
15002 }
15003 }
15004 }
15005
15006 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15007 match &self.active_diagnostics {
15008 ActiveDiagnostic::Group(group) => Some(group),
15009 _ => None,
15010 }
15011 }
15012
15013 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15014 self.dismiss_diagnostics(cx);
15015 self.active_diagnostics = ActiveDiagnostic::All;
15016 }
15017
15018 fn activate_diagnostics(
15019 &mut self,
15020 buffer_id: BufferId,
15021 diagnostic: DiagnosticEntry<usize>,
15022 window: &mut Window,
15023 cx: &mut Context<Self>,
15024 ) {
15025 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15026 return;
15027 }
15028 self.dismiss_diagnostics(cx);
15029 let snapshot = self.snapshot(window, cx);
15030 let buffer = self.buffer.read(cx).snapshot(cx);
15031 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15032 return;
15033 };
15034
15035 let diagnostic_group = buffer
15036 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15037 .collect::<Vec<_>>();
15038
15039 let blocks =
15040 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15041
15042 let blocks = self.display_map.update(cx, |display_map, cx| {
15043 display_map.insert_blocks(blocks, cx).into_iter().collect()
15044 });
15045 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15046 active_range: buffer.anchor_before(diagnostic.range.start)
15047 ..buffer.anchor_after(diagnostic.range.end),
15048 active_message: diagnostic.diagnostic.message.clone(),
15049 group_id: diagnostic.diagnostic.group_id,
15050 blocks,
15051 });
15052 cx.notify();
15053 }
15054
15055 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15056 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15057 return;
15058 };
15059
15060 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15061 if let ActiveDiagnostic::Group(group) = prev {
15062 self.display_map.update(cx, |display_map, cx| {
15063 display_map.remove_blocks(group.blocks, cx);
15064 });
15065 cx.notify();
15066 }
15067 }
15068
15069 /// Disable inline diagnostics rendering for this editor.
15070 pub fn disable_inline_diagnostics(&mut self) {
15071 self.inline_diagnostics_enabled = false;
15072 self.inline_diagnostics_update = Task::ready(());
15073 self.inline_diagnostics.clear();
15074 }
15075
15076 pub fn inline_diagnostics_enabled(&self) -> bool {
15077 self.inline_diagnostics_enabled
15078 }
15079
15080 pub fn show_inline_diagnostics(&self) -> bool {
15081 self.show_inline_diagnostics
15082 }
15083
15084 pub fn toggle_inline_diagnostics(
15085 &mut self,
15086 _: &ToggleInlineDiagnostics,
15087 window: &mut Window,
15088 cx: &mut Context<Editor>,
15089 ) {
15090 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15091 self.refresh_inline_diagnostics(false, window, cx);
15092 }
15093
15094 fn refresh_inline_diagnostics(
15095 &mut self,
15096 debounce: bool,
15097 window: &mut Window,
15098 cx: &mut Context<Self>,
15099 ) {
15100 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15101 self.inline_diagnostics_update = Task::ready(());
15102 self.inline_diagnostics.clear();
15103 return;
15104 }
15105
15106 let debounce_ms = ProjectSettings::get_global(cx)
15107 .diagnostics
15108 .inline
15109 .update_debounce_ms;
15110 let debounce = if debounce && debounce_ms > 0 {
15111 Some(Duration::from_millis(debounce_ms))
15112 } else {
15113 None
15114 };
15115 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15116 let editor = editor.upgrade().unwrap();
15117
15118 if let Some(debounce) = debounce {
15119 cx.background_executor().timer(debounce).await;
15120 }
15121 let Some(snapshot) = editor
15122 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15123 .ok()
15124 else {
15125 return;
15126 };
15127
15128 let new_inline_diagnostics = cx
15129 .background_spawn(async move {
15130 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15131 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15132 let message = diagnostic_entry
15133 .diagnostic
15134 .message
15135 .split_once('\n')
15136 .map(|(line, _)| line)
15137 .map(SharedString::new)
15138 .unwrap_or_else(|| {
15139 SharedString::from(diagnostic_entry.diagnostic.message)
15140 });
15141 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15142 let (Ok(i) | Err(i)) = inline_diagnostics
15143 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15144 inline_diagnostics.insert(
15145 i,
15146 (
15147 start_anchor,
15148 InlineDiagnostic {
15149 message,
15150 group_id: diagnostic_entry.diagnostic.group_id,
15151 start: diagnostic_entry.range.start.to_point(&snapshot),
15152 is_primary: diagnostic_entry.diagnostic.is_primary,
15153 severity: diagnostic_entry.diagnostic.severity,
15154 },
15155 ),
15156 );
15157 }
15158 inline_diagnostics
15159 })
15160 .await;
15161
15162 editor
15163 .update(cx, |editor, cx| {
15164 editor.inline_diagnostics = new_inline_diagnostics;
15165 cx.notify();
15166 })
15167 .ok();
15168 });
15169 }
15170
15171 pub fn set_selections_from_remote(
15172 &mut self,
15173 selections: Vec<Selection<Anchor>>,
15174 pending_selection: Option<Selection<Anchor>>,
15175 window: &mut Window,
15176 cx: &mut Context<Self>,
15177 ) {
15178 let old_cursor_position = self.selections.newest_anchor().head();
15179 self.selections.change_with(cx, |s| {
15180 s.select_anchors(selections);
15181 if let Some(pending_selection) = pending_selection {
15182 s.set_pending(pending_selection, SelectMode::Character);
15183 } else {
15184 s.clear_pending();
15185 }
15186 });
15187 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15188 }
15189
15190 fn push_to_selection_history(&mut self) {
15191 self.selection_history.push(SelectionHistoryEntry {
15192 selections: self.selections.disjoint_anchors(),
15193 select_next_state: self.select_next_state.clone(),
15194 select_prev_state: self.select_prev_state.clone(),
15195 add_selections_state: self.add_selections_state.clone(),
15196 });
15197 }
15198
15199 pub fn transact(
15200 &mut self,
15201 window: &mut Window,
15202 cx: &mut Context<Self>,
15203 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15204 ) -> Option<TransactionId> {
15205 self.start_transaction_at(Instant::now(), window, cx);
15206 update(self, window, cx);
15207 self.end_transaction_at(Instant::now(), cx)
15208 }
15209
15210 pub fn start_transaction_at(
15211 &mut self,
15212 now: Instant,
15213 window: &mut Window,
15214 cx: &mut Context<Self>,
15215 ) {
15216 self.end_selection(window, cx);
15217 if let Some(tx_id) = self
15218 .buffer
15219 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15220 {
15221 self.selection_history
15222 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15223 cx.emit(EditorEvent::TransactionBegun {
15224 transaction_id: tx_id,
15225 })
15226 }
15227 }
15228
15229 pub fn end_transaction_at(
15230 &mut self,
15231 now: Instant,
15232 cx: &mut Context<Self>,
15233 ) -> Option<TransactionId> {
15234 if let Some(transaction_id) = self
15235 .buffer
15236 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15237 {
15238 if let Some((_, end_selections)) =
15239 self.selection_history.transaction_mut(transaction_id)
15240 {
15241 *end_selections = Some(self.selections.disjoint_anchors());
15242 } else {
15243 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15244 }
15245
15246 cx.emit(EditorEvent::Edited { transaction_id });
15247 Some(transaction_id)
15248 } else {
15249 None
15250 }
15251 }
15252
15253 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15254 if self.selection_mark_mode {
15255 self.change_selections(None, window, cx, |s| {
15256 s.move_with(|_, sel| {
15257 sel.collapse_to(sel.head(), SelectionGoal::None);
15258 });
15259 })
15260 }
15261 self.selection_mark_mode = true;
15262 cx.notify();
15263 }
15264
15265 pub fn swap_selection_ends(
15266 &mut self,
15267 _: &actions::SwapSelectionEnds,
15268 window: &mut Window,
15269 cx: &mut Context<Self>,
15270 ) {
15271 self.change_selections(None, window, cx, |s| {
15272 s.move_with(|_, sel| {
15273 if sel.start != sel.end {
15274 sel.reversed = !sel.reversed
15275 }
15276 });
15277 });
15278 self.request_autoscroll(Autoscroll::newest(), cx);
15279 cx.notify();
15280 }
15281
15282 pub fn toggle_fold(
15283 &mut self,
15284 _: &actions::ToggleFold,
15285 window: &mut Window,
15286 cx: &mut Context<Self>,
15287 ) {
15288 if self.is_singleton(cx) {
15289 let selection = self.selections.newest::<Point>(cx);
15290
15291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15292 let range = if selection.is_empty() {
15293 let point = selection.head().to_display_point(&display_map);
15294 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15295 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15296 .to_point(&display_map);
15297 start..end
15298 } else {
15299 selection.range()
15300 };
15301 if display_map.folds_in_range(range).next().is_some() {
15302 self.unfold_lines(&Default::default(), window, cx)
15303 } else {
15304 self.fold(&Default::default(), window, cx)
15305 }
15306 } else {
15307 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15308 let buffer_ids: HashSet<_> = self
15309 .selections
15310 .disjoint_anchor_ranges()
15311 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15312 .collect();
15313
15314 let should_unfold = buffer_ids
15315 .iter()
15316 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15317
15318 for buffer_id in buffer_ids {
15319 if should_unfold {
15320 self.unfold_buffer(buffer_id, cx);
15321 } else {
15322 self.fold_buffer(buffer_id, cx);
15323 }
15324 }
15325 }
15326 }
15327
15328 pub fn toggle_fold_recursive(
15329 &mut self,
15330 _: &actions::ToggleFoldRecursive,
15331 window: &mut Window,
15332 cx: &mut Context<Self>,
15333 ) {
15334 let selection = self.selections.newest::<Point>(cx);
15335
15336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15337 let range = if selection.is_empty() {
15338 let point = selection.head().to_display_point(&display_map);
15339 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15340 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15341 .to_point(&display_map);
15342 start..end
15343 } else {
15344 selection.range()
15345 };
15346 if display_map.folds_in_range(range).next().is_some() {
15347 self.unfold_recursive(&Default::default(), window, cx)
15348 } else {
15349 self.fold_recursive(&Default::default(), window, cx)
15350 }
15351 }
15352
15353 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15354 if self.is_singleton(cx) {
15355 let mut to_fold = Vec::new();
15356 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15357 let selections = self.selections.all_adjusted(cx);
15358
15359 for selection in selections {
15360 let range = selection.range().sorted();
15361 let buffer_start_row = range.start.row;
15362
15363 if range.start.row != range.end.row {
15364 let mut found = false;
15365 let mut row = range.start.row;
15366 while row <= range.end.row {
15367 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15368 {
15369 found = true;
15370 row = crease.range().end.row + 1;
15371 to_fold.push(crease);
15372 } else {
15373 row += 1
15374 }
15375 }
15376 if found {
15377 continue;
15378 }
15379 }
15380
15381 for row in (0..=range.start.row).rev() {
15382 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15383 if crease.range().end.row >= buffer_start_row {
15384 to_fold.push(crease);
15385 if row <= range.start.row {
15386 break;
15387 }
15388 }
15389 }
15390 }
15391 }
15392
15393 self.fold_creases(to_fold, true, window, cx);
15394 } else {
15395 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15396 let buffer_ids = self
15397 .selections
15398 .disjoint_anchor_ranges()
15399 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15400 .collect::<HashSet<_>>();
15401 for buffer_id in buffer_ids {
15402 self.fold_buffer(buffer_id, cx);
15403 }
15404 }
15405 }
15406
15407 fn fold_at_level(
15408 &mut self,
15409 fold_at: &FoldAtLevel,
15410 window: &mut Window,
15411 cx: &mut Context<Self>,
15412 ) {
15413 if !self.buffer.read(cx).is_singleton() {
15414 return;
15415 }
15416
15417 let fold_at_level = fold_at.0;
15418 let snapshot = self.buffer.read(cx).snapshot(cx);
15419 let mut to_fold = Vec::new();
15420 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15421
15422 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15423 while start_row < end_row {
15424 match self
15425 .snapshot(window, cx)
15426 .crease_for_buffer_row(MultiBufferRow(start_row))
15427 {
15428 Some(crease) => {
15429 let nested_start_row = crease.range().start.row + 1;
15430 let nested_end_row = crease.range().end.row;
15431
15432 if current_level < fold_at_level {
15433 stack.push((nested_start_row, nested_end_row, current_level + 1));
15434 } else if current_level == fold_at_level {
15435 to_fold.push(crease);
15436 }
15437
15438 start_row = nested_end_row + 1;
15439 }
15440 None => start_row += 1,
15441 }
15442 }
15443 }
15444
15445 self.fold_creases(to_fold, true, window, cx);
15446 }
15447
15448 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15449 if self.buffer.read(cx).is_singleton() {
15450 let mut fold_ranges = Vec::new();
15451 let snapshot = self.buffer.read(cx).snapshot(cx);
15452
15453 for row in 0..snapshot.max_row().0 {
15454 if let Some(foldable_range) = self
15455 .snapshot(window, cx)
15456 .crease_for_buffer_row(MultiBufferRow(row))
15457 {
15458 fold_ranges.push(foldable_range);
15459 }
15460 }
15461
15462 self.fold_creases(fold_ranges, true, window, cx);
15463 } else {
15464 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15465 editor
15466 .update_in(cx, |editor, _, cx| {
15467 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15468 editor.fold_buffer(buffer_id, cx);
15469 }
15470 })
15471 .ok();
15472 });
15473 }
15474 }
15475
15476 pub fn fold_function_bodies(
15477 &mut self,
15478 _: &actions::FoldFunctionBodies,
15479 window: &mut Window,
15480 cx: &mut Context<Self>,
15481 ) {
15482 let snapshot = self.buffer.read(cx).snapshot(cx);
15483
15484 let ranges = snapshot
15485 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15486 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15487 .collect::<Vec<_>>();
15488
15489 let creases = ranges
15490 .into_iter()
15491 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15492 .collect();
15493
15494 self.fold_creases(creases, true, window, cx);
15495 }
15496
15497 pub fn fold_recursive(
15498 &mut self,
15499 _: &actions::FoldRecursive,
15500 window: &mut Window,
15501 cx: &mut Context<Self>,
15502 ) {
15503 let mut to_fold = Vec::new();
15504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15505 let selections = self.selections.all_adjusted(cx);
15506
15507 for selection in selections {
15508 let range = selection.range().sorted();
15509 let buffer_start_row = range.start.row;
15510
15511 if range.start.row != range.end.row {
15512 let mut found = false;
15513 for row in range.start.row..=range.end.row {
15514 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15515 found = true;
15516 to_fold.push(crease);
15517 }
15518 }
15519 if found {
15520 continue;
15521 }
15522 }
15523
15524 for row in (0..=range.start.row).rev() {
15525 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15526 if crease.range().end.row >= buffer_start_row {
15527 to_fold.push(crease);
15528 } else {
15529 break;
15530 }
15531 }
15532 }
15533 }
15534
15535 self.fold_creases(to_fold, true, window, cx);
15536 }
15537
15538 pub fn fold_at(
15539 &mut self,
15540 buffer_row: MultiBufferRow,
15541 window: &mut Window,
15542 cx: &mut Context<Self>,
15543 ) {
15544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15545
15546 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15547 let autoscroll = self
15548 .selections
15549 .all::<Point>(cx)
15550 .iter()
15551 .any(|selection| crease.range().overlaps(&selection.range()));
15552
15553 self.fold_creases(vec![crease], autoscroll, window, cx);
15554 }
15555 }
15556
15557 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15558 if self.is_singleton(cx) {
15559 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15560 let buffer = &display_map.buffer_snapshot;
15561 let selections = self.selections.all::<Point>(cx);
15562 let ranges = selections
15563 .iter()
15564 .map(|s| {
15565 let range = s.display_range(&display_map).sorted();
15566 let mut start = range.start.to_point(&display_map);
15567 let mut end = range.end.to_point(&display_map);
15568 start.column = 0;
15569 end.column = buffer.line_len(MultiBufferRow(end.row));
15570 start..end
15571 })
15572 .collect::<Vec<_>>();
15573
15574 self.unfold_ranges(&ranges, true, true, cx);
15575 } else {
15576 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15577 let buffer_ids = self
15578 .selections
15579 .disjoint_anchor_ranges()
15580 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15581 .collect::<HashSet<_>>();
15582 for buffer_id in buffer_ids {
15583 self.unfold_buffer(buffer_id, cx);
15584 }
15585 }
15586 }
15587
15588 pub fn unfold_recursive(
15589 &mut self,
15590 _: &UnfoldRecursive,
15591 _window: &mut Window,
15592 cx: &mut Context<Self>,
15593 ) {
15594 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15595 let selections = self.selections.all::<Point>(cx);
15596 let ranges = selections
15597 .iter()
15598 .map(|s| {
15599 let mut range = s.display_range(&display_map).sorted();
15600 *range.start.column_mut() = 0;
15601 *range.end.column_mut() = display_map.line_len(range.end.row());
15602 let start = range.start.to_point(&display_map);
15603 let end = range.end.to_point(&display_map);
15604 start..end
15605 })
15606 .collect::<Vec<_>>();
15607
15608 self.unfold_ranges(&ranges, true, true, cx);
15609 }
15610
15611 pub fn unfold_at(
15612 &mut self,
15613 buffer_row: MultiBufferRow,
15614 _window: &mut Window,
15615 cx: &mut Context<Self>,
15616 ) {
15617 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15618
15619 let intersection_range = Point::new(buffer_row.0, 0)
15620 ..Point::new(
15621 buffer_row.0,
15622 display_map.buffer_snapshot.line_len(buffer_row),
15623 );
15624
15625 let autoscroll = self
15626 .selections
15627 .all::<Point>(cx)
15628 .iter()
15629 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15630
15631 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15632 }
15633
15634 pub fn unfold_all(
15635 &mut self,
15636 _: &actions::UnfoldAll,
15637 _window: &mut Window,
15638 cx: &mut Context<Self>,
15639 ) {
15640 if self.buffer.read(cx).is_singleton() {
15641 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15642 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15643 } else {
15644 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15645 editor
15646 .update(cx, |editor, cx| {
15647 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15648 editor.unfold_buffer(buffer_id, cx);
15649 }
15650 })
15651 .ok();
15652 });
15653 }
15654 }
15655
15656 pub fn fold_selected_ranges(
15657 &mut self,
15658 _: &FoldSelectedRanges,
15659 window: &mut Window,
15660 cx: &mut Context<Self>,
15661 ) {
15662 let selections = self.selections.all_adjusted(cx);
15663 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15664 let ranges = selections
15665 .into_iter()
15666 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15667 .collect::<Vec<_>>();
15668 self.fold_creases(ranges, true, window, cx);
15669 }
15670
15671 pub fn fold_ranges<T: ToOffset + Clone>(
15672 &mut self,
15673 ranges: Vec<Range<T>>,
15674 auto_scroll: bool,
15675 window: &mut Window,
15676 cx: &mut Context<Self>,
15677 ) {
15678 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15679 let ranges = ranges
15680 .into_iter()
15681 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15682 .collect::<Vec<_>>();
15683 self.fold_creases(ranges, auto_scroll, window, cx);
15684 }
15685
15686 pub fn fold_creases<T: ToOffset + Clone>(
15687 &mut self,
15688 creases: Vec<Crease<T>>,
15689 auto_scroll: bool,
15690 _window: &mut Window,
15691 cx: &mut Context<Self>,
15692 ) {
15693 if creases.is_empty() {
15694 return;
15695 }
15696
15697 let mut buffers_affected = HashSet::default();
15698 let multi_buffer = self.buffer().read(cx);
15699 for crease in &creases {
15700 if let Some((_, buffer, _)) =
15701 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15702 {
15703 buffers_affected.insert(buffer.read(cx).remote_id());
15704 };
15705 }
15706
15707 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15708
15709 if auto_scroll {
15710 self.request_autoscroll(Autoscroll::fit(), cx);
15711 }
15712
15713 cx.notify();
15714
15715 self.scrollbar_marker_state.dirty = true;
15716 self.folds_did_change(cx);
15717 }
15718
15719 /// Removes any folds whose ranges intersect any of the given ranges.
15720 pub fn unfold_ranges<T: ToOffset + Clone>(
15721 &mut self,
15722 ranges: &[Range<T>],
15723 inclusive: bool,
15724 auto_scroll: bool,
15725 cx: &mut Context<Self>,
15726 ) {
15727 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15728 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15729 });
15730 self.folds_did_change(cx);
15731 }
15732
15733 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15734 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15735 return;
15736 }
15737 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15738 self.display_map.update(cx, |display_map, cx| {
15739 display_map.fold_buffers([buffer_id], cx)
15740 });
15741 cx.emit(EditorEvent::BufferFoldToggled {
15742 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15743 folded: true,
15744 });
15745 cx.notify();
15746 }
15747
15748 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15749 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15750 return;
15751 }
15752 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15753 self.display_map.update(cx, |display_map, cx| {
15754 display_map.unfold_buffers([buffer_id], cx);
15755 });
15756 cx.emit(EditorEvent::BufferFoldToggled {
15757 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15758 folded: false,
15759 });
15760 cx.notify();
15761 }
15762
15763 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15764 self.display_map.read(cx).is_buffer_folded(buffer)
15765 }
15766
15767 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15768 self.display_map.read(cx).folded_buffers()
15769 }
15770
15771 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15772 self.display_map.update(cx, |display_map, cx| {
15773 display_map.disable_header_for_buffer(buffer_id, cx);
15774 });
15775 cx.notify();
15776 }
15777
15778 /// Removes any folds with the given ranges.
15779 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15780 &mut self,
15781 ranges: &[Range<T>],
15782 type_id: TypeId,
15783 auto_scroll: bool,
15784 cx: &mut Context<Self>,
15785 ) {
15786 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15787 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15788 });
15789 self.folds_did_change(cx);
15790 }
15791
15792 fn remove_folds_with<T: ToOffset + Clone>(
15793 &mut self,
15794 ranges: &[Range<T>],
15795 auto_scroll: bool,
15796 cx: &mut Context<Self>,
15797 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15798 ) {
15799 if ranges.is_empty() {
15800 return;
15801 }
15802
15803 let mut buffers_affected = HashSet::default();
15804 let multi_buffer = self.buffer().read(cx);
15805 for range in ranges {
15806 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15807 buffers_affected.insert(buffer.read(cx).remote_id());
15808 };
15809 }
15810
15811 self.display_map.update(cx, update);
15812
15813 if auto_scroll {
15814 self.request_autoscroll(Autoscroll::fit(), cx);
15815 }
15816
15817 cx.notify();
15818 self.scrollbar_marker_state.dirty = true;
15819 self.active_indent_guides_state.dirty = true;
15820 }
15821
15822 pub fn update_fold_widths(
15823 &mut self,
15824 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15825 cx: &mut Context<Self>,
15826 ) -> bool {
15827 self.display_map
15828 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15829 }
15830
15831 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15832 self.display_map.read(cx).fold_placeholder.clone()
15833 }
15834
15835 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15836 self.buffer.update(cx, |buffer, cx| {
15837 buffer.set_all_diff_hunks_expanded(cx);
15838 });
15839 }
15840
15841 pub fn expand_all_diff_hunks(
15842 &mut self,
15843 _: &ExpandAllDiffHunks,
15844 _window: &mut Window,
15845 cx: &mut Context<Self>,
15846 ) {
15847 self.buffer.update(cx, |buffer, cx| {
15848 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15849 });
15850 }
15851
15852 pub fn toggle_selected_diff_hunks(
15853 &mut self,
15854 _: &ToggleSelectedDiffHunks,
15855 _window: &mut Window,
15856 cx: &mut Context<Self>,
15857 ) {
15858 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15859 self.toggle_diff_hunks_in_ranges(ranges, cx);
15860 }
15861
15862 pub fn diff_hunks_in_ranges<'a>(
15863 &'a self,
15864 ranges: &'a [Range<Anchor>],
15865 buffer: &'a MultiBufferSnapshot,
15866 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15867 ranges.iter().flat_map(move |range| {
15868 let end_excerpt_id = range.end.excerpt_id;
15869 let range = range.to_point(buffer);
15870 let mut peek_end = range.end;
15871 if range.end.row < buffer.max_row().0 {
15872 peek_end = Point::new(range.end.row + 1, 0);
15873 }
15874 buffer
15875 .diff_hunks_in_range(range.start..peek_end)
15876 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15877 })
15878 }
15879
15880 pub fn has_stageable_diff_hunks_in_ranges(
15881 &self,
15882 ranges: &[Range<Anchor>],
15883 snapshot: &MultiBufferSnapshot,
15884 ) -> bool {
15885 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15886 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15887 }
15888
15889 pub fn toggle_staged_selected_diff_hunks(
15890 &mut self,
15891 _: &::git::ToggleStaged,
15892 _: &mut Window,
15893 cx: &mut Context<Self>,
15894 ) {
15895 let snapshot = self.buffer.read(cx).snapshot(cx);
15896 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15897 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15898 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15899 }
15900
15901 pub fn set_render_diff_hunk_controls(
15902 &mut self,
15903 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15904 cx: &mut Context<Self>,
15905 ) {
15906 self.render_diff_hunk_controls = render_diff_hunk_controls;
15907 cx.notify();
15908 }
15909
15910 pub fn stage_and_next(
15911 &mut self,
15912 _: &::git::StageAndNext,
15913 window: &mut Window,
15914 cx: &mut Context<Self>,
15915 ) {
15916 self.do_stage_or_unstage_and_next(true, window, cx);
15917 }
15918
15919 pub fn unstage_and_next(
15920 &mut self,
15921 _: &::git::UnstageAndNext,
15922 window: &mut Window,
15923 cx: &mut Context<Self>,
15924 ) {
15925 self.do_stage_or_unstage_and_next(false, window, cx);
15926 }
15927
15928 pub fn stage_or_unstage_diff_hunks(
15929 &mut self,
15930 stage: bool,
15931 ranges: Vec<Range<Anchor>>,
15932 cx: &mut Context<Self>,
15933 ) {
15934 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15935 cx.spawn(async move |this, cx| {
15936 task.await?;
15937 this.update(cx, |this, cx| {
15938 let snapshot = this.buffer.read(cx).snapshot(cx);
15939 let chunk_by = this
15940 .diff_hunks_in_ranges(&ranges, &snapshot)
15941 .chunk_by(|hunk| hunk.buffer_id);
15942 for (buffer_id, hunks) in &chunk_by {
15943 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15944 }
15945 })
15946 })
15947 .detach_and_log_err(cx);
15948 }
15949
15950 fn save_buffers_for_ranges_if_needed(
15951 &mut self,
15952 ranges: &[Range<Anchor>],
15953 cx: &mut Context<Editor>,
15954 ) -> Task<Result<()>> {
15955 let multibuffer = self.buffer.read(cx);
15956 let snapshot = multibuffer.read(cx);
15957 let buffer_ids: HashSet<_> = ranges
15958 .iter()
15959 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15960 .collect();
15961 drop(snapshot);
15962
15963 let mut buffers = HashSet::default();
15964 for buffer_id in buffer_ids {
15965 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15966 let buffer = buffer_entity.read(cx);
15967 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15968 {
15969 buffers.insert(buffer_entity);
15970 }
15971 }
15972 }
15973
15974 if let Some(project) = &self.project {
15975 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15976 } else {
15977 Task::ready(Ok(()))
15978 }
15979 }
15980
15981 fn do_stage_or_unstage_and_next(
15982 &mut self,
15983 stage: bool,
15984 window: &mut Window,
15985 cx: &mut Context<Self>,
15986 ) {
15987 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15988
15989 if ranges.iter().any(|range| range.start != range.end) {
15990 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15991 return;
15992 }
15993
15994 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15995 let snapshot = self.snapshot(window, cx);
15996 let position = self.selections.newest::<Point>(cx).head();
15997 let mut row = snapshot
15998 .buffer_snapshot
15999 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
16000 .find(|hunk| hunk.row_range.start.0 > position.row)
16001 .map(|hunk| hunk.row_range.start);
16002
16003 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16004 // Outside of the project diff editor, wrap around to the beginning.
16005 if !all_diff_hunks_expanded {
16006 row = row.or_else(|| {
16007 snapshot
16008 .buffer_snapshot
16009 .diff_hunks_in_range(Point::zero()..position)
16010 .find(|hunk| hunk.row_range.end.0 < position.row)
16011 .map(|hunk| hunk.row_range.start)
16012 });
16013 }
16014
16015 if let Some(row) = row {
16016 let destination = Point::new(row.0, 0);
16017 let autoscroll = Autoscroll::center();
16018
16019 self.unfold_ranges(&[destination..destination], false, false, cx);
16020 self.change_selections(Some(autoscroll), window, cx, |s| {
16021 s.select_ranges([destination..destination]);
16022 });
16023 }
16024 }
16025
16026 fn do_stage_or_unstage(
16027 &self,
16028 stage: bool,
16029 buffer_id: BufferId,
16030 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16031 cx: &mut App,
16032 ) -> Option<()> {
16033 let project = self.project.as_ref()?;
16034 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16035 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16036 let buffer_snapshot = buffer.read(cx).snapshot();
16037 let file_exists = buffer_snapshot
16038 .file()
16039 .is_some_and(|file| file.disk_state().exists());
16040 diff.update(cx, |diff, cx| {
16041 diff.stage_or_unstage_hunks(
16042 stage,
16043 &hunks
16044 .map(|hunk| buffer_diff::DiffHunk {
16045 buffer_range: hunk.buffer_range,
16046 diff_base_byte_range: hunk.diff_base_byte_range,
16047 secondary_status: hunk.secondary_status,
16048 range: Point::zero()..Point::zero(), // unused
16049 })
16050 .collect::<Vec<_>>(),
16051 &buffer_snapshot,
16052 file_exists,
16053 cx,
16054 )
16055 });
16056 None
16057 }
16058
16059 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16060 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16061 self.buffer
16062 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16063 }
16064
16065 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16066 self.buffer.update(cx, |buffer, cx| {
16067 let ranges = vec![Anchor::min()..Anchor::max()];
16068 if !buffer.all_diff_hunks_expanded()
16069 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16070 {
16071 buffer.collapse_diff_hunks(ranges, cx);
16072 true
16073 } else {
16074 false
16075 }
16076 })
16077 }
16078
16079 fn toggle_diff_hunks_in_ranges(
16080 &mut self,
16081 ranges: Vec<Range<Anchor>>,
16082 cx: &mut Context<Editor>,
16083 ) {
16084 self.buffer.update(cx, |buffer, cx| {
16085 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16086 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16087 })
16088 }
16089
16090 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16091 self.buffer.update(cx, |buffer, cx| {
16092 let snapshot = buffer.snapshot(cx);
16093 let excerpt_id = range.end.excerpt_id;
16094 let point_range = range.to_point(&snapshot);
16095 let expand = !buffer.single_hunk_is_expanded(range, cx);
16096 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16097 })
16098 }
16099
16100 pub(crate) fn apply_all_diff_hunks(
16101 &mut self,
16102 _: &ApplyAllDiffHunks,
16103 window: &mut Window,
16104 cx: &mut Context<Self>,
16105 ) {
16106 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16107
16108 let buffers = self.buffer.read(cx).all_buffers();
16109 for branch_buffer in buffers {
16110 branch_buffer.update(cx, |branch_buffer, cx| {
16111 branch_buffer.merge_into_base(Vec::new(), cx);
16112 });
16113 }
16114
16115 if let Some(project) = self.project.clone() {
16116 self.save(true, project, window, cx).detach_and_log_err(cx);
16117 }
16118 }
16119
16120 pub(crate) fn apply_selected_diff_hunks(
16121 &mut self,
16122 _: &ApplyDiffHunk,
16123 window: &mut Window,
16124 cx: &mut Context<Self>,
16125 ) {
16126 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16127 let snapshot = self.snapshot(window, cx);
16128 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16129 let mut ranges_by_buffer = HashMap::default();
16130 self.transact(window, cx, |editor, _window, cx| {
16131 for hunk in hunks {
16132 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16133 ranges_by_buffer
16134 .entry(buffer.clone())
16135 .or_insert_with(Vec::new)
16136 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16137 }
16138 }
16139
16140 for (buffer, ranges) in ranges_by_buffer {
16141 buffer.update(cx, |buffer, cx| {
16142 buffer.merge_into_base(ranges, cx);
16143 });
16144 }
16145 });
16146
16147 if let Some(project) = self.project.clone() {
16148 self.save(true, project, window, cx).detach_and_log_err(cx);
16149 }
16150 }
16151
16152 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16153 if hovered != self.gutter_hovered {
16154 self.gutter_hovered = hovered;
16155 cx.notify();
16156 }
16157 }
16158
16159 pub fn insert_blocks(
16160 &mut self,
16161 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16162 autoscroll: Option<Autoscroll>,
16163 cx: &mut Context<Self>,
16164 ) -> Vec<CustomBlockId> {
16165 let blocks = self
16166 .display_map
16167 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16168 if let Some(autoscroll) = autoscroll {
16169 self.request_autoscroll(autoscroll, cx);
16170 }
16171 cx.notify();
16172 blocks
16173 }
16174
16175 pub fn resize_blocks(
16176 &mut self,
16177 heights: HashMap<CustomBlockId, u32>,
16178 autoscroll: Option<Autoscroll>,
16179 cx: &mut Context<Self>,
16180 ) {
16181 self.display_map
16182 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16183 if let Some(autoscroll) = autoscroll {
16184 self.request_autoscroll(autoscroll, cx);
16185 }
16186 cx.notify();
16187 }
16188
16189 pub fn replace_blocks(
16190 &mut self,
16191 renderers: HashMap<CustomBlockId, RenderBlock>,
16192 autoscroll: Option<Autoscroll>,
16193 cx: &mut Context<Self>,
16194 ) {
16195 self.display_map
16196 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16197 if let Some(autoscroll) = autoscroll {
16198 self.request_autoscroll(autoscroll, cx);
16199 }
16200 cx.notify();
16201 }
16202
16203 pub fn remove_blocks(
16204 &mut self,
16205 block_ids: HashSet<CustomBlockId>,
16206 autoscroll: Option<Autoscroll>,
16207 cx: &mut Context<Self>,
16208 ) {
16209 self.display_map.update(cx, |display_map, cx| {
16210 display_map.remove_blocks(block_ids, cx)
16211 });
16212 if let Some(autoscroll) = autoscroll {
16213 self.request_autoscroll(autoscroll, cx);
16214 }
16215 cx.notify();
16216 }
16217
16218 pub fn row_for_block(
16219 &self,
16220 block_id: CustomBlockId,
16221 cx: &mut Context<Self>,
16222 ) -> Option<DisplayRow> {
16223 self.display_map
16224 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16225 }
16226
16227 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16228 self.focused_block = Some(focused_block);
16229 }
16230
16231 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16232 self.focused_block.take()
16233 }
16234
16235 pub fn insert_creases(
16236 &mut self,
16237 creases: impl IntoIterator<Item = Crease<Anchor>>,
16238 cx: &mut Context<Self>,
16239 ) -> Vec<CreaseId> {
16240 self.display_map
16241 .update(cx, |map, cx| map.insert_creases(creases, cx))
16242 }
16243
16244 pub fn remove_creases(
16245 &mut self,
16246 ids: impl IntoIterator<Item = CreaseId>,
16247 cx: &mut Context<Self>,
16248 ) -> Vec<(CreaseId, Range<Anchor>)> {
16249 self.display_map
16250 .update(cx, |map, cx| map.remove_creases(ids, cx))
16251 }
16252
16253 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16254 self.display_map
16255 .update(cx, |map, cx| map.snapshot(cx))
16256 .longest_row()
16257 }
16258
16259 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16260 self.display_map
16261 .update(cx, |map, cx| map.snapshot(cx))
16262 .max_point()
16263 }
16264
16265 pub fn text(&self, cx: &App) -> String {
16266 self.buffer.read(cx).read(cx).text()
16267 }
16268
16269 pub fn is_empty(&self, cx: &App) -> bool {
16270 self.buffer.read(cx).read(cx).is_empty()
16271 }
16272
16273 pub fn text_option(&self, cx: &App) -> Option<String> {
16274 let text = self.text(cx);
16275 let text = text.trim();
16276
16277 if text.is_empty() {
16278 return None;
16279 }
16280
16281 Some(text.to_string())
16282 }
16283
16284 pub fn set_text(
16285 &mut self,
16286 text: impl Into<Arc<str>>,
16287 window: &mut Window,
16288 cx: &mut Context<Self>,
16289 ) {
16290 self.transact(window, cx, |this, _, cx| {
16291 this.buffer
16292 .read(cx)
16293 .as_singleton()
16294 .expect("you can only call set_text on editors for singleton buffers")
16295 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16296 });
16297 }
16298
16299 pub fn display_text(&self, cx: &mut App) -> String {
16300 self.display_map
16301 .update(cx, |map, cx| map.snapshot(cx))
16302 .text()
16303 }
16304
16305 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16306 let mut wrap_guides = smallvec::smallvec![];
16307
16308 if self.show_wrap_guides == Some(false) {
16309 return wrap_guides;
16310 }
16311
16312 let settings = self.buffer.read(cx).language_settings(cx);
16313 if settings.show_wrap_guides {
16314 match self.soft_wrap_mode(cx) {
16315 SoftWrap::Column(soft_wrap) => {
16316 wrap_guides.push((soft_wrap as usize, true));
16317 }
16318 SoftWrap::Bounded(soft_wrap) => {
16319 wrap_guides.push((soft_wrap as usize, true));
16320 }
16321 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16322 }
16323 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16324 }
16325
16326 wrap_guides
16327 }
16328
16329 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16330 let settings = self.buffer.read(cx).language_settings(cx);
16331 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16332 match mode {
16333 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16334 SoftWrap::None
16335 }
16336 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16337 language_settings::SoftWrap::PreferredLineLength => {
16338 SoftWrap::Column(settings.preferred_line_length)
16339 }
16340 language_settings::SoftWrap::Bounded => {
16341 SoftWrap::Bounded(settings.preferred_line_length)
16342 }
16343 }
16344 }
16345
16346 pub fn set_soft_wrap_mode(
16347 &mut self,
16348 mode: language_settings::SoftWrap,
16349
16350 cx: &mut Context<Self>,
16351 ) {
16352 self.soft_wrap_mode_override = Some(mode);
16353 cx.notify();
16354 }
16355
16356 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16357 self.hard_wrap = hard_wrap;
16358 cx.notify();
16359 }
16360
16361 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16362 self.text_style_refinement = Some(style);
16363 }
16364
16365 /// called by the Element so we know what style we were most recently rendered with.
16366 pub(crate) fn set_style(
16367 &mut self,
16368 style: EditorStyle,
16369 window: &mut Window,
16370 cx: &mut Context<Self>,
16371 ) {
16372 let rem_size = window.rem_size();
16373 self.display_map.update(cx, |map, cx| {
16374 map.set_font(
16375 style.text.font(),
16376 style.text.font_size.to_pixels(rem_size),
16377 cx,
16378 )
16379 });
16380 self.style = Some(style);
16381 }
16382
16383 pub fn style(&self) -> Option<&EditorStyle> {
16384 self.style.as_ref()
16385 }
16386
16387 // Called by the element. This method is not designed to be called outside of the editor
16388 // element's layout code because it does not notify when rewrapping is computed synchronously.
16389 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16390 self.display_map
16391 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16392 }
16393
16394 pub fn set_soft_wrap(&mut self) {
16395 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16396 }
16397
16398 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16399 if self.soft_wrap_mode_override.is_some() {
16400 self.soft_wrap_mode_override.take();
16401 } else {
16402 let soft_wrap = match self.soft_wrap_mode(cx) {
16403 SoftWrap::GitDiff => return,
16404 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16405 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16406 language_settings::SoftWrap::None
16407 }
16408 };
16409 self.soft_wrap_mode_override = Some(soft_wrap);
16410 }
16411 cx.notify();
16412 }
16413
16414 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16415 let Some(workspace) = self.workspace() else {
16416 return;
16417 };
16418 let fs = workspace.read(cx).app_state().fs.clone();
16419 let current_show = TabBarSettings::get_global(cx).show;
16420 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16421 setting.show = Some(!current_show);
16422 });
16423 }
16424
16425 pub fn toggle_indent_guides(
16426 &mut self,
16427 _: &ToggleIndentGuides,
16428 _: &mut Window,
16429 cx: &mut Context<Self>,
16430 ) {
16431 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16432 self.buffer
16433 .read(cx)
16434 .language_settings(cx)
16435 .indent_guides
16436 .enabled
16437 });
16438 self.show_indent_guides = Some(!currently_enabled);
16439 cx.notify();
16440 }
16441
16442 fn should_show_indent_guides(&self) -> Option<bool> {
16443 self.show_indent_guides
16444 }
16445
16446 pub fn toggle_line_numbers(
16447 &mut self,
16448 _: &ToggleLineNumbers,
16449 _: &mut Window,
16450 cx: &mut Context<Self>,
16451 ) {
16452 let mut editor_settings = EditorSettings::get_global(cx).clone();
16453 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16454 EditorSettings::override_global(editor_settings, cx);
16455 }
16456
16457 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16458 if let Some(show_line_numbers) = self.show_line_numbers {
16459 return show_line_numbers;
16460 }
16461 EditorSettings::get_global(cx).gutter.line_numbers
16462 }
16463
16464 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16465 self.use_relative_line_numbers
16466 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16467 }
16468
16469 pub fn toggle_relative_line_numbers(
16470 &mut self,
16471 _: &ToggleRelativeLineNumbers,
16472 _: &mut Window,
16473 cx: &mut Context<Self>,
16474 ) {
16475 let is_relative = self.should_use_relative_line_numbers(cx);
16476 self.set_relative_line_number(Some(!is_relative), cx)
16477 }
16478
16479 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16480 self.use_relative_line_numbers = is_relative;
16481 cx.notify();
16482 }
16483
16484 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16485 self.show_gutter = show_gutter;
16486 cx.notify();
16487 }
16488
16489 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16490 self.show_scrollbars = show_scrollbars;
16491 cx.notify();
16492 }
16493
16494 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16495 self.show_line_numbers = Some(show_line_numbers);
16496 cx.notify();
16497 }
16498
16499 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16500 self.disable_expand_excerpt_buttons = true;
16501 cx.notify();
16502 }
16503
16504 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16505 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16506 cx.notify();
16507 }
16508
16509 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16510 self.show_code_actions = Some(show_code_actions);
16511 cx.notify();
16512 }
16513
16514 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16515 self.show_runnables = Some(show_runnables);
16516 cx.notify();
16517 }
16518
16519 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16520 self.show_breakpoints = Some(show_breakpoints);
16521 cx.notify();
16522 }
16523
16524 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16525 if self.display_map.read(cx).masked != masked {
16526 self.display_map.update(cx, |map, _| map.masked = masked);
16527 }
16528 cx.notify()
16529 }
16530
16531 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16532 self.show_wrap_guides = Some(show_wrap_guides);
16533 cx.notify();
16534 }
16535
16536 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16537 self.show_indent_guides = Some(show_indent_guides);
16538 cx.notify();
16539 }
16540
16541 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16542 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16543 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16544 if let Some(dir) = file.abs_path(cx).parent() {
16545 return Some(dir.to_owned());
16546 }
16547 }
16548
16549 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16550 return Some(project_path.path.to_path_buf());
16551 }
16552 }
16553
16554 None
16555 }
16556
16557 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16558 self.active_excerpt(cx)?
16559 .1
16560 .read(cx)
16561 .file()
16562 .and_then(|f| f.as_local())
16563 }
16564
16565 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16566 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16567 let buffer = buffer.read(cx);
16568 if let Some(project_path) = buffer.project_path(cx) {
16569 let project = self.project.as_ref()?.read(cx);
16570 project.absolute_path(&project_path, cx)
16571 } else {
16572 buffer
16573 .file()
16574 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16575 }
16576 })
16577 }
16578
16579 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16580 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16581 let project_path = buffer.read(cx).project_path(cx)?;
16582 let project = self.project.as_ref()?.read(cx);
16583 let entry = project.entry_for_path(&project_path, cx)?;
16584 let path = entry.path.to_path_buf();
16585 Some(path)
16586 })
16587 }
16588
16589 pub fn reveal_in_finder(
16590 &mut self,
16591 _: &RevealInFileManager,
16592 _window: &mut Window,
16593 cx: &mut Context<Self>,
16594 ) {
16595 if let Some(target) = self.target_file(cx) {
16596 cx.reveal_path(&target.abs_path(cx));
16597 }
16598 }
16599
16600 pub fn copy_path(
16601 &mut self,
16602 _: &zed_actions::workspace::CopyPath,
16603 _window: &mut Window,
16604 cx: &mut Context<Self>,
16605 ) {
16606 if let Some(path) = self.target_file_abs_path(cx) {
16607 if let Some(path) = path.to_str() {
16608 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16609 }
16610 }
16611 }
16612
16613 pub fn copy_relative_path(
16614 &mut self,
16615 _: &zed_actions::workspace::CopyRelativePath,
16616 _window: &mut Window,
16617 cx: &mut Context<Self>,
16618 ) {
16619 if let Some(path) = self.target_file_path(cx) {
16620 if let Some(path) = path.to_str() {
16621 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16622 }
16623 }
16624 }
16625
16626 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16627 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16628 buffer.read(cx).project_path(cx)
16629 } else {
16630 None
16631 }
16632 }
16633
16634 // Returns true if the editor handled a go-to-line request
16635 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16636 maybe!({
16637 let breakpoint_store = self.breakpoint_store.as_ref()?;
16638
16639 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16640 else {
16641 self.clear_row_highlights::<ActiveDebugLine>();
16642 return None;
16643 };
16644
16645 let position = active_stack_frame.position;
16646 let buffer_id = position.buffer_id?;
16647 let snapshot = self
16648 .project
16649 .as_ref()?
16650 .read(cx)
16651 .buffer_for_id(buffer_id, cx)?
16652 .read(cx)
16653 .snapshot();
16654
16655 let mut handled = false;
16656 for (id, ExcerptRange { context, .. }) in
16657 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16658 {
16659 if context.start.cmp(&position, &snapshot).is_ge()
16660 || context.end.cmp(&position, &snapshot).is_lt()
16661 {
16662 continue;
16663 }
16664 let snapshot = self.buffer.read(cx).snapshot(cx);
16665 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16666
16667 handled = true;
16668 self.clear_row_highlights::<ActiveDebugLine>();
16669 self.go_to_line::<ActiveDebugLine>(
16670 multibuffer_anchor,
16671 Some(cx.theme().colors().editor_debugger_active_line_background),
16672 window,
16673 cx,
16674 );
16675
16676 cx.notify();
16677 }
16678
16679 handled.then_some(())
16680 })
16681 .is_some()
16682 }
16683
16684 pub fn copy_file_name_without_extension(
16685 &mut self,
16686 _: &CopyFileNameWithoutExtension,
16687 _: &mut Window,
16688 cx: &mut Context<Self>,
16689 ) {
16690 if let Some(file) = self.target_file(cx) {
16691 if let Some(file_stem) = file.path().file_stem() {
16692 if let Some(name) = file_stem.to_str() {
16693 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16694 }
16695 }
16696 }
16697 }
16698
16699 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16700 if let Some(file) = self.target_file(cx) {
16701 if let Some(file_name) = file.path().file_name() {
16702 if let Some(name) = file_name.to_str() {
16703 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16704 }
16705 }
16706 }
16707 }
16708
16709 pub fn toggle_git_blame(
16710 &mut self,
16711 _: &::git::Blame,
16712 window: &mut Window,
16713 cx: &mut Context<Self>,
16714 ) {
16715 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16716
16717 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16718 self.start_git_blame(true, window, cx);
16719 }
16720
16721 cx.notify();
16722 }
16723
16724 pub fn toggle_git_blame_inline(
16725 &mut self,
16726 _: &ToggleGitBlameInline,
16727 window: &mut Window,
16728 cx: &mut Context<Self>,
16729 ) {
16730 self.toggle_git_blame_inline_internal(true, window, cx);
16731 cx.notify();
16732 }
16733
16734 pub fn open_git_blame_commit(
16735 &mut self,
16736 _: &OpenGitBlameCommit,
16737 window: &mut Window,
16738 cx: &mut Context<Self>,
16739 ) {
16740 self.open_git_blame_commit_internal(window, cx);
16741 }
16742
16743 fn open_git_blame_commit_internal(
16744 &mut self,
16745 window: &mut Window,
16746 cx: &mut Context<Self>,
16747 ) -> Option<()> {
16748 let blame = self.blame.as_ref()?;
16749 let snapshot = self.snapshot(window, cx);
16750 let cursor = self.selections.newest::<Point>(cx).head();
16751 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16752 let blame_entry = blame
16753 .update(cx, |blame, cx| {
16754 blame
16755 .blame_for_rows(
16756 &[RowInfo {
16757 buffer_id: Some(buffer.remote_id()),
16758 buffer_row: Some(point.row),
16759 ..Default::default()
16760 }],
16761 cx,
16762 )
16763 .next()
16764 })
16765 .flatten()?;
16766 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16767 let repo = blame.read(cx).repository(cx)?;
16768 let workspace = self.workspace()?.downgrade();
16769 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16770 None
16771 }
16772
16773 pub fn git_blame_inline_enabled(&self) -> bool {
16774 self.git_blame_inline_enabled
16775 }
16776
16777 pub fn toggle_selection_menu(
16778 &mut self,
16779 _: &ToggleSelectionMenu,
16780 _: &mut Window,
16781 cx: &mut Context<Self>,
16782 ) {
16783 self.show_selection_menu = self
16784 .show_selection_menu
16785 .map(|show_selections_menu| !show_selections_menu)
16786 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16787
16788 cx.notify();
16789 }
16790
16791 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16792 self.show_selection_menu
16793 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16794 }
16795
16796 fn start_git_blame(
16797 &mut self,
16798 user_triggered: bool,
16799 window: &mut Window,
16800 cx: &mut Context<Self>,
16801 ) {
16802 if let Some(project) = self.project.as_ref() {
16803 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16804 return;
16805 };
16806
16807 if buffer.read(cx).file().is_none() {
16808 return;
16809 }
16810
16811 let focused = self.focus_handle(cx).contains_focused(window, cx);
16812
16813 let project = project.clone();
16814 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16815 self.blame_subscription =
16816 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16817 self.blame = Some(blame);
16818 }
16819 }
16820
16821 fn toggle_git_blame_inline_internal(
16822 &mut self,
16823 user_triggered: bool,
16824 window: &mut Window,
16825 cx: &mut Context<Self>,
16826 ) {
16827 if self.git_blame_inline_enabled {
16828 self.git_blame_inline_enabled = false;
16829 self.show_git_blame_inline = false;
16830 self.show_git_blame_inline_delay_task.take();
16831 } else {
16832 self.git_blame_inline_enabled = true;
16833 self.start_git_blame_inline(user_triggered, window, cx);
16834 }
16835
16836 cx.notify();
16837 }
16838
16839 fn start_git_blame_inline(
16840 &mut self,
16841 user_triggered: bool,
16842 window: &mut Window,
16843 cx: &mut Context<Self>,
16844 ) {
16845 self.start_git_blame(user_triggered, window, cx);
16846
16847 if ProjectSettings::get_global(cx)
16848 .git
16849 .inline_blame_delay()
16850 .is_some()
16851 {
16852 self.start_inline_blame_timer(window, cx);
16853 } else {
16854 self.show_git_blame_inline = true
16855 }
16856 }
16857
16858 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16859 self.blame.as_ref()
16860 }
16861
16862 pub fn show_git_blame_gutter(&self) -> bool {
16863 self.show_git_blame_gutter
16864 }
16865
16866 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16867 self.show_git_blame_gutter && self.has_blame_entries(cx)
16868 }
16869
16870 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16871 self.show_git_blame_inline
16872 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16873 && !self.newest_selection_head_on_empty_line(cx)
16874 && self.has_blame_entries(cx)
16875 }
16876
16877 fn has_blame_entries(&self, cx: &App) -> bool {
16878 self.blame()
16879 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16880 }
16881
16882 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16883 let cursor_anchor = self.selections.newest_anchor().head();
16884
16885 let snapshot = self.buffer.read(cx).snapshot(cx);
16886 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16887
16888 snapshot.line_len(buffer_row) == 0
16889 }
16890
16891 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16892 let buffer_and_selection = maybe!({
16893 let selection = self.selections.newest::<Point>(cx);
16894 let selection_range = selection.range();
16895
16896 let multi_buffer = self.buffer().read(cx);
16897 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16898 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16899
16900 let (buffer, range, _) = if selection.reversed {
16901 buffer_ranges.first()
16902 } else {
16903 buffer_ranges.last()
16904 }?;
16905
16906 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16907 ..text::ToPoint::to_point(&range.end, &buffer).row;
16908 Some((
16909 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16910 selection,
16911 ))
16912 });
16913
16914 let Some((buffer, selection)) = buffer_and_selection else {
16915 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16916 };
16917
16918 let Some(project) = self.project.as_ref() else {
16919 return Task::ready(Err(anyhow!("editor does not have project")));
16920 };
16921
16922 project.update(cx, |project, cx| {
16923 project.get_permalink_to_line(&buffer, selection, cx)
16924 })
16925 }
16926
16927 pub fn copy_permalink_to_line(
16928 &mut self,
16929 _: &CopyPermalinkToLine,
16930 window: &mut Window,
16931 cx: &mut Context<Self>,
16932 ) {
16933 let permalink_task = self.get_permalink_to_line(cx);
16934 let workspace = self.workspace();
16935
16936 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16937 Ok(permalink) => {
16938 cx.update(|_, cx| {
16939 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16940 })
16941 .ok();
16942 }
16943 Err(err) => {
16944 let message = format!("Failed to copy permalink: {err}");
16945
16946 Err::<(), anyhow::Error>(err).log_err();
16947
16948 if let Some(workspace) = workspace {
16949 workspace
16950 .update_in(cx, |workspace, _, cx| {
16951 struct CopyPermalinkToLine;
16952
16953 workspace.show_toast(
16954 Toast::new(
16955 NotificationId::unique::<CopyPermalinkToLine>(),
16956 message,
16957 ),
16958 cx,
16959 )
16960 })
16961 .ok();
16962 }
16963 }
16964 })
16965 .detach();
16966 }
16967
16968 pub fn copy_file_location(
16969 &mut self,
16970 _: &CopyFileLocation,
16971 _: &mut Window,
16972 cx: &mut Context<Self>,
16973 ) {
16974 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16975 if let Some(file) = self.target_file(cx) {
16976 if let Some(path) = file.path().to_str() {
16977 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16978 }
16979 }
16980 }
16981
16982 pub fn open_permalink_to_line(
16983 &mut self,
16984 _: &OpenPermalinkToLine,
16985 window: &mut Window,
16986 cx: &mut Context<Self>,
16987 ) {
16988 let permalink_task = self.get_permalink_to_line(cx);
16989 let workspace = self.workspace();
16990
16991 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16992 Ok(permalink) => {
16993 cx.update(|_, cx| {
16994 cx.open_url(permalink.as_ref());
16995 })
16996 .ok();
16997 }
16998 Err(err) => {
16999 let message = format!("Failed to open permalink: {err}");
17000
17001 Err::<(), anyhow::Error>(err).log_err();
17002
17003 if let Some(workspace) = workspace {
17004 workspace
17005 .update(cx, |workspace, cx| {
17006 struct OpenPermalinkToLine;
17007
17008 workspace.show_toast(
17009 Toast::new(
17010 NotificationId::unique::<OpenPermalinkToLine>(),
17011 message,
17012 ),
17013 cx,
17014 )
17015 })
17016 .ok();
17017 }
17018 }
17019 })
17020 .detach();
17021 }
17022
17023 pub fn insert_uuid_v4(
17024 &mut self,
17025 _: &InsertUuidV4,
17026 window: &mut Window,
17027 cx: &mut Context<Self>,
17028 ) {
17029 self.insert_uuid(UuidVersion::V4, window, cx);
17030 }
17031
17032 pub fn insert_uuid_v7(
17033 &mut self,
17034 _: &InsertUuidV7,
17035 window: &mut Window,
17036 cx: &mut Context<Self>,
17037 ) {
17038 self.insert_uuid(UuidVersion::V7, window, cx);
17039 }
17040
17041 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17042 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17043 self.transact(window, cx, |this, window, cx| {
17044 let edits = this
17045 .selections
17046 .all::<Point>(cx)
17047 .into_iter()
17048 .map(|selection| {
17049 let uuid = match version {
17050 UuidVersion::V4 => uuid::Uuid::new_v4(),
17051 UuidVersion::V7 => uuid::Uuid::now_v7(),
17052 };
17053
17054 (selection.range(), uuid.to_string())
17055 });
17056 this.edit(edits, cx);
17057 this.refresh_inline_completion(true, false, window, cx);
17058 });
17059 }
17060
17061 pub fn open_selections_in_multibuffer(
17062 &mut self,
17063 _: &OpenSelectionsInMultibuffer,
17064 window: &mut Window,
17065 cx: &mut Context<Self>,
17066 ) {
17067 let multibuffer = self.buffer.read(cx);
17068
17069 let Some(buffer) = multibuffer.as_singleton() else {
17070 return;
17071 };
17072
17073 let Some(workspace) = self.workspace() else {
17074 return;
17075 };
17076
17077 let locations = self
17078 .selections
17079 .disjoint_anchors()
17080 .iter()
17081 .map(|range| Location {
17082 buffer: buffer.clone(),
17083 range: range.start.text_anchor..range.end.text_anchor,
17084 })
17085 .collect::<Vec<_>>();
17086
17087 let title = multibuffer.title(cx).to_string();
17088
17089 cx.spawn_in(window, async move |_, cx| {
17090 workspace.update_in(cx, |workspace, window, cx| {
17091 Self::open_locations_in_multibuffer(
17092 workspace,
17093 locations,
17094 format!("Selections for '{title}'"),
17095 false,
17096 MultibufferSelectionMode::All,
17097 window,
17098 cx,
17099 );
17100 })
17101 })
17102 .detach();
17103 }
17104
17105 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17106 /// last highlight added will be used.
17107 ///
17108 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17109 pub fn highlight_rows<T: 'static>(
17110 &mut self,
17111 range: Range<Anchor>,
17112 color: Hsla,
17113 options: RowHighlightOptions,
17114 cx: &mut Context<Self>,
17115 ) {
17116 let snapshot = self.buffer().read(cx).snapshot(cx);
17117 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17118 let ix = row_highlights.binary_search_by(|highlight| {
17119 Ordering::Equal
17120 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17121 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17122 });
17123
17124 if let Err(mut ix) = ix {
17125 let index = post_inc(&mut self.highlight_order);
17126
17127 // If this range intersects with the preceding highlight, then merge it with
17128 // the preceding highlight. Otherwise insert a new highlight.
17129 let mut merged = false;
17130 if ix > 0 {
17131 let prev_highlight = &mut row_highlights[ix - 1];
17132 if prev_highlight
17133 .range
17134 .end
17135 .cmp(&range.start, &snapshot)
17136 .is_ge()
17137 {
17138 ix -= 1;
17139 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17140 prev_highlight.range.end = range.end;
17141 }
17142 merged = true;
17143 prev_highlight.index = index;
17144 prev_highlight.color = color;
17145 prev_highlight.options = options;
17146 }
17147 }
17148
17149 if !merged {
17150 row_highlights.insert(
17151 ix,
17152 RowHighlight {
17153 range: range.clone(),
17154 index,
17155 color,
17156 options,
17157 type_id: TypeId::of::<T>(),
17158 },
17159 );
17160 }
17161
17162 // If any of the following highlights intersect with this one, merge them.
17163 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17164 let highlight = &row_highlights[ix];
17165 if next_highlight
17166 .range
17167 .start
17168 .cmp(&highlight.range.end, &snapshot)
17169 .is_le()
17170 {
17171 if next_highlight
17172 .range
17173 .end
17174 .cmp(&highlight.range.end, &snapshot)
17175 .is_gt()
17176 {
17177 row_highlights[ix].range.end = next_highlight.range.end;
17178 }
17179 row_highlights.remove(ix + 1);
17180 } else {
17181 break;
17182 }
17183 }
17184 }
17185 }
17186
17187 /// Remove any highlighted row ranges of the given type that intersect the
17188 /// given ranges.
17189 pub fn remove_highlighted_rows<T: 'static>(
17190 &mut self,
17191 ranges_to_remove: Vec<Range<Anchor>>,
17192 cx: &mut Context<Self>,
17193 ) {
17194 let snapshot = self.buffer().read(cx).snapshot(cx);
17195 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17196 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17197 row_highlights.retain(|highlight| {
17198 while let Some(range_to_remove) = ranges_to_remove.peek() {
17199 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17200 Ordering::Less | Ordering::Equal => {
17201 ranges_to_remove.next();
17202 }
17203 Ordering::Greater => {
17204 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17205 Ordering::Less | Ordering::Equal => {
17206 return false;
17207 }
17208 Ordering::Greater => break,
17209 }
17210 }
17211 }
17212 }
17213
17214 true
17215 })
17216 }
17217
17218 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17219 pub fn clear_row_highlights<T: 'static>(&mut self) {
17220 self.highlighted_rows.remove(&TypeId::of::<T>());
17221 }
17222
17223 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17224 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17225 self.highlighted_rows
17226 .get(&TypeId::of::<T>())
17227 .map_or(&[] as &[_], |vec| vec.as_slice())
17228 .iter()
17229 .map(|highlight| (highlight.range.clone(), highlight.color))
17230 }
17231
17232 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17233 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17234 /// Allows to ignore certain kinds of highlights.
17235 pub fn highlighted_display_rows(
17236 &self,
17237 window: &mut Window,
17238 cx: &mut App,
17239 ) -> BTreeMap<DisplayRow, LineHighlight> {
17240 let snapshot = self.snapshot(window, cx);
17241 let mut used_highlight_orders = HashMap::default();
17242 self.highlighted_rows
17243 .iter()
17244 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17245 .fold(
17246 BTreeMap::<DisplayRow, LineHighlight>::new(),
17247 |mut unique_rows, highlight| {
17248 let start = highlight.range.start.to_display_point(&snapshot);
17249 let end = highlight.range.end.to_display_point(&snapshot);
17250 let start_row = start.row().0;
17251 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17252 && end.column() == 0
17253 {
17254 end.row().0.saturating_sub(1)
17255 } else {
17256 end.row().0
17257 };
17258 for row in start_row..=end_row {
17259 let used_index =
17260 used_highlight_orders.entry(row).or_insert(highlight.index);
17261 if highlight.index >= *used_index {
17262 *used_index = highlight.index;
17263 unique_rows.insert(
17264 DisplayRow(row),
17265 LineHighlight {
17266 include_gutter: highlight.options.include_gutter,
17267 border: None,
17268 background: highlight.color.into(),
17269 type_id: Some(highlight.type_id),
17270 },
17271 );
17272 }
17273 }
17274 unique_rows
17275 },
17276 )
17277 }
17278
17279 pub fn highlighted_display_row_for_autoscroll(
17280 &self,
17281 snapshot: &DisplaySnapshot,
17282 ) -> Option<DisplayRow> {
17283 self.highlighted_rows
17284 .values()
17285 .flat_map(|highlighted_rows| highlighted_rows.iter())
17286 .filter_map(|highlight| {
17287 if highlight.options.autoscroll {
17288 Some(highlight.range.start.to_display_point(snapshot).row())
17289 } else {
17290 None
17291 }
17292 })
17293 .min()
17294 }
17295
17296 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17297 self.highlight_background::<SearchWithinRange>(
17298 ranges,
17299 |colors| colors.editor_document_highlight_read_background,
17300 cx,
17301 )
17302 }
17303
17304 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17305 self.breadcrumb_header = Some(new_header);
17306 }
17307
17308 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17309 self.clear_background_highlights::<SearchWithinRange>(cx);
17310 }
17311
17312 pub fn highlight_background<T: 'static>(
17313 &mut self,
17314 ranges: &[Range<Anchor>],
17315 color_fetcher: fn(&ThemeColors) -> Hsla,
17316 cx: &mut Context<Self>,
17317 ) {
17318 self.background_highlights
17319 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17320 self.scrollbar_marker_state.dirty = true;
17321 cx.notify();
17322 }
17323
17324 pub fn clear_background_highlights<T: 'static>(
17325 &mut self,
17326 cx: &mut Context<Self>,
17327 ) -> Option<BackgroundHighlight> {
17328 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17329 if !text_highlights.1.is_empty() {
17330 self.scrollbar_marker_state.dirty = true;
17331 cx.notify();
17332 }
17333 Some(text_highlights)
17334 }
17335
17336 pub fn highlight_gutter<T: 'static>(
17337 &mut self,
17338 ranges: &[Range<Anchor>],
17339 color_fetcher: fn(&App) -> Hsla,
17340 cx: &mut Context<Self>,
17341 ) {
17342 self.gutter_highlights
17343 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17344 cx.notify();
17345 }
17346
17347 pub fn clear_gutter_highlights<T: 'static>(
17348 &mut self,
17349 cx: &mut Context<Self>,
17350 ) -> Option<GutterHighlight> {
17351 cx.notify();
17352 self.gutter_highlights.remove(&TypeId::of::<T>())
17353 }
17354
17355 #[cfg(feature = "test-support")]
17356 pub fn all_text_background_highlights(
17357 &self,
17358 window: &mut Window,
17359 cx: &mut Context<Self>,
17360 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17361 let snapshot = self.snapshot(window, cx);
17362 let buffer = &snapshot.buffer_snapshot;
17363 let start = buffer.anchor_before(0);
17364 let end = buffer.anchor_after(buffer.len());
17365 let theme = cx.theme().colors();
17366 self.background_highlights_in_range(start..end, &snapshot, theme)
17367 }
17368
17369 #[cfg(feature = "test-support")]
17370 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17371 let snapshot = self.buffer().read(cx).snapshot(cx);
17372
17373 let highlights = self
17374 .background_highlights
17375 .get(&TypeId::of::<items::BufferSearchHighlights>());
17376
17377 if let Some((_color, ranges)) = highlights {
17378 ranges
17379 .iter()
17380 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17381 .collect_vec()
17382 } else {
17383 vec![]
17384 }
17385 }
17386
17387 fn document_highlights_for_position<'a>(
17388 &'a self,
17389 position: Anchor,
17390 buffer: &'a MultiBufferSnapshot,
17391 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17392 let read_highlights = self
17393 .background_highlights
17394 .get(&TypeId::of::<DocumentHighlightRead>())
17395 .map(|h| &h.1);
17396 let write_highlights = self
17397 .background_highlights
17398 .get(&TypeId::of::<DocumentHighlightWrite>())
17399 .map(|h| &h.1);
17400 let left_position = position.bias_left(buffer);
17401 let right_position = position.bias_right(buffer);
17402 read_highlights
17403 .into_iter()
17404 .chain(write_highlights)
17405 .flat_map(move |ranges| {
17406 let start_ix = match ranges.binary_search_by(|probe| {
17407 let cmp = probe.end.cmp(&left_position, buffer);
17408 if cmp.is_ge() {
17409 Ordering::Greater
17410 } else {
17411 Ordering::Less
17412 }
17413 }) {
17414 Ok(i) | Err(i) => i,
17415 };
17416
17417 ranges[start_ix..]
17418 .iter()
17419 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17420 })
17421 }
17422
17423 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17424 self.background_highlights
17425 .get(&TypeId::of::<T>())
17426 .map_or(false, |(_, highlights)| !highlights.is_empty())
17427 }
17428
17429 pub fn background_highlights_in_range(
17430 &self,
17431 search_range: Range<Anchor>,
17432 display_snapshot: &DisplaySnapshot,
17433 theme: &ThemeColors,
17434 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17435 let mut results = Vec::new();
17436 for (color_fetcher, ranges) in self.background_highlights.values() {
17437 let color = color_fetcher(theme);
17438 let start_ix = match ranges.binary_search_by(|probe| {
17439 let cmp = probe
17440 .end
17441 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17442 if cmp.is_gt() {
17443 Ordering::Greater
17444 } else {
17445 Ordering::Less
17446 }
17447 }) {
17448 Ok(i) | Err(i) => i,
17449 };
17450 for range in &ranges[start_ix..] {
17451 if range
17452 .start
17453 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17454 .is_ge()
17455 {
17456 break;
17457 }
17458
17459 let start = range.start.to_display_point(display_snapshot);
17460 let end = range.end.to_display_point(display_snapshot);
17461 results.push((start..end, color))
17462 }
17463 }
17464 results
17465 }
17466
17467 pub fn background_highlight_row_ranges<T: 'static>(
17468 &self,
17469 search_range: Range<Anchor>,
17470 display_snapshot: &DisplaySnapshot,
17471 count: usize,
17472 ) -> Vec<RangeInclusive<DisplayPoint>> {
17473 let mut results = Vec::new();
17474 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17475 return vec![];
17476 };
17477
17478 let start_ix = match ranges.binary_search_by(|probe| {
17479 let cmp = probe
17480 .end
17481 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17482 if cmp.is_gt() {
17483 Ordering::Greater
17484 } else {
17485 Ordering::Less
17486 }
17487 }) {
17488 Ok(i) | Err(i) => i,
17489 };
17490 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17491 if let (Some(start_display), Some(end_display)) = (start, end) {
17492 results.push(
17493 start_display.to_display_point(display_snapshot)
17494 ..=end_display.to_display_point(display_snapshot),
17495 );
17496 }
17497 };
17498 let mut start_row: Option<Point> = None;
17499 let mut end_row: Option<Point> = None;
17500 if ranges.len() > count {
17501 return Vec::new();
17502 }
17503 for range in &ranges[start_ix..] {
17504 if range
17505 .start
17506 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17507 .is_ge()
17508 {
17509 break;
17510 }
17511 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17512 if let Some(current_row) = &end_row {
17513 if end.row == current_row.row {
17514 continue;
17515 }
17516 }
17517 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17518 if start_row.is_none() {
17519 assert_eq!(end_row, None);
17520 start_row = Some(start);
17521 end_row = Some(end);
17522 continue;
17523 }
17524 if let Some(current_end) = end_row.as_mut() {
17525 if start.row > current_end.row + 1 {
17526 push_region(start_row, end_row);
17527 start_row = Some(start);
17528 end_row = Some(end);
17529 } else {
17530 // Merge two hunks.
17531 *current_end = end;
17532 }
17533 } else {
17534 unreachable!();
17535 }
17536 }
17537 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17538 push_region(start_row, end_row);
17539 results
17540 }
17541
17542 pub fn gutter_highlights_in_range(
17543 &self,
17544 search_range: Range<Anchor>,
17545 display_snapshot: &DisplaySnapshot,
17546 cx: &App,
17547 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17548 let mut results = Vec::new();
17549 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17550 let color = color_fetcher(cx);
17551 let start_ix = match ranges.binary_search_by(|probe| {
17552 let cmp = probe
17553 .end
17554 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17555 if cmp.is_gt() {
17556 Ordering::Greater
17557 } else {
17558 Ordering::Less
17559 }
17560 }) {
17561 Ok(i) | Err(i) => i,
17562 };
17563 for range in &ranges[start_ix..] {
17564 if range
17565 .start
17566 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17567 .is_ge()
17568 {
17569 break;
17570 }
17571
17572 let start = range.start.to_display_point(display_snapshot);
17573 let end = range.end.to_display_point(display_snapshot);
17574 results.push((start..end, color))
17575 }
17576 }
17577 results
17578 }
17579
17580 /// Get the text ranges corresponding to the redaction query
17581 pub fn redacted_ranges(
17582 &self,
17583 search_range: Range<Anchor>,
17584 display_snapshot: &DisplaySnapshot,
17585 cx: &App,
17586 ) -> Vec<Range<DisplayPoint>> {
17587 display_snapshot
17588 .buffer_snapshot
17589 .redacted_ranges(search_range, |file| {
17590 if let Some(file) = file {
17591 file.is_private()
17592 && EditorSettings::get(
17593 Some(SettingsLocation {
17594 worktree_id: file.worktree_id(cx),
17595 path: file.path().as_ref(),
17596 }),
17597 cx,
17598 )
17599 .redact_private_values
17600 } else {
17601 false
17602 }
17603 })
17604 .map(|range| {
17605 range.start.to_display_point(display_snapshot)
17606 ..range.end.to_display_point(display_snapshot)
17607 })
17608 .collect()
17609 }
17610
17611 pub fn highlight_text<T: 'static>(
17612 &mut self,
17613 ranges: Vec<Range<Anchor>>,
17614 style: HighlightStyle,
17615 cx: &mut Context<Self>,
17616 ) {
17617 self.display_map.update(cx, |map, _| {
17618 map.highlight_text(TypeId::of::<T>(), ranges, style)
17619 });
17620 cx.notify();
17621 }
17622
17623 pub(crate) fn highlight_inlays<T: 'static>(
17624 &mut self,
17625 highlights: Vec<InlayHighlight>,
17626 style: HighlightStyle,
17627 cx: &mut Context<Self>,
17628 ) {
17629 self.display_map.update(cx, |map, _| {
17630 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17631 });
17632 cx.notify();
17633 }
17634
17635 pub fn text_highlights<'a, T: 'static>(
17636 &'a self,
17637 cx: &'a App,
17638 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17639 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17640 }
17641
17642 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17643 let cleared = self
17644 .display_map
17645 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17646 if cleared {
17647 cx.notify();
17648 }
17649 }
17650
17651 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17652 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17653 && self.focus_handle.is_focused(window)
17654 }
17655
17656 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17657 self.show_cursor_when_unfocused = is_enabled;
17658 cx.notify();
17659 }
17660
17661 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17662 cx.notify();
17663 }
17664
17665 fn on_debug_session_event(
17666 &mut self,
17667 _session: Entity<Session>,
17668 event: &SessionEvent,
17669 cx: &mut Context<Self>,
17670 ) {
17671 match event {
17672 SessionEvent::InvalidateInlineValue => {
17673 self.refresh_inline_values(cx);
17674 }
17675 _ => {}
17676 }
17677 }
17678
17679 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17680 let Some(project) = self.project.clone() else {
17681 return;
17682 };
17683 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17684 return;
17685 };
17686 if !self.inline_value_cache.enabled {
17687 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17688 self.splice_inlays(&inlays, Vec::new(), cx);
17689 return;
17690 }
17691
17692 let current_execution_position = self
17693 .highlighted_rows
17694 .get(&TypeId::of::<ActiveDebugLine>())
17695 .and_then(|lines| lines.last().map(|line| line.range.start));
17696
17697 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17698 let snapshot = editor
17699 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17700 .ok()?;
17701
17702 let inline_values = editor
17703 .update(cx, |_, cx| {
17704 let Some(current_execution_position) = current_execution_position else {
17705 return Some(Task::ready(Ok(Vec::new())));
17706 };
17707
17708 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17709 // anchor is in the same buffer
17710 let range =
17711 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17712 project.inline_values(buffer, range, cx)
17713 })
17714 .ok()
17715 .flatten()?
17716 .await
17717 .context("refreshing debugger inlays")
17718 .log_err()?;
17719
17720 let (excerpt_id, buffer_id) = snapshot
17721 .excerpts()
17722 .next()
17723 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17724 editor
17725 .update(cx, |editor, cx| {
17726 let new_inlays = inline_values
17727 .into_iter()
17728 .map(|debugger_value| {
17729 Inlay::debugger_hint(
17730 post_inc(&mut editor.next_inlay_id),
17731 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17732 debugger_value.text(),
17733 )
17734 })
17735 .collect::<Vec<_>>();
17736 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17737 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17738
17739 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17740 })
17741 .ok()?;
17742 Some(())
17743 });
17744 }
17745
17746 fn on_buffer_event(
17747 &mut self,
17748 multibuffer: &Entity<MultiBuffer>,
17749 event: &multi_buffer::Event,
17750 window: &mut Window,
17751 cx: &mut Context<Self>,
17752 ) {
17753 match event {
17754 multi_buffer::Event::Edited {
17755 singleton_buffer_edited,
17756 edited_buffer: buffer_edited,
17757 } => {
17758 self.scrollbar_marker_state.dirty = true;
17759 self.active_indent_guides_state.dirty = true;
17760 self.refresh_active_diagnostics(cx);
17761 self.refresh_code_actions(window, cx);
17762 self.refresh_selected_text_highlights(true, window, cx);
17763 refresh_matching_bracket_highlights(self, window, cx);
17764 if self.has_active_inline_completion() {
17765 self.update_visible_inline_completion(window, cx);
17766 }
17767 if let Some(buffer) = buffer_edited {
17768 let buffer_id = buffer.read(cx).remote_id();
17769 if !self.registered_buffers.contains_key(&buffer_id) {
17770 if let Some(project) = self.project.as_ref() {
17771 project.update(cx, |project, cx| {
17772 self.registered_buffers.insert(
17773 buffer_id,
17774 project.register_buffer_with_language_servers(&buffer, cx),
17775 );
17776 })
17777 }
17778 }
17779 }
17780 cx.emit(EditorEvent::BufferEdited);
17781 cx.emit(SearchEvent::MatchesInvalidated);
17782 if *singleton_buffer_edited {
17783 if let Some(project) = &self.project {
17784 #[allow(clippy::mutable_key_type)]
17785 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17786 multibuffer
17787 .all_buffers()
17788 .into_iter()
17789 .filter_map(|buffer| {
17790 buffer.update(cx, |buffer, cx| {
17791 let language = buffer.language()?;
17792 let should_discard = project.update(cx, |project, cx| {
17793 project.is_local()
17794 && !project.has_language_servers_for(buffer, cx)
17795 });
17796 should_discard.not().then_some(language.clone())
17797 })
17798 })
17799 .collect::<HashSet<_>>()
17800 });
17801 if !languages_affected.is_empty() {
17802 self.refresh_inlay_hints(
17803 InlayHintRefreshReason::BufferEdited(languages_affected),
17804 cx,
17805 );
17806 }
17807 }
17808 }
17809
17810 let Some(project) = &self.project else { return };
17811 let (telemetry, is_via_ssh) = {
17812 let project = project.read(cx);
17813 let telemetry = project.client().telemetry().clone();
17814 let is_via_ssh = project.is_via_ssh();
17815 (telemetry, is_via_ssh)
17816 };
17817 refresh_linked_ranges(self, window, cx);
17818 telemetry.log_edit_event("editor", is_via_ssh);
17819 }
17820 multi_buffer::Event::ExcerptsAdded {
17821 buffer,
17822 predecessor,
17823 excerpts,
17824 } => {
17825 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17826 let buffer_id = buffer.read(cx).remote_id();
17827 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17828 if let Some(project) = &self.project {
17829 update_uncommitted_diff_for_buffer(
17830 cx.entity(),
17831 project,
17832 [buffer.clone()],
17833 self.buffer.clone(),
17834 cx,
17835 )
17836 .detach();
17837 }
17838 }
17839 cx.emit(EditorEvent::ExcerptsAdded {
17840 buffer: buffer.clone(),
17841 predecessor: *predecessor,
17842 excerpts: excerpts.clone(),
17843 });
17844 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17845 }
17846 multi_buffer::Event::ExcerptsRemoved {
17847 ids,
17848 removed_buffer_ids,
17849 } => {
17850 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17851 let buffer = self.buffer.read(cx);
17852 self.registered_buffers
17853 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17854 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17855 cx.emit(EditorEvent::ExcerptsRemoved {
17856 ids: ids.clone(),
17857 removed_buffer_ids: removed_buffer_ids.clone(),
17858 })
17859 }
17860 multi_buffer::Event::ExcerptsEdited {
17861 excerpt_ids,
17862 buffer_ids,
17863 } => {
17864 self.display_map.update(cx, |map, cx| {
17865 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17866 });
17867 cx.emit(EditorEvent::ExcerptsEdited {
17868 ids: excerpt_ids.clone(),
17869 })
17870 }
17871 multi_buffer::Event::ExcerptsExpanded { ids } => {
17872 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17873 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17874 }
17875 multi_buffer::Event::Reparsed(buffer_id) => {
17876 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17877 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17878
17879 cx.emit(EditorEvent::Reparsed(*buffer_id));
17880 }
17881 multi_buffer::Event::DiffHunksToggled => {
17882 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17883 }
17884 multi_buffer::Event::LanguageChanged(buffer_id) => {
17885 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17886 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17887 cx.emit(EditorEvent::Reparsed(*buffer_id));
17888 cx.notify();
17889 }
17890 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17891 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17892 multi_buffer::Event::FileHandleChanged
17893 | multi_buffer::Event::Reloaded
17894 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17895 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17896 multi_buffer::Event::DiagnosticsUpdated => {
17897 self.refresh_active_diagnostics(cx);
17898 self.refresh_inline_diagnostics(true, window, cx);
17899 self.scrollbar_marker_state.dirty = true;
17900 cx.notify();
17901 }
17902 _ => {}
17903 };
17904 }
17905
17906 pub fn start_temporary_diff_override(&mut self) {
17907 self.load_diff_task.take();
17908 self.temporary_diff_override = true;
17909 }
17910
17911 pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17912 self.temporary_diff_override = false;
17913 self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17914 self.buffer.update(cx, |buffer, cx| {
17915 buffer.set_all_diff_hunks_collapsed(cx);
17916 });
17917
17918 if let Some(project) = self.project.clone() {
17919 self.load_diff_task = Some(
17920 update_uncommitted_diff_for_buffer(
17921 cx.entity(),
17922 &project,
17923 self.buffer.read(cx).all_buffers(),
17924 self.buffer.clone(),
17925 cx,
17926 )
17927 .shared(),
17928 );
17929 }
17930 }
17931
17932 fn on_display_map_changed(
17933 &mut self,
17934 _: Entity<DisplayMap>,
17935 _: &mut Window,
17936 cx: &mut Context<Self>,
17937 ) {
17938 cx.notify();
17939 }
17940
17941 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17942 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17943 self.update_edit_prediction_settings(cx);
17944 self.refresh_inline_completion(true, false, window, cx);
17945 self.refresh_inlay_hints(
17946 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17947 self.selections.newest_anchor().head(),
17948 &self.buffer.read(cx).snapshot(cx),
17949 cx,
17950 )),
17951 cx,
17952 );
17953
17954 let old_cursor_shape = self.cursor_shape;
17955
17956 {
17957 let editor_settings = EditorSettings::get_global(cx);
17958 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17959 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17960 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17961 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17962 }
17963
17964 if old_cursor_shape != self.cursor_shape {
17965 cx.emit(EditorEvent::CursorShapeChanged);
17966 }
17967
17968 let project_settings = ProjectSettings::get_global(cx);
17969 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17970
17971 if self.mode.is_full() {
17972 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17973 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17974 if self.show_inline_diagnostics != show_inline_diagnostics {
17975 self.show_inline_diagnostics = show_inline_diagnostics;
17976 self.refresh_inline_diagnostics(false, window, cx);
17977 }
17978
17979 if self.git_blame_inline_enabled != inline_blame_enabled {
17980 self.toggle_git_blame_inline_internal(false, window, cx);
17981 }
17982 }
17983
17984 cx.notify();
17985 }
17986
17987 pub fn set_searchable(&mut self, searchable: bool) {
17988 self.searchable = searchable;
17989 }
17990
17991 pub fn searchable(&self) -> bool {
17992 self.searchable
17993 }
17994
17995 fn open_proposed_changes_editor(
17996 &mut self,
17997 _: &OpenProposedChangesEditor,
17998 window: &mut Window,
17999 cx: &mut Context<Self>,
18000 ) {
18001 let Some(workspace) = self.workspace() else {
18002 cx.propagate();
18003 return;
18004 };
18005
18006 let selections = self.selections.all::<usize>(cx);
18007 let multi_buffer = self.buffer.read(cx);
18008 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18009 let mut new_selections_by_buffer = HashMap::default();
18010 for selection in selections {
18011 for (buffer, range, _) in
18012 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18013 {
18014 let mut range = range.to_point(buffer);
18015 range.start.column = 0;
18016 range.end.column = buffer.line_len(range.end.row);
18017 new_selections_by_buffer
18018 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18019 .or_insert(Vec::new())
18020 .push(range)
18021 }
18022 }
18023
18024 let proposed_changes_buffers = new_selections_by_buffer
18025 .into_iter()
18026 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18027 .collect::<Vec<_>>();
18028 let proposed_changes_editor = cx.new(|cx| {
18029 ProposedChangesEditor::new(
18030 "Proposed changes",
18031 proposed_changes_buffers,
18032 self.project.clone(),
18033 window,
18034 cx,
18035 )
18036 });
18037
18038 window.defer(cx, move |window, cx| {
18039 workspace.update(cx, |workspace, cx| {
18040 workspace.active_pane().update(cx, |pane, cx| {
18041 pane.add_item(
18042 Box::new(proposed_changes_editor),
18043 true,
18044 true,
18045 None,
18046 window,
18047 cx,
18048 );
18049 });
18050 });
18051 });
18052 }
18053
18054 pub fn open_excerpts_in_split(
18055 &mut self,
18056 _: &OpenExcerptsSplit,
18057 window: &mut Window,
18058 cx: &mut Context<Self>,
18059 ) {
18060 self.open_excerpts_common(None, true, window, cx)
18061 }
18062
18063 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18064 self.open_excerpts_common(None, false, window, cx)
18065 }
18066
18067 fn open_excerpts_common(
18068 &mut self,
18069 jump_data: Option<JumpData>,
18070 split: bool,
18071 window: &mut Window,
18072 cx: &mut Context<Self>,
18073 ) {
18074 let Some(workspace) = self.workspace() else {
18075 cx.propagate();
18076 return;
18077 };
18078
18079 if self.buffer.read(cx).is_singleton() {
18080 cx.propagate();
18081 return;
18082 }
18083
18084 let mut new_selections_by_buffer = HashMap::default();
18085 match &jump_data {
18086 Some(JumpData::MultiBufferPoint {
18087 excerpt_id,
18088 position,
18089 anchor,
18090 line_offset_from_top,
18091 }) => {
18092 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18093 if let Some(buffer) = multi_buffer_snapshot
18094 .buffer_id_for_excerpt(*excerpt_id)
18095 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18096 {
18097 let buffer_snapshot = buffer.read(cx).snapshot();
18098 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18099 language::ToPoint::to_point(anchor, &buffer_snapshot)
18100 } else {
18101 buffer_snapshot.clip_point(*position, Bias::Left)
18102 };
18103 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18104 new_selections_by_buffer.insert(
18105 buffer,
18106 (
18107 vec![jump_to_offset..jump_to_offset],
18108 Some(*line_offset_from_top),
18109 ),
18110 );
18111 }
18112 }
18113 Some(JumpData::MultiBufferRow {
18114 row,
18115 line_offset_from_top,
18116 }) => {
18117 let point = MultiBufferPoint::new(row.0, 0);
18118 if let Some((buffer, buffer_point, _)) =
18119 self.buffer.read(cx).point_to_buffer_point(point, cx)
18120 {
18121 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18122 new_selections_by_buffer
18123 .entry(buffer)
18124 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18125 .0
18126 .push(buffer_offset..buffer_offset)
18127 }
18128 }
18129 None => {
18130 let selections = self.selections.all::<usize>(cx);
18131 let multi_buffer = self.buffer.read(cx);
18132 for selection in selections {
18133 for (snapshot, range, _, anchor) in multi_buffer
18134 .snapshot(cx)
18135 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18136 {
18137 if let Some(anchor) = anchor {
18138 // selection is in a deleted hunk
18139 let Some(buffer_id) = anchor.buffer_id else {
18140 continue;
18141 };
18142 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18143 continue;
18144 };
18145 let offset = text::ToOffset::to_offset(
18146 &anchor.text_anchor,
18147 &buffer_handle.read(cx).snapshot(),
18148 );
18149 let range = offset..offset;
18150 new_selections_by_buffer
18151 .entry(buffer_handle)
18152 .or_insert((Vec::new(), None))
18153 .0
18154 .push(range)
18155 } else {
18156 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18157 else {
18158 continue;
18159 };
18160 new_selections_by_buffer
18161 .entry(buffer_handle)
18162 .or_insert((Vec::new(), None))
18163 .0
18164 .push(range)
18165 }
18166 }
18167 }
18168 }
18169 }
18170
18171 new_selections_by_buffer
18172 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18173
18174 if new_selections_by_buffer.is_empty() {
18175 return;
18176 }
18177
18178 // We defer the pane interaction because we ourselves are a workspace item
18179 // and activating a new item causes the pane to call a method on us reentrantly,
18180 // which panics if we're on the stack.
18181 window.defer(cx, move |window, cx| {
18182 workspace.update(cx, |workspace, cx| {
18183 let pane = if split {
18184 workspace.adjacent_pane(window, cx)
18185 } else {
18186 workspace.active_pane().clone()
18187 };
18188
18189 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18190 let editor = buffer
18191 .read(cx)
18192 .file()
18193 .is_none()
18194 .then(|| {
18195 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18196 // so `workspace.open_project_item` will never find them, always opening a new editor.
18197 // Instead, we try to activate the existing editor in the pane first.
18198 let (editor, pane_item_index) =
18199 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18200 let editor = item.downcast::<Editor>()?;
18201 let singleton_buffer =
18202 editor.read(cx).buffer().read(cx).as_singleton()?;
18203 if singleton_buffer == buffer {
18204 Some((editor, i))
18205 } else {
18206 None
18207 }
18208 })?;
18209 pane.update(cx, |pane, cx| {
18210 pane.activate_item(pane_item_index, true, true, window, cx)
18211 });
18212 Some(editor)
18213 })
18214 .flatten()
18215 .unwrap_or_else(|| {
18216 workspace.open_project_item::<Self>(
18217 pane.clone(),
18218 buffer,
18219 true,
18220 true,
18221 window,
18222 cx,
18223 )
18224 });
18225
18226 editor.update(cx, |editor, cx| {
18227 let autoscroll = match scroll_offset {
18228 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18229 None => Autoscroll::newest(),
18230 };
18231 let nav_history = editor.nav_history.take();
18232 editor.change_selections(Some(autoscroll), window, cx, |s| {
18233 s.select_ranges(ranges);
18234 });
18235 editor.nav_history = nav_history;
18236 });
18237 }
18238 })
18239 });
18240 }
18241
18242 // For now, don't allow opening excerpts in buffers that aren't backed by
18243 // regular project files.
18244 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18245 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18246 }
18247
18248 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18249 let snapshot = self.buffer.read(cx).read(cx);
18250 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18251 Some(
18252 ranges
18253 .iter()
18254 .map(move |range| {
18255 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18256 })
18257 .collect(),
18258 )
18259 }
18260
18261 fn selection_replacement_ranges(
18262 &self,
18263 range: Range<OffsetUtf16>,
18264 cx: &mut App,
18265 ) -> Vec<Range<OffsetUtf16>> {
18266 let selections = self.selections.all::<OffsetUtf16>(cx);
18267 let newest_selection = selections
18268 .iter()
18269 .max_by_key(|selection| selection.id)
18270 .unwrap();
18271 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18272 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18273 let snapshot = self.buffer.read(cx).read(cx);
18274 selections
18275 .into_iter()
18276 .map(|mut selection| {
18277 selection.start.0 =
18278 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18279 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18280 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18281 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18282 })
18283 .collect()
18284 }
18285
18286 fn report_editor_event(
18287 &self,
18288 event_type: &'static str,
18289 file_extension: Option<String>,
18290 cx: &App,
18291 ) {
18292 if cfg!(any(test, feature = "test-support")) {
18293 return;
18294 }
18295
18296 let Some(project) = &self.project else { return };
18297
18298 // If None, we are in a file without an extension
18299 let file = self
18300 .buffer
18301 .read(cx)
18302 .as_singleton()
18303 .and_then(|b| b.read(cx).file());
18304 let file_extension = file_extension.or(file
18305 .as_ref()
18306 .and_then(|file| Path::new(file.file_name(cx)).extension())
18307 .and_then(|e| e.to_str())
18308 .map(|a| a.to_string()));
18309
18310 let vim_mode = vim_enabled(cx);
18311
18312 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18313 let copilot_enabled = edit_predictions_provider
18314 == language::language_settings::EditPredictionProvider::Copilot;
18315 let copilot_enabled_for_language = self
18316 .buffer
18317 .read(cx)
18318 .language_settings(cx)
18319 .show_edit_predictions;
18320
18321 let project = project.read(cx);
18322 telemetry::event!(
18323 event_type,
18324 file_extension,
18325 vim_mode,
18326 copilot_enabled,
18327 copilot_enabled_for_language,
18328 edit_predictions_provider,
18329 is_via_ssh = project.is_via_ssh(),
18330 );
18331 }
18332
18333 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18334 /// with each line being an array of {text, highlight} objects.
18335 fn copy_highlight_json(
18336 &mut self,
18337 _: &CopyHighlightJson,
18338 window: &mut Window,
18339 cx: &mut Context<Self>,
18340 ) {
18341 #[derive(Serialize)]
18342 struct Chunk<'a> {
18343 text: String,
18344 highlight: Option<&'a str>,
18345 }
18346
18347 let snapshot = self.buffer.read(cx).snapshot(cx);
18348 let range = self
18349 .selected_text_range(false, window, cx)
18350 .and_then(|selection| {
18351 if selection.range.is_empty() {
18352 None
18353 } else {
18354 Some(selection.range)
18355 }
18356 })
18357 .unwrap_or_else(|| 0..snapshot.len());
18358
18359 let chunks = snapshot.chunks(range, true);
18360 let mut lines = Vec::new();
18361 let mut line: VecDeque<Chunk> = VecDeque::new();
18362
18363 let Some(style) = self.style.as_ref() else {
18364 return;
18365 };
18366
18367 for chunk in chunks {
18368 let highlight = chunk
18369 .syntax_highlight_id
18370 .and_then(|id| id.name(&style.syntax));
18371 let mut chunk_lines = chunk.text.split('\n').peekable();
18372 while let Some(text) = chunk_lines.next() {
18373 let mut merged_with_last_token = false;
18374 if let Some(last_token) = line.back_mut() {
18375 if last_token.highlight == highlight {
18376 last_token.text.push_str(text);
18377 merged_with_last_token = true;
18378 }
18379 }
18380
18381 if !merged_with_last_token {
18382 line.push_back(Chunk {
18383 text: text.into(),
18384 highlight,
18385 });
18386 }
18387
18388 if chunk_lines.peek().is_some() {
18389 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18390 line.pop_front();
18391 }
18392 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18393 line.pop_back();
18394 }
18395
18396 lines.push(mem::take(&mut line));
18397 }
18398 }
18399 }
18400
18401 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18402 return;
18403 };
18404 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18405 }
18406
18407 pub fn open_context_menu(
18408 &mut self,
18409 _: &OpenContextMenu,
18410 window: &mut Window,
18411 cx: &mut Context<Self>,
18412 ) {
18413 self.request_autoscroll(Autoscroll::newest(), cx);
18414 let position = self.selections.newest_display(cx).start;
18415 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18416 }
18417
18418 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18419 &self.inlay_hint_cache
18420 }
18421
18422 pub fn replay_insert_event(
18423 &mut self,
18424 text: &str,
18425 relative_utf16_range: Option<Range<isize>>,
18426 window: &mut Window,
18427 cx: &mut Context<Self>,
18428 ) {
18429 if !self.input_enabled {
18430 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18431 return;
18432 }
18433 if let Some(relative_utf16_range) = relative_utf16_range {
18434 let selections = self.selections.all::<OffsetUtf16>(cx);
18435 self.change_selections(None, window, cx, |s| {
18436 let new_ranges = selections.into_iter().map(|range| {
18437 let start = OffsetUtf16(
18438 range
18439 .head()
18440 .0
18441 .saturating_add_signed(relative_utf16_range.start),
18442 );
18443 let end = OffsetUtf16(
18444 range
18445 .head()
18446 .0
18447 .saturating_add_signed(relative_utf16_range.end),
18448 );
18449 start..end
18450 });
18451 s.select_ranges(new_ranges);
18452 });
18453 }
18454
18455 self.handle_input(text, window, cx);
18456 }
18457
18458 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18459 let Some(provider) = self.semantics_provider.as_ref() else {
18460 return false;
18461 };
18462
18463 let mut supports = false;
18464 self.buffer().update(cx, |this, cx| {
18465 this.for_each_buffer(|buffer| {
18466 supports |= provider.supports_inlay_hints(buffer, cx);
18467 });
18468 });
18469
18470 supports
18471 }
18472
18473 pub fn is_focused(&self, window: &Window) -> bool {
18474 self.focus_handle.is_focused(window)
18475 }
18476
18477 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18478 cx.emit(EditorEvent::Focused);
18479
18480 if let Some(descendant) = self
18481 .last_focused_descendant
18482 .take()
18483 .and_then(|descendant| descendant.upgrade())
18484 {
18485 window.focus(&descendant);
18486 } else {
18487 if let Some(blame) = self.blame.as_ref() {
18488 blame.update(cx, GitBlame::focus)
18489 }
18490
18491 self.blink_manager.update(cx, BlinkManager::enable);
18492 self.show_cursor_names(window, cx);
18493 self.buffer.update(cx, |buffer, cx| {
18494 buffer.finalize_last_transaction(cx);
18495 if self.leader_id.is_none() {
18496 buffer.set_active_selections(
18497 &self.selections.disjoint_anchors(),
18498 self.selections.line_mode,
18499 self.cursor_shape,
18500 cx,
18501 );
18502 }
18503 });
18504 }
18505 }
18506
18507 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18508 cx.emit(EditorEvent::FocusedIn)
18509 }
18510
18511 fn handle_focus_out(
18512 &mut self,
18513 event: FocusOutEvent,
18514 _window: &mut Window,
18515 cx: &mut Context<Self>,
18516 ) {
18517 if event.blurred != self.focus_handle {
18518 self.last_focused_descendant = Some(event.blurred);
18519 }
18520 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18521 }
18522
18523 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18524 self.blink_manager.update(cx, BlinkManager::disable);
18525 self.buffer
18526 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18527
18528 if let Some(blame) = self.blame.as_ref() {
18529 blame.update(cx, GitBlame::blur)
18530 }
18531 if !self.hover_state.focused(window, cx) {
18532 hide_hover(self, cx);
18533 }
18534 if !self
18535 .context_menu
18536 .borrow()
18537 .as_ref()
18538 .is_some_and(|context_menu| context_menu.focused(window, cx))
18539 {
18540 self.hide_context_menu(window, cx);
18541 }
18542 self.discard_inline_completion(false, cx);
18543 cx.emit(EditorEvent::Blurred);
18544 cx.notify();
18545 }
18546
18547 pub fn register_action<A: Action>(
18548 &mut self,
18549 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18550 ) -> Subscription {
18551 let id = self.next_editor_action_id.post_inc();
18552 let listener = Arc::new(listener);
18553 self.editor_actions.borrow_mut().insert(
18554 id,
18555 Box::new(move |window, _| {
18556 let listener = listener.clone();
18557 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18558 let action = action.downcast_ref().unwrap();
18559 if phase == DispatchPhase::Bubble {
18560 listener(action, window, cx)
18561 }
18562 })
18563 }),
18564 );
18565
18566 let editor_actions = self.editor_actions.clone();
18567 Subscription::new(move || {
18568 editor_actions.borrow_mut().remove(&id);
18569 })
18570 }
18571
18572 pub fn file_header_size(&self) -> u32 {
18573 FILE_HEADER_HEIGHT
18574 }
18575
18576 pub fn restore(
18577 &mut self,
18578 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18579 window: &mut Window,
18580 cx: &mut Context<Self>,
18581 ) {
18582 let workspace = self.workspace();
18583 let project = self.project.as_ref();
18584 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18585 let mut tasks = Vec::new();
18586 for (buffer_id, changes) in revert_changes {
18587 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18588 buffer.update(cx, |buffer, cx| {
18589 buffer.edit(
18590 changes
18591 .into_iter()
18592 .map(|(range, text)| (range, text.to_string())),
18593 None,
18594 cx,
18595 );
18596 });
18597
18598 if let Some(project) =
18599 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18600 {
18601 project.update(cx, |project, cx| {
18602 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18603 })
18604 }
18605 }
18606 }
18607 tasks
18608 });
18609 cx.spawn_in(window, async move |_, cx| {
18610 for (buffer, task) in save_tasks {
18611 let result = task.await;
18612 if result.is_err() {
18613 let Some(path) = buffer
18614 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18615 .ok()
18616 else {
18617 continue;
18618 };
18619 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18620 let Some(task) = cx
18621 .update_window_entity(&workspace, |workspace, window, cx| {
18622 workspace
18623 .open_path_preview(path, None, false, false, false, window, cx)
18624 })
18625 .ok()
18626 else {
18627 continue;
18628 };
18629 task.await.log_err();
18630 }
18631 }
18632 }
18633 })
18634 .detach();
18635 self.change_selections(None, window, cx, |selections| selections.refresh());
18636 }
18637
18638 pub fn to_pixel_point(
18639 &self,
18640 source: multi_buffer::Anchor,
18641 editor_snapshot: &EditorSnapshot,
18642 window: &mut Window,
18643 ) -> Option<gpui::Point<Pixels>> {
18644 let source_point = source.to_display_point(editor_snapshot);
18645 self.display_to_pixel_point(source_point, editor_snapshot, window)
18646 }
18647
18648 pub fn display_to_pixel_point(
18649 &self,
18650 source: DisplayPoint,
18651 editor_snapshot: &EditorSnapshot,
18652 window: &mut Window,
18653 ) -> Option<gpui::Point<Pixels>> {
18654 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18655 let text_layout_details = self.text_layout_details(window);
18656 let scroll_top = text_layout_details
18657 .scroll_anchor
18658 .scroll_position(editor_snapshot)
18659 .y;
18660
18661 if source.row().as_f32() < scroll_top.floor() {
18662 return None;
18663 }
18664 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18665 let source_y = line_height * (source.row().as_f32() - scroll_top);
18666 Some(gpui::Point::new(source_x, source_y))
18667 }
18668
18669 pub fn has_visible_completions_menu(&self) -> bool {
18670 !self.edit_prediction_preview_is_active()
18671 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18672 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18673 })
18674 }
18675
18676 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18677 self.addons
18678 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18679 }
18680
18681 pub fn unregister_addon<T: Addon>(&mut self) {
18682 self.addons.remove(&std::any::TypeId::of::<T>());
18683 }
18684
18685 pub fn addon<T: Addon>(&self) -> Option<&T> {
18686 let type_id = std::any::TypeId::of::<T>();
18687 self.addons
18688 .get(&type_id)
18689 .and_then(|item| item.to_any().downcast_ref::<T>())
18690 }
18691
18692 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18693 let type_id = std::any::TypeId::of::<T>();
18694 self.addons
18695 .get_mut(&type_id)
18696 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18697 }
18698
18699 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18700 let text_layout_details = self.text_layout_details(window);
18701 let style = &text_layout_details.editor_style;
18702 let font_id = window.text_system().resolve_font(&style.text.font());
18703 let font_size = style.text.font_size.to_pixels(window.rem_size());
18704 let line_height = style.text.line_height_in_pixels(window.rem_size());
18705 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18706
18707 gpui::Size::new(em_width, line_height)
18708 }
18709
18710 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18711 self.load_diff_task.clone()
18712 }
18713
18714 fn read_metadata_from_db(
18715 &mut self,
18716 item_id: u64,
18717 workspace_id: WorkspaceId,
18718 window: &mut Window,
18719 cx: &mut Context<Editor>,
18720 ) {
18721 if self.is_singleton(cx)
18722 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18723 {
18724 let buffer_snapshot = OnceCell::new();
18725
18726 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18727 if !folds.is_empty() {
18728 let snapshot =
18729 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18730 self.fold_ranges(
18731 folds
18732 .into_iter()
18733 .map(|(start, end)| {
18734 snapshot.clip_offset(start, Bias::Left)
18735 ..snapshot.clip_offset(end, Bias::Right)
18736 })
18737 .collect(),
18738 false,
18739 window,
18740 cx,
18741 );
18742 }
18743 }
18744
18745 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18746 if !selections.is_empty() {
18747 let snapshot =
18748 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18749 self.change_selections(None, window, cx, |s| {
18750 s.select_ranges(selections.into_iter().map(|(start, end)| {
18751 snapshot.clip_offset(start, Bias::Left)
18752 ..snapshot.clip_offset(end, Bias::Right)
18753 }));
18754 });
18755 }
18756 };
18757 }
18758
18759 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18760 }
18761}
18762
18763fn vim_enabled(cx: &App) -> bool {
18764 cx.global::<SettingsStore>()
18765 .raw_user_settings()
18766 .get("vim_mode")
18767 == Some(&serde_json::Value::Bool(true))
18768}
18769
18770// Consider user intent and default settings
18771fn choose_completion_range(
18772 completion: &Completion,
18773 intent: CompletionIntent,
18774 buffer: &Entity<Buffer>,
18775 cx: &mut Context<Editor>,
18776) -> Range<usize> {
18777 fn should_replace(
18778 completion: &Completion,
18779 insert_range: &Range<text::Anchor>,
18780 intent: CompletionIntent,
18781 completion_mode_setting: LspInsertMode,
18782 buffer: &Buffer,
18783 ) -> bool {
18784 // specific actions take precedence over settings
18785 match intent {
18786 CompletionIntent::CompleteWithInsert => return false,
18787 CompletionIntent::CompleteWithReplace => return true,
18788 CompletionIntent::Complete | CompletionIntent::Compose => {}
18789 }
18790
18791 match completion_mode_setting {
18792 LspInsertMode::Insert => false,
18793 LspInsertMode::Replace => true,
18794 LspInsertMode::ReplaceSubsequence => {
18795 let mut text_to_replace = buffer.chars_for_range(
18796 buffer.anchor_before(completion.replace_range.start)
18797 ..buffer.anchor_after(completion.replace_range.end),
18798 );
18799 let mut completion_text = completion.new_text.chars();
18800
18801 // is `text_to_replace` a subsequence of `completion_text`
18802 text_to_replace
18803 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18804 }
18805 LspInsertMode::ReplaceSuffix => {
18806 let range_after_cursor = insert_range.end..completion.replace_range.end;
18807
18808 let text_after_cursor = buffer
18809 .text_for_range(
18810 buffer.anchor_before(range_after_cursor.start)
18811 ..buffer.anchor_after(range_after_cursor.end),
18812 )
18813 .collect::<String>();
18814 completion.new_text.ends_with(&text_after_cursor)
18815 }
18816 }
18817 }
18818
18819 let buffer = buffer.read(cx);
18820
18821 if let CompletionSource::Lsp {
18822 insert_range: Some(insert_range),
18823 ..
18824 } = &completion.source
18825 {
18826 let completion_mode_setting =
18827 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18828 .completions
18829 .lsp_insert_mode;
18830
18831 if !should_replace(
18832 completion,
18833 &insert_range,
18834 intent,
18835 completion_mode_setting,
18836 buffer,
18837 ) {
18838 return insert_range.to_offset(buffer);
18839 }
18840 }
18841
18842 completion.replace_range.to_offset(buffer)
18843}
18844
18845fn insert_extra_newline_brackets(
18846 buffer: &MultiBufferSnapshot,
18847 range: Range<usize>,
18848 language: &language::LanguageScope,
18849) -> bool {
18850 let leading_whitespace_len = buffer
18851 .reversed_chars_at(range.start)
18852 .take_while(|c| c.is_whitespace() && *c != '\n')
18853 .map(|c| c.len_utf8())
18854 .sum::<usize>();
18855 let trailing_whitespace_len = buffer
18856 .chars_at(range.end)
18857 .take_while(|c| c.is_whitespace() && *c != '\n')
18858 .map(|c| c.len_utf8())
18859 .sum::<usize>();
18860 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18861
18862 language.brackets().any(|(pair, enabled)| {
18863 let pair_start = pair.start.trim_end();
18864 let pair_end = pair.end.trim_start();
18865
18866 enabled
18867 && pair.newline
18868 && buffer.contains_str_at(range.end, pair_end)
18869 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18870 })
18871}
18872
18873fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18874 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18875 [(buffer, range, _)] => (*buffer, range.clone()),
18876 _ => return false,
18877 };
18878 let pair = {
18879 let mut result: Option<BracketMatch> = None;
18880
18881 for pair in buffer
18882 .all_bracket_ranges(range.clone())
18883 .filter(move |pair| {
18884 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18885 })
18886 {
18887 let len = pair.close_range.end - pair.open_range.start;
18888
18889 if let Some(existing) = &result {
18890 let existing_len = existing.close_range.end - existing.open_range.start;
18891 if len > existing_len {
18892 continue;
18893 }
18894 }
18895
18896 result = Some(pair);
18897 }
18898
18899 result
18900 };
18901 let Some(pair) = pair else {
18902 return false;
18903 };
18904 pair.newline_only
18905 && buffer
18906 .chars_for_range(pair.open_range.end..range.start)
18907 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18908 .all(|c| c.is_whitespace() && c != '\n')
18909}
18910
18911fn update_uncommitted_diff_for_buffer(
18912 editor: Entity<Editor>,
18913 project: &Entity<Project>,
18914 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18915 buffer: Entity<MultiBuffer>,
18916 cx: &mut App,
18917) -> Task<()> {
18918 let mut tasks = Vec::new();
18919 project.update(cx, |project, cx| {
18920 for buffer in buffers {
18921 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18922 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18923 }
18924 }
18925 });
18926 cx.spawn(async move |cx| {
18927 let diffs = future::join_all(tasks).await;
18928 if editor
18929 .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18930 .unwrap_or(false)
18931 {
18932 return;
18933 }
18934
18935 buffer
18936 .update(cx, |buffer, cx| {
18937 for diff in diffs.into_iter().flatten() {
18938 buffer.add_diff(diff, cx);
18939 }
18940 })
18941 .ok();
18942 })
18943}
18944
18945fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18946 let tab_size = tab_size.get() as usize;
18947 let mut width = offset;
18948
18949 for ch in text.chars() {
18950 width += if ch == '\t' {
18951 tab_size - (width % tab_size)
18952 } else {
18953 1
18954 };
18955 }
18956
18957 width - offset
18958}
18959
18960#[cfg(test)]
18961mod tests {
18962 use super::*;
18963
18964 #[test]
18965 fn test_string_size_with_expanded_tabs() {
18966 let nz = |val| NonZeroU32::new(val).unwrap();
18967 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18968 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18969 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18970 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18971 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18972 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18973 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18974 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18975 }
18976}
18977
18978/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18979struct WordBreakingTokenizer<'a> {
18980 input: &'a str,
18981}
18982
18983impl<'a> WordBreakingTokenizer<'a> {
18984 fn new(input: &'a str) -> Self {
18985 Self { input }
18986 }
18987}
18988
18989fn is_char_ideographic(ch: char) -> bool {
18990 use unicode_script::Script::*;
18991 use unicode_script::UnicodeScript;
18992 matches!(ch.script(), Han | Tangut | Yi)
18993}
18994
18995fn is_grapheme_ideographic(text: &str) -> bool {
18996 text.chars().any(is_char_ideographic)
18997}
18998
18999fn is_grapheme_whitespace(text: &str) -> bool {
19000 text.chars().any(|x| x.is_whitespace())
19001}
19002
19003fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19004 text.chars().next().map_or(false, |ch| {
19005 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19006 })
19007}
19008
19009#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19010enum WordBreakToken<'a> {
19011 Word { token: &'a str, grapheme_len: usize },
19012 InlineWhitespace { token: &'a str, grapheme_len: usize },
19013 Newline,
19014}
19015
19016impl<'a> Iterator for WordBreakingTokenizer<'a> {
19017 /// Yields a span, the count of graphemes in the token, and whether it was
19018 /// whitespace. Note that it also breaks at word boundaries.
19019 type Item = WordBreakToken<'a>;
19020
19021 fn next(&mut self) -> Option<Self::Item> {
19022 use unicode_segmentation::UnicodeSegmentation;
19023 if self.input.is_empty() {
19024 return None;
19025 }
19026
19027 let mut iter = self.input.graphemes(true).peekable();
19028 let mut offset = 0;
19029 let mut grapheme_len = 0;
19030 if let Some(first_grapheme) = iter.next() {
19031 let is_newline = first_grapheme == "\n";
19032 let is_whitespace = is_grapheme_whitespace(first_grapheme);
19033 offset += first_grapheme.len();
19034 grapheme_len += 1;
19035 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19036 if let Some(grapheme) = iter.peek().copied() {
19037 if should_stay_with_preceding_ideograph(grapheme) {
19038 offset += grapheme.len();
19039 grapheme_len += 1;
19040 }
19041 }
19042 } else {
19043 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19044 let mut next_word_bound = words.peek().copied();
19045 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19046 next_word_bound = words.next();
19047 }
19048 while let Some(grapheme) = iter.peek().copied() {
19049 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19050 break;
19051 };
19052 if is_grapheme_whitespace(grapheme) != is_whitespace
19053 || (grapheme == "\n") != is_newline
19054 {
19055 break;
19056 };
19057 offset += grapheme.len();
19058 grapheme_len += 1;
19059 iter.next();
19060 }
19061 }
19062 let token = &self.input[..offset];
19063 self.input = &self.input[offset..];
19064 if token == "\n" {
19065 Some(WordBreakToken::Newline)
19066 } else if is_whitespace {
19067 Some(WordBreakToken::InlineWhitespace {
19068 token,
19069 grapheme_len,
19070 })
19071 } else {
19072 Some(WordBreakToken::Word {
19073 token,
19074 grapheme_len,
19075 })
19076 }
19077 } else {
19078 None
19079 }
19080 }
19081}
19082
19083#[test]
19084fn test_word_breaking_tokenizer() {
19085 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19086 ("", &[]),
19087 (" ", &[whitespace(" ", 2)]),
19088 ("Ʒ", &[word("Ʒ", 1)]),
19089 ("Ǽ", &[word("Ǽ", 1)]),
19090 ("⋑", &[word("⋑", 1)]),
19091 ("⋑⋑", &[word("⋑⋑", 2)]),
19092 (
19093 "原理,进而",
19094 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19095 ),
19096 (
19097 "hello world",
19098 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19099 ),
19100 (
19101 "hello, world",
19102 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19103 ),
19104 (
19105 " hello world",
19106 &[
19107 whitespace(" ", 2),
19108 word("hello", 5),
19109 whitespace(" ", 1),
19110 word("world", 5),
19111 ],
19112 ),
19113 (
19114 "这是什么 \n 钢笔",
19115 &[
19116 word("这", 1),
19117 word("是", 1),
19118 word("什", 1),
19119 word("么", 1),
19120 whitespace(" ", 1),
19121 newline(),
19122 whitespace(" ", 1),
19123 word("钢", 1),
19124 word("笔", 1),
19125 ],
19126 ),
19127 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19128 ];
19129
19130 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19131 WordBreakToken::Word {
19132 token,
19133 grapheme_len,
19134 }
19135 }
19136
19137 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19138 WordBreakToken::InlineWhitespace {
19139 token,
19140 grapheme_len,
19141 }
19142 }
19143
19144 fn newline() -> WordBreakToken<'static> {
19145 WordBreakToken::Newline
19146 }
19147
19148 for (input, result) in tests {
19149 assert_eq!(
19150 WordBreakingTokenizer::new(input)
19151 .collect::<Vec<_>>()
19152 .as_slice(),
19153 *result,
19154 );
19155 }
19156}
19157
19158fn wrap_with_prefix(
19159 line_prefix: String,
19160 unwrapped_text: String,
19161 wrap_column: usize,
19162 tab_size: NonZeroU32,
19163 preserve_existing_whitespace: bool,
19164) -> String {
19165 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19166 let mut wrapped_text = String::new();
19167 let mut current_line = line_prefix.clone();
19168
19169 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19170 let mut current_line_len = line_prefix_len;
19171 let mut in_whitespace = false;
19172 for token in tokenizer {
19173 let have_preceding_whitespace = in_whitespace;
19174 match token {
19175 WordBreakToken::Word {
19176 token,
19177 grapheme_len,
19178 } => {
19179 in_whitespace = false;
19180 if current_line_len + grapheme_len > wrap_column
19181 && current_line_len != line_prefix_len
19182 {
19183 wrapped_text.push_str(current_line.trim_end());
19184 wrapped_text.push('\n');
19185 current_line.truncate(line_prefix.len());
19186 current_line_len = line_prefix_len;
19187 }
19188 current_line.push_str(token);
19189 current_line_len += grapheme_len;
19190 }
19191 WordBreakToken::InlineWhitespace {
19192 mut token,
19193 mut grapheme_len,
19194 } => {
19195 in_whitespace = true;
19196 if have_preceding_whitespace && !preserve_existing_whitespace {
19197 continue;
19198 }
19199 if !preserve_existing_whitespace {
19200 token = " ";
19201 grapheme_len = 1;
19202 }
19203 if current_line_len + grapheme_len > wrap_column {
19204 wrapped_text.push_str(current_line.trim_end());
19205 wrapped_text.push('\n');
19206 current_line.truncate(line_prefix.len());
19207 current_line_len = line_prefix_len;
19208 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19209 current_line.push_str(token);
19210 current_line_len += grapheme_len;
19211 }
19212 }
19213 WordBreakToken::Newline => {
19214 in_whitespace = true;
19215 if preserve_existing_whitespace {
19216 wrapped_text.push_str(current_line.trim_end());
19217 wrapped_text.push('\n');
19218 current_line.truncate(line_prefix.len());
19219 current_line_len = line_prefix_len;
19220 } else if have_preceding_whitespace {
19221 continue;
19222 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19223 {
19224 wrapped_text.push_str(current_line.trim_end());
19225 wrapped_text.push('\n');
19226 current_line.truncate(line_prefix.len());
19227 current_line_len = line_prefix_len;
19228 } else if current_line_len != line_prefix_len {
19229 current_line.push(' ');
19230 current_line_len += 1;
19231 }
19232 }
19233 }
19234 }
19235
19236 if !current_line.is_empty() {
19237 wrapped_text.push_str(¤t_line);
19238 }
19239 wrapped_text
19240}
19241
19242#[test]
19243fn test_wrap_with_prefix() {
19244 assert_eq!(
19245 wrap_with_prefix(
19246 "# ".to_string(),
19247 "abcdefg".to_string(),
19248 4,
19249 NonZeroU32::new(4).unwrap(),
19250 false,
19251 ),
19252 "# abcdefg"
19253 );
19254 assert_eq!(
19255 wrap_with_prefix(
19256 "".to_string(),
19257 "\thello world".to_string(),
19258 8,
19259 NonZeroU32::new(4).unwrap(),
19260 false,
19261 ),
19262 "hello\nworld"
19263 );
19264 assert_eq!(
19265 wrap_with_prefix(
19266 "// ".to_string(),
19267 "xx \nyy zz aa bb cc".to_string(),
19268 12,
19269 NonZeroU32::new(4).unwrap(),
19270 false,
19271 ),
19272 "// xx yy zz\n// aa bb cc"
19273 );
19274 assert_eq!(
19275 wrap_with_prefix(
19276 String::new(),
19277 "这是什么 \n 钢笔".to_string(),
19278 3,
19279 NonZeroU32::new(4).unwrap(),
19280 false,
19281 ),
19282 "这是什\n么 钢\n笔"
19283 );
19284}
19285
19286pub trait CollaborationHub {
19287 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19288 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19289 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19290}
19291
19292impl CollaborationHub for Entity<Project> {
19293 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19294 self.read(cx).collaborators()
19295 }
19296
19297 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19298 self.read(cx).user_store().read(cx).participant_indices()
19299 }
19300
19301 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19302 let this = self.read(cx);
19303 let user_ids = this.collaborators().values().map(|c| c.user_id);
19304 this.user_store().read_with(cx, |user_store, cx| {
19305 user_store.participant_names(user_ids, cx)
19306 })
19307 }
19308}
19309
19310pub trait SemanticsProvider {
19311 fn hover(
19312 &self,
19313 buffer: &Entity<Buffer>,
19314 position: text::Anchor,
19315 cx: &mut App,
19316 ) -> Option<Task<Vec<project::Hover>>>;
19317
19318 fn inline_values(
19319 &self,
19320 buffer_handle: Entity<Buffer>,
19321 range: Range<text::Anchor>,
19322 cx: &mut App,
19323 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19324
19325 fn inlay_hints(
19326 &self,
19327 buffer_handle: Entity<Buffer>,
19328 range: Range<text::Anchor>,
19329 cx: &mut App,
19330 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19331
19332 fn resolve_inlay_hint(
19333 &self,
19334 hint: InlayHint,
19335 buffer_handle: Entity<Buffer>,
19336 server_id: LanguageServerId,
19337 cx: &mut App,
19338 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19339
19340 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19341
19342 fn document_highlights(
19343 &self,
19344 buffer: &Entity<Buffer>,
19345 position: text::Anchor,
19346 cx: &mut App,
19347 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19348
19349 fn definitions(
19350 &self,
19351 buffer: &Entity<Buffer>,
19352 position: text::Anchor,
19353 kind: GotoDefinitionKind,
19354 cx: &mut App,
19355 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19356
19357 fn range_for_rename(
19358 &self,
19359 buffer: &Entity<Buffer>,
19360 position: text::Anchor,
19361 cx: &mut App,
19362 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19363
19364 fn perform_rename(
19365 &self,
19366 buffer: &Entity<Buffer>,
19367 position: text::Anchor,
19368 new_name: String,
19369 cx: &mut App,
19370 ) -> Option<Task<Result<ProjectTransaction>>>;
19371}
19372
19373pub trait CompletionProvider {
19374 fn completions(
19375 &self,
19376 excerpt_id: ExcerptId,
19377 buffer: &Entity<Buffer>,
19378 buffer_position: text::Anchor,
19379 trigger: CompletionContext,
19380 window: &mut Window,
19381 cx: &mut Context<Editor>,
19382 ) -> Task<Result<Option<Vec<Completion>>>>;
19383
19384 fn resolve_completions(
19385 &self,
19386 buffer: Entity<Buffer>,
19387 completion_indices: Vec<usize>,
19388 completions: Rc<RefCell<Box<[Completion]>>>,
19389 cx: &mut Context<Editor>,
19390 ) -> Task<Result<bool>>;
19391
19392 fn apply_additional_edits_for_completion(
19393 &self,
19394 _buffer: Entity<Buffer>,
19395 _completions: Rc<RefCell<Box<[Completion]>>>,
19396 _completion_index: usize,
19397 _push_to_history: bool,
19398 _cx: &mut Context<Editor>,
19399 ) -> Task<Result<Option<language::Transaction>>> {
19400 Task::ready(Ok(None))
19401 }
19402
19403 fn is_completion_trigger(
19404 &self,
19405 buffer: &Entity<Buffer>,
19406 position: language::Anchor,
19407 text: &str,
19408 trigger_in_words: bool,
19409 cx: &mut Context<Editor>,
19410 ) -> bool;
19411
19412 fn sort_completions(&self) -> bool {
19413 true
19414 }
19415
19416 fn filter_completions(&self) -> bool {
19417 true
19418 }
19419}
19420
19421pub trait CodeActionProvider {
19422 fn id(&self) -> Arc<str>;
19423
19424 fn code_actions(
19425 &self,
19426 buffer: &Entity<Buffer>,
19427 range: Range<text::Anchor>,
19428 window: &mut Window,
19429 cx: &mut App,
19430 ) -> Task<Result<Vec<CodeAction>>>;
19431
19432 fn apply_code_action(
19433 &self,
19434 buffer_handle: Entity<Buffer>,
19435 action: CodeAction,
19436 excerpt_id: ExcerptId,
19437 push_to_history: bool,
19438 window: &mut Window,
19439 cx: &mut App,
19440 ) -> Task<Result<ProjectTransaction>>;
19441}
19442
19443impl CodeActionProvider for Entity<Project> {
19444 fn id(&self) -> Arc<str> {
19445 "project".into()
19446 }
19447
19448 fn code_actions(
19449 &self,
19450 buffer: &Entity<Buffer>,
19451 range: Range<text::Anchor>,
19452 _window: &mut Window,
19453 cx: &mut App,
19454 ) -> Task<Result<Vec<CodeAction>>> {
19455 self.update(cx, |project, cx| {
19456 let code_lens = project.code_lens(buffer, range.clone(), cx);
19457 let code_actions = project.code_actions(buffer, range, None, cx);
19458 cx.background_spawn(async move {
19459 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19460 Ok(code_lens
19461 .context("code lens fetch")?
19462 .into_iter()
19463 .chain(code_actions.context("code action fetch")?)
19464 .collect())
19465 })
19466 })
19467 }
19468
19469 fn apply_code_action(
19470 &self,
19471 buffer_handle: Entity<Buffer>,
19472 action: CodeAction,
19473 _excerpt_id: ExcerptId,
19474 push_to_history: bool,
19475 _window: &mut Window,
19476 cx: &mut App,
19477 ) -> Task<Result<ProjectTransaction>> {
19478 self.update(cx, |project, cx| {
19479 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19480 })
19481 }
19482}
19483
19484fn snippet_completions(
19485 project: &Project,
19486 buffer: &Entity<Buffer>,
19487 buffer_position: text::Anchor,
19488 cx: &mut App,
19489) -> Task<Result<Vec<Completion>>> {
19490 let languages = buffer.read(cx).languages_at(buffer_position);
19491 let snippet_store = project.snippets().read(cx);
19492
19493 let scopes: Vec<_> = languages
19494 .iter()
19495 .filter_map(|language| {
19496 let language_name = language.lsp_id();
19497 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19498
19499 if snippets.is_empty() {
19500 None
19501 } else {
19502 Some((language.default_scope(), snippets))
19503 }
19504 })
19505 .collect();
19506
19507 if scopes.is_empty() {
19508 return Task::ready(Ok(vec![]));
19509 }
19510
19511 let snapshot = buffer.read(cx).text_snapshot();
19512 let chars: String = snapshot
19513 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19514 .collect();
19515 let executor = cx.background_executor().clone();
19516
19517 cx.background_spawn(async move {
19518 let mut all_results: Vec<Completion> = Vec::new();
19519 for (scope, snippets) in scopes.into_iter() {
19520 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19521 let mut last_word = chars
19522 .chars()
19523 .take_while(|c| classifier.is_word(*c))
19524 .collect::<String>();
19525 last_word = last_word.chars().rev().collect();
19526
19527 if last_word.is_empty() {
19528 return Ok(vec![]);
19529 }
19530
19531 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19532 let to_lsp = |point: &text::Anchor| {
19533 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19534 point_to_lsp(end)
19535 };
19536 let lsp_end = to_lsp(&buffer_position);
19537
19538 let candidates = snippets
19539 .iter()
19540 .enumerate()
19541 .flat_map(|(ix, snippet)| {
19542 snippet
19543 .prefix
19544 .iter()
19545 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19546 })
19547 .collect::<Vec<StringMatchCandidate>>();
19548
19549 let mut matches = fuzzy::match_strings(
19550 &candidates,
19551 &last_word,
19552 last_word.chars().any(|c| c.is_uppercase()),
19553 100,
19554 &Default::default(),
19555 executor.clone(),
19556 )
19557 .await;
19558
19559 // Remove all candidates where the query's start does not match the start of any word in the candidate
19560 if let Some(query_start) = last_word.chars().next() {
19561 matches.retain(|string_match| {
19562 split_words(&string_match.string).any(|word| {
19563 // Check that the first codepoint of the word as lowercase matches the first
19564 // codepoint of the query as lowercase
19565 word.chars()
19566 .flat_map(|codepoint| codepoint.to_lowercase())
19567 .zip(query_start.to_lowercase())
19568 .all(|(word_cp, query_cp)| word_cp == query_cp)
19569 })
19570 });
19571 }
19572
19573 let matched_strings = matches
19574 .into_iter()
19575 .map(|m| m.string)
19576 .collect::<HashSet<_>>();
19577
19578 let mut result: Vec<Completion> = snippets
19579 .iter()
19580 .filter_map(|snippet| {
19581 let matching_prefix = snippet
19582 .prefix
19583 .iter()
19584 .find(|prefix| matched_strings.contains(*prefix))?;
19585 let start = as_offset - last_word.len();
19586 let start = snapshot.anchor_before(start);
19587 let range = start..buffer_position;
19588 let lsp_start = to_lsp(&start);
19589 let lsp_range = lsp::Range {
19590 start: lsp_start,
19591 end: lsp_end,
19592 };
19593 Some(Completion {
19594 replace_range: range,
19595 new_text: snippet.body.clone(),
19596 source: CompletionSource::Lsp {
19597 insert_range: None,
19598 server_id: LanguageServerId(usize::MAX),
19599 resolved: true,
19600 lsp_completion: Box::new(lsp::CompletionItem {
19601 label: snippet.prefix.first().unwrap().clone(),
19602 kind: Some(CompletionItemKind::SNIPPET),
19603 label_details: snippet.description.as_ref().map(|description| {
19604 lsp::CompletionItemLabelDetails {
19605 detail: Some(description.clone()),
19606 description: None,
19607 }
19608 }),
19609 insert_text_format: Some(InsertTextFormat::SNIPPET),
19610 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19611 lsp::InsertReplaceEdit {
19612 new_text: snippet.body.clone(),
19613 insert: lsp_range,
19614 replace: lsp_range,
19615 },
19616 )),
19617 filter_text: Some(snippet.body.clone()),
19618 sort_text: Some(char::MAX.to_string()),
19619 ..lsp::CompletionItem::default()
19620 }),
19621 lsp_defaults: None,
19622 },
19623 label: CodeLabel {
19624 text: matching_prefix.clone(),
19625 runs: Vec::new(),
19626 filter_range: 0..matching_prefix.len(),
19627 },
19628 icon_path: None,
19629 documentation: snippet.description.clone().map(|description| {
19630 CompletionDocumentation::SingleLine(description.into())
19631 }),
19632 insert_text_mode: None,
19633 confirm: None,
19634 })
19635 })
19636 .collect();
19637
19638 all_results.append(&mut result);
19639 }
19640
19641 Ok(all_results)
19642 })
19643}
19644
19645impl CompletionProvider for Entity<Project> {
19646 fn completions(
19647 &self,
19648 _excerpt_id: ExcerptId,
19649 buffer: &Entity<Buffer>,
19650 buffer_position: text::Anchor,
19651 options: CompletionContext,
19652 _window: &mut Window,
19653 cx: &mut Context<Editor>,
19654 ) -> Task<Result<Option<Vec<Completion>>>> {
19655 self.update(cx, |project, cx| {
19656 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19657 let project_completions = project.completions(buffer, buffer_position, options, cx);
19658 cx.background_spawn(async move {
19659 let snippets_completions = snippets.await?;
19660 match project_completions.await? {
19661 Some(mut completions) => {
19662 completions.extend(snippets_completions);
19663 Ok(Some(completions))
19664 }
19665 None => {
19666 if snippets_completions.is_empty() {
19667 Ok(None)
19668 } else {
19669 Ok(Some(snippets_completions))
19670 }
19671 }
19672 }
19673 })
19674 })
19675 }
19676
19677 fn resolve_completions(
19678 &self,
19679 buffer: Entity<Buffer>,
19680 completion_indices: Vec<usize>,
19681 completions: Rc<RefCell<Box<[Completion]>>>,
19682 cx: &mut Context<Editor>,
19683 ) -> Task<Result<bool>> {
19684 self.update(cx, |project, cx| {
19685 project.lsp_store().update(cx, |lsp_store, cx| {
19686 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19687 })
19688 })
19689 }
19690
19691 fn apply_additional_edits_for_completion(
19692 &self,
19693 buffer: Entity<Buffer>,
19694 completions: Rc<RefCell<Box<[Completion]>>>,
19695 completion_index: usize,
19696 push_to_history: bool,
19697 cx: &mut Context<Editor>,
19698 ) -> Task<Result<Option<language::Transaction>>> {
19699 self.update(cx, |project, cx| {
19700 project.lsp_store().update(cx, |lsp_store, cx| {
19701 lsp_store.apply_additional_edits_for_completion(
19702 buffer,
19703 completions,
19704 completion_index,
19705 push_to_history,
19706 cx,
19707 )
19708 })
19709 })
19710 }
19711
19712 fn is_completion_trigger(
19713 &self,
19714 buffer: &Entity<Buffer>,
19715 position: language::Anchor,
19716 text: &str,
19717 trigger_in_words: bool,
19718 cx: &mut Context<Editor>,
19719 ) -> bool {
19720 let mut chars = text.chars();
19721 let char = if let Some(char) = chars.next() {
19722 char
19723 } else {
19724 return false;
19725 };
19726 if chars.next().is_some() {
19727 return false;
19728 }
19729
19730 let buffer = buffer.read(cx);
19731 let snapshot = buffer.snapshot();
19732 if !snapshot.settings_at(position, cx).show_completions_on_input {
19733 return false;
19734 }
19735 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19736 if trigger_in_words && classifier.is_word(char) {
19737 return true;
19738 }
19739
19740 buffer.completion_triggers().contains(text)
19741 }
19742}
19743
19744impl SemanticsProvider for Entity<Project> {
19745 fn hover(
19746 &self,
19747 buffer: &Entity<Buffer>,
19748 position: text::Anchor,
19749 cx: &mut App,
19750 ) -> Option<Task<Vec<project::Hover>>> {
19751 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19752 }
19753
19754 fn document_highlights(
19755 &self,
19756 buffer: &Entity<Buffer>,
19757 position: text::Anchor,
19758 cx: &mut App,
19759 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19760 Some(self.update(cx, |project, cx| {
19761 project.document_highlights(buffer, position, cx)
19762 }))
19763 }
19764
19765 fn definitions(
19766 &self,
19767 buffer: &Entity<Buffer>,
19768 position: text::Anchor,
19769 kind: GotoDefinitionKind,
19770 cx: &mut App,
19771 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19772 Some(self.update(cx, |project, cx| match kind {
19773 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19774 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19775 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19776 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19777 }))
19778 }
19779
19780 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19781 // TODO: make this work for remote projects
19782 self.update(cx, |project, cx| {
19783 if project
19784 .active_debug_session(cx)
19785 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19786 {
19787 return true;
19788 }
19789
19790 buffer.update(cx, |buffer, cx| {
19791 project.any_language_server_supports_inlay_hints(buffer, cx)
19792 })
19793 })
19794 }
19795
19796 fn inline_values(
19797 &self,
19798 buffer_handle: Entity<Buffer>,
19799 range: Range<text::Anchor>,
19800 cx: &mut App,
19801 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19802 self.update(cx, |project, cx| {
19803 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19804
19805 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19806 })
19807 }
19808
19809 fn inlay_hints(
19810 &self,
19811 buffer_handle: Entity<Buffer>,
19812 range: Range<text::Anchor>,
19813 cx: &mut App,
19814 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19815 Some(self.update(cx, |project, cx| {
19816 project.inlay_hints(buffer_handle, range, cx)
19817 }))
19818 }
19819
19820 fn resolve_inlay_hint(
19821 &self,
19822 hint: InlayHint,
19823 buffer_handle: Entity<Buffer>,
19824 server_id: LanguageServerId,
19825 cx: &mut App,
19826 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19827 Some(self.update(cx, |project, cx| {
19828 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19829 }))
19830 }
19831
19832 fn range_for_rename(
19833 &self,
19834 buffer: &Entity<Buffer>,
19835 position: text::Anchor,
19836 cx: &mut App,
19837 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19838 Some(self.update(cx, |project, cx| {
19839 let buffer = buffer.clone();
19840 let task = project.prepare_rename(buffer.clone(), position, cx);
19841 cx.spawn(async move |_, cx| {
19842 Ok(match task.await? {
19843 PrepareRenameResponse::Success(range) => Some(range),
19844 PrepareRenameResponse::InvalidPosition => None,
19845 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19846 // Fallback on using TreeSitter info to determine identifier range
19847 buffer.update(cx, |buffer, _| {
19848 let snapshot = buffer.snapshot();
19849 let (range, kind) = snapshot.surrounding_word(position);
19850 if kind != Some(CharKind::Word) {
19851 return None;
19852 }
19853 Some(
19854 snapshot.anchor_before(range.start)
19855 ..snapshot.anchor_after(range.end),
19856 )
19857 })?
19858 }
19859 })
19860 })
19861 }))
19862 }
19863
19864 fn perform_rename(
19865 &self,
19866 buffer: &Entity<Buffer>,
19867 position: text::Anchor,
19868 new_name: String,
19869 cx: &mut App,
19870 ) -> Option<Task<Result<ProjectTransaction>>> {
19871 Some(self.update(cx, |project, cx| {
19872 project.perform_rename(buffer.clone(), position, new_name, cx)
19873 }))
19874 }
19875}
19876
19877fn inlay_hint_settings(
19878 location: Anchor,
19879 snapshot: &MultiBufferSnapshot,
19880 cx: &mut Context<Editor>,
19881) -> InlayHintSettings {
19882 let file = snapshot.file_at(location);
19883 let language = snapshot.language_at(location).map(|l| l.name());
19884 language_settings(language, file, cx).inlay_hints
19885}
19886
19887fn consume_contiguous_rows(
19888 contiguous_row_selections: &mut Vec<Selection<Point>>,
19889 selection: &Selection<Point>,
19890 display_map: &DisplaySnapshot,
19891 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19892) -> (MultiBufferRow, MultiBufferRow) {
19893 contiguous_row_selections.push(selection.clone());
19894 let start_row = MultiBufferRow(selection.start.row);
19895 let mut end_row = ending_row(selection, display_map);
19896
19897 while let Some(next_selection) = selections.peek() {
19898 if next_selection.start.row <= end_row.0 {
19899 end_row = ending_row(next_selection, display_map);
19900 contiguous_row_selections.push(selections.next().unwrap().clone());
19901 } else {
19902 break;
19903 }
19904 }
19905 (start_row, end_row)
19906}
19907
19908fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19909 if next_selection.end.column > 0 || next_selection.is_empty() {
19910 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19911 } else {
19912 MultiBufferRow(next_selection.end.row)
19913 }
19914}
19915
19916impl EditorSnapshot {
19917 pub fn remote_selections_in_range<'a>(
19918 &'a self,
19919 range: &'a Range<Anchor>,
19920 collaboration_hub: &dyn CollaborationHub,
19921 cx: &'a App,
19922 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19923 let participant_names = collaboration_hub.user_names(cx);
19924 let participant_indices = collaboration_hub.user_participant_indices(cx);
19925 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19926 let collaborators_by_replica_id = collaborators_by_peer_id
19927 .iter()
19928 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19929 .collect::<HashMap<_, _>>();
19930 self.buffer_snapshot
19931 .selections_in_range(range, false)
19932 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19933 if replica_id == AGENT_REPLICA_ID {
19934 Some(RemoteSelection {
19935 replica_id,
19936 selection,
19937 cursor_shape,
19938 line_mode,
19939 collaborator_id: CollaboratorId::Agent,
19940 user_name: Some("Agent".into()),
19941 color: cx.theme().players().agent(),
19942 })
19943 } else {
19944 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19945 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19946 let user_name = participant_names.get(&collaborator.user_id).cloned();
19947 Some(RemoteSelection {
19948 replica_id,
19949 selection,
19950 cursor_shape,
19951 line_mode,
19952 collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19953 user_name,
19954 color: if let Some(index) = participant_index {
19955 cx.theme().players().color_for_participant(index.0)
19956 } else {
19957 cx.theme().players().absent()
19958 },
19959 })
19960 }
19961 })
19962 }
19963
19964 pub fn hunks_for_ranges(
19965 &self,
19966 ranges: impl IntoIterator<Item = Range<Point>>,
19967 ) -> Vec<MultiBufferDiffHunk> {
19968 let mut hunks = Vec::new();
19969 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19970 HashMap::default();
19971 for query_range in ranges {
19972 let query_rows =
19973 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19974 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19975 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19976 ) {
19977 // Include deleted hunks that are adjacent to the query range, because
19978 // otherwise they would be missed.
19979 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19980 if hunk.status().is_deleted() {
19981 intersects_range |= hunk.row_range.start == query_rows.end;
19982 intersects_range |= hunk.row_range.end == query_rows.start;
19983 }
19984 if intersects_range {
19985 if !processed_buffer_rows
19986 .entry(hunk.buffer_id)
19987 .or_default()
19988 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19989 {
19990 continue;
19991 }
19992 hunks.push(hunk);
19993 }
19994 }
19995 }
19996
19997 hunks
19998 }
19999
20000 fn display_diff_hunks_for_rows<'a>(
20001 &'a self,
20002 display_rows: Range<DisplayRow>,
20003 folded_buffers: &'a HashSet<BufferId>,
20004 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20005 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20006 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20007
20008 self.buffer_snapshot
20009 .diff_hunks_in_range(buffer_start..buffer_end)
20010 .filter_map(|hunk| {
20011 if folded_buffers.contains(&hunk.buffer_id) {
20012 return None;
20013 }
20014
20015 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20016 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20017
20018 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20019 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20020
20021 let display_hunk = if hunk_display_start.column() != 0 {
20022 DisplayDiffHunk::Folded {
20023 display_row: hunk_display_start.row(),
20024 }
20025 } else {
20026 let mut end_row = hunk_display_end.row();
20027 if hunk_display_end.column() > 0 {
20028 end_row.0 += 1;
20029 }
20030 let is_created_file = hunk.is_created_file();
20031 DisplayDiffHunk::Unfolded {
20032 status: hunk.status(),
20033 diff_base_byte_range: hunk.diff_base_byte_range,
20034 display_row_range: hunk_display_start.row()..end_row,
20035 multi_buffer_range: Anchor::range_in_buffer(
20036 hunk.excerpt_id,
20037 hunk.buffer_id,
20038 hunk.buffer_range,
20039 ),
20040 is_created_file,
20041 }
20042 };
20043
20044 Some(display_hunk)
20045 })
20046 }
20047
20048 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20049 self.display_snapshot.buffer_snapshot.language_at(position)
20050 }
20051
20052 pub fn is_focused(&self) -> bool {
20053 self.is_focused
20054 }
20055
20056 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20057 self.placeholder_text.as_ref()
20058 }
20059
20060 pub fn scroll_position(&self) -> gpui::Point<f32> {
20061 self.scroll_anchor.scroll_position(&self.display_snapshot)
20062 }
20063
20064 fn gutter_dimensions(
20065 &self,
20066 font_id: FontId,
20067 font_size: Pixels,
20068 max_line_number_width: Pixels,
20069 cx: &App,
20070 ) -> Option<GutterDimensions> {
20071 if !self.show_gutter {
20072 return None;
20073 }
20074
20075 let descent = cx.text_system().descent(font_id, font_size);
20076 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20077 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20078
20079 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20080 matches!(
20081 ProjectSettings::get_global(cx).git.git_gutter,
20082 Some(GitGutterSetting::TrackedFiles)
20083 )
20084 });
20085 let gutter_settings = EditorSettings::get_global(cx).gutter;
20086 let show_line_numbers = self
20087 .show_line_numbers
20088 .unwrap_or(gutter_settings.line_numbers);
20089 let line_gutter_width = if show_line_numbers {
20090 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20091 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20092 max_line_number_width.max(min_width_for_number_on_gutter)
20093 } else {
20094 0.0.into()
20095 };
20096
20097 let show_code_actions = self
20098 .show_code_actions
20099 .unwrap_or(gutter_settings.code_actions);
20100
20101 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20102 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20103
20104 let git_blame_entries_width =
20105 self.git_blame_gutter_max_author_length
20106 .map(|max_author_length| {
20107 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20108 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20109
20110 /// The number of characters to dedicate to gaps and margins.
20111 const SPACING_WIDTH: usize = 4;
20112
20113 let max_char_count = max_author_length.min(renderer.max_author_length())
20114 + ::git::SHORT_SHA_LENGTH
20115 + MAX_RELATIVE_TIMESTAMP.len()
20116 + SPACING_WIDTH;
20117
20118 em_advance * max_char_count
20119 });
20120
20121 let is_singleton = self.buffer_snapshot.is_singleton();
20122
20123 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20124 left_padding += if !is_singleton {
20125 em_width * 4.0
20126 } else if show_code_actions || show_runnables || show_breakpoints {
20127 em_width * 3.0
20128 } else if show_git_gutter && show_line_numbers {
20129 em_width * 2.0
20130 } else if show_git_gutter || show_line_numbers {
20131 em_width
20132 } else {
20133 px(0.)
20134 };
20135
20136 let shows_folds = is_singleton && gutter_settings.folds;
20137
20138 let right_padding = if shows_folds && show_line_numbers {
20139 em_width * 4.0
20140 } else if shows_folds || (!is_singleton && show_line_numbers) {
20141 em_width * 3.0
20142 } else if show_line_numbers {
20143 em_width
20144 } else {
20145 px(0.)
20146 };
20147
20148 Some(GutterDimensions {
20149 left_padding,
20150 right_padding,
20151 width: line_gutter_width + left_padding + right_padding,
20152 margin: -descent,
20153 git_blame_entries_width,
20154 })
20155 }
20156
20157 pub fn render_crease_toggle(
20158 &self,
20159 buffer_row: MultiBufferRow,
20160 row_contains_cursor: bool,
20161 editor: Entity<Editor>,
20162 window: &mut Window,
20163 cx: &mut App,
20164 ) -> Option<AnyElement> {
20165 let folded = self.is_line_folded(buffer_row);
20166 let mut is_foldable = false;
20167
20168 if let Some(crease) = self
20169 .crease_snapshot
20170 .query_row(buffer_row, &self.buffer_snapshot)
20171 {
20172 is_foldable = true;
20173 match crease {
20174 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20175 if let Some(render_toggle) = render_toggle {
20176 let toggle_callback =
20177 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20178 if folded {
20179 editor.update(cx, |editor, cx| {
20180 editor.fold_at(buffer_row, window, cx)
20181 });
20182 } else {
20183 editor.update(cx, |editor, cx| {
20184 editor.unfold_at(buffer_row, window, cx)
20185 });
20186 }
20187 });
20188 return Some((render_toggle)(
20189 buffer_row,
20190 folded,
20191 toggle_callback,
20192 window,
20193 cx,
20194 ));
20195 }
20196 }
20197 }
20198 }
20199
20200 is_foldable |= self.starts_indent(buffer_row);
20201
20202 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20203 Some(
20204 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20205 .toggle_state(folded)
20206 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20207 if folded {
20208 this.unfold_at(buffer_row, window, cx);
20209 } else {
20210 this.fold_at(buffer_row, window, cx);
20211 }
20212 }))
20213 .into_any_element(),
20214 )
20215 } else {
20216 None
20217 }
20218 }
20219
20220 pub fn render_crease_trailer(
20221 &self,
20222 buffer_row: MultiBufferRow,
20223 window: &mut Window,
20224 cx: &mut App,
20225 ) -> Option<AnyElement> {
20226 let folded = self.is_line_folded(buffer_row);
20227 if let Crease::Inline { render_trailer, .. } = self
20228 .crease_snapshot
20229 .query_row(buffer_row, &self.buffer_snapshot)?
20230 {
20231 let render_trailer = render_trailer.as_ref()?;
20232 Some(render_trailer(buffer_row, folded, window, cx))
20233 } else {
20234 None
20235 }
20236 }
20237}
20238
20239impl Deref for EditorSnapshot {
20240 type Target = DisplaySnapshot;
20241
20242 fn deref(&self) -> &Self::Target {
20243 &self.display_snapshot
20244 }
20245}
20246
20247#[derive(Clone, Debug, PartialEq, Eq)]
20248pub enum EditorEvent {
20249 InputIgnored {
20250 text: Arc<str>,
20251 },
20252 InputHandled {
20253 utf16_range_to_replace: Option<Range<isize>>,
20254 text: Arc<str>,
20255 },
20256 ExcerptsAdded {
20257 buffer: Entity<Buffer>,
20258 predecessor: ExcerptId,
20259 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20260 },
20261 ExcerptsRemoved {
20262 ids: Vec<ExcerptId>,
20263 removed_buffer_ids: Vec<BufferId>,
20264 },
20265 BufferFoldToggled {
20266 ids: Vec<ExcerptId>,
20267 folded: bool,
20268 },
20269 ExcerptsEdited {
20270 ids: Vec<ExcerptId>,
20271 },
20272 ExcerptsExpanded {
20273 ids: Vec<ExcerptId>,
20274 },
20275 BufferEdited,
20276 Edited {
20277 transaction_id: clock::Lamport,
20278 },
20279 Reparsed(BufferId),
20280 Focused,
20281 FocusedIn,
20282 Blurred,
20283 DirtyChanged,
20284 Saved,
20285 TitleChanged,
20286 DiffBaseChanged,
20287 SelectionsChanged {
20288 local: bool,
20289 },
20290 ScrollPositionChanged {
20291 local: bool,
20292 autoscroll: bool,
20293 },
20294 Closed,
20295 TransactionUndone {
20296 transaction_id: clock::Lamport,
20297 },
20298 TransactionBegun {
20299 transaction_id: clock::Lamport,
20300 },
20301 Reloaded,
20302 CursorShapeChanged,
20303 PushedToNavHistory {
20304 anchor: Anchor,
20305 is_deactivate: bool,
20306 },
20307}
20308
20309impl EventEmitter<EditorEvent> for Editor {}
20310
20311impl Focusable for Editor {
20312 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20313 self.focus_handle.clone()
20314 }
20315}
20316
20317impl Render for Editor {
20318 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20319 let settings = ThemeSettings::get_global(cx);
20320
20321 let mut text_style = match self.mode {
20322 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20323 color: cx.theme().colors().editor_foreground,
20324 font_family: settings.ui_font.family.clone(),
20325 font_features: settings.ui_font.features.clone(),
20326 font_fallbacks: settings.ui_font.fallbacks.clone(),
20327 font_size: rems(0.875).into(),
20328 font_weight: settings.ui_font.weight,
20329 line_height: relative(settings.buffer_line_height.value()),
20330 ..Default::default()
20331 },
20332 EditorMode::Full { .. } => TextStyle {
20333 color: cx.theme().colors().editor_foreground,
20334 font_family: settings.buffer_font.family.clone(),
20335 font_features: settings.buffer_font.features.clone(),
20336 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20337 font_size: settings.buffer_font_size(cx).into(),
20338 font_weight: settings.buffer_font.weight,
20339 line_height: relative(settings.buffer_line_height.value()),
20340 ..Default::default()
20341 },
20342 };
20343 if let Some(text_style_refinement) = &self.text_style_refinement {
20344 text_style.refine(text_style_refinement)
20345 }
20346
20347 let background = match self.mode {
20348 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20349 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20350 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20351 };
20352
20353 EditorElement::new(
20354 &cx.entity(),
20355 EditorStyle {
20356 background,
20357 horizontal_padding: Pixels::default(),
20358 local_player: cx.theme().players().local(),
20359 text: text_style,
20360 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20361 syntax: cx.theme().syntax().clone(),
20362 status: cx.theme().status().clone(),
20363 inlay_hints_style: make_inlay_hints_style(cx),
20364 inline_completion_styles: make_suggestion_styles(cx),
20365 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20366 },
20367 )
20368 }
20369}
20370
20371impl EntityInputHandler for Editor {
20372 fn text_for_range(
20373 &mut self,
20374 range_utf16: Range<usize>,
20375 adjusted_range: &mut Option<Range<usize>>,
20376 _: &mut Window,
20377 cx: &mut Context<Self>,
20378 ) -> Option<String> {
20379 let snapshot = self.buffer.read(cx).read(cx);
20380 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20381 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20382 if (start.0..end.0) != range_utf16 {
20383 adjusted_range.replace(start.0..end.0);
20384 }
20385 Some(snapshot.text_for_range(start..end).collect())
20386 }
20387
20388 fn selected_text_range(
20389 &mut self,
20390 ignore_disabled_input: bool,
20391 _: &mut Window,
20392 cx: &mut Context<Self>,
20393 ) -> Option<UTF16Selection> {
20394 // Prevent the IME menu from appearing when holding down an alphabetic key
20395 // while input is disabled.
20396 if !ignore_disabled_input && !self.input_enabled {
20397 return None;
20398 }
20399
20400 let selection = self.selections.newest::<OffsetUtf16>(cx);
20401 let range = selection.range();
20402
20403 Some(UTF16Selection {
20404 range: range.start.0..range.end.0,
20405 reversed: selection.reversed,
20406 })
20407 }
20408
20409 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20410 let snapshot = self.buffer.read(cx).read(cx);
20411 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20412 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20413 }
20414
20415 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20416 self.clear_highlights::<InputComposition>(cx);
20417 self.ime_transaction.take();
20418 }
20419
20420 fn replace_text_in_range(
20421 &mut self,
20422 range_utf16: Option<Range<usize>>,
20423 text: &str,
20424 window: &mut Window,
20425 cx: &mut Context<Self>,
20426 ) {
20427 if !self.input_enabled {
20428 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20429 return;
20430 }
20431
20432 self.transact(window, cx, |this, window, cx| {
20433 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20434 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20435 Some(this.selection_replacement_ranges(range_utf16, cx))
20436 } else {
20437 this.marked_text_ranges(cx)
20438 };
20439
20440 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20441 let newest_selection_id = this.selections.newest_anchor().id;
20442 this.selections
20443 .all::<OffsetUtf16>(cx)
20444 .iter()
20445 .zip(ranges_to_replace.iter())
20446 .find_map(|(selection, range)| {
20447 if selection.id == newest_selection_id {
20448 Some(
20449 (range.start.0 as isize - selection.head().0 as isize)
20450 ..(range.end.0 as isize - selection.head().0 as isize),
20451 )
20452 } else {
20453 None
20454 }
20455 })
20456 });
20457
20458 cx.emit(EditorEvent::InputHandled {
20459 utf16_range_to_replace: range_to_replace,
20460 text: text.into(),
20461 });
20462
20463 if let Some(new_selected_ranges) = new_selected_ranges {
20464 this.change_selections(None, window, cx, |selections| {
20465 selections.select_ranges(new_selected_ranges)
20466 });
20467 this.backspace(&Default::default(), window, cx);
20468 }
20469
20470 this.handle_input(text, window, cx);
20471 });
20472
20473 if let Some(transaction) = self.ime_transaction {
20474 self.buffer.update(cx, |buffer, cx| {
20475 buffer.group_until_transaction(transaction, cx);
20476 });
20477 }
20478
20479 self.unmark_text(window, cx);
20480 }
20481
20482 fn replace_and_mark_text_in_range(
20483 &mut self,
20484 range_utf16: Option<Range<usize>>,
20485 text: &str,
20486 new_selected_range_utf16: Option<Range<usize>>,
20487 window: &mut Window,
20488 cx: &mut Context<Self>,
20489 ) {
20490 if !self.input_enabled {
20491 return;
20492 }
20493
20494 let transaction = self.transact(window, cx, |this, window, cx| {
20495 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20496 let snapshot = this.buffer.read(cx).read(cx);
20497 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20498 for marked_range in &mut marked_ranges {
20499 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20500 marked_range.start.0 += relative_range_utf16.start;
20501 marked_range.start =
20502 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20503 marked_range.end =
20504 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20505 }
20506 }
20507 Some(marked_ranges)
20508 } else if let Some(range_utf16) = range_utf16 {
20509 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20510 Some(this.selection_replacement_ranges(range_utf16, cx))
20511 } else {
20512 None
20513 };
20514
20515 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20516 let newest_selection_id = this.selections.newest_anchor().id;
20517 this.selections
20518 .all::<OffsetUtf16>(cx)
20519 .iter()
20520 .zip(ranges_to_replace.iter())
20521 .find_map(|(selection, range)| {
20522 if selection.id == newest_selection_id {
20523 Some(
20524 (range.start.0 as isize - selection.head().0 as isize)
20525 ..(range.end.0 as isize - selection.head().0 as isize),
20526 )
20527 } else {
20528 None
20529 }
20530 })
20531 });
20532
20533 cx.emit(EditorEvent::InputHandled {
20534 utf16_range_to_replace: range_to_replace,
20535 text: text.into(),
20536 });
20537
20538 if let Some(ranges) = ranges_to_replace {
20539 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20540 }
20541
20542 let marked_ranges = {
20543 let snapshot = this.buffer.read(cx).read(cx);
20544 this.selections
20545 .disjoint_anchors()
20546 .iter()
20547 .map(|selection| {
20548 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20549 })
20550 .collect::<Vec<_>>()
20551 };
20552
20553 if text.is_empty() {
20554 this.unmark_text(window, cx);
20555 } else {
20556 this.highlight_text::<InputComposition>(
20557 marked_ranges.clone(),
20558 HighlightStyle {
20559 underline: Some(UnderlineStyle {
20560 thickness: px(1.),
20561 color: None,
20562 wavy: false,
20563 }),
20564 ..Default::default()
20565 },
20566 cx,
20567 );
20568 }
20569
20570 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20571 let use_autoclose = this.use_autoclose;
20572 let use_auto_surround = this.use_auto_surround;
20573 this.set_use_autoclose(false);
20574 this.set_use_auto_surround(false);
20575 this.handle_input(text, window, cx);
20576 this.set_use_autoclose(use_autoclose);
20577 this.set_use_auto_surround(use_auto_surround);
20578
20579 if let Some(new_selected_range) = new_selected_range_utf16 {
20580 let snapshot = this.buffer.read(cx).read(cx);
20581 let new_selected_ranges = marked_ranges
20582 .into_iter()
20583 .map(|marked_range| {
20584 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20585 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20586 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20587 snapshot.clip_offset_utf16(new_start, Bias::Left)
20588 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20589 })
20590 .collect::<Vec<_>>();
20591
20592 drop(snapshot);
20593 this.change_selections(None, window, cx, |selections| {
20594 selections.select_ranges(new_selected_ranges)
20595 });
20596 }
20597 });
20598
20599 self.ime_transaction = self.ime_transaction.or(transaction);
20600 if let Some(transaction) = self.ime_transaction {
20601 self.buffer.update(cx, |buffer, cx| {
20602 buffer.group_until_transaction(transaction, cx);
20603 });
20604 }
20605
20606 if self.text_highlights::<InputComposition>(cx).is_none() {
20607 self.ime_transaction.take();
20608 }
20609 }
20610
20611 fn bounds_for_range(
20612 &mut self,
20613 range_utf16: Range<usize>,
20614 element_bounds: gpui::Bounds<Pixels>,
20615 window: &mut Window,
20616 cx: &mut Context<Self>,
20617 ) -> Option<gpui::Bounds<Pixels>> {
20618 let text_layout_details = self.text_layout_details(window);
20619 let gpui::Size {
20620 width: em_width,
20621 height: line_height,
20622 } = self.character_size(window);
20623
20624 let snapshot = self.snapshot(window, cx);
20625 let scroll_position = snapshot.scroll_position();
20626 let scroll_left = scroll_position.x * em_width;
20627
20628 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20629 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20630 + self.gutter_dimensions.width
20631 + self.gutter_dimensions.margin;
20632 let y = line_height * (start.row().as_f32() - scroll_position.y);
20633
20634 Some(Bounds {
20635 origin: element_bounds.origin + point(x, y),
20636 size: size(em_width, line_height),
20637 })
20638 }
20639
20640 fn character_index_for_point(
20641 &mut self,
20642 point: gpui::Point<Pixels>,
20643 _window: &mut Window,
20644 _cx: &mut Context<Self>,
20645 ) -> Option<usize> {
20646 let position_map = self.last_position_map.as_ref()?;
20647 if !position_map.text_hitbox.contains(&point) {
20648 return None;
20649 }
20650 let display_point = position_map.point_for_position(point).previous_valid;
20651 let anchor = position_map
20652 .snapshot
20653 .display_point_to_anchor(display_point, Bias::Left);
20654 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20655 Some(utf16_offset.0)
20656 }
20657}
20658
20659trait SelectionExt {
20660 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20661 fn spanned_rows(
20662 &self,
20663 include_end_if_at_line_start: bool,
20664 map: &DisplaySnapshot,
20665 ) -> Range<MultiBufferRow>;
20666}
20667
20668impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20669 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20670 let start = self
20671 .start
20672 .to_point(&map.buffer_snapshot)
20673 .to_display_point(map);
20674 let end = self
20675 .end
20676 .to_point(&map.buffer_snapshot)
20677 .to_display_point(map);
20678 if self.reversed {
20679 end..start
20680 } else {
20681 start..end
20682 }
20683 }
20684
20685 fn spanned_rows(
20686 &self,
20687 include_end_if_at_line_start: bool,
20688 map: &DisplaySnapshot,
20689 ) -> Range<MultiBufferRow> {
20690 let start = self.start.to_point(&map.buffer_snapshot);
20691 let mut end = self.end.to_point(&map.buffer_snapshot);
20692 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20693 end.row -= 1;
20694 }
20695
20696 let buffer_start = map.prev_line_boundary(start).0;
20697 let buffer_end = map.next_line_boundary(end).0;
20698 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20699 }
20700}
20701
20702impl<T: InvalidationRegion> InvalidationStack<T> {
20703 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20704 where
20705 S: Clone + ToOffset,
20706 {
20707 while let Some(region) = self.last() {
20708 let all_selections_inside_invalidation_ranges =
20709 if selections.len() == region.ranges().len() {
20710 selections
20711 .iter()
20712 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20713 .all(|(selection, invalidation_range)| {
20714 let head = selection.head().to_offset(buffer);
20715 invalidation_range.start <= head && invalidation_range.end >= head
20716 })
20717 } else {
20718 false
20719 };
20720
20721 if all_selections_inside_invalidation_ranges {
20722 break;
20723 } else {
20724 self.pop();
20725 }
20726 }
20727 }
20728}
20729
20730impl<T> Default for InvalidationStack<T> {
20731 fn default() -> Self {
20732 Self(Default::default())
20733 }
20734}
20735
20736impl<T> Deref for InvalidationStack<T> {
20737 type Target = Vec<T>;
20738
20739 fn deref(&self) -> &Self::Target {
20740 &self.0
20741 }
20742}
20743
20744impl<T> DerefMut for InvalidationStack<T> {
20745 fn deref_mut(&mut self) -> &mut Self::Target {
20746 &mut self.0
20747 }
20748}
20749
20750impl InvalidationRegion for SnippetState {
20751 fn ranges(&self) -> &[Range<Anchor>] {
20752 &self.ranges[self.active_index]
20753 }
20754}
20755
20756fn inline_completion_edit_text(
20757 current_snapshot: &BufferSnapshot,
20758 edits: &[(Range<Anchor>, String)],
20759 edit_preview: &EditPreview,
20760 include_deletions: bool,
20761 cx: &App,
20762) -> HighlightedText {
20763 let edits = edits
20764 .iter()
20765 .map(|(anchor, text)| {
20766 (
20767 anchor.start.text_anchor..anchor.end.text_anchor,
20768 text.clone(),
20769 )
20770 })
20771 .collect::<Vec<_>>();
20772
20773 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20774}
20775
20776pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20777 match severity {
20778 DiagnosticSeverity::ERROR => colors.error,
20779 DiagnosticSeverity::WARNING => colors.warning,
20780 DiagnosticSeverity::INFORMATION => colors.info,
20781 DiagnosticSeverity::HINT => colors.info,
20782 _ => colors.ignored,
20783 }
20784}
20785
20786pub fn styled_runs_for_code_label<'a>(
20787 label: &'a CodeLabel,
20788 syntax_theme: &'a theme::SyntaxTheme,
20789) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20790 let fade_out = HighlightStyle {
20791 fade_out: Some(0.35),
20792 ..Default::default()
20793 };
20794
20795 let mut prev_end = label.filter_range.end;
20796 label
20797 .runs
20798 .iter()
20799 .enumerate()
20800 .flat_map(move |(ix, (range, highlight_id))| {
20801 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20802 style
20803 } else {
20804 return Default::default();
20805 };
20806 let mut muted_style = style;
20807 muted_style.highlight(fade_out);
20808
20809 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20810 if range.start >= label.filter_range.end {
20811 if range.start > prev_end {
20812 runs.push((prev_end..range.start, fade_out));
20813 }
20814 runs.push((range.clone(), muted_style));
20815 } else if range.end <= label.filter_range.end {
20816 runs.push((range.clone(), style));
20817 } else {
20818 runs.push((range.start..label.filter_range.end, style));
20819 runs.push((label.filter_range.end..range.end, muted_style));
20820 }
20821 prev_end = cmp::max(prev_end, range.end);
20822
20823 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20824 runs.push((prev_end..label.text.len(), fade_out));
20825 }
20826
20827 runs
20828 })
20829}
20830
20831pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20832 let mut prev_index = 0;
20833 let mut prev_codepoint: Option<char> = None;
20834 text.char_indices()
20835 .chain([(text.len(), '\0')])
20836 .filter_map(move |(index, codepoint)| {
20837 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20838 let is_boundary = index == text.len()
20839 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20840 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20841 if is_boundary {
20842 let chunk = &text[prev_index..index];
20843 prev_index = index;
20844 Some(chunk)
20845 } else {
20846 None
20847 }
20848 })
20849}
20850
20851pub trait RangeToAnchorExt: Sized {
20852 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20853
20854 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20855 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20856 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20857 }
20858}
20859
20860impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20861 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20862 let start_offset = self.start.to_offset(snapshot);
20863 let end_offset = self.end.to_offset(snapshot);
20864 if start_offset == end_offset {
20865 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20866 } else {
20867 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20868 }
20869 }
20870}
20871
20872pub trait RowExt {
20873 fn as_f32(&self) -> f32;
20874
20875 fn next_row(&self) -> Self;
20876
20877 fn previous_row(&self) -> Self;
20878
20879 fn minus(&self, other: Self) -> u32;
20880}
20881
20882impl RowExt for DisplayRow {
20883 fn as_f32(&self) -> f32 {
20884 self.0 as f32
20885 }
20886
20887 fn next_row(&self) -> Self {
20888 Self(self.0 + 1)
20889 }
20890
20891 fn previous_row(&self) -> Self {
20892 Self(self.0.saturating_sub(1))
20893 }
20894
20895 fn minus(&self, other: Self) -> u32 {
20896 self.0 - other.0
20897 }
20898}
20899
20900impl RowExt for MultiBufferRow {
20901 fn as_f32(&self) -> f32 {
20902 self.0 as f32
20903 }
20904
20905 fn next_row(&self) -> Self {
20906 Self(self.0 + 1)
20907 }
20908
20909 fn previous_row(&self) -> Self {
20910 Self(self.0.saturating_sub(1))
20911 }
20912
20913 fn minus(&self, other: Self) -> u32 {
20914 self.0 - other.0
20915 }
20916}
20917
20918trait RowRangeExt {
20919 type Row;
20920
20921 fn len(&self) -> usize;
20922
20923 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20924}
20925
20926impl RowRangeExt for Range<MultiBufferRow> {
20927 type Row = MultiBufferRow;
20928
20929 fn len(&self) -> usize {
20930 (self.end.0 - self.start.0) as usize
20931 }
20932
20933 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20934 (self.start.0..self.end.0).map(MultiBufferRow)
20935 }
20936}
20937
20938impl RowRangeExt for Range<DisplayRow> {
20939 type Row = DisplayRow;
20940
20941 fn len(&self) -> usize {
20942 (self.end.0 - self.start.0) as usize
20943 }
20944
20945 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20946 (self.start.0..self.end.0).map(DisplayRow)
20947 }
20948}
20949
20950/// If select range has more than one line, we
20951/// just point the cursor to range.start.
20952fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20953 if range.start.row == range.end.row {
20954 range
20955 } else {
20956 range.start..range.start
20957 }
20958}
20959pub struct KillRing(ClipboardItem);
20960impl Global for KillRing {}
20961
20962const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20963
20964enum BreakpointPromptEditAction {
20965 Log,
20966 Condition,
20967 HitCondition,
20968}
20969
20970struct BreakpointPromptEditor {
20971 pub(crate) prompt: Entity<Editor>,
20972 editor: WeakEntity<Editor>,
20973 breakpoint_anchor: Anchor,
20974 breakpoint: Breakpoint,
20975 edit_action: BreakpointPromptEditAction,
20976 block_ids: HashSet<CustomBlockId>,
20977 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20978 _subscriptions: Vec<Subscription>,
20979}
20980
20981impl BreakpointPromptEditor {
20982 const MAX_LINES: u8 = 4;
20983
20984 fn new(
20985 editor: WeakEntity<Editor>,
20986 breakpoint_anchor: Anchor,
20987 breakpoint: Breakpoint,
20988 edit_action: BreakpointPromptEditAction,
20989 window: &mut Window,
20990 cx: &mut Context<Self>,
20991 ) -> Self {
20992 let base_text = match edit_action {
20993 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20994 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20995 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20996 }
20997 .map(|msg| msg.to_string())
20998 .unwrap_or_default();
20999
21000 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
21001 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
21002
21003 let prompt = cx.new(|cx| {
21004 let mut prompt = Editor::new(
21005 EditorMode::AutoHeight {
21006 max_lines: Self::MAX_LINES as usize,
21007 },
21008 buffer,
21009 None,
21010 window,
21011 cx,
21012 );
21013 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21014 prompt.set_show_cursor_when_unfocused(false, cx);
21015 prompt.set_placeholder_text(
21016 match edit_action {
21017 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21018 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21019 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21020 },
21021 cx,
21022 );
21023
21024 prompt
21025 });
21026
21027 Self {
21028 prompt,
21029 editor,
21030 breakpoint_anchor,
21031 breakpoint,
21032 edit_action,
21033 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21034 block_ids: Default::default(),
21035 _subscriptions: vec![],
21036 }
21037 }
21038
21039 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21040 self.block_ids.extend(block_ids)
21041 }
21042
21043 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21044 if let Some(editor) = self.editor.upgrade() {
21045 let message = self
21046 .prompt
21047 .read(cx)
21048 .buffer
21049 .read(cx)
21050 .as_singleton()
21051 .expect("A multi buffer in breakpoint prompt isn't possible")
21052 .read(cx)
21053 .as_rope()
21054 .to_string();
21055
21056 editor.update(cx, |editor, cx| {
21057 editor.edit_breakpoint_at_anchor(
21058 self.breakpoint_anchor,
21059 self.breakpoint.clone(),
21060 match self.edit_action {
21061 BreakpointPromptEditAction::Log => {
21062 BreakpointEditAction::EditLogMessage(message.into())
21063 }
21064 BreakpointPromptEditAction::Condition => {
21065 BreakpointEditAction::EditCondition(message.into())
21066 }
21067 BreakpointPromptEditAction::HitCondition => {
21068 BreakpointEditAction::EditHitCondition(message.into())
21069 }
21070 },
21071 cx,
21072 );
21073
21074 editor.remove_blocks(self.block_ids.clone(), None, cx);
21075 cx.focus_self(window);
21076 });
21077 }
21078 }
21079
21080 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21081 self.editor
21082 .update(cx, |editor, cx| {
21083 editor.remove_blocks(self.block_ids.clone(), None, cx);
21084 window.focus(&editor.focus_handle);
21085 })
21086 .log_err();
21087 }
21088
21089 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21090 let settings = ThemeSettings::get_global(cx);
21091 let text_style = TextStyle {
21092 color: if self.prompt.read(cx).read_only(cx) {
21093 cx.theme().colors().text_disabled
21094 } else {
21095 cx.theme().colors().text
21096 },
21097 font_family: settings.buffer_font.family.clone(),
21098 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21099 font_size: settings.buffer_font_size(cx).into(),
21100 font_weight: settings.buffer_font.weight,
21101 line_height: relative(settings.buffer_line_height.value()),
21102 ..Default::default()
21103 };
21104 EditorElement::new(
21105 &self.prompt,
21106 EditorStyle {
21107 background: cx.theme().colors().editor_background,
21108 local_player: cx.theme().players().local(),
21109 text: text_style,
21110 ..Default::default()
21111 },
21112 )
21113 }
21114}
21115
21116impl Render for BreakpointPromptEditor {
21117 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21118 let gutter_dimensions = *self.gutter_dimensions.lock();
21119 h_flex()
21120 .key_context("Editor")
21121 .bg(cx.theme().colors().editor_background)
21122 .border_y_1()
21123 .border_color(cx.theme().status().info_border)
21124 .size_full()
21125 .py(window.line_height() / 2.5)
21126 .on_action(cx.listener(Self::confirm))
21127 .on_action(cx.listener(Self::cancel))
21128 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21129 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21130 }
21131}
21132
21133impl Focusable for BreakpointPromptEditor {
21134 fn focus_handle(&self, cx: &App) -> FocusHandle {
21135 self.prompt.focus_handle(cx)
21136 }
21137}
21138
21139fn all_edits_insertions_or_deletions(
21140 edits: &Vec<(Range<Anchor>, String)>,
21141 snapshot: &MultiBufferSnapshot,
21142) -> bool {
21143 let mut all_insertions = true;
21144 let mut all_deletions = true;
21145
21146 for (range, new_text) in edits.iter() {
21147 let range_is_empty = range.to_offset(&snapshot).is_empty();
21148 let text_is_empty = new_text.is_empty();
21149
21150 if range_is_empty != text_is_empty {
21151 if range_is_empty {
21152 all_deletions = false;
21153 } else {
21154 all_insertions = false;
21155 }
21156 } else {
21157 return false;
21158 }
21159
21160 if !all_insertions && !all_deletions {
21161 return false;
21162 }
21163 }
21164 all_insertions || all_deletions
21165}
21166
21167struct MissingEditPredictionKeybindingTooltip;
21168
21169impl Render for MissingEditPredictionKeybindingTooltip {
21170 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21171 ui::tooltip_container(window, cx, |container, _, cx| {
21172 container
21173 .flex_shrink_0()
21174 .max_w_80()
21175 .min_h(rems_from_px(124.))
21176 .justify_between()
21177 .child(
21178 v_flex()
21179 .flex_1()
21180 .text_ui_sm(cx)
21181 .child(Label::new("Conflict with Accept Keybinding"))
21182 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21183 )
21184 .child(
21185 h_flex()
21186 .pb_1()
21187 .gap_1()
21188 .items_end()
21189 .w_full()
21190 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21191 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21192 }))
21193 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21194 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21195 })),
21196 )
21197 })
21198 }
21199}
21200
21201#[derive(Debug, Clone, Copy, PartialEq)]
21202pub struct LineHighlight {
21203 pub background: Background,
21204 pub border: Option<gpui::Hsla>,
21205 pub include_gutter: bool,
21206 pub type_id: Option<TypeId>,
21207}
21208
21209fn render_diff_hunk_controls(
21210 row: u32,
21211 status: &DiffHunkStatus,
21212 hunk_range: Range<Anchor>,
21213 is_created_file: bool,
21214 line_height: Pixels,
21215 editor: &Entity<Editor>,
21216 _window: &mut Window,
21217 cx: &mut App,
21218) -> AnyElement {
21219 h_flex()
21220 .h(line_height)
21221 .mr_1()
21222 .gap_1()
21223 .px_0p5()
21224 .pb_1()
21225 .border_x_1()
21226 .border_b_1()
21227 .border_color(cx.theme().colors().border_variant)
21228 .rounded_b_lg()
21229 .bg(cx.theme().colors().editor_background)
21230 .gap_1()
21231 .occlude()
21232 .shadow_md()
21233 .child(if status.has_secondary_hunk() {
21234 Button::new(("stage", row as u64), "Stage")
21235 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21236 .tooltip({
21237 let focus_handle = editor.focus_handle(cx);
21238 move |window, cx| {
21239 Tooltip::for_action_in(
21240 "Stage Hunk",
21241 &::git::ToggleStaged,
21242 &focus_handle,
21243 window,
21244 cx,
21245 )
21246 }
21247 })
21248 .on_click({
21249 let editor = editor.clone();
21250 move |_event, _window, cx| {
21251 editor.update(cx, |editor, cx| {
21252 editor.stage_or_unstage_diff_hunks(
21253 true,
21254 vec![hunk_range.start..hunk_range.start],
21255 cx,
21256 );
21257 });
21258 }
21259 })
21260 } else {
21261 Button::new(("unstage", row as u64), "Unstage")
21262 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21263 .tooltip({
21264 let focus_handle = editor.focus_handle(cx);
21265 move |window, cx| {
21266 Tooltip::for_action_in(
21267 "Unstage Hunk",
21268 &::git::ToggleStaged,
21269 &focus_handle,
21270 window,
21271 cx,
21272 )
21273 }
21274 })
21275 .on_click({
21276 let editor = editor.clone();
21277 move |_event, _window, cx| {
21278 editor.update(cx, |editor, cx| {
21279 editor.stage_or_unstage_diff_hunks(
21280 false,
21281 vec![hunk_range.start..hunk_range.start],
21282 cx,
21283 );
21284 });
21285 }
21286 })
21287 })
21288 .child(
21289 Button::new(("restore", row as u64), "Restore")
21290 .tooltip({
21291 let focus_handle = editor.focus_handle(cx);
21292 move |window, cx| {
21293 Tooltip::for_action_in(
21294 "Restore Hunk",
21295 &::git::Restore,
21296 &focus_handle,
21297 window,
21298 cx,
21299 )
21300 }
21301 })
21302 .on_click({
21303 let editor = editor.clone();
21304 move |_event, window, cx| {
21305 editor.update(cx, |editor, cx| {
21306 let snapshot = editor.snapshot(window, cx);
21307 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21308 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21309 });
21310 }
21311 })
21312 .disabled(is_created_file),
21313 )
21314 .when(
21315 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21316 |el| {
21317 el.child(
21318 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21319 .shape(IconButtonShape::Square)
21320 .icon_size(IconSize::Small)
21321 // .disabled(!has_multiple_hunks)
21322 .tooltip({
21323 let focus_handle = editor.focus_handle(cx);
21324 move |window, cx| {
21325 Tooltip::for_action_in(
21326 "Next Hunk",
21327 &GoToHunk,
21328 &focus_handle,
21329 window,
21330 cx,
21331 )
21332 }
21333 })
21334 .on_click({
21335 let editor = editor.clone();
21336 move |_event, window, cx| {
21337 editor.update(cx, |editor, cx| {
21338 let snapshot = editor.snapshot(window, cx);
21339 let position =
21340 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21341 editor.go_to_hunk_before_or_after_position(
21342 &snapshot,
21343 position,
21344 Direction::Next,
21345 window,
21346 cx,
21347 );
21348 editor.expand_selected_diff_hunks(cx);
21349 });
21350 }
21351 }),
21352 )
21353 .child(
21354 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21355 .shape(IconButtonShape::Square)
21356 .icon_size(IconSize::Small)
21357 // .disabled(!has_multiple_hunks)
21358 .tooltip({
21359 let focus_handle = editor.focus_handle(cx);
21360 move |window, cx| {
21361 Tooltip::for_action_in(
21362 "Previous Hunk",
21363 &GoToPreviousHunk,
21364 &focus_handle,
21365 window,
21366 cx,
21367 )
21368 }
21369 })
21370 .on_click({
21371 let editor = editor.clone();
21372 move |_event, window, cx| {
21373 editor.update(cx, |editor, cx| {
21374 let snapshot = editor.snapshot(window, cx);
21375 let point =
21376 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21377 editor.go_to_hunk_before_or_after_position(
21378 &snapshot,
21379 point,
21380 Direction::Prev,
21381 window,
21382 cx,
21383 );
21384 editor.expand_selected_diff_hunks(cx);
21385 });
21386 }
21387 }),
21388 )
21389 },
21390 )
21391 .into_any_element()
21392}