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 debug_adapter: SharedString = buffer
5210 .read(cx)
5211 .language()?
5212 .context_provider()?
5213 .debug_adapter()?
5214 .into();
5215 dap_store.update(cx, |this, cx| {
5216 for (_, task) in &resolved_tasks.templates {
5217 if let Some(scenario) = this
5218 .debug_scenario_for_build_task(
5219 task.resolved.clone(),
5220 SharedString::from(
5221 task.original_task().label.clone(),
5222 ),
5223 debug_adapter.clone(),
5224 cx,
5225 )
5226 {
5227 scenarios.push(scenario);
5228 }
5229 }
5230 });
5231 Some(scenarios)
5232 })
5233 .unwrap_or_default()
5234 } else {
5235 vec![]
5236 }
5237 })?;
5238 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5239 *editor.context_menu.borrow_mut() =
5240 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5241 buffer,
5242 actions: CodeActionContents::new(
5243 resolved_tasks,
5244 code_actions,
5245 debug_scenarios,
5246 task_context.unwrap_or_default(),
5247 ),
5248 selected_item: Default::default(),
5249 scroll_handle: UniformListScrollHandle::default(),
5250 deployed_from_indicator,
5251 }));
5252 if spawn_straight_away {
5253 if let Some(task) = editor.confirm_code_action(
5254 &ConfirmCodeAction { item_ix: Some(0) },
5255 window,
5256 cx,
5257 ) {
5258 cx.notify();
5259 return task;
5260 }
5261 }
5262 cx.notify();
5263 Task::ready(Ok(()))
5264 }) {
5265 task.await
5266 } else {
5267 Ok(())
5268 }
5269 }))
5270 } else {
5271 Some(Task::ready(Ok(())))
5272 }
5273 })?;
5274 if let Some(task) = spawned_test_task {
5275 task.await?;
5276 }
5277
5278 Ok::<_, anyhow::Error>(())
5279 })
5280 .detach_and_log_err(cx);
5281 }
5282
5283 pub fn confirm_code_action(
5284 &mut self,
5285 action: &ConfirmCodeAction,
5286 window: &mut Window,
5287 cx: &mut Context<Self>,
5288 ) -> Option<Task<Result<()>>> {
5289 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5290
5291 let actions_menu =
5292 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5293 menu
5294 } else {
5295 return None;
5296 };
5297
5298 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5299 let action = actions_menu.actions.get(action_ix)?;
5300 let title = action.label();
5301 let buffer = actions_menu.buffer;
5302 let workspace = self.workspace()?;
5303
5304 match action {
5305 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5306 workspace.update(cx, |workspace, cx| {
5307 workspace.schedule_resolved_task(
5308 task_source_kind,
5309 resolved_task,
5310 false,
5311 window,
5312 cx,
5313 );
5314
5315 Some(Task::ready(Ok(())))
5316 })
5317 }
5318 CodeActionsItem::CodeAction {
5319 excerpt_id,
5320 action,
5321 provider,
5322 } => {
5323 let apply_code_action =
5324 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5325 let workspace = workspace.downgrade();
5326 Some(cx.spawn_in(window, async move |editor, cx| {
5327 let project_transaction = apply_code_action.await?;
5328 Self::open_project_transaction(
5329 &editor,
5330 workspace,
5331 project_transaction,
5332 title,
5333 cx,
5334 )
5335 .await
5336 }))
5337 }
5338 CodeActionsItem::DebugScenario(scenario) => {
5339 let context = actions_menu.actions.context.clone();
5340
5341 workspace.update(cx, |workspace, cx| {
5342 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5343 });
5344 Some(Task::ready(Ok(())))
5345 }
5346 }
5347 }
5348
5349 pub async fn open_project_transaction(
5350 this: &WeakEntity<Editor>,
5351 workspace: WeakEntity<Workspace>,
5352 transaction: ProjectTransaction,
5353 title: String,
5354 cx: &mut AsyncWindowContext,
5355 ) -> Result<()> {
5356 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5357 cx.update(|_, cx| {
5358 entries.sort_unstable_by_key(|(buffer, _)| {
5359 buffer.read(cx).file().map(|f| f.path().clone())
5360 });
5361 })?;
5362
5363 // If the project transaction's edits are all contained within this editor, then
5364 // avoid opening a new editor to display them.
5365
5366 if let Some((buffer, transaction)) = entries.first() {
5367 if entries.len() == 1 {
5368 let excerpt = this.update(cx, |editor, cx| {
5369 editor
5370 .buffer()
5371 .read(cx)
5372 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5373 })?;
5374 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5375 if excerpted_buffer == *buffer {
5376 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5377 let excerpt_range = excerpt_range.to_offset(buffer);
5378 buffer
5379 .edited_ranges_for_transaction::<usize>(transaction)
5380 .all(|range| {
5381 excerpt_range.start <= range.start
5382 && excerpt_range.end >= range.end
5383 })
5384 })?;
5385
5386 if all_edits_within_excerpt {
5387 return Ok(());
5388 }
5389 }
5390 }
5391 }
5392 } else {
5393 return Ok(());
5394 }
5395
5396 let mut ranges_to_highlight = Vec::new();
5397 let excerpt_buffer = cx.new(|cx| {
5398 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5399 for (buffer_handle, transaction) in &entries {
5400 let edited_ranges = buffer_handle
5401 .read(cx)
5402 .edited_ranges_for_transaction::<Point>(transaction)
5403 .collect::<Vec<_>>();
5404 let (ranges, _) = multibuffer.set_excerpts_for_path(
5405 PathKey::for_buffer(buffer_handle, cx),
5406 buffer_handle.clone(),
5407 edited_ranges,
5408 DEFAULT_MULTIBUFFER_CONTEXT,
5409 cx,
5410 );
5411
5412 ranges_to_highlight.extend(ranges);
5413 }
5414 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5415 multibuffer
5416 })?;
5417
5418 workspace.update_in(cx, |workspace, window, cx| {
5419 let project = workspace.project().clone();
5420 let editor =
5421 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5422 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5423 editor.update(cx, |editor, cx| {
5424 editor.highlight_background::<Self>(
5425 &ranges_to_highlight,
5426 |theme| theme.editor_highlighted_line_background,
5427 cx,
5428 );
5429 });
5430 })?;
5431
5432 Ok(())
5433 }
5434
5435 pub fn clear_code_action_providers(&mut self) {
5436 self.code_action_providers.clear();
5437 self.available_code_actions.take();
5438 }
5439
5440 pub fn add_code_action_provider(
5441 &mut self,
5442 provider: Rc<dyn CodeActionProvider>,
5443 window: &mut Window,
5444 cx: &mut Context<Self>,
5445 ) {
5446 if self
5447 .code_action_providers
5448 .iter()
5449 .any(|existing_provider| existing_provider.id() == provider.id())
5450 {
5451 return;
5452 }
5453
5454 self.code_action_providers.push(provider);
5455 self.refresh_code_actions(window, cx);
5456 }
5457
5458 pub fn remove_code_action_provider(
5459 &mut self,
5460 id: Arc<str>,
5461 window: &mut Window,
5462 cx: &mut Context<Self>,
5463 ) {
5464 self.code_action_providers
5465 .retain(|provider| provider.id() != id);
5466 self.refresh_code_actions(window, cx);
5467 }
5468
5469 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5470 let newest_selection = self.selections.newest_anchor().clone();
5471 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5472 let buffer = self.buffer.read(cx);
5473 if newest_selection.head().diff_base_anchor.is_some() {
5474 return None;
5475 }
5476 let (start_buffer, start) =
5477 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5478 let (end_buffer, end) =
5479 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5480 if start_buffer != end_buffer {
5481 return None;
5482 }
5483
5484 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5485 cx.background_executor()
5486 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5487 .await;
5488
5489 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5490 let providers = this.code_action_providers.clone();
5491 let tasks = this
5492 .code_action_providers
5493 .iter()
5494 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5495 .collect::<Vec<_>>();
5496 (providers, tasks)
5497 })?;
5498
5499 let mut actions = Vec::new();
5500 for (provider, provider_actions) in
5501 providers.into_iter().zip(future::join_all(tasks).await)
5502 {
5503 if let Some(provider_actions) = provider_actions.log_err() {
5504 actions.extend(provider_actions.into_iter().map(|action| {
5505 AvailableCodeAction {
5506 excerpt_id: newest_selection.start.excerpt_id,
5507 action,
5508 provider: provider.clone(),
5509 }
5510 }));
5511 }
5512 }
5513
5514 this.update(cx, |this, cx| {
5515 this.available_code_actions = if actions.is_empty() {
5516 None
5517 } else {
5518 Some((
5519 Location {
5520 buffer: start_buffer,
5521 range: start..end,
5522 },
5523 actions.into(),
5524 ))
5525 };
5526 cx.notify();
5527 })
5528 }));
5529 None
5530 }
5531
5532 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5533 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5534 self.show_git_blame_inline = false;
5535
5536 self.show_git_blame_inline_delay_task =
5537 Some(cx.spawn_in(window, async move |this, cx| {
5538 cx.background_executor().timer(delay).await;
5539
5540 this.update(cx, |this, cx| {
5541 this.show_git_blame_inline = true;
5542 cx.notify();
5543 })
5544 .log_err();
5545 }));
5546 }
5547 }
5548
5549 fn show_blame_popover(
5550 &mut self,
5551 blame_entry: &BlameEntry,
5552 position: gpui::Point<Pixels>,
5553 cx: &mut Context<Self>,
5554 ) {
5555 if let Some(state) = &mut self.inline_blame_popover {
5556 state.hide_task.take();
5557 cx.notify();
5558 } else {
5559 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5560 let show_task = cx.spawn(async move |editor, cx| {
5561 cx.background_executor()
5562 .timer(std::time::Duration::from_millis(delay))
5563 .await;
5564 editor
5565 .update(cx, |editor, cx| {
5566 if let Some(state) = &mut editor.inline_blame_popover {
5567 state.show_task = None;
5568 cx.notify();
5569 }
5570 })
5571 .ok();
5572 });
5573 let Some(blame) = self.blame.as_ref() else {
5574 return;
5575 };
5576 let blame = blame.read(cx);
5577 let details = blame.details_for_entry(&blame_entry);
5578 let markdown = cx.new(|cx| {
5579 Markdown::new(
5580 details
5581 .as_ref()
5582 .map(|message| message.message.clone())
5583 .unwrap_or_default(),
5584 None,
5585 None,
5586 cx,
5587 )
5588 });
5589 self.inline_blame_popover = Some(InlineBlamePopover {
5590 position,
5591 show_task: Some(show_task),
5592 hide_task: None,
5593 popover_bounds: None,
5594 popover_state: InlineBlamePopoverState {
5595 scroll_handle: ScrollHandle::new(),
5596 commit_message: details,
5597 markdown,
5598 },
5599 });
5600 }
5601 }
5602
5603 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5604 if let Some(state) = &mut self.inline_blame_popover {
5605 if state.show_task.is_some() {
5606 self.inline_blame_popover.take();
5607 cx.notify();
5608 } else {
5609 let hide_task = cx.spawn(async move |editor, cx| {
5610 cx.background_executor()
5611 .timer(std::time::Duration::from_millis(100))
5612 .await;
5613 editor
5614 .update(cx, |editor, cx| {
5615 editor.inline_blame_popover.take();
5616 cx.notify();
5617 })
5618 .ok();
5619 });
5620 state.hide_task = Some(hide_task);
5621 }
5622 }
5623 }
5624
5625 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5626 if self.pending_rename.is_some() {
5627 return None;
5628 }
5629
5630 let provider = self.semantics_provider.clone()?;
5631 let buffer = self.buffer.read(cx);
5632 let newest_selection = self.selections.newest_anchor().clone();
5633 let cursor_position = newest_selection.head();
5634 let (cursor_buffer, cursor_buffer_position) =
5635 buffer.text_anchor_for_position(cursor_position, cx)?;
5636 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5637 if cursor_buffer != tail_buffer {
5638 return None;
5639 }
5640 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5641 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5642 cx.background_executor()
5643 .timer(Duration::from_millis(debounce))
5644 .await;
5645
5646 let highlights = if let Some(highlights) = cx
5647 .update(|cx| {
5648 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5649 })
5650 .ok()
5651 .flatten()
5652 {
5653 highlights.await.log_err()
5654 } else {
5655 None
5656 };
5657
5658 if let Some(highlights) = highlights {
5659 this.update(cx, |this, cx| {
5660 if this.pending_rename.is_some() {
5661 return;
5662 }
5663
5664 let buffer_id = cursor_position.buffer_id;
5665 let buffer = this.buffer.read(cx);
5666 if !buffer
5667 .text_anchor_for_position(cursor_position, cx)
5668 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5669 {
5670 return;
5671 }
5672
5673 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5674 let mut write_ranges = Vec::new();
5675 let mut read_ranges = Vec::new();
5676 for highlight in highlights {
5677 for (excerpt_id, excerpt_range) in
5678 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5679 {
5680 let start = highlight
5681 .range
5682 .start
5683 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5684 let end = highlight
5685 .range
5686 .end
5687 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5688 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5689 continue;
5690 }
5691
5692 let range = Anchor {
5693 buffer_id,
5694 excerpt_id,
5695 text_anchor: start,
5696 diff_base_anchor: None,
5697 }..Anchor {
5698 buffer_id,
5699 excerpt_id,
5700 text_anchor: end,
5701 diff_base_anchor: None,
5702 };
5703 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5704 write_ranges.push(range);
5705 } else {
5706 read_ranges.push(range);
5707 }
5708 }
5709 }
5710
5711 this.highlight_background::<DocumentHighlightRead>(
5712 &read_ranges,
5713 |theme| theme.editor_document_highlight_read_background,
5714 cx,
5715 );
5716 this.highlight_background::<DocumentHighlightWrite>(
5717 &write_ranges,
5718 |theme| theme.editor_document_highlight_write_background,
5719 cx,
5720 );
5721 cx.notify();
5722 })
5723 .log_err();
5724 }
5725 }));
5726 None
5727 }
5728
5729 fn prepare_highlight_query_from_selection(
5730 &mut self,
5731 cx: &mut Context<Editor>,
5732 ) -> Option<(String, Range<Anchor>)> {
5733 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5734 return None;
5735 }
5736 if !EditorSettings::get_global(cx).selection_highlight {
5737 return None;
5738 }
5739 if self.selections.count() != 1 || self.selections.line_mode {
5740 return None;
5741 }
5742 let selection = self.selections.newest::<Point>(cx);
5743 if selection.is_empty() || selection.start.row != selection.end.row {
5744 return None;
5745 }
5746 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5747 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5748 let query = multi_buffer_snapshot
5749 .text_for_range(selection_anchor_range.clone())
5750 .collect::<String>();
5751 if query.trim().is_empty() {
5752 return None;
5753 }
5754 Some((query, selection_anchor_range))
5755 }
5756
5757 fn update_selection_occurrence_highlights(
5758 &mut self,
5759 query_text: String,
5760 query_range: Range<Anchor>,
5761 multi_buffer_range_to_query: Range<Point>,
5762 use_debounce: bool,
5763 window: &mut Window,
5764 cx: &mut Context<Editor>,
5765 ) -> Task<()> {
5766 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5767 cx.spawn_in(window, async move |editor, cx| {
5768 if use_debounce {
5769 cx.background_executor()
5770 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5771 .await;
5772 }
5773 let match_task = cx.background_spawn(async move {
5774 let buffer_ranges = multi_buffer_snapshot
5775 .range_to_buffer_ranges(multi_buffer_range_to_query)
5776 .into_iter()
5777 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5778 let mut match_ranges = Vec::new();
5779 let Ok(regex) = project::search::SearchQuery::text(
5780 query_text.clone(),
5781 false,
5782 false,
5783 false,
5784 Default::default(),
5785 Default::default(),
5786 false,
5787 None,
5788 ) else {
5789 return Vec::default();
5790 };
5791 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5792 match_ranges.extend(
5793 regex
5794 .search(&buffer_snapshot, Some(search_range.clone()))
5795 .await
5796 .into_iter()
5797 .filter_map(|match_range| {
5798 let match_start = buffer_snapshot
5799 .anchor_after(search_range.start + match_range.start);
5800 let match_end = buffer_snapshot
5801 .anchor_before(search_range.start + match_range.end);
5802 let match_anchor_range = Anchor::range_in_buffer(
5803 excerpt_id,
5804 buffer_snapshot.remote_id(),
5805 match_start..match_end,
5806 );
5807 (match_anchor_range != query_range).then_some(match_anchor_range)
5808 }),
5809 );
5810 }
5811 match_ranges
5812 });
5813 let match_ranges = match_task.await;
5814 editor
5815 .update_in(cx, |editor, _, cx| {
5816 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5817 if !match_ranges.is_empty() {
5818 editor.highlight_background::<SelectedTextHighlight>(
5819 &match_ranges,
5820 |theme| theme.editor_document_highlight_bracket_background,
5821 cx,
5822 )
5823 }
5824 })
5825 .log_err();
5826 })
5827 }
5828
5829 fn refresh_selected_text_highlights(
5830 &mut self,
5831 on_buffer_edit: bool,
5832 window: &mut Window,
5833 cx: &mut Context<Editor>,
5834 ) {
5835 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5836 else {
5837 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5838 self.quick_selection_highlight_task.take();
5839 self.debounced_selection_highlight_task.take();
5840 return;
5841 };
5842 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5843 if on_buffer_edit
5844 || self
5845 .quick_selection_highlight_task
5846 .as_ref()
5847 .map_or(true, |(prev_anchor_range, _)| {
5848 prev_anchor_range != &query_range
5849 })
5850 {
5851 let multi_buffer_visible_start = self
5852 .scroll_manager
5853 .anchor()
5854 .anchor
5855 .to_point(&multi_buffer_snapshot);
5856 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5857 multi_buffer_visible_start
5858 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5859 Bias::Left,
5860 );
5861 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5862 self.quick_selection_highlight_task = Some((
5863 query_range.clone(),
5864 self.update_selection_occurrence_highlights(
5865 query_text.clone(),
5866 query_range.clone(),
5867 multi_buffer_visible_range,
5868 false,
5869 window,
5870 cx,
5871 ),
5872 ));
5873 }
5874 if on_buffer_edit
5875 || self
5876 .debounced_selection_highlight_task
5877 .as_ref()
5878 .map_or(true, |(prev_anchor_range, _)| {
5879 prev_anchor_range != &query_range
5880 })
5881 {
5882 let multi_buffer_start = multi_buffer_snapshot
5883 .anchor_before(0)
5884 .to_point(&multi_buffer_snapshot);
5885 let multi_buffer_end = multi_buffer_snapshot
5886 .anchor_after(multi_buffer_snapshot.len())
5887 .to_point(&multi_buffer_snapshot);
5888 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5889 self.debounced_selection_highlight_task = Some((
5890 query_range.clone(),
5891 self.update_selection_occurrence_highlights(
5892 query_text,
5893 query_range,
5894 multi_buffer_full_range,
5895 true,
5896 window,
5897 cx,
5898 ),
5899 ));
5900 }
5901 }
5902
5903 pub fn refresh_inline_completion(
5904 &mut self,
5905 debounce: bool,
5906 user_requested: bool,
5907 window: &mut Window,
5908 cx: &mut Context<Self>,
5909 ) -> Option<()> {
5910 let provider = self.edit_prediction_provider()?;
5911 let cursor = self.selections.newest_anchor().head();
5912 let (buffer, cursor_buffer_position) =
5913 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5914
5915 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5916 self.discard_inline_completion(false, cx);
5917 return None;
5918 }
5919
5920 if !user_requested
5921 && (!self.should_show_edit_predictions()
5922 || !self.is_focused(window)
5923 || buffer.read(cx).is_empty())
5924 {
5925 self.discard_inline_completion(false, cx);
5926 return None;
5927 }
5928
5929 self.update_visible_inline_completion(window, cx);
5930 provider.refresh(
5931 self.project.clone(),
5932 buffer,
5933 cursor_buffer_position,
5934 debounce,
5935 cx,
5936 );
5937 Some(())
5938 }
5939
5940 fn show_edit_predictions_in_menu(&self) -> bool {
5941 match self.edit_prediction_settings {
5942 EditPredictionSettings::Disabled => false,
5943 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5944 }
5945 }
5946
5947 pub fn edit_predictions_enabled(&self) -> bool {
5948 match self.edit_prediction_settings {
5949 EditPredictionSettings::Disabled => false,
5950 EditPredictionSettings::Enabled { .. } => true,
5951 }
5952 }
5953
5954 fn edit_prediction_requires_modifier(&self) -> bool {
5955 match self.edit_prediction_settings {
5956 EditPredictionSettings::Disabled => false,
5957 EditPredictionSettings::Enabled {
5958 preview_requires_modifier,
5959 ..
5960 } => preview_requires_modifier,
5961 }
5962 }
5963
5964 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5965 if self.edit_prediction_provider.is_none() {
5966 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5967 } else {
5968 let selection = self.selections.newest_anchor();
5969 let cursor = selection.head();
5970
5971 if let Some((buffer, cursor_buffer_position)) =
5972 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5973 {
5974 self.edit_prediction_settings =
5975 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5976 }
5977 }
5978 }
5979
5980 fn edit_prediction_settings_at_position(
5981 &self,
5982 buffer: &Entity<Buffer>,
5983 buffer_position: language::Anchor,
5984 cx: &App,
5985 ) -> EditPredictionSettings {
5986 if !self.mode.is_full()
5987 || !self.show_inline_completions_override.unwrap_or(true)
5988 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5989 {
5990 return EditPredictionSettings::Disabled;
5991 }
5992
5993 let buffer = buffer.read(cx);
5994
5995 let file = buffer.file();
5996
5997 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5998 return EditPredictionSettings::Disabled;
5999 };
6000
6001 let by_provider = matches!(
6002 self.menu_inline_completions_policy,
6003 MenuInlineCompletionsPolicy::ByProvider
6004 );
6005
6006 let show_in_menu = by_provider
6007 && self
6008 .edit_prediction_provider
6009 .as_ref()
6010 .map_or(false, |provider| {
6011 provider.provider.show_completions_in_menu()
6012 });
6013
6014 let preview_requires_modifier =
6015 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6016
6017 EditPredictionSettings::Enabled {
6018 show_in_menu,
6019 preview_requires_modifier,
6020 }
6021 }
6022
6023 fn should_show_edit_predictions(&self) -> bool {
6024 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6025 }
6026
6027 pub fn edit_prediction_preview_is_active(&self) -> bool {
6028 matches!(
6029 self.edit_prediction_preview,
6030 EditPredictionPreview::Active { .. }
6031 )
6032 }
6033
6034 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6035 let cursor = self.selections.newest_anchor().head();
6036 if let Some((buffer, cursor_position)) =
6037 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6038 {
6039 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6040 } else {
6041 false
6042 }
6043 }
6044
6045 fn edit_predictions_enabled_in_buffer(
6046 &self,
6047 buffer: &Entity<Buffer>,
6048 buffer_position: language::Anchor,
6049 cx: &App,
6050 ) -> bool {
6051 maybe!({
6052 if self.read_only(cx) {
6053 return Some(false);
6054 }
6055 let provider = self.edit_prediction_provider()?;
6056 if !provider.is_enabled(&buffer, buffer_position, cx) {
6057 return Some(false);
6058 }
6059 let buffer = buffer.read(cx);
6060 let Some(file) = buffer.file() else {
6061 return Some(true);
6062 };
6063 let settings = all_language_settings(Some(file), cx);
6064 Some(settings.edit_predictions_enabled_for_file(file, cx))
6065 })
6066 .unwrap_or(false)
6067 }
6068
6069 fn cycle_inline_completion(
6070 &mut self,
6071 direction: Direction,
6072 window: &mut Window,
6073 cx: &mut Context<Self>,
6074 ) -> Option<()> {
6075 let provider = self.edit_prediction_provider()?;
6076 let cursor = self.selections.newest_anchor().head();
6077 let (buffer, cursor_buffer_position) =
6078 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6079 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6080 return None;
6081 }
6082
6083 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6084 self.update_visible_inline_completion(window, cx);
6085
6086 Some(())
6087 }
6088
6089 pub fn show_inline_completion(
6090 &mut self,
6091 _: &ShowEditPrediction,
6092 window: &mut Window,
6093 cx: &mut Context<Self>,
6094 ) {
6095 if !self.has_active_inline_completion() {
6096 self.refresh_inline_completion(false, true, window, cx);
6097 return;
6098 }
6099
6100 self.update_visible_inline_completion(window, cx);
6101 }
6102
6103 pub fn display_cursor_names(
6104 &mut self,
6105 _: &DisplayCursorNames,
6106 window: &mut Window,
6107 cx: &mut Context<Self>,
6108 ) {
6109 self.show_cursor_names(window, cx);
6110 }
6111
6112 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6113 self.show_cursor_names = true;
6114 cx.notify();
6115 cx.spawn_in(window, async move |this, cx| {
6116 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6117 this.update(cx, |this, cx| {
6118 this.show_cursor_names = false;
6119 cx.notify()
6120 })
6121 .ok()
6122 })
6123 .detach();
6124 }
6125
6126 pub fn next_edit_prediction(
6127 &mut self,
6128 _: &NextEditPrediction,
6129 window: &mut Window,
6130 cx: &mut Context<Self>,
6131 ) {
6132 if self.has_active_inline_completion() {
6133 self.cycle_inline_completion(Direction::Next, window, cx);
6134 } else {
6135 let is_copilot_disabled = self
6136 .refresh_inline_completion(false, true, window, cx)
6137 .is_none();
6138 if is_copilot_disabled {
6139 cx.propagate();
6140 }
6141 }
6142 }
6143
6144 pub fn previous_edit_prediction(
6145 &mut self,
6146 _: &PreviousEditPrediction,
6147 window: &mut Window,
6148 cx: &mut Context<Self>,
6149 ) {
6150 if self.has_active_inline_completion() {
6151 self.cycle_inline_completion(Direction::Prev, window, cx);
6152 } else {
6153 let is_copilot_disabled = self
6154 .refresh_inline_completion(false, true, window, cx)
6155 .is_none();
6156 if is_copilot_disabled {
6157 cx.propagate();
6158 }
6159 }
6160 }
6161
6162 pub fn accept_edit_prediction(
6163 &mut self,
6164 _: &AcceptEditPrediction,
6165 window: &mut Window,
6166 cx: &mut Context<Self>,
6167 ) {
6168 if self.show_edit_predictions_in_menu() {
6169 self.hide_context_menu(window, cx);
6170 }
6171
6172 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6173 return;
6174 };
6175
6176 self.report_inline_completion_event(
6177 active_inline_completion.completion_id.clone(),
6178 true,
6179 cx,
6180 );
6181
6182 match &active_inline_completion.completion {
6183 InlineCompletion::Move { target, .. } => {
6184 let target = *target;
6185
6186 if let Some(position_map) = &self.last_position_map {
6187 if position_map
6188 .visible_row_range
6189 .contains(&target.to_display_point(&position_map.snapshot).row())
6190 || !self.edit_prediction_requires_modifier()
6191 {
6192 self.unfold_ranges(&[target..target], true, false, cx);
6193 // Note that this is also done in vim's handler of the Tab action.
6194 self.change_selections(
6195 Some(Autoscroll::newest()),
6196 window,
6197 cx,
6198 |selections| {
6199 selections.select_anchor_ranges([target..target]);
6200 },
6201 );
6202 self.clear_row_highlights::<EditPredictionPreview>();
6203
6204 self.edit_prediction_preview
6205 .set_previous_scroll_position(None);
6206 } else {
6207 self.edit_prediction_preview
6208 .set_previous_scroll_position(Some(
6209 position_map.snapshot.scroll_anchor,
6210 ));
6211
6212 self.highlight_rows::<EditPredictionPreview>(
6213 target..target,
6214 cx.theme().colors().editor_highlighted_line_background,
6215 RowHighlightOptions {
6216 autoscroll: true,
6217 ..Default::default()
6218 },
6219 cx,
6220 );
6221 self.request_autoscroll(Autoscroll::fit(), cx);
6222 }
6223 }
6224 }
6225 InlineCompletion::Edit { edits, .. } => {
6226 if let Some(provider) = self.edit_prediction_provider() {
6227 provider.accept(cx);
6228 }
6229
6230 let snapshot = self.buffer.read(cx).snapshot(cx);
6231 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6232
6233 self.buffer.update(cx, |buffer, cx| {
6234 buffer.edit(edits.iter().cloned(), None, cx)
6235 });
6236
6237 self.change_selections(None, window, cx, |s| {
6238 s.select_anchor_ranges([last_edit_end..last_edit_end])
6239 });
6240
6241 self.update_visible_inline_completion(window, cx);
6242 if self.active_inline_completion.is_none() {
6243 self.refresh_inline_completion(true, true, window, cx);
6244 }
6245
6246 cx.notify();
6247 }
6248 }
6249
6250 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6251 }
6252
6253 pub fn accept_partial_inline_completion(
6254 &mut self,
6255 _: &AcceptPartialEditPrediction,
6256 window: &mut Window,
6257 cx: &mut Context<Self>,
6258 ) {
6259 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6260 return;
6261 };
6262 if self.selections.count() != 1 {
6263 return;
6264 }
6265
6266 self.report_inline_completion_event(
6267 active_inline_completion.completion_id.clone(),
6268 true,
6269 cx,
6270 );
6271
6272 match &active_inline_completion.completion {
6273 InlineCompletion::Move { target, .. } => {
6274 let target = *target;
6275 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6276 selections.select_anchor_ranges([target..target]);
6277 });
6278 }
6279 InlineCompletion::Edit { edits, .. } => {
6280 // Find an insertion that starts at the cursor position.
6281 let snapshot = self.buffer.read(cx).snapshot(cx);
6282 let cursor_offset = self.selections.newest::<usize>(cx).head();
6283 let insertion = edits.iter().find_map(|(range, text)| {
6284 let range = range.to_offset(&snapshot);
6285 if range.is_empty() && range.start == cursor_offset {
6286 Some(text)
6287 } else {
6288 None
6289 }
6290 });
6291
6292 if let Some(text) = insertion {
6293 let mut partial_completion = text
6294 .chars()
6295 .by_ref()
6296 .take_while(|c| c.is_alphabetic())
6297 .collect::<String>();
6298 if partial_completion.is_empty() {
6299 partial_completion = text
6300 .chars()
6301 .by_ref()
6302 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6303 .collect::<String>();
6304 }
6305
6306 cx.emit(EditorEvent::InputHandled {
6307 utf16_range_to_replace: None,
6308 text: partial_completion.clone().into(),
6309 });
6310
6311 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6312
6313 self.refresh_inline_completion(true, true, window, cx);
6314 cx.notify();
6315 } else {
6316 self.accept_edit_prediction(&Default::default(), window, cx);
6317 }
6318 }
6319 }
6320 }
6321
6322 fn discard_inline_completion(
6323 &mut self,
6324 should_report_inline_completion_event: bool,
6325 cx: &mut Context<Self>,
6326 ) -> bool {
6327 if should_report_inline_completion_event {
6328 let completion_id = self
6329 .active_inline_completion
6330 .as_ref()
6331 .and_then(|active_completion| active_completion.completion_id.clone());
6332
6333 self.report_inline_completion_event(completion_id, false, cx);
6334 }
6335
6336 if let Some(provider) = self.edit_prediction_provider() {
6337 provider.discard(cx);
6338 }
6339
6340 self.take_active_inline_completion(cx)
6341 }
6342
6343 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6344 let Some(provider) = self.edit_prediction_provider() else {
6345 return;
6346 };
6347
6348 let Some((_, buffer, _)) = self
6349 .buffer
6350 .read(cx)
6351 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6352 else {
6353 return;
6354 };
6355
6356 let extension = buffer
6357 .read(cx)
6358 .file()
6359 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6360
6361 let event_type = match accepted {
6362 true => "Edit Prediction Accepted",
6363 false => "Edit Prediction Discarded",
6364 };
6365 telemetry::event!(
6366 event_type,
6367 provider = provider.name(),
6368 prediction_id = id,
6369 suggestion_accepted = accepted,
6370 file_extension = extension,
6371 );
6372 }
6373
6374 pub fn has_active_inline_completion(&self) -> bool {
6375 self.active_inline_completion.is_some()
6376 }
6377
6378 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6379 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6380 return false;
6381 };
6382
6383 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6384 self.clear_highlights::<InlineCompletionHighlight>(cx);
6385 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6386 true
6387 }
6388
6389 /// Returns true when we're displaying the edit prediction popover below the cursor
6390 /// like we are not previewing and the LSP autocomplete menu is visible
6391 /// or we are in `when_holding_modifier` mode.
6392 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6393 if self.edit_prediction_preview_is_active()
6394 || !self.show_edit_predictions_in_menu()
6395 || !self.edit_predictions_enabled()
6396 {
6397 return false;
6398 }
6399
6400 if self.has_visible_completions_menu() {
6401 return true;
6402 }
6403
6404 has_completion && self.edit_prediction_requires_modifier()
6405 }
6406
6407 fn handle_modifiers_changed(
6408 &mut self,
6409 modifiers: Modifiers,
6410 position_map: &PositionMap,
6411 window: &mut Window,
6412 cx: &mut Context<Self>,
6413 ) {
6414 if self.show_edit_predictions_in_menu() {
6415 self.update_edit_prediction_preview(&modifiers, window, cx);
6416 }
6417
6418 self.update_selection_mode(&modifiers, position_map, window, cx);
6419
6420 let mouse_position = window.mouse_position();
6421 if !position_map.text_hitbox.is_hovered(window) {
6422 return;
6423 }
6424
6425 self.update_hovered_link(
6426 position_map.point_for_position(mouse_position),
6427 &position_map.snapshot,
6428 modifiers,
6429 window,
6430 cx,
6431 )
6432 }
6433
6434 fn update_selection_mode(
6435 &mut self,
6436 modifiers: &Modifiers,
6437 position_map: &PositionMap,
6438 window: &mut Window,
6439 cx: &mut Context<Self>,
6440 ) {
6441 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6442 return;
6443 }
6444
6445 let mouse_position = window.mouse_position();
6446 let point_for_position = position_map.point_for_position(mouse_position);
6447 let position = point_for_position.previous_valid;
6448
6449 self.select(
6450 SelectPhase::BeginColumnar {
6451 position,
6452 reset: false,
6453 goal_column: point_for_position.exact_unclipped.column(),
6454 },
6455 window,
6456 cx,
6457 );
6458 }
6459
6460 fn update_edit_prediction_preview(
6461 &mut self,
6462 modifiers: &Modifiers,
6463 window: &mut Window,
6464 cx: &mut Context<Self>,
6465 ) {
6466 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6467 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6468 return;
6469 };
6470
6471 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6472 if matches!(
6473 self.edit_prediction_preview,
6474 EditPredictionPreview::Inactive { .. }
6475 ) {
6476 self.edit_prediction_preview = EditPredictionPreview::Active {
6477 previous_scroll_position: None,
6478 since: Instant::now(),
6479 };
6480
6481 self.update_visible_inline_completion(window, cx);
6482 cx.notify();
6483 }
6484 } else if let EditPredictionPreview::Active {
6485 previous_scroll_position,
6486 since,
6487 } = self.edit_prediction_preview
6488 {
6489 if let (Some(previous_scroll_position), Some(position_map)) =
6490 (previous_scroll_position, self.last_position_map.as_ref())
6491 {
6492 self.set_scroll_position(
6493 previous_scroll_position
6494 .scroll_position(&position_map.snapshot.display_snapshot),
6495 window,
6496 cx,
6497 );
6498 }
6499
6500 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6501 released_too_fast: since.elapsed() < Duration::from_millis(200),
6502 };
6503 self.clear_row_highlights::<EditPredictionPreview>();
6504 self.update_visible_inline_completion(window, cx);
6505 cx.notify();
6506 }
6507 }
6508
6509 fn update_visible_inline_completion(
6510 &mut self,
6511 _window: &mut Window,
6512 cx: &mut Context<Self>,
6513 ) -> Option<()> {
6514 let selection = self.selections.newest_anchor();
6515 let cursor = selection.head();
6516 let multibuffer = self.buffer.read(cx).snapshot(cx);
6517 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6518 let excerpt_id = cursor.excerpt_id;
6519
6520 let show_in_menu = self.show_edit_predictions_in_menu();
6521 let completions_menu_has_precedence = !show_in_menu
6522 && (self.context_menu.borrow().is_some()
6523 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6524
6525 if completions_menu_has_precedence
6526 || !offset_selection.is_empty()
6527 || self
6528 .active_inline_completion
6529 .as_ref()
6530 .map_or(false, |completion| {
6531 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6532 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6533 !invalidation_range.contains(&offset_selection.head())
6534 })
6535 {
6536 self.discard_inline_completion(false, cx);
6537 return None;
6538 }
6539
6540 self.take_active_inline_completion(cx);
6541 let Some(provider) = self.edit_prediction_provider() else {
6542 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6543 return None;
6544 };
6545
6546 let (buffer, cursor_buffer_position) =
6547 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6548
6549 self.edit_prediction_settings =
6550 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6551
6552 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6553
6554 if self.edit_prediction_indent_conflict {
6555 let cursor_point = cursor.to_point(&multibuffer);
6556
6557 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6558
6559 if let Some((_, indent)) = indents.iter().next() {
6560 if indent.len == cursor_point.column {
6561 self.edit_prediction_indent_conflict = false;
6562 }
6563 }
6564 }
6565
6566 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6567 let edits = inline_completion
6568 .edits
6569 .into_iter()
6570 .flat_map(|(range, new_text)| {
6571 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6572 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6573 Some((start..end, new_text))
6574 })
6575 .collect::<Vec<_>>();
6576 if edits.is_empty() {
6577 return None;
6578 }
6579
6580 let first_edit_start = edits.first().unwrap().0.start;
6581 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6582 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6583
6584 let last_edit_end = edits.last().unwrap().0.end;
6585 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6586 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6587
6588 let cursor_row = cursor.to_point(&multibuffer).row;
6589
6590 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6591
6592 let mut inlay_ids = Vec::new();
6593 let invalidation_row_range;
6594 let move_invalidation_row_range = if cursor_row < edit_start_row {
6595 Some(cursor_row..edit_end_row)
6596 } else if cursor_row > edit_end_row {
6597 Some(edit_start_row..cursor_row)
6598 } else {
6599 None
6600 };
6601 let is_move =
6602 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6603 let completion = if is_move {
6604 invalidation_row_range =
6605 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6606 let target = first_edit_start;
6607 InlineCompletion::Move { target, snapshot }
6608 } else {
6609 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6610 && !self.inline_completions_hidden_for_vim_mode;
6611
6612 if show_completions_in_buffer {
6613 if edits
6614 .iter()
6615 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6616 {
6617 let mut inlays = Vec::new();
6618 for (range, new_text) in &edits {
6619 let inlay = Inlay::inline_completion(
6620 post_inc(&mut self.next_inlay_id),
6621 range.start,
6622 new_text.as_str(),
6623 );
6624 inlay_ids.push(inlay.id);
6625 inlays.push(inlay);
6626 }
6627
6628 self.splice_inlays(&[], inlays, cx);
6629 } else {
6630 let background_color = cx.theme().status().deleted_background;
6631 self.highlight_text::<InlineCompletionHighlight>(
6632 edits.iter().map(|(range, _)| range.clone()).collect(),
6633 HighlightStyle {
6634 background_color: Some(background_color),
6635 ..Default::default()
6636 },
6637 cx,
6638 );
6639 }
6640 }
6641
6642 invalidation_row_range = edit_start_row..edit_end_row;
6643
6644 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6645 if provider.show_tab_accept_marker() {
6646 EditDisplayMode::TabAccept
6647 } else {
6648 EditDisplayMode::Inline
6649 }
6650 } else {
6651 EditDisplayMode::DiffPopover
6652 };
6653
6654 InlineCompletion::Edit {
6655 edits,
6656 edit_preview: inline_completion.edit_preview,
6657 display_mode,
6658 snapshot,
6659 }
6660 };
6661
6662 let invalidation_range = multibuffer
6663 .anchor_before(Point::new(invalidation_row_range.start, 0))
6664 ..multibuffer.anchor_after(Point::new(
6665 invalidation_row_range.end,
6666 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6667 ));
6668
6669 self.stale_inline_completion_in_menu = None;
6670 self.active_inline_completion = Some(InlineCompletionState {
6671 inlay_ids,
6672 completion,
6673 completion_id: inline_completion.id,
6674 invalidation_range,
6675 });
6676
6677 cx.notify();
6678
6679 Some(())
6680 }
6681
6682 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6683 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6684 }
6685
6686 fn render_code_actions_indicator(
6687 &self,
6688 _style: &EditorStyle,
6689 row: DisplayRow,
6690 is_active: bool,
6691 breakpoint: Option<&(Anchor, Breakpoint)>,
6692 cx: &mut Context<Self>,
6693 ) -> Option<IconButton> {
6694 let color = Color::Muted;
6695 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6696 let show_tooltip = !self.context_menu_visible();
6697
6698 if self.available_code_actions.is_some() {
6699 Some(
6700 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6701 .shape(ui::IconButtonShape::Square)
6702 .icon_size(IconSize::XSmall)
6703 .icon_color(color)
6704 .toggle_state(is_active)
6705 .when(show_tooltip, |this| {
6706 this.tooltip({
6707 let focus_handle = self.focus_handle.clone();
6708 move |window, cx| {
6709 Tooltip::for_action_in(
6710 "Toggle Code Actions",
6711 &ToggleCodeActions {
6712 deployed_from_indicator: None,
6713 quick_launch: false,
6714 },
6715 &focus_handle,
6716 window,
6717 cx,
6718 )
6719 }
6720 })
6721 })
6722 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
6723 let quick_launch = e.down.button == MouseButton::Left;
6724 window.focus(&editor.focus_handle(cx));
6725 editor.toggle_code_actions(
6726 &ToggleCodeActions {
6727 deployed_from_indicator: Some(row),
6728 quick_launch,
6729 },
6730 window,
6731 cx,
6732 );
6733 }))
6734 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6735 editor.set_breakpoint_context_menu(
6736 row,
6737 position,
6738 event.down.position,
6739 window,
6740 cx,
6741 );
6742 })),
6743 )
6744 } else {
6745 None
6746 }
6747 }
6748
6749 fn clear_tasks(&mut self) {
6750 self.tasks.clear()
6751 }
6752
6753 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6754 if self.tasks.insert(key, value).is_some() {
6755 // This case should hopefully be rare, but just in case...
6756 log::error!(
6757 "multiple different run targets found on a single line, only the last target will be rendered"
6758 )
6759 }
6760 }
6761
6762 /// Get all display points of breakpoints that will be rendered within editor
6763 ///
6764 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6765 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6766 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6767 fn active_breakpoints(
6768 &self,
6769 range: Range<DisplayRow>,
6770 window: &mut Window,
6771 cx: &mut Context<Self>,
6772 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6773 let mut breakpoint_display_points = HashMap::default();
6774
6775 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6776 return breakpoint_display_points;
6777 };
6778
6779 let snapshot = self.snapshot(window, cx);
6780
6781 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6782 let Some(project) = self.project.as_ref() else {
6783 return breakpoint_display_points;
6784 };
6785
6786 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6787 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6788
6789 for (buffer_snapshot, range, excerpt_id) in
6790 multi_buffer_snapshot.range_to_buffer_ranges(range)
6791 {
6792 let Some(buffer) = project.read_with(cx, |this, cx| {
6793 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6794 }) else {
6795 continue;
6796 };
6797 let breakpoints = breakpoint_store.read(cx).breakpoints(
6798 &buffer,
6799 Some(
6800 buffer_snapshot.anchor_before(range.start)
6801 ..buffer_snapshot.anchor_after(range.end),
6802 ),
6803 buffer_snapshot,
6804 cx,
6805 );
6806 for (anchor, breakpoint) in breakpoints {
6807 let multi_buffer_anchor =
6808 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6809 let position = multi_buffer_anchor
6810 .to_point(&multi_buffer_snapshot)
6811 .to_display_point(&snapshot);
6812
6813 breakpoint_display_points
6814 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6815 }
6816 }
6817
6818 breakpoint_display_points
6819 }
6820
6821 fn breakpoint_context_menu(
6822 &self,
6823 anchor: Anchor,
6824 window: &mut Window,
6825 cx: &mut Context<Self>,
6826 ) -> Entity<ui::ContextMenu> {
6827 let weak_editor = cx.weak_entity();
6828 let focus_handle = self.focus_handle(cx);
6829
6830 let row = self
6831 .buffer
6832 .read(cx)
6833 .snapshot(cx)
6834 .summary_for_anchor::<Point>(&anchor)
6835 .row;
6836
6837 let breakpoint = self
6838 .breakpoint_at_row(row, window, cx)
6839 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6840
6841 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6842 "Edit Log Breakpoint"
6843 } else {
6844 "Set Log Breakpoint"
6845 };
6846
6847 let condition_breakpoint_msg = if breakpoint
6848 .as_ref()
6849 .is_some_and(|bp| bp.1.condition.is_some())
6850 {
6851 "Edit Condition Breakpoint"
6852 } else {
6853 "Set Condition Breakpoint"
6854 };
6855
6856 let hit_condition_breakpoint_msg = if breakpoint
6857 .as_ref()
6858 .is_some_and(|bp| bp.1.hit_condition.is_some())
6859 {
6860 "Edit Hit Condition Breakpoint"
6861 } else {
6862 "Set Hit Condition Breakpoint"
6863 };
6864
6865 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6866 "Unset Breakpoint"
6867 } else {
6868 "Set Breakpoint"
6869 };
6870
6871 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6872 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6873
6874 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6875 BreakpointState::Enabled => Some("Disable"),
6876 BreakpointState::Disabled => Some("Enable"),
6877 });
6878
6879 let (anchor, breakpoint) =
6880 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6881
6882 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6883 menu.on_blur_subscription(Subscription::new(|| {}))
6884 .context(focus_handle)
6885 .when(run_to_cursor, |this| {
6886 let weak_editor = weak_editor.clone();
6887 this.entry("Run to cursor", None, move |window, cx| {
6888 weak_editor
6889 .update(cx, |editor, cx| {
6890 editor.change_selections(None, window, cx, |s| {
6891 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6892 });
6893 })
6894 .ok();
6895
6896 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6897 })
6898 .separator()
6899 })
6900 .when_some(toggle_state_msg, |this, msg| {
6901 this.entry(msg, None, {
6902 let weak_editor = weak_editor.clone();
6903 let breakpoint = breakpoint.clone();
6904 move |_window, cx| {
6905 weak_editor
6906 .update(cx, |this, cx| {
6907 this.edit_breakpoint_at_anchor(
6908 anchor,
6909 breakpoint.as_ref().clone(),
6910 BreakpointEditAction::InvertState,
6911 cx,
6912 );
6913 })
6914 .log_err();
6915 }
6916 })
6917 })
6918 .entry(set_breakpoint_msg, None, {
6919 let weak_editor = weak_editor.clone();
6920 let breakpoint = breakpoint.clone();
6921 move |_window, cx| {
6922 weak_editor
6923 .update(cx, |this, cx| {
6924 this.edit_breakpoint_at_anchor(
6925 anchor,
6926 breakpoint.as_ref().clone(),
6927 BreakpointEditAction::Toggle,
6928 cx,
6929 );
6930 })
6931 .log_err();
6932 }
6933 })
6934 .entry(log_breakpoint_msg, None, {
6935 let breakpoint = breakpoint.clone();
6936 let weak_editor = weak_editor.clone();
6937 move |window, cx| {
6938 weak_editor
6939 .update(cx, |this, cx| {
6940 this.add_edit_breakpoint_block(
6941 anchor,
6942 breakpoint.as_ref(),
6943 BreakpointPromptEditAction::Log,
6944 window,
6945 cx,
6946 );
6947 })
6948 .log_err();
6949 }
6950 })
6951 .entry(condition_breakpoint_msg, None, {
6952 let breakpoint = breakpoint.clone();
6953 let weak_editor = weak_editor.clone();
6954 move |window, cx| {
6955 weak_editor
6956 .update(cx, |this, cx| {
6957 this.add_edit_breakpoint_block(
6958 anchor,
6959 breakpoint.as_ref(),
6960 BreakpointPromptEditAction::Condition,
6961 window,
6962 cx,
6963 );
6964 })
6965 .log_err();
6966 }
6967 })
6968 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6969 weak_editor
6970 .update(cx, |this, cx| {
6971 this.add_edit_breakpoint_block(
6972 anchor,
6973 breakpoint.as_ref(),
6974 BreakpointPromptEditAction::HitCondition,
6975 window,
6976 cx,
6977 );
6978 })
6979 .log_err();
6980 })
6981 })
6982 }
6983
6984 fn render_breakpoint(
6985 &self,
6986 position: Anchor,
6987 row: DisplayRow,
6988 breakpoint: &Breakpoint,
6989 cx: &mut Context<Self>,
6990 ) -> IconButton {
6991 // Is it a breakpoint that shows up when hovering over gutter?
6992 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
6993 (false, false),
6994 |PhantomBreakpointIndicator {
6995 is_active,
6996 display_row,
6997 collides_with_existing_breakpoint,
6998 }| {
6999 (
7000 is_active && display_row == row,
7001 collides_with_existing_breakpoint,
7002 )
7003 },
7004 );
7005
7006 let (color, icon) = {
7007 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7008 (false, false) => ui::IconName::DebugBreakpoint,
7009 (true, false) => ui::IconName::DebugLogBreakpoint,
7010 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7011 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7012 };
7013
7014 let color = if is_phantom {
7015 Color::Hint
7016 } else {
7017 Color::Debugger
7018 };
7019
7020 (color, icon)
7021 };
7022
7023 let breakpoint = Arc::from(breakpoint.clone());
7024
7025 let alt_as_text = gpui::Keystroke {
7026 modifiers: Modifiers::secondary_key(),
7027 ..Default::default()
7028 };
7029 let primary_action_text = if breakpoint.is_disabled() {
7030 "enable"
7031 } else if is_phantom && !collides_with_existing {
7032 "set"
7033 } else {
7034 "unset"
7035 };
7036 let mut primary_text = format!("Click to {primary_action_text}");
7037 if collides_with_existing && !breakpoint.is_disabled() {
7038 use std::fmt::Write;
7039 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7040 }
7041 let primary_text = SharedString::from(primary_text);
7042 let focus_handle = self.focus_handle.clone();
7043 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7044 .icon_size(IconSize::XSmall)
7045 .size(ui::ButtonSize::None)
7046 .icon_color(color)
7047 .style(ButtonStyle::Transparent)
7048 .on_click(cx.listener({
7049 let breakpoint = breakpoint.clone();
7050
7051 move |editor, event: &ClickEvent, window, cx| {
7052 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7053 BreakpointEditAction::InvertState
7054 } else {
7055 BreakpointEditAction::Toggle
7056 };
7057
7058 window.focus(&editor.focus_handle(cx));
7059 editor.edit_breakpoint_at_anchor(
7060 position,
7061 breakpoint.as_ref().clone(),
7062 edit_action,
7063 cx,
7064 );
7065 }
7066 }))
7067 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7068 editor.set_breakpoint_context_menu(
7069 row,
7070 Some(position),
7071 event.down.position,
7072 window,
7073 cx,
7074 );
7075 }))
7076 .tooltip(move |window, cx| {
7077 Tooltip::with_meta_in(
7078 primary_text.clone(),
7079 None,
7080 "Right-click for more options",
7081 &focus_handle,
7082 window,
7083 cx,
7084 )
7085 })
7086 }
7087
7088 fn build_tasks_context(
7089 project: &Entity<Project>,
7090 buffer: &Entity<Buffer>,
7091 buffer_row: u32,
7092 tasks: &Arc<RunnableTasks>,
7093 cx: &mut Context<Self>,
7094 ) -> Task<Option<task::TaskContext>> {
7095 let position = Point::new(buffer_row, tasks.column);
7096 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7097 let location = Location {
7098 buffer: buffer.clone(),
7099 range: range_start..range_start,
7100 };
7101 // Fill in the environmental variables from the tree-sitter captures
7102 let mut captured_task_variables = TaskVariables::default();
7103 for (capture_name, value) in tasks.extra_variables.clone() {
7104 captured_task_variables.insert(
7105 task::VariableName::Custom(capture_name.into()),
7106 value.clone(),
7107 );
7108 }
7109 project.update(cx, |project, cx| {
7110 project.task_store().update(cx, |task_store, cx| {
7111 task_store.task_context_for_location(captured_task_variables, location, cx)
7112 })
7113 })
7114 }
7115
7116 pub fn spawn_nearest_task(
7117 &mut self,
7118 action: &SpawnNearestTask,
7119 window: &mut Window,
7120 cx: &mut Context<Self>,
7121 ) {
7122 let Some((workspace, _)) = self.workspace.clone() else {
7123 return;
7124 };
7125 let Some(project) = self.project.clone() else {
7126 return;
7127 };
7128
7129 // Try to find a closest, enclosing node using tree-sitter that has a
7130 // task
7131 let Some((buffer, buffer_row, tasks)) = self
7132 .find_enclosing_node_task(cx)
7133 // Or find the task that's closest in row-distance.
7134 .or_else(|| self.find_closest_task(cx))
7135 else {
7136 return;
7137 };
7138
7139 let reveal_strategy = action.reveal;
7140 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7141 cx.spawn_in(window, async move |_, cx| {
7142 let context = task_context.await?;
7143 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7144
7145 let resolved = &mut resolved_task.resolved;
7146 resolved.reveal = reveal_strategy;
7147
7148 workspace
7149 .update_in(cx, |workspace, window, cx| {
7150 workspace.schedule_resolved_task(
7151 task_source_kind,
7152 resolved_task,
7153 false,
7154 window,
7155 cx,
7156 );
7157 })
7158 .ok()
7159 })
7160 .detach();
7161 }
7162
7163 fn find_closest_task(
7164 &mut self,
7165 cx: &mut Context<Self>,
7166 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7167 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7168
7169 let ((buffer_id, row), tasks) = self
7170 .tasks
7171 .iter()
7172 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7173
7174 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7175 let tasks = Arc::new(tasks.to_owned());
7176 Some((buffer, *row, tasks))
7177 }
7178
7179 fn find_enclosing_node_task(
7180 &mut self,
7181 cx: &mut Context<Self>,
7182 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7183 let snapshot = self.buffer.read(cx).snapshot(cx);
7184 let offset = self.selections.newest::<usize>(cx).head();
7185 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7186 let buffer_id = excerpt.buffer().remote_id();
7187
7188 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7189 let mut cursor = layer.node().walk();
7190
7191 while cursor.goto_first_child_for_byte(offset).is_some() {
7192 if cursor.node().end_byte() == offset {
7193 cursor.goto_next_sibling();
7194 }
7195 }
7196
7197 // Ascend to the smallest ancestor that contains the range and has a task.
7198 loop {
7199 let node = cursor.node();
7200 let node_range = node.byte_range();
7201 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7202
7203 // Check if this node contains our offset
7204 if node_range.start <= offset && node_range.end >= offset {
7205 // If it contains offset, check for task
7206 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7207 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7208 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7209 }
7210 }
7211
7212 if !cursor.goto_parent() {
7213 break;
7214 }
7215 }
7216 None
7217 }
7218
7219 fn render_run_indicator(
7220 &self,
7221 _style: &EditorStyle,
7222 is_active: bool,
7223 row: DisplayRow,
7224 breakpoint: Option<(Anchor, Breakpoint)>,
7225 cx: &mut Context<Self>,
7226 ) -> IconButton {
7227 let color = Color::Muted;
7228 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7229
7230 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7231 .shape(ui::IconButtonShape::Square)
7232 .icon_size(IconSize::XSmall)
7233 .icon_color(color)
7234 .toggle_state(is_active)
7235 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7236 let quick_launch = e.down.button == MouseButton::Left;
7237 window.focus(&editor.focus_handle(cx));
7238 editor.toggle_code_actions(
7239 &ToggleCodeActions {
7240 deployed_from_indicator: Some(row),
7241 quick_launch,
7242 },
7243 window,
7244 cx,
7245 );
7246 }))
7247 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7248 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7249 }))
7250 }
7251
7252 pub fn context_menu_visible(&self) -> bool {
7253 !self.edit_prediction_preview_is_active()
7254 && self
7255 .context_menu
7256 .borrow()
7257 .as_ref()
7258 .map_or(false, |menu| menu.visible())
7259 }
7260
7261 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7262 self.context_menu
7263 .borrow()
7264 .as_ref()
7265 .map(|menu| menu.origin())
7266 }
7267
7268 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7269 self.context_menu_options = Some(options);
7270 }
7271
7272 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7273 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7274
7275 fn render_edit_prediction_popover(
7276 &mut self,
7277 text_bounds: &Bounds<Pixels>,
7278 content_origin: gpui::Point<Pixels>,
7279 editor_snapshot: &EditorSnapshot,
7280 visible_row_range: Range<DisplayRow>,
7281 scroll_top: f32,
7282 scroll_bottom: f32,
7283 line_layouts: &[LineWithInvisibles],
7284 line_height: Pixels,
7285 scroll_pixel_position: gpui::Point<Pixels>,
7286 newest_selection_head: Option<DisplayPoint>,
7287 editor_width: Pixels,
7288 style: &EditorStyle,
7289 window: &mut Window,
7290 cx: &mut App,
7291 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7292 let active_inline_completion = self.active_inline_completion.as_ref()?;
7293
7294 if self.edit_prediction_visible_in_cursor_popover(true) {
7295 return None;
7296 }
7297
7298 match &active_inline_completion.completion {
7299 InlineCompletion::Move { target, .. } => {
7300 let target_display_point = target.to_display_point(editor_snapshot);
7301
7302 if self.edit_prediction_requires_modifier() {
7303 if !self.edit_prediction_preview_is_active() {
7304 return None;
7305 }
7306
7307 self.render_edit_prediction_modifier_jump_popover(
7308 text_bounds,
7309 content_origin,
7310 visible_row_range,
7311 line_layouts,
7312 line_height,
7313 scroll_pixel_position,
7314 newest_selection_head,
7315 target_display_point,
7316 window,
7317 cx,
7318 )
7319 } else {
7320 self.render_edit_prediction_eager_jump_popover(
7321 text_bounds,
7322 content_origin,
7323 editor_snapshot,
7324 visible_row_range,
7325 scroll_top,
7326 scroll_bottom,
7327 line_height,
7328 scroll_pixel_position,
7329 target_display_point,
7330 editor_width,
7331 window,
7332 cx,
7333 )
7334 }
7335 }
7336 InlineCompletion::Edit {
7337 display_mode: EditDisplayMode::Inline,
7338 ..
7339 } => None,
7340 InlineCompletion::Edit {
7341 display_mode: EditDisplayMode::TabAccept,
7342 edits,
7343 ..
7344 } => {
7345 let range = &edits.first()?.0;
7346 let target_display_point = range.end.to_display_point(editor_snapshot);
7347
7348 self.render_edit_prediction_end_of_line_popover(
7349 "Accept",
7350 editor_snapshot,
7351 visible_row_range,
7352 target_display_point,
7353 line_height,
7354 scroll_pixel_position,
7355 content_origin,
7356 editor_width,
7357 window,
7358 cx,
7359 )
7360 }
7361 InlineCompletion::Edit {
7362 edits,
7363 edit_preview,
7364 display_mode: EditDisplayMode::DiffPopover,
7365 snapshot,
7366 } => self.render_edit_prediction_diff_popover(
7367 text_bounds,
7368 content_origin,
7369 editor_snapshot,
7370 visible_row_range,
7371 line_layouts,
7372 line_height,
7373 scroll_pixel_position,
7374 newest_selection_head,
7375 editor_width,
7376 style,
7377 edits,
7378 edit_preview,
7379 snapshot,
7380 window,
7381 cx,
7382 ),
7383 }
7384 }
7385
7386 fn render_edit_prediction_modifier_jump_popover(
7387 &mut self,
7388 text_bounds: &Bounds<Pixels>,
7389 content_origin: gpui::Point<Pixels>,
7390 visible_row_range: Range<DisplayRow>,
7391 line_layouts: &[LineWithInvisibles],
7392 line_height: Pixels,
7393 scroll_pixel_position: gpui::Point<Pixels>,
7394 newest_selection_head: Option<DisplayPoint>,
7395 target_display_point: DisplayPoint,
7396 window: &mut Window,
7397 cx: &mut App,
7398 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7399 let scrolled_content_origin =
7400 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7401
7402 const SCROLL_PADDING_Y: Pixels = px(12.);
7403
7404 if target_display_point.row() < visible_row_range.start {
7405 return self.render_edit_prediction_scroll_popover(
7406 |_| SCROLL_PADDING_Y,
7407 IconName::ArrowUp,
7408 visible_row_range,
7409 line_layouts,
7410 newest_selection_head,
7411 scrolled_content_origin,
7412 window,
7413 cx,
7414 );
7415 } else if target_display_point.row() >= visible_row_range.end {
7416 return self.render_edit_prediction_scroll_popover(
7417 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7418 IconName::ArrowDown,
7419 visible_row_range,
7420 line_layouts,
7421 newest_selection_head,
7422 scrolled_content_origin,
7423 window,
7424 cx,
7425 );
7426 }
7427
7428 const POLE_WIDTH: Pixels = px(2.);
7429
7430 let line_layout =
7431 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7432 let target_column = target_display_point.column() as usize;
7433
7434 let target_x = line_layout.x_for_index(target_column);
7435 let target_y =
7436 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7437
7438 let flag_on_right = target_x < text_bounds.size.width / 2.;
7439
7440 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7441 border_color.l += 0.001;
7442
7443 let mut element = v_flex()
7444 .items_end()
7445 .when(flag_on_right, |el| el.items_start())
7446 .child(if flag_on_right {
7447 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7448 .rounded_bl(px(0.))
7449 .rounded_tl(px(0.))
7450 .border_l_2()
7451 .border_color(border_color)
7452 } else {
7453 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7454 .rounded_br(px(0.))
7455 .rounded_tr(px(0.))
7456 .border_r_2()
7457 .border_color(border_color)
7458 })
7459 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7460 .into_any();
7461
7462 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7463
7464 let mut origin = scrolled_content_origin + point(target_x, target_y)
7465 - point(
7466 if flag_on_right {
7467 POLE_WIDTH
7468 } else {
7469 size.width - POLE_WIDTH
7470 },
7471 size.height - line_height,
7472 );
7473
7474 origin.x = origin.x.max(content_origin.x);
7475
7476 element.prepaint_at(origin, window, cx);
7477
7478 Some((element, origin))
7479 }
7480
7481 fn render_edit_prediction_scroll_popover(
7482 &mut self,
7483 to_y: impl Fn(Size<Pixels>) -> Pixels,
7484 scroll_icon: IconName,
7485 visible_row_range: Range<DisplayRow>,
7486 line_layouts: &[LineWithInvisibles],
7487 newest_selection_head: Option<DisplayPoint>,
7488 scrolled_content_origin: gpui::Point<Pixels>,
7489 window: &mut Window,
7490 cx: &mut App,
7491 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7492 let mut element = self
7493 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7494 .into_any();
7495
7496 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7497
7498 let cursor = newest_selection_head?;
7499 let cursor_row_layout =
7500 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7501 let cursor_column = cursor.column() as usize;
7502
7503 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7504
7505 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7506
7507 element.prepaint_at(origin, window, cx);
7508 Some((element, origin))
7509 }
7510
7511 fn render_edit_prediction_eager_jump_popover(
7512 &mut self,
7513 text_bounds: &Bounds<Pixels>,
7514 content_origin: gpui::Point<Pixels>,
7515 editor_snapshot: &EditorSnapshot,
7516 visible_row_range: Range<DisplayRow>,
7517 scroll_top: f32,
7518 scroll_bottom: f32,
7519 line_height: Pixels,
7520 scroll_pixel_position: gpui::Point<Pixels>,
7521 target_display_point: DisplayPoint,
7522 editor_width: Pixels,
7523 window: &mut Window,
7524 cx: &mut App,
7525 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7526 if target_display_point.row().as_f32() < scroll_top {
7527 let mut element = self
7528 .render_edit_prediction_line_popover(
7529 "Jump to Edit",
7530 Some(IconName::ArrowUp),
7531 window,
7532 cx,
7533 )?
7534 .into_any();
7535
7536 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7537 let offset = point(
7538 (text_bounds.size.width - size.width) / 2.,
7539 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7540 );
7541
7542 let origin = text_bounds.origin + offset;
7543 element.prepaint_at(origin, window, cx);
7544 Some((element, origin))
7545 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7546 let mut element = self
7547 .render_edit_prediction_line_popover(
7548 "Jump to Edit",
7549 Some(IconName::ArrowDown),
7550 window,
7551 cx,
7552 )?
7553 .into_any();
7554
7555 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7556 let offset = point(
7557 (text_bounds.size.width - size.width) / 2.,
7558 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7559 );
7560
7561 let origin = text_bounds.origin + offset;
7562 element.prepaint_at(origin, window, cx);
7563 Some((element, origin))
7564 } else {
7565 self.render_edit_prediction_end_of_line_popover(
7566 "Jump to Edit",
7567 editor_snapshot,
7568 visible_row_range,
7569 target_display_point,
7570 line_height,
7571 scroll_pixel_position,
7572 content_origin,
7573 editor_width,
7574 window,
7575 cx,
7576 )
7577 }
7578 }
7579
7580 fn render_edit_prediction_end_of_line_popover(
7581 self: &mut Editor,
7582 label: &'static str,
7583 editor_snapshot: &EditorSnapshot,
7584 visible_row_range: Range<DisplayRow>,
7585 target_display_point: DisplayPoint,
7586 line_height: Pixels,
7587 scroll_pixel_position: gpui::Point<Pixels>,
7588 content_origin: gpui::Point<Pixels>,
7589 editor_width: Pixels,
7590 window: &mut Window,
7591 cx: &mut App,
7592 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7593 let target_line_end = DisplayPoint::new(
7594 target_display_point.row(),
7595 editor_snapshot.line_len(target_display_point.row()),
7596 );
7597
7598 let mut element = self
7599 .render_edit_prediction_line_popover(label, None, window, cx)?
7600 .into_any();
7601
7602 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7603
7604 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7605
7606 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7607 let mut origin = start_point
7608 + line_origin
7609 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7610 origin.x = origin.x.max(content_origin.x);
7611
7612 let max_x = content_origin.x + editor_width - size.width;
7613
7614 if origin.x > max_x {
7615 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7616
7617 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7618 origin.y += offset;
7619 IconName::ArrowUp
7620 } else {
7621 origin.y -= offset;
7622 IconName::ArrowDown
7623 };
7624
7625 element = self
7626 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7627 .into_any();
7628
7629 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7630
7631 origin.x = content_origin.x + editor_width - size.width - px(2.);
7632 }
7633
7634 element.prepaint_at(origin, window, cx);
7635 Some((element, origin))
7636 }
7637
7638 fn render_edit_prediction_diff_popover(
7639 self: &Editor,
7640 text_bounds: &Bounds<Pixels>,
7641 content_origin: gpui::Point<Pixels>,
7642 editor_snapshot: &EditorSnapshot,
7643 visible_row_range: Range<DisplayRow>,
7644 line_layouts: &[LineWithInvisibles],
7645 line_height: Pixels,
7646 scroll_pixel_position: gpui::Point<Pixels>,
7647 newest_selection_head: Option<DisplayPoint>,
7648 editor_width: Pixels,
7649 style: &EditorStyle,
7650 edits: &Vec<(Range<Anchor>, String)>,
7651 edit_preview: &Option<language::EditPreview>,
7652 snapshot: &language::BufferSnapshot,
7653 window: &mut Window,
7654 cx: &mut App,
7655 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7656 let edit_start = edits
7657 .first()
7658 .unwrap()
7659 .0
7660 .start
7661 .to_display_point(editor_snapshot);
7662 let edit_end = edits
7663 .last()
7664 .unwrap()
7665 .0
7666 .end
7667 .to_display_point(editor_snapshot);
7668
7669 let is_visible = visible_row_range.contains(&edit_start.row())
7670 || visible_row_range.contains(&edit_end.row());
7671 if !is_visible {
7672 return None;
7673 }
7674
7675 let highlighted_edits =
7676 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7677
7678 let styled_text = highlighted_edits.to_styled_text(&style.text);
7679 let line_count = highlighted_edits.text.lines().count();
7680
7681 const BORDER_WIDTH: Pixels = px(1.);
7682
7683 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7684 let has_keybind = keybind.is_some();
7685
7686 let mut element = h_flex()
7687 .items_start()
7688 .child(
7689 h_flex()
7690 .bg(cx.theme().colors().editor_background)
7691 .border(BORDER_WIDTH)
7692 .shadow_sm()
7693 .border_color(cx.theme().colors().border)
7694 .rounded_l_lg()
7695 .when(line_count > 1, |el| el.rounded_br_lg())
7696 .pr_1()
7697 .child(styled_text),
7698 )
7699 .child(
7700 h_flex()
7701 .h(line_height + BORDER_WIDTH * 2.)
7702 .px_1p5()
7703 .gap_1()
7704 // Workaround: For some reason, there's a gap if we don't do this
7705 .ml(-BORDER_WIDTH)
7706 .shadow(smallvec![gpui::BoxShadow {
7707 color: gpui::black().opacity(0.05),
7708 offset: point(px(1.), px(1.)),
7709 blur_radius: px(2.),
7710 spread_radius: px(0.),
7711 }])
7712 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7713 .border(BORDER_WIDTH)
7714 .border_color(cx.theme().colors().border)
7715 .rounded_r_lg()
7716 .id("edit_prediction_diff_popover_keybind")
7717 .when(!has_keybind, |el| {
7718 let status_colors = cx.theme().status();
7719
7720 el.bg(status_colors.error_background)
7721 .border_color(status_colors.error.opacity(0.6))
7722 .child(Icon::new(IconName::Info).color(Color::Error))
7723 .cursor_default()
7724 .hoverable_tooltip(move |_window, cx| {
7725 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7726 })
7727 })
7728 .children(keybind),
7729 )
7730 .into_any();
7731
7732 let longest_row =
7733 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7734 let longest_line_width = if visible_row_range.contains(&longest_row) {
7735 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7736 } else {
7737 layout_line(
7738 longest_row,
7739 editor_snapshot,
7740 style,
7741 editor_width,
7742 |_| false,
7743 window,
7744 cx,
7745 )
7746 .width
7747 };
7748
7749 let viewport_bounds =
7750 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7751 right: -EditorElement::SCROLLBAR_WIDTH,
7752 ..Default::default()
7753 });
7754
7755 let x_after_longest =
7756 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7757 - scroll_pixel_position.x;
7758
7759 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7760
7761 // Fully visible if it can be displayed within the window (allow overlapping other
7762 // panes). However, this is only allowed if the popover starts within text_bounds.
7763 let can_position_to_the_right = x_after_longest < text_bounds.right()
7764 && x_after_longest + element_bounds.width < viewport_bounds.right();
7765
7766 let mut origin = if can_position_to_the_right {
7767 point(
7768 x_after_longest,
7769 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7770 - scroll_pixel_position.y,
7771 )
7772 } else {
7773 let cursor_row = newest_selection_head.map(|head| head.row());
7774 let above_edit = edit_start
7775 .row()
7776 .0
7777 .checked_sub(line_count as u32)
7778 .map(DisplayRow);
7779 let below_edit = Some(edit_end.row() + 1);
7780 let above_cursor =
7781 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7782 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7783
7784 // Place the edit popover adjacent to the edit if there is a location
7785 // available that is onscreen and does not obscure the cursor. Otherwise,
7786 // place it adjacent to the cursor.
7787 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7788 .into_iter()
7789 .flatten()
7790 .find(|&start_row| {
7791 let end_row = start_row + line_count as u32;
7792 visible_row_range.contains(&start_row)
7793 && visible_row_range.contains(&end_row)
7794 && cursor_row.map_or(true, |cursor_row| {
7795 !((start_row..end_row).contains(&cursor_row))
7796 })
7797 })?;
7798
7799 content_origin
7800 + point(
7801 -scroll_pixel_position.x,
7802 row_target.as_f32() * line_height - scroll_pixel_position.y,
7803 )
7804 };
7805
7806 origin.x -= BORDER_WIDTH;
7807
7808 window.defer_draw(element, origin, 1);
7809
7810 // Do not return an element, since it will already be drawn due to defer_draw.
7811 None
7812 }
7813
7814 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7815 px(30.)
7816 }
7817
7818 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7819 if self.read_only(cx) {
7820 cx.theme().players().read_only()
7821 } else {
7822 self.style.as_ref().unwrap().local_player
7823 }
7824 }
7825
7826 fn render_edit_prediction_accept_keybind(
7827 &self,
7828 window: &mut Window,
7829 cx: &App,
7830 ) -> Option<AnyElement> {
7831 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7832 let accept_keystroke = accept_binding.keystroke()?;
7833
7834 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7835
7836 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7837 Color::Accent
7838 } else {
7839 Color::Muted
7840 };
7841
7842 h_flex()
7843 .px_0p5()
7844 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7845 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7846 .text_size(TextSize::XSmall.rems(cx))
7847 .child(h_flex().children(ui::render_modifiers(
7848 &accept_keystroke.modifiers,
7849 PlatformStyle::platform(),
7850 Some(modifiers_color),
7851 Some(IconSize::XSmall.rems().into()),
7852 true,
7853 )))
7854 .when(is_platform_style_mac, |parent| {
7855 parent.child(accept_keystroke.key.clone())
7856 })
7857 .when(!is_platform_style_mac, |parent| {
7858 parent.child(
7859 Key::new(
7860 util::capitalize(&accept_keystroke.key),
7861 Some(Color::Default),
7862 )
7863 .size(Some(IconSize::XSmall.rems().into())),
7864 )
7865 })
7866 .into_any()
7867 .into()
7868 }
7869
7870 fn render_edit_prediction_line_popover(
7871 &self,
7872 label: impl Into<SharedString>,
7873 icon: Option<IconName>,
7874 window: &mut Window,
7875 cx: &App,
7876 ) -> Option<Stateful<Div>> {
7877 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7878
7879 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7880 let has_keybind = keybind.is_some();
7881
7882 let result = h_flex()
7883 .id("ep-line-popover")
7884 .py_0p5()
7885 .pl_1()
7886 .pr(padding_right)
7887 .gap_1()
7888 .rounded_md()
7889 .border_1()
7890 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7891 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7892 .shadow_sm()
7893 .when(!has_keybind, |el| {
7894 let status_colors = cx.theme().status();
7895
7896 el.bg(status_colors.error_background)
7897 .border_color(status_colors.error.opacity(0.6))
7898 .pl_2()
7899 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7900 .cursor_default()
7901 .hoverable_tooltip(move |_window, cx| {
7902 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7903 })
7904 })
7905 .children(keybind)
7906 .child(
7907 Label::new(label)
7908 .size(LabelSize::Small)
7909 .when(!has_keybind, |el| {
7910 el.color(cx.theme().status().error.into()).strikethrough()
7911 }),
7912 )
7913 .when(!has_keybind, |el| {
7914 el.child(
7915 h_flex().ml_1().child(
7916 Icon::new(IconName::Info)
7917 .size(IconSize::Small)
7918 .color(cx.theme().status().error.into()),
7919 ),
7920 )
7921 })
7922 .when_some(icon, |element, icon| {
7923 element.child(
7924 div()
7925 .mt(px(1.5))
7926 .child(Icon::new(icon).size(IconSize::Small)),
7927 )
7928 });
7929
7930 Some(result)
7931 }
7932
7933 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7934 let accent_color = cx.theme().colors().text_accent;
7935 let editor_bg_color = cx.theme().colors().editor_background;
7936 editor_bg_color.blend(accent_color.opacity(0.1))
7937 }
7938
7939 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7940 let accent_color = cx.theme().colors().text_accent;
7941 let editor_bg_color = cx.theme().colors().editor_background;
7942 editor_bg_color.blend(accent_color.opacity(0.6))
7943 }
7944
7945 fn render_edit_prediction_cursor_popover(
7946 &self,
7947 min_width: Pixels,
7948 max_width: Pixels,
7949 cursor_point: Point,
7950 style: &EditorStyle,
7951 accept_keystroke: Option<&gpui::Keystroke>,
7952 _window: &Window,
7953 cx: &mut Context<Editor>,
7954 ) -> Option<AnyElement> {
7955 let provider = self.edit_prediction_provider.as_ref()?;
7956
7957 if provider.provider.needs_terms_acceptance(cx) {
7958 return Some(
7959 h_flex()
7960 .min_w(min_width)
7961 .flex_1()
7962 .px_2()
7963 .py_1()
7964 .gap_3()
7965 .elevation_2(cx)
7966 .hover(|style| style.bg(cx.theme().colors().element_hover))
7967 .id("accept-terms")
7968 .cursor_pointer()
7969 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7970 .on_click(cx.listener(|this, _event, window, cx| {
7971 cx.stop_propagation();
7972 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7973 window.dispatch_action(
7974 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7975 cx,
7976 );
7977 }))
7978 .child(
7979 h_flex()
7980 .flex_1()
7981 .gap_2()
7982 .child(Icon::new(IconName::ZedPredict))
7983 .child(Label::new("Accept Terms of Service"))
7984 .child(div().w_full())
7985 .child(
7986 Icon::new(IconName::ArrowUpRight)
7987 .color(Color::Muted)
7988 .size(IconSize::Small),
7989 )
7990 .into_any_element(),
7991 )
7992 .into_any(),
7993 );
7994 }
7995
7996 let is_refreshing = provider.provider.is_refreshing(cx);
7997
7998 fn pending_completion_container() -> Div {
7999 h_flex()
8000 .h_full()
8001 .flex_1()
8002 .gap_2()
8003 .child(Icon::new(IconName::ZedPredict))
8004 }
8005
8006 let completion = match &self.active_inline_completion {
8007 Some(prediction) => {
8008 if !self.has_visible_completions_menu() {
8009 const RADIUS: Pixels = px(6.);
8010 const BORDER_WIDTH: Pixels = px(1.);
8011
8012 return Some(
8013 h_flex()
8014 .elevation_2(cx)
8015 .border(BORDER_WIDTH)
8016 .border_color(cx.theme().colors().border)
8017 .when(accept_keystroke.is_none(), |el| {
8018 el.border_color(cx.theme().status().error)
8019 })
8020 .rounded(RADIUS)
8021 .rounded_tl(px(0.))
8022 .overflow_hidden()
8023 .child(div().px_1p5().child(match &prediction.completion {
8024 InlineCompletion::Move { target, snapshot } => {
8025 use text::ToPoint as _;
8026 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8027 {
8028 Icon::new(IconName::ZedPredictDown)
8029 } else {
8030 Icon::new(IconName::ZedPredictUp)
8031 }
8032 }
8033 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8034 }))
8035 .child(
8036 h_flex()
8037 .gap_1()
8038 .py_1()
8039 .px_2()
8040 .rounded_r(RADIUS - BORDER_WIDTH)
8041 .border_l_1()
8042 .border_color(cx.theme().colors().border)
8043 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8044 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8045 el.child(
8046 Label::new("Hold")
8047 .size(LabelSize::Small)
8048 .when(accept_keystroke.is_none(), |el| {
8049 el.strikethrough()
8050 })
8051 .line_height_style(LineHeightStyle::UiLabel),
8052 )
8053 })
8054 .id("edit_prediction_cursor_popover_keybind")
8055 .when(accept_keystroke.is_none(), |el| {
8056 let status_colors = cx.theme().status();
8057
8058 el.bg(status_colors.error_background)
8059 .border_color(status_colors.error.opacity(0.6))
8060 .child(Icon::new(IconName::Info).color(Color::Error))
8061 .cursor_default()
8062 .hoverable_tooltip(move |_window, cx| {
8063 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8064 .into()
8065 })
8066 })
8067 .when_some(
8068 accept_keystroke.as_ref(),
8069 |el, accept_keystroke| {
8070 el.child(h_flex().children(ui::render_modifiers(
8071 &accept_keystroke.modifiers,
8072 PlatformStyle::platform(),
8073 Some(Color::Default),
8074 Some(IconSize::XSmall.rems().into()),
8075 false,
8076 )))
8077 },
8078 ),
8079 )
8080 .into_any(),
8081 );
8082 }
8083
8084 self.render_edit_prediction_cursor_popover_preview(
8085 prediction,
8086 cursor_point,
8087 style,
8088 cx,
8089 )?
8090 }
8091
8092 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8093 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8094 stale_completion,
8095 cursor_point,
8096 style,
8097 cx,
8098 )?,
8099
8100 None => {
8101 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8102 }
8103 },
8104
8105 None => pending_completion_container().child(Label::new("No Prediction")),
8106 };
8107
8108 let completion = if is_refreshing {
8109 completion
8110 .with_animation(
8111 "loading-completion",
8112 Animation::new(Duration::from_secs(2))
8113 .repeat()
8114 .with_easing(pulsating_between(0.4, 0.8)),
8115 |label, delta| label.opacity(delta),
8116 )
8117 .into_any_element()
8118 } else {
8119 completion.into_any_element()
8120 };
8121
8122 let has_completion = self.active_inline_completion.is_some();
8123
8124 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8125 Some(
8126 h_flex()
8127 .min_w(min_width)
8128 .max_w(max_width)
8129 .flex_1()
8130 .elevation_2(cx)
8131 .border_color(cx.theme().colors().border)
8132 .child(
8133 div()
8134 .flex_1()
8135 .py_1()
8136 .px_2()
8137 .overflow_hidden()
8138 .child(completion),
8139 )
8140 .when_some(accept_keystroke, |el, accept_keystroke| {
8141 if !accept_keystroke.modifiers.modified() {
8142 return el;
8143 }
8144
8145 el.child(
8146 h_flex()
8147 .h_full()
8148 .border_l_1()
8149 .rounded_r_lg()
8150 .border_color(cx.theme().colors().border)
8151 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8152 .gap_1()
8153 .py_1()
8154 .px_2()
8155 .child(
8156 h_flex()
8157 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8158 .when(is_platform_style_mac, |parent| parent.gap_1())
8159 .child(h_flex().children(ui::render_modifiers(
8160 &accept_keystroke.modifiers,
8161 PlatformStyle::platform(),
8162 Some(if !has_completion {
8163 Color::Muted
8164 } else {
8165 Color::Default
8166 }),
8167 None,
8168 false,
8169 ))),
8170 )
8171 .child(Label::new("Preview").into_any_element())
8172 .opacity(if has_completion { 1.0 } else { 0.4 }),
8173 )
8174 })
8175 .into_any(),
8176 )
8177 }
8178
8179 fn render_edit_prediction_cursor_popover_preview(
8180 &self,
8181 completion: &InlineCompletionState,
8182 cursor_point: Point,
8183 style: &EditorStyle,
8184 cx: &mut Context<Editor>,
8185 ) -> Option<Div> {
8186 use text::ToPoint as _;
8187
8188 fn render_relative_row_jump(
8189 prefix: impl Into<String>,
8190 current_row: u32,
8191 target_row: u32,
8192 ) -> Div {
8193 let (row_diff, arrow) = if target_row < current_row {
8194 (current_row - target_row, IconName::ArrowUp)
8195 } else {
8196 (target_row - current_row, IconName::ArrowDown)
8197 };
8198
8199 h_flex()
8200 .child(
8201 Label::new(format!("{}{}", prefix.into(), row_diff))
8202 .color(Color::Muted)
8203 .size(LabelSize::Small),
8204 )
8205 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8206 }
8207
8208 match &completion.completion {
8209 InlineCompletion::Move {
8210 target, snapshot, ..
8211 } => Some(
8212 h_flex()
8213 .px_2()
8214 .gap_2()
8215 .flex_1()
8216 .child(
8217 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8218 Icon::new(IconName::ZedPredictDown)
8219 } else {
8220 Icon::new(IconName::ZedPredictUp)
8221 },
8222 )
8223 .child(Label::new("Jump to Edit")),
8224 ),
8225
8226 InlineCompletion::Edit {
8227 edits,
8228 edit_preview,
8229 snapshot,
8230 display_mode: _,
8231 } => {
8232 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8233
8234 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8235 &snapshot,
8236 &edits,
8237 edit_preview.as_ref()?,
8238 true,
8239 cx,
8240 )
8241 .first_line_preview();
8242
8243 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8244 .with_default_highlights(&style.text, highlighted_edits.highlights);
8245
8246 let preview = h_flex()
8247 .gap_1()
8248 .min_w_16()
8249 .child(styled_text)
8250 .when(has_more_lines, |parent| parent.child("…"));
8251
8252 let left = if first_edit_row != cursor_point.row {
8253 render_relative_row_jump("", cursor_point.row, first_edit_row)
8254 .into_any_element()
8255 } else {
8256 Icon::new(IconName::ZedPredict).into_any_element()
8257 };
8258
8259 Some(
8260 h_flex()
8261 .h_full()
8262 .flex_1()
8263 .gap_2()
8264 .pr_1()
8265 .overflow_x_hidden()
8266 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8267 .child(left)
8268 .child(preview),
8269 )
8270 }
8271 }
8272 }
8273
8274 fn render_context_menu(
8275 &self,
8276 style: &EditorStyle,
8277 max_height_in_lines: u32,
8278 window: &mut Window,
8279 cx: &mut Context<Editor>,
8280 ) -> Option<AnyElement> {
8281 let menu = self.context_menu.borrow();
8282 let menu = menu.as_ref()?;
8283 if !menu.visible() {
8284 return None;
8285 };
8286 Some(menu.render(style, max_height_in_lines, window, cx))
8287 }
8288
8289 fn render_context_menu_aside(
8290 &mut self,
8291 max_size: Size<Pixels>,
8292 window: &mut Window,
8293 cx: &mut Context<Editor>,
8294 ) -> Option<AnyElement> {
8295 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8296 if menu.visible() {
8297 menu.render_aside(self, max_size, window, cx)
8298 } else {
8299 None
8300 }
8301 })
8302 }
8303
8304 fn hide_context_menu(
8305 &mut self,
8306 window: &mut Window,
8307 cx: &mut Context<Self>,
8308 ) -> Option<CodeContextMenu> {
8309 cx.notify();
8310 self.completion_tasks.clear();
8311 let context_menu = self.context_menu.borrow_mut().take();
8312 self.stale_inline_completion_in_menu.take();
8313 self.update_visible_inline_completion(window, cx);
8314 context_menu
8315 }
8316
8317 fn show_snippet_choices(
8318 &mut self,
8319 choices: &Vec<String>,
8320 selection: Range<Anchor>,
8321 cx: &mut Context<Self>,
8322 ) {
8323 if selection.start.buffer_id.is_none() {
8324 return;
8325 }
8326 let buffer_id = selection.start.buffer_id.unwrap();
8327 let buffer = self.buffer().read(cx).buffer(buffer_id);
8328 let id = post_inc(&mut self.next_completion_id);
8329 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8330
8331 if let Some(buffer) = buffer {
8332 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8333 CompletionsMenu::new_snippet_choices(
8334 id,
8335 true,
8336 choices,
8337 selection,
8338 buffer,
8339 snippet_sort_order,
8340 ),
8341 ));
8342 }
8343 }
8344
8345 pub fn insert_snippet(
8346 &mut self,
8347 insertion_ranges: &[Range<usize>],
8348 snippet: Snippet,
8349 window: &mut Window,
8350 cx: &mut Context<Self>,
8351 ) -> Result<()> {
8352 struct Tabstop<T> {
8353 is_end_tabstop: bool,
8354 ranges: Vec<Range<T>>,
8355 choices: Option<Vec<String>>,
8356 }
8357
8358 let tabstops = self.buffer.update(cx, |buffer, cx| {
8359 let snippet_text: Arc<str> = snippet.text.clone().into();
8360 let edits = insertion_ranges
8361 .iter()
8362 .cloned()
8363 .map(|range| (range, snippet_text.clone()));
8364 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8365
8366 let snapshot = &*buffer.read(cx);
8367 let snippet = &snippet;
8368 snippet
8369 .tabstops
8370 .iter()
8371 .map(|tabstop| {
8372 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8373 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8374 });
8375 let mut tabstop_ranges = tabstop
8376 .ranges
8377 .iter()
8378 .flat_map(|tabstop_range| {
8379 let mut delta = 0_isize;
8380 insertion_ranges.iter().map(move |insertion_range| {
8381 let insertion_start = insertion_range.start as isize + delta;
8382 delta +=
8383 snippet.text.len() as isize - insertion_range.len() as isize;
8384
8385 let start = ((insertion_start + tabstop_range.start) as usize)
8386 .min(snapshot.len());
8387 let end = ((insertion_start + tabstop_range.end) as usize)
8388 .min(snapshot.len());
8389 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8390 })
8391 })
8392 .collect::<Vec<_>>();
8393 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8394
8395 Tabstop {
8396 is_end_tabstop,
8397 ranges: tabstop_ranges,
8398 choices: tabstop.choices.clone(),
8399 }
8400 })
8401 .collect::<Vec<_>>()
8402 });
8403 if let Some(tabstop) = tabstops.first() {
8404 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8405 s.select_ranges(tabstop.ranges.iter().cloned());
8406 });
8407
8408 if let Some(choices) = &tabstop.choices {
8409 if let Some(selection) = tabstop.ranges.first() {
8410 self.show_snippet_choices(choices, selection.clone(), cx)
8411 }
8412 }
8413
8414 // If we're already at the last tabstop and it's at the end of the snippet,
8415 // we're done, we don't need to keep the state around.
8416 if !tabstop.is_end_tabstop {
8417 let choices = tabstops
8418 .iter()
8419 .map(|tabstop| tabstop.choices.clone())
8420 .collect();
8421
8422 let ranges = tabstops
8423 .into_iter()
8424 .map(|tabstop| tabstop.ranges)
8425 .collect::<Vec<_>>();
8426
8427 self.snippet_stack.push(SnippetState {
8428 active_index: 0,
8429 ranges,
8430 choices,
8431 });
8432 }
8433
8434 // Check whether the just-entered snippet ends with an auto-closable bracket.
8435 if self.autoclose_regions.is_empty() {
8436 let snapshot = self.buffer.read(cx).snapshot(cx);
8437 for selection in &mut self.selections.all::<Point>(cx) {
8438 let selection_head = selection.head();
8439 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8440 continue;
8441 };
8442
8443 let mut bracket_pair = None;
8444 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8445 let prev_chars = snapshot
8446 .reversed_chars_at(selection_head)
8447 .collect::<String>();
8448 for (pair, enabled) in scope.brackets() {
8449 if enabled
8450 && pair.close
8451 && prev_chars.starts_with(pair.start.as_str())
8452 && next_chars.starts_with(pair.end.as_str())
8453 {
8454 bracket_pair = Some(pair.clone());
8455 break;
8456 }
8457 }
8458 if let Some(pair) = bracket_pair {
8459 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8460 let autoclose_enabled =
8461 self.use_autoclose && snapshot_settings.use_autoclose;
8462 if autoclose_enabled {
8463 let start = snapshot.anchor_after(selection_head);
8464 let end = snapshot.anchor_after(selection_head);
8465 self.autoclose_regions.push(AutocloseRegion {
8466 selection_id: selection.id,
8467 range: start..end,
8468 pair,
8469 });
8470 }
8471 }
8472 }
8473 }
8474 }
8475 Ok(())
8476 }
8477
8478 pub fn move_to_next_snippet_tabstop(
8479 &mut self,
8480 window: &mut Window,
8481 cx: &mut Context<Self>,
8482 ) -> bool {
8483 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8484 }
8485
8486 pub fn move_to_prev_snippet_tabstop(
8487 &mut self,
8488 window: &mut Window,
8489 cx: &mut Context<Self>,
8490 ) -> bool {
8491 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8492 }
8493
8494 pub fn move_to_snippet_tabstop(
8495 &mut self,
8496 bias: Bias,
8497 window: &mut Window,
8498 cx: &mut Context<Self>,
8499 ) -> bool {
8500 if let Some(mut snippet) = self.snippet_stack.pop() {
8501 match bias {
8502 Bias::Left => {
8503 if snippet.active_index > 0 {
8504 snippet.active_index -= 1;
8505 } else {
8506 self.snippet_stack.push(snippet);
8507 return false;
8508 }
8509 }
8510 Bias::Right => {
8511 if snippet.active_index + 1 < snippet.ranges.len() {
8512 snippet.active_index += 1;
8513 } else {
8514 self.snippet_stack.push(snippet);
8515 return false;
8516 }
8517 }
8518 }
8519 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8520 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8521 s.select_anchor_ranges(current_ranges.iter().cloned())
8522 });
8523
8524 if let Some(choices) = &snippet.choices[snippet.active_index] {
8525 if let Some(selection) = current_ranges.first() {
8526 self.show_snippet_choices(&choices, selection.clone(), cx);
8527 }
8528 }
8529
8530 // If snippet state is not at the last tabstop, push it back on the stack
8531 if snippet.active_index + 1 < snippet.ranges.len() {
8532 self.snippet_stack.push(snippet);
8533 }
8534 return true;
8535 }
8536 }
8537
8538 false
8539 }
8540
8541 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8542 self.transact(window, cx, |this, window, cx| {
8543 this.select_all(&SelectAll, window, cx);
8544 this.insert("", window, cx);
8545 });
8546 }
8547
8548 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8549 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8550 self.transact(window, cx, |this, window, cx| {
8551 this.select_autoclose_pair(window, cx);
8552 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8553 if !this.linked_edit_ranges.is_empty() {
8554 let selections = this.selections.all::<MultiBufferPoint>(cx);
8555 let snapshot = this.buffer.read(cx).snapshot(cx);
8556
8557 for selection in selections.iter() {
8558 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8559 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8560 if selection_start.buffer_id != selection_end.buffer_id {
8561 continue;
8562 }
8563 if let Some(ranges) =
8564 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8565 {
8566 for (buffer, entries) in ranges {
8567 linked_ranges.entry(buffer).or_default().extend(entries);
8568 }
8569 }
8570 }
8571 }
8572
8573 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8574 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8575 for selection in &mut selections {
8576 if selection.is_empty() {
8577 let old_head = selection.head();
8578 let mut new_head =
8579 movement::left(&display_map, old_head.to_display_point(&display_map))
8580 .to_point(&display_map);
8581 if let Some((buffer, line_buffer_range)) = display_map
8582 .buffer_snapshot
8583 .buffer_line_for_row(MultiBufferRow(old_head.row))
8584 {
8585 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8586 let indent_len = match indent_size.kind {
8587 IndentKind::Space => {
8588 buffer.settings_at(line_buffer_range.start, cx).tab_size
8589 }
8590 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8591 };
8592 if old_head.column <= indent_size.len && old_head.column > 0 {
8593 let indent_len = indent_len.get();
8594 new_head = cmp::min(
8595 new_head,
8596 MultiBufferPoint::new(
8597 old_head.row,
8598 ((old_head.column - 1) / indent_len) * indent_len,
8599 ),
8600 );
8601 }
8602 }
8603
8604 selection.set_head(new_head, SelectionGoal::None);
8605 }
8606 }
8607
8608 this.signature_help_state.set_backspace_pressed(true);
8609 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8610 s.select(selections)
8611 });
8612 this.insert("", window, cx);
8613 let empty_str: Arc<str> = Arc::from("");
8614 for (buffer, edits) in linked_ranges {
8615 let snapshot = buffer.read(cx).snapshot();
8616 use text::ToPoint as TP;
8617
8618 let edits = edits
8619 .into_iter()
8620 .map(|range| {
8621 let end_point = TP::to_point(&range.end, &snapshot);
8622 let mut start_point = TP::to_point(&range.start, &snapshot);
8623
8624 if end_point == start_point {
8625 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8626 .saturating_sub(1);
8627 start_point =
8628 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8629 };
8630
8631 (start_point..end_point, empty_str.clone())
8632 })
8633 .sorted_by_key(|(range, _)| range.start)
8634 .collect::<Vec<_>>();
8635 buffer.update(cx, |this, cx| {
8636 this.edit(edits, None, cx);
8637 })
8638 }
8639 this.refresh_inline_completion(true, false, window, cx);
8640 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8641 });
8642 }
8643
8644 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8645 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8646 self.transact(window, cx, |this, window, cx| {
8647 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8648 s.move_with(|map, selection| {
8649 if selection.is_empty() {
8650 let cursor = movement::right(map, selection.head());
8651 selection.end = cursor;
8652 selection.reversed = true;
8653 selection.goal = SelectionGoal::None;
8654 }
8655 })
8656 });
8657 this.insert("", window, cx);
8658 this.refresh_inline_completion(true, false, window, cx);
8659 });
8660 }
8661
8662 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8663 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8664 if self.move_to_prev_snippet_tabstop(window, cx) {
8665 return;
8666 }
8667 self.outdent(&Outdent, window, cx);
8668 }
8669
8670 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8671 if self.move_to_next_snippet_tabstop(window, cx) {
8672 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8673 return;
8674 }
8675 if self.read_only(cx) {
8676 return;
8677 }
8678 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8679 let mut selections = self.selections.all_adjusted(cx);
8680 let buffer = self.buffer.read(cx);
8681 let snapshot = buffer.snapshot(cx);
8682 let rows_iter = selections.iter().map(|s| s.head().row);
8683 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8684
8685 let has_some_cursor_in_whitespace = selections
8686 .iter()
8687 .filter(|selection| selection.is_empty())
8688 .any(|selection| {
8689 let cursor = selection.head();
8690 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8691 cursor.column < current_indent.len
8692 });
8693
8694 let mut edits = Vec::new();
8695 let mut prev_edited_row = 0;
8696 let mut row_delta = 0;
8697 for selection in &mut selections {
8698 if selection.start.row != prev_edited_row {
8699 row_delta = 0;
8700 }
8701 prev_edited_row = selection.end.row;
8702
8703 // If the selection is non-empty, then increase the indentation of the selected lines.
8704 if !selection.is_empty() {
8705 row_delta =
8706 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8707 continue;
8708 }
8709
8710 // If the selection is empty and the cursor is in the leading whitespace before the
8711 // suggested indentation, then auto-indent the line.
8712 let cursor = selection.head();
8713 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8714 if let Some(suggested_indent) =
8715 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8716 {
8717 // If there exist any empty selection in the leading whitespace, then skip
8718 // indent for selections at the boundary.
8719 if has_some_cursor_in_whitespace
8720 && cursor.column == current_indent.len
8721 && current_indent.len == suggested_indent.len
8722 {
8723 continue;
8724 }
8725
8726 if cursor.column < suggested_indent.len
8727 && cursor.column <= current_indent.len
8728 && current_indent.len <= suggested_indent.len
8729 {
8730 selection.start = Point::new(cursor.row, suggested_indent.len);
8731 selection.end = selection.start;
8732 if row_delta == 0 {
8733 edits.extend(Buffer::edit_for_indent_size_adjustment(
8734 cursor.row,
8735 current_indent,
8736 suggested_indent,
8737 ));
8738 row_delta = suggested_indent.len - current_indent.len;
8739 }
8740 continue;
8741 }
8742 }
8743
8744 // Otherwise, insert a hard or soft tab.
8745 let settings = buffer.language_settings_at(cursor, cx);
8746 let tab_size = if settings.hard_tabs {
8747 IndentSize::tab()
8748 } else {
8749 let tab_size = settings.tab_size.get();
8750 let indent_remainder = snapshot
8751 .text_for_range(Point::new(cursor.row, 0)..cursor)
8752 .flat_map(str::chars)
8753 .fold(row_delta % tab_size, |counter: u32, c| {
8754 if c == '\t' {
8755 0
8756 } else {
8757 (counter + 1) % tab_size
8758 }
8759 });
8760
8761 let chars_to_next_tab_stop = tab_size - indent_remainder;
8762 IndentSize::spaces(chars_to_next_tab_stop)
8763 };
8764 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8765 selection.end = selection.start;
8766 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8767 row_delta += tab_size.len;
8768 }
8769
8770 self.transact(window, cx, |this, window, cx| {
8771 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8772 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.select(selections)
8774 });
8775 this.refresh_inline_completion(true, false, window, cx);
8776 });
8777 }
8778
8779 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8780 if self.read_only(cx) {
8781 return;
8782 }
8783 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8784 let mut selections = self.selections.all::<Point>(cx);
8785 let mut prev_edited_row = 0;
8786 let mut row_delta = 0;
8787 let mut edits = Vec::new();
8788 let buffer = self.buffer.read(cx);
8789 let snapshot = buffer.snapshot(cx);
8790 for selection in &mut selections {
8791 if selection.start.row != prev_edited_row {
8792 row_delta = 0;
8793 }
8794 prev_edited_row = selection.end.row;
8795
8796 row_delta =
8797 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8798 }
8799
8800 self.transact(window, cx, |this, window, cx| {
8801 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8802 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8803 s.select(selections)
8804 });
8805 });
8806 }
8807
8808 fn indent_selection(
8809 buffer: &MultiBuffer,
8810 snapshot: &MultiBufferSnapshot,
8811 selection: &mut Selection<Point>,
8812 edits: &mut Vec<(Range<Point>, String)>,
8813 delta_for_start_row: u32,
8814 cx: &App,
8815 ) -> u32 {
8816 let settings = buffer.language_settings_at(selection.start, cx);
8817 let tab_size = settings.tab_size.get();
8818 let indent_kind = if settings.hard_tabs {
8819 IndentKind::Tab
8820 } else {
8821 IndentKind::Space
8822 };
8823 let mut start_row = selection.start.row;
8824 let mut end_row = selection.end.row + 1;
8825
8826 // If a selection ends at the beginning of a line, don't indent
8827 // that last line.
8828 if selection.end.column == 0 && selection.end.row > selection.start.row {
8829 end_row -= 1;
8830 }
8831
8832 // Avoid re-indenting a row that has already been indented by a
8833 // previous selection, but still update this selection's column
8834 // to reflect that indentation.
8835 if delta_for_start_row > 0 {
8836 start_row += 1;
8837 selection.start.column += delta_for_start_row;
8838 if selection.end.row == selection.start.row {
8839 selection.end.column += delta_for_start_row;
8840 }
8841 }
8842
8843 let mut delta_for_end_row = 0;
8844 let has_multiple_rows = start_row + 1 != end_row;
8845 for row in start_row..end_row {
8846 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8847 let indent_delta = match (current_indent.kind, indent_kind) {
8848 (IndentKind::Space, IndentKind::Space) => {
8849 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8850 IndentSize::spaces(columns_to_next_tab_stop)
8851 }
8852 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8853 (_, IndentKind::Tab) => IndentSize::tab(),
8854 };
8855
8856 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8857 0
8858 } else {
8859 selection.start.column
8860 };
8861 let row_start = Point::new(row, start);
8862 edits.push((
8863 row_start..row_start,
8864 indent_delta.chars().collect::<String>(),
8865 ));
8866
8867 // Update this selection's endpoints to reflect the indentation.
8868 if row == selection.start.row {
8869 selection.start.column += indent_delta.len;
8870 }
8871 if row == selection.end.row {
8872 selection.end.column += indent_delta.len;
8873 delta_for_end_row = indent_delta.len;
8874 }
8875 }
8876
8877 if selection.start.row == selection.end.row {
8878 delta_for_start_row + delta_for_end_row
8879 } else {
8880 delta_for_end_row
8881 }
8882 }
8883
8884 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8885 if self.read_only(cx) {
8886 return;
8887 }
8888 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8890 let selections = self.selections.all::<Point>(cx);
8891 let mut deletion_ranges = Vec::new();
8892 let mut last_outdent = None;
8893 {
8894 let buffer = self.buffer.read(cx);
8895 let snapshot = buffer.snapshot(cx);
8896 for selection in &selections {
8897 let settings = buffer.language_settings_at(selection.start, cx);
8898 let tab_size = settings.tab_size.get();
8899 let mut rows = selection.spanned_rows(false, &display_map);
8900
8901 // Avoid re-outdenting a row that has already been outdented by a
8902 // previous selection.
8903 if let Some(last_row) = last_outdent {
8904 if last_row == rows.start {
8905 rows.start = rows.start.next_row();
8906 }
8907 }
8908 let has_multiple_rows = rows.len() > 1;
8909 for row in rows.iter_rows() {
8910 let indent_size = snapshot.indent_size_for_line(row);
8911 if indent_size.len > 0 {
8912 let deletion_len = match indent_size.kind {
8913 IndentKind::Space => {
8914 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8915 if columns_to_prev_tab_stop == 0 {
8916 tab_size
8917 } else {
8918 columns_to_prev_tab_stop
8919 }
8920 }
8921 IndentKind::Tab => 1,
8922 };
8923 let start = if has_multiple_rows
8924 || deletion_len > selection.start.column
8925 || indent_size.len < selection.start.column
8926 {
8927 0
8928 } else {
8929 selection.start.column - deletion_len
8930 };
8931 deletion_ranges.push(
8932 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8933 );
8934 last_outdent = Some(row);
8935 }
8936 }
8937 }
8938 }
8939
8940 self.transact(window, cx, |this, window, cx| {
8941 this.buffer.update(cx, |buffer, cx| {
8942 let empty_str: Arc<str> = Arc::default();
8943 buffer.edit(
8944 deletion_ranges
8945 .into_iter()
8946 .map(|range| (range, empty_str.clone())),
8947 None,
8948 cx,
8949 );
8950 });
8951 let selections = this.selections.all::<usize>(cx);
8952 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8953 s.select(selections)
8954 });
8955 });
8956 }
8957
8958 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8959 if self.read_only(cx) {
8960 return;
8961 }
8962 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8963 let selections = self
8964 .selections
8965 .all::<usize>(cx)
8966 .into_iter()
8967 .map(|s| s.range());
8968
8969 self.transact(window, cx, |this, window, cx| {
8970 this.buffer.update(cx, |buffer, cx| {
8971 buffer.autoindent_ranges(selections, cx);
8972 });
8973 let selections = this.selections.all::<usize>(cx);
8974 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8975 s.select(selections)
8976 });
8977 });
8978 }
8979
8980 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8981 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8982 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8983 let selections = self.selections.all::<Point>(cx);
8984
8985 let mut new_cursors = Vec::new();
8986 let mut edit_ranges = Vec::new();
8987 let mut selections = selections.iter().peekable();
8988 while let Some(selection) = selections.next() {
8989 let mut rows = selection.spanned_rows(false, &display_map);
8990 let goal_display_column = selection.head().to_display_point(&display_map).column();
8991
8992 // Accumulate contiguous regions of rows that we want to delete.
8993 while let Some(next_selection) = selections.peek() {
8994 let next_rows = next_selection.spanned_rows(false, &display_map);
8995 if next_rows.start <= rows.end {
8996 rows.end = next_rows.end;
8997 selections.next().unwrap();
8998 } else {
8999 break;
9000 }
9001 }
9002
9003 let buffer = &display_map.buffer_snapshot;
9004 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9005 let edit_end;
9006 let cursor_buffer_row;
9007 if buffer.max_point().row >= rows.end.0 {
9008 // If there's a line after the range, delete the \n from the end of the row range
9009 // and position the cursor on the next line.
9010 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9011 cursor_buffer_row = rows.end;
9012 } else {
9013 // If there isn't a line after the range, delete the \n from the line before the
9014 // start of the row range and position the cursor there.
9015 edit_start = edit_start.saturating_sub(1);
9016 edit_end = buffer.len();
9017 cursor_buffer_row = rows.start.previous_row();
9018 }
9019
9020 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9021 *cursor.column_mut() =
9022 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9023
9024 new_cursors.push((
9025 selection.id,
9026 buffer.anchor_after(cursor.to_point(&display_map)),
9027 ));
9028 edit_ranges.push(edit_start..edit_end);
9029 }
9030
9031 self.transact(window, cx, |this, window, cx| {
9032 let buffer = this.buffer.update(cx, |buffer, cx| {
9033 let empty_str: Arc<str> = Arc::default();
9034 buffer.edit(
9035 edit_ranges
9036 .into_iter()
9037 .map(|range| (range, empty_str.clone())),
9038 None,
9039 cx,
9040 );
9041 buffer.snapshot(cx)
9042 });
9043 let new_selections = new_cursors
9044 .into_iter()
9045 .map(|(id, cursor)| {
9046 let cursor = cursor.to_point(&buffer);
9047 Selection {
9048 id,
9049 start: cursor,
9050 end: cursor,
9051 reversed: false,
9052 goal: SelectionGoal::None,
9053 }
9054 })
9055 .collect();
9056
9057 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9058 s.select(new_selections);
9059 });
9060 });
9061 }
9062
9063 pub fn join_lines_impl(
9064 &mut self,
9065 insert_whitespace: bool,
9066 window: &mut Window,
9067 cx: &mut Context<Self>,
9068 ) {
9069 if self.read_only(cx) {
9070 return;
9071 }
9072 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9073 for selection in self.selections.all::<Point>(cx) {
9074 let start = MultiBufferRow(selection.start.row);
9075 // Treat single line selections as if they include the next line. Otherwise this action
9076 // would do nothing for single line selections individual cursors.
9077 let end = if selection.start.row == selection.end.row {
9078 MultiBufferRow(selection.start.row + 1)
9079 } else {
9080 MultiBufferRow(selection.end.row)
9081 };
9082
9083 if let Some(last_row_range) = row_ranges.last_mut() {
9084 if start <= last_row_range.end {
9085 last_row_range.end = end;
9086 continue;
9087 }
9088 }
9089 row_ranges.push(start..end);
9090 }
9091
9092 let snapshot = self.buffer.read(cx).snapshot(cx);
9093 let mut cursor_positions = Vec::new();
9094 for row_range in &row_ranges {
9095 let anchor = snapshot.anchor_before(Point::new(
9096 row_range.end.previous_row().0,
9097 snapshot.line_len(row_range.end.previous_row()),
9098 ));
9099 cursor_positions.push(anchor..anchor);
9100 }
9101
9102 self.transact(window, cx, |this, window, cx| {
9103 for row_range in row_ranges.into_iter().rev() {
9104 for row in row_range.iter_rows().rev() {
9105 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9106 let next_line_row = row.next_row();
9107 let indent = snapshot.indent_size_for_line(next_line_row);
9108 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9109
9110 let replace =
9111 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9112 " "
9113 } else {
9114 ""
9115 };
9116
9117 this.buffer.update(cx, |buffer, cx| {
9118 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9119 });
9120 }
9121 }
9122
9123 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9124 s.select_anchor_ranges(cursor_positions)
9125 });
9126 });
9127 }
9128
9129 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9130 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9131 self.join_lines_impl(true, window, cx);
9132 }
9133
9134 pub fn sort_lines_case_sensitive(
9135 &mut self,
9136 _: &SortLinesCaseSensitive,
9137 window: &mut Window,
9138 cx: &mut Context<Self>,
9139 ) {
9140 self.manipulate_lines(window, cx, |lines| lines.sort())
9141 }
9142
9143 pub fn sort_lines_case_insensitive(
9144 &mut self,
9145 _: &SortLinesCaseInsensitive,
9146 window: &mut Window,
9147 cx: &mut Context<Self>,
9148 ) {
9149 self.manipulate_lines(window, cx, |lines| {
9150 lines.sort_by_key(|line| line.to_lowercase())
9151 })
9152 }
9153
9154 pub fn unique_lines_case_insensitive(
9155 &mut self,
9156 _: &UniqueLinesCaseInsensitive,
9157 window: &mut Window,
9158 cx: &mut Context<Self>,
9159 ) {
9160 self.manipulate_lines(window, cx, |lines| {
9161 let mut seen = HashSet::default();
9162 lines.retain(|line| seen.insert(line.to_lowercase()));
9163 })
9164 }
9165
9166 pub fn unique_lines_case_sensitive(
9167 &mut self,
9168 _: &UniqueLinesCaseSensitive,
9169 window: &mut Window,
9170 cx: &mut Context<Self>,
9171 ) {
9172 self.manipulate_lines(window, cx, |lines| {
9173 let mut seen = HashSet::default();
9174 lines.retain(|line| seen.insert(*line));
9175 })
9176 }
9177
9178 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9179 let Some(project) = self.project.clone() else {
9180 return;
9181 };
9182 self.reload(project, window, cx)
9183 .detach_and_notify_err(window, cx);
9184 }
9185
9186 pub fn restore_file(
9187 &mut self,
9188 _: &::git::RestoreFile,
9189 window: &mut Window,
9190 cx: &mut Context<Self>,
9191 ) {
9192 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9193 let mut buffer_ids = HashSet::default();
9194 let snapshot = self.buffer().read(cx).snapshot(cx);
9195 for selection in self.selections.all::<usize>(cx) {
9196 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9197 }
9198
9199 let buffer = self.buffer().read(cx);
9200 let ranges = buffer_ids
9201 .into_iter()
9202 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9203 .collect::<Vec<_>>();
9204
9205 self.restore_hunks_in_ranges(ranges, window, cx);
9206 }
9207
9208 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9209 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9210 let selections = self
9211 .selections
9212 .all(cx)
9213 .into_iter()
9214 .map(|s| s.range())
9215 .collect();
9216 self.restore_hunks_in_ranges(selections, window, cx);
9217 }
9218
9219 pub fn restore_hunks_in_ranges(
9220 &mut self,
9221 ranges: Vec<Range<Point>>,
9222 window: &mut Window,
9223 cx: &mut Context<Editor>,
9224 ) {
9225 let mut revert_changes = HashMap::default();
9226 let chunk_by = self
9227 .snapshot(window, cx)
9228 .hunks_for_ranges(ranges)
9229 .into_iter()
9230 .chunk_by(|hunk| hunk.buffer_id);
9231 for (buffer_id, hunks) in &chunk_by {
9232 let hunks = hunks.collect::<Vec<_>>();
9233 for hunk in &hunks {
9234 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9235 }
9236 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9237 }
9238 drop(chunk_by);
9239 if !revert_changes.is_empty() {
9240 self.transact(window, cx, |editor, window, cx| {
9241 editor.restore(revert_changes, window, cx);
9242 });
9243 }
9244 }
9245
9246 pub fn open_active_item_in_terminal(
9247 &mut self,
9248 _: &OpenInTerminal,
9249 window: &mut Window,
9250 cx: &mut Context<Self>,
9251 ) {
9252 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9253 let project_path = buffer.read(cx).project_path(cx)?;
9254 let project = self.project.as_ref()?.read(cx);
9255 let entry = project.entry_for_path(&project_path, cx)?;
9256 let parent = match &entry.canonical_path {
9257 Some(canonical_path) => canonical_path.to_path_buf(),
9258 None => project.absolute_path(&project_path, cx)?,
9259 }
9260 .parent()?
9261 .to_path_buf();
9262 Some(parent)
9263 }) {
9264 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9265 }
9266 }
9267
9268 fn set_breakpoint_context_menu(
9269 &mut self,
9270 display_row: DisplayRow,
9271 position: Option<Anchor>,
9272 clicked_point: gpui::Point<Pixels>,
9273 window: &mut Window,
9274 cx: &mut Context<Self>,
9275 ) {
9276 if !cx.has_flag::<DebuggerFeatureFlag>() {
9277 return;
9278 }
9279 let source = self
9280 .buffer
9281 .read(cx)
9282 .snapshot(cx)
9283 .anchor_before(Point::new(display_row.0, 0u32));
9284
9285 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9286
9287 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9288 self,
9289 source,
9290 clicked_point,
9291 context_menu,
9292 window,
9293 cx,
9294 );
9295 }
9296
9297 fn add_edit_breakpoint_block(
9298 &mut self,
9299 anchor: Anchor,
9300 breakpoint: &Breakpoint,
9301 edit_action: BreakpointPromptEditAction,
9302 window: &mut Window,
9303 cx: &mut Context<Self>,
9304 ) {
9305 let weak_editor = cx.weak_entity();
9306 let bp_prompt = cx.new(|cx| {
9307 BreakpointPromptEditor::new(
9308 weak_editor,
9309 anchor,
9310 breakpoint.clone(),
9311 edit_action,
9312 window,
9313 cx,
9314 )
9315 });
9316
9317 let height = bp_prompt.update(cx, |this, cx| {
9318 this.prompt
9319 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9320 });
9321 let cloned_prompt = bp_prompt.clone();
9322 let blocks = vec![BlockProperties {
9323 style: BlockStyle::Sticky,
9324 placement: BlockPlacement::Above(anchor),
9325 height: Some(height),
9326 render: Arc::new(move |cx| {
9327 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9328 cloned_prompt.clone().into_any_element()
9329 }),
9330 priority: 0,
9331 }];
9332
9333 let focus_handle = bp_prompt.focus_handle(cx);
9334 window.focus(&focus_handle);
9335
9336 let block_ids = self.insert_blocks(blocks, None, cx);
9337 bp_prompt.update(cx, |prompt, _| {
9338 prompt.add_block_ids(block_ids);
9339 });
9340 }
9341
9342 pub(crate) fn breakpoint_at_row(
9343 &self,
9344 row: u32,
9345 window: &mut Window,
9346 cx: &mut Context<Self>,
9347 ) -> Option<(Anchor, Breakpoint)> {
9348 let snapshot = self.snapshot(window, cx);
9349 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9350
9351 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9352 }
9353
9354 pub(crate) fn breakpoint_at_anchor(
9355 &self,
9356 breakpoint_position: Anchor,
9357 snapshot: &EditorSnapshot,
9358 cx: &mut Context<Self>,
9359 ) -> Option<(Anchor, Breakpoint)> {
9360 let project = self.project.clone()?;
9361
9362 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9363 snapshot
9364 .buffer_snapshot
9365 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9366 })?;
9367
9368 let enclosing_excerpt = breakpoint_position.excerpt_id;
9369 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9370 let buffer_snapshot = buffer.read(cx).snapshot();
9371
9372 let row = buffer_snapshot
9373 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9374 .row;
9375
9376 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9377 let anchor_end = snapshot
9378 .buffer_snapshot
9379 .anchor_after(Point::new(row, line_len));
9380
9381 let bp = self
9382 .breakpoint_store
9383 .as_ref()?
9384 .read_with(cx, |breakpoint_store, cx| {
9385 breakpoint_store
9386 .breakpoints(
9387 &buffer,
9388 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9389 &buffer_snapshot,
9390 cx,
9391 )
9392 .next()
9393 .and_then(|(anchor, bp)| {
9394 let breakpoint_row = buffer_snapshot
9395 .summary_for_anchor::<text::PointUtf16>(anchor)
9396 .row;
9397
9398 if breakpoint_row == row {
9399 snapshot
9400 .buffer_snapshot
9401 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9402 .map(|anchor| (anchor, bp.clone()))
9403 } else {
9404 None
9405 }
9406 })
9407 });
9408 bp
9409 }
9410
9411 pub fn edit_log_breakpoint(
9412 &mut self,
9413 _: &EditLogBreakpoint,
9414 window: &mut Window,
9415 cx: &mut Context<Self>,
9416 ) {
9417 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9418 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9419 message: None,
9420 state: BreakpointState::Enabled,
9421 condition: None,
9422 hit_condition: None,
9423 });
9424
9425 self.add_edit_breakpoint_block(
9426 anchor,
9427 &breakpoint,
9428 BreakpointPromptEditAction::Log,
9429 window,
9430 cx,
9431 );
9432 }
9433 }
9434
9435 fn breakpoints_at_cursors(
9436 &self,
9437 window: &mut Window,
9438 cx: &mut Context<Self>,
9439 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9440 let snapshot = self.snapshot(window, cx);
9441 let cursors = self
9442 .selections
9443 .disjoint_anchors()
9444 .into_iter()
9445 .map(|selection| {
9446 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9447
9448 let breakpoint_position = self
9449 .breakpoint_at_row(cursor_position.row, window, cx)
9450 .map(|bp| bp.0)
9451 .unwrap_or_else(|| {
9452 snapshot
9453 .display_snapshot
9454 .buffer_snapshot
9455 .anchor_after(Point::new(cursor_position.row, 0))
9456 });
9457
9458 let breakpoint = self
9459 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9460 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9461
9462 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9463 })
9464 // 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.
9465 .collect::<HashMap<Anchor, _>>();
9466
9467 cursors.into_iter().collect()
9468 }
9469
9470 pub fn enable_breakpoint(
9471 &mut self,
9472 _: &crate::actions::EnableBreakpoint,
9473 window: &mut Window,
9474 cx: &mut Context<Self>,
9475 ) {
9476 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9477 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9478 continue;
9479 };
9480 self.edit_breakpoint_at_anchor(
9481 anchor,
9482 breakpoint,
9483 BreakpointEditAction::InvertState,
9484 cx,
9485 );
9486 }
9487 }
9488
9489 pub fn disable_breakpoint(
9490 &mut self,
9491 _: &crate::actions::DisableBreakpoint,
9492 window: &mut Window,
9493 cx: &mut Context<Self>,
9494 ) {
9495 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9496 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9497 continue;
9498 };
9499 self.edit_breakpoint_at_anchor(
9500 anchor,
9501 breakpoint,
9502 BreakpointEditAction::InvertState,
9503 cx,
9504 );
9505 }
9506 }
9507
9508 pub fn toggle_breakpoint(
9509 &mut self,
9510 _: &crate::actions::ToggleBreakpoint,
9511 window: &mut Window,
9512 cx: &mut Context<Self>,
9513 ) {
9514 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9515 if let Some(breakpoint) = breakpoint {
9516 self.edit_breakpoint_at_anchor(
9517 anchor,
9518 breakpoint,
9519 BreakpointEditAction::Toggle,
9520 cx,
9521 );
9522 } else {
9523 self.edit_breakpoint_at_anchor(
9524 anchor,
9525 Breakpoint::new_standard(),
9526 BreakpointEditAction::Toggle,
9527 cx,
9528 );
9529 }
9530 }
9531 }
9532
9533 pub fn edit_breakpoint_at_anchor(
9534 &mut self,
9535 breakpoint_position: Anchor,
9536 breakpoint: Breakpoint,
9537 edit_action: BreakpointEditAction,
9538 cx: &mut Context<Self>,
9539 ) {
9540 let Some(breakpoint_store) = &self.breakpoint_store else {
9541 return;
9542 };
9543
9544 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9545 if breakpoint_position == Anchor::min() {
9546 self.buffer()
9547 .read(cx)
9548 .excerpt_buffer_ids()
9549 .into_iter()
9550 .next()
9551 } else {
9552 None
9553 }
9554 }) else {
9555 return;
9556 };
9557
9558 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9559 return;
9560 };
9561
9562 breakpoint_store.update(cx, |breakpoint_store, cx| {
9563 breakpoint_store.toggle_breakpoint(
9564 buffer,
9565 (breakpoint_position.text_anchor, breakpoint),
9566 edit_action,
9567 cx,
9568 );
9569 });
9570
9571 cx.notify();
9572 }
9573
9574 #[cfg(any(test, feature = "test-support"))]
9575 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9576 self.breakpoint_store.clone()
9577 }
9578
9579 pub fn prepare_restore_change(
9580 &self,
9581 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9582 hunk: &MultiBufferDiffHunk,
9583 cx: &mut App,
9584 ) -> Option<()> {
9585 if hunk.is_created_file() {
9586 return None;
9587 }
9588 let buffer = self.buffer.read(cx);
9589 let diff = buffer.diff_for(hunk.buffer_id)?;
9590 let buffer = buffer.buffer(hunk.buffer_id)?;
9591 let buffer = buffer.read(cx);
9592 let original_text = diff
9593 .read(cx)
9594 .base_text()
9595 .as_rope()
9596 .slice(hunk.diff_base_byte_range.clone());
9597 let buffer_snapshot = buffer.snapshot();
9598 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9599 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9600 probe
9601 .0
9602 .start
9603 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9604 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9605 }) {
9606 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9607 Some(())
9608 } else {
9609 None
9610 }
9611 }
9612
9613 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9614 self.manipulate_lines(window, cx, |lines| lines.reverse())
9615 }
9616
9617 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9618 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9619 }
9620
9621 fn manipulate_lines<Fn>(
9622 &mut self,
9623 window: &mut Window,
9624 cx: &mut Context<Self>,
9625 mut callback: Fn,
9626 ) where
9627 Fn: FnMut(&mut Vec<&str>),
9628 {
9629 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9630
9631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9632 let buffer = self.buffer.read(cx).snapshot(cx);
9633
9634 let mut edits = Vec::new();
9635
9636 let selections = self.selections.all::<Point>(cx);
9637 let mut selections = selections.iter().peekable();
9638 let mut contiguous_row_selections = Vec::new();
9639 let mut new_selections = Vec::new();
9640 let mut added_lines = 0;
9641 let mut removed_lines = 0;
9642
9643 while let Some(selection) = selections.next() {
9644 let (start_row, end_row) = consume_contiguous_rows(
9645 &mut contiguous_row_selections,
9646 selection,
9647 &display_map,
9648 &mut selections,
9649 );
9650
9651 let start_point = Point::new(start_row.0, 0);
9652 let end_point = Point::new(
9653 end_row.previous_row().0,
9654 buffer.line_len(end_row.previous_row()),
9655 );
9656 let text = buffer
9657 .text_for_range(start_point..end_point)
9658 .collect::<String>();
9659
9660 let mut lines = text.split('\n').collect_vec();
9661
9662 let lines_before = lines.len();
9663 callback(&mut lines);
9664 let lines_after = lines.len();
9665
9666 edits.push((start_point..end_point, lines.join("\n")));
9667
9668 // Selections must change based on added and removed line count
9669 let start_row =
9670 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9671 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9672 new_selections.push(Selection {
9673 id: selection.id,
9674 start: start_row,
9675 end: end_row,
9676 goal: SelectionGoal::None,
9677 reversed: selection.reversed,
9678 });
9679
9680 if lines_after > lines_before {
9681 added_lines += lines_after - lines_before;
9682 } else if lines_before > lines_after {
9683 removed_lines += lines_before - lines_after;
9684 }
9685 }
9686
9687 self.transact(window, cx, |this, window, cx| {
9688 let buffer = this.buffer.update(cx, |buffer, cx| {
9689 buffer.edit(edits, None, cx);
9690 buffer.snapshot(cx)
9691 });
9692
9693 // Recalculate offsets on newly edited buffer
9694 let new_selections = new_selections
9695 .iter()
9696 .map(|s| {
9697 let start_point = Point::new(s.start.0, 0);
9698 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9699 Selection {
9700 id: s.id,
9701 start: buffer.point_to_offset(start_point),
9702 end: buffer.point_to_offset(end_point),
9703 goal: s.goal,
9704 reversed: s.reversed,
9705 }
9706 })
9707 .collect();
9708
9709 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9710 s.select(new_selections);
9711 });
9712
9713 this.request_autoscroll(Autoscroll::fit(), cx);
9714 });
9715 }
9716
9717 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9718 self.manipulate_text(window, cx, |text| {
9719 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9720 if has_upper_case_characters {
9721 text.to_lowercase()
9722 } else {
9723 text.to_uppercase()
9724 }
9725 })
9726 }
9727
9728 pub fn convert_to_upper_case(
9729 &mut self,
9730 _: &ConvertToUpperCase,
9731 window: &mut Window,
9732 cx: &mut Context<Self>,
9733 ) {
9734 self.manipulate_text(window, cx, |text| text.to_uppercase())
9735 }
9736
9737 pub fn convert_to_lower_case(
9738 &mut self,
9739 _: &ConvertToLowerCase,
9740 window: &mut Window,
9741 cx: &mut Context<Self>,
9742 ) {
9743 self.manipulate_text(window, cx, |text| text.to_lowercase())
9744 }
9745
9746 pub fn convert_to_title_case(
9747 &mut self,
9748 _: &ConvertToTitleCase,
9749 window: &mut Window,
9750 cx: &mut Context<Self>,
9751 ) {
9752 self.manipulate_text(window, cx, |text| {
9753 text.split('\n')
9754 .map(|line| line.to_case(Case::Title))
9755 .join("\n")
9756 })
9757 }
9758
9759 pub fn convert_to_snake_case(
9760 &mut self,
9761 _: &ConvertToSnakeCase,
9762 window: &mut Window,
9763 cx: &mut Context<Self>,
9764 ) {
9765 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9766 }
9767
9768 pub fn convert_to_kebab_case(
9769 &mut self,
9770 _: &ConvertToKebabCase,
9771 window: &mut Window,
9772 cx: &mut Context<Self>,
9773 ) {
9774 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9775 }
9776
9777 pub fn convert_to_upper_camel_case(
9778 &mut self,
9779 _: &ConvertToUpperCamelCase,
9780 window: &mut Window,
9781 cx: &mut Context<Self>,
9782 ) {
9783 self.manipulate_text(window, cx, |text| {
9784 text.split('\n')
9785 .map(|line| line.to_case(Case::UpperCamel))
9786 .join("\n")
9787 })
9788 }
9789
9790 pub fn convert_to_lower_camel_case(
9791 &mut self,
9792 _: &ConvertToLowerCamelCase,
9793 window: &mut Window,
9794 cx: &mut Context<Self>,
9795 ) {
9796 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9797 }
9798
9799 pub fn convert_to_opposite_case(
9800 &mut self,
9801 _: &ConvertToOppositeCase,
9802 window: &mut Window,
9803 cx: &mut Context<Self>,
9804 ) {
9805 self.manipulate_text(window, cx, |text| {
9806 text.chars()
9807 .fold(String::with_capacity(text.len()), |mut t, c| {
9808 if c.is_uppercase() {
9809 t.extend(c.to_lowercase());
9810 } else {
9811 t.extend(c.to_uppercase());
9812 }
9813 t
9814 })
9815 })
9816 }
9817
9818 pub fn convert_to_rot13(
9819 &mut self,
9820 _: &ConvertToRot13,
9821 window: &mut Window,
9822 cx: &mut Context<Self>,
9823 ) {
9824 self.manipulate_text(window, cx, |text| {
9825 text.chars()
9826 .map(|c| match c {
9827 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9828 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9829 _ => c,
9830 })
9831 .collect()
9832 })
9833 }
9834
9835 pub fn convert_to_rot47(
9836 &mut self,
9837 _: &ConvertToRot47,
9838 window: &mut Window,
9839 cx: &mut Context<Self>,
9840 ) {
9841 self.manipulate_text(window, cx, |text| {
9842 text.chars()
9843 .map(|c| {
9844 let code_point = c as u32;
9845 if code_point >= 33 && code_point <= 126 {
9846 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9847 }
9848 c
9849 })
9850 .collect()
9851 })
9852 }
9853
9854 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9855 where
9856 Fn: FnMut(&str) -> String,
9857 {
9858 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9859 let buffer = self.buffer.read(cx).snapshot(cx);
9860
9861 let mut new_selections = Vec::new();
9862 let mut edits = Vec::new();
9863 let mut selection_adjustment = 0i32;
9864
9865 for selection in self.selections.all::<usize>(cx) {
9866 let selection_is_empty = selection.is_empty();
9867
9868 let (start, end) = if selection_is_empty {
9869 let word_range = movement::surrounding_word(
9870 &display_map,
9871 selection.start.to_display_point(&display_map),
9872 );
9873 let start = word_range.start.to_offset(&display_map, Bias::Left);
9874 let end = word_range.end.to_offset(&display_map, Bias::Left);
9875 (start, end)
9876 } else {
9877 (selection.start, selection.end)
9878 };
9879
9880 let text = buffer.text_for_range(start..end).collect::<String>();
9881 let old_length = text.len() as i32;
9882 let text = callback(&text);
9883
9884 new_selections.push(Selection {
9885 start: (start as i32 - selection_adjustment) as usize,
9886 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9887 goal: SelectionGoal::None,
9888 ..selection
9889 });
9890
9891 selection_adjustment += old_length - text.len() as i32;
9892
9893 edits.push((start..end, text));
9894 }
9895
9896 self.transact(window, cx, |this, window, cx| {
9897 this.buffer.update(cx, |buffer, cx| {
9898 buffer.edit(edits, None, cx);
9899 });
9900
9901 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9902 s.select(new_selections);
9903 });
9904
9905 this.request_autoscroll(Autoscroll::fit(), cx);
9906 });
9907 }
9908
9909 pub fn duplicate(
9910 &mut self,
9911 upwards: bool,
9912 whole_lines: bool,
9913 window: &mut Window,
9914 cx: &mut Context<Self>,
9915 ) {
9916 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9917
9918 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9919 let buffer = &display_map.buffer_snapshot;
9920 let selections = self.selections.all::<Point>(cx);
9921
9922 let mut edits = Vec::new();
9923 let mut selections_iter = selections.iter().peekable();
9924 while let Some(selection) = selections_iter.next() {
9925 let mut rows = selection.spanned_rows(false, &display_map);
9926 // duplicate line-wise
9927 if whole_lines || selection.start == selection.end {
9928 // Avoid duplicating the same lines twice.
9929 while let Some(next_selection) = selections_iter.peek() {
9930 let next_rows = next_selection.spanned_rows(false, &display_map);
9931 if next_rows.start < rows.end {
9932 rows.end = next_rows.end;
9933 selections_iter.next().unwrap();
9934 } else {
9935 break;
9936 }
9937 }
9938
9939 // Copy the text from the selected row region and splice it either at the start
9940 // or end of the region.
9941 let start = Point::new(rows.start.0, 0);
9942 let end = Point::new(
9943 rows.end.previous_row().0,
9944 buffer.line_len(rows.end.previous_row()),
9945 );
9946 let text = buffer
9947 .text_for_range(start..end)
9948 .chain(Some("\n"))
9949 .collect::<String>();
9950 let insert_location = if upwards {
9951 Point::new(rows.end.0, 0)
9952 } else {
9953 start
9954 };
9955 edits.push((insert_location..insert_location, text));
9956 } else {
9957 // duplicate character-wise
9958 let start = selection.start;
9959 let end = selection.end;
9960 let text = buffer.text_for_range(start..end).collect::<String>();
9961 edits.push((selection.end..selection.end, text));
9962 }
9963 }
9964
9965 self.transact(window, cx, |this, _, cx| {
9966 this.buffer.update(cx, |buffer, cx| {
9967 buffer.edit(edits, None, cx);
9968 });
9969
9970 this.request_autoscroll(Autoscroll::fit(), cx);
9971 });
9972 }
9973
9974 pub fn duplicate_line_up(
9975 &mut self,
9976 _: &DuplicateLineUp,
9977 window: &mut Window,
9978 cx: &mut Context<Self>,
9979 ) {
9980 self.duplicate(true, true, window, cx);
9981 }
9982
9983 pub fn duplicate_line_down(
9984 &mut self,
9985 _: &DuplicateLineDown,
9986 window: &mut Window,
9987 cx: &mut Context<Self>,
9988 ) {
9989 self.duplicate(false, true, window, cx);
9990 }
9991
9992 pub fn duplicate_selection(
9993 &mut self,
9994 _: &DuplicateSelection,
9995 window: &mut Window,
9996 cx: &mut Context<Self>,
9997 ) {
9998 self.duplicate(false, false, window, cx);
9999 }
10000
10001 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10002 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10003
10004 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10005 let buffer = self.buffer.read(cx).snapshot(cx);
10006
10007 let mut edits = Vec::new();
10008 let mut unfold_ranges = Vec::new();
10009 let mut refold_creases = Vec::new();
10010
10011 let selections = self.selections.all::<Point>(cx);
10012 let mut selections = selections.iter().peekable();
10013 let mut contiguous_row_selections = Vec::new();
10014 let mut new_selections = Vec::new();
10015
10016 while let Some(selection) = selections.next() {
10017 // Find all the selections that span a contiguous row range
10018 let (start_row, end_row) = consume_contiguous_rows(
10019 &mut contiguous_row_selections,
10020 selection,
10021 &display_map,
10022 &mut selections,
10023 );
10024
10025 // Move the text spanned by the row range to be before the line preceding the row range
10026 if start_row.0 > 0 {
10027 let range_to_move = Point::new(
10028 start_row.previous_row().0,
10029 buffer.line_len(start_row.previous_row()),
10030 )
10031 ..Point::new(
10032 end_row.previous_row().0,
10033 buffer.line_len(end_row.previous_row()),
10034 );
10035 let insertion_point = display_map
10036 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10037 .0;
10038
10039 // Don't move lines across excerpts
10040 if buffer
10041 .excerpt_containing(insertion_point..range_to_move.end)
10042 .is_some()
10043 {
10044 let text = buffer
10045 .text_for_range(range_to_move.clone())
10046 .flat_map(|s| s.chars())
10047 .skip(1)
10048 .chain(['\n'])
10049 .collect::<String>();
10050
10051 edits.push((
10052 buffer.anchor_after(range_to_move.start)
10053 ..buffer.anchor_before(range_to_move.end),
10054 String::new(),
10055 ));
10056 let insertion_anchor = buffer.anchor_after(insertion_point);
10057 edits.push((insertion_anchor..insertion_anchor, text));
10058
10059 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10060
10061 // Move selections up
10062 new_selections.extend(contiguous_row_selections.drain(..).map(
10063 |mut selection| {
10064 selection.start.row -= row_delta;
10065 selection.end.row -= row_delta;
10066 selection
10067 },
10068 ));
10069
10070 // Move folds up
10071 unfold_ranges.push(range_to_move.clone());
10072 for fold in display_map.folds_in_range(
10073 buffer.anchor_before(range_to_move.start)
10074 ..buffer.anchor_after(range_to_move.end),
10075 ) {
10076 let mut start = fold.range.start.to_point(&buffer);
10077 let mut end = fold.range.end.to_point(&buffer);
10078 start.row -= row_delta;
10079 end.row -= row_delta;
10080 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10081 }
10082 }
10083 }
10084
10085 // If we didn't move line(s), preserve the existing selections
10086 new_selections.append(&mut contiguous_row_selections);
10087 }
10088
10089 self.transact(window, cx, |this, window, cx| {
10090 this.unfold_ranges(&unfold_ranges, true, true, cx);
10091 this.buffer.update(cx, |buffer, cx| {
10092 for (range, text) in edits {
10093 buffer.edit([(range, text)], None, cx);
10094 }
10095 });
10096 this.fold_creases(refold_creases, true, window, cx);
10097 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10098 s.select(new_selections);
10099 })
10100 });
10101 }
10102
10103 pub fn move_line_down(
10104 &mut self,
10105 _: &MoveLineDown,
10106 window: &mut Window,
10107 cx: &mut Context<Self>,
10108 ) {
10109 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10110
10111 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10112 let buffer = self.buffer.read(cx).snapshot(cx);
10113
10114 let mut edits = Vec::new();
10115 let mut unfold_ranges = Vec::new();
10116 let mut refold_creases = Vec::new();
10117
10118 let selections = self.selections.all::<Point>(cx);
10119 let mut selections = selections.iter().peekable();
10120 let mut contiguous_row_selections = Vec::new();
10121 let mut new_selections = Vec::new();
10122
10123 while let Some(selection) = selections.next() {
10124 // Find all the selections that span a contiguous row range
10125 let (start_row, end_row) = consume_contiguous_rows(
10126 &mut contiguous_row_selections,
10127 selection,
10128 &display_map,
10129 &mut selections,
10130 );
10131
10132 // Move the text spanned by the row range to be after the last line of the row range
10133 if end_row.0 <= buffer.max_point().row {
10134 let range_to_move =
10135 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10136 let insertion_point = display_map
10137 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10138 .0;
10139
10140 // Don't move lines across excerpt boundaries
10141 if buffer
10142 .excerpt_containing(range_to_move.start..insertion_point)
10143 .is_some()
10144 {
10145 let mut text = String::from("\n");
10146 text.extend(buffer.text_for_range(range_to_move.clone()));
10147 text.pop(); // Drop trailing newline
10148 edits.push((
10149 buffer.anchor_after(range_to_move.start)
10150 ..buffer.anchor_before(range_to_move.end),
10151 String::new(),
10152 ));
10153 let insertion_anchor = buffer.anchor_after(insertion_point);
10154 edits.push((insertion_anchor..insertion_anchor, text));
10155
10156 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10157
10158 // Move selections down
10159 new_selections.extend(contiguous_row_selections.drain(..).map(
10160 |mut selection| {
10161 selection.start.row += row_delta;
10162 selection.end.row += row_delta;
10163 selection
10164 },
10165 ));
10166
10167 // Move folds down
10168 unfold_ranges.push(range_to_move.clone());
10169 for fold in display_map.folds_in_range(
10170 buffer.anchor_before(range_to_move.start)
10171 ..buffer.anchor_after(range_to_move.end),
10172 ) {
10173 let mut start = fold.range.start.to_point(&buffer);
10174 let mut end = fold.range.end.to_point(&buffer);
10175 start.row += row_delta;
10176 end.row += row_delta;
10177 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10178 }
10179 }
10180 }
10181
10182 // If we didn't move line(s), preserve the existing selections
10183 new_selections.append(&mut contiguous_row_selections);
10184 }
10185
10186 self.transact(window, cx, |this, window, cx| {
10187 this.unfold_ranges(&unfold_ranges, true, true, cx);
10188 this.buffer.update(cx, |buffer, cx| {
10189 for (range, text) in edits {
10190 buffer.edit([(range, text)], None, cx);
10191 }
10192 });
10193 this.fold_creases(refold_creases, true, window, cx);
10194 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10195 s.select(new_selections)
10196 });
10197 });
10198 }
10199
10200 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10201 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10202 let text_layout_details = &self.text_layout_details(window);
10203 self.transact(window, cx, |this, window, cx| {
10204 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10205 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10206 s.move_with(|display_map, selection| {
10207 if !selection.is_empty() {
10208 return;
10209 }
10210
10211 let mut head = selection.head();
10212 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10213 if head.column() == display_map.line_len(head.row()) {
10214 transpose_offset = display_map
10215 .buffer_snapshot
10216 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10217 }
10218
10219 if transpose_offset == 0 {
10220 return;
10221 }
10222
10223 *head.column_mut() += 1;
10224 head = display_map.clip_point(head, Bias::Right);
10225 let goal = SelectionGoal::HorizontalPosition(
10226 display_map
10227 .x_for_display_point(head, text_layout_details)
10228 .into(),
10229 );
10230 selection.collapse_to(head, goal);
10231
10232 let transpose_start = display_map
10233 .buffer_snapshot
10234 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10235 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10236 let transpose_end = display_map
10237 .buffer_snapshot
10238 .clip_offset(transpose_offset + 1, Bias::Right);
10239 if let Some(ch) =
10240 display_map.buffer_snapshot.chars_at(transpose_start).next()
10241 {
10242 edits.push((transpose_start..transpose_offset, String::new()));
10243 edits.push((transpose_end..transpose_end, ch.to_string()));
10244 }
10245 }
10246 });
10247 edits
10248 });
10249 this.buffer
10250 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10251 let selections = this.selections.all::<usize>(cx);
10252 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10253 s.select(selections);
10254 });
10255 });
10256 }
10257
10258 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10259 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10260 self.rewrap_impl(RewrapOptions::default(), cx)
10261 }
10262
10263 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10264 let buffer = self.buffer.read(cx).snapshot(cx);
10265 let selections = self.selections.all::<Point>(cx);
10266 let mut selections = selections.iter().peekable();
10267
10268 let mut edits = Vec::new();
10269 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10270
10271 while let Some(selection) = selections.next() {
10272 let mut start_row = selection.start.row;
10273 let mut end_row = selection.end.row;
10274
10275 // Skip selections that overlap with a range that has already been rewrapped.
10276 let selection_range = start_row..end_row;
10277 if rewrapped_row_ranges
10278 .iter()
10279 .any(|range| range.overlaps(&selection_range))
10280 {
10281 continue;
10282 }
10283
10284 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10285
10286 // Since not all lines in the selection may be at the same indent
10287 // level, choose the indent size that is the most common between all
10288 // of the lines.
10289 //
10290 // If there is a tie, we use the deepest indent.
10291 let (indent_size, indent_end) = {
10292 let mut indent_size_occurrences = HashMap::default();
10293 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10294
10295 for row in start_row..=end_row {
10296 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10297 rows_by_indent_size.entry(indent).or_default().push(row);
10298 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10299 }
10300
10301 let indent_size = indent_size_occurrences
10302 .into_iter()
10303 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10304 .map(|(indent, _)| indent)
10305 .unwrap_or_default();
10306 let row = rows_by_indent_size[&indent_size][0];
10307 let indent_end = Point::new(row, indent_size.len);
10308
10309 (indent_size, indent_end)
10310 };
10311
10312 let mut line_prefix = indent_size.chars().collect::<String>();
10313
10314 let mut inside_comment = false;
10315 if let Some(comment_prefix) =
10316 buffer
10317 .language_scope_at(selection.head())
10318 .and_then(|language| {
10319 language
10320 .line_comment_prefixes()
10321 .iter()
10322 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10323 .cloned()
10324 })
10325 {
10326 line_prefix.push_str(&comment_prefix);
10327 inside_comment = true;
10328 }
10329
10330 let language_settings = buffer.language_settings_at(selection.head(), cx);
10331 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10332 RewrapBehavior::InComments => inside_comment,
10333 RewrapBehavior::InSelections => !selection.is_empty(),
10334 RewrapBehavior::Anywhere => true,
10335 };
10336
10337 let should_rewrap = options.override_language_settings
10338 || allow_rewrap_based_on_language
10339 || self.hard_wrap.is_some();
10340 if !should_rewrap {
10341 continue;
10342 }
10343
10344 if selection.is_empty() {
10345 'expand_upwards: while start_row > 0 {
10346 let prev_row = start_row - 1;
10347 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10348 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10349 {
10350 start_row = prev_row;
10351 } else {
10352 break 'expand_upwards;
10353 }
10354 }
10355
10356 'expand_downwards: while end_row < buffer.max_point().row {
10357 let next_row = end_row + 1;
10358 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10359 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10360 {
10361 end_row = next_row;
10362 } else {
10363 break 'expand_downwards;
10364 }
10365 }
10366 }
10367
10368 let start = Point::new(start_row, 0);
10369 let start_offset = start.to_offset(&buffer);
10370 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10371 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10372 let Some(lines_without_prefixes) = selection_text
10373 .lines()
10374 .map(|line| {
10375 line.strip_prefix(&line_prefix)
10376 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10377 .ok_or_else(|| {
10378 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10379 })
10380 })
10381 .collect::<Result<Vec<_>, _>>()
10382 .log_err()
10383 else {
10384 continue;
10385 };
10386
10387 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10388 buffer
10389 .language_settings_at(Point::new(start_row, 0), cx)
10390 .preferred_line_length as usize
10391 });
10392 let wrapped_text = wrap_with_prefix(
10393 line_prefix,
10394 lines_without_prefixes.join("\n"),
10395 wrap_column,
10396 tab_size,
10397 options.preserve_existing_whitespace,
10398 );
10399
10400 // TODO: should always use char-based diff while still supporting cursor behavior that
10401 // matches vim.
10402 let mut diff_options = DiffOptions::default();
10403 if options.override_language_settings {
10404 diff_options.max_word_diff_len = 0;
10405 diff_options.max_word_diff_line_count = 0;
10406 } else {
10407 diff_options.max_word_diff_len = usize::MAX;
10408 diff_options.max_word_diff_line_count = usize::MAX;
10409 }
10410
10411 for (old_range, new_text) in
10412 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10413 {
10414 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10415 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10416 edits.push((edit_start..edit_end, new_text));
10417 }
10418
10419 rewrapped_row_ranges.push(start_row..=end_row);
10420 }
10421
10422 self.buffer
10423 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10424 }
10425
10426 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10427 let mut text = String::new();
10428 let buffer = self.buffer.read(cx).snapshot(cx);
10429 let mut selections = self.selections.all::<Point>(cx);
10430 let mut clipboard_selections = Vec::with_capacity(selections.len());
10431 {
10432 let max_point = buffer.max_point();
10433 let mut is_first = true;
10434 for selection in &mut selections {
10435 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10436 if is_entire_line {
10437 selection.start = Point::new(selection.start.row, 0);
10438 if !selection.is_empty() && selection.end.column == 0 {
10439 selection.end = cmp::min(max_point, selection.end);
10440 } else {
10441 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10442 }
10443 selection.goal = SelectionGoal::None;
10444 }
10445 if is_first {
10446 is_first = false;
10447 } else {
10448 text += "\n";
10449 }
10450 let mut len = 0;
10451 for chunk in buffer.text_for_range(selection.start..selection.end) {
10452 text.push_str(chunk);
10453 len += chunk.len();
10454 }
10455 clipboard_selections.push(ClipboardSelection {
10456 len,
10457 is_entire_line,
10458 first_line_indent: buffer
10459 .indent_size_for_line(MultiBufferRow(selection.start.row))
10460 .len,
10461 });
10462 }
10463 }
10464
10465 self.transact(window, cx, |this, window, cx| {
10466 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10467 s.select(selections);
10468 });
10469 this.insert("", window, cx);
10470 });
10471 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10472 }
10473
10474 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10475 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10476 let item = self.cut_common(window, cx);
10477 cx.write_to_clipboard(item);
10478 }
10479
10480 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10481 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10482 self.change_selections(None, window, cx, |s| {
10483 s.move_with(|snapshot, sel| {
10484 if sel.is_empty() {
10485 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10486 }
10487 });
10488 });
10489 let item = self.cut_common(window, cx);
10490 cx.set_global(KillRing(item))
10491 }
10492
10493 pub fn kill_ring_yank(
10494 &mut self,
10495 _: &KillRingYank,
10496 window: &mut Window,
10497 cx: &mut Context<Self>,
10498 ) {
10499 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10500 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10501 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10502 (kill_ring.text().to_string(), kill_ring.metadata_json())
10503 } else {
10504 return;
10505 }
10506 } else {
10507 return;
10508 };
10509 self.do_paste(&text, metadata, false, window, cx);
10510 }
10511
10512 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10513 self.do_copy(true, cx);
10514 }
10515
10516 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10517 self.do_copy(false, cx);
10518 }
10519
10520 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10521 let selections = self.selections.all::<Point>(cx);
10522 let buffer = self.buffer.read(cx).read(cx);
10523 let mut text = String::new();
10524
10525 let mut clipboard_selections = Vec::with_capacity(selections.len());
10526 {
10527 let max_point = buffer.max_point();
10528 let mut is_first = true;
10529 for selection in &selections {
10530 let mut start = selection.start;
10531 let mut end = selection.end;
10532 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10533 if is_entire_line {
10534 start = Point::new(start.row, 0);
10535 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10536 }
10537
10538 let mut trimmed_selections = Vec::new();
10539 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10540 let row = MultiBufferRow(start.row);
10541 let first_indent = buffer.indent_size_for_line(row);
10542 if first_indent.len == 0 || start.column > first_indent.len {
10543 trimmed_selections.push(start..end);
10544 } else {
10545 trimmed_selections.push(
10546 Point::new(row.0, first_indent.len)
10547 ..Point::new(row.0, buffer.line_len(row)),
10548 );
10549 for row in start.row + 1..=end.row {
10550 let mut line_len = buffer.line_len(MultiBufferRow(row));
10551 if row == end.row {
10552 line_len = end.column;
10553 }
10554 if line_len == 0 {
10555 trimmed_selections
10556 .push(Point::new(row, 0)..Point::new(row, line_len));
10557 continue;
10558 }
10559 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10560 if row_indent_size.len >= first_indent.len {
10561 trimmed_selections.push(
10562 Point::new(row, first_indent.len)..Point::new(row, line_len),
10563 );
10564 } else {
10565 trimmed_selections.clear();
10566 trimmed_selections.push(start..end);
10567 break;
10568 }
10569 }
10570 }
10571 } else {
10572 trimmed_selections.push(start..end);
10573 }
10574
10575 for trimmed_range in trimmed_selections {
10576 if is_first {
10577 is_first = false;
10578 } else {
10579 text += "\n";
10580 }
10581 let mut len = 0;
10582 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10583 text.push_str(chunk);
10584 len += chunk.len();
10585 }
10586 clipboard_selections.push(ClipboardSelection {
10587 len,
10588 is_entire_line,
10589 first_line_indent: buffer
10590 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10591 .len,
10592 });
10593 }
10594 }
10595 }
10596
10597 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10598 text,
10599 clipboard_selections,
10600 ));
10601 }
10602
10603 pub fn do_paste(
10604 &mut self,
10605 text: &String,
10606 clipboard_selections: Option<Vec<ClipboardSelection>>,
10607 handle_entire_lines: bool,
10608 window: &mut Window,
10609 cx: &mut Context<Self>,
10610 ) {
10611 if self.read_only(cx) {
10612 return;
10613 }
10614
10615 let clipboard_text = Cow::Borrowed(text);
10616
10617 self.transact(window, cx, |this, window, cx| {
10618 if let Some(mut clipboard_selections) = clipboard_selections {
10619 let old_selections = this.selections.all::<usize>(cx);
10620 let all_selections_were_entire_line =
10621 clipboard_selections.iter().all(|s| s.is_entire_line);
10622 let first_selection_indent_column =
10623 clipboard_selections.first().map(|s| s.first_line_indent);
10624 if clipboard_selections.len() != old_selections.len() {
10625 clipboard_selections.drain(..);
10626 }
10627 let cursor_offset = this.selections.last::<usize>(cx).head();
10628 let mut auto_indent_on_paste = true;
10629
10630 this.buffer.update(cx, |buffer, cx| {
10631 let snapshot = buffer.read(cx);
10632 auto_indent_on_paste = snapshot
10633 .language_settings_at(cursor_offset, cx)
10634 .auto_indent_on_paste;
10635
10636 let mut start_offset = 0;
10637 let mut edits = Vec::new();
10638 let mut original_indent_columns = Vec::new();
10639 for (ix, selection) in old_selections.iter().enumerate() {
10640 let to_insert;
10641 let entire_line;
10642 let original_indent_column;
10643 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10644 let end_offset = start_offset + clipboard_selection.len;
10645 to_insert = &clipboard_text[start_offset..end_offset];
10646 entire_line = clipboard_selection.is_entire_line;
10647 start_offset = end_offset + 1;
10648 original_indent_column = Some(clipboard_selection.first_line_indent);
10649 } else {
10650 to_insert = clipboard_text.as_str();
10651 entire_line = all_selections_were_entire_line;
10652 original_indent_column = first_selection_indent_column
10653 }
10654
10655 // If the corresponding selection was empty when this slice of the
10656 // clipboard text was written, then the entire line containing the
10657 // selection was copied. If this selection is also currently empty,
10658 // then paste the line before the current line of the buffer.
10659 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10660 let column = selection.start.to_point(&snapshot).column as usize;
10661 let line_start = selection.start - column;
10662 line_start..line_start
10663 } else {
10664 selection.range()
10665 };
10666
10667 edits.push((range, to_insert));
10668 original_indent_columns.push(original_indent_column);
10669 }
10670 drop(snapshot);
10671
10672 buffer.edit(
10673 edits,
10674 if auto_indent_on_paste {
10675 Some(AutoindentMode::Block {
10676 original_indent_columns,
10677 })
10678 } else {
10679 None
10680 },
10681 cx,
10682 );
10683 });
10684
10685 let selections = this.selections.all::<usize>(cx);
10686 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10687 s.select(selections)
10688 });
10689 } else {
10690 this.insert(&clipboard_text, window, cx);
10691 }
10692 });
10693 }
10694
10695 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10696 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10697 if let Some(item) = cx.read_from_clipboard() {
10698 let entries = item.entries();
10699
10700 match entries.first() {
10701 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10702 // of all the pasted entries.
10703 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10704 .do_paste(
10705 clipboard_string.text(),
10706 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10707 true,
10708 window,
10709 cx,
10710 ),
10711 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10712 }
10713 }
10714 }
10715
10716 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10717 if self.read_only(cx) {
10718 return;
10719 }
10720
10721 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10722
10723 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10724 if let Some((selections, _)) =
10725 self.selection_history.transaction(transaction_id).cloned()
10726 {
10727 self.change_selections(None, window, cx, |s| {
10728 s.select_anchors(selections.to_vec());
10729 });
10730 } else {
10731 log::error!(
10732 "No entry in selection_history found for undo. \
10733 This may correspond to a bug where undo does not update the selection. \
10734 If this is occurring, please add details to \
10735 https://github.com/zed-industries/zed/issues/22692"
10736 );
10737 }
10738 self.request_autoscroll(Autoscroll::fit(), cx);
10739 self.unmark_text(window, cx);
10740 self.refresh_inline_completion(true, false, window, cx);
10741 cx.emit(EditorEvent::Edited { transaction_id });
10742 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10743 }
10744 }
10745
10746 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10747 if self.read_only(cx) {
10748 return;
10749 }
10750
10751 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10752
10753 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10754 if let Some((_, Some(selections))) =
10755 self.selection_history.transaction(transaction_id).cloned()
10756 {
10757 self.change_selections(None, window, cx, |s| {
10758 s.select_anchors(selections.to_vec());
10759 });
10760 } else {
10761 log::error!(
10762 "No entry in selection_history found for redo. \
10763 This may correspond to a bug where undo does not update the selection. \
10764 If this is occurring, please add details to \
10765 https://github.com/zed-industries/zed/issues/22692"
10766 );
10767 }
10768 self.request_autoscroll(Autoscroll::fit(), cx);
10769 self.unmark_text(window, cx);
10770 self.refresh_inline_completion(true, false, window, cx);
10771 cx.emit(EditorEvent::Edited { transaction_id });
10772 }
10773 }
10774
10775 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10776 self.buffer
10777 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10778 }
10779
10780 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10781 self.buffer
10782 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10783 }
10784
10785 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10786 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10787 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10788 s.move_with(|map, selection| {
10789 let cursor = if selection.is_empty() {
10790 movement::left(map, selection.start)
10791 } else {
10792 selection.start
10793 };
10794 selection.collapse_to(cursor, SelectionGoal::None);
10795 });
10796 })
10797 }
10798
10799 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10800 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10801 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10802 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10803 })
10804 }
10805
10806 pub fn move_right(&mut self, _: &MoveRight, 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_with(|map, selection| {
10810 let cursor = if selection.is_empty() {
10811 movement::right(map, selection.end)
10812 } else {
10813 selection.end
10814 };
10815 selection.collapse_to(cursor, SelectionGoal::None)
10816 });
10817 })
10818 }
10819
10820 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10821 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10822 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10823 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10824 })
10825 }
10826
10827 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10828 if self.take_rename(true, window, cx).is_some() {
10829 return;
10830 }
10831
10832 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10833 cx.propagate();
10834 return;
10835 }
10836
10837 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10838
10839 let text_layout_details = &self.text_layout_details(window);
10840 let selection_count = self.selections.count();
10841 let first_selection = self.selections.first_anchor();
10842
10843 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10844 s.move_with(|map, selection| {
10845 if !selection.is_empty() {
10846 selection.goal = SelectionGoal::None;
10847 }
10848 let (cursor, goal) = movement::up(
10849 map,
10850 selection.start,
10851 selection.goal,
10852 false,
10853 text_layout_details,
10854 );
10855 selection.collapse_to(cursor, goal);
10856 });
10857 });
10858
10859 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10860 {
10861 cx.propagate();
10862 }
10863 }
10864
10865 pub fn move_up_by_lines(
10866 &mut self,
10867 action: &MoveUpByLines,
10868 window: &mut Window,
10869 cx: &mut Context<Self>,
10870 ) {
10871 if self.take_rename(true, window, cx).is_some() {
10872 return;
10873 }
10874
10875 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10876 cx.propagate();
10877 return;
10878 }
10879
10880 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10881
10882 let text_layout_details = &self.text_layout_details(window);
10883
10884 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10885 s.move_with(|map, selection| {
10886 if !selection.is_empty() {
10887 selection.goal = SelectionGoal::None;
10888 }
10889 let (cursor, goal) = movement::up_by_rows(
10890 map,
10891 selection.start,
10892 action.lines,
10893 selection.goal,
10894 false,
10895 text_layout_details,
10896 );
10897 selection.collapse_to(cursor, goal);
10898 });
10899 })
10900 }
10901
10902 pub fn move_down_by_lines(
10903 &mut self,
10904 action: &MoveDownByLines,
10905 window: &mut Window,
10906 cx: &mut Context<Self>,
10907 ) {
10908 if self.take_rename(true, window, cx).is_some() {
10909 return;
10910 }
10911
10912 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10913 cx.propagate();
10914 return;
10915 }
10916
10917 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10918
10919 let text_layout_details = &self.text_layout_details(window);
10920
10921 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10922 s.move_with(|map, selection| {
10923 if !selection.is_empty() {
10924 selection.goal = SelectionGoal::None;
10925 }
10926 let (cursor, goal) = movement::down_by_rows(
10927 map,
10928 selection.start,
10929 action.lines,
10930 selection.goal,
10931 false,
10932 text_layout_details,
10933 );
10934 selection.collapse_to(cursor, goal);
10935 });
10936 })
10937 }
10938
10939 pub fn select_down_by_lines(
10940 &mut self,
10941 action: &SelectDownByLines,
10942 window: &mut Window,
10943 cx: &mut Context<Self>,
10944 ) {
10945 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10946 let text_layout_details = &self.text_layout_details(window);
10947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10948 s.move_heads_with(|map, head, goal| {
10949 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10950 })
10951 })
10952 }
10953
10954 pub fn select_up_by_lines(
10955 &mut self,
10956 action: &SelectUpByLines,
10957 window: &mut Window,
10958 cx: &mut Context<Self>,
10959 ) {
10960 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10961 let text_layout_details = &self.text_layout_details(window);
10962 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10963 s.move_heads_with(|map, head, goal| {
10964 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10965 })
10966 })
10967 }
10968
10969 pub fn select_page_up(
10970 &mut self,
10971 _: &SelectPageUp,
10972 window: &mut Window,
10973 cx: &mut Context<Self>,
10974 ) {
10975 let Some(row_count) = self.visible_row_count() else {
10976 return;
10977 };
10978
10979 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10980
10981 let text_layout_details = &self.text_layout_details(window);
10982
10983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10984 s.move_heads_with(|map, head, goal| {
10985 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10986 })
10987 })
10988 }
10989
10990 pub fn move_page_up(
10991 &mut self,
10992 action: &MovePageUp,
10993 window: &mut Window,
10994 cx: &mut Context<Self>,
10995 ) {
10996 if self.take_rename(true, window, cx).is_some() {
10997 return;
10998 }
10999
11000 if self
11001 .context_menu
11002 .borrow_mut()
11003 .as_mut()
11004 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11005 .unwrap_or(false)
11006 {
11007 return;
11008 }
11009
11010 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11011 cx.propagate();
11012 return;
11013 }
11014
11015 let Some(row_count) = self.visible_row_count() else {
11016 return;
11017 };
11018
11019 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11020
11021 let autoscroll = if action.center_cursor {
11022 Autoscroll::center()
11023 } else {
11024 Autoscroll::fit()
11025 };
11026
11027 let text_layout_details = &self.text_layout_details(window);
11028
11029 self.change_selections(Some(autoscroll), window, cx, |s| {
11030 s.move_with(|map, selection| {
11031 if !selection.is_empty() {
11032 selection.goal = SelectionGoal::None;
11033 }
11034 let (cursor, goal) = movement::up_by_rows(
11035 map,
11036 selection.end,
11037 row_count,
11038 selection.goal,
11039 false,
11040 text_layout_details,
11041 );
11042 selection.collapse_to(cursor, goal);
11043 });
11044 });
11045 }
11046
11047 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11048 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11049 let text_layout_details = &self.text_layout_details(window);
11050 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11051 s.move_heads_with(|map, head, goal| {
11052 movement::up(map, head, goal, false, text_layout_details)
11053 })
11054 })
11055 }
11056
11057 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11058 self.take_rename(true, window, cx);
11059
11060 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11061 cx.propagate();
11062 return;
11063 }
11064
11065 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11066
11067 let text_layout_details = &self.text_layout_details(window);
11068 let selection_count = self.selections.count();
11069 let first_selection = self.selections.first_anchor();
11070
11071 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11072 s.move_with(|map, selection| {
11073 if !selection.is_empty() {
11074 selection.goal = SelectionGoal::None;
11075 }
11076 let (cursor, goal) = movement::down(
11077 map,
11078 selection.end,
11079 selection.goal,
11080 false,
11081 text_layout_details,
11082 );
11083 selection.collapse_to(cursor, goal);
11084 });
11085 });
11086
11087 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11088 {
11089 cx.propagate();
11090 }
11091 }
11092
11093 pub fn select_page_down(
11094 &mut self,
11095 _: &SelectPageDown,
11096 window: &mut Window,
11097 cx: &mut Context<Self>,
11098 ) {
11099 let Some(row_count) = self.visible_row_count() else {
11100 return;
11101 };
11102
11103 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11104
11105 let text_layout_details = &self.text_layout_details(window);
11106
11107 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11108 s.move_heads_with(|map, head, goal| {
11109 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11110 })
11111 })
11112 }
11113
11114 pub fn move_page_down(
11115 &mut self,
11116 action: &MovePageDown,
11117 window: &mut Window,
11118 cx: &mut Context<Self>,
11119 ) {
11120 if self.take_rename(true, window, cx).is_some() {
11121 return;
11122 }
11123
11124 if self
11125 .context_menu
11126 .borrow_mut()
11127 .as_mut()
11128 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11129 .unwrap_or(false)
11130 {
11131 return;
11132 }
11133
11134 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11135 cx.propagate();
11136 return;
11137 }
11138
11139 let Some(row_count) = self.visible_row_count() else {
11140 return;
11141 };
11142
11143 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11144
11145 let autoscroll = if action.center_cursor {
11146 Autoscroll::center()
11147 } else {
11148 Autoscroll::fit()
11149 };
11150
11151 let text_layout_details = &self.text_layout_details(window);
11152 self.change_selections(Some(autoscroll), window, cx, |s| {
11153 s.move_with(|map, selection| {
11154 if !selection.is_empty() {
11155 selection.goal = SelectionGoal::None;
11156 }
11157 let (cursor, goal) = movement::down_by_rows(
11158 map,
11159 selection.end,
11160 row_count,
11161 selection.goal,
11162 false,
11163 text_layout_details,
11164 );
11165 selection.collapse_to(cursor, goal);
11166 });
11167 });
11168 }
11169
11170 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11171 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11172 let text_layout_details = &self.text_layout_details(window);
11173 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11174 s.move_heads_with(|map, head, goal| {
11175 movement::down(map, head, goal, false, text_layout_details)
11176 })
11177 });
11178 }
11179
11180 pub fn context_menu_first(
11181 &mut self,
11182 _: &ContextMenuFirst,
11183 _window: &mut Window,
11184 cx: &mut Context<Self>,
11185 ) {
11186 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11187 context_menu.select_first(self.completion_provider.as_deref(), cx);
11188 }
11189 }
11190
11191 pub fn context_menu_prev(
11192 &mut self,
11193 _: &ContextMenuPrevious,
11194 _window: &mut Window,
11195 cx: &mut Context<Self>,
11196 ) {
11197 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11198 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11199 }
11200 }
11201
11202 pub fn context_menu_next(
11203 &mut self,
11204 _: &ContextMenuNext,
11205 _window: &mut Window,
11206 cx: &mut Context<Self>,
11207 ) {
11208 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11209 context_menu.select_next(self.completion_provider.as_deref(), cx);
11210 }
11211 }
11212
11213 pub fn context_menu_last(
11214 &mut self,
11215 _: &ContextMenuLast,
11216 _window: &mut Window,
11217 cx: &mut Context<Self>,
11218 ) {
11219 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11220 context_menu.select_last(self.completion_provider.as_deref(), cx);
11221 }
11222 }
11223
11224 pub fn move_to_previous_word_start(
11225 &mut self,
11226 _: &MoveToPreviousWordStart,
11227 window: &mut Window,
11228 cx: &mut Context<Self>,
11229 ) {
11230 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11231 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11232 s.move_cursors_with(|map, head, _| {
11233 (
11234 movement::previous_word_start(map, head),
11235 SelectionGoal::None,
11236 )
11237 });
11238 })
11239 }
11240
11241 pub fn move_to_previous_subword_start(
11242 &mut self,
11243 _: &MoveToPreviousSubwordStart,
11244 window: &mut Window,
11245 cx: &mut Context<Self>,
11246 ) {
11247 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11248 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11249 s.move_cursors_with(|map, head, _| {
11250 (
11251 movement::previous_subword_start(map, head),
11252 SelectionGoal::None,
11253 )
11254 });
11255 })
11256 }
11257
11258 pub fn select_to_previous_word_start(
11259 &mut self,
11260 _: &SelectToPreviousWordStart,
11261 window: &mut Window,
11262 cx: &mut Context<Self>,
11263 ) {
11264 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11265 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11266 s.move_heads_with(|map, head, _| {
11267 (
11268 movement::previous_word_start(map, head),
11269 SelectionGoal::None,
11270 )
11271 });
11272 })
11273 }
11274
11275 pub fn select_to_previous_subword_start(
11276 &mut self,
11277 _: &SelectToPreviousSubwordStart,
11278 window: &mut Window,
11279 cx: &mut Context<Self>,
11280 ) {
11281 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11282 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11283 s.move_heads_with(|map, head, _| {
11284 (
11285 movement::previous_subword_start(map, head),
11286 SelectionGoal::None,
11287 )
11288 });
11289 })
11290 }
11291
11292 pub fn delete_to_previous_word_start(
11293 &mut self,
11294 action: &DeleteToPreviousWordStart,
11295 window: &mut Window,
11296 cx: &mut Context<Self>,
11297 ) {
11298 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11299 self.transact(window, cx, |this, window, cx| {
11300 this.select_autoclose_pair(window, cx);
11301 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11302 s.move_with(|map, selection| {
11303 if selection.is_empty() {
11304 let cursor = if action.ignore_newlines {
11305 movement::previous_word_start(map, selection.head())
11306 } else {
11307 movement::previous_word_start_or_newline(map, selection.head())
11308 };
11309 selection.set_head(cursor, SelectionGoal::None);
11310 }
11311 });
11312 });
11313 this.insert("", window, cx);
11314 });
11315 }
11316
11317 pub fn delete_to_previous_subword_start(
11318 &mut self,
11319 _: &DeleteToPreviousSubwordStart,
11320 window: &mut Window,
11321 cx: &mut Context<Self>,
11322 ) {
11323 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11324 self.transact(window, cx, |this, window, cx| {
11325 this.select_autoclose_pair(window, cx);
11326 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11327 s.move_with(|map, selection| {
11328 if selection.is_empty() {
11329 let cursor = movement::previous_subword_start(map, selection.head());
11330 selection.set_head(cursor, SelectionGoal::None);
11331 }
11332 });
11333 });
11334 this.insert("", window, cx);
11335 });
11336 }
11337
11338 pub fn move_to_next_word_end(
11339 &mut self,
11340 _: &MoveToNextWordEnd,
11341 window: &mut Window,
11342 cx: &mut Context<Self>,
11343 ) {
11344 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11345 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11346 s.move_cursors_with(|map, head, _| {
11347 (movement::next_word_end(map, head), SelectionGoal::None)
11348 });
11349 })
11350 }
11351
11352 pub fn move_to_next_subword_end(
11353 &mut self,
11354 _: &MoveToNextSubwordEnd,
11355 window: &mut Window,
11356 cx: &mut Context<Self>,
11357 ) {
11358 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11359 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11360 s.move_cursors_with(|map, head, _| {
11361 (movement::next_subword_end(map, head), SelectionGoal::None)
11362 });
11363 })
11364 }
11365
11366 pub fn select_to_next_word_end(
11367 &mut self,
11368 _: &SelectToNextWordEnd,
11369 window: &mut Window,
11370 cx: &mut Context<Self>,
11371 ) {
11372 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11373 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11374 s.move_heads_with(|map, head, _| {
11375 (movement::next_word_end(map, head), SelectionGoal::None)
11376 });
11377 })
11378 }
11379
11380 pub fn select_to_next_subword_end(
11381 &mut self,
11382 _: &SelectToNextSubwordEnd,
11383 window: &mut Window,
11384 cx: &mut Context<Self>,
11385 ) {
11386 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11387 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11388 s.move_heads_with(|map, head, _| {
11389 (movement::next_subword_end(map, head), SelectionGoal::None)
11390 });
11391 })
11392 }
11393
11394 pub fn delete_to_next_word_end(
11395 &mut self,
11396 action: &DeleteToNextWordEnd,
11397 window: &mut Window,
11398 cx: &mut Context<Self>,
11399 ) {
11400 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11401 self.transact(window, cx, |this, window, cx| {
11402 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11403 s.move_with(|map, selection| {
11404 if selection.is_empty() {
11405 let cursor = if action.ignore_newlines {
11406 movement::next_word_end(map, selection.head())
11407 } else {
11408 movement::next_word_end_or_newline(map, selection.head())
11409 };
11410 selection.set_head(cursor, SelectionGoal::None);
11411 }
11412 });
11413 });
11414 this.insert("", window, cx);
11415 });
11416 }
11417
11418 pub fn delete_to_next_subword_end(
11419 &mut self,
11420 _: &DeleteToNextSubwordEnd,
11421 window: &mut Window,
11422 cx: &mut Context<Self>,
11423 ) {
11424 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11425 self.transact(window, cx, |this, window, cx| {
11426 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11427 s.move_with(|map, selection| {
11428 if selection.is_empty() {
11429 let cursor = movement::next_subword_end(map, selection.head());
11430 selection.set_head(cursor, SelectionGoal::None);
11431 }
11432 });
11433 });
11434 this.insert("", window, cx);
11435 });
11436 }
11437
11438 pub fn move_to_beginning_of_line(
11439 &mut self,
11440 action: &MoveToBeginningOfLine,
11441 window: &mut Window,
11442 cx: &mut Context<Self>,
11443 ) {
11444 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11445 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11446 s.move_cursors_with(|map, head, _| {
11447 (
11448 movement::indented_line_beginning(
11449 map,
11450 head,
11451 action.stop_at_soft_wraps,
11452 action.stop_at_indent,
11453 ),
11454 SelectionGoal::None,
11455 )
11456 });
11457 })
11458 }
11459
11460 pub fn select_to_beginning_of_line(
11461 &mut self,
11462 action: &SelectToBeginningOfLine,
11463 window: &mut Window,
11464 cx: &mut Context<Self>,
11465 ) {
11466 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11468 s.move_heads_with(|map, head, _| {
11469 (
11470 movement::indented_line_beginning(
11471 map,
11472 head,
11473 action.stop_at_soft_wraps,
11474 action.stop_at_indent,
11475 ),
11476 SelectionGoal::None,
11477 )
11478 });
11479 });
11480 }
11481
11482 pub fn delete_to_beginning_of_line(
11483 &mut self,
11484 action: &DeleteToBeginningOfLine,
11485 window: &mut Window,
11486 cx: &mut Context<Self>,
11487 ) {
11488 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11489 self.transact(window, cx, |this, window, cx| {
11490 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11491 s.move_with(|_, selection| {
11492 selection.reversed = true;
11493 });
11494 });
11495
11496 this.select_to_beginning_of_line(
11497 &SelectToBeginningOfLine {
11498 stop_at_soft_wraps: false,
11499 stop_at_indent: action.stop_at_indent,
11500 },
11501 window,
11502 cx,
11503 );
11504 this.backspace(&Backspace, window, cx);
11505 });
11506 }
11507
11508 pub fn move_to_end_of_line(
11509 &mut self,
11510 action: &MoveToEndOfLine,
11511 window: &mut Window,
11512 cx: &mut Context<Self>,
11513 ) {
11514 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11516 s.move_cursors_with(|map, head, _| {
11517 (
11518 movement::line_end(map, head, action.stop_at_soft_wraps),
11519 SelectionGoal::None,
11520 )
11521 });
11522 })
11523 }
11524
11525 pub fn select_to_end_of_line(
11526 &mut self,
11527 action: &SelectToEndOfLine,
11528 window: &mut Window,
11529 cx: &mut Context<Self>,
11530 ) {
11531 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11532 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11533 s.move_heads_with(|map, head, _| {
11534 (
11535 movement::line_end(map, head, action.stop_at_soft_wraps),
11536 SelectionGoal::None,
11537 )
11538 });
11539 })
11540 }
11541
11542 pub fn delete_to_end_of_line(
11543 &mut self,
11544 _: &DeleteToEndOfLine,
11545 window: &mut Window,
11546 cx: &mut Context<Self>,
11547 ) {
11548 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11549 self.transact(window, cx, |this, window, cx| {
11550 this.select_to_end_of_line(
11551 &SelectToEndOfLine {
11552 stop_at_soft_wraps: false,
11553 },
11554 window,
11555 cx,
11556 );
11557 this.delete(&Delete, window, cx);
11558 });
11559 }
11560
11561 pub fn cut_to_end_of_line(
11562 &mut self,
11563 _: &CutToEndOfLine,
11564 window: &mut Window,
11565 cx: &mut Context<Self>,
11566 ) {
11567 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11568 self.transact(window, cx, |this, window, cx| {
11569 this.select_to_end_of_line(
11570 &SelectToEndOfLine {
11571 stop_at_soft_wraps: false,
11572 },
11573 window,
11574 cx,
11575 );
11576 this.cut(&Cut, window, cx);
11577 });
11578 }
11579
11580 pub fn move_to_start_of_paragraph(
11581 &mut self,
11582 _: &MoveToStartOfParagraph,
11583 window: &mut Window,
11584 cx: &mut Context<Self>,
11585 ) {
11586 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11587 cx.propagate();
11588 return;
11589 }
11590 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11591 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11592 s.move_with(|map, selection| {
11593 selection.collapse_to(
11594 movement::start_of_paragraph(map, selection.head(), 1),
11595 SelectionGoal::None,
11596 )
11597 });
11598 })
11599 }
11600
11601 pub fn move_to_end_of_paragraph(
11602 &mut self,
11603 _: &MoveToEndOfParagraph,
11604 window: &mut Window,
11605 cx: &mut Context<Self>,
11606 ) {
11607 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11608 cx.propagate();
11609 return;
11610 }
11611 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11612 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11613 s.move_with(|map, selection| {
11614 selection.collapse_to(
11615 movement::end_of_paragraph(map, selection.head(), 1),
11616 SelectionGoal::None,
11617 )
11618 });
11619 })
11620 }
11621
11622 pub fn select_to_start_of_paragraph(
11623 &mut self,
11624 _: &SelectToStartOfParagraph,
11625 window: &mut Window,
11626 cx: &mut Context<Self>,
11627 ) {
11628 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11629 cx.propagate();
11630 return;
11631 }
11632 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11633 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11634 s.move_heads_with(|map, head, _| {
11635 (
11636 movement::start_of_paragraph(map, head, 1),
11637 SelectionGoal::None,
11638 )
11639 });
11640 })
11641 }
11642
11643 pub fn select_to_end_of_paragraph(
11644 &mut self,
11645 _: &SelectToEndOfParagraph,
11646 window: &mut Window,
11647 cx: &mut Context<Self>,
11648 ) {
11649 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11650 cx.propagate();
11651 return;
11652 }
11653 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11654 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11655 s.move_heads_with(|map, head, _| {
11656 (
11657 movement::end_of_paragraph(map, head, 1),
11658 SelectionGoal::None,
11659 )
11660 });
11661 })
11662 }
11663
11664 pub fn move_to_start_of_excerpt(
11665 &mut self,
11666 _: &MoveToStartOfExcerpt,
11667 window: &mut Window,
11668 cx: &mut Context<Self>,
11669 ) {
11670 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11671 cx.propagate();
11672 return;
11673 }
11674 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11675 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11676 s.move_with(|map, selection| {
11677 selection.collapse_to(
11678 movement::start_of_excerpt(
11679 map,
11680 selection.head(),
11681 workspace::searchable::Direction::Prev,
11682 ),
11683 SelectionGoal::None,
11684 )
11685 });
11686 })
11687 }
11688
11689 pub fn move_to_start_of_next_excerpt(
11690 &mut self,
11691 _: &MoveToStartOfNextExcerpt,
11692 window: &mut Window,
11693 cx: &mut Context<Self>,
11694 ) {
11695 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11696 cx.propagate();
11697 return;
11698 }
11699
11700 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11701 s.move_with(|map, selection| {
11702 selection.collapse_to(
11703 movement::start_of_excerpt(
11704 map,
11705 selection.head(),
11706 workspace::searchable::Direction::Next,
11707 ),
11708 SelectionGoal::None,
11709 )
11710 });
11711 })
11712 }
11713
11714 pub fn move_to_end_of_excerpt(
11715 &mut self,
11716 _: &MoveToEndOfExcerpt,
11717 window: &mut Window,
11718 cx: &mut Context<Self>,
11719 ) {
11720 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11721 cx.propagate();
11722 return;
11723 }
11724 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11725 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11726 s.move_with(|map, selection| {
11727 selection.collapse_to(
11728 movement::end_of_excerpt(
11729 map,
11730 selection.head(),
11731 workspace::searchable::Direction::Next,
11732 ),
11733 SelectionGoal::None,
11734 )
11735 });
11736 })
11737 }
11738
11739 pub fn move_to_end_of_previous_excerpt(
11740 &mut self,
11741 _: &MoveToEndOfPreviousExcerpt,
11742 window: &mut Window,
11743 cx: &mut Context<Self>,
11744 ) {
11745 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11746 cx.propagate();
11747 return;
11748 }
11749 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11750 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11751 s.move_with(|map, selection| {
11752 selection.collapse_to(
11753 movement::end_of_excerpt(
11754 map,
11755 selection.head(),
11756 workspace::searchable::Direction::Prev,
11757 ),
11758 SelectionGoal::None,
11759 )
11760 });
11761 })
11762 }
11763
11764 pub fn select_to_start_of_excerpt(
11765 &mut self,
11766 _: &SelectToStartOfExcerpt,
11767 window: &mut Window,
11768 cx: &mut Context<Self>,
11769 ) {
11770 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11771 cx.propagate();
11772 return;
11773 }
11774 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11775 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11776 s.move_heads_with(|map, head, _| {
11777 (
11778 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11779 SelectionGoal::None,
11780 )
11781 });
11782 })
11783 }
11784
11785 pub fn select_to_start_of_next_excerpt(
11786 &mut self,
11787 _: &SelectToStartOfNextExcerpt,
11788 window: &mut Window,
11789 cx: &mut Context<Self>,
11790 ) {
11791 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11792 cx.propagate();
11793 return;
11794 }
11795 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11797 s.move_heads_with(|map, head, _| {
11798 (
11799 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11800 SelectionGoal::None,
11801 )
11802 });
11803 })
11804 }
11805
11806 pub fn select_to_end_of_excerpt(
11807 &mut self,
11808 _: &SelectToEndOfExcerpt,
11809 window: &mut Window,
11810 cx: &mut Context<Self>,
11811 ) {
11812 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11813 cx.propagate();
11814 return;
11815 }
11816 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11818 s.move_heads_with(|map, head, _| {
11819 (
11820 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11821 SelectionGoal::None,
11822 )
11823 });
11824 })
11825 }
11826
11827 pub fn select_to_end_of_previous_excerpt(
11828 &mut self,
11829 _: &SelectToEndOfPreviousExcerpt,
11830 window: &mut Window,
11831 cx: &mut Context<Self>,
11832 ) {
11833 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11834 cx.propagate();
11835 return;
11836 }
11837 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11838 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11839 s.move_heads_with(|map, head, _| {
11840 (
11841 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11842 SelectionGoal::None,
11843 )
11844 });
11845 })
11846 }
11847
11848 pub fn move_to_beginning(
11849 &mut self,
11850 _: &MoveToBeginning,
11851 window: &mut Window,
11852 cx: &mut Context<Self>,
11853 ) {
11854 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11855 cx.propagate();
11856 return;
11857 }
11858 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11859 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11860 s.select_ranges(vec![0..0]);
11861 });
11862 }
11863
11864 pub fn select_to_beginning(
11865 &mut self,
11866 _: &SelectToBeginning,
11867 window: &mut Window,
11868 cx: &mut Context<Self>,
11869 ) {
11870 let mut selection = self.selections.last::<Point>(cx);
11871 selection.set_head(Point::zero(), SelectionGoal::None);
11872 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11873 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11874 s.select(vec![selection]);
11875 });
11876 }
11877
11878 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11879 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11880 cx.propagate();
11881 return;
11882 }
11883 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11884 let cursor = self.buffer.read(cx).read(cx).len();
11885 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11886 s.select_ranges(vec![cursor..cursor])
11887 });
11888 }
11889
11890 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11891 self.nav_history = nav_history;
11892 }
11893
11894 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11895 self.nav_history.as_ref()
11896 }
11897
11898 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11899 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11900 }
11901
11902 fn push_to_nav_history(
11903 &mut self,
11904 cursor_anchor: Anchor,
11905 new_position: Option<Point>,
11906 is_deactivate: bool,
11907 cx: &mut Context<Self>,
11908 ) {
11909 if let Some(nav_history) = self.nav_history.as_mut() {
11910 let buffer = self.buffer.read(cx).read(cx);
11911 let cursor_position = cursor_anchor.to_point(&buffer);
11912 let scroll_state = self.scroll_manager.anchor();
11913 let scroll_top_row = scroll_state.top_row(&buffer);
11914 drop(buffer);
11915
11916 if let Some(new_position) = new_position {
11917 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11918 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11919 return;
11920 }
11921 }
11922
11923 nav_history.push(
11924 Some(NavigationData {
11925 cursor_anchor,
11926 cursor_position,
11927 scroll_anchor: scroll_state,
11928 scroll_top_row,
11929 }),
11930 cx,
11931 );
11932 cx.emit(EditorEvent::PushedToNavHistory {
11933 anchor: cursor_anchor,
11934 is_deactivate,
11935 })
11936 }
11937 }
11938
11939 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11940 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11941 let buffer = self.buffer.read(cx).snapshot(cx);
11942 let mut selection = self.selections.first::<usize>(cx);
11943 selection.set_head(buffer.len(), SelectionGoal::None);
11944 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11945 s.select(vec![selection]);
11946 });
11947 }
11948
11949 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11950 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11951 let end = self.buffer.read(cx).read(cx).len();
11952 self.change_selections(None, window, cx, |s| {
11953 s.select_ranges(vec![0..end]);
11954 });
11955 }
11956
11957 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11958 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11960 let mut selections = self.selections.all::<Point>(cx);
11961 let max_point = display_map.buffer_snapshot.max_point();
11962 for selection in &mut selections {
11963 let rows = selection.spanned_rows(true, &display_map);
11964 selection.start = Point::new(rows.start.0, 0);
11965 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11966 selection.reversed = false;
11967 }
11968 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11969 s.select(selections);
11970 });
11971 }
11972
11973 pub fn split_selection_into_lines(
11974 &mut self,
11975 _: &SplitSelectionIntoLines,
11976 window: &mut Window,
11977 cx: &mut Context<Self>,
11978 ) {
11979 let selections = self
11980 .selections
11981 .all::<Point>(cx)
11982 .into_iter()
11983 .map(|selection| selection.start..selection.end)
11984 .collect::<Vec<_>>();
11985 self.unfold_ranges(&selections, true, true, cx);
11986
11987 let mut new_selection_ranges = Vec::new();
11988 {
11989 let buffer = self.buffer.read(cx).read(cx);
11990 for selection in selections {
11991 for row in selection.start.row..selection.end.row {
11992 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11993 new_selection_ranges.push(cursor..cursor);
11994 }
11995
11996 let is_multiline_selection = selection.start.row != selection.end.row;
11997 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11998 // so this action feels more ergonomic when paired with other selection operations
11999 let should_skip_last = is_multiline_selection && selection.end.column == 0;
12000 if !should_skip_last {
12001 new_selection_ranges.push(selection.end..selection.end);
12002 }
12003 }
12004 }
12005 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12006 s.select_ranges(new_selection_ranges);
12007 });
12008 }
12009
12010 pub fn add_selection_above(
12011 &mut self,
12012 _: &AddSelectionAbove,
12013 window: &mut Window,
12014 cx: &mut Context<Self>,
12015 ) {
12016 self.add_selection(true, window, cx);
12017 }
12018
12019 pub fn add_selection_below(
12020 &mut self,
12021 _: &AddSelectionBelow,
12022 window: &mut Window,
12023 cx: &mut Context<Self>,
12024 ) {
12025 self.add_selection(false, window, cx);
12026 }
12027
12028 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12029 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12030
12031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12032 let mut selections = self.selections.all::<Point>(cx);
12033 let text_layout_details = self.text_layout_details(window);
12034 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12035 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12036 let range = oldest_selection.display_range(&display_map).sorted();
12037
12038 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12039 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12040 let positions = start_x.min(end_x)..start_x.max(end_x);
12041
12042 selections.clear();
12043 let mut stack = Vec::new();
12044 for row in range.start.row().0..=range.end.row().0 {
12045 if let Some(selection) = self.selections.build_columnar_selection(
12046 &display_map,
12047 DisplayRow(row),
12048 &positions,
12049 oldest_selection.reversed,
12050 &text_layout_details,
12051 ) {
12052 stack.push(selection.id);
12053 selections.push(selection);
12054 }
12055 }
12056
12057 if above {
12058 stack.reverse();
12059 }
12060
12061 AddSelectionsState { above, stack }
12062 });
12063
12064 let last_added_selection = *state.stack.last().unwrap();
12065 let mut new_selections = Vec::new();
12066 if above == state.above {
12067 let end_row = if above {
12068 DisplayRow(0)
12069 } else {
12070 display_map.max_point().row()
12071 };
12072
12073 'outer: for selection in selections {
12074 if selection.id == last_added_selection {
12075 let range = selection.display_range(&display_map).sorted();
12076 debug_assert_eq!(range.start.row(), range.end.row());
12077 let mut row = range.start.row();
12078 let positions =
12079 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12080 px(start)..px(end)
12081 } else {
12082 let start_x =
12083 display_map.x_for_display_point(range.start, &text_layout_details);
12084 let end_x =
12085 display_map.x_for_display_point(range.end, &text_layout_details);
12086 start_x.min(end_x)..start_x.max(end_x)
12087 };
12088
12089 while row != end_row {
12090 if above {
12091 row.0 -= 1;
12092 } else {
12093 row.0 += 1;
12094 }
12095
12096 if let Some(new_selection) = self.selections.build_columnar_selection(
12097 &display_map,
12098 row,
12099 &positions,
12100 selection.reversed,
12101 &text_layout_details,
12102 ) {
12103 state.stack.push(new_selection.id);
12104 if above {
12105 new_selections.push(new_selection);
12106 new_selections.push(selection);
12107 } else {
12108 new_selections.push(selection);
12109 new_selections.push(new_selection);
12110 }
12111
12112 continue 'outer;
12113 }
12114 }
12115 }
12116
12117 new_selections.push(selection);
12118 }
12119 } else {
12120 new_selections = selections;
12121 new_selections.retain(|s| s.id != last_added_selection);
12122 state.stack.pop();
12123 }
12124
12125 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12126 s.select(new_selections);
12127 });
12128 if state.stack.len() > 1 {
12129 self.add_selections_state = Some(state);
12130 }
12131 }
12132
12133 fn select_match_ranges(
12134 &mut self,
12135 range: Range<usize>,
12136 reversed: bool,
12137 replace_newest: bool,
12138 auto_scroll: Option<Autoscroll>,
12139 window: &mut Window,
12140 cx: &mut Context<Editor>,
12141 ) {
12142 self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12143 self.change_selections(auto_scroll, window, cx, |s| {
12144 if replace_newest {
12145 s.delete(s.newest_anchor().id);
12146 }
12147 if reversed {
12148 s.insert_range(range.end..range.start);
12149 } else {
12150 s.insert_range(range);
12151 }
12152 });
12153 }
12154
12155 pub fn select_next_match_internal(
12156 &mut self,
12157 display_map: &DisplaySnapshot,
12158 replace_newest: bool,
12159 autoscroll: Option<Autoscroll>,
12160 window: &mut Window,
12161 cx: &mut Context<Self>,
12162 ) -> Result<()> {
12163 let buffer = &display_map.buffer_snapshot;
12164 let mut selections = self.selections.all::<usize>(cx);
12165 if let Some(mut select_next_state) = self.select_next_state.take() {
12166 let query = &select_next_state.query;
12167 if !select_next_state.done {
12168 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12169 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12170 let mut next_selected_range = None;
12171
12172 let bytes_after_last_selection =
12173 buffer.bytes_in_range(last_selection.end..buffer.len());
12174 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12175 let query_matches = query
12176 .stream_find_iter(bytes_after_last_selection)
12177 .map(|result| (last_selection.end, result))
12178 .chain(
12179 query
12180 .stream_find_iter(bytes_before_first_selection)
12181 .map(|result| (0, result)),
12182 );
12183
12184 for (start_offset, query_match) in query_matches {
12185 let query_match = query_match.unwrap(); // can only fail due to I/O
12186 let offset_range =
12187 start_offset + query_match.start()..start_offset + query_match.end();
12188 let display_range = offset_range.start.to_display_point(display_map)
12189 ..offset_range.end.to_display_point(display_map);
12190
12191 if !select_next_state.wordwise
12192 || (!movement::is_inside_word(display_map, display_range.start)
12193 && !movement::is_inside_word(display_map, display_range.end))
12194 {
12195 // TODO: This is n^2, because we might check all the selections
12196 if !selections
12197 .iter()
12198 .any(|selection| selection.range().overlaps(&offset_range))
12199 {
12200 next_selected_range = Some(offset_range);
12201 break;
12202 }
12203 }
12204 }
12205
12206 if let Some(next_selected_range) = next_selected_range {
12207 self.select_match_ranges(
12208 next_selected_range,
12209 last_selection.reversed,
12210 replace_newest,
12211 autoscroll,
12212 window,
12213 cx,
12214 );
12215 } else {
12216 select_next_state.done = true;
12217 }
12218 }
12219
12220 self.select_next_state = Some(select_next_state);
12221 } else {
12222 let mut only_carets = true;
12223 let mut same_text_selected = true;
12224 let mut selected_text = None;
12225
12226 let mut selections_iter = selections.iter().peekable();
12227 while let Some(selection) = selections_iter.next() {
12228 if selection.start != selection.end {
12229 only_carets = false;
12230 }
12231
12232 if same_text_selected {
12233 if selected_text.is_none() {
12234 selected_text =
12235 Some(buffer.text_for_range(selection.range()).collect::<String>());
12236 }
12237
12238 if let Some(next_selection) = selections_iter.peek() {
12239 if next_selection.range().len() == selection.range().len() {
12240 let next_selected_text = buffer
12241 .text_for_range(next_selection.range())
12242 .collect::<String>();
12243 if Some(next_selected_text) != selected_text {
12244 same_text_selected = false;
12245 selected_text = None;
12246 }
12247 } else {
12248 same_text_selected = false;
12249 selected_text = None;
12250 }
12251 }
12252 }
12253 }
12254
12255 if only_carets {
12256 for selection in &mut selections {
12257 let word_range = movement::surrounding_word(
12258 display_map,
12259 selection.start.to_display_point(display_map),
12260 );
12261 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12262 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12263 selection.goal = SelectionGoal::None;
12264 selection.reversed = false;
12265 self.select_match_ranges(
12266 selection.start..selection.end,
12267 selection.reversed,
12268 replace_newest,
12269 autoscroll,
12270 window,
12271 cx,
12272 );
12273 }
12274
12275 if selections.len() == 1 {
12276 let selection = selections
12277 .last()
12278 .expect("ensured that there's only one selection");
12279 let query = buffer
12280 .text_for_range(selection.start..selection.end)
12281 .collect::<String>();
12282 let is_empty = query.is_empty();
12283 let select_state = SelectNextState {
12284 query: AhoCorasick::new(&[query])?,
12285 wordwise: true,
12286 done: is_empty,
12287 };
12288 self.select_next_state = Some(select_state);
12289 } else {
12290 self.select_next_state = None;
12291 }
12292 } else if let Some(selected_text) = selected_text {
12293 self.select_next_state = Some(SelectNextState {
12294 query: AhoCorasick::new(&[selected_text])?,
12295 wordwise: false,
12296 done: false,
12297 });
12298 self.select_next_match_internal(
12299 display_map,
12300 replace_newest,
12301 autoscroll,
12302 window,
12303 cx,
12304 )?;
12305 }
12306 }
12307 Ok(())
12308 }
12309
12310 pub fn select_all_matches(
12311 &mut self,
12312 _action: &SelectAllMatches,
12313 window: &mut Window,
12314 cx: &mut Context<Self>,
12315 ) -> Result<()> {
12316 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12317
12318 self.push_to_selection_history();
12319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12320
12321 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12322 let Some(select_next_state) = self.select_next_state.as_mut() else {
12323 return Ok(());
12324 };
12325 if select_next_state.done {
12326 return Ok(());
12327 }
12328
12329 let mut new_selections = Vec::new();
12330
12331 let reversed = self.selections.oldest::<usize>(cx).reversed;
12332 let buffer = &display_map.buffer_snapshot;
12333 let query_matches = select_next_state
12334 .query
12335 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12336
12337 for query_match in query_matches.into_iter() {
12338 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12339 let offset_range = if reversed {
12340 query_match.end()..query_match.start()
12341 } else {
12342 query_match.start()..query_match.end()
12343 };
12344 let display_range = offset_range.start.to_display_point(&display_map)
12345 ..offset_range.end.to_display_point(&display_map);
12346
12347 if !select_next_state.wordwise
12348 || (!movement::is_inside_word(&display_map, display_range.start)
12349 && !movement::is_inside_word(&display_map, display_range.end))
12350 {
12351 new_selections.push(offset_range.start..offset_range.end);
12352 }
12353 }
12354
12355 select_next_state.done = true;
12356 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12357 self.change_selections(None, window, cx, |selections| {
12358 selections.select_ranges(new_selections)
12359 });
12360
12361 Ok(())
12362 }
12363
12364 pub fn select_next(
12365 &mut self,
12366 action: &SelectNext,
12367 window: &mut Window,
12368 cx: &mut Context<Self>,
12369 ) -> Result<()> {
12370 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12371 self.push_to_selection_history();
12372 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12373 self.select_next_match_internal(
12374 &display_map,
12375 action.replace_newest,
12376 Some(Autoscroll::newest()),
12377 window,
12378 cx,
12379 )?;
12380 Ok(())
12381 }
12382
12383 pub fn select_previous(
12384 &mut self,
12385 action: &SelectPrevious,
12386 window: &mut Window,
12387 cx: &mut Context<Self>,
12388 ) -> Result<()> {
12389 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12390 self.push_to_selection_history();
12391 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12392 let buffer = &display_map.buffer_snapshot;
12393 let mut selections = self.selections.all::<usize>(cx);
12394 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12395 let query = &select_prev_state.query;
12396 if !select_prev_state.done {
12397 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12398 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12399 let mut next_selected_range = None;
12400 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12401 let bytes_before_last_selection =
12402 buffer.reversed_bytes_in_range(0..last_selection.start);
12403 let bytes_after_first_selection =
12404 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12405 let query_matches = query
12406 .stream_find_iter(bytes_before_last_selection)
12407 .map(|result| (last_selection.start, result))
12408 .chain(
12409 query
12410 .stream_find_iter(bytes_after_first_selection)
12411 .map(|result| (buffer.len(), result)),
12412 );
12413 for (end_offset, query_match) in query_matches {
12414 let query_match = query_match.unwrap(); // can only fail due to I/O
12415 let offset_range =
12416 end_offset - query_match.end()..end_offset - query_match.start();
12417 let display_range = offset_range.start.to_display_point(&display_map)
12418 ..offset_range.end.to_display_point(&display_map);
12419
12420 if !select_prev_state.wordwise
12421 || (!movement::is_inside_word(&display_map, display_range.start)
12422 && !movement::is_inside_word(&display_map, display_range.end))
12423 {
12424 next_selected_range = Some(offset_range);
12425 break;
12426 }
12427 }
12428
12429 if let Some(next_selected_range) = next_selected_range {
12430 self.select_match_ranges(
12431 next_selected_range,
12432 last_selection.reversed,
12433 action.replace_newest,
12434 Some(Autoscroll::newest()),
12435 window,
12436 cx,
12437 );
12438 } else {
12439 select_prev_state.done = true;
12440 }
12441 }
12442
12443 self.select_prev_state = Some(select_prev_state);
12444 } else {
12445 let mut only_carets = true;
12446 let mut same_text_selected = true;
12447 let mut selected_text = None;
12448
12449 let mut selections_iter = selections.iter().peekable();
12450 while let Some(selection) = selections_iter.next() {
12451 if selection.start != selection.end {
12452 only_carets = false;
12453 }
12454
12455 if same_text_selected {
12456 if selected_text.is_none() {
12457 selected_text =
12458 Some(buffer.text_for_range(selection.range()).collect::<String>());
12459 }
12460
12461 if let Some(next_selection) = selections_iter.peek() {
12462 if next_selection.range().len() == selection.range().len() {
12463 let next_selected_text = buffer
12464 .text_for_range(next_selection.range())
12465 .collect::<String>();
12466 if Some(next_selected_text) != selected_text {
12467 same_text_selected = false;
12468 selected_text = None;
12469 }
12470 } else {
12471 same_text_selected = false;
12472 selected_text = None;
12473 }
12474 }
12475 }
12476 }
12477
12478 if only_carets {
12479 for selection in &mut selections {
12480 let word_range = movement::surrounding_word(
12481 &display_map,
12482 selection.start.to_display_point(&display_map),
12483 );
12484 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12485 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12486 selection.goal = SelectionGoal::None;
12487 selection.reversed = false;
12488 self.select_match_ranges(
12489 selection.start..selection.end,
12490 selection.reversed,
12491 action.replace_newest,
12492 Some(Autoscroll::newest()),
12493 window,
12494 cx,
12495 );
12496 }
12497 if selections.len() == 1 {
12498 let selection = selections
12499 .last()
12500 .expect("ensured that there's only one selection");
12501 let query = buffer
12502 .text_for_range(selection.start..selection.end)
12503 .collect::<String>();
12504 let is_empty = query.is_empty();
12505 let select_state = SelectNextState {
12506 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12507 wordwise: true,
12508 done: is_empty,
12509 };
12510 self.select_prev_state = Some(select_state);
12511 } else {
12512 self.select_prev_state = None;
12513 }
12514 } else if let Some(selected_text) = selected_text {
12515 self.select_prev_state = Some(SelectNextState {
12516 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12517 wordwise: false,
12518 done: false,
12519 });
12520 self.select_previous(action, window, cx)?;
12521 }
12522 }
12523 Ok(())
12524 }
12525
12526 pub fn find_next_match(
12527 &mut self,
12528 _: &FindNextMatch,
12529 window: &mut Window,
12530 cx: &mut Context<Self>,
12531 ) -> Result<()> {
12532 let selections = self.selections.disjoint_anchors();
12533 match selections.first() {
12534 Some(first) if selections.len() >= 2 => {
12535 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12536 s.select_ranges([first.range()]);
12537 });
12538 }
12539 _ => self.select_next(
12540 &SelectNext {
12541 replace_newest: true,
12542 },
12543 window,
12544 cx,
12545 )?,
12546 }
12547 Ok(())
12548 }
12549
12550 pub fn find_previous_match(
12551 &mut self,
12552 _: &FindPreviousMatch,
12553 window: &mut Window,
12554 cx: &mut Context<Self>,
12555 ) -> Result<()> {
12556 let selections = self.selections.disjoint_anchors();
12557 match selections.last() {
12558 Some(last) if selections.len() >= 2 => {
12559 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12560 s.select_ranges([last.range()]);
12561 });
12562 }
12563 _ => self.select_previous(
12564 &SelectPrevious {
12565 replace_newest: true,
12566 },
12567 window,
12568 cx,
12569 )?,
12570 }
12571 Ok(())
12572 }
12573
12574 pub fn toggle_comments(
12575 &mut self,
12576 action: &ToggleComments,
12577 window: &mut Window,
12578 cx: &mut Context<Self>,
12579 ) {
12580 if self.read_only(cx) {
12581 return;
12582 }
12583 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12584 let text_layout_details = &self.text_layout_details(window);
12585 self.transact(window, cx, |this, window, cx| {
12586 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12587 let mut edits = Vec::new();
12588 let mut selection_edit_ranges = Vec::new();
12589 let mut last_toggled_row = None;
12590 let snapshot = this.buffer.read(cx).read(cx);
12591 let empty_str: Arc<str> = Arc::default();
12592 let mut suffixes_inserted = Vec::new();
12593 let ignore_indent = action.ignore_indent;
12594
12595 fn comment_prefix_range(
12596 snapshot: &MultiBufferSnapshot,
12597 row: MultiBufferRow,
12598 comment_prefix: &str,
12599 comment_prefix_whitespace: &str,
12600 ignore_indent: bool,
12601 ) -> Range<Point> {
12602 let indent_size = if ignore_indent {
12603 0
12604 } else {
12605 snapshot.indent_size_for_line(row).len
12606 };
12607
12608 let start = Point::new(row.0, indent_size);
12609
12610 let mut line_bytes = snapshot
12611 .bytes_in_range(start..snapshot.max_point())
12612 .flatten()
12613 .copied();
12614
12615 // If this line currently begins with the line comment prefix, then record
12616 // the range containing the prefix.
12617 if line_bytes
12618 .by_ref()
12619 .take(comment_prefix.len())
12620 .eq(comment_prefix.bytes())
12621 {
12622 // Include any whitespace that matches the comment prefix.
12623 let matching_whitespace_len = line_bytes
12624 .zip(comment_prefix_whitespace.bytes())
12625 .take_while(|(a, b)| a == b)
12626 .count() as u32;
12627 let end = Point::new(
12628 start.row,
12629 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12630 );
12631 start..end
12632 } else {
12633 start..start
12634 }
12635 }
12636
12637 fn comment_suffix_range(
12638 snapshot: &MultiBufferSnapshot,
12639 row: MultiBufferRow,
12640 comment_suffix: &str,
12641 comment_suffix_has_leading_space: bool,
12642 ) -> Range<Point> {
12643 let end = Point::new(row.0, snapshot.line_len(row));
12644 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12645
12646 let mut line_end_bytes = snapshot
12647 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12648 .flatten()
12649 .copied();
12650
12651 let leading_space_len = if suffix_start_column > 0
12652 && line_end_bytes.next() == Some(b' ')
12653 && comment_suffix_has_leading_space
12654 {
12655 1
12656 } else {
12657 0
12658 };
12659
12660 // If this line currently begins with the line comment prefix, then record
12661 // the range containing the prefix.
12662 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12663 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12664 start..end
12665 } else {
12666 end..end
12667 }
12668 }
12669
12670 // TODO: Handle selections that cross excerpts
12671 for selection in &mut selections {
12672 let start_column = snapshot
12673 .indent_size_for_line(MultiBufferRow(selection.start.row))
12674 .len;
12675 let language = if let Some(language) =
12676 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12677 {
12678 language
12679 } else {
12680 continue;
12681 };
12682
12683 selection_edit_ranges.clear();
12684
12685 // If multiple selections contain a given row, avoid processing that
12686 // row more than once.
12687 let mut start_row = MultiBufferRow(selection.start.row);
12688 if last_toggled_row == Some(start_row) {
12689 start_row = start_row.next_row();
12690 }
12691 let end_row =
12692 if selection.end.row > selection.start.row && selection.end.column == 0 {
12693 MultiBufferRow(selection.end.row - 1)
12694 } else {
12695 MultiBufferRow(selection.end.row)
12696 };
12697 last_toggled_row = Some(end_row);
12698
12699 if start_row > end_row {
12700 continue;
12701 }
12702
12703 // If the language has line comments, toggle those.
12704 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12705
12706 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12707 if ignore_indent {
12708 full_comment_prefixes = full_comment_prefixes
12709 .into_iter()
12710 .map(|s| Arc::from(s.trim_end()))
12711 .collect();
12712 }
12713
12714 if !full_comment_prefixes.is_empty() {
12715 let first_prefix = full_comment_prefixes
12716 .first()
12717 .expect("prefixes is non-empty");
12718 let prefix_trimmed_lengths = full_comment_prefixes
12719 .iter()
12720 .map(|p| p.trim_end_matches(' ').len())
12721 .collect::<SmallVec<[usize; 4]>>();
12722
12723 let mut all_selection_lines_are_comments = true;
12724
12725 for row in start_row.0..=end_row.0 {
12726 let row = MultiBufferRow(row);
12727 if start_row < end_row && snapshot.is_line_blank(row) {
12728 continue;
12729 }
12730
12731 let prefix_range = full_comment_prefixes
12732 .iter()
12733 .zip(prefix_trimmed_lengths.iter().copied())
12734 .map(|(prefix, trimmed_prefix_len)| {
12735 comment_prefix_range(
12736 snapshot.deref(),
12737 row,
12738 &prefix[..trimmed_prefix_len],
12739 &prefix[trimmed_prefix_len..],
12740 ignore_indent,
12741 )
12742 })
12743 .max_by_key(|range| range.end.column - range.start.column)
12744 .expect("prefixes is non-empty");
12745
12746 if prefix_range.is_empty() {
12747 all_selection_lines_are_comments = false;
12748 }
12749
12750 selection_edit_ranges.push(prefix_range);
12751 }
12752
12753 if all_selection_lines_are_comments {
12754 edits.extend(
12755 selection_edit_ranges
12756 .iter()
12757 .cloned()
12758 .map(|range| (range, empty_str.clone())),
12759 );
12760 } else {
12761 let min_column = selection_edit_ranges
12762 .iter()
12763 .map(|range| range.start.column)
12764 .min()
12765 .unwrap_or(0);
12766 edits.extend(selection_edit_ranges.iter().map(|range| {
12767 let position = Point::new(range.start.row, min_column);
12768 (position..position, first_prefix.clone())
12769 }));
12770 }
12771 } else if let Some((full_comment_prefix, comment_suffix)) =
12772 language.block_comment_delimiters()
12773 {
12774 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12775 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12776 let prefix_range = comment_prefix_range(
12777 snapshot.deref(),
12778 start_row,
12779 comment_prefix,
12780 comment_prefix_whitespace,
12781 ignore_indent,
12782 );
12783 let suffix_range = comment_suffix_range(
12784 snapshot.deref(),
12785 end_row,
12786 comment_suffix.trim_start_matches(' '),
12787 comment_suffix.starts_with(' '),
12788 );
12789
12790 if prefix_range.is_empty() || suffix_range.is_empty() {
12791 edits.push((
12792 prefix_range.start..prefix_range.start,
12793 full_comment_prefix.clone(),
12794 ));
12795 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12796 suffixes_inserted.push((end_row, comment_suffix.len()));
12797 } else {
12798 edits.push((prefix_range, empty_str.clone()));
12799 edits.push((suffix_range, empty_str.clone()));
12800 }
12801 } else {
12802 continue;
12803 }
12804 }
12805
12806 drop(snapshot);
12807 this.buffer.update(cx, |buffer, cx| {
12808 buffer.edit(edits, None, cx);
12809 });
12810
12811 // Adjust selections so that they end before any comment suffixes that
12812 // were inserted.
12813 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12814 let mut selections = this.selections.all::<Point>(cx);
12815 let snapshot = this.buffer.read(cx).read(cx);
12816 for selection in &mut selections {
12817 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12818 match row.cmp(&MultiBufferRow(selection.end.row)) {
12819 Ordering::Less => {
12820 suffixes_inserted.next();
12821 continue;
12822 }
12823 Ordering::Greater => break,
12824 Ordering::Equal => {
12825 if selection.end.column == snapshot.line_len(row) {
12826 if selection.is_empty() {
12827 selection.start.column -= suffix_len as u32;
12828 }
12829 selection.end.column -= suffix_len as u32;
12830 }
12831 break;
12832 }
12833 }
12834 }
12835 }
12836
12837 drop(snapshot);
12838 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12839 s.select(selections)
12840 });
12841
12842 let selections = this.selections.all::<Point>(cx);
12843 let selections_on_single_row = selections.windows(2).all(|selections| {
12844 selections[0].start.row == selections[1].start.row
12845 && selections[0].end.row == selections[1].end.row
12846 && selections[0].start.row == selections[0].end.row
12847 });
12848 let selections_selecting = selections
12849 .iter()
12850 .any(|selection| selection.start != selection.end);
12851 let advance_downwards = action.advance_downwards
12852 && selections_on_single_row
12853 && !selections_selecting
12854 && !matches!(this.mode, EditorMode::SingleLine { .. });
12855
12856 if advance_downwards {
12857 let snapshot = this.buffer.read(cx).snapshot(cx);
12858
12859 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12860 s.move_cursors_with(|display_snapshot, display_point, _| {
12861 let mut point = display_point.to_point(display_snapshot);
12862 point.row += 1;
12863 point = snapshot.clip_point(point, Bias::Left);
12864 let display_point = point.to_display_point(display_snapshot);
12865 let goal = SelectionGoal::HorizontalPosition(
12866 display_snapshot
12867 .x_for_display_point(display_point, text_layout_details)
12868 .into(),
12869 );
12870 (display_point, goal)
12871 })
12872 });
12873 }
12874 });
12875 }
12876
12877 pub fn select_enclosing_symbol(
12878 &mut self,
12879 _: &SelectEnclosingSymbol,
12880 window: &mut Window,
12881 cx: &mut Context<Self>,
12882 ) {
12883 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12884
12885 let buffer = self.buffer.read(cx).snapshot(cx);
12886 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12887
12888 fn update_selection(
12889 selection: &Selection<usize>,
12890 buffer_snap: &MultiBufferSnapshot,
12891 ) -> Option<Selection<usize>> {
12892 let cursor = selection.head();
12893 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12894 for symbol in symbols.iter().rev() {
12895 let start = symbol.range.start.to_offset(buffer_snap);
12896 let end = symbol.range.end.to_offset(buffer_snap);
12897 let new_range = start..end;
12898 if start < selection.start || end > selection.end {
12899 return Some(Selection {
12900 id: selection.id,
12901 start: new_range.start,
12902 end: new_range.end,
12903 goal: SelectionGoal::None,
12904 reversed: selection.reversed,
12905 });
12906 }
12907 }
12908 None
12909 }
12910
12911 let mut selected_larger_symbol = false;
12912 let new_selections = old_selections
12913 .iter()
12914 .map(|selection| match update_selection(selection, &buffer) {
12915 Some(new_selection) => {
12916 if new_selection.range() != selection.range() {
12917 selected_larger_symbol = true;
12918 }
12919 new_selection
12920 }
12921 None => selection.clone(),
12922 })
12923 .collect::<Vec<_>>();
12924
12925 if selected_larger_symbol {
12926 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12927 s.select(new_selections);
12928 });
12929 }
12930 }
12931
12932 pub fn select_larger_syntax_node(
12933 &mut self,
12934 _: &SelectLargerSyntaxNode,
12935 window: &mut Window,
12936 cx: &mut Context<Self>,
12937 ) {
12938 let Some(visible_row_count) = self.visible_row_count() else {
12939 return;
12940 };
12941 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12942 if old_selections.is_empty() {
12943 return;
12944 }
12945
12946 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12947
12948 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12949 let buffer = self.buffer.read(cx).snapshot(cx);
12950
12951 let mut selected_larger_node = false;
12952 let mut new_selections = old_selections
12953 .iter()
12954 .map(|selection| {
12955 let old_range = selection.start..selection.end;
12956
12957 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12958 // manually select word at selection
12959 if ["string_content", "inline"].contains(&node.kind()) {
12960 let word_range = {
12961 let display_point = buffer
12962 .offset_to_point(old_range.start)
12963 .to_display_point(&display_map);
12964 let Range { start, end } =
12965 movement::surrounding_word(&display_map, display_point);
12966 start.to_point(&display_map).to_offset(&buffer)
12967 ..end.to_point(&display_map).to_offset(&buffer)
12968 };
12969 // ignore if word is already selected
12970 if !word_range.is_empty() && old_range != word_range {
12971 let last_word_range = {
12972 let display_point = buffer
12973 .offset_to_point(old_range.end)
12974 .to_display_point(&display_map);
12975 let Range { start, end } =
12976 movement::surrounding_word(&display_map, display_point);
12977 start.to_point(&display_map).to_offset(&buffer)
12978 ..end.to_point(&display_map).to_offset(&buffer)
12979 };
12980 // only select word if start and end point belongs to same word
12981 if word_range == last_word_range {
12982 selected_larger_node = true;
12983 return Selection {
12984 id: selection.id,
12985 start: word_range.start,
12986 end: word_range.end,
12987 goal: SelectionGoal::None,
12988 reversed: selection.reversed,
12989 };
12990 }
12991 }
12992 }
12993 }
12994
12995 let mut new_range = old_range.clone();
12996 while let Some((_node, containing_range)) =
12997 buffer.syntax_ancestor(new_range.clone())
12998 {
12999 new_range = match containing_range {
13000 MultiOrSingleBufferOffsetRange::Single(_) => break,
13001 MultiOrSingleBufferOffsetRange::Multi(range) => range,
13002 };
13003 if !display_map.intersects_fold(new_range.start)
13004 && !display_map.intersects_fold(new_range.end)
13005 {
13006 break;
13007 }
13008 }
13009
13010 selected_larger_node |= new_range != old_range;
13011 Selection {
13012 id: selection.id,
13013 start: new_range.start,
13014 end: new_range.end,
13015 goal: SelectionGoal::None,
13016 reversed: selection.reversed,
13017 }
13018 })
13019 .collect::<Vec<_>>();
13020
13021 if !selected_larger_node {
13022 return; // don't put this call in the history
13023 }
13024
13025 // scroll based on transformation done to the last selection created by the user
13026 let (last_old, last_new) = old_selections
13027 .last()
13028 .zip(new_selections.last().cloned())
13029 .expect("old_selections isn't empty");
13030
13031 // revert selection
13032 let is_selection_reversed = {
13033 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13034 new_selections.last_mut().expect("checked above").reversed =
13035 should_newest_selection_be_reversed;
13036 should_newest_selection_be_reversed
13037 };
13038
13039 if selected_larger_node {
13040 self.select_syntax_node_history.disable_clearing = true;
13041 self.change_selections(None, window, cx, |s| {
13042 s.select(new_selections.clone());
13043 });
13044 self.select_syntax_node_history.disable_clearing = false;
13045 }
13046
13047 let start_row = last_new.start.to_display_point(&display_map).row().0;
13048 let end_row = last_new.end.to_display_point(&display_map).row().0;
13049 let selection_height = end_row - start_row + 1;
13050 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13051
13052 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13053 let scroll_behavior = if fits_on_the_screen {
13054 self.request_autoscroll(Autoscroll::fit(), cx);
13055 SelectSyntaxNodeScrollBehavior::FitSelection
13056 } else if is_selection_reversed {
13057 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13058 SelectSyntaxNodeScrollBehavior::CursorTop
13059 } else {
13060 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13061 SelectSyntaxNodeScrollBehavior::CursorBottom
13062 };
13063
13064 self.select_syntax_node_history.push((
13065 old_selections,
13066 scroll_behavior,
13067 is_selection_reversed,
13068 ));
13069 }
13070
13071 pub fn select_smaller_syntax_node(
13072 &mut self,
13073 _: &SelectSmallerSyntaxNode,
13074 window: &mut Window,
13075 cx: &mut Context<Self>,
13076 ) {
13077 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13078
13079 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13080 self.select_syntax_node_history.pop()
13081 {
13082 if let Some(selection) = selections.last_mut() {
13083 selection.reversed = is_selection_reversed;
13084 }
13085
13086 self.select_syntax_node_history.disable_clearing = true;
13087 self.change_selections(None, window, cx, |s| {
13088 s.select(selections.to_vec());
13089 });
13090 self.select_syntax_node_history.disable_clearing = false;
13091
13092 match scroll_behavior {
13093 SelectSyntaxNodeScrollBehavior::CursorTop => {
13094 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13095 }
13096 SelectSyntaxNodeScrollBehavior::FitSelection => {
13097 self.request_autoscroll(Autoscroll::fit(), cx);
13098 }
13099 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13100 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13101 }
13102 }
13103 }
13104 }
13105
13106 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13107 if !EditorSettings::get_global(cx).gutter.runnables {
13108 self.clear_tasks();
13109 return Task::ready(());
13110 }
13111 let project = self.project.as_ref().map(Entity::downgrade);
13112 let task_sources = self.lsp_task_sources(cx);
13113 cx.spawn_in(window, async move |editor, cx| {
13114 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13115 let Some(project) = project.and_then(|p| p.upgrade()) else {
13116 return;
13117 };
13118 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13119 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13120 }) else {
13121 return;
13122 };
13123
13124 let hide_runnables = project
13125 .update(cx, |project, cx| {
13126 // Do not display any test indicators in non-dev server remote projects.
13127 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13128 })
13129 .unwrap_or(true);
13130 if hide_runnables {
13131 return;
13132 }
13133 let new_rows =
13134 cx.background_spawn({
13135 let snapshot = display_snapshot.clone();
13136 async move {
13137 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13138 }
13139 })
13140 .await;
13141 let Ok(lsp_tasks) =
13142 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13143 else {
13144 return;
13145 };
13146 let lsp_tasks = lsp_tasks.await;
13147
13148 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13149 lsp_tasks
13150 .into_iter()
13151 .flat_map(|(kind, tasks)| {
13152 tasks.into_iter().filter_map(move |(location, task)| {
13153 Some((kind.clone(), location?, task))
13154 })
13155 })
13156 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13157 let buffer = location.target.buffer;
13158 let buffer_snapshot = buffer.read(cx).snapshot();
13159 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13160 |(excerpt_id, snapshot, _)| {
13161 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13162 display_snapshot
13163 .buffer_snapshot
13164 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13165 } else {
13166 None
13167 }
13168 },
13169 );
13170 if let Some(offset) = offset {
13171 let task_buffer_range =
13172 location.target.range.to_point(&buffer_snapshot);
13173 let context_buffer_range =
13174 task_buffer_range.to_offset(&buffer_snapshot);
13175 let context_range = BufferOffset(context_buffer_range.start)
13176 ..BufferOffset(context_buffer_range.end);
13177
13178 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13179 .or_insert_with(|| RunnableTasks {
13180 templates: Vec::new(),
13181 offset,
13182 column: task_buffer_range.start.column,
13183 extra_variables: HashMap::default(),
13184 context_range,
13185 })
13186 .templates
13187 .push((kind, task.original_task().clone()));
13188 }
13189
13190 acc
13191 })
13192 }) else {
13193 return;
13194 };
13195
13196 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13197 editor
13198 .update(cx, |editor, _| {
13199 editor.clear_tasks();
13200 for (key, mut value) in rows {
13201 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13202 value.templates.extend(lsp_tasks.templates);
13203 }
13204
13205 editor.insert_tasks(key, value);
13206 }
13207 for (key, value) in lsp_tasks_by_rows {
13208 editor.insert_tasks(key, value);
13209 }
13210 })
13211 .ok();
13212 })
13213 }
13214 fn fetch_runnable_ranges(
13215 snapshot: &DisplaySnapshot,
13216 range: Range<Anchor>,
13217 ) -> Vec<language::RunnableRange> {
13218 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13219 }
13220
13221 fn runnable_rows(
13222 project: Entity<Project>,
13223 snapshot: DisplaySnapshot,
13224 runnable_ranges: Vec<RunnableRange>,
13225 mut cx: AsyncWindowContext,
13226 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13227 runnable_ranges
13228 .into_iter()
13229 .filter_map(|mut runnable| {
13230 let tasks = cx
13231 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13232 .ok()?;
13233 if tasks.is_empty() {
13234 return None;
13235 }
13236
13237 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13238
13239 let row = snapshot
13240 .buffer_snapshot
13241 .buffer_line_for_row(MultiBufferRow(point.row))?
13242 .1
13243 .start
13244 .row;
13245
13246 let context_range =
13247 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13248 Some((
13249 (runnable.buffer_id, row),
13250 RunnableTasks {
13251 templates: tasks,
13252 offset: snapshot
13253 .buffer_snapshot
13254 .anchor_before(runnable.run_range.start),
13255 context_range,
13256 column: point.column,
13257 extra_variables: runnable.extra_captures,
13258 },
13259 ))
13260 })
13261 .collect()
13262 }
13263
13264 fn templates_with_tags(
13265 project: &Entity<Project>,
13266 runnable: &mut Runnable,
13267 cx: &mut App,
13268 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13269 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13270 let (worktree_id, file) = project
13271 .buffer_for_id(runnable.buffer, cx)
13272 .and_then(|buffer| buffer.read(cx).file())
13273 .map(|file| (file.worktree_id(cx), file.clone()))
13274 .unzip();
13275
13276 (
13277 project.task_store().read(cx).task_inventory().cloned(),
13278 worktree_id,
13279 file,
13280 )
13281 });
13282
13283 let mut templates_with_tags = mem::take(&mut runnable.tags)
13284 .into_iter()
13285 .flat_map(|RunnableTag(tag)| {
13286 inventory
13287 .as_ref()
13288 .into_iter()
13289 .flat_map(|inventory| {
13290 inventory.read(cx).list_tasks(
13291 file.clone(),
13292 Some(runnable.language.clone()),
13293 worktree_id,
13294 cx,
13295 )
13296 })
13297 .filter(move |(_, template)| {
13298 template.tags.iter().any(|source_tag| source_tag == &tag)
13299 })
13300 })
13301 .sorted_by_key(|(kind, _)| kind.to_owned())
13302 .collect::<Vec<_>>();
13303 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13304 // Strongest source wins; if we have worktree tag binding, prefer that to
13305 // global and language bindings;
13306 // if we have a global binding, prefer that to language binding.
13307 let first_mismatch = templates_with_tags
13308 .iter()
13309 .position(|(tag_source, _)| tag_source != leading_tag_source);
13310 if let Some(index) = first_mismatch {
13311 templates_with_tags.truncate(index);
13312 }
13313 }
13314
13315 templates_with_tags
13316 }
13317
13318 pub fn move_to_enclosing_bracket(
13319 &mut self,
13320 _: &MoveToEnclosingBracket,
13321 window: &mut Window,
13322 cx: &mut Context<Self>,
13323 ) {
13324 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13325 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13326 s.move_offsets_with(|snapshot, selection| {
13327 let Some(enclosing_bracket_ranges) =
13328 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13329 else {
13330 return;
13331 };
13332
13333 let mut best_length = usize::MAX;
13334 let mut best_inside = false;
13335 let mut best_in_bracket_range = false;
13336 let mut best_destination = None;
13337 for (open, close) in enclosing_bracket_ranges {
13338 let close = close.to_inclusive();
13339 let length = close.end() - open.start;
13340 let inside = selection.start >= open.end && selection.end <= *close.start();
13341 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13342 || close.contains(&selection.head());
13343
13344 // If best is next to a bracket and current isn't, skip
13345 if !in_bracket_range && best_in_bracket_range {
13346 continue;
13347 }
13348
13349 // Prefer smaller lengths unless best is inside and current isn't
13350 if length > best_length && (best_inside || !inside) {
13351 continue;
13352 }
13353
13354 best_length = length;
13355 best_inside = inside;
13356 best_in_bracket_range = in_bracket_range;
13357 best_destination = Some(
13358 if close.contains(&selection.start) && close.contains(&selection.end) {
13359 if inside { open.end } else { open.start }
13360 } else if inside {
13361 *close.start()
13362 } else {
13363 *close.end()
13364 },
13365 );
13366 }
13367
13368 if let Some(destination) = best_destination {
13369 selection.collapse_to(destination, SelectionGoal::None);
13370 }
13371 })
13372 });
13373 }
13374
13375 pub fn undo_selection(
13376 &mut self,
13377 _: &UndoSelection,
13378 window: &mut Window,
13379 cx: &mut Context<Self>,
13380 ) {
13381 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13382 self.end_selection(window, cx);
13383 self.selection_history.mode = SelectionHistoryMode::Undoing;
13384 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13385 self.change_selections(None, window, cx, |s| {
13386 s.select_anchors(entry.selections.to_vec())
13387 });
13388 self.select_next_state = entry.select_next_state;
13389 self.select_prev_state = entry.select_prev_state;
13390 self.add_selections_state = entry.add_selections_state;
13391 self.request_autoscroll(Autoscroll::newest(), cx);
13392 }
13393 self.selection_history.mode = SelectionHistoryMode::Normal;
13394 }
13395
13396 pub fn redo_selection(
13397 &mut self,
13398 _: &RedoSelection,
13399 window: &mut Window,
13400 cx: &mut Context<Self>,
13401 ) {
13402 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13403 self.end_selection(window, cx);
13404 self.selection_history.mode = SelectionHistoryMode::Redoing;
13405 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13406 self.change_selections(None, window, cx, |s| {
13407 s.select_anchors(entry.selections.to_vec())
13408 });
13409 self.select_next_state = entry.select_next_state;
13410 self.select_prev_state = entry.select_prev_state;
13411 self.add_selections_state = entry.add_selections_state;
13412 self.request_autoscroll(Autoscroll::newest(), cx);
13413 }
13414 self.selection_history.mode = SelectionHistoryMode::Normal;
13415 }
13416
13417 pub fn expand_excerpts(
13418 &mut self,
13419 action: &ExpandExcerpts,
13420 _: &mut Window,
13421 cx: &mut Context<Self>,
13422 ) {
13423 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13424 }
13425
13426 pub fn expand_excerpts_down(
13427 &mut self,
13428 action: &ExpandExcerptsDown,
13429 _: &mut Window,
13430 cx: &mut Context<Self>,
13431 ) {
13432 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13433 }
13434
13435 pub fn expand_excerpts_up(
13436 &mut self,
13437 action: &ExpandExcerptsUp,
13438 _: &mut Window,
13439 cx: &mut Context<Self>,
13440 ) {
13441 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13442 }
13443
13444 pub fn expand_excerpts_for_direction(
13445 &mut self,
13446 lines: u32,
13447 direction: ExpandExcerptDirection,
13448
13449 cx: &mut Context<Self>,
13450 ) {
13451 let selections = self.selections.disjoint_anchors();
13452
13453 let lines = if lines == 0 {
13454 EditorSettings::get_global(cx).expand_excerpt_lines
13455 } else {
13456 lines
13457 };
13458
13459 self.buffer.update(cx, |buffer, cx| {
13460 let snapshot = buffer.snapshot(cx);
13461 let mut excerpt_ids = selections
13462 .iter()
13463 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13464 .collect::<Vec<_>>();
13465 excerpt_ids.sort();
13466 excerpt_ids.dedup();
13467 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13468 })
13469 }
13470
13471 pub fn expand_excerpt(
13472 &mut self,
13473 excerpt: ExcerptId,
13474 direction: ExpandExcerptDirection,
13475 window: &mut Window,
13476 cx: &mut Context<Self>,
13477 ) {
13478 let current_scroll_position = self.scroll_position(cx);
13479 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13480 let mut should_scroll_up = false;
13481
13482 if direction == ExpandExcerptDirection::Down {
13483 let multi_buffer = self.buffer.read(cx);
13484 let snapshot = multi_buffer.snapshot(cx);
13485 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13486 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13487 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13488 let buffer_snapshot = buffer.read(cx).snapshot();
13489 let excerpt_end_row =
13490 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13491 let last_row = buffer_snapshot.max_point().row;
13492 let lines_below = last_row.saturating_sub(excerpt_end_row);
13493 should_scroll_up = lines_below >= lines_to_expand;
13494 }
13495 }
13496 }
13497 }
13498
13499 self.buffer.update(cx, |buffer, cx| {
13500 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13501 });
13502
13503 if should_scroll_up {
13504 let new_scroll_position =
13505 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13506 self.set_scroll_position(new_scroll_position, window, cx);
13507 }
13508 }
13509
13510 pub fn go_to_singleton_buffer_point(
13511 &mut self,
13512 point: Point,
13513 window: &mut Window,
13514 cx: &mut Context<Self>,
13515 ) {
13516 self.go_to_singleton_buffer_range(point..point, window, cx);
13517 }
13518
13519 pub fn go_to_singleton_buffer_range(
13520 &mut self,
13521 range: Range<Point>,
13522 window: &mut Window,
13523 cx: &mut Context<Self>,
13524 ) {
13525 let multibuffer = self.buffer().read(cx);
13526 let Some(buffer) = multibuffer.as_singleton() else {
13527 return;
13528 };
13529 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13530 return;
13531 };
13532 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13533 return;
13534 };
13535 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13536 s.select_anchor_ranges([start..end])
13537 });
13538 }
13539
13540 pub fn go_to_diagnostic(
13541 &mut self,
13542 _: &GoToDiagnostic,
13543 window: &mut Window,
13544 cx: &mut Context<Self>,
13545 ) {
13546 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13547 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13548 }
13549
13550 pub fn go_to_prev_diagnostic(
13551 &mut self,
13552 _: &GoToPreviousDiagnostic,
13553 window: &mut Window,
13554 cx: &mut Context<Self>,
13555 ) {
13556 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13557 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13558 }
13559
13560 pub fn go_to_diagnostic_impl(
13561 &mut self,
13562 direction: Direction,
13563 window: &mut Window,
13564 cx: &mut Context<Self>,
13565 ) {
13566 let buffer = self.buffer.read(cx).snapshot(cx);
13567 let selection = self.selections.newest::<usize>(cx);
13568
13569 let mut active_group_id = None;
13570 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13571 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13572 active_group_id = Some(active_group.group_id);
13573 }
13574 }
13575
13576 fn filtered(
13577 snapshot: EditorSnapshot,
13578 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13579 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13580 diagnostics
13581 .filter(|entry| entry.range.start != entry.range.end)
13582 .filter(|entry| !entry.diagnostic.is_unnecessary)
13583 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13584 }
13585
13586 let snapshot = self.snapshot(window, cx);
13587 let before = filtered(
13588 snapshot.clone(),
13589 buffer
13590 .diagnostics_in_range(0..selection.start)
13591 .filter(|entry| entry.range.start <= selection.start),
13592 );
13593 let after = filtered(
13594 snapshot,
13595 buffer
13596 .diagnostics_in_range(selection.start..buffer.len())
13597 .filter(|entry| entry.range.start >= selection.start),
13598 );
13599
13600 let mut found: Option<DiagnosticEntry<usize>> = None;
13601 if direction == Direction::Prev {
13602 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13603 {
13604 for diagnostic in prev_diagnostics.into_iter().rev() {
13605 if diagnostic.range.start != selection.start
13606 || active_group_id
13607 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13608 {
13609 found = Some(diagnostic);
13610 break 'outer;
13611 }
13612 }
13613 }
13614 } else {
13615 for diagnostic in after.chain(before) {
13616 if diagnostic.range.start != selection.start
13617 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13618 {
13619 found = Some(diagnostic);
13620 break;
13621 }
13622 }
13623 }
13624 let Some(next_diagnostic) = found else {
13625 return;
13626 };
13627
13628 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13629 return;
13630 };
13631 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13632 s.select_ranges(vec![
13633 next_diagnostic.range.start..next_diagnostic.range.start,
13634 ])
13635 });
13636 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13637 self.refresh_inline_completion(false, true, window, cx);
13638 }
13639
13640 pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13641 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13642 let snapshot = self.snapshot(window, cx);
13643 let selection = self.selections.newest::<Point>(cx);
13644 self.go_to_hunk_before_or_after_position(
13645 &snapshot,
13646 selection.head(),
13647 Direction::Next,
13648 window,
13649 cx,
13650 );
13651 }
13652
13653 pub fn go_to_hunk_before_or_after_position(
13654 &mut self,
13655 snapshot: &EditorSnapshot,
13656 position: Point,
13657 direction: Direction,
13658 window: &mut Window,
13659 cx: &mut Context<Editor>,
13660 ) {
13661 let row = if direction == Direction::Next {
13662 self.hunk_after_position(snapshot, position)
13663 .map(|hunk| hunk.row_range.start)
13664 } else {
13665 self.hunk_before_position(snapshot, position)
13666 };
13667
13668 if let Some(row) = row {
13669 let destination = Point::new(row.0, 0);
13670 let autoscroll = Autoscroll::center();
13671
13672 self.unfold_ranges(&[destination..destination], false, false, cx);
13673 self.change_selections(Some(autoscroll), window, cx, |s| {
13674 s.select_ranges([destination..destination]);
13675 });
13676 }
13677 }
13678
13679 fn hunk_after_position(
13680 &mut self,
13681 snapshot: &EditorSnapshot,
13682 position: Point,
13683 ) -> Option<MultiBufferDiffHunk> {
13684 snapshot
13685 .buffer_snapshot
13686 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13687 .find(|hunk| hunk.row_range.start.0 > position.row)
13688 .or_else(|| {
13689 snapshot
13690 .buffer_snapshot
13691 .diff_hunks_in_range(Point::zero()..position)
13692 .find(|hunk| hunk.row_range.end.0 < position.row)
13693 })
13694 }
13695
13696 fn go_to_prev_hunk(
13697 &mut self,
13698 _: &GoToPreviousHunk,
13699 window: &mut Window,
13700 cx: &mut Context<Self>,
13701 ) {
13702 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13703 let snapshot = self.snapshot(window, cx);
13704 let selection = self.selections.newest::<Point>(cx);
13705 self.go_to_hunk_before_or_after_position(
13706 &snapshot,
13707 selection.head(),
13708 Direction::Prev,
13709 window,
13710 cx,
13711 );
13712 }
13713
13714 fn hunk_before_position(
13715 &mut self,
13716 snapshot: &EditorSnapshot,
13717 position: Point,
13718 ) -> Option<MultiBufferRow> {
13719 snapshot
13720 .buffer_snapshot
13721 .diff_hunk_before(position)
13722 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13723 }
13724
13725 fn go_to_next_change(
13726 &mut self,
13727 _: &GoToNextChange,
13728 window: &mut Window,
13729 cx: &mut Context<Self>,
13730 ) {
13731 if let Some(selections) = self
13732 .change_list
13733 .next_change(1, Direction::Next)
13734 .map(|s| s.to_vec())
13735 {
13736 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13737 let map = s.display_map();
13738 s.select_display_ranges(selections.iter().map(|a| {
13739 let point = a.to_display_point(&map);
13740 point..point
13741 }))
13742 })
13743 }
13744 }
13745
13746 fn go_to_previous_change(
13747 &mut self,
13748 _: &GoToPreviousChange,
13749 window: &mut Window,
13750 cx: &mut Context<Self>,
13751 ) {
13752 if let Some(selections) = self
13753 .change_list
13754 .next_change(1, Direction::Prev)
13755 .map(|s| s.to_vec())
13756 {
13757 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13758 let map = s.display_map();
13759 s.select_display_ranges(selections.iter().map(|a| {
13760 let point = a.to_display_point(&map);
13761 point..point
13762 }))
13763 })
13764 }
13765 }
13766
13767 fn go_to_line<T: 'static>(
13768 &mut self,
13769 position: Anchor,
13770 highlight_color: Option<Hsla>,
13771 window: &mut Window,
13772 cx: &mut Context<Self>,
13773 ) {
13774 let snapshot = self.snapshot(window, cx).display_snapshot;
13775 let position = position.to_point(&snapshot.buffer_snapshot);
13776 let start = snapshot
13777 .buffer_snapshot
13778 .clip_point(Point::new(position.row, 0), Bias::Left);
13779 let end = start + Point::new(1, 0);
13780 let start = snapshot.buffer_snapshot.anchor_before(start);
13781 let end = snapshot.buffer_snapshot.anchor_before(end);
13782
13783 self.highlight_rows::<T>(
13784 start..end,
13785 highlight_color
13786 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13787 Default::default(),
13788 cx,
13789 );
13790 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13791 }
13792
13793 pub fn go_to_definition(
13794 &mut self,
13795 _: &GoToDefinition,
13796 window: &mut Window,
13797 cx: &mut Context<Self>,
13798 ) -> Task<Result<Navigated>> {
13799 let definition =
13800 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13801 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13802 cx.spawn_in(window, async move |editor, cx| {
13803 if definition.await? == Navigated::Yes {
13804 return Ok(Navigated::Yes);
13805 }
13806 match fallback_strategy {
13807 GoToDefinitionFallback::None => Ok(Navigated::No),
13808 GoToDefinitionFallback::FindAllReferences => {
13809 match editor.update_in(cx, |editor, window, cx| {
13810 editor.find_all_references(&FindAllReferences, window, cx)
13811 })? {
13812 Some(references) => references.await,
13813 None => Ok(Navigated::No),
13814 }
13815 }
13816 }
13817 })
13818 }
13819
13820 pub fn go_to_declaration(
13821 &mut self,
13822 _: &GoToDeclaration,
13823 window: &mut Window,
13824 cx: &mut Context<Self>,
13825 ) -> Task<Result<Navigated>> {
13826 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13827 }
13828
13829 pub fn go_to_declaration_split(
13830 &mut self,
13831 _: &GoToDeclaration,
13832 window: &mut Window,
13833 cx: &mut Context<Self>,
13834 ) -> Task<Result<Navigated>> {
13835 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13836 }
13837
13838 pub fn go_to_implementation(
13839 &mut self,
13840 _: &GoToImplementation,
13841 window: &mut Window,
13842 cx: &mut Context<Self>,
13843 ) -> Task<Result<Navigated>> {
13844 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13845 }
13846
13847 pub fn go_to_implementation_split(
13848 &mut self,
13849 _: &GoToImplementationSplit,
13850 window: &mut Window,
13851 cx: &mut Context<Self>,
13852 ) -> Task<Result<Navigated>> {
13853 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13854 }
13855
13856 pub fn go_to_type_definition(
13857 &mut self,
13858 _: &GoToTypeDefinition,
13859 window: &mut Window,
13860 cx: &mut Context<Self>,
13861 ) -> Task<Result<Navigated>> {
13862 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13863 }
13864
13865 pub fn go_to_definition_split(
13866 &mut self,
13867 _: &GoToDefinitionSplit,
13868 window: &mut Window,
13869 cx: &mut Context<Self>,
13870 ) -> Task<Result<Navigated>> {
13871 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13872 }
13873
13874 pub fn go_to_type_definition_split(
13875 &mut self,
13876 _: &GoToTypeDefinitionSplit,
13877 window: &mut Window,
13878 cx: &mut Context<Self>,
13879 ) -> Task<Result<Navigated>> {
13880 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13881 }
13882
13883 fn go_to_definition_of_kind(
13884 &mut self,
13885 kind: GotoDefinitionKind,
13886 split: bool,
13887 window: &mut Window,
13888 cx: &mut Context<Self>,
13889 ) -> Task<Result<Navigated>> {
13890 let Some(provider) = self.semantics_provider.clone() else {
13891 return Task::ready(Ok(Navigated::No));
13892 };
13893 let head = self.selections.newest::<usize>(cx).head();
13894 let buffer = self.buffer.read(cx);
13895 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13896 text_anchor
13897 } else {
13898 return Task::ready(Ok(Navigated::No));
13899 };
13900
13901 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13902 return Task::ready(Ok(Navigated::No));
13903 };
13904
13905 cx.spawn_in(window, async move |editor, cx| {
13906 let definitions = definitions.await?;
13907 let navigated = editor
13908 .update_in(cx, |editor, window, cx| {
13909 editor.navigate_to_hover_links(
13910 Some(kind),
13911 definitions
13912 .into_iter()
13913 .filter(|location| {
13914 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13915 })
13916 .map(HoverLink::Text)
13917 .collect::<Vec<_>>(),
13918 split,
13919 window,
13920 cx,
13921 )
13922 })?
13923 .await?;
13924 anyhow::Ok(navigated)
13925 })
13926 }
13927
13928 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13929 let selection = self.selections.newest_anchor();
13930 let head = selection.head();
13931 let tail = selection.tail();
13932
13933 let Some((buffer, start_position)) =
13934 self.buffer.read(cx).text_anchor_for_position(head, cx)
13935 else {
13936 return;
13937 };
13938
13939 let end_position = if head != tail {
13940 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13941 return;
13942 };
13943 Some(pos)
13944 } else {
13945 None
13946 };
13947
13948 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13949 let url = if let Some(end_pos) = end_position {
13950 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13951 } else {
13952 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13953 };
13954
13955 if let Some(url) = url {
13956 editor.update(cx, |_, cx| {
13957 cx.open_url(&url);
13958 })
13959 } else {
13960 Ok(())
13961 }
13962 });
13963
13964 url_finder.detach();
13965 }
13966
13967 pub fn open_selected_filename(
13968 &mut self,
13969 _: &OpenSelectedFilename,
13970 window: &mut Window,
13971 cx: &mut Context<Self>,
13972 ) {
13973 let Some(workspace) = self.workspace() else {
13974 return;
13975 };
13976
13977 let position = self.selections.newest_anchor().head();
13978
13979 let Some((buffer, buffer_position)) =
13980 self.buffer.read(cx).text_anchor_for_position(position, cx)
13981 else {
13982 return;
13983 };
13984
13985 let project = self.project.clone();
13986
13987 cx.spawn_in(window, async move |_, cx| {
13988 let result = find_file(&buffer, project, buffer_position, cx).await;
13989
13990 if let Some((_, path)) = result {
13991 workspace
13992 .update_in(cx, |workspace, window, cx| {
13993 workspace.open_resolved_path(path, window, cx)
13994 })?
13995 .await?;
13996 }
13997 anyhow::Ok(())
13998 })
13999 .detach();
14000 }
14001
14002 pub(crate) fn navigate_to_hover_links(
14003 &mut self,
14004 kind: Option<GotoDefinitionKind>,
14005 mut definitions: Vec<HoverLink>,
14006 split: bool,
14007 window: &mut Window,
14008 cx: &mut Context<Editor>,
14009 ) -> Task<Result<Navigated>> {
14010 // If there is one definition, just open it directly
14011 if definitions.len() == 1 {
14012 let definition = definitions.pop().unwrap();
14013
14014 enum TargetTaskResult {
14015 Location(Option<Location>),
14016 AlreadyNavigated,
14017 }
14018
14019 let target_task = match definition {
14020 HoverLink::Text(link) => {
14021 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14022 }
14023 HoverLink::InlayHint(lsp_location, server_id) => {
14024 let computation =
14025 self.compute_target_location(lsp_location, server_id, window, cx);
14026 cx.background_spawn(async move {
14027 let location = computation.await?;
14028 Ok(TargetTaskResult::Location(location))
14029 })
14030 }
14031 HoverLink::Url(url) => {
14032 cx.open_url(&url);
14033 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14034 }
14035 HoverLink::File(path) => {
14036 if let Some(workspace) = self.workspace() {
14037 cx.spawn_in(window, async move |_, cx| {
14038 workspace
14039 .update_in(cx, |workspace, window, cx| {
14040 workspace.open_resolved_path(path, window, cx)
14041 })?
14042 .await
14043 .map(|_| TargetTaskResult::AlreadyNavigated)
14044 })
14045 } else {
14046 Task::ready(Ok(TargetTaskResult::Location(None)))
14047 }
14048 }
14049 };
14050 cx.spawn_in(window, async move |editor, cx| {
14051 let target = match target_task.await.context("target resolution task")? {
14052 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14053 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14054 TargetTaskResult::Location(Some(target)) => target,
14055 };
14056
14057 editor.update_in(cx, |editor, window, cx| {
14058 let Some(workspace) = editor.workspace() else {
14059 return Navigated::No;
14060 };
14061 let pane = workspace.read(cx).active_pane().clone();
14062
14063 let range = target.range.to_point(target.buffer.read(cx));
14064 let range = editor.range_for_match(&range);
14065 let range = collapse_multiline_range(range);
14066
14067 if !split
14068 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14069 {
14070 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14071 } else {
14072 window.defer(cx, move |window, cx| {
14073 let target_editor: Entity<Self> =
14074 workspace.update(cx, |workspace, cx| {
14075 let pane = if split {
14076 workspace.adjacent_pane(window, cx)
14077 } else {
14078 workspace.active_pane().clone()
14079 };
14080
14081 workspace.open_project_item(
14082 pane,
14083 target.buffer.clone(),
14084 true,
14085 true,
14086 window,
14087 cx,
14088 )
14089 });
14090 target_editor.update(cx, |target_editor, cx| {
14091 // When selecting a definition in a different buffer, disable the nav history
14092 // to avoid creating a history entry at the previous cursor location.
14093 pane.update(cx, |pane, _| pane.disable_history());
14094 target_editor.go_to_singleton_buffer_range(range, window, cx);
14095 pane.update(cx, |pane, _| pane.enable_history());
14096 });
14097 });
14098 }
14099 Navigated::Yes
14100 })
14101 })
14102 } else if !definitions.is_empty() {
14103 cx.spawn_in(window, async move |editor, cx| {
14104 let (title, location_tasks, workspace) = editor
14105 .update_in(cx, |editor, window, cx| {
14106 let tab_kind = match kind {
14107 Some(GotoDefinitionKind::Implementation) => "Implementations",
14108 _ => "Definitions",
14109 };
14110 let title = definitions
14111 .iter()
14112 .find_map(|definition| match definition {
14113 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14114 let buffer = origin.buffer.read(cx);
14115 format!(
14116 "{} for {}",
14117 tab_kind,
14118 buffer
14119 .text_for_range(origin.range.clone())
14120 .collect::<String>()
14121 )
14122 }),
14123 HoverLink::InlayHint(_, _) => None,
14124 HoverLink::Url(_) => None,
14125 HoverLink::File(_) => None,
14126 })
14127 .unwrap_or(tab_kind.to_string());
14128 let location_tasks = definitions
14129 .into_iter()
14130 .map(|definition| match definition {
14131 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14132 HoverLink::InlayHint(lsp_location, server_id) => editor
14133 .compute_target_location(lsp_location, server_id, window, cx),
14134 HoverLink::Url(_) => Task::ready(Ok(None)),
14135 HoverLink::File(_) => Task::ready(Ok(None)),
14136 })
14137 .collect::<Vec<_>>();
14138 (title, location_tasks, editor.workspace().clone())
14139 })
14140 .context("location tasks preparation")?;
14141
14142 let locations = future::join_all(location_tasks)
14143 .await
14144 .into_iter()
14145 .filter_map(|location| location.transpose())
14146 .collect::<Result<_>>()
14147 .context("location tasks")?;
14148
14149 let Some(workspace) = workspace else {
14150 return Ok(Navigated::No);
14151 };
14152 let opened = workspace
14153 .update_in(cx, |workspace, window, cx| {
14154 Self::open_locations_in_multibuffer(
14155 workspace,
14156 locations,
14157 title,
14158 split,
14159 MultibufferSelectionMode::First,
14160 window,
14161 cx,
14162 )
14163 })
14164 .ok();
14165
14166 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14167 })
14168 } else {
14169 Task::ready(Ok(Navigated::No))
14170 }
14171 }
14172
14173 fn compute_target_location(
14174 &self,
14175 lsp_location: lsp::Location,
14176 server_id: LanguageServerId,
14177 window: &mut Window,
14178 cx: &mut Context<Self>,
14179 ) -> Task<anyhow::Result<Option<Location>>> {
14180 let Some(project) = self.project.clone() else {
14181 return Task::ready(Ok(None));
14182 };
14183
14184 cx.spawn_in(window, async move |editor, cx| {
14185 let location_task = editor.update(cx, |_, cx| {
14186 project.update(cx, |project, cx| {
14187 let language_server_name = project
14188 .language_server_statuses(cx)
14189 .find(|(id, _)| server_id == *id)
14190 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14191 language_server_name.map(|language_server_name| {
14192 project.open_local_buffer_via_lsp(
14193 lsp_location.uri.clone(),
14194 server_id,
14195 language_server_name,
14196 cx,
14197 )
14198 })
14199 })
14200 })?;
14201 let location = match location_task {
14202 Some(task) => Some({
14203 let target_buffer_handle = task.await.context("open local buffer")?;
14204 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14205 let target_start = target_buffer
14206 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14207 let target_end = target_buffer
14208 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14209 target_buffer.anchor_after(target_start)
14210 ..target_buffer.anchor_before(target_end)
14211 })?;
14212 Location {
14213 buffer: target_buffer_handle,
14214 range,
14215 }
14216 }),
14217 None => None,
14218 };
14219 Ok(location)
14220 })
14221 }
14222
14223 pub fn find_all_references(
14224 &mut self,
14225 _: &FindAllReferences,
14226 window: &mut Window,
14227 cx: &mut Context<Self>,
14228 ) -> Option<Task<Result<Navigated>>> {
14229 let selection = self.selections.newest::<usize>(cx);
14230 let multi_buffer = self.buffer.read(cx);
14231 let head = selection.head();
14232
14233 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14234 let head_anchor = multi_buffer_snapshot.anchor_at(
14235 head,
14236 if head < selection.tail() {
14237 Bias::Right
14238 } else {
14239 Bias::Left
14240 },
14241 );
14242
14243 match self
14244 .find_all_references_task_sources
14245 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14246 {
14247 Ok(_) => {
14248 log::info!(
14249 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14250 );
14251 return None;
14252 }
14253 Err(i) => {
14254 self.find_all_references_task_sources.insert(i, head_anchor);
14255 }
14256 }
14257
14258 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14259 let workspace = self.workspace()?;
14260 let project = workspace.read(cx).project().clone();
14261 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14262 Some(cx.spawn_in(window, async move |editor, cx| {
14263 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14264 if let Ok(i) = editor
14265 .find_all_references_task_sources
14266 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14267 {
14268 editor.find_all_references_task_sources.remove(i);
14269 }
14270 });
14271
14272 let locations = references.await?;
14273 if locations.is_empty() {
14274 return anyhow::Ok(Navigated::No);
14275 }
14276
14277 workspace.update_in(cx, |workspace, window, cx| {
14278 let title = locations
14279 .first()
14280 .as_ref()
14281 .map(|location| {
14282 let buffer = location.buffer.read(cx);
14283 format!(
14284 "References to `{}`",
14285 buffer
14286 .text_for_range(location.range.clone())
14287 .collect::<String>()
14288 )
14289 })
14290 .unwrap();
14291 Self::open_locations_in_multibuffer(
14292 workspace,
14293 locations,
14294 title,
14295 false,
14296 MultibufferSelectionMode::First,
14297 window,
14298 cx,
14299 );
14300 Navigated::Yes
14301 })
14302 }))
14303 }
14304
14305 /// Opens a multibuffer with the given project locations in it
14306 pub fn open_locations_in_multibuffer(
14307 workspace: &mut Workspace,
14308 mut locations: Vec<Location>,
14309 title: String,
14310 split: bool,
14311 multibuffer_selection_mode: MultibufferSelectionMode,
14312 window: &mut Window,
14313 cx: &mut Context<Workspace>,
14314 ) {
14315 // If there are multiple definitions, open them in a multibuffer
14316 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14317 let mut locations = locations.into_iter().peekable();
14318 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14319 let capability = workspace.project().read(cx).capability();
14320
14321 let excerpt_buffer = cx.new(|cx| {
14322 let mut multibuffer = MultiBuffer::new(capability);
14323 while let Some(location) = locations.next() {
14324 let buffer = location.buffer.read(cx);
14325 let mut ranges_for_buffer = Vec::new();
14326 let range = location.range.to_point(buffer);
14327 ranges_for_buffer.push(range.clone());
14328
14329 while let Some(next_location) = locations.peek() {
14330 if next_location.buffer == location.buffer {
14331 ranges_for_buffer.push(next_location.range.to_point(buffer));
14332 locations.next();
14333 } else {
14334 break;
14335 }
14336 }
14337
14338 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14339 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14340 PathKey::for_buffer(&location.buffer, cx),
14341 location.buffer.clone(),
14342 ranges_for_buffer,
14343 DEFAULT_MULTIBUFFER_CONTEXT,
14344 cx,
14345 );
14346 ranges.extend(new_ranges)
14347 }
14348
14349 multibuffer.with_title(title)
14350 });
14351
14352 let editor = cx.new(|cx| {
14353 Editor::for_multibuffer(
14354 excerpt_buffer,
14355 Some(workspace.project().clone()),
14356 window,
14357 cx,
14358 )
14359 });
14360 editor.update(cx, |editor, cx| {
14361 match multibuffer_selection_mode {
14362 MultibufferSelectionMode::First => {
14363 if let Some(first_range) = ranges.first() {
14364 editor.change_selections(None, window, cx, |selections| {
14365 selections.clear_disjoint();
14366 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14367 });
14368 }
14369 editor.highlight_background::<Self>(
14370 &ranges,
14371 |theme| theme.editor_highlighted_line_background,
14372 cx,
14373 );
14374 }
14375 MultibufferSelectionMode::All => {
14376 editor.change_selections(None, window, cx, |selections| {
14377 selections.clear_disjoint();
14378 selections.select_anchor_ranges(ranges);
14379 });
14380 }
14381 }
14382 editor.register_buffers_with_language_servers(cx);
14383 });
14384
14385 let item = Box::new(editor);
14386 let item_id = item.item_id();
14387
14388 if split {
14389 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14390 } else {
14391 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14392 let (preview_item_id, preview_item_idx) =
14393 workspace.active_pane().update(cx, |pane, _| {
14394 (pane.preview_item_id(), pane.preview_item_idx())
14395 });
14396
14397 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14398
14399 if let Some(preview_item_id) = preview_item_id {
14400 workspace.active_pane().update(cx, |pane, cx| {
14401 pane.remove_item(preview_item_id, false, false, window, cx);
14402 });
14403 }
14404 } else {
14405 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14406 }
14407 }
14408 workspace.active_pane().update(cx, |pane, cx| {
14409 pane.set_preview_item_id(Some(item_id), cx);
14410 });
14411 }
14412
14413 pub fn rename(
14414 &mut self,
14415 _: &Rename,
14416 window: &mut Window,
14417 cx: &mut Context<Self>,
14418 ) -> Option<Task<Result<()>>> {
14419 use language::ToOffset as _;
14420
14421 let provider = self.semantics_provider.clone()?;
14422 let selection = self.selections.newest_anchor().clone();
14423 let (cursor_buffer, cursor_buffer_position) = self
14424 .buffer
14425 .read(cx)
14426 .text_anchor_for_position(selection.head(), cx)?;
14427 let (tail_buffer, cursor_buffer_position_end) = self
14428 .buffer
14429 .read(cx)
14430 .text_anchor_for_position(selection.tail(), cx)?;
14431 if tail_buffer != cursor_buffer {
14432 return None;
14433 }
14434
14435 let snapshot = cursor_buffer.read(cx).snapshot();
14436 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14437 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14438 let prepare_rename = provider
14439 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14440 .unwrap_or_else(|| Task::ready(Ok(None)));
14441 drop(snapshot);
14442
14443 Some(cx.spawn_in(window, async move |this, cx| {
14444 let rename_range = if let Some(range) = prepare_rename.await? {
14445 Some(range)
14446 } else {
14447 this.update(cx, |this, cx| {
14448 let buffer = this.buffer.read(cx).snapshot(cx);
14449 let mut buffer_highlights = this
14450 .document_highlights_for_position(selection.head(), &buffer)
14451 .filter(|highlight| {
14452 highlight.start.excerpt_id == selection.head().excerpt_id
14453 && highlight.end.excerpt_id == selection.head().excerpt_id
14454 });
14455 buffer_highlights
14456 .next()
14457 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14458 })?
14459 };
14460 if let Some(rename_range) = rename_range {
14461 this.update_in(cx, |this, window, cx| {
14462 let snapshot = cursor_buffer.read(cx).snapshot();
14463 let rename_buffer_range = rename_range.to_offset(&snapshot);
14464 let cursor_offset_in_rename_range =
14465 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14466 let cursor_offset_in_rename_range_end =
14467 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14468
14469 this.take_rename(false, window, cx);
14470 let buffer = this.buffer.read(cx).read(cx);
14471 let cursor_offset = selection.head().to_offset(&buffer);
14472 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14473 let rename_end = rename_start + rename_buffer_range.len();
14474 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14475 let mut old_highlight_id = None;
14476 let old_name: Arc<str> = buffer
14477 .chunks(rename_start..rename_end, true)
14478 .map(|chunk| {
14479 if old_highlight_id.is_none() {
14480 old_highlight_id = chunk.syntax_highlight_id;
14481 }
14482 chunk.text
14483 })
14484 .collect::<String>()
14485 .into();
14486
14487 drop(buffer);
14488
14489 // Position the selection in the rename editor so that it matches the current selection.
14490 this.show_local_selections = false;
14491 let rename_editor = cx.new(|cx| {
14492 let mut editor = Editor::single_line(window, cx);
14493 editor.buffer.update(cx, |buffer, cx| {
14494 buffer.edit([(0..0, old_name.clone())], None, cx)
14495 });
14496 let rename_selection_range = match cursor_offset_in_rename_range
14497 .cmp(&cursor_offset_in_rename_range_end)
14498 {
14499 Ordering::Equal => {
14500 editor.select_all(&SelectAll, window, cx);
14501 return editor;
14502 }
14503 Ordering::Less => {
14504 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14505 }
14506 Ordering::Greater => {
14507 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14508 }
14509 };
14510 if rename_selection_range.end > old_name.len() {
14511 editor.select_all(&SelectAll, window, cx);
14512 } else {
14513 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14514 s.select_ranges([rename_selection_range]);
14515 });
14516 }
14517 editor
14518 });
14519 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14520 if e == &EditorEvent::Focused {
14521 cx.emit(EditorEvent::FocusedIn)
14522 }
14523 })
14524 .detach();
14525
14526 let write_highlights =
14527 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14528 let read_highlights =
14529 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14530 let ranges = write_highlights
14531 .iter()
14532 .flat_map(|(_, ranges)| ranges.iter())
14533 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14534 .cloned()
14535 .collect();
14536
14537 this.highlight_text::<Rename>(
14538 ranges,
14539 HighlightStyle {
14540 fade_out: Some(0.6),
14541 ..Default::default()
14542 },
14543 cx,
14544 );
14545 let rename_focus_handle = rename_editor.focus_handle(cx);
14546 window.focus(&rename_focus_handle);
14547 let block_id = this.insert_blocks(
14548 [BlockProperties {
14549 style: BlockStyle::Flex,
14550 placement: BlockPlacement::Below(range.start),
14551 height: Some(1),
14552 render: Arc::new({
14553 let rename_editor = rename_editor.clone();
14554 move |cx: &mut BlockContext| {
14555 let mut text_style = cx.editor_style.text.clone();
14556 if let Some(highlight_style) = old_highlight_id
14557 .and_then(|h| h.style(&cx.editor_style.syntax))
14558 {
14559 text_style = text_style.highlight(highlight_style);
14560 }
14561 div()
14562 .block_mouse_down()
14563 .pl(cx.anchor_x)
14564 .child(EditorElement::new(
14565 &rename_editor,
14566 EditorStyle {
14567 background: cx.theme().system().transparent,
14568 local_player: cx.editor_style.local_player,
14569 text: text_style,
14570 scrollbar_width: cx.editor_style.scrollbar_width,
14571 syntax: cx.editor_style.syntax.clone(),
14572 status: cx.editor_style.status.clone(),
14573 inlay_hints_style: HighlightStyle {
14574 font_weight: Some(FontWeight::BOLD),
14575 ..make_inlay_hints_style(cx.app)
14576 },
14577 inline_completion_styles: make_suggestion_styles(
14578 cx.app,
14579 ),
14580 ..EditorStyle::default()
14581 },
14582 ))
14583 .into_any_element()
14584 }
14585 }),
14586 priority: 0,
14587 }],
14588 Some(Autoscroll::fit()),
14589 cx,
14590 )[0];
14591 this.pending_rename = Some(RenameState {
14592 range,
14593 old_name,
14594 editor: rename_editor,
14595 block_id,
14596 });
14597 })?;
14598 }
14599
14600 Ok(())
14601 }))
14602 }
14603
14604 pub fn confirm_rename(
14605 &mut self,
14606 _: &ConfirmRename,
14607 window: &mut Window,
14608 cx: &mut Context<Self>,
14609 ) -> Option<Task<Result<()>>> {
14610 let rename = self.take_rename(false, window, cx)?;
14611 let workspace = self.workspace()?.downgrade();
14612 let (buffer, start) = self
14613 .buffer
14614 .read(cx)
14615 .text_anchor_for_position(rename.range.start, cx)?;
14616 let (end_buffer, _) = self
14617 .buffer
14618 .read(cx)
14619 .text_anchor_for_position(rename.range.end, cx)?;
14620 if buffer != end_buffer {
14621 return None;
14622 }
14623
14624 let old_name = rename.old_name;
14625 let new_name = rename.editor.read(cx).text(cx);
14626
14627 let rename = self.semantics_provider.as_ref()?.perform_rename(
14628 &buffer,
14629 start,
14630 new_name.clone(),
14631 cx,
14632 )?;
14633
14634 Some(cx.spawn_in(window, async move |editor, cx| {
14635 let project_transaction = rename.await?;
14636 Self::open_project_transaction(
14637 &editor,
14638 workspace,
14639 project_transaction,
14640 format!("Rename: {} → {}", old_name, new_name),
14641 cx,
14642 )
14643 .await?;
14644
14645 editor.update(cx, |editor, cx| {
14646 editor.refresh_document_highlights(cx);
14647 })?;
14648 Ok(())
14649 }))
14650 }
14651
14652 fn take_rename(
14653 &mut self,
14654 moving_cursor: bool,
14655 window: &mut Window,
14656 cx: &mut Context<Self>,
14657 ) -> Option<RenameState> {
14658 let rename = self.pending_rename.take()?;
14659 if rename.editor.focus_handle(cx).is_focused(window) {
14660 window.focus(&self.focus_handle);
14661 }
14662
14663 self.remove_blocks(
14664 [rename.block_id].into_iter().collect(),
14665 Some(Autoscroll::fit()),
14666 cx,
14667 );
14668 self.clear_highlights::<Rename>(cx);
14669 self.show_local_selections = true;
14670
14671 if moving_cursor {
14672 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14673 editor.selections.newest::<usize>(cx).head()
14674 });
14675
14676 // Update the selection to match the position of the selection inside
14677 // the rename editor.
14678 let snapshot = self.buffer.read(cx).read(cx);
14679 let rename_range = rename.range.to_offset(&snapshot);
14680 let cursor_in_editor = snapshot
14681 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14682 .min(rename_range.end);
14683 drop(snapshot);
14684
14685 self.change_selections(None, window, cx, |s| {
14686 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14687 });
14688 } else {
14689 self.refresh_document_highlights(cx);
14690 }
14691
14692 Some(rename)
14693 }
14694
14695 pub fn pending_rename(&self) -> Option<&RenameState> {
14696 self.pending_rename.as_ref()
14697 }
14698
14699 fn format(
14700 &mut self,
14701 _: &Format,
14702 window: &mut Window,
14703 cx: &mut Context<Self>,
14704 ) -> Option<Task<Result<()>>> {
14705 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14706
14707 let project = match &self.project {
14708 Some(project) => project.clone(),
14709 None => return None,
14710 };
14711
14712 Some(self.perform_format(
14713 project,
14714 FormatTrigger::Manual,
14715 FormatTarget::Buffers,
14716 window,
14717 cx,
14718 ))
14719 }
14720
14721 fn format_selections(
14722 &mut self,
14723 _: &FormatSelections,
14724 window: &mut Window,
14725 cx: &mut Context<Self>,
14726 ) -> Option<Task<Result<()>>> {
14727 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14728
14729 let project = match &self.project {
14730 Some(project) => project.clone(),
14731 None => return None,
14732 };
14733
14734 let ranges = self
14735 .selections
14736 .all_adjusted(cx)
14737 .into_iter()
14738 .map(|selection| selection.range())
14739 .collect_vec();
14740
14741 Some(self.perform_format(
14742 project,
14743 FormatTrigger::Manual,
14744 FormatTarget::Ranges(ranges),
14745 window,
14746 cx,
14747 ))
14748 }
14749
14750 fn perform_format(
14751 &mut self,
14752 project: Entity<Project>,
14753 trigger: FormatTrigger,
14754 target: FormatTarget,
14755 window: &mut Window,
14756 cx: &mut Context<Self>,
14757 ) -> Task<Result<()>> {
14758 let buffer = self.buffer.clone();
14759 let (buffers, target) = match target {
14760 FormatTarget::Buffers => {
14761 let mut buffers = buffer.read(cx).all_buffers();
14762 if trigger == FormatTrigger::Save {
14763 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14764 }
14765 (buffers, LspFormatTarget::Buffers)
14766 }
14767 FormatTarget::Ranges(selection_ranges) => {
14768 let multi_buffer = buffer.read(cx);
14769 let snapshot = multi_buffer.read(cx);
14770 let mut buffers = HashSet::default();
14771 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14772 BTreeMap::new();
14773 for selection_range in selection_ranges {
14774 for (buffer, buffer_range, _) in
14775 snapshot.range_to_buffer_ranges(selection_range)
14776 {
14777 let buffer_id = buffer.remote_id();
14778 let start = buffer.anchor_before(buffer_range.start);
14779 let end = buffer.anchor_after(buffer_range.end);
14780 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14781 buffer_id_to_ranges
14782 .entry(buffer_id)
14783 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14784 .or_insert_with(|| vec![start..end]);
14785 }
14786 }
14787 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14788 }
14789 };
14790
14791 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14792 let selections_prev = transaction_id_prev
14793 .and_then(|transaction_id_prev| {
14794 // default to selections as they were after the last edit, if we have them,
14795 // instead of how they are now.
14796 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14797 // will take you back to where you made the last edit, instead of staying where you scrolled
14798 self.selection_history
14799 .transaction(transaction_id_prev)
14800 .map(|t| t.0.clone())
14801 })
14802 .unwrap_or_else(|| {
14803 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14804 self.selections.disjoint_anchors()
14805 });
14806
14807 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14808 let format = project.update(cx, |project, cx| {
14809 project.format(buffers, target, true, trigger, cx)
14810 });
14811
14812 cx.spawn_in(window, async move |editor, cx| {
14813 let transaction = futures::select_biased! {
14814 transaction = format.log_err().fuse() => transaction,
14815 () = timeout => {
14816 log::warn!("timed out waiting for formatting");
14817 None
14818 }
14819 };
14820
14821 buffer
14822 .update(cx, |buffer, cx| {
14823 if let Some(transaction) = transaction {
14824 if !buffer.is_singleton() {
14825 buffer.push_transaction(&transaction.0, cx);
14826 }
14827 }
14828 cx.notify();
14829 })
14830 .ok();
14831
14832 if let Some(transaction_id_now) =
14833 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14834 {
14835 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14836 if has_new_transaction {
14837 _ = editor.update(cx, |editor, _| {
14838 editor
14839 .selection_history
14840 .insert_transaction(transaction_id_now, selections_prev);
14841 });
14842 }
14843 }
14844
14845 Ok(())
14846 })
14847 }
14848
14849 fn organize_imports(
14850 &mut self,
14851 _: &OrganizeImports,
14852 window: &mut Window,
14853 cx: &mut Context<Self>,
14854 ) -> Option<Task<Result<()>>> {
14855 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14856 let project = match &self.project {
14857 Some(project) => project.clone(),
14858 None => return None,
14859 };
14860 Some(self.perform_code_action_kind(
14861 project,
14862 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14863 window,
14864 cx,
14865 ))
14866 }
14867
14868 fn perform_code_action_kind(
14869 &mut self,
14870 project: Entity<Project>,
14871 kind: CodeActionKind,
14872 window: &mut Window,
14873 cx: &mut Context<Self>,
14874 ) -> Task<Result<()>> {
14875 let buffer = self.buffer.clone();
14876 let buffers = buffer.read(cx).all_buffers();
14877 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14878 let apply_action = project.update(cx, |project, cx| {
14879 project.apply_code_action_kind(buffers, kind, true, cx)
14880 });
14881 cx.spawn_in(window, async move |_, cx| {
14882 let transaction = futures::select_biased! {
14883 () = timeout => {
14884 log::warn!("timed out waiting for executing code action");
14885 None
14886 }
14887 transaction = apply_action.log_err().fuse() => transaction,
14888 };
14889 buffer
14890 .update(cx, |buffer, cx| {
14891 // check if we need this
14892 if let Some(transaction) = transaction {
14893 if !buffer.is_singleton() {
14894 buffer.push_transaction(&transaction.0, cx);
14895 }
14896 }
14897 cx.notify();
14898 })
14899 .ok();
14900 Ok(())
14901 })
14902 }
14903
14904 fn restart_language_server(
14905 &mut self,
14906 _: &RestartLanguageServer,
14907 _: &mut Window,
14908 cx: &mut Context<Self>,
14909 ) {
14910 if let Some(project) = self.project.clone() {
14911 self.buffer.update(cx, |multi_buffer, cx| {
14912 project.update(cx, |project, cx| {
14913 project.restart_language_servers_for_buffers(
14914 multi_buffer.all_buffers().into_iter().collect(),
14915 cx,
14916 );
14917 });
14918 })
14919 }
14920 }
14921
14922 fn stop_language_server(
14923 &mut self,
14924 _: &StopLanguageServer,
14925 _: &mut Window,
14926 cx: &mut Context<Self>,
14927 ) {
14928 if let Some(project) = self.project.clone() {
14929 self.buffer.update(cx, |multi_buffer, cx| {
14930 project.update(cx, |project, cx| {
14931 project.stop_language_servers_for_buffers(
14932 multi_buffer.all_buffers().into_iter().collect(),
14933 cx,
14934 );
14935 cx.emit(project::Event::RefreshInlayHints);
14936 });
14937 });
14938 }
14939 }
14940
14941 fn cancel_language_server_work(
14942 workspace: &mut Workspace,
14943 _: &actions::CancelLanguageServerWork,
14944 _: &mut Window,
14945 cx: &mut Context<Workspace>,
14946 ) {
14947 let project = workspace.project();
14948 let buffers = workspace
14949 .active_item(cx)
14950 .and_then(|item| item.act_as::<Editor>(cx))
14951 .map_or(HashSet::default(), |editor| {
14952 editor.read(cx).buffer.read(cx).all_buffers()
14953 });
14954 project.update(cx, |project, cx| {
14955 project.cancel_language_server_work_for_buffers(buffers, cx);
14956 });
14957 }
14958
14959 fn show_character_palette(
14960 &mut self,
14961 _: &ShowCharacterPalette,
14962 window: &mut Window,
14963 _: &mut Context<Self>,
14964 ) {
14965 window.show_character_palette();
14966 }
14967
14968 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14969 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14970 let buffer = self.buffer.read(cx).snapshot(cx);
14971 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14972 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14973 let is_valid = buffer
14974 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14975 .any(|entry| {
14976 entry.diagnostic.is_primary
14977 && !entry.range.is_empty()
14978 && entry.range.start == primary_range_start
14979 && entry.diagnostic.message == active_diagnostics.active_message
14980 });
14981
14982 if !is_valid {
14983 self.dismiss_diagnostics(cx);
14984 }
14985 }
14986 }
14987
14988 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14989 match &self.active_diagnostics {
14990 ActiveDiagnostic::Group(group) => Some(group),
14991 _ => None,
14992 }
14993 }
14994
14995 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14996 self.dismiss_diagnostics(cx);
14997 self.active_diagnostics = ActiveDiagnostic::All;
14998 }
14999
15000 fn activate_diagnostics(
15001 &mut self,
15002 buffer_id: BufferId,
15003 diagnostic: DiagnosticEntry<usize>,
15004 window: &mut Window,
15005 cx: &mut Context<Self>,
15006 ) {
15007 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15008 return;
15009 }
15010 self.dismiss_diagnostics(cx);
15011 let snapshot = self.snapshot(window, cx);
15012 let buffer = self.buffer.read(cx).snapshot(cx);
15013 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15014 return;
15015 };
15016
15017 let diagnostic_group = buffer
15018 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15019 .collect::<Vec<_>>();
15020
15021 let blocks =
15022 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15023
15024 let blocks = self.display_map.update(cx, |display_map, cx| {
15025 display_map.insert_blocks(blocks, cx).into_iter().collect()
15026 });
15027 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15028 active_range: buffer.anchor_before(diagnostic.range.start)
15029 ..buffer.anchor_after(diagnostic.range.end),
15030 active_message: diagnostic.diagnostic.message.clone(),
15031 group_id: diagnostic.diagnostic.group_id,
15032 blocks,
15033 });
15034 cx.notify();
15035 }
15036
15037 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15038 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15039 return;
15040 };
15041
15042 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15043 if let ActiveDiagnostic::Group(group) = prev {
15044 self.display_map.update(cx, |display_map, cx| {
15045 display_map.remove_blocks(group.blocks, cx);
15046 });
15047 cx.notify();
15048 }
15049 }
15050
15051 /// Disable inline diagnostics rendering for this editor.
15052 pub fn disable_inline_diagnostics(&mut self) {
15053 self.inline_diagnostics_enabled = false;
15054 self.inline_diagnostics_update = Task::ready(());
15055 self.inline_diagnostics.clear();
15056 }
15057
15058 pub fn inline_diagnostics_enabled(&self) -> bool {
15059 self.inline_diagnostics_enabled
15060 }
15061
15062 pub fn show_inline_diagnostics(&self) -> bool {
15063 self.show_inline_diagnostics
15064 }
15065
15066 pub fn toggle_inline_diagnostics(
15067 &mut self,
15068 _: &ToggleInlineDiagnostics,
15069 window: &mut Window,
15070 cx: &mut Context<Editor>,
15071 ) {
15072 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15073 self.refresh_inline_diagnostics(false, window, cx);
15074 }
15075
15076 fn refresh_inline_diagnostics(
15077 &mut self,
15078 debounce: bool,
15079 window: &mut Window,
15080 cx: &mut Context<Self>,
15081 ) {
15082 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15083 self.inline_diagnostics_update = Task::ready(());
15084 self.inline_diagnostics.clear();
15085 return;
15086 }
15087
15088 let debounce_ms = ProjectSettings::get_global(cx)
15089 .diagnostics
15090 .inline
15091 .update_debounce_ms;
15092 let debounce = if debounce && debounce_ms > 0 {
15093 Some(Duration::from_millis(debounce_ms))
15094 } else {
15095 None
15096 };
15097 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15098 let editor = editor.upgrade().unwrap();
15099
15100 if let Some(debounce) = debounce {
15101 cx.background_executor().timer(debounce).await;
15102 }
15103 let Some(snapshot) = editor
15104 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15105 .ok()
15106 else {
15107 return;
15108 };
15109
15110 let new_inline_diagnostics = cx
15111 .background_spawn(async move {
15112 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15113 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15114 let message = diagnostic_entry
15115 .diagnostic
15116 .message
15117 .split_once('\n')
15118 .map(|(line, _)| line)
15119 .map(SharedString::new)
15120 .unwrap_or_else(|| {
15121 SharedString::from(diagnostic_entry.diagnostic.message)
15122 });
15123 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15124 let (Ok(i) | Err(i)) = inline_diagnostics
15125 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15126 inline_diagnostics.insert(
15127 i,
15128 (
15129 start_anchor,
15130 InlineDiagnostic {
15131 message,
15132 group_id: diagnostic_entry.diagnostic.group_id,
15133 start: diagnostic_entry.range.start.to_point(&snapshot),
15134 is_primary: diagnostic_entry.diagnostic.is_primary,
15135 severity: diagnostic_entry.diagnostic.severity,
15136 },
15137 ),
15138 );
15139 }
15140 inline_diagnostics
15141 })
15142 .await;
15143
15144 editor
15145 .update(cx, |editor, cx| {
15146 editor.inline_diagnostics = new_inline_diagnostics;
15147 cx.notify();
15148 })
15149 .ok();
15150 });
15151 }
15152
15153 pub fn set_selections_from_remote(
15154 &mut self,
15155 selections: Vec<Selection<Anchor>>,
15156 pending_selection: Option<Selection<Anchor>>,
15157 window: &mut Window,
15158 cx: &mut Context<Self>,
15159 ) {
15160 let old_cursor_position = self.selections.newest_anchor().head();
15161 self.selections.change_with(cx, |s| {
15162 s.select_anchors(selections);
15163 if let Some(pending_selection) = pending_selection {
15164 s.set_pending(pending_selection, SelectMode::Character);
15165 } else {
15166 s.clear_pending();
15167 }
15168 });
15169 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15170 }
15171
15172 fn push_to_selection_history(&mut self) {
15173 self.selection_history.push(SelectionHistoryEntry {
15174 selections: self.selections.disjoint_anchors(),
15175 select_next_state: self.select_next_state.clone(),
15176 select_prev_state: self.select_prev_state.clone(),
15177 add_selections_state: self.add_selections_state.clone(),
15178 });
15179 }
15180
15181 pub fn transact(
15182 &mut self,
15183 window: &mut Window,
15184 cx: &mut Context<Self>,
15185 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15186 ) -> Option<TransactionId> {
15187 self.start_transaction_at(Instant::now(), window, cx);
15188 update(self, window, cx);
15189 self.end_transaction_at(Instant::now(), cx)
15190 }
15191
15192 pub fn start_transaction_at(
15193 &mut self,
15194 now: Instant,
15195 window: &mut Window,
15196 cx: &mut Context<Self>,
15197 ) {
15198 self.end_selection(window, cx);
15199 if let Some(tx_id) = self
15200 .buffer
15201 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15202 {
15203 self.selection_history
15204 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15205 cx.emit(EditorEvent::TransactionBegun {
15206 transaction_id: tx_id,
15207 })
15208 }
15209 }
15210
15211 pub fn end_transaction_at(
15212 &mut self,
15213 now: Instant,
15214 cx: &mut Context<Self>,
15215 ) -> Option<TransactionId> {
15216 if let Some(transaction_id) = self
15217 .buffer
15218 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15219 {
15220 if let Some((_, end_selections)) =
15221 self.selection_history.transaction_mut(transaction_id)
15222 {
15223 *end_selections = Some(self.selections.disjoint_anchors());
15224 } else {
15225 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15226 }
15227
15228 cx.emit(EditorEvent::Edited { transaction_id });
15229 Some(transaction_id)
15230 } else {
15231 None
15232 }
15233 }
15234
15235 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15236 if self.selection_mark_mode {
15237 self.change_selections(None, window, cx, |s| {
15238 s.move_with(|_, sel| {
15239 sel.collapse_to(sel.head(), SelectionGoal::None);
15240 });
15241 })
15242 }
15243 self.selection_mark_mode = true;
15244 cx.notify();
15245 }
15246
15247 pub fn swap_selection_ends(
15248 &mut self,
15249 _: &actions::SwapSelectionEnds,
15250 window: &mut Window,
15251 cx: &mut Context<Self>,
15252 ) {
15253 self.change_selections(None, window, cx, |s| {
15254 s.move_with(|_, sel| {
15255 if sel.start != sel.end {
15256 sel.reversed = !sel.reversed
15257 }
15258 });
15259 });
15260 self.request_autoscroll(Autoscroll::newest(), cx);
15261 cx.notify();
15262 }
15263
15264 pub fn toggle_fold(
15265 &mut self,
15266 _: &actions::ToggleFold,
15267 window: &mut Window,
15268 cx: &mut Context<Self>,
15269 ) {
15270 if self.is_singleton(cx) {
15271 let selection = self.selections.newest::<Point>(cx);
15272
15273 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15274 let range = if selection.is_empty() {
15275 let point = selection.head().to_display_point(&display_map);
15276 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15277 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15278 .to_point(&display_map);
15279 start..end
15280 } else {
15281 selection.range()
15282 };
15283 if display_map.folds_in_range(range).next().is_some() {
15284 self.unfold_lines(&Default::default(), window, cx)
15285 } else {
15286 self.fold(&Default::default(), window, cx)
15287 }
15288 } else {
15289 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15290 let buffer_ids: HashSet<_> = self
15291 .selections
15292 .disjoint_anchor_ranges()
15293 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15294 .collect();
15295
15296 let should_unfold = buffer_ids
15297 .iter()
15298 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15299
15300 for buffer_id in buffer_ids {
15301 if should_unfold {
15302 self.unfold_buffer(buffer_id, cx);
15303 } else {
15304 self.fold_buffer(buffer_id, cx);
15305 }
15306 }
15307 }
15308 }
15309
15310 pub fn toggle_fold_recursive(
15311 &mut self,
15312 _: &actions::ToggleFoldRecursive,
15313 window: &mut Window,
15314 cx: &mut Context<Self>,
15315 ) {
15316 let selection = self.selections.newest::<Point>(cx);
15317
15318 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15319 let range = if selection.is_empty() {
15320 let point = selection.head().to_display_point(&display_map);
15321 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15322 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15323 .to_point(&display_map);
15324 start..end
15325 } else {
15326 selection.range()
15327 };
15328 if display_map.folds_in_range(range).next().is_some() {
15329 self.unfold_recursive(&Default::default(), window, cx)
15330 } else {
15331 self.fold_recursive(&Default::default(), window, cx)
15332 }
15333 }
15334
15335 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15336 if self.is_singleton(cx) {
15337 let mut to_fold = Vec::new();
15338 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15339 let selections = self.selections.all_adjusted(cx);
15340
15341 for selection in selections {
15342 let range = selection.range().sorted();
15343 let buffer_start_row = range.start.row;
15344
15345 if range.start.row != range.end.row {
15346 let mut found = false;
15347 let mut row = range.start.row;
15348 while row <= range.end.row {
15349 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15350 {
15351 found = true;
15352 row = crease.range().end.row + 1;
15353 to_fold.push(crease);
15354 } else {
15355 row += 1
15356 }
15357 }
15358 if found {
15359 continue;
15360 }
15361 }
15362
15363 for row in (0..=range.start.row).rev() {
15364 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15365 if crease.range().end.row >= buffer_start_row {
15366 to_fold.push(crease);
15367 if row <= range.start.row {
15368 break;
15369 }
15370 }
15371 }
15372 }
15373 }
15374
15375 self.fold_creases(to_fold, true, window, cx);
15376 } else {
15377 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15378 let buffer_ids = self
15379 .selections
15380 .disjoint_anchor_ranges()
15381 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15382 .collect::<HashSet<_>>();
15383 for buffer_id in buffer_ids {
15384 self.fold_buffer(buffer_id, cx);
15385 }
15386 }
15387 }
15388
15389 fn fold_at_level(
15390 &mut self,
15391 fold_at: &FoldAtLevel,
15392 window: &mut Window,
15393 cx: &mut Context<Self>,
15394 ) {
15395 if !self.buffer.read(cx).is_singleton() {
15396 return;
15397 }
15398
15399 let fold_at_level = fold_at.0;
15400 let snapshot = self.buffer.read(cx).snapshot(cx);
15401 let mut to_fold = Vec::new();
15402 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15403
15404 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15405 while start_row < end_row {
15406 match self
15407 .snapshot(window, cx)
15408 .crease_for_buffer_row(MultiBufferRow(start_row))
15409 {
15410 Some(crease) => {
15411 let nested_start_row = crease.range().start.row + 1;
15412 let nested_end_row = crease.range().end.row;
15413
15414 if current_level < fold_at_level {
15415 stack.push((nested_start_row, nested_end_row, current_level + 1));
15416 } else if current_level == fold_at_level {
15417 to_fold.push(crease);
15418 }
15419
15420 start_row = nested_end_row + 1;
15421 }
15422 None => start_row += 1,
15423 }
15424 }
15425 }
15426
15427 self.fold_creases(to_fold, true, window, cx);
15428 }
15429
15430 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15431 if self.buffer.read(cx).is_singleton() {
15432 let mut fold_ranges = Vec::new();
15433 let snapshot = self.buffer.read(cx).snapshot(cx);
15434
15435 for row in 0..snapshot.max_row().0 {
15436 if let Some(foldable_range) = self
15437 .snapshot(window, cx)
15438 .crease_for_buffer_row(MultiBufferRow(row))
15439 {
15440 fold_ranges.push(foldable_range);
15441 }
15442 }
15443
15444 self.fold_creases(fold_ranges, true, window, cx);
15445 } else {
15446 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15447 editor
15448 .update_in(cx, |editor, _, cx| {
15449 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15450 editor.fold_buffer(buffer_id, cx);
15451 }
15452 })
15453 .ok();
15454 });
15455 }
15456 }
15457
15458 pub fn fold_function_bodies(
15459 &mut self,
15460 _: &actions::FoldFunctionBodies,
15461 window: &mut Window,
15462 cx: &mut Context<Self>,
15463 ) {
15464 let snapshot = self.buffer.read(cx).snapshot(cx);
15465
15466 let ranges = snapshot
15467 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15468 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15469 .collect::<Vec<_>>();
15470
15471 let creases = ranges
15472 .into_iter()
15473 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15474 .collect();
15475
15476 self.fold_creases(creases, true, window, cx);
15477 }
15478
15479 pub fn fold_recursive(
15480 &mut self,
15481 _: &actions::FoldRecursive,
15482 window: &mut Window,
15483 cx: &mut Context<Self>,
15484 ) {
15485 let mut to_fold = Vec::new();
15486 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15487 let selections = self.selections.all_adjusted(cx);
15488
15489 for selection in selections {
15490 let range = selection.range().sorted();
15491 let buffer_start_row = range.start.row;
15492
15493 if range.start.row != range.end.row {
15494 let mut found = false;
15495 for row in range.start.row..=range.end.row {
15496 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15497 found = true;
15498 to_fold.push(crease);
15499 }
15500 }
15501 if found {
15502 continue;
15503 }
15504 }
15505
15506 for row in (0..=range.start.row).rev() {
15507 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15508 if crease.range().end.row >= buffer_start_row {
15509 to_fold.push(crease);
15510 } else {
15511 break;
15512 }
15513 }
15514 }
15515 }
15516
15517 self.fold_creases(to_fold, true, window, cx);
15518 }
15519
15520 pub fn fold_at(
15521 &mut self,
15522 buffer_row: MultiBufferRow,
15523 window: &mut Window,
15524 cx: &mut Context<Self>,
15525 ) {
15526 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15527
15528 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15529 let autoscroll = self
15530 .selections
15531 .all::<Point>(cx)
15532 .iter()
15533 .any(|selection| crease.range().overlaps(&selection.range()));
15534
15535 self.fold_creases(vec![crease], autoscroll, window, cx);
15536 }
15537 }
15538
15539 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15540 if self.is_singleton(cx) {
15541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15542 let buffer = &display_map.buffer_snapshot;
15543 let selections = self.selections.all::<Point>(cx);
15544 let ranges = selections
15545 .iter()
15546 .map(|s| {
15547 let range = s.display_range(&display_map).sorted();
15548 let mut start = range.start.to_point(&display_map);
15549 let mut end = range.end.to_point(&display_map);
15550 start.column = 0;
15551 end.column = buffer.line_len(MultiBufferRow(end.row));
15552 start..end
15553 })
15554 .collect::<Vec<_>>();
15555
15556 self.unfold_ranges(&ranges, true, true, cx);
15557 } else {
15558 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15559 let buffer_ids = self
15560 .selections
15561 .disjoint_anchor_ranges()
15562 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15563 .collect::<HashSet<_>>();
15564 for buffer_id in buffer_ids {
15565 self.unfold_buffer(buffer_id, cx);
15566 }
15567 }
15568 }
15569
15570 pub fn unfold_recursive(
15571 &mut self,
15572 _: &UnfoldRecursive,
15573 _window: &mut Window,
15574 cx: &mut Context<Self>,
15575 ) {
15576 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15577 let selections = self.selections.all::<Point>(cx);
15578 let ranges = selections
15579 .iter()
15580 .map(|s| {
15581 let mut range = s.display_range(&display_map).sorted();
15582 *range.start.column_mut() = 0;
15583 *range.end.column_mut() = display_map.line_len(range.end.row());
15584 let start = range.start.to_point(&display_map);
15585 let end = range.end.to_point(&display_map);
15586 start..end
15587 })
15588 .collect::<Vec<_>>();
15589
15590 self.unfold_ranges(&ranges, true, true, cx);
15591 }
15592
15593 pub fn unfold_at(
15594 &mut self,
15595 buffer_row: MultiBufferRow,
15596 _window: &mut Window,
15597 cx: &mut Context<Self>,
15598 ) {
15599 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15600
15601 let intersection_range = Point::new(buffer_row.0, 0)
15602 ..Point::new(
15603 buffer_row.0,
15604 display_map.buffer_snapshot.line_len(buffer_row),
15605 );
15606
15607 let autoscroll = self
15608 .selections
15609 .all::<Point>(cx)
15610 .iter()
15611 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15612
15613 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15614 }
15615
15616 pub fn unfold_all(
15617 &mut self,
15618 _: &actions::UnfoldAll,
15619 _window: &mut Window,
15620 cx: &mut Context<Self>,
15621 ) {
15622 if self.buffer.read(cx).is_singleton() {
15623 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15624 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15625 } else {
15626 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15627 editor
15628 .update(cx, |editor, cx| {
15629 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15630 editor.unfold_buffer(buffer_id, cx);
15631 }
15632 })
15633 .ok();
15634 });
15635 }
15636 }
15637
15638 pub fn fold_selected_ranges(
15639 &mut self,
15640 _: &FoldSelectedRanges,
15641 window: &mut Window,
15642 cx: &mut Context<Self>,
15643 ) {
15644 let selections = self.selections.all_adjusted(cx);
15645 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15646 let ranges = selections
15647 .into_iter()
15648 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15649 .collect::<Vec<_>>();
15650 self.fold_creases(ranges, true, window, cx);
15651 }
15652
15653 pub fn fold_ranges<T: ToOffset + Clone>(
15654 &mut self,
15655 ranges: Vec<Range<T>>,
15656 auto_scroll: bool,
15657 window: &mut Window,
15658 cx: &mut Context<Self>,
15659 ) {
15660 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15661 let ranges = ranges
15662 .into_iter()
15663 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15664 .collect::<Vec<_>>();
15665 self.fold_creases(ranges, auto_scroll, window, cx);
15666 }
15667
15668 pub fn fold_creases<T: ToOffset + Clone>(
15669 &mut self,
15670 creases: Vec<Crease<T>>,
15671 auto_scroll: bool,
15672 _window: &mut Window,
15673 cx: &mut Context<Self>,
15674 ) {
15675 if creases.is_empty() {
15676 return;
15677 }
15678
15679 let mut buffers_affected = HashSet::default();
15680 let multi_buffer = self.buffer().read(cx);
15681 for crease in &creases {
15682 if let Some((_, buffer, _)) =
15683 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15684 {
15685 buffers_affected.insert(buffer.read(cx).remote_id());
15686 };
15687 }
15688
15689 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15690
15691 if auto_scroll {
15692 self.request_autoscroll(Autoscroll::fit(), cx);
15693 }
15694
15695 cx.notify();
15696
15697 self.scrollbar_marker_state.dirty = true;
15698 self.folds_did_change(cx);
15699 }
15700
15701 /// Removes any folds whose ranges intersect any of the given ranges.
15702 pub fn unfold_ranges<T: ToOffset + Clone>(
15703 &mut self,
15704 ranges: &[Range<T>],
15705 inclusive: bool,
15706 auto_scroll: bool,
15707 cx: &mut Context<Self>,
15708 ) {
15709 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15710 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15711 });
15712 self.folds_did_change(cx);
15713 }
15714
15715 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15716 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15717 return;
15718 }
15719 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15720 self.display_map.update(cx, |display_map, cx| {
15721 display_map.fold_buffers([buffer_id], cx)
15722 });
15723 cx.emit(EditorEvent::BufferFoldToggled {
15724 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15725 folded: true,
15726 });
15727 cx.notify();
15728 }
15729
15730 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15731 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15732 return;
15733 }
15734 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15735 self.display_map.update(cx, |display_map, cx| {
15736 display_map.unfold_buffers([buffer_id], cx);
15737 });
15738 cx.emit(EditorEvent::BufferFoldToggled {
15739 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15740 folded: false,
15741 });
15742 cx.notify();
15743 }
15744
15745 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15746 self.display_map.read(cx).is_buffer_folded(buffer)
15747 }
15748
15749 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15750 self.display_map.read(cx).folded_buffers()
15751 }
15752
15753 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15754 self.display_map.update(cx, |display_map, cx| {
15755 display_map.disable_header_for_buffer(buffer_id, cx);
15756 });
15757 cx.notify();
15758 }
15759
15760 /// Removes any folds with the given ranges.
15761 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15762 &mut self,
15763 ranges: &[Range<T>],
15764 type_id: TypeId,
15765 auto_scroll: bool,
15766 cx: &mut Context<Self>,
15767 ) {
15768 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15769 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15770 });
15771 self.folds_did_change(cx);
15772 }
15773
15774 fn remove_folds_with<T: ToOffset + Clone>(
15775 &mut self,
15776 ranges: &[Range<T>],
15777 auto_scroll: bool,
15778 cx: &mut Context<Self>,
15779 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15780 ) {
15781 if ranges.is_empty() {
15782 return;
15783 }
15784
15785 let mut buffers_affected = HashSet::default();
15786 let multi_buffer = self.buffer().read(cx);
15787 for range in ranges {
15788 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15789 buffers_affected.insert(buffer.read(cx).remote_id());
15790 };
15791 }
15792
15793 self.display_map.update(cx, update);
15794
15795 if auto_scroll {
15796 self.request_autoscroll(Autoscroll::fit(), cx);
15797 }
15798
15799 cx.notify();
15800 self.scrollbar_marker_state.dirty = true;
15801 self.active_indent_guides_state.dirty = true;
15802 }
15803
15804 pub fn update_fold_widths(
15805 &mut self,
15806 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15807 cx: &mut Context<Self>,
15808 ) -> bool {
15809 self.display_map
15810 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15811 }
15812
15813 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15814 self.display_map.read(cx).fold_placeholder.clone()
15815 }
15816
15817 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15818 self.buffer.update(cx, |buffer, cx| {
15819 buffer.set_all_diff_hunks_expanded(cx);
15820 });
15821 }
15822
15823 pub fn expand_all_diff_hunks(
15824 &mut self,
15825 _: &ExpandAllDiffHunks,
15826 _window: &mut Window,
15827 cx: &mut Context<Self>,
15828 ) {
15829 self.buffer.update(cx, |buffer, cx| {
15830 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15831 });
15832 }
15833
15834 pub fn toggle_selected_diff_hunks(
15835 &mut self,
15836 _: &ToggleSelectedDiffHunks,
15837 _window: &mut Window,
15838 cx: &mut Context<Self>,
15839 ) {
15840 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15841 self.toggle_diff_hunks_in_ranges(ranges, cx);
15842 }
15843
15844 pub fn diff_hunks_in_ranges<'a>(
15845 &'a self,
15846 ranges: &'a [Range<Anchor>],
15847 buffer: &'a MultiBufferSnapshot,
15848 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15849 ranges.iter().flat_map(move |range| {
15850 let end_excerpt_id = range.end.excerpt_id;
15851 let range = range.to_point(buffer);
15852 let mut peek_end = range.end;
15853 if range.end.row < buffer.max_row().0 {
15854 peek_end = Point::new(range.end.row + 1, 0);
15855 }
15856 buffer
15857 .diff_hunks_in_range(range.start..peek_end)
15858 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15859 })
15860 }
15861
15862 pub fn has_stageable_diff_hunks_in_ranges(
15863 &self,
15864 ranges: &[Range<Anchor>],
15865 snapshot: &MultiBufferSnapshot,
15866 ) -> bool {
15867 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15868 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15869 }
15870
15871 pub fn toggle_staged_selected_diff_hunks(
15872 &mut self,
15873 _: &::git::ToggleStaged,
15874 _: &mut Window,
15875 cx: &mut Context<Self>,
15876 ) {
15877 let snapshot = self.buffer.read(cx).snapshot(cx);
15878 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15879 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15880 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15881 }
15882
15883 pub fn set_render_diff_hunk_controls(
15884 &mut self,
15885 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15886 cx: &mut Context<Self>,
15887 ) {
15888 self.render_diff_hunk_controls = render_diff_hunk_controls;
15889 cx.notify();
15890 }
15891
15892 pub fn stage_and_next(
15893 &mut self,
15894 _: &::git::StageAndNext,
15895 window: &mut Window,
15896 cx: &mut Context<Self>,
15897 ) {
15898 self.do_stage_or_unstage_and_next(true, window, cx);
15899 }
15900
15901 pub fn unstage_and_next(
15902 &mut self,
15903 _: &::git::UnstageAndNext,
15904 window: &mut Window,
15905 cx: &mut Context<Self>,
15906 ) {
15907 self.do_stage_or_unstage_and_next(false, window, cx);
15908 }
15909
15910 pub fn stage_or_unstage_diff_hunks(
15911 &mut self,
15912 stage: bool,
15913 ranges: Vec<Range<Anchor>>,
15914 cx: &mut Context<Self>,
15915 ) {
15916 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15917 cx.spawn(async move |this, cx| {
15918 task.await?;
15919 this.update(cx, |this, cx| {
15920 let snapshot = this.buffer.read(cx).snapshot(cx);
15921 let chunk_by = this
15922 .diff_hunks_in_ranges(&ranges, &snapshot)
15923 .chunk_by(|hunk| hunk.buffer_id);
15924 for (buffer_id, hunks) in &chunk_by {
15925 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15926 }
15927 })
15928 })
15929 .detach_and_log_err(cx);
15930 }
15931
15932 fn save_buffers_for_ranges_if_needed(
15933 &mut self,
15934 ranges: &[Range<Anchor>],
15935 cx: &mut Context<Editor>,
15936 ) -> Task<Result<()>> {
15937 let multibuffer = self.buffer.read(cx);
15938 let snapshot = multibuffer.read(cx);
15939 let buffer_ids: HashSet<_> = ranges
15940 .iter()
15941 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15942 .collect();
15943 drop(snapshot);
15944
15945 let mut buffers = HashSet::default();
15946 for buffer_id in buffer_ids {
15947 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15948 let buffer = buffer_entity.read(cx);
15949 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15950 {
15951 buffers.insert(buffer_entity);
15952 }
15953 }
15954 }
15955
15956 if let Some(project) = &self.project {
15957 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15958 } else {
15959 Task::ready(Ok(()))
15960 }
15961 }
15962
15963 fn do_stage_or_unstage_and_next(
15964 &mut self,
15965 stage: bool,
15966 window: &mut Window,
15967 cx: &mut Context<Self>,
15968 ) {
15969 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15970
15971 if ranges.iter().any(|range| range.start != range.end) {
15972 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15973 return;
15974 }
15975
15976 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15977 let snapshot = self.snapshot(window, cx);
15978 let position = self.selections.newest::<Point>(cx).head();
15979 let mut row = snapshot
15980 .buffer_snapshot
15981 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15982 .find(|hunk| hunk.row_range.start.0 > position.row)
15983 .map(|hunk| hunk.row_range.start);
15984
15985 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15986 // Outside of the project diff editor, wrap around to the beginning.
15987 if !all_diff_hunks_expanded {
15988 row = row.or_else(|| {
15989 snapshot
15990 .buffer_snapshot
15991 .diff_hunks_in_range(Point::zero()..position)
15992 .find(|hunk| hunk.row_range.end.0 < position.row)
15993 .map(|hunk| hunk.row_range.start)
15994 });
15995 }
15996
15997 if let Some(row) = row {
15998 let destination = Point::new(row.0, 0);
15999 let autoscroll = Autoscroll::center();
16000
16001 self.unfold_ranges(&[destination..destination], false, false, cx);
16002 self.change_selections(Some(autoscroll), window, cx, |s| {
16003 s.select_ranges([destination..destination]);
16004 });
16005 }
16006 }
16007
16008 fn do_stage_or_unstage(
16009 &self,
16010 stage: bool,
16011 buffer_id: BufferId,
16012 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16013 cx: &mut App,
16014 ) -> Option<()> {
16015 let project = self.project.as_ref()?;
16016 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16017 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16018 let buffer_snapshot = buffer.read(cx).snapshot();
16019 let file_exists = buffer_snapshot
16020 .file()
16021 .is_some_and(|file| file.disk_state().exists());
16022 diff.update(cx, |diff, cx| {
16023 diff.stage_or_unstage_hunks(
16024 stage,
16025 &hunks
16026 .map(|hunk| buffer_diff::DiffHunk {
16027 buffer_range: hunk.buffer_range,
16028 diff_base_byte_range: hunk.diff_base_byte_range,
16029 secondary_status: hunk.secondary_status,
16030 range: Point::zero()..Point::zero(), // unused
16031 })
16032 .collect::<Vec<_>>(),
16033 &buffer_snapshot,
16034 file_exists,
16035 cx,
16036 )
16037 });
16038 None
16039 }
16040
16041 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16042 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16043 self.buffer
16044 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16045 }
16046
16047 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16048 self.buffer.update(cx, |buffer, cx| {
16049 let ranges = vec![Anchor::min()..Anchor::max()];
16050 if !buffer.all_diff_hunks_expanded()
16051 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16052 {
16053 buffer.collapse_diff_hunks(ranges, cx);
16054 true
16055 } else {
16056 false
16057 }
16058 })
16059 }
16060
16061 fn toggle_diff_hunks_in_ranges(
16062 &mut self,
16063 ranges: Vec<Range<Anchor>>,
16064 cx: &mut Context<Editor>,
16065 ) {
16066 self.buffer.update(cx, |buffer, cx| {
16067 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16068 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16069 })
16070 }
16071
16072 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16073 self.buffer.update(cx, |buffer, cx| {
16074 let snapshot = buffer.snapshot(cx);
16075 let excerpt_id = range.end.excerpt_id;
16076 let point_range = range.to_point(&snapshot);
16077 let expand = !buffer.single_hunk_is_expanded(range, cx);
16078 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16079 })
16080 }
16081
16082 pub(crate) fn apply_all_diff_hunks(
16083 &mut self,
16084 _: &ApplyAllDiffHunks,
16085 window: &mut Window,
16086 cx: &mut Context<Self>,
16087 ) {
16088 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16089
16090 let buffers = self.buffer.read(cx).all_buffers();
16091 for branch_buffer in buffers {
16092 branch_buffer.update(cx, |branch_buffer, cx| {
16093 branch_buffer.merge_into_base(Vec::new(), cx);
16094 });
16095 }
16096
16097 if let Some(project) = self.project.clone() {
16098 self.save(true, project, window, cx).detach_and_log_err(cx);
16099 }
16100 }
16101
16102 pub(crate) fn apply_selected_diff_hunks(
16103 &mut self,
16104 _: &ApplyDiffHunk,
16105 window: &mut Window,
16106 cx: &mut Context<Self>,
16107 ) {
16108 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16109 let snapshot = self.snapshot(window, cx);
16110 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16111 let mut ranges_by_buffer = HashMap::default();
16112 self.transact(window, cx, |editor, _window, cx| {
16113 for hunk in hunks {
16114 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16115 ranges_by_buffer
16116 .entry(buffer.clone())
16117 .or_insert_with(Vec::new)
16118 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16119 }
16120 }
16121
16122 for (buffer, ranges) in ranges_by_buffer {
16123 buffer.update(cx, |buffer, cx| {
16124 buffer.merge_into_base(ranges, cx);
16125 });
16126 }
16127 });
16128
16129 if let Some(project) = self.project.clone() {
16130 self.save(true, project, window, cx).detach_and_log_err(cx);
16131 }
16132 }
16133
16134 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16135 if hovered != self.gutter_hovered {
16136 self.gutter_hovered = hovered;
16137 cx.notify();
16138 }
16139 }
16140
16141 pub fn insert_blocks(
16142 &mut self,
16143 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16144 autoscroll: Option<Autoscroll>,
16145 cx: &mut Context<Self>,
16146 ) -> Vec<CustomBlockId> {
16147 let blocks = self
16148 .display_map
16149 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16150 if let Some(autoscroll) = autoscroll {
16151 self.request_autoscroll(autoscroll, cx);
16152 }
16153 cx.notify();
16154 blocks
16155 }
16156
16157 pub fn resize_blocks(
16158 &mut self,
16159 heights: HashMap<CustomBlockId, u32>,
16160 autoscroll: Option<Autoscroll>,
16161 cx: &mut Context<Self>,
16162 ) {
16163 self.display_map
16164 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16165 if let Some(autoscroll) = autoscroll {
16166 self.request_autoscroll(autoscroll, cx);
16167 }
16168 cx.notify();
16169 }
16170
16171 pub fn replace_blocks(
16172 &mut self,
16173 renderers: HashMap<CustomBlockId, RenderBlock>,
16174 autoscroll: Option<Autoscroll>,
16175 cx: &mut Context<Self>,
16176 ) {
16177 self.display_map
16178 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16179 if let Some(autoscroll) = autoscroll {
16180 self.request_autoscroll(autoscroll, cx);
16181 }
16182 cx.notify();
16183 }
16184
16185 pub fn remove_blocks(
16186 &mut self,
16187 block_ids: HashSet<CustomBlockId>,
16188 autoscroll: Option<Autoscroll>,
16189 cx: &mut Context<Self>,
16190 ) {
16191 self.display_map.update(cx, |display_map, cx| {
16192 display_map.remove_blocks(block_ids, cx)
16193 });
16194 if let Some(autoscroll) = autoscroll {
16195 self.request_autoscroll(autoscroll, cx);
16196 }
16197 cx.notify();
16198 }
16199
16200 pub fn row_for_block(
16201 &self,
16202 block_id: CustomBlockId,
16203 cx: &mut Context<Self>,
16204 ) -> Option<DisplayRow> {
16205 self.display_map
16206 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16207 }
16208
16209 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16210 self.focused_block = Some(focused_block);
16211 }
16212
16213 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16214 self.focused_block.take()
16215 }
16216
16217 pub fn insert_creases(
16218 &mut self,
16219 creases: impl IntoIterator<Item = Crease<Anchor>>,
16220 cx: &mut Context<Self>,
16221 ) -> Vec<CreaseId> {
16222 self.display_map
16223 .update(cx, |map, cx| map.insert_creases(creases, cx))
16224 }
16225
16226 pub fn remove_creases(
16227 &mut self,
16228 ids: impl IntoIterator<Item = CreaseId>,
16229 cx: &mut Context<Self>,
16230 ) -> Vec<(CreaseId, Range<Anchor>)> {
16231 self.display_map
16232 .update(cx, |map, cx| map.remove_creases(ids, cx))
16233 }
16234
16235 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16236 self.display_map
16237 .update(cx, |map, cx| map.snapshot(cx))
16238 .longest_row()
16239 }
16240
16241 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16242 self.display_map
16243 .update(cx, |map, cx| map.snapshot(cx))
16244 .max_point()
16245 }
16246
16247 pub fn text(&self, cx: &App) -> String {
16248 self.buffer.read(cx).read(cx).text()
16249 }
16250
16251 pub fn is_empty(&self, cx: &App) -> bool {
16252 self.buffer.read(cx).read(cx).is_empty()
16253 }
16254
16255 pub fn text_option(&self, cx: &App) -> Option<String> {
16256 let text = self.text(cx);
16257 let text = text.trim();
16258
16259 if text.is_empty() {
16260 return None;
16261 }
16262
16263 Some(text.to_string())
16264 }
16265
16266 pub fn set_text(
16267 &mut self,
16268 text: impl Into<Arc<str>>,
16269 window: &mut Window,
16270 cx: &mut Context<Self>,
16271 ) {
16272 self.transact(window, cx, |this, _, cx| {
16273 this.buffer
16274 .read(cx)
16275 .as_singleton()
16276 .expect("you can only call set_text on editors for singleton buffers")
16277 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16278 });
16279 }
16280
16281 pub fn display_text(&self, cx: &mut App) -> String {
16282 self.display_map
16283 .update(cx, |map, cx| map.snapshot(cx))
16284 .text()
16285 }
16286
16287 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16288 let mut wrap_guides = smallvec::smallvec![];
16289
16290 if self.show_wrap_guides == Some(false) {
16291 return wrap_guides;
16292 }
16293
16294 let settings = self.buffer.read(cx).language_settings(cx);
16295 if settings.show_wrap_guides {
16296 match self.soft_wrap_mode(cx) {
16297 SoftWrap::Column(soft_wrap) => {
16298 wrap_guides.push((soft_wrap as usize, true));
16299 }
16300 SoftWrap::Bounded(soft_wrap) => {
16301 wrap_guides.push((soft_wrap as usize, true));
16302 }
16303 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16304 }
16305 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16306 }
16307
16308 wrap_guides
16309 }
16310
16311 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16312 let settings = self.buffer.read(cx).language_settings(cx);
16313 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16314 match mode {
16315 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16316 SoftWrap::None
16317 }
16318 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16319 language_settings::SoftWrap::PreferredLineLength => {
16320 SoftWrap::Column(settings.preferred_line_length)
16321 }
16322 language_settings::SoftWrap::Bounded => {
16323 SoftWrap::Bounded(settings.preferred_line_length)
16324 }
16325 }
16326 }
16327
16328 pub fn set_soft_wrap_mode(
16329 &mut self,
16330 mode: language_settings::SoftWrap,
16331
16332 cx: &mut Context<Self>,
16333 ) {
16334 self.soft_wrap_mode_override = Some(mode);
16335 cx.notify();
16336 }
16337
16338 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16339 self.hard_wrap = hard_wrap;
16340 cx.notify();
16341 }
16342
16343 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16344 self.text_style_refinement = Some(style);
16345 }
16346
16347 /// called by the Element so we know what style we were most recently rendered with.
16348 pub(crate) fn set_style(
16349 &mut self,
16350 style: EditorStyle,
16351 window: &mut Window,
16352 cx: &mut Context<Self>,
16353 ) {
16354 let rem_size = window.rem_size();
16355 self.display_map.update(cx, |map, cx| {
16356 map.set_font(
16357 style.text.font(),
16358 style.text.font_size.to_pixels(rem_size),
16359 cx,
16360 )
16361 });
16362 self.style = Some(style);
16363 }
16364
16365 pub fn style(&self) -> Option<&EditorStyle> {
16366 self.style.as_ref()
16367 }
16368
16369 // Called by the element. This method is not designed to be called outside of the editor
16370 // element's layout code because it does not notify when rewrapping is computed synchronously.
16371 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16372 self.display_map
16373 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16374 }
16375
16376 pub fn set_soft_wrap(&mut self) {
16377 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16378 }
16379
16380 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16381 if self.soft_wrap_mode_override.is_some() {
16382 self.soft_wrap_mode_override.take();
16383 } else {
16384 let soft_wrap = match self.soft_wrap_mode(cx) {
16385 SoftWrap::GitDiff => return,
16386 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16387 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16388 language_settings::SoftWrap::None
16389 }
16390 };
16391 self.soft_wrap_mode_override = Some(soft_wrap);
16392 }
16393 cx.notify();
16394 }
16395
16396 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16397 let Some(workspace) = self.workspace() else {
16398 return;
16399 };
16400 let fs = workspace.read(cx).app_state().fs.clone();
16401 let current_show = TabBarSettings::get_global(cx).show;
16402 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16403 setting.show = Some(!current_show);
16404 });
16405 }
16406
16407 pub fn toggle_indent_guides(
16408 &mut self,
16409 _: &ToggleIndentGuides,
16410 _: &mut Window,
16411 cx: &mut Context<Self>,
16412 ) {
16413 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16414 self.buffer
16415 .read(cx)
16416 .language_settings(cx)
16417 .indent_guides
16418 .enabled
16419 });
16420 self.show_indent_guides = Some(!currently_enabled);
16421 cx.notify();
16422 }
16423
16424 fn should_show_indent_guides(&self) -> Option<bool> {
16425 self.show_indent_guides
16426 }
16427
16428 pub fn toggle_line_numbers(
16429 &mut self,
16430 _: &ToggleLineNumbers,
16431 _: &mut Window,
16432 cx: &mut Context<Self>,
16433 ) {
16434 let mut editor_settings = EditorSettings::get_global(cx).clone();
16435 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16436 EditorSettings::override_global(editor_settings, cx);
16437 }
16438
16439 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16440 if let Some(show_line_numbers) = self.show_line_numbers {
16441 return show_line_numbers;
16442 }
16443 EditorSettings::get_global(cx).gutter.line_numbers
16444 }
16445
16446 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16447 self.use_relative_line_numbers
16448 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16449 }
16450
16451 pub fn toggle_relative_line_numbers(
16452 &mut self,
16453 _: &ToggleRelativeLineNumbers,
16454 _: &mut Window,
16455 cx: &mut Context<Self>,
16456 ) {
16457 let is_relative = self.should_use_relative_line_numbers(cx);
16458 self.set_relative_line_number(Some(!is_relative), cx)
16459 }
16460
16461 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16462 self.use_relative_line_numbers = is_relative;
16463 cx.notify();
16464 }
16465
16466 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16467 self.show_gutter = show_gutter;
16468 cx.notify();
16469 }
16470
16471 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16472 self.show_scrollbars = show_scrollbars;
16473 cx.notify();
16474 }
16475
16476 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16477 self.show_line_numbers = Some(show_line_numbers);
16478 cx.notify();
16479 }
16480
16481 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16482 self.disable_expand_excerpt_buttons = true;
16483 cx.notify();
16484 }
16485
16486 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16487 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16488 cx.notify();
16489 }
16490
16491 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16492 self.show_code_actions = Some(show_code_actions);
16493 cx.notify();
16494 }
16495
16496 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16497 self.show_runnables = Some(show_runnables);
16498 cx.notify();
16499 }
16500
16501 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16502 self.show_breakpoints = Some(show_breakpoints);
16503 cx.notify();
16504 }
16505
16506 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16507 if self.display_map.read(cx).masked != masked {
16508 self.display_map.update(cx, |map, _| map.masked = masked);
16509 }
16510 cx.notify()
16511 }
16512
16513 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16514 self.show_wrap_guides = Some(show_wrap_guides);
16515 cx.notify();
16516 }
16517
16518 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16519 self.show_indent_guides = Some(show_indent_guides);
16520 cx.notify();
16521 }
16522
16523 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16524 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16525 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16526 if let Some(dir) = file.abs_path(cx).parent() {
16527 return Some(dir.to_owned());
16528 }
16529 }
16530
16531 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16532 return Some(project_path.path.to_path_buf());
16533 }
16534 }
16535
16536 None
16537 }
16538
16539 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16540 self.active_excerpt(cx)?
16541 .1
16542 .read(cx)
16543 .file()
16544 .and_then(|f| f.as_local())
16545 }
16546
16547 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16548 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16549 let buffer = buffer.read(cx);
16550 if let Some(project_path) = buffer.project_path(cx) {
16551 let project = self.project.as_ref()?.read(cx);
16552 project.absolute_path(&project_path, cx)
16553 } else {
16554 buffer
16555 .file()
16556 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16557 }
16558 })
16559 }
16560
16561 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16562 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16563 let project_path = buffer.read(cx).project_path(cx)?;
16564 let project = self.project.as_ref()?.read(cx);
16565 let entry = project.entry_for_path(&project_path, cx)?;
16566 let path = entry.path.to_path_buf();
16567 Some(path)
16568 })
16569 }
16570
16571 pub fn reveal_in_finder(
16572 &mut self,
16573 _: &RevealInFileManager,
16574 _window: &mut Window,
16575 cx: &mut Context<Self>,
16576 ) {
16577 if let Some(target) = self.target_file(cx) {
16578 cx.reveal_path(&target.abs_path(cx));
16579 }
16580 }
16581
16582 pub fn copy_path(
16583 &mut self,
16584 _: &zed_actions::workspace::CopyPath,
16585 _window: &mut Window,
16586 cx: &mut Context<Self>,
16587 ) {
16588 if let Some(path) = self.target_file_abs_path(cx) {
16589 if let Some(path) = path.to_str() {
16590 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16591 }
16592 }
16593 }
16594
16595 pub fn copy_relative_path(
16596 &mut self,
16597 _: &zed_actions::workspace::CopyRelativePath,
16598 _window: &mut Window,
16599 cx: &mut Context<Self>,
16600 ) {
16601 if let Some(path) = self.target_file_path(cx) {
16602 if let Some(path) = path.to_str() {
16603 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16604 }
16605 }
16606 }
16607
16608 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16609 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16610 buffer.read(cx).project_path(cx)
16611 } else {
16612 None
16613 }
16614 }
16615
16616 // Returns true if the editor handled a go-to-line request
16617 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16618 maybe!({
16619 let breakpoint_store = self.breakpoint_store.as_ref()?;
16620
16621 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16622 else {
16623 self.clear_row_highlights::<ActiveDebugLine>();
16624 return None;
16625 };
16626
16627 let position = active_stack_frame.position;
16628 let buffer_id = position.buffer_id?;
16629 let snapshot = self
16630 .project
16631 .as_ref()?
16632 .read(cx)
16633 .buffer_for_id(buffer_id, cx)?
16634 .read(cx)
16635 .snapshot();
16636
16637 let mut handled = false;
16638 for (id, ExcerptRange { context, .. }) in
16639 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16640 {
16641 if context.start.cmp(&position, &snapshot).is_ge()
16642 || context.end.cmp(&position, &snapshot).is_lt()
16643 {
16644 continue;
16645 }
16646 let snapshot = self.buffer.read(cx).snapshot(cx);
16647 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16648
16649 handled = true;
16650 self.clear_row_highlights::<ActiveDebugLine>();
16651 self.go_to_line::<ActiveDebugLine>(
16652 multibuffer_anchor,
16653 Some(cx.theme().colors().editor_debugger_active_line_background),
16654 window,
16655 cx,
16656 );
16657
16658 cx.notify();
16659 }
16660
16661 handled.then_some(())
16662 })
16663 .is_some()
16664 }
16665
16666 pub fn copy_file_name_without_extension(
16667 &mut self,
16668 _: &CopyFileNameWithoutExtension,
16669 _: &mut Window,
16670 cx: &mut Context<Self>,
16671 ) {
16672 if let Some(file) = self.target_file(cx) {
16673 if let Some(file_stem) = file.path().file_stem() {
16674 if let Some(name) = file_stem.to_str() {
16675 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16676 }
16677 }
16678 }
16679 }
16680
16681 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16682 if let Some(file) = self.target_file(cx) {
16683 if let Some(file_name) = file.path().file_name() {
16684 if let Some(name) = file_name.to_str() {
16685 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16686 }
16687 }
16688 }
16689 }
16690
16691 pub fn toggle_git_blame(
16692 &mut self,
16693 _: &::git::Blame,
16694 window: &mut Window,
16695 cx: &mut Context<Self>,
16696 ) {
16697 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16698
16699 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16700 self.start_git_blame(true, window, cx);
16701 }
16702
16703 cx.notify();
16704 }
16705
16706 pub fn toggle_git_blame_inline(
16707 &mut self,
16708 _: &ToggleGitBlameInline,
16709 window: &mut Window,
16710 cx: &mut Context<Self>,
16711 ) {
16712 self.toggle_git_blame_inline_internal(true, window, cx);
16713 cx.notify();
16714 }
16715
16716 pub fn open_git_blame_commit(
16717 &mut self,
16718 _: &OpenGitBlameCommit,
16719 window: &mut Window,
16720 cx: &mut Context<Self>,
16721 ) {
16722 self.open_git_blame_commit_internal(window, cx);
16723 }
16724
16725 fn open_git_blame_commit_internal(
16726 &mut self,
16727 window: &mut Window,
16728 cx: &mut Context<Self>,
16729 ) -> Option<()> {
16730 let blame = self.blame.as_ref()?;
16731 let snapshot = self.snapshot(window, cx);
16732 let cursor = self.selections.newest::<Point>(cx).head();
16733 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16734 let blame_entry = blame
16735 .update(cx, |blame, cx| {
16736 blame
16737 .blame_for_rows(
16738 &[RowInfo {
16739 buffer_id: Some(buffer.remote_id()),
16740 buffer_row: Some(point.row),
16741 ..Default::default()
16742 }],
16743 cx,
16744 )
16745 .next()
16746 })
16747 .flatten()?;
16748 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16749 let repo = blame.read(cx).repository(cx)?;
16750 let workspace = self.workspace()?.downgrade();
16751 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16752 None
16753 }
16754
16755 pub fn git_blame_inline_enabled(&self) -> bool {
16756 self.git_blame_inline_enabled
16757 }
16758
16759 pub fn toggle_selection_menu(
16760 &mut self,
16761 _: &ToggleSelectionMenu,
16762 _: &mut Window,
16763 cx: &mut Context<Self>,
16764 ) {
16765 self.show_selection_menu = self
16766 .show_selection_menu
16767 .map(|show_selections_menu| !show_selections_menu)
16768 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16769
16770 cx.notify();
16771 }
16772
16773 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16774 self.show_selection_menu
16775 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16776 }
16777
16778 fn start_git_blame(
16779 &mut self,
16780 user_triggered: bool,
16781 window: &mut Window,
16782 cx: &mut Context<Self>,
16783 ) {
16784 if let Some(project) = self.project.as_ref() {
16785 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16786 return;
16787 };
16788
16789 if buffer.read(cx).file().is_none() {
16790 return;
16791 }
16792
16793 let focused = self.focus_handle(cx).contains_focused(window, cx);
16794
16795 let project = project.clone();
16796 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16797 self.blame_subscription =
16798 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16799 self.blame = Some(blame);
16800 }
16801 }
16802
16803 fn toggle_git_blame_inline_internal(
16804 &mut self,
16805 user_triggered: bool,
16806 window: &mut Window,
16807 cx: &mut Context<Self>,
16808 ) {
16809 if self.git_blame_inline_enabled {
16810 self.git_blame_inline_enabled = false;
16811 self.show_git_blame_inline = false;
16812 self.show_git_blame_inline_delay_task.take();
16813 } else {
16814 self.git_blame_inline_enabled = true;
16815 self.start_git_blame_inline(user_triggered, window, cx);
16816 }
16817
16818 cx.notify();
16819 }
16820
16821 fn start_git_blame_inline(
16822 &mut self,
16823 user_triggered: bool,
16824 window: &mut Window,
16825 cx: &mut Context<Self>,
16826 ) {
16827 self.start_git_blame(user_triggered, window, cx);
16828
16829 if ProjectSettings::get_global(cx)
16830 .git
16831 .inline_blame_delay()
16832 .is_some()
16833 {
16834 self.start_inline_blame_timer(window, cx);
16835 } else {
16836 self.show_git_blame_inline = true
16837 }
16838 }
16839
16840 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16841 self.blame.as_ref()
16842 }
16843
16844 pub fn show_git_blame_gutter(&self) -> bool {
16845 self.show_git_blame_gutter
16846 }
16847
16848 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16849 self.show_git_blame_gutter && self.has_blame_entries(cx)
16850 }
16851
16852 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16853 self.show_git_blame_inline
16854 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16855 && !self.newest_selection_head_on_empty_line(cx)
16856 && self.has_blame_entries(cx)
16857 }
16858
16859 fn has_blame_entries(&self, cx: &App) -> bool {
16860 self.blame()
16861 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16862 }
16863
16864 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16865 let cursor_anchor = self.selections.newest_anchor().head();
16866
16867 let snapshot = self.buffer.read(cx).snapshot(cx);
16868 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16869
16870 snapshot.line_len(buffer_row) == 0
16871 }
16872
16873 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16874 let buffer_and_selection = maybe!({
16875 let selection = self.selections.newest::<Point>(cx);
16876 let selection_range = selection.range();
16877
16878 let multi_buffer = self.buffer().read(cx);
16879 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16880 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16881
16882 let (buffer, range, _) = if selection.reversed {
16883 buffer_ranges.first()
16884 } else {
16885 buffer_ranges.last()
16886 }?;
16887
16888 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16889 ..text::ToPoint::to_point(&range.end, &buffer).row;
16890 Some((
16891 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16892 selection,
16893 ))
16894 });
16895
16896 let Some((buffer, selection)) = buffer_and_selection else {
16897 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16898 };
16899
16900 let Some(project) = self.project.as_ref() else {
16901 return Task::ready(Err(anyhow!("editor does not have project")));
16902 };
16903
16904 project.update(cx, |project, cx| {
16905 project.get_permalink_to_line(&buffer, selection, cx)
16906 })
16907 }
16908
16909 pub fn copy_permalink_to_line(
16910 &mut self,
16911 _: &CopyPermalinkToLine,
16912 window: &mut Window,
16913 cx: &mut Context<Self>,
16914 ) {
16915 let permalink_task = self.get_permalink_to_line(cx);
16916 let workspace = self.workspace();
16917
16918 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16919 Ok(permalink) => {
16920 cx.update(|_, cx| {
16921 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16922 })
16923 .ok();
16924 }
16925 Err(err) => {
16926 let message = format!("Failed to copy permalink: {err}");
16927
16928 Err::<(), anyhow::Error>(err).log_err();
16929
16930 if let Some(workspace) = workspace {
16931 workspace
16932 .update_in(cx, |workspace, _, cx| {
16933 struct CopyPermalinkToLine;
16934
16935 workspace.show_toast(
16936 Toast::new(
16937 NotificationId::unique::<CopyPermalinkToLine>(),
16938 message,
16939 ),
16940 cx,
16941 )
16942 })
16943 .ok();
16944 }
16945 }
16946 })
16947 .detach();
16948 }
16949
16950 pub fn copy_file_location(
16951 &mut self,
16952 _: &CopyFileLocation,
16953 _: &mut Window,
16954 cx: &mut Context<Self>,
16955 ) {
16956 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16957 if let Some(file) = self.target_file(cx) {
16958 if let Some(path) = file.path().to_str() {
16959 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16960 }
16961 }
16962 }
16963
16964 pub fn open_permalink_to_line(
16965 &mut self,
16966 _: &OpenPermalinkToLine,
16967 window: &mut Window,
16968 cx: &mut Context<Self>,
16969 ) {
16970 let permalink_task = self.get_permalink_to_line(cx);
16971 let workspace = self.workspace();
16972
16973 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16974 Ok(permalink) => {
16975 cx.update(|_, cx| {
16976 cx.open_url(permalink.as_ref());
16977 })
16978 .ok();
16979 }
16980 Err(err) => {
16981 let message = format!("Failed to open permalink: {err}");
16982
16983 Err::<(), anyhow::Error>(err).log_err();
16984
16985 if let Some(workspace) = workspace {
16986 workspace
16987 .update(cx, |workspace, cx| {
16988 struct OpenPermalinkToLine;
16989
16990 workspace.show_toast(
16991 Toast::new(
16992 NotificationId::unique::<OpenPermalinkToLine>(),
16993 message,
16994 ),
16995 cx,
16996 )
16997 })
16998 .ok();
16999 }
17000 }
17001 })
17002 .detach();
17003 }
17004
17005 pub fn insert_uuid_v4(
17006 &mut self,
17007 _: &InsertUuidV4,
17008 window: &mut Window,
17009 cx: &mut Context<Self>,
17010 ) {
17011 self.insert_uuid(UuidVersion::V4, window, cx);
17012 }
17013
17014 pub fn insert_uuid_v7(
17015 &mut self,
17016 _: &InsertUuidV7,
17017 window: &mut Window,
17018 cx: &mut Context<Self>,
17019 ) {
17020 self.insert_uuid(UuidVersion::V7, window, cx);
17021 }
17022
17023 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17024 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17025 self.transact(window, cx, |this, window, cx| {
17026 let edits = this
17027 .selections
17028 .all::<Point>(cx)
17029 .into_iter()
17030 .map(|selection| {
17031 let uuid = match version {
17032 UuidVersion::V4 => uuid::Uuid::new_v4(),
17033 UuidVersion::V7 => uuid::Uuid::now_v7(),
17034 };
17035
17036 (selection.range(), uuid.to_string())
17037 });
17038 this.edit(edits, cx);
17039 this.refresh_inline_completion(true, false, window, cx);
17040 });
17041 }
17042
17043 pub fn open_selections_in_multibuffer(
17044 &mut self,
17045 _: &OpenSelectionsInMultibuffer,
17046 window: &mut Window,
17047 cx: &mut Context<Self>,
17048 ) {
17049 let multibuffer = self.buffer.read(cx);
17050
17051 let Some(buffer) = multibuffer.as_singleton() else {
17052 return;
17053 };
17054
17055 let Some(workspace) = self.workspace() else {
17056 return;
17057 };
17058
17059 let locations = self
17060 .selections
17061 .disjoint_anchors()
17062 .iter()
17063 .map(|range| Location {
17064 buffer: buffer.clone(),
17065 range: range.start.text_anchor..range.end.text_anchor,
17066 })
17067 .collect::<Vec<_>>();
17068
17069 let title = multibuffer.title(cx).to_string();
17070
17071 cx.spawn_in(window, async move |_, cx| {
17072 workspace.update_in(cx, |workspace, window, cx| {
17073 Self::open_locations_in_multibuffer(
17074 workspace,
17075 locations,
17076 format!("Selections for '{title}'"),
17077 false,
17078 MultibufferSelectionMode::All,
17079 window,
17080 cx,
17081 );
17082 })
17083 })
17084 .detach();
17085 }
17086
17087 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17088 /// last highlight added will be used.
17089 ///
17090 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17091 pub fn highlight_rows<T: 'static>(
17092 &mut self,
17093 range: Range<Anchor>,
17094 color: Hsla,
17095 options: RowHighlightOptions,
17096 cx: &mut Context<Self>,
17097 ) {
17098 let snapshot = self.buffer().read(cx).snapshot(cx);
17099 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17100 let ix = row_highlights.binary_search_by(|highlight| {
17101 Ordering::Equal
17102 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17103 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17104 });
17105
17106 if let Err(mut ix) = ix {
17107 let index = post_inc(&mut self.highlight_order);
17108
17109 // If this range intersects with the preceding highlight, then merge it with
17110 // the preceding highlight. Otherwise insert a new highlight.
17111 let mut merged = false;
17112 if ix > 0 {
17113 let prev_highlight = &mut row_highlights[ix - 1];
17114 if prev_highlight
17115 .range
17116 .end
17117 .cmp(&range.start, &snapshot)
17118 .is_ge()
17119 {
17120 ix -= 1;
17121 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17122 prev_highlight.range.end = range.end;
17123 }
17124 merged = true;
17125 prev_highlight.index = index;
17126 prev_highlight.color = color;
17127 prev_highlight.options = options;
17128 }
17129 }
17130
17131 if !merged {
17132 row_highlights.insert(
17133 ix,
17134 RowHighlight {
17135 range: range.clone(),
17136 index,
17137 color,
17138 options,
17139 type_id: TypeId::of::<T>(),
17140 },
17141 );
17142 }
17143
17144 // If any of the following highlights intersect with this one, merge them.
17145 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17146 let highlight = &row_highlights[ix];
17147 if next_highlight
17148 .range
17149 .start
17150 .cmp(&highlight.range.end, &snapshot)
17151 .is_le()
17152 {
17153 if next_highlight
17154 .range
17155 .end
17156 .cmp(&highlight.range.end, &snapshot)
17157 .is_gt()
17158 {
17159 row_highlights[ix].range.end = next_highlight.range.end;
17160 }
17161 row_highlights.remove(ix + 1);
17162 } else {
17163 break;
17164 }
17165 }
17166 }
17167 }
17168
17169 /// Remove any highlighted row ranges of the given type that intersect the
17170 /// given ranges.
17171 pub fn remove_highlighted_rows<T: 'static>(
17172 &mut self,
17173 ranges_to_remove: Vec<Range<Anchor>>,
17174 cx: &mut Context<Self>,
17175 ) {
17176 let snapshot = self.buffer().read(cx).snapshot(cx);
17177 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17178 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17179 row_highlights.retain(|highlight| {
17180 while let Some(range_to_remove) = ranges_to_remove.peek() {
17181 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17182 Ordering::Less | Ordering::Equal => {
17183 ranges_to_remove.next();
17184 }
17185 Ordering::Greater => {
17186 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17187 Ordering::Less | Ordering::Equal => {
17188 return false;
17189 }
17190 Ordering::Greater => break,
17191 }
17192 }
17193 }
17194 }
17195
17196 true
17197 })
17198 }
17199
17200 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17201 pub fn clear_row_highlights<T: 'static>(&mut self) {
17202 self.highlighted_rows.remove(&TypeId::of::<T>());
17203 }
17204
17205 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17206 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17207 self.highlighted_rows
17208 .get(&TypeId::of::<T>())
17209 .map_or(&[] as &[_], |vec| vec.as_slice())
17210 .iter()
17211 .map(|highlight| (highlight.range.clone(), highlight.color))
17212 }
17213
17214 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17215 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17216 /// Allows to ignore certain kinds of highlights.
17217 pub fn highlighted_display_rows(
17218 &self,
17219 window: &mut Window,
17220 cx: &mut App,
17221 ) -> BTreeMap<DisplayRow, LineHighlight> {
17222 let snapshot = self.snapshot(window, cx);
17223 let mut used_highlight_orders = HashMap::default();
17224 self.highlighted_rows
17225 .iter()
17226 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17227 .fold(
17228 BTreeMap::<DisplayRow, LineHighlight>::new(),
17229 |mut unique_rows, highlight| {
17230 let start = highlight.range.start.to_display_point(&snapshot);
17231 let end = highlight.range.end.to_display_point(&snapshot);
17232 let start_row = start.row().0;
17233 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17234 && end.column() == 0
17235 {
17236 end.row().0.saturating_sub(1)
17237 } else {
17238 end.row().0
17239 };
17240 for row in start_row..=end_row {
17241 let used_index =
17242 used_highlight_orders.entry(row).or_insert(highlight.index);
17243 if highlight.index >= *used_index {
17244 *used_index = highlight.index;
17245 unique_rows.insert(
17246 DisplayRow(row),
17247 LineHighlight {
17248 include_gutter: highlight.options.include_gutter,
17249 border: None,
17250 background: highlight.color.into(),
17251 type_id: Some(highlight.type_id),
17252 },
17253 );
17254 }
17255 }
17256 unique_rows
17257 },
17258 )
17259 }
17260
17261 pub fn highlighted_display_row_for_autoscroll(
17262 &self,
17263 snapshot: &DisplaySnapshot,
17264 ) -> Option<DisplayRow> {
17265 self.highlighted_rows
17266 .values()
17267 .flat_map(|highlighted_rows| highlighted_rows.iter())
17268 .filter_map(|highlight| {
17269 if highlight.options.autoscroll {
17270 Some(highlight.range.start.to_display_point(snapshot).row())
17271 } else {
17272 None
17273 }
17274 })
17275 .min()
17276 }
17277
17278 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17279 self.highlight_background::<SearchWithinRange>(
17280 ranges,
17281 |colors| colors.editor_document_highlight_read_background,
17282 cx,
17283 )
17284 }
17285
17286 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17287 self.breadcrumb_header = Some(new_header);
17288 }
17289
17290 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17291 self.clear_background_highlights::<SearchWithinRange>(cx);
17292 }
17293
17294 pub fn highlight_background<T: 'static>(
17295 &mut self,
17296 ranges: &[Range<Anchor>],
17297 color_fetcher: fn(&ThemeColors) -> Hsla,
17298 cx: &mut Context<Self>,
17299 ) {
17300 self.background_highlights
17301 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17302 self.scrollbar_marker_state.dirty = true;
17303 cx.notify();
17304 }
17305
17306 pub fn clear_background_highlights<T: 'static>(
17307 &mut self,
17308 cx: &mut Context<Self>,
17309 ) -> Option<BackgroundHighlight> {
17310 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17311 if !text_highlights.1.is_empty() {
17312 self.scrollbar_marker_state.dirty = true;
17313 cx.notify();
17314 }
17315 Some(text_highlights)
17316 }
17317
17318 pub fn highlight_gutter<T: 'static>(
17319 &mut self,
17320 ranges: &[Range<Anchor>],
17321 color_fetcher: fn(&App) -> Hsla,
17322 cx: &mut Context<Self>,
17323 ) {
17324 self.gutter_highlights
17325 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17326 cx.notify();
17327 }
17328
17329 pub fn clear_gutter_highlights<T: 'static>(
17330 &mut self,
17331 cx: &mut Context<Self>,
17332 ) -> Option<GutterHighlight> {
17333 cx.notify();
17334 self.gutter_highlights.remove(&TypeId::of::<T>())
17335 }
17336
17337 #[cfg(feature = "test-support")]
17338 pub fn all_text_background_highlights(
17339 &self,
17340 window: &mut Window,
17341 cx: &mut Context<Self>,
17342 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17343 let snapshot = self.snapshot(window, cx);
17344 let buffer = &snapshot.buffer_snapshot;
17345 let start = buffer.anchor_before(0);
17346 let end = buffer.anchor_after(buffer.len());
17347 let theme = cx.theme().colors();
17348 self.background_highlights_in_range(start..end, &snapshot, theme)
17349 }
17350
17351 #[cfg(feature = "test-support")]
17352 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17353 let snapshot = self.buffer().read(cx).snapshot(cx);
17354
17355 let highlights = self
17356 .background_highlights
17357 .get(&TypeId::of::<items::BufferSearchHighlights>());
17358
17359 if let Some((_color, ranges)) = highlights {
17360 ranges
17361 .iter()
17362 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17363 .collect_vec()
17364 } else {
17365 vec![]
17366 }
17367 }
17368
17369 fn document_highlights_for_position<'a>(
17370 &'a self,
17371 position: Anchor,
17372 buffer: &'a MultiBufferSnapshot,
17373 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17374 let read_highlights = self
17375 .background_highlights
17376 .get(&TypeId::of::<DocumentHighlightRead>())
17377 .map(|h| &h.1);
17378 let write_highlights = self
17379 .background_highlights
17380 .get(&TypeId::of::<DocumentHighlightWrite>())
17381 .map(|h| &h.1);
17382 let left_position = position.bias_left(buffer);
17383 let right_position = position.bias_right(buffer);
17384 read_highlights
17385 .into_iter()
17386 .chain(write_highlights)
17387 .flat_map(move |ranges| {
17388 let start_ix = match ranges.binary_search_by(|probe| {
17389 let cmp = probe.end.cmp(&left_position, buffer);
17390 if cmp.is_ge() {
17391 Ordering::Greater
17392 } else {
17393 Ordering::Less
17394 }
17395 }) {
17396 Ok(i) | Err(i) => i,
17397 };
17398
17399 ranges[start_ix..]
17400 .iter()
17401 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17402 })
17403 }
17404
17405 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17406 self.background_highlights
17407 .get(&TypeId::of::<T>())
17408 .map_or(false, |(_, highlights)| !highlights.is_empty())
17409 }
17410
17411 pub fn background_highlights_in_range(
17412 &self,
17413 search_range: Range<Anchor>,
17414 display_snapshot: &DisplaySnapshot,
17415 theme: &ThemeColors,
17416 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17417 let mut results = Vec::new();
17418 for (color_fetcher, ranges) in self.background_highlights.values() {
17419 let color = color_fetcher(theme);
17420 let start_ix = match ranges.binary_search_by(|probe| {
17421 let cmp = probe
17422 .end
17423 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17424 if cmp.is_gt() {
17425 Ordering::Greater
17426 } else {
17427 Ordering::Less
17428 }
17429 }) {
17430 Ok(i) | Err(i) => i,
17431 };
17432 for range in &ranges[start_ix..] {
17433 if range
17434 .start
17435 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17436 .is_ge()
17437 {
17438 break;
17439 }
17440
17441 let start = range.start.to_display_point(display_snapshot);
17442 let end = range.end.to_display_point(display_snapshot);
17443 results.push((start..end, color))
17444 }
17445 }
17446 results
17447 }
17448
17449 pub fn background_highlight_row_ranges<T: 'static>(
17450 &self,
17451 search_range: Range<Anchor>,
17452 display_snapshot: &DisplaySnapshot,
17453 count: usize,
17454 ) -> Vec<RangeInclusive<DisplayPoint>> {
17455 let mut results = Vec::new();
17456 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17457 return vec![];
17458 };
17459
17460 let start_ix = match ranges.binary_search_by(|probe| {
17461 let cmp = probe
17462 .end
17463 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17464 if cmp.is_gt() {
17465 Ordering::Greater
17466 } else {
17467 Ordering::Less
17468 }
17469 }) {
17470 Ok(i) | Err(i) => i,
17471 };
17472 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17473 if let (Some(start_display), Some(end_display)) = (start, end) {
17474 results.push(
17475 start_display.to_display_point(display_snapshot)
17476 ..=end_display.to_display_point(display_snapshot),
17477 );
17478 }
17479 };
17480 let mut start_row: Option<Point> = None;
17481 let mut end_row: Option<Point> = None;
17482 if ranges.len() > count {
17483 return Vec::new();
17484 }
17485 for range in &ranges[start_ix..] {
17486 if range
17487 .start
17488 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17489 .is_ge()
17490 {
17491 break;
17492 }
17493 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17494 if let Some(current_row) = &end_row {
17495 if end.row == current_row.row {
17496 continue;
17497 }
17498 }
17499 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17500 if start_row.is_none() {
17501 assert_eq!(end_row, None);
17502 start_row = Some(start);
17503 end_row = Some(end);
17504 continue;
17505 }
17506 if let Some(current_end) = end_row.as_mut() {
17507 if start.row > current_end.row + 1 {
17508 push_region(start_row, end_row);
17509 start_row = Some(start);
17510 end_row = Some(end);
17511 } else {
17512 // Merge two hunks.
17513 *current_end = end;
17514 }
17515 } else {
17516 unreachable!();
17517 }
17518 }
17519 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17520 push_region(start_row, end_row);
17521 results
17522 }
17523
17524 pub fn gutter_highlights_in_range(
17525 &self,
17526 search_range: Range<Anchor>,
17527 display_snapshot: &DisplaySnapshot,
17528 cx: &App,
17529 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17530 let mut results = Vec::new();
17531 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17532 let color = color_fetcher(cx);
17533 let start_ix = match ranges.binary_search_by(|probe| {
17534 let cmp = probe
17535 .end
17536 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17537 if cmp.is_gt() {
17538 Ordering::Greater
17539 } else {
17540 Ordering::Less
17541 }
17542 }) {
17543 Ok(i) | Err(i) => i,
17544 };
17545 for range in &ranges[start_ix..] {
17546 if range
17547 .start
17548 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17549 .is_ge()
17550 {
17551 break;
17552 }
17553
17554 let start = range.start.to_display_point(display_snapshot);
17555 let end = range.end.to_display_point(display_snapshot);
17556 results.push((start..end, color))
17557 }
17558 }
17559 results
17560 }
17561
17562 /// Get the text ranges corresponding to the redaction query
17563 pub fn redacted_ranges(
17564 &self,
17565 search_range: Range<Anchor>,
17566 display_snapshot: &DisplaySnapshot,
17567 cx: &App,
17568 ) -> Vec<Range<DisplayPoint>> {
17569 display_snapshot
17570 .buffer_snapshot
17571 .redacted_ranges(search_range, |file| {
17572 if let Some(file) = file {
17573 file.is_private()
17574 && EditorSettings::get(
17575 Some(SettingsLocation {
17576 worktree_id: file.worktree_id(cx),
17577 path: file.path().as_ref(),
17578 }),
17579 cx,
17580 )
17581 .redact_private_values
17582 } else {
17583 false
17584 }
17585 })
17586 .map(|range| {
17587 range.start.to_display_point(display_snapshot)
17588 ..range.end.to_display_point(display_snapshot)
17589 })
17590 .collect()
17591 }
17592
17593 pub fn highlight_text<T: 'static>(
17594 &mut self,
17595 ranges: Vec<Range<Anchor>>,
17596 style: HighlightStyle,
17597 cx: &mut Context<Self>,
17598 ) {
17599 self.display_map.update(cx, |map, _| {
17600 map.highlight_text(TypeId::of::<T>(), ranges, style)
17601 });
17602 cx.notify();
17603 }
17604
17605 pub(crate) fn highlight_inlays<T: 'static>(
17606 &mut self,
17607 highlights: Vec<InlayHighlight>,
17608 style: HighlightStyle,
17609 cx: &mut Context<Self>,
17610 ) {
17611 self.display_map.update(cx, |map, _| {
17612 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17613 });
17614 cx.notify();
17615 }
17616
17617 pub fn text_highlights<'a, T: 'static>(
17618 &'a self,
17619 cx: &'a App,
17620 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17621 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17622 }
17623
17624 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17625 let cleared = self
17626 .display_map
17627 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17628 if cleared {
17629 cx.notify();
17630 }
17631 }
17632
17633 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17634 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17635 && self.focus_handle.is_focused(window)
17636 }
17637
17638 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17639 self.show_cursor_when_unfocused = is_enabled;
17640 cx.notify();
17641 }
17642
17643 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17644 cx.notify();
17645 }
17646
17647 fn on_debug_session_event(
17648 &mut self,
17649 _session: Entity<Session>,
17650 event: &SessionEvent,
17651 cx: &mut Context<Self>,
17652 ) {
17653 match event {
17654 SessionEvent::InvalidateInlineValue => {
17655 self.refresh_inline_values(cx);
17656 }
17657 _ => {}
17658 }
17659 }
17660
17661 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17662 let Some(project) = self.project.clone() else {
17663 return;
17664 };
17665 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17666 return;
17667 };
17668 if !self.inline_value_cache.enabled {
17669 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17670 self.splice_inlays(&inlays, Vec::new(), cx);
17671 return;
17672 }
17673
17674 let current_execution_position = self
17675 .highlighted_rows
17676 .get(&TypeId::of::<ActiveDebugLine>())
17677 .and_then(|lines| lines.last().map(|line| line.range.start));
17678
17679 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17680 let snapshot = editor
17681 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17682 .ok()?;
17683
17684 let inline_values = editor
17685 .update(cx, |_, cx| {
17686 let Some(current_execution_position) = current_execution_position else {
17687 return Some(Task::ready(Ok(Vec::new())));
17688 };
17689
17690 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17691 // anchor is in the same buffer
17692 let range =
17693 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17694 project.inline_values(buffer, range, cx)
17695 })
17696 .ok()
17697 .flatten()?
17698 .await
17699 .context("refreshing debugger inlays")
17700 .log_err()?;
17701
17702 let (excerpt_id, buffer_id) = snapshot
17703 .excerpts()
17704 .next()
17705 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17706 editor
17707 .update(cx, |editor, cx| {
17708 let new_inlays = inline_values
17709 .into_iter()
17710 .map(|debugger_value| {
17711 Inlay::debugger_hint(
17712 post_inc(&mut editor.next_inlay_id),
17713 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17714 debugger_value.text(),
17715 )
17716 })
17717 .collect::<Vec<_>>();
17718 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17719 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17720
17721 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17722 })
17723 .ok()?;
17724 Some(())
17725 });
17726 }
17727
17728 fn on_buffer_event(
17729 &mut self,
17730 multibuffer: &Entity<MultiBuffer>,
17731 event: &multi_buffer::Event,
17732 window: &mut Window,
17733 cx: &mut Context<Self>,
17734 ) {
17735 match event {
17736 multi_buffer::Event::Edited {
17737 singleton_buffer_edited,
17738 edited_buffer: buffer_edited,
17739 } => {
17740 self.scrollbar_marker_state.dirty = true;
17741 self.active_indent_guides_state.dirty = true;
17742 self.refresh_active_diagnostics(cx);
17743 self.refresh_code_actions(window, cx);
17744 self.refresh_selected_text_highlights(true, window, cx);
17745 refresh_matching_bracket_highlights(self, window, cx);
17746 if self.has_active_inline_completion() {
17747 self.update_visible_inline_completion(window, cx);
17748 }
17749 if let Some(buffer) = buffer_edited {
17750 let buffer_id = buffer.read(cx).remote_id();
17751 if !self.registered_buffers.contains_key(&buffer_id) {
17752 if let Some(project) = self.project.as_ref() {
17753 project.update(cx, |project, cx| {
17754 self.registered_buffers.insert(
17755 buffer_id,
17756 project.register_buffer_with_language_servers(&buffer, cx),
17757 );
17758 })
17759 }
17760 }
17761 }
17762 cx.emit(EditorEvent::BufferEdited);
17763 cx.emit(SearchEvent::MatchesInvalidated);
17764 if *singleton_buffer_edited {
17765 if let Some(project) = &self.project {
17766 #[allow(clippy::mutable_key_type)]
17767 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17768 multibuffer
17769 .all_buffers()
17770 .into_iter()
17771 .filter_map(|buffer| {
17772 buffer.update(cx, |buffer, cx| {
17773 let language = buffer.language()?;
17774 let should_discard = project.update(cx, |project, cx| {
17775 project.is_local()
17776 && !project.has_language_servers_for(buffer, cx)
17777 });
17778 should_discard.not().then_some(language.clone())
17779 })
17780 })
17781 .collect::<HashSet<_>>()
17782 });
17783 if !languages_affected.is_empty() {
17784 self.refresh_inlay_hints(
17785 InlayHintRefreshReason::BufferEdited(languages_affected),
17786 cx,
17787 );
17788 }
17789 }
17790 }
17791
17792 let Some(project) = &self.project else { return };
17793 let (telemetry, is_via_ssh) = {
17794 let project = project.read(cx);
17795 let telemetry = project.client().telemetry().clone();
17796 let is_via_ssh = project.is_via_ssh();
17797 (telemetry, is_via_ssh)
17798 };
17799 refresh_linked_ranges(self, window, cx);
17800 telemetry.log_edit_event("editor", is_via_ssh);
17801 }
17802 multi_buffer::Event::ExcerptsAdded {
17803 buffer,
17804 predecessor,
17805 excerpts,
17806 } => {
17807 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17808 let buffer_id = buffer.read(cx).remote_id();
17809 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17810 if let Some(project) = &self.project {
17811 update_uncommitted_diff_for_buffer(
17812 cx.entity(),
17813 project,
17814 [buffer.clone()],
17815 self.buffer.clone(),
17816 cx,
17817 )
17818 .detach();
17819 }
17820 }
17821 cx.emit(EditorEvent::ExcerptsAdded {
17822 buffer: buffer.clone(),
17823 predecessor: *predecessor,
17824 excerpts: excerpts.clone(),
17825 });
17826 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17827 }
17828 multi_buffer::Event::ExcerptsRemoved {
17829 ids,
17830 removed_buffer_ids,
17831 } => {
17832 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17833 let buffer = self.buffer.read(cx);
17834 self.registered_buffers
17835 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17836 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17837 cx.emit(EditorEvent::ExcerptsRemoved {
17838 ids: ids.clone(),
17839 removed_buffer_ids: removed_buffer_ids.clone(),
17840 })
17841 }
17842 multi_buffer::Event::ExcerptsEdited {
17843 excerpt_ids,
17844 buffer_ids,
17845 } => {
17846 self.display_map.update(cx, |map, cx| {
17847 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17848 });
17849 cx.emit(EditorEvent::ExcerptsEdited {
17850 ids: excerpt_ids.clone(),
17851 })
17852 }
17853 multi_buffer::Event::ExcerptsExpanded { ids } => {
17854 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17855 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17856 }
17857 multi_buffer::Event::Reparsed(buffer_id) => {
17858 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17859 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17860
17861 cx.emit(EditorEvent::Reparsed(*buffer_id));
17862 }
17863 multi_buffer::Event::DiffHunksToggled => {
17864 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17865 }
17866 multi_buffer::Event::LanguageChanged(buffer_id) => {
17867 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17868 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17869 cx.emit(EditorEvent::Reparsed(*buffer_id));
17870 cx.notify();
17871 }
17872 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17873 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17874 multi_buffer::Event::FileHandleChanged
17875 | multi_buffer::Event::Reloaded
17876 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17877 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17878 multi_buffer::Event::DiagnosticsUpdated => {
17879 self.refresh_active_diagnostics(cx);
17880 self.refresh_inline_diagnostics(true, window, cx);
17881 self.scrollbar_marker_state.dirty = true;
17882 cx.notify();
17883 }
17884 _ => {}
17885 };
17886 }
17887
17888 pub fn start_temporary_diff_override(&mut self) {
17889 self.load_diff_task.take();
17890 self.temporary_diff_override = true;
17891 }
17892
17893 pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17894 self.temporary_diff_override = false;
17895 self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17896 self.buffer.update(cx, |buffer, cx| {
17897 buffer.set_all_diff_hunks_collapsed(cx);
17898 });
17899
17900 if let Some(project) = self.project.clone() {
17901 self.load_diff_task = Some(
17902 update_uncommitted_diff_for_buffer(
17903 cx.entity(),
17904 &project,
17905 self.buffer.read(cx).all_buffers(),
17906 self.buffer.clone(),
17907 cx,
17908 )
17909 .shared(),
17910 );
17911 }
17912 }
17913
17914 fn on_display_map_changed(
17915 &mut self,
17916 _: Entity<DisplayMap>,
17917 _: &mut Window,
17918 cx: &mut Context<Self>,
17919 ) {
17920 cx.notify();
17921 }
17922
17923 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17924 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17925 self.update_edit_prediction_settings(cx);
17926 self.refresh_inline_completion(true, false, window, cx);
17927 self.refresh_inlay_hints(
17928 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17929 self.selections.newest_anchor().head(),
17930 &self.buffer.read(cx).snapshot(cx),
17931 cx,
17932 )),
17933 cx,
17934 );
17935
17936 let old_cursor_shape = self.cursor_shape;
17937
17938 {
17939 let editor_settings = EditorSettings::get_global(cx);
17940 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17941 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17942 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17943 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17944 }
17945
17946 if old_cursor_shape != self.cursor_shape {
17947 cx.emit(EditorEvent::CursorShapeChanged);
17948 }
17949
17950 let project_settings = ProjectSettings::get_global(cx);
17951 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17952
17953 if self.mode.is_full() {
17954 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17955 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17956 if self.show_inline_diagnostics != show_inline_diagnostics {
17957 self.show_inline_diagnostics = show_inline_diagnostics;
17958 self.refresh_inline_diagnostics(false, window, cx);
17959 }
17960
17961 if self.git_blame_inline_enabled != inline_blame_enabled {
17962 self.toggle_git_blame_inline_internal(false, window, cx);
17963 }
17964 }
17965
17966 cx.notify();
17967 }
17968
17969 pub fn set_searchable(&mut self, searchable: bool) {
17970 self.searchable = searchable;
17971 }
17972
17973 pub fn searchable(&self) -> bool {
17974 self.searchable
17975 }
17976
17977 fn open_proposed_changes_editor(
17978 &mut self,
17979 _: &OpenProposedChangesEditor,
17980 window: &mut Window,
17981 cx: &mut Context<Self>,
17982 ) {
17983 let Some(workspace) = self.workspace() else {
17984 cx.propagate();
17985 return;
17986 };
17987
17988 let selections = self.selections.all::<usize>(cx);
17989 let multi_buffer = self.buffer.read(cx);
17990 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17991 let mut new_selections_by_buffer = HashMap::default();
17992 for selection in selections {
17993 for (buffer, range, _) in
17994 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17995 {
17996 let mut range = range.to_point(buffer);
17997 range.start.column = 0;
17998 range.end.column = buffer.line_len(range.end.row);
17999 new_selections_by_buffer
18000 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18001 .or_insert(Vec::new())
18002 .push(range)
18003 }
18004 }
18005
18006 let proposed_changes_buffers = new_selections_by_buffer
18007 .into_iter()
18008 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18009 .collect::<Vec<_>>();
18010 let proposed_changes_editor = cx.new(|cx| {
18011 ProposedChangesEditor::new(
18012 "Proposed changes",
18013 proposed_changes_buffers,
18014 self.project.clone(),
18015 window,
18016 cx,
18017 )
18018 });
18019
18020 window.defer(cx, move |window, cx| {
18021 workspace.update(cx, |workspace, cx| {
18022 workspace.active_pane().update(cx, |pane, cx| {
18023 pane.add_item(
18024 Box::new(proposed_changes_editor),
18025 true,
18026 true,
18027 None,
18028 window,
18029 cx,
18030 );
18031 });
18032 });
18033 });
18034 }
18035
18036 pub fn open_excerpts_in_split(
18037 &mut self,
18038 _: &OpenExcerptsSplit,
18039 window: &mut Window,
18040 cx: &mut Context<Self>,
18041 ) {
18042 self.open_excerpts_common(None, true, window, cx)
18043 }
18044
18045 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18046 self.open_excerpts_common(None, false, window, cx)
18047 }
18048
18049 fn open_excerpts_common(
18050 &mut self,
18051 jump_data: Option<JumpData>,
18052 split: bool,
18053 window: &mut Window,
18054 cx: &mut Context<Self>,
18055 ) {
18056 let Some(workspace) = self.workspace() else {
18057 cx.propagate();
18058 return;
18059 };
18060
18061 if self.buffer.read(cx).is_singleton() {
18062 cx.propagate();
18063 return;
18064 }
18065
18066 let mut new_selections_by_buffer = HashMap::default();
18067 match &jump_data {
18068 Some(JumpData::MultiBufferPoint {
18069 excerpt_id,
18070 position,
18071 anchor,
18072 line_offset_from_top,
18073 }) => {
18074 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18075 if let Some(buffer) = multi_buffer_snapshot
18076 .buffer_id_for_excerpt(*excerpt_id)
18077 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18078 {
18079 let buffer_snapshot = buffer.read(cx).snapshot();
18080 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18081 language::ToPoint::to_point(anchor, &buffer_snapshot)
18082 } else {
18083 buffer_snapshot.clip_point(*position, Bias::Left)
18084 };
18085 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18086 new_selections_by_buffer.insert(
18087 buffer,
18088 (
18089 vec![jump_to_offset..jump_to_offset],
18090 Some(*line_offset_from_top),
18091 ),
18092 );
18093 }
18094 }
18095 Some(JumpData::MultiBufferRow {
18096 row,
18097 line_offset_from_top,
18098 }) => {
18099 let point = MultiBufferPoint::new(row.0, 0);
18100 if let Some((buffer, buffer_point, _)) =
18101 self.buffer.read(cx).point_to_buffer_point(point, cx)
18102 {
18103 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18104 new_selections_by_buffer
18105 .entry(buffer)
18106 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18107 .0
18108 .push(buffer_offset..buffer_offset)
18109 }
18110 }
18111 None => {
18112 let selections = self.selections.all::<usize>(cx);
18113 let multi_buffer = self.buffer.read(cx);
18114 for selection in selections {
18115 for (snapshot, range, _, anchor) in multi_buffer
18116 .snapshot(cx)
18117 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18118 {
18119 if let Some(anchor) = anchor {
18120 // selection is in a deleted hunk
18121 let Some(buffer_id) = anchor.buffer_id else {
18122 continue;
18123 };
18124 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18125 continue;
18126 };
18127 let offset = text::ToOffset::to_offset(
18128 &anchor.text_anchor,
18129 &buffer_handle.read(cx).snapshot(),
18130 );
18131 let range = offset..offset;
18132 new_selections_by_buffer
18133 .entry(buffer_handle)
18134 .or_insert((Vec::new(), None))
18135 .0
18136 .push(range)
18137 } else {
18138 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18139 else {
18140 continue;
18141 };
18142 new_selections_by_buffer
18143 .entry(buffer_handle)
18144 .or_insert((Vec::new(), None))
18145 .0
18146 .push(range)
18147 }
18148 }
18149 }
18150 }
18151 }
18152
18153 new_selections_by_buffer
18154 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18155
18156 if new_selections_by_buffer.is_empty() {
18157 return;
18158 }
18159
18160 // We defer the pane interaction because we ourselves are a workspace item
18161 // and activating a new item causes the pane to call a method on us reentrantly,
18162 // which panics if we're on the stack.
18163 window.defer(cx, move |window, cx| {
18164 workspace.update(cx, |workspace, cx| {
18165 let pane = if split {
18166 workspace.adjacent_pane(window, cx)
18167 } else {
18168 workspace.active_pane().clone()
18169 };
18170
18171 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18172 let editor = buffer
18173 .read(cx)
18174 .file()
18175 .is_none()
18176 .then(|| {
18177 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18178 // so `workspace.open_project_item` will never find them, always opening a new editor.
18179 // Instead, we try to activate the existing editor in the pane first.
18180 let (editor, pane_item_index) =
18181 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18182 let editor = item.downcast::<Editor>()?;
18183 let singleton_buffer =
18184 editor.read(cx).buffer().read(cx).as_singleton()?;
18185 if singleton_buffer == buffer {
18186 Some((editor, i))
18187 } else {
18188 None
18189 }
18190 })?;
18191 pane.update(cx, |pane, cx| {
18192 pane.activate_item(pane_item_index, true, true, window, cx)
18193 });
18194 Some(editor)
18195 })
18196 .flatten()
18197 .unwrap_or_else(|| {
18198 workspace.open_project_item::<Self>(
18199 pane.clone(),
18200 buffer,
18201 true,
18202 true,
18203 window,
18204 cx,
18205 )
18206 });
18207
18208 editor.update(cx, |editor, cx| {
18209 let autoscroll = match scroll_offset {
18210 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18211 None => Autoscroll::newest(),
18212 };
18213 let nav_history = editor.nav_history.take();
18214 editor.change_selections(Some(autoscroll), window, cx, |s| {
18215 s.select_ranges(ranges);
18216 });
18217 editor.nav_history = nav_history;
18218 });
18219 }
18220 })
18221 });
18222 }
18223
18224 // For now, don't allow opening excerpts in buffers that aren't backed by
18225 // regular project files.
18226 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18227 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18228 }
18229
18230 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18231 let snapshot = self.buffer.read(cx).read(cx);
18232 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18233 Some(
18234 ranges
18235 .iter()
18236 .map(move |range| {
18237 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18238 })
18239 .collect(),
18240 )
18241 }
18242
18243 fn selection_replacement_ranges(
18244 &self,
18245 range: Range<OffsetUtf16>,
18246 cx: &mut App,
18247 ) -> Vec<Range<OffsetUtf16>> {
18248 let selections = self.selections.all::<OffsetUtf16>(cx);
18249 let newest_selection = selections
18250 .iter()
18251 .max_by_key(|selection| selection.id)
18252 .unwrap();
18253 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18254 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18255 let snapshot = self.buffer.read(cx).read(cx);
18256 selections
18257 .into_iter()
18258 .map(|mut selection| {
18259 selection.start.0 =
18260 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18261 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18262 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18263 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18264 })
18265 .collect()
18266 }
18267
18268 fn report_editor_event(
18269 &self,
18270 event_type: &'static str,
18271 file_extension: Option<String>,
18272 cx: &App,
18273 ) {
18274 if cfg!(any(test, feature = "test-support")) {
18275 return;
18276 }
18277
18278 let Some(project) = &self.project else { return };
18279
18280 // If None, we are in a file without an extension
18281 let file = self
18282 .buffer
18283 .read(cx)
18284 .as_singleton()
18285 .and_then(|b| b.read(cx).file());
18286 let file_extension = file_extension.or(file
18287 .as_ref()
18288 .and_then(|file| Path::new(file.file_name(cx)).extension())
18289 .and_then(|e| e.to_str())
18290 .map(|a| a.to_string()));
18291
18292 let vim_mode = vim_enabled(cx);
18293
18294 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18295 let copilot_enabled = edit_predictions_provider
18296 == language::language_settings::EditPredictionProvider::Copilot;
18297 let copilot_enabled_for_language = self
18298 .buffer
18299 .read(cx)
18300 .language_settings(cx)
18301 .show_edit_predictions;
18302
18303 let project = project.read(cx);
18304 telemetry::event!(
18305 event_type,
18306 file_extension,
18307 vim_mode,
18308 copilot_enabled,
18309 copilot_enabled_for_language,
18310 edit_predictions_provider,
18311 is_via_ssh = project.is_via_ssh(),
18312 );
18313 }
18314
18315 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18316 /// with each line being an array of {text, highlight} objects.
18317 fn copy_highlight_json(
18318 &mut self,
18319 _: &CopyHighlightJson,
18320 window: &mut Window,
18321 cx: &mut Context<Self>,
18322 ) {
18323 #[derive(Serialize)]
18324 struct Chunk<'a> {
18325 text: String,
18326 highlight: Option<&'a str>,
18327 }
18328
18329 let snapshot = self.buffer.read(cx).snapshot(cx);
18330 let range = self
18331 .selected_text_range(false, window, cx)
18332 .and_then(|selection| {
18333 if selection.range.is_empty() {
18334 None
18335 } else {
18336 Some(selection.range)
18337 }
18338 })
18339 .unwrap_or_else(|| 0..snapshot.len());
18340
18341 let chunks = snapshot.chunks(range, true);
18342 let mut lines = Vec::new();
18343 let mut line: VecDeque<Chunk> = VecDeque::new();
18344
18345 let Some(style) = self.style.as_ref() else {
18346 return;
18347 };
18348
18349 for chunk in chunks {
18350 let highlight = chunk
18351 .syntax_highlight_id
18352 .and_then(|id| id.name(&style.syntax));
18353 let mut chunk_lines = chunk.text.split('\n').peekable();
18354 while let Some(text) = chunk_lines.next() {
18355 let mut merged_with_last_token = false;
18356 if let Some(last_token) = line.back_mut() {
18357 if last_token.highlight == highlight {
18358 last_token.text.push_str(text);
18359 merged_with_last_token = true;
18360 }
18361 }
18362
18363 if !merged_with_last_token {
18364 line.push_back(Chunk {
18365 text: text.into(),
18366 highlight,
18367 });
18368 }
18369
18370 if chunk_lines.peek().is_some() {
18371 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18372 line.pop_front();
18373 }
18374 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18375 line.pop_back();
18376 }
18377
18378 lines.push(mem::take(&mut line));
18379 }
18380 }
18381 }
18382
18383 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18384 return;
18385 };
18386 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18387 }
18388
18389 pub fn open_context_menu(
18390 &mut self,
18391 _: &OpenContextMenu,
18392 window: &mut Window,
18393 cx: &mut Context<Self>,
18394 ) {
18395 self.request_autoscroll(Autoscroll::newest(), cx);
18396 let position = self.selections.newest_display(cx).start;
18397 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18398 }
18399
18400 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18401 &self.inlay_hint_cache
18402 }
18403
18404 pub fn replay_insert_event(
18405 &mut self,
18406 text: &str,
18407 relative_utf16_range: Option<Range<isize>>,
18408 window: &mut Window,
18409 cx: &mut Context<Self>,
18410 ) {
18411 if !self.input_enabled {
18412 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18413 return;
18414 }
18415 if let Some(relative_utf16_range) = relative_utf16_range {
18416 let selections = self.selections.all::<OffsetUtf16>(cx);
18417 self.change_selections(None, window, cx, |s| {
18418 let new_ranges = selections.into_iter().map(|range| {
18419 let start = OffsetUtf16(
18420 range
18421 .head()
18422 .0
18423 .saturating_add_signed(relative_utf16_range.start),
18424 );
18425 let end = OffsetUtf16(
18426 range
18427 .head()
18428 .0
18429 .saturating_add_signed(relative_utf16_range.end),
18430 );
18431 start..end
18432 });
18433 s.select_ranges(new_ranges);
18434 });
18435 }
18436
18437 self.handle_input(text, window, cx);
18438 }
18439
18440 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18441 let Some(provider) = self.semantics_provider.as_ref() else {
18442 return false;
18443 };
18444
18445 let mut supports = false;
18446 self.buffer().update(cx, |this, cx| {
18447 this.for_each_buffer(|buffer| {
18448 supports |= provider.supports_inlay_hints(buffer, cx);
18449 });
18450 });
18451
18452 supports
18453 }
18454
18455 pub fn is_focused(&self, window: &Window) -> bool {
18456 self.focus_handle.is_focused(window)
18457 }
18458
18459 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18460 cx.emit(EditorEvent::Focused);
18461
18462 if let Some(descendant) = self
18463 .last_focused_descendant
18464 .take()
18465 .and_then(|descendant| descendant.upgrade())
18466 {
18467 window.focus(&descendant);
18468 } else {
18469 if let Some(blame) = self.blame.as_ref() {
18470 blame.update(cx, GitBlame::focus)
18471 }
18472
18473 self.blink_manager.update(cx, BlinkManager::enable);
18474 self.show_cursor_names(window, cx);
18475 self.buffer.update(cx, |buffer, cx| {
18476 buffer.finalize_last_transaction(cx);
18477 if self.leader_id.is_none() {
18478 buffer.set_active_selections(
18479 &self.selections.disjoint_anchors(),
18480 self.selections.line_mode,
18481 self.cursor_shape,
18482 cx,
18483 );
18484 }
18485 });
18486 }
18487 }
18488
18489 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18490 cx.emit(EditorEvent::FocusedIn)
18491 }
18492
18493 fn handle_focus_out(
18494 &mut self,
18495 event: FocusOutEvent,
18496 _window: &mut Window,
18497 cx: &mut Context<Self>,
18498 ) {
18499 if event.blurred != self.focus_handle {
18500 self.last_focused_descendant = Some(event.blurred);
18501 }
18502 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18503 }
18504
18505 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18506 self.blink_manager.update(cx, BlinkManager::disable);
18507 self.buffer
18508 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18509
18510 if let Some(blame) = self.blame.as_ref() {
18511 blame.update(cx, GitBlame::blur)
18512 }
18513 if !self.hover_state.focused(window, cx) {
18514 hide_hover(self, cx);
18515 }
18516 if !self
18517 .context_menu
18518 .borrow()
18519 .as_ref()
18520 .is_some_and(|context_menu| context_menu.focused(window, cx))
18521 {
18522 self.hide_context_menu(window, cx);
18523 }
18524 self.discard_inline_completion(false, cx);
18525 cx.emit(EditorEvent::Blurred);
18526 cx.notify();
18527 }
18528
18529 pub fn register_action<A: Action>(
18530 &mut self,
18531 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18532 ) -> Subscription {
18533 let id = self.next_editor_action_id.post_inc();
18534 let listener = Arc::new(listener);
18535 self.editor_actions.borrow_mut().insert(
18536 id,
18537 Box::new(move |window, _| {
18538 let listener = listener.clone();
18539 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18540 let action = action.downcast_ref().unwrap();
18541 if phase == DispatchPhase::Bubble {
18542 listener(action, window, cx)
18543 }
18544 })
18545 }),
18546 );
18547
18548 let editor_actions = self.editor_actions.clone();
18549 Subscription::new(move || {
18550 editor_actions.borrow_mut().remove(&id);
18551 })
18552 }
18553
18554 pub fn file_header_size(&self) -> u32 {
18555 FILE_HEADER_HEIGHT
18556 }
18557
18558 pub fn restore(
18559 &mut self,
18560 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18561 window: &mut Window,
18562 cx: &mut Context<Self>,
18563 ) {
18564 let workspace = self.workspace();
18565 let project = self.project.as_ref();
18566 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18567 let mut tasks = Vec::new();
18568 for (buffer_id, changes) in revert_changes {
18569 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18570 buffer.update(cx, |buffer, cx| {
18571 buffer.edit(
18572 changes
18573 .into_iter()
18574 .map(|(range, text)| (range, text.to_string())),
18575 None,
18576 cx,
18577 );
18578 });
18579
18580 if let Some(project) =
18581 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18582 {
18583 project.update(cx, |project, cx| {
18584 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18585 })
18586 }
18587 }
18588 }
18589 tasks
18590 });
18591 cx.spawn_in(window, async move |_, cx| {
18592 for (buffer, task) in save_tasks {
18593 let result = task.await;
18594 if result.is_err() {
18595 let Some(path) = buffer
18596 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18597 .ok()
18598 else {
18599 continue;
18600 };
18601 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18602 let Some(task) = cx
18603 .update_window_entity(&workspace, |workspace, window, cx| {
18604 workspace
18605 .open_path_preview(path, None, false, false, false, window, cx)
18606 })
18607 .ok()
18608 else {
18609 continue;
18610 };
18611 task.await.log_err();
18612 }
18613 }
18614 }
18615 })
18616 .detach();
18617 self.change_selections(None, window, cx, |selections| selections.refresh());
18618 }
18619
18620 pub fn to_pixel_point(
18621 &self,
18622 source: multi_buffer::Anchor,
18623 editor_snapshot: &EditorSnapshot,
18624 window: &mut Window,
18625 ) -> Option<gpui::Point<Pixels>> {
18626 let source_point = source.to_display_point(editor_snapshot);
18627 self.display_to_pixel_point(source_point, editor_snapshot, window)
18628 }
18629
18630 pub fn display_to_pixel_point(
18631 &self,
18632 source: DisplayPoint,
18633 editor_snapshot: &EditorSnapshot,
18634 window: &mut Window,
18635 ) -> Option<gpui::Point<Pixels>> {
18636 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18637 let text_layout_details = self.text_layout_details(window);
18638 let scroll_top = text_layout_details
18639 .scroll_anchor
18640 .scroll_position(editor_snapshot)
18641 .y;
18642
18643 if source.row().as_f32() < scroll_top.floor() {
18644 return None;
18645 }
18646 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18647 let source_y = line_height * (source.row().as_f32() - scroll_top);
18648 Some(gpui::Point::new(source_x, source_y))
18649 }
18650
18651 pub fn has_visible_completions_menu(&self) -> bool {
18652 !self.edit_prediction_preview_is_active()
18653 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18654 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18655 })
18656 }
18657
18658 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18659 self.addons
18660 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18661 }
18662
18663 pub fn unregister_addon<T: Addon>(&mut self) {
18664 self.addons.remove(&std::any::TypeId::of::<T>());
18665 }
18666
18667 pub fn addon<T: Addon>(&self) -> Option<&T> {
18668 let type_id = std::any::TypeId::of::<T>();
18669 self.addons
18670 .get(&type_id)
18671 .and_then(|item| item.to_any().downcast_ref::<T>())
18672 }
18673
18674 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18675 let type_id = std::any::TypeId::of::<T>();
18676 self.addons
18677 .get_mut(&type_id)
18678 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18679 }
18680
18681 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18682 let text_layout_details = self.text_layout_details(window);
18683 let style = &text_layout_details.editor_style;
18684 let font_id = window.text_system().resolve_font(&style.text.font());
18685 let font_size = style.text.font_size.to_pixels(window.rem_size());
18686 let line_height = style.text.line_height_in_pixels(window.rem_size());
18687 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18688
18689 gpui::Size::new(em_width, line_height)
18690 }
18691
18692 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18693 self.load_diff_task.clone()
18694 }
18695
18696 fn read_metadata_from_db(
18697 &mut self,
18698 item_id: u64,
18699 workspace_id: WorkspaceId,
18700 window: &mut Window,
18701 cx: &mut Context<Editor>,
18702 ) {
18703 if self.is_singleton(cx)
18704 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18705 {
18706 let buffer_snapshot = OnceCell::new();
18707
18708 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18709 if !folds.is_empty() {
18710 let snapshot =
18711 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18712 self.fold_ranges(
18713 folds
18714 .into_iter()
18715 .map(|(start, end)| {
18716 snapshot.clip_offset(start, Bias::Left)
18717 ..snapshot.clip_offset(end, Bias::Right)
18718 })
18719 .collect(),
18720 false,
18721 window,
18722 cx,
18723 );
18724 }
18725 }
18726
18727 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18728 if !selections.is_empty() {
18729 let snapshot =
18730 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18731 self.change_selections(None, window, cx, |s| {
18732 s.select_ranges(selections.into_iter().map(|(start, end)| {
18733 snapshot.clip_offset(start, Bias::Left)
18734 ..snapshot.clip_offset(end, Bias::Right)
18735 }));
18736 });
18737 }
18738 };
18739 }
18740
18741 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18742 }
18743}
18744
18745fn vim_enabled(cx: &App) -> bool {
18746 cx.global::<SettingsStore>()
18747 .raw_user_settings()
18748 .get("vim_mode")
18749 == Some(&serde_json::Value::Bool(true))
18750}
18751
18752// Consider user intent and default settings
18753fn choose_completion_range(
18754 completion: &Completion,
18755 intent: CompletionIntent,
18756 buffer: &Entity<Buffer>,
18757 cx: &mut Context<Editor>,
18758) -> Range<usize> {
18759 fn should_replace(
18760 completion: &Completion,
18761 insert_range: &Range<text::Anchor>,
18762 intent: CompletionIntent,
18763 completion_mode_setting: LspInsertMode,
18764 buffer: &Buffer,
18765 ) -> bool {
18766 // specific actions take precedence over settings
18767 match intent {
18768 CompletionIntent::CompleteWithInsert => return false,
18769 CompletionIntent::CompleteWithReplace => return true,
18770 CompletionIntent::Complete | CompletionIntent::Compose => {}
18771 }
18772
18773 match completion_mode_setting {
18774 LspInsertMode::Insert => false,
18775 LspInsertMode::Replace => true,
18776 LspInsertMode::ReplaceSubsequence => {
18777 let mut text_to_replace = buffer.chars_for_range(
18778 buffer.anchor_before(completion.replace_range.start)
18779 ..buffer.anchor_after(completion.replace_range.end),
18780 );
18781 let mut completion_text = completion.new_text.chars();
18782
18783 // is `text_to_replace` a subsequence of `completion_text`
18784 text_to_replace
18785 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18786 }
18787 LspInsertMode::ReplaceSuffix => {
18788 let range_after_cursor = insert_range.end..completion.replace_range.end;
18789
18790 let text_after_cursor = buffer
18791 .text_for_range(
18792 buffer.anchor_before(range_after_cursor.start)
18793 ..buffer.anchor_after(range_after_cursor.end),
18794 )
18795 .collect::<String>();
18796 completion.new_text.ends_with(&text_after_cursor)
18797 }
18798 }
18799 }
18800
18801 let buffer = buffer.read(cx);
18802
18803 if let CompletionSource::Lsp {
18804 insert_range: Some(insert_range),
18805 ..
18806 } = &completion.source
18807 {
18808 let completion_mode_setting =
18809 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18810 .completions
18811 .lsp_insert_mode;
18812
18813 if !should_replace(
18814 completion,
18815 &insert_range,
18816 intent,
18817 completion_mode_setting,
18818 buffer,
18819 ) {
18820 return insert_range.to_offset(buffer);
18821 }
18822 }
18823
18824 completion.replace_range.to_offset(buffer)
18825}
18826
18827fn insert_extra_newline_brackets(
18828 buffer: &MultiBufferSnapshot,
18829 range: Range<usize>,
18830 language: &language::LanguageScope,
18831) -> bool {
18832 let leading_whitespace_len = buffer
18833 .reversed_chars_at(range.start)
18834 .take_while(|c| c.is_whitespace() && *c != '\n')
18835 .map(|c| c.len_utf8())
18836 .sum::<usize>();
18837 let trailing_whitespace_len = buffer
18838 .chars_at(range.end)
18839 .take_while(|c| c.is_whitespace() && *c != '\n')
18840 .map(|c| c.len_utf8())
18841 .sum::<usize>();
18842 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18843
18844 language.brackets().any(|(pair, enabled)| {
18845 let pair_start = pair.start.trim_end();
18846 let pair_end = pair.end.trim_start();
18847
18848 enabled
18849 && pair.newline
18850 && buffer.contains_str_at(range.end, pair_end)
18851 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18852 })
18853}
18854
18855fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18856 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18857 [(buffer, range, _)] => (*buffer, range.clone()),
18858 _ => return false,
18859 };
18860 let pair = {
18861 let mut result: Option<BracketMatch> = None;
18862
18863 for pair in buffer
18864 .all_bracket_ranges(range.clone())
18865 .filter(move |pair| {
18866 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18867 })
18868 {
18869 let len = pair.close_range.end - pair.open_range.start;
18870
18871 if let Some(existing) = &result {
18872 let existing_len = existing.close_range.end - existing.open_range.start;
18873 if len > existing_len {
18874 continue;
18875 }
18876 }
18877
18878 result = Some(pair);
18879 }
18880
18881 result
18882 };
18883 let Some(pair) = pair else {
18884 return false;
18885 };
18886 pair.newline_only
18887 && buffer
18888 .chars_for_range(pair.open_range.end..range.start)
18889 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18890 .all(|c| c.is_whitespace() && c != '\n')
18891}
18892
18893fn update_uncommitted_diff_for_buffer(
18894 editor: Entity<Editor>,
18895 project: &Entity<Project>,
18896 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18897 buffer: Entity<MultiBuffer>,
18898 cx: &mut App,
18899) -> Task<()> {
18900 let mut tasks = Vec::new();
18901 project.update(cx, |project, cx| {
18902 for buffer in buffers {
18903 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18904 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18905 }
18906 }
18907 });
18908 cx.spawn(async move |cx| {
18909 let diffs = future::join_all(tasks).await;
18910 if editor
18911 .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18912 .unwrap_or(false)
18913 {
18914 return;
18915 }
18916
18917 buffer
18918 .update(cx, |buffer, cx| {
18919 for diff in diffs.into_iter().flatten() {
18920 buffer.add_diff(diff, cx);
18921 }
18922 })
18923 .ok();
18924 })
18925}
18926
18927fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18928 let tab_size = tab_size.get() as usize;
18929 let mut width = offset;
18930
18931 for ch in text.chars() {
18932 width += if ch == '\t' {
18933 tab_size - (width % tab_size)
18934 } else {
18935 1
18936 };
18937 }
18938
18939 width - offset
18940}
18941
18942#[cfg(test)]
18943mod tests {
18944 use super::*;
18945
18946 #[test]
18947 fn test_string_size_with_expanded_tabs() {
18948 let nz = |val| NonZeroU32::new(val).unwrap();
18949 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18950 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18951 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18952 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18953 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18954 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18955 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18956 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18957 }
18958}
18959
18960/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18961struct WordBreakingTokenizer<'a> {
18962 input: &'a str,
18963}
18964
18965impl<'a> WordBreakingTokenizer<'a> {
18966 fn new(input: &'a str) -> Self {
18967 Self { input }
18968 }
18969}
18970
18971fn is_char_ideographic(ch: char) -> bool {
18972 use unicode_script::Script::*;
18973 use unicode_script::UnicodeScript;
18974 matches!(ch.script(), Han | Tangut | Yi)
18975}
18976
18977fn is_grapheme_ideographic(text: &str) -> bool {
18978 text.chars().any(is_char_ideographic)
18979}
18980
18981fn is_grapheme_whitespace(text: &str) -> bool {
18982 text.chars().any(|x| x.is_whitespace())
18983}
18984
18985fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18986 text.chars().next().map_or(false, |ch| {
18987 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18988 })
18989}
18990
18991#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18992enum WordBreakToken<'a> {
18993 Word { token: &'a str, grapheme_len: usize },
18994 InlineWhitespace { token: &'a str, grapheme_len: usize },
18995 Newline,
18996}
18997
18998impl<'a> Iterator for WordBreakingTokenizer<'a> {
18999 /// Yields a span, the count of graphemes in the token, and whether it was
19000 /// whitespace. Note that it also breaks at word boundaries.
19001 type Item = WordBreakToken<'a>;
19002
19003 fn next(&mut self) -> Option<Self::Item> {
19004 use unicode_segmentation::UnicodeSegmentation;
19005 if self.input.is_empty() {
19006 return None;
19007 }
19008
19009 let mut iter = self.input.graphemes(true).peekable();
19010 let mut offset = 0;
19011 let mut grapheme_len = 0;
19012 if let Some(first_grapheme) = iter.next() {
19013 let is_newline = first_grapheme == "\n";
19014 let is_whitespace = is_grapheme_whitespace(first_grapheme);
19015 offset += first_grapheme.len();
19016 grapheme_len += 1;
19017 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19018 if let Some(grapheme) = iter.peek().copied() {
19019 if should_stay_with_preceding_ideograph(grapheme) {
19020 offset += grapheme.len();
19021 grapheme_len += 1;
19022 }
19023 }
19024 } else {
19025 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19026 let mut next_word_bound = words.peek().copied();
19027 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19028 next_word_bound = words.next();
19029 }
19030 while let Some(grapheme) = iter.peek().copied() {
19031 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19032 break;
19033 };
19034 if is_grapheme_whitespace(grapheme) != is_whitespace
19035 || (grapheme == "\n") != is_newline
19036 {
19037 break;
19038 };
19039 offset += grapheme.len();
19040 grapheme_len += 1;
19041 iter.next();
19042 }
19043 }
19044 let token = &self.input[..offset];
19045 self.input = &self.input[offset..];
19046 if token == "\n" {
19047 Some(WordBreakToken::Newline)
19048 } else if is_whitespace {
19049 Some(WordBreakToken::InlineWhitespace {
19050 token,
19051 grapheme_len,
19052 })
19053 } else {
19054 Some(WordBreakToken::Word {
19055 token,
19056 grapheme_len,
19057 })
19058 }
19059 } else {
19060 None
19061 }
19062 }
19063}
19064
19065#[test]
19066fn test_word_breaking_tokenizer() {
19067 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19068 ("", &[]),
19069 (" ", &[whitespace(" ", 2)]),
19070 ("Ʒ", &[word("Ʒ", 1)]),
19071 ("Ǽ", &[word("Ǽ", 1)]),
19072 ("⋑", &[word("⋑", 1)]),
19073 ("⋑⋑", &[word("⋑⋑", 2)]),
19074 (
19075 "原理,进而",
19076 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19077 ),
19078 (
19079 "hello world",
19080 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19081 ),
19082 (
19083 "hello, world",
19084 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19085 ),
19086 (
19087 " hello world",
19088 &[
19089 whitespace(" ", 2),
19090 word("hello", 5),
19091 whitespace(" ", 1),
19092 word("world", 5),
19093 ],
19094 ),
19095 (
19096 "这是什么 \n 钢笔",
19097 &[
19098 word("这", 1),
19099 word("是", 1),
19100 word("什", 1),
19101 word("么", 1),
19102 whitespace(" ", 1),
19103 newline(),
19104 whitespace(" ", 1),
19105 word("钢", 1),
19106 word("笔", 1),
19107 ],
19108 ),
19109 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19110 ];
19111
19112 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19113 WordBreakToken::Word {
19114 token,
19115 grapheme_len,
19116 }
19117 }
19118
19119 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19120 WordBreakToken::InlineWhitespace {
19121 token,
19122 grapheme_len,
19123 }
19124 }
19125
19126 fn newline() -> WordBreakToken<'static> {
19127 WordBreakToken::Newline
19128 }
19129
19130 for (input, result) in tests {
19131 assert_eq!(
19132 WordBreakingTokenizer::new(input)
19133 .collect::<Vec<_>>()
19134 .as_slice(),
19135 *result,
19136 );
19137 }
19138}
19139
19140fn wrap_with_prefix(
19141 line_prefix: String,
19142 unwrapped_text: String,
19143 wrap_column: usize,
19144 tab_size: NonZeroU32,
19145 preserve_existing_whitespace: bool,
19146) -> String {
19147 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19148 let mut wrapped_text = String::new();
19149 let mut current_line = line_prefix.clone();
19150
19151 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19152 let mut current_line_len = line_prefix_len;
19153 let mut in_whitespace = false;
19154 for token in tokenizer {
19155 let have_preceding_whitespace = in_whitespace;
19156 match token {
19157 WordBreakToken::Word {
19158 token,
19159 grapheme_len,
19160 } => {
19161 in_whitespace = false;
19162 if current_line_len + grapheme_len > wrap_column
19163 && current_line_len != line_prefix_len
19164 {
19165 wrapped_text.push_str(current_line.trim_end());
19166 wrapped_text.push('\n');
19167 current_line.truncate(line_prefix.len());
19168 current_line_len = line_prefix_len;
19169 }
19170 current_line.push_str(token);
19171 current_line_len += grapheme_len;
19172 }
19173 WordBreakToken::InlineWhitespace {
19174 mut token,
19175 mut grapheme_len,
19176 } => {
19177 in_whitespace = true;
19178 if have_preceding_whitespace && !preserve_existing_whitespace {
19179 continue;
19180 }
19181 if !preserve_existing_whitespace {
19182 token = " ";
19183 grapheme_len = 1;
19184 }
19185 if current_line_len + grapheme_len > wrap_column {
19186 wrapped_text.push_str(current_line.trim_end());
19187 wrapped_text.push('\n');
19188 current_line.truncate(line_prefix.len());
19189 current_line_len = line_prefix_len;
19190 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19191 current_line.push_str(token);
19192 current_line_len += grapheme_len;
19193 }
19194 }
19195 WordBreakToken::Newline => {
19196 in_whitespace = true;
19197 if preserve_existing_whitespace {
19198 wrapped_text.push_str(current_line.trim_end());
19199 wrapped_text.push('\n');
19200 current_line.truncate(line_prefix.len());
19201 current_line_len = line_prefix_len;
19202 } else if have_preceding_whitespace {
19203 continue;
19204 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19205 {
19206 wrapped_text.push_str(current_line.trim_end());
19207 wrapped_text.push('\n');
19208 current_line.truncate(line_prefix.len());
19209 current_line_len = line_prefix_len;
19210 } else if current_line_len != line_prefix_len {
19211 current_line.push(' ');
19212 current_line_len += 1;
19213 }
19214 }
19215 }
19216 }
19217
19218 if !current_line.is_empty() {
19219 wrapped_text.push_str(¤t_line);
19220 }
19221 wrapped_text
19222}
19223
19224#[test]
19225fn test_wrap_with_prefix() {
19226 assert_eq!(
19227 wrap_with_prefix(
19228 "# ".to_string(),
19229 "abcdefg".to_string(),
19230 4,
19231 NonZeroU32::new(4).unwrap(),
19232 false,
19233 ),
19234 "# abcdefg"
19235 );
19236 assert_eq!(
19237 wrap_with_prefix(
19238 "".to_string(),
19239 "\thello world".to_string(),
19240 8,
19241 NonZeroU32::new(4).unwrap(),
19242 false,
19243 ),
19244 "hello\nworld"
19245 );
19246 assert_eq!(
19247 wrap_with_prefix(
19248 "// ".to_string(),
19249 "xx \nyy zz aa bb cc".to_string(),
19250 12,
19251 NonZeroU32::new(4).unwrap(),
19252 false,
19253 ),
19254 "// xx yy zz\n// aa bb cc"
19255 );
19256 assert_eq!(
19257 wrap_with_prefix(
19258 String::new(),
19259 "这是什么 \n 钢笔".to_string(),
19260 3,
19261 NonZeroU32::new(4).unwrap(),
19262 false,
19263 ),
19264 "这是什\n么 钢\n笔"
19265 );
19266}
19267
19268pub trait CollaborationHub {
19269 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19270 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19271 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19272}
19273
19274impl CollaborationHub for Entity<Project> {
19275 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19276 self.read(cx).collaborators()
19277 }
19278
19279 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19280 self.read(cx).user_store().read(cx).participant_indices()
19281 }
19282
19283 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19284 let this = self.read(cx);
19285 let user_ids = this.collaborators().values().map(|c| c.user_id);
19286 this.user_store().read_with(cx, |user_store, cx| {
19287 user_store.participant_names(user_ids, cx)
19288 })
19289 }
19290}
19291
19292pub trait SemanticsProvider {
19293 fn hover(
19294 &self,
19295 buffer: &Entity<Buffer>,
19296 position: text::Anchor,
19297 cx: &mut App,
19298 ) -> Option<Task<Vec<project::Hover>>>;
19299
19300 fn inline_values(
19301 &self,
19302 buffer_handle: Entity<Buffer>,
19303 range: Range<text::Anchor>,
19304 cx: &mut App,
19305 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19306
19307 fn inlay_hints(
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 resolve_inlay_hint(
19315 &self,
19316 hint: InlayHint,
19317 buffer_handle: Entity<Buffer>,
19318 server_id: LanguageServerId,
19319 cx: &mut App,
19320 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19321
19322 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19323
19324 fn document_highlights(
19325 &self,
19326 buffer: &Entity<Buffer>,
19327 position: text::Anchor,
19328 cx: &mut App,
19329 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19330
19331 fn definitions(
19332 &self,
19333 buffer: &Entity<Buffer>,
19334 position: text::Anchor,
19335 kind: GotoDefinitionKind,
19336 cx: &mut App,
19337 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19338
19339 fn range_for_rename(
19340 &self,
19341 buffer: &Entity<Buffer>,
19342 position: text::Anchor,
19343 cx: &mut App,
19344 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19345
19346 fn perform_rename(
19347 &self,
19348 buffer: &Entity<Buffer>,
19349 position: text::Anchor,
19350 new_name: String,
19351 cx: &mut App,
19352 ) -> Option<Task<Result<ProjectTransaction>>>;
19353}
19354
19355pub trait CompletionProvider {
19356 fn completions(
19357 &self,
19358 excerpt_id: ExcerptId,
19359 buffer: &Entity<Buffer>,
19360 buffer_position: text::Anchor,
19361 trigger: CompletionContext,
19362 window: &mut Window,
19363 cx: &mut Context<Editor>,
19364 ) -> Task<Result<Option<Vec<Completion>>>>;
19365
19366 fn resolve_completions(
19367 &self,
19368 buffer: Entity<Buffer>,
19369 completion_indices: Vec<usize>,
19370 completions: Rc<RefCell<Box<[Completion]>>>,
19371 cx: &mut Context<Editor>,
19372 ) -> Task<Result<bool>>;
19373
19374 fn apply_additional_edits_for_completion(
19375 &self,
19376 _buffer: Entity<Buffer>,
19377 _completions: Rc<RefCell<Box<[Completion]>>>,
19378 _completion_index: usize,
19379 _push_to_history: bool,
19380 _cx: &mut Context<Editor>,
19381 ) -> Task<Result<Option<language::Transaction>>> {
19382 Task::ready(Ok(None))
19383 }
19384
19385 fn is_completion_trigger(
19386 &self,
19387 buffer: &Entity<Buffer>,
19388 position: language::Anchor,
19389 text: &str,
19390 trigger_in_words: bool,
19391 cx: &mut Context<Editor>,
19392 ) -> bool;
19393
19394 fn sort_completions(&self) -> bool {
19395 true
19396 }
19397
19398 fn filter_completions(&self) -> bool {
19399 true
19400 }
19401}
19402
19403pub trait CodeActionProvider {
19404 fn id(&self) -> Arc<str>;
19405
19406 fn code_actions(
19407 &self,
19408 buffer: &Entity<Buffer>,
19409 range: Range<text::Anchor>,
19410 window: &mut Window,
19411 cx: &mut App,
19412 ) -> Task<Result<Vec<CodeAction>>>;
19413
19414 fn apply_code_action(
19415 &self,
19416 buffer_handle: Entity<Buffer>,
19417 action: CodeAction,
19418 excerpt_id: ExcerptId,
19419 push_to_history: bool,
19420 window: &mut Window,
19421 cx: &mut App,
19422 ) -> Task<Result<ProjectTransaction>>;
19423}
19424
19425impl CodeActionProvider for Entity<Project> {
19426 fn id(&self) -> Arc<str> {
19427 "project".into()
19428 }
19429
19430 fn code_actions(
19431 &self,
19432 buffer: &Entity<Buffer>,
19433 range: Range<text::Anchor>,
19434 _window: &mut Window,
19435 cx: &mut App,
19436 ) -> Task<Result<Vec<CodeAction>>> {
19437 self.update(cx, |project, cx| {
19438 let code_lens = project.code_lens(buffer, range.clone(), cx);
19439 let code_actions = project.code_actions(buffer, range, None, cx);
19440 cx.background_spawn(async move {
19441 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19442 Ok(code_lens
19443 .context("code lens fetch")?
19444 .into_iter()
19445 .chain(code_actions.context("code action fetch")?)
19446 .collect())
19447 })
19448 })
19449 }
19450
19451 fn apply_code_action(
19452 &self,
19453 buffer_handle: Entity<Buffer>,
19454 action: CodeAction,
19455 _excerpt_id: ExcerptId,
19456 push_to_history: bool,
19457 _window: &mut Window,
19458 cx: &mut App,
19459 ) -> Task<Result<ProjectTransaction>> {
19460 self.update(cx, |project, cx| {
19461 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19462 })
19463 }
19464}
19465
19466fn snippet_completions(
19467 project: &Project,
19468 buffer: &Entity<Buffer>,
19469 buffer_position: text::Anchor,
19470 cx: &mut App,
19471) -> Task<Result<Vec<Completion>>> {
19472 let languages = buffer.read(cx).languages_at(buffer_position);
19473 let snippet_store = project.snippets().read(cx);
19474
19475 let scopes: Vec<_> = languages
19476 .iter()
19477 .filter_map(|language| {
19478 let language_name = language.lsp_id();
19479 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19480
19481 if snippets.is_empty() {
19482 None
19483 } else {
19484 Some((language.default_scope(), snippets))
19485 }
19486 })
19487 .collect();
19488
19489 if scopes.is_empty() {
19490 return Task::ready(Ok(vec![]));
19491 }
19492
19493 let snapshot = buffer.read(cx).text_snapshot();
19494 let chars: String = snapshot
19495 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19496 .collect();
19497 let executor = cx.background_executor().clone();
19498
19499 cx.background_spawn(async move {
19500 let mut all_results: Vec<Completion> = Vec::new();
19501 for (scope, snippets) in scopes.into_iter() {
19502 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19503 let mut last_word = chars
19504 .chars()
19505 .take_while(|c| classifier.is_word(*c))
19506 .collect::<String>();
19507 last_word = last_word.chars().rev().collect();
19508
19509 if last_word.is_empty() {
19510 return Ok(vec![]);
19511 }
19512
19513 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19514 let to_lsp = |point: &text::Anchor| {
19515 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19516 point_to_lsp(end)
19517 };
19518 let lsp_end = to_lsp(&buffer_position);
19519
19520 let candidates = snippets
19521 .iter()
19522 .enumerate()
19523 .flat_map(|(ix, snippet)| {
19524 snippet
19525 .prefix
19526 .iter()
19527 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19528 })
19529 .collect::<Vec<StringMatchCandidate>>();
19530
19531 let mut matches = fuzzy::match_strings(
19532 &candidates,
19533 &last_word,
19534 last_word.chars().any(|c| c.is_uppercase()),
19535 100,
19536 &Default::default(),
19537 executor.clone(),
19538 )
19539 .await;
19540
19541 // Remove all candidates where the query's start does not match the start of any word in the candidate
19542 if let Some(query_start) = last_word.chars().next() {
19543 matches.retain(|string_match| {
19544 split_words(&string_match.string).any(|word| {
19545 // Check that the first codepoint of the word as lowercase matches the first
19546 // codepoint of the query as lowercase
19547 word.chars()
19548 .flat_map(|codepoint| codepoint.to_lowercase())
19549 .zip(query_start.to_lowercase())
19550 .all(|(word_cp, query_cp)| word_cp == query_cp)
19551 })
19552 });
19553 }
19554
19555 let matched_strings = matches
19556 .into_iter()
19557 .map(|m| m.string)
19558 .collect::<HashSet<_>>();
19559
19560 let mut result: Vec<Completion> = snippets
19561 .iter()
19562 .filter_map(|snippet| {
19563 let matching_prefix = snippet
19564 .prefix
19565 .iter()
19566 .find(|prefix| matched_strings.contains(*prefix))?;
19567 let start = as_offset - last_word.len();
19568 let start = snapshot.anchor_before(start);
19569 let range = start..buffer_position;
19570 let lsp_start = to_lsp(&start);
19571 let lsp_range = lsp::Range {
19572 start: lsp_start,
19573 end: lsp_end,
19574 };
19575 Some(Completion {
19576 replace_range: range,
19577 new_text: snippet.body.clone(),
19578 source: CompletionSource::Lsp {
19579 insert_range: None,
19580 server_id: LanguageServerId(usize::MAX),
19581 resolved: true,
19582 lsp_completion: Box::new(lsp::CompletionItem {
19583 label: snippet.prefix.first().unwrap().clone(),
19584 kind: Some(CompletionItemKind::SNIPPET),
19585 label_details: snippet.description.as_ref().map(|description| {
19586 lsp::CompletionItemLabelDetails {
19587 detail: Some(description.clone()),
19588 description: None,
19589 }
19590 }),
19591 insert_text_format: Some(InsertTextFormat::SNIPPET),
19592 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19593 lsp::InsertReplaceEdit {
19594 new_text: snippet.body.clone(),
19595 insert: lsp_range,
19596 replace: lsp_range,
19597 },
19598 )),
19599 filter_text: Some(snippet.body.clone()),
19600 sort_text: Some(char::MAX.to_string()),
19601 ..lsp::CompletionItem::default()
19602 }),
19603 lsp_defaults: None,
19604 },
19605 label: CodeLabel {
19606 text: matching_prefix.clone(),
19607 runs: Vec::new(),
19608 filter_range: 0..matching_prefix.len(),
19609 },
19610 icon_path: None,
19611 documentation: snippet.description.clone().map(|description| {
19612 CompletionDocumentation::SingleLine(description.into())
19613 }),
19614 insert_text_mode: None,
19615 confirm: None,
19616 })
19617 })
19618 .collect();
19619
19620 all_results.append(&mut result);
19621 }
19622
19623 Ok(all_results)
19624 })
19625}
19626
19627impl CompletionProvider for Entity<Project> {
19628 fn completions(
19629 &self,
19630 _excerpt_id: ExcerptId,
19631 buffer: &Entity<Buffer>,
19632 buffer_position: text::Anchor,
19633 options: CompletionContext,
19634 _window: &mut Window,
19635 cx: &mut Context<Editor>,
19636 ) -> Task<Result<Option<Vec<Completion>>>> {
19637 self.update(cx, |project, cx| {
19638 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19639 let project_completions = project.completions(buffer, buffer_position, options, cx);
19640 cx.background_spawn(async move {
19641 let snippets_completions = snippets.await?;
19642 match project_completions.await? {
19643 Some(mut completions) => {
19644 completions.extend(snippets_completions);
19645 Ok(Some(completions))
19646 }
19647 None => {
19648 if snippets_completions.is_empty() {
19649 Ok(None)
19650 } else {
19651 Ok(Some(snippets_completions))
19652 }
19653 }
19654 }
19655 })
19656 })
19657 }
19658
19659 fn resolve_completions(
19660 &self,
19661 buffer: Entity<Buffer>,
19662 completion_indices: Vec<usize>,
19663 completions: Rc<RefCell<Box<[Completion]>>>,
19664 cx: &mut Context<Editor>,
19665 ) -> Task<Result<bool>> {
19666 self.update(cx, |project, cx| {
19667 project.lsp_store().update(cx, |lsp_store, cx| {
19668 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19669 })
19670 })
19671 }
19672
19673 fn apply_additional_edits_for_completion(
19674 &self,
19675 buffer: Entity<Buffer>,
19676 completions: Rc<RefCell<Box<[Completion]>>>,
19677 completion_index: usize,
19678 push_to_history: bool,
19679 cx: &mut Context<Editor>,
19680 ) -> Task<Result<Option<language::Transaction>>> {
19681 self.update(cx, |project, cx| {
19682 project.lsp_store().update(cx, |lsp_store, cx| {
19683 lsp_store.apply_additional_edits_for_completion(
19684 buffer,
19685 completions,
19686 completion_index,
19687 push_to_history,
19688 cx,
19689 )
19690 })
19691 })
19692 }
19693
19694 fn is_completion_trigger(
19695 &self,
19696 buffer: &Entity<Buffer>,
19697 position: language::Anchor,
19698 text: &str,
19699 trigger_in_words: bool,
19700 cx: &mut Context<Editor>,
19701 ) -> bool {
19702 let mut chars = text.chars();
19703 let char = if let Some(char) = chars.next() {
19704 char
19705 } else {
19706 return false;
19707 };
19708 if chars.next().is_some() {
19709 return false;
19710 }
19711
19712 let buffer = buffer.read(cx);
19713 let snapshot = buffer.snapshot();
19714 if !snapshot.settings_at(position, cx).show_completions_on_input {
19715 return false;
19716 }
19717 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19718 if trigger_in_words && classifier.is_word(char) {
19719 return true;
19720 }
19721
19722 buffer.completion_triggers().contains(text)
19723 }
19724}
19725
19726impl SemanticsProvider for Entity<Project> {
19727 fn hover(
19728 &self,
19729 buffer: &Entity<Buffer>,
19730 position: text::Anchor,
19731 cx: &mut App,
19732 ) -> Option<Task<Vec<project::Hover>>> {
19733 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19734 }
19735
19736 fn document_highlights(
19737 &self,
19738 buffer: &Entity<Buffer>,
19739 position: text::Anchor,
19740 cx: &mut App,
19741 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19742 Some(self.update(cx, |project, cx| {
19743 project.document_highlights(buffer, position, cx)
19744 }))
19745 }
19746
19747 fn definitions(
19748 &self,
19749 buffer: &Entity<Buffer>,
19750 position: text::Anchor,
19751 kind: GotoDefinitionKind,
19752 cx: &mut App,
19753 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19754 Some(self.update(cx, |project, cx| match kind {
19755 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19756 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19757 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19758 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19759 }))
19760 }
19761
19762 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19763 // TODO: make this work for remote projects
19764 self.update(cx, |project, cx| {
19765 if project
19766 .active_debug_session(cx)
19767 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19768 {
19769 return true;
19770 }
19771
19772 buffer.update(cx, |buffer, cx| {
19773 project.any_language_server_supports_inlay_hints(buffer, cx)
19774 })
19775 })
19776 }
19777
19778 fn inline_values(
19779 &self,
19780 buffer_handle: Entity<Buffer>,
19781 range: Range<text::Anchor>,
19782 cx: &mut App,
19783 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19784 self.update(cx, |project, cx| {
19785 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19786
19787 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19788 })
19789 }
19790
19791 fn inlay_hints(
19792 &self,
19793 buffer_handle: Entity<Buffer>,
19794 range: Range<text::Anchor>,
19795 cx: &mut App,
19796 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19797 Some(self.update(cx, |project, cx| {
19798 project.inlay_hints(buffer_handle, range, cx)
19799 }))
19800 }
19801
19802 fn resolve_inlay_hint(
19803 &self,
19804 hint: InlayHint,
19805 buffer_handle: Entity<Buffer>,
19806 server_id: LanguageServerId,
19807 cx: &mut App,
19808 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19809 Some(self.update(cx, |project, cx| {
19810 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19811 }))
19812 }
19813
19814 fn range_for_rename(
19815 &self,
19816 buffer: &Entity<Buffer>,
19817 position: text::Anchor,
19818 cx: &mut App,
19819 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19820 Some(self.update(cx, |project, cx| {
19821 let buffer = buffer.clone();
19822 let task = project.prepare_rename(buffer.clone(), position, cx);
19823 cx.spawn(async move |_, cx| {
19824 Ok(match task.await? {
19825 PrepareRenameResponse::Success(range) => Some(range),
19826 PrepareRenameResponse::InvalidPosition => None,
19827 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19828 // Fallback on using TreeSitter info to determine identifier range
19829 buffer.update(cx, |buffer, _| {
19830 let snapshot = buffer.snapshot();
19831 let (range, kind) = snapshot.surrounding_word(position);
19832 if kind != Some(CharKind::Word) {
19833 return None;
19834 }
19835 Some(
19836 snapshot.anchor_before(range.start)
19837 ..snapshot.anchor_after(range.end),
19838 )
19839 })?
19840 }
19841 })
19842 })
19843 }))
19844 }
19845
19846 fn perform_rename(
19847 &self,
19848 buffer: &Entity<Buffer>,
19849 position: text::Anchor,
19850 new_name: String,
19851 cx: &mut App,
19852 ) -> Option<Task<Result<ProjectTransaction>>> {
19853 Some(self.update(cx, |project, cx| {
19854 project.perform_rename(buffer.clone(), position, new_name, cx)
19855 }))
19856 }
19857}
19858
19859fn inlay_hint_settings(
19860 location: Anchor,
19861 snapshot: &MultiBufferSnapshot,
19862 cx: &mut Context<Editor>,
19863) -> InlayHintSettings {
19864 let file = snapshot.file_at(location);
19865 let language = snapshot.language_at(location).map(|l| l.name());
19866 language_settings(language, file, cx).inlay_hints
19867}
19868
19869fn consume_contiguous_rows(
19870 contiguous_row_selections: &mut Vec<Selection<Point>>,
19871 selection: &Selection<Point>,
19872 display_map: &DisplaySnapshot,
19873 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19874) -> (MultiBufferRow, MultiBufferRow) {
19875 contiguous_row_selections.push(selection.clone());
19876 let start_row = MultiBufferRow(selection.start.row);
19877 let mut end_row = ending_row(selection, display_map);
19878
19879 while let Some(next_selection) = selections.peek() {
19880 if next_selection.start.row <= end_row.0 {
19881 end_row = ending_row(next_selection, display_map);
19882 contiguous_row_selections.push(selections.next().unwrap().clone());
19883 } else {
19884 break;
19885 }
19886 }
19887 (start_row, end_row)
19888}
19889
19890fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19891 if next_selection.end.column > 0 || next_selection.is_empty() {
19892 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19893 } else {
19894 MultiBufferRow(next_selection.end.row)
19895 }
19896}
19897
19898impl EditorSnapshot {
19899 pub fn remote_selections_in_range<'a>(
19900 &'a self,
19901 range: &'a Range<Anchor>,
19902 collaboration_hub: &dyn CollaborationHub,
19903 cx: &'a App,
19904 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19905 let participant_names = collaboration_hub.user_names(cx);
19906 let participant_indices = collaboration_hub.user_participant_indices(cx);
19907 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19908 let collaborators_by_replica_id = collaborators_by_peer_id
19909 .iter()
19910 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19911 .collect::<HashMap<_, _>>();
19912 self.buffer_snapshot
19913 .selections_in_range(range, false)
19914 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19915 if replica_id == AGENT_REPLICA_ID {
19916 Some(RemoteSelection {
19917 replica_id,
19918 selection,
19919 cursor_shape,
19920 line_mode,
19921 collaborator_id: CollaboratorId::Agent,
19922 user_name: Some("Agent".into()),
19923 color: cx.theme().players().agent(),
19924 })
19925 } else {
19926 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19927 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19928 let user_name = participant_names.get(&collaborator.user_id).cloned();
19929 Some(RemoteSelection {
19930 replica_id,
19931 selection,
19932 cursor_shape,
19933 line_mode,
19934 collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19935 user_name,
19936 color: if let Some(index) = participant_index {
19937 cx.theme().players().color_for_participant(index.0)
19938 } else {
19939 cx.theme().players().absent()
19940 },
19941 })
19942 }
19943 })
19944 }
19945
19946 pub fn hunks_for_ranges(
19947 &self,
19948 ranges: impl IntoIterator<Item = Range<Point>>,
19949 ) -> Vec<MultiBufferDiffHunk> {
19950 let mut hunks = Vec::new();
19951 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19952 HashMap::default();
19953 for query_range in ranges {
19954 let query_rows =
19955 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19956 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19957 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19958 ) {
19959 // Include deleted hunks that are adjacent to the query range, because
19960 // otherwise they would be missed.
19961 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19962 if hunk.status().is_deleted() {
19963 intersects_range |= hunk.row_range.start == query_rows.end;
19964 intersects_range |= hunk.row_range.end == query_rows.start;
19965 }
19966 if intersects_range {
19967 if !processed_buffer_rows
19968 .entry(hunk.buffer_id)
19969 .or_default()
19970 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19971 {
19972 continue;
19973 }
19974 hunks.push(hunk);
19975 }
19976 }
19977 }
19978
19979 hunks
19980 }
19981
19982 fn display_diff_hunks_for_rows<'a>(
19983 &'a self,
19984 display_rows: Range<DisplayRow>,
19985 folded_buffers: &'a HashSet<BufferId>,
19986 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19987 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19988 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19989
19990 self.buffer_snapshot
19991 .diff_hunks_in_range(buffer_start..buffer_end)
19992 .filter_map(|hunk| {
19993 if folded_buffers.contains(&hunk.buffer_id) {
19994 return None;
19995 }
19996
19997 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19998 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19999
20000 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20001 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20002
20003 let display_hunk = if hunk_display_start.column() != 0 {
20004 DisplayDiffHunk::Folded {
20005 display_row: hunk_display_start.row(),
20006 }
20007 } else {
20008 let mut end_row = hunk_display_end.row();
20009 if hunk_display_end.column() > 0 {
20010 end_row.0 += 1;
20011 }
20012 let is_created_file = hunk.is_created_file();
20013 DisplayDiffHunk::Unfolded {
20014 status: hunk.status(),
20015 diff_base_byte_range: hunk.diff_base_byte_range,
20016 display_row_range: hunk_display_start.row()..end_row,
20017 multi_buffer_range: Anchor::range_in_buffer(
20018 hunk.excerpt_id,
20019 hunk.buffer_id,
20020 hunk.buffer_range,
20021 ),
20022 is_created_file,
20023 }
20024 };
20025
20026 Some(display_hunk)
20027 })
20028 }
20029
20030 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20031 self.display_snapshot.buffer_snapshot.language_at(position)
20032 }
20033
20034 pub fn is_focused(&self) -> bool {
20035 self.is_focused
20036 }
20037
20038 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20039 self.placeholder_text.as_ref()
20040 }
20041
20042 pub fn scroll_position(&self) -> gpui::Point<f32> {
20043 self.scroll_anchor.scroll_position(&self.display_snapshot)
20044 }
20045
20046 fn gutter_dimensions(
20047 &self,
20048 font_id: FontId,
20049 font_size: Pixels,
20050 max_line_number_width: Pixels,
20051 cx: &App,
20052 ) -> Option<GutterDimensions> {
20053 if !self.show_gutter {
20054 return None;
20055 }
20056
20057 let descent = cx.text_system().descent(font_id, font_size);
20058 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20059 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20060
20061 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20062 matches!(
20063 ProjectSettings::get_global(cx).git.git_gutter,
20064 Some(GitGutterSetting::TrackedFiles)
20065 )
20066 });
20067 let gutter_settings = EditorSettings::get_global(cx).gutter;
20068 let show_line_numbers = self
20069 .show_line_numbers
20070 .unwrap_or(gutter_settings.line_numbers);
20071 let line_gutter_width = if show_line_numbers {
20072 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20073 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20074 max_line_number_width.max(min_width_for_number_on_gutter)
20075 } else {
20076 0.0.into()
20077 };
20078
20079 let show_code_actions = self
20080 .show_code_actions
20081 .unwrap_or(gutter_settings.code_actions);
20082
20083 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20084 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20085
20086 let git_blame_entries_width =
20087 self.git_blame_gutter_max_author_length
20088 .map(|max_author_length| {
20089 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20090 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20091
20092 /// The number of characters to dedicate to gaps and margins.
20093 const SPACING_WIDTH: usize = 4;
20094
20095 let max_char_count = max_author_length.min(renderer.max_author_length())
20096 + ::git::SHORT_SHA_LENGTH
20097 + MAX_RELATIVE_TIMESTAMP.len()
20098 + SPACING_WIDTH;
20099
20100 em_advance * max_char_count
20101 });
20102
20103 let is_singleton = self.buffer_snapshot.is_singleton();
20104
20105 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20106 left_padding += if !is_singleton {
20107 em_width * 4.0
20108 } else if show_code_actions || show_runnables || show_breakpoints {
20109 em_width * 3.0
20110 } else if show_git_gutter && show_line_numbers {
20111 em_width * 2.0
20112 } else if show_git_gutter || show_line_numbers {
20113 em_width
20114 } else {
20115 px(0.)
20116 };
20117
20118 let shows_folds = is_singleton && gutter_settings.folds;
20119
20120 let right_padding = if shows_folds && show_line_numbers {
20121 em_width * 4.0
20122 } else if shows_folds || (!is_singleton && show_line_numbers) {
20123 em_width * 3.0
20124 } else if show_line_numbers {
20125 em_width
20126 } else {
20127 px(0.)
20128 };
20129
20130 Some(GutterDimensions {
20131 left_padding,
20132 right_padding,
20133 width: line_gutter_width + left_padding + right_padding,
20134 margin: -descent,
20135 git_blame_entries_width,
20136 })
20137 }
20138
20139 pub fn render_crease_toggle(
20140 &self,
20141 buffer_row: MultiBufferRow,
20142 row_contains_cursor: bool,
20143 editor: Entity<Editor>,
20144 window: &mut Window,
20145 cx: &mut App,
20146 ) -> Option<AnyElement> {
20147 let folded = self.is_line_folded(buffer_row);
20148 let mut is_foldable = false;
20149
20150 if let Some(crease) = self
20151 .crease_snapshot
20152 .query_row(buffer_row, &self.buffer_snapshot)
20153 {
20154 is_foldable = true;
20155 match crease {
20156 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20157 if let Some(render_toggle) = render_toggle {
20158 let toggle_callback =
20159 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20160 if folded {
20161 editor.update(cx, |editor, cx| {
20162 editor.fold_at(buffer_row, window, cx)
20163 });
20164 } else {
20165 editor.update(cx, |editor, cx| {
20166 editor.unfold_at(buffer_row, window, cx)
20167 });
20168 }
20169 });
20170 return Some((render_toggle)(
20171 buffer_row,
20172 folded,
20173 toggle_callback,
20174 window,
20175 cx,
20176 ));
20177 }
20178 }
20179 }
20180 }
20181
20182 is_foldable |= self.starts_indent(buffer_row);
20183
20184 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20185 Some(
20186 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20187 .toggle_state(folded)
20188 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20189 if folded {
20190 this.unfold_at(buffer_row, window, cx);
20191 } else {
20192 this.fold_at(buffer_row, window, cx);
20193 }
20194 }))
20195 .into_any_element(),
20196 )
20197 } else {
20198 None
20199 }
20200 }
20201
20202 pub fn render_crease_trailer(
20203 &self,
20204 buffer_row: MultiBufferRow,
20205 window: &mut Window,
20206 cx: &mut App,
20207 ) -> Option<AnyElement> {
20208 let folded = self.is_line_folded(buffer_row);
20209 if let Crease::Inline { render_trailer, .. } = self
20210 .crease_snapshot
20211 .query_row(buffer_row, &self.buffer_snapshot)?
20212 {
20213 let render_trailer = render_trailer.as_ref()?;
20214 Some(render_trailer(buffer_row, folded, window, cx))
20215 } else {
20216 None
20217 }
20218 }
20219}
20220
20221impl Deref for EditorSnapshot {
20222 type Target = DisplaySnapshot;
20223
20224 fn deref(&self) -> &Self::Target {
20225 &self.display_snapshot
20226 }
20227}
20228
20229#[derive(Clone, Debug, PartialEq, Eq)]
20230pub enum EditorEvent {
20231 InputIgnored {
20232 text: Arc<str>,
20233 },
20234 InputHandled {
20235 utf16_range_to_replace: Option<Range<isize>>,
20236 text: Arc<str>,
20237 },
20238 ExcerptsAdded {
20239 buffer: Entity<Buffer>,
20240 predecessor: ExcerptId,
20241 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20242 },
20243 ExcerptsRemoved {
20244 ids: Vec<ExcerptId>,
20245 removed_buffer_ids: Vec<BufferId>,
20246 },
20247 BufferFoldToggled {
20248 ids: Vec<ExcerptId>,
20249 folded: bool,
20250 },
20251 ExcerptsEdited {
20252 ids: Vec<ExcerptId>,
20253 },
20254 ExcerptsExpanded {
20255 ids: Vec<ExcerptId>,
20256 },
20257 BufferEdited,
20258 Edited {
20259 transaction_id: clock::Lamport,
20260 },
20261 Reparsed(BufferId),
20262 Focused,
20263 FocusedIn,
20264 Blurred,
20265 DirtyChanged,
20266 Saved,
20267 TitleChanged,
20268 DiffBaseChanged,
20269 SelectionsChanged {
20270 local: bool,
20271 },
20272 ScrollPositionChanged {
20273 local: bool,
20274 autoscroll: bool,
20275 },
20276 Closed,
20277 TransactionUndone {
20278 transaction_id: clock::Lamport,
20279 },
20280 TransactionBegun {
20281 transaction_id: clock::Lamport,
20282 },
20283 Reloaded,
20284 CursorShapeChanged,
20285 PushedToNavHistory {
20286 anchor: Anchor,
20287 is_deactivate: bool,
20288 },
20289}
20290
20291impl EventEmitter<EditorEvent> for Editor {}
20292
20293impl Focusable for Editor {
20294 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20295 self.focus_handle.clone()
20296 }
20297}
20298
20299impl Render for Editor {
20300 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20301 let settings = ThemeSettings::get_global(cx);
20302
20303 let mut text_style = match self.mode {
20304 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20305 color: cx.theme().colors().editor_foreground,
20306 font_family: settings.ui_font.family.clone(),
20307 font_features: settings.ui_font.features.clone(),
20308 font_fallbacks: settings.ui_font.fallbacks.clone(),
20309 font_size: rems(0.875).into(),
20310 font_weight: settings.ui_font.weight,
20311 line_height: relative(settings.buffer_line_height.value()),
20312 ..Default::default()
20313 },
20314 EditorMode::Full { .. } => TextStyle {
20315 color: cx.theme().colors().editor_foreground,
20316 font_family: settings.buffer_font.family.clone(),
20317 font_features: settings.buffer_font.features.clone(),
20318 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20319 font_size: settings.buffer_font_size(cx).into(),
20320 font_weight: settings.buffer_font.weight,
20321 line_height: relative(settings.buffer_line_height.value()),
20322 ..Default::default()
20323 },
20324 };
20325 if let Some(text_style_refinement) = &self.text_style_refinement {
20326 text_style.refine(text_style_refinement)
20327 }
20328
20329 let background = match self.mode {
20330 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20331 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20332 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20333 };
20334
20335 EditorElement::new(
20336 &cx.entity(),
20337 EditorStyle {
20338 background,
20339 horizontal_padding: Pixels::default(),
20340 local_player: cx.theme().players().local(),
20341 text: text_style,
20342 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20343 syntax: cx.theme().syntax().clone(),
20344 status: cx.theme().status().clone(),
20345 inlay_hints_style: make_inlay_hints_style(cx),
20346 inline_completion_styles: make_suggestion_styles(cx),
20347 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20348 },
20349 )
20350 }
20351}
20352
20353impl EntityInputHandler for Editor {
20354 fn text_for_range(
20355 &mut self,
20356 range_utf16: Range<usize>,
20357 adjusted_range: &mut Option<Range<usize>>,
20358 _: &mut Window,
20359 cx: &mut Context<Self>,
20360 ) -> Option<String> {
20361 let snapshot = self.buffer.read(cx).read(cx);
20362 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20363 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20364 if (start.0..end.0) != range_utf16 {
20365 adjusted_range.replace(start.0..end.0);
20366 }
20367 Some(snapshot.text_for_range(start..end).collect())
20368 }
20369
20370 fn selected_text_range(
20371 &mut self,
20372 ignore_disabled_input: bool,
20373 _: &mut Window,
20374 cx: &mut Context<Self>,
20375 ) -> Option<UTF16Selection> {
20376 // Prevent the IME menu from appearing when holding down an alphabetic key
20377 // while input is disabled.
20378 if !ignore_disabled_input && !self.input_enabled {
20379 return None;
20380 }
20381
20382 let selection = self.selections.newest::<OffsetUtf16>(cx);
20383 let range = selection.range();
20384
20385 Some(UTF16Selection {
20386 range: range.start.0..range.end.0,
20387 reversed: selection.reversed,
20388 })
20389 }
20390
20391 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20392 let snapshot = self.buffer.read(cx).read(cx);
20393 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20394 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20395 }
20396
20397 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20398 self.clear_highlights::<InputComposition>(cx);
20399 self.ime_transaction.take();
20400 }
20401
20402 fn replace_text_in_range(
20403 &mut self,
20404 range_utf16: Option<Range<usize>>,
20405 text: &str,
20406 window: &mut Window,
20407 cx: &mut Context<Self>,
20408 ) {
20409 if !self.input_enabled {
20410 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20411 return;
20412 }
20413
20414 self.transact(window, cx, |this, window, cx| {
20415 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20416 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20417 Some(this.selection_replacement_ranges(range_utf16, cx))
20418 } else {
20419 this.marked_text_ranges(cx)
20420 };
20421
20422 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20423 let newest_selection_id = this.selections.newest_anchor().id;
20424 this.selections
20425 .all::<OffsetUtf16>(cx)
20426 .iter()
20427 .zip(ranges_to_replace.iter())
20428 .find_map(|(selection, range)| {
20429 if selection.id == newest_selection_id {
20430 Some(
20431 (range.start.0 as isize - selection.head().0 as isize)
20432 ..(range.end.0 as isize - selection.head().0 as isize),
20433 )
20434 } else {
20435 None
20436 }
20437 })
20438 });
20439
20440 cx.emit(EditorEvent::InputHandled {
20441 utf16_range_to_replace: range_to_replace,
20442 text: text.into(),
20443 });
20444
20445 if let Some(new_selected_ranges) = new_selected_ranges {
20446 this.change_selections(None, window, cx, |selections| {
20447 selections.select_ranges(new_selected_ranges)
20448 });
20449 this.backspace(&Default::default(), window, cx);
20450 }
20451
20452 this.handle_input(text, window, cx);
20453 });
20454
20455 if let Some(transaction) = self.ime_transaction {
20456 self.buffer.update(cx, |buffer, cx| {
20457 buffer.group_until_transaction(transaction, cx);
20458 });
20459 }
20460
20461 self.unmark_text(window, cx);
20462 }
20463
20464 fn replace_and_mark_text_in_range(
20465 &mut self,
20466 range_utf16: Option<Range<usize>>,
20467 text: &str,
20468 new_selected_range_utf16: Option<Range<usize>>,
20469 window: &mut Window,
20470 cx: &mut Context<Self>,
20471 ) {
20472 if !self.input_enabled {
20473 return;
20474 }
20475
20476 let transaction = self.transact(window, cx, |this, window, cx| {
20477 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20478 let snapshot = this.buffer.read(cx).read(cx);
20479 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20480 for marked_range in &mut marked_ranges {
20481 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20482 marked_range.start.0 += relative_range_utf16.start;
20483 marked_range.start =
20484 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20485 marked_range.end =
20486 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20487 }
20488 }
20489 Some(marked_ranges)
20490 } else if let Some(range_utf16) = range_utf16 {
20491 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20492 Some(this.selection_replacement_ranges(range_utf16, cx))
20493 } else {
20494 None
20495 };
20496
20497 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20498 let newest_selection_id = this.selections.newest_anchor().id;
20499 this.selections
20500 .all::<OffsetUtf16>(cx)
20501 .iter()
20502 .zip(ranges_to_replace.iter())
20503 .find_map(|(selection, range)| {
20504 if selection.id == newest_selection_id {
20505 Some(
20506 (range.start.0 as isize - selection.head().0 as isize)
20507 ..(range.end.0 as isize - selection.head().0 as isize),
20508 )
20509 } else {
20510 None
20511 }
20512 })
20513 });
20514
20515 cx.emit(EditorEvent::InputHandled {
20516 utf16_range_to_replace: range_to_replace,
20517 text: text.into(),
20518 });
20519
20520 if let Some(ranges) = ranges_to_replace {
20521 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20522 }
20523
20524 let marked_ranges = {
20525 let snapshot = this.buffer.read(cx).read(cx);
20526 this.selections
20527 .disjoint_anchors()
20528 .iter()
20529 .map(|selection| {
20530 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20531 })
20532 .collect::<Vec<_>>()
20533 };
20534
20535 if text.is_empty() {
20536 this.unmark_text(window, cx);
20537 } else {
20538 this.highlight_text::<InputComposition>(
20539 marked_ranges.clone(),
20540 HighlightStyle {
20541 underline: Some(UnderlineStyle {
20542 thickness: px(1.),
20543 color: None,
20544 wavy: false,
20545 }),
20546 ..Default::default()
20547 },
20548 cx,
20549 );
20550 }
20551
20552 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20553 let use_autoclose = this.use_autoclose;
20554 let use_auto_surround = this.use_auto_surround;
20555 this.set_use_autoclose(false);
20556 this.set_use_auto_surround(false);
20557 this.handle_input(text, window, cx);
20558 this.set_use_autoclose(use_autoclose);
20559 this.set_use_auto_surround(use_auto_surround);
20560
20561 if let Some(new_selected_range) = new_selected_range_utf16 {
20562 let snapshot = this.buffer.read(cx).read(cx);
20563 let new_selected_ranges = marked_ranges
20564 .into_iter()
20565 .map(|marked_range| {
20566 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20567 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20568 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20569 snapshot.clip_offset_utf16(new_start, Bias::Left)
20570 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20571 })
20572 .collect::<Vec<_>>();
20573
20574 drop(snapshot);
20575 this.change_selections(None, window, cx, |selections| {
20576 selections.select_ranges(new_selected_ranges)
20577 });
20578 }
20579 });
20580
20581 self.ime_transaction = self.ime_transaction.or(transaction);
20582 if let Some(transaction) = self.ime_transaction {
20583 self.buffer.update(cx, |buffer, cx| {
20584 buffer.group_until_transaction(transaction, cx);
20585 });
20586 }
20587
20588 if self.text_highlights::<InputComposition>(cx).is_none() {
20589 self.ime_transaction.take();
20590 }
20591 }
20592
20593 fn bounds_for_range(
20594 &mut self,
20595 range_utf16: Range<usize>,
20596 element_bounds: gpui::Bounds<Pixels>,
20597 window: &mut Window,
20598 cx: &mut Context<Self>,
20599 ) -> Option<gpui::Bounds<Pixels>> {
20600 let text_layout_details = self.text_layout_details(window);
20601 let gpui::Size {
20602 width: em_width,
20603 height: line_height,
20604 } = self.character_size(window);
20605
20606 let snapshot = self.snapshot(window, cx);
20607 let scroll_position = snapshot.scroll_position();
20608 let scroll_left = scroll_position.x * em_width;
20609
20610 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20611 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20612 + self.gutter_dimensions.width
20613 + self.gutter_dimensions.margin;
20614 let y = line_height * (start.row().as_f32() - scroll_position.y);
20615
20616 Some(Bounds {
20617 origin: element_bounds.origin + point(x, y),
20618 size: size(em_width, line_height),
20619 })
20620 }
20621
20622 fn character_index_for_point(
20623 &mut self,
20624 point: gpui::Point<Pixels>,
20625 _window: &mut Window,
20626 _cx: &mut Context<Self>,
20627 ) -> Option<usize> {
20628 let position_map = self.last_position_map.as_ref()?;
20629 if !position_map.text_hitbox.contains(&point) {
20630 return None;
20631 }
20632 let display_point = position_map.point_for_position(point).previous_valid;
20633 let anchor = position_map
20634 .snapshot
20635 .display_point_to_anchor(display_point, Bias::Left);
20636 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20637 Some(utf16_offset.0)
20638 }
20639}
20640
20641trait SelectionExt {
20642 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20643 fn spanned_rows(
20644 &self,
20645 include_end_if_at_line_start: bool,
20646 map: &DisplaySnapshot,
20647 ) -> Range<MultiBufferRow>;
20648}
20649
20650impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20651 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20652 let start = self
20653 .start
20654 .to_point(&map.buffer_snapshot)
20655 .to_display_point(map);
20656 let end = self
20657 .end
20658 .to_point(&map.buffer_snapshot)
20659 .to_display_point(map);
20660 if self.reversed {
20661 end..start
20662 } else {
20663 start..end
20664 }
20665 }
20666
20667 fn spanned_rows(
20668 &self,
20669 include_end_if_at_line_start: bool,
20670 map: &DisplaySnapshot,
20671 ) -> Range<MultiBufferRow> {
20672 let start = self.start.to_point(&map.buffer_snapshot);
20673 let mut end = self.end.to_point(&map.buffer_snapshot);
20674 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20675 end.row -= 1;
20676 }
20677
20678 let buffer_start = map.prev_line_boundary(start).0;
20679 let buffer_end = map.next_line_boundary(end).0;
20680 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20681 }
20682}
20683
20684impl<T: InvalidationRegion> InvalidationStack<T> {
20685 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20686 where
20687 S: Clone + ToOffset,
20688 {
20689 while let Some(region) = self.last() {
20690 let all_selections_inside_invalidation_ranges =
20691 if selections.len() == region.ranges().len() {
20692 selections
20693 .iter()
20694 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20695 .all(|(selection, invalidation_range)| {
20696 let head = selection.head().to_offset(buffer);
20697 invalidation_range.start <= head && invalidation_range.end >= head
20698 })
20699 } else {
20700 false
20701 };
20702
20703 if all_selections_inside_invalidation_ranges {
20704 break;
20705 } else {
20706 self.pop();
20707 }
20708 }
20709 }
20710}
20711
20712impl<T> Default for InvalidationStack<T> {
20713 fn default() -> Self {
20714 Self(Default::default())
20715 }
20716}
20717
20718impl<T> Deref for InvalidationStack<T> {
20719 type Target = Vec<T>;
20720
20721 fn deref(&self) -> &Self::Target {
20722 &self.0
20723 }
20724}
20725
20726impl<T> DerefMut for InvalidationStack<T> {
20727 fn deref_mut(&mut self) -> &mut Self::Target {
20728 &mut self.0
20729 }
20730}
20731
20732impl InvalidationRegion for SnippetState {
20733 fn ranges(&self) -> &[Range<Anchor>] {
20734 &self.ranges[self.active_index]
20735 }
20736}
20737
20738fn inline_completion_edit_text(
20739 current_snapshot: &BufferSnapshot,
20740 edits: &[(Range<Anchor>, String)],
20741 edit_preview: &EditPreview,
20742 include_deletions: bool,
20743 cx: &App,
20744) -> HighlightedText {
20745 let edits = edits
20746 .iter()
20747 .map(|(anchor, text)| {
20748 (
20749 anchor.start.text_anchor..anchor.end.text_anchor,
20750 text.clone(),
20751 )
20752 })
20753 .collect::<Vec<_>>();
20754
20755 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20756}
20757
20758pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20759 match severity {
20760 DiagnosticSeverity::ERROR => colors.error,
20761 DiagnosticSeverity::WARNING => colors.warning,
20762 DiagnosticSeverity::INFORMATION => colors.info,
20763 DiagnosticSeverity::HINT => colors.info,
20764 _ => colors.ignored,
20765 }
20766}
20767
20768pub fn styled_runs_for_code_label<'a>(
20769 label: &'a CodeLabel,
20770 syntax_theme: &'a theme::SyntaxTheme,
20771) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20772 let fade_out = HighlightStyle {
20773 fade_out: Some(0.35),
20774 ..Default::default()
20775 };
20776
20777 let mut prev_end = label.filter_range.end;
20778 label
20779 .runs
20780 .iter()
20781 .enumerate()
20782 .flat_map(move |(ix, (range, highlight_id))| {
20783 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20784 style
20785 } else {
20786 return Default::default();
20787 };
20788 let mut muted_style = style;
20789 muted_style.highlight(fade_out);
20790
20791 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20792 if range.start >= label.filter_range.end {
20793 if range.start > prev_end {
20794 runs.push((prev_end..range.start, fade_out));
20795 }
20796 runs.push((range.clone(), muted_style));
20797 } else if range.end <= label.filter_range.end {
20798 runs.push((range.clone(), style));
20799 } else {
20800 runs.push((range.start..label.filter_range.end, style));
20801 runs.push((label.filter_range.end..range.end, muted_style));
20802 }
20803 prev_end = cmp::max(prev_end, range.end);
20804
20805 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20806 runs.push((prev_end..label.text.len(), fade_out));
20807 }
20808
20809 runs
20810 })
20811}
20812
20813pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20814 let mut prev_index = 0;
20815 let mut prev_codepoint: Option<char> = None;
20816 text.char_indices()
20817 .chain([(text.len(), '\0')])
20818 .filter_map(move |(index, codepoint)| {
20819 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20820 let is_boundary = index == text.len()
20821 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20822 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20823 if is_boundary {
20824 let chunk = &text[prev_index..index];
20825 prev_index = index;
20826 Some(chunk)
20827 } else {
20828 None
20829 }
20830 })
20831}
20832
20833pub trait RangeToAnchorExt: Sized {
20834 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20835
20836 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20837 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20838 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20839 }
20840}
20841
20842impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20843 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20844 let start_offset = self.start.to_offset(snapshot);
20845 let end_offset = self.end.to_offset(snapshot);
20846 if start_offset == end_offset {
20847 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20848 } else {
20849 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20850 }
20851 }
20852}
20853
20854pub trait RowExt {
20855 fn as_f32(&self) -> f32;
20856
20857 fn next_row(&self) -> Self;
20858
20859 fn previous_row(&self) -> Self;
20860
20861 fn minus(&self, other: Self) -> u32;
20862}
20863
20864impl RowExt for DisplayRow {
20865 fn as_f32(&self) -> f32 {
20866 self.0 as f32
20867 }
20868
20869 fn next_row(&self) -> Self {
20870 Self(self.0 + 1)
20871 }
20872
20873 fn previous_row(&self) -> Self {
20874 Self(self.0.saturating_sub(1))
20875 }
20876
20877 fn minus(&self, other: Self) -> u32 {
20878 self.0 - other.0
20879 }
20880}
20881
20882impl RowExt for MultiBufferRow {
20883 fn as_f32(&self) -> f32 {
20884 self.0 as f32
20885 }
20886
20887 fn next_row(&self) -> Self {
20888 Self(self.0 + 1)
20889 }
20890
20891 fn previous_row(&self) -> Self {
20892 Self(self.0.saturating_sub(1))
20893 }
20894
20895 fn minus(&self, other: Self) -> u32 {
20896 self.0 - other.0
20897 }
20898}
20899
20900trait RowRangeExt {
20901 type Row;
20902
20903 fn len(&self) -> usize;
20904
20905 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20906}
20907
20908impl RowRangeExt for Range<MultiBufferRow> {
20909 type Row = MultiBufferRow;
20910
20911 fn len(&self) -> usize {
20912 (self.end.0 - self.start.0) as usize
20913 }
20914
20915 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20916 (self.start.0..self.end.0).map(MultiBufferRow)
20917 }
20918}
20919
20920impl RowRangeExt for Range<DisplayRow> {
20921 type Row = DisplayRow;
20922
20923 fn len(&self) -> usize {
20924 (self.end.0 - self.start.0) as usize
20925 }
20926
20927 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20928 (self.start.0..self.end.0).map(DisplayRow)
20929 }
20930}
20931
20932/// If select range has more than one line, we
20933/// just point the cursor to range.start.
20934fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20935 if range.start.row == range.end.row {
20936 range
20937 } else {
20938 range.start..range.start
20939 }
20940}
20941pub struct KillRing(ClipboardItem);
20942impl Global for KillRing {}
20943
20944const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20945
20946enum BreakpointPromptEditAction {
20947 Log,
20948 Condition,
20949 HitCondition,
20950}
20951
20952struct BreakpointPromptEditor {
20953 pub(crate) prompt: Entity<Editor>,
20954 editor: WeakEntity<Editor>,
20955 breakpoint_anchor: Anchor,
20956 breakpoint: Breakpoint,
20957 edit_action: BreakpointPromptEditAction,
20958 block_ids: HashSet<CustomBlockId>,
20959 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20960 _subscriptions: Vec<Subscription>,
20961}
20962
20963impl BreakpointPromptEditor {
20964 const MAX_LINES: u8 = 4;
20965
20966 fn new(
20967 editor: WeakEntity<Editor>,
20968 breakpoint_anchor: Anchor,
20969 breakpoint: Breakpoint,
20970 edit_action: BreakpointPromptEditAction,
20971 window: &mut Window,
20972 cx: &mut Context<Self>,
20973 ) -> Self {
20974 let base_text = match edit_action {
20975 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20976 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20977 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20978 }
20979 .map(|msg| msg.to_string())
20980 .unwrap_or_default();
20981
20982 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20983 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20984
20985 let prompt = cx.new(|cx| {
20986 let mut prompt = Editor::new(
20987 EditorMode::AutoHeight {
20988 max_lines: Self::MAX_LINES as usize,
20989 },
20990 buffer,
20991 None,
20992 window,
20993 cx,
20994 );
20995 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20996 prompt.set_show_cursor_when_unfocused(false, cx);
20997 prompt.set_placeholder_text(
20998 match edit_action {
20999 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21000 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21001 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21002 },
21003 cx,
21004 );
21005
21006 prompt
21007 });
21008
21009 Self {
21010 prompt,
21011 editor,
21012 breakpoint_anchor,
21013 breakpoint,
21014 edit_action,
21015 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21016 block_ids: Default::default(),
21017 _subscriptions: vec![],
21018 }
21019 }
21020
21021 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21022 self.block_ids.extend(block_ids)
21023 }
21024
21025 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21026 if let Some(editor) = self.editor.upgrade() {
21027 let message = self
21028 .prompt
21029 .read(cx)
21030 .buffer
21031 .read(cx)
21032 .as_singleton()
21033 .expect("A multi buffer in breakpoint prompt isn't possible")
21034 .read(cx)
21035 .as_rope()
21036 .to_string();
21037
21038 editor.update(cx, |editor, cx| {
21039 editor.edit_breakpoint_at_anchor(
21040 self.breakpoint_anchor,
21041 self.breakpoint.clone(),
21042 match self.edit_action {
21043 BreakpointPromptEditAction::Log => {
21044 BreakpointEditAction::EditLogMessage(message.into())
21045 }
21046 BreakpointPromptEditAction::Condition => {
21047 BreakpointEditAction::EditCondition(message.into())
21048 }
21049 BreakpointPromptEditAction::HitCondition => {
21050 BreakpointEditAction::EditHitCondition(message.into())
21051 }
21052 },
21053 cx,
21054 );
21055
21056 editor.remove_blocks(self.block_ids.clone(), None, cx);
21057 cx.focus_self(window);
21058 });
21059 }
21060 }
21061
21062 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21063 self.editor
21064 .update(cx, |editor, cx| {
21065 editor.remove_blocks(self.block_ids.clone(), None, cx);
21066 window.focus(&editor.focus_handle);
21067 })
21068 .log_err();
21069 }
21070
21071 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21072 let settings = ThemeSettings::get_global(cx);
21073 let text_style = TextStyle {
21074 color: if self.prompt.read(cx).read_only(cx) {
21075 cx.theme().colors().text_disabled
21076 } else {
21077 cx.theme().colors().text
21078 },
21079 font_family: settings.buffer_font.family.clone(),
21080 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21081 font_size: settings.buffer_font_size(cx).into(),
21082 font_weight: settings.buffer_font.weight,
21083 line_height: relative(settings.buffer_line_height.value()),
21084 ..Default::default()
21085 };
21086 EditorElement::new(
21087 &self.prompt,
21088 EditorStyle {
21089 background: cx.theme().colors().editor_background,
21090 local_player: cx.theme().players().local(),
21091 text: text_style,
21092 ..Default::default()
21093 },
21094 )
21095 }
21096}
21097
21098impl Render for BreakpointPromptEditor {
21099 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21100 let gutter_dimensions = *self.gutter_dimensions.lock();
21101 h_flex()
21102 .key_context("Editor")
21103 .bg(cx.theme().colors().editor_background)
21104 .border_y_1()
21105 .border_color(cx.theme().status().info_border)
21106 .size_full()
21107 .py(window.line_height() / 2.5)
21108 .on_action(cx.listener(Self::confirm))
21109 .on_action(cx.listener(Self::cancel))
21110 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21111 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21112 }
21113}
21114
21115impl Focusable for BreakpointPromptEditor {
21116 fn focus_handle(&self, cx: &App) -> FocusHandle {
21117 self.prompt.focus_handle(cx)
21118 }
21119}
21120
21121fn all_edits_insertions_or_deletions(
21122 edits: &Vec<(Range<Anchor>, String)>,
21123 snapshot: &MultiBufferSnapshot,
21124) -> bool {
21125 let mut all_insertions = true;
21126 let mut all_deletions = true;
21127
21128 for (range, new_text) in edits.iter() {
21129 let range_is_empty = range.to_offset(&snapshot).is_empty();
21130 let text_is_empty = new_text.is_empty();
21131
21132 if range_is_empty != text_is_empty {
21133 if range_is_empty {
21134 all_deletions = false;
21135 } else {
21136 all_insertions = false;
21137 }
21138 } else {
21139 return false;
21140 }
21141
21142 if !all_insertions && !all_deletions {
21143 return false;
21144 }
21145 }
21146 all_insertions || all_deletions
21147}
21148
21149struct MissingEditPredictionKeybindingTooltip;
21150
21151impl Render for MissingEditPredictionKeybindingTooltip {
21152 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21153 ui::tooltip_container(window, cx, |container, _, cx| {
21154 container
21155 .flex_shrink_0()
21156 .max_w_80()
21157 .min_h(rems_from_px(124.))
21158 .justify_between()
21159 .child(
21160 v_flex()
21161 .flex_1()
21162 .text_ui_sm(cx)
21163 .child(Label::new("Conflict with Accept Keybinding"))
21164 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21165 )
21166 .child(
21167 h_flex()
21168 .pb_1()
21169 .gap_1()
21170 .items_end()
21171 .w_full()
21172 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21173 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21174 }))
21175 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21176 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21177 })),
21178 )
21179 })
21180 }
21181}
21182
21183#[derive(Debug, Clone, Copy, PartialEq)]
21184pub struct LineHighlight {
21185 pub background: Background,
21186 pub border: Option<gpui::Hsla>,
21187 pub include_gutter: bool,
21188 pub type_id: Option<TypeId>,
21189}
21190
21191fn render_diff_hunk_controls(
21192 row: u32,
21193 status: &DiffHunkStatus,
21194 hunk_range: Range<Anchor>,
21195 is_created_file: bool,
21196 line_height: Pixels,
21197 editor: &Entity<Editor>,
21198 _window: &mut Window,
21199 cx: &mut App,
21200) -> AnyElement {
21201 h_flex()
21202 .h(line_height)
21203 .mr_1()
21204 .gap_1()
21205 .px_0p5()
21206 .pb_1()
21207 .border_x_1()
21208 .border_b_1()
21209 .border_color(cx.theme().colors().border_variant)
21210 .rounded_b_lg()
21211 .bg(cx.theme().colors().editor_background)
21212 .gap_1()
21213 .occlude()
21214 .shadow_md()
21215 .child(if status.has_secondary_hunk() {
21216 Button::new(("stage", row as u64), "Stage")
21217 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21218 .tooltip({
21219 let focus_handle = editor.focus_handle(cx);
21220 move |window, cx| {
21221 Tooltip::for_action_in(
21222 "Stage Hunk",
21223 &::git::ToggleStaged,
21224 &focus_handle,
21225 window,
21226 cx,
21227 )
21228 }
21229 })
21230 .on_click({
21231 let editor = editor.clone();
21232 move |_event, _window, cx| {
21233 editor.update(cx, |editor, cx| {
21234 editor.stage_or_unstage_diff_hunks(
21235 true,
21236 vec![hunk_range.start..hunk_range.start],
21237 cx,
21238 );
21239 });
21240 }
21241 })
21242 } else {
21243 Button::new(("unstage", row as u64), "Unstage")
21244 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21245 .tooltip({
21246 let focus_handle = editor.focus_handle(cx);
21247 move |window, cx| {
21248 Tooltip::for_action_in(
21249 "Unstage Hunk",
21250 &::git::ToggleStaged,
21251 &focus_handle,
21252 window,
21253 cx,
21254 )
21255 }
21256 })
21257 .on_click({
21258 let editor = editor.clone();
21259 move |_event, _window, cx| {
21260 editor.update(cx, |editor, cx| {
21261 editor.stage_or_unstage_diff_hunks(
21262 false,
21263 vec![hunk_range.start..hunk_range.start],
21264 cx,
21265 );
21266 });
21267 }
21268 })
21269 })
21270 .child(
21271 Button::new(("restore", row as u64), "Restore")
21272 .tooltip({
21273 let focus_handle = editor.focus_handle(cx);
21274 move |window, cx| {
21275 Tooltip::for_action_in(
21276 "Restore Hunk",
21277 &::git::Restore,
21278 &focus_handle,
21279 window,
21280 cx,
21281 )
21282 }
21283 })
21284 .on_click({
21285 let editor = editor.clone();
21286 move |_event, window, cx| {
21287 editor.update(cx, |editor, cx| {
21288 let snapshot = editor.snapshot(window, cx);
21289 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21290 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21291 });
21292 }
21293 })
21294 .disabled(is_created_file),
21295 )
21296 .when(
21297 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21298 |el| {
21299 el.child(
21300 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21301 .shape(IconButtonShape::Square)
21302 .icon_size(IconSize::Small)
21303 // .disabled(!has_multiple_hunks)
21304 .tooltip({
21305 let focus_handle = editor.focus_handle(cx);
21306 move |window, cx| {
21307 Tooltip::for_action_in(
21308 "Next Hunk",
21309 &GoToHunk,
21310 &focus_handle,
21311 window,
21312 cx,
21313 )
21314 }
21315 })
21316 .on_click({
21317 let editor = editor.clone();
21318 move |_event, window, cx| {
21319 editor.update(cx, |editor, cx| {
21320 let snapshot = editor.snapshot(window, cx);
21321 let position =
21322 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21323 editor.go_to_hunk_before_or_after_position(
21324 &snapshot,
21325 position,
21326 Direction::Next,
21327 window,
21328 cx,
21329 );
21330 editor.expand_selected_diff_hunks(cx);
21331 });
21332 }
21333 }),
21334 )
21335 .child(
21336 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21337 .shape(IconButtonShape::Square)
21338 .icon_size(IconSize::Small)
21339 // .disabled(!has_multiple_hunks)
21340 .tooltip({
21341 let focus_handle = editor.focus_handle(cx);
21342 move |window, cx| {
21343 Tooltip::for_action_in(
21344 "Previous Hunk",
21345 &GoToPreviousHunk,
21346 &focus_handle,
21347 window,
21348 cx,
21349 )
21350 }
21351 })
21352 .on_click({
21353 let editor = editor.clone();
21354 move |_event, window, cx| {
21355 editor.update(cx, |editor, cx| {
21356 let snapshot = editor.snapshot(window, cx);
21357 let point =
21358 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21359 editor.go_to_hunk_before_or_after_position(
21360 &snapshot,
21361 point,
21362 Direction::Prev,
21363 window,
21364 cx,
21365 );
21366 editor.expand_selected_diff_hunks(cx);
21367 });
21368 }
21369 }),
21370 )
21371 },
21372 )
21373 .into_any_element()
21374}