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 let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
2956
2957 self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
2958 s.set_pending(pending_selection, pending_mode)
2959 });
2960 }
2961
2962 fn begin_selection(
2963 &mut self,
2964 position: DisplayPoint,
2965 add: bool,
2966 click_count: usize,
2967 window: &mut Window,
2968 cx: &mut Context<Self>,
2969 ) {
2970 if !self.focus_handle.is_focused(window) {
2971 self.last_focused_descendant = None;
2972 window.focus(&self.focus_handle);
2973 }
2974
2975 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2976 let buffer = &display_map.buffer_snapshot;
2977 let position = display_map.clip_point(position, Bias::Left);
2978
2979 let start;
2980 let end;
2981 let mode;
2982 let mut auto_scroll;
2983 match click_count {
2984 1 => {
2985 start = buffer.anchor_before(position.to_point(&display_map));
2986 end = start;
2987 mode = SelectMode::Character;
2988 auto_scroll = true;
2989 }
2990 2 => {
2991 let range = movement::surrounding_word(&display_map, position);
2992 start = buffer.anchor_before(range.start.to_point(&display_map));
2993 end = buffer.anchor_before(range.end.to_point(&display_map));
2994 mode = SelectMode::Word(start..end);
2995 auto_scroll = true;
2996 }
2997 3 => {
2998 let position = display_map
2999 .clip_point(position, Bias::Left)
3000 .to_point(&display_map);
3001 let line_start = display_map.prev_line_boundary(position).0;
3002 let next_line_start = buffer.clip_point(
3003 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3004 Bias::Left,
3005 );
3006 start = buffer.anchor_before(line_start);
3007 end = buffer.anchor_before(next_line_start);
3008 mode = SelectMode::Line(start..end);
3009 auto_scroll = true;
3010 }
3011 _ => {
3012 start = buffer.anchor_before(0);
3013 end = buffer.anchor_before(buffer.len());
3014 mode = SelectMode::All;
3015 auto_scroll = false;
3016 }
3017 }
3018 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3019
3020 let point_to_delete: Option<usize> = {
3021 let selected_points: Vec<Selection<Point>> =
3022 self.selections.disjoint_in_range(start..end, cx);
3023
3024 if !add || click_count > 1 {
3025 None
3026 } else if !selected_points.is_empty() {
3027 Some(selected_points[0].id)
3028 } else {
3029 let clicked_point_already_selected =
3030 self.selections.disjoint.iter().find(|selection| {
3031 selection.start.to_point(buffer) == start.to_point(buffer)
3032 || selection.end.to_point(buffer) == end.to_point(buffer)
3033 });
3034
3035 clicked_point_already_selected.map(|selection| selection.id)
3036 }
3037 };
3038
3039 let selections_count = self.selections.count();
3040
3041 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3042 if let Some(point_to_delete) = point_to_delete {
3043 s.delete(point_to_delete);
3044
3045 if selections_count == 1 {
3046 s.set_pending_anchor_range(start..end, mode);
3047 }
3048 } else {
3049 if !add {
3050 s.clear_disjoint();
3051 }
3052
3053 s.set_pending_anchor_range(start..end, mode);
3054 }
3055 });
3056 }
3057
3058 fn begin_columnar_selection(
3059 &mut self,
3060 position: DisplayPoint,
3061 goal_column: u32,
3062 reset: bool,
3063 window: &mut Window,
3064 cx: &mut Context<Self>,
3065 ) {
3066 if !self.focus_handle.is_focused(window) {
3067 self.last_focused_descendant = None;
3068 window.focus(&self.focus_handle);
3069 }
3070
3071 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3072
3073 if reset {
3074 let pointer_position = display_map
3075 .buffer_snapshot
3076 .anchor_before(position.to_point(&display_map));
3077
3078 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3079 s.clear_disjoint();
3080 s.set_pending_anchor_range(
3081 pointer_position..pointer_position,
3082 SelectMode::Character,
3083 );
3084 });
3085 }
3086
3087 let tail = self.selections.newest::<Point>(cx).tail();
3088 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3089
3090 if !reset {
3091 self.select_columns(
3092 tail.to_display_point(&display_map),
3093 position,
3094 goal_column,
3095 &display_map,
3096 window,
3097 cx,
3098 );
3099 }
3100 }
3101
3102 fn update_selection(
3103 &mut self,
3104 position: DisplayPoint,
3105 goal_column: u32,
3106 scroll_delta: gpui::Point<f32>,
3107 window: &mut Window,
3108 cx: &mut Context<Self>,
3109 ) {
3110 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3111
3112 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3113 let tail = tail.to_display_point(&display_map);
3114 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3115 } else if let Some(mut pending) = self.selections.pending_anchor() {
3116 let buffer = self.buffer.read(cx).snapshot(cx);
3117 let head;
3118 let tail;
3119 let mode = self.selections.pending_mode().unwrap();
3120 match &mode {
3121 SelectMode::Character => {
3122 head = position.to_point(&display_map);
3123 tail = pending.tail().to_point(&buffer);
3124 }
3125 SelectMode::Word(original_range) => {
3126 let original_display_range = original_range.start.to_display_point(&display_map)
3127 ..original_range.end.to_display_point(&display_map);
3128 let original_buffer_range = original_display_range.start.to_point(&display_map)
3129 ..original_display_range.end.to_point(&display_map);
3130 if movement::is_inside_word(&display_map, position)
3131 || original_display_range.contains(&position)
3132 {
3133 let word_range = movement::surrounding_word(&display_map, position);
3134 if word_range.start < original_display_range.start {
3135 head = word_range.start.to_point(&display_map);
3136 } else {
3137 head = word_range.end.to_point(&display_map);
3138 }
3139 } else {
3140 head = position.to_point(&display_map);
3141 }
3142
3143 if head <= original_buffer_range.start {
3144 tail = original_buffer_range.end;
3145 } else {
3146 tail = original_buffer_range.start;
3147 }
3148 }
3149 SelectMode::Line(original_range) => {
3150 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3151
3152 let position = display_map
3153 .clip_point(position, Bias::Left)
3154 .to_point(&display_map);
3155 let line_start = display_map.prev_line_boundary(position).0;
3156 let next_line_start = buffer.clip_point(
3157 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3158 Bias::Left,
3159 );
3160
3161 if line_start < original_range.start {
3162 head = line_start
3163 } else {
3164 head = next_line_start
3165 }
3166
3167 if head <= original_range.start {
3168 tail = original_range.end;
3169 } else {
3170 tail = original_range.start;
3171 }
3172 }
3173 SelectMode::All => {
3174 return;
3175 }
3176 };
3177
3178 if head < tail {
3179 pending.start = buffer.anchor_before(head);
3180 pending.end = buffer.anchor_before(tail);
3181 pending.reversed = true;
3182 } else {
3183 pending.start = buffer.anchor_before(tail);
3184 pending.end = buffer.anchor_before(head);
3185 pending.reversed = false;
3186 }
3187
3188 self.change_selections(None, window, cx, |s| {
3189 s.set_pending(pending, mode);
3190 });
3191 } else {
3192 log::error!("update_selection dispatched with no pending selection");
3193 return;
3194 }
3195
3196 self.apply_scroll_delta(scroll_delta, window, cx);
3197 cx.notify();
3198 }
3199
3200 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3201 self.columnar_selection_tail.take();
3202 if self.selections.pending_anchor().is_some() {
3203 let selections = self.selections.all::<usize>(cx);
3204 self.change_selections(None, window, cx, |s| {
3205 s.select(selections);
3206 s.clear_pending();
3207 });
3208 }
3209 }
3210
3211 fn select_columns(
3212 &mut self,
3213 tail: DisplayPoint,
3214 head: DisplayPoint,
3215 goal_column: u32,
3216 display_map: &DisplaySnapshot,
3217 window: &mut Window,
3218 cx: &mut Context<Self>,
3219 ) {
3220 let start_row = cmp::min(tail.row(), head.row());
3221 let end_row = cmp::max(tail.row(), head.row());
3222 let start_column = cmp::min(tail.column(), goal_column);
3223 let end_column = cmp::max(tail.column(), goal_column);
3224 let reversed = start_column < tail.column();
3225
3226 let selection_ranges = (start_row.0..=end_row.0)
3227 .map(DisplayRow)
3228 .filter_map(|row| {
3229 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3230 let start = display_map
3231 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3232 .to_point(display_map);
3233 let end = display_map
3234 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3235 .to_point(display_map);
3236 if reversed {
3237 Some(end..start)
3238 } else {
3239 Some(start..end)
3240 }
3241 } else {
3242 None
3243 }
3244 })
3245 .collect::<Vec<_>>();
3246
3247 self.change_selections(None, window, cx, |s| {
3248 s.select_ranges(selection_ranges);
3249 });
3250 cx.notify();
3251 }
3252
3253 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3254 self.selections
3255 .all_adjusted(cx)
3256 .iter()
3257 .any(|selection| !selection.is_empty())
3258 }
3259
3260 pub fn has_pending_nonempty_selection(&self) -> bool {
3261 let pending_nonempty_selection = match self.selections.pending_anchor() {
3262 Some(Selection { start, end, .. }) => start != end,
3263 None => false,
3264 };
3265
3266 pending_nonempty_selection
3267 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3268 }
3269
3270 pub fn has_pending_selection(&self) -> bool {
3271 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3272 }
3273
3274 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3275 self.selection_mark_mode = false;
3276
3277 if self.clear_expanded_diff_hunks(cx) {
3278 cx.notify();
3279 return;
3280 }
3281 if self.dismiss_menus_and_popups(true, window, cx) {
3282 return;
3283 }
3284
3285 if self.mode.is_full()
3286 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3287 {
3288 return;
3289 }
3290
3291 cx.propagate();
3292 }
3293
3294 pub fn dismiss_menus_and_popups(
3295 &mut self,
3296 is_user_requested: bool,
3297 window: &mut Window,
3298 cx: &mut Context<Self>,
3299 ) -> bool {
3300 if self.take_rename(false, window, cx).is_some() {
3301 return true;
3302 }
3303
3304 if hide_hover(self, cx) {
3305 return true;
3306 }
3307
3308 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3309 return true;
3310 }
3311
3312 if self.hide_context_menu(window, cx).is_some() {
3313 return true;
3314 }
3315
3316 if self.mouse_context_menu.take().is_some() {
3317 return true;
3318 }
3319
3320 if is_user_requested && self.discard_inline_completion(true, cx) {
3321 return true;
3322 }
3323
3324 if self.snippet_stack.pop().is_some() {
3325 return true;
3326 }
3327
3328 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3329 self.dismiss_diagnostics(cx);
3330 return true;
3331 }
3332
3333 false
3334 }
3335
3336 fn linked_editing_ranges_for(
3337 &self,
3338 selection: Range<text::Anchor>,
3339 cx: &App,
3340 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3341 if self.linked_edit_ranges.is_empty() {
3342 return None;
3343 }
3344 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3345 selection.end.buffer_id.and_then(|end_buffer_id| {
3346 if selection.start.buffer_id != Some(end_buffer_id) {
3347 return None;
3348 }
3349 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3350 let snapshot = buffer.read(cx).snapshot();
3351 self.linked_edit_ranges
3352 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3353 .map(|ranges| (ranges, snapshot, buffer))
3354 })?;
3355 use text::ToOffset as TO;
3356 // find offset from the start of current range to current cursor position
3357 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3358
3359 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3360 let start_difference = start_offset - start_byte_offset;
3361 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3362 let end_difference = end_offset - start_byte_offset;
3363 // Current range has associated linked ranges.
3364 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3365 for range in linked_ranges.iter() {
3366 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3367 let end_offset = start_offset + end_difference;
3368 let start_offset = start_offset + start_difference;
3369 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3370 continue;
3371 }
3372 if self.selections.disjoint_anchor_ranges().any(|s| {
3373 if s.start.buffer_id != selection.start.buffer_id
3374 || s.end.buffer_id != selection.end.buffer_id
3375 {
3376 return false;
3377 }
3378 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3379 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3380 }) {
3381 continue;
3382 }
3383 let start = buffer_snapshot.anchor_after(start_offset);
3384 let end = buffer_snapshot.anchor_after(end_offset);
3385 linked_edits
3386 .entry(buffer.clone())
3387 .or_default()
3388 .push(start..end);
3389 }
3390 Some(linked_edits)
3391 }
3392
3393 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3394 let text: Arc<str> = text.into();
3395
3396 if self.read_only(cx) {
3397 return;
3398 }
3399
3400 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3401
3402 let selections = self.selections.all_adjusted(cx);
3403 let mut bracket_inserted = false;
3404 let mut edits = Vec::new();
3405 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3406 let mut new_selections = Vec::with_capacity(selections.len());
3407 let mut new_autoclose_regions = Vec::new();
3408 let snapshot = self.buffer.read(cx).read(cx);
3409 let mut clear_linked_edit_ranges = false;
3410
3411 for (selection, autoclose_region) in
3412 self.selections_with_autoclose_regions(selections, &snapshot)
3413 {
3414 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3415 // Determine if the inserted text matches the opening or closing
3416 // bracket of any of this language's bracket pairs.
3417 let mut bracket_pair = None;
3418 let mut is_bracket_pair_start = false;
3419 let mut is_bracket_pair_end = false;
3420 if !text.is_empty() {
3421 let mut bracket_pair_matching_end = None;
3422 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3423 // and they are removing the character that triggered IME popup.
3424 for (pair, enabled) in scope.brackets() {
3425 if !pair.close && !pair.surround {
3426 continue;
3427 }
3428
3429 if enabled && pair.start.ends_with(text.as_ref()) {
3430 let prefix_len = pair.start.len() - text.len();
3431 let preceding_text_matches_prefix = prefix_len == 0
3432 || (selection.start.column >= (prefix_len as u32)
3433 && snapshot.contains_str_at(
3434 Point::new(
3435 selection.start.row,
3436 selection.start.column - (prefix_len as u32),
3437 ),
3438 &pair.start[..prefix_len],
3439 ));
3440 if preceding_text_matches_prefix {
3441 bracket_pair = Some(pair.clone());
3442 is_bracket_pair_start = true;
3443 break;
3444 }
3445 }
3446 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3447 {
3448 // take first bracket pair matching end, but don't break in case a later bracket
3449 // pair matches start
3450 bracket_pair_matching_end = Some(pair.clone());
3451 }
3452 }
3453 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3454 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3455 is_bracket_pair_end = true;
3456 }
3457 }
3458
3459 if let Some(bracket_pair) = bracket_pair {
3460 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3461 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3462 let auto_surround =
3463 self.use_auto_surround && snapshot_settings.use_auto_surround;
3464 if selection.is_empty() {
3465 if is_bracket_pair_start {
3466 // If the inserted text is a suffix of an opening bracket and the
3467 // selection is preceded by the rest of the opening bracket, then
3468 // insert the closing bracket.
3469 let following_text_allows_autoclose = snapshot
3470 .chars_at(selection.start)
3471 .next()
3472 .map_or(true, |c| scope.should_autoclose_before(c));
3473
3474 let preceding_text_allows_autoclose = selection.start.column == 0
3475 || snapshot.reversed_chars_at(selection.start).next().map_or(
3476 true,
3477 |c| {
3478 bracket_pair.start != bracket_pair.end
3479 || !snapshot
3480 .char_classifier_at(selection.start)
3481 .is_word(c)
3482 },
3483 );
3484
3485 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3486 && bracket_pair.start.len() == 1
3487 {
3488 let target = bracket_pair.start.chars().next().unwrap();
3489 let current_line_count = snapshot
3490 .reversed_chars_at(selection.start)
3491 .take_while(|&c| c != '\n')
3492 .filter(|&c| c == target)
3493 .count();
3494 current_line_count % 2 == 1
3495 } else {
3496 false
3497 };
3498
3499 if autoclose
3500 && bracket_pair.close
3501 && following_text_allows_autoclose
3502 && preceding_text_allows_autoclose
3503 && !is_closing_quote
3504 {
3505 let anchor = snapshot.anchor_before(selection.end);
3506 new_selections.push((selection.map(|_| anchor), text.len()));
3507 new_autoclose_regions.push((
3508 anchor,
3509 text.len(),
3510 selection.id,
3511 bracket_pair.clone(),
3512 ));
3513 edits.push((
3514 selection.range(),
3515 format!("{}{}", text, bracket_pair.end).into(),
3516 ));
3517 bracket_inserted = true;
3518 continue;
3519 }
3520 }
3521
3522 if let Some(region) = autoclose_region {
3523 // If the selection is followed by an auto-inserted closing bracket,
3524 // then don't insert that closing bracket again; just move the selection
3525 // past the closing bracket.
3526 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3527 && text.as_ref() == region.pair.end.as_str();
3528 if should_skip {
3529 let anchor = snapshot.anchor_after(selection.end);
3530 new_selections
3531 .push((selection.map(|_| anchor), region.pair.end.len()));
3532 continue;
3533 }
3534 }
3535
3536 let always_treat_brackets_as_autoclosed = snapshot
3537 .language_settings_at(selection.start, cx)
3538 .always_treat_brackets_as_autoclosed;
3539 if always_treat_brackets_as_autoclosed
3540 && is_bracket_pair_end
3541 && snapshot.contains_str_at(selection.end, text.as_ref())
3542 {
3543 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3544 // and the inserted text is a closing bracket and the selection is followed
3545 // by the closing bracket then move the selection past the closing bracket.
3546 let anchor = snapshot.anchor_after(selection.end);
3547 new_selections.push((selection.map(|_| anchor), text.len()));
3548 continue;
3549 }
3550 }
3551 // If an opening bracket is 1 character long and is typed while
3552 // text is selected, then surround that text with the bracket pair.
3553 else if auto_surround
3554 && bracket_pair.surround
3555 && is_bracket_pair_start
3556 && bracket_pair.start.chars().count() == 1
3557 {
3558 edits.push((selection.start..selection.start, text.clone()));
3559 edits.push((
3560 selection.end..selection.end,
3561 bracket_pair.end.as_str().into(),
3562 ));
3563 bracket_inserted = true;
3564 new_selections.push((
3565 Selection {
3566 id: selection.id,
3567 start: snapshot.anchor_after(selection.start),
3568 end: snapshot.anchor_before(selection.end),
3569 reversed: selection.reversed,
3570 goal: selection.goal,
3571 },
3572 0,
3573 ));
3574 continue;
3575 }
3576 }
3577 }
3578
3579 if self.auto_replace_emoji_shortcode
3580 && selection.is_empty()
3581 && text.as_ref().ends_with(':')
3582 {
3583 if let Some(possible_emoji_short_code) =
3584 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3585 {
3586 if !possible_emoji_short_code.is_empty() {
3587 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3588 let emoji_shortcode_start = Point::new(
3589 selection.start.row,
3590 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3591 );
3592
3593 // Remove shortcode from buffer
3594 edits.push((
3595 emoji_shortcode_start..selection.start,
3596 "".to_string().into(),
3597 ));
3598 new_selections.push((
3599 Selection {
3600 id: selection.id,
3601 start: snapshot.anchor_after(emoji_shortcode_start),
3602 end: snapshot.anchor_before(selection.start),
3603 reversed: selection.reversed,
3604 goal: selection.goal,
3605 },
3606 0,
3607 ));
3608
3609 // Insert emoji
3610 let selection_start_anchor = snapshot.anchor_after(selection.start);
3611 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3612 edits.push((selection.start..selection.end, emoji.to_string().into()));
3613
3614 continue;
3615 }
3616 }
3617 }
3618 }
3619
3620 // If not handling any auto-close operation, then just replace the selected
3621 // text with the given input and move the selection to the end of the
3622 // newly inserted text.
3623 let anchor = snapshot.anchor_after(selection.end);
3624 if !self.linked_edit_ranges.is_empty() {
3625 let start_anchor = snapshot.anchor_before(selection.start);
3626
3627 let is_word_char = text.chars().next().map_or(true, |char| {
3628 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3629 classifier.is_word(char)
3630 });
3631
3632 if is_word_char {
3633 if let Some(ranges) = self
3634 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3635 {
3636 for (buffer, edits) in ranges {
3637 linked_edits
3638 .entry(buffer.clone())
3639 .or_default()
3640 .extend(edits.into_iter().map(|range| (range, text.clone())));
3641 }
3642 }
3643 } else {
3644 clear_linked_edit_ranges = true;
3645 }
3646 }
3647
3648 new_selections.push((selection.map(|_| anchor), 0));
3649 edits.push((selection.start..selection.end, text.clone()));
3650 }
3651
3652 drop(snapshot);
3653
3654 self.transact(window, cx, |this, window, cx| {
3655 if clear_linked_edit_ranges {
3656 this.linked_edit_ranges.clear();
3657 }
3658 let initial_buffer_versions =
3659 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3660
3661 this.buffer.update(cx, |buffer, cx| {
3662 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3663 });
3664 for (buffer, edits) in linked_edits {
3665 buffer.update(cx, |buffer, cx| {
3666 let snapshot = buffer.snapshot();
3667 let edits = edits
3668 .into_iter()
3669 .map(|(range, text)| {
3670 use text::ToPoint as TP;
3671 let end_point = TP::to_point(&range.end, &snapshot);
3672 let start_point = TP::to_point(&range.start, &snapshot);
3673 (start_point..end_point, text)
3674 })
3675 .sorted_by_key(|(range, _)| range.start);
3676 buffer.edit(edits, None, cx);
3677 })
3678 }
3679 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3680 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3681 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3682 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3683 .zip(new_selection_deltas)
3684 .map(|(selection, delta)| Selection {
3685 id: selection.id,
3686 start: selection.start + delta,
3687 end: selection.end + delta,
3688 reversed: selection.reversed,
3689 goal: SelectionGoal::None,
3690 })
3691 .collect::<Vec<_>>();
3692
3693 let mut i = 0;
3694 for (position, delta, selection_id, pair) in new_autoclose_regions {
3695 let position = position.to_offset(&map.buffer_snapshot) + delta;
3696 let start = map.buffer_snapshot.anchor_before(position);
3697 let end = map.buffer_snapshot.anchor_after(position);
3698 while let Some(existing_state) = this.autoclose_regions.get(i) {
3699 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3700 Ordering::Less => i += 1,
3701 Ordering::Greater => break,
3702 Ordering::Equal => {
3703 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3704 Ordering::Less => i += 1,
3705 Ordering::Equal => break,
3706 Ordering::Greater => break,
3707 }
3708 }
3709 }
3710 }
3711 this.autoclose_regions.insert(
3712 i,
3713 AutocloseRegion {
3714 selection_id,
3715 range: start..end,
3716 pair,
3717 },
3718 );
3719 }
3720
3721 let had_active_inline_completion = this.has_active_inline_completion();
3722 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3723 s.select(new_selections)
3724 });
3725
3726 if !bracket_inserted {
3727 if let Some(on_type_format_task) =
3728 this.trigger_on_type_formatting(text.to_string(), window, cx)
3729 {
3730 on_type_format_task.detach_and_log_err(cx);
3731 }
3732 }
3733
3734 let editor_settings = EditorSettings::get_global(cx);
3735 if bracket_inserted
3736 && (editor_settings.auto_signature_help
3737 || editor_settings.show_signature_help_after_edits)
3738 {
3739 this.show_signature_help(&ShowSignatureHelp, window, cx);
3740 }
3741
3742 let trigger_in_words =
3743 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3744 if this.hard_wrap.is_some() {
3745 let latest: Range<Point> = this.selections.newest(cx).range();
3746 if latest.is_empty()
3747 && this
3748 .buffer()
3749 .read(cx)
3750 .snapshot(cx)
3751 .line_len(MultiBufferRow(latest.start.row))
3752 == latest.start.column
3753 {
3754 this.rewrap_impl(
3755 RewrapOptions {
3756 override_language_settings: true,
3757 preserve_existing_whitespace: true,
3758 },
3759 cx,
3760 )
3761 }
3762 }
3763 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3764 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3765 this.refresh_inline_completion(true, false, window, cx);
3766 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3767 });
3768 }
3769
3770 fn find_possible_emoji_shortcode_at_position(
3771 snapshot: &MultiBufferSnapshot,
3772 position: Point,
3773 ) -> Option<String> {
3774 let mut chars = Vec::new();
3775 let mut found_colon = false;
3776 for char in snapshot.reversed_chars_at(position).take(100) {
3777 // Found a possible emoji shortcode in the middle of the buffer
3778 if found_colon {
3779 if char.is_whitespace() {
3780 chars.reverse();
3781 return Some(chars.iter().collect());
3782 }
3783 // If the previous character is not a whitespace, we are in the middle of a word
3784 // and we only want to complete the shortcode if the word is made up of other emojis
3785 let mut containing_word = String::new();
3786 for ch in snapshot
3787 .reversed_chars_at(position)
3788 .skip(chars.len() + 1)
3789 .take(100)
3790 {
3791 if ch.is_whitespace() {
3792 break;
3793 }
3794 containing_word.push(ch);
3795 }
3796 let containing_word = containing_word.chars().rev().collect::<String>();
3797 if util::word_consists_of_emojis(containing_word.as_str()) {
3798 chars.reverse();
3799 return Some(chars.iter().collect());
3800 }
3801 }
3802
3803 if char.is_whitespace() || !char.is_ascii() {
3804 return None;
3805 }
3806 if char == ':' {
3807 found_colon = true;
3808 } else {
3809 chars.push(char);
3810 }
3811 }
3812 // Found a possible emoji shortcode at the beginning of the buffer
3813 chars.reverse();
3814 Some(chars.iter().collect())
3815 }
3816
3817 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3818 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3819 self.transact(window, cx, |this, window, cx| {
3820 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3821 let selections = this.selections.all::<usize>(cx);
3822 let multi_buffer = this.buffer.read(cx);
3823 let buffer = multi_buffer.snapshot(cx);
3824 selections
3825 .iter()
3826 .map(|selection| {
3827 let start_point = selection.start.to_point(&buffer);
3828 let mut indent =
3829 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3830 indent.len = cmp::min(indent.len, start_point.column);
3831 let start = selection.start;
3832 let end = selection.end;
3833 let selection_is_empty = start == end;
3834 let language_scope = buffer.language_scope_at(start);
3835 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3836 &language_scope
3837 {
3838 let insert_extra_newline =
3839 insert_extra_newline_brackets(&buffer, start..end, language)
3840 || insert_extra_newline_tree_sitter(&buffer, start..end);
3841
3842 // Comment extension on newline is allowed only for cursor selections
3843 let comment_delimiter = maybe!({
3844 if !selection_is_empty {
3845 return None;
3846 }
3847
3848 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3849 return None;
3850 }
3851
3852 let delimiters = language.line_comment_prefixes();
3853 let max_len_of_delimiter =
3854 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3855 let (snapshot, range) =
3856 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3857
3858 let mut index_of_first_non_whitespace = 0;
3859 let comment_candidate = snapshot
3860 .chars_for_range(range)
3861 .skip_while(|c| {
3862 let should_skip = c.is_whitespace();
3863 if should_skip {
3864 index_of_first_non_whitespace += 1;
3865 }
3866 should_skip
3867 })
3868 .take(max_len_of_delimiter)
3869 .collect::<String>();
3870 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3871 comment_candidate.starts_with(comment_prefix.as_ref())
3872 })?;
3873 let cursor_is_placed_after_comment_marker =
3874 index_of_first_non_whitespace + comment_prefix.len()
3875 <= start_point.column as usize;
3876 if cursor_is_placed_after_comment_marker {
3877 Some(comment_prefix.clone())
3878 } else {
3879 None
3880 }
3881 });
3882 (comment_delimiter, insert_extra_newline)
3883 } else {
3884 (None, false)
3885 };
3886
3887 let capacity_for_delimiter = comment_delimiter
3888 .as_deref()
3889 .map(str::len)
3890 .unwrap_or_default();
3891 let mut new_text =
3892 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3893 new_text.push('\n');
3894 new_text.extend(indent.chars());
3895 if let Some(delimiter) = &comment_delimiter {
3896 new_text.push_str(delimiter);
3897 }
3898 if insert_extra_newline {
3899 new_text = new_text.repeat(2);
3900 }
3901
3902 let anchor = buffer.anchor_after(end);
3903 let new_selection = selection.map(|_| anchor);
3904 (
3905 (start..end, new_text),
3906 (insert_extra_newline, new_selection),
3907 )
3908 })
3909 .unzip()
3910 };
3911
3912 this.edit_with_autoindent(edits, cx);
3913 let buffer = this.buffer.read(cx).snapshot(cx);
3914 let new_selections = selection_fixup_info
3915 .into_iter()
3916 .map(|(extra_newline_inserted, new_selection)| {
3917 let mut cursor = new_selection.end.to_point(&buffer);
3918 if extra_newline_inserted {
3919 cursor.row -= 1;
3920 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3921 }
3922 new_selection.map(|_| cursor)
3923 })
3924 .collect();
3925
3926 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3927 s.select(new_selections)
3928 });
3929 this.refresh_inline_completion(true, false, window, cx);
3930 });
3931 }
3932
3933 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3934 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3935
3936 let buffer = self.buffer.read(cx);
3937 let snapshot = buffer.snapshot(cx);
3938
3939 let mut edits = Vec::new();
3940 let mut rows = Vec::new();
3941
3942 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3943 let cursor = selection.head();
3944 let row = cursor.row;
3945
3946 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3947
3948 let newline = "\n".to_string();
3949 edits.push((start_of_line..start_of_line, newline));
3950
3951 rows.push(row + rows_inserted as u32);
3952 }
3953
3954 self.transact(window, cx, |editor, window, cx| {
3955 editor.edit(edits, cx);
3956
3957 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3958 let mut index = 0;
3959 s.move_cursors_with(|map, _, _| {
3960 let row = rows[index];
3961 index += 1;
3962
3963 let point = Point::new(row, 0);
3964 let boundary = map.next_line_boundary(point).1;
3965 let clipped = map.clip_point(boundary, Bias::Left);
3966
3967 (clipped, SelectionGoal::None)
3968 });
3969 });
3970
3971 let mut indent_edits = Vec::new();
3972 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3973 for row in rows {
3974 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3975 for (row, indent) in indents {
3976 if indent.len == 0 {
3977 continue;
3978 }
3979
3980 let text = match indent.kind {
3981 IndentKind::Space => " ".repeat(indent.len as usize),
3982 IndentKind::Tab => "\t".repeat(indent.len as usize),
3983 };
3984 let point = Point::new(row.0, 0);
3985 indent_edits.push((point..point, text));
3986 }
3987 }
3988 editor.edit(indent_edits, cx);
3989 });
3990 }
3991
3992 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3993 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3994
3995 let buffer = self.buffer.read(cx);
3996 let snapshot = buffer.snapshot(cx);
3997
3998 let mut edits = Vec::new();
3999 let mut rows = Vec::new();
4000 let mut rows_inserted = 0;
4001
4002 for selection in self.selections.all_adjusted(cx) {
4003 let cursor = selection.head();
4004 let row = cursor.row;
4005
4006 let point = Point::new(row + 1, 0);
4007 let start_of_line = snapshot.clip_point(point, Bias::Left);
4008
4009 let newline = "\n".to_string();
4010 edits.push((start_of_line..start_of_line, newline));
4011
4012 rows_inserted += 1;
4013 rows.push(row + rows_inserted);
4014 }
4015
4016 self.transact(window, cx, |editor, window, cx| {
4017 editor.edit(edits, cx);
4018
4019 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4020 let mut index = 0;
4021 s.move_cursors_with(|map, _, _| {
4022 let row = rows[index];
4023 index += 1;
4024
4025 let point = Point::new(row, 0);
4026 let boundary = map.next_line_boundary(point).1;
4027 let clipped = map.clip_point(boundary, Bias::Left);
4028
4029 (clipped, SelectionGoal::None)
4030 });
4031 });
4032
4033 let mut indent_edits = Vec::new();
4034 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4035 for row in rows {
4036 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4037 for (row, indent) in indents {
4038 if indent.len == 0 {
4039 continue;
4040 }
4041
4042 let text = match indent.kind {
4043 IndentKind::Space => " ".repeat(indent.len as usize),
4044 IndentKind::Tab => "\t".repeat(indent.len as usize),
4045 };
4046 let point = Point::new(row.0, 0);
4047 indent_edits.push((point..point, text));
4048 }
4049 }
4050 editor.edit(indent_edits, cx);
4051 });
4052 }
4053
4054 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4055 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4056 original_indent_columns: Vec::new(),
4057 });
4058 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4059 }
4060
4061 fn insert_with_autoindent_mode(
4062 &mut self,
4063 text: &str,
4064 autoindent_mode: Option<AutoindentMode>,
4065 window: &mut Window,
4066 cx: &mut Context<Self>,
4067 ) {
4068 if self.read_only(cx) {
4069 return;
4070 }
4071
4072 let text: Arc<str> = text.into();
4073 self.transact(window, cx, |this, window, cx| {
4074 let old_selections = this.selections.all_adjusted(cx);
4075 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4076 let anchors = {
4077 let snapshot = buffer.read(cx);
4078 old_selections
4079 .iter()
4080 .map(|s| {
4081 let anchor = snapshot.anchor_after(s.head());
4082 s.map(|_| anchor)
4083 })
4084 .collect::<Vec<_>>()
4085 };
4086 buffer.edit(
4087 old_selections
4088 .iter()
4089 .map(|s| (s.start..s.end, text.clone())),
4090 autoindent_mode,
4091 cx,
4092 );
4093 anchors
4094 });
4095
4096 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4097 s.select_anchors(selection_anchors);
4098 });
4099
4100 cx.notify();
4101 });
4102 }
4103
4104 fn trigger_completion_on_input(
4105 &mut self,
4106 text: &str,
4107 trigger_in_words: bool,
4108 window: &mut Window,
4109 cx: &mut Context<Self>,
4110 ) {
4111 let ignore_completion_provider = self
4112 .context_menu
4113 .borrow()
4114 .as_ref()
4115 .map(|menu| match menu {
4116 CodeContextMenu::Completions(completions_menu) => {
4117 completions_menu.ignore_completion_provider
4118 }
4119 CodeContextMenu::CodeActions(_) => false,
4120 })
4121 .unwrap_or(false);
4122
4123 if ignore_completion_provider {
4124 self.show_word_completions(&ShowWordCompletions, window, cx);
4125 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4126 self.show_completions(
4127 &ShowCompletions {
4128 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4129 },
4130 window,
4131 cx,
4132 );
4133 } else {
4134 self.hide_context_menu(window, cx);
4135 }
4136 }
4137
4138 fn is_completion_trigger(
4139 &self,
4140 text: &str,
4141 trigger_in_words: bool,
4142 cx: &mut Context<Self>,
4143 ) -> bool {
4144 let position = self.selections.newest_anchor().head();
4145 let multibuffer = self.buffer.read(cx);
4146 let Some(buffer) = position
4147 .buffer_id
4148 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4149 else {
4150 return false;
4151 };
4152
4153 if let Some(completion_provider) = &self.completion_provider {
4154 completion_provider.is_completion_trigger(
4155 &buffer,
4156 position.text_anchor,
4157 text,
4158 trigger_in_words,
4159 cx,
4160 )
4161 } else {
4162 false
4163 }
4164 }
4165
4166 /// If any empty selections is touching the start of its innermost containing autoclose
4167 /// region, expand it to select the brackets.
4168 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4169 let selections = self.selections.all::<usize>(cx);
4170 let buffer = self.buffer.read(cx).read(cx);
4171 let new_selections = self
4172 .selections_with_autoclose_regions(selections, &buffer)
4173 .map(|(mut selection, region)| {
4174 if !selection.is_empty() {
4175 return selection;
4176 }
4177
4178 if let Some(region) = region {
4179 let mut range = region.range.to_offset(&buffer);
4180 if selection.start == range.start && range.start >= region.pair.start.len() {
4181 range.start -= region.pair.start.len();
4182 if buffer.contains_str_at(range.start, ®ion.pair.start)
4183 && buffer.contains_str_at(range.end, ®ion.pair.end)
4184 {
4185 range.end += region.pair.end.len();
4186 selection.start = range.start;
4187 selection.end = range.end;
4188
4189 return selection;
4190 }
4191 }
4192 }
4193
4194 let always_treat_brackets_as_autoclosed = buffer
4195 .language_settings_at(selection.start, cx)
4196 .always_treat_brackets_as_autoclosed;
4197
4198 if !always_treat_brackets_as_autoclosed {
4199 return selection;
4200 }
4201
4202 if let Some(scope) = buffer.language_scope_at(selection.start) {
4203 for (pair, enabled) in scope.brackets() {
4204 if !enabled || !pair.close {
4205 continue;
4206 }
4207
4208 if buffer.contains_str_at(selection.start, &pair.end) {
4209 let pair_start_len = pair.start.len();
4210 if buffer.contains_str_at(
4211 selection.start.saturating_sub(pair_start_len),
4212 &pair.start,
4213 ) {
4214 selection.start -= pair_start_len;
4215 selection.end += pair.end.len();
4216
4217 return selection;
4218 }
4219 }
4220 }
4221 }
4222
4223 selection
4224 })
4225 .collect();
4226
4227 drop(buffer);
4228 self.change_selections(None, window, cx, |selections| {
4229 selections.select(new_selections)
4230 });
4231 }
4232
4233 /// Iterate the given selections, and for each one, find the smallest surrounding
4234 /// autoclose region. This uses the ordering of the selections and the autoclose
4235 /// regions to avoid repeated comparisons.
4236 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4237 &'a self,
4238 selections: impl IntoIterator<Item = Selection<D>>,
4239 buffer: &'a MultiBufferSnapshot,
4240 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4241 let mut i = 0;
4242 let mut regions = self.autoclose_regions.as_slice();
4243 selections.into_iter().map(move |selection| {
4244 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4245
4246 let mut enclosing = None;
4247 while let Some(pair_state) = regions.get(i) {
4248 if pair_state.range.end.to_offset(buffer) < range.start {
4249 regions = ®ions[i + 1..];
4250 i = 0;
4251 } else if pair_state.range.start.to_offset(buffer) > range.end {
4252 break;
4253 } else {
4254 if pair_state.selection_id == selection.id {
4255 enclosing = Some(pair_state);
4256 }
4257 i += 1;
4258 }
4259 }
4260
4261 (selection, enclosing)
4262 })
4263 }
4264
4265 /// Remove any autoclose regions that no longer contain their selection.
4266 fn invalidate_autoclose_regions(
4267 &mut self,
4268 mut selections: &[Selection<Anchor>],
4269 buffer: &MultiBufferSnapshot,
4270 ) {
4271 self.autoclose_regions.retain(|state| {
4272 let mut i = 0;
4273 while let Some(selection) = selections.get(i) {
4274 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4275 selections = &selections[1..];
4276 continue;
4277 }
4278 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4279 break;
4280 }
4281 if selection.id == state.selection_id {
4282 return true;
4283 } else {
4284 i += 1;
4285 }
4286 }
4287 false
4288 });
4289 }
4290
4291 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4292 let offset = position.to_offset(buffer);
4293 let (word_range, kind) = buffer.surrounding_word(offset, true);
4294 if offset > word_range.start && kind == Some(CharKind::Word) {
4295 Some(
4296 buffer
4297 .text_for_range(word_range.start..offset)
4298 .collect::<String>(),
4299 )
4300 } else {
4301 None
4302 }
4303 }
4304
4305 pub fn toggle_inline_values(
4306 &mut self,
4307 _: &ToggleInlineValues,
4308 _: &mut Window,
4309 cx: &mut Context<Self>,
4310 ) {
4311 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4312
4313 self.refresh_inline_values(cx);
4314 }
4315
4316 pub fn toggle_inlay_hints(
4317 &mut self,
4318 _: &ToggleInlayHints,
4319 _: &mut Window,
4320 cx: &mut Context<Self>,
4321 ) {
4322 self.refresh_inlay_hints(
4323 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4324 cx,
4325 );
4326 }
4327
4328 pub fn inlay_hints_enabled(&self) -> bool {
4329 self.inlay_hint_cache.enabled
4330 }
4331
4332 pub fn inline_values_enabled(&self) -> bool {
4333 self.inline_value_cache.enabled
4334 }
4335
4336 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4337 if self.semantics_provider.is_none() || !self.mode.is_full() {
4338 return;
4339 }
4340
4341 let reason_description = reason.description();
4342 let ignore_debounce = matches!(
4343 reason,
4344 InlayHintRefreshReason::SettingsChange(_)
4345 | InlayHintRefreshReason::Toggle(_)
4346 | InlayHintRefreshReason::ExcerptsRemoved(_)
4347 | InlayHintRefreshReason::ModifiersChanged(_)
4348 );
4349 let (invalidate_cache, required_languages) = match reason {
4350 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4351 match self.inlay_hint_cache.modifiers_override(enabled) {
4352 Some(enabled) => {
4353 if enabled {
4354 (InvalidationStrategy::RefreshRequested, None)
4355 } else {
4356 self.splice_inlays(
4357 &self
4358 .visible_inlay_hints(cx)
4359 .iter()
4360 .map(|inlay| inlay.id)
4361 .collect::<Vec<InlayId>>(),
4362 Vec::new(),
4363 cx,
4364 );
4365 return;
4366 }
4367 }
4368 None => return,
4369 }
4370 }
4371 InlayHintRefreshReason::Toggle(enabled) => {
4372 if self.inlay_hint_cache.toggle(enabled) {
4373 if enabled {
4374 (InvalidationStrategy::RefreshRequested, None)
4375 } else {
4376 self.splice_inlays(
4377 &self
4378 .visible_inlay_hints(cx)
4379 .iter()
4380 .map(|inlay| inlay.id)
4381 .collect::<Vec<InlayId>>(),
4382 Vec::new(),
4383 cx,
4384 );
4385 return;
4386 }
4387 } else {
4388 return;
4389 }
4390 }
4391 InlayHintRefreshReason::SettingsChange(new_settings) => {
4392 match self.inlay_hint_cache.update_settings(
4393 &self.buffer,
4394 new_settings,
4395 self.visible_inlay_hints(cx),
4396 cx,
4397 ) {
4398 ControlFlow::Break(Some(InlaySplice {
4399 to_remove,
4400 to_insert,
4401 })) => {
4402 self.splice_inlays(&to_remove, to_insert, cx);
4403 return;
4404 }
4405 ControlFlow::Break(None) => return,
4406 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4407 }
4408 }
4409 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4410 if let Some(InlaySplice {
4411 to_remove,
4412 to_insert,
4413 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4414 {
4415 self.splice_inlays(&to_remove, to_insert, cx);
4416 }
4417 self.display_map.update(cx, |display_map, _| {
4418 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4419 });
4420 return;
4421 }
4422 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4423 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4424 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4425 }
4426 InlayHintRefreshReason::RefreshRequested => {
4427 (InvalidationStrategy::RefreshRequested, None)
4428 }
4429 };
4430
4431 if let Some(InlaySplice {
4432 to_remove,
4433 to_insert,
4434 }) = self.inlay_hint_cache.spawn_hint_refresh(
4435 reason_description,
4436 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4437 invalidate_cache,
4438 ignore_debounce,
4439 cx,
4440 ) {
4441 self.splice_inlays(&to_remove, to_insert, cx);
4442 }
4443 }
4444
4445 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4446 self.display_map
4447 .read(cx)
4448 .current_inlays()
4449 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4450 .cloned()
4451 .collect()
4452 }
4453
4454 pub fn excerpts_for_inlay_hints_query(
4455 &self,
4456 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4457 cx: &mut Context<Editor>,
4458 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4459 let Some(project) = self.project.as_ref() else {
4460 return HashMap::default();
4461 };
4462 let project = project.read(cx);
4463 let multi_buffer = self.buffer().read(cx);
4464 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4465 let multi_buffer_visible_start = self
4466 .scroll_manager
4467 .anchor()
4468 .anchor
4469 .to_point(&multi_buffer_snapshot);
4470 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4471 multi_buffer_visible_start
4472 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4473 Bias::Left,
4474 );
4475 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4476 multi_buffer_snapshot
4477 .range_to_buffer_ranges(multi_buffer_visible_range)
4478 .into_iter()
4479 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4480 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4481 let buffer_file = project::File::from_dyn(buffer.file())?;
4482 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4483 let worktree_entry = buffer_worktree
4484 .read(cx)
4485 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4486 if worktree_entry.is_ignored {
4487 return None;
4488 }
4489
4490 let language = buffer.language()?;
4491 if let Some(restrict_to_languages) = restrict_to_languages {
4492 if !restrict_to_languages.contains(language) {
4493 return None;
4494 }
4495 }
4496 Some((
4497 excerpt_id,
4498 (
4499 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4500 buffer.version().clone(),
4501 excerpt_visible_range,
4502 ),
4503 ))
4504 })
4505 .collect()
4506 }
4507
4508 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4509 TextLayoutDetails {
4510 text_system: window.text_system().clone(),
4511 editor_style: self.style.clone().unwrap(),
4512 rem_size: window.rem_size(),
4513 scroll_anchor: self.scroll_manager.anchor(),
4514 visible_rows: self.visible_line_count(),
4515 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4516 }
4517 }
4518
4519 pub fn splice_inlays(
4520 &self,
4521 to_remove: &[InlayId],
4522 to_insert: Vec<Inlay>,
4523 cx: &mut Context<Self>,
4524 ) {
4525 self.display_map.update(cx, |display_map, cx| {
4526 display_map.splice_inlays(to_remove, to_insert, cx)
4527 });
4528 cx.notify();
4529 }
4530
4531 fn trigger_on_type_formatting(
4532 &self,
4533 input: String,
4534 window: &mut Window,
4535 cx: &mut Context<Self>,
4536 ) -> Option<Task<Result<()>>> {
4537 if input.len() != 1 {
4538 return None;
4539 }
4540
4541 let project = self.project.as_ref()?;
4542 let position = self.selections.newest_anchor().head();
4543 let (buffer, buffer_position) = self
4544 .buffer
4545 .read(cx)
4546 .text_anchor_for_position(position, cx)?;
4547
4548 let settings = language_settings::language_settings(
4549 buffer
4550 .read(cx)
4551 .language_at(buffer_position)
4552 .map(|l| l.name()),
4553 buffer.read(cx).file(),
4554 cx,
4555 );
4556 if !settings.use_on_type_format {
4557 return None;
4558 }
4559
4560 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4561 // hence we do LSP request & edit on host side only — add formats to host's history.
4562 let push_to_lsp_host_history = true;
4563 // If this is not the host, append its history with new edits.
4564 let push_to_client_history = project.read(cx).is_via_collab();
4565
4566 let on_type_formatting = project.update(cx, |project, cx| {
4567 project.on_type_format(
4568 buffer.clone(),
4569 buffer_position,
4570 input,
4571 push_to_lsp_host_history,
4572 cx,
4573 )
4574 });
4575 Some(cx.spawn_in(window, async move |editor, cx| {
4576 if let Some(transaction) = on_type_formatting.await? {
4577 if push_to_client_history {
4578 buffer
4579 .update(cx, |buffer, _| {
4580 buffer.push_transaction(transaction, Instant::now());
4581 buffer.finalize_last_transaction();
4582 })
4583 .ok();
4584 }
4585 editor.update(cx, |editor, cx| {
4586 editor.refresh_document_highlights(cx);
4587 })?;
4588 }
4589 Ok(())
4590 }))
4591 }
4592
4593 pub fn show_word_completions(
4594 &mut self,
4595 _: &ShowWordCompletions,
4596 window: &mut Window,
4597 cx: &mut Context<Self>,
4598 ) {
4599 self.open_completions_menu(true, None, window, cx);
4600 }
4601
4602 pub fn show_completions(
4603 &mut self,
4604 options: &ShowCompletions,
4605 window: &mut Window,
4606 cx: &mut Context<Self>,
4607 ) {
4608 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4609 }
4610
4611 fn open_completions_menu(
4612 &mut self,
4613 ignore_completion_provider: bool,
4614 trigger: Option<&str>,
4615 window: &mut Window,
4616 cx: &mut Context<Self>,
4617 ) {
4618 if self.pending_rename.is_some() {
4619 return;
4620 }
4621 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4622 return;
4623 }
4624
4625 let position = self.selections.newest_anchor().head();
4626 if position.diff_base_anchor.is_some() {
4627 return;
4628 }
4629 let (buffer, buffer_position) =
4630 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4631 output
4632 } else {
4633 return;
4634 };
4635 let buffer_snapshot = buffer.read(cx).snapshot();
4636 let show_completion_documentation = buffer_snapshot
4637 .settings_at(buffer_position, cx)
4638 .show_completion_documentation;
4639
4640 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4641
4642 let trigger_kind = match trigger {
4643 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4644 CompletionTriggerKind::TRIGGER_CHARACTER
4645 }
4646 _ => CompletionTriggerKind::INVOKED,
4647 };
4648 let completion_context = CompletionContext {
4649 trigger_character: trigger.and_then(|trigger| {
4650 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4651 Some(String::from(trigger))
4652 } else {
4653 None
4654 }
4655 }),
4656 trigger_kind,
4657 };
4658
4659 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4660 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4661 let word_to_exclude = buffer_snapshot
4662 .text_for_range(old_range.clone())
4663 .collect::<String>();
4664 (
4665 buffer_snapshot.anchor_before(old_range.start)
4666 ..buffer_snapshot.anchor_after(old_range.end),
4667 Some(word_to_exclude),
4668 )
4669 } else {
4670 (buffer_position..buffer_position, None)
4671 };
4672
4673 let completion_settings = language_settings(
4674 buffer_snapshot
4675 .language_at(buffer_position)
4676 .map(|language| language.name()),
4677 buffer_snapshot.file(),
4678 cx,
4679 )
4680 .completions;
4681
4682 // The document can be large, so stay in reasonable bounds when searching for words,
4683 // otherwise completion pop-up might be slow to appear.
4684 const WORD_LOOKUP_ROWS: u32 = 5_000;
4685 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4686 let min_word_search = buffer_snapshot.clip_point(
4687 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4688 Bias::Left,
4689 );
4690 let max_word_search = buffer_snapshot.clip_point(
4691 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4692 Bias::Right,
4693 );
4694 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4695 ..buffer_snapshot.point_to_offset(max_word_search);
4696
4697 let provider = self
4698 .completion_provider
4699 .as_ref()
4700 .filter(|_| !ignore_completion_provider);
4701 let skip_digits = query
4702 .as_ref()
4703 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4704
4705 let (mut words, provided_completions) = match provider {
4706 Some(provider) => {
4707 let completions = provider.completions(
4708 position.excerpt_id,
4709 &buffer,
4710 buffer_position,
4711 completion_context,
4712 window,
4713 cx,
4714 );
4715
4716 let words = match completion_settings.words {
4717 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4718 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4719 .background_spawn(async move {
4720 buffer_snapshot.words_in_range(WordsQuery {
4721 fuzzy_contents: None,
4722 range: word_search_range,
4723 skip_digits,
4724 })
4725 }),
4726 };
4727
4728 (words, completions)
4729 }
4730 None => (
4731 cx.background_spawn(async move {
4732 buffer_snapshot.words_in_range(WordsQuery {
4733 fuzzy_contents: None,
4734 range: word_search_range,
4735 skip_digits,
4736 })
4737 }),
4738 Task::ready(Ok(None)),
4739 ),
4740 };
4741
4742 let sort_completions = provider
4743 .as_ref()
4744 .map_or(false, |provider| provider.sort_completions());
4745
4746 let filter_completions = provider
4747 .as_ref()
4748 .map_or(true, |provider| provider.filter_completions());
4749
4750 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4751
4752 let id = post_inc(&mut self.next_completion_id);
4753 let task = cx.spawn_in(window, async move |editor, cx| {
4754 async move {
4755 editor.update(cx, |this, _| {
4756 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4757 })?;
4758
4759 let mut completions = Vec::new();
4760 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4761 completions.extend(provided_completions);
4762 if completion_settings.words == WordsCompletionMode::Fallback {
4763 words = Task::ready(BTreeMap::default());
4764 }
4765 }
4766
4767 let mut words = words.await;
4768 if let Some(word_to_exclude) = &word_to_exclude {
4769 words.remove(word_to_exclude);
4770 }
4771 for lsp_completion in &completions {
4772 words.remove(&lsp_completion.new_text);
4773 }
4774 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4775 replace_range: old_range.clone(),
4776 new_text: word.clone(),
4777 label: CodeLabel::plain(word, None),
4778 icon_path: None,
4779 documentation: None,
4780 source: CompletionSource::BufferWord {
4781 word_range,
4782 resolved: false,
4783 },
4784 insert_text_mode: Some(InsertTextMode::AS_IS),
4785 confirm: None,
4786 }));
4787
4788 let menu = if completions.is_empty() {
4789 None
4790 } else {
4791 let mut menu = CompletionsMenu::new(
4792 id,
4793 sort_completions,
4794 show_completion_documentation,
4795 ignore_completion_provider,
4796 position,
4797 buffer.clone(),
4798 completions.into(),
4799 snippet_sort_order,
4800 );
4801
4802 menu.filter(
4803 if filter_completions {
4804 query.as_deref()
4805 } else {
4806 None
4807 },
4808 cx.background_executor().clone(),
4809 )
4810 .await;
4811
4812 menu.visible().then_some(menu)
4813 };
4814
4815 editor.update_in(cx, |editor, window, cx| {
4816 match editor.context_menu.borrow().as_ref() {
4817 None => {}
4818 Some(CodeContextMenu::Completions(prev_menu)) => {
4819 if prev_menu.id > id {
4820 return;
4821 }
4822 }
4823 _ => return,
4824 }
4825
4826 if editor.focus_handle.is_focused(window) && menu.is_some() {
4827 let mut menu = menu.unwrap();
4828 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4829
4830 *editor.context_menu.borrow_mut() =
4831 Some(CodeContextMenu::Completions(menu));
4832
4833 if editor.show_edit_predictions_in_menu() {
4834 editor.update_visible_inline_completion(window, cx);
4835 } else {
4836 editor.discard_inline_completion(false, cx);
4837 }
4838
4839 cx.notify();
4840 } else if editor.completion_tasks.len() <= 1 {
4841 // If there are no more completion tasks and the last menu was
4842 // empty, we should hide it.
4843 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4844 // If it was already hidden and we don't show inline
4845 // completions in the menu, we should also show the
4846 // inline-completion when available.
4847 if was_hidden && editor.show_edit_predictions_in_menu() {
4848 editor.update_visible_inline_completion(window, cx);
4849 }
4850 }
4851 })?;
4852
4853 anyhow::Ok(())
4854 }
4855 .log_err()
4856 .await
4857 });
4858
4859 self.completion_tasks.push((id, task));
4860 }
4861
4862 #[cfg(feature = "test-support")]
4863 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4864 let menu = self.context_menu.borrow();
4865 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4866 let completions = menu.completions.borrow();
4867 Some(completions.to_vec())
4868 } else {
4869 None
4870 }
4871 }
4872
4873 pub fn confirm_completion(
4874 &mut self,
4875 action: &ConfirmCompletion,
4876 window: &mut Window,
4877 cx: &mut Context<Self>,
4878 ) -> Option<Task<Result<()>>> {
4879 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4880 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4881 }
4882
4883 pub fn confirm_completion_insert(
4884 &mut self,
4885 _: &ConfirmCompletionInsert,
4886 window: &mut Window,
4887 cx: &mut Context<Self>,
4888 ) -> Option<Task<Result<()>>> {
4889 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4890 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4891 }
4892
4893 pub fn confirm_completion_replace(
4894 &mut self,
4895 _: &ConfirmCompletionReplace,
4896 window: &mut Window,
4897 cx: &mut Context<Self>,
4898 ) -> Option<Task<Result<()>>> {
4899 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4900 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4901 }
4902
4903 pub fn compose_completion(
4904 &mut self,
4905 action: &ComposeCompletion,
4906 window: &mut Window,
4907 cx: &mut Context<Self>,
4908 ) -> Option<Task<Result<()>>> {
4909 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4910 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4911 }
4912
4913 fn do_completion(
4914 &mut self,
4915 item_ix: Option<usize>,
4916 intent: CompletionIntent,
4917 window: &mut Window,
4918 cx: &mut Context<Editor>,
4919 ) -> Option<Task<Result<()>>> {
4920 use language::ToOffset as _;
4921
4922 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4923 else {
4924 return None;
4925 };
4926
4927 let candidate_id = {
4928 let entries = completions_menu.entries.borrow();
4929 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4930 if self.show_edit_predictions_in_menu() {
4931 self.discard_inline_completion(true, cx);
4932 }
4933 mat.candidate_id
4934 };
4935
4936 let buffer_handle = completions_menu.buffer;
4937 let completion = completions_menu
4938 .completions
4939 .borrow()
4940 .get(candidate_id)?
4941 .clone();
4942 cx.stop_propagation();
4943
4944 let snippet;
4945 let new_text;
4946 if completion.is_snippet() {
4947 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4948 new_text = snippet.as_ref().unwrap().text.clone();
4949 } else {
4950 snippet = None;
4951 new_text = completion.new_text.clone();
4952 };
4953
4954 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4955 let buffer = buffer_handle.read(cx);
4956 let snapshot = self.buffer.read(cx).snapshot(cx);
4957 let replace_range_multibuffer = {
4958 let excerpt = snapshot
4959 .excerpt_containing(self.selections.newest_anchor().range())
4960 .unwrap();
4961 let multibuffer_anchor = snapshot
4962 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4963 .unwrap()
4964 ..snapshot
4965 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4966 .unwrap();
4967 multibuffer_anchor.start.to_offset(&snapshot)
4968 ..multibuffer_anchor.end.to_offset(&snapshot)
4969 };
4970 let newest_anchor = self.selections.newest_anchor();
4971 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4972 return None;
4973 }
4974
4975 let old_text = buffer
4976 .text_for_range(replace_range.clone())
4977 .collect::<String>();
4978 let lookbehind = newest_anchor
4979 .start
4980 .text_anchor
4981 .to_offset(buffer)
4982 .saturating_sub(replace_range.start);
4983 let lookahead = replace_range
4984 .end
4985 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4986 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4987 let suffix = &old_text[lookbehind.min(old_text.len())..];
4988
4989 let selections = self.selections.all::<usize>(cx);
4990 let mut ranges = Vec::new();
4991 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4992
4993 for selection in &selections {
4994 let range = if selection.id == newest_anchor.id {
4995 replace_range_multibuffer.clone()
4996 } else {
4997 let mut range = selection.range();
4998
4999 // if prefix is present, don't duplicate it
5000 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
5001 range.start = range.start.saturating_sub(lookbehind);
5002
5003 // if suffix is also present, mimic the newest cursor and replace it
5004 if selection.id != newest_anchor.id
5005 && snapshot.contains_str_at(range.end, suffix)
5006 {
5007 range.end += lookahead;
5008 }
5009 }
5010 range
5011 };
5012
5013 ranges.push(range.clone());
5014
5015 if !self.linked_edit_ranges.is_empty() {
5016 let start_anchor = snapshot.anchor_before(range.start);
5017 let end_anchor = snapshot.anchor_after(range.end);
5018 if let Some(ranges) = self
5019 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5020 {
5021 for (buffer, edits) in ranges {
5022 linked_edits
5023 .entry(buffer.clone())
5024 .or_default()
5025 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5026 }
5027 }
5028 }
5029 }
5030
5031 cx.emit(EditorEvent::InputHandled {
5032 utf16_range_to_replace: None,
5033 text: new_text.clone().into(),
5034 });
5035
5036 self.transact(window, cx, |this, window, cx| {
5037 if let Some(mut snippet) = snippet {
5038 snippet.text = new_text.to_string();
5039 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5040 } else {
5041 this.buffer.update(cx, |buffer, cx| {
5042 let auto_indent = match completion.insert_text_mode {
5043 Some(InsertTextMode::AS_IS) => None,
5044 _ => this.autoindent_mode.clone(),
5045 };
5046 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5047 buffer.edit(edits, auto_indent, cx);
5048 });
5049 }
5050 for (buffer, edits) in linked_edits {
5051 buffer.update(cx, |buffer, cx| {
5052 let snapshot = buffer.snapshot();
5053 let edits = edits
5054 .into_iter()
5055 .map(|(range, text)| {
5056 use text::ToPoint as TP;
5057 let end_point = TP::to_point(&range.end, &snapshot);
5058 let start_point = TP::to_point(&range.start, &snapshot);
5059 (start_point..end_point, text)
5060 })
5061 .sorted_by_key(|(range, _)| range.start);
5062 buffer.edit(edits, None, cx);
5063 })
5064 }
5065
5066 this.refresh_inline_completion(true, false, window, cx);
5067 });
5068
5069 let show_new_completions_on_confirm = completion
5070 .confirm
5071 .as_ref()
5072 .map_or(false, |confirm| confirm(intent, window, cx));
5073 if show_new_completions_on_confirm {
5074 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5075 }
5076
5077 let provider = self.completion_provider.as_ref()?;
5078 drop(completion);
5079 let apply_edits = provider.apply_additional_edits_for_completion(
5080 buffer_handle,
5081 completions_menu.completions.clone(),
5082 candidate_id,
5083 true,
5084 cx,
5085 );
5086
5087 let editor_settings = EditorSettings::get_global(cx);
5088 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5089 // After the code completion is finished, users often want to know what signatures are needed.
5090 // so we should automatically call signature_help
5091 self.show_signature_help(&ShowSignatureHelp, window, cx);
5092 }
5093
5094 Some(cx.foreground_executor().spawn(async move {
5095 apply_edits.await?;
5096 Ok(())
5097 }))
5098 }
5099
5100 pub fn toggle_code_actions(
5101 &mut self,
5102 action: &ToggleCodeActions,
5103 window: &mut Window,
5104 cx: &mut Context<Self>,
5105 ) {
5106 let quick_launch = action.quick_launch;
5107 let mut context_menu = self.context_menu.borrow_mut();
5108 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5109 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5110 // Toggle if we're selecting the same one
5111 *context_menu = None;
5112 cx.notify();
5113 return;
5114 } else {
5115 // Otherwise, clear it and start a new one
5116 *context_menu = None;
5117 cx.notify();
5118 }
5119 }
5120 drop(context_menu);
5121 let snapshot = self.snapshot(window, cx);
5122 let deployed_from_indicator = action.deployed_from_indicator;
5123 let mut task = self.code_actions_task.take();
5124 let action = action.clone();
5125 cx.spawn_in(window, async move |editor, cx| {
5126 while let Some(prev_task) = task {
5127 prev_task.await.log_err();
5128 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5129 }
5130
5131 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5132 if editor.focus_handle.is_focused(window) {
5133 let multibuffer_point = action
5134 .deployed_from_indicator
5135 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5136 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5137 let (buffer, buffer_row) = snapshot
5138 .buffer_snapshot
5139 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5140 .and_then(|(buffer_snapshot, range)| {
5141 editor
5142 .buffer
5143 .read(cx)
5144 .buffer(buffer_snapshot.remote_id())
5145 .map(|buffer| (buffer, range.start.row))
5146 })?;
5147 let (_, code_actions) = editor
5148 .available_code_actions
5149 .clone()
5150 .and_then(|(location, code_actions)| {
5151 let snapshot = location.buffer.read(cx).snapshot();
5152 let point_range = location.range.to_point(&snapshot);
5153 let point_range = point_range.start.row..=point_range.end.row;
5154 if point_range.contains(&buffer_row) {
5155 Some((location, code_actions))
5156 } else {
5157 None
5158 }
5159 })
5160 .unzip();
5161 let buffer_id = buffer.read(cx).remote_id();
5162 let tasks = editor
5163 .tasks
5164 .get(&(buffer_id, buffer_row))
5165 .map(|t| Arc::new(t.to_owned()));
5166 if tasks.is_none() && code_actions.is_none() {
5167 return None;
5168 }
5169
5170 editor.completion_tasks.clear();
5171 editor.discard_inline_completion(false, cx);
5172 let task_context =
5173 tasks
5174 .as_ref()
5175 .zip(editor.project.clone())
5176 .map(|(tasks, project)| {
5177 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5178 });
5179
5180 Some(cx.spawn_in(window, async move |editor, cx| {
5181 let task_context = match task_context {
5182 Some(task_context) => task_context.await,
5183 None => None,
5184 };
5185 let resolved_tasks =
5186 tasks
5187 .zip(task_context.clone())
5188 .map(|(tasks, task_context)| ResolvedTasks {
5189 templates: tasks.resolve(&task_context).collect(),
5190 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5191 multibuffer_point.row,
5192 tasks.column,
5193 )),
5194 });
5195 let spawn_straight_away = quick_launch
5196 && resolved_tasks
5197 .as_ref()
5198 .map_or(false, |tasks| tasks.templates.len() == 1)
5199 && code_actions
5200 .as_ref()
5201 .map_or(true, |actions| actions.is_empty());
5202 let debug_scenarios = editor.update(cx, |editor, cx| {
5203 if cx.has_flag::<DebuggerFeatureFlag>() {
5204 maybe!({
5205 let project = editor.project.as_ref()?;
5206 let dap_store = project.read(cx).dap_store();
5207 let mut scenarios = vec![];
5208 let resolved_tasks = resolved_tasks.as_ref()?;
5209 let buffer = buffer.read(cx);
5210 let language = buffer.language()?;
5211 let file = buffer.file();
5212 let debug_adapter =
5213 language_settings(language.name().into(), file, cx)
5214 .debuggers
5215 .first()
5216 .map(SharedString::from)
5217 .or_else(|| {
5218 language
5219 .config()
5220 .debuggers
5221 .first()
5222 .map(SharedString::from)
5223 })?;
5224
5225 dap_store.update(cx, |this, cx| {
5226 for (_, task) in &resolved_tasks.templates {
5227 if let Some(scenario) = this
5228 .debug_scenario_for_build_task(
5229 task.original_task().clone(),
5230 debug_adapter.clone(),
5231 cx,
5232 )
5233 {
5234 scenarios.push(scenario);
5235 }
5236 }
5237 });
5238 Some(scenarios)
5239 })
5240 .unwrap_or_default()
5241 } else {
5242 vec![]
5243 }
5244 })?;
5245 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5246 *editor.context_menu.borrow_mut() =
5247 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5248 buffer,
5249 actions: CodeActionContents::new(
5250 resolved_tasks,
5251 code_actions,
5252 debug_scenarios,
5253 task_context.unwrap_or_default(),
5254 ),
5255 selected_item: Default::default(),
5256 scroll_handle: UniformListScrollHandle::default(),
5257 deployed_from_indicator,
5258 }));
5259 if spawn_straight_away {
5260 if let Some(task) = editor.confirm_code_action(
5261 &ConfirmCodeAction { item_ix: Some(0) },
5262 window,
5263 cx,
5264 ) {
5265 cx.notify();
5266 return task;
5267 }
5268 }
5269 cx.notify();
5270 Task::ready(Ok(()))
5271 }) {
5272 task.await
5273 } else {
5274 Ok(())
5275 }
5276 }))
5277 } else {
5278 Some(Task::ready(Ok(())))
5279 }
5280 })?;
5281 if let Some(task) = spawned_test_task {
5282 task.await?;
5283 }
5284
5285 Ok::<_, anyhow::Error>(())
5286 })
5287 .detach_and_log_err(cx);
5288 }
5289
5290 pub fn confirm_code_action(
5291 &mut self,
5292 action: &ConfirmCodeAction,
5293 window: &mut Window,
5294 cx: &mut Context<Self>,
5295 ) -> Option<Task<Result<()>>> {
5296 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5297
5298 let actions_menu =
5299 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5300 menu
5301 } else {
5302 return None;
5303 };
5304
5305 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5306 let action = actions_menu.actions.get(action_ix)?;
5307 let title = action.label();
5308 let buffer = actions_menu.buffer;
5309 let workspace = self.workspace()?;
5310
5311 match action {
5312 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5313 workspace.update(cx, |workspace, cx| {
5314 workspace.schedule_resolved_task(
5315 task_source_kind,
5316 resolved_task,
5317 false,
5318 window,
5319 cx,
5320 );
5321
5322 Some(Task::ready(Ok(())))
5323 })
5324 }
5325 CodeActionsItem::CodeAction {
5326 excerpt_id,
5327 action,
5328 provider,
5329 } => {
5330 let apply_code_action =
5331 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5332 let workspace = workspace.downgrade();
5333 Some(cx.spawn_in(window, async move |editor, cx| {
5334 let project_transaction = apply_code_action.await?;
5335 Self::open_project_transaction(
5336 &editor,
5337 workspace,
5338 project_transaction,
5339 title,
5340 cx,
5341 )
5342 .await
5343 }))
5344 }
5345 CodeActionsItem::DebugScenario(scenario) => {
5346 let context = actions_menu.actions.context.clone();
5347
5348 workspace.update(cx, |workspace, cx| {
5349 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5350 });
5351 Some(Task::ready(Ok(())))
5352 }
5353 }
5354 }
5355
5356 pub async fn open_project_transaction(
5357 this: &WeakEntity<Editor>,
5358 workspace: WeakEntity<Workspace>,
5359 transaction: ProjectTransaction,
5360 title: String,
5361 cx: &mut AsyncWindowContext,
5362 ) -> Result<()> {
5363 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5364 cx.update(|_, cx| {
5365 entries.sort_unstable_by_key(|(buffer, _)| {
5366 buffer.read(cx).file().map(|f| f.path().clone())
5367 });
5368 })?;
5369
5370 // If the project transaction's edits are all contained within this editor, then
5371 // avoid opening a new editor to display them.
5372
5373 if let Some((buffer, transaction)) = entries.first() {
5374 if entries.len() == 1 {
5375 let excerpt = this.update(cx, |editor, cx| {
5376 editor
5377 .buffer()
5378 .read(cx)
5379 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5380 })?;
5381 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5382 if excerpted_buffer == *buffer {
5383 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5384 let excerpt_range = excerpt_range.to_offset(buffer);
5385 buffer
5386 .edited_ranges_for_transaction::<usize>(transaction)
5387 .all(|range| {
5388 excerpt_range.start <= range.start
5389 && excerpt_range.end >= range.end
5390 })
5391 })?;
5392
5393 if all_edits_within_excerpt {
5394 return Ok(());
5395 }
5396 }
5397 }
5398 }
5399 } else {
5400 return Ok(());
5401 }
5402
5403 let mut ranges_to_highlight = Vec::new();
5404 let excerpt_buffer = cx.new(|cx| {
5405 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5406 for (buffer_handle, transaction) in &entries {
5407 let edited_ranges = buffer_handle
5408 .read(cx)
5409 .edited_ranges_for_transaction::<Point>(transaction)
5410 .collect::<Vec<_>>();
5411 let (ranges, _) = multibuffer.set_excerpts_for_path(
5412 PathKey::for_buffer(buffer_handle, cx),
5413 buffer_handle.clone(),
5414 edited_ranges,
5415 DEFAULT_MULTIBUFFER_CONTEXT,
5416 cx,
5417 );
5418
5419 ranges_to_highlight.extend(ranges);
5420 }
5421 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5422 multibuffer
5423 })?;
5424
5425 workspace.update_in(cx, |workspace, window, cx| {
5426 let project = workspace.project().clone();
5427 let editor =
5428 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5429 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5430 editor.update(cx, |editor, cx| {
5431 editor.highlight_background::<Self>(
5432 &ranges_to_highlight,
5433 |theme| theme.editor_highlighted_line_background,
5434 cx,
5435 );
5436 });
5437 })?;
5438
5439 Ok(())
5440 }
5441
5442 pub fn clear_code_action_providers(&mut self) {
5443 self.code_action_providers.clear();
5444 self.available_code_actions.take();
5445 }
5446
5447 pub fn add_code_action_provider(
5448 &mut self,
5449 provider: Rc<dyn CodeActionProvider>,
5450 window: &mut Window,
5451 cx: &mut Context<Self>,
5452 ) {
5453 if self
5454 .code_action_providers
5455 .iter()
5456 .any(|existing_provider| existing_provider.id() == provider.id())
5457 {
5458 return;
5459 }
5460
5461 self.code_action_providers.push(provider);
5462 self.refresh_code_actions(window, cx);
5463 }
5464
5465 pub fn remove_code_action_provider(
5466 &mut self,
5467 id: Arc<str>,
5468 window: &mut Window,
5469 cx: &mut Context<Self>,
5470 ) {
5471 self.code_action_providers
5472 .retain(|provider| provider.id() != id);
5473 self.refresh_code_actions(window, cx);
5474 }
5475
5476 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5477 let newest_selection = self.selections.newest_anchor().clone();
5478 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5479 let buffer = self.buffer.read(cx);
5480 if newest_selection.head().diff_base_anchor.is_some() {
5481 return None;
5482 }
5483 let (start_buffer, start) =
5484 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5485 let (end_buffer, end) =
5486 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5487 if start_buffer != end_buffer {
5488 return None;
5489 }
5490
5491 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5492 cx.background_executor()
5493 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5494 .await;
5495
5496 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5497 let providers = this.code_action_providers.clone();
5498 let tasks = this
5499 .code_action_providers
5500 .iter()
5501 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5502 .collect::<Vec<_>>();
5503 (providers, tasks)
5504 })?;
5505
5506 let mut actions = Vec::new();
5507 for (provider, provider_actions) in
5508 providers.into_iter().zip(future::join_all(tasks).await)
5509 {
5510 if let Some(provider_actions) = provider_actions.log_err() {
5511 actions.extend(provider_actions.into_iter().map(|action| {
5512 AvailableCodeAction {
5513 excerpt_id: newest_selection.start.excerpt_id,
5514 action,
5515 provider: provider.clone(),
5516 }
5517 }));
5518 }
5519 }
5520
5521 this.update(cx, |this, cx| {
5522 this.available_code_actions = if actions.is_empty() {
5523 None
5524 } else {
5525 Some((
5526 Location {
5527 buffer: start_buffer,
5528 range: start..end,
5529 },
5530 actions.into(),
5531 ))
5532 };
5533 cx.notify();
5534 })
5535 }));
5536 None
5537 }
5538
5539 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5540 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5541 self.show_git_blame_inline = false;
5542
5543 self.show_git_blame_inline_delay_task =
5544 Some(cx.spawn_in(window, async move |this, cx| {
5545 cx.background_executor().timer(delay).await;
5546
5547 this.update(cx, |this, cx| {
5548 this.show_git_blame_inline = true;
5549 cx.notify();
5550 })
5551 .log_err();
5552 }));
5553 }
5554 }
5555
5556 fn show_blame_popover(
5557 &mut self,
5558 blame_entry: &BlameEntry,
5559 position: gpui::Point<Pixels>,
5560 cx: &mut Context<Self>,
5561 ) {
5562 if let Some(state) = &mut self.inline_blame_popover {
5563 state.hide_task.take();
5564 cx.notify();
5565 } else {
5566 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5567 let show_task = cx.spawn(async move |editor, cx| {
5568 cx.background_executor()
5569 .timer(std::time::Duration::from_millis(delay))
5570 .await;
5571 editor
5572 .update(cx, |editor, cx| {
5573 if let Some(state) = &mut editor.inline_blame_popover {
5574 state.show_task = None;
5575 cx.notify();
5576 }
5577 })
5578 .ok();
5579 });
5580 let Some(blame) = self.blame.as_ref() else {
5581 return;
5582 };
5583 let blame = blame.read(cx);
5584 let details = blame.details_for_entry(&blame_entry);
5585 let markdown = cx.new(|cx| {
5586 Markdown::new(
5587 details
5588 .as_ref()
5589 .map(|message| message.message.clone())
5590 .unwrap_or_default(),
5591 None,
5592 None,
5593 cx,
5594 )
5595 });
5596 self.inline_blame_popover = Some(InlineBlamePopover {
5597 position,
5598 show_task: Some(show_task),
5599 hide_task: None,
5600 popover_bounds: None,
5601 popover_state: InlineBlamePopoverState {
5602 scroll_handle: ScrollHandle::new(),
5603 commit_message: details,
5604 markdown,
5605 },
5606 });
5607 }
5608 }
5609
5610 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5611 if let Some(state) = &mut self.inline_blame_popover {
5612 if state.show_task.is_some() {
5613 self.inline_blame_popover.take();
5614 cx.notify();
5615 } else {
5616 let hide_task = cx.spawn(async move |editor, cx| {
5617 cx.background_executor()
5618 .timer(std::time::Duration::from_millis(100))
5619 .await;
5620 editor
5621 .update(cx, |editor, cx| {
5622 editor.inline_blame_popover.take();
5623 cx.notify();
5624 })
5625 .ok();
5626 });
5627 state.hide_task = Some(hide_task);
5628 }
5629 }
5630 }
5631
5632 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5633 if self.pending_rename.is_some() {
5634 return None;
5635 }
5636
5637 let provider = self.semantics_provider.clone()?;
5638 let buffer = self.buffer.read(cx);
5639 let newest_selection = self.selections.newest_anchor().clone();
5640 let cursor_position = newest_selection.head();
5641 let (cursor_buffer, cursor_buffer_position) =
5642 buffer.text_anchor_for_position(cursor_position, cx)?;
5643 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5644 if cursor_buffer != tail_buffer {
5645 return None;
5646 }
5647 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5648 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5649 cx.background_executor()
5650 .timer(Duration::from_millis(debounce))
5651 .await;
5652
5653 let highlights = if let Some(highlights) = cx
5654 .update(|cx| {
5655 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5656 })
5657 .ok()
5658 .flatten()
5659 {
5660 highlights.await.log_err()
5661 } else {
5662 None
5663 };
5664
5665 if let Some(highlights) = highlights {
5666 this.update(cx, |this, cx| {
5667 if this.pending_rename.is_some() {
5668 return;
5669 }
5670
5671 let buffer_id = cursor_position.buffer_id;
5672 let buffer = this.buffer.read(cx);
5673 if !buffer
5674 .text_anchor_for_position(cursor_position, cx)
5675 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5676 {
5677 return;
5678 }
5679
5680 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5681 let mut write_ranges = Vec::new();
5682 let mut read_ranges = Vec::new();
5683 for highlight in highlights {
5684 for (excerpt_id, excerpt_range) in
5685 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5686 {
5687 let start = highlight
5688 .range
5689 .start
5690 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5691 let end = highlight
5692 .range
5693 .end
5694 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5695 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5696 continue;
5697 }
5698
5699 let range = Anchor {
5700 buffer_id,
5701 excerpt_id,
5702 text_anchor: start,
5703 diff_base_anchor: None,
5704 }..Anchor {
5705 buffer_id,
5706 excerpt_id,
5707 text_anchor: end,
5708 diff_base_anchor: None,
5709 };
5710 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5711 write_ranges.push(range);
5712 } else {
5713 read_ranges.push(range);
5714 }
5715 }
5716 }
5717
5718 this.highlight_background::<DocumentHighlightRead>(
5719 &read_ranges,
5720 |theme| theme.editor_document_highlight_read_background,
5721 cx,
5722 );
5723 this.highlight_background::<DocumentHighlightWrite>(
5724 &write_ranges,
5725 |theme| theme.editor_document_highlight_write_background,
5726 cx,
5727 );
5728 cx.notify();
5729 })
5730 .log_err();
5731 }
5732 }));
5733 None
5734 }
5735
5736 fn prepare_highlight_query_from_selection(
5737 &mut self,
5738 cx: &mut Context<Editor>,
5739 ) -> Option<(String, Range<Anchor>)> {
5740 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5741 return None;
5742 }
5743 if !EditorSettings::get_global(cx).selection_highlight {
5744 return None;
5745 }
5746 if self.selections.count() != 1 || self.selections.line_mode {
5747 return None;
5748 }
5749 let selection = self.selections.newest::<Point>(cx);
5750 if selection.is_empty() || selection.start.row != selection.end.row {
5751 return None;
5752 }
5753 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5754 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5755 let query = multi_buffer_snapshot
5756 .text_for_range(selection_anchor_range.clone())
5757 .collect::<String>();
5758 if query.trim().is_empty() {
5759 return None;
5760 }
5761 Some((query, selection_anchor_range))
5762 }
5763
5764 fn update_selection_occurrence_highlights(
5765 &mut self,
5766 query_text: String,
5767 query_range: Range<Anchor>,
5768 multi_buffer_range_to_query: Range<Point>,
5769 use_debounce: bool,
5770 window: &mut Window,
5771 cx: &mut Context<Editor>,
5772 ) -> Task<()> {
5773 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5774 cx.spawn_in(window, async move |editor, cx| {
5775 if use_debounce {
5776 cx.background_executor()
5777 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5778 .await;
5779 }
5780 let match_task = cx.background_spawn(async move {
5781 let buffer_ranges = multi_buffer_snapshot
5782 .range_to_buffer_ranges(multi_buffer_range_to_query)
5783 .into_iter()
5784 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5785 let mut match_ranges = Vec::new();
5786 let Ok(regex) = project::search::SearchQuery::text(
5787 query_text.clone(),
5788 false,
5789 false,
5790 false,
5791 Default::default(),
5792 Default::default(),
5793 false,
5794 None,
5795 ) else {
5796 return Vec::default();
5797 };
5798 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5799 match_ranges.extend(
5800 regex
5801 .search(&buffer_snapshot, Some(search_range.clone()))
5802 .await
5803 .into_iter()
5804 .filter_map(|match_range| {
5805 let match_start = buffer_snapshot
5806 .anchor_after(search_range.start + match_range.start);
5807 let match_end = buffer_snapshot
5808 .anchor_before(search_range.start + match_range.end);
5809 let match_anchor_range = Anchor::range_in_buffer(
5810 excerpt_id,
5811 buffer_snapshot.remote_id(),
5812 match_start..match_end,
5813 );
5814 (match_anchor_range != query_range).then_some(match_anchor_range)
5815 }),
5816 );
5817 }
5818 match_ranges
5819 });
5820 let match_ranges = match_task.await;
5821 editor
5822 .update_in(cx, |editor, _, cx| {
5823 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5824 if !match_ranges.is_empty() {
5825 editor.highlight_background::<SelectedTextHighlight>(
5826 &match_ranges,
5827 |theme| theme.editor_document_highlight_bracket_background,
5828 cx,
5829 )
5830 }
5831 })
5832 .log_err();
5833 })
5834 }
5835
5836 fn refresh_selected_text_highlights(
5837 &mut self,
5838 on_buffer_edit: bool,
5839 window: &mut Window,
5840 cx: &mut Context<Editor>,
5841 ) {
5842 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5843 else {
5844 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5845 self.quick_selection_highlight_task.take();
5846 self.debounced_selection_highlight_task.take();
5847 return;
5848 };
5849 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5850 if on_buffer_edit
5851 || self
5852 .quick_selection_highlight_task
5853 .as_ref()
5854 .map_or(true, |(prev_anchor_range, _)| {
5855 prev_anchor_range != &query_range
5856 })
5857 {
5858 let multi_buffer_visible_start = self
5859 .scroll_manager
5860 .anchor()
5861 .anchor
5862 .to_point(&multi_buffer_snapshot);
5863 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5864 multi_buffer_visible_start
5865 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5866 Bias::Left,
5867 );
5868 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5869 self.quick_selection_highlight_task = Some((
5870 query_range.clone(),
5871 self.update_selection_occurrence_highlights(
5872 query_text.clone(),
5873 query_range.clone(),
5874 multi_buffer_visible_range,
5875 false,
5876 window,
5877 cx,
5878 ),
5879 ));
5880 }
5881 if on_buffer_edit
5882 || self
5883 .debounced_selection_highlight_task
5884 .as_ref()
5885 .map_or(true, |(prev_anchor_range, _)| {
5886 prev_anchor_range != &query_range
5887 })
5888 {
5889 let multi_buffer_start = multi_buffer_snapshot
5890 .anchor_before(0)
5891 .to_point(&multi_buffer_snapshot);
5892 let multi_buffer_end = multi_buffer_snapshot
5893 .anchor_after(multi_buffer_snapshot.len())
5894 .to_point(&multi_buffer_snapshot);
5895 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5896 self.debounced_selection_highlight_task = Some((
5897 query_range.clone(),
5898 self.update_selection_occurrence_highlights(
5899 query_text,
5900 query_range,
5901 multi_buffer_full_range,
5902 true,
5903 window,
5904 cx,
5905 ),
5906 ));
5907 }
5908 }
5909
5910 pub fn refresh_inline_completion(
5911 &mut self,
5912 debounce: bool,
5913 user_requested: bool,
5914 window: &mut Window,
5915 cx: &mut Context<Self>,
5916 ) -> Option<()> {
5917 let provider = self.edit_prediction_provider()?;
5918 let cursor = self.selections.newest_anchor().head();
5919 let (buffer, cursor_buffer_position) =
5920 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5921
5922 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5923 self.discard_inline_completion(false, cx);
5924 return None;
5925 }
5926
5927 if !user_requested
5928 && (!self.should_show_edit_predictions()
5929 || !self.is_focused(window)
5930 || buffer.read(cx).is_empty())
5931 {
5932 self.discard_inline_completion(false, cx);
5933 return None;
5934 }
5935
5936 self.update_visible_inline_completion(window, cx);
5937 provider.refresh(
5938 self.project.clone(),
5939 buffer,
5940 cursor_buffer_position,
5941 debounce,
5942 cx,
5943 );
5944 Some(())
5945 }
5946
5947 fn show_edit_predictions_in_menu(&self) -> bool {
5948 match self.edit_prediction_settings {
5949 EditPredictionSettings::Disabled => false,
5950 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5951 }
5952 }
5953
5954 pub fn edit_predictions_enabled(&self) -> bool {
5955 match self.edit_prediction_settings {
5956 EditPredictionSettings::Disabled => false,
5957 EditPredictionSettings::Enabled { .. } => true,
5958 }
5959 }
5960
5961 fn edit_prediction_requires_modifier(&self) -> bool {
5962 match self.edit_prediction_settings {
5963 EditPredictionSettings::Disabled => false,
5964 EditPredictionSettings::Enabled {
5965 preview_requires_modifier,
5966 ..
5967 } => preview_requires_modifier,
5968 }
5969 }
5970
5971 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5972 if self.edit_prediction_provider.is_none() {
5973 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5974 } else {
5975 let selection = self.selections.newest_anchor();
5976 let cursor = selection.head();
5977
5978 if let Some((buffer, cursor_buffer_position)) =
5979 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5980 {
5981 self.edit_prediction_settings =
5982 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5983 }
5984 }
5985 }
5986
5987 fn edit_prediction_settings_at_position(
5988 &self,
5989 buffer: &Entity<Buffer>,
5990 buffer_position: language::Anchor,
5991 cx: &App,
5992 ) -> EditPredictionSettings {
5993 if !self.mode.is_full()
5994 || !self.show_inline_completions_override.unwrap_or(true)
5995 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5996 {
5997 return EditPredictionSettings::Disabled;
5998 }
5999
6000 let buffer = buffer.read(cx);
6001
6002 let file = buffer.file();
6003
6004 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
6005 return EditPredictionSettings::Disabled;
6006 };
6007
6008 let by_provider = matches!(
6009 self.menu_inline_completions_policy,
6010 MenuInlineCompletionsPolicy::ByProvider
6011 );
6012
6013 let show_in_menu = by_provider
6014 && self
6015 .edit_prediction_provider
6016 .as_ref()
6017 .map_or(false, |provider| {
6018 provider.provider.show_completions_in_menu()
6019 });
6020
6021 let preview_requires_modifier =
6022 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6023
6024 EditPredictionSettings::Enabled {
6025 show_in_menu,
6026 preview_requires_modifier,
6027 }
6028 }
6029
6030 fn should_show_edit_predictions(&self) -> bool {
6031 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6032 }
6033
6034 pub fn edit_prediction_preview_is_active(&self) -> bool {
6035 matches!(
6036 self.edit_prediction_preview,
6037 EditPredictionPreview::Active { .. }
6038 )
6039 }
6040
6041 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6042 let cursor = self.selections.newest_anchor().head();
6043 if let Some((buffer, cursor_position)) =
6044 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6045 {
6046 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6047 } else {
6048 false
6049 }
6050 }
6051
6052 fn edit_predictions_enabled_in_buffer(
6053 &self,
6054 buffer: &Entity<Buffer>,
6055 buffer_position: language::Anchor,
6056 cx: &App,
6057 ) -> bool {
6058 maybe!({
6059 if self.read_only(cx) {
6060 return Some(false);
6061 }
6062 let provider = self.edit_prediction_provider()?;
6063 if !provider.is_enabled(&buffer, buffer_position, cx) {
6064 return Some(false);
6065 }
6066 let buffer = buffer.read(cx);
6067 let Some(file) = buffer.file() else {
6068 return Some(true);
6069 };
6070 let settings = all_language_settings(Some(file), cx);
6071 Some(settings.edit_predictions_enabled_for_file(file, cx))
6072 })
6073 .unwrap_or(false)
6074 }
6075
6076 fn cycle_inline_completion(
6077 &mut self,
6078 direction: Direction,
6079 window: &mut Window,
6080 cx: &mut Context<Self>,
6081 ) -> Option<()> {
6082 let provider = self.edit_prediction_provider()?;
6083 let cursor = self.selections.newest_anchor().head();
6084 let (buffer, cursor_buffer_position) =
6085 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6086 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6087 return None;
6088 }
6089
6090 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6091 self.update_visible_inline_completion(window, cx);
6092
6093 Some(())
6094 }
6095
6096 pub fn show_inline_completion(
6097 &mut self,
6098 _: &ShowEditPrediction,
6099 window: &mut Window,
6100 cx: &mut Context<Self>,
6101 ) {
6102 if !self.has_active_inline_completion() {
6103 self.refresh_inline_completion(false, true, window, cx);
6104 return;
6105 }
6106
6107 self.update_visible_inline_completion(window, cx);
6108 }
6109
6110 pub fn display_cursor_names(
6111 &mut self,
6112 _: &DisplayCursorNames,
6113 window: &mut Window,
6114 cx: &mut Context<Self>,
6115 ) {
6116 self.show_cursor_names(window, cx);
6117 }
6118
6119 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6120 self.show_cursor_names = true;
6121 cx.notify();
6122 cx.spawn_in(window, async move |this, cx| {
6123 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6124 this.update(cx, |this, cx| {
6125 this.show_cursor_names = false;
6126 cx.notify()
6127 })
6128 .ok()
6129 })
6130 .detach();
6131 }
6132
6133 pub fn next_edit_prediction(
6134 &mut self,
6135 _: &NextEditPrediction,
6136 window: &mut Window,
6137 cx: &mut Context<Self>,
6138 ) {
6139 if self.has_active_inline_completion() {
6140 self.cycle_inline_completion(Direction::Next, window, cx);
6141 } else {
6142 let is_copilot_disabled = self
6143 .refresh_inline_completion(false, true, window, cx)
6144 .is_none();
6145 if is_copilot_disabled {
6146 cx.propagate();
6147 }
6148 }
6149 }
6150
6151 pub fn previous_edit_prediction(
6152 &mut self,
6153 _: &PreviousEditPrediction,
6154 window: &mut Window,
6155 cx: &mut Context<Self>,
6156 ) {
6157 if self.has_active_inline_completion() {
6158 self.cycle_inline_completion(Direction::Prev, window, cx);
6159 } else {
6160 let is_copilot_disabled = self
6161 .refresh_inline_completion(false, true, window, cx)
6162 .is_none();
6163 if is_copilot_disabled {
6164 cx.propagate();
6165 }
6166 }
6167 }
6168
6169 pub fn accept_edit_prediction(
6170 &mut self,
6171 _: &AcceptEditPrediction,
6172 window: &mut Window,
6173 cx: &mut Context<Self>,
6174 ) {
6175 if self.show_edit_predictions_in_menu() {
6176 self.hide_context_menu(window, cx);
6177 }
6178
6179 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6180 return;
6181 };
6182
6183 self.report_inline_completion_event(
6184 active_inline_completion.completion_id.clone(),
6185 true,
6186 cx,
6187 );
6188
6189 match &active_inline_completion.completion {
6190 InlineCompletion::Move { target, .. } => {
6191 let target = *target;
6192
6193 if let Some(position_map) = &self.last_position_map {
6194 if position_map
6195 .visible_row_range
6196 .contains(&target.to_display_point(&position_map.snapshot).row())
6197 || !self.edit_prediction_requires_modifier()
6198 {
6199 self.unfold_ranges(&[target..target], true, false, cx);
6200 // Note that this is also done in vim's handler of the Tab action.
6201 self.change_selections(
6202 Some(Autoscroll::newest()),
6203 window,
6204 cx,
6205 |selections| {
6206 selections.select_anchor_ranges([target..target]);
6207 },
6208 );
6209 self.clear_row_highlights::<EditPredictionPreview>();
6210
6211 self.edit_prediction_preview
6212 .set_previous_scroll_position(None);
6213 } else {
6214 self.edit_prediction_preview
6215 .set_previous_scroll_position(Some(
6216 position_map.snapshot.scroll_anchor,
6217 ));
6218
6219 self.highlight_rows::<EditPredictionPreview>(
6220 target..target,
6221 cx.theme().colors().editor_highlighted_line_background,
6222 RowHighlightOptions {
6223 autoscroll: true,
6224 ..Default::default()
6225 },
6226 cx,
6227 );
6228 self.request_autoscroll(Autoscroll::fit(), cx);
6229 }
6230 }
6231 }
6232 InlineCompletion::Edit { edits, .. } => {
6233 if let Some(provider) = self.edit_prediction_provider() {
6234 provider.accept(cx);
6235 }
6236
6237 let snapshot = self.buffer.read(cx).snapshot(cx);
6238 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6239
6240 self.buffer.update(cx, |buffer, cx| {
6241 buffer.edit(edits.iter().cloned(), None, cx)
6242 });
6243
6244 self.change_selections(None, window, cx, |s| {
6245 s.select_anchor_ranges([last_edit_end..last_edit_end])
6246 });
6247
6248 self.update_visible_inline_completion(window, cx);
6249 if self.active_inline_completion.is_none() {
6250 self.refresh_inline_completion(true, true, window, cx);
6251 }
6252
6253 cx.notify();
6254 }
6255 }
6256
6257 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6258 }
6259
6260 pub fn accept_partial_inline_completion(
6261 &mut self,
6262 _: &AcceptPartialEditPrediction,
6263 window: &mut Window,
6264 cx: &mut Context<Self>,
6265 ) {
6266 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6267 return;
6268 };
6269 if self.selections.count() != 1 {
6270 return;
6271 }
6272
6273 self.report_inline_completion_event(
6274 active_inline_completion.completion_id.clone(),
6275 true,
6276 cx,
6277 );
6278
6279 match &active_inline_completion.completion {
6280 InlineCompletion::Move { target, .. } => {
6281 let target = *target;
6282 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6283 selections.select_anchor_ranges([target..target]);
6284 });
6285 }
6286 InlineCompletion::Edit { edits, .. } => {
6287 // Find an insertion that starts at the cursor position.
6288 let snapshot = self.buffer.read(cx).snapshot(cx);
6289 let cursor_offset = self.selections.newest::<usize>(cx).head();
6290 let insertion = edits.iter().find_map(|(range, text)| {
6291 let range = range.to_offset(&snapshot);
6292 if range.is_empty() && range.start == cursor_offset {
6293 Some(text)
6294 } else {
6295 None
6296 }
6297 });
6298
6299 if let Some(text) = insertion {
6300 let mut partial_completion = text
6301 .chars()
6302 .by_ref()
6303 .take_while(|c| c.is_alphabetic())
6304 .collect::<String>();
6305 if partial_completion.is_empty() {
6306 partial_completion = text
6307 .chars()
6308 .by_ref()
6309 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6310 .collect::<String>();
6311 }
6312
6313 cx.emit(EditorEvent::InputHandled {
6314 utf16_range_to_replace: None,
6315 text: partial_completion.clone().into(),
6316 });
6317
6318 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6319
6320 self.refresh_inline_completion(true, true, window, cx);
6321 cx.notify();
6322 } else {
6323 self.accept_edit_prediction(&Default::default(), window, cx);
6324 }
6325 }
6326 }
6327 }
6328
6329 fn discard_inline_completion(
6330 &mut self,
6331 should_report_inline_completion_event: bool,
6332 cx: &mut Context<Self>,
6333 ) -> bool {
6334 if should_report_inline_completion_event {
6335 let completion_id = self
6336 .active_inline_completion
6337 .as_ref()
6338 .and_then(|active_completion| active_completion.completion_id.clone());
6339
6340 self.report_inline_completion_event(completion_id, false, cx);
6341 }
6342
6343 if let Some(provider) = self.edit_prediction_provider() {
6344 provider.discard(cx);
6345 }
6346
6347 self.take_active_inline_completion(cx)
6348 }
6349
6350 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6351 let Some(provider) = self.edit_prediction_provider() else {
6352 return;
6353 };
6354
6355 let Some((_, buffer, _)) = self
6356 .buffer
6357 .read(cx)
6358 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6359 else {
6360 return;
6361 };
6362
6363 let extension = buffer
6364 .read(cx)
6365 .file()
6366 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6367
6368 let event_type = match accepted {
6369 true => "Edit Prediction Accepted",
6370 false => "Edit Prediction Discarded",
6371 };
6372 telemetry::event!(
6373 event_type,
6374 provider = provider.name(),
6375 prediction_id = id,
6376 suggestion_accepted = accepted,
6377 file_extension = extension,
6378 );
6379 }
6380
6381 pub fn has_active_inline_completion(&self) -> bool {
6382 self.active_inline_completion.is_some()
6383 }
6384
6385 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6386 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6387 return false;
6388 };
6389
6390 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6391 self.clear_highlights::<InlineCompletionHighlight>(cx);
6392 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6393 true
6394 }
6395
6396 /// Returns true when we're displaying the edit prediction popover below the cursor
6397 /// like we are not previewing and the LSP autocomplete menu is visible
6398 /// or we are in `when_holding_modifier` mode.
6399 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6400 if self.edit_prediction_preview_is_active()
6401 || !self.show_edit_predictions_in_menu()
6402 || !self.edit_predictions_enabled()
6403 {
6404 return false;
6405 }
6406
6407 if self.has_visible_completions_menu() {
6408 return true;
6409 }
6410
6411 has_completion && self.edit_prediction_requires_modifier()
6412 }
6413
6414 fn handle_modifiers_changed(
6415 &mut self,
6416 modifiers: Modifiers,
6417 position_map: &PositionMap,
6418 window: &mut Window,
6419 cx: &mut Context<Self>,
6420 ) {
6421 if self.show_edit_predictions_in_menu() {
6422 self.update_edit_prediction_preview(&modifiers, window, cx);
6423 }
6424
6425 self.update_selection_mode(&modifiers, position_map, window, cx);
6426
6427 let mouse_position = window.mouse_position();
6428 if !position_map.text_hitbox.is_hovered(window) {
6429 return;
6430 }
6431
6432 self.update_hovered_link(
6433 position_map.point_for_position(mouse_position),
6434 &position_map.snapshot,
6435 modifiers,
6436 window,
6437 cx,
6438 )
6439 }
6440
6441 fn update_selection_mode(
6442 &mut self,
6443 modifiers: &Modifiers,
6444 position_map: &PositionMap,
6445 window: &mut Window,
6446 cx: &mut Context<Self>,
6447 ) {
6448 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6449 return;
6450 }
6451
6452 let mouse_position = window.mouse_position();
6453 let point_for_position = position_map.point_for_position(mouse_position);
6454 let position = point_for_position.previous_valid;
6455
6456 self.select(
6457 SelectPhase::BeginColumnar {
6458 position,
6459 reset: false,
6460 goal_column: point_for_position.exact_unclipped.column(),
6461 },
6462 window,
6463 cx,
6464 );
6465 }
6466
6467 fn update_edit_prediction_preview(
6468 &mut self,
6469 modifiers: &Modifiers,
6470 window: &mut Window,
6471 cx: &mut Context<Self>,
6472 ) {
6473 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6474 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6475 return;
6476 };
6477
6478 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6479 if matches!(
6480 self.edit_prediction_preview,
6481 EditPredictionPreview::Inactive { .. }
6482 ) {
6483 self.edit_prediction_preview = EditPredictionPreview::Active {
6484 previous_scroll_position: None,
6485 since: Instant::now(),
6486 };
6487
6488 self.update_visible_inline_completion(window, cx);
6489 cx.notify();
6490 }
6491 } else if let EditPredictionPreview::Active {
6492 previous_scroll_position,
6493 since,
6494 } = self.edit_prediction_preview
6495 {
6496 if let (Some(previous_scroll_position), Some(position_map)) =
6497 (previous_scroll_position, self.last_position_map.as_ref())
6498 {
6499 self.set_scroll_position(
6500 previous_scroll_position
6501 .scroll_position(&position_map.snapshot.display_snapshot),
6502 window,
6503 cx,
6504 );
6505 }
6506
6507 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6508 released_too_fast: since.elapsed() < Duration::from_millis(200),
6509 };
6510 self.clear_row_highlights::<EditPredictionPreview>();
6511 self.update_visible_inline_completion(window, cx);
6512 cx.notify();
6513 }
6514 }
6515
6516 fn update_visible_inline_completion(
6517 &mut self,
6518 _window: &mut Window,
6519 cx: &mut Context<Self>,
6520 ) -> Option<()> {
6521 let selection = self.selections.newest_anchor();
6522 let cursor = selection.head();
6523 let multibuffer = self.buffer.read(cx).snapshot(cx);
6524 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6525 let excerpt_id = cursor.excerpt_id;
6526
6527 let show_in_menu = self.show_edit_predictions_in_menu();
6528 let completions_menu_has_precedence = !show_in_menu
6529 && (self.context_menu.borrow().is_some()
6530 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6531
6532 if completions_menu_has_precedence
6533 || !offset_selection.is_empty()
6534 || self
6535 .active_inline_completion
6536 .as_ref()
6537 .map_or(false, |completion| {
6538 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6539 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6540 !invalidation_range.contains(&offset_selection.head())
6541 })
6542 {
6543 self.discard_inline_completion(false, cx);
6544 return None;
6545 }
6546
6547 self.take_active_inline_completion(cx);
6548 let Some(provider) = self.edit_prediction_provider() else {
6549 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6550 return None;
6551 };
6552
6553 let (buffer, cursor_buffer_position) =
6554 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6555
6556 self.edit_prediction_settings =
6557 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6558
6559 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6560
6561 if self.edit_prediction_indent_conflict {
6562 let cursor_point = cursor.to_point(&multibuffer);
6563
6564 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6565
6566 if let Some((_, indent)) = indents.iter().next() {
6567 if indent.len == cursor_point.column {
6568 self.edit_prediction_indent_conflict = false;
6569 }
6570 }
6571 }
6572
6573 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6574 let edits = inline_completion
6575 .edits
6576 .into_iter()
6577 .flat_map(|(range, new_text)| {
6578 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6579 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6580 Some((start..end, new_text))
6581 })
6582 .collect::<Vec<_>>();
6583 if edits.is_empty() {
6584 return None;
6585 }
6586
6587 let first_edit_start = edits.first().unwrap().0.start;
6588 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6589 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6590
6591 let last_edit_end = edits.last().unwrap().0.end;
6592 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6593 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6594
6595 let cursor_row = cursor.to_point(&multibuffer).row;
6596
6597 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6598
6599 let mut inlay_ids = Vec::new();
6600 let invalidation_row_range;
6601 let move_invalidation_row_range = if cursor_row < edit_start_row {
6602 Some(cursor_row..edit_end_row)
6603 } else if cursor_row > edit_end_row {
6604 Some(edit_start_row..cursor_row)
6605 } else {
6606 None
6607 };
6608 let is_move =
6609 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6610 let completion = if is_move {
6611 invalidation_row_range =
6612 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6613 let target = first_edit_start;
6614 InlineCompletion::Move { target, snapshot }
6615 } else {
6616 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6617 && !self.inline_completions_hidden_for_vim_mode;
6618
6619 if show_completions_in_buffer {
6620 if edits
6621 .iter()
6622 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6623 {
6624 let mut inlays = Vec::new();
6625 for (range, new_text) in &edits {
6626 let inlay = Inlay::inline_completion(
6627 post_inc(&mut self.next_inlay_id),
6628 range.start,
6629 new_text.as_str(),
6630 );
6631 inlay_ids.push(inlay.id);
6632 inlays.push(inlay);
6633 }
6634
6635 self.splice_inlays(&[], inlays, cx);
6636 } else {
6637 let background_color = cx.theme().status().deleted_background;
6638 self.highlight_text::<InlineCompletionHighlight>(
6639 edits.iter().map(|(range, _)| range.clone()).collect(),
6640 HighlightStyle {
6641 background_color: Some(background_color),
6642 ..Default::default()
6643 },
6644 cx,
6645 );
6646 }
6647 }
6648
6649 invalidation_row_range = edit_start_row..edit_end_row;
6650
6651 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6652 if provider.show_tab_accept_marker() {
6653 EditDisplayMode::TabAccept
6654 } else {
6655 EditDisplayMode::Inline
6656 }
6657 } else {
6658 EditDisplayMode::DiffPopover
6659 };
6660
6661 InlineCompletion::Edit {
6662 edits,
6663 edit_preview: inline_completion.edit_preview,
6664 display_mode,
6665 snapshot,
6666 }
6667 };
6668
6669 let invalidation_range = multibuffer
6670 .anchor_before(Point::new(invalidation_row_range.start, 0))
6671 ..multibuffer.anchor_after(Point::new(
6672 invalidation_row_range.end,
6673 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6674 ));
6675
6676 self.stale_inline_completion_in_menu = None;
6677 self.active_inline_completion = Some(InlineCompletionState {
6678 inlay_ids,
6679 completion,
6680 completion_id: inline_completion.id,
6681 invalidation_range,
6682 });
6683
6684 cx.notify();
6685
6686 Some(())
6687 }
6688
6689 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6690 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6691 }
6692
6693 fn render_code_actions_indicator(
6694 &self,
6695 _style: &EditorStyle,
6696 row: DisplayRow,
6697 is_active: bool,
6698 breakpoint: Option<&(Anchor, Breakpoint)>,
6699 cx: &mut Context<Self>,
6700 ) -> Option<IconButton> {
6701 let color = Color::Muted;
6702 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6703 let show_tooltip = !self.context_menu_visible();
6704
6705 if self.available_code_actions.is_some() {
6706 Some(
6707 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6708 .shape(ui::IconButtonShape::Square)
6709 .icon_size(IconSize::XSmall)
6710 .icon_color(color)
6711 .toggle_state(is_active)
6712 .when(show_tooltip, |this| {
6713 this.tooltip({
6714 let focus_handle = self.focus_handle.clone();
6715 move |window, cx| {
6716 Tooltip::for_action_in(
6717 "Toggle Code Actions",
6718 &ToggleCodeActions {
6719 deployed_from_indicator: None,
6720 quick_launch: false,
6721 },
6722 &focus_handle,
6723 window,
6724 cx,
6725 )
6726 }
6727 })
6728 })
6729 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
6730 let quick_launch = e.down.button == MouseButton::Left;
6731 window.focus(&editor.focus_handle(cx));
6732 editor.toggle_code_actions(
6733 &ToggleCodeActions {
6734 deployed_from_indicator: Some(row),
6735 quick_launch,
6736 },
6737 window,
6738 cx,
6739 );
6740 }))
6741 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6742 editor.set_breakpoint_context_menu(
6743 row,
6744 position,
6745 event.down.position,
6746 window,
6747 cx,
6748 );
6749 })),
6750 )
6751 } else {
6752 None
6753 }
6754 }
6755
6756 fn clear_tasks(&mut self) {
6757 self.tasks.clear()
6758 }
6759
6760 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6761 if self.tasks.insert(key, value).is_some() {
6762 // This case should hopefully be rare, but just in case...
6763 log::error!(
6764 "multiple different run targets found on a single line, only the last target will be rendered"
6765 )
6766 }
6767 }
6768
6769 /// Get all display points of breakpoints that will be rendered within editor
6770 ///
6771 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6772 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6773 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6774 fn active_breakpoints(
6775 &self,
6776 range: Range<DisplayRow>,
6777 window: &mut Window,
6778 cx: &mut Context<Self>,
6779 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6780 let mut breakpoint_display_points = HashMap::default();
6781
6782 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6783 return breakpoint_display_points;
6784 };
6785
6786 let snapshot = self.snapshot(window, cx);
6787
6788 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6789 let Some(project) = self.project.as_ref() else {
6790 return breakpoint_display_points;
6791 };
6792
6793 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6794 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6795
6796 for (buffer_snapshot, range, excerpt_id) in
6797 multi_buffer_snapshot.range_to_buffer_ranges(range)
6798 {
6799 let Some(buffer) = project.read_with(cx, |this, cx| {
6800 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6801 }) else {
6802 continue;
6803 };
6804 let breakpoints = breakpoint_store.read(cx).breakpoints(
6805 &buffer,
6806 Some(
6807 buffer_snapshot.anchor_before(range.start)
6808 ..buffer_snapshot.anchor_after(range.end),
6809 ),
6810 buffer_snapshot,
6811 cx,
6812 );
6813 for (anchor, breakpoint) in breakpoints {
6814 let multi_buffer_anchor =
6815 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6816 let position = multi_buffer_anchor
6817 .to_point(&multi_buffer_snapshot)
6818 .to_display_point(&snapshot);
6819
6820 breakpoint_display_points
6821 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6822 }
6823 }
6824
6825 breakpoint_display_points
6826 }
6827
6828 fn breakpoint_context_menu(
6829 &self,
6830 anchor: Anchor,
6831 window: &mut Window,
6832 cx: &mut Context<Self>,
6833 ) -> Entity<ui::ContextMenu> {
6834 let weak_editor = cx.weak_entity();
6835 let focus_handle = self.focus_handle(cx);
6836
6837 let row = self
6838 .buffer
6839 .read(cx)
6840 .snapshot(cx)
6841 .summary_for_anchor::<Point>(&anchor)
6842 .row;
6843
6844 let breakpoint = self
6845 .breakpoint_at_row(row, window, cx)
6846 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6847
6848 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6849 "Edit Log Breakpoint"
6850 } else {
6851 "Set Log Breakpoint"
6852 };
6853
6854 let condition_breakpoint_msg = if breakpoint
6855 .as_ref()
6856 .is_some_and(|bp| bp.1.condition.is_some())
6857 {
6858 "Edit Condition Breakpoint"
6859 } else {
6860 "Set Condition Breakpoint"
6861 };
6862
6863 let hit_condition_breakpoint_msg = if breakpoint
6864 .as_ref()
6865 .is_some_and(|bp| bp.1.hit_condition.is_some())
6866 {
6867 "Edit Hit Condition Breakpoint"
6868 } else {
6869 "Set Hit Condition Breakpoint"
6870 };
6871
6872 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6873 "Unset Breakpoint"
6874 } else {
6875 "Set Breakpoint"
6876 };
6877
6878 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6879 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6880
6881 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6882 BreakpointState::Enabled => Some("Disable"),
6883 BreakpointState::Disabled => Some("Enable"),
6884 });
6885
6886 let (anchor, breakpoint) =
6887 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6888
6889 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6890 menu.on_blur_subscription(Subscription::new(|| {}))
6891 .context(focus_handle)
6892 .when(run_to_cursor, |this| {
6893 let weak_editor = weak_editor.clone();
6894 this.entry("Run to cursor", None, move |window, cx| {
6895 weak_editor
6896 .update(cx, |editor, cx| {
6897 editor.change_selections(None, window, cx, |s| {
6898 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6899 });
6900 })
6901 .ok();
6902
6903 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6904 })
6905 .separator()
6906 })
6907 .when_some(toggle_state_msg, |this, msg| {
6908 this.entry(msg, None, {
6909 let weak_editor = weak_editor.clone();
6910 let breakpoint = breakpoint.clone();
6911 move |_window, cx| {
6912 weak_editor
6913 .update(cx, |this, cx| {
6914 this.edit_breakpoint_at_anchor(
6915 anchor,
6916 breakpoint.as_ref().clone(),
6917 BreakpointEditAction::InvertState,
6918 cx,
6919 );
6920 })
6921 .log_err();
6922 }
6923 })
6924 })
6925 .entry(set_breakpoint_msg, None, {
6926 let weak_editor = weak_editor.clone();
6927 let breakpoint = breakpoint.clone();
6928 move |_window, cx| {
6929 weak_editor
6930 .update(cx, |this, cx| {
6931 this.edit_breakpoint_at_anchor(
6932 anchor,
6933 breakpoint.as_ref().clone(),
6934 BreakpointEditAction::Toggle,
6935 cx,
6936 );
6937 })
6938 .log_err();
6939 }
6940 })
6941 .entry(log_breakpoint_msg, None, {
6942 let breakpoint = breakpoint.clone();
6943 let weak_editor = weak_editor.clone();
6944 move |window, cx| {
6945 weak_editor
6946 .update(cx, |this, cx| {
6947 this.add_edit_breakpoint_block(
6948 anchor,
6949 breakpoint.as_ref(),
6950 BreakpointPromptEditAction::Log,
6951 window,
6952 cx,
6953 );
6954 })
6955 .log_err();
6956 }
6957 })
6958 .entry(condition_breakpoint_msg, None, {
6959 let breakpoint = breakpoint.clone();
6960 let weak_editor = weak_editor.clone();
6961 move |window, cx| {
6962 weak_editor
6963 .update(cx, |this, cx| {
6964 this.add_edit_breakpoint_block(
6965 anchor,
6966 breakpoint.as_ref(),
6967 BreakpointPromptEditAction::Condition,
6968 window,
6969 cx,
6970 );
6971 })
6972 .log_err();
6973 }
6974 })
6975 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6976 weak_editor
6977 .update(cx, |this, cx| {
6978 this.add_edit_breakpoint_block(
6979 anchor,
6980 breakpoint.as_ref(),
6981 BreakpointPromptEditAction::HitCondition,
6982 window,
6983 cx,
6984 );
6985 })
6986 .log_err();
6987 })
6988 })
6989 }
6990
6991 fn render_breakpoint(
6992 &self,
6993 position: Anchor,
6994 row: DisplayRow,
6995 breakpoint: &Breakpoint,
6996 cx: &mut Context<Self>,
6997 ) -> IconButton {
6998 // Is it a breakpoint that shows up when hovering over gutter?
6999 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
7000 (false, false),
7001 |PhantomBreakpointIndicator {
7002 is_active,
7003 display_row,
7004 collides_with_existing_breakpoint,
7005 }| {
7006 (
7007 is_active && display_row == row,
7008 collides_with_existing_breakpoint,
7009 )
7010 },
7011 );
7012
7013 let (color, icon) = {
7014 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7015 (false, false) => ui::IconName::DebugBreakpoint,
7016 (true, false) => ui::IconName::DebugLogBreakpoint,
7017 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7018 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7019 };
7020
7021 let color = if is_phantom {
7022 Color::Hint
7023 } else {
7024 Color::Debugger
7025 };
7026
7027 (color, icon)
7028 };
7029
7030 let breakpoint = Arc::from(breakpoint.clone());
7031
7032 let alt_as_text = gpui::Keystroke {
7033 modifiers: Modifiers::secondary_key(),
7034 ..Default::default()
7035 };
7036 let primary_action_text = if breakpoint.is_disabled() {
7037 "enable"
7038 } else if is_phantom && !collides_with_existing {
7039 "set"
7040 } else {
7041 "unset"
7042 };
7043 let mut primary_text = format!("Click to {primary_action_text}");
7044 if collides_with_existing && !breakpoint.is_disabled() {
7045 use std::fmt::Write;
7046 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7047 }
7048 let primary_text = SharedString::from(primary_text);
7049 let focus_handle = self.focus_handle.clone();
7050 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7051 .icon_size(IconSize::XSmall)
7052 .size(ui::ButtonSize::None)
7053 .icon_color(color)
7054 .style(ButtonStyle::Transparent)
7055 .on_click(cx.listener({
7056 let breakpoint = breakpoint.clone();
7057
7058 move |editor, event: &ClickEvent, window, cx| {
7059 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7060 BreakpointEditAction::InvertState
7061 } else {
7062 BreakpointEditAction::Toggle
7063 };
7064
7065 window.focus(&editor.focus_handle(cx));
7066 editor.edit_breakpoint_at_anchor(
7067 position,
7068 breakpoint.as_ref().clone(),
7069 edit_action,
7070 cx,
7071 );
7072 }
7073 }))
7074 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7075 editor.set_breakpoint_context_menu(
7076 row,
7077 Some(position),
7078 event.down.position,
7079 window,
7080 cx,
7081 );
7082 }))
7083 .tooltip(move |window, cx| {
7084 Tooltip::with_meta_in(
7085 primary_text.clone(),
7086 None,
7087 "Right-click for more options",
7088 &focus_handle,
7089 window,
7090 cx,
7091 )
7092 })
7093 }
7094
7095 fn build_tasks_context(
7096 project: &Entity<Project>,
7097 buffer: &Entity<Buffer>,
7098 buffer_row: u32,
7099 tasks: &Arc<RunnableTasks>,
7100 cx: &mut Context<Self>,
7101 ) -> Task<Option<task::TaskContext>> {
7102 let position = Point::new(buffer_row, tasks.column);
7103 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7104 let location = Location {
7105 buffer: buffer.clone(),
7106 range: range_start..range_start,
7107 };
7108 // Fill in the environmental variables from the tree-sitter captures
7109 let mut captured_task_variables = TaskVariables::default();
7110 for (capture_name, value) in tasks.extra_variables.clone() {
7111 captured_task_variables.insert(
7112 task::VariableName::Custom(capture_name.into()),
7113 value.clone(),
7114 );
7115 }
7116 project.update(cx, |project, cx| {
7117 project.task_store().update(cx, |task_store, cx| {
7118 task_store.task_context_for_location(captured_task_variables, location, cx)
7119 })
7120 })
7121 }
7122
7123 pub fn spawn_nearest_task(
7124 &mut self,
7125 action: &SpawnNearestTask,
7126 window: &mut Window,
7127 cx: &mut Context<Self>,
7128 ) {
7129 let Some((workspace, _)) = self.workspace.clone() else {
7130 return;
7131 };
7132 let Some(project) = self.project.clone() else {
7133 return;
7134 };
7135
7136 // Try to find a closest, enclosing node using tree-sitter that has a
7137 // task
7138 let Some((buffer, buffer_row, tasks)) = self
7139 .find_enclosing_node_task(cx)
7140 // Or find the task that's closest in row-distance.
7141 .or_else(|| self.find_closest_task(cx))
7142 else {
7143 return;
7144 };
7145
7146 let reveal_strategy = action.reveal;
7147 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7148 cx.spawn_in(window, async move |_, cx| {
7149 let context = task_context.await?;
7150 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7151
7152 let resolved = &mut resolved_task.resolved;
7153 resolved.reveal = reveal_strategy;
7154
7155 workspace
7156 .update_in(cx, |workspace, window, cx| {
7157 workspace.schedule_resolved_task(
7158 task_source_kind,
7159 resolved_task,
7160 false,
7161 window,
7162 cx,
7163 );
7164 })
7165 .ok()
7166 })
7167 .detach();
7168 }
7169
7170 fn find_closest_task(
7171 &mut self,
7172 cx: &mut Context<Self>,
7173 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7174 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7175
7176 let ((buffer_id, row), tasks) = self
7177 .tasks
7178 .iter()
7179 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7180
7181 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7182 let tasks = Arc::new(tasks.to_owned());
7183 Some((buffer, *row, tasks))
7184 }
7185
7186 fn find_enclosing_node_task(
7187 &mut self,
7188 cx: &mut Context<Self>,
7189 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7190 let snapshot = self.buffer.read(cx).snapshot(cx);
7191 let offset = self.selections.newest::<usize>(cx).head();
7192 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7193 let buffer_id = excerpt.buffer().remote_id();
7194
7195 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7196 let mut cursor = layer.node().walk();
7197
7198 while cursor.goto_first_child_for_byte(offset).is_some() {
7199 if cursor.node().end_byte() == offset {
7200 cursor.goto_next_sibling();
7201 }
7202 }
7203
7204 // Ascend to the smallest ancestor that contains the range and has a task.
7205 loop {
7206 let node = cursor.node();
7207 let node_range = node.byte_range();
7208 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7209
7210 // Check if this node contains our offset
7211 if node_range.start <= offset && node_range.end >= offset {
7212 // If it contains offset, check for task
7213 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7214 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7215 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7216 }
7217 }
7218
7219 if !cursor.goto_parent() {
7220 break;
7221 }
7222 }
7223 None
7224 }
7225
7226 fn render_run_indicator(
7227 &self,
7228 _style: &EditorStyle,
7229 is_active: bool,
7230 row: DisplayRow,
7231 breakpoint: Option<(Anchor, Breakpoint)>,
7232 cx: &mut Context<Self>,
7233 ) -> IconButton {
7234 let color = Color::Muted;
7235 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7236
7237 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7238 .shape(ui::IconButtonShape::Square)
7239 .icon_size(IconSize::XSmall)
7240 .icon_color(color)
7241 .toggle_state(is_active)
7242 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7243 let quick_launch = e.down.button == MouseButton::Left;
7244 window.focus(&editor.focus_handle(cx));
7245 editor.toggle_code_actions(
7246 &ToggleCodeActions {
7247 deployed_from_indicator: Some(row),
7248 quick_launch,
7249 },
7250 window,
7251 cx,
7252 );
7253 }))
7254 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7255 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7256 }))
7257 }
7258
7259 pub fn context_menu_visible(&self) -> bool {
7260 !self.edit_prediction_preview_is_active()
7261 && self
7262 .context_menu
7263 .borrow()
7264 .as_ref()
7265 .map_or(false, |menu| menu.visible())
7266 }
7267
7268 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7269 self.context_menu
7270 .borrow()
7271 .as_ref()
7272 .map(|menu| menu.origin())
7273 }
7274
7275 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7276 self.context_menu_options = Some(options);
7277 }
7278
7279 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7280 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7281
7282 fn render_edit_prediction_popover(
7283 &mut self,
7284 text_bounds: &Bounds<Pixels>,
7285 content_origin: gpui::Point<Pixels>,
7286 editor_snapshot: &EditorSnapshot,
7287 visible_row_range: Range<DisplayRow>,
7288 scroll_top: f32,
7289 scroll_bottom: f32,
7290 line_layouts: &[LineWithInvisibles],
7291 line_height: Pixels,
7292 scroll_pixel_position: gpui::Point<Pixels>,
7293 newest_selection_head: Option<DisplayPoint>,
7294 editor_width: Pixels,
7295 style: &EditorStyle,
7296 window: &mut Window,
7297 cx: &mut App,
7298 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7299 let active_inline_completion = self.active_inline_completion.as_ref()?;
7300
7301 if self.edit_prediction_visible_in_cursor_popover(true) {
7302 return None;
7303 }
7304
7305 match &active_inline_completion.completion {
7306 InlineCompletion::Move { target, .. } => {
7307 let target_display_point = target.to_display_point(editor_snapshot);
7308
7309 if self.edit_prediction_requires_modifier() {
7310 if !self.edit_prediction_preview_is_active() {
7311 return None;
7312 }
7313
7314 self.render_edit_prediction_modifier_jump_popover(
7315 text_bounds,
7316 content_origin,
7317 visible_row_range,
7318 line_layouts,
7319 line_height,
7320 scroll_pixel_position,
7321 newest_selection_head,
7322 target_display_point,
7323 window,
7324 cx,
7325 )
7326 } else {
7327 self.render_edit_prediction_eager_jump_popover(
7328 text_bounds,
7329 content_origin,
7330 editor_snapshot,
7331 visible_row_range,
7332 scroll_top,
7333 scroll_bottom,
7334 line_height,
7335 scroll_pixel_position,
7336 target_display_point,
7337 editor_width,
7338 window,
7339 cx,
7340 )
7341 }
7342 }
7343 InlineCompletion::Edit {
7344 display_mode: EditDisplayMode::Inline,
7345 ..
7346 } => None,
7347 InlineCompletion::Edit {
7348 display_mode: EditDisplayMode::TabAccept,
7349 edits,
7350 ..
7351 } => {
7352 let range = &edits.first()?.0;
7353 let target_display_point = range.end.to_display_point(editor_snapshot);
7354
7355 self.render_edit_prediction_end_of_line_popover(
7356 "Accept",
7357 editor_snapshot,
7358 visible_row_range,
7359 target_display_point,
7360 line_height,
7361 scroll_pixel_position,
7362 content_origin,
7363 editor_width,
7364 window,
7365 cx,
7366 )
7367 }
7368 InlineCompletion::Edit {
7369 edits,
7370 edit_preview,
7371 display_mode: EditDisplayMode::DiffPopover,
7372 snapshot,
7373 } => self.render_edit_prediction_diff_popover(
7374 text_bounds,
7375 content_origin,
7376 editor_snapshot,
7377 visible_row_range,
7378 line_layouts,
7379 line_height,
7380 scroll_pixel_position,
7381 newest_selection_head,
7382 editor_width,
7383 style,
7384 edits,
7385 edit_preview,
7386 snapshot,
7387 window,
7388 cx,
7389 ),
7390 }
7391 }
7392
7393 fn render_edit_prediction_modifier_jump_popover(
7394 &mut self,
7395 text_bounds: &Bounds<Pixels>,
7396 content_origin: gpui::Point<Pixels>,
7397 visible_row_range: Range<DisplayRow>,
7398 line_layouts: &[LineWithInvisibles],
7399 line_height: Pixels,
7400 scroll_pixel_position: gpui::Point<Pixels>,
7401 newest_selection_head: Option<DisplayPoint>,
7402 target_display_point: DisplayPoint,
7403 window: &mut Window,
7404 cx: &mut App,
7405 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7406 let scrolled_content_origin =
7407 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7408
7409 const SCROLL_PADDING_Y: Pixels = px(12.);
7410
7411 if target_display_point.row() < visible_row_range.start {
7412 return self.render_edit_prediction_scroll_popover(
7413 |_| SCROLL_PADDING_Y,
7414 IconName::ArrowUp,
7415 visible_row_range,
7416 line_layouts,
7417 newest_selection_head,
7418 scrolled_content_origin,
7419 window,
7420 cx,
7421 );
7422 } else if target_display_point.row() >= visible_row_range.end {
7423 return self.render_edit_prediction_scroll_popover(
7424 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7425 IconName::ArrowDown,
7426 visible_row_range,
7427 line_layouts,
7428 newest_selection_head,
7429 scrolled_content_origin,
7430 window,
7431 cx,
7432 );
7433 }
7434
7435 const POLE_WIDTH: Pixels = px(2.);
7436
7437 let line_layout =
7438 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7439 let target_column = target_display_point.column() as usize;
7440
7441 let target_x = line_layout.x_for_index(target_column);
7442 let target_y =
7443 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7444
7445 let flag_on_right = target_x < text_bounds.size.width / 2.;
7446
7447 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7448 border_color.l += 0.001;
7449
7450 let mut element = v_flex()
7451 .items_end()
7452 .when(flag_on_right, |el| el.items_start())
7453 .child(if flag_on_right {
7454 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7455 .rounded_bl(px(0.))
7456 .rounded_tl(px(0.))
7457 .border_l_2()
7458 .border_color(border_color)
7459 } else {
7460 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7461 .rounded_br(px(0.))
7462 .rounded_tr(px(0.))
7463 .border_r_2()
7464 .border_color(border_color)
7465 })
7466 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7467 .into_any();
7468
7469 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7470
7471 let mut origin = scrolled_content_origin + point(target_x, target_y)
7472 - point(
7473 if flag_on_right {
7474 POLE_WIDTH
7475 } else {
7476 size.width - POLE_WIDTH
7477 },
7478 size.height - line_height,
7479 );
7480
7481 origin.x = origin.x.max(content_origin.x);
7482
7483 element.prepaint_at(origin, window, cx);
7484
7485 Some((element, origin))
7486 }
7487
7488 fn render_edit_prediction_scroll_popover(
7489 &mut self,
7490 to_y: impl Fn(Size<Pixels>) -> Pixels,
7491 scroll_icon: IconName,
7492 visible_row_range: Range<DisplayRow>,
7493 line_layouts: &[LineWithInvisibles],
7494 newest_selection_head: Option<DisplayPoint>,
7495 scrolled_content_origin: gpui::Point<Pixels>,
7496 window: &mut Window,
7497 cx: &mut App,
7498 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7499 let mut element = self
7500 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7501 .into_any();
7502
7503 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7504
7505 let cursor = newest_selection_head?;
7506 let cursor_row_layout =
7507 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7508 let cursor_column = cursor.column() as usize;
7509
7510 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7511
7512 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7513
7514 element.prepaint_at(origin, window, cx);
7515 Some((element, origin))
7516 }
7517
7518 fn render_edit_prediction_eager_jump_popover(
7519 &mut self,
7520 text_bounds: &Bounds<Pixels>,
7521 content_origin: gpui::Point<Pixels>,
7522 editor_snapshot: &EditorSnapshot,
7523 visible_row_range: Range<DisplayRow>,
7524 scroll_top: f32,
7525 scroll_bottom: f32,
7526 line_height: Pixels,
7527 scroll_pixel_position: gpui::Point<Pixels>,
7528 target_display_point: DisplayPoint,
7529 editor_width: Pixels,
7530 window: &mut Window,
7531 cx: &mut App,
7532 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7533 if target_display_point.row().as_f32() < scroll_top {
7534 let mut element = self
7535 .render_edit_prediction_line_popover(
7536 "Jump to Edit",
7537 Some(IconName::ArrowUp),
7538 window,
7539 cx,
7540 )?
7541 .into_any();
7542
7543 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7544 let offset = point(
7545 (text_bounds.size.width - size.width) / 2.,
7546 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7547 );
7548
7549 let origin = text_bounds.origin + offset;
7550 element.prepaint_at(origin, window, cx);
7551 Some((element, origin))
7552 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7553 let mut element = self
7554 .render_edit_prediction_line_popover(
7555 "Jump to Edit",
7556 Some(IconName::ArrowDown),
7557 window,
7558 cx,
7559 )?
7560 .into_any();
7561
7562 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7563 let offset = point(
7564 (text_bounds.size.width - size.width) / 2.,
7565 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7566 );
7567
7568 let origin = text_bounds.origin + offset;
7569 element.prepaint_at(origin, window, cx);
7570 Some((element, origin))
7571 } else {
7572 self.render_edit_prediction_end_of_line_popover(
7573 "Jump to Edit",
7574 editor_snapshot,
7575 visible_row_range,
7576 target_display_point,
7577 line_height,
7578 scroll_pixel_position,
7579 content_origin,
7580 editor_width,
7581 window,
7582 cx,
7583 )
7584 }
7585 }
7586
7587 fn render_edit_prediction_end_of_line_popover(
7588 self: &mut Editor,
7589 label: &'static str,
7590 editor_snapshot: &EditorSnapshot,
7591 visible_row_range: Range<DisplayRow>,
7592 target_display_point: DisplayPoint,
7593 line_height: Pixels,
7594 scroll_pixel_position: gpui::Point<Pixels>,
7595 content_origin: gpui::Point<Pixels>,
7596 editor_width: Pixels,
7597 window: &mut Window,
7598 cx: &mut App,
7599 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7600 let target_line_end = DisplayPoint::new(
7601 target_display_point.row(),
7602 editor_snapshot.line_len(target_display_point.row()),
7603 );
7604
7605 let mut element = self
7606 .render_edit_prediction_line_popover(label, None, window, cx)?
7607 .into_any();
7608
7609 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7610
7611 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7612
7613 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7614 let mut origin = start_point
7615 + line_origin
7616 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7617 origin.x = origin.x.max(content_origin.x);
7618
7619 let max_x = content_origin.x + editor_width - size.width;
7620
7621 if origin.x > max_x {
7622 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7623
7624 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7625 origin.y += offset;
7626 IconName::ArrowUp
7627 } else {
7628 origin.y -= offset;
7629 IconName::ArrowDown
7630 };
7631
7632 element = self
7633 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7634 .into_any();
7635
7636 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7637
7638 origin.x = content_origin.x + editor_width - size.width - px(2.);
7639 }
7640
7641 element.prepaint_at(origin, window, cx);
7642 Some((element, origin))
7643 }
7644
7645 fn render_edit_prediction_diff_popover(
7646 self: &Editor,
7647 text_bounds: &Bounds<Pixels>,
7648 content_origin: gpui::Point<Pixels>,
7649 editor_snapshot: &EditorSnapshot,
7650 visible_row_range: Range<DisplayRow>,
7651 line_layouts: &[LineWithInvisibles],
7652 line_height: Pixels,
7653 scroll_pixel_position: gpui::Point<Pixels>,
7654 newest_selection_head: Option<DisplayPoint>,
7655 editor_width: Pixels,
7656 style: &EditorStyle,
7657 edits: &Vec<(Range<Anchor>, String)>,
7658 edit_preview: &Option<language::EditPreview>,
7659 snapshot: &language::BufferSnapshot,
7660 window: &mut Window,
7661 cx: &mut App,
7662 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7663 let edit_start = edits
7664 .first()
7665 .unwrap()
7666 .0
7667 .start
7668 .to_display_point(editor_snapshot);
7669 let edit_end = edits
7670 .last()
7671 .unwrap()
7672 .0
7673 .end
7674 .to_display_point(editor_snapshot);
7675
7676 let is_visible = visible_row_range.contains(&edit_start.row())
7677 || visible_row_range.contains(&edit_end.row());
7678 if !is_visible {
7679 return None;
7680 }
7681
7682 let highlighted_edits =
7683 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7684
7685 let styled_text = highlighted_edits.to_styled_text(&style.text);
7686 let line_count = highlighted_edits.text.lines().count();
7687
7688 const BORDER_WIDTH: Pixels = px(1.);
7689
7690 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7691 let has_keybind = keybind.is_some();
7692
7693 let mut element = h_flex()
7694 .items_start()
7695 .child(
7696 h_flex()
7697 .bg(cx.theme().colors().editor_background)
7698 .border(BORDER_WIDTH)
7699 .shadow_sm()
7700 .border_color(cx.theme().colors().border)
7701 .rounded_l_lg()
7702 .when(line_count > 1, |el| el.rounded_br_lg())
7703 .pr_1()
7704 .child(styled_text),
7705 )
7706 .child(
7707 h_flex()
7708 .h(line_height + BORDER_WIDTH * 2.)
7709 .px_1p5()
7710 .gap_1()
7711 // Workaround: For some reason, there's a gap if we don't do this
7712 .ml(-BORDER_WIDTH)
7713 .shadow(smallvec![gpui::BoxShadow {
7714 color: gpui::black().opacity(0.05),
7715 offset: point(px(1.), px(1.)),
7716 blur_radius: px(2.),
7717 spread_radius: px(0.),
7718 }])
7719 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7720 .border(BORDER_WIDTH)
7721 .border_color(cx.theme().colors().border)
7722 .rounded_r_lg()
7723 .id("edit_prediction_diff_popover_keybind")
7724 .when(!has_keybind, |el| {
7725 let status_colors = cx.theme().status();
7726
7727 el.bg(status_colors.error_background)
7728 .border_color(status_colors.error.opacity(0.6))
7729 .child(Icon::new(IconName::Info).color(Color::Error))
7730 .cursor_default()
7731 .hoverable_tooltip(move |_window, cx| {
7732 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7733 })
7734 })
7735 .children(keybind),
7736 )
7737 .into_any();
7738
7739 let longest_row =
7740 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7741 let longest_line_width = if visible_row_range.contains(&longest_row) {
7742 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7743 } else {
7744 layout_line(
7745 longest_row,
7746 editor_snapshot,
7747 style,
7748 editor_width,
7749 |_| false,
7750 window,
7751 cx,
7752 )
7753 .width
7754 };
7755
7756 let viewport_bounds =
7757 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7758 right: -EditorElement::SCROLLBAR_WIDTH,
7759 ..Default::default()
7760 });
7761
7762 let x_after_longest =
7763 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7764 - scroll_pixel_position.x;
7765
7766 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7767
7768 // Fully visible if it can be displayed within the window (allow overlapping other
7769 // panes). However, this is only allowed if the popover starts within text_bounds.
7770 let can_position_to_the_right = x_after_longest < text_bounds.right()
7771 && x_after_longest + element_bounds.width < viewport_bounds.right();
7772
7773 let mut origin = if can_position_to_the_right {
7774 point(
7775 x_after_longest,
7776 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7777 - scroll_pixel_position.y,
7778 )
7779 } else {
7780 let cursor_row = newest_selection_head.map(|head| head.row());
7781 let above_edit = edit_start
7782 .row()
7783 .0
7784 .checked_sub(line_count as u32)
7785 .map(DisplayRow);
7786 let below_edit = Some(edit_end.row() + 1);
7787 let above_cursor =
7788 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7789 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7790
7791 // Place the edit popover adjacent to the edit if there is a location
7792 // available that is onscreen and does not obscure the cursor. Otherwise,
7793 // place it adjacent to the cursor.
7794 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7795 .into_iter()
7796 .flatten()
7797 .find(|&start_row| {
7798 let end_row = start_row + line_count as u32;
7799 visible_row_range.contains(&start_row)
7800 && visible_row_range.contains(&end_row)
7801 && cursor_row.map_or(true, |cursor_row| {
7802 !((start_row..end_row).contains(&cursor_row))
7803 })
7804 })?;
7805
7806 content_origin
7807 + point(
7808 -scroll_pixel_position.x,
7809 row_target.as_f32() * line_height - scroll_pixel_position.y,
7810 )
7811 };
7812
7813 origin.x -= BORDER_WIDTH;
7814
7815 window.defer_draw(element, origin, 1);
7816
7817 // Do not return an element, since it will already be drawn due to defer_draw.
7818 None
7819 }
7820
7821 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7822 px(30.)
7823 }
7824
7825 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7826 if self.read_only(cx) {
7827 cx.theme().players().read_only()
7828 } else {
7829 self.style.as_ref().unwrap().local_player
7830 }
7831 }
7832
7833 fn render_edit_prediction_accept_keybind(
7834 &self,
7835 window: &mut Window,
7836 cx: &App,
7837 ) -> Option<AnyElement> {
7838 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7839 let accept_keystroke = accept_binding.keystroke()?;
7840
7841 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7842
7843 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7844 Color::Accent
7845 } else {
7846 Color::Muted
7847 };
7848
7849 h_flex()
7850 .px_0p5()
7851 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7852 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7853 .text_size(TextSize::XSmall.rems(cx))
7854 .child(h_flex().children(ui::render_modifiers(
7855 &accept_keystroke.modifiers,
7856 PlatformStyle::platform(),
7857 Some(modifiers_color),
7858 Some(IconSize::XSmall.rems().into()),
7859 true,
7860 )))
7861 .when(is_platform_style_mac, |parent| {
7862 parent.child(accept_keystroke.key.clone())
7863 })
7864 .when(!is_platform_style_mac, |parent| {
7865 parent.child(
7866 Key::new(
7867 util::capitalize(&accept_keystroke.key),
7868 Some(Color::Default),
7869 )
7870 .size(Some(IconSize::XSmall.rems().into())),
7871 )
7872 })
7873 .into_any()
7874 .into()
7875 }
7876
7877 fn render_edit_prediction_line_popover(
7878 &self,
7879 label: impl Into<SharedString>,
7880 icon: Option<IconName>,
7881 window: &mut Window,
7882 cx: &App,
7883 ) -> Option<Stateful<Div>> {
7884 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7885
7886 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7887 let has_keybind = keybind.is_some();
7888
7889 let result = h_flex()
7890 .id("ep-line-popover")
7891 .py_0p5()
7892 .pl_1()
7893 .pr(padding_right)
7894 .gap_1()
7895 .rounded_md()
7896 .border_1()
7897 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7898 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7899 .shadow_sm()
7900 .when(!has_keybind, |el| {
7901 let status_colors = cx.theme().status();
7902
7903 el.bg(status_colors.error_background)
7904 .border_color(status_colors.error.opacity(0.6))
7905 .pl_2()
7906 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7907 .cursor_default()
7908 .hoverable_tooltip(move |_window, cx| {
7909 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7910 })
7911 })
7912 .children(keybind)
7913 .child(
7914 Label::new(label)
7915 .size(LabelSize::Small)
7916 .when(!has_keybind, |el| {
7917 el.color(cx.theme().status().error.into()).strikethrough()
7918 }),
7919 )
7920 .when(!has_keybind, |el| {
7921 el.child(
7922 h_flex().ml_1().child(
7923 Icon::new(IconName::Info)
7924 .size(IconSize::Small)
7925 .color(cx.theme().status().error.into()),
7926 ),
7927 )
7928 })
7929 .when_some(icon, |element, icon| {
7930 element.child(
7931 div()
7932 .mt(px(1.5))
7933 .child(Icon::new(icon).size(IconSize::Small)),
7934 )
7935 });
7936
7937 Some(result)
7938 }
7939
7940 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7941 let accent_color = cx.theme().colors().text_accent;
7942 let editor_bg_color = cx.theme().colors().editor_background;
7943 editor_bg_color.blend(accent_color.opacity(0.1))
7944 }
7945
7946 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7947 let accent_color = cx.theme().colors().text_accent;
7948 let editor_bg_color = cx.theme().colors().editor_background;
7949 editor_bg_color.blend(accent_color.opacity(0.6))
7950 }
7951
7952 fn render_edit_prediction_cursor_popover(
7953 &self,
7954 min_width: Pixels,
7955 max_width: Pixels,
7956 cursor_point: Point,
7957 style: &EditorStyle,
7958 accept_keystroke: Option<&gpui::Keystroke>,
7959 _window: &Window,
7960 cx: &mut Context<Editor>,
7961 ) -> Option<AnyElement> {
7962 let provider = self.edit_prediction_provider.as_ref()?;
7963
7964 if provider.provider.needs_terms_acceptance(cx) {
7965 return Some(
7966 h_flex()
7967 .min_w(min_width)
7968 .flex_1()
7969 .px_2()
7970 .py_1()
7971 .gap_3()
7972 .elevation_2(cx)
7973 .hover(|style| style.bg(cx.theme().colors().element_hover))
7974 .id("accept-terms")
7975 .cursor_pointer()
7976 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7977 .on_click(cx.listener(|this, _event, window, cx| {
7978 cx.stop_propagation();
7979 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7980 window.dispatch_action(
7981 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7982 cx,
7983 );
7984 }))
7985 .child(
7986 h_flex()
7987 .flex_1()
7988 .gap_2()
7989 .child(Icon::new(IconName::ZedPredict))
7990 .child(Label::new("Accept Terms of Service"))
7991 .child(div().w_full())
7992 .child(
7993 Icon::new(IconName::ArrowUpRight)
7994 .color(Color::Muted)
7995 .size(IconSize::Small),
7996 )
7997 .into_any_element(),
7998 )
7999 .into_any(),
8000 );
8001 }
8002
8003 let is_refreshing = provider.provider.is_refreshing(cx);
8004
8005 fn pending_completion_container() -> Div {
8006 h_flex()
8007 .h_full()
8008 .flex_1()
8009 .gap_2()
8010 .child(Icon::new(IconName::ZedPredict))
8011 }
8012
8013 let completion = match &self.active_inline_completion {
8014 Some(prediction) => {
8015 if !self.has_visible_completions_menu() {
8016 const RADIUS: Pixels = px(6.);
8017 const BORDER_WIDTH: Pixels = px(1.);
8018
8019 return Some(
8020 h_flex()
8021 .elevation_2(cx)
8022 .border(BORDER_WIDTH)
8023 .border_color(cx.theme().colors().border)
8024 .when(accept_keystroke.is_none(), |el| {
8025 el.border_color(cx.theme().status().error)
8026 })
8027 .rounded(RADIUS)
8028 .rounded_tl(px(0.))
8029 .overflow_hidden()
8030 .child(div().px_1p5().child(match &prediction.completion {
8031 InlineCompletion::Move { target, snapshot } => {
8032 use text::ToPoint as _;
8033 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8034 {
8035 Icon::new(IconName::ZedPredictDown)
8036 } else {
8037 Icon::new(IconName::ZedPredictUp)
8038 }
8039 }
8040 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8041 }))
8042 .child(
8043 h_flex()
8044 .gap_1()
8045 .py_1()
8046 .px_2()
8047 .rounded_r(RADIUS - BORDER_WIDTH)
8048 .border_l_1()
8049 .border_color(cx.theme().colors().border)
8050 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8051 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8052 el.child(
8053 Label::new("Hold")
8054 .size(LabelSize::Small)
8055 .when(accept_keystroke.is_none(), |el| {
8056 el.strikethrough()
8057 })
8058 .line_height_style(LineHeightStyle::UiLabel),
8059 )
8060 })
8061 .id("edit_prediction_cursor_popover_keybind")
8062 .when(accept_keystroke.is_none(), |el| {
8063 let status_colors = cx.theme().status();
8064
8065 el.bg(status_colors.error_background)
8066 .border_color(status_colors.error.opacity(0.6))
8067 .child(Icon::new(IconName::Info).color(Color::Error))
8068 .cursor_default()
8069 .hoverable_tooltip(move |_window, cx| {
8070 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8071 .into()
8072 })
8073 })
8074 .when_some(
8075 accept_keystroke.as_ref(),
8076 |el, accept_keystroke| {
8077 el.child(h_flex().children(ui::render_modifiers(
8078 &accept_keystroke.modifiers,
8079 PlatformStyle::platform(),
8080 Some(Color::Default),
8081 Some(IconSize::XSmall.rems().into()),
8082 false,
8083 )))
8084 },
8085 ),
8086 )
8087 .into_any(),
8088 );
8089 }
8090
8091 self.render_edit_prediction_cursor_popover_preview(
8092 prediction,
8093 cursor_point,
8094 style,
8095 cx,
8096 )?
8097 }
8098
8099 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8100 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8101 stale_completion,
8102 cursor_point,
8103 style,
8104 cx,
8105 )?,
8106
8107 None => {
8108 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8109 }
8110 },
8111
8112 None => pending_completion_container().child(Label::new("No Prediction")),
8113 };
8114
8115 let completion = if is_refreshing {
8116 completion
8117 .with_animation(
8118 "loading-completion",
8119 Animation::new(Duration::from_secs(2))
8120 .repeat()
8121 .with_easing(pulsating_between(0.4, 0.8)),
8122 |label, delta| label.opacity(delta),
8123 )
8124 .into_any_element()
8125 } else {
8126 completion.into_any_element()
8127 };
8128
8129 let has_completion = self.active_inline_completion.is_some();
8130
8131 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8132 Some(
8133 h_flex()
8134 .min_w(min_width)
8135 .max_w(max_width)
8136 .flex_1()
8137 .elevation_2(cx)
8138 .border_color(cx.theme().colors().border)
8139 .child(
8140 div()
8141 .flex_1()
8142 .py_1()
8143 .px_2()
8144 .overflow_hidden()
8145 .child(completion),
8146 )
8147 .when_some(accept_keystroke, |el, accept_keystroke| {
8148 if !accept_keystroke.modifiers.modified() {
8149 return el;
8150 }
8151
8152 el.child(
8153 h_flex()
8154 .h_full()
8155 .border_l_1()
8156 .rounded_r_lg()
8157 .border_color(cx.theme().colors().border)
8158 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8159 .gap_1()
8160 .py_1()
8161 .px_2()
8162 .child(
8163 h_flex()
8164 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8165 .when(is_platform_style_mac, |parent| parent.gap_1())
8166 .child(h_flex().children(ui::render_modifiers(
8167 &accept_keystroke.modifiers,
8168 PlatformStyle::platform(),
8169 Some(if !has_completion {
8170 Color::Muted
8171 } else {
8172 Color::Default
8173 }),
8174 None,
8175 false,
8176 ))),
8177 )
8178 .child(Label::new("Preview").into_any_element())
8179 .opacity(if has_completion { 1.0 } else { 0.4 }),
8180 )
8181 })
8182 .into_any(),
8183 )
8184 }
8185
8186 fn render_edit_prediction_cursor_popover_preview(
8187 &self,
8188 completion: &InlineCompletionState,
8189 cursor_point: Point,
8190 style: &EditorStyle,
8191 cx: &mut Context<Editor>,
8192 ) -> Option<Div> {
8193 use text::ToPoint as _;
8194
8195 fn render_relative_row_jump(
8196 prefix: impl Into<String>,
8197 current_row: u32,
8198 target_row: u32,
8199 ) -> Div {
8200 let (row_diff, arrow) = if target_row < current_row {
8201 (current_row - target_row, IconName::ArrowUp)
8202 } else {
8203 (target_row - current_row, IconName::ArrowDown)
8204 };
8205
8206 h_flex()
8207 .child(
8208 Label::new(format!("{}{}", prefix.into(), row_diff))
8209 .color(Color::Muted)
8210 .size(LabelSize::Small),
8211 )
8212 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8213 }
8214
8215 match &completion.completion {
8216 InlineCompletion::Move {
8217 target, snapshot, ..
8218 } => Some(
8219 h_flex()
8220 .px_2()
8221 .gap_2()
8222 .flex_1()
8223 .child(
8224 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8225 Icon::new(IconName::ZedPredictDown)
8226 } else {
8227 Icon::new(IconName::ZedPredictUp)
8228 },
8229 )
8230 .child(Label::new("Jump to Edit")),
8231 ),
8232
8233 InlineCompletion::Edit {
8234 edits,
8235 edit_preview,
8236 snapshot,
8237 display_mode: _,
8238 } => {
8239 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8240
8241 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8242 &snapshot,
8243 &edits,
8244 edit_preview.as_ref()?,
8245 true,
8246 cx,
8247 )
8248 .first_line_preview();
8249
8250 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8251 .with_default_highlights(&style.text, highlighted_edits.highlights);
8252
8253 let preview = h_flex()
8254 .gap_1()
8255 .min_w_16()
8256 .child(styled_text)
8257 .when(has_more_lines, |parent| parent.child("…"));
8258
8259 let left = if first_edit_row != cursor_point.row {
8260 render_relative_row_jump("", cursor_point.row, first_edit_row)
8261 .into_any_element()
8262 } else {
8263 Icon::new(IconName::ZedPredict).into_any_element()
8264 };
8265
8266 Some(
8267 h_flex()
8268 .h_full()
8269 .flex_1()
8270 .gap_2()
8271 .pr_1()
8272 .overflow_x_hidden()
8273 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8274 .child(left)
8275 .child(preview),
8276 )
8277 }
8278 }
8279 }
8280
8281 fn render_context_menu(
8282 &self,
8283 style: &EditorStyle,
8284 max_height_in_lines: u32,
8285 window: &mut Window,
8286 cx: &mut Context<Editor>,
8287 ) -> Option<AnyElement> {
8288 let menu = self.context_menu.borrow();
8289 let menu = menu.as_ref()?;
8290 if !menu.visible() {
8291 return None;
8292 };
8293 Some(menu.render(style, max_height_in_lines, window, cx))
8294 }
8295
8296 fn render_context_menu_aside(
8297 &mut self,
8298 max_size: Size<Pixels>,
8299 window: &mut Window,
8300 cx: &mut Context<Editor>,
8301 ) -> Option<AnyElement> {
8302 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8303 if menu.visible() {
8304 menu.render_aside(self, max_size, window, cx)
8305 } else {
8306 None
8307 }
8308 })
8309 }
8310
8311 fn hide_context_menu(
8312 &mut self,
8313 window: &mut Window,
8314 cx: &mut Context<Self>,
8315 ) -> Option<CodeContextMenu> {
8316 cx.notify();
8317 self.completion_tasks.clear();
8318 let context_menu = self.context_menu.borrow_mut().take();
8319 self.stale_inline_completion_in_menu.take();
8320 self.update_visible_inline_completion(window, cx);
8321 context_menu
8322 }
8323
8324 fn show_snippet_choices(
8325 &mut self,
8326 choices: &Vec<String>,
8327 selection: Range<Anchor>,
8328 cx: &mut Context<Self>,
8329 ) {
8330 if selection.start.buffer_id.is_none() {
8331 return;
8332 }
8333 let buffer_id = selection.start.buffer_id.unwrap();
8334 let buffer = self.buffer().read(cx).buffer(buffer_id);
8335 let id = post_inc(&mut self.next_completion_id);
8336 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8337
8338 if let Some(buffer) = buffer {
8339 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8340 CompletionsMenu::new_snippet_choices(
8341 id,
8342 true,
8343 choices,
8344 selection,
8345 buffer,
8346 snippet_sort_order,
8347 ),
8348 ));
8349 }
8350 }
8351
8352 pub fn insert_snippet(
8353 &mut self,
8354 insertion_ranges: &[Range<usize>],
8355 snippet: Snippet,
8356 window: &mut Window,
8357 cx: &mut Context<Self>,
8358 ) -> Result<()> {
8359 struct Tabstop<T> {
8360 is_end_tabstop: bool,
8361 ranges: Vec<Range<T>>,
8362 choices: Option<Vec<String>>,
8363 }
8364
8365 let tabstops = self.buffer.update(cx, |buffer, cx| {
8366 let snippet_text: Arc<str> = snippet.text.clone().into();
8367 let edits = insertion_ranges
8368 .iter()
8369 .cloned()
8370 .map(|range| (range, snippet_text.clone()));
8371 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8372
8373 let snapshot = &*buffer.read(cx);
8374 let snippet = &snippet;
8375 snippet
8376 .tabstops
8377 .iter()
8378 .map(|tabstop| {
8379 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8380 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8381 });
8382 let mut tabstop_ranges = tabstop
8383 .ranges
8384 .iter()
8385 .flat_map(|tabstop_range| {
8386 let mut delta = 0_isize;
8387 insertion_ranges.iter().map(move |insertion_range| {
8388 let insertion_start = insertion_range.start as isize + delta;
8389 delta +=
8390 snippet.text.len() as isize - insertion_range.len() as isize;
8391
8392 let start = ((insertion_start + tabstop_range.start) as usize)
8393 .min(snapshot.len());
8394 let end = ((insertion_start + tabstop_range.end) as usize)
8395 .min(snapshot.len());
8396 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8397 })
8398 })
8399 .collect::<Vec<_>>();
8400 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8401
8402 Tabstop {
8403 is_end_tabstop,
8404 ranges: tabstop_ranges,
8405 choices: tabstop.choices.clone(),
8406 }
8407 })
8408 .collect::<Vec<_>>()
8409 });
8410 if let Some(tabstop) = tabstops.first() {
8411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8412 s.select_ranges(tabstop.ranges.iter().cloned());
8413 });
8414
8415 if let Some(choices) = &tabstop.choices {
8416 if let Some(selection) = tabstop.ranges.first() {
8417 self.show_snippet_choices(choices, selection.clone(), cx)
8418 }
8419 }
8420
8421 // If we're already at the last tabstop and it's at the end of the snippet,
8422 // we're done, we don't need to keep the state around.
8423 if !tabstop.is_end_tabstop {
8424 let choices = tabstops
8425 .iter()
8426 .map(|tabstop| tabstop.choices.clone())
8427 .collect();
8428
8429 let ranges = tabstops
8430 .into_iter()
8431 .map(|tabstop| tabstop.ranges)
8432 .collect::<Vec<_>>();
8433
8434 self.snippet_stack.push(SnippetState {
8435 active_index: 0,
8436 ranges,
8437 choices,
8438 });
8439 }
8440
8441 // Check whether the just-entered snippet ends with an auto-closable bracket.
8442 if self.autoclose_regions.is_empty() {
8443 let snapshot = self.buffer.read(cx).snapshot(cx);
8444 for selection in &mut self.selections.all::<Point>(cx) {
8445 let selection_head = selection.head();
8446 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8447 continue;
8448 };
8449
8450 let mut bracket_pair = None;
8451 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8452 let prev_chars = snapshot
8453 .reversed_chars_at(selection_head)
8454 .collect::<String>();
8455 for (pair, enabled) in scope.brackets() {
8456 if enabled
8457 && pair.close
8458 && prev_chars.starts_with(pair.start.as_str())
8459 && next_chars.starts_with(pair.end.as_str())
8460 {
8461 bracket_pair = Some(pair.clone());
8462 break;
8463 }
8464 }
8465 if let Some(pair) = bracket_pair {
8466 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8467 let autoclose_enabled =
8468 self.use_autoclose && snapshot_settings.use_autoclose;
8469 if autoclose_enabled {
8470 let start = snapshot.anchor_after(selection_head);
8471 let end = snapshot.anchor_after(selection_head);
8472 self.autoclose_regions.push(AutocloseRegion {
8473 selection_id: selection.id,
8474 range: start..end,
8475 pair,
8476 });
8477 }
8478 }
8479 }
8480 }
8481 }
8482 Ok(())
8483 }
8484
8485 pub fn move_to_next_snippet_tabstop(
8486 &mut self,
8487 window: &mut Window,
8488 cx: &mut Context<Self>,
8489 ) -> bool {
8490 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8491 }
8492
8493 pub fn move_to_prev_snippet_tabstop(
8494 &mut self,
8495 window: &mut Window,
8496 cx: &mut Context<Self>,
8497 ) -> bool {
8498 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8499 }
8500
8501 pub fn move_to_snippet_tabstop(
8502 &mut self,
8503 bias: Bias,
8504 window: &mut Window,
8505 cx: &mut Context<Self>,
8506 ) -> bool {
8507 if let Some(mut snippet) = self.snippet_stack.pop() {
8508 match bias {
8509 Bias::Left => {
8510 if snippet.active_index > 0 {
8511 snippet.active_index -= 1;
8512 } else {
8513 self.snippet_stack.push(snippet);
8514 return false;
8515 }
8516 }
8517 Bias::Right => {
8518 if snippet.active_index + 1 < snippet.ranges.len() {
8519 snippet.active_index += 1;
8520 } else {
8521 self.snippet_stack.push(snippet);
8522 return false;
8523 }
8524 }
8525 }
8526 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8527 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8528 s.select_anchor_ranges(current_ranges.iter().cloned())
8529 });
8530
8531 if let Some(choices) = &snippet.choices[snippet.active_index] {
8532 if let Some(selection) = current_ranges.first() {
8533 self.show_snippet_choices(&choices, selection.clone(), cx);
8534 }
8535 }
8536
8537 // If snippet state is not at the last tabstop, push it back on the stack
8538 if snippet.active_index + 1 < snippet.ranges.len() {
8539 self.snippet_stack.push(snippet);
8540 }
8541 return true;
8542 }
8543 }
8544
8545 false
8546 }
8547
8548 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8549 self.transact(window, cx, |this, window, cx| {
8550 this.select_all(&SelectAll, window, cx);
8551 this.insert("", window, cx);
8552 });
8553 }
8554
8555 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8556 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8557 self.transact(window, cx, |this, window, cx| {
8558 this.select_autoclose_pair(window, cx);
8559 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8560 if !this.linked_edit_ranges.is_empty() {
8561 let selections = this.selections.all::<MultiBufferPoint>(cx);
8562 let snapshot = this.buffer.read(cx).snapshot(cx);
8563
8564 for selection in selections.iter() {
8565 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8566 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8567 if selection_start.buffer_id != selection_end.buffer_id {
8568 continue;
8569 }
8570 if let Some(ranges) =
8571 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8572 {
8573 for (buffer, entries) in ranges {
8574 linked_ranges.entry(buffer).or_default().extend(entries);
8575 }
8576 }
8577 }
8578 }
8579
8580 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8581 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8582 for selection in &mut selections {
8583 if selection.is_empty() {
8584 let old_head = selection.head();
8585 let mut new_head =
8586 movement::left(&display_map, old_head.to_display_point(&display_map))
8587 .to_point(&display_map);
8588 if let Some((buffer, line_buffer_range)) = display_map
8589 .buffer_snapshot
8590 .buffer_line_for_row(MultiBufferRow(old_head.row))
8591 {
8592 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8593 let indent_len = match indent_size.kind {
8594 IndentKind::Space => {
8595 buffer.settings_at(line_buffer_range.start, cx).tab_size
8596 }
8597 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8598 };
8599 if old_head.column <= indent_size.len && old_head.column > 0 {
8600 let indent_len = indent_len.get();
8601 new_head = cmp::min(
8602 new_head,
8603 MultiBufferPoint::new(
8604 old_head.row,
8605 ((old_head.column - 1) / indent_len) * indent_len,
8606 ),
8607 );
8608 }
8609 }
8610
8611 selection.set_head(new_head, SelectionGoal::None);
8612 }
8613 }
8614
8615 this.signature_help_state.set_backspace_pressed(true);
8616 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8617 s.select(selections)
8618 });
8619 this.insert("", window, cx);
8620 let empty_str: Arc<str> = Arc::from("");
8621 for (buffer, edits) in linked_ranges {
8622 let snapshot = buffer.read(cx).snapshot();
8623 use text::ToPoint as TP;
8624
8625 let edits = edits
8626 .into_iter()
8627 .map(|range| {
8628 let end_point = TP::to_point(&range.end, &snapshot);
8629 let mut start_point = TP::to_point(&range.start, &snapshot);
8630
8631 if end_point == start_point {
8632 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8633 .saturating_sub(1);
8634 start_point =
8635 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8636 };
8637
8638 (start_point..end_point, empty_str.clone())
8639 })
8640 .sorted_by_key(|(range, _)| range.start)
8641 .collect::<Vec<_>>();
8642 buffer.update(cx, |this, cx| {
8643 this.edit(edits, None, cx);
8644 })
8645 }
8646 this.refresh_inline_completion(true, false, window, cx);
8647 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8648 });
8649 }
8650
8651 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8652 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8653 self.transact(window, cx, |this, window, cx| {
8654 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8655 s.move_with(|map, selection| {
8656 if selection.is_empty() {
8657 let cursor = movement::right(map, selection.head());
8658 selection.end = cursor;
8659 selection.reversed = true;
8660 selection.goal = SelectionGoal::None;
8661 }
8662 })
8663 });
8664 this.insert("", window, cx);
8665 this.refresh_inline_completion(true, false, window, cx);
8666 });
8667 }
8668
8669 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8670 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8671 if self.move_to_prev_snippet_tabstop(window, cx) {
8672 return;
8673 }
8674 self.outdent(&Outdent, window, cx);
8675 }
8676
8677 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8678 if self.move_to_next_snippet_tabstop(window, cx) {
8679 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8680 return;
8681 }
8682 if self.read_only(cx) {
8683 return;
8684 }
8685 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8686 let mut selections = self.selections.all_adjusted(cx);
8687 let buffer = self.buffer.read(cx);
8688 let snapshot = buffer.snapshot(cx);
8689 let rows_iter = selections.iter().map(|s| s.head().row);
8690 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8691
8692 let has_some_cursor_in_whitespace = selections
8693 .iter()
8694 .filter(|selection| selection.is_empty())
8695 .any(|selection| {
8696 let cursor = selection.head();
8697 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8698 cursor.column < current_indent.len
8699 });
8700
8701 let mut edits = Vec::new();
8702 let mut prev_edited_row = 0;
8703 let mut row_delta = 0;
8704 for selection in &mut selections {
8705 if selection.start.row != prev_edited_row {
8706 row_delta = 0;
8707 }
8708 prev_edited_row = selection.end.row;
8709
8710 // If the selection is non-empty, then increase the indentation of the selected lines.
8711 if !selection.is_empty() {
8712 row_delta =
8713 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8714 continue;
8715 }
8716
8717 // If the selection is empty and the cursor is in the leading whitespace before the
8718 // suggested indentation, then auto-indent the line.
8719 let cursor = selection.head();
8720 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8721 if let Some(suggested_indent) =
8722 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8723 {
8724 // If there exist any empty selection in the leading whitespace, then skip
8725 // indent for selections at the boundary.
8726 if has_some_cursor_in_whitespace
8727 && cursor.column == current_indent.len
8728 && current_indent.len == suggested_indent.len
8729 {
8730 continue;
8731 }
8732
8733 if cursor.column < suggested_indent.len
8734 && cursor.column <= current_indent.len
8735 && current_indent.len <= suggested_indent.len
8736 {
8737 selection.start = Point::new(cursor.row, suggested_indent.len);
8738 selection.end = selection.start;
8739 if row_delta == 0 {
8740 edits.extend(Buffer::edit_for_indent_size_adjustment(
8741 cursor.row,
8742 current_indent,
8743 suggested_indent,
8744 ));
8745 row_delta = suggested_indent.len - current_indent.len;
8746 }
8747 continue;
8748 }
8749 }
8750
8751 // Otherwise, insert a hard or soft tab.
8752 let settings = buffer.language_settings_at(cursor, cx);
8753 let tab_size = if settings.hard_tabs {
8754 IndentSize::tab()
8755 } else {
8756 let tab_size = settings.tab_size.get();
8757 let indent_remainder = snapshot
8758 .text_for_range(Point::new(cursor.row, 0)..cursor)
8759 .flat_map(str::chars)
8760 .fold(row_delta % tab_size, |counter: u32, c| {
8761 if c == '\t' {
8762 0
8763 } else {
8764 (counter + 1) % tab_size
8765 }
8766 });
8767
8768 let chars_to_next_tab_stop = tab_size - indent_remainder;
8769 IndentSize::spaces(chars_to_next_tab_stop)
8770 };
8771 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8772 selection.end = selection.start;
8773 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8774 row_delta += tab_size.len;
8775 }
8776
8777 self.transact(window, cx, |this, window, cx| {
8778 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8779 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8780 s.select(selections)
8781 });
8782 this.refresh_inline_completion(true, false, window, cx);
8783 });
8784 }
8785
8786 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8787 if self.read_only(cx) {
8788 return;
8789 }
8790 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8791 let mut selections = self.selections.all::<Point>(cx);
8792 let mut prev_edited_row = 0;
8793 let mut row_delta = 0;
8794 let mut edits = Vec::new();
8795 let buffer = self.buffer.read(cx);
8796 let snapshot = buffer.snapshot(cx);
8797 for selection in &mut selections {
8798 if selection.start.row != prev_edited_row {
8799 row_delta = 0;
8800 }
8801 prev_edited_row = selection.end.row;
8802
8803 row_delta =
8804 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8805 }
8806
8807 self.transact(window, cx, |this, window, cx| {
8808 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8809 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8810 s.select(selections)
8811 });
8812 });
8813 }
8814
8815 fn indent_selection(
8816 buffer: &MultiBuffer,
8817 snapshot: &MultiBufferSnapshot,
8818 selection: &mut Selection<Point>,
8819 edits: &mut Vec<(Range<Point>, String)>,
8820 delta_for_start_row: u32,
8821 cx: &App,
8822 ) -> u32 {
8823 let settings = buffer.language_settings_at(selection.start, cx);
8824 let tab_size = settings.tab_size.get();
8825 let indent_kind = if settings.hard_tabs {
8826 IndentKind::Tab
8827 } else {
8828 IndentKind::Space
8829 };
8830 let mut start_row = selection.start.row;
8831 let mut end_row = selection.end.row + 1;
8832
8833 // If a selection ends at the beginning of a line, don't indent
8834 // that last line.
8835 if selection.end.column == 0 && selection.end.row > selection.start.row {
8836 end_row -= 1;
8837 }
8838
8839 // Avoid re-indenting a row that has already been indented by a
8840 // previous selection, but still update this selection's column
8841 // to reflect that indentation.
8842 if delta_for_start_row > 0 {
8843 start_row += 1;
8844 selection.start.column += delta_for_start_row;
8845 if selection.end.row == selection.start.row {
8846 selection.end.column += delta_for_start_row;
8847 }
8848 }
8849
8850 let mut delta_for_end_row = 0;
8851 let has_multiple_rows = start_row + 1 != end_row;
8852 for row in start_row..end_row {
8853 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8854 let indent_delta = match (current_indent.kind, indent_kind) {
8855 (IndentKind::Space, IndentKind::Space) => {
8856 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8857 IndentSize::spaces(columns_to_next_tab_stop)
8858 }
8859 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8860 (_, IndentKind::Tab) => IndentSize::tab(),
8861 };
8862
8863 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8864 0
8865 } else {
8866 selection.start.column
8867 };
8868 let row_start = Point::new(row, start);
8869 edits.push((
8870 row_start..row_start,
8871 indent_delta.chars().collect::<String>(),
8872 ));
8873
8874 // Update this selection's endpoints to reflect the indentation.
8875 if row == selection.start.row {
8876 selection.start.column += indent_delta.len;
8877 }
8878 if row == selection.end.row {
8879 selection.end.column += indent_delta.len;
8880 delta_for_end_row = indent_delta.len;
8881 }
8882 }
8883
8884 if selection.start.row == selection.end.row {
8885 delta_for_start_row + delta_for_end_row
8886 } else {
8887 delta_for_end_row
8888 }
8889 }
8890
8891 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8892 if self.read_only(cx) {
8893 return;
8894 }
8895 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8896 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8897 let selections = self.selections.all::<Point>(cx);
8898 let mut deletion_ranges = Vec::new();
8899 let mut last_outdent = None;
8900 {
8901 let buffer = self.buffer.read(cx);
8902 let snapshot = buffer.snapshot(cx);
8903 for selection in &selections {
8904 let settings = buffer.language_settings_at(selection.start, cx);
8905 let tab_size = settings.tab_size.get();
8906 let mut rows = selection.spanned_rows(false, &display_map);
8907
8908 // Avoid re-outdenting a row that has already been outdented by a
8909 // previous selection.
8910 if let Some(last_row) = last_outdent {
8911 if last_row == rows.start {
8912 rows.start = rows.start.next_row();
8913 }
8914 }
8915 let has_multiple_rows = rows.len() > 1;
8916 for row in rows.iter_rows() {
8917 let indent_size = snapshot.indent_size_for_line(row);
8918 if indent_size.len > 0 {
8919 let deletion_len = match indent_size.kind {
8920 IndentKind::Space => {
8921 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8922 if columns_to_prev_tab_stop == 0 {
8923 tab_size
8924 } else {
8925 columns_to_prev_tab_stop
8926 }
8927 }
8928 IndentKind::Tab => 1,
8929 };
8930 let start = if has_multiple_rows
8931 || deletion_len > selection.start.column
8932 || indent_size.len < selection.start.column
8933 {
8934 0
8935 } else {
8936 selection.start.column - deletion_len
8937 };
8938 deletion_ranges.push(
8939 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8940 );
8941 last_outdent = Some(row);
8942 }
8943 }
8944 }
8945 }
8946
8947 self.transact(window, cx, |this, window, cx| {
8948 this.buffer.update(cx, |buffer, cx| {
8949 let empty_str: Arc<str> = Arc::default();
8950 buffer.edit(
8951 deletion_ranges
8952 .into_iter()
8953 .map(|range| (range, empty_str.clone())),
8954 None,
8955 cx,
8956 );
8957 });
8958 let selections = this.selections.all::<usize>(cx);
8959 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8960 s.select(selections)
8961 });
8962 });
8963 }
8964
8965 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8966 if self.read_only(cx) {
8967 return;
8968 }
8969 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8970 let selections = self
8971 .selections
8972 .all::<usize>(cx)
8973 .into_iter()
8974 .map(|s| s.range());
8975
8976 self.transact(window, cx, |this, window, cx| {
8977 this.buffer.update(cx, |buffer, cx| {
8978 buffer.autoindent_ranges(selections, cx);
8979 });
8980 let selections = this.selections.all::<usize>(cx);
8981 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8982 s.select(selections)
8983 });
8984 });
8985 }
8986
8987 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8988 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8989 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8990 let selections = self.selections.all::<Point>(cx);
8991
8992 let mut new_cursors = Vec::new();
8993 let mut edit_ranges = Vec::new();
8994 let mut selections = selections.iter().peekable();
8995 while let Some(selection) = selections.next() {
8996 let mut rows = selection.spanned_rows(false, &display_map);
8997 let goal_display_column = selection.head().to_display_point(&display_map).column();
8998
8999 // Accumulate contiguous regions of rows that we want to delete.
9000 while let Some(next_selection) = selections.peek() {
9001 let next_rows = next_selection.spanned_rows(false, &display_map);
9002 if next_rows.start <= rows.end {
9003 rows.end = next_rows.end;
9004 selections.next().unwrap();
9005 } else {
9006 break;
9007 }
9008 }
9009
9010 let buffer = &display_map.buffer_snapshot;
9011 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9012 let edit_end;
9013 let cursor_buffer_row;
9014 if buffer.max_point().row >= rows.end.0 {
9015 // If there's a line after the range, delete the \n from the end of the row range
9016 // and position the cursor on the next line.
9017 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9018 cursor_buffer_row = rows.end;
9019 } else {
9020 // If there isn't a line after the range, delete the \n from the line before the
9021 // start of the row range and position the cursor there.
9022 edit_start = edit_start.saturating_sub(1);
9023 edit_end = buffer.len();
9024 cursor_buffer_row = rows.start.previous_row();
9025 }
9026
9027 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9028 *cursor.column_mut() =
9029 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9030
9031 new_cursors.push((
9032 selection.id,
9033 buffer.anchor_after(cursor.to_point(&display_map)),
9034 ));
9035 edit_ranges.push(edit_start..edit_end);
9036 }
9037
9038 self.transact(window, cx, |this, window, cx| {
9039 let buffer = this.buffer.update(cx, |buffer, cx| {
9040 let empty_str: Arc<str> = Arc::default();
9041 buffer.edit(
9042 edit_ranges
9043 .into_iter()
9044 .map(|range| (range, empty_str.clone())),
9045 None,
9046 cx,
9047 );
9048 buffer.snapshot(cx)
9049 });
9050 let new_selections = new_cursors
9051 .into_iter()
9052 .map(|(id, cursor)| {
9053 let cursor = cursor.to_point(&buffer);
9054 Selection {
9055 id,
9056 start: cursor,
9057 end: cursor,
9058 reversed: false,
9059 goal: SelectionGoal::None,
9060 }
9061 })
9062 .collect();
9063
9064 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9065 s.select(new_selections);
9066 });
9067 });
9068 }
9069
9070 pub fn join_lines_impl(
9071 &mut self,
9072 insert_whitespace: bool,
9073 window: &mut Window,
9074 cx: &mut Context<Self>,
9075 ) {
9076 if self.read_only(cx) {
9077 return;
9078 }
9079 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9080 for selection in self.selections.all::<Point>(cx) {
9081 let start = MultiBufferRow(selection.start.row);
9082 // Treat single line selections as if they include the next line. Otherwise this action
9083 // would do nothing for single line selections individual cursors.
9084 let end = if selection.start.row == selection.end.row {
9085 MultiBufferRow(selection.start.row + 1)
9086 } else {
9087 MultiBufferRow(selection.end.row)
9088 };
9089
9090 if let Some(last_row_range) = row_ranges.last_mut() {
9091 if start <= last_row_range.end {
9092 last_row_range.end = end;
9093 continue;
9094 }
9095 }
9096 row_ranges.push(start..end);
9097 }
9098
9099 let snapshot = self.buffer.read(cx).snapshot(cx);
9100 let mut cursor_positions = Vec::new();
9101 for row_range in &row_ranges {
9102 let anchor = snapshot.anchor_before(Point::new(
9103 row_range.end.previous_row().0,
9104 snapshot.line_len(row_range.end.previous_row()),
9105 ));
9106 cursor_positions.push(anchor..anchor);
9107 }
9108
9109 self.transact(window, cx, |this, window, cx| {
9110 for row_range in row_ranges.into_iter().rev() {
9111 for row in row_range.iter_rows().rev() {
9112 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9113 let next_line_row = row.next_row();
9114 let indent = snapshot.indent_size_for_line(next_line_row);
9115 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9116
9117 let replace =
9118 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9119 " "
9120 } else {
9121 ""
9122 };
9123
9124 this.buffer.update(cx, |buffer, cx| {
9125 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9126 });
9127 }
9128 }
9129
9130 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9131 s.select_anchor_ranges(cursor_positions)
9132 });
9133 });
9134 }
9135
9136 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9137 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9138 self.join_lines_impl(true, window, cx);
9139 }
9140
9141 pub fn sort_lines_case_sensitive(
9142 &mut self,
9143 _: &SortLinesCaseSensitive,
9144 window: &mut Window,
9145 cx: &mut Context<Self>,
9146 ) {
9147 self.manipulate_lines(window, cx, |lines| lines.sort())
9148 }
9149
9150 pub fn sort_lines_case_insensitive(
9151 &mut self,
9152 _: &SortLinesCaseInsensitive,
9153 window: &mut Window,
9154 cx: &mut Context<Self>,
9155 ) {
9156 self.manipulate_lines(window, cx, |lines| {
9157 lines.sort_by_key(|line| line.to_lowercase())
9158 })
9159 }
9160
9161 pub fn unique_lines_case_insensitive(
9162 &mut self,
9163 _: &UniqueLinesCaseInsensitive,
9164 window: &mut Window,
9165 cx: &mut Context<Self>,
9166 ) {
9167 self.manipulate_lines(window, cx, |lines| {
9168 let mut seen = HashSet::default();
9169 lines.retain(|line| seen.insert(line.to_lowercase()));
9170 })
9171 }
9172
9173 pub fn unique_lines_case_sensitive(
9174 &mut self,
9175 _: &UniqueLinesCaseSensitive,
9176 window: &mut Window,
9177 cx: &mut Context<Self>,
9178 ) {
9179 self.manipulate_lines(window, cx, |lines| {
9180 let mut seen = HashSet::default();
9181 lines.retain(|line| seen.insert(*line));
9182 })
9183 }
9184
9185 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9186 let Some(project) = self.project.clone() else {
9187 return;
9188 };
9189 self.reload(project, window, cx)
9190 .detach_and_notify_err(window, cx);
9191 }
9192
9193 pub fn restore_file(
9194 &mut self,
9195 _: &::git::RestoreFile,
9196 window: &mut Window,
9197 cx: &mut Context<Self>,
9198 ) {
9199 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9200 let mut buffer_ids = HashSet::default();
9201 let snapshot = self.buffer().read(cx).snapshot(cx);
9202 for selection in self.selections.all::<usize>(cx) {
9203 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9204 }
9205
9206 let buffer = self.buffer().read(cx);
9207 let ranges = buffer_ids
9208 .into_iter()
9209 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9210 .collect::<Vec<_>>();
9211
9212 self.restore_hunks_in_ranges(ranges, window, cx);
9213 }
9214
9215 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9216 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9217 let selections = self
9218 .selections
9219 .all(cx)
9220 .into_iter()
9221 .map(|s| s.range())
9222 .collect();
9223 self.restore_hunks_in_ranges(selections, window, cx);
9224 }
9225
9226 pub fn restore_hunks_in_ranges(
9227 &mut self,
9228 ranges: Vec<Range<Point>>,
9229 window: &mut Window,
9230 cx: &mut Context<Editor>,
9231 ) {
9232 let mut revert_changes = HashMap::default();
9233 let chunk_by = self
9234 .snapshot(window, cx)
9235 .hunks_for_ranges(ranges)
9236 .into_iter()
9237 .chunk_by(|hunk| hunk.buffer_id);
9238 for (buffer_id, hunks) in &chunk_by {
9239 let hunks = hunks.collect::<Vec<_>>();
9240 for hunk in &hunks {
9241 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9242 }
9243 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9244 }
9245 drop(chunk_by);
9246 if !revert_changes.is_empty() {
9247 self.transact(window, cx, |editor, window, cx| {
9248 editor.restore(revert_changes, window, cx);
9249 });
9250 }
9251 }
9252
9253 pub fn open_active_item_in_terminal(
9254 &mut self,
9255 _: &OpenInTerminal,
9256 window: &mut Window,
9257 cx: &mut Context<Self>,
9258 ) {
9259 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9260 let project_path = buffer.read(cx).project_path(cx)?;
9261 let project = self.project.as_ref()?.read(cx);
9262 let entry = project.entry_for_path(&project_path, cx)?;
9263 let parent = match &entry.canonical_path {
9264 Some(canonical_path) => canonical_path.to_path_buf(),
9265 None => project.absolute_path(&project_path, cx)?,
9266 }
9267 .parent()?
9268 .to_path_buf();
9269 Some(parent)
9270 }) {
9271 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9272 }
9273 }
9274
9275 fn set_breakpoint_context_menu(
9276 &mut self,
9277 display_row: DisplayRow,
9278 position: Option<Anchor>,
9279 clicked_point: gpui::Point<Pixels>,
9280 window: &mut Window,
9281 cx: &mut Context<Self>,
9282 ) {
9283 if !cx.has_flag::<DebuggerFeatureFlag>() {
9284 return;
9285 }
9286 let source = self
9287 .buffer
9288 .read(cx)
9289 .snapshot(cx)
9290 .anchor_before(Point::new(display_row.0, 0u32));
9291
9292 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9293
9294 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9295 self,
9296 source,
9297 clicked_point,
9298 context_menu,
9299 window,
9300 cx,
9301 );
9302 }
9303
9304 fn add_edit_breakpoint_block(
9305 &mut self,
9306 anchor: Anchor,
9307 breakpoint: &Breakpoint,
9308 edit_action: BreakpointPromptEditAction,
9309 window: &mut Window,
9310 cx: &mut Context<Self>,
9311 ) {
9312 let weak_editor = cx.weak_entity();
9313 let bp_prompt = cx.new(|cx| {
9314 BreakpointPromptEditor::new(
9315 weak_editor,
9316 anchor,
9317 breakpoint.clone(),
9318 edit_action,
9319 window,
9320 cx,
9321 )
9322 });
9323
9324 let height = bp_prompt.update(cx, |this, cx| {
9325 this.prompt
9326 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9327 });
9328 let cloned_prompt = bp_prompt.clone();
9329 let blocks = vec![BlockProperties {
9330 style: BlockStyle::Sticky,
9331 placement: BlockPlacement::Above(anchor),
9332 height: Some(height),
9333 render: Arc::new(move |cx| {
9334 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9335 cloned_prompt.clone().into_any_element()
9336 }),
9337 priority: 0,
9338 }];
9339
9340 let focus_handle = bp_prompt.focus_handle(cx);
9341 window.focus(&focus_handle);
9342
9343 let block_ids = self.insert_blocks(blocks, None, cx);
9344 bp_prompt.update(cx, |prompt, _| {
9345 prompt.add_block_ids(block_ids);
9346 });
9347 }
9348
9349 pub(crate) fn breakpoint_at_row(
9350 &self,
9351 row: u32,
9352 window: &mut Window,
9353 cx: &mut Context<Self>,
9354 ) -> Option<(Anchor, Breakpoint)> {
9355 let snapshot = self.snapshot(window, cx);
9356 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9357
9358 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9359 }
9360
9361 pub(crate) fn breakpoint_at_anchor(
9362 &self,
9363 breakpoint_position: Anchor,
9364 snapshot: &EditorSnapshot,
9365 cx: &mut Context<Self>,
9366 ) -> Option<(Anchor, Breakpoint)> {
9367 let project = self.project.clone()?;
9368
9369 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9370 snapshot
9371 .buffer_snapshot
9372 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9373 })?;
9374
9375 let enclosing_excerpt = breakpoint_position.excerpt_id;
9376 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9377 let buffer_snapshot = buffer.read(cx).snapshot();
9378
9379 let row = buffer_snapshot
9380 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9381 .row;
9382
9383 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9384 let anchor_end = snapshot
9385 .buffer_snapshot
9386 .anchor_after(Point::new(row, line_len));
9387
9388 let bp = self
9389 .breakpoint_store
9390 .as_ref()?
9391 .read_with(cx, |breakpoint_store, cx| {
9392 breakpoint_store
9393 .breakpoints(
9394 &buffer,
9395 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9396 &buffer_snapshot,
9397 cx,
9398 )
9399 .next()
9400 .and_then(|(anchor, bp)| {
9401 let breakpoint_row = buffer_snapshot
9402 .summary_for_anchor::<text::PointUtf16>(anchor)
9403 .row;
9404
9405 if breakpoint_row == row {
9406 snapshot
9407 .buffer_snapshot
9408 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9409 .map(|anchor| (anchor, bp.clone()))
9410 } else {
9411 None
9412 }
9413 })
9414 });
9415 bp
9416 }
9417
9418 pub fn edit_log_breakpoint(
9419 &mut self,
9420 _: &EditLogBreakpoint,
9421 window: &mut Window,
9422 cx: &mut Context<Self>,
9423 ) {
9424 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9425 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9426 message: None,
9427 state: BreakpointState::Enabled,
9428 condition: None,
9429 hit_condition: None,
9430 });
9431
9432 self.add_edit_breakpoint_block(
9433 anchor,
9434 &breakpoint,
9435 BreakpointPromptEditAction::Log,
9436 window,
9437 cx,
9438 );
9439 }
9440 }
9441
9442 fn breakpoints_at_cursors(
9443 &self,
9444 window: &mut Window,
9445 cx: &mut Context<Self>,
9446 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9447 let snapshot = self.snapshot(window, cx);
9448 let cursors = self
9449 .selections
9450 .disjoint_anchors()
9451 .into_iter()
9452 .map(|selection| {
9453 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9454
9455 let breakpoint_position = self
9456 .breakpoint_at_row(cursor_position.row, window, cx)
9457 .map(|bp| bp.0)
9458 .unwrap_or_else(|| {
9459 snapshot
9460 .display_snapshot
9461 .buffer_snapshot
9462 .anchor_after(Point::new(cursor_position.row, 0))
9463 });
9464
9465 let breakpoint = self
9466 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9467 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9468
9469 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9470 })
9471 // 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.
9472 .collect::<HashMap<Anchor, _>>();
9473
9474 cursors.into_iter().collect()
9475 }
9476
9477 pub fn enable_breakpoint(
9478 &mut self,
9479 _: &crate::actions::EnableBreakpoint,
9480 window: &mut Window,
9481 cx: &mut Context<Self>,
9482 ) {
9483 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9484 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9485 continue;
9486 };
9487 self.edit_breakpoint_at_anchor(
9488 anchor,
9489 breakpoint,
9490 BreakpointEditAction::InvertState,
9491 cx,
9492 );
9493 }
9494 }
9495
9496 pub fn disable_breakpoint(
9497 &mut self,
9498 _: &crate::actions::DisableBreakpoint,
9499 window: &mut Window,
9500 cx: &mut Context<Self>,
9501 ) {
9502 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9503 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9504 continue;
9505 };
9506 self.edit_breakpoint_at_anchor(
9507 anchor,
9508 breakpoint,
9509 BreakpointEditAction::InvertState,
9510 cx,
9511 );
9512 }
9513 }
9514
9515 pub fn toggle_breakpoint(
9516 &mut self,
9517 _: &crate::actions::ToggleBreakpoint,
9518 window: &mut Window,
9519 cx: &mut Context<Self>,
9520 ) {
9521 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9522 if let Some(breakpoint) = breakpoint {
9523 self.edit_breakpoint_at_anchor(
9524 anchor,
9525 breakpoint,
9526 BreakpointEditAction::Toggle,
9527 cx,
9528 );
9529 } else {
9530 self.edit_breakpoint_at_anchor(
9531 anchor,
9532 Breakpoint::new_standard(),
9533 BreakpointEditAction::Toggle,
9534 cx,
9535 );
9536 }
9537 }
9538 }
9539
9540 pub fn edit_breakpoint_at_anchor(
9541 &mut self,
9542 breakpoint_position: Anchor,
9543 breakpoint: Breakpoint,
9544 edit_action: BreakpointEditAction,
9545 cx: &mut Context<Self>,
9546 ) {
9547 let Some(breakpoint_store) = &self.breakpoint_store else {
9548 return;
9549 };
9550
9551 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9552 if breakpoint_position == Anchor::min() {
9553 self.buffer()
9554 .read(cx)
9555 .excerpt_buffer_ids()
9556 .into_iter()
9557 .next()
9558 } else {
9559 None
9560 }
9561 }) else {
9562 return;
9563 };
9564
9565 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9566 return;
9567 };
9568
9569 breakpoint_store.update(cx, |breakpoint_store, cx| {
9570 breakpoint_store.toggle_breakpoint(
9571 buffer,
9572 (breakpoint_position.text_anchor, breakpoint),
9573 edit_action,
9574 cx,
9575 );
9576 });
9577
9578 cx.notify();
9579 }
9580
9581 #[cfg(any(test, feature = "test-support"))]
9582 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9583 self.breakpoint_store.clone()
9584 }
9585
9586 pub fn prepare_restore_change(
9587 &self,
9588 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9589 hunk: &MultiBufferDiffHunk,
9590 cx: &mut App,
9591 ) -> Option<()> {
9592 if hunk.is_created_file() {
9593 return None;
9594 }
9595 let buffer = self.buffer.read(cx);
9596 let diff = buffer.diff_for(hunk.buffer_id)?;
9597 let buffer = buffer.buffer(hunk.buffer_id)?;
9598 let buffer = buffer.read(cx);
9599 let original_text = diff
9600 .read(cx)
9601 .base_text()
9602 .as_rope()
9603 .slice(hunk.diff_base_byte_range.clone());
9604 let buffer_snapshot = buffer.snapshot();
9605 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9606 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9607 probe
9608 .0
9609 .start
9610 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9611 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9612 }) {
9613 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9614 Some(())
9615 } else {
9616 None
9617 }
9618 }
9619
9620 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9621 self.manipulate_lines(window, cx, |lines| lines.reverse())
9622 }
9623
9624 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9625 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9626 }
9627
9628 fn manipulate_lines<Fn>(
9629 &mut self,
9630 window: &mut Window,
9631 cx: &mut Context<Self>,
9632 mut callback: Fn,
9633 ) where
9634 Fn: FnMut(&mut Vec<&str>),
9635 {
9636 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9637
9638 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9639 let buffer = self.buffer.read(cx).snapshot(cx);
9640
9641 let mut edits = Vec::new();
9642
9643 let selections = self.selections.all::<Point>(cx);
9644 let mut selections = selections.iter().peekable();
9645 let mut contiguous_row_selections = Vec::new();
9646 let mut new_selections = Vec::new();
9647 let mut added_lines = 0;
9648 let mut removed_lines = 0;
9649
9650 while let Some(selection) = selections.next() {
9651 let (start_row, end_row) = consume_contiguous_rows(
9652 &mut contiguous_row_selections,
9653 selection,
9654 &display_map,
9655 &mut selections,
9656 );
9657
9658 let start_point = Point::new(start_row.0, 0);
9659 let end_point = Point::new(
9660 end_row.previous_row().0,
9661 buffer.line_len(end_row.previous_row()),
9662 );
9663 let text = buffer
9664 .text_for_range(start_point..end_point)
9665 .collect::<String>();
9666
9667 let mut lines = text.split('\n').collect_vec();
9668
9669 let lines_before = lines.len();
9670 callback(&mut lines);
9671 let lines_after = lines.len();
9672
9673 edits.push((start_point..end_point, lines.join("\n")));
9674
9675 // Selections must change based on added and removed line count
9676 let start_row =
9677 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9678 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9679 new_selections.push(Selection {
9680 id: selection.id,
9681 start: start_row,
9682 end: end_row,
9683 goal: SelectionGoal::None,
9684 reversed: selection.reversed,
9685 });
9686
9687 if lines_after > lines_before {
9688 added_lines += lines_after - lines_before;
9689 } else if lines_before > lines_after {
9690 removed_lines += lines_before - lines_after;
9691 }
9692 }
9693
9694 self.transact(window, cx, |this, window, cx| {
9695 let buffer = this.buffer.update(cx, |buffer, cx| {
9696 buffer.edit(edits, None, cx);
9697 buffer.snapshot(cx)
9698 });
9699
9700 // Recalculate offsets on newly edited buffer
9701 let new_selections = new_selections
9702 .iter()
9703 .map(|s| {
9704 let start_point = Point::new(s.start.0, 0);
9705 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9706 Selection {
9707 id: s.id,
9708 start: buffer.point_to_offset(start_point),
9709 end: buffer.point_to_offset(end_point),
9710 goal: s.goal,
9711 reversed: s.reversed,
9712 }
9713 })
9714 .collect();
9715
9716 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9717 s.select(new_selections);
9718 });
9719
9720 this.request_autoscroll(Autoscroll::fit(), cx);
9721 });
9722 }
9723
9724 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9725 self.manipulate_text(window, cx, |text| {
9726 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9727 if has_upper_case_characters {
9728 text.to_lowercase()
9729 } else {
9730 text.to_uppercase()
9731 }
9732 })
9733 }
9734
9735 pub fn convert_to_upper_case(
9736 &mut self,
9737 _: &ConvertToUpperCase,
9738 window: &mut Window,
9739 cx: &mut Context<Self>,
9740 ) {
9741 self.manipulate_text(window, cx, |text| text.to_uppercase())
9742 }
9743
9744 pub fn convert_to_lower_case(
9745 &mut self,
9746 _: &ConvertToLowerCase,
9747 window: &mut Window,
9748 cx: &mut Context<Self>,
9749 ) {
9750 self.manipulate_text(window, cx, |text| text.to_lowercase())
9751 }
9752
9753 pub fn convert_to_title_case(
9754 &mut self,
9755 _: &ConvertToTitleCase,
9756 window: &mut Window,
9757 cx: &mut Context<Self>,
9758 ) {
9759 self.manipulate_text(window, cx, |text| {
9760 text.split('\n')
9761 .map(|line| line.to_case(Case::Title))
9762 .join("\n")
9763 })
9764 }
9765
9766 pub fn convert_to_snake_case(
9767 &mut self,
9768 _: &ConvertToSnakeCase,
9769 window: &mut Window,
9770 cx: &mut Context<Self>,
9771 ) {
9772 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9773 }
9774
9775 pub fn convert_to_kebab_case(
9776 &mut self,
9777 _: &ConvertToKebabCase,
9778 window: &mut Window,
9779 cx: &mut Context<Self>,
9780 ) {
9781 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9782 }
9783
9784 pub fn convert_to_upper_camel_case(
9785 &mut self,
9786 _: &ConvertToUpperCamelCase,
9787 window: &mut Window,
9788 cx: &mut Context<Self>,
9789 ) {
9790 self.manipulate_text(window, cx, |text| {
9791 text.split('\n')
9792 .map(|line| line.to_case(Case::UpperCamel))
9793 .join("\n")
9794 })
9795 }
9796
9797 pub fn convert_to_lower_camel_case(
9798 &mut self,
9799 _: &ConvertToLowerCamelCase,
9800 window: &mut Window,
9801 cx: &mut Context<Self>,
9802 ) {
9803 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9804 }
9805
9806 pub fn convert_to_opposite_case(
9807 &mut self,
9808 _: &ConvertToOppositeCase,
9809 window: &mut Window,
9810 cx: &mut Context<Self>,
9811 ) {
9812 self.manipulate_text(window, cx, |text| {
9813 text.chars()
9814 .fold(String::with_capacity(text.len()), |mut t, c| {
9815 if c.is_uppercase() {
9816 t.extend(c.to_lowercase());
9817 } else {
9818 t.extend(c.to_uppercase());
9819 }
9820 t
9821 })
9822 })
9823 }
9824
9825 pub fn convert_to_rot13(
9826 &mut self,
9827 _: &ConvertToRot13,
9828 window: &mut Window,
9829 cx: &mut Context<Self>,
9830 ) {
9831 self.manipulate_text(window, cx, |text| {
9832 text.chars()
9833 .map(|c| match c {
9834 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9835 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9836 _ => c,
9837 })
9838 .collect()
9839 })
9840 }
9841
9842 pub fn convert_to_rot47(
9843 &mut self,
9844 _: &ConvertToRot47,
9845 window: &mut Window,
9846 cx: &mut Context<Self>,
9847 ) {
9848 self.manipulate_text(window, cx, |text| {
9849 text.chars()
9850 .map(|c| {
9851 let code_point = c as u32;
9852 if code_point >= 33 && code_point <= 126 {
9853 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9854 }
9855 c
9856 })
9857 .collect()
9858 })
9859 }
9860
9861 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9862 where
9863 Fn: FnMut(&str) -> String,
9864 {
9865 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9866 let buffer = self.buffer.read(cx).snapshot(cx);
9867
9868 let mut new_selections = Vec::new();
9869 let mut edits = Vec::new();
9870 let mut selection_adjustment = 0i32;
9871
9872 for selection in self.selections.all::<usize>(cx) {
9873 let selection_is_empty = selection.is_empty();
9874
9875 let (start, end) = if selection_is_empty {
9876 let word_range = movement::surrounding_word(
9877 &display_map,
9878 selection.start.to_display_point(&display_map),
9879 );
9880 let start = word_range.start.to_offset(&display_map, Bias::Left);
9881 let end = word_range.end.to_offset(&display_map, Bias::Left);
9882 (start, end)
9883 } else {
9884 (selection.start, selection.end)
9885 };
9886
9887 let text = buffer.text_for_range(start..end).collect::<String>();
9888 let old_length = text.len() as i32;
9889 let text = callback(&text);
9890
9891 new_selections.push(Selection {
9892 start: (start as i32 - selection_adjustment) as usize,
9893 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9894 goal: SelectionGoal::None,
9895 ..selection
9896 });
9897
9898 selection_adjustment += old_length - text.len() as i32;
9899
9900 edits.push((start..end, text));
9901 }
9902
9903 self.transact(window, cx, |this, window, cx| {
9904 this.buffer.update(cx, |buffer, cx| {
9905 buffer.edit(edits, None, cx);
9906 });
9907
9908 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9909 s.select(new_selections);
9910 });
9911
9912 this.request_autoscroll(Autoscroll::fit(), cx);
9913 });
9914 }
9915
9916 pub fn duplicate(
9917 &mut self,
9918 upwards: bool,
9919 whole_lines: bool,
9920 window: &mut Window,
9921 cx: &mut Context<Self>,
9922 ) {
9923 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9924
9925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9926 let buffer = &display_map.buffer_snapshot;
9927 let selections = self.selections.all::<Point>(cx);
9928
9929 let mut edits = Vec::new();
9930 let mut selections_iter = selections.iter().peekable();
9931 while let Some(selection) = selections_iter.next() {
9932 let mut rows = selection.spanned_rows(false, &display_map);
9933 // duplicate line-wise
9934 if whole_lines || selection.start == selection.end {
9935 // Avoid duplicating the same lines twice.
9936 while let Some(next_selection) = selections_iter.peek() {
9937 let next_rows = next_selection.spanned_rows(false, &display_map);
9938 if next_rows.start < rows.end {
9939 rows.end = next_rows.end;
9940 selections_iter.next().unwrap();
9941 } else {
9942 break;
9943 }
9944 }
9945
9946 // Copy the text from the selected row region and splice it either at the start
9947 // or end of the region.
9948 let start = Point::new(rows.start.0, 0);
9949 let end = Point::new(
9950 rows.end.previous_row().0,
9951 buffer.line_len(rows.end.previous_row()),
9952 );
9953 let text = buffer
9954 .text_for_range(start..end)
9955 .chain(Some("\n"))
9956 .collect::<String>();
9957 let insert_location = if upwards {
9958 Point::new(rows.end.0, 0)
9959 } else {
9960 start
9961 };
9962 edits.push((insert_location..insert_location, text));
9963 } else {
9964 // duplicate character-wise
9965 let start = selection.start;
9966 let end = selection.end;
9967 let text = buffer.text_for_range(start..end).collect::<String>();
9968 edits.push((selection.end..selection.end, text));
9969 }
9970 }
9971
9972 self.transact(window, cx, |this, _, cx| {
9973 this.buffer.update(cx, |buffer, cx| {
9974 buffer.edit(edits, None, cx);
9975 });
9976
9977 this.request_autoscroll(Autoscroll::fit(), cx);
9978 });
9979 }
9980
9981 pub fn duplicate_line_up(
9982 &mut self,
9983 _: &DuplicateLineUp,
9984 window: &mut Window,
9985 cx: &mut Context<Self>,
9986 ) {
9987 self.duplicate(true, true, window, cx);
9988 }
9989
9990 pub fn duplicate_line_down(
9991 &mut self,
9992 _: &DuplicateLineDown,
9993 window: &mut Window,
9994 cx: &mut Context<Self>,
9995 ) {
9996 self.duplicate(false, true, window, cx);
9997 }
9998
9999 pub fn duplicate_selection(
10000 &mut self,
10001 _: &DuplicateSelection,
10002 window: &mut Window,
10003 cx: &mut Context<Self>,
10004 ) {
10005 self.duplicate(false, false, window, cx);
10006 }
10007
10008 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10009 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10010
10011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10012 let buffer = self.buffer.read(cx).snapshot(cx);
10013
10014 let mut edits = Vec::new();
10015 let mut unfold_ranges = Vec::new();
10016 let mut refold_creases = Vec::new();
10017
10018 let selections = self.selections.all::<Point>(cx);
10019 let mut selections = selections.iter().peekable();
10020 let mut contiguous_row_selections = Vec::new();
10021 let mut new_selections = Vec::new();
10022
10023 while let Some(selection) = selections.next() {
10024 // Find all the selections that span a contiguous row range
10025 let (start_row, end_row) = consume_contiguous_rows(
10026 &mut contiguous_row_selections,
10027 selection,
10028 &display_map,
10029 &mut selections,
10030 );
10031
10032 // Move the text spanned by the row range to be before the line preceding the row range
10033 if start_row.0 > 0 {
10034 let range_to_move = Point::new(
10035 start_row.previous_row().0,
10036 buffer.line_len(start_row.previous_row()),
10037 )
10038 ..Point::new(
10039 end_row.previous_row().0,
10040 buffer.line_len(end_row.previous_row()),
10041 );
10042 let insertion_point = display_map
10043 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10044 .0;
10045
10046 // Don't move lines across excerpts
10047 if buffer
10048 .excerpt_containing(insertion_point..range_to_move.end)
10049 .is_some()
10050 {
10051 let text = buffer
10052 .text_for_range(range_to_move.clone())
10053 .flat_map(|s| s.chars())
10054 .skip(1)
10055 .chain(['\n'])
10056 .collect::<String>();
10057
10058 edits.push((
10059 buffer.anchor_after(range_to_move.start)
10060 ..buffer.anchor_before(range_to_move.end),
10061 String::new(),
10062 ));
10063 let insertion_anchor = buffer.anchor_after(insertion_point);
10064 edits.push((insertion_anchor..insertion_anchor, text));
10065
10066 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10067
10068 // Move selections up
10069 new_selections.extend(contiguous_row_selections.drain(..).map(
10070 |mut selection| {
10071 selection.start.row -= row_delta;
10072 selection.end.row -= row_delta;
10073 selection
10074 },
10075 ));
10076
10077 // Move folds up
10078 unfold_ranges.push(range_to_move.clone());
10079 for fold in display_map.folds_in_range(
10080 buffer.anchor_before(range_to_move.start)
10081 ..buffer.anchor_after(range_to_move.end),
10082 ) {
10083 let mut start = fold.range.start.to_point(&buffer);
10084 let mut end = fold.range.end.to_point(&buffer);
10085 start.row -= row_delta;
10086 end.row -= row_delta;
10087 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10088 }
10089 }
10090 }
10091
10092 // If we didn't move line(s), preserve the existing selections
10093 new_selections.append(&mut contiguous_row_selections);
10094 }
10095
10096 self.transact(window, cx, |this, window, cx| {
10097 this.unfold_ranges(&unfold_ranges, true, true, cx);
10098 this.buffer.update(cx, |buffer, cx| {
10099 for (range, text) in edits {
10100 buffer.edit([(range, text)], None, cx);
10101 }
10102 });
10103 this.fold_creases(refold_creases, true, window, cx);
10104 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10105 s.select(new_selections);
10106 })
10107 });
10108 }
10109
10110 pub fn move_line_down(
10111 &mut self,
10112 _: &MoveLineDown,
10113 window: &mut Window,
10114 cx: &mut Context<Self>,
10115 ) {
10116 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10117
10118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10119 let buffer = self.buffer.read(cx).snapshot(cx);
10120
10121 let mut edits = Vec::new();
10122 let mut unfold_ranges = Vec::new();
10123 let mut refold_creases = Vec::new();
10124
10125 let selections = self.selections.all::<Point>(cx);
10126 let mut selections = selections.iter().peekable();
10127 let mut contiguous_row_selections = Vec::new();
10128 let mut new_selections = Vec::new();
10129
10130 while let Some(selection) = selections.next() {
10131 // Find all the selections that span a contiguous row range
10132 let (start_row, end_row) = consume_contiguous_rows(
10133 &mut contiguous_row_selections,
10134 selection,
10135 &display_map,
10136 &mut selections,
10137 );
10138
10139 // Move the text spanned by the row range to be after the last line of the row range
10140 if end_row.0 <= buffer.max_point().row {
10141 let range_to_move =
10142 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10143 let insertion_point = display_map
10144 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10145 .0;
10146
10147 // Don't move lines across excerpt boundaries
10148 if buffer
10149 .excerpt_containing(range_to_move.start..insertion_point)
10150 .is_some()
10151 {
10152 let mut text = String::from("\n");
10153 text.extend(buffer.text_for_range(range_to_move.clone()));
10154 text.pop(); // Drop trailing newline
10155 edits.push((
10156 buffer.anchor_after(range_to_move.start)
10157 ..buffer.anchor_before(range_to_move.end),
10158 String::new(),
10159 ));
10160 let insertion_anchor = buffer.anchor_after(insertion_point);
10161 edits.push((insertion_anchor..insertion_anchor, text));
10162
10163 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10164
10165 // Move selections down
10166 new_selections.extend(contiguous_row_selections.drain(..).map(
10167 |mut selection| {
10168 selection.start.row += row_delta;
10169 selection.end.row += row_delta;
10170 selection
10171 },
10172 ));
10173
10174 // Move folds down
10175 unfold_ranges.push(range_to_move.clone());
10176 for fold in display_map.folds_in_range(
10177 buffer.anchor_before(range_to_move.start)
10178 ..buffer.anchor_after(range_to_move.end),
10179 ) {
10180 let mut start = fold.range.start.to_point(&buffer);
10181 let mut end = fold.range.end.to_point(&buffer);
10182 start.row += row_delta;
10183 end.row += row_delta;
10184 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10185 }
10186 }
10187 }
10188
10189 // If we didn't move line(s), preserve the existing selections
10190 new_selections.append(&mut contiguous_row_selections);
10191 }
10192
10193 self.transact(window, cx, |this, window, cx| {
10194 this.unfold_ranges(&unfold_ranges, true, true, cx);
10195 this.buffer.update(cx, |buffer, cx| {
10196 for (range, text) in edits {
10197 buffer.edit([(range, text)], None, cx);
10198 }
10199 });
10200 this.fold_creases(refold_creases, true, window, cx);
10201 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10202 s.select(new_selections)
10203 });
10204 });
10205 }
10206
10207 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10208 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10209 let text_layout_details = &self.text_layout_details(window);
10210 self.transact(window, cx, |this, window, cx| {
10211 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10212 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10213 s.move_with(|display_map, selection| {
10214 if !selection.is_empty() {
10215 return;
10216 }
10217
10218 let mut head = selection.head();
10219 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10220 if head.column() == display_map.line_len(head.row()) {
10221 transpose_offset = display_map
10222 .buffer_snapshot
10223 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10224 }
10225
10226 if transpose_offset == 0 {
10227 return;
10228 }
10229
10230 *head.column_mut() += 1;
10231 head = display_map.clip_point(head, Bias::Right);
10232 let goal = SelectionGoal::HorizontalPosition(
10233 display_map
10234 .x_for_display_point(head, text_layout_details)
10235 .into(),
10236 );
10237 selection.collapse_to(head, goal);
10238
10239 let transpose_start = display_map
10240 .buffer_snapshot
10241 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10242 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10243 let transpose_end = display_map
10244 .buffer_snapshot
10245 .clip_offset(transpose_offset + 1, Bias::Right);
10246 if let Some(ch) =
10247 display_map.buffer_snapshot.chars_at(transpose_start).next()
10248 {
10249 edits.push((transpose_start..transpose_offset, String::new()));
10250 edits.push((transpose_end..transpose_end, ch.to_string()));
10251 }
10252 }
10253 });
10254 edits
10255 });
10256 this.buffer
10257 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10258 let selections = this.selections.all::<usize>(cx);
10259 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10260 s.select(selections);
10261 });
10262 });
10263 }
10264
10265 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10266 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10267 self.rewrap_impl(RewrapOptions::default(), cx)
10268 }
10269
10270 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10271 let buffer = self.buffer.read(cx).snapshot(cx);
10272 let selections = self.selections.all::<Point>(cx);
10273 let mut selections = selections.iter().peekable();
10274
10275 let mut edits = Vec::new();
10276 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10277
10278 while let Some(selection) = selections.next() {
10279 let mut start_row = selection.start.row;
10280 let mut end_row = selection.end.row;
10281
10282 // Skip selections that overlap with a range that has already been rewrapped.
10283 let selection_range = start_row..end_row;
10284 if rewrapped_row_ranges
10285 .iter()
10286 .any(|range| range.overlaps(&selection_range))
10287 {
10288 continue;
10289 }
10290
10291 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10292
10293 // Since not all lines in the selection may be at the same indent
10294 // level, choose the indent size that is the most common between all
10295 // of the lines.
10296 //
10297 // If there is a tie, we use the deepest indent.
10298 let (indent_size, indent_end) = {
10299 let mut indent_size_occurrences = HashMap::default();
10300 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10301
10302 for row in start_row..=end_row {
10303 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10304 rows_by_indent_size.entry(indent).or_default().push(row);
10305 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10306 }
10307
10308 let indent_size = indent_size_occurrences
10309 .into_iter()
10310 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10311 .map(|(indent, _)| indent)
10312 .unwrap_or_default();
10313 let row = rows_by_indent_size[&indent_size][0];
10314 let indent_end = Point::new(row, indent_size.len);
10315
10316 (indent_size, indent_end)
10317 };
10318
10319 let mut line_prefix = indent_size.chars().collect::<String>();
10320
10321 let mut inside_comment = false;
10322 if let Some(comment_prefix) =
10323 buffer
10324 .language_scope_at(selection.head())
10325 .and_then(|language| {
10326 language
10327 .line_comment_prefixes()
10328 .iter()
10329 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10330 .cloned()
10331 })
10332 {
10333 line_prefix.push_str(&comment_prefix);
10334 inside_comment = true;
10335 }
10336
10337 let language_settings = buffer.language_settings_at(selection.head(), cx);
10338 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10339 RewrapBehavior::InComments => inside_comment,
10340 RewrapBehavior::InSelections => !selection.is_empty(),
10341 RewrapBehavior::Anywhere => true,
10342 };
10343
10344 let should_rewrap = options.override_language_settings
10345 || allow_rewrap_based_on_language
10346 || self.hard_wrap.is_some();
10347 if !should_rewrap {
10348 continue;
10349 }
10350
10351 if selection.is_empty() {
10352 'expand_upwards: while start_row > 0 {
10353 let prev_row = start_row - 1;
10354 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10355 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10356 {
10357 start_row = prev_row;
10358 } else {
10359 break 'expand_upwards;
10360 }
10361 }
10362
10363 'expand_downwards: while end_row < buffer.max_point().row {
10364 let next_row = end_row + 1;
10365 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10366 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10367 {
10368 end_row = next_row;
10369 } else {
10370 break 'expand_downwards;
10371 }
10372 }
10373 }
10374
10375 let start = Point::new(start_row, 0);
10376 let start_offset = start.to_offset(&buffer);
10377 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10378 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10379 let Some(lines_without_prefixes) = selection_text
10380 .lines()
10381 .map(|line| {
10382 line.strip_prefix(&line_prefix)
10383 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10384 .ok_or_else(|| {
10385 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10386 })
10387 })
10388 .collect::<Result<Vec<_>, _>>()
10389 .log_err()
10390 else {
10391 continue;
10392 };
10393
10394 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10395 buffer
10396 .language_settings_at(Point::new(start_row, 0), cx)
10397 .preferred_line_length as usize
10398 });
10399 let wrapped_text = wrap_with_prefix(
10400 line_prefix,
10401 lines_without_prefixes.join("\n"),
10402 wrap_column,
10403 tab_size,
10404 options.preserve_existing_whitespace,
10405 );
10406
10407 // TODO: should always use char-based diff while still supporting cursor behavior that
10408 // matches vim.
10409 let mut diff_options = DiffOptions::default();
10410 if options.override_language_settings {
10411 diff_options.max_word_diff_len = 0;
10412 diff_options.max_word_diff_line_count = 0;
10413 } else {
10414 diff_options.max_word_diff_len = usize::MAX;
10415 diff_options.max_word_diff_line_count = usize::MAX;
10416 }
10417
10418 for (old_range, new_text) in
10419 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10420 {
10421 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10422 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10423 edits.push((edit_start..edit_end, new_text));
10424 }
10425
10426 rewrapped_row_ranges.push(start_row..=end_row);
10427 }
10428
10429 self.buffer
10430 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10431 }
10432
10433 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10434 let mut text = String::new();
10435 let buffer = self.buffer.read(cx).snapshot(cx);
10436 let mut selections = self.selections.all::<Point>(cx);
10437 let mut clipboard_selections = Vec::with_capacity(selections.len());
10438 {
10439 let max_point = buffer.max_point();
10440 let mut is_first = true;
10441 for selection in &mut selections {
10442 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10443 if is_entire_line {
10444 selection.start = Point::new(selection.start.row, 0);
10445 if !selection.is_empty() && selection.end.column == 0 {
10446 selection.end = cmp::min(max_point, selection.end);
10447 } else {
10448 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10449 }
10450 selection.goal = SelectionGoal::None;
10451 }
10452 if is_first {
10453 is_first = false;
10454 } else {
10455 text += "\n";
10456 }
10457 let mut len = 0;
10458 for chunk in buffer.text_for_range(selection.start..selection.end) {
10459 text.push_str(chunk);
10460 len += chunk.len();
10461 }
10462 clipboard_selections.push(ClipboardSelection {
10463 len,
10464 is_entire_line,
10465 first_line_indent: buffer
10466 .indent_size_for_line(MultiBufferRow(selection.start.row))
10467 .len,
10468 });
10469 }
10470 }
10471
10472 self.transact(window, cx, |this, window, cx| {
10473 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10474 s.select(selections);
10475 });
10476 this.insert("", window, cx);
10477 });
10478 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10479 }
10480
10481 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10482 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10483 let item = self.cut_common(window, cx);
10484 cx.write_to_clipboard(item);
10485 }
10486
10487 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10488 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10489 self.change_selections(None, window, cx, |s| {
10490 s.move_with(|snapshot, sel| {
10491 if sel.is_empty() {
10492 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10493 }
10494 });
10495 });
10496 let item = self.cut_common(window, cx);
10497 cx.set_global(KillRing(item))
10498 }
10499
10500 pub fn kill_ring_yank(
10501 &mut self,
10502 _: &KillRingYank,
10503 window: &mut Window,
10504 cx: &mut Context<Self>,
10505 ) {
10506 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10507 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10508 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10509 (kill_ring.text().to_string(), kill_ring.metadata_json())
10510 } else {
10511 return;
10512 }
10513 } else {
10514 return;
10515 };
10516 self.do_paste(&text, metadata, false, window, cx);
10517 }
10518
10519 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10520 self.do_copy(true, cx);
10521 }
10522
10523 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10524 self.do_copy(false, cx);
10525 }
10526
10527 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10528 let selections = self.selections.all::<Point>(cx);
10529 let buffer = self.buffer.read(cx).read(cx);
10530 let mut text = String::new();
10531
10532 let mut clipboard_selections = Vec::with_capacity(selections.len());
10533 {
10534 let max_point = buffer.max_point();
10535 let mut is_first = true;
10536 for selection in &selections {
10537 let mut start = selection.start;
10538 let mut end = selection.end;
10539 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10540 if is_entire_line {
10541 start = Point::new(start.row, 0);
10542 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10543 }
10544
10545 let mut trimmed_selections = Vec::new();
10546 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10547 let row = MultiBufferRow(start.row);
10548 let first_indent = buffer.indent_size_for_line(row);
10549 if first_indent.len == 0 || start.column > first_indent.len {
10550 trimmed_selections.push(start..end);
10551 } else {
10552 trimmed_selections.push(
10553 Point::new(row.0, first_indent.len)
10554 ..Point::new(row.0, buffer.line_len(row)),
10555 );
10556 for row in start.row + 1..=end.row {
10557 let mut line_len = buffer.line_len(MultiBufferRow(row));
10558 if row == end.row {
10559 line_len = end.column;
10560 }
10561 if line_len == 0 {
10562 trimmed_selections
10563 .push(Point::new(row, 0)..Point::new(row, line_len));
10564 continue;
10565 }
10566 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10567 if row_indent_size.len >= first_indent.len {
10568 trimmed_selections.push(
10569 Point::new(row, first_indent.len)..Point::new(row, line_len),
10570 );
10571 } else {
10572 trimmed_selections.clear();
10573 trimmed_selections.push(start..end);
10574 break;
10575 }
10576 }
10577 }
10578 } else {
10579 trimmed_selections.push(start..end);
10580 }
10581
10582 for trimmed_range in trimmed_selections {
10583 if is_first {
10584 is_first = false;
10585 } else {
10586 text += "\n";
10587 }
10588 let mut len = 0;
10589 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10590 text.push_str(chunk);
10591 len += chunk.len();
10592 }
10593 clipboard_selections.push(ClipboardSelection {
10594 len,
10595 is_entire_line,
10596 first_line_indent: buffer
10597 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10598 .len,
10599 });
10600 }
10601 }
10602 }
10603
10604 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10605 text,
10606 clipboard_selections,
10607 ));
10608 }
10609
10610 pub fn do_paste(
10611 &mut self,
10612 text: &String,
10613 clipboard_selections: Option<Vec<ClipboardSelection>>,
10614 handle_entire_lines: bool,
10615 window: &mut Window,
10616 cx: &mut Context<Self>,
10617 ) {
10618 if self.read_only(cx) {
10619 return;
10620 }
10621
10622 let clipboard_text = Cow::Borrowed(text);
10623
10624 self.transact(window, cx, |this, window, cx| {
10625 if let Some(mut clipboard_selections) = clipboard_selections {
10626 let old_selections = this.selections.all::<usize>(cx);
10627 let all_selections_were_entire_line =
10628 clipboard_selections.iter().all(|s| s.is_entire_line);
10629 let first_selection_indent_column =
10630 clipboard_selections.first().map(|s| s.first_line_indent);
10631 if clipboard_selections.len() != old_selections.len() {
10632 clipboard_selections.drain(..);
10633 }
10634 let cursor_offset = this.selections.last::<usize>(cx).head();
10635 let mut auto_indent_on_paste = true;
10636
10637 this.buffer.update(cx, |buffer, cx| {
10638 let snapshot = buffer.read(cx);
10639 auto_indent_on_paste = snapshot
10640 .language_settings_at(cursor_offset, cx)
10641 .auto_indent_on_paste;
10642
10643 let mut start_offset = 0;
10644 let mut edits = Vec::new();
10645 let mut original_indent_columns = Vec::new();
10646 for (ix, selection) in old_selections.iter().enumerate() {
10647 let to_insert;
10648 let entire_line;
10649 let original_indent_column;
10650 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10651 let end_offset = start_offset + clipboard_selection.len;
10652 to_insert = &clipboard_text[start_offset..end_offset];
10653 entire_line = clipboard_selection.is_entire_line;
10654 start_offset = end_offset + 1;
10655 original_indent_column = Some(clipboard_selection.first_line_indent);
10656 } else {
10657 to_insert = clipboard_text.as_str();
10658 entire_line = all_selections_were_entire_line;
10659 original_indent_column = first_selection_indent_column
10660 }
10661
10662 // If the corresponding selection was empty when this slice of the
10663 // clipboard text was written, then the entire line containing the
10664 // selection was copied. If this selection is also currently empty,
10665 // then paste the line before the current line of the buffer.
10666 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10667 let column = selection.start.to_point(&snapshot).column as usize;
10668 let line_start = selection.start - column;
10669 line_start..line_start
10670 } else {
10671 selection.range()
10672 };
10673
10674 edits.push((range, to_insert));
10675 original_indent_columns.push(original_indent_column);
10676 }
10677 drop(snapshot);
10678
10679 buffer.edit(
10680 edits,
10681 if auto_indent_on_paste {
10682 Some(AutoindentMode::Block {
10683 original_indent_columns,
10684 })
10685 } else {
10686 None
10687 },
10688 cx,
10689 );
10690 });
10691
10692 let selections = this.selections.all::<usize>(cx);
10693 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10694 s.select(selections)
10695 });
10696 } else {
10697 this.insert(&clipboard_text, window, cx);
10698 }
10699 });
10700 }
10701
10702 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10703 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10704 if let Some(item) = cx.read_from_clipboard() {
10705 let entries = item.entries();
10706
10707 match entries.first() {
10708 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10709 // of all the pasted entries.
10710 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10711 .do_paste(
10712 clipboard_string.text(),
10713 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10714 true,
10715 window,
10716 cx,
10717 ),
10718 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10719 }
10720 }
10721 }
10722
10723 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10724 if self.read_only(cx) {
10725 return;
10726 }
10727
10728 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10729
10730 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10731 if let Some((selections, _)) =
10732 self.selection_history.transaction(transaction_id).cloned()
10733 {
10734 self.change_selections(None, window, cx, |s| {
10735 s.select_anchors(selections.to_vec());
10736 });
10737 } else {
10738 log::error!(
10739 "No entry in selection_history found for undo. \
10740 This may correspond to a bug where undo does not update the selection. \
10741 If this is occurring, please add details to \
10742 https://github.com/zed-industries/zed/issues/22692"
10743 );
10744 }
10745 self.request_autoscroll(Autoscroll::fit(), cx);
10746 self.unmark_text(window, cx);
10747 self.refresh_inline_completion(true, false, window, cx);
10748 cx.emit(EditorEvent::Edited { transaction_id });
10749 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10750 }
10751 }
10752
10753 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10754 if self.read_only(cx) {
10755 return;
10756 }
10757
10758 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10759
10760 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10761 if let Some((_, Some(selections))) =
10762 self.selection_history.transaction(transaction_id).cloned()
10763 {
10764 self.change_selections(None, window, cx, |s| {
10765 s.select_anchors(selections.to_vec());
10766 });
10767 } else {
10768 log::error!(
10769 "No entry in selection_history found for redo. \
10770 This may correspond to a bug where undo does not update the selection. \
10771 If this is occurring, please add details to \
10772 https://github.com/zed-industries/zed/issues/22692"
10773 );
10774 }
10775 self.request_autoscroll(Autoscroll::fit(), cx);
10776 self.unmark_text(window, cx);
10777 self.refresh_inline_completion(true, false, window, cx);
10778 cx.emit(EditorEvent::Edited { transaction_id });
10779 }
10780 }
10781
10782 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10783 self.buffer
10784 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10785 }
10786
10787 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10788 self.buffer
10789 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10790 }
10791
10792 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10793 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10794 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10795 s.move_with(|map, selection| {
10796 let cursor = if selection.is_empty() {
10797 movement::left(map, selection.start)
10798 } else {
10799 selection.start
10800 };
10801 selection.collapse_to(cursor, SelectionGoal::None);
10802 });
10803 })
10804 }
10805
10806 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10807 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10808 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10809 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10810 })
10811 }
10812
10813 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10814 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10815 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10816 s.move_with(|map, selection| {
10817 let cursor = if selection.is_empty() {
10818 movement::right(map, selection.end)
10819 } else {
10820 selection.end
10821 };
10822 selection.collapse_to(cursor, SelectionGoal::None)
10823 });
10824 })
10825 }
10826
10827 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10828 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10829 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10830 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10831 })
10832 }
10833
10834 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10835 if self.take_rename(true, window, cx).is_some() {
10836 return;
10837 }
10838
10839 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10840 cx.propagate();
10841 return;
10842 }
10843
10844 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10845
10846 let text_layout_details = &self.text_layout_details(window);
10847 let selection_count = self.selections.count();
10848 let first_selection = self.selections.first_anchor();
10849
10850 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10851 s.move_with(|map, selection| {
10852 if !selection.is_empty() {
10853 selection.goal = SelectionGoal::None;
10854 }
10855 let (cursor, goal) = movement::up(
10856 map,
10857 selection.start,
10858 selection.goal,
10859 false,
10860 text_layout_details,
10861 );
10862 selection.collapse_to(cursor, goal);
10863 });
10864 });
10865
10866 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10867 {
10868 cx.propagate();
10869 }
10870 }
10871
10872 pub fn move_up_by_lines(
10873 &mut self,
10874 action: &MoveUpByLines,
10875 window: &mut Window,
10876 cx: &mut Context<Self>,
10877 ) {
10878 if self.take_rename(true, window, cx).is_some() {
10879 return;
10880 }
10881
10882 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10883 cx.propagate();
10884 return;
10885 }
10886
10887 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10888
10889 let text_layout_details = &self.text_layout_details(window);
10890
10891 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10892 s.move_with(|map, selection| {
10893 if !selection.is_empty() {
10894 selection.goal = SelectionGoal::None;
10895 }
10896 let (cursor, goal) = movement::up_by_rows(
10897 map,
10898 selection.start,
10899 action.lines,
10900 selection.goal,
10901 false,
10902 text_layout_details,
10903 );
10904 selection.collapse_to(cursor, goal);
10905 });
10906 })
10907 }
10908
10909 pub fn move_down_by_lines(
10910 &mut self,
10911 action: &MoveDownByLines,
10912 window: &mut Window,
10913 cx: &mut Context<Self>,
10914 ) {
10915 if self.take_rename(true, window, cx).is_some() {
10916 return;
10917 }
10918
10919 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10920 cx.propagate();
10921 return;
10922 }
10923
10924 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10925
10926 let text_layout_details = &self.text_layout_details(window);
10927
10928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10929 s.move_with(|map, selection| {
10930 if !selection.is_empty() {
10931 selection.goal = SelectionGoal::None;
10932 }
10933 let (cursor, goal) = movement::down_by_rows(
10934 map,
10935 selection.start,
10936 action.lines,
10937 selection.goal,
10938 false,
10939 text_layout_details,
10940 );
10941 selection.collapse_to(cursor, goal);
10942 });
10943 })
10944 }
10945
10946 pub fn select_down_by_lines(
10947 &mut self,
10948 action: &SelectDownByLines,
10949 window: &mut Window,
10950 cx: &mut Context<Self>,
10951 ) {
10952 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10953 let text_layout_details = &self.text_layout_details(window);
10954 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10955 s.move_heads_with(|map, head, goal| {
10956 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10957 })
10958 })
10959 }
10960
10961 pub fn select_up_by_lines(
10962 &mut self,
10963 action: &SelectUpByLines,
10964 window: &mut Window,
10965 cx: &mut Context<Self>,
10966 ) {
10967 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10968 let text_layout_details = &self.text_layout_details(window);
10969 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10970 s.move_heads_with(|map, head, goal| {
10971 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10972 })
10973 })
10974 }
10975
10976 pub fn select_page_up(
10977 &mut self,
10978 _: &SelectPageUp,
10979 window: &mut Window,
10980 cx: &mut Context<Self>,
10981 ) {
10982 let Some(row_count) = self.visible_row_count() else {
10983 return;
10984 };
10985
10986 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10987
10988 let text_layout_details = &self.text_layout_details(window);
10989
10990 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10991 s.move_heads_with(|map, head, goal| {
10992 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10993 })
10994 })
10995 }
10996
10997 pub fn move_page_up(
10998 &mut self,
10999 action: &MovePageUp,
11000 window: &mut Window,
11001 cx: &mut Context<Self>,
11002 ) {
11003 if self.take_rename(true, window, cx).is_some() {
11004 return;
11005 }
11006
11007 if self
11008 .context_menu
11009 .borrow_mut()
11010 .as_mut()
11011 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11012 .unwrap_or(false)
11013 {
11014 return;
11015 }
11016
11017 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11018 cx.propagate();
11019 return;
11020 }
11021
11022 let Some(row_count) = self.visible_row_count() else {
11023 return;
11024 };
11025
11026 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11027
11028 let autoscroll = if action.center_cursor {
11029 Autoscroll::center()
11030 } else {
11031 Autoscroll::fit()
11032 };
11033
11034 let text_layout_details = &self.text_layout_details(window);
11035
11036 self.change_selections(Some(autoscroll), window, cx, |s| {
11037 s.move_with(|map, selection| {
11038 if !selection.is_empty() {
11039 selection.goal = SelectionGoal::None;
11040 }
11041 let (cursor, goal) = movement::up_by_rows(
11042 map,
11043 selection.end,
11044 row_count,
11045 selection.goal,
11046 false,
11047 text_layout_details,
11048 );
11049 selection.collapse_to(cursor, goal);
11050 });
11051 });
11052 }
11053
11054 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11055 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11056 let text_layout_details = &self.text_layout_details(window);
11057 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11058 s.move_heads_with(|map, head, goal| {
11059 movement::up(map, head, goal, false, text_layout_details)
11060 })
11061 })
11062 }
11063
11064 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11065 self.take_rename(true, window, cx);
11066
11067 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11068 cx.propagate();
11069 return;
11070 }
11071
11072 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11073
11074 let text_layout_details = &self.text_layout_details(window);
11075 let selection_count = self.selections.count();
11076 let first_selection = self.selections.first_anchor();
11077
11078 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11079 s.move_with(|map, selection| {
11080 if !selection.is_empty() {
11081 selection.goal = SelectionGoal::None;
11082 }
11083 let (cursor, goal) = movement::down(
11084 map,
11085 selection.end,
11086 selection.goal,
11087 false,
11088 text_layout_details,
11089 );
11090 selection.collapse_to(cursor, goal);
11091 });
11092 });
11093
11094 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11095 {
11096 cx.propagate();
11097 }
11098 }
11099
11100 pub fn select_page_down(
11101 &mut self,
11102 _: &SelectPageDown,
11103 window: &mut Window,
11104 cx: &mut Context<Self>,
11105 ) {
11106 let Some(row_count) = self.visible_row_count() else {
11107 return;
11108 };
11109
11110 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11111
11112 let text_layout_details = &self.text_layout_details(window);
11113
11114 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11115 s.move_heads_with(|map, head, goal| {
11116 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11117 })
11118 })
11119 }
11120
11121 pub fn move_page_down(
11122 &mut self,
11123 action: &MovePageDown,
11124 window: &mut Window,
11125 cx: &mut Context<Self>,
11126 ) {
11127 if self.take_rename(true, window, cx).is_some() {
11128 return;
11129 }
11130
11131 if self
11132 .context_menu
11133 .borrow_mut()
11134 .as_mut()
11135 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11136 .unwrap_or(false)
11137 {
11138 return;
11139 }
11140
11141 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11142 cx.propagate();
11143 return;
11144 }
11145
11146 let Some(row_count) = self.visible_row_count() else {
11147 return;
11148 };
11149
11150 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11151
11152 let autoscroll = if action.center_cursor {
11153 Autoscroll::center()
11154 } else {
11155 Autoscroll::fit()
11156 };
11157
11158 let text_layout_details = &self.text_layout_details(window);
11159 self.change_selections(Some(autoscroll), window, cx, |s| {
11160 s.move_with(|map, selection| {
11161 if !selection.is_empty() {
11162 selection.goal = SelectionGoal::None;
11163 }
11164 let (cursor, goal) = movement::down_by_rows(
11165 map,
11166 selection.end,
11167 row_count,
11168 selection.goal,
11169 false,
11170 text_layout_details,
11171 );
11172 selection.collapse_to(cursor, goal);
11173 });
11174 });
11175 }
11176
11177 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11178 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11179 let text_layout_details = &self.text_layout_details(window);
11180 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11181 s.move_heads_with(|map, head, goal| {
11182 movement::down(map, head, goal, false, text_layout_details)
11183 })
11184 });
11185 }
11186
11187 pub fn context_menu_first(
11188 &mut self,
11189 _: &ContextMenuFirst,
11190 _window: &mut Window,
11191 cx: &mut Context<Self>,
11192 ) {
11193 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11194 context_menu.select_first(self.completion_provider.as_deref(), cx);
11195 }
11196 }
11197
11198 pub fn context_menu_prev(
11199 &mut self,
11200 _: &ContextMenuPrevious,
11201 _window: &mut Window,
11202 cx: &mut Context<Self>,
11203 ) {
11204 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11205 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11206 }
11207 }
11208
11209 pub fn context_menu_next(
11210 &mut self,
11211 _: &ContextMenuNext,
11212 _window: &mut Window,
11213 cx: &mut Context<Self>,
11214 ) {
11215 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11216 context_menu.select_next(self.completion_provider.as_deref(), cx);
11217 }
11218 }
11219
11220 pub fn context_menu_last(
11221 &mut self,
11222 _: &ContextMenuLast,
11223 _window: &mut Window,
11224 cx: &mut Context<Self>,
11225 ) {
11226 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11227 context_menu.select_last(self.completion_provider.as_deref(), cx);
11228 }
11229 }
11230
11231 pub fn move_to_previous_word_start(
11232 &mut self,
11233 _: &MoveToPreviousWordStart,
11234 window: &mut Window,
11235 cx: &mut Context<Self>,
11236 ) {
11237 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11238 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11239 s.move_cursors_with(|map, head, _| {
11240 (
11241 movement::previous_word_start(map, head),
11242 SelectionGoal::None,
11243 )
11244 });
11245 })
11246 }
11247
11248 pub fn move_to_previous_subword_start(
11249 &mut self,
11250 _: &MoveToPreviousSubwordStart,
11251 window: &mut Window,
11252 cx: &mut Context<Self>,
11253 ) {
11254 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11255 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11256 s.move_cursors_with(|map, head, _| {
11257 (
11258 movement::previous_subword_start(map, head),
11259 SelectionGoal::None,
11260 )
11261 });
11262 })
11263 }
11264
11265 pub fn select_to_previous_word_start(
11266 &mut self,
11267 _: &SelectToPreviousWordStart,
11268 window: &mut Window,
11269 cx: &mut Context<Self>,
11270 ) {
11271 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11273 s.move_heads_with(|map, head, _| {
11274 (
11275 movement::previous_word_start(map, head),
11276 SelectionGoal::None,
11277 )
11278 });
11279 })
11280 }
11281
11282 pub fn select_to_previous_subword_start(
11283 &mut self,
11284 _: &SelectToPreviousSubwordStart,
11285 window: &mut Window,
11286 cx: &mut Context<Self>,
11287 ) {
11288 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11289 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11290 s.move_heads_with(|map, head, _| {
11291 (
11292 movement::previous_subword_start(map, head),
11293 SelectionGoal::None,
11294 )
11295 });
11296 })
11297 }
11298
11299 pub fn delete_to_previous_word_start(
11300 &mut self,
11301 action: &DeleteToPreviousWordStart,
11302 window: &mut Window,
11303 cx: &mut Context<Self>,
11304 ) {
11305 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11306 self.transact(window, cx, |this, window, cx| {
11307 this.select_autoclose_pair(window, cx);
11308 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11309 s.move_with(|map, selection| {
11310 if selection.is_empty() {
11311 let cursor = if action.ignore_newlines {
11312 movement::previous_word_start(map, selection.head())
11313 } else {
11314 movement::previous_word_start_or_newline(map, selection.head())
11315 };
11316 selection.set_head(cursor, SelectionGoal::None);
11317 }
11318 });
11319 });
11320 this.insert("", window, cx);
11321 });
11322 }
11323
11324 pub fn delete_to_previous_subword_start(
11325 &mut self,
11326 _: &DeleteToPreviousSubwordStart,
11327 window: &mut Window,
11328 cx: &mut Context<Self>,
11329 ) {
11330 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11331 self.transact(window, cx, |this, window, cx| {
11332 this.select_autoclose_pair(window, cx);
11333 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11334 s.move_with(|map, selection| {
11335 if selection.is_empty() {
11336 let cursor = movement::previous_subword_start(map, selection.head());
11337 selection.set_head(cursor, SelectionGoal::None);
11338 }
11339 });
11340 });
11341 this.insert("", window, cx);
11342 });
11343 }
11344
11345 pub fn move_to_next_word_end(
11346 &mut self,
11347 _: &MoveToNextWordEnd,
11348 window: &mut Window,
11349 cx: &mut Context<Self>,
11350 ) {
11351 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11353 s.move_cursors_with(|map, head, _| {
11354 (movement::next_word_end(map, head), SelectionGoal::None)
11355 });
11356 })
11357 }
11358
11359 pub fn move_to_next_subword_end(
11360 &mut self,
11361 _: &MoveToNextSubwordEnd,
11362 window: &mut Window,
11363 cx: &mut Context<Self>,
11364 ) {
11365 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11366 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11367 s.move_cursors_with(|map, head, _| {
11368 (movement::next_subword_end(map, head), SelectionGoal::None)
11369 });
11370 })
11371 }
11372
11373 pub fn select_to_next_word_end(
11374 &mut self,
11375 _: &SelectToNextWordEnd,
11376 window: &mut Window,
11377 cx: &mut Context<Self>,
11378 ) {
11379 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11380 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11381 s.move_heads_with(|map, head, _| {
11382 (movement::next_word_end(map, head), SelectionGoal::None)
11383 });
11384 })
11385 }
11386
11387 pub fn select_to_next_subword_end(
11388 &mut self,
11389 _: &SelectToNextSubwordEnd,
11390 window: &mut Window,
11391 cx: &mut Context<Self>,
11392 ) {
11393 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11394 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11395 s.move_heads_with(|map, head, _| {
11396 (movement::next_subword_end(map, head), SelectionGoal::None)
11397 });
11398 })
11399 }
11400
11401 pub fn delete_to_next_word_end(
11402 &mut self,
11403 action: &DeleteToNextWordEnd,
11404 window: &mut Window,
11405 cx: &mut Context<Self>,
11406 ) {
11407 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11408 self.transact(window, cx, |this, window, cx| {
11409 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11410 s.move_with(|map, selection| {
11411 if selection.is_empty() {
11412 let cursor = if action.ignore_newlines {
11413 movement::next_word_end(map, selection.head())
11414 } else {
11415 movement::next_word_end_or_newline(map, selection.head())
11416 };
11417 selection.set_head(cursor, SelectionGoal::None);
11418 }
11419 });
11420 });
11421 this.insert("", window, cx);
11422 });
11423 }
11424
11425 pub fn delete_to_next_subword_end(
11426 &mut self,
11427 _: &DeleteToNextSubwordEnd,
11428 window: &mut Window,
11429 cx: &mut Context<Self>,
11430 ) {
11431 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11432 self.transact(window, cx, |this, window, cx| {
11433 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11434 s.move_with(|map, selection| {
11435 if selection.is_empty() {
11436 let cursor = movement::next_subword_end(map, selection.head());
11437 selection.set_head(cursor, SelectionGoal::None);
11438 }
11439 });
11440 });
11441 this.insert("", window, cx);
11442 });
11443 }
11444
11445 pub fn move_to_beginning_of_line(
11446 &mut self,
11447 action: &MoveToBeginningOfLine,
11448 window: &mut Window,
11449 cx: &mut Context<Self>,
11450 ) {
11451 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11452 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11453 s.move_cursors_with(|map, head, _| {
11454 (
11455 movement::indented_line_beginning(
11456 map,
11457 head,
11458 action.stop_at_soft_wraps,
11459 action.stop_at_indent,
11460 ),
11461 SelectionGoal::None,
11462 )
11463 });
11464 })
11465 }
11466
11467 pub fn select_to_beginning_of_line(
11468 &mut self,
11469 action: &SelectToBeginningOfLine,
11470 window: &mut Window,
11471 cx: &mut Context<Self>,
11472 ) {
11473 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11474 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11475 s.move_heads_with(|map, head, _| {
11476 (
11477 movement::indented_line_beginning(
11478 map,
11479 head,
11480 action.stop_at_soft_wraps,
11481 action.stop_at_indent,
11482 ),
11483 SelectionGoal::None,
11484 )
11485 });
11486 });
11487 }
11488
11489 pub fn delete_to_beginning_of_line(
11490 &mut self,
11491 action: &DeleteToBeginningOfLine,
11492 window: &mut Window,
11493 cx: &mut Context<Self>,
11494 ) {
11495 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11496 self.transact(window, cx, |this, window, cx| {
11497 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11498 s.move_with(|_, selection| {
11499 selection.reversed = true;
11500 });
11501 });
11502
11503 this.select_to_beginning_of_line(
11504 &SelectToBeginningOfLine {
11505 stop_at_soft_wraps: false,
11506 stop_at_indent: action.stop_at_indent,
11507 },
11508 window,
11509 cx,
11510 );
11511 this.backspace(&Backspace, window, cx);
11512 });
11513 }
11514
11515 pub fn move_to_end_of_line(
11516 &mut self,
11517 action: &MoveToEndOfLine,
11518 window: &mut Window,
11519 cx: &mut Context<Self>,
11520 ) {
11521 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11522 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11523 s.move_cursors_with(|map, head, _| {
11524 (
11525 movement::line_end(map, head, action.stop_at_soft_wraps),
11526 SelectionGoal::None,
11527 )
11528 });
11529 })
11530 }
11531
11532 pub fn select_to_end_of_line(
11533 &mut self,
11534 action: &SelectToEndOfLine,
11535 window: &mut Window,
11536 cx: &mut Context<Self>,
11537 ) {
11538 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11539 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11540 s.move_heads_with(|map, head, _| {
11541 (
11542 movement::line_end(map, head, action.stop_at_soft_wraps),
11543 SelectionGoal::None,
11544 )
11545 });
11546 })
11547 }
11548
11549 pub fn delete_to_end_of_line(
11550 &mut self,
11551 _: &DeleteToEndOfLine,
11552 window: &mut Window,
11553 cx: &mut Context<Self>,
11554 ) {
11555 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11556 self.transact(window, cx, |this, window, cx| {
11557 this.select_to_end_of_line(
11558 &SelectToEndOfLine {
11559 stop_at_soft_wraps: false,
11560 },
11561 window,
11562 cx,
11563 );
11564 this.delete(&Delete, window, cx);
11565 });
11566 }
11567
11568 pub fn cut_to_end_of_line(
11569 &mut self,
11570 _: &CutToEndOfLine,
11571 window: &mut Window,
11572 cx: &mut Context<Self>,
11573 ) {
11574 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11575 self.transact(window, cx, |this, window, cx| {
11576 this.select_to_end_of_line(
11577 &SelectToEndOfLine {
11578 stop_at_soft_wraps: false,
11579 },
11580 window,
11581 cx,
11582 );
11583 this.cut(&Cut, window, cx);
11584 });
11585 }
11586
11587 pub fn move_to_start_of_paragraph(
11588 &mut self,
11589 _: &MoveToStartOfParagraph,
11590 window: &mut Window,
11591 cx: &mut Context<Self>,
11592 ) {
11593 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11594 cx.propagate();
11595 return;
11596 }
11597 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11598 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11599 s.move_with(|map, selection| {
11600 selection.collapse_to(
11601 movement::start_of_paragraph(map, selection.head(), 1),
11602 SelectionGoal::None,
11603 )
11604 });
11605 })
11606 }
11607
11608 pub fn move_to_end_of_paragraph(
11609 &mut self,
11610 _: &MoveToEndOfParagraph,
11611 window: &mut Window,
11612 cx: &mut Context<Self>,
11613 ) {
11614 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11615 cx.propagate();
11616 return;
11617 }
11618 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11619 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11620 s.move_with(|map, selection| {
11621 selection.collapse_to(
11622 movement::end_of_paragraph(map, selection.head(), 1),
11623 SelectionGoal::None,
11624 )
11625 });
11626 })
11627 }
11628
11629 pub fn select_to_start_of_paragraph(
11630 &mut self,
11631 _: &SelectToStartOfParagraph,
11632 window: &mut Window,
11633 cx: &mut Context<Self>,
11634 ) {
11635 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11636 cx.propagate();
11637 return;
11638 }
11639 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11640 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11641 s.move_heads_with(|map, head, _| {
11642 (
11643 movement::start_of_paragraph(map, head, 1),
11644 SelectionGoal::None,
11645 )
11646 });
11647 })
11648 }
11649
11650 pub fn select_to_end_of_paragraph(
11651 &mut self,
11652 _: &SelectToEndOfParagraph,
11653 window: &mut Window,
11654 cx: &mut Context<Self>,
11655 ) {
11656 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11657 cx.propagate();
11658 return;
11659 }
11660 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11661 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11662 s.move_heads_with(|map, head, _| {
11663 (
11664 movement::end_of_paragraph(map, head, 1),
11665 SelectionGoal::None,
11666 )
11667 });
11668 })
11669 }
11670
11671 pub fn move_to_start_of_excerpt(
11672 &mut self,
11673 _: &MoveToStartOfExcerpt,
11674 window: &mut Window,
11675 cx: &mut Context<Self>,
11676 ) {
11677 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11678 cx.propagate();
11679 return;
11680 }
11681 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11682 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11683 s.move_with(|map, selection| {
11684 selection.collapse_to(
11685 movement::start_of_excerpt(
11686 map,
11687 selection.head(),
11688 workspace::searchable::Direction::Prev,
11689 ),
11690 SelectionGoal::None,
11691 )
11692 });
11693 })
11694 }
11695
11696 pub fn move_to_start_of_next_excerpt(
11697 &mut self,
11698 _: &MoveToStartOfNextExcerpt,
11699 window: &mut Window,
11700 cx: &mut Context<Self>,
11701 ) {
11702 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11703 cx.propagate();
11704 return;
11705 }
11706
11707 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11708 s.move_with(|map, selection| {
11709 selection.collapse_to(
11710 movement::start_of_excerpt(
11711 map,
11712 selection.head(),
11713 workspace::searchable::Direction::Next,
11714 ),
11715 SelectionGoal::None,
11716 )
11717 });
11718 })
11719 }
11720
11721 pub fn move_to_end_of_excerpt(
11722 &mut self,
11723 _: &MoveToEndOfExcerpt,
11724 window: &mut Window,
11725 cx: &mut Context<Self>,
11726 ) {
11727 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11728 cx.propagate();
11729 return;
11730 }
11731 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11732 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11733 s.move_with(|map, selection| {
11734 selection.collapse_to(
11735 movement::end_of_excerpt(
11736 map,
11737 selection.head(),
11738 workspace::searchable::Direction::Next,
11739 ),
11740 SelectionGoal::None,
11741 )
11742 });
11743 })
11744 }
11745
11746 pub fn move_to_end_of_previous_excerpt(
11747 &mut self,
11748 _: &MoveToEndOfPreviousExcerpt,
11749 window: &mut Window,
11750 cx: &mut Context<Self>,
11751 ) {
11752 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11753 cx.propagate();
11754 return;
11755 }
11756 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11757 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11758 s.move_with(|map, selection| {
11759 selection.collapse_to(
11760 movement::end_of_excerpt(
11761 map,
11762 selection.head(),
11763 workspace::searchable::Direction::Prev,
11764 ),
11765 SelectionGoal::None,
11766 )
11767 });
11768 })
11769 }
11770
11771 pub fn select_to_start_of_excerpt(
11772 &mut self,
11773 _: &SelectToStartOfExcerpt,
11774 window: &mut Window,
11775 cx: &mut Context<Self>,
11776 ) {
11777 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11778 cx.propagate();
11779 return;
11780 }
11781 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11782 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11783 s.move_heads_with(|map, head, _| {
11784 (
11785 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11786 SelectionGoal::None,
11787 )
11788 });
11789 })
11790 }
11791
11792 pub fn select_to_start_of_next_excerpt(
11793 &mut self,
11794 _: &SelectToStartOfNextExcerpt,
11795 window: &mut Window,
11796 cx: &mut Context<Self>,
11797 ) {
11798 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11799 cx.propagate();
11800 return;
11801 }
11802 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11804 s.move_heads_with(|map, head, _| {
11805 (
11806 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11807 SelectionGoal::None,
11808 )
11809 });
11810 })
11811 }
11812
11813 pub fn select_to_end_of_excerpt(
11814 &mut self,
11815 _: &SelectToEndOfExcerpt,
11816 window: &mut Window,
11817 cx: &mut Context<Self>,
11818 ) {
11819 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11820 cx.propagate();
11821 return;
11822 }
11823 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11824 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11825 s.move_heads_with(|map, head, _| {
11826 (
11827 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11828 SelectionGoal::None,
11829 )
11830 });
11831 })
11832 }
11833
11834 pub fn select_to_end_of_previous_excerpt(
11835 &mut self,
11836 _: &SelectToEndOfPreviousExcerpt,
11837 window: &mut Window,
11838 cx: &mut Context<Self>,
11839 ) {
11840 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11841 cx.propagate();
11842 return;
11843 }
11844 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11845 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11846 s.move_heads_with(|map, head, _| {
11847 (
11848 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11849 SelectionGoal::None,
11850 )
11851 });
11852 })
11853 }
11854
11855 pub fn move_to_beginning(
11856 &mut self,
11857 _: &MoveToBeginning,
11858 window: &mut Window,
11859 cx: &mut Context<Self>,
11860 ) {
11861 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11862 cx.propagate();
11863 return;
11864 }
11865 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11866 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11867 s.select_ranges(vec![0..0]);
11868 });
11869 }
11870
11871 pub fn select_to_beginning(
11872 &mut self,
11873 _: &SelectToBeginning,
11874 window: &mut Window,
11875 cx: &mut Context<Self>,
11876 ) {
11877 let mut selection = self.selections.last::<Point>(cx);
11878 selection.set_head(Point::zero(), SelectionGoal::None);
11879 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11881 s.select(vec![selection]);
11882 });
11883 }
11884
11885 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11886 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11887 cx.propagate();
11888 return;
11889 }
11890 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11891 let cursor = self.buffer.read(cx).read(cx).len();
11892 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11893 s.select_ranges(vec![cursor..cursor])
11894 });
11895 }
11896
11897 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11898 self.nav_history = nav_history;
11899 }
11900
11901 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11902 self.nav_history.as_ref()
11903 }
11904
11905 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11906 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11907 }
11908
11909 fn push_to_nav_history(
11910 &mut self,
11911 cursor_anchor: Anchor,
11912 new_position: Option<Point>,
11913 is_deactivate: bool,
11914 cx: &mut Context<Self>,
11915 ) {
11916 if let Some(nav_history) = self.nav_history.as_mut() {
11917 let buffer = self.buffer.read(cx).read(cx);
11918 let cursor_position = cursor_anchor.to_point(&buffer);
11919 let scroll_state = self.scroll_manager.anchor();
11920 let scroll_top_row = scroll_state.top_row(&buffer);
11921 drop(buffer);
11922
11923 if let Some(new_position) = new_position {
11924 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11925 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11926 return;
11927 }
11928 }
11929
11930 nav_history.push(
11931 Some(NavigationData {
11932 cursor_anchor,
11933 cursor_position,
11934 scroll_anchor: scroll_state,
11935 scroll_top_row,
11936 }),
11937 cx,
11938 );
11939 cx.emit(EditorEvent::PushedToNavHistory {
11940 anchor: cursor_anchor,
11941 is_deactivate,
11942 })
11943 }
11944 }
11945
11946 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11947 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11948 let buffer = self.buffer.read(cx).snapshot(cx);
11949 let mut selection = self.selections.first::<usize>(cx);
11950 selection.set_head(buffer.len(), SelectionGoal::None);
11951 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11952 s.select(vec![selection]);
11953 });
11954 }
11955
11956 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11957 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11958 let end = self.buffer.read(cx).read(cx).len();
11959 self.change_selections(None, window, cx, |s| {
11960 s.select_ranges(vec![0..end]);
11961 });
11962 }
11963
11964 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11965 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11966 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11967 let mut selections = self.selections.all::<Point>(cx);
11968 let max_point = display_map.buffer_snapshot.max_point();
11969 for selection in &mut selections {
11970 let rows = selection.spanned_rows(true, &display_map);
11971 selection.start = Point::new(rows.start.0, 0);
11972 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11973 selection.reversed = false;
11974 }
11975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11976 s.select(selections);
11977 });
11978 }
11979
11980 pub fn split_selection_into_lines(
11981 &mut self,
11982 _: &SplitSelectionIntoLines,
11983 window: &mut Window,
11984 cx: &mut Context<Self>,
11985 ) {
11986 let selections = self
11987 .selections
11988 .all::<Point>(cx)
11989 .into_iter()
11990 .map(|selection| selection.start..selection.end)
11991 .collect::<Vec<_>>();
11992 self.unfold_ranges(&selections, true, true, cx);
11993
11994 let mut new_selection_ranges = Vec::new();
11995 {
11996 let buffer = self.buffer.read(cx).read(cx);
11997 for selection in selections {
11998 for row in selection.start.row..selection.end.row {
11999 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12000 new_selection_ranges.push(cursor..cursor);
12001 }
12002
12003 let is_multiline_selection = selection.start.row != selection.end.row;
12004 // Don't insert last one if it's a multi-line selection ending at the start of a line,
12005 // so this action feels more ergonomic when paired with other selection operations
12006 let should_skip_last = is_multiline_selection && selection.end.column == 0;
12007 if !should_skip_last {
12008 new_selection_ranges.push(selection.end..selection.end);
12009 }
12010 }
12011 }
12012 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12013 s.select_ranges(new_selection_ranges);
12014 });
12015 }
12016
12017 pub fn add_selection_above(
12018 &mut self,
12019 _: &AddSelectionAbove,
12020 window: &mut Window,
12021 cx: &mut Context<Self>,
12022 ) {
12023 self.add_selection(true, window, cx);
12024 }
12025
12026 pub fn add_selection_below(
12027 &mut self,
12028 _: &AddSelectionBelow,
12029 window: &mut Window,
12030 cx: &mut Context<Self>,
12031 ) {
12032 self.add_selection(false, window, cx);
12033 }
12034
12035 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12036 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12037
12038 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12039 let mut selections = self.selections.all::<Point>(cx);
12040 let text_layout_details = self.text_layout_details(window);
12041 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12042 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12043 let range = oldest_selection.display_range(&display_map).sorted();
12044
12045 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12046 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12047 let positions = start_x.min(end_x)..start_x.max(end_x);
12048
12049 selections.clear();
12050 let mut stack = Vec::new();
12051 for row in range.start.row().0..=range.end.row().0 {
12052 if let Some(selection) = self.selections.build_columnar_selection(
12053 &display_map,
12054 DisplayRow(row),
12055 &positions,
12056 oldest_selection.reversed,
12057 &text_layout_details,
12058 ) {
12059 stack.push(selection.id);
12060 selections.push(selection);
12061 }
12062 }
12063
12064 if above {
12065 stack.reverse();
12066 }
12067
12068 AddSelectionsState { above, stack }
12069 });
12070
12071 let last_added_selection = *state.stack.last().unwrap();
12072 let mut new_selections = Vec::new();
12073 if above == state.above {
12074 let end_row = if above {
12075 DisplayRow(0)
12076 } else {
12077 display_map.max_point().row()
12078 };
12079
12080 'outer: for selection in selections {
12081 if selection.id == last_added_selection {
12082 let range = selection.display_range(&display_map).sorted();
12083 debug_assert_eq!(range.start.row(), range.end.row());
12084 let mut row = range.start.row();
12085 let positions =
12086 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12087 px(start)..px(end)
12088 } else {
12089 let start_x =
12090 display_map.x_for_display_point(range.start, &text_layout_details);
12091 let end_x =
12092 display_map.x_for_display_point(range.end, &text_layout_details);
12093 start_x.min(end_x)..start_x.max(end_x)
12094 };
12095
12096 while row != end_row {
12097 if above {
12098 row.0 -= 1;
12099 } else {
12100 row.0 += 1;
12101 }
12102
12103 if let Some(new_selection) = self.selections.build_columnar_selection(
12104 &display_map,
12105 row,
12106 &positions,
12107 selection.reversed,
12108 &text_layout_details,
12109 ) {
12110 state.stack.push(new_selection.id);
12111 if above {
12112 new_selections.push(new_selection);
12113 new_selections.push(selection);
12114 } else {
12115 new_selections.push(selection);
12116 new_selections.push(new_selection);
12117 }
12118
12119 continue 'outer;
12120 }
12121 }
12122 }
12123
12124 new_selections.push(selection);
12125 }
12126 } else {
12127 new_selections = selections;
12128 new_selections.retain(|s| s.id != last_added_selection);
12129 state.stack.pop();
12130 }
12131
12132 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12133 s.select(new_selections);
12134 });
12135 if state.stack.len() > 1 {
12136 self.add_selections_state = Some(state);
12137 }
12138 }
12139
12140 fn select_match_ranges(
12141 &mut self,
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 self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12150 self.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 pub fn select_next_match_internal(
12163 &mut self,
12164 display_map: &DisplaySnapshot,
12165 replace_newest: bool,
12166 autoscroll: Option<Autoscroll>,
12167 window: &mut Window,
12168 cx: &mut Context<Self>,
12169 ) -> Result<()> {
12170 let buffer = &display_map.buffer_snapshot;
12171 let mut selections = self.selections.all::<usize>(cx);
12172 if let Some(mut select_next_state) = self.select_next_state.take() {
12173 let query = &select_next_state.query;
12174 if !select_next_state.done {
12175 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12176 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12177 let mut next_selected_range = None;
12178
12179 let bytes_after_last_selection =
12180 buffer.bytes_in_range(last_selection.end..buffer.len());
12181 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12182 let query_matches = query
12183 .stream_find_iter(bytes_after_last_selection)
12184 .map(|result| (last_selection.end, result))
12185 .chain(
12186 query
12187 .stream_find_iter(bytes_before_first_selection)
12188 .map(|result| (0, result)),
12189 );
12190
12191 for (start_offset, query_match) in query_matches {
12192 let query_match = query_match.unwrap(); // can only fail due to I/O
12193 let offset_range =
12194 start_offset + query_match.start()..start_offset + query_match.end();
12195 let display_range = offset_range.start.to_display_point(display_map)
12196 ..offset_range.end.to_display_point(display_map);
12197
12198 if !select_next_state.wordwise
12199 || (!movement::is_inside_word(display_map, display_range.start)
12200 && !movement::is_inside_word(display_map, display_range.end))
12201 {
12202 // TODO: This is n^2, because we might check all the selections
12203 if !selections
12204 .iter()
12205 .any(|selection| selection.range().overlaps(&offset_range))
12206 {
12207 next_selected_range = Some(offset_range);
12208 break;
12209 }
12210 }
12211 }
12212
12213 if let Some(next_selected_range) = next_selected_range {
12214 self.select_match_ranges(
12215 next_selected_range,
12216 last_selection.reversed,
12217 replace_newest,
12218 autoscroll,
12219 window,
12220 cx,
12221 );
12222 } else {
12223 select_next_state.done = true;
12224 }
12225 }
12226
12227 self.select_next_state = Some(select_next_state);
12228 } else {
12229 let mut only_carets = true;
12230 let mut same_text_selected = true;
12231 let mut selected_text = None;
12232
12233 let mut selections_iter = selections.iter().peekable();
12234 while let Some(selection) = selections_iter.next() {
12235 if selection.start != selection.end {
12236 only_carets = false;
12237 }
12238
12239 if same_text_selected {
12240 if selected_text.is_none() {
12241 selected_text =
12242 Some(buffer.text_for_range(selection.range()).collect::<String>());
12243 }
12244
12245 if let Some(next_selection) = selections_iter.peek() {
12246 if next_selection.range().len() == selection.range().len() {
12247 let next_selected_text = buffer
12248 .text_for_range(next_selection.range())
12249 .collect::<String>();
12250 if Some(next_selected_text) != selected_text {
12251 same_text_selected = false;
12252 selected_text = None;
12253 }
12254 } else {
12255 same_text_selected = false;
12256 selected_text = None;
12257 }
12258 }
12259 }
12260 }
12261
12262 if only_carets {
12263 for selection in &mut selections {
12264 let word_range = movement::surrounding_word(
12265 display_map,
12266 selection.start.to_display_point(display_map),
12267 );
12268 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12269 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12270 selection.goal = SelectionGoal::None;
12271 selection.reversed = false;
12272 self.select_match_ranges(
12273 selection.start..selection.end,
12274 selection.reversed,
12275 replace_newest,
12276 autoscroll,
12277 window,
12278 cx,
12279 );
12280 }
12281
12282 if selections.len() == 1 {
12283 let selection = selections
12284 .last()
12285 .expect("ensured that there's only one selection");
12286 let query = buffer
12287 .text_for_range(selection.start..selection.end)
12288 .collect::<String>();
12289 let is_empty = query.is_empty();
12290 let select_state = SelectNextState {
12291 query: AhoCorasick::new(&[query])?,
12292 wordwise: true,
12293 done: is_empty,
12294 };
12295 self.select_next_state = Some(select_state);
12296 } else {
12297 self.select_next_state = None;
12298 }
12299 } else if let Some(selected_text) = selected_text {
12300 self.select_next_state = Some(SelectNextState {
12301 query: AhoCorasick::new(&[selected_text])?,
12302 wordwise: false,
12303 done: false,
12304 });
12305 self.select_next_match_internal(
12306 display_map,
12307 replace_newest,
12308 autoscroll,
12309 window,
12310 cx,
12311 )?;
12312 }
12313 }
12314 Ok(())
12315 }
12316
12317 pub fn select_all_matches(
12318 &mut self,
12319 _action: &SelectAllMatches,
12320 window: &mut Window,
12321 cx: &mut Context<Self>,
12322 ) -> Result<()> {
12323 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12324
12325 self.push_to_selection_history();
12326 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12327
12328 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12329 let Some(select_next_state) = self.select_next_state.as_mut() else {
12330 return Ok(());
12331 };
12332 if select_next_state.done {
12333 return Ok(());
12334 }
12335
12336 let mut new_selections = Vec::new();
12337
12338 let reversed = self.selections.oldest::<usize>(cx).reversed;
12339 let buffer = &display_map.buffer_snapshot;
12340 let query_matches = select_next_state
12341 .query
12342 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12343
12344 for query_match in query_matches.into_iter() {
12345 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12346 let offset_range = if reversed {
12347 query_match.end()..query_match.start()
12348 } else {
12349 query_match.start()..query_match.end()
12350 };
12351 let display_range = offset_range.start.to_display_point(&display_map)
12352 ..offset_range.end.to_display_point(&display_map);
12353
12354 if !select_next_state.wordwise
12355 || (!movement::is_inside_word(&display_map, display_range.start)
12356 && !movement::is_inside_word(&display_map, display_range.end))
12357 {
12358 new_selections.push(offset_range.start..offset_range.end);
12359 }
12360 }
12361
12362 select_next_state.done = true;
12363 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12364 self.change_selections(None, window, cx, |selections| {
12365 selections.select_ranges(new_selections)
12366 });
12367
12368 Ok(())
12369 }
12370
12371 pub fn select_next(
12372 &mut self,
12373 action: &SelectNext,
12374 window: &mut Window,
12375 cx: &mut Context<Self>,
12376 ) -> Result<()> {
12377 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12378 self.push_to_selection_history();
12379 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12380 self.select_next_match_internal(
12381 &display_map,
12382 action.replace_newest,
12383 Some(Autoscroll::newest()),
12384 window,
12385 cx,
12386 )?;
12387 Ok(())
12388 }
12389
12390 pub fn select_previous(
12391 &mut self,
12392 action: &SelectPrevious,
12393 window: &mut Window,
12394 cx: &mut Context<Self>,
12395 ) -> Result<()> {
12396 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12397 self.push_to_selection_history();
12398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12399 let buffer = &display_map.buffer_snapshot;
12400 let mut selections = self.selections.all::<usize>(cx);
12401 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12402 let query = &select_prev_state.query;
12403 if !select_prev_state.done {
12404 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12405 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12406 let mut next_selected_range = None;
12407 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12408 let bytes_before_last_selection =
12409 buffer.reversed_bytes_in_range(0..last_selection.start);
12410 let bytes_after_first_selection =
12411 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12412 let query_matches = query
12413 .stream_find_iter(bytes_before_last_selection)
12414 .map(|result| (last_selection.start, result))
12415 .chain(
12416 query
12417 .stream_find_iter(bytes_after_first_selection)
12418 .map(|result| (buffer.len(), result)),
12419 );
12420 for (end_offset, query_match) in query_matches {
12421 let query_match = query_match.unwrap(); // can only fail due to I/O
12422 let offset_range =
12423 end_offset - query_match.end()..end_offset - query_match.start();
12424 let display_range = offset_range.start.to_display_point(&display_map)
12425 ..offset_range.end.to_display_point(&display_map);
12426
12427 if !select_prev_state.wordwise
12428 || (!movement::is_inside_word(&display_map, display_range.start)
12429 && !movement::is_inside_word(&display_map, display_range.end))
12430 {
12431 next_selected_range = Some(offset_range);
12432 break;
12433 }
12434 }
12435
12436 if let Some(next_selected_range) = next_selected_range {
12437 self.select_match_ranges(
12438 next_selected_range,
12439 last_selection.reversed,
12440 action.replace_newest,
12441 Some(Autoscroll::newest()),
12442 window,
12443 cx,
12444 );
12445 } else {
12446 select_prev_state.done = true;
12447 }
12448 }
12449
12450 self.select_prev_state = Some(select_prev_state);
12451 } else {
12452 let mut only_carets = true;
12453 let mut same_text_selected = true;
12454 let mut selected_text = None;
12455
12456 let mut selections_iter = selections.iter().peekable();
12457 while let Some(selection) = selections_iter.next() {
12458 if selection.start != selection.end {
12459 only_carets = false;
12460 }
12461
12462 if same_text_selected {
12463 if selected_text.is_none() {
12464 selected_text =
12465 Some(buffer.text_for_range(selection.range()).collect::<String>());
12466 }
12467
12468 if let Some(next_selection) = selections_iter.peek() {
12469 if next_selection.range().len() == selection.range().len() {
12470 let next_selected_text = buffer
12471 .text_for_range(next_selection.range())
12472 .collect::<String>();
12473 if Some(next_selected_text) != selected_text {
12474 same_text_selected = false;
12475 selected_text = None;
12476 }
12477 } else {
12478 same_text_selected = false;
12479 selected_text = None;
12480 }
12481 }
12482 }
12483 }
12484
12485 if only_carets {
12486 for selection in &mut selections {
12487 let word_range = movement::surrounding_word(
12488 &display_map,
12489 selection.start.to_display_point(&display_map),
12490 );
12491 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12492 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12493 selection.goal = SelectionGoal::None;
12494 selection.reversed = false;
12495 self.select_match_ranges(
12496 selection.start..selection.end,
12497 selection.reversed,
12498 action.replace_newest,
12499 Some(Autoscroll::newest()),
12500 window,
12501 cx,
12502 );
12503 }
12504 if selections.len() == 1 {
12505 let selection = selections
12506 .last()
12507 .expect("ensured that there's only one selection");
12508 let query = buffer
12509 .text_for_range(selection.start..selection.end)
12510 .collect::<String>();
12511 let is_empty = query.is_empty();
12512 let select_state = SelectNextState {
12513 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12514 wordwise: true,
12515 done: is_empty,
12516 };
12517 self.select_prev_state = Some(select_state);
12518 } else {
12519 self.select_prev_state = None;
12520 }
12521 } else if let Some(selected_text) = selected_text {
12522 self.select_prev_state = Some(SelectNextState {
12523 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12524 wordwise: false,
12525 done: false,
12526 });
12527 self.select_previous(action, window, cx)?;
12528 }
12529 }
12530 Ok(())
12531 }
12532
12533 pub fn find_next_match(
12534 &mut self,
12535 _: &FindNextMatch,
12536 window: &mut Window,
12537 cx: &mut Context<Self>,
12538 ) -> Result<()> {
12539 let selections = self.selections.disjoint_anchors();
12540 match selections.first() {
12541 Some(first) if selections.len() >= 2 => {
12542 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12543 s.select_ranges([first.range()]);
12544 });
12545 }
12546 _ => self.select_next(
12547 &SelectNext {
12548 replace_newest: true,
12549 },
12550 window,
12551 cx,
12552 )?,
12553 }
12554 Ok(())
12555 }
12556
12557 pub fn find_previous_match(
12558 &mut self,
12559 _: &FindPreviousMatch,
12560 window: &mut Window,
12561 cx: &mut Context<Self>,
12562 ) -> Result<()> {
12563 let selections = self.selections.disjoint_anchors();
12564 match selections.last() {
12565 Some(last) if selections.len() >= 2 => {
12566 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12567 s.select_ranges([last.range()]);
12568 });
12569 }
12570 _ => self.select_previous(
12571 &SelectPrevious {
12572 replace_newest: true,
12573 },
12574 window,
12575 cx,
12576 )?,
12577 }
12578 Ok(())
12579 }
12580
12581 pub fn toggle_comments(
12582 &mut self,
12583 action: &ToggleComments,
12584 window: &mut Window,
12585 cx: &mut Context<Self>,
12586 ) {
12587 if self.read_only(cx) {
12588 return;
12589 }
12590 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12591 let text_layout_details = &self.text_layout_details(window);
12592 self.transact(window, cx, |this, window, cx| {
12593 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12594 let mut edits = Vec::new();
12595 let mut selection_edit_ranges = Vec::new();
12596 let mut last_toggled_row = None;
12597 let snapshot = this.buffer.read(cx).read(cx);
12598 let empty_str: Arc<str> = Arc::default();
12599 let mut suffixes_inserted = Vec::new();
12600 let ignore_indent = action.ignore_indent;
12601
12602 fn comment_prefix_range(
12603 snapshot: &MultiBufferSnapshot,
12604 row: MultiBufferRow,
12605 comment_prefix: &str,
12606 comment_prefix_whitespace: &str,
12607 ignore_indent: bool,
12608 ) -> Range<Point> {
12609 let indent_size = if ignore_indent {
12610 0
12611 } else {
12612 snapshot.indent_size_for_line(row).len
12613 };
12614
12615 let start = Point::new(row.0, indent_size);
12616
12617 let mut line_bytes = snapshot
12618 .bytes_in_range(start..snapshot.max_point())
12619 .flatten()
12620 .copied();
12621
12622 // If this line currently begins with the line comment prefix, then record
12623 // the range containing the prefix.
12624 if line_bytes
12625 .by_ref()
12626 .take(comment_prefix.len())
12627 .eq(comment_prefix.bytes())
12628 {
12629 // Include any whitespace that matches the comment prefix.
12630 let matching_whitespace_len = line_bytes
12631 .zip(comment_prefix_whitespace.bytes())
12632 .take_while(|(a, b)| a == b)
12633 .count() as u32;
12634 let end = Point::new(
12635 start.row,
12636 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12637 );
12638 start..end
12639 } else {
12640 start..start
12641 }
12642 }
12643
12644 fn comment_suffix_range(
12645 snapshot: &MultiBufferSnapshot,
12646 row: MultiBufferRow,
12647 comment_suffix: &str,
12648 comment_suffix_has_leading_space: bool,
12649 ) -> Range<Point> {
12650 let end = Point::new(row.0, snapshot.line_len(row));
12651 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12652
12653 let mut line_end_bytes = snapshot
12654 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12655 .flatten()
12656 .copied();
12657
12658 let leading_space_len = if suffix_start_column > 0
12659 && line_end_bytes.next() == Some(b' ')
12660 && comment_suffix_has_leading_space
12661 {
12662 1
12663 } else {
12664 0
12665 };
12666
12667 // If this line currently begins with the line comment prefix, then record
12668 // the range containing the prefix.
12669 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12670 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12671 start..end
12672 } else {
12673 end..end
12674 }
12675 }
12676
12677 // TODO: Handle selections that cross excerpts
12678 for selection in &mut selections {
12679 let start_column = snapshot
12680 .indent_size_for_line(MultiBufferRow(selection.start.row))
12681 .len;
12682 let language = if let Some(language) =
12683 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12684 {
12685 language
12686 } else {
12687 continue;
12688 };
12689
12690 selection_edit_ranges.clear();
12691
12692 // If multiple selections contain a given row, avoid processing that
12693 // row more than once.
12694 let mut start_row = MultiBufferRow(selection.start.row);
12695 if last_toggled_row == Some(start_row) {
12696 start_row = start_row.next_row();
12697 }
12698 let end_row =
12699 if selection.end.row > selection.start.row && selection.end.column == 0 {
12700 MultiBufferRow(selection.end.row - 1)
12701 } else {
12702 MultiBufferRow(selection.end.row)
12703 };
12704 last_toggled_row = Some(end_row);
12705
12706 if start_row > end_row {
12707 continue;
12708 }
12709
12710 // If the language has line comments, toggle those.
12711 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12712
12713 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12714 if ignore_indent {
12715 full_comment_prefixes = full_comment_prefixes
12716 .into_iter()
12717 .map(|s| Arc::from(s.trim_end()))
12718 .collect();
12719 }
12720
12721 if !full_comment_prefixes.is_empty() {
12722 let first_prefix = full_comment_prefixes
12723 .first()
12724 .expect("prefixes is non-empty");
12725 let prefix_trimmed_lengths = full_comment_prefixes
12726 .iter()
12727 .map(|p| p.trim_end_matches(' ').len())
12728 .collect::<SmallVec<[usize; 4]>>();
12729
12730 let mut all_selection_lines_are_comments = true;
12731
12732 for row in start_row.0..=end_row.0 {
12733 let row = MultiBufferRow(row);
12734 if start_row < end_row && snapshot.is_line_blank(row) {
12735 continue;
12736 }
12737
12738 let prefix_range = full_comment_prefixes
12739 .iter()
12740 .zip(prefix_trimmed_lengths.iter().copied())
12741 .map(|(prefix, trimmed_prefix_len)| {
12742 comment_prefix_range(
12743 snapshot.deref(),
12744 row,
12745 &prefix[..trimmed_prefix_len],
12746 &prefix[trimmed_prefix_len..],
12747 ignore_indent,
12748 )
12749 })
12750 .max_by_key(|range| range.end.column - range.start.column)
12751 .expect("prefixes is non-empty");
12752
12753 if prefix_range.is_empty() {
12754 all_selection_lines_are_comments = false;
12755 }
12756
12757 selection_edit_ranges.push(prefix_range);
12758 }
12759
12760 if all_selection_lines_are_comments {
12761 edits.extend(
12762 selection_edit_ranges
12763 .iter()
12764 .cloned()
12765 .map(|range| (range, empty_str.clone())),
12766 );
12767 } else {
12768 let min_column = selection_edit_ranges
12769 .iter()
12770 .map(|range| range.start.column)
12771 .min()
12772 .unwrap_or(0);
12773 edits.extend(selection_edit_ranges.iter().map(|range| {
12774 let position = Point::new(range.start.row, min_column);
12775 (position..position, first_prefix.clone())
12776 }));
12777 }
12778 } else if let Some((full_comment_prefix, comment_suffix)) =
12779 language.block_comment_delimiters()
12780 {
12781 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12782 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12783 let prefix_range = comment_prefix_range(
12784 snapshot.deref(),
12785 start_row,
12786 comment_prefix,
12787 comment_prefix_whitespace,
12788 ignore_indent,
12789 );
12790 let suffix_range = comment_suffix_range(
12791 snapshot.deref(),
12792 end_row,
12793 comment_suffix.trim_start_matches(' '),
12794 comment_suffix.starts_with(' '),
12795 );
12796
12797 if prefix_range.is_empty() || suffix_range.is_empty() {
12798 edits.push((
12799 prefix_range.start..prefix_range.start,
12800 full_comment_prefix.clone(),
12801 ));
12802 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12803 suffixes_inserted.push((end_row, comment_suffix.len()));
12804 } else {
12805 edits.push((prefix_range, empty_str.clone()));
12806 edits.push((suffix_range, empty_str.clone()));
12807 }
12808 } else {
12809 continue;
12810 }
12811 }
12812
12813 drop(snapshot);
12814 this.buffer.update(cx, |buffer, cx| {
12815 buffer.edit(edits, None, cx);
12816 });
12817
12818 // Adjust selections so that they end before any comment suffixes that
12819 // were inserted.
12820 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12821 let mut selections = this.selections.all::<Point>(cx);
12822 let snapshot = this.buffer.read(cx).read(cx);
12823 for selection in &mut selections {
12824 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12825 match row.cmp(&MultiBufferRow(selection.end.row)) {
12826 Ordering::Less => {
12827 suffixes_inserted.next();
12828 continue;
12829 }
12830 Ordering::Greater => break,
12831 Ordering::Equal => {
12832 if selection.end.column == snapshot.line_len(row) {
12833 if selection.is_empty() {
12834 selection.start.column -= suffix_len as u32;
12835 }
12836 selection.end.column -= suffix_len as u32;
12837 }
12838 break;
12839 }
12840 }
12841 }
12842 }
12843
12844 drop(snapshot);
12845 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12846 s.select(selections)
12847 });
12848
12849 let selections = this.selections.all::<Point>(cx);
12850 let selections_on_single_row = selections.windows(2).all(|selections| {
12851 selections[0].start.row == selections[1].start.row
12852 && selections[0].end.row == selections[1].end.row
12853 && selections[0].start.row == selections[0].end.row
12854 });
12855 let selections_selecting = selections
12856 .iter()
12857 .any(|selection| selection.start != selection.end);
12858 let advance_downwards = action.advance_downwards
12859 && selections_on_single_row
12860 && !selections_selecting
12861 && !matches!(this.mode, EditorMode::SingleLine { .. });
12862
12863 if advance_downwards {
12864 let snapshot = this.buffer.read(cx).snapshot(cx);
12865
12866 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12867 s.move_cursors_with(|display_snapshot, display_point, _| {
12868 let mut point = display_point.to_point(display_snapshot);
12869 point.row += 1;
12870 point = snapshot.clip_point(point, Bias::Left);
12871 let display_point = point.to_display_point(display_snapshot);
12872 let goal = SelectionGoal::HorizontalPosition(
12873 display_snapshot
12874 .x_for_display_point(display_point, text_layout_details)
12875 .into(),
12876 );
12877 (display_point, goal)
12878 })
12879 });
12880 }
12881 });
12882 }
12883
12884 pub fn select_enclosing_symbol(
12885 &mut self,
12886 _: &SelectEnclosingSymbol,
12887 window: &mut Window,
12888 cx: &mut Context<Self>,
12889 ) {
12890 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12891
12892 let buffer = self.buffer.read(cx).snapshot(cx);
12893 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12894
12895 fn update_selection(
12896 selection: &Selection<usize>,
12897 buffer_snap: &MultiBufferSnapshot,
12898 ) -> Option<Selection<usize>> {
12899 let cursor = selection.head();
12900 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12901 for symbol in symbols.iter().rev() {
12902 let start = symbol.range.start.to_offset(buffer_snap);
12903 let end = symbol.range.end.to_offset(buffer_snap);
12904 let new_range = start..end;
12905 if start < selection.start || end > selection.end {
12906 return Some(Selection {
12907 id: selection.id,
12908 start: new_range.start,
12909 end: new_range.end,
12910 goal: SelectionGoal::None,
12911 reversed: selection.reversed,
12912 });
12913 }
12914 }
12915 None
12916 }
12917
12918 let mut selected_larger_symbol = false;
12919 let new_selections = old_selections
12920 .iter()
12921 .map(|selection| match update_selection(selection, &buffer) {
12922 Some(new_selection) => {
12923 if new_selection.range() != selection.range() {
12924 selected_larger_symbol = true;
12925 }
12926 new_selection
12927 }
12928 None => selection.clone(),
12929 })
12930 .collect::<Vec<_>>();
12931
12932 if selected_larger_symbol {
12933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12934 s.select(new_selections);
12935 });
12936 }
12937 }
12938
12939 pub fn select_larger_syntax_node(
12940 &mut self,
12941 _: &SelectLargerSyntaxNode,
12942 window: &mut Window,
12943 cx: &mut Context<Self>,
12944 ) {
12945 let Some(visible_row_count) = self.visible_row_count() else {
12946 return;
12947 };
12948 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12949 if old_selections.is_empty() {
12950 return;
12951 }
12952
12953 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12954
12955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12956 let buffer = self.buffer.read(cx).snapshot(cx);
12957
12958 let mut selected_larger_node = false;
12959 let mut new_selections = old_selections
12960 .iter()
12961 .map(|selection| {
12962 let old_range = selection.start..selection.end;
12963
12964 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12965 // manually select word at selection
12966 if ["string_content", "inline"].contains(&node.kind()) {
12967 let word_range = {
12968 let display_point = buffer
12969 .offset_to_point(old_range.start)
12970 .to_display_point(&display_map);
12971 let Range { start, end } =
12972 movement::surrounding_word(&display_map, display_point);
12973 start.to_point(&display_map).to_offset(&buffer)
12974 ..end.to_point(&display_map).to_offset(&buffer)
12975 };
12976 // ignore if word is already selected
12977 if !word_range.is_empty() && old_range != word_range {
12978 let last_word_range = {
12979 let display_point = buffer
12980 .offset_to_point(old_range.end)
12981 .to_display_point(&display_map);
12982 let Range { start, end } =
12983 movement::surrounding_word(&display_map, display_point);
12984 start.to_point(&display_map).to_offset(&buffer)
12985 ..end.to_point(&display_map).to_offset(&buffer)
12986 };
12987 // only select word if start and end point belongs to same word
12988 if word_range == last_word_range {
12989 selected_larger_node = true;
12990 return Selection {
12991 id: selection.id,
12992 start: word_range.start,
12993 end: word_range.end,
12994 goal: SelectionGoal::None,
12995 reversed: selection.reversed,
12996 };
12997 }
12998 }
12999 }
13000 }
13001
13002 let mut new_range = old_range.clone();
13003 while let Some((_node, containing_range)) =
13004 buffer.syntax_ancestor(new_range.clone())
13005 {
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 selected_larger_node |= new_range != old_range;
13018 Selection {
13019 id: selection.id,
13020 start: new_range.start,
13021 end: new_range.end,
13022 goal: SelectionGoal::None,
13023 reversed: selection.reversed,
13024 }
13025 })
13026 .collect::<Vec<_>>();
13027
13028 if !selected_larger_node {
13029 return; // don't put this call in the history
13030 }
13031
13032 // scroll based on transformation done to the last selection created by the user
13033 let (last_old, last_new) = old_selections
13034 .last()
13035 .zip(new_selections.last().cloned())
13036 .expect("old_selections isn't empty");
13037
13038 // revert selection
13039 let is_selection_reversed = {
13040 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13041 new_selections.last_mut().expect("checked above").reversed =
13042 should_newest_selection_be_reversed;
13043 should_newest_selection_be_reversed
13044 };
13045
13046 if selected_larger_node {
13047 self.select_syntax_node_history.disable_clearing = true;
13048 self.change_selections(None, window, cx, |s| {
13049 s.select(new_selections.clone());
13050 });
13051 self.select_syntax_node_history.disable_clearing = false;
13052 }
13053
13054 let start_row = last_new.start.to_display_point(&display_map).row().0;
13055 let end_row = last_new.end.to_display_point(&display_map).row().0;
13056 let selection_height = end_row - start_row + 1;
13057 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13058
13059 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13060 let scroll_behavior = if fits_on_the_screen {
13061 self.request_autoscroll(Autoscroll::fit(), cx);
13062 SelectSyntaxNodeScrollBehavior::FitSelection
13063 } else if is_selection_reversed {
13064 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13065 SelectSyntaxNodeScrollBehavior::CursorTop
13066 } else {
13067 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13068 SelectSyntaxNodeScrollBehavior::CursorBottom
13069 };
13070
13071 self.select_syntax_node_history.push((
13072 old_selections,
13073 scroll_behavior,
13074 is_selection_reversed,
13075 ));
13076 }
13077
13078 pub fn select_smaller_syntax_node(
13079 &mut self,
13080 _: &SelectSmallerSyntaxNode,
13081 window: &mut Window,
13082 cx: &mut Context<Self>,
13083 ) {
13084 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13085
13086 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13087 self.select_syntax_node_history.pop()
13088 {
13089 if let Some(selection) = selections.last_mut() {
13090 selection.reversed = is_selection_reversed;
13091 }
13092
13093 self.select_syntax_node_history.disable_clearing = true;
13094 self.change_selections(None, window, cx, |s| {
13095 s.select(selections.to_vec());
13096 });
13097 self.select_syntax_node_history.disable_clearing = false;
13098
13099 match scroll_behavior {
13100 SelectSyntaxNodeScrollBehavior::CursorTop => {
13101 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13102 }
13103 SelectSyntaxNodeScrollBehavior::FitSelection => {
13104 self.request_autoscroll(Autoscroll::fit(), cx);
13105 }
13106 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13107 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13108 }
13109 }
13110 }
13111 }
13112
13113 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13114 if !EditorSettings::get_global(cx).gutter.runnables {
13115 self.clear_tasks();
13116 return Task::ready(());
13117 }
13118 let project = self.project.as_ref().map(Entity::downgrade);
13119 let task_sources = self.lsp_task_sources(cx);
13120 cx.spawn_in(window, async move |editor, cx| {
13121 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13122 let Some(project) = project.and_then(|p| p.upgrade()) else {
13123 return;
13124 };
13125 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13126 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13127 }) else {
13128 return;
13129 };
13130
13131 let hide_runnables = project
13132 .update(cx, |project, cx| {
13133 // Do not display any test indicators in non-dev server remote projects.
13134 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13135 })
13136 .unwrap_or(true);
13137 if hide_runnables {
13138 return;
13139 }
13140 let new_rows =
13141 cx.background_spawn({
13142 let snapshot = display_snapshot.clone();
13143 async move {
13144 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13145 }
13146 })
13147 .await;
13148 let Ok(lsp_tasks) =
13149 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13150 else {
13151 return;
13152 };
13153 let lsp_tasks = lsp_tasks.await;
13154
13155 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13156 lsp_tasks
13157 .into_iter()
13158 .flat_map(|(kind, tasks)| {
13159 tasks.into_iter().filter_map(move |(location, task)| {
13160 Some((kind.clone(), location?, task))
13161 })
13162 })
13163 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13164 let buffer = location.target.buffer;
13165 let buffer_snapshot = buffer.read(cx).snapshot();
13166 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13167 |(excerpt_id, snapshot, _)| {
13168 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13169 display_snapshot
13170 .buffer_snapshot
13171 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13172 } else {
13173 None
13174 }
13175 },
13176 );
13177 if let Some(offset) = offset {
13178 let task_buffer_range =
13179 location.target.range.to_point(&buffer_snapshot);
13180 let context_buffer_range =
13181 task_buffer_range.to_offset(&buffer_snapshot);
13182 let context_range = BufferOffset(context_buffer_range.start)
13183 ..BufferOffset(context_buffer_range.end);
13184
13185 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13186 .or_insert_with(|| RunnableTasks {
13187 templates: Vec::new(),
13188 offset,
13189 column: task_buffer_range.start.column,
13190 extra_variables: HashMap::default(),
13191 context_range,
13192 })
13193 .templates
13194 .push((kind, task.original_task().clone()));
13195 }
13196
13197 acc
13198 })
13199 }) else {
13200 return;
13201 };
13202
13203 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13204 editor
13205 .update(cx, |editor, _| {
13206 editor.clear_tasks();
13207 for (key, mut value) in rows {
13208 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13209 value.templates.extend(lsp_tasks.templates);
13210 }
13211
13212 editor.insert_tasks(key, value);
13213 }
13214 for (key, value) in lsp_tasks_by_rows {
13215 editor.insert_tasks(key, value);
13216 }
13217 })
13218 .ok();
13219 })
13220 }
13221 fn fetch_runnable_ranges(
13222 snapshot: &DisplaySnapshot,
13223 range: Range<Anchor>,
13224 ) -> Vec<language::RunnableRange> {
13225 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13226 }
13227
13228 fn runnable_rows(
13229 project: Entity<Project>,
13230 snapshot: DisplaySnapshot,
13231 runnable_ranges: Vec<RunnableRange>,
13232 mut cx: AsyncWindowContext,
13233 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13234 runnable_ranges
13235 .into_iter()
13236 .filter_map(|mut runnable| {
13237 let tasks = cx
13238 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13239 .ok()?;
13240 if tasks.is_empty() {
13241 return None;
13242 }
13243
13244 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13245
13246 let row = snapshot
13247 .buffer_snapshot
13248 .buffer_line_for_row(MultiBufferRow(point.row))?
13249 .1
13250 .start
13251 .row;
13252
13253 let context_range =
13254 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13255 Some((
13256 (runnable.buffer_id, row),
13257 RunnableTasks {
13258 templates: tasks,
13259 offset: snapshot
13260 .buffer_snapshot
13261 .anchor_before(runnable.run_range.start),
13262 context_range,
13263 column: point.column,
13264 extra_variables: runnable.extra_captures,
13265 },
13266 ))
13267 })
13268 .collect()
13269 }
13270
13271 fn templates_with_tags(
13272 project: &Entity<Project>,
13273 runnable: &mut Runnable,
13274 cx: &mut App,
13275 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13276 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13277 let (worktree_id, file) = project
13278 .buffer_for_id(runnable.buffer, cx)
13279 .and_then(|buffer| buffer.read(cx).file())
13280 .map(|file| (file.worktree_id(cx), file.clone()))
13281 .unzip();
13282
13283 (
13284 project.task_store().read(cx).task_inventory().cloned(),
13285 worktree_id,
13286 file,
13287 )
13288 });
13289
13290 let mut templates_with_tags = mem::take(&mut runnable.tags)
13291 .into_iter()
13292 .flat_map(|RunnableTag(tag)| {
13293 inventory
13294 .as_ref()
13295 .into_iter()
13296 .flat_map(|inventory| {
13297 inventory.read(cx).list_tasks(
13298 file.clone(),
13299 Some(runnable.language.clone()),
13300 worktree_id,
13301 cx,
13302 )
13303 })
13304 .filter(move |(_, template)| {
13305 template.tags.iter().any(|source_tag| source_tag == &tag)
13306 })
13307 })
13308 .sorted_by_key(|(kind, _)| kind.to_owned())
13309 .collect::<Vec<_>>();
13310 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13311 // Strongest source wins; if we have worktree tag binding, prefer that to
13312 // global and language bindings;
13313 // if we have a global binding, prefer that to language binding.
13314 let first_mismatch = templates_with_tags
13315 .iter()
13316 .position(|(tag_source, _)| tag_source != leading_tag_source);
13317 if let Some(index) = first_mismatch {
13318 templates_with_tags.truncate(index);
13319 }
13320 }
13321
13322 templates_with_tags
13323 }
13324
13325 pub fn move_to_enclosing_bracket(
13326 &mut self,
13327 _: &MoveToEnclosingBracket,
13328 window: &mut Window,
13329 cx: &mut Context<Self>,
13330 ) {
13331 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13332 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13333 s.move_offsets_with(|snapshot, selection| {
13334 let Some(enclosing_bracket_ranges) =
13335 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13336 else {
13337 return;
13338 };
13339
13340 let mut best_length = usize::MAX;
13341 let mut best_inside = false;
13342 let mut best_in_bracket_range = false;
13343 let mut best_destination = None;
13344 for (open, close) in enclosing_bracket_ranges {
13345 let close = close.to_inclusive();
13346 let length = close.end() - open.start;
13347 let inside = selection.start >= open.end && selection.end <= *close.start();
13348 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13349 || close.contains(&selection.head());
13350
13351 // If best is next to a bracket and current isn't, skip
13352 if !in_bracket_range && best_in_bracket_range {
13353 continue;
13354 }
13355
13356 // Prefer smaller lengths unless best is inside and current isn't
13357 if length > best_length && (best_inside || !inside) {
13358 continue;
13359 }
13360
13361 best_length = length;
13362 best_inside = inside;
13363 best_in_bracket_range = in_bracket_range;
13364 best_destination = Some(
13365 if close.contains(&selection.start) && close.contains(&selection.end) {
13366 if inside { open.end } else { open.start }
13367 } else if inside {
13368 *close.start()
13369 } else {
13370 *close.end()
13371 },
13372 );
13373 }
13374
13375 if let Some(destination) = best_destination {
13376 selection.collapse_to(destination, SelectionGoal::None);
13377 }
13378 })
13379 });
13380 }
13381
13382 pub fn undo_selection(
13383 &mut self,
13384 _: &UndoSelection,
13385 window: &mut Window,
13386 cx: &mut Context<Self>,
13387 ) {
13388 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13389 self.end_selection(window, cx);
13390 self.selection_history.mode = SelectionHistoryMode::Undoing;
13391 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13392 self.change_selections(None, window, cx, |s| {
13393 s.select_anchors(entry.selections.to_vec())
13394 });
13395 self.select_next_state = entry.select_next_state;
13396 self.select_prev_state = entry.select_prev_state;
13397 self.add_selections_state = entry.add_selections_state;
13398 self.request_autoscroll(Autoscroll::newest(), cx);
13399 }
13400 self.selection_history.mode = SelectionHistoryMode::Normal;
13401 }
13402
13403 pub fn redo_selection(
13404 &mut self,
13405 _: &RedoSelection,
13406 window: &mut Window,
13407 cx: &mut Context<Self>,
13408 ) {
13409 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13410 self.end_selection(window, cx);
13411 self.selection_history.mode = SelectionHistoryMode::Redoing;
13412 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13413 self.change_selections(None, window, cx, |s| {
13414 s.select_anchors(entry.selections.to_vec())
13415 });
13416 self.select_next_state = entry.select_next_state;
13417 self.select_prev_state = entry.select_prev_state;
13418 self.add_selections_state = entry.add_selections_state;
13419 self.request_autoscroll(Autoscroll::newest(), cx);
13420 }
13421 self.selection_history.mode = SelectionHistoryMode::Normal;
13422 }
13423
13424 pub fn expand_excerpts(
13425 &mut self,
13426 action: &ExpandExcerpts,
13427 _: &mut Window,
13428 cx: &mut Context<Self>,
13429 ) {
13430 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13431 }
13432
13433 pub fn expand_excerpts_down(
13434 &mut self,
13435 action: &ExpandExcerptsDown,
13436 _: &mut Window,
13437 cx: &mut Context<Self>,
13438 ) {
13439 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13440 }
13441
13442 pub fn expand_excerpts_up(
13443 &mut self,
13444 action: &ExpandExcerptsUp,
13445 _: &mut Window,
13446 cx: &mut Context<Self>,
13447 ) {
13448 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13449 }
13450
13451 pub fn expand_excerpts_for_direction(
13452 &mut self,
13453 lines: u32,
13454 direction: ExpandExcerptDirection,
13455
13456 cx: &mut Context<Self>,
13457 ) {
13458 let selections = self.selections.disjoint_anchors();
13459
13460 let lines = if lines == 0 {
13461 EditorSettings::get_global(cx).expand_excerpt_lines
13462 } else {
13463 lines
13464 };
13465
13466 self.buffer.update(cx, |buffer, cx| {
13467 let snapshot = buffer.snapshot(cx);
13468 let mut excerpt_ids = selections
13469 .iter()
13470 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13471 .collect::<Vec<_>>();
13472 excerpt_ids.sort();
13473 excerpt_ids.dedup();
13474 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13475 })
13476 }
13477
13478 pub fn expand_excerpt(
13479 &mut self,
13480 excerpt: ExcerptId,
13481 direction: ExpandExcerptDirection,
13482 window: &mut Window,
13483 cx: &mut Context<Self>,
13484 ) {
13485 let current_scroll_position = self.scroll_position(cx);
13486 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13487 let mut should_scroll_up = false;
13488
13489 if direction == ExpandExcerptDirection::Down {
13490 let multi_buffer = self.buffer.read(cx);
13491 let snapshot = multi_buffer.snapshot(cx);
13492 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13493 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13494 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13495 let buffer_snapshot = buffer.read(cx).snapshot();
13496 let excerpt_end_row =
13497 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13498 let last_row = buffer_snapshot.max_point().row;
13499 let lines_below = last_row.saturating_sub(excerpt_end_row);
13500 should_scroll_up = lines_below >= lines_to_expand;
13501 }
13502 }
13503 }
13504 }
13505
13506 self.buffer.update(cx, |buffer, cx| {
13507 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13508 });
13509
13510 if should_scroll_up {
13511 let new_scroll_position =
13512 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13513 self.set_scroll_position(new_scroll_position, window, cx);
13514 }
13515 }
13516
13517 pub fn go_to_singleton_buffer_point(
13518 &mut self,
13519 point: Point,
13520 window: &mut Window,
13521 cx: &mut Context<Self>,
13522 ) {
13523 self.go_to_singleton_buffer_range(point..point, window, cx);
13524 }
13525
13526 pub fn go_to_singleton_buffer_range(
13527 &mut self,
13528 range: Range<Point>,
13529 window: &mut Window,
13530 cx: &mut Context<Self>,
13531 ) {
13532 let multibuffer = self.buffer().read(cx);
13533 let Some(buffer) = multibuffer.as_singleton() else {
13534 return;
13535 };
13536 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13537 return;
13538 };
13539 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13540 return;
13541 };
13542 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13543 s.select_anchor_ranges([start..end])
13544 });
13545 }
13546
13547 pub fn go_to_diagnostic(
13548 &mut self,
13549 _: &GoToDiagnostic,
13550 window: &mut Window,
13551 cx: &mut Context<Self>,
13552 ) {
13553 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13554 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13555 }
13556
13557 pub fn go_to_prev_diagnostic(
13558 &mut self,
13559 _: &GoToPreviousDiagnostic,
13560 window: &mut Window,
13561 cx: &mut Context<Self>,
13562 ) {
13563 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13564 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13565 }
13566
13567 pub fn go_to_diagnostic_impl(
13568 &mut self,
13569 direction: Direction,
13570 window: &mut Window,
13571 cx: &mut Context<Self>,
13572 ) {
13573 let buffer = self.buffer.read(cx).snapshot(cx);
13574 let selection = self.selections.newest::<usize>(cx);
13575
13576 let mut active_group_id = None;
13577 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13578 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13579 active_group_id = Some(active_group.group_id);
13580 }
13581 }
13582
13583 fn filtered(
13584 snapshot: EditorSnapshot,
13585 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13586 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13587 diagnostics
13588 .filter(|entry| entry.range.start != entry.range.end)
13589 .filter(|entry| !entry.diagnostic.is_unnecessary)
13590 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13591 }
13592
13593 let snapshot = self.snapshot(window, cx);
13594 let before = filtered(
13595 snapshot.clone(),
13596 buffer
13597 .diagnostics_in_range(0..selection.start)
13598 .filter(|entry| entry.range.start <= selection.start),
13599 );
13600 let after = filtered(
13601 snapshot,
13602 buffer
13603 .diagnostics_in_range(selection.start..buffer.len())
13604 .filter(|entry| entry.range.start >= selection.start),
13605 );
13606
13607 let mut found: Option<DiagnosticEntry<usize>> = None;
13608 if direction == Direction::Prev {
13609 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13610 {
13611 for diagnostic in prev_diagnostics.into_iter().rev() {
13612 if diagnostic.range.start != selection.start
13613 || active_group_id
13614 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13615 {
13616 found = Some(diagnostic);
13617 break 'outer;
13618 }
13619 }
13620 }
13621 } else {
13622 for diagnostic in after.chain(before) {
13623 if diagnostic.range.start != selection.start
13624 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13625 {
13626 found = Some(diagnostic);
13627 break;
13628 }
13629 }
13630 }
13631 let Some(next_diagnostic) = found else {
13632 return;
13633 };
13634
13635 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13636 return;
13637 };
13638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13639 s.select_ranges(vec![
13640 next_diagnostic.range.start..next_diagnostic.range.start,
13641 ])
13642 });
13643 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13644 self.refresh_inline_completion(false, true, window, cx);
13645 }
13646
13647 pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13648 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13649 let snapshot = self.snapshot(window, cx);
13650 let selection = self.selections.newest::<Point>(cx);
13651 self.go_to_hunk_before_or_after_position(
13652 &snapshot,
13653 selection.head(),
13654 Direction::Next,
13655 window,
13656 cx,
13657 );
13658 }
13659
13660 pub fn go_to_hunk_before_or_after_position(
13661 &mut self,
13662 snapshot: &EditorSnapshot,
13663 position: Point,
13664 direction: Direction,
13665 window: &mut Window,
13666 cx: &mut Context<Editor>,
13667 ) {
13668 let row = if direction == Direction::Next {
13669 self.hunk_after_position(snapshot, position)
13670 .map(|hunk| hunk.row_range.start)
13671 } else {
13672 self.hunk_before_position(snapshot, position)
13673 };
13674
13675 if let Some(row) = row {
13676 let destination = Point::new(row.0, 0);
13677 let autoscroll = Autoscroll::center();
13678
13679 self.unfold_ranges(&[destination..destination], false, false, cx);
13680 self.change_selections(Some(autoscroll), window, cx, |s| {
13681 s.select_ranges([destination..destination]);
13682 });
13683 }
13684 }
13685
13686 fn hunk_after_position(
13687 &mut self,
13688 snapshot: &EditorSnapshot,
13689 position: Point,
13690 ) -> Option<MultiBufferDiffHunk> {
13691 snapshot
13692 .buffer_snapshot
13693 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13694 .find(|hunk| hunk.row_range.start.0 > position.row)
13695 .or_else(|| {
13696 snapshot
13697 .buffer_snapshot
13698 .diff_hunks_in_range(Point::zero()..position)
13699 .find(|hunk| hunk.row_range.end.0 < position.row)
13700 })
13701 }
13702
13703 fn go_to_prev_hunk(
13704 &mut self,
13705 _: &GoToPreviousHunk,
13706 window: &mut Window,
13707 cx: &mut Context<Self>,
13708 ) {
13709 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13710 let snapshot = self.snapshot(window, cx);
13711 let selection = self.selections.newest::<Point>(cx);
13712 self.go_to_hunk_before_or_after_position(
13713 &snapshot,
13714 selection.head(),
13715 Direction::Prev,
13716 window,
13717 cx,
13718 );
13719 }
13720
13721 fn hunk_before_position(
13722 &mut self,
13723 snapshot: &EditorSnapshot,
13724 position: Point,
13725 ) -> Option<MultiBufferRow> {
13726 snapshot
13727 .buffer_snapshot
13728 .diff_hunk_before(position)
13729 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13730 }
13731
13732 fn go_to_next_change(
13733 &mut self,
13734 _: &GoToNextChange,
13735 window: &mut Window,
13736 cx: &mut Context<Self>,
13737 ) {
13738 if let Some(selections) = self
13739 .change_list
13740 .next_change(1, Direction::Next)
13741 .map(|s| s.to_vec())
13742 {
13743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13744 let map = s.display_map();
13745 s.select_display_ranges(selections.iter().map(|a| {
13746 let point = a.to_display_point(&map);
13747 point..point
13748 }))
13749 })
13750 }
13751 }
13752
13753 fn go_to_previous_change(
13754 &mut self,
13755 _: &GoToPreviousChange,
13756 window: &mut Window,
13757 cx: &mut Context<Self>,
13758 ) {
13759 if let Some(selections) = self
13760 .change_list
13761 .next_change(1, Direction::Prev)
13762 .map(|s| s.to_vec())
13763 {
13764 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13765 let map = s.display_map();
13766 s.select_display_ranges(selections.iter().map(|a| {
13767 let point = a.to_display_point(&map);
13768 point..point
13769 }))
13770 })
13771 }
13772 }
13773
13774 fn go_to_line<T: 'static>(
13775 &mut self,
13776 position: Anchor,
13777 highlight_color: Option<Hsla>,
13778 window: &mut Window,
13779 cx: &mut Context<Self>,
13780 ) {
13781 let snapshot = self.snapshot(window, cx).display_snapshot;
13782 let position = position.to_point(&snapshot.buffer_snapshot);
13783 let start = snapshot
13784 .buffer_snapshot
13785 .clip_point(Point::new(position.row, 0), Bias::Left);
13786 let end = start + Point::new(1, 0);
13787 let start = snapshot.buffer_snapshot.anchor_before(start);
13788 let end = snapshot.buffer_snapshot.anchor_before(end);
13789
13790 self.highlight_rows::<T>(
13791 start..end,
13792 highlight_color
13793 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13794 Default::default(),
13795 cx,
13796 );
13797 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13798 }
13799
13800 pub fn go_to_definition(
13801 &mut self,
13802 _: &GoToDefinition,
13803 window: &mut Window,
13804 cx: &mut Context<Self>,
13805 ) -> Task<Result<Navigated>> {
13806 let definition =
13807 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13808 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13809 cx.spawn_in(window, async move |editor, cx| {
13810 if definition.await? == Navigated::Yes {
13811 return Ok(Navigated::Yes);
13812 }
13813 match fallback_strategy {
13814 GoToDefinitionFallback::None => Ok(Navigated::No),
13815 GoToDefinitionFallback::FindAllReferences => {
13816 match editor.update_in(cx, |editor, window, cx| {
13817 editor.find_all_references(&FindAllReferences, window, cx)
13818 })? {
13819 Some(references) => references.await,
13820 None => Ok(Navigated::No),
13821 }
13822 }
13823 }
13824 })
13825 }
13826
13827 pub fn go_to_declaration(
13828 &mut self,
13829 _: &GoToDeclaration,
13830 window: &mut Window,
13831 cx: &mut Context<Self>,
13832 ) -> Task<Result<Navigated>> {
13833 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13834 }
13835
13836 pub fn go_to_declaration_split(
13837 &mut self,
13838 _: &GoToDeclaration,
13839 window: &mut Window,
13840 cx: &mut Context<Self>,
13841 ) -> Task<Result<Navigated>> {
13842 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13843 }
13844
13845 pub fn go_to_implementation(
13846 &mut self,
13847 _: &GoToImplementation,
13848 window: &mut Window,
13849 cx: &mut Context<Self>,
13850 ) -> Task<Result<Navigated>> {
13851 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13852 }
13853
13854 pub fn go_to_implementation_split(
13855 &mut self,
13856 _: &GoToImplementationSplit,
13857 window: &mut Window,
13858 cx: &mut Context<Self>,
13859 ) -> Task<Result<Navigated>> {
13860 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13861 }
13862
13863 pub fn go_to_type_definition(
13864 &mut self,
13865 _: &GoToTypeDefinition,
13866 window: &mut Window,
13867 cx: &mut Context<Self>,
13868 ) -> Task<Result<Navigated>> {
13869 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13870 }
13871
13872 pub fn go_to_definition_split(
13873 &mut self,
13874 _: &GoToDefinitionSplit,
13875 window: &mut Window,
13876 cx: &mut Context<Self>,
13877 ) -> Task<Result<Navigated>> {
13878 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13879 }
13880
13881 pub fn go_to_type_definition_split(
13882 &mut self,
13883 _: &GoToTypeDefinitionSplit,
13884 window: &mut Window,
13885 cx: &mut Context<Self>,
13886 ) -> Task<Result<Navigated>> {
13887 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13888 }
13889
13890 fn go_to_definition_of_kind(
13891 &mut self,
13892 kind: GotoDefinitionKind,
13893 split: bool,
13894 window: &mut Window,
13895 cx: &mut Context<Self>,
13896 ) -> Task<Result<Navigated>> {
13897 let Some(provider) = self.semantics_provider.clone() else {
13898 return Task::ready(Ok(Navigated::No));
13899 };
13900 let head = self.selections.newest::<usize>(cx).head();
13901 let buffer = self.buffer.read(cx);
13902 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13903 text_anchor
13904 } else {
13905 return Task::ready(Ok(Navigated::No));
13906 };
13907
13908 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13909 return Task::ready(Ok(Navigated::No));
13910 };
13911
13912 cx.spawn_in(window, async move |editor, cx| {
13913 let definitions = definitions.await?;
13914 let navigated = editor
13915 .update_in(cx, |editor, window, cx| {
13916 editor.navigate_to_hover_links(
13917 Some(kind),
13918 definitions
13919 .into_iter()
13920 .filter(|location| {
13921 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13922 })
13923 .map(HoverLink::Text)
13924 .collect::<Vec<_>>(),
13925 split,
13926 window,
13927 cx,
13928 )
13929 })?
13930 .await?;
13931 anyhow::Ok(navigated)
13932 })
13933 }
13934
13935 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13936 let selection = self.selections.newest_anchor();
13937 let head = selection.head();
13938 let tail = selection.tail();
13939
13940 let Some((buffer, start_position)) =
13941 self.buffer.read(cx).text_anchor_for_position(head, cx)
13942 else {
13943 return;
13944 };
13945
13946 let end_position = if head != tail {
13947 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13948 return;
13949 };
13950 Some(pos)
13951 } else {
13952 None
13953 };
13954
13955 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13956 let url = if let Some(end_pos) = end_position {
13957 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13958 } else {
13959 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13960 };
13961
13962 if let Some(url) = url {
13963 editor.update(cx, |_, cx| {
13964 cx.open_url(&url);
13965 })
13966 } else {
13967 Ok(())
13968 }
13969 });
13970
13971 url_finder.detach();
13972 }
13973
13974 pub fn open_selected_filename(
13975 &mut self,
13976 _: &OpenSelectedFilename,
13977 window: &mut Window,
13978 cx: &mut Context<Self>,
13979 ) {
13980 let Some(workspace) = self.workspace() else {
13981 return;
13982 };
13983
13984 let position = self.selections.newest_anchor().head();
13985
13986 let Some((buffer, buffer_position)) =
13987 self.buffer.read(cx).text_anchor_for_position(position, cx)
13988 else {
13989 return;
13990 };
13991
13992 let project = self.project.clone();
13993
13994 cx.spawn_in(window, async move |_, cx| {
13995 let result = find_file(&buffer, project, buffer_position, cx).await;
13996
13997 if let Some((_, path)) = result {
13998 workspace
13999 .update_in(cx, |workspace, window, cx| {
14000 workspace.open_resolved_path(path, window, cx)
14001 })?
14002 .await?;
14003 }
14004 anyhow::Ok(())
14005 })
14006 .detach();
14007 }
14008
14009 pub(crate) fn navigate_to_hover_links(
14010 &mut self,
14011 kind: Option<GotoDefinitionKind>,
14012 mut definitions: Vec<HoverLink>,
14013 split: bool,
14014 window: &mut Window,
14015 cx: &mut Context<Editor>,
14016 ) -> Task<Result<Navigated>> {
14017 // If there is one definition, just open it directly
14018 if definitions.len() == 1 {
14019 let definition = definitions.pop().unwrap();
14020
14021 enum TargetTaskResult {
14022 Location(Option<Location>),
14023 AlreadyNavigated,
14024 }
14025
14026 let target_task = match definition {
14027 HoverLink::Text(link) => {
14028 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14029 }
14030 HoverLink::InlayHint(lsp_location, server_id) => {
14031 let computation =
14032 self.compute_target_location(lsp_location, server_id, window, cx);
14033 cx.background_spawn(async move {
14034 let location = computation.await?;
14035 Ok(TargetTaskResult::Location(location))
14036 })
14037 }
14038 HoverLink::Url(url) => {
14039 cx.open_url(&url);
14040 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14041 }
14042 HoverLink::File(path) => {
14043 if let Some(workspace) = self.workspace() {
14044 cx.spawn_in(window, async move |_, cx| {
14045 workspace
14046 .update_in(cx, |workspace, window, cx| {
14047 workspace.open_resolved_path(path, window, cx)
14048 })?
14049 .await
14050 .map(|_| TargetTaskResult::AlreadyNavigated)
14051 })
14052 } else {
14053 Task::ready(Ok(TargetTaskResult::Location(None)))
14054 }
14055 }
14056 };
14057 cx.spawn_in(window, async move |editor, cx| {
14058 let target = match target_task.await.context("target resolution task")? {
14059 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14060 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14061 TargetTaskResult::Location(Some(target)) => target,
14062 };
14063
14064 editor.update_in(cx, |editor, window, cx| {
14065 let Some(workspace) = editor.workspace() else {
14066 return Navigated::No;
14067 };
14068 let pane = workspace.read(cx).active_pane().clone();
14069
14070 let range = target.range.to_point(target.buffer.read(cx));
14071 let range = editor.range_for_match(&range);
14072 let range = collapse_multiline_range(range);
14073
14074 if !split
14075 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14076 {
14077 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14078 } else {
14079 window.defer(cx, move |window, cx| {
14080 let target_editor: Entity<Self> =
14081 workspace.update(cx, |workspace, cx| {
14082 let pane = if split {
14083 workspace.adjacent_pane(window, cx)
14084 } else {
14085 workspace.active_pane().clone()
14086 };
14087
14088 workspace.open_project_item(
14089 pane,
14090 target.buffer.clone(),
14091 true,
14092 true,
14093 window,
14094 cx,
14095 )
14096 });
14097 target_editor.update(cx, |target_editor, cx| {
14098 // When selecting a definition in a different buffer, disable the nav history
14099 // to avoid creating a history entry at the previous cursor location.
14100 pane.update(cx, |pane, _| pane.disable_history());
14101 target_editor.go_to_singleton_buffer_range(range, window, cx);
14102 pane.update(cx, |pane, _| pane.enable_history());
14103 });
14104 });
14105 }
14106 Navigated::Yes
14107 })
14108 })
14109 } else if !definitions.is_empty() {
14110 cx.spawn_in(window, async move |editor, cx| {
14111 let (title, location_tasks, workspace) = editor
14112 .update_in(cx, |editor, window, cx| {
14113 let tab_kind = match kind {
14114 Some(GotoDefinitionKind::Implementation) => "Implementations",
14115 _ => "Definitions",
14116 };
14117 let title = definitions
14118 .iter()
14119 .find_map(|definition| match definition {
14120 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14121 let buffer = origin.buffer.read(cx);
14122 format!(
14123 "{} for {}",
14124 tab_kind,
14125 buffer
14126 .text_for_range(origin.range.clone())
14127 .collect::<String>()
14128 )
14129 }),
14130 HoverLink::InlayHint(_, _) => None,
14131 HoverLink::Url(_) => None,
14132 HoverLink::File(_) => None,
14133 })
14134 .unwrap_or(tab_kind.to_string());
14135 let location_tasks = definitions
14136 .into_iter()
14137 .map(|definition| match definition {
14138 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14139 HoverLink::InlayHint(lsp_location, server_id) => editor
14140 .compute_target_location(lsp_location, server_id, window, cx),
14141 HoverLink::Url(_) => Task::ready(Ok(None)),
14142 HoverLink::File(_) => Task::ready(Ok(None)),
14143 })
14144 .collect::<Vec<_>>();
14145 (title, location_tasks, editor.workspace().clone())
14146 })
14147 .context("location tasks preparation")?;
14148
14149 let locations = future::join_all(location_tasks)
14150 .await
14151 .into_iter()
14152 .filter_map(|location| location.transpose())
14153 .collect::<Result<_>>()
14154 .context("location tasks")?;
14155
14156 let Some(workspace) = workspace else {
14157 return Ok(Navigated::No);
14158 };
14159 let opened = workspace
14160 .update_in(cx, |workspace, window, cx| {
14161 Self::open_locations_in_multibuffer(
14162 workspace,
14163 locations,
14164 title,
14165 split,
14166 MultibufferSelectionMode::First,
14167 window,
14168 cx,
14169 )
14170 })
14171 .ok();
14172
14173 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14174 })
14175 } else {
14176 Task::ready(Ok(Navigated::No))
14177 }
14178 }
14179
14180 fn compute_target_location(
14181 &self,
14182 lsp_location: lsp::Location,
14183 server_id: LanguageServerId,
14184 window: &mut Window,
14185 cx: &mut Context<Self>,
14186 ) -> Task<anyhow::Result<Option<Location>>> {
14187 let Some(project) = self.project.clone() else {
14188 return Task::ready(Ok(None));
14189 };
14190
14191 cx.spawn_in(window, async move |editor, cx| {
14192 let location_task = editor.update(cx, |_, cx| {
14193 project.update(cx, |project, cx| {
14194 let language_server_name = project
14195 .language_server_statuses(cx)
14196 .find(|(id, _)| server_id == *id)
14197 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14198 language_server_name.map(|language_server_name| {
14199 project.open_local_buffer_via_lsp(
14200 lsp_location.uri.clone(),
14201 server_id,
14202 language_server_name,
14203 cx,
14204 )
14205 })
14206 })
14207 })?;
14208 let location = match location_task {
14209 Some(task) => Some({
14210 let target_buffer_handle = task.await.context("open local buffer")?;
14211 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14212 let target_start = target_buffer
14213 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14214 let target_end = target_buffer
14215 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14216 target_buffer.anchor_after(target_start)
14217 ..target_buffer.anchor_before(target_end)
14218 })?;
14219 Location {
14220 buffer: target_buffer_handle,
14221 range,
14222 }
14223 }),
14224 None => None,
14225 };
14226 Ok(location)
14227 })
14228 }
14229
14230 pub fn find_all_references(
14231 &mut self,
14232 _: &FindAllReferences,
14233 window: &mut Window,
14234 cx: &mut Context<Self>,
14235 ) -> Option<Task<Result<Navigated>>> {
14236 let selection = self.selections.newest::<usize>(cx);
14237 let multi_buffer = self.buffer.read(cx);
14238 let head = selection.head();
14239
14240 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14241 let head_anchor = multi_buffer_snapshot.anchor_at(
14242 head,
14243 if head < selection.tail() {
14244 Bias::Right
14245 } else {
14246 Bias::Left
14247 },
14248 );
14249
14250 match self
14251 .find_all_references_task_sources
14252 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14253 {
14254 Ok(_) => {
14255 log::info!(
14256 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14257 );
14258 return None;
14259 }
14260 Err(i) => {
14261 self.find_all_references_task_sources.insert(i, head_anchor);
14262 }
14263 }
14264
14265 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14266 let workspace = self.workspace()?;
14267 let project = workspace.read(cx).project().clone();
14268 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14269 Some(cx.spawn_in(window, async move |editor, cx| {
14270 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14271 if let Ok(i) = editor
14272 .find_all_references_task_sources
14273 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14274 {
14275 editor.find_all_references_task_sources.remove(i);
14276 }
14277 });
14278
14279 let locations = references.await?;
14280 if locations.is_empty() {
14281 return anyhow::Ok(Navigated::No);
14282 }
14283
14284 workspace.update_in(cx, |workspace, window, cx| {
14285 let title = locations
14286 .first()
14287 .as_ref()
14288 .map(|location| {
14289 let buffer = location.buffer.read(cx);
14290 format!(
14291 "References to `{}`",
14292 buffer
14293 .text_for_range(location.range.clone())
14294 .collect::<String>()
14295 )
14296 })
14297 .unwrap();
14298 Self::open_locations_in_multibuffer(
14299 workspace,
14300 locations,
14301 title,
14302 false,
14303 MultibufferSelectionMode::First,
14304 window,
14305 cx,
14306 );
14307 Navigated::Yes
14308 })
14309 }))
14310 }
14311
14312 /// Opens a multibuffer with the given project locations in it
14313 pub fn open_locations_in_multibuffer(
14314 workspace: &mut Workspace,
14315 mut locations: Vec<Location>,
14316 title: String,
14317 split: bool,
14318 multibuffer_selection_mode: MultibufferSelectionMode,
14319 window: &mut Window,
14320 cx: &mut Context<Workspace>,
14321 ) {
14322 // If there are multiple definitions, open them in a multibuffer
14323 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14324 let mut locations = locations.into_iter().peekable();
14325 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14326 let capability = workspace.project().read(cx).capability();
14327
14328 let excerpt_buffer = cx.new(|cx| {
14329 let mut multibuffer = MultiBuffer::new(capability);
14330 while let Some(location) = locations.next() {
14331 let buffer = location.buffer.read(cx);
14332 let mut ranges_for_buffer = Vec::new();
14333 let range = location.range.to_point(buffer);
14334 ranges_for_buffer.push(range.clone());
14335
14336 while let Some(next_location) = locations.peek() {
14337 if next_location.buffer == location.buffer {
14338 ranges_for_buffer.push(next_location.range.to_point(buffer));
14339 locations.next();
14340 } else {
14341 break;
14342 }
14343 }
14344
14345 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14346 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14347 PathKey::for_buffer(&location.buffer, cx),
14348 location.buffer.clone(),
14349 ranges_for_buffer,
14350 DEFAULT_MULTIBUFFER_CONTEXT,
14351 cx,
14352 );
14353 ranges.extend(new_ranges)
14354 }
14355
14356 multibuffer.with_title(title)
14357 });
14358
14359 let editor = cx.new(|cx| {
14360 Editor::for_multibuffer(
14361 excerpt_buffer,
14362 Some(workspace.project().clone()),
14363 window,
14364 cx,
14365 )
14366 });
14367 editor.update(cx, |editor, cx| {
14368 match multibuffer_selection_mode {
14369 MultibufferSelectionMode::First => {
14370 if let Some(first_range) = ranges.first() {
14371 editor.change_selections(None, window, cx, |selections| {
14372 selections.clear_disjoint();
14373 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14374 });
14375 }
14376 editor.highlight_background::<Self>(
14377 &ranges,
14378 |theme| theme.editor_highlighted_line_background,
14379 cx,
14380 );
14381 }
14382 MultibufferSelectionMode::All => {
14383 editor.change_selections(None, window, cx, |selections| {
14384 selections.clear_disjoint();
14385 selections.select_anchor_ranges(ranges);
14386 });
14387 }
14388 }
14389 editor.register_buffers_with_language_servers(cx);
14390 });
14391
14392 let item = Box::new(editor);
14393 let item_id = item.item_id();
14394
14395 if split {
14396 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14397 } else {
14398 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14399 let (preview_item_id, preview_item_idx) =
14400 workspace.active_pane().update(cx, |pane, _| {
14401 (pane.preview_item_id(), pane.preview_item_idx())
14402 });
14403
14404 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14405
14406 if let Some(preview_item_id) = preview_item_id {
14407 workspace.active_pane().update(cx, |pane, cx| {
14408 pane.remove_item(preview_item_id, false, false, window, cx);
14409 });
14410 }
14411 } else {
14412 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14413 }
14414 }
14415 workspace.active_pane().update(cx, |pane, cx| {
14416 pane.set_preview_item_id(Some(item_id), cx);
14417 });
14418 }
14419
14420 pub fn rename(
14421 &mut self,
14422 _: &Rename,
14423 window: &mut Window,
14424 cx: &mut Context<Self>,
14425 ) -> Option<Task<Result<()>>> {
14426 use language::ToOffset as _;
14427
14428 let provider = self.semantics_provider.clone()?;
14429 let selection = self.selections.newest_anchor().clone();
14430 let (cursor_buffer, cursor_buffer_position) = self
14431 .buffer
14432 .read(cx)
14433 .text_anchor_for_position(selection.head(), cx)?;
14434 let (tail_buffer, cursor_buffer_position_end) = self
14435 .buffer
14436 .read(cx)
14437 .text_anchor_for_position(selection.tail(), cx)?;
14438 if tail_buffer != cursor_buffer {
14439 return None;
14440 }
14441
14442 let snapshot = cursor_buffer.read(cx).snapshot();
14443 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14444 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14445 let prepare_rename = provider
14446 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14447 .unwrap_or_else(|| Task::ready(Ok(None)));
14448 drop(snapshot);
14449
14450 Some(cx.spawn_in(window, async move |this, cx| {
14451 let rename_range = if let Some(range) = prepare_rename.await? {
14452 Some(range)
14453 } else {
14454 this.update(cx, |this, cx| {
14455 let buffer = this.buffer.read(cx).snapshot(cx);
14456 let mut buffer_highlights = this
14457 .document_highlights_for_position(selection.head(), &buffer)
14458 .filter(|highlight| {
14459 highlight.start.excerpt_id == selection.head().excerpt_id
14460 && highlight.end.excerpt_id == selection.head().excerpt_id
14461 });
14462 buffer_highlights
14463 .next()
14464 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14465 })?
14466 };
14467 if let Some(rename_range) = rename_range {
14468 this.update_in(cx, |this, window, cx| {
14469 let snapshot = cursor_buffer.read(cx).snapshot();
14470 let rename_buffer_range = rename_range.to_offset(&snapshot);
14471 let cursor_offset_in_rename_range =
14472 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14473 let cursor_offset_in_rename_range_end =
14474 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14475
14476 this.take_rename(false, window, cx);
14477 let buffer = this.buffer.read(cx).read(cx);
14478 let cursor_offset = selection.head().to_offset(&buffer);
14479 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14480 let rename_end = rename_start + rename_buffer_range.len();
14481 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14482 let mut old_highlight_id = None;
14483 let old_name: Arc<str> = buffer
14484 .chunks(rename_start..rename_end, true)
14485 .map(|chunk| {
14486 if old_highlight_id.is_none() {
14487 old_highlight_id = chunk.syntax_highlight_id;
14488 }
14489 chunk.text
14490 })
14491 .collect::<String>()
14492 .into();
14493
14494 drop(buffer);
14495
14496 // Position the selection in the rename editor so that it matches the current selection.
14497 this.show_local_selections = false;
14498 let rename_editor = cx.new(|cx| {
14499 let mut editor = Editor::single_line(window, cx);
14500 editor.buffer.update(cx, |buffer, cx| {
14501 buffer.edit([(0..0, old_name.clone())], None, cx)
14502 });
14503 let rename_selection_range = match cursor_offset_in_rename_range
14504 .cmp(&cursor_offset_in_rename_range_end)
14505 {
14506 Ordering::Equal => {
14507 editor.select_all(&SelectAll, window, cx);
14508 return editor;
14509 }
14510 Ordering::Less => {
14511 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14512 }
14513 Ordering::Greater => {
14514 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14515 }
14516 };
14517 if rename_selection_range.end > old_name.len() {
14518 editor.select_all(&SelectAll, window, cx);
14519 } else {
14520 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14521 s.select_ranges([rename_selection_range]);
14522 });
14523 }
14524 editor
14525 });
14526 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14527 if e == &EditorEvent::Focused {
14528 cx.emit(EditorEvent::FocusedIn)
14529 }
14530 })
14531 .detach();
14532
14533 let write_highlights =
14534 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14535 let read_highlights =
14536 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14537 let ranges = write_highlights
14538 .iter()
14539 .flat_map(|(_, ranges)| ranges.iter())
14540 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14541 .cloned()
14542 .collect();
14543
14544 this.highlight_text::<Rename>(
14545 ranges,
14546 HighlightStyle {
14547 fade_out: Some(0.6),
14548 ..Default::default()
14549 },
14550 cx,
14551 );
14552 let rename_focus_handle = rename_editor.focus_handle(cx);
14553 window.focus(&rename_focus_handle);
14554 let block_id = this.insert_blocks(
14555 [BlockProperties {
14556 style: BlockStyle::Flex,
14557 placement: BlockPlacement::Below(range.start),
14558 height: Some(1),
14559 render: Arc::new({
14560 let rename_editor = rename_editor.clone();
14561 move |cx: &mut BlockContext| {
14562 let mut text_style = cx.editor_style.text.clone();
14563 if let Some(highlight_style) = old_highlight_id
14564 .and_then(|h| h.style(&cx.editor_style.syntax))
14565 {
14566 text_style = text_style.highlight(highlight_style);
14567 }
14568 div()
14569 .block_mouse_down()
14570 .pl(cx.anchor_x)
14571 .child(EditorElement::new(
14572 &rename_editor,
14573 EditorStyle {
14574 background: cx.theme().system().transparent,
14575 local_player: cx.editor_style.local_player,
14576 text: text_style,
14577 scrollbar_width: cx.editor_style.scrollbar_width,
14578 syntax: cx.editor_style.syntax.clone(),
14579 status: cx.editor_style.status.clone(),
14580 inlay_hints_style: HighlightStyle {
14581 font_weight: Some(FontWeight::BOLD),
14582 ..make_inlay_hints_style(cx.app)
14583 },
14584 inline_completion_styles: make_suggestion_styles(
14585 cx.app,
14586 ),
14587 ..EditorStyle::default()
14588 },
14589 ))
14590 .into_any_element()
14591 }
14592 }),
14593 priority: 0,
14594 }],
14595 Some(Autoscroll::fit()),
14596 cx,
14597 )[0];
14598 this.pending_rename = Some(RenameState {
14599 range,
14600 old_name,
14601 editor: rename_editor,
14602 block_id,
14603 });
14604 })?;
14605 }
14606
14607 Ok(())
14608 }))
14609 }
14610
14611 pub fn confirm_rename(
14612 &mut self,
14613 _: &ConfirmRename,
14614 window: &mut Window,
14615 cx: &mut Context<Self>,
14616 ) -> Option<Task<Result<()>>> {
14617 let rename = self.take_rename(false, window, cx)?;
14618 let workspace = self.workspace()?.downgrade();
14619 let (buffer, start) = self
14620 .buffer
14621 .read(cx)
14622 .text_anchor_for_position(rename.range.start, cx)?;
14623 let (end_buffer, _) = self
14624 .buffer
14625 .read(cx)
14626 .text_anchor_for_position(rename.range.end, cx)?;
14627 if buffer != end_buffer {
14628 return None;
14629 }
14630
14631 let old_name = rename.old_name;
14632 let new_name = rename.editor.read(cx).text(cx);
14633
14634 let rename = self.semantics_provider.as_ref()?.perform_rename(
14635 &buffer,
14636 start,
14637 new_name.clone(),
14638 cx,
14639 )?;
14640
14641 Some(cx.spawn_in(window, async move |editor, cx| {
14642 let project_transaction = rename.await?;
14643 Self::open_project_transaction(
14644 &editor,
14645 workspace,
14646 project_transaction,
14647 format!("Rename: {} → {}", old_name, new_name),
14648 cx,
14649 )
14650 .await?;
14651
14652 editor.update(cx, |editor, cx| {
14653 editor.refresh_document_highlights(cx);
14654 })?;
14655 Ok(())
14656 }))
14657 }
14658
14659 fn take_rename(
14660 &mut self,
14661 moving_cursor: bool,
14662 window: &mut Window,
14663 cx: &mut Context<Self>,
14664 ) -> Option<RenameState> {
14665 let rename = self.pending_rename.take()?;
14666 if rename.editor.focus_handle(cx).is_focused(window) {
14667 window.focus(&self.focus_handle);
14668 }
14669
14670 self.remove_blocks(
14671 [rename.block_id].into_iter().collect(),
14672 Some(Autoscroll::fit()),
14673 cx,
14674 );
14675 self.clear_highlights::<Rename>(cx);
14676 self.show_local_selections = true;
14677
14678 if moving_cursor {
14679 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14680 editor.selections.newest::<usize>(cx).head()
14681 });
14682
14683 // Update the selection to match the position of the selection inside
14684 // the rename editor.
14685 let snapshot = self.buffer.read(cx).read(cx);
14686 let rename_range = rename.range.to_offset(&snapshot);
14687 let cursor_in_editor = snapshot
14688 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14689 .min(rename_range.end);
14690 drop(snapshot);
14691
14692 self.change_selections(None, window, cx, |s| {
14693 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14694 });
14695 } else {
14696 self.refresh_document_highlights(cx);
14697 }
14698
14699 Some(rename)
14700 }
14701
14702 pub fn pending_rename(&self) -> Option<&RenameState> {
14703 self.pending_rename.as_ref()
14704 }
14705
14706 fn format(
14707 &mut self,
14708 _: &Format,
14709 window: &mut Window,
14710 cx: &mut Context<Self>,
14711 ) -> Option<Task<Result<()>>> {
14712 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14713
14714 let project = match &self.project {
14715 Some(project) => project.clone(),
14716 None => return None,
14717 };
14718
14719 Some(self.perform_format(
14720 project,
14721 FormatTrigger::Manual,
14722 FormatTarget::Buffers,
14723 window,
14724 cx,
14725 ))
14726 }
14727
14728 fn format_selections(
14729 &mut self,
14730 _: &FormatSelections,
14731 window: &mut Window,
14732 cx: &mut Context<Self>,
14733 ) -> Option<Task<Result<()>>> {
14734 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14735
14736 let project = match &self.project {
14737 Some(project) => project.clone(),
14738 None => return None,
14739 };
14740
14741 let ranges = self
14742 .selections
14743 .all_adjusted(cx)
14744 .into_iter()
14745 .map(|selection| selection.range())
14746 .collect_vec();
14747
14748 Some(self.perform_format(
14749 project,
14750 FormatTrigger::Manual,
14751 FormatTarget::Ranges(ranges),
14752 window,
14753 cx,
14754 ))
14755 }
14756
14757 fn perform_format(
14758 &mut self,
14759 project: Entity<Project>,
14760 trigger: FormatTrigger,
14761 target: FormatTarget,
14762 window: &mut Window,
14763 cx: &mut Context<Self>,
14764 ) -> Task<Result<()>> {
14765 let buffer = self.buffer.clone();
14766 let (buffers, target) = match target {
14767 FormatTarget::Buffers => {
14768 let mut buffers = buffer.read(cx).all_buffers();
14769 if trigger == FormatTrigger::Save {
14770 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14771 }
14772 (buffers, LspFormatTarget::Buffers)
14773 }
14774 FormatTarget::Ranges(selection_ranges) => {
14775 let multi_buffer = buffer.read(cx);
14776 let snapshot = multi_buffer.read(cx);
14777 let mut buffers = HashSet::default();
14778 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14779 BTreeMap::new();
14780 for selection_range in selection_ranges {
14781 for (buffer, buffer_range, _) in
14782 snapshot.range_to_buffer_ranges(selection_range)
14783 {
14784 let buffer_id = buffer.remote_id();
14785 let start = buffer.anchor_before(buffer_range.start);
14786 let end = buffer.anchor_after(buffer_range.end);
14787 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14788 buffer_id_to_ranges
14789 .entry(buffer_id)
14790 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14791 .or_insert_with(|| vec![start..end]);
14792 }
14793 }
14794 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14795 }
14796 };
14797
14798 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14799 let selections_prev = transaction_id_prev
14800 .and_then(|transaction_id_prev| {
14801 // default to selections as they were after the last edit, if we have them,
14802 // instead of how they are now.
14803 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14804 // will take you back to where you made the last edit, instead of staying where you scrolled
14805 self.selection_history
14806 .transaction(transaction_id_prev)
14807 .map(|t| t.0.clone())
14808 })
14809 .unwrap_or_else(|| {
14810 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14811 self.selections.disjoint_anchors()
14812 });
14813
14814 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14815 let format = project.update(cx, |project, cx| {
14816 project.format(buffers, target, true, trigger, cx)
14817 });
14818
14819 cx.spawn_in(window, async move |editor, cx| {
14820 let transaction = futures::select_biased! {
14821 transaction = format.log_err().fuse() => transaction,
14822 () = timeout => {
14823 log::warn!("timed out waiting for formatting");
14824 None
14825 }
14826 };
14827
14828 buffer
14829 .update(cx, |buffer, cx| {
14830 if let Some(transaction) = transaction {
14831 if !buffer.is_singleton() {
14832 buffer.push_transaction(&transaction.0, cx);
14833 }
14834 }
14835 cx.notify();
14836 })
14837 .ok();
14838
14839 if let Some(transaction_id_now) =
14840 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14841 {
14842 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14843 if has_new_transaction {
14844 _ = editor.update(cx, |editor, _| {
14845 editor
14846 .selection_history
14847 .insert_transaction(transaction_id_now, selections_prev);
14848 });
14849 }
14850 }
14851
14852 Ok(())
14853 })
14854 }
14855
14856 fn organize_imports(
14857 &mut self,
14858 _: &OrganizeImports,
14859 window: &mut Window,
14860 cx: &mut Context<Self>,
14861 ) -> Option<Task<Result<()>>> {
14862 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14863 let project = match &self.project {
14864 Some(project) => project.clone(),
14865 None => return None,
14866 };
14867 Some(self.perform_code_action_kind(
14868 project,
14869 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14870 window,
14871 cx,
14872 ))
14873 }
14874
14875 fn perform_code_action_kind(
14876 &mut self,
14877 project: Entity<Project>,
14878 kind: CodeActionKind,
14879 window: &mut Window,
14880 cx: &mut Context<Self>,
14881 ) -> Task<Result<()>> {
14882 let buffer = self.buffer.clone();
14883 let buffers = buffer.read(cx).all_buffers();
14884 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14885 let apply_action = project.update(cx, |project, cx| {
14886 project.apply_code_action_kind(buffers, kind, true, cx)
14887 });
14888 cx.spawn_in(window, async move |_, cx| {
14889 let transaction = futures::select_biased! {
14890 () = timeout => {
14891 log::warn!("timed out waiting for executing code action");
14892 None
14893 }
14894 transaction = apply_action.log_err().fuse() => transaction,
14895 };
14896 buffer
14897 .update(cx, |buffer, cx| {
14898 // check if we need this
14899 if let Some(transaction) = transaction {
14900 if !buffer.is_singleton() {
14901 buffer.push_transaction(&transaction.0, cx);
14902 }
14903 }
14904 cx.notify();
14905 })
14906 .ok();
14907 Ok(())
14908 })
14909 }
14910
14911 fn restart_language_server(
14912 &mut self,
14913 _: &RestartLanguageServer,
14914 _: &mut Window,
14915 cx: &mut Context<Self>,
14916 ) {
14917 if let Some(project) = self.project.clone() {
14918 self.buffer.update(cx, |multi_buffer, cx| {
14919 project.update(cx, |project, cx| {
14920 project.restart_language_servers_for_buffers(
14921 multi_buffer.all_buffers().into_iter().collect(),
14922 cx,
14923 );
14924 });
14925 })
14926 }
14927 }
14928
14929 fn stop_language_server(
14930 &mut self,
14931 _: &StopLanguageServer,
14932 _: &mut Window,
14933 cx: &mut Context<Self>,
14934 ) {
14935 if let Some(project) = self.project.clone() {
14936 self.buffer.update(cx, |multi_buffer, cx| {
14937 project.update(cx, |project, cx| {
14938 project.stop_language_servers_for_buffers(
14939 multi_buffer.all_buffers().into_iter().collect(),
14940 cx,
14941 );
14942 cx.emit(project::Event::RefreshInlayHints);
14943 });
14944 });
14945 }
14946 }
14947
14948 fn cancel_language_server_work(
14949 workspace: &mut Workspace,
14950 _: &actions::CancelLanguageServerWork,
14951 _: &mut Window,
14952 cx: &mut Context<Workspace>,
14953 ) {
14954 let project = workspace.project();
14955 let buffers = workspace
14956 .active_item(cx)
14957 .and_then(|item| item.act_as::<Editor>(cx))
14958 .map_or(HashSet::default(), |editor| {
14959 editor.read(cx).buffer.read(cx).all_buffers()
14960 });
14961 project.update(cx, |project, cx| {
14962 project.cancel_language_server_work_for_buffers(buffers, cx);
14963 });
14964 }
14965
14966 fn show_character_palette(
14967 &mut self,
14968 _: &ShowCharacterPalette,
14969 window: &mut Window,
14970 _: &mut Context<Self>,
14971 ) {
14972 window.show_character_palette();
14973 }
14974
14975 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14976 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14977 let buffer = self.buffer.read(cx).snapshot(cx);
14978 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14979 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14980 let is_valid = buffer
14981 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14982 .any(|entry| {
14983 entry.diagnostic.is_primary
14984 && !entry.range.is_empty()
14985 && entry.range.start == primary_range_start
14986 && entry.diagnostic.message == active_diagnostics.active_message
14987 });
14988
14989 if !is_valid {
14990 self.dismiss_diagnostics(cx);
14991 }
14992 }
14993 }
14994
14995 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14996 match &self.active_diagnostics {
14997 ActiveDiagnostic::Group(group) => Some(group),
14998 _ => None,
14999 }
15000 }
15001
15002 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15003 self.dismiss_diagnostics(cx);
15004 self.active_diagnostics = ActiveDiagnostic::All;
15005 }
15006
15007 fn activate_diagnostics(
15008 &mut self,
15009 buffer_id: BufferId,
15010 diagnostic: DiagnosticEntry<usize>,
15011 window: &mut Window,
15012 cx: &mut Context<Self>,
15013 ) {
15014 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15015 return;
15016 }
15017 self.dismiss_diagnostics(cx);
15018 let snapshot = self.snapshot(window, cx);
15019 let buffer = self.buffer.read(cx).snapshot(cx);
15020 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15021 return;
15022 };
15023
15024 let diagnostic_group = buffer
15025 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15026 .collect::<Vec<_>>();
15027
15028 let blocks =
15029 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15030
15031 let blocks = self.display_map.update(cx, |display_map, cx| {
15032 display_map.insert_blocks(blocks, cx).into_iter().collect()
15033 });
15034 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15035 active_range: buffer.anchor_before(diagnostic.range.start)
15036 ..buffer.anchor_after(diagnostic.range.end),
15037 active_message: diagnostic.diagnostic.message.clone(),
15038 group_id: diagnostic.diagnostic.group_id,
15039 blocks,
15040 });
15041 cx.notify();
15042 }
15043
15044 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15045 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15046 return;
15047 };
15048
15049 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15050 if let ActiveDiagnostic::Group(group) = prev {
15051 self.display_map.update(cx, |display_map, cx| {
15052 display_map.remove_blocks(group.blocks, cx);
15053 });
15054 cx.notify();
15055 }
15056 }
15057
15058 /// Disable inline diagnostics rendering for this editor.
15059 pub fn disable_inline_diagnostics(&mut self) {
15060 self.inline_diagnostics_enabled = false;
15061 self.inline_diagnostics_update = Task::ready(());
15062 self.inline_diagnostics.clear();
15063 }
15064
15065 pub fn inline_diagnostics_enabled(&self) -> bool {
15066 self.inline_diagnostics_enabled
15067 }
15068
15069 pub fn show_inline_diagnostics(&self) -> bool {
15070 self.show_inline_diagnostics
15071 }
15072
15073 pub fn toggle_inline_diagnostics(
15074 &mut self,
15075 _: &ToggleInlineDiagnostics,
15076 window: &mut Window,
15077 cx: &mut Context<Editor>,
15078 ) {
15079 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15080 self.refresh_inline_diagnostics(false, window, cx);
15081 }
15082
15083 fn refresh_inline_diagnostics(
15084 &mut self,
15085 debounce: bool,
15086 window: &mut Window,
15087 cx: &mut Context<Self>,
15088 ) {
15089 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15090 self.inline_diagnostics_update = Task::ready(());
15091 self.inline_diagnostics.clear();
15092 return;
15093 }
15094
15095 let debounce_ms = ProjectSettings::get_global(cx)
15096 .diagnostics
15097 .inline
15098 .update_debounce_ms;
15099 let debounce = if debounce && debounce_ms > 0 {
15100 Some(Duration::from_millis(debounce_ms))
15101 } else {
15102 None
15103 };
15104 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15105 let editor = editor.upgrade().unwrap();
15106
15107 if let Some(debounce) = debounce {
15108 cx.background_executor().timer(debounce).await;
15109 }
15110 let Some(snapshot) = editor
15111 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15112 .ok()
15113 else {
15114 return;
15115 };
15116
15117 let new_inline_diagnostics = cx
15118 .background_spawn(async move {
15119 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15120 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15121 let message = diagnostic_entry
15122 .diagnostic
15123 .message
15124 .split_once('\n')
15125 .map(|(line, _)| line)
15126 .map(SharedString::new)
15127 .unwrap_or_else(|| {
15128 SharedString::from(diagnostic_entry.diagnostic.message)
15129 });
15130 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15131 let (Ok(i) | Err(i)) = inline_diagnostics
15132 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15133 inline_diagnostics.insert(
15134 i,
15135 (
15136 start_anchor,
15137 InlineDiagnostic {
15138 message,
15139 group_id: diagnostic_entry.diagnostic.group_id,
15140 start: diagnostic_entry.range.start.to_point(&snapshot),
15141 is_primary: diagnostic_entry.diagnostic.is_primary,
15142 severity: diagnostic_entry.diagnostic.severity,
15143 },
15144 ),
15145 );
15146 }
15147 inline_diagnostics
15148 })
15149 .await;
15150
15151 editor
15152 .update(cx, |editor, cx| {
15153 editor.inline_diagnostics = new_inline_diagnostics;
15154 cx.notify();
15155 })
15156 .ok();
15157 });
15158 }
15159
15160 pub fn set_selections_from_remote(
15161 &mut self,
15162 selections: Vec<Selection<Anchor>>,
15163 pending_selection: Option<Selection<Anchor>>,
15164 window: &mut Window,
15165 cx: &mut Context<Self>,
15166 ) {
15167 let old_cursor_position = self.selections.newest_anchor().head();
15168 self.selections.change_with(cx, |s| {
15169 s.select_anchors(selections);
15170 if let Some(pending_selection) = pending_selection {
15171 s.set_pending(pending_selection, SelectMode::Character);
15172 } else {
15173 s.clear_pending();
15174 }
15175 });
15176 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15177 }
15178
15179 fn push_to_selection_history(&mut self) {
15180 self.selection_history.push(SelectionHistoryEntry {
15181 selections: self.selections.disjoint_anchors(),
15182 select_next_state: self.select_next_state.clone(),
15183 select_prev_state: self.select_prev_state.clone(),
15184 add_selections_state: self.add_selections_state.clone(),
15185 });
15186 }
15187
15188 pub fn transact(
15189 &mut self,
15190 window: &mut Window,
15191 cx: &mut Context<Self>,
15192 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15193 ) -> Option<TransactionId> {
15194 self.start_transaction_at(Instant::now(), window, cx);
15195 update(self, window, cx);
15196 self.end_transaction_at(Instant::now(), cx)
15197 }
15198
15199 pub fn start_transaction_at(
15200 &mut self,
15201 now: Instant,
15202 window: &mut Window,
15203 cx: &mut Context<Self>,
15204 ) {
15205 self.end_selection(window, cx);
15206 if let Some(tx_id) = self
15207 .buffer
15208 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15209 {
15210 self.selection_history
15211 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15212 cx.emit(EditorEvent::TransactionBegun {
15213 transaction_id: tx_id,
15214 })
15215 }
15216 }
15217
15218 pub fn end_transaction_at(
15219 &mut self,
15220 now: Instant,
15221 cx: &mut Context<Self>,
15222 ) -> Option<TransactionId> {
15223 if let Some(transaction_id) = self
15224 .buffer
15225 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15226 {
15227 if let Some((_, end_selections)) =
15228 self.selection_history.transaction_mut(transaction_id)
15229 {
15230 *end_selections = Some(self.selections.disjoint_anchors());
15231 } else {
15232 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15233 }
15234
15235 cx.emit(EditorEvent::Edited { transaction_id });
15236 Some(transaction_id)
15237 } else {
15238 None
15239 }
15240 }
15241
15242 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15243 if self.selection_mark_mode {
15244 self.change_selections(None, window, cx, |s| {
15245 s.move_with(|_, sel| {
15246 sel.collapse_to(sel.head(), SelectionGoal::None);
15247 });
15248 })
15249 }
15250 self.selection_mark_mode = true;
15251 cx.notify();
15252 }
15253
15254 pub fn swap_selection_ends(
15255 &mut self,
15256 _: &actions::SwapSelectionEnds,
15257 window: &mut Window,
15258 cx: &mut Context<Self>,
15259 ) {
15260 self.change_selections(None, window, cx, |s| {
15261 s.move_with(|_, sel| {
15262 if sel.start != sel.end {
15263 sel.reversed = !sel.reversed
15264 }
15265 });
15266 });
15267 self.request_autoscroll(Autoscroll::newest(), cx);
15268 cx.notify();
15269 }
15270
15271 pub fn toggle_fold(
15272 &mut self,
15273 _: &actions::ToggleFold,
15274 window: &mut Window,
15275 cx: &mut Context<Self>,
15276 ) {
15277 if self.is_singleton(cx) {
15278 let selection = self.selections.newest::<Point>(cx);
15279
15280 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15281 let range = if selection.is_empty() {
15282 let point = selection.head().to_display_point(&display_map);
15283 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15284 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15285 .to_point(&display_map);
15286 start..end
15287 } else {
15288 selection.range()
15289 };
15290 if display_map.folds_in_range(range).next().is_some() {
15291 self.unfold_lines(&Default::default(), window, cx)
15292 } else {
15293 self.fold(&Default::default(), window, cx)
15294 }
15295 } else {
15296 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15297 let buffer_ids: HashSet<_> = self
15298 .selections
15299 .disjoint_anchor_ranges()
15300 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15301 .collect();
15302
15303 let should_unfold = buffer_ids
15304 .iter()
15305 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15306
15307 for buffer_id in buffer_ids {
15308 if should_unfold {
15309 self.unfold_buffer(buffer_id, cx);
15310 } else {
15311 self.fold_buffer(buffer_id, cx);
15312 }
15313 }
15314 }
15315 }
15316
15317 pub fn toggle_fold_recursive(
15318 &mut self,
15319 _: &actions::ToggleFoldRecursive,
15320 window: &mut Window,
15321 cx: &mut Context<Self>,
15322 ) {
15323 let selection = self.selections.newest::<Point>(cx);
15324
15325 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15326 let range = if selection.is_empty() {
15327 let point = selection.head().to_display_point(&display_map);
15328 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15329 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15330 .to_point(&display_map);
15331 start..end
15332 } else {
15333 selection.range()
15334 };
15335 if display_map.folds_in_range(range).next().is_some() {
15336 self.unfold_recursive(&Default::default(), window, cx)
15337 } else {
15338 self.fold_recursive(&Default::default(), window, cx)
15339 }
15340 }
15341
15342 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15343 if self.is_singleton(cx) {
15344 let mut to_fold = Vec::new();
15345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15346 let selections = self.selections.all_adjusted(cx);
15347
15348 for selection in selections {
15349 let range = selection.range().sorted();
15350 let buffer_start_row = range.start.row;
15351
15352 if range.start.row != range.end.row {
15353 let mut found = false;
15354 let mut row = range.start.row;
15355 while row <= range.end.row {
15356 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15357 {
15358 found = true;
15359 row = crease.range().end.row + 1;
15360 to_fold.push(crease);
15361 } else {
15362 row += 1
15363 }
15364 }
15365 if found {
15366 continue;
15367 }
15368 }
15369
15370 for row in (0..=range.start.row).rev() {
15371 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15372 if crease.range().end.row >= buffer_start_row {
15373 to_fold.push(crease);
15374 if row <= range.start.row {
15375 break;
15376 }
15377 }
15378 }
15379 }
15380 }
15381
15382 self.fold_creases(to_fold, true, window, cx);
15383 } else {
15384 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15385 let buffer_ids = self
15386 .selections
15387 .disjoint_anchor_ranges()
15388 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15389 .collect::<HashSet<_>>();
15390 for buffer_id in buffer_ids {
15391 self.fold_buffer(buffer_id, cx);
15392 }
15393 }
15394 }
15395
15396 fn fold_at_level(
15397 &mut self,
15398 fold_at: &FoldAtLevel,
15399 window: &mut Window,
15400 cx: &mut Context<Self>,
15401 ) {
15402 if !self.buffer.read(cx).is_singleton() {
15403 return;
15404 }
15405
15406 let fold_at_level = fold_at.0;
15407 let snapshot = self.buffer.read(cx).snapshot(cx);
15408 let mut to_fold = Vec::new();
15409 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15410
15411 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15412 while start_row < end_row {
15413 match self
15414 .snapshot(window, cx)
15415 .crease_for_buffer_row(MultiBufferRow(start_row))
15416 {
15417 Some(crease) => {
15418 let nested_start_row = crease.range().start.row + 1;
15419 let nested_end_row = crease.range().end.row;
15420
15421 if current_level < fold_at_level {
15422 stack.push((nested_start_row, nested_end_row, current_level + 1));
15423 } else if current_level == fold_at_level {
15424 to_fold.push(crease);
15425 }
15426
15427 start_row = nested_end_row + 1;
15428 }
15429 None => start_row += 1,
15430 }
15431 }
15432 }
15433
15434 self.fold_creases(to_fold, true, window, cx);
15435 }
15436
15437 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15438 if self.buffer.read(cx).is_singleton() {
15439 let mut fold_ranges = Vec::new();
15440 let snapshot = self.buffer.read(cx).snapshot(cx);
15441
15442 for row in 0..snapshot.max_row().0 {
15443 if let Some(foldable_range) = self
15444 .snapshot(window, cx)
15445 .crease_for_buffer_row(MultiBufferRow(row))
15446 {
15447 fold_ranges.push(foldable_range);
15448 }
15449 }
15450
15451 self.fold_creases(fold_ranges, true, window, cx);
15452 } else {
15453 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15454 editor
15455 .update_in(cx, |editor, _, cx| {
15456 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15457 editor.fold_buffer(buffer_id, cx);
15458 }
15459 })
15460 .ok();
15461 });
15462 }
15463 }
15464
15465 pub fn fold_function_bodies(
15466 &mut self,
15467 _: &actions::FoldFunctionBodies,
15468 window: &mut Window,
15469 cx: &mut Context<Self>,
15470 ) {
15471 let snapshot = self.buffer.read(cx).snapshot(cx);
15472
15473 let ranges = snapshot
15474 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15475 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15476 .collect::<Vec<_>>();
15477
15478 let creases = ranges
15479 .into_iter()
15480 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15481 .collect();
15482
15483 self.fold_creases(creases, true, window, cx);
15484 }
15485
15486 pub fn fold_recursive(
15487 &mut self,
15488 _: &actions::FoldRecursive,
15489 window: &mut Window,
15490 cx: &mut Context<Self>,
15491 ) {
15492 let mut to_fold = Vec::new();
15493 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15494 let selections = self.selections.all_adjusted(cx);
15495
15496 for selection in selections {
15497 let range = selection.range().sorted();
15498 let buffer_start_row = range.start.row;
15499
15500 if range.start.row != range.end.row {
15501 let mut found = false;
15502 for row in range.start.row..=range.end.row {
15503 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15504 found = true;
15505 to_fold.push(crease);
15506 }
15507 }
15508 if found {
15509 continue;
15510 }
15511 }
15512
15513 for row in (0..=range.start.row).rev() {
15514 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15515 if crease.range().end.row >= buffer_start_row {
15516 to_fold.push(crease);
15517 } else {
15518 break;
15519 }
15520 }
15521 }
15522 }
15523
15524 self.fold_creases(to_fold, true, window, cx);
15525 }
15526
15527 pub fn fold_at(
15528 &mut self,
15529 buffer_row: MultiBufferRow,
15530 window: &mut Window,
15531 cx: &mut Context<Self>,
15532 ) {
15533 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15534
15535 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15536 let autoscroll = self
15537 .selections
15538 .all::<Point>(cx)
15539 .iter()
15540 .any(|selection| crease.range().overlaps(&selection.range()));
15541
15542 self.fold_creases(vec![crease], autoscroll, window, cx);
15543 }
15544 }
15545
15546 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15547 if self.is_singleton(cx) {
15548 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15549 let buffer = &display_map.buffer_snapshot;
15550 let selections = self.selections.all::<Point>(cx);
15551 let ranges = selections
15552 .iter()
15553 .map(|s| {
15554 let range = s.display_range(&display_map).sorted();
15555 let mut start = range.start.to_point(&display_map);
15556 let mut end = range.end.to_point(&display_map);
15557 start.column = 0;
15558 end.column = buffer.line_len(MultiBufferRow(end.row));
15559 start..end
15560 })
15561 .collect::<Vec<_>>();
15562
15563 self.unfold_ranges(&ranges, true, true, cx);
15564 } else {
15565 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15566 let buffer_ids = self
15567 .selections
15568 .disjoint_anchor_ranges()
15569 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15570 .collect::<HashSet<_>>();
15571 for buffer_id in buffer_ids {
15572 self.unfold_buffer(buffer_id, cx);
15573 }
15574 }
15575 }
15576
15577 pub fn unfold_recursive(
15578 &mut self,
15579 _: &UnfoldRecursive,
15580 _window: &mut Window,
15581 cx: &mut Context<Self>,
15582 ) {
15583 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15584 let selections = self.selections.all::<Point>(cx);
15585 let ranges = selections
15586 .iter()
15587 .map(|s| {
15588 let mut range = s.display_range(&display_map).sorted();
15589 *range.start.column_mut() = 0;
15590 *range.end.column_mut() = display_map.line_len(range.end.row());
15591 let start = range.start.to_point(&display_map);
15592 let end = range.end.to_point(&display_map);
15593 start..end
15594 })
15595 .collect::<Vec<_>>();
15596
15597 self.unfold_ranges(&ranges, true, true, cx);
15598 }
15599
15600 pub fn unfold_at(
15601 &mut self,
15602 buffer_row: MultiBufferRow,
15603 _window: &mut Window,
15604 cx: &mut Context<Self>,
15605 ) {
15606 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15607
15608 let intersection_range = Point::new(buffer_row.0, 0)
15609 ..Point::new(
15610 buffer_row.0,
15611 display_map.buffer_snapshot.line_len(buffer_row),
15612 );
15613
15614 let autoscroll = self
15615 .selections
15616 .all::<Point>(cx)
15617 .iter()
15618 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15619
15620 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15621 }
15622
15623 pub fn unfold_all(
15624 &mut self,
15625 _: &actions::UnfoldAll,
15626 _window: &mut Window,
15627 cx: &mut Context<Self>,
15628 ) {
15629 if self.buffer.read(cx).is_singleton() {
15630 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15631 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15632 } else {
15633 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15634 editor
15635 .update(cx, |editor, cx| {
15636 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15637 editor.unfold_buffer(buffer_id, cx);
15638 }
15639 })
15640 .ok();
15641 });
15642 }
15643 }
15644
15645 pub fn fold_selected_ranges(
15646 &mut self,
15647 _: &FoldSelectedRanges,
15648 window: &mut Window,
15649 cx: &mut Context<Self>,
15650 ) {
15651 let selections = self.selections.all_adjusted(cx);
15652 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15653 let ranges = selections
15654 .into_iter()
15655 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15656 .collect::<Vec<_>>();
15657 self.fold_creases(ranges, true, window, cx);
15658 }
15659
15660 pub fn fold_ranges<T: ToOffset + Clone>(
15661 &mut self,
15662 ranges: Vec<Range<T>>,
15663 auto_scroll: bool,
15664 window: &mut Window,
15665 cx: &mut Context<Self>,
15666 ) {
15667 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15668 let ranges = ranges
15669 .into_iter()
15670 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15671 .collect::<Vec<_>>();
15672 self.fold_creases(ranges, auto_scroll, window, cx);
15673 }
15674
15675 pub fn fold_creases<T: ToOffset + Clone>(
15676 &mut self,
15677 creases: Vec<Crease<T>>,
15678 auto_scroll: bool,
15679 _window: &mut Window,
15680 cx: &mut Context<Self>,
15681 ) {
15682 if creases.is_empty() {
15683 return;
15684 }
15685
15686 let mut buffers_affected = HashSet::default();
15687 let multi_buffer = self.buffer().read(cx);
15688 for crease in &creases {
15689 if let Some((_, buffer, _)) =
15690 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15691 {
15692 buffers_affected.insert(buffer.read(cx).remote_id());
15693 };
15694 }
15695
15696 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15697
15698 if auto_scroll {
15699 self.request_autoscroll(Autoscroll::fit(), cx);
15700 }
15701
15702 cx.notify();
15703
15704 self.scrollbar_marker_state.dirty = true;
15705 self.folds_did_change(cx);
15706 }
15707
15708 /// Removes any folds whose ranges intersect any of the given ranges.
15709 pub fn unfold_ranges<T: ToOffset + Clone>(
15710 &mut self,
15711 ranges: &[Range<T>],
15712 inclusive: bool,
15713 auto_scroll: bool,
15714 cx: &mut Context<Self>,
15715 ) {
15716 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15717 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15718 });
15719 self.folds_did_change(cx);
15720 }
15721
15722 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15723 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15724 return;
15725 }
15726 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15727 self.display_map.update(cx, |display_map, cx| {
15728 display_map.fold_buffers([buffer_id], cx)
15729 });
15730 cx.emit(EditorEvent::BufferFoldToggled {
15731 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15732 folded: true,
15733 });
15734 cx.notify();
15735 }
15736
15737 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15738 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15739 return;
15740 }
15741 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15742 self.display_map.update(cx, |display_map, cx| {
15743 display_map.unfold_buffers([buffer_id], cx);
15744 });
15745 cx.emit(EditorEvent::BufferFoldToggled {
15746 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15747 folded: false,
15748 });
15749 cx.notify();
15750 }
15751
15752 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15753 self.display_map.read(cx).is_buffer_folded(buffer)
15754 }
15755
15756 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15757 self.display_map.read(cx).folded_buffers()
15758 }
15759
15760 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15761 self.display_map.update(cx, |display_map, cx| {
15762 display_map.disable_header_for_buffer(buffer_id, cx);
15763 });
15764 cx.notify();
15765 }
15766
15767 /// Removes any folds with the given ranges.
15768 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15769 &mut self,
15770 ranges: &[Range<T>],
15771 type_id: TypeId,
15772 auto_scroll: bool,
15773 cx: &mut Context<Self>,
15774 ) {
15775 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15776 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15777 });
15778 self.folds_did_change(cx);
15779 }
15780
15781 fn remove_folds_with<T: ToOffset + Clone>(
15782 &mut self,
15783 ranges: &[Range<T>],
15784 auto_scroll: bool,
15785 cx: &mut Context<Self>,
15786 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15787 ) {
15788 if ranges.is_empty() {
15789 return;
15790 }
15791
15792 let mut buffers_affected = HashSet::default();
15793 let multi_buffer = self.buffer().read(cx);
15794 for range in ranges {
15795 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15796 buffers_affected.insert(buffer.read(cx).remote_id());
15797 };
15798 }
15799
15800 self.display_map.update(cx, update);
15801
15802 if auto_scroll {
15803 self.request_autoscroll(Autoscroll::fit(), cx);
15804 }
15805
15806 cx.notify();
15807 self.scrollbar_marker_state.dirty = true;
15808 self.active_indent_guides_state.dirty = true;
15809 }
15810
15811 pub fn update_fold_widths(
15812 &mut self,
15813 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15814 cx: &mut Context<Self>,
15815 ) -> bool {
15816 self.display_map
15817 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15818 }
15819
15820 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15821 self.display_map.read(cx).fold_placeholder.clone()
15822 }
15823
15824 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15825 self.buffer.update(cx, |buffer, cx| {
15826 buffer.set_all_diff_hunks_expanded(cx);
15827 });
15828 }
15829
15830 pub fn expand_all_diff_hunks(
15831 &mut self,
15832 _: &ExpandAllDiffHunks,
15833 _window: &mut Window,
15834 cx: &mut Context<Self>,
15835 ) {
15836 self.buffer.update(cx, |buffer, cx| {
15837 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15838 });
15839 }
15840
15841 pub fn toggle_selected_diff_hunks(
15842 &mut self,
15843 _: &ToggleSelectedDiffHunks,
15844 _window: &mut Window,
15845 cx: &mut Context<Self>,
15846 ) {
15847 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15848 self.toggle_diff_hunks_in_ranges(ranges, cx);
15849 }
15850
15851 pub fn diff_hunks_in_ranges<'a>(
15852 &'a self,
15853 ranges: &'a [Range<Anchor>],
15854 buffer: &'a MultiBufferSnapshot,
15855 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15856 ranges.iter().flat_map(move |range| {
15857 let end_excerpt_id = range.end.excerpt_id;
15858 let range = range.to_point(buffer);
15859 let mut peek_end = range.end;
15860 if range.end.row < buffer.max_row().0 {
15861 peek_end = Point::new(range.end.row + 1, 0);
15862 }
15863 buffer
15864 .diff_hunks_in_range(range.start..peek_end)
15865 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15866 })
15867 }
15868
15869 pub fn has_stageable_diff_hunks_in_ranges(
15870 &self,
15871 ranges: &[Range<Anchor>],
15872 snapshot: &MultiBufferSnapshot,
15873 ) -> bool {
15874 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15875 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15876 }
15877
15878 pub fn toggle_staged_selected_diff_hunks(
15879 &mut self,
15880 _: &::git::ToggleStaged,
15881 _: &mut Window,
15882 cx: &mut Context<Self>,
15883 ) {
15884 let snapshot = self.buffer.read(cx).snapshot(cx);
15885 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15886 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15887 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15888 }
15889
15890 pub fn set_render_diff_hunk_controls(
15891 &mut self,
15892 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15893 cx: &mut Context<Self>,
15894 ) {
15895 self.render_diff_hunk_controls = render_diff_hunk_controls;
15896 cx.notify();
15897 }
15898
15899 pub fn stage_and_next(
15900 &mut self,
15901 _: &::git::StageAndNext,
15902 window: &mut Window,
15903 cx: &mut Context<Self>,
15904 ) {
15905 self.do_stage_or_unstage_and_next(true, window, cx);
15906 }
15907
15908 pub fn unstage_and_next(
15909 &mut self,
15910 _: &::git::UnstageAndNext,
15911 window: &mut Window,
15912 cx: &mut Context<Self>,
15913 ) {
15914 self.do_stage_or_unstage_and_next(false, window, cx);
15915 }
15916
15917 pub fn stage_or_unstage_diff_hunks(
15918 &mut self,
15919 stage: bool,
15920 ranges: Vec<Range<Anchor>>,
15921 cx: &mut Context<Self>,
15922 ) {
15923 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15924 cx.spawn(async move |this, cx| {
15925 task.await?;
15926 this.update(cx, |this, cx| {
15927 let snapshot = this.buffer.read(cx).snapshot(cx);
15928 let chunk_by = this
15929 .diff_hunks_in_ranges(&ranges, &snapshot)
15930 .chunk_by(|hunk| hunk.buffer_id);
15931 for (buffer_id, hunks) in &chunk_by {
15932 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15933 }
15934 })
15935 })
15936 .detach_and_log_err(cx);
15937 }
15938
15939 fn save_buffers_for_ranges_if_needed(
15940 &mut self,
15941 ranges: &[Range<Anchor>],
15942 cx: &mut Context<Editor>,
15943 ) -> Task<Result<()>> {
15944 let multibuffer = self.buffer.read(cx);
15945 let snapshot = multibuffer.read(cx);
15946 let buffer_ids: HashSet<_> = ranges
15947 .iter()
15948 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15949 .collect();
15950 drop(snapshot);
15951
15952 let mut buffers = HashSet::default();
15953 for buffer_id in buffer_ids {
15954 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15955 let buffer = buffer_entity.read(cx);
15956 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15957 {
15958 buffers.insert(buffer_entity);
15959 }
15960 }
15961 }
15962
15963 if let Some(project) = &self.project {
15964 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15965 } else {
15966 Task::ready(Ok(()))
15967 }
15968 }
15969
15970 fn do_stage_or_unstage_and_next(
15971 &mut self,
15972 stage: bool,
15973 window: &mut Window,
15974 cx: &mut Context<Self>,
15975 ) {
15976 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15977
15978 if ranges.iter().any(|range| range.start != range.end) {
15979 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15980 return;
15981 }
15982
15983 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15984 let snapshot = self.snapshot(window, cx);
15985 let position = self.selections.newest::<Point>(cx).head();
15986 let mut row = snapshot
15987 .buffer_snapshot
15988 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15989 .find(|hunk| hunk.row_range.start.0 > position.row)
15990 .map(|hunk| hunk.row_range.start);
15991
15992 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15993 // Outside of the project diff editor, wrap around to the beginning.
15994 if !all_diff_hunks_expanded {
15995 row = row.or_else(|| {
15996 snapshot
15997 .buffer_snapshot
15998 .diff_hunks_in_range(Point::zero()..position)
15999 .find(|hunk| hunk.row_range.end.0 < position.row)
16000 .map(|hunk| hunk.row_range.start)
16001 });
16002 }
16003
16004 if let Some(row) = row {
16005 let destination = Point::new(row.0, 0);
16006 let autoscroll = Autoscroll::center();
16007
16008 self.unfold_ranges(&[destination..destination], false, false, cx);
16009 self.change_selections(Some(autoscroll), window, cx, |s| {
16010 s.select_ranges([destination..destination]);
16011 });
16012 }
16013 }
16014
16015 fn do_stage_or_unstage(
16016 &self,
16017 stage: bool,
16018 buffer_id: BufferId,
16019 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16020 cx: &mut App,
16021 ) -> Option<()> {
16022 let project = self.project.as_ref()?;
16023 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16024 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16025 let buffer_snapshot = buffer.read(cx).snapshot();
16026 let file_exists = buffer_snapshot
16027 .file()
16028 .is_some_and(|file| file.disk_state().exists());
16029 diff.update(cx, |diff, cx| {
16030 diff.stage_or_unstage_hunks(
16031 stage,
16032 &hunks
16033 .map(|hunk| buffer_diff::DiffHunk {
16034 buffer_range: hunk.buffer_range,
16035 diff_base_byte_range: hunk.diff_base_byte_range,
16036 secondary_status: hunk.secondary_status,
16037 range: Point::zero()..Point::zero(), // unused
16038 })
16039 .collect::<Vec<_>>(),
16040 &buffer_snapshot,
16041 file_exists,
16042 cx,
16043 )
16044 });
16045 None
16046 }
16047
16048 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16049 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16050 self.buffer
16051 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16052 }
16053
16054 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16055 self.buffer.update(cx, |buffer, cx| {
16056 let ranges = vec![Anchor::min()..Anchor::max()];
16057 if !buffer.all_diff_hunks_expanded()
16058 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16059 {
16060 buffer.collapse_diff_hunks(ranges, cx);
16061 true
16062 } else {
16063 false
16064 }
16065 })
16066 }
16067
16068 fn toggle_diff_hunks_in_ranges(
16069 &mut self,
16070 ranges: Vec<Range<Anchor>>,
16071 cx: &mut Context<Editor>,
16072 ) {
16073 self.buffer.update(cx, |buffer, cx| {
16074 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16075 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16076 })
16077 }
16078
16079 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16080 self.buffer.update(cx, |buffer, cx| {
16081 let snapshot = buffer.snapshot(cx);
16082 let excerpt_id = range.end.excerpt_id;
16083 let point_range = range.to_point(&snapshot);
16084 let expand = !buffer.single_hunk_is_expanded(range, cx);
16085 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16086 })
16087 }
16088
16089 pub(crate) fn apply_all_diff_hunks(
16090 &mut self,
16091 _: &ApplyAllDiffHunks,
16092 window: &mut Window,
16093 cx: &mut Context<Self>,
16094 ) {
16095 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16096
16097 let buffers = self.buffer.read(cx).all_buffers();
16098 for branch_buffer in buffers {
16099 branch_buffer.update(cx, |branch_buffer, cx| {
16100 branch_buffer.merge_into_base(Vec::new(), cx);
16101 });
16102 }
16103
16104 if let Some(project) = self.project.clone() {
16105 self.save(true, project, window, cx).detach_and_log_err(cx);
16106 }
16107 }
16108
16109 pub(crate) fn apply_selected_diff_hunks(
16110 &mut self,
16111 _: &ApplyDiffHunk,
16112 window: &mut Window,
16113 cx: &mut Context<Self>,
16114 ) {
16115 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16116 let snapshot = self.snapshot(window, cx);
16117 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16118 let mut ranges_by_buffer = HashMap::default();
16119 self.transact(window, cx, |editor, _window, cx| {
16120 for hunk in hunks {
16121 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16122 ranges_by_buffer
16123 .entry(buffer.clone())
16124 .or_insert_with(Vec::new)
16125 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16126 }
16127 }
16128
16129 for (buffer, ranges) in ranges_by_buffer {
16130 buffer.update(cx, |buffer, cx| {
16131 buffer.merge_into_base(ranges, cx);
16132 });
16133 }
16134 });
16135
16136 if let Some(project) = self.project.clone() {
16137 self.save(true, project, window, cx).detach_and_log_err(cx);
16138 }
16139 }
16140
16141 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16142 if hovered != self.gutter_hovered {
16143 self.gutter_hovered = hovered;
16144 cx.notify();
16145 }
16146 }
16147
16148 pub fn insert_blocks(
16149 &mut self,
16150 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16151 autoscroll: Option<Autoscroll>,
16152 cx: &mut Context<Self>,
16153 ) -> Vec<CustomBlockId> {
16154 let blocks = self
16155 .display_map
16156 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16157 if let Some(autoscroll) = autoscroll {
16158 self.request_autoscroll(autoscroll, cx);
16159 }
16160 cx.notify();
16161 blocks
16162 }
16163
16164 pub fn resize_blocks(
16165 &mut self,
16166 heights: HashMap<CustomBlockId, u32>,
16167 autoscroll: Option<Autoscroll>,
16168 cx: &mut Context<Self>,
16169 ) {
16170 self.display_map
16171 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16172 if let Some(autoscroll) = autoscroll {
16173 self.request_autoscroll(autoscroll, cx);
16174 }
16175 cx.notify();
16176 }
16177
16178 pub fn replace_blocks(
16179 &mut self,
16180 renderers: HashMap<CustomBlockId, RenderBlock>,
16181 autoscroll: Option<Autoscroll>,
16182 cx: &mut Context<Self>,
16183 ) {
16184 self.display_map
16185 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16186 if let Some(autoscroll) = autoscroll {
16187 self.request_autoscroll(autoscroll, cx);
16188 }
16189 cx.notify();
16190 }
16191
16192 pub fn remove_blocks(
16193 &mut self,
16194 block_ids: HashSet<CustomBlockId>,
16195 autoscroll: Option<Autoscroll>,
16196 cx: &mut Context<Self>,
16197 ) {
16198 self.display_map.update(cx, |display_map, cx| {
16199 display_map.remove_blocks(block_ids, cx)
16200 });
16201 if let Some(autoscroll) = autoscroll {
16202 self.request_autoscroll(autoscroll, cx);
16203 }
16204 cx.notify();
16205 }
16206
16207 pub fn row_for_block(
16208 &self,
16209 block_id: CustomBlockId,
16210 cx: &mut Context<Self>,
16211 ) -> Option<DisplayRow> {
16212 self.display_map
16213 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16214 }
16215
16216 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16217 self.focused_block = Some(focused_block);
16218 }
16219
16220 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16221 self.focused_block.take()
16222 }
16223
16224 pub fn insert_creases(
16225 &mut self,
16226 creases: impl IntoIterator<Item = Crease<Anchor>>,
16227 cx: &mut Context<Self>,
16228 ) -> Vec<CreaseId> {
16229 self.display_map
16230 .update(cx, |map, cx| map.insert_creases(creases, cx))
16231 }
16232
16233 pub fn remove_creases(
16234 &mut self,
16235 ids: impl IntoIterator<Item = CreaseId>,
16236 cx: &mut Context<Self>,
16237 ) -> Vec<(CreaseId, Range<Anchor>)> {
16238 self.display_map
16239 .update(cx, |map, cx| map.remove_creases(ids, cx))
16240 }
16241
16242 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16243 self.display_map
16244 .update(cx, |map, cx| map.snapshot(cx))
16245 .longest_row()
16246 }
16247
16248 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16249 self.display_map
16250 .update(cx, |map, cx| map.snapshot(cx))
16251 .max_point()
16252 }
16253
16254 pub fn text(&self, cx: &App) -> String {
16255 self.buffer.read(cx).read(cx).text()
16256 }
16257
16258 pub fn is_empty(&self, cx: &App) -> bool {
16259 self.buffer.read(cx).read(cx).is_empty()
16260 }
16261
16262 pub fn text_option(&self, cx: &App) -> Option<String> {
16263 let text = self.text(cx);
16264 let text = text.trim();
16265
16266 if text.is_empty() {
16267 return None;
16268 }
16269
16270 Some(text.to_string())
16271 }
16272
16273 pub fn set_text(
16274 &mut self,
16275 text: impl Into<Arc<str>>,
16276 window: &mut Window,
16277 cx: &mut Context<Self>,
16278 ) {
16279 self.transact(window, cx, |this, _, cx| {
16280 this.buffer
16281 .read(cx)
16282 .as_singleton()
16283 .expect("you can only call set_text on editors for singleton buffers")
16284 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16285 });
16286 }
16287
16288 pub fn display_text(&self, cx: &mut App) -> String {
16289 self.display_map
16290 .update(cx, |map, cx| map.snapshot(cx))
16291 .text()
16292 }
16293
16294 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16295 let mut wrap_guides = smallvec::smallvec![];
16296
16297 if self.show_wrap_guides == Some(false) {
16298 return wrap_guides;
16299 }
16300
16301 let settings = self.buffer.read(cx).language_settings(cx);
16302 if settings.show_wrap_guides {
16303 match self.soft_wrap_mode(cx) {
16304 SoftWrap::Column(soft_wrap) => {
16305 wrap_guides.push((soft_wrap as usize, true));
16306 }
16307 SoftWrap::Bounded(soft_wrap) => {
16308 wrap_guides.push((soft_wrap as usize, true));
16309 }
16310 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16311 }
16312 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16313 }
16314
16315 wrap_guides
16316 }
16317
16318 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16319 let settings = self.buffer.read(cx).language_settings(cx);
16320 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16321 match mode {
16322 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16323 SoftWrap::None
16324 }
16325 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16326 language_settings::SoftWrap::PreferredLineLength => {
16327 SoftWrap::Column(settings.preferred_line_length)
16328 }
16329 language_settings::SoftWrap::Bounded => {
16330 SoftWrap::Bounded(settings.preferred_line_length)
16331 }
16332 }
16333 }
16334
16335 pub fn set_soft_wrap_mode(
16336 &mut self,
16337 mode: language_settings::SoftWrap,
16338
16339 cx: &mut Context<Self>,
16340 ) {
16341 self.soft_wrap_mode_override = Some(mode);
16342 cx.notify();
16343 }
16344
16345 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16346 self.hard_wrap = hard_wrap;
16347 cx.notify();
16348 }
16349
16350 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16351 self.text_style_refinement = Some(style);
16352 }
16353
16354 /// called by the Element so we know what style we were most recently rendered with.
16355 pub(crate) fn set_style(
16356 &mut self,
16357 style: EditorStyle,
16358 window: &mut Window,
16359 cx: &mut Context<Self>,
16360 ) {
16361 let rem_size = window.rem_size();
16362 self.display_map.update(cx, |map, cx| {
16363 map.set_font(
16364 style.text.font(),
16365 style.text.font_size.to_pixels(rem_size),
16366 cx,
16367 )
16368 });
16369 self.style = Some(style);
16370 }
16371
16372 pub fn style(&self) -> Option<&EditorStyle> {
16373 self.style.as_ref()
16374 }
16375
16376 // Called by the element. This method is not designed to be called outside of the editor
16377 // element's layout code because it does not notify when rewrapping is computed synchronously.
16378 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16379 self.display_map
16380 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16381 }
16382
16383 pub fn set_soft_wrap(&mut self) {
16384 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16385 }
16386
16387 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16388 if self.soft_wrap_mode_override.is_some() {
16389 self.soft_wrap_mode_override.take();
16390 } else {
16391 let soft_wrap = match self.soft_wrap_mode(cx) {
16392 SoftWrap::GitDiff => return,
16393 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16394 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16395 language_settings::SoftWrap::None
16396 }
16397 };
16398 self.soft_wrap_mode_override = Some(soft_wrap);
16399 }
16400 cx.notify();
16401 }
16402
16403 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16404 let Some(workspace) = self.workspace() else {
16405 return;
16406 };
16407 let fs = workspace.read(cx).app_state().fs.clone();
16408 let current_show = TabBarSettings::get_global(cx).show;
16409 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16410 setting.show = Some(!current_show);
16411 });
16412 }
16413
16414 pub fn toggle_indent_guides(
16415 &mut self,
16416 _: &ToggleIndentGuides,
16417 _: &mut Window,
16418 cx: &mut Context<Self>,
16419 ) {
16420 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16421 self.buffer
16422 .read(cx)
16423 .language_settings(cx)
16424 .indent_guides
16425 .enabled
16426 });
16427 self.show_indent_guides = Some(!currently_enabled);
16428 cx.notify();
16429 }
16430
16431 fn should_show_indent_guides(&self) -> Option<bool> {
16432 self.show_indent_guides
16433 }
16434
16435 pub fn toggle_line_numbers(
16436 &mut self,
16437 _: &ToggleLineNumbers,
16438 _: &mut Window,
16439 cx: &mut Context<Self>,
16440 ) {
16441 let mut editor_settings = EditorSettings::get_global(cx).clone();
16442 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16443 EditorSettings::override_global(editor_settings, cx);
16444 }
16445
16446 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16447 if let Some(show_line_numbers) = self.show_line_numbers {
16448 return show_line_numbers;
16449 }
16450 EditorSettings::get_global(cx).gutter.line_numbers
16451 }
16452
16453 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16454 self.use_relative_line_numbers
16455 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16456 }
16457
16458 pub fn toggle_relative_line_numbers(
16459 &mut self,
16460 _: &ToggleRelativeLineNumbers,
16461 _: &mut Window,
16462 cx: &mut Context<Self>,
16463 ) {
16464 let is_relative = self.should_use_relative_line_numbers(cx);
16465 self.set_relative_line_number(Some(!is_relative), cx)
16466 }
16467
16468 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16469 self.use_relative_line_numbers = is_relative;
16470 cx.notify();
16471 }
16472
16473 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16474 self.show_gutter = show_gutter;
16475 cx.notify();
16476 }
16477
16478 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16479 self.show_scrollbars = show_scrollbars;
16480 cx.notify();
16481 }
16482
16483 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16484 self.show_line_numbers = Some(show_line_numbers);
16485 cx.notify();
16486 }
16487
16488 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16489 self.disable_expand_excerpt_buttons = true;
16490 cx.notify();
16491 }
16492
16493 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16494 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16495 cx.notify();
16496 }
16497
16498 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16499 self.show_code_actions = Some(show_code_actions);
16500 cx.notify();
16501 }
16502
16503 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16504 self.show_runnables = Some(show_runnables);
16505 cx.notify();
16506 }
16507
16508 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16509 self.show_breakpoints = Some(show_breakpoints);
16510 cx.notify();
16511 }
16512
16513 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16514 if self.display_map.read(cx).masked != masked {
16515 self.display_map.update(cx, |map, _| map.masked = masked);
16516 }
16517 cx.notify()
16518 }
16519
16520 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16521 self.show_wrap_guides = Some(show_wrap_guides);
16522 cx.notify();
16523 }
16524
16525 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16526 self.show_indent_guides = Some(show_indent_guides);
16527 cx.notify();
16528 }
16529
16530 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16531 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16532 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16533 if let Some(dir) = file.abs_path(cx).parent() {
16534 return Some(dir.to_owned());
16535 }
16536 }
16537
16538 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16539 return Some(project_path.path.to_path_buf());
16540 }
16541 }
16542
16543 None
16544 }
16545
16546 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16547 self.active_excerpt(cx)?
16548 .1
16549 .read(cx)
16550 .file()
16551 .and_then(|f| f.as_local())
16552 }
16553
16554 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16555 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16556 let buffer = buffer.read(cx);
16557 if let Some(project_path) = buffer.project_path(cx) {
16558 let project = self.project.as_ref()?.read(cx);
16559 project.absolute_path(&project_path, cx)
16560 } else {
16561 buffer
16562 .file()
16563 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16564 }
16565 })
16566 }
16567
16568 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16569 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16570 let project_path = buffer.read(cx).project_path(cx)?;
16571 let project = self.project.as_ref()?.read(cx);
16572 let entry = project.entry_for_path(&project_path, cx)?;
16573 let path = entry.path.to_path_buf();
16574 Some(path)
16575 })
16576 }
16577
16578 pub fn reveal_in_finder(
16579 &mut self,
16580 _: &RevealInFileManager,
16581 _window: &mut Window,
16582 cx: &mut Context<Self>,
16583 ) {
16584 if let Some(target) = self.target_file(cx) {
16585 cx.reveal_path(&target.abs_path(cx));
16586 }
16587 }
16588
16589 pub fn copy_path(
16590 &mut self,
16591 _: &zed_actions::workspace::CopyPath,
16592 _window: &mut Window,
16593 cx: &mut Context<Self>,
16594 ) {
16595 if let Some(path) = self.target_file_abs_path(cx) {
16596 if let Some(path) = path.to_str() {
16597 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16598 }
16599 }
16600 }
16601
16602 pub fn copy_relative_path(
16603 &mut self,
16604 _: &zed_actions::workspace::CopyRelativePath,
16605 _window: &mut Window,
16606 cx: &mut Context<Self>,
16607 ) {
16608 if let Some(path) = self.target_file_path(cx) {
16609 if let Some(path) = path.to_str() {
16610 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16611 }
16612 }
16613 }
16614
16615 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16616 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16617 buffer.read(cx).project_path(cx)
16618 } else {
16619 None
16620 }
16621 }
16622
16623 // Returns true if the editor handled a go-to-line request
16624 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16625 maybe!({
16626 let breakpoint_store = self.breakpoint_store.as_ref()?;
16627
16628 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16629 else {
16630 self.clear_row_highlights::<ActiveDebugLine>();
16631 return None;
16632 };
16633
16634 let position = active_stack_frame.position;
16635 let buffer_id = position.buffer_id?;
16636 let snapshot = self
16637 .project
16638 .as_ref()?
16639 .read(cx)
16640 .buffer_for_id(buffer_id, cx)?
16641 .read(cx)
16642 .snapshot();
16643
16644 let mut handled = false;
16645 for (id, ExcerptRange { context, .. }) in
16646 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16647 {
16648 if context.start.cmp(&position, &snapshot).is_ge()
16649 || context.end.cmp(&position, &snapshot).is_lt()
16650 {
16651 continue;
16652 }
16653 let snapshot = self.buffer.read(cx).snapshot(cx);
16654 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16655
16656 handled = true;
16657 self.clear_row_highlights::<ActiveDebugLine>();
16658 self.go_to_line::<ActiveDebugLine>(
16659 multibuffer_anchor,
16660 Some(cx.theme().colors().editor_debugger_active_line_background),
16661 window,
16662 cx,
16663 );
16664
16665 cx.notify();
16666 }
16667
16668 handled.then_some(())
16669 })
16670 .is_some()
16671 }
16672
16673 pub fn copy_file_name_without_extension(
16674 &mut self,
16675 _: &CopyFileNameWithoutExtension,
16676 _: &mut Window,
16677 cx: &mut Context<Self>,
16678 ) {
16679 if let Some(file) = self.target_file(cx) {
16680 if let Some(file_stem) = file.path().file_stem() {
16681 if let Some(name) = file_stem.to_str() {
16682 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16683 }
16684 }
16685 }
16686 }
16687
16688 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16689 if let Some(file) = self.target_file(cx) {
16690 if let Some(file_name) = file.path().file_name() {
16691 if let Some(name) = file_name.to_str() {
16692 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16693 }
16694 }
16695 }
16696 }
16697
16698 pub fn toggle_git_blame(
16699 &mut self,
16700 _: &::git::Blame,
16701 window: &mut Window,
16702 cx: &mut Context<Self>,
16703 ) {
16704 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16705
16706 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16707 self.start_git_blame(true, window, cx);
16708 }
16709
16710 cx.notify();
16711 }
16712
16713 pub fn toggle_git_blame_inline(
16714 &mut self,
16715 _: &ToggleGitBlameInline,
16716 window: &mut Window,
16717 cx: &mut Context<Self>,
16718 ) {
16719 self.toggle_git_blame_inline_internal(true, window, cx);
16720 cx.notify();
16721 }
16722
16723 pub fn open_git_blame_commit(
16724 &mut self,
16725 _: &OpenGitBlameCommit,
16726 window: &mut Window,
16727 cx: &mut Context<Self>,
16728 ) {
16729 self.open_git_blame_commit_internal(window, cx);
16730 }
16731
16732 fn open_git_blame_commit_internal(
16733 &mut self,
16734 window: &mut Window,
16735 cx: &mut Context<Self>,
16736 ) -> Option<()> {
16737 let blame = self.blame.as_ref()?;
16738 let snapshot = self.snapshot(window, cx);
16739 let cursor = self.selections.newest::<Point>(cx).head();
16740 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16741 let blame_entry = blame
16742 .update(cx, |blame, cx| {
16743 blame
16744 .blame_for_rows(
16745 &[RowInfo {
16746 buffer_id: Some(buffer.remote_id()),
16747 buffer_row: Some(point.row),
16748 ..Default::default()
16749 }],
16750 cx,
16751 )
16752 .next()
16753 })
16754 .flatten()?;
16755 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16756 let repo = blame.read(cx).repository(cx)?;
16757 let workspace = self.workspace()?.downgrade();
16758 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16759 None
16760 }
16761
16762 pub fn git_blame_inline_enabled(&self) -> bool {
16763 self.git_blame_inline_enabled
16764 }
16765
16766 pub fn toggle_selection_menu(
16767 &mut self,
16768 _: &ToggleSelectionMenu,
16769 _: &mut Window,
16770 cx: &mut Context<Self>,
16771 ) {
16772 self.show_selection_menu = self
16773 .show_selection_menu
16774 .map(|show_selections_menu| !show_selections_menu)
16775 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16776
16777 cx.notify();
16778 }
16779
16780 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16781 self.show_selection_menu
16782 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16783 }
16784
16785 fn start_git_blame(
16786 &mut self,
16787 user_triggered: bool,
16788 window: &mut Window,
16789 cx: &mut Context<Self>,
16790 ) {
16791 if let Some(project) = self.project.as_ref() {
16792 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16793 return;
16794 };
16795
16796 if buffer.read(cx).file().is_none() {
16797 return;
16798 }
16799
16800 let focused = self.focus_handle(cx).contains_focused(window, cx);
16801
16802 let project = project.clone();
16803 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16804 self.blame_subscription =
16805 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16806 self.blame = Some(blame);
16807 }
16808 }
16809
16810 fn toggle_git_blame_inline_internal(
16811 &mut self,
16812 user_triggered: bool,
16813 window: &mut Window,
16814 cx: &mut Context<Self>,
16815 ) {
16816 if self.git_blame_inline_enabled {
16817 self.git_blame_inline_enabled = false;
16818 self.show_git_blame_inline = false;
16819 self.show_git_blame_inline_delay_task.take();
16820 } else {
16821 self.git_blame_inline_enabled = true;
16822 self.start_git_blame_inline(user_triggered, window, cx);
16823 }
16824
16825 cx.notify();
16826 }
16827
16828 fn start_git_blame_inline(
16829 &mut self,
16830 user_triggered: bool,
16831 window: &mut Window,
16832 cx: &mut Context<Self>,
16833 ) {
16834 self.start_git_blame(user_triggered, window, cx);
16835
16836 if ProjectSettings::get_global(cx)
16837 .git
16838 .inline_blame_delay()
16839 .is_some()
16840 {
16841 self.start_inline_blame_timer(window, cx);
16842 } else {
16843 self.show_git_blame_inline = true
16844 }
16845 }
16846
16847 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16848 self.blame.as_ref()
16849 }
16850
16851 pub fn show_git_blame_gutter(&self) -> bool {
16852 self.show_git_blame_gutter
16853 }
16854
16855 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16856 self.show_git_blame_gutter && self.has_blame_entries(cx)
16857 }
16858
16859 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16860 self.show_git_blame_inline
16861 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16862 && !self.newest_selection_head_on_empty_line(cx)
16863 && self.has_blame_entries(cx)
16864 }
16865
16866 fn has_blame_entries(&self, cx: &App) -> bool {
16867 self.blame()
16868 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16869 }
16870
16871 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16872 let cursor_anchor = self.selections.newest_anchor().head();
16873
16874 let snapshot = self.buffer.read(cx).snapshot(cx);
16875 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16876
16877 snapshot.line_len(buffer_row) == 0
16878 }
16879
16880 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16881 let buffer_and_selection = maybe!({
16882 let selection = self.selections.newest::<Point>(cx);
16883 let selection_range = selection.range();
16884
16885 let multi_buffer = self.buffer().read(cx);
16886 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16887 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16888
16889 let (buffer, range, _) = if selection.reversed {
16890 buffer_ranges.first()
16891 } else {
16892 buffer_ranges.last()
16893 }?;
16894
16895 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16896 ..text::ToPoint::to_point(&range.end, &buffer).row;
16897 Some((
16898 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16899 selection,
16900 ))
16901 });
16902
16903 let Some((buffer, selection)) = buffer_and_selection else {
16904 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16905 };
16906
16907 let Some(project) = self.project.as_ref() else {
16908 return Task::ready(Err(anyhow!("editor does not have project")));
16909 };
16910
16911 project.update(cx, |project, cx| {
16912 project.get_permalink_to_line(&buffer, selection, cx)
16913 })
16914 }
16915
16916 pub fn copy_permalink_to_line(
16917 &mut self,
16918 _: &CopyPermalinkToLine,
16919 window: &mut Window,
16920 cx: &mut Context<Self>,
16921 ) {
16922 let permalink_task = self.get_permalink_to_line(cx);
16923 let workspace = self.workspace();
16924
16925 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16926 Ok(permalink) => {
16927 cx.update(|_, cx| {
16928 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16929 })
16930 .ok();
16931 }
16932 Err(err) => {
16933 let message = format!("Failed to copy permalink: {err}");
16934
16935 Err::<(), anyhow::Error>(err).log_err();
16936
16937 if let Some(workspace) = workspace {
16938 workspace
16939 .update_in(cx, |workspace, _, cx| {
16940 struct CopyPermalinkToLine;
16941
16942 workspace.show_toast(
16943 Toast::new(
16944 NotificationId::unique::<CopyPermalinkToLine>(),
16945 message,
16946 ),
16947 cx,
16948 )
16949 })
16950 .ok();
16951 }
16952 }
16953 })
16954 .detach();
16955 }
16956
16957 pub fn copy_file_location(
16958 &mut self,
16959 _: &CopyFileLocation,
16960 _: &mut Window,
16961 cx: &mut Context<Self>,
16962 ) {
16963 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16964 if let Some(file) = self.target_file(cx) {
16965 if let Some(path) = file.path().to_str() {
16966 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16967 }
16968 }
16969 }
16970
16971 pub fn open_permalink_to_line(
16972 &mut self,
16973 _: &OpenPermalinkToLine,
16974 window: &mut Window,
16975 cx: &mut Context<Self>,
16976 ) {
16977 let permalink_task = self.get_permalink_to_line(cx);
16978 let workspace = self.workspace();
16979
16980 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16981 Ok(permalink) => {
16982 cx.update(|_, cx| {
16983 cx.open_url(permalink.as_ref());
16984 })
16985 .ok();
16986 }
16987 Err(err) => {
16988 let message = format!("Failed to open permalink: {err}");
16989
16990 Err::<(), anyhow::Error>(err).log_err();
16991
16992 if let Some(workspace) = workspace {
16993 workspace
16994 .update(cx, |workspace, cx| {
16995 struct OpenPermalinkToLine;
16996
16997 workspace.show_toast(
16998 Toast::new(
16999 NotificationId::unique::<OpenPermalinkToLine>(),
17000 message,
17001 ),
17002 cx,
17003 )
17004 })
17005 .ok();
17006 }
17007 }
17008 })
17009 .detach();
17010 }
17011
17012 pub fn insert_uuid_v4(
17013 &mut self,
17014 _: &InsertUuidV4,
17015 window: &mut Window,
17016 cx: &mut Context<Self>,
17017 ) {
17018 self.insert_uuid(UuidVersion::V4, window, cx);
17019 }
17020
17021 pub fn insert_uuid_v7(
17022 &mut self,
17023 _: &InsertUuidV7,
17024 window: &mut Window,
17025 cx: &mut Context<Self>,
17026 ) {
17027 self.insert_uuid(UuidVersion::V7, window, cx);
17028 }
17029
17030 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17031 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17032 self.transact(window, cx, |this, window, cx| {
17033 let edits = this
17034 .selections
17035 .all::<Point>(cx)
17036 .into_iter()
17037 .map(|selection| {
17038 let uuid = match version {
17039 UuidVersion::V4 => uuid::Uuid::new_v4(),
17040 UuidVersion::V7 => uuid::Uuid::now_v7(),
17041 };
17042
17043 (selection.range(), uuid.to_string())
17044 });
17045 this.edit(edits, cx);
17046 this.refresh_inline_completion(true, false, window, cx);
17047 });
17048 }
17049
17050 pub fn open_selections_in_multibuffer(
17051 &mut self,
17052 _: &OpenSelectionsInMultibuffer,
17053 window: &mut Window,
17054 cx: &mut Context<Self>,
17055 ) {
17056 let multibuffer = self.buffer.read(cx);
17057
17058 let Some(buffer) = multibuffer.as_singleton() else {
17059 return;
17060 };
17061
17062 let Some(workspace) = self.workspace() else {
17063 return;
17064 };
17065
17066 let locations = self
17067 .selections
17068 .disjoint_anchors()
17069 .iter()
17070 .map(|range| Location {
17071 buffer: buffer.clone(),
17072 range: range.start.text_anchor..range.end.text_anchor,
17073 })
17074 .collect::<Vec<_>>();
17075
17076 let title = multibuffer.title(cx).to_string();
17077
17078 cx.spawn_in(window, async move |_, cx| {
17079 workspace.update_in(cx, |workspace, window, cx| {
17080 Self::open_locations_in_multibuffer(
17081 workspace,
17082 locations,
17083 format!("Selections for '{title}'"),
17084 false,
17085 MultibufferSelectionMode::All,
17086 window,
17087 cx,
17088 );
17089 })
17090 })
17091 .detach();
17092 }
17093
17094 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17095 /// last highlight added will be used.
17096 ///
17097 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17098 pub fn highlight_rows<T: 'static>(
17099 &mut self,
17100 range: Range<Anchor>,
17101 color: Hsla,
17102 options: RowHighlightOptions,
17103 cx: &mut Context<Self>,
17104 ) {
17105 let snapshot = self.buffer().read(cx).snapshot(cx);
17106 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17107 let ix = row_highlights.binary_search_by(|highlight| {
17108 Ordering::Equal
17109 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17110 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17111 });
17112
17113 if let Err(mut ix) = ix {
17114 let index = post_inc(&mut self.highlight_order);
17115
17116 // If this range intersects with the preceding highlight, then merge it with
17117 // the preceding highlight. Otherwise insert a new highlight.
17118 let mut merged = false;
17119 if ix > 0 {
17120 let prev_highlight = &mut row_highlights[ix - 1];
17121 if prev_highlight
17122 .range
17123 .end
17124 .cmp(&range.start, &snapshot)
17125 .is_ge()
17126 {
17127 ix -= 1;
17128 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17129 prev_highlight.range.end = range.end;
17130 }
17131 merged = true;
17132 prev_highlight.index = index;
17133 prev_highlight.color = color;
17134 prev_highlight.options = options;
17135 }
17136 }
17137
17138 if !merged {
17139 row_highlights.insert(
17140 ix,
17141 RowHighlight {
17142 range: range.clone(),
17143 index,
17144 color,
17145 options,
17146 type_id: TypeId::of::<T>(),
17147 },
17148 );
17149 }
17150
17151 // If any of the following highlights intersect with this one, merge them.
17152 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17153 let highlight = &row_highlights[ix];
17154 if next_highlight
17155 .range
17156 .start
17157 .cmp(&highlight.range.end, &snapshot)
17158 .is_le()
17159 {
17160 if next_highlight
17161 .range
17162 .end
17163 .cmp(&highlight.range.end, &snapshot)
17164 .is_gt()
17165 {
17166 row_highlights[ix].range.end = next_highlight.range.end;
17167 }
17168 row_highlights.remove(ix + 1);
17169 } else {
17170 break;
17171 }
17172 }
17173 }
17174 }
17175
17176 /// Remove any highlighted row ranges of the given type that intersect the
17177 /// given ranges.
17178 pub fn remove_highlighted_rows<T: 'static>(
17179 &mut self,
17180 ranges_to_remove: Vec<Range<Anchor>>,
17181 cx: &mut Context<Self>,
17182 ) {
17183 let snapshot = self.buffer().read(cx).snapshot(cx);
17184 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17185 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17186 row_highlights.retain(|highlight| {
17187 while let Some(range_to_remove) = ranges_to_remove.peek() {
17188 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17189 Ordering::Less | Ordering::Equal => {
17190 ranges_to_remove.next();
17191 }
17192 Ordering::Greater => {
17193 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17194 Ordering::Less | Ordering::Equal => {
17195 return false;
17196 }
17197 Ordering::Greater => break,
17198 }
17199 }
17200 }
17201 }
17202
17203 true
17204 })
17205 }
17206
17207 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17208 pub fn clear_row_highlights<T: 'static>(&mut self) {
17209 self.highlighted_rows.remove(&TypeId::of::<T>());
17210 }
17211
17212 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17213 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17214 self.highlighted_rows
17215 .get(&TypeId::of::<T>())
17216 .map_or(&[] as &[_], |vec| vec.as_slice())
17217 .iter()
17218 .map(|highlight| (highlight.range.clone(), highlight.color))
17219 }
17220
17221 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17222 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17223 /// Allows to ignore certain kinds of highlights.
17224 pub fn highlighted_display_rows(
17225 &self,
17226 window: &mut Window,
17227 cx: &mut App,
17228 ) -> BTreeMap<DisplayRow, LineHighlight> {
17229 let snapshot = self.snapshot(window, cx);
17230 let mut used_highlight_orders = HashMap::default();
17231 self.highlighted_rows
17232 .iter()
17233 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17234 .fold(
17235 BTreeMap::<DisplayRow, LineHighlight>::new(),
17236 |mut unique_rows, highlight| {
17237 let start = highlight.range.start.to_display_point(&snapshot);
17238 let end = highlight.range.end.to_display_point(&snapshot);
17239 let start_row = start.row().0;
17240 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17241 && end.column() == 0
17242 {
17243 end.row().0.saturating_sub(1)
17244 } else {
17245 end.row().0
17246 };
17247 for row in start_row..=end_row {
17248 let used_index =
17249 used_highlight_orders.entry(row).or_insert(highlight.index);
17250 if highlight.index >= *used_index {
17251 *used_index = highlight.index;
17252 unique_rows.insert(
17253 DisplayRow(row),
17254 LineHighlight {
17255 include_gutter: highlight.options.include_gutter,
17256 border: None,
17257 background: highlight.color.into(),
17258 type_id: Some(highlight.type_id),
17259 },
17260 );
17261 }
17262 }
17263 unique_rows
17264 },
17265 )
17266 }
17267
17268 pub fn highlighted_display_row_for_autoscroll(
17269 &self,
17270 snapshot: &DisplaySnapshot,
17271 ) -> Option<DisplayRow> {
17272 self.highlighted_rows
17273 .values()
17274 .flat_map(|highlighted_rows| highlighted_rows.iter())
17275 .filter_map(|highlight| {
17276 if highlight.options.autoscroll {
17277 Some(highlight.range.start.to_display_point(snapshot).row())
17278 } else {
17279 None
17280 }
17281 })
17282 .min()
17283 }
17284
17285 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17286 self.highlight_background::<SearchWithinRange>(
17287 ranges,
17288 |colors| colors.editor_document_highlight_read_background,
17289 cx,
17290 )
17291 }
17292
17293 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17294 self.breadcrumb_header = Some(new_header);
17295 }
17296
17297 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17298 self.clear_background_highlights::<SearchWithinRange>(cx);
17299 }
17300
17301 pub fn highlight_background<T: 'static>(
17302 &mut self,
17303 ranges: &[Range<Anchor>],
17304 color_fetcher: fn(&ThemeColors) -> Hsla,
17305 cx: &mut Context<Self>,
17306 ) {
17307 self.background_highlights
17308 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17309 self.scrollbar_marker_state.dirty = true;
17310 cx.notify();
17311 }
17312
17313 pub fn clear_background_highlights<T: 'static>(
17314 &mut self,
17315 cx: &mut Context<Self>,
17316 ) -> Option<BackgroundHighlight> {
17317 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17318 if !text_highlights.1.is_empty() {
17319 self.scrollbar_marker_state.dirty = true;
17320 cx.notify();
17321 }
17322 Some(text_highlights)
17323 }
17324
17325 pub fn highlight_gutter<T: 'static>(
17326 &mut self,
17327 ranges: &[Range<Anchor>],
17328 color_fetcher: fn(&App) -> Hsla,
17329 cx: &mut Context<Self>,
17330 ) {
17331 self.gutter_highlights
17332 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17333 cx.notify();
17334 }
17335
17336 pub fn clear_gutter_highlights<T: 'static>(
17337 &mut self,
17338 cx: &mut Context<Self>,
17339 ) -> Option<GutterHighlight> {
17340 cx.notify();
17341 self.gutter_highlights.remove(&TypeId::of::<T>())
17342 }
17343
17344 #[cfg(feature = "test-support")]
17345 pub fn all_text_background_highlights(
17346 &self,
17347 window: &mut Window,
17348 cx: &mut Context<Self>,
17349 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17350 let snapshot = self.snapshot(window, cx);
17351 let buffer = &snapshot.buffer_snapshot;
17352 let start = buffer.anchor_before(0);
17353 let end = buffer.anchor_after(buffer.len());
17354 let theme = cx.theme().colors();
17355 self.background_highlights_in_range(start..end, &snapshot, theme)
17356 }
17357
17358 #[cfg(feature = "test-support")]
17359 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17360 let snapshot = self.buffer().read(cx).snapshot(cx);
17361
17362 let highlights = self
17363 .background_highlights
17364 .get(&TypeId::of::<items::BufferSearchHighlights>());
17365
17366 if let Some((_color, ranges)) = highlights {
17367 ranges
17368 .iter()
17369 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17370 .collect_vec()
17371 } else {
17372 vec![]
17373 }
17374 }
17375
17376 fn document_highlights_for_position<'a>(
17377 &'a self,
17378 position: Anchor,
17379 buffer: &'a MultiBufferSnapshot,
17380 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17381 let read_highlights = self
17382 .background_highlights
17383 .get(&TypeId::of::<DocumentHighlightRead>())
17384 .map(|h| &h.1);
17385 let write_highlights = self
17386 .background_highlights
17387 .get(&TypeId::of::<DocumentHighlightWrite>())
17388 .map(|h| &h.1);
17389 let left_position = position.bias_left(buffer);
17390 let right_position = position.bias_right(buffer);
17391 read_highlights
17392 .into_iter()
17393 .chain(write_highlights)
17394 .flat_map(move |ranges| {
17395 let start_ix = match ranges.binary_search_by(|probe| {
17396 let cmp = probe.end.cmp(&left_position, buffer);
17397 if cmp.is_ge() {
17398 Ordering::Greater
17399 } else {
17400 Ordering::Less
17401 }
17402 }) {
17403 Ok(i) | Err(i) => i,
17404 };
17405
17406 ranges[start_ix..]
17407 .iter()
17408 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17409 })
17410 }
17411
17412 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17413 self.background_highlights
17414 .get(&TypeId::of::<T>())
17415 .map_or(false, |(_, highlights)| !highlights.is_empty())
17416 }
17417
17418 pub fn background_highlights_in_range(
17419 &self,
17420 search_range: Range<Anchor>,
17421 display_snapshot: &DisplaySnapshot,
17422 theme: &ThemeColors,
17423 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17424 let mut results = Vec::new();
17425 for (color_fetcher, ranges) in self.background_highlights.values() {
17426 let color = color_fetcher(theme);
17427 let start_ix = match ranges.binary_search_by(|probe| {
17428 let cmp = probe
17429 .end
17430 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17431 if cmp.is_gt() {
17432 Ordering::Greater
17433 } else {
17434 Ordering::Less
17435 }
17436 }) {
17437 Ok(i) | Err(i) => i,
17438 };
17439 for range in &ranges[start_ix..] {
17440 if range
17441 .start
17442 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17443 .is_ge()
17444 {
17445 break;
17446 }
17447
17448 let start = range.start.to_display_point(display_snapshot);
17449 let end = range.end.to_display_point(display_snapshot);
17450 results.push((start..end, color))
17451 }
17452 }
17453 results
17454 }
17455
17456 pub fn background_highlight_row_ranges<T: 'static>(
17457 &self,
17458 search_range: Range<Anchor>,
17459 display_snapshot: &DisplaySnapshot,
17460 count: usize,
17461 ) -> Vec<RangeInclusive<DisplayPoint>> {
17462 let mut results = Vec::new();
17463 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17464 return vec![];
17465 };
17466
17467 let start_ix = match ranges.binary_search_by(|probe| {
17468 let cmp = probe
17469 .end
17470 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17471 if cmp.is_gt() {
17472 Ordering::Greater
17473 } else {
17474 Ordering::Less
17475 }
17476 }) {
17477 Ok(i) | Err(i) => i,
17478 };
17479 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17480 if let (Some(start_display), Some(end_display)) = (start, end) {
17481 results.push(
17482 start_display.to_display_point(display_snapshot)
17483 ..=end_display.to_display_point(display_snapshot),
17484 );
17485 }
17486 };
17487 let mut start_row: Option<Point> = None;
17488 let mut end_row: Option<Point> = None;
17489 if ranges.len() > count {
17490 return Vec::new();
17491 }
17492 for range in &ranges[start_ix..] {
17493 if range
17494 .start
17495 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17496 .is_ge()
17497 {
17498 break;
17499 }
17500 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17501 if let Some(current_row) = &end_row {
17502 if end.row == current_row.row {
17503 continue;
17504 }
17505 }
17506 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17507 if start_row.is_none() {
17508 assert_eq!(end_row, None);
17509 start_row = Some(start);
17510 end_row = Some(end);
17511 continue;
17512 }
17513 if let Some(current_end) = end_row.as_mut() {
17514 if start.row > current_end.row + 1 {
17515 push_region(start_row, end_row);
17516 start_row = Some(start);
17517 end_row = Some(end);
17518 } else {
17519 // Merge two hunks.
17520 *current_end = end;
17521 }
17522 } else {
17523 unreachable!();
17524 }
17525 }
17526 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17527 push_region(start_row, end_row);
17528 results
17529 }
17530
17531 pub fn gutter_highlights_in_range(
17532 &self,
17533 search_range: Range<Anchor>,
17534 display_snapshot: &DisplaySnapshot,
17535 cx: &App,
17536 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17537 let mut results = Vec::new();
17538 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17539 let color = color_fetcher(cx);
17540 let start_ix = match ranges.binary_search_by(|probe| {
17541 let cmp = probe
17542 .end
17543 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17544 if cmp.is_gt() {
17545 Ordering::Greater
17546 } else {
17547 Ordering::Less
17548 }
17549 }) {
17550 Ok(i) | Err(i) => i,
17551 };
17552 for range in &ranges[start_ix..] {
17553 if range
17554 .start
17555 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17556 .is_ge()
17557 {
17558 break;
17559 }
17560
17561 let start = range.start.to_display_point(display_snapshot);
17562 let end = range.end.to_display_point(display_snapshot);
17563 results.push((start..end, color))
17564 }
17565 }
17566 results
17567 }
17568
17569 /// Get the text ranges corresponding to the redaction query
17570 pub fn redacted_ranges(
17571 &self,
17572 search_range: Range<Anchor>,
17573 display_snapshot: &DisplaySnapshot,
17574 cx: &App,
17575 ) -> Vec<Range<DisplayPoint>> {
17576 display_snapshot
17577 .buffer_snapshot
17578 .redacted_ranges(search_range, |file| {
17579 if let Some(file) = file {
17580 file.is_private()
17581 && EditorSettings::get(
17582 Some(SettingsLocation {
17583 worktree_id: file.worktree_id(cx),
17584 path: file.path().as_ref(),
17585 }),
17586 cx,
17587 )
17588 .redact_private_values
17589 } else {
17590 false
17591 }
17592 })
17593 .map(|range| {
17594 range.start.to_display_point(display_snapshot)
17595 ..range.end.to_display_point(display_snapshot)
17596 })
17597 .collect()
17598 }
17599
17600 pub fn highlight_text<T: 'static>(
17601 &mut self,
17602 ranges: Vec<Range<Anchor>>,
17603 style: HighlightStyle,
17604 cx: &mut Context<Self>,
17605 ) {
17606 self.display_map.update(cx, |map, _| {
17607 map.highlight_text(TypeId::of::<T>(), ranges, style)
17608 });
17609 cx.notify();
17610 }
17611
17612 pub(crate) fn highlight_inlays<T: 'static>(
17613 &mut self,
17614 highlights: Vec<InlayHighlight>,
17615 style: HighlightStyle,
17616 cx: &mut Context<Self>,
17617 ) {
17618 self.display_map.update(cx, |map, _| {
17619 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17620 });
17621 cx.notify();
17622 }
17623
17624 pub fn text_highlights<'a, T: 'static>(
17625 &'a self,
17626 cx: &'a App,
17627 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17628 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17629 }
17630
17631 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17632 let cleared = self
17633 .display_map
17634 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17635 if cleared {
17636 cx.notify();
17637 }
17638 }
17639
17640 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17641 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17642 && self.focus_handle.is_focused(window)
17643 }
17644
17645 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17646 self.show_cursor_when_unfocused = is_enabled;
17647 cx.notify();
17648 }
17649
17650 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17651 cx.notify();
17652 }
17653
17654 fn on_debug_session_event(
17655 &mut self,
17656 _session: Entity<Session>,
17657 event: &SessionEvent,
17658 cx: &mut Context<Self>,
17659 ) {
17660 match event {
17661 SessionEvent::InvalidateInlineValue => {
17662 self.refresh_inline_values(cx);
17663 }
17664 _ => {}
17665 }
17666 }
17667
17668 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17669 let Some(project) = self.project.clone() else {
17670 return;
17671 };
17672 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17673 return;
17674 };
17675 if !self.inline_value_cache.enabled {
17676 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17677 self.splice_inlays(&inlays, Vec::new(), cx);
17678 return;
17679 }
17680
17681 let current_execution_position = self
17682 .highlighted_rows
17683 .get(&TypeId::of::<ActiveDebugLine>())
17684 .and_then(|lines| lines.last().map(|line| line.range.start));
17685
17686 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17687 let snapshot = editor
17688 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17689 .ok()?;
17690
17691 let inline_values = editor
17692 .update(cx, |_, cx| {
17693 let Some(current_execution_position) = current_execution_position else {
17694 return Some(Task::ready(Ok(Vec::new())));
17695 };
17696
17697 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17698 // anchor is in the same buffer
17699 let range =
17700 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17701 project.inline_values(buffer, range, cx)
17702 })
17703 .ok()
17704 .flatten()?
17705 .await
17706 .context("refreshing debugger inlays")
17707 .log_err()?;
17708
17709 let (excerpt_id, buffer_id) = snapshot
17710 .excerpts()
17711 .next()
17712 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17713 editor
17714 .update(cx, |editor, cx| {
17715 let new_inlays = inline_values
17716 .into_iter()
17717 .map(|debugger_value| {
17718 Inlay::debugger_hint(
17719 post_inc(&mut editor.next_inlay_id),
17720 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17721 debugger_value.text(),
17722 )
17723 })
17724 .collect::<Vec<_>>();
17725 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17726 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17727
17728 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17729 })
17730 .ok()?;
17731 Some(())
17732 });
17733 }
17734
17735 fn on_buffer_event(
17736 &mut self,
17737 multibuffer: &Entity<MultiBuffer>,
17738 event: &multi_buffer::Event,
17739 window: &mut Window,
17740 cx: &mut Context<Self>,
17741 ) {
17742 match event {
17743 multi_buffer::Event::Edited {
17744 singleton_buffer_edited,
17745 edited_buffer: buffer_edited,
17746 } => {
17747 self.scrollbar_marker_state.dirty = true;
17748 self.active_indent_guides_state.dirty = true;
17749 self.refresh_active_diagnostics(cx);
17750 self.refresh_code_actions(window, cx);
17751 self.refresh_selected_text_highlights(true, window, cx);
17752 refresh_matching_bracket_highlights(self, window, cx);
17753 if self.has_active_inline_completion() {
17754 self.update_visible_inline_completion(window, cx);
17755 }
17756 if let Some(buffer) = buffer_edited {
17757 let buffer_id = buffer.read(cx).remote_id();
17758 if !self.registered_buffers.contains_key(&buffer_id) {
17759 if let Some(project) = self.project.as_ref() {
17760 project.update(cx, |project, cx| {
17761 self.registered_buffers.insert(
17762 buffer_id,
17763 project.register_buffer_with_language_servers(&buffer, cx),
17764 );
17765 })
17766 }
17767 }
17768 }
17769 cx.emit(EditorEvent::BufferEdited);
17770 cx.emit(SearchEvent::MatchesInvalidated);
17771 if *singleton_buffer_edited {
17772 if let Some(project) = &self.project {
17773 #[allow(clippy::mutable_key_type)]
17774 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17775 multibuffer
17776 .all_buffers()
17777 .into_iter()
17778 .filter_map(|buffer| {
17779 buffer.update(cx, |buffer, cx| {
17780 let language = buffer.language()?;
17781 let should_discard = project.update(cx, |project, cx| {
17782 project.is_local()
17783 && !project.has_language_servers_for(buffer, cx)
17784 });
17785 should_discard.not().then_some(language.clone())
17786 })
17787 })
17788 .collect::<HashSet<_>>()
17789 });
17790 if !languages_affected.is_empty() {
17791 self.refresh_inlay_hints(
17792 InlayHintRefreshReason::BufferEdited(languages_affected),
17793 cx,
17794 );
17795 }
17796 }
17797 }
17798
17799 let Some(project) = &self.project else { return };
17800 let (telemetry, is_via_ssh) = {
17801 let project = project.read(cx);
17802 let telemetry = project.client().telemetry().clone();
17803 let is_via_ssh = project.is_via_ssh();
17804 (telemetry, is_via_ssh)
17805 };
17806 refresh_linked_ranges(self, window, cx);
17807 telemetry.log_edit_event("editor", is_via_ssh);
17808 }
17809 multi_buffer::Event::ExcerptsAdded {
17810 buffer,
17811 predecessor,
17812 excerpts,
17813 } => {
17814 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17815 let buffer_id = buffer.read(cx).remote_id();
17816 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17817 if let Some(project) = &self.project {
17818 update_uncommitted_diff_for_buffer(
17819 cx.entity(),
17820 project,
17821 [buffer.clone()],
17822 self.buffer.clone(),
17823 cx,
17824 )
17825 .detach();
17826 }
17827 }
17828 cx.emit(EditorEvent::ExcerptsAdded {
17829 buffer: buffer.clone(),
17830 predecessor: *predecessor,
17831 excerpts: excerpts.clone(),
17832 });
17833 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17834 }
17835 multi_buffer::Event::ExcerptsRemoved {
17836 ids,
17837 removed_buffer_ids,
17838 } => {
17839 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17840 let buffer = self.buffer.read(cx);
17841 self.registered_buffers
17842 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17843 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17844 cx.emit(EditorEvent::ExcerptsRemoved {
17845 ids: ids.clone(),
17846 removed_buffer_ids: removed_buffer_ids.clone(),
17847 })
17848 }
17849 multi_buffer::Event::ExcerptsEdited {
17850 excerpt_ids,
17851 buffer_ids,
17852 } => {
17853 self.display_map.update(cx, |map, cx| {
17854 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17855 });
17856 cx.emit(EditorEvent::ExcerptsEdited {
17857 ids: excerpt_ids.clone(),
17858 })
17859 }
17860 multi_buffer::Event::ExcerptsExpanded { ids } => {
17861 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17862 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17863 }
17864 multi_buffer::Event::Reparsed(buffer_id) => {
17865 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17866 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17867
17868 cx.emit(EditorEvent::Reparsed(*buffer_id));
17869 }
17870 multi_buffer::Event::DiffHunksToggled => {
17871 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17872 }
17873 multi_buffer::Event::LanguageChanged(buffer_id) => {
17874 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17875 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17876 cx.emit(EditorEvent::Reparsed(*buffer_id));
17877 cx.notify();
17878 }
17879 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17880 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17881 multi_buffer::Event::FileHandleChanged
17882 | multi_buffer::Event::Reloaded
17883 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17884 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17885 multi_buffer::Event::DiagnosticsUpdated => {
17886 self.refresh_active_diagnostics(cx);
17887 self.refresh_inline_diagnostics(true, window, cx);
17888 self.scrollbar_marker_state.dirty = true;
17889 cx.notify();
17890 }
17891 _ => {}
17892 };
17893 }
17894
17895 pub fn start_temporary_diff_override(&mut self) {
17896 self.load_diff_task.take();
17897 self.temporary_diff_override = true;
17898 }
17899
17900 pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17901 self.temporary_diff_override = false;
17902 self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17903 self.buffer.update(cx, |buffer, cx| {
17904 buffer.set_all_diff_hunks_collapsed(cx);
17905 });
17906
17907 if let Some(project) = self.project.clone() {
17908 self.load_diff_task = Some(
17909 update_uncommitted_diff_for_buffer(
17910 cx.entity(),
17911 &project,
17912 self.buffer.read(cx).all_buffers(),
17913 self.buffer.clone(),
17914 cx,
17915 )
17916 .shared(),
17917 );
17918 }
17919 }
17920
17921 fn on_display_map_changed(
17922 &mut self,
17923 _: Entity<DisplayMap>,
17924 _: &mut Window,
17925 cx: &mut Context<Self>,
17926 ) {
17927 cx.notify();
17928 }
17929
17930 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17931 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17932 self.update_edit_prediction_settings(cx);
17933 self.refresh_inline_completion(true, false, window, cx);
17934 self.refresh_inlay_hints(
17935 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17936 self.selections.newest_anchor().head(),
17937 &self.buffer.read(cx).snapshot(cx),
17938 cx,
17939 )),
17940 cx,
17941 );
17942
17943 let old_cursor_shape = self.cursor_shape;
17944
17945 {
17946 let editor_settings = EditorSettings::get_global(cx);
17947 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17948 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17949 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17950 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17951 }
17952
17953 if old_cursor_shape != self.cursor_shape {
17954 cx.emit(EditorEvent::CursorShapeChanged);
17955 }
17956
17957 let project_settings = ProjectSettings::get_global(cx);
17958 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17959
17960 if self.mode.is_full() {
17961 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17962 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17963 if self.show_inline_diagnostics != show_inline_diagnostics {
17964 self.show_inline_diagnostics = show_inline_diagnostics;
17965 self.refresh_inline_diagnostics(false, window, cx);
17966 }
17967
17968 if self.git_blame_inline_enabled != inline_blame_enabled {
17969 self.toggle_git_blame_inline_internal(false, window, cx);
17970 }
17971 }
17972
17973 cx.notify();
17974 }
17975
17976 pub fn set_searchable(&mut self, searchable: bool) {
17977 self.searchable = searchable;
17978 }
17979
17980 pub fn searchable(&self) -> bool {
17981 self.searchable
17982 }
17983
17984 fn open_proposed_changes_editor(
17985 &mut self,
17986 _: &OpenProposedChangesEditor,
17987 window: &mut Window,
17988 cx: &mut Context<Self>,
17989 ) {
17990 let Some(workspace) = self.workspace() else {
17991 cx.propagate();
17992 return;
17993 };
17994
17995 let selections = self.selections.all::<usize>(cx);
17996 let multi_buffer = self.buffer.read(cx);
17997 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17998 let mut new_selections_by_buffer = HashMap::default();
17999 for selection in selections {
18000 for (buffer, range, _) in
18001 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18002 {
18003 let mut range = range.to_point(buffer);
18004 range.start.column = 0;
18005 range.end.column = buffer.line_len(range.end.row);
18006 new_selections_by_buffer
18007 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18008 .or_insert(Vec::new())
18009 .push(range)
18010 }
18011 }
18012
18013 let proposed_changes_buffers = new_selections_by_buffer
18014 .into_iter()
18015 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18016 .collect::<Vec<_>>();
18017 let proposed_changes_editor = cx.new(|cx| {
18018 ProposedChangesEditor::new(
18019 "Proposed changes",
18020 proposed_changes_buffers,
18021 self.project.clone(),
18022 window,
18023 cx,
18024 )
18025 });
18026
18027 window.defer(cx, move |window, cx| {
18028 workspace.update(cx, |workspace, cx| {
18029 workspace.active_pane().update(cx, |pane, cx| {
18030 pane.add_item(
18031 Box::new(proposed_changes_editor),
18032 true,
18033 true,
18034 None,
18035 window,
18036 cx,
18037 );
18038 });
18039 });
18040 });
18041 }
18042
18043 pub fn open_excerpts_in_split(
18044 &mut self,
18045 _: &OpenExcerptsSplit,
18046 window: &mut Window,
18047 cx: &mut Context<Self>,
18048 ) {
18049 self.open_excerpts_common(None, true, window, cx)
18050 }
18051
18052 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18053 self.open_excerpts_common(None, false, window, cx)
18054 }
18055
18056 fn open_excerpts_common(
18057 &mut self,
18058 jump_data: Option<JumpData>,
18059 split: bool,
18060 window: &mut Window,
18061 cx: &mut Context<Self>,
18062 ) {
18063 let Some(workspace) = self.workspace() else {
18064 cx.propagate();
18065 return;
18066 };
18067
18068 if self.buffer.read(cx).is_singleton() {
18069 cx.propagate();
18070 return;
18071 }
18072
18073 let mut new_selections_by_buffer = HashMap::default();
18074 match &jump_data {
18075 Some(JumpData::MultiBufferPoint {
18076 excerpt_id,
18077 position,
18078 anchor,
18079 line_offset_from_top,
18080 }) => {
18081 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18082 if let Some(buffer) = multi_buffer_snapshot
18083 .buffer_id_for_excerpt(*excerpt_id)
18084 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18085 {
18086 let buffer_snapshot = buffer.read(cx).snapshot();
18087 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18088 language::ToPoint::to_point(anchor, &buffer_snapshot)
18089 } else {
18090 buffer_snapshot.clip_point(*position, Bias::Left)
18091 };
18092 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18093 new_selections_by_buffer.insert(
18094 buffer,
18095 (
18096 vec![jump_to_offset..jump_to_offset],
18097 Some(*line_offset_from_top),
18098 ),
18099 );
18100 }
18101 }
18102 Some(JumpData::MultiBufferRow {
18103 row,
18104 line_offset_from_top,
18105 }) => {
18106 let point = MultiBufferPoint::new(row.0, 0);
18107 if let Some((buffer, buffer_point, _)) =
18108 self.buffer.read(cx).point_to_buffer_point(point, cx)
18109 {
18110 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18111 new_selections_by_buffer
18112 .entry(buffer)
18113 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18114 .0
18115 .push(buffer_offset..buffer_offset)
18116 }
18117 }
18118 None => {
18119 let selections = self.selections.all::<usize>(cx);
18120 let multi_buffer = self.buffer.read(cx);
18121 for selection in selections {
18122 for (snapshot, range, _, anchor) in multi_buffer
18123 .snapshot(cx)
18124 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18125 {
18126 if let Some(anchor) = anchor {
18127 // selection is in a deleted hunk
18128 let Some(buffer_id) = anchor.buffer_id else {
18129 continue;
18130 };
18131 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18132 continue;
18133 };
18134 let offset = text::ToOffset::to_offset(
18135 &anchor.text_anchor,
18136 &buffer_handle.read(cx).snapshot(),
18137 );
18138 let range = offset..offset;
18139 new_selections_by_buffer
18140 .entry(buffer_handle)
18141 .or_insert((Vec::new(), None))
18142 .0
18143 .push(range)
18144 } else {
18145 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18146 else {
18147 continue;
18148 };
18149 new_selections_by_buffer
18150 .entry(buffer_handle)
18151 .or_insert((Vec::new(), None))
18152 .0
18153 .push(range)
18154 }
18155 }
18156 }
18157 }
18158 }
18159
18160 new_selections_by_buffer
18161 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18162
18163 if new_selections_by_buffer.is_empty() {
18164 return;
18165 }
18166
18167 // We defer the pane interaction because we ourselves are a workspace item
18168 // and activating a new item causes the pane to call a method on us reentrantly,
18169 // which panics if we're on the stack.
18170 window.defer(cx, move |window, cx| {
18171 workspace.update(cx, |workspace, cx| {
18172 let pane = if split {
18173 workspace.adjacent_pane(window, cx)
18174 } else {
18175 workspace.active_pane().clone()
18176 };
18177
18178 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18179 let editor = buffer
18180 .read(cx)
18181 .file()
18182 .is_none()
18183 .then(|| {
18184 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18185 // so `workspace.open_project_item` will never find them, always opening a new editor.
18186 // Instead, we try to activate the existing editor in the pane first.
18187 let (editor, pane_item_index) =
18188 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18189 let editor = item.downcast::<Editor>()?;
18190 let singleton_buffer =
18191 editor.read(cx).buffer().read(cx).as_singleton()?;
18192 if singleton_buffer == buffer {
18193 Some((editor, i))
18194 } else {
18195 None
18196 }
18197 })?;
18198 pane.update(cx, |pane, cx| {
18199 pane.activate_item(pane_item_index, true, true, window, cx)
18200 });
18201 Some(editor)
18202 })
18203 .flatten()
18204 .unwrap_or_else(|| {
18205 workspace.open_project_item::<Self>(
18206 pane.clone(),
18207 buffer,
18208 true,
18209 true,
18210 window,
18211 cx,
18212 )
18213 });
18214
18215 editor.update(cx, |editor, cx| {
18216 let autoscroll = match scroll_offset {
18217 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18218 None => Autoscroll::newest(),
18219 };
18220 let nav_history = editor.nav_history.take();
18221 editor.change_selections(Some(autoscroll), window, cx, |s| {
18222 s.select_ranges(ranges);
18223 });
18224 editor.nav_history = nav_history;
18225 });
18226 }
18227 })
18228 });
18229 }
18230
18231 // For now, don't allow opening excerpts in buffers that aren't backed by
18232 // regular project files.
18233 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18234 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18235 }
18236
18237 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18238 let snapshot = self.buffer.read(cx).read(cx);
18239 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18240 Some(
18241 ranges
18242 .iter()
18243 .map(move |range| {
18244 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18245 })
18246 .collect(),
18247 )
18248 }
18249
18250 fn selection_replacement_ranges(
18251 &self,
18252 range: Range<OffsetUtf16>,
18253 cx: &mut App,
18254 ) -> Vec<Range<OffsetUtf16>> {
18255 let selections = self.selections.all::<OffsetUtf16>(cx);
18256 let newest_selection = selections
18257 .iter()
18258 .max_by_key(|selection| selection.id)
18259 .unwrap();
18260 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18261 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18262 let snapshot = self.buffer.read(cx).read(cx);
18263 selections
18264 .into_iter()
18265 .map(|mut selection| {
18266 selection.start.0 =
18267 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18268 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18269 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18270 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18271 })
18272 .collect()
18273 }
18274
18275 fn report_editor_event(
18276 &self,
18277 event_type: &'static str,
18278 file_extension: Option<String>,
18279 cx: &App,
18280 ) {
18281 if cfg!(any(test, feature = "test-support")) {
18282 return;
18283 }
18284
18285 let Some(project) = &self.project else { return };
18286
18287 // If None, we are in a file without an extension
18288 let file = self
18289 .buffer
18290 .read(cx)
18291 .as_singleton()
18292 .and_then(|b| b.read(cx).file());
18293 let file_extension = file_extension.or(file
18294 .as_ref()
18295 .and_then(|file| Path::new(file.file_name(cx)).extension())
18296 .and_then(|e| e.to_str())
18297 .map(|a| a.to_string()));
18298
18299 let vim_mode = vim_enabled(cx);
18300
18301 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18302 let copilot_enabled = edit_predictions_provider
18303 == language::language_settings::EditPredictionProvider::Copilot;
18304 let copilot_enabled_for_language = self
18305 .buffer
18306 .read(cx)
18307 .language_settings(cx)
18308 .show_edit_predictions;
18309
18310 let project = project.read(cx);
18311 telemetry::event!(
18312 event_type,
18313 file_extension,
18314 vim_mode,
18315 copilot_enabled,
18316 copilot_enabled_for_language,
18317 edit_predictions_provider,
18318 is_via_ssh = project.is_via_ssh(),
18319 );
18320 }
18321
18322 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18323 /// with each line being an array of {text, highlight} objects.
18324 fn copy_highlight_json(
18325 &mut self,
18326 _: &CopyHighlightJson,
18327 window: &mut Window,
18328 cx: &mut Context<Self>,
18329 ) {
18330 #[derive(Serialize)]
18331 struct Chunk<'a> {
18332 text: String,
18333 highlight: Option<&'a str>,
18334 }
18335
18336 let snapshot = self.buffer.read(cx).snapshot(cx);
18337 let range = self
18338 .selected_text_range(false, window, cx)
18339 .and_then(|selection| {
18340 if selection.range.is_empty() {
18341 None
18342 } else {
18343 Some(selection.range)
18344 }
18345 })
18346 .unwrap_or_else(|| 0..snapshot.len());
18347
18348 let chunks = snapshot.chunks(range, true);
18349 let mut lines = Vec::new();
18350 let mut line: VecDeque<Chunk> = VecDeque::new();
18351
18352 let Some(style) = self.style.as_ref() else {
18353 return;
18354 };
18355
18356 for chunk in chunks {
18357 let highlight = chunk
18358 .syntax_highlight_id
18359 .and_then(|id| id.name(&style.syntax));
18360 let mut chunk_lines = chunk.text.split('\n').peekable();
18361 while let Some(text) = chunk_lines.next() {
18362 let mut merged_with_last_token = false;
18363 if let Some(last_token) = line.back_mut() {
18364 if last_token.highlight == highlight {
18365 last_token.text.push_str(text);
18366 merged_with_last_token = true;
18367 }
18368 }
18369
18370 if !merged_with_last_token {
18371 line.push_back(Chunk {
18372 text: text.into(),
18373 highlight,
18374 });
18375 }
18376
18377 if chunk_lines.peek().is_some() {
18378 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18379 line.pop_front();
18380 }
18381 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18382 line.pop_back();
18383 }
18384
18385 lines.push(mem::take(&mut line));
18386 }
18387 }
18388 }
18389
18390 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18391 return;
18392 };
18393 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18394 }
18395
18396 pub fn open_context_menu(
18397 &mut self,
18398 _: &OpenContextMenu,
18399 window: &mut Window,
18400 cx: &mut Context<Self>,
18401 ) {
18402 self.request_autoscroll(Autoscroll::newest(), cx);
18403 let position = self.selections.newest_display(cx).start;
18404 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18405 }
18406
18407 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18408 &self.inlay_hint_cache
18409 }
18410
18411 pub fn replay_insert_event(
18412 &mut self,
18413 text: &str,
18414 relative_utf16_range: Option<Range<isize>>,
18415 window: &mut Window,
18416 cx: &mut Context<Self>,
18417 ) {
18418 if !self.input_enabled {
18419 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18420 return;
18421 }
18422 if let Some(relative_utf16_range) = relative_utf16_range {
18423 let selections = self.selections.all::<OffsetUtf16>(cx);
18424 self.change_selections(None, window, cx, |s| {
18425 let new_ranges = selections.into_iter().map(|range| {
18426 let start = OffsetUtf16(
18427 range
18428 .head()
18429 .0
18430 .saturating_add_signed(relative_utf16_range.start),
18431 );
18432 let end = OffsetUtf16(
18433 range
18434 .head()
18435 .0
18436 .saturating_add_signed(relative_utf16_range.end),
18437 );
18438 start..end
18439 });
18440 s.select_ranges(new_ranges);
18441 });
18442 }
18443
18444 self.handle_input(text, window, cx);
18445 }
18446
18447 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18448 let Some(provider) = self.semantics_provider.as_ref() else {
18449 return false;
18450 };
18451
18452 let mut supports = false;
18453 self.buffer().update(cx, |this, cx| {
18454 this.for_each_buffer(|buffer| {
18455 supports |= provider.supports_inlay_hints(buffer, cx);
18456 });
18457 });
18458
18459 supports
18460 }
18461
18462 pub fn is_focused(&self, window: &Window) -> bool {
18463 self.focus_handle.is_focused(window)
18464 }
18465
18466 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18467 cx.emit(EditorEvent::Focused);
18468
18469 if let Some(descendant) = self
18470 .last_focused_descendant
18471 .take()
18472 .and_then(|descendant| descendant.upgrade())
18473 {
18474 window.focus(&descendant);
18475 } else {
18476 if let Some(blame) = self.blame.as_ref() {
18477 blame.update(cx, GitBlame::focus)
18478 }
18479
18480 self.blink_manager.update(cx, BlinkManager::enable);
18481 self.show_cursor_names(window, cx);
18482 self.buffer.update(cx, |buffer, cx| {
18483 buffer.finalize_last_transaction(cx);
18484 if self.leader_id.is_none() {
18485 buffer.set_active_selections(
18486 &self.selections.disjoint_anchors(),
18487 self.selections.line_mode,
18488 self.cursor_shape,
18489 cx,
18490 );
18491 }
18492 });
18493 }
18494 }
18495
18496 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18497 cx.emit(EditorEvent::FocusedIn)
18498 }
18499
18500 fn handle_focus_out(
18501 &mut self,
18502 event: FocusOutEvent,
18503 _window: &mut Window,
18504 cx: &mut Context<Self>,
18505 ) {
18506 if event.blurred != self.focus_handle {
18507 self.last_focused_descendant = Some(event.blurred);
18508 }
18509 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18510 }
18511
18512 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18513 self.blink_manager.update(cx, BlinkManager::disable);
18514 self.buffer
18515 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18516
18517 if let Some(blame) = self.blame.as_ref() {
18518 blame.update(cx, GitBlame::blur)
18519 }
18520 if !self.hover_state.focused(window, cx) {
18521 hide_hover(self, cx);
18522 }
18523 if !self
18524 .context_menu
18525 .borrow()
18526 .as_ref()
18527 .is_some_and(|context_menu| context_menu.focused(window, cx))
18528 {
18529 self.hide_context_menu(window, cx);
18530 }
18531 self.discard_inline_completion(false, cx);
18532 cx.emit(EditorEvent::Blurred);
18533 cx.notify();
18534 }
18535
18536 pub fn register_action<A: Action>(
18537 &mut self,
18538 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18539 ) -> Subscription {
18540 let id = self.next_editor_action_id.post_inc();
18541 let listener = Arc::new(listener);
18542 self.editor_actions.borrow_mut().insert(
18543 id,
18544 Box::new(move |window, _| {
18545 let listener = listener.clone();
18546 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18547 let action = action.downcast_ref().unwrap();
18548 if phase == DispatchPhase::Bubble {
18549 listener(action, window, cx)
18550 }
18551 })
18552 }),
18553 );
18554
18555 let editor_actions = self.editor_actions.clone();
18556 Subscription::new(move || {
18557 editor_actions.borrow_mut().remove(&id);
18558 })
18559 }
18560
18561 pub fn file_header_size(&self) -> u32 {
18562 FILE_HEADER_HEIGHT
18563 }
18564
18565 pub fn restore(
18566 &mut self,
18567 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18568 window: &mut Window,
18569 cx: &mut Context<Self>,
18570 ) {
18571 let workspace = self.workspace();
18572 let project = self.project.as_ref();
18573 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18574 let mut tasks = Vec::new();
18575 for (buffer_id, changes) in revert_changes {
18576 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18577 buffer.update(cx, |buffer, cx| {
18578 buffer.edit(
18579 changes
18580 .into_iter()
18581 .map(|(range, text)| (range, text.to_string())),
18582 None,
18583 cx,
18584 );
18585 });
18586
18587 if let Some(project) =
18588 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18589 {
18590 project.update(cx, |project, cx| {
18591 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18592 })
18593 }
18594 }
18595 }
18596 tasks
18597 });
18598 cx.spawn_in(window, async move |_, cx| {
18599 for (buffer, task) in save_tasks {
18600 let result = task.await;
18601 if result.is_err() {
18602 let Some(path) = buffer
18603 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18604 .ok()
18605 else {
18606 continue;
18607 };
18608 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18609 let Some(task) = cx
18610 .update_window_entity(&workspace, |workspace, window, cx| {
18611 workspace
18612 .open_path_preview(path, None, false, false, false, window, cx)
18613 })
18614 .ok()
18615 else {
18616 continue;
18617 };
18618 task.await.log_err();
18619 }
18620 }
18621 }
18622 })
18623 .detach();
18624 self.change_selections(None, window, cx, |selections| selections.refresh());
18625 }
18626
18627 pub fn to_pixel_point(
18628 &self,
18629 source: multi_buffer::Anchor,
18630 editor_snapshot: &EditorSnapshot,
18631 window: &mut Window,
18632 ) -> Option<gpui::Point<Pixels>> {
18633 let source_point = source.to_display_point(editor_snapshot);
18634 self.display_to_pixel_point(source_point, editor_snapshot, window)
18635 }
18636
18637 pub fn display_to_pixel_point(
18638 &self,
18639 source: DisplayPoint,
18640 editor_snapshot: &EditorSnapshot,
18641 window: &mut Window,
18642 ) -> Option<gpui::Point<Pixels>> {
18643 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18644 let text_layout_details = self.text_layout_details(window);
18645 let scroll_top = text_layout_details
18646 .scroll_anchor
18647 .scroll_position(editor_snapshot)
18648 .y;
18649
18650 if source.row().as_f32() < scroll_top.floor() {
18651 return None;
18652 }
18653 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18654 let source_y = line_height * (source.row().as_f32() - scroll_top);
18655 Some(gpui::Point::new(source_x, source_y))
18656 }
18657
18658 pub fn has_visible_completions_menu(&self) -> bool {
18659 !self.edit_prediction_preview_is_active()
18660 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18661 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18662 })
18663 }
18664
18665 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18666 self.addons
18667 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18668 }
18669
18670 pub fn unregister_addon<T: Addon>(&mut self) {
18671 self.addons.remove(&std::any::TypeId::of::<T>());
18672 }
18673
18674 pub fn addon<T: Addon>(&self) -> Option<&T> {
18675 let type_id = std::any::TypeId::of::<T>();
18676 self.addons
18677 .get(&type_id)
18678 .and_then(|item| item.to_any().downcast_ref::<T>())
18679 }
18680
18681 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18682 let type_id = std::any::TypeId::of::<T>();
18683 self.addons
18684 .get_mut(&type_id)
18685 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18686 }
18687
18688 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18689 let text_layout_details = self.text_layout_details(window);
18690 let style = &text_layout_details.editor_style;
18691 let font_id = window.text_system().resolve_font(&style.text.font());
18692 let font_size = style.text.font_size.to_pixels(window.rem_size());
18693 let line_height = style.text.line_height_in_pixels(window.rem_size());
18694 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18695
18696 gpui::Size::new(em_width, line_height)
18697 }
18698
18699 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18700 self.load_diff_task.clone()
18701 }
18702
18703 fn read_metadata_from_db(
18704 &mut self,
18705 item_id: u64,
18706 workspace_id: WorkspaceId,
18707 window: &mut Window,
18708 cx: &mut Context<Editor>,
18709 ) {
18710 if self.is_singleton(cx)
18711 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18712 {
18713 let buffer_snapshot = OnceCell::new();
18714
18715 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18716 if !folds.is_empty() {
18717 let snapshot =
18718 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18719 self.fold_ranges(
18720 folds
18721 .into_iter()
18722 .map(|(start, end)| {
18723 snapshot.clip_offset(start, Bias::Left)
18724 ..snapshot.clip_offset(end, Bias::Right)
18725 })
18726 .collect(),
18727 false,
18728 window,
18729 cx,
18730 );
18731 }
18732 }
18733
18734 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18735 if !selections.is_empty() {
18736 let snapshot =
18737 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18738 self.change_selections(None, window, cx, |s| {
18739 s.select_ranges(selections.into_iter().map(|(start, end)| {
18740 snapshot.clip_offset(start, Bias::Left)
18741 ..snapshot.clip_offset(end, Bias::Right)
18742 }));
18743 });
18744 }
18745 };
18746 }
18747
18748 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18749 }
18750}
18751
18752fn vim_enabled(cx: &App) -> bool {
18753 cx.global::<SettingsStore>()
18754 .raw_user_settings()
18755 .get("vim_mode")
18756 == Some(&serde_json::Value::Bool(true))
18757}
18758
18759// Consider user intent and default settings
18760fn choose_completion_range(
18761 completion: &Completion,
18762 intent: CompletionIntent,
18763 buffer: &Entity<Buffer>,
18764 cx: &mut Context<Editor>,
18765) -> Range<usize> {
18766 fn should_replace(
18767 completion: &Completion,
18768 insert_range: &Range<text::Anchor>,
18769 intent: CompletionIntent,
18770 completion_mode_setting: LspInsertMode,
18771 buffer: &Buffer,
18772 ) -> bool {
18773 // specific actions take precedence over settings
18774 match intent {
18775 CompletionIntent::CompleteWithInsert => return false,
18776 CompletionIntent::CompleteWithReplace => return true,
18777 CompletionIntent::Complete | CompletionIntent::Compose => {}
18778 }
18779
18780 match completion_mode_setting {
18781 LspInsertMode::Insert => false,
18782 LspInsertMode::Replace => true,
18783 LspInsertMode::ReplaceSubsequence => {
18784 let mut text_to_replace = buffer.chars_for_range(
18785 buffer.anchor_before(completion.replace_range.start)
18786 ..buffer.anchor_after(completion.replace_range.end),
18787 );
18788 let mut completion_text = completion.new_text.chars();
18789
18790 // is `text_to_replace` a subsequence of `completion_text`
18791 text_to_replace
18792 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18793 }
18794 LspInsertMode::ReplaceSuffix => {
18795 let range_after_cursor = insert_range.end..completion.replace_range.end;
18796
18797 let text_after_cursor = buffer
18798 .text_for_range(
18799 buffer.anchor_before(range_after_cursor.start)
18800 ..buffer.anchor_after(range_after_cursor.end),
18801 )
18802 .collect::<String>();
18803 completion.new_text.ends_with(&text_after_cursor)
18804 }
18805 }
18806 }
18807
18808 let buffer = buffer.read(cx);
18809
18810 if let CompletionSource::Lsp {
18811 insert_range: Some(insert_range),
18812 ..
18813 } = &completion.source
18814 {
18815 let completion_mode_setting =
18816 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18817 .completions
18818 .lsp_insert_mode;
18819
18820 if !should_replace(
18821 completion,
18822 &insert_range,
18823 intent,
18824 completion_mode_setting,
18825 buffer,
18826 ) {
18827 return insert_range.to_offset(buffer);
18828 }
18829 }
18830
18831 completion.replace_range.to_offset(buffer)
18832}
18833
18834fn insert_extra_newline_brackets(
18835 buffer: &MultiBufferSnapshot,
18836 range: Range<usize>,
18837 language: &language::LanguageScope,
18838) -> bool {
18839 let leading_whitespace_len = buffer
18840 .reversed_chars_at(range.start)
18841 .take_while(|c| c.is_whitespace() && *c != '\n')
18842 .map(|c| c.len_utf8())
18843 .sum::<usize>();
18844 let trailing_whitespace_len = buffer
18845 .chars_at(range.end)
18846 .take_while(|c| c.is_whitespace() && *c != '\n')
18847 .map(|c| c.len_utf8())
18848 .sum::<usize>();
18849 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18850
18851 language.brackets().any(|(pair, enabled)| {
18852 let pair_start = pair.start.trim_end();
18853 let pair_end = pair.end.trim_start();
18854
18855 enabled
18856 && pair.newline
18857 && buffer.contains_str_at(range.end, pair_end)
18858 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18859 })
18860}
18861
18862fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18863 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18864 [(buffer, range, _)] => (*buffer, range.clone()),
18865 _ => return false,
18866 };
18867 let pair = {
18868 let mut result: Option<BracketMatch> = None;
18869
18870 for pair in buffer
18871 .all_bracket_ranges(range.clone())
18872 .filter(move |pair| {
18873 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18874 })
18875 {
18876 let len = pair.close_range.end - pair.open_range.start;
18877
18878 if let Some(existing) = &result {
18879 let existing_len = existing.close_range.end - existing.open_range.start;
18880 if len > existing_len {
18881 continue;
18882 }
18883 }
18884
18885 result = Some(pair);
18886 }
18887
18888 result
18889 };
18890 let Some(pair) = pair else {
18891 return false;
18892 };
18893 pair.newline_only
18894 && buffer
18895 .chars_for_range(pair.open_range.end..range.start)
18896 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18897 .all(|c| c.is_whitespace() && c != '\n')
18898}
18899
18900fn update_uncommitted_diff_for_buffer(
18901 editor: Entity<Editor>,
18902 project: &Entity<Project>,
18903 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18904 buffer: Entity<MultiBuffer>,
18905 cx: &mut App,
18906) -> Task<()> {
18907 let mut tasks = Vec::new();
18908 project.update(cx, |project, cx| {
18909 for buffer in buffers {
18910 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18911 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18912 }
18913 }
18914 });
18915 cx.spawn(async move |cx| {
18916 let diffs = future::join_all(tasks).await;
18917 if editor
18918 .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18919 .unwrap_or(false)
18920 {
18921 return;
18922 }
18923
18924 buffer
18925 .update(cx, |buffer, cx| {
18926 for diff in diffs.into_iter().flatten() {
18927 buffer.add_diff(diff, cx);
18928 }
18929 })
18930 .ok();
18931 })
18932}
18933
18934fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18935 let tab_size = tab_size.get() as usize;
18936 let mut width = offset;
18937
18938 for ch in text.chars() {
18939 width += if ch == '\t' {
18940 tab_size - (width % tab_size)
18941 } else {
18942 1
18943 };
18944 }
18945
18946 width - offset
18947}
18948
18949#[cfg(test)]
18950mod tests {
18951 use super::*;
18952
18953 #[test]
18954 fn test_string_size_with_expanded_tabs() {
18955 let nz = |val| NonZeroU32::new(val).unwrap();
18956 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18957 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18958 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18959 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18960 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18961 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18962 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18963 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18964 }
18965}
18966
18967/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18968struct WordBreakingTokenizer<'a> {
18969 input: &'a str,
18970}
18971
18972impl<'a> WordBreakingTokenizer<'a> {
18973 fn new(input: &'a str) -> Self {
18974 Self { input }
18975 }
18976}
18977
18978fn is_char_ideographic(ch: char) -> bool {
18979 use unicode_script::Script::*;
18980 use unicode_script::UnicodeScript;
18981 matches!(ch.script(), Han | Tangut | Yi)
18982}
18983
18984fn is_grapheme_ideographic(text: &str) -> bool {
18985 text.chars().any(is_char_ideographic)
18986}
18987
18988fn is_grapheme_whitespace(text: &str) -> bool {
18989 text.chars().any(|x| x.is_whitespace())
18990}
18991
18992fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18993 text.chars().next().map_or(false, |ch| {
18994 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18995 })
18996}
18997
18998#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18999enum WordBreakToken<'a> {
19000 Word { token: &'a str, grapheme_len: usize },
19001 InlineWhitespace { token: &'a str, grapheme_len: usize },
19002 Newline,
19003}
19004
19005impl<'a> Iterator for WordBreakingTokenizer<'a> {
19006 /// Yields a span, the count of graphemes in the token, and whether it was
19007 /// whitespace. Note that it also breaks at word boundaries.
19008 type Item = WordBreakToken<'a>;
19009
19010 fn next(&mut self) -> Option<Self::Item> {
19011 use unicode_segmentation::UnicodeSegmentation;
19012 if self.input.is_empty() {
19013 return None;
19014 }
19015
19016 let mut iter = self.input.graphemes(true).peekable();
19017 let mut offset = 0;
19018 let mut grapheme_len = 0;
19019 if let Some(first_grapheme) = iter.next() {
19020 let is_newline = first_grapheme == "\n";
19021 let is_whitespace = is_grapheme_whitespace(first_grapheme);
19022 offset += first_grapheme.len();
19023 grapheme_len += 1;
19024 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19025 if let Some(grapheme) = iter.peek().copied() {
19026 if should_stay_with_preceding_ideograph(grapheme) {
19027 offset += grapheme.len();
19028 grapheme_len += 1;
19029 }
19030 }
19031 } else {
19032 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19033 let mut next_word_bound = words.peek().copied();
19034 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19035 next_word_bound = words.next();
19036 }
19037 while let Some(grapheme) = iter.peek().copied() {
19038 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19039 break;
19040 };
19041 if is_grapheme_whitespace(grapheme) != is_whitespace
19042 || (grapheme == "\n") != is_newline
19043 {
19044 break;
19045 };
19046 offset += grapheme.len();
19047 grapheme_len += 1;
19048 iter.next();
19049 }
19050 }
19051 let token = &self.input[..offset];
19052 self.input = &self.input[offset..];
19053 if token == "\n" {
19054 Some(WordBreakToken::Newline)
19055 } else if is_whitespace {
19056 Some(WordBreakToken::InlineWhitespace {
19057 token,
19058 grapheme_len,
19059 })
19060 } else {
19061 Some(WordBreakToken::Word {
19062 token,
19063 grapheme_len,
19064 })
19065 }
19066 } else {
19067 None
19068 }
19069 }
19070}
19071
19072#[test]
19073fn test_word_breaking_tokenizer() {
19074 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19075 ("", &[]),
19076 (" ", &[whitespace(" ", 2)]),
19077 ("Ʒ", &[word("Ʒ", 1)]),
19078 ("Ǽ", &[word("Ǽ", 1)]),
19079 ("⋑", &[word("⋑", 1)]),
19080 ("⋑⋑", &[word("⋑⋑", 2)]),
19081 (
19082 "原理,进而",
19083 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19084 ),
19085 (
19086 "hello world",
19087 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19088 ),
19089 (
19090 "hello, world",
19091 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19092 ),
19093 (
19094 " hello world",
19095 &[
19096 whitespace(" ", 2),
19097 word("hello", 5),
19098 whitespace(" ", 1),
19099 word("world", 5),
19100 ],
19101 ),
19102 (
19103 "这是什么 \n 钢笔",
19104 &[
19105 word("这", 1),
19106 word("是", 1),
19107 word("什", 1),
19108 word("么", 1),
19109 whitespace(" ", 1),
19110 newline(),
19111 whitespace(" ", 1),
19112 word("钢", 1),
19113 word("笔", 1),
19114 ],
19115 ),
19116 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19117 ];
19118
19119 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19120 WordBreakToken::Word {
19121 token,
19122 grapheme_len,
19123 }
19124 }
19125
19126 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19127 WordBreakToken::InlineWhitespace {
19128 token,
19129 grapheme_len,
19130 }
19131 }
19132
19133 fn newline() -> WordBreakToken<'static> {
19134 WordBreakToken::Newline
19135 }
19136
19137 for (input, result) in tests {
19138 assert_eq!(
19139 WordBreakingTokenizer::new(input)
19140 .collect::<Vec<_>>()
19141 .as_slice(),
19142 *result,
19143 );
19144 }
19145}
19146
19147fn wrap_with_prefix(
19148 line_prefix: String,
19149 unwrapped_text: String,
19150 wrap_column: usize,
19151 tab_size: NonZeroU32,
19152 preserve_existing_whitespace: bool,
19153) -> String {
19154 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19155 let mut wrapped_text = String::new();
19156 let mut current_line = line_prefix.clone();
19157
19158 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19159 let mut current_line_len = line_prefix_len;
19160 let mut in_whitespace = false;
19161 for token in tokenizer {
19162 let have_preceding_whitespace = in_whitespace;
19163 match token {
19164 WordBreakToken::Word {
19165 token,
19166 grapheme_len,
19167 } => {
19168 in_whitespace = false;
19169 if current_line_len + grapheme_len > wrap_column
19170 && current_line_len != line_prefix_len
19171 {
19172 wrapped_text.push_str(current_line.trim_end());
19173 wrapped_text.push('\n');
19174 current_line.truncate(line_prefix.len());
19175 current_line_len = line_prefix_len;
19176 }
19177 current_line.push_str(token);
19178 current_line_len += grapheme_len;
19179 }
19180 WordBreakToken::InlineWhitespace {
19181 mut token,
19182 mut grapheme_len,
19183 } => {
19184 in_whitespace = true;
19185 if have_preceding_whitespace && !preserve_existing_whitespace {
19186 continue;
19187 }
19188 if !preserve_existing_whitespace {
19189 token = " ";
19190 grapheme_len = 1;
19191 }
19192 if current_line_len + grapheme_len > wrap_column {
19193 wrapped_text.push_str(current_line.trim_end());
19194 wrapped_text.push('\n');
19195 current_line.truncate(line_prefix.len());
19196 current_line_len = line_prefix_len;
19197 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19198 current_line.push_str(token);
19199 current_line_len += grapheme_len;
19200 }
19201 }
19202 WordBreakToken::Newline => {
19203 in_whitespace = true;
19204 if preserve_existing_whitespace {
19205 wrapped_text.push_str(current_line.trim_end());
19206 wrapped_text.push('\n');
19207 current_line.truncate(line_prefix.len());
19208 current_line_len = line_prefix_len;
19209 } else if have_preceding_whitespace {
19210 continue;
19211 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19212 {
19213 wrapped_text.push_str(current_line.trim_end());
19214 wrapped_text.push('\n');
19215 current_line.truncate(line_prefix.len());
19216 current_line_len = line_prefix_len;
19217 } else if current_line_len != line_prefix_len {
19218 current_line.push(' ');
19219 current_line_len += 1;
19220 }
19221 }
19222 }
19223 }
19224
19225 if !current_line.is_empty() {
19226 wrapped_text.push_str(¤t_line);
19227 }
19228 wrapped_text
19229}
19230
19231#[test]
19232fn test_wrap_with_prefix() {
19233 assert_eq!(
19234 wrap_with_prefix(
19235 "# ".to_string(),
19236 "abcdefg".to_string(),
19237 4,
19238 NonZeroU32::new(4).unwrap(),
19239 false,
19240 ),
19241 "# abcdefg"
19242 );
19243 assert_eq!(
19244 wrap_with_prefix(
19245 "".to_string(),
19246 "\thello world".to_string(),
19247 8,
19248 NonZeroU32::new(4).unwrap(),
19249 false,
19250 ),
19251 "hello\nworld"
19252 );
19253 assert_eq!(
19254 wrap_with_prefix(
19255 "// ".to_string(),
19256 "xx \nyy zz aa bb cc".to_string(),
19257 12,
19258 NonZeroU32::new(4).unwrap(),
19259 false,
19260 ),
19261 "// xx yy zz\n// aa bb cc"
19262 );
19263 assert_eq!(
19264 wrap_with_prefix(
19265 String::new(),
19266 "这是什么 \n 钢笔".to_string(),
19267 3,
19268 NonZeroU32::new(4).unwrap(),
19269 false,
19270 ),
19271 "这是什\n么 钢\n笔"
19272 );
19273}
19274
19275pub trait CollaborationHub {
19276 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19277 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19278 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19279}
19280
19281impl CollaborationHub for Entity<Project> {
19282 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19283 self.read(cx).collaborators()
19284 }
19285
19286 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19287 self.read(cx).user_store().read(cx).participant_indices()
19288 }
19289
19290 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19291 let this = self.read(cx);
19292 let user_ids = this.collaborators().values().map(|c| c.user_id);
19293 this.user_store().read_with(cx, |user_store, cx| {
19294 user_store.participant_names(user_ids, cx)
19295 })
19296 }
19297}
19298
19299pub trait SemanticsProvider {
19300 fn hover(
19301 &self,
19302 buffer: &Entity<Buffer>,
19303 position: text::Anchor,
19304 cx: &mut App,
19305 ) -> Option<Task<Vec<project::Hover>>>;
19306
19307 fn inline_values(
19308 &self,
19309 buffer_handle: Entity<Buffer>,
19310 range: Range<text::Anchor>,
19311 cx: &mut App,
19312 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19313
19314 fn inlay_hints(
19315 &self,
19316 buffer_handle: Entity<Buffer>,
19317 range: Range<text::Anchor>,
19318 cx: &mut App,
19319 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19320
19321 fn resolve_inlay_hint(
19322 &self,
19323 hint: InlayHint,
19324 buffer_handle: Entity<Buffer>,
19325 server_id: LanguageServerId,
19326 cx: &mut App,
19327 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19328
19329 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19330
19331 fn document_highlights(
19332 &self,
19333 buffer: &Entity<Buffer>,
19334 position: text::Anchor,
19335 cx: &mut App,
19336 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19337
19338 fn definitions(
19339 &self,
19340 buffer: &Entity<Buffer>,
19341 position: text::Anchor,
19342 kind: GotoDefinitionKind,
19343 cx: &mut App,
19344 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19345
19346 fn range_for_rename(
19347 &self,
19348 buffer: &Entity<Buffer>,
19349 position: text::Anchor,
19350 cx: &mut App,
19351 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19352
19353 fn perform_rename(
19354 &self,
19355 buffer: &Entity<Buffer>,
19356 position: text::Anchor,
19357 new_name: String,
19358 cx: &mut App,
19359 ) -> Option<Task<Result<ProjectTransaction>>>;
19360}
19361
19362pub trait CompletionProvider {
19363 fn completions(
19364 &self,
19365 excerpt_id: ExcerptId,
19366 buffer: &Entity<Buffer>,
19367 buffer_position: text::Anchor,
19368 trigger: CompletionContext,
19369 window: &mut Window,
19370 cx: &mut Context<Editor>,
19371 ) -> Task<Result<Option<Vec<Completion>>>>;
19372
19373 fn resolve_completions(
19374 &self,
19375 buffer: Entity<Buffer>,
19376 completion_indices: Vec<usize>,
19377 completions: Rc<RefCell<Box<[Completion]>>>,
19378 cx: &mut Context<Editor>,
19379 ) -> Task<Result<bool>>;
19380
19381 fn apply_additional_edits_for_completion(
19382 &self,
19383 _buffer: Entity<Buffer>,
19384 _completions: Rc<RefCell<Box<[Completion]>>>,
19385 _completion_index: usize,
19386 _push_to_history: bool,
19387 _cx: &mut Context<Editor>,
19388 ) -> Task<Result<Option<language::Transaction>>> {
19389 Task::ready(Ok(None))
19390 }
19391
19392 fn is_completion_trigger(
19393 &self,
19394 buffer: &Entity<Buffer>,
19395 position: language::Anchor,
19396 text: &str,
19397 trigger_in_words: bool,
19398 cx: &mut Context<Editor>,
19399 ) -> bool;
19400
19401 fn sort_completions(&self) -> bool {
19402 true
19403 }
19404
19405 fn filter_completions(&self) -> bool {
19406 true
19407 }
19408}
19409
19410pub trait CodeActionProvider {
19411 fn id(&self) -> Arc<str>;
19412
19413 fn code_actions(
19414 &self,
19415 buffer: &Entity<Buffer>,
19416 range: Range<text::Anchor>,
19417 window: &mut Window,
19418 cx: &mut App,
19419 ) -> Task<Result<Vec<CodeAction>>>;
19420
19421 fn apply_code_action(
19422 &self,
19423 buffer_handle: Entity<Buffer>,
19424 action: CodeAction,
19425 excerpt_id: ExcerptId,
19426 push_to_history: bool,
19427 window: &mut Window,
19428 cx: &mut App,
19429 ) -> Task<Result<ProjectTransaction>>;
19430}
19431
19432impl CodeActionProvider for Entity<Project> {
19433 fn id(&self) -> Arc<str> {
19434 "project".into()
19435 }
19436
19437 fn code_actions(
19438 &self,
19439 buffer: &Entity<Buffer>,
19440 range: Range<text::Anchor>,
19441 _window: &mut Window,
19442 cx: &mut App,
19443 ) -> Task<Result<Vec<CodeAction>>> {
19444 self.update(cx, |project, cx| {
19445 let code_lens = project.code_lens(buffer, range.clone(), cx);
19446 let code_actions = project.code_actions(buffer, range, None, cx);
19447 cx.background_spawn(async move {
19448 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19449 Ok(code_lens
19450 .context("code lens fetch")?
19451 .into_iter()
19452 .chain(code_actions.context("code action fetch")?)
19453 .collect())
19454 })
19455 })
19456 }
19457
19458 fn apply_code_action(
19459 &self,
19460 buffer_handle: Entity<Buffer>,
19461 action: CodeAction,
19462 _excerpt_id: ExcerptId,
19463 push_to_history: bool,
19464 _window: &mut Window,
19465 cx: &mut App,
19466 ) -> Task<Result<ProjectTransaction>> {
19467 self.update(cx, |project, cx| {
19468 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19469 })
19470 }
19471}
19472
19473fn snippet_completions(
19474 project: &Project,
19475 buffer: &Entity<Buffer>,
19476 buffer_position: text::Anchor,
19477 cx: &mut App,
19478) -> Task<Result<Vec<Completion>>> {
19479 let languages = buffer.read(cx).languages_at(buffer_position);
19480 let snippet_store = project.snippets().read(cx);
19481
19482 let scopes: Vec<_> = languages
19483 .iter()
19484 .filter_map(|language| {
19485 let language_name = language.lsp_id();
19486 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19487
19488 if snippets.is_empty() {
19489 None
19490 } else {
19491 Some((language.default_scope(), snippets))
19492 }
19493 })
19494 .collect();
19495
19496 if scopes.is_empty() {
19497 return Task::ready(Ok(vec![]));
19498 }
19499
19500 let snapshot = buffer.read(cx).text_snapshot();
19501 let chars: String = snapshot
19502 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19503 .collect();
19504 let executor = cx.background_executor().clone();
19505
19506 cx.background_spawn(async move {
19507 let mut all_results: Vec<Completion> = Vec::new();
19508 for (scope, snippets) in scopes.into_iter() {
19509 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19510 let mut last_word = chars
19511 .chars()
19512 .take_while(|c| classifier.is_word(*c))
19513 .collect::<String>();
19514 last_word = last_word.chars().rev().collect();
19515
19516 if last_word.is_empty() {
19517 return Ok(vec![]);
19518 }
19519
19520 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19521 let to_lsp = |point: &text::Anchor| {
19522 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19523 point_to_lsp(end)
19524 };
19525 let lsp_end = to_lsp(&buffer_position);
19526
19527 let candidates = snippets
19528 .iter()
19529 .enumerate()
19530 .flat_map(|(ix, snippet)| {
19531 snippet
19532 .prefix
19533 .iter()
19534 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19535 })
19536 .collect::<Vec<StringMatchCandidate>>();
19537
19538 let mut matches = fuzzy::match_strings(
19539 &candidates,
19540 &last_word,
19541 last_word.chars().any(|c| c.is_uppercase()),
19542 100,
19543 &Default::default(),
19544 executor.clone(),
19545 )
19546 .await;
19547
19548 // Remove all candidates where the query's start does not match the start of any word in the candidate
19549 if let Some(query_start) = last_word.chars().next() {
19550 matches.retain(|string_match| {
19551 split_words(&string_match.string).any(|word| {
19552 // Check that the first codepoint of the word as lowercase matches the first
19553 // codepoint of the query as lowercase
19554 word.chars()
19555 .flat_map(|codepoint| codepoint.to_lowercase())
19556 .zip(query_start.to_lowercase())
19557 .all(|(word_cp, query_cp)| word_cp == query_cp)
19558 })
19559 });
19560 }
19561
19562 let matched_strings = matches
19563 .into_iter()
19564 .map(|m| m.string)
19565 .collect::<HashSet<_>>();
19566
19567 let mut result: Vec<Completion> = snippets
19568 .iter()
19569 .filter_map(|snippet| {
19570 let matching_prefix = snippet
19571 .prefix
19572 .iter()
19573 .find(|prefix| matched_strings.contains(*prefix))?;
19574 let start = as_offset - last_word.len();
19575 let start = snapshot.anchor_before(start);
19576 let range = start..buffer_position;
19577 let lsp_start = to_lsp(&start);
19578 let lsp_range = lsp::Range {
19579 start: lsp_start,
19580 end: lsp_end,
19581 };
19582 Some(Completion {
19583 replace_range: range,
19584 new_text: snippet.body.clone(),
19585 source: CompletionSource::Lsp {
19586 insert_range: None,
19587 server_id: LanguageServerId(usize::MAX),
19588 resolved: true,
19589 lsp_completion: Box::new(lsp::CompletionItem {
19590 label: snippet.prefix.first().unwrap().clone(),
19591 kind: Some(CompletionItemKind::SNIPPET),
19592 label_details: snippet.description.as_ref().map(|description| {
19593 lsp::CompletionItemLabelDetails {
19594 detail: Some(description.clone()),
19595 description: None,
19596 }
19597 }),
19598 insert_text_format: Some(InsertTextFormat::SNIPPET),
19599 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19600 lsp::InsertReplaceEdit {
19601 new_text: snippet.body.clone(),
19602 insert: lsp_range,
19603 replace: lsp_range,
19604 },
19605 )),
19606 filter_text: Some(snippet.body.clone()),
19607 sort_text: Some(char::MAX.to_string()),
19608 ..lsp::CompletionItem::default()
19609 }),
19610 lsp_defaults: None,
19611 },
19612 label: CodeLabel {
19613 text: matching_prefix.clone(),
19614 runs: Vec::new(),
19615 filter_range: 0..matching_prefix.len(),
19616 },
19617 icon_path: None,
19618 documentation: snippet.description.clone().map(|description| {
19619 CompletionDocumentation::SingleLine(description.into())
19620 }),
19621 insert_text_mode: None,
19622 confirm: None,
19623 })
19624 })
19625 .collect();
19626
19627 all_results.append(&mut result);
19628 }
19629
19630 Ok(all_results)
19631 })
19632}
19633
19634impl CompletionProvider for Entity<Project> {
19635 fn completions(
19636 &self,
19637 _excerpt_id: ExcerptId,
19638 buffer: &Entity<Buffer>,
19639 buffer_position: text::Anchor,
19640 options: CompletionContext,
19641 _window: &mut Window,
19642 cx: &mut Context<Editor>,
19643 ) -> Task<Result<Option<Vec<Completion>>>> {
19644 self.update(cx, |project, cx| {
19645 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19646 let project_completions = project.completions(buffer, buffer_position, options, cx);
19647 cx.background_spawn(async move {
19648 let snippets_completions = snippets.await?;
19649 match project_completions.await? {
19650 Some(mut completions) => {
19651 completions.extend(snippets_completions);
19652 Ok(Some(completions))
19653 }
19654 None => {
19655 if snippets_completions.is_empty() {
19656 Ok(None)
19657 } else {
19658 Ok(Some(snippets_completions))
19659 }
19660 }
19661 }
19662 })
19663 })
19664 }
19665
19666 fn resolve_completions(
19667 &self,
19668 buffer: Entity<Buffer>,
19669 completion_indices: Vec<usize>,
19670 completions: Rc<RefCell<Box<[Completion]>>>,
19671 cx: &mut Context<Editor>,
19672 ) -> Task<Result<bool>> {
19673 self.update(cx, |project, cx| {
19674 project.lsp_store().update(cx, |lsp_store, cx| {
19675 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19676 })
19677 })
19678 }
19679
19680 fn apply_additional_edits_for_completion(
19681 &self,
19682 buffer: Entity<Buffer>,
19683 completions: Rc<RefCell<Box<[Completion]>>>,
19684 completion_index: usize,
19685 push_to_history: bool,
19686 cx: &mut Context<Editor>,
19687 ) -> Task<Result<Option<language::Transaction>>> {
19688 self.update(cx, |project, cx| {
19689 project.lsp_store().update(cx, |lsp_store, cx| {
19690 lsp_store.apply_additional_edits_for_completion(
19691 buffer,
19692 completions,
19693 completion_index,
19694 push_to_history,
19695 cx,
19696 )
19697 })
19698 })
19699 }
19700
19701 fn is_completion_trigger(
19702 &self,
19703 buffer: &Entity<Buffer>,
19704 position: language::Anchor,
19705 text: &str,
19706 trigger_in_words: bool,
19707 cx: &mut Context<Editor>,
19708 ) -> bool {
19709 let mut chars = text.chars();
19710 let char = if let Some(char) = chars.next() {
19711 char
19712 } else {
19713 return false;
19714 };
19715 if chars.next().is_some() {
19716 return false;
19717 }
19718
19719 let buffer = buffer.read(cx);
19720 let snapshot = buffer.snapshot();
19721 if !snapshot.settings_at(position, cx).show_completions_on_input {
19722 return false;
19723 }
19724 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19725 if trigger_in_words && classifier.is_word(char) {
19726 return true;
19727 }
19728
19729 buffer.completion_triggers().contains(text)
19730 }
19731}
19732
19733impl SemanticsProvider for Entity<Project> {
19734 fn hover(
19735 &self,
19736 buffer: &Entity<Buffer>,
19737 position: text::Anchor,
19738 cx: &mut App,
19739 ) -> Option<Task<Vec<project::Hover>>> {
19740 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19741 }
19742
19743 fn document_highlights(
19744 &self,
19745 buffer: &Entity<Buffer>,
19746 position: text::Anchor,
19747 cx: &mut App,
19748 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19749 Some(self.update(cx, |project, cx| {
19750 project.document_highlights(buffer, position, cx)
19751 }))
19752 }
19753
19754 fn definitions(
19755 &self,
19756 buffer: &Entity<Buffer>,
19757 position: text::Anchor,
19758 kind: GotoDefinitionKind,
19759 cx: &mut App,
19760 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19761 Some(self.update(cx, |project, cx| match kind {
19762 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19763 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19764 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19765 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19766 }))
19767 }
19768
19769 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19770 // TODO: make this work for remote projects
19771 self.update(cx, |project, cx| {
19772 if project
19773 .active_debug_session(cx)
19774 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19775 {
19776 return true;
19777 }
19778
19779 buffer.update(cx, |buffer, cx| {
19780 project.any_language_server_supports_inlay_hints(buffer, cx)
19781 })
19782 })
19783 }
19784
19785 fn inline_values(
19786 &self,
19787 buffer_handle: Entity<Buffer>,
19788 range: Range<text::Anchor>,
19789 cx: &mut App,
19790 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19791 self.update(cx, |project, cx| {
19792 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19793
19794 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19795 })
19796 }
19797
19798 fn inlay_hints(
19799 &self,
19800 buffer_handle: Entity<Buffer>,
19801 range: Range<text::Anchor>,
19802 cx: &mut App,
19803 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19804 Some(self.update(cx, |project, cx| {
19805 project.inlay_hints(buffer_handle, range, cx)
19806 }))
19807 }
19808
19809 fn resolve_inlay_hint(
19810 &self,
19811 hint: InlayHint,
19812 buffer_handle: Entity<Buffer>,
19813 server_id: LanguageServerId,
19814 cx: &mut App,
19815 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19816 Some(self.update(cx, |project, cx| {
19817 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19818 }))
19819 }
19820
19821 fn range_for_rename(
19822 &self,
19823 buffer: &Entity<Buffer>,
19824 position: text::Anchor,
19825 cx: &mut App,
19826 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19827 Some(self.update(cx, |project, cx| {
19828 let buffer = buffer.clone();
19829 let task = project.prepare_rename(buffer.clone(), position, cx);
19830 cx.spawn(async move |_, cx| {
19831 Ok(match task.await? {
19832 PrepareRenameResponse::Success(range) => Some(range),
19833 PrepareRenameResponse::InvalidPosition => None,
19834 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19835 // Fallback on using TreeSitter info to determine identifier range
19836 buffer.update(cx, |buffer, _| {
19837 let snapshot = buffer.snapshot();
19838 let (range, kind) = snapshot.surrounding_word(position);
19839 if kind != Some(CharKind::Word) {
19840 return None;
19841 }
19842 Some(
19843 snapshot.anchor_before(range.start)
19844 ..snapshot.anchor_after(range.end),
19845 )
19846 })?
19847 }
19848 })
19849 })
19850 }))
19851 }
19852
19853 fn perform_rename(
19854 &self,
19855 buffer: &Entity<Buffer>,
19856 position: text::Anchor,
19857 new_name: String,
19858 cx: &mut App,
19859 ) -> Option<Task<Result<ProjectTransaction>>> {
19860 Some(self.update(cx, |project, cx| {
19861 project.perform_rename(buffer.clone(), position, new_name, cx)
19862 }))
19863 }
19864}
19865
19866fn inlay_hint_settings(
19867 location: Anchor,
19868 snapshot: &MultiBufferSnapshot,
19869 cx: &mut Context<Editor>,
19870) -> InlayHintSettings {
19871 let file = snapshot.file_at(location);
19872 let language = snapshot.language_at(location).map(|l| l.name());
19873 language_settings(language, file, cx).inlay_hints
19874}
19875
19876fn consume_contiguous_rows(
19877 contiguous_row_selections: &mut Vec<Selection<Point>>,
19878 selection: &Selection<Point>,
19879 display_map: &DisplaySnapshot,
19880 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19881) -> (MultiBufferRow, MultiBufferRow) {
19882 contiguous_row_selections.push(selection.clone());
19883 let start_row = MultiBufferRow(selection.start.row);
19884 let mut end_row = ending_row(selection, display_map);
19885
19886 while let Some(next_selection) = selections.peek() {
19887 if next_selection.start.row <= end_row.0 {
19888 end_row = ending_row(next_selection, display_map);
19889 contiguous_row_selections.push(selections.next().unwrap().clone());
19890 } else {
19891 break;
19892 }
19893 }
19894 (start_row, end_row)
19895}
19896
19897fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19898 if next_selection.end.column > 0 || next_selection.is_empty() {
19899 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19900 } else {
19901 MultiBufferRow(next_selection.end.row)
19902 }
19903}
19904
19905impl EditorSnapshot {
19906 pub fn remote_selections_in_range<'a>(
19907 &'a self,
19908 range: &'a Range<Anchor>,
19909 collaboration_hub: &dyn CollaborationHub,
19910 cx: &'a App,
19911 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19912 let participant_names = collaboration_hub.user_names(cx);
19913 let participant_indices = collaboration_hub.user_participant_indices(cx);
19914 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19915 let collaborators_by_replica_id = collaborators_by_peer_id
19916 .iter()
19917 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19918 .collect::<HashMap<_, _>>();
19919 self.buffer_snapshot
19920 .selections_in_range(range, false)
19921 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19922 if replica_id == AGENT_REPLICA_ID {
19923 Some(RemoteSelection {
19924 replica_id,
19925 selection,
19926 cursor_shape,
19927 line_mode,
19928 collaborator_id: CollaboratorId::Agent,
19929 user_name: Some("Agent".into()),
19930 color: cx.theme().players().agent(),
19931 })
19932 } else {
19933 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19934 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19935 let user_name = participant_names.get(&collaborator.user_id).cloned();
19936 Some(RemoteSelection {
19937 replica_id,
19938 selection,
19939 cursor_shape,
19940 line_mode,
19941 collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19942 user_name,
19943 color: if let Some(index) = participant_index {
19944 cx.theme().players().color_for_participant(index.0)
19945 } else {
19946 cx.theme().players().absent()
19947 },
19948 })
19949 }
19950 })
19951 }
19952
19953 pub fn hunks_for_ranges(
19954 &self,
19955 ranges: impl IntoIterator<Item = Range<Point>>,
19956 ) -> Vec<MultiBufferDiffHunk> {
19957 let mut hunks = Vec::new();
19958 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19959 HashMap::default();
19960 for query_range in ranges {
19961 let query_rows =
19962 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19963 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19964 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19965 ) {
19966 // Include deleted hunks that are adjacent to the query range, because
19967 // otherwise they would be missed.
19968 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19969 if hunk.status().is_deleted() {
19970 intersects_range |= hunk.row_range.start == query_rows.end;
19971 intersects_range |= hunk.row_range.end == query_rows.start;
19972 }
19973 if intersects_range {
19974 if !processed_buffer_rows
19975 .entry(hunk.buffer_id)
19976 .or_default()
19977 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19978 {
19979 continue;
19980 }
19981 hunks.push(hunk);
19982 }
19983 }
19984 }
19985
19986 hunks
19987 }
19988
19989 fn display_diff_hunks_for_rows<'a>(
19990 &'a self,
19991 display_rows: Range<DisplayRow>,
19992 folded_buffers: &'a HashSet<BufferId>,
19993 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19994 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19995 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19996
19997 self.buffer_snapshot
19998 .diff_hunks_in_range(buffer_start..buffer_end)
19999 .filter_map(|hunk| {
20000 if folded_buffers.contains(&hunk.buffer_id) {
20001 return None;
20002 }
20003
20004 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20005 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20006
20007 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20008 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20009
20010 let display_hunk = if hunk_display_start.column() != 0 {
20011 DisplayDiffHunk::Folded {
20012 display_row: hunk_display_start.row(),
20013 }
20014 } else {
20015 let mut end_row = hunk_display_end.row();
20016 if hunk_display_end.column() > 0 {
20017 end_row.0 += 1;
20018 }
20019 let is_created_file = hunk.is_created_file();
20020 DisplayDiffHunk::Unfolded {
20021 status: hunk.status(),
20022 diff_base_byte_range: hunk.diff_base_byte_range,
20023 display_row_range: hunk_display_start.row()..end_row,
20024 multi_buffer_range: Anchor::range_in_buffer(
20025 hunk.excerpt_id,
20026 hunk.buffer_id,
20027 hunk.buffer_range,
20028 ),
20029 is_created_file,
20030 }
20031 };
20032
20033 Some(display_hunk)
20034 })
20035 }
20036
20037 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20038 self.display_snapshot.buffer_snapshot.language_at(position)
20039 }
20040
20041 pub fn is_focused(&self) -> bool {
20042 self.is_focused
20043 }
20044
20045 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20046 self.placeholder_text.as_ref()
20047 }
20048
20049 pub fn scroll_position(&self) -> gpui::Point<f32> {
20050 self.scroll_anchor.scroll_position(&self.display_snapshot)
20051 }
20052
20053 fn gutter_dimensions(
20054 &self,
20055 font_id: FontId,
20056 font_size: Pixels,
20057 max_line_number_width: Pixels,
20058 cx: &App,
20059 ) -> Option<GutterDimensions> {
20060 if !self.show_gutter {
20061 return None;
20062 }
20063
20064 let descent = cx.text_system().descent(font_id, font_size);
20065 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20066 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20067
20068 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20069 matches!(
20070 ProjectSettings::get_global(cx).git.git_gutter,
20071 Some(GitGutterSetting::TrackedFiles)
20072 )
20073 });
20074 let gutter_settings = EditorSettings::get_global(cx).gutter;
20075 let show_line_numbers = self
20076 .show_line_numbers
20077 .unwrap_or(gutter_settings.line_numbers);
20078 let line_gutter_width = if show_line_numbers {
20079 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20080 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20081 max_line_number_width.max(min_width_for_number_on_gutter)
20082 } else {
20083 0.0.into()
20084 };
20085
20086 let show_code_actions = self
20087 .show_code_actions
20088 .unwrap_or(gutter_settings.code_actions);
20089
20090 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20091 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20092
20093 let git_blame_entries_width =
20094 self.git_blame_gutter_max_author_length
20095 .map(|max_author_length| {
20096 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20097 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20098
20099 /// The number of characters to dedicate to gaps and margins.
20100 const SPACING_WIDTH: usize = 4;
20101
20102 let max_char_count = max_author_length.min(renderer.max_author_length())
20103 + ::git::SHORT_SHA_LENGTH
20104 + MAX_RELATIVE_TIMESTAMP.len()
20105 + SPACING_WIDTH;
20106
20107 em_advance * max_char_count
20108 });
20109
20110 let is_singleton = self.buffer_snapshot.is_singleton();
20111
20112 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20113 left_padding += if !is_singleton {
20114 em_width * 4.0
20115 } else if show_code_actions || show_runnables || show_breakpoints {
20116 em_width * 3.0
20117 } else if show_git_gutter && show_line_numbers {
20118 em_width * 2.0
20119 } else if show_git_gutter || show_line_numbers {
20120 em_width
20121 } else {
20122 px(0.)
20123 };
20124
20125 let shows_folds = is_singleton && gutter_settings.folds;
20126
20127 let right_padding = if shows_folds && show_line_numbers {
20128 em_width * 4.0
20129 } else if shows_folds || (!is_singleton && show_line_numbers) {
20130 em_width * 3.0
20131 } else if show_line_numbers {
20132 em_width
20133 } else {
20134 px(0.)
20135 };
20136
20137 Some(GutterDimensions {
20138 left_padding,
20139 right_padding,
20140 width: line_gutter_width + left_padding + right_padding,
20141 margin: -descent,
20142 git_blame_entries_width,
20143 })
20144 }
20145
20146 pub fn render_crease_toggle(
20147 &self,
20148 buffer_row: MultiBufferRow,
20149 row_contains_cursor: bool,
20150 editor: Entity<Editor>,
20151 window: &mut Window,
20152 cx: &mut App,
20153 ) -> Option<AnyElement> {
20154 let folded = self.is_line_folded(buffer_row);
20155 let mut is_foldable = false;
20156
20157 if let Some(crease) = self
20158 .crease_snapshot
20159 .query_row(buffer_row, &self.buffer_snapshot)
20160 {
20161 is_foldable = true;
20162 match crease {
20163 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20164 if let Some(render_toggle) = render_toggle {
20165 let toggle_callback =
20166 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20167 if folded {
20168 editor.update(cx, |editor, cx| {
20169 editor.fold_at(buffer_row, window, cx)
20170 });
20171 } else {
20172 editor.update(cx, |editor, cx| {
20173 editor.unfold_at(buffer_row, window, cx)
20174 });
20175 }
20176 });
20177 return Some((render_toggle)(
20178 buffer_row,
20179 folded,
20180 toggle_callback,
20181 window,
20182 cx,
20183 ));
20184 }
20185 }
20186 }
20187 }
20188
20189 is_foldable |= self.starts_indent(buffer_row);
20190
20191 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20192 Some(
20193 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20194 .toggle_state(folded)
20195 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20196 if folded {
20197 this.unfold_at(buffer_row, window, cx);
20198 } else {
20199 this.fold_at(buffer_row, window, cx);
20200 }
20201 }))
20202 .into_any_element(),
20203 )
20204 } else {
20205 None
20206 }
20207 }
20208
20209 pub fn render_crease_trailer(
20210 &self,
20211 buffer_row: MultiBufferRow,
20212 window: &mut Window,
20213 cx: &mut App,
20214 ) -> Option<AnyElement> {
20215 let folded = self.is_line_folded(buffer_row);
20216 if let Crease::Inline { render_trailer, .. } = self
20217 .crease_snapshot
20218 .query_row(buffer_row, &self.buffer_snapshot)?
20219 {
20220 let render_trailer = render_trailer.as_ref()?;
20221 Some(render_trailer(buffer_row, folded, window, cx))
20222 } else {
20223 None
20224 }
20225 }
20226}
20227
20228impl Deref for EditorSnapshot {
20229 type Target = DisplaySnapshot;
20230
20231 fn deref(&self) -> &Self::Target {
20232 &self.display_snapshot
20233 }
20234}
20235
20236#[derive(Clone, Debug, PartialEq, Eq)]
20237pub enum EditorEvent {
20238 InputIgnored {
20239 text: Arc<str>,
20240 },
20241 InputHandled {
20242 utf16_range_to_replace: Option<Range<isize>>,
20243 text: Arc<str>,
20244 },
20245 ExcerptsAdded {
20246 buffer: Entity<Buffer>,
20247 predecessor: ExcerptId,
20248 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20249 },
20250 ExcerptsRemoved {
20251 ids: Vec<ExcerptId>,
20252 removed_buffer_ids: Vec<BufferId>,
20253 },
20254 BufferFoldToggled {
20255 ids: Vec<ExcerptId>,
20256 folded: bool,
20257 },
20258 ExcerptsEdited {
20259 ids: Vec<ExcerptId>,
20260 },
20261 ExcerptsExpanded {
20262 ids: Vec<ExcerptId>,
20263 },
20264 BufferEdited,
20265 Edited {
20266 transaction_id: clock::Lamport,
20267 },
20268 Reparsed(BufferId),
20269 Focused,
20270 FocusedIn,
20271 Blurred,
20272 DirtyChanged,
20273 Saved,
20274 TitleChanged,
20275 DiffBaseChanged,
20276 SelectionsChanged {
20277 local: bool,
20278 },
20279 ScrollPositionChanged {
20280 local: bool,
20281 autoscroll: bool,
20282 },
20283 Closed,
20284 TransactionUndone {
20285 transaction_id: clock::Lamport,
20286 },
20287 TransactionBegun {
20288 transaction_id: clock::Lamport,
20289 },
20290 Reloaded,
20291 CursorShapeChanged,
20292 PushedToNavHistory {
20293 anchor: Anchor,
20294 is_deactivate: bool,
20295 },
20296}
20297
20298impl EventEmitter<EditorEvent> for Editor {}
20299
20300impl Focusable for Editor {
20301 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20302 self.focus_handle.clone()
20303 }
20304}
20305
20306impl Render for Editor {
20307 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20308 let settings = ThemeSettings::get_global(cx);
20309
20310 let mut text_style = match self.mode {
20311 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20312 color: cx.theme().colors().editor_foreground,
20313 font_family: settings.ui_font.family.clone(),
20314 font_features: settings.ui_font.features.clone(),
20315 font_fallbacks: settings.ui_font.fallbacks.clone(),
20316 font_size: rems(0.875).into(),
20317 font_weight: settings.ui_font.weight,
20318 line_height: relative(settings.buffer_line_height.value()),
20319 ..Default::default()
20320 },
20321 EditorMode::Full { .. } => TextStyle {
20322 color: cx.theme().colors().editor_foreground,
20323 font_family: settings.buffer_font.family.clone(),
20324 font_features: settings.buffer_font.features.clone(),
20325 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20326 font_size: settings.buffer_font_size(cx).into(),
20327 font_weight: settings.buffer_font.weight,
20328 line_height: relative(settings.buffer_line_height.value()),
20329 ..Default::default()
20330 },
20331 };
20332 if let Some(text_style_refinement) = &self.text_style_refinement {
20333 text_style.refine(text_style_refinement)
20334 }
20335
20336 let background = match self.mode {
20337 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20338 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20339 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20340 };
20341
20342 EditorElement::new(
20343 &cx.entity(),
20344 EditorStyle {
20345 background,
20346 horizontal_padding: Pixels::default(),
20347 local_player: cx.theme().players().local(),
20348 text: text_style,
20349 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20350 syntax: cx.theme().syntax().clone(),
20351 status: cx.theme().status().clone(),
20352 inlay_hints_style: make_inlay_hints_style(cx),
20353 inline_completion_styles: make_suggestion_styles(cx),
20354 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20355 },
20356 )
20357 }
20358}
20359
20360impl EntityInputHandler for Editor {
20361 fn text_for_range(
20362 &mut self,
20363 range_utf16: Range<usize>,
20364 adjusted_range: &mut Option<Range<usize>>,
20365 _: &mut Window,
20366 cx: &mut Context<Self>,
20367 ) -> Option<String> {
20368 let snapshot = self.buffer.read(cx).read(cx);
20369 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20370 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20371 if (start.0..end.0) != range_utf16 {
20372 adjusted_range.replace(start.0..end.0);
20373 }
20374 Some(snapshot.text_for_range(start..end).collect())
20375 }
20376
20377 fn selected_text_range(
20378 &mut self,
20379 ignore_disabled_input: bool,
20380 _: &mut Window,
20381 cx: &mut Context<Self>,
20382 ) -> Option<UTF16Selection> {
20383 // Prevent the IME menu from appearing when holding down an alphabetic key
20384 // while input is disabled.
20385 if !ignore_disabled_input && !self.input_enabled {
20386 return None;
20387 }
20388
20389 let selection = self.selections.newest::<OffsetUtf16>(cx);
20390 let range = selection.range();
20391
20392 Some(UTF16Selection {
20393 range: range.start.0..range.end.0,
20394 reversed: selection.reversed,
20395 })
20396 }
20397
20398 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20399 let snapshot = self.buffer.read(cx).read(cx);
20400 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20401 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20402 }
20403
20404 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20405 self.clear_highlights::<InputComposition>(cx);
20406 self.ime_transaction.take();
20407 }
20408
20409 fn replace_text_in_range(
20410 &mut self,
20411 range_utf16: Option<Range<usize>>,
20412 text: &str,
20413 window: &mut Window,
20414 cx: &mut Context<Self>,
20415 ) {
20416 if !self.input_enabled {
20417 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20418 return;
20419 }
20420
20421 self.transact(window, cx, |this, window, cx| {
20422 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20423 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20424 Some(this.selection_replacement_ranges(range_utf16, cx))
20425 } else {
20426 this.marked_text_ranges(cx)
20427 };
20428
20429 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20430 let newest_selection_id = this.selections.newest_anchor().id;
20431 this.selections
20432 .all::<OffsetUtf16>(cx)
20433 .iter()
20434 .zip(ranges_to_replace.iter())
20435 .find_map(|(selection, range)| {
20436 if selection.id == newest_selection_id {
20437 Some(
20438 (range.start.0 as isize - selection.head().0 as isize)
20439 ..(range.end.0 as isize - selection.head().0 as isize),
20440 )
20441 } else {
20442 None
20443 }
20444 })
20445 });
20446
20447 cx.emit(EditorEvent::InputHandled {
20448 utf16_range_to_replace: range_to_replace,
20449 text: text.into(),
20450 });
20451
20452 if let Some(new_selected_ranges) = new_selected_ranges {
20453 this.change_selections(None, window, cx, |selections| {
20454 selections.select_ranges(new_selected_ranges)
20455 });
20456 this.backspace(&Default::default(), window, cx);
20457 }
20458
20459 this.handle_input(text, window, cx);
20460 });
20461
20462 if let Some(transaction) = self.ime_transaction {
20463 self.buffer.update(cx, |buffer, cx| {
20464 buffer.group_until_transaction(transaction, cx);
20465 });
20466 }
20467
20468 self.unmark_text(window, cx);
20469 }
20470
20471 fn replace_and_mark_text_in_range(
20472 &mut self,
20473 range_utf16: Option<Range<usize>>,
20474 text: &str,
20475 new_selected_range_utf16: Option<Range<usize>>,
20476 window: &mut Window,
20477 cx: &mut Context<Self>,
20478 ) {
20479 if !self.input_enabled {
20480 return;
20481 }
20482
20483 let transaction = self.transact(window, cx, |this, window, cx| {
20484 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20485 let snapshot = this.buffer.read(cx).read(cx);
20486 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20487 for marked_range in &mut marked_ranges {
20488 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20489 marked_range.start.0 += relative_range_utf16.start;
20490 marked_range.start =
20491 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20492 marked_range.end =
20493 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20494 }
20495 }
20496 Some(marked_ranges)
20497 } else if let Some(range_utf16) = range_utf16 {
20498 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20499 Some(this.selection_replacement_ranges(range_utf16, cx))
20500 } else {
20501 None
20502 };
20503
20504 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20505 let newest_selection_id = this.selections.newest_anchor().id;
20506 this.selections
20507 .all::<OffsetUtf16>(cx)
20508 .iter()
20509 .zip(ranges_to_replace.iter())
20510 .find_map(|(selection, range)| {
20511 if selection.id == newest_selection_id {
20512 Some(
20513 (range.start.0 as isize - selection.head().0 as isize)
20514 ..(range.end.0 as isize - selection.head().0 as isize),
20515 )
20516 } else {
20517 None
20518 }
20519 })
20520 });
20521
20522 cx.emit(EditorEvent::InputHandled {
20523 utf16_range_to_replace: range_to_replace,
20524 text: text.into(),
20525 });
20526
20527 if let Some(ranges) = ranges_to_replace {
20528 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20529 }
20530
20531 let marked_ranges = {
20532 let snapshot = this.buffer.read(cx).read(cx);
20533 this.selections
20534 .disjoint_anchors()
20535 .iter()
20536 .map(|selection| {
20537 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20538 })
20539 .collect::<Vec<_>>()
20540 };
20541
20542 if text.is_empty() {
20543 this.unmark_text(window, cx);
20544 } else {
20545 this.highlight_text::<InputComposition>(
20546 marked_ranges.clone(),
20547 HighlightStyle {
20548 underline: Some(UnderlineStyle {
20549 thickness: px(1.),
20550 color: None,
20551 wavy: false,
20552 }),
20553 ..Default::default()
20554 },
20555 cx,
20556 );
20557 }
20558
20559 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20560 let use_autoclose = this.use_autoclose;
20561 let use_auto_surround = this.use_auto_surround;
20562 this.set_use_autoclose(false);
20563 this.set_use_auto_surround(false);
20564 this.handle_input(text, window, cx);
20565 this.set_use_autoclose(use_autoclose);
20566 this.set_use_auto_surround(use_auto_surround);
20567
20568 if let Some(new_selected_range) = new_selected_range_utf16 {
20569 let snapshot = this.buffer.read(cx).read(cx);
20570 let new_selected_ranges = marked_ranges
20571 .into_iter()
20572 .map(|marked_range| {
20573 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20574 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20575 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20576 snapshot.clip_offset_utf16(new_start, Bias::Left)
20577 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20578 })
20579 .collect::<Vec<_>>();
20580
20581 drop(snapshot);
20582 this.change_selections(None, window, cx, |selections| {
20583 selections.select_ranges(new_selected_ranges)
20584 });
20585 }
20586 });
20587
20588 self.ime_transaction = self.ime_transaction.or(transaction);
20589 if let Some(transaction) = self.ime_transaction {
20590 self.buffer.update(cx, |buffer, cx| {
20591 buffer.group_until_transaction(transaction, cx);
20592 });
20593 }
20594
20595 if self.text_highlights::<InputComposition>(cx).is_none() {
20596 self.ime_transaction.take();
20597 }
20598 }
20599
20600 fn bounds_for_range(
20601 &mut self,
20602 range_utf16: Range<usize>,
20603 element_bounds: gpui::Bounds<Pixels>,
20604 window: &mut Window,
20605 cx: &mut Context<Self>,
20606 ) -> Option<gpui::Bounds<Pixels>> {
20607 let text_layout_details = self.text_layout_details(window);
20608 let gpui::Size {
20609 width: em_width,
20610 height: line_height,
20611 } = self.character_size(window);
20612
20613 let snapshot = self.snapshot(window, cx);
20614 let scroll_position = snapshot.scroll_position();
20615 let scroll_left = scroll_position.x * em_width;
20616
20617 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20618 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20619 + self.gutter_dimensions.width
20620 + self.gutter_dimensions.margin;
20621 let y = line_height * (start.row().as_f32() - scroll_position.y);
20622
20623 Some(Bounds {
20624 origin: element_bounds.origin + point(x, y),
20625 size: size(em_width, line_height),
20626 })
20627 }
20628
20629 fn character_index_for_point(
20630 &mut self,
20631 point: gpui::Point<Pixels>,
20632 _window: &mut Window,
20633 _cx: &mut Context<Self>,
20634 ) -> Option<usize> {
20635 let position_map = self.last_position_map.as_ref()?;
20636 if !position_map.text_hitbox.contains(&point) {
20637 return None;
20638 }
20639 let display_point = position_map.point_for_position(point).previous_valid;
20640 let anchor = position_map
20641 .snapshot
20642 .display_point_to_anchor(display_point, Bias::Left);
20643 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20644 Some(utf16_offset.0)
20645 }
20646}
20647
20648trait SelectionExt {
20649 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20650 fn spanned_rows(
20651 &self,
20652 include_end_if_at_line_start: bool,
20653 map: &DisplaySnapshot,
20654 ) -> Range<MultiBufferRow>;
20655}
20656
20657impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20658 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20659 let start = self
20660 .start
20661 .to_point(&map.buffer_snapshot)
20662 .to_display_point(map);
20663 let end = self
20664 .end
20665 .to_point(&map.buffer_snapshot)
20666 .to_display_point(map);
20667 if self.reversed {
20668 end..start
20669 } else {
20670 start..end
20671 }
20672 }
20673
20674 fn spanned_rows(
20675 &self,
20676 include_end_if_at_line_start: bool,
20677 map: &DisplaySnapshot,
20678 ) -> Range<MultiBufferRow> {
20679 let start = self.start.to_point(&map.buffer_snapshot);
20680 let mut end = self.end.to_point(&map.buffer_snapshot);
20681 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20682 end.row -= 1;
20683 }
20684
20685 let buffer_start = map.prev_line_boundary(start).0;
20686 let buffer_end = map.next_line_boundary(end).0;
20687 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20688 }
20689}
20690
20691impl<T: InvalidationRegion> InvalidationStack<T> {
20692 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20693 where
20694 S: Clone + ToOffset,
20695 {
20696 while let Some(region) = self.last() {
20697 let all_selections_inside_invalidation_ranges =
20698 if selections.len() == region.ranges().len() {
20699 selections
20700 .iter()
20701 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20702 .all(|(selection, invalidation_range)| {
20703 let head = selection.head().to_offset(buffer);
20704 invalidation_range.start <= head && invalidation_range.end >= head
20705 })
20706 } else {
20707 false
20708 };
20709
20710 if all_selections_inside_invalidation_ranges {
20711 break;
20712 } else {
20713 self.pop();
20714 }
20715 }
20716 }
20717}
20718
20719impl<T> Default for InvalidationStack<T> {
20720 fn default() -> Self {
20721 Self(Default::default())
20722 }
20723}
20724
20725impl<T> Deref for InvalidationStack<T> {
20726 type Target = Vec<T>;
20727
20728 fn deref(&self) -> &Self::Target {
20729 &self.0
20730 }
20731}
20732
20733impl<T> DerefMut for InvalidationStack<T> {
20734 fn deref_mut(&mut self) -> &mut Self::Target {
20735 &mut self.0
20736 }
20737}
20738
20739impl InvalidationRegion for SnippetState {
20740 fn ranges(&self) -> &[Range<Anchor>] {
20741 &self.ranges[self.active_index]
20742 }
20743}
20744
20745fn inline_completion_edit_text(
20746 current_snapshot: &BufferSnapshot,
20747 edits: &[(Range<Anchor>, String)],
20748 edit_preview: &EditPreview,
20749 include_deletions: bool,
20750 cx: &App,
20751) -> HighlightedText {
20752 let edits = edits
20753 .iter()
20754 .map(|(anchor, text)| {
20755 (
20756 anchor.start.text_anchor..anchor.end.text_anchor,
20757 text.clone(),
20758 )
20759 })
20760 .collect::<Vec<_>>();
20761
20762 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20763}
20764
20765pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20766 match severity {
20767 DiagnosticSeverity::ERROR => colors.error,
20768 DiagnosticSeverity::WARNING => colors.warning,
20769 DiagnosticSeverity::INFORMATION => colors.info,
20770 DiagnosticSeverity::HINT => colors.info,
20771 _ => colors.ignored,
20772 }
20773}
20774
20775pub fn styled_runs_for_code_label<'a>(
20776 label: &'a CodeLabel,
20777 syntax_theme: &'a theme::SyntaxTheme,
20778) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20779 let fade_out = HighlightStyle {
20780 fade_out: Some(0.35),
20781 ..Default::default()
20782 };
20783
20784 let mut prev_end = label.filter_range.end;
20785 label
20786 .runs
20787 .iter()
20788 .enumerate()
20789 .flat_map(move |(ix, (range, highlight_id))| {
20790 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20791 style
20792 } else {
20793 return Default::default();
20794 };
20795 let mut muted_style = style;
20796 muted_style.highlight(fade_out);
20797
20798 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20799 if range.start >= label.filter_range.end {
20800 if range.start > prev_end {
20801 runs.push((prev_end..range.start, fade_out));
20802 }
20803 runs.push((range.clone(), muted_style));
20804 } else if range.end <= label.filter_range.end {
20805 runs.push((range.clone(), style));
20806 } else {
20807 runs.push((range.start..label.filter_range.end, style));
20808 runs.push((label.filter_range.end..range.end, muted_style));
20809 }
20810 prev_end = cmp::max(prev_end, range.end);
20811
20812 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20813 runs.push((prev_end..label.text.len(), fade_out));
20814 }
20815
20816 runs
20817 })
20818}
20819
20820pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20821 let mut prev_index = 0;
20822 let mut prev_codepoint: Option<char> = None;
20823 text.char_indices()
20824 .chain([(text.len(), '\0')])
20825 .filter_map(move |(index, codepoint)| {
20826 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20827 let is_boundary = index == text.len()
20828 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20829 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20830 if is_boundary {
20831 let chunk = &text[prev_index..index];
20832 prev_index = index;
20833 Some(chunk)
20834 } else {
20835 None
20836 }
20837 })
20838}
20839
20840pub trait RangeToAnchorExt: Sized {
20841 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20842
20843 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20844 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20845 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20846 }
20847}
20848
20849impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20850 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20851 let start_offset = self.start.to_offset(snapshot);
20852 let end_offset = self.end.to_offset(snapshot);
20853 if start_offset == end_offset {
20854 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20855 } else {
20856 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20857 }
20858 }
20859}
20860
20861pub trait RowExt {
20862 fn as_f32(&self) -> f32;
20863
20864 fn next_row(&self) -> Self;
20865
20866 fn previous_row(&self) -> Self;
20867
20868 fn minus(&self, other: Self) -> u32;
20869}
20870
20871impl RowExt for DisplayRow {
20872 fn as_f32(&self) -> f32 {
20873 self.0 as f32
20874 }
20875
20876 fn next_row(&self) -> Self {
20877 Self(self.0 + 1)
20878 }
20879
20880 fn previous_row(&self) -> Self {
20881 Self(self.0.saturating_sub(1))
20882 }
20883
20884 fn minus(&self, other: Self) -> u32 {
20885 self.0 - other.0
20886 }
20887}
20888
20889impl RowExt for MultiBufferRow {
20890 fn as_f32(&self) -> f32 {
20891 self.0 as f32
20892 }
20893
20894 fn next_row(&self) -> Self {
20895 Self(self.0 + 1)
20896 }
20897
20898 fn previous_row(&self) -> Self {
20899 Self(self.0.saturating_sub(1))
20900 }
20901
20902 fn minus(&self, other: Self) -> u32 {
20903 self.0 - other.0
20904 }
20905}
20906
20907trait RowRangeExt {
20908 type Row;
20909
20910 fn len(&self) -> usize;
20911
20912 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20913}
20914
20915impl RowRangeExt for Range<MultiBufferRow> {
20916 type Row = MultiBufferRow;
20917
20918 fn len(&self) -> usize {
20919 (self.end.0 - self.start.0) as usize
20920 }
20921
20922 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20923 (self.start.0..self.end.0).map(MultiBufferRow)
20924 }
20925}
20926
20927impl RowRangeExt for Range<DisplayRow> {
20928 type Row = DisplayRow;
20929
20930 fn len(&self) -> usize {
20931 (self.end.0 - self.start.0) as usize
20932 }
20933
20934 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20935 (self.start.0..self.end.0).map(DisplayRow)
20936 }
20937}
20938
20939/// If select range has more than one line, we
20940/// just point the cursor to range.start.
20941fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20942 if range.start.row == range.end.row {
20943 range
20944 } else {
20945 range.start..range.start
20946 }
20947}
20948pub struct KillRing(ClipboardItem);
20949impl Global for KillRing {}
20950
20951const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20952
20953enum BreakpointPromptEditAction {
20954 Log,
20955 Condition,
20956 HitCondition,
20957}
20958
20959struct BreakpointPromptEditor {
20960 pub(crate) prompt: Entity<Editor>,
20961 editor: WeakEntity<Editor>,
20962 breakpoint_anchor: Anchor,
20963 breakpoint: Breakpoint,
20964 edit_action: BreakpointPromptEditAction,
20965 block_ids: HashSet<CustomBlockId>,
20966 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20967 _subscriptions: Vec<Subscription>,
20968}
20969
20970impl BreakpointPromptEditor {
20971 const MAX_LINES: u8 = 4;
20972
20973 fn new(
20974 editor: WeakEntity<Editor>,
20975 breakpoint_anchor: Anchor,
20976 breakpoint: Breakpoint,
20977 edit_action: BreakpointPromptEditAction,
20978 window: &mut Window,
20979 cx: &mut Context<Self>,
20980 ) -> Self {
20981 let base_text = match edit_action {
20982 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20983 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20984 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20985 }
20986 .map(|msg| msg.to_string())
20987 .unwrap_or_default();
20988
20989 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20990 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20991
20992 let prompt = cx.new(|cx| {
20993 let mut prompt = Editor::new(
20994 EditorMode::AutoHeight {
20995 max_lines: Self::MAX_LINES as usize,
20996 },
20997 buffer,
20998 None,
20999 window,
21000 cx,
21001 );
21002 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21003 prompt.set_show_cursor_when_unfocused(false, cx);
21004 prompt.set_placeholder_text(
21005 match edit_action {
21006 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21007 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21008 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21009 },
21010 cx,
21011 );
21012
21013 prompt
21014 });
21015
21016 Self {
21017 prompt,
21018 editor,
21019 breakpoint_anchor,
21020 breakpoint,
21021 edit_action,
21022 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21023 block_ids: Default::default(),
21024 _subscriptions: vec![],
21025 }
21026 }
21027
21028 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21029 self.block_ids.extend(block_ids)
21030 }
21031
21032 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21033 if let Some(editor) = self.editor.upgrade() {
21034 let message = self
21035 .prompt
21036 .read(cx)
21037 .buffer
21038 .read(cx)
21039 .as_singleton()
21040 .expect("A multi buffer in breakpoint prompt isn't possible")
21041 .read(cx)
21042 .as_rope()
21043 .to_string();
21044
21045 editor.update(cx, |editor, cx| {
21046 editor.edit_breakpoint_at_anchor(
21047 self.breakpoint_anchor,
21048 self.breakpoint.clone(),
21049 match self.edit_action {
21050 BreakpointPromptEditAction::Log => {
21051 BreakpointEditAction::EditLogMessage(message.into())
21052 }
21053 BreakpointPromptEditAction::Condition => {
21054 BreakpointEditAction::EditCondition(message.into())
21055 }
21056 BreakpointPromptEditAction::HitCondition => {
21057 BreakpointEditAction::EditHitCondition(message.into())
21058 }
21059 },
21060 cx,
21061 );
21062
21063 editor.remove_blocks(self.block_ids.clone(), None, cx);
21064 cx.focus_self(window);
21065 });
21066 }
21067 }
21068
21069 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21070 self.editor
21071 .update(cx, |editor, cx| {
21072 editor.remove_blocks(self.block_ids.clone(), None, cx);
21073 window.focus(&editor.focus_handle);
21074 })
21075 .log_err();
21076 }
21077
21078 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21079 let settings = ThemeSettings::get_global(cx);
21080 let text_style = TextStyle {
21081 color: if self.prompt.read(cx).read_only(cx) {
21082 cx.theme().colors().text_disabled
21083 } else {
21084 cx.theme().colors().text
21085 },
21086 font_family: settings.buffer_font.family.clone(),
21087 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21088 font_size: settings.buffer_font_size(cx).into(),
21089 font_weight: settings.buffer_font.weight,
21090 line_height: relative(settings.buffer_line_height.value()),
21091 ..Default::default()
21092 };
21093 EditorElement::new(
21094 &self.prompt,
21095 EditorStyle {
21096 background: cx.theme().colors().editor_background,
21097 local_player: cx.theme().players().local(),
21098 text: text_style,
21099 ..Default::default()
21100 },
21101 )
21102 }
21103}
21104
21105impl Render for BreakpointPromptEditor {
21106 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21107 let gutter_dimensions = *self.gutter_dimensions.lock();
21108 h_flex()
21109 .key_context("Editor")
21110 .bg(cx.theme().colors().editor_background)
21111 .border_y_1()
21112 .border_color(cx.theme().status().info_border)
21113 .size_full()
21114 .py(window.line_height() / 2.5)
21115 .on_action(cx.listener(Self::confirm))
21116 .on_action(cx.listener(Self::cancel))
21117 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21118 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21119 }
21120}
21121
21122impl Focusable for BreakpointPromptEditor {
21123 fn focus_handle(&self, cx: &App) -> FocusHandle {
21124 self.prompt.focus_handle(cx)
21125 }
21126}
21127
21128fn all_edits_insertions_or_deletions(
21129 edits: &Vec<(Range<Anchor>, String)>,
21130 snapshot: &MultiBufferSnapshot,
21131) -> bool {
21132 let mut all_insertions = true;
21133 let mut all_deletions = true;
21134
21135 for (range, new_text) in edits.iter() {
21136 let range_is_empty = range.to_offset(&snapshot).is_empty();
21137 let text_is_empty = new_text.is_empty();
21138
21139 if range_is_empty != text_is_empty {
21140 if range_is_empty {
21141 all_deletions = false;
21142 } else {
21143 all_insertions = false;
21144 }
21145 } else {
21146 return false;
21147 }
21148
21149 if !all_insertions && !all_deletions {
21150 return false;
21151 }
21152 }
21153 all_insertions || all_deletions
21154}
21155
21156struct MissingEditPredictionKeybindingTooltip;
21157
21158impl Render for MissingEditPredictionKeybindingTooltip {
21159 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21160 ui::tooltip_container(window, cx, |container, _, cx| {
21161 container
21162 .flex_shrink_0()
21163 .max_w_80()
21164 .min_h(rems_from_px(124.))
21165 .justify_between()
21166 .child(
21167 v_flex()
21168 .flex_1()
21169 .text_ui_sm(cx)
21170 .child(Label::new("Conflict with Accept Keybinding"))
21171 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21172 )
21173 .child(
21174 h_flex()
21175 .pb_1()
21176 .gap_1()
21177 .items_end()
21178 .w_full()
21179 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21180 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21181 }))
21182 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21183 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21184 })),
21185 )
21186 })
21187 }
21188}
21189
21190#[derive(Debug, Clone, Copy, PartialEq)]
21191pub struct LineHighlight {
21192 pub background: Background,
21193 pub border: Option<gpui::Hsla>,
21194 pub include_gutter: bool,
21195 pub type_id: Option<TypeId>,
21196}
21197
21198fn render_diff_hunk_controls(
21199 row: u32,
21200 status: &DiffHunkStatus,
21201 hunk_range: Range<Anchor>,
21202 is_created_file: bool,
21203 line_height: Pixels,
21204 editor: &Entity<Editor>,
21205 _window: &mut Window,
21206 cx: &mut App,
21207) -> AnyElement {
21208 h_flex()
21209 .h(line_height)
21210 .mr_1()
21211 .gap_1()
21212 .px_0p5()
21213 .pb_1()
21214 .border_x_1()
21215 .border_b_1()
21216 .border_color(cx.theme().colors().border_variant)
21217 .rounded_b_lg()
21218 .bg(cx.theme().colors().editor_background)
21219 .gap_1()
21220 .occlude()
21221 .shadow_md()
21222 .child(if status.has_secondary_hunk() {
21223 Button::new(("stage", row as u64), "Stage")
21224 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21225 .tooltip({
21226 let focus_handle = editor.focus_handle(cx);
21227 move |window, cx| {
21228 Tooltip::for_action_in(
21229 "Stage Hunk",
21230 &::git::ToggleStaged,
21231 &focus_handle,
21232 window,
21233 cx,
21234 )
21235 }
21236 })
21237 .on_click({
21238 let editor = editor.clone();
21239 move |_event, _window, cx| {
21240 editor.update(cx, |editor, cx| {
21241 editor.stage_or_unstage_diff_hunks(
21242 true,
21243 vec![hunk_range.start..hunk_range.start],
21244 cx,
21245 );
21246 });
21247 }
21248 })
21249 } else {
21250 Button::new(("unstage", row as u64), "Unstage")
21251 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21252 .tooltip({
21253 let focus_handle = editor.focus_handle(cx);
21254 move |window, cx| {
21255 Tooltip::for_action_in(
21256 "Unstage Hunk",
21257 &::git::ToggleStaged,
21258 &focus_handle,
21259 window,
21260 cx,
21261 )
21262 }
21263 })
21264 .on_click({
21265 let editor = editor.clone();
21266 move |_event, _window, cx| {
21267 editor.update(cx, |editor, cx| {
21268 editor.stage_or_unstage_diff_hunks(
21269 false,
21270 vec![hunk_range.start..hunk_range.start],
21271 cx,
21272 );
21273 });
21274 }
21275 })
21276 })
21277 .child(
21278 Button::new(("restore", row as u64), "Restore")
21279 .tooltip({
21280 let focus_handle = editor.focus_handle(cx);
21281 move |window, cx| {
21282 Tooltip::for_action_in(
21283 "Restore Hunk",
21284 &::git::Restore,
21285 &focus_handle,
21286 window,
21287 cx,
21288 )
21289 }
21290 })
21291 .on_click({
21292 let editor = editor.clone();
21293 move |_event, window, cx| {
21294 editor.update(cx, |editor, cx| {
21295 let snapshot = editor.snapshot(window, cx);
21296 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21297 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21298 });
21299 }
21300 })
21301 .disabled(is_created_file),
21302 )
21303 .when(
21304 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21305 |el| {
21306 el.child(
21307 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21308 .shape(IconButtonShape::Square)
21309 .icon_size(IconSize::Small)
21310 // .disabled(!has_multiple_hunks)
21311 .tooltip({
21312 let focus_handle = editor.focus_handle(cx);
21313 move |window, cx| {
21314 Tooltip::for_action_in(
21315 "Next Hunk",
21316 &GoToHunk,
21317 &focus_handle,
21318 window,
21319 cx,
21320 )
21321 }
21322 })
21323 .on_click({
21324 let editor = editor.clone();
21325 move |_event, window, cx| {
21326 editor.update(cx, |editor, cx| {
21327 let snapshot = editor.snapshot(window, cx);
21328 let position =
21329 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21330 editor.go_to_hunk_before_or_after_position(
21331 &snapshot,
21332 position,
21333 Direction::Next,
21334 window,
21335 cx,
21336 );
21337 editor.expand_selected_diff_hunks(cx);
21338 });
21339 }
21340 }),
21341 )
21342 .child(
21343 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21344 .shape(IconButtonShape::Square)
21345 .icon_size(IconSize::Small)
21346 // .disabled(!has_multiple_hunks)
21347 .tooltip({
21348 let focus_handle = editor.focus_handle(cx);
21349 move |window, cx| {
21350 Tooltip::for_action_in(
21351 "Previous Hunk",
21352 &GoToPreviousHunk,
21353 &focus_handle,
21354 window,
21355 cx,
21356 )
21357 }
21358 })
21359 .on_click({
21360 let editor = editor.clone();
21361 move |_event, window, cx| {
21362 editor.update(cx, |editor, cx| {
21363 let snapshot = editor.snapshot(window, cx);
21364 let point =
21365 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21366 editor.go_to_hunk_before_or_after_position(
21367 &snapshot,
21368 point,
21369 Direction::Prev,
21370 window,
21371 cx,
21372 );
21373 editor.expand_selected_diff_hunks(cx);
21374 });
21375 }
21376 }),
21377 )
21378 },
21379 )
21380 .into_any_element()
21381}