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::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::{Debugger, FeatureFlagAppExt};
75use futures::{
76 FutureExt,
77 future::{self, Shared, join},
78};
79use fuzzy::StringMatchCandidate;
80
81use ::git::Restore;
82use code_context_menus::{
83 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
84 CompletionsMenu, ContextMenuOrigin,
85};
86use git::blame::{GitBlame, GlobalBlameRenderer};
87use gpui::{
88 Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
89 AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
90 ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
91 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
92 KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
93 SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
94 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
95 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
96};
97use highlight_matching_bracket::refresh_matching_bracket_highlights;
98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
99pub use hover_popover::hover_markdown_style;
100use hover_popover::{HoverState, hide_hover};
101use indent_guides::ActiveIndentGuidesState;
102use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
103pub use inline_completion::Direction;
104use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
105pub use items::MAX_TAB_TITLE_LEN;
106use itertools::Itertools;
107use language::{
108 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
109 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
110 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
111 TransactionId, TreeSitterOptions, WordsQuery,
112 language_settings::{
113 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
114 all_language_settings, language_settings,
115 },
116 point_from_lsp, text_diff_with_options,
117};
118use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
119use linked_editing_ranges::refresh_linked_ranges;
120use mouse_context_menu::MouseContextMenu;
121use persistence::DB;
122use project::{
123 ProjectPath,
124 debugger::{
125 breakpoint_store::{
126 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
127 },
128 session::{Session, SessionEvent},
129 },
130};
131
132pub use git::blame::BlameRenderer;
133pub use proposed_changes_editor::{
134 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
135};
136use smallvec::smallvec;
137use std::{cell::OnceCell, iter::Peekable};
138use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
139
140pub use lsp::CompletionContext;
141use lsp::{
142 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
143 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
144};
145
146use language::BufferSnapshot;
147pub use lsp_ext::lsp_tasks;
148use movement::TextLayoutDetails;
149pub use multi_buffer::{
150 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
151 RowInfo, ToOffset, ToPoint,
152};
153use multi_buffer::{
154 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
155 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
156};
157use parking_lot::Mutex;
158use project::{
159 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
160 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
161 TaskSourceKind,
162 debugger::breakpoint_store::Breakpoint,
163 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
164 project_settings::{GitGutterSetting, ProjectSettings},
165};
166use rand::prelude::*;
167use rpc::{ErrorExt, proto::*};
168use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
169use selections_collection::{
170 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
171};
172use serde::{Deserialize, Serialize};
173use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
174use smallvec::SmallVec;
175use snippet::Snippet;
176use std::sync::Arc;
177use std::{
178 any::TypeId,
179 borrow::Cow,
180 cell::RefCell,
181 cmp::{self, Ordering, Reverse},
182 mem,
183 num::NonZeroU32,
184 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
185 path::{Path, PathBuf},
186 rc::Rc,
187 time::{Duration, Instant},
188};
189pub use sum_tree::Bias;
190use sum_tree::TreeMap;
191use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
192use theme::{
193 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
194 observe_buffer_font_size_adjustment,
195};
196use ui::{
197 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
198 IconSize, Key, Tooltip, h_flex, prelude::*,
199};
200use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
201use workspace::{
202 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
203 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
204 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
205 item::{ItemHandle, PreviewTabsSettings},
206 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
207 searchable::SearchEvent,
208};
209
210use crate::hover_links::{find_url, find_url_from_range};
211use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
212
213pub const FILE_HEADER_HEIGHT: u32 = 2;
214pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
215pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
216const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
217const MAX_LINE_LEN: usize = 1024;
218const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
219const MAX_SELECTION_HISTORY_LEN: usize = 1024;
220pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
221#[doc(hidden)]
222pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
223const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
224
225pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
226pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
227pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
228
229pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
230pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
231pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
232
233pub type RenderDiffHunkControlsFn = Arc<
234 dyn Fn(
235 u32,
236 &DiffHunkStatus,
237 Range<Anchor>,
238 bool,
239 Pixels,
240 &Entity<Editor>,
241 &mut Window,
242 &mut App,
243 ) -> AnyElement,
244>;
245
246const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
247 alt: true,
248 shift: true,
249 control: false,
250 platform: false,
251 function: false,
252};
253
254struct InlineValueCache {
255 enabled: bool,
256 inlays: Vec<InlayId>,
257 refresh_task: Task<Option<()>>,
258}
259
260impl InlineValueCache {
261 fn new(enabled: bool) -> Self {
262 Self {
263 enabled,
264 inlays: Vec::new(),
265 refresh_task: Task::ready(None),
266 }
267 }
268}
269
270#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
271pub enum InlayId {
272 InlineCompletion(usize),
273 Hint(usize),
274 DebuggerValue(usize),
275}
276
277impl InlayId {
278 fn id(&self) -> usize {
279 match self {
280 Self::InlineCompletion(id) => *id,
281 Self::Hint(id) => *id,
282 Self::DebuggerValue(id) => *id,
283 }
284 }
285}
286
287pub enum DebugCurrentRowHighlight {}
288enum DocumentHighlightRead {}
289enum DocumentHighlightWrite {}
290enum InputComposition {}
291enum SelectedTextHighlight {}
292
293pub enum ConflictsOuter {}
294pub enum ConflictsOurs {}
295pub enum ConflictsTheirs {}
296pub enum ConflictsOursMarker {}
297pub enum ConflictsTheirsMarker {}
298
299#[derive(Debug, Copy, Clone, PartialEq, Eq)]
300pub enum Navigated {
301 Yes,
302 No,
303}
304
305impl Navigated {
306 pub fn from_bool(yes: bool) -> Navigated {
307 if yes { Navigated::Yes } else { Navigated::No }
308 }
309}
310
311#[derive(Debug, Clone, PartialEq, Eq)]
312enum DisplayDiffHunk {
313 Folded {
314 display_row: DisplayRow,
315 },
316 Unfolded {
317 is_created_file: bool,
318 diff_base_byte_range: Range<usize>,
319 display_row_range: Range<DisplayRow>,
320 multi_buffer_range: Range<Anchor>,
321 status: DiffHunkStatus,
322 },
323}
324
325pub enum HideMouseCursorOrigin {
326 TypingAction,
327 MovementAction,
328}
329
330pub fn init_settings(cx: &mut App) {
331 EditorSettings::register(cx);
332}
333
334pub fn init(cx: &mut App) {
335 init_settings(cx);
336
337 cx.set_global(GlobalBlameRenderer(Arc::new(())));
338
339 workspace::register_project_item::<Editor>(cx);
340 workspace::FollowableViewRegistry::register::<Editor>(cx);
341 workspace::register_serializable_item::<Editor>(cx);
342
343 cx.observe_new(
344 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
345 workspace.register_action(Editor::new_file);
346 workspace.register_action(Editor::new_file_vertical);
347 workspace.register_action(Editor::new_file_horizontal);
348 workspace.register_action(Editor::cancel_language_server_work);
349 },
350 )
351 .detach();
352
353 cx.on_action(move |_: &workspace::NewFile, cx| {
354 let app_state = workspace::AppState::global(cx);
355 if let Some(app_state) = app_state.upgrade() {
356 workspace::open_new(
357 Default::default(),
358 app_state,
359 cx,
360 |workspace, window, cx| {
361 Editor::new_file(workspace, &Default::default(), window, cx)
362 },
363 )
364 .detach();
365 }
366 });
367 cx.on_action(move |_: &workspace::NewWindow, cx| {
368 let app_state = workspace::AppState::global(cx);
369 if let Some(app_state) = app_state.upgrade() {
370 workspace::open_new(
371 Default::default(),
372 app_state,
373 cx,
374 |workspace, window, cx| {
375 cx.activate(true);
376 Editor::new_file(workspace, &Default::default(), window, cx)
377 },
378 )
379 .detach();
380 }
381 });
382}
383
384pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
385 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
386}
387
388pub trait DiagnosticRenderer {
389 fn render_group(
390 &self,
391 diagnostic_group: Vec<DiagnosticEntry<Point>>,
392 buffer_id: BufferId,
393 snapshot: EditorSnapshot,
394 editor: WeakEntity<Editor>,
395 cx: &mut App,
396 ) -> Vec<BlockProperties<Anchor>>;
397}
398
399pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
400
401impl gpui::Global for GlobalDiagnosticRenderer {}
402pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
403 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
404}
405
406pub struct SearchWithinRange;
407
408trait InvalidationRegion {
409 fn ranges(&self) -> &[Range<Anchor>];
410}
411
412#[derive(Clone, Debug, PartialEq)]
413pub enum SelectPhase {
414 Begin {
415 position: DisplayPoint,
416 add: bool,
417 click_count: usize,
418 },
419 BeginColumnar {
420 position: DisplayPoint,
421 reset: bool,
422 goal_column: u32,
423 },
424 Extend {
425 position: DisplayPoint,
426 click_count: usize,
427 },
428 Update {
429 position: DisplayPoint,
430 goal_column: u32,
431 scroll_delta: gpui::Point<f32>,
432 },
433 End,
434}
435
436#[derive(Clone, Debug)]
437pub enum SelectMode {
438 Character,
439 Word(Range<Anchor>),
440 Line(Range<Anchor>),
441 All,
442}
443
444#[derive(Copy, Clone, PartialEq, Eq, Debug)]
445pub enum EditorMode {
446 SingleLine {
447 auto_width: bool,
448 },
449 AutoHeight {
450 max_lines: usize,
451 },
452 Full {
453 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
454 scale_ui_elements_with_buffer_font_size: bool,
455 /// When set to `true`, the editor will render a background for the active line.
456 show_active_line_background: bool,
457 /// When set to `true`, the editor's height will be determined by its content.
458 sized_by_content: bool,
459 },
460}
461
462impl EditorMode {
463 pub fn full() -> Self {
464 Self::Full {
465 scale_ui_elements_with_buffer_font_size: true,
466 show_active_line_background: true,
467 sized_by_content: false,
468 }
469 }
470
471 pub fn is_full(&self) -> bool {
472 matches!(self, Self::Full { .. })
473 }
474}
475
476#[derive(Copy, Clone, Debug)]
477pub enum SoftWrap {
478 /// Prefer not to wrap at all.
479 ///
480 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
481 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
482 GitDiff,
483 /// Prefer a single line generally, unless an overly long line is encountered.
484 None,
485 /// Soft wrap lines that exceed the editor width.
486 EditorWidth,
487 /// Soft wrap lines at the preferred line length.
488 Column(u32),
489 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
490 Bounded(u32),
491}
492
493#[derive(Clone)]
494pub struct EditorStyle {
495 pub background: Hsla,
496 pub local_player: PlayerColor,
497 pub text: TextStyle,
498 pub scrollbar_width: Pixels,
499 pub syntax: Arc<SyntaxTheme>,
500 pub status: StatusColors,
501 pub inlay_hints_style: HighlightStyle,
502 pub inline_completion_styles: InlineCompletionStyles,
503 pub unnecessary_code_fade: f32,
504}
505
506impl Default for EditorStyle {
507 fn default() -> Self {
508 Self {
509 background: Hsla::default(),
510 local_player: PlayerColor::default(),
511 text: TextStyle::default(),
512 scrollbar_width: Pixels::default(),
513 syntax: Default::default(),
514 // HACK: Status colors don't have a real default.
515 // We should look into removing the status colors from the editor
516 // style and retrieve them directly from the theme.
517 status: StatusColors::dark(),
518 inlay_hints_style: HighlightStyle::default(),
519 inline_completion_styles: InlineCompletionStyles {
520 insertion: HighlightStyle::default(),
521 whitespace: HighlightStyle::default(),
522 },
523 unnecessary_code_fade: Default::default(),
524 }
525 }
526}
527
528pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
529 let show_background = language_settings::language_settings(None, None, cx)
530 .inlay_hints
531 .show_background;
532
533 HighlightStyle {
534 color: Some(cx.theme().status().hint),
535 background_color: show_background.then(|| cx.theme().status().hint_background),
536 ..HighlightStyle::default()
537 }
538}
539
540pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
541 InlineCompletionStyles {
542 insertion: HighlightStyle {
543 color: Some(cx.theme().status().predictive),
544 ..HighlightStyle::default()
545 },
546 whitespace: HighlightStyle {
547 background_color: Some(cx.theme().status().created_background),
548 ..HighlightStyle::default()
549 },
550 }
551}
552
553type CompletionId = usize;
554
555pub(crate) enum EditDisplayMode {
556 TabAccept,
557 DiffPopover,
558 Inline,
559}
560
561enum InlineCompletion {
562 Edit {
563 edits: Vec<(Range<Anchor>, String)>,
564 edit_preview: Option<EditPreview>,
565 display_mode: EditDisplayMode,
566 snapshot: BufferSnapshot,
567 },
568 Move {
569 target: Anchor,
570 snapshot: BufferSnapshot,
571 },
572}
573
574struct InlineCompletionState {
575 inlay_ids: Vec<InlayId>,
576 completion: InlineCompletion,
577 completion_id: Option<SharedString>,
578 invalidation_range: Range<Anchor>,
579}
580
581enum EditPredictionSettings {
582 Disabled,
583 Enabled {
584 show_in_menu: bool,
585 preview_requires_modifier: bool,
586 },
587}
588
589enum InlineCompletionHighlight {}
590
591#[derive(Debug, Clone)]
592struct InlineDiagnostic {
593 message: SharedString,
594 group_id: usize,
595 is_primary: bool,
596 start: Point,
597 severity: DiagnosticSeverity,
598}
599
600pub enum MenuInlineCompletionsPolicy {
601 Never,
602 ByProvider,
603}
604
605pub enum EditPredictionPreview {
606 /// Modifier is not pressed
607 Inactive { released_too_fast: bool },
608 /// Modifier pressed
609 Active {
610 since: Instant,
611 previous_scroll_position: Option<ScrollAnchor>,
612 },
613}
614
615impl EditPredictionPreview {
616 pub fn released_too_fast(&self) -> bool {
617 match self {
618 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
619 EditPredictionPreview::Active { .. } => false,
620 }
621 }
622
623 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
624 if let EditPredictionPreview::Active {
625 previous_scroll_position,
626 ..
627 } = self
628 {
629 *previous_scroll_position = scroll_position;
630 }
631 }
632}
633
634pub struct ContextMenuOptions {
635 pub min_entries_visible: usize,
636 pub max_entries_visible: usize,
637 pub placement: Option<ContextMenuPlacement>,
638}
639
640#[derive(Debug, Clone, PartialEq, Eq)]
641pub enum ContextMenuPlacement {
642 Above,
643 Below,
644}
645
646#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
647struct EditorActionId(usize);
648
649impl EditorActionId {
650 pub fn post_inc(&mut self) -> Self {
651 let answer = self.0;
652
653 *self = Self(answer + 1);
654
655 Self(answer)
656 }
657}
658
659// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
660// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
661
662type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
663type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
664
665#[derive(Default)]
666struct ScrollbarMarkerState {
667 scrollbar_size: Size<Pixels>,
668 dirty: bool,
669 markers: Arc<[PaintQuad]>,
670 pending_refresh: Option<Task<Result<()>>>,
671}
672
673impl ScrollbarMarkerState {
674 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
675 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
676 }
677}
678
679#[derive(Clone, Debug)]
680struct RunnableTasks {
681 templates: Vec<(TaskSourceKind, TaskTemplate)>,
682 offset: multi_buffer::Anchor,
683 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
684 column: u32,
685 // Values of all named captures, including those starting with '_'
686 extra_variables: HashMap<String, String>,
687 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
688 context_range: Range<BufferOffset>,
689}
690
691impl RunnableTasks {
692 fn resolve<'a>(
693 &'a self,
694 cx: &'a task::TaskContext,
695 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
696 self.templates.iter().filter_map(|(kind, template)| {
697 template
698 .resolve_task(&kind.to_id_base(), cx)
699 .map(|task| (kind.clone(), task))
700 })
701 }
702}
703
704#[derive(Clone)]
705struct ResolvedTasks {
706 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
707 position: Anchor,
708}
709
710#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
711struct BufferOffset(usize);
712
713// Addons allow storing per-editor state in other crates (e.g. Vim)
714pub trait Addon: 'static {
715 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
716
717 fn render_buffer_header_controls(
718 &self,
719 _: &ExcerptInfo,
720 _: &Window,
721 _: &App,
722 ) -> Option<AnyElement> {
723 None
724 }
725
726 fn to_any(&self) -> &dyn std::any::Any;
727
728 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
729 None
730 }
731}
732
733/// A set of caret positions, registered when the editor was edited.
734pub struct ChangeList {
735 changes: Vec<Vec<Anchor>>,
736 /// Currently "selected" change.
737 position: Option<usize>,
738}
739
740impl ChangeList {
741 pub fn new() -> Self {
742 Self {
743 changes: Vec::new(),
744 position: None,
745 }
746 }
747
748 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
749 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
750 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
751 if self.changes.is_empty() {
752 return None;
753 }
754
755 let prev = self.position.unwrap_or(self.changes.len());
756 let next = if direction == Direction::Prev {
757 prev.saturating_sub(count)
758 } else {
759 (prev + count).min(self.changes.len() - 1)
760 };
761 self.position = Some(next);
762 self.changes.get(next).map(|anchors| anchors.as_slice())
763 }
764
765 /// Adds a new change to the list, resetting the change list position.
766 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
767 self.position.take();
768 if pop_state {
769 self.changes.pop();
770 }
771 self.changes.push(new_positions.clone());
772 }
773
774 pub fn last(&self) -> Option<&[Anchor]> {
775 self.changes.last().map(|anchors| anchors.as_slice())
776 }
777}
778
779/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
780///
781/// See the [module level documentation](self) for more information.
782pub struct Editor {
783 focus_handle: FocusHandle,
784 last_focused_descendant: Option<WeakFocusHandle>,
785 /// The text buffer being edited
786 buffer: Entity<MultiBuffer>,
787 /// Map of how text in the buffer should be displayed.
788 /// Handles soft wraps, folds, fake inlay text insertions, etc.
789 pub display_map: Entity<DisplayMap>,
790 pub selections: SelectionsCollection,
791 pub scroll_manager: ScrollManager,
792 /// When inline assist editors are linked, they all render cursors because
793 /// typing enters text into each of them, even the ones that aren't focused.
794 pub(crate) show_cursor_when_unfocused: bool,
795 columnar_selection_tail: Option<Anchor>,
796 add_selections_state: Option<AddSelectionsState>,
797 select_next_state: Option<SelectNextState>,
798 select_prev_state: Option<SelectNextState>,
799 selection_history: SelectionHistory,
800 autoclose_regions: Vec<AutocloseRegion>,
801 snippet_stack: InvalidationStack<SnippetState>,
802 select_syntax_node_history: SelectSyntaxNodeHistory,
803 ime_transaction: Option<TransactionId>,
804 active_diagnostics: ActiveDiagnostic,
805 show_inline_diagnostics: bool,
806 inline_diagnostics_update: Task<()>,
807 inline_diagnostics_enabled: bool,
808 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
809 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
810 hard_wrap: Option<usize>,
811
812 // TODO: make this a access method
813 pub project: Option<Entity<Project>>,
814 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
815 completion_provider: Option<Box<dyn CompletionProvider>>,
816 collaboration_hub: Option<Box<dyn CollaborationHub>>,
817 blink_manager: Entity<BlinkManager>,
818 show_cursor_names: bool,
819 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
820 pub show_local_selections: bool,
821 mode: EditorMode,
822 show_breadcrumbs: bool,
823 show_gutter: bool,
824 show_scrollbars: bool,
825 disable_scrolling: bool,
826 disable_expand_excerpt_buttons: bool,
827 show_line_numbers: Option<bool>,
828 use_relative_line_numbers: Option<bool>,
829 show_git_diff_gutter: Option<bool>,
830 show_code_actions: Option<bool>,
831 show_runnables: Option<bool>,
832 show_breakpoints: Option<bool>,
833 show_wrap_guides: Option<bool>,
834 show_indent_guides: Option<bool>,
835 placeholder_text: Option<Arc<str>>,
836 highlight_order: usize,
837 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
838 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
839 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
840 scrollbar_marker_state: ScrollbarMarkerState,
841 active_indent_guides_state: ActiveIndentGuidesState,
842 nav_history: Option<ItemNavHistory>,
843 context_menu: RefCell<Option<CodeContextMenu>>,
844 context_menu_options: Option<ContextMenuOptions>,
845 mouse_context_menu: Option<MouseContextMenu>,
846 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
847 signature_help_state: SignatureHelpState,
848 auto_signature_help: Option<bool>,
849 find_all_references_task_sources: Vec<Anchor>,
850 next_completion_id: CompletionId,
851 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
852 code_actions_task: Option<Task<Result<()>>>,
853 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
854 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
855 document_highlights_task: Option<Task<()>>,
856 linked_editing_range_task: Option<Task<Option<()>>>,
857 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
858 pending_rename: Option<RenameState>,
859 searchable: bool,
860 cursor_shape: CursorShape,
861 current_line_highlight: Option<CurrentLineHighlight>,
862 collapse_matches: bool,
863 autoindent_mode: Option<AutoindentMode>,
864 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
865 input_enabled: bool,
866 use_modal_editing: bool,
867 read_only: bool,
868 leader_peer_id: Option<PeerId>,
869 remote_id: Option<ViewId>,
870 hover_state: HoverState,
871 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
872 gutter_hovered: bool,
873 hovered_link_state: Option<HoveredLinkState>,
874 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
875 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
876 active_inline_completion: Option<InlineCompletionState>,
877 /// Used to prevent flickering as the user types while the menu is open
878 stale_inline_completion_in_menu: Option<InlineCompletionState>,
879 edit_prediction_settings: EditPredictionSettings,
880 inline_completions_hidden_for_vim_mode: bool,
881 show_inline_completions_override: Option<bool>,
882 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
883 edit_prediction_preview: EditPredictionPreview,
884 edit_prediction_indent_conflict: bool,
885 edit_prediction_requires_modifier_in_indent_conflict: bool,
886 inlay_hint_cache: InlayHintCache,
887 next_inlay_id: usize,
888 _subscriptions: Vec<Subscription>,
889 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
890 gutter_dimensions: GutterDimensions,
891 style: Option<EditorStyle>,
892 text_style_refinement: Option<TextStyleRefinement>,
893 next_editor_action_id: EditorActionId,
894 editor_actions:
895 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
896 use_autoclose: bool,
897 use_auto_surround: bool,
898 auto_replace_emoji_shortcode: bool,
899 jsx_tag_auto_close_enabled_in_any_buffer: bool,
900 show_git_blame_gutter: bool,
901 show_git_blame_inline: bool,
902 show_git_blame_inline_delay_task: Option<Task<()>>,
903 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
904 git_blame_inline_enabled: bool,
905 render_diff_hunk_controls: RenderDiffHunkControlsFn,
906 serialize_dirty_buffers: bool,
907 show_selection_menu: Option<bool>,
908 blame: Option<Entity<GitBlame>>,
909 blame_subscription: Option<Subscription>,
910 custom_context_menu: Option<
911 Box<
912 dyn 'static
913 + Fn(
914 &mut Self,
915 DisplayPoint,
916 &mut Window,
917 &mut Context<Self>,
918 ) -> Option<Entity<ui::ContextMenu>>,
919 >,
920 >,
921 last_bounds: Option<Bounds<Pixels>>,
922 last_position_map: Option<Rc<PositionMap>>,
923 expect_bounds_change: Option<Bounds<Pixels>>,
924 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
925 tasks_update_task: Option<Task<()>>,
926 breakpoint_store: Option<Entity<BreakpointStore>>,
927 /// Allow's a user to create a breakpoint by selecting this indicator
928 /// It should be None while a user is not hovering over the gutter
929 /// Otherwise it represents the point that the breakpoint will be shown
930 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
931 in_project_search: bool,
932 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
933 breadcrumb_header: Option<String>,
934 focused_block: Option<FocusedBlock>,
935 next_scroll_position: NextScrollCursorCenterTopBottom,
936 addons: HashMap<TypeId, Box<dyn Addon>>,
937 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
938 load_diff_task: Option<Shared<Task<()>>>,
939 selection_mark_mode: bool,
940 toggle_fold_multiple_buffers: Task<()>,
941 _scroll_cursor_center_top_bottom_task: Task<()>,
942 serialize_selections: Task<()>,
943 serialize_folds: Task<()>,
944 mouse_cursor_hidden: bool,
945 hide_mouse_mode: HideMouseMode,
946 pub change_list: ChangeList,
947 inline_value_cache: InlineValueCache,
948}
949
950#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
951enum NextScrollCursorCenterTopBottom {
952 #[default]
953 Center,
954 Top,
955 Bottom,
956}
957
958impl NextScrollCursorCenterTopBottom {
959 fn next(&self) -> Self {
960 match self {
961 Self::Center => Self::Top,
962 Self::Top => Self::Bottom,
963 Self::Bottom => Self::Center,
964 }
965 }
966}
967
968#[derive(Clone)]
969pub struct EditorSnapshot {
970 pub mode: EditorMode,
971 show_gutter: bool,
972 show_line_numbers: Option<bool>,
973 show_git_diff_gutter: Option<bool>,
974 show_code_actions: Option<bool>,
975 show_runnables: Option<bool>,
976 show_breakpoints: Option<bool>,
977 git_blame_gutter_max_author_length: Option<usize>,
978 pub display_snapshot: DisplaySnapshot,
979 pub placeholder_text: Option<Arc<str>>,
980 is_focused: bool,
981 scroll_anchor: ScrollAnchor,
982 ongoing_scroll: OngoingScroll,
983 current_line_highlight: CurrentLineHighlight,
984 gutter_hovered: bool,
985}
986
987#[derive(Default, Debug, Clone, Copy)]
988pub struct GutterDimensions {
989 pub left_padding: Pixels,
990 pub right_padding: Pixels,
991 pub width: Pixels,
992 pub margin: Pixels,
993 pub git_blame_entries_width: Option<Pixels>,
994}
995
996impl GutterDimensions {
997 /// The full width of the space taken up by the gutter.
998 pub fn full_width(&self) -> Pixels {
999 self.margin + self.width
1000 }
1001
1002 /// The width of the space reserved for the fold indicators,
1003 /// use alongside 'justify_end' and `gutter_width` to
1004 /// right align content with the line numbers
1005 pub fn fold_area_width(&self) -> Pixels {
1006 self.margin + self.right_padding
1007 }
1008}
1009
1010#[derive(Debug)]
1011pub struct RemoteSelection {
1012 pub replica_id: ReplicaId,
1013 pub selection: Selection<Anchor>,
1014 pub cursor_shape: CursorShape,
1015 pub peer_id: PeerId,
1016 pub line_mode: bool,
1017 pub participant_index: Option<ParticipantIndex>,
1018 pub user_name: Option<SharedString>,
1019}
1020
1021#[derive(Clone, Debug)]
1022struct SelectionHistoryEntry {
1023 selections: Arc<[Selection<Anchor>]>,
1024 select_next_state: Option<SelectNextState>,
1025 select_prev_state: Option<SelectNextState>,
1026 add_selections_state: Option<AddSelectionsState>,
1027}
1028
1029enum SelectionHistoryMode {
1030 Normal,
1031 Undoing,
1032 Redoing,
1033}
1034
1035#[derive(Clone, PartialEq, Eq, Hash)]
1036struct HoveredCursor {
1037 replica_id: u16,
1038 selection_id: usize,
1039}
1040
1041impl Default for SelectionHistoryMode {
1042 fn default() -> Self {
1043 Self::Normal
1044 }
1045}
1046
1047#[derive(Default)]
1048struct SelectionHistory {
1049 #[allow(clippy::type_complexity)]
1050 selections_by_transaction:
1051 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1052 mode: SelectionHistoryMode,
1053 undo_stack: VecDeque<SelectionHistoryEntry>,
1054 redo_stack: VecDeque<SelectionHistoryEntry>,
1055}
1056
1057impl SelectionHistory {
1058 fn insert_transaction(
1059 &mut self,
1060 transaction_id: TransactionId,
1061 selections: Arc<[Selection<Anchor>]>,
1062 ) {
1063 self.selections_by_transaction
1064 .insert(transaction_id, (selections, None));
1065 }
1066
1067 #[allow(clippy::type_complexity)]
1068 fn transaction(
1069 &self,
1070 transaction_id: TransactionId,
1071 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1072 self.selections_by_transaction.get(&transaction_id)
1073 }
1074
1075 #[allow(clippy::type_complexity)]
1076 fn transaction_mut(
1077 &mut self,
1078 transaction_id: TransactionId,
1079 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1080 self.selections_by_transaction.get_mut(&transaction_id)
1081 }
1082
1083 fn push(&mut self, entry: SelectionHistoryEntry) {
1084 if !entry.selections.is_empty() {
1085 match self.mode {
1086 SelectionHistoryMode::Normal => {
1087 self.push_undo(entry);
1088 self.redo_stack.clear();
1089 }
1090 SelectionHistoryMode::Undoing => self.push_redo(entry),
1091 SelectionHistoryMode::Redoing => self.push_undo(entry),
1092 }
1093 }
1094 }
1095
1096 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1097 if self
1098 .undo_stack
1099 .back()
1100 .map_or(true, |e| e.selections != entry.selections)
1101 {
1102 self.undo_stack.push_back(entry);
1103 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1104 self.undo_stack.pop_front();
1105 }
1106 }
1107 }
1108
1109 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1110 if self
1111 .redo_stack
1112 .back()
1113 .map_or(true, |e| e.selections != entry.selections)
1114 {
1115 self.redo_stack.push_back(entry);
1116 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1117 self.redo_stack.pop_front();
1118 }
1119 }
1120 }
1121}
1122
1123#[derive(Clone, Copy)]
1124pub struct RowHighlightOptions {
1125 pub autoscroll: bool,
1126 pub include_gutter: bool,
1127}
1128
1129impl Default for RowHighlightOptions {
1130 fn default() -> Self {
1131 Self {
1132 autoscroll: Default::default(),
1133 include_gutter: true,
1134 }
1135 }
1136}
1137
1138struct RowHighlight {
1139 index: usize,
1140 range: Range<Anchor>,
1141 color: Hsla,
1142 options: RowHighlightOptions,
1143 type_id: TypeId,
1144}
1145
1146#[derive(Clone, Debug)]
1147struct AddSelectionsState {
1148 above: bool,
1149 stack: Vec<usize>,
1150}
1151
1152#[derive(Clone)]
1153struct SelectNextState {
1154 query: AhoCorasick,
1155 wordwise: bool,
1156 done: bool,
1157}
1158
1159impl std::fmt::Debug for SelectNextState {
1160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1161 f.debug_struct(std::any::type_name::<Self>())
1162 .field("wordwise", &self.wordwise)
1163 .field("done", &self.done)
1164 .finish()
1165 }
1166}
1167
1168#[derive(Debug)]
1169struct AutocloseRegion {
1170 selection_id: usize,
1171 range: Range<Anchor>,
1172 pair: BracketPair,
1173}
1174
1175#[derive(Debug)]
1176struct SnippetState {
1177 ranges: Vec<Vec<Range<Anchor>>>,
1178 active_index: usize,
1179 choices: Vec<Option<Vec<String>>>,
1180}
1181
1182#[doc(hidden)]
1183pub struct RenameState {
1184 pub range: Range<Anchor>,
1185 pub old_name: Arc<str>,
1186 pub editor: Entity<Editor>,
1187 block_id: CustomBlockId,
1188}
1189
1190struct InvalidationStack<T>(Vec<T>);
1191
1192struct RegisteredInlineCompletionProvider {
1193 provider: Arc<dyn InlineCompletionProviderHandle>,
1194 _subscription: Subscription,
1195}
1196
1197#[derive(Debug, PartialEq, Eq)]
1198pub struct ActiveDiagnosticGroup {
1199 pub active_range: Range<Anchor>,
1200 pub active_message: String,
1201 pub group_id: usize,
1202 pub blocks: HashSet<CustomBlockId>,
1203}
1204
1205#[derive(Debug, PartialEq, Eq)]
1206#[allow(clippy::large_enum_variant)]
1207pub(crate) enum ActiveDiagnostic {
1208 None,
1209 All,
1210 Group(ActiveDiagnosticGroup),
1211}
1212
1213#[derive(Serialize, Deserialize, Clone, Debug)]
1214pub struct ClipboardSelection {
1215 /// The number of bytes in this selection.
1216 pub len: usize,
1217 /// Whether this was a full-line selection.
1218 pub is_entire_line: bool,
1219 /// The indentation of the first line when this content was originally copied.
1220 pub first_line_indent: u32,
1221}
1222
1223// selections, scroll behavior, was newest selection reversed
1224type SelectSyntaxNodeHistoryState = (
1225 Box<[Selection<usize>]>,
1226 SelectSyntaxNodeScrollBehavior,
1227 bool,
1228);
1229
1230#[derive(Default)]
1231struct SelectSyntaxNodeHistory {
1232 stack: Vec<SelectSyntaxNodeHistoryState>,
1233 // disable temporarily to allow changing selections without losing the stack
1234 pub disable_clearing: bool,
1235}
1236
1237impl SelectSyntaxNodeHistory {
1238 pub fn try_clear(&mut self) {
1239 if !self.disable_clearing {
1240 self.stack.clear();
1241 }
1242 }
1243
1244 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1245 self.stack.push(selection);
1246 }
1247
1248 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1249 self.stack.pop()
1250 }
1251}
1252
1253enum SelectSyntaxNodeScrollBehavior {
1254 CursorTop,
1255 FitSelection,
1256 CursorBottom,
1257}
1258
1259#[derive(Debug)]
1260pub(crate) struct NavigationData {
1261 cursor_anchor: Anchor,
1262 cursor_position: Point,
1263 scroll_anchor: ScrollAnchor,
1264 scroll_top_row: u32,
1265}
1266
1267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1268pub enum GotoDefinitionKind {
1269 Symbol,
1270 Declaration,
1271 Type,
1272 Implementation,
1273}
1274
1275#[derive(Debug, Clone)]
1276enum InlayHintRefreshReason {
1277 ModifiersChanged(bool),
1278 Toggle(bool),
1279 SettingsChange(InlayHintSettings),
1280 NewLinesShown,
1281 BufferEdited(HashSet<Arc<Language>>),
1282 RefreshRequested,
1283 ExcerptsRemoved(Vec<ExcerptId>),
1284}
1285
1286impl InlayHintRefreshReason {
1287 fn description(&self) -> &'static str {
1288 match self {
1289 Self::ModifiersChanged(_) => "modifiers changed",
1290 Self::Toggle(_) => "toggle",
1291 Self::SettingsChange(_) => "settings change",
1292 Self::NewLinesShown => "new lines shown",
1293 Self::BufferEdited(_) => "buffer edited",
1294 Self::RefreshRequested => "refresh requested",
1295 Self::ExcerptsRemoved(_) => "excerpts removed",
1296 }
1297 }
1298}
1299
1300pub enum FormatTarget {
1301 Buffers,
1302 Ranges(Vec<Range<MultiBufferPoint>>),
1303}
1304
1305pub(crate) struct FocusedBlock {
1306 id: BlockId,
1307 focus_handle: WeakFocusHandle,
1308}
1309
1310#[derive(Clone)]
1311enum JumpData {
1312 MultiBufferRow {
1313 row: MultiBufferRow,
1314 line_offset_from_top: u32,
1315 },
1316 MultiBufferPoint {
1317 excerpt_id: ExcerptId,
1318 position: Point,
1319 anchor: text::Anchor,
1320 line_offset_from_top: u32,
1321 },
1322}
1323
1324pub enum MultibufferSelectionMode {
1325 First,
1326 All,
1327}
1328
1329#[derive(Clone, Copy, Debug, Default)]
1330pub struct RewrapOptions {
1331 pub override_language_settings: bool,
1332 pub preserve_existing_whitespace: bool,
1333}
1334
1335impl Editor {
1336 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1337 let buffer = cx.new(|cx| Buffer::local("", cx));
1338 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1339 Self::new(
1340 EditorMode::SingleLine { auto_width: false },
1341 buffer,
1342 None,
1343 window,
1344 cx,
1345 )
1346 }
1347
1348 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1349 let buffer = cx.new(|cx| Buffer::local("", cx));
1350 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1351 Self::new(EditorMode::full(), buffer, None, window, cx)
1352 }
1353
1354 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1355 let buffer = cx.new(|cx| Buffer::local("", cx));
1356 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1357 Self::new(
1358 EditorMode::SingleLine { auto_width: true },
1359 buffer,
1360 None,
1361 window,
1362 cx,
1363 )
1364 }
1365
1366 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1367 let buffer = cx.new(|cx| Buffer::local("", cx));
1368 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1369 Self::new(
1370 EditorMode::AutoHeight { max_lines },
1371 buffer,
1372 None,
1373 window,
1374 cx,
1375 )
1376 }
1377
1378 pub fn for_buffer(
1379 buffer: Entity<Buffer>,
1380 project: Option<Entity<Project>>,
1381 window: &mut Window,
1382 cx: &mut Context<Self>,
1383 ) -> Self {
1384 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1385 Self::new(EditorMode::full(), buffer, project, window, cx)
1386 }
1387
1388 pub fn for_multibuffer(
1389 buffer: Entity<MultiBuffer>,
1390 project: Option<Entity<Project>>,
1391 window: &mut Window,
1392 cx: &mut Context<Self>,
1393 ) -> Self {
1394 Self::new(EditorMode::full(), buffer, project, window, cx)
1395 }
1396
1397 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1398 let mut clone = Self::new(
1399 self.mode,
1400 self.buffer.clone(),
1401 self.project.clone(),
1402 window,
1403 cx,
1404 );
1405 self.display_map.update(cx, |display_map, cx| {
1406 let snapshot = display_map.snapshot(cx);
1407 clone.display_map.update(cx, |display_map, cx| {
1408 display_map.set_state(&snapshot, cx);
1409 });
1410 });
1411 clone.folds_did_change(cx);
1412 clone.selections.clone_state(&self.selections);
1413 clone.scroll_manager.clone_state(&self.scroll_manager);
1414 clone.searchable = self.searchable;
1415 clone.read_only = self.read_only;
1416 clone
1417 }
1418
1419 pub fn new(
1420 mode: EditorMode,
1421 buffer: Entity<MultiBuffer>,
1422 project: Option<Entity<Project>>,
1423 window: &mut Window,
1424 cx: &mut Context<Self>,
1425 ) -> Self {
1426 let style = window.text_style();
1427 let font_size = style.font_size.to_pixels(window.rem_size());
1428 let editor = cx.entity().downgrade();
1429 let fold_placeholder = FoldPlaceholder {
1430 constrain_width: true,
1431 render: Arc::new(move |fold_id, fold_range, cx| {
1432 let editor = editor.clone();
1433 div()
1434 .id(fold_id)
1435 .bg(cx.theme().colors().ghost_element_background)
1436 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1437 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1438 .rounded_xs()
1439 .size_full()
1440 .cursor_pointer()
1441 .child("⋯")
1442 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1443 .on_click(move |_, _window, cx| {
1444 editor
1445 .update(cx, |editor, cx| {
1446 editor.unfold_ranges(
1447 &[fold_range.start..fold_range.end],
1448 true,
1449 false,
1450 cx,
1451 );
1452 cx.stop_propagation();
1453 })
1454 .ok();
1455 })
1456 .into_any()
1457 }),
1458 merge_adjacent: true,
1459 ..Default::default()
1460 };
1461 let display_map = cx.new(|cx| {
1462 DisplayMap::new(
1463 buffer.clone(),
1464 style.font(),
1465 font_size,
1466 None,
1467 FILE_HEADER_HEIGHT,
1468 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1469 fold_placeholder,
1470 cx,
1471 )
1472 });
1473
1474 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1475
1476 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1477
1478 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1479 .then(|| language_settings::SoftWrap::None);
1480
1481 let mut project_subscriptions = Vec::new();
1482 if mode.is_full() {
1483 if let Some(project) = project.as_ref() {
1484 project_subscriptions.push(cx.subscribe_in(
1485 project,
1486 window,
1487 |editor, _, event, window, cx| match event {
1488 project::Event::RefreshCodeLens => {
1489 // we always query lens with actions, without storing them, always refreshing them
1490 }
1491 project::Event::RefreshInlayHints => {
1492 editor
1493 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1494 }
1495 project::Event::SnippetEdit(id, snippet_edits) => {
1496 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1497 let focus_handle = editor.focus_handle(cx);
1498 if focus_handle.is_focused(window) {
1499 let snapshot = buffer.read(cx).snapshot();
1500 for (range, snippet) in snippet_edits {
1501 let editor_range =
1502 language::range_from_lsp(*range).to_offset(&snapshot);
1503 editor
1504 .insert_snippet(
1505 &[editor_range],
1506 snippet.clone(),
1507 window,
1508 cx,
1509 )
1510 .ok();
1511 }
1512 }
1513 }
1514 }
1515 _ => {}
1516 },
1517 ));
1518 if let Some(task_inventory) = project
1519 .read(cx)
1520 .task_store()
1521 .read(cx)
1522 .task_inventory()
1523 .cloned()
1524 {
1525 project_subscriptions.push(cx.observe_in(
1526 &task_inventory,
1527 window,
1528 |editor, _, window, cx| {
1529 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1530 },
1531 ));
1532 };
1533
1534 project_subscriptions.push(cx.subscribe_in(
1535 &project.read(cx).breakpoint_store(),
1536 window,
1537 |editor, _, event, window, cx| match event {
1538 BreakpointStoreEvent::ActiveDebugLineChanged => {
1539 if editor.go_to_active_debug_line(window, cx) {
1540 cx.stop_propagation();
1541 }
1542
1543 editor.refresh_inline_values(cx);
1544 }
1545 _ => {}
1546 },
1547 ));
1548 }
1549 }
1550
1551 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1552
1553 let inlay_hint_settings =
1554 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1555 let focus_handle = cx.focus_handle();
1556 cx.on_focus(&focus_handle, window, Self::handle_focus)
1557 .detach();
1558 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1559 .detach();
1560 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1561 .detach();
1562 cx.on_blur(&focus_handle, window, Self::handle_blur)
1563 .detach();
1564
1565 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1566 Some(false)
1567 } else {
1568 None
1569 };
1570
1571 let breakpoint_store = match (mode, project.as_ref()) {
1572 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1573 _ => None,
1574 };
1575
1576 let mut code_action_providers = Vec::new();
1577 let mut load_uncommitted_diff = None;
1578 if let Some(project) = project.clone() {
1579 load_uncommitted_diff = Some(
1580 get_uncommitted_diff_for_buffer(
1581 &project,
1582 buffer.read(cx).all_buffers(),
1583 buffer.clone(),
1584 cx,
1585 )
1586 .shared(),
1587 );
1588 code_action_providers.push(Rc::new(project) as Rc<_>);
1589 }
1590
1591 let mut this = Self {
1592 focus_handle,
1593 show_cursor_when_unfocused: false,
1594 last_focused_descendant: None,
1595 buffer: buffer.clone(),
1596 display_map: display_map.clone(),
1597 selections,
1598 scroll_manager: ScrollManager::new(cx),
1599 columnar_selection_tail: None,
1600 add_selections_state: None,
1601 select_next_state: None,
1602 select_prev_state: None,
1603 selection_history: Default::default(),
1604 autoclose_regions: Default::default(),
1605 snippet_stack: Default::default(),
1606 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1607 ime_transaction: Default::default(),
1608 active_diagnostics: ActiveDiagnostic::None,
1609 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1610 inline_diagnostics_update: Task::ready(()),
1611 inline_diagnostics: Vec::new(),
1612 soft_wrap_mode_override,
1613 hard_wrap: None,
1614 completion_provider: project.clone().map(|project| Box::new(project) as _),
1615 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1616 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1617 project,
1618 blink_manager: blink_manager.clone(),
1619 show_local_selections: true,
1620 show_scrollbars: true,
1621 disable_scrolling: false,
1622 mode,
1623 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1624 show_gutter: mode.is_full(),
1625 show_line_numbers: None,
1626 use_relative_line_numbers: None,
1627 disable_expand_excerpt_buttons: false,
1628 show_git_diff_gutter: None,
1629 show_code_actions: None,
1630 show_runnables: None,
1631 show_breakpoints: None,
1632 show_wrap_guides: None,
1633 show_indent_guides,
1634 placeholder_text: None,
1635 highlight_order: 0,
1636 highlighted_rows: HashMap::default(),
1637 background_highlights: Default::default(),
1638 gutter_highlights: TreeMap::default(),
1639 scrollbar_marker_state: ScrollbarMarkerState::default(),
1640 active_indent_guides_state: ActiveIndentGuidesState::default(),
1641 nav_history: None,
1642 context_menu: RefCell::new(None),
1643 context_menu_options: None,
1644 mouse_context_menu: None,
1645 completion_tasks: Default::default(),
1646 signature_help_state: SignatureHelpState::default(),
1647 auto_signature_help: None,
1648 find_all_references_task_sources: Vec::new(),
1649 next_completion_id: 0,
1650 next_inlay_id: 0,
1651 code_action_providers,
1652 available_code_actions: Default::default(),
1653 code_actions_task: Default::default(),
1654 quick_selection_highlight_task: Default::default(),
1655 debounced_selection_highlight_task: Default::default(),
1656 document_highlights_task: Default::default(),
1657 linked_editing_range_task: Default::default(),
1658 pending_rename: Default::default(),
1659 searchable: true,
1660 cursor_shape: EditorSettings::get_global(cx)
1661 .cursor_shape
1662 .unwrap_or_default(),
1663 current_line_highlight: None,
1664 autoindent_mode: Some(AutoindentMode::EachLine),
1665 collapse_matches: false,
1666 workspace: None,
1667 input_enabled: true,
1668 use_modal_editing: mode.is_full(),
1669 read_only: false,
1670 use_autoclose: true,
1671 use_auto_surround: true,
1672 auto_replace_emoji_shortcode: false,
1673 jsx_tag_auto_close_enabled_in_any_buffer: false,
1674 leader_peer_id: None,
1675 remote_id: None,
1676 hover_state: Default::default(),
1677 pending_mouse_down: None,
1678 hovered_link_state: Default::default(),
1679 edit_prediction_provider: None,
1680 active_inline_completion: None,
1681 stale_inline_completion_in_menu: None,
1682 edit_prediction_preview: EditPredictionPreview::Inactive {
1683 released_too_fast: false,
1684 },
1685 inline_diagnostics_enabled: mode.is_full(),
1686 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1687 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1688
1689 gutter_hovered: false,
1690 pixel_position_of_newest_cursor: None,
1691 last_bounds: None,
1692 last_position_map: None,
1693 expect_bounds_change: None,
1694 gutter_dimensions: GutterDimensions::default(),
1695 style: None,
1696 show_cursor_names: false,
1697 hovered_cursors: Default::default(),
1698 next_editor_action_id: EditorActionId::default(),
1699 editor_actions: Rc::default(),
1700 inline_completions_hidden_for_vim_mode: false,
1701 show_inline_completions_override: None,
1702 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1703 edit_prediction_settings: EditPredictionSettings::Disabled,
1704 edit_prediction_indent_conflict: false,
1705 edit_prediction_requires_modifier_in_indent_conflict: true,
1706 custom_context_menu: None,
1707 show_git_blame_gutter: false,
1708 show_git_blame_inline: false,
1709 show_selection_menu: None,
1710 show_git_blame_inline_delay_task: None,
1711 git_blame_inline_tooltip: None,
1712 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1713 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1714 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1715 .session
1716 .restore_unsaved_buffers,
1717 blame: None,
1718 blame_subscription: None,
1719 tasks: Default::default(),
1720
1721 breakpoint_store,
1722 gutter_breakpoint_indicator: (None, None),
1723 _subscriptions: vec![
1724 cx.observe(&buffer, Self::on_buffer_changed),
1725 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1726 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1727 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1728 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1729 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1730 cx.observe_window_activation(window, |editor, window, cx| {
1731 let active = window.is_window_active();
1732 editor.blink_manager.update(cx, |blink_manager, cx| {
1733 if active {
1734 blink_manager.enable(cx);
1735 } else {
1736 blink_manager.disable(cx);
1737 }
1738 });
1739 }),
1740 ],
1741 tasks_update_task: None,
1742 linked_edit_ranges: Default::default(),
1743 in_project_search: false,
1744 previous_search_ranges: None,
1745 breadcrumb_header: None,
1746 focused_block: None,
1747 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1748 addons: HashMap::default(),
1749 registered_buffers: HashMap::default(),
1750 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1751 selection_mark_mode: false,
1752 toggle_fold_multiple_buffers: Task::ready(()),
1753 serialize_selections: Task::ready(()),
1754 serialize_folds: Task::ready(()),
1755 text_style_refinement: None,
1756 load_diff_task: load_uncommitted_diff,
1757 mouse_cursor_hidden: false,
1758 hide_mouse_mode: EditorSettings::get_global(cx)
1759 .hide_mouse
1760 .unwrap_or_default(),
1761 change_list: ChangeList::new(),
1762 };
1763 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1764 this._subscriptions
1765 .push(cx.observe(breakpoints, |_, _, cx| {
1766 cx.notify();
1767 }));
1768 }
1769 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1770 this._subscriptions.extend(project_subscriptions);
1771
1772 this._subscriptions.push(cx.subscribe_in(
1773 &cx.entity(),
1774 window,
1775 |editor, _, e: &EditorEvent, window, cx| match e {
1776 EditorEvent::ScrollPositionChanged { local, .. } => {
1777 if *local {
1778 let new_anchor = editor.scroll_manager.anchor();
1779 let snapshot = editor.snapshot(window, cx);
1780 editor.update_restoration_data(cx, move |data| {
1781 data.scroll_position = (
1782 new_anchor.top_row(&snapshot.buffer_snapshot),
1783 new_anchor.offset,
1784 );
1785 });
1786 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1787 }
1788 }
1789 EditorEvent::Edited { .. } => {
1790 if !vim_enabled(cx) {
1791 let (map, selections) = editor.selections.all_adjusted_display(cx);
1792 let pop_state = editor
1793 .change_list
1794 .last()
1795 .map(|previous| {
1796 previous.len() == selections.len()
1797 && previous.iter().enumerate().all(|(ix, p)| {
1798 p.to_display_point(&map).row()
1799 == selections[ix].head().row()
1800 })
1801 })
1802 .unwrap_or(false);
1803 let new_positions = selections
1804 .into_iter()
1805 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1806 .collect();
1807 editor
1808 .change_list
1809 .push_to_change_list(pop_state, new_positions);
1810 }
1811 }
1812 _ => (),
1813 },
1814 ));
1815
1816 if let Some(dap_store) = this
1817 .project
1818 .as_ref()
1819 .map(|project| project.read(cx).dap_store())
1820 {
1821 let weak_editor = cx.weak_entity();
1822
1823 this._subscriptions
1824 .push(
1825 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1826 let session_entity = cx.entity();
1827 weak_editor
1828 .update(cx, |editor, cx| {
1829 editor._subscriptions.push(
1830 cx.subscribe(&session_entity, Self::on_debug_session_event),
1831 );
1832 })
1833 .ok();
1834 }),
1835 );
1836
1837 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1838 this._subscriptions
1839 .push(cx.subscribe(&session, Self::on_debug_session_event));
1840 }
1841 }
1842
1843 this.end_selection(window, cx);
1844 this.scroll_manager.show_scrollbars(window, cx);
1845 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1846
1847 if mode.is_full() {
1848 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1849 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1850
1851 if this.git_blame_inline_enabled {
1852 this.git_blame_inline_enabled = true;
1853 this.start_git_blame_inline(false, window, cx);
1854 }
1855
1856 this.go_to_active_debug_line(window, cx);
1857
1858 if let Some(buffer) = buffer.read(cx).as_singleton() {
1859 if let Some(project) = this.project.as_ref() {
1860 let handle = project.update(cx, |project, cx| {
1861 project.register_buffer_with_language_servers(&buffer, cx)
1862 });
1863 this.registered_buffers
1864 .insert(buffer.read(cx).remote_id(), handle);
1865 }
1866 }
1867 }
1868
1869 this.report_editor_event("Editor Opened", None, cx);
1870 this
1871 }
1872
1873 pub fn deploy_mouse_context_menu(
1874 &mut self,
1875 position: gpui::Point<Pixels>,
1876 context_menu: Entity<ContextMenu>,
1877 window: &mut Window,
1878 cx: &mut Context<Self>,
1879 ) {
1880 self.mouse_context_menu = Some(MouseContextMenu::new(
1881 self,
1882 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1883 context_menu,
1884 window,
1885 cx,
1886 ));
1887 }
1888
1889 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1890 self.mouse_context_menu
1891 .as_ref()
1892 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1893 }
1894
1895 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1896 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1897 }
1898
1899 fn key_context_internal(
1900 &self,
1901 has_active_edit_prediction: bool,
1902 window: &Window,
1903 cx: &App,
1904 ) -> KeyContext {
1905 let mut key_context = KeyContext::new_with_defaults();
1906 key_context.add("Editor");
1907 let mode = match self.mode {
1908 EditorMode::SingleLine { .. } => "single_line",
1909 EditorMode::AutoHeight { .. } => "auto_height",
1910 EditorMode::Full { .. } => "full",
1911 };
1912
1913 if EditorSettings::jupyter_enabled(cx) {
1914 key_context.add("jupyter");
1915 }
1916
1917 key_context.set("mode", mode);
1918 if self.pending_rename.is_some() {
1919 key_context.add("renaming");
1920 }
1921
1922 match self.context_menu.borrow().as_ref() {
1923 Some(CodeContextMenu::Completions(_)) => {
1924 key_context.add("menu");
1925 key_context.add("showing_completions");
1926 }
1927 Some(CodeContextMenu::CodeActions(_)) => {
1928 key_context.add("menu");
1929 key_context.add("showing_code_actions")
1930 }
1931 None => {}
1932 }
1933
1934 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1935 if !self.focus_handle(cx).contains_focused(window, cx)
1936 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1937 {
1938 for addon in self.addons.values() {
1939 addon.extend_key_context(&mut key_context, cx)
1940 }
1941 }
1942
1943 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1944 if let Some(extension) = singleton_buffer
1945 .read(cx)
1946 .file()
1947 .and_then(|file| file.path().extension()?.to_str())
1948 {
1949 key_context.set("extension", extension.to_string());
1950 }
1951 } else {
1952 key_context.add("multibuffer");
1953 }
1954
1955 if has_active_edit_prediction {
1956 if self.edit_prediction_in_conflict() {
1957 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1958 } else {
1959 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1960 key_context.add("copilot_suggestion");
1961 }
1962 }
1963
1964 if self.selection_mark_mode {
1965 key_context.add("selection_mode");
1966 }
1967
1968 key_context
1969 }
1970
1971 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1972 self.mouse_cursor_hidden = match origin {
1973 HideMouseCursorOrigin::TypingAction => {
1974 matches!(
1975 self.hide_mouse_mode,
1976 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1977 )
1978 }
1979 HideMouseCursorOrigin::MovementAction => {
1980 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1981 }
1982 };
1983 }
1984
1985 pub fn edit_prediction_in_conflict(&self) -> bool {
1986 if !self.show_edit_predictions_in_menu() {
1987 return false;
1988 }
1989
1990 let showing_completions = self
1991 .context_menu
1992 .borrow()
1993 .as_ref()
1994 .map_or(false, |context| {
1995 matches!(context, CodeContextMenu::Completions(_))
1996 });
1997
1998 showing_completions
1999 || self.edit_prediction_requires_modifier()
2000 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2001 // bindings to insert tab characters.
2002 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2003 }
2004
2005 pub fn accept_edit_prediction_keybind(
2006 &self,
2007 window: &Window,
2008 cx: &App,
2009 ) -> AcceptEditPredictionBinding {
2010 let key_context = self.key_context_internal(true, window, cx);
2011 let in_conflict = self.edit_prediction_in_conflict();
2012
2013 AcceptEditPredictionBinding(
2014 window
2015 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2016 .into_iter()
2017 .filter(|binding| {
2018 !in_conflict
2019 || binding
2020 .keystrokes()
2021 .first()
2022 .map_or(false, |keystroke| keystroke.modifiers.modified())
2023 })
2024 .rev()
2025 .min_by_key(|binding| {
2026 binding
2027 .keystrokes()
2028 .first()
2029 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2030 }),
2031 )
2032 }
2033
2034 pub fn new_file(
2035 workspace: &mut Workspace,
2036 _: &workspace::NewFile,
2037 window: &mut Window,
2038 cx: &mut Context<Workspace>,
2039 ) {
2040 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2041 "Failed to create buffer",
2042 window,
2043 cx,
2044 |e, _, _| match e.error_code() {
2045 ErrorCode::RemoteUpgradeRequired => Some(format!(
2046 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2047 e.error_tag("required").unwrap_or("the latest version")
2048 )),
2049 _ => None,
2050 },
2051 );
2052 }
2053
2054 pub fn new_in_workspace(
2055 workspace: &mut Workspace,
2056 window: &mut Window,
2057 cx: &mut Context<Workspace>,
2058 ) -> Task<Result<Entity<Editor>>> {
2059 let project = workspace.project().clone();
2060 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2061
2062 cx.spawn_in(window, async move |workspace, cx| {
2063 let buffer = create.await?;
2064 workspace.update_in(cx, |workspace, window, cx| {
2065 let editor =
2066 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2067 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2068 editor
2069 })
2070 })
2071 }
2072
2073 fn new_file_vertical(
2074 workspace: &mut Workspace,
2075 _: &workspace::NewFileSplitVertical,
2076 window: &mut Window,
2077 cx: &mut Context<Workspace>,
2078 ) {
2079 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2080 }
2081
2082 fn new_file_horizontal(
2083 workspace: &mut Workspace,
2084 _: &workspace::NewFileSplitHorizontal,
2085 window: &mut Window,
2086 cx: &mut Context<Workspace>,
2087 ) {
2088 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2089 }
2090
2091 fn new_file_in_direction(
2092 workspace: &mut Workspace,
2093 direction: SplitDirection,
2094 window: &mut Window,
2095 cx: &mut Context<Workspace>,
2096 ) {
2097 let project = workspace.project().clone();
2098 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2099
2100 cx.spawn_in(window, async move |workspace, cx| {
2101 let buffer = create.await?;
2102 workspace.update_in(cx, move |workspace, window, cx| {
2103 workspace.split_item(
2104 direction,
2105 Box::new(
2106 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2107 ),
2108 window,
2109 cx,
2110 )
2111 })?;
2112 anyhow::Ok(())
2113 })
2114 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2115 match e.error_code() {
2116 ErrorCode::RemoteUpgradeRequired => Some(format!(
2117 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2118 e.error_tag("required").unwrap_or("the latest version")
2119 )),
2120 _ => None,
2121 }
2122 });
2123 }
2124
2125 pub fn leader_peer_id(&self) -> Option<PeerId> {
2126 self.leader_peer_id
2127 }
2128
2129 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2130 &self.buffer
2131 }
2132
2133 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2134 self.workspace.as_ref()?.0.upgrade()
2135 }
2136
2137 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2138 self.buffer().read(cx).title(cx)
2139 }
2140
2141 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2142 let git_blame_gutter_max_author_length = self
2143 .render_git_blame_gutter(cx)
2144 .then(|| {
2145 if let Some(blame) = self.blame.as_ref() {
2146 let max_author_length =
2147 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2148 Some(max_author_length)
2149 } else {
2150 None
2151 }
2152 })
2153 .flatten();
2154
2155 EditorSnapshot {
2156 mode: self.mode,
2157 show_gutter: self.show_gutter,
2158 show_line_numbers: self.show_line_numbers,
2159 show_git_diff_gutter: self.show_git_diff_gutter,
2160 show_code_actions: self.show_code_actions,
2161 show_runnables: self.show_runnables,
2162 show_breakpoints: self.show_breakpoints,
2163 git_blame_gutter_max_author_length,
2164 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2165 scroll_anchor: self.scroll_manager.anchor(),
2166 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2167 placeholder_text: self.placeholder_text.clone(),
2168 is_focused: self.focus_handle.is_focused(window),
2169 current_line_highlight: self
2170 .current_line_highlight
2171 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2172 gutter_hovered: self.gutter_hovered,
2173 }
2174 }
2175
2176 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2177 self.buffer.read(cx).language_at(point, cx)
2178 }
2179
2180 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2181 self.buffer.read(cx).read(cx).file_at(point).cloned()
2182 }
2183
2184 pub fn active_excerpt(
2185 &self,
2186 cx: &App,
2187 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2188 self.buffer
2189 .read(cx)
2190 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2191 }
2192
2193 pub fn mode(&self) -> EditorMode {
2194 self.mode
2195 }
2196
2197 pub fn set_mode(&mut self, mode: EditorMode) {
2198 self.mode = mode;
2199 }
2200
2201 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2202 self.collaboration_hub.as_deref()
2203 }
2204
2205 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2206 self.collaboration_hub = Some(hub);
2207 }
2208
2209 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2210 self.in_project_search = in_project_search;
2211 }
2212
2213 pub fn set_custom_context_menu(
2214 &mut self,
2215 f: impl 'static
2216 + Fn(
2217 &mut Self,
2218 DisplayPoint,
2219 &mut Window,
2220 &mut Context<Self>,
2221 ) -> Option<Entity<ui::ContextMenu>>,
2222 ) {
2223 self.custom_context_menu = Some(Box::new(f))
2224 }
2225
2226 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2227 self.completion_provider = provider;
2228 }
2229
2230 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2231 self.semantics_provider.clone()
2232 }
2233
2234 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2235 self.semantics_provider = provider;
2236 }
2237
2238 pub fn set_edit_prediction_provider<T>(
2239 &mut self,
2240 provider: Option<Entity<T>>,
2241 window: &mut Window,
2242 cx: &mut Context<Self>,
2243 ) where
2244 T: EditPredictionProvider,
2245 {
2246 self.edit_prediction_provider =
2247 provider.map(|provider| RegisteredInlineCompletionProvider {
2248 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2249 if this.focus_handle.is_focused(window) {
2250 this.update_visible_inline_completion(window, cx);
2251 }
2252 }),
2253 provider: Arc::new(provider),
2254 });
2255 self.update_edit_prediction_settings(cx);
2256 self.refresh_inline_completion(false, false, window, cx);
2257 }
2258
2259 pub fn placeholder_text(&self) -> Option<&str> {
2260 self.placeholder_text.as_deref()
2261 }
2262
2263 pub fn set_placeholder_text(
2264 &mut self,
2265 placeholder_text: impl Into<Arc<str>>,
2266 cx: &mut Context<Self>,
2267 ) {
2268 let placeholder_text = Some(placeholder_text.into());
2269 if self.placeholder_text != placeholder_text {
2270 self.placeholder_text = placeholder_text;
2271 cx.notify();
2272 }
2273 }
2274
2275 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2276 self.cursor_shape = cursor_shape;
2277
2278 // Disrupt blink for immediate user feedback that the cursor shape has changed
2279 self.blink_manager.update(cx, BlinkManager::show_cursor);
2280
2281 cx.notify();
2282 }
2283
2284 pub fn set_current_line_highlight(
2285 &mut self,
2286 current_line_highlight: Option<CurrentLineHighlight>,
2287 ) {
2288 self.current_line_highlight = current_line_highlight;
2289 }
2290
2291 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2292 self.collapse_matches = collapse_matches;
2293 }
2294
2295 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2296 let buffers = self.buffer.read(cx).all_buffers();
2297 let Some(project) = self.project.as_ref() else {
2298 return;
2299 };
2300 project.update(cx, |project, cx| {
2301 for buffer in buffers {
2302 self.registered_buffers
2303 .entry(buffer.read(cx).remote_id())
2304 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2305 }
2306 })
2307 }
2308
2309 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2310 if self.collapse_matches {
2311 return range.start..range.start;
2312 }
2313 range.clone()
2314 }
2315
2316 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2317 if self.display_map.read(cx).clip_at_line_ends != clip {
2318 self.display_map
2319 .update(cx, |map, _| map.clip_at_line_ends = clip);
2320 }
2321 }
2322
2323 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2324 self.input_enabled = input_enabled;
2325 }
2326
2327 pub fn set_inline_completions_hidden_for_vim_mode(
2328 &mut self,
2329 hidden: bool,
2330 window: &mut Window,
2331 cx: &mut Context<Self>,
2332 ) {
2333 if hidden != self.inline_completions_hidden_for_vim_mode {
2334 self.inline_completions_hidden_for_vim_mode = hidden;
2335 if hidden {
2336 self.update_visible_inline_completion(window, cx);
2337 } else {
2338 self.refresh_inline_completion(true, false, window, cx);
2339 }
2340 }
2341 }
2342
2343 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2344 self.menu_inline_completions_policy = value;
2345 }
2346
2347 pub fn set_autoindent(&mut self, autoindent: bool) {
2348 if autoindent {
2349 self.autoindent_mode = Some(AutoindentMode::EachLine);
2350 } else {
2351 self.autoindent_mode = None;
2352 }
2353 }
2354
2355 pub fn read_only(&self, cx: &App) -> bool {
2356 self.read_only || self.buffer.read(cx).read_only()
2357 }
2358
2359 pub fn set_read_only(&mut self, read_only: bool) {
2360 self.read_only = read_only;
2361 }
2362
2363 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2364 self.use_autoclose = autoclose;
2365 }
2366
2367 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2368 self.use_auto_surround = auto_surround;
2369 }
2370
2371 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2372 self.auto_replace_emoji_shortcode = auto_replace;
2373 }
2374
2375 pub fn toggle_edit_predictions(
2376 &mut self,
2377 _: &ToggleEditPrediction,
2378 window: &mut Window,
2379 cx: &mut Context<Self>,
2380 ) {
2381 if self.show_inline_completions_override.is_some() {
2382 self.set_show_edit_predictions(None, window, cx);
2383 } else {
2384 let show_edit_predictions = !self.edit_predictions_enabled();
2385 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2386 }
2387 }
2388
2389 pub fn set_show_edit_predictions(
2390 &mut self,
2391 show_edit_predictions: Option<bool>,
2392 window: &mut Window,
2393 cx: &mut Context<Self>,
2394 ) {
2395 self.show_inline_completions_override = show_edit_predictions;
2396 self.update_edit_prediction_settings(cx);
2397
2398 if let Some(false) = show_edit_predictions {
2399 self.discard_inline_completion(false, cx);
2400 } else {
2401 self.refresh_inline_completion(false, true, window, cx);
2402 }
2403 }
2404
2405 fn inline_completions_disabled_in_scope(
2406 &self,
2407 buffer: &Entity<Buffer>,
2408 buffer_position: language::Anchor,
2409 cx: &App,
2410 ) -> bool {
2411 let snapshot = buffer.read(cx).snapshot();
2412 let settings = snapshot.settings_at(buffer_position, cx);
2413
2414 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2415 return false;
2416 };
2417
2418 scope.override_name().map_or(false, |scope_name| {
2419 settings
2420 .edit_predictions_disabled_in
2421 .iter()
2422 .any(|s| s == scope_name)
2423 })
2424 }
2425
2426 pub fn set_use_modal_editing(&mut self, to: bool) {
2427 self.use_modal_editing = to;
2428 }
2429
2430 pub fn use_modal_editing(&self) -> bool {
2431 self.use_modal_editing
2432 }
2433
2434 fn selections_did_change(
2435 &mut self,
2436 local: bool,
2437 old_cursor_position: &Anchor,
2438 show_completions: bool,
2439 window: &mut Window,
2440 cx: &mut Context<Self>,
2441 ) {
2442 window.invalidate_character_coordinates();
2443
2444 // Copy selections to primary selection buffer
2445 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2446 if local {
2447 let selections = self.selections.all::<usize>(cx);
2448 let buffer_handle = self.buffer.read(cx).read(cx);
2449
2450 let mut text = String::new();
2451 for (index, selection) in selections.iter().enumerate() {
2452 let text_for_selection = buffer_handle
2453 .text_for_range(selection.start..selection.end)
2454 .collect::<String>();
2455
2456 text.push_str(&text_for_selection);
2457 if index != selections.len() - 1 {
2458 text.push('\n');
2459 }
2460 }
2461
2462 if !text.is_empty() {
2463 cx.write_to_primary(ClipboardItem::new_string(text));
2464 }
2465 }
2466
2467 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2468 self.buffer.update(cx, |buffer, cx| {
2469 buffer.set_active_selections(
2470 &self.selections.disjoint_anchors(),
2471 self.selections.line_mode,
2472 self.cursor_shape,
2473 cx,
2474 )
2475 });
2476 }
2477 let display_map = self
2478 .display_map
2479 .update(cx, |display_map, cx| display_map.snapshot(cx));
2480 let buffer = &display_map.buffer_snapshot;
2481 self.add_selections_state = None;
2482 self.select_next_state = None;
2483 self.select_prev_state = None;
2484 self.select_syntax_node_history.try_clear();
2485 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2486 self.snippet_stack
2487 .invalidate(&self.selections.disjoint_anchors(), buffer);
2488 self.take_rename(false, window, cx);
2489
2490 let new_cursor_position = self.selections.newest_anchor().head();
2491
2492 self.push_to_nav_history(
2493 *old_cursor_position,
2494 Some(new_cursor_position.to_point(buffer)),
2495 false,
2496 cx,
2497 );
2498
2499 if local {
2500 let new_cursor_position = self.selections.newest_anchor().head();
2501 let mut context_menu = self.context_menu.borrow_mut();
2502 let completion_menu = match context_menu.as_ref() {
2503 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2504 _ => {
2505 *context_menu = None;
2506 None
2507 }
2508 };
2509 if let Some(buffer_id) = new_cursor_position.buffer_id {
2510 if !self.registered_buffers.contains_key(&buffer_id) {
2511 if let Some(project) = self.project.as_ref() {
2512 project.update(cx, |project, cx| {
2513 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2514 return;
2515 };
2516 self.registered_buffers.insert(
2517 buffer_id,
2518 project.register_buffer_with_language_servers(&buffer, cx),
2519 );
2520 })
2521 }
2522 }
2523 }
2524
2525 if let Some(completion_menu) = completion_menu {
2526 let cursor_position = new_cursor_position.to_offset(buffer);
2527 let (word_range, kind) =
2528 buffer.surrounding_word(completion_menu.initial_position, true);
2529 if kind == Some(CharKind::Word)
2530 && word_range.to_inclusive().contains(&cursor_position)
2531 {
2532 let mut completion_menu = completion_menu.clone();
2533 drop(context_menu);
2534
2535 let query = Self::completion_query(buffer, cursor_position);
2536 cx.spawn(async move |this, cx| {
2537 completion_menu
2538 .filter(query.as_deref(), cx.background_executor().clone())
2539 .await;
2540
2541 this.update(cx, |this, cx| {
2542 let mut context_menu = this.context_menu.borrow_mut();
2543 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2544 else {
2545 return;
2546 };
2547
2548 if menu.id > completion_menu.id {
2549 return;
2550 }
2551
2552 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2553 drop(context_menu);
2554 cx.notify();
2555 })
2556 })
2557 .detach();
2558
2559 if show_completions {
2560 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2561 }
2562 } else {
2563 drop(context_menu);
2564 self.hide_context_menu(window, cx);
2565 }
2566 } else {
2567 drop(context_menu);
2568 }
2569
2570 hide_hover(self, cx);
2571
2572 if old_cursor_position.to_display_point(&display_map).row()
2573 != new_cursor_position.to_display_point(&display_map).row()
2574 {
2575 self.available_code_actions.take();
2576 }
2577 self.refresh_code_actions(window, cx);
2578 self.refresh_document_highlights(cx);
2579 self.refresh_selected_text_highlights(window, cx);
2580 refresh_matching_bracket_highlights(self, window, cx);
2581 self.update_visible_inline_completion(window, cx);
2582 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2583 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2584 if self.git_blame_inline_enabled {
2585 self.start_inline_blame_timer(window, cx);
2586 }
2587 }
2588
2589 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2590 cx.emit(EditorEvent::SelectionsChanged { local });
2591
2592 let selections = &self.selections.disjoint;
2593 if selections.len() == 1 {
2594 cx.emit(SearchEvent::ActiveMatchChanged)
2595 }
2596 if local {
2597 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2598 let inmemory_selections = selections
2599 .iter()
2600 .map(|s| {
2601 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2602 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2603 })
2604 .collect();
2605 self.update_restoration_data(cx, |data| {
2606 data.selections = inmemory_selections;
2607 });
2608
2609 if WorkspaceSettings::get(None, cx).restore_on_startup
2610 != RestoreOnStartupBehavior::None
2611 {
2612 if let Some(workspace_id) =
2613 self.workspace.as_ref().and_then(|workspace| workspace.1)
2614 {
2615 let snapshot = self.buffer().read(cx).snapshot(cx);
2616 let selections = selections.clone();
2617 let background_executor = cx.background_executor().clone();
2618 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2619 self.serialize_selections = cx.background_spawn(async move {
2620 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2621 let db_selections = selections
2622 .iter()
2623 .map(|selection| {
2624 (
2625 selection.start.to_offset(&snapshot),
2626 selection.end.to_offset(&snapshot),
2627 )
2628 })
2629 .collect();
2630
2631 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2632 .await
2633 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2634 .log_err();
2635 });
2636 }
2637 }
2638 }
2639 }
2640
2641 cx.notify();
2642 }
2643
2644 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2645 use text::ToOffset as _;
2646 use text::ToPoint as _;
2647
2648 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2649 return;
2650 }
2651
2652 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2653 return;
2654 };
2655
2656 let snapshot = singleton.read(cx).snapshot();
2657 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2658 let display_snapshot = display_map.snapshot(cx);
2659
2660 display_snapshot
2661 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2662 .map(|fold| {
2663 fold.range.start.text_anchor.to_point(&snapshot)
2664 ..fold.range.end.text_anchor.to_point(&snapshot)
2665 })
2666 .collect()
2667 });
2668 self.update_restoration_data(cx, |data| {
2669 data.folds = inmemory_folds;
2670 });
2671
2672 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2673 return;
2674 };
2675 let background_executor = cx.background_executor().clone();
2676 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2677 let db_folds = self.display_map.update(cx, |display_map, cx| {
2678 display_map
2679 .snapshot(cx)
2680 .folds_in_range(0..snapshot.len())
2681 .map(|fold| {
2682 (
2683 fold.range.start.text_anchor.to_offset(&snapshot),
2684 fold.range.end.text_anchor.to_offset(&snapshot),
2685 )
2686 })
2687 .collect()
2688 });
2689 self.serialize_folds = cx.background_spawn(async move {
2690 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2691 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2692 .await
2693 .with_context(|| {
2694 format!(
2695 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2696 )
2697 })
2698 .log_err();
2699 });
2700 }
2701
2702 pub fn sync_selections(
2703 &mut self,
2704 other: Entity<Editor>,
2705 cx: &mut Context<Self>,
2706 ) -> gpui::Subscription {
2707 let other_selections = other.read(cx).selections.disjoint.to_vec();
2708 self.selections.change_with(cx, |selections| {
2709 selections.select_anchors(other_selections);
2710 });
2711
2712 let other_subscription =
2713 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2714 EditorEvent::SelectionsChanged { local: true } => {
2715 let other_selections = other.read(cx).selections.disjoint.to_vec();
2716 if other_selections.is_empty() {
2717 return;
2718 }
2719 this.selections.change_with(cx, |selections| {
2720 selections.select_anchors(other_selections);
2721 });
2722 }
2723 _ => {}
2724 });
2725
2726 let this_subscription =
2727 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2728 EditorEvent::SelectionsChanged { local: true } => {
2729 let these_selections = this.selections.disjoint.to_vec();
2730 if these_selections.is_empty() {
2731 return;
2732 }
2733 other.update(cx, |other_editor, cx| {
2734 other_editor.selections.change_with(cx, |selections| {
2735 selections.select_anchors(these_selections);
2736 })
2737 });
2738 }
2739 _ => {}
2740 });
2741
2742 Subscription::join(other_subscription, this_subscription)
2743 }
2744
2745 pub fn change_selections<R>(
2746 &mut self,
2747 autoscroll: Option<Autoscroll>,
2748 window: &mut Window,
2749 cx: &mut Context<Self>,
2750 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2751 ) -> R {
2752 self.change_selections_inner(autoscroll, true, window, cx, change)
2753 }
2754
2755 fn change_selections_inner<R>(
2756 &mut self,
2757 autoscroll: Option<Autoscroll>,
2758 request_completions: bool,
2759 window: &mut Window,
2760 cx: &mut Context<Self>,
2761 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2762 ) -> R {
2763 let old_cursor_position = self.selections.newest_anchor().head();
2764 self.push_to_selection_history();
2765
2766 let (changed, result) = self.selections.change_with(cx, change);
2767
2768 if changed {
2769 if let Some(autoscroll) = autoscroll {
2770 self.request_autoscroll(autoscroll, cx);
2771 }
2772 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2773
2774 if self.should_open_signature_help_automatically(
2775 &old_cursor_position,
2776 self.signature_help_state.backspace_pressed(),
2777 cx,
2778 ) {
2779 self.show_signature_help(&ShowSignatureHelp, window, cx);
2780 }
2781 self.signature_help_state.set_backspace_pressed(false);
2782 }
2783
2784 result
2785 }
2786
2787 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2788 where
2789 I: IntoIterator<Item = (Range<S>, T)>,
2790 S: ToOffset,
2791 T: Into<Arc<str>>,
2792 {
2793 if self.read_only(cx) {
2794 return;
2795 }
2796
2797 self.buffer
2798 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2799 }
2800
2801 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2802 where
2803 I: IntoIterator<Item = (Range<S>, T)>,
2804 S: ToOffset,
2805 T: Into<Arc<str>>,
2806 {
2807 if self.read_only(cx) {
2808 return;
2809 }
2810
2811 self.buffer.update(cx, |buffer, cx| {
2812 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2813 });
2814 }
2815
2816 pub fn edit_with_block_indent<I, S, T>(
2817 &mut self,
2818 edits: I,
2819 original_indent_columns: Vec<Option<u32>>,
2820 cx: &mut Context<Self>,
2821 ) where
2822 I: IntoIterator<Item = (Range<S>, T)>,
2823 S: ToOffset,
2824 T: Into<Arc<str>>,
2825 {
2826 if self.read_only(cx) {
2827 return;
2828 }
2829
2830 self.buffer.update(cx, |buffer, cx| {
2831 buffer.edit(
2832 edits,
2833 Some(AutoindentMode::Block {
2834 original_indent_columns,
2835 }),
2836 cx,
2837 )
2838 });
2839 }
2840
2841 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2842 self.hide_context_menu(window, cx);
2843
2844 match phase {
2845 SelectPhase::Begin {
2846 position,
2847 add,
2848 click_count,
2849 } => self.begin_selection(position, add, click_count, window, cx),
2850 SelectPhase::BeginColumnar {
2851 position,
2852 goal_column,
2853 reset,
2854 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2855 SelectPhase::Extend {
2856 position,
2857 click_count,
2858 } => self.extend_selection(position, click_count, window, cx),
2859 SelectPhase::Update {
2860 position,
2861 goal_column,
2862 scroll_delta,
2863 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2864 SelectPhase::End => self.end_selection(window, cx),
2865 }
2866 }
2867
2868 fn extend_selection(
2869 &mut self,
2870 position: DisplayPoint,
2871 click_count: usize,
2872 window: &mut Window,
2873 cx: &mut Context<Self>,
2874 ) {
2875 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2876 let tail = self.selections.newest::<usize>(cx).tail();
2877 self.begin_selection(position, false, click_count, window, cx);
2878
2879 let position = position.to_offset(&display_map, Bias::Left);
2880 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2881
2882 let mut pending_selection = self
2883 .selections
2884 .pending_anchor()
2885 .expect("extend_selection not called with pending selection");
2886 if position >= tail {
2887 pending_selection.start = tail_anchor;
2888 } else {
2889 pending_selection.end = tail_anchor;
2890 pending_selection.reversed = true;
2891 }
2892
2893 let mut pending_mode = self.selections.pending_mode().unwrap();
2894 match &mut pending_mode {
2895 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2896 _ => {}
2897 }
2898
2899 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2900 s.set_pending(pending_selection, pending_mode)
2901 });
2902 }
2903
2904 fn begin_selection(
2905 &mut self,
2906 position: DisplayPoint,
2907 add: bool,
2908 click_count: usize,
2909 window: &mut Window,
2910 cx: &mut Context<Self>,
2911 ) {
2912 if !self.focus_handle.is_focused(window) {
2913 self.last_focused_descendant = None;
2914 window.focus(&self.focus_handle);
2915 }
2916
2917 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2918 let buffer = &display_map.buffer_snapshot;
2919 let newest_selection = self.selections.newest_anchor().clone();
2920 let position = display_map.clip_point(position, Bias::Left);
2921
2922 let start;
2923 let end;
2924 let mode;
2925 let mut auto_scroll;
2926 match click_count {
2927 1 => {
2928 start = buffer.anchor_before(position.to_point(&display_map));
2929 end = start;
2930 mode = SelectMode::Character;
2931 auto_scroll = true;
2932 }
2933 2 => {
2934 let range = movement::surrounding_word(&display_map, position);
2935 start = buffer.anchor_before(range.start.to_point(&display_map));
2936 end = buffer.anchor_before(range.end.to_point(&display_map));
2937 mode = SelectMode::Word(start..end);
2938 auto_scroll = true;
2939 }
2940 3 => {
2941 let position = display_map
2942 .clip_point(position, Bias::Left)
2943 .to_point(&display_map);
2944 let line_start = display_map.prev_line_boundary(position).0;
2945 let next_line_start = buffer.clip_point(
2946 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2947 Bias::Left,
2948 );
2949 start = buffer.anchor_before(line_start);
2950 end = buffer.anchor_before(next_line_start);
2951 mode = SelectMode::Line(start..end);
2952 auto_scroll = true;
2953 }
2954 _ => {
2955 start = buffer.anchor_before(0);
2956 end = buffer.anchor_before(buffer.len());
2957 mode = SelectMode::All;
2958 auto_scroll = false;
2959 }
2960 }
2961 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2962
2963 let point_to_delete: Option<usize> = {
2964 let selected_points: Vec<Selection<Point>> =
2965 self.selections.disjoint_in_range(start..end, cx);
2966
2967 if !add || click_count > 1 {
2968 None
2969 } else if !selected_points.is_empty() {
2970 Some(selected_points[0].id)
2971 } else {
2972 let clicked_point_already_selected =
2973 self.selections.disjoint.iter().find(|selection| {
2974 selection.start.to_point(buffer) == start.to_point(buffer)
2975 || selection.end.to_point(buffer) == end.to_point(buffer)
2976 });
2977
2978 clicked_point_already_selected.map(|selection| selection.id)
2979 }
2980 };
2981
2982 let selections_count = self.selections.count();
2983
2984 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2985 if let Some(point_to_delete) = point_to_delete {
2986 s.delete(point_to_delete);
2987
2988 if selections_count == 1 {
2989 s.set_pending_anchor_range(start..end, mode);
2990 }
2991 } else {
2992 if !add {
2993 s.clear_disjoint();
2994 } else if click_count > 1 {
2995 s.delete(newest_selection.id)
2996 }
2997
2998 s.set_pending_anchor_range(start..end, mode);
2999 }
3000 });
3001 }
3002
3003 fn begin_columnar_selection(
3004 &mut self,
3005 position: DisplayPoint,
3006 goal_column: u32,
3007 reset: bool,
3008 window: &mut Window,
3009 cx: &mut Context<Self>,
3010 ) {
3011 if !self.focus_handle.is_focused(window) {
3012 self.last_focused_descendant = None;
3013 window.focus(&self.focus_handle);
3014 }
3015
3016 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3017
3018 if reset {
3019 let pointer_position = display_map
3020 .buffer_snapshot
3021 .anchor_before(position.to_point(&display_map));
3022
3023 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3024 s.clear_disjoint();
3025 s.set_pending_anchor_range(
3026 pointer_position..pointer_position,
3027 SelectMode::Character,
3028 );
3029 });
3030 }
3031
3032 let tail = self.selections.newest::<Point>(cx).tail();
3033 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3034
3035 if !reset {
3036 self.select_columns(
3037 tail.to_display_point(&display_map),
3038 position,
3039 goal_column,
3040 &display_map,
3041 window,
3042 cx,
3043 );
3044 }
3045 }
3046
3047 fn update_selection(
3048 &mut self,
3049 position: DisplayPoint,
3050 goal_column: u32,
3051 scroll_delta: gpui::Point<f32>,
3052 window: &mut Window,
3053 cx: &mut Context<Self>,
3054 ) {
3055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3056
3057 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3058 let tail = tail.to_display_point(&display_map);
3059 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3060 } else if let Some(mut pending) = self.selections.pending_anchor() {
3061 let buffer = self.buffer.read(cx).snapshot(cx);
3062 let head;
3063 let tail;
3064 let mode = self.selections.pending_mode().unwrap();
3065 match &mode {
3066 SelectMode::Character => {
3067 head = position.to_point(&display_map);
3068 tail = pending.tail().to_point(&buffer);
3069 }
3070 SelectMode::Word(original_range) => {
3071 let original_display_range = original_range.start.to_display_point(&display_map)
3072 ..original_range.end.to_display_point(&display_map);
3073 let original_buffer_range = original_display_range.start.to_point(&display_map)
3074 ..original_display_range.end.to_point(&display_map);
3075 if movement::is_inside_word(&display_map, position)
3076 || original_display_range.contains(&position)
3077 {
3078 let word_range = movement::surrounding_word(&display_map, position);
3079 if word_range.start < original_display_range.start {
3080 head = word_range.start.to_point(&display_map);
3081 } else {
3082 head = word_range.end.to_point(&display_map);
3083 }
3084 } else {
3085 head = position.to_point(&display_map);
3086 }
3087
3088 if head <= original_buffer_range.start {
3089 tail = original_buffer_range.end;
3090 } else {
3091 tail = original_buffer_range.start;
3092 }
3093 }
3094 SelectMode::Line(original_range) => {
3095 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3096
3097 let position = display_map
3098 .clip_point(position, Bias::Left)
3099 .to_point(&display_map);
3100 let line_start = display_map.prev_line_boundary(position).0;
3101 let next_line_start = buffer.clip_point(
3102 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3103 Bias::Left,
3104 );
3105
3106 if line_start < original_range.start {
3107 head = line_start
3108 } else {
3109 head = next_line_start
3110 }
3111
3112 if head <= original_range.start {
3113 tail = original_range.end;
3114 } else {
3115 tail = original_range.start;
3116 }
3117 }
3118 SelectMode::All => {
3119 return;
3120 }
3121 };
3122
3123 if head < tail {
3124 pending.start = buffer.anchor_before(head);
3125 pending.end = buffer.anchor_before(tail);
3126 pending.reversed = true;
3127 } else {
3128 pending.start = buffer.anchor_before(tail);
3129 pending.end = buffer.anchor_before(head);
3130 pending.reversed = false;
3131 }
3132
3133 self.change_selections(None, window, cx, |s| {
3134 s.set_pending(pending, mode);
3135 });
3136 } else {
3137 log::error!("update_selection dispatched with no pending selection");
3138 return;
3139 }
3140
3141 self.apply_scroll_delta(scroll_delta, window, cx);
3142 cx.notify();
3143 }
3144
3145 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3146 self.columnar_selection_tail.take();
3147 if self.selections.pending_anchor().is_some() {
3148 let selections = self.selections.all::<usize>(cx);
3149 self.change_selections(None, window, cx, |s| {
3150 s.select(selections);
3151 s.clear_pending();
3152 });
3153 }
3154 }
3155
3156 fn select_columns(
3157 &mut self,
3158 tail: DisplayPoint,
3159 head: DisplayPoint,
3160 goal_column: u32,
3161 display_map: &DisplaySnapshot,
3162 window: &mut Window,
3163 cx: &mut Context<Self>,
3164 ) {
3165 let start_row = cmp::min(tail.row(), head.row());
3166 let end_row = cmp::max(tail.row(), head.row());
3167 let start_column = cmp::min(tail.column(), goal_column);
3168 let end_column = cmp::max(tail.column(), goal_column);
3169 let reversed = start_column < tail.column();
3170
3171 let selection_ranges = (start_row.0..=end_row.0)
3172 .map(DisplayRow)
3173 .filter_map(|row| {
3174 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3175 let start = display_map
3176 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3177 .to_point(display_map);
3178 let end = display_map
3179 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3180 .to_point(display_map);
3181 if reversed {
3182 Some(end..start)
3183 } else {
3184 Some(start..end)
3185 }
3186 } else {
3187 None
3188 }
3189 })
3190 .collect::<Vec<_>>();
3191
3192 self.change_selections(None, window, cx, |s| {
3193 s.select_ranges(selection_ranges);
3194 });
3195 cx.notify();
3196 }
3197
3198 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3199 self.selections
3200 .all_adjusted(cx)
3201 .iter()
3202 .any(|selection| !selection.is_empty())
3203 }
3204
3205 pub fn has_pending_nonempty_selection(&self) -> bool {
3206 let pending_nonempty_selection = match self.selections.pending_anchor() {
3207 Some(Selection { start, end, .. }) => start != end,
3208 None => false,
3209 };
3210
3211 pending_nonempty_selection
3212 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3213 }
3214
3215 pub fn has_pending_selection(&self) -> bool {
3216 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3217 }
3218
3219 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3220 self.selection_mark_mode = false;
3221
3222 if self.clear_expanded_diff_hunks(cx) {
3223 cx.notify();
3224 return;
3225 }
3226 if self.dismiss_menus_and_popups(true, window, cx) {
3227 return;
3228 }
3229
3230 if self.mode.is_full()
3231 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3232 {
3233 return;
3234 }
3235
3236 cx.propagate();
3237 }
3238
3239 pub fn dismiss_menus_and_popups(
3240 &mut self,
3241 is_user_requested: bool,
3242 window: &mut Window,
3243 cx: &mut Context<Self>,
3244 ) -> bool {
3245 if self.take_rename(false, window, cx).is_some() {
3246 return true;
3247 }
3248
3249 if hide_hover(self, cx) {
3250 return true;
3251 }
3252
3253 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3254 return true;
3255 }
3256
3257 if self.hide_context_menu(window, cx).is_some() {
3258 return true;
3259 }
3260
3261 if self.mouse_context_menu.take().is_some() {
3262 return true;
3263 }
3264
3265 if is_user_requested && self.discard_inline_completion(true, cx) {
3266 return true;
3267 }
3268
3269 if self.snippet_stack.pop().is_some() {
3270 return true;
3271 }
3272
3273 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3274 self.dismiss_diagnostics(cx);
3275 return true;
3276 }
3277
3278 false
3279 }
3280
3281 fn linked_editing_ranges_for(
3282 &self,
3283 selection: Range<text::Anchor>,
3284 cx: &App,
3285 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3286 if self.linked_edit_ranges.is_empty() {
3287 return None;
3288 }
3289 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3290 selection.end.buffer_id.and_then(|end_buffer_id| {
3291 if selection.start.buffer_id != Some(end_buffer_id) {
3292 return None;
3293 }
3294 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3295 let snapshot = buffer.read(cx).snapshot();
3296 self.linked_edit_ranges
3297 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3298 .map(|ranges| (ranges, snapshot, buffer))
3299 })?;
3300 use text::ToOffset as TO;
3301 // find offset from the start of current range to current cursor position
3302 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3303
3304 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3305 let start_difference = start_offset - start_byte_offset;
3306 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3307 let end_difference = end_offset - start_byte_offset;
3308 // Current range has associated linked ranges.
3309 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3310 for range in linked_ranges.iter() {
3311 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3312 let end_offset = start_offset + end_difference;
3313 let start_offset = start_offset + start_difference;
3314 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3315 continue;
3316 }
3317 if self.selections.disjoint_anchor_ranges().any(|s| {
3318 if s.start.buffer_id != selection.start.buffer_id
3319 || s.end.buffer_id != selection.end.buffer_id
3320 {
3321 return false;
3322 }
3323 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3324 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3325 }) {
3326 continue;
3327 }
3328 let start = buffer_snapshot.anchor_after(start_offset);
3329 let end = buffer_snapshot.anchor_after(end_offset);
3330 linked_edits
3331 .entry(buffer.clone())
3332 .or_default()
3333 .push(start..end);
3334 }
3335 Some(linked_edits)
3336 }
3337
3338 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3339 let text: Arc<str> = text.into();
3340
3341 if self.read_only(cx) {
3342 return;
3343 }
3344
3345 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3346
3347 let selections = self.selections.all_adjusted(cx);
3348 let mut bracket_inserted = false;
3349 let mut edits = Vec::new();
3350 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3351 let mut new_selections = Vec::with_capacity(selections.len());
3352 let mut new_autoclose_regions = Vec::new();
3353 let snapshot = self.buffer.read(cx).read(cx);
3354 let mut clear_linked_edit_ranges = false;
3355
3356 for (selection, autoclose_region) in
3357 self.selections_with_autoclose_regions(selections, &snapshot)
3358 {
3359 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3360 // Determine if the inserted text matches the opening or closing
3361 // bracket of any of this language's bracket pairs.
3362 let mut bracket_pair = None;
3363 let mut is_bracket_pair_start = false;
3364 let mut is_bracket_pair_end = false;
3365 if !text.is_empty() {
3366 let mut bracket_pair_matching_end = None;
3367 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3368 // and they are removing the character that triggered IME popup.
3369 for (pair, enabled) in scope.brackets() {
3370 if !pair.close && !pair.surround {
3371 continue;
3372 }
3373
3374 if enabled && pair.start.ends_with(text.as_ref()) {
3375 let prefix_len = pair.start.len() - text.len();
3376 let preceding_text_matches_prefix = prefix_len == 0
3377 || (selection.start.column >= (prefix_len as u32)
3378 && snapshot.contains_str_at(
3379 Point::new(
3380 selection.start.row,
3381 selection.start.column - (prefix_len as u32),
3382 ),
3383 &pair.start[..prefix_len],
3384 ));
3385 if preceding_text_matches_prefix {
3386 bracket_pair = Some(pair.clone());
3387 is_bracket_pair_start = true;
3388 break;
3389 }
3390 }
3391 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3392 {
3393 // take first bracket pair matching end, but don't break in case a later bracket
3394 // pair matches start
3395 bracket_pair_matching_end = Some(pair.clone());
3396 }
3397 }
3398 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3399 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3400 is_bracket_pair_end = true;
3401 }
3402 }
3403
3404 if let Some(bracket_pair) = bracket_pair {
3405 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3406 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3407 let auto_surround =
3408 self.use_auto_surround && snapshot_settings.use_auto_surround;
3409 if selection.is_empty() {
3410 if is_bracket_pair_start {
3411 // If the inserted text is a suffix of an opening bracket and the
3412 // selection is preceded by the rest of the opening bracket, then
3413 // insert the closing bracket.
3414 let following_text_allows_autoclose = snapshot
3415 .chars_at(selection.start)
3416 .next()
3417 .map_or(true, |c| scope.should_autoclose_before(c));
3418
3419 let preceding_text_allows_autoclose = selection.start.column == 0
3420 || snapshot.reversed_chars_at(selection.start).next().map_or(
3421 true,
3422 |c| {
3423 bracket_pair.start != bracket_pair.end
3424 || !snapshot
3425 .char_classifier_at(selection.start)
3426 .is_word(c)
3427 },
3428 );
3429
3430 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3431 && bracket_pair.start.len() == 1
3432 {
3433 let target = bracket_pair.start.chars().next().unwrap();
3434 let current_line_count = snapshot
3435 .reversed_chars_at(selection.start)
3436 .take_while(|&c| c != '\n')
3437 .filter(|&c| c == target)
3438 .count();
3439 current_line_count % 2 == 1
3440 } else {
3441 false
3442 };
3443
3444 if autoclose
3445 && bracket_pair.close
3446 && following_text_allows_autoclose
3447 && preceding_text_allows_autoclose
3448 && !is_closing_quote
3449 {
3450 let anchor = snapshot.anchor_before(selection.end);
3451 new_selections.push((selection.map(|_| anchor), text.len()));
3452 new_autoclose_regions.push((
3453 anchor,
3454 text.len(),
3455 selection.id,
3456 bracket_pair.clone(),
3457 ));
3458 edits.push((
3459 selection.range(),
3460 format!("{}{}", text, bracket_pair.end).into(),
3461 ));
3462 bracket_inserted = true;
3463 continue;
3464 }
3465 }
3466
3467 if let Some(region) = autoclose_region {
3468 // If the selection is followed by an auto-inserted closing bracket,
3469 // then don't insert that closing bracket again; just move the selection
3470 // past the closing bracket.
3471 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3472 && text.as_ref() == region.pair.end.as_str();
3473 if should_skip {
3474 let anchor = snapshot.anchor_after(selection.end);
3475 new_selections
3476 .push((selection.map(|_| anchor), region.pair.end.len()));
3477 continue;
3478 }
3479 }
3480
3481 let always_treat_brackets_as_autoclosed = snapshot
3482 .language_settings_at(selection.start, cx)
3483 .always_treat_brackets_as_autoclosed;
3484 if always_treat_brackets_as_autoclosed
3485 && is_bracket_pair_end
3486 && snapshot.contains_str_at(selection.end, text.as_ref())
3487 {
3488 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3489 // and the inserted text is a closing bracket and the selection is followed
3490 // by the closing bracket then move the selection past the closing bracket.
3491 let anchor = snapshot.anchor_after(selection.end);
3492 new_selections.push((selection.map(|_| anchor), text.len()));
3493 continue;
3494 }
3495 }
3496 // If an opening bracket is 1 character long and is typed while
3497 // text is selected, then surround that text with the bracket pair.
3498 else if auto_surround
3499 && bracket_pair.surround
3500 && is_bracket_pair_start
3501 && bracket_pair.start.chars().count() == 1
3502 {
3503 edits.push((selection.start..selection.start, text.clone()));
3504 edits.push((
3505 selection.end..selection.end,
3506 bracket_pair.end.as_str().into(),
3507 ));
3508 bracket_inserted = true;
3509 new_selections.push((
3510 Selection {
3511 id: selection.id,
3512 start: snapshot.anchor_after(selection.start),
3513 end: snapshot.anchor_before(selection.end),
3514 reversed: selection.reversed,
3515 goal: selection.goal,
3516 },
3517 0,
3518 ));
3519 continue;
3520 }
3521 }
3522 }
3523
3524 if self.auto_replace_emoji_shortcode
3525 && selection.is_empty()
3526 && text.as_ref().ends_with(':')
3527 {
3528 if let Some(possible_emoji_short_code) =
3529 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3530 {
3531 if !possible_emoji_short_code.is_empty() {
3532 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3533 let emoji_shortcode_start = Point::new(
3534 selection.start.row,
3535 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3536 );
3537
3538 // Remove shortcode from buffer
3539 edits.push((
3540 emoji_shortcode_start..selection.start,
3541 "".to_string().into(),
3542 ));
3543 new_selections.push((
3544 Selection {
3545 id: selection.id,
3546 start: snapshot.anchor_after(emoji_shortcode_start),
3547 end: snapshot.anchor_before(selection.start),
3548 reversed: selection.reversed,
3549 goal: selection.goal,
3550 },
3551 0,
3552 ));
3553
3554 // Insert emoji
3555 let selection_start_anchor = snapshot.anchor_after(selection.start);
3556 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3557 edits.push((selection.start..selection.end, emoji.to_string().into()));
3558
3559 continue;
3560 }
3561 }
3562 }
3563 }
3564
3565 // If not handling any auto-close operation, then just replace the selected
3566 // text with the given input and move the selection to the end of the
3567 // newly inserted text.
3568 let anchor = snapshot.anchor_after(selection.end);
3569 if !self.linked_edit_ranges.is_empty() {
3570 let start_anchor = snapshot.anchor_before(selection.start);
3571
3572 let is_word_char = text.chars().next().map_or(true, |char| {
3573 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3574 classifier.is_word(char)
3575 });
3576
3577 if is_word_char {
3578 if let Some(ranges) = self
3579 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3580 {
3581 for (buffer, edits) in ranges {
3582 linked_edits
3583 .entry(buffer.clone())
3584 .or_default()
3585 .extend(edits.into_iter().map(|range| (range, text.clone())));
3586 }
3587 }
3588 } else {
3589 clear_linked_edit_ranges = true;
3590 }
3591 }
3592
3593 new_selections.push((selection.map(|_| anchor), 0));
3594 edits.push((selection.start..selection.end, text.clone()));
3595 }
3596
3597 drop(snapshot);
3598
3599 self.transact(window, cx, |this, window, cx| {
3600 if clear_linked_edit_ranges {
3601 this.linked_edit_ranges.clear();
3602 }
3603 let initial_buffer_versions =
3604 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3605
3606 this.buffer.update(cx, |buffer, cx| {
3607 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3608 });
3609 for (buffer, edits) in linked_edits {
3610 buffer.update(cx, |buffer, cx| {
3611 let snapshot = buffer.snapshot();
3612 let edits = edits
3613 .into_iter()
3614 .map(|(range, text)| {
3615 use text::ToPoint as TP;
3616 let end_point = TP::to_point(&range.end, &snapshot);
3617 let start_point = TP::to_point(&range.start, &snapshot);
3618 (start_point..end_point, text)
3619 })
3620 .sorted_by_key(|(range, _)| range.start);
3621 buffer.edit(edits, None, cx);
3622 })
3623 }
3624 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3625 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3626 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3627 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3628 .zip(new_selection_deltas)
3629 .map(|(selection, delta)| Selection {
3630 id: selection.id,
3631 start: selection.start + delta,
3632 end: selection.end + delta,
3633 reversed: selection.reversed,
3634 goal: SelectionGoal::None,
3635 })
3636 .collect::<Vec<_>>();
3637
3638 let mut i = 0;
3639 for (position, delta, selection_id, pair) in new_autoclose_regions {
3640 let position = position.to_offset(&map.buffer_snapshot) + delta;
3641 let start = map.buffer_snapshot.anchor_before(position);
3642 let end = map.buffer_snapshot.anchor_after(position);
3643 while let Some(existing_state) = this.autoclose_regions.get(i) {
3644 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3645 Ordering::Less => i += 1,
3646 Ordering::Greater => break,
3647 Ordering::Equal => {
3648 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3649 Ordering::Less => i += 1,
3650 Ordering::Equal => break,
3651 Ordering::Greater => break,
3652 }
3653 }
3654 }
3655 }
3656 this.autoclose_regions.insert(
3657 i,
3658 AutocloseRegion {
3659 selection_id,
3660 range: start..end,
3661 pair,
3662 },
3663 );
3664 }
3665
3666 let had_active_inline_completion = this.has_active_inline_completion();
3667 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3668 s.select(new_selections)
3669 });
3670
3671 if !bracket_inserted {
3672 if let Some(on_type_format_task) =
3673 this.trigger_on_type_formatting(text.to_string(), window, cx)
3674 {
3675 on_type_format_task.detach_and_log_err(cx);
3676 }
3677 }
3678
3679 let editor_settings = EditorSettings::get_global(cx);
3680 if bracket_inserted
3681 && (editor_settings.auto_signature_help
3682 || editor_settings.show_signature_help_after_edits)
3683 {
3684 this.show_signature_help(&ShowSignatureHelp, window, cx);
3685 }
3686
3687 let trigger_in_words =
3688 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3689 if this.hard_wrap.is_some() {
3690 let latest: Range<Point> = this.selections.newest(cx).range();
3691 if latest.is_empty()
3692 && this
3693 .buffer()
3694 .read(cx)
3695 .snapshot(cx)
3696 .line_len(MultiBufferRow(latest.start.row))
3697 == latest.start.column
3698 {
3699 this.rewrap_impl(
3700 RewrapOptions {
3701 override_language_settings: true,
3702 preserve_existing_whitespace: true,
3703 },
3704 cx,
3705 )
3706 }
3707 }
3708 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3709 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3710 this.refresh_inline_completion(true, false, window, cx);
3711 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3712 });
3713 }
3714
3715 fn find_possible_emoji_shortcode_at_position(
3716 snapshot: &MultiBufferSnapshot,
3717 position: Point,
3718 ) -> Option<String> {
3719 let mut chars = Vec::new();
3720 let mut found_colon = false;
3721 for char in snapshot.reversed_chars_at(position).take(100) {
3722 // Found a possible emoji shortcode in the middle of the buffer
3723 if found_colon {
3724 if char.is_whitespace() {
3725 chars.reverse();
3726 return Some(chars.iter().collect());
3727 }
3728 // If the previous character is not a whitespace, we are in the middle of a word
3729 // and we only want to complete the shortcode if the word is made up of other emojis
3730 let mut containing_word = String::new();
3731 for ch in snapshot
3732 .reversed_chars_at(position)
3733 .skip(chars.len() + 1)
3734 .take(100)
3735 {
3736 if ch.is_whitespace() {
3737 break;
3738 }
3739 containing_word.push(ch);
3740 }
3741 let containing_word = containing_word.chars().rev().collect::<String>();
3742 if util::word_consists_of_emojis(containing_word.as_str()) {
3743 chars.reverse();
3744 return Some(chars.iter().collect());
3745 }
3746 }
3747
3748 if char.is_whitespace() || !char.is_ascii() {
3749 return None;
3750 }
3751 if char == ':' {
3752 found_colon = true;
3753 } else {
3754 chars.push(char);
3755 }
3756 }
3757 // Found a possible emoji shortcode at the beginning of the buffer
3758 chars.reverse();
3759 Some(chars.iter().collect())
3760 }
3761
3762 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3763 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3764 self.transact(window, cx, |this, window, cx| {
3765 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3766 let selections = this.selections.all::<usize>(cx);
3767 let multi_buffer = this.buffer.read(cx);
3768 let buffer = multi_buffer.snapshot(cx);
3769 selections
3770 .iter()
3771 .map(|selection| {
3772 let start_point = selection.start.to_point(&buffer);
3773 let mut indent =
3774 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3775 indent.len = cmp::min(indent.len, start_point.column);
3776 let start = selection.start;
3777 let end = selection.end;
3778 let selection_is_empty = start == end;
3779 let language_scope = buffer.language_scope_at(start);
3780 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3781 &language_scope
3782 {
3783 let insert_extra_newline =
3784 insert_extra_newline_brackets(&buffer, start..end, language)
3785 || insert_extra_newline_tree_sitter(&buffer, start..end);
3786
3787 // Comment extension on newline is allowed only for cursor selections
3788 let comment_delimiter = maybe!({
3789 if !selection_is_empty {
3790 return None;
3791 }
3792
3793 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3794 return None;
3795 }
3796
3797 let delimiters = language.line_comment_prefixes();
3798 let max_len_of_delimiter =
3799 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3800 let (snapshot, range) =
3801 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3802
3803 let mut index_of_first_non_whitespace = 0;
3804 let comment_candidate = snapshot
3805 .chars_for_range(range)
3806 .skip_while(|c| {
3807 let should_skip = c.is_whitespace();
3808 if should_skip {
3809 index_of_first_non_whitespace += 1;
3810 }
3811 should_skip
3812 })
3813 .take(max_len_of_delimiter)
3814 .collect::<String>();
3815 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3816 comment_candidate.starts_with(comment_prefix.as_ref())
3817 })?;
3818 let cursor_is_placed_after_comment_marker =
3819 index_of_first_non_whitespace + comment_prefix.len()
3820 <= start_point.column as usize;
3821 if cursor_is_placed_after_comment_marker {
3822 Some(comment_prefix.clone())
3823 } else {
3824 None
3825 }
3826 });
3827 (comment_delimiter, insert_extra_newline)
3828 } else {
3829 (None, false)
3830 };
3831
3832 let capacity_for_delimiter = comment_delimiter
3833 .as_deref()
3834 .map(str::len)
3835 .unwrap_or_default();
3836 let mut new_text =
3837 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3838 new_text.push('\n');
3839 new_text.extend(indent.chars());
3840 if let Some(delimiter) = &comment_delimiter {
3841 new_text.push_str(delimiter);
3842 }
3843 if insert_extra_newline {
3844 new_text = new_text.repeat(2);
3845 }
3846
3847 let anchor = buffer.anchor_after(end);
3848 let new_selection = selection.map(|_| anchor);
3849 (
3850 (start..end, new_text),
3851 (insert_extra_newline, new_selection),
3852 )
3853 })
3854 .unzip()
3855 };
3856
3857 this.edit_with_autoindent(edits, cx);
3858 let buffer = this.buffer.read(cx).snapshot(cx);
3859 let new_selections = selection_fixup_info
3860 .into_iter()
3861 .map(|(extra_newline_inserted, new_selection)| {
3862 let mut cursor = new_selection.end.to_point(&buffer);
3863 if extra_newline_inserted {
3864 cursor.row -= 1;
3865 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3866 }
3867 new_selection.map(|_| cursor)
3868 })
3869 .collect();
3870
3871 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3872 s.select(new_selections)
3873 });
3874 this.refresh_inline_completion(true, false, window, cx);
3875 });
3876 }
3877
3878 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3879 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3880
3881 let buffer = self.buffer.read(cx);
3882 let snapshot = buffer.snapshot(cx);
3883
3884 let mut edits = Vec::new();
3885 let mut rows = Vec::new();
3886
3887 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3888 let cursor = selection.head();
3889 let row = cursor.row;
3890
3891 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3892
3893 let newline = "\n".to_string();
3894 edits.push((start_of_line..start_of_line, newline));
3895
3896 rows.push(row + rows_inserted as u32);
3897 }
3898
3899 self.transact(window, cx, |editor, window, cx| {
3900 editor.edit(edits, cx);
3901
3902 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3903 let mut index = 0;
3904 s.move_cursors_with(|map, _, _| {
3905 let row = rows[index];
3906 index += 1;
3907
3908 let point = Point::new(row, 0);
3909 let boundary = map.next_line_boundary(point).1;
3910 let clipped = map.clip_point(boundary, Bias::Left);
3911
3912 (clipped, SelectionGoal::None)
3913 });
3914 });
3915
3916 let mut indent_edits = Vec::new();
3917 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3918 for row in rows {
3919 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3920 for (row, indent) in indents {
3921 if indent.len == 0 {
3922 continue;
3923 }
3924
3925 let text = match indent.kind {
3926 IndentKind::Space => " ".repeat(indent.len as usize),
3927 IndentKind::Tab => "\t".repeat(indent.len as usize),
3928 };
3929 let point = Point::new(row.0, 0);
3930 indent_edits.push((point..point, text));
3931 }
3932 }
3933 editor.edit(indent_edits, cx);
3934 });
3935 }
3936
3937 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3938 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3939
3940 let buffer = self.buffer.read(cx);
3941 let snapshot = buffer.snapshot(cx);
3942
3943 let mut edits = Vec::new();
3944 let mut rows = Vec::new();
3945 let mut rows_inserted = 0;
3946
3947 for selection in self.selections.all_adjusted(cx) {
3948 let cursor = selection.head();
3949 let row = cursor.row;
3950
3951 let point = Point::new(row + 1, 0);
3952 let start_of_line = snapshot.clip_point(point, Bias::Left);
3953
3954 let newline = "\n".to_string();
3955 edits.push((start_of_line..start_of_line, newline));
3956
3957 rows_inserted += 1;
3958 rows.push(row + rows_inserted);
3959 }
3960
3961 self.transact(window, cx, |editor, window, cx| {
3962 editor.edit(edits, cx);
3963
3964 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3965 let mut index = 0;
3966 s.move_cursors_with(|map, _, _| {
3967 let row = rows[index];
3968 index += 1;
3969
3970 let point = Point::new(row, 0);
3971 let boundary = map.next_line_boundary(point).1;
3972 let clipped = map.clip_point(boundary, Bias::Left);
3973
3974 (clipped, SelectionGoal::None)
3975 });
3976 });
3977
3978 let mut indent_edits = Vec::new();
3979 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3980 for row in rows {
3981 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3982 for (row, indent) in indents {
3983 if indent.len == 0 {
3984 continue;
3985 }
3986
3987 let text = match indent.kind {
3988 IndentKind::Space => " ".repeat(indent.len as usize),
3989 IndentKind::Tab => "\t".repeat(indent.len as usize),
3990 };
3991 let point = Point::new(row.0, 0);
3992 indent_edits.push((point..point, text));
3993 }
3994 }
3995 editor.edit(indent_edits, cx);
3996 });
3997 }
3998
3999 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4000 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4001 original_indent_columns: Vec::new(),
4002 });
4003 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4004 }
4005
4006 fn insert_with_autoindent_mode(
4007 &mut self,
4008 text: &str,
4009 autoindent_mode: Option<AutoindentMode>,
4010 window: &mut Window,
4011 cx: &mut Context<Self>,
4012 ) {
4013 if self.read_only(cx) {
4014 return;
4015 }
4016
4017 let text: Arc<str> = text.into();
4018 self.transact(window, cx, |this, window, cx| {
4019 let old_selections = this.selections.all_adjusted(cx);
4020 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4021 let anchors = {
4022 let snapshot = buffer.read(cx);
4023 old_selections
4024 .iter()
4025 .map(|s| {
4026 let anchor = snapshot.anchor_after(s.head());
4027 s.map(|_| anchor)
4028 })
4029 .collect::<Vec<_>>()
4030 };
4031 buffer.edit(
4032 old_selections
4033 .iter()
4034 .map(|s| (s.start..s.end, text.clone())),
4035 autoindent_mode,
4036 cx,
4037 );
4038 anchors
4039 });
4040
4041 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4042 s.select_anchors(selection_anchors);
4043 });
4044
4045 cx.notify();
4046 });
4047 }
4048
4049 fn trigger_completion_on_input(
4050 &mut self,
4051 text: &str,
4052 trigger_in_words: bool,
4053 window: &mut Window,
4054 cx: &mut Context<Self>,
4055 ) {
4056 let ignore_completion_provider = self
4057 .context_menu
4058 .borrow()
4059 .as_ref()
4060 .map(|menu| match menu {
4061 CodeContextMenu::Completions(completions_menu) => {
4062 completions_menu.ignore_completion_provider
4063 }
4064 CodeContextMenu::CodeActions(_) => false,
4065 })
4066 .unwrap_or(false);
4067
4068 if ignore_completion_provider {
4069 self.show_word_completions(&ShowWordCompletions, window, cx);
4070 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4071 self.show_completions(
4072 &ShowCompletions {
4073 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4074 },
4075 window,
4076 cx,
4077 );
4078 } else {
4079 self.hide_context_menu(window, cx);
4080 }
4081 }
4082
4083 fn is_completion_trigger(
4084 &self,
4085 text: &str,
4086 trigger_in_words: bool,
4087 cx: &mut Context<Self>,
4088 ) -> bool {
4089 let position = self.selections.newest_anchor().head();
4090 let multibuffer = self.buffer.read(cx);
4091 let Some(buffer) = position
4092 .buffer_id
4093 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4094 else {
4095 return false;
4096 };
4097
4098 if let Some(completion_provider) = &self.completion_provider {
4099 completion_provider.is_completion_trigger(
4100 &buffer,
4101 position.text_anchor,
4102 text,
4103 trigger_in_words,
4104 cx,
4105 )
4106 } else {
4107 false
4108 }
4109 }
4110
4111 /// If any empty selections is touching the start of its innermost containing autoclose
4112 /// region, expand it to select the brackets.
4113 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4114 let selections = self.selections.all::<usize>(cx);
4115 let buffer = self.buffer.read(cx).read(cx);
4116 let new_selections = self
4117 .selections_with_autoclose_regions(selections, &buffer)
4118 .map(|(mut selection, region)| {
4119 if !selection.is_empty() {
4120 return selection;
4121 }
4122
4123 if let Some(region) = region {
4124 let mut range = region.range.to_offset(&buffer);
4125 if selection.start == range.start && range.start >= region.pair.start.len() {
4126 range.start -= region.pair.start.len();
4127 if buffer.contains_str_at(range.start, ®ion.pair.start)
4128 && buffer.contains_str_at(range.end, ®ion.pair.end)
4129 {
4130 range.end += region.pair.end.len();
4131 selection.start = range.start;
4132 selection.end = range.end;
4133
4134 return selection;
4135 }
4136 }
4137 }
4138
4139 let always_treat_brackets_as_autoclosed = buffer
4140 .language_settings_at(selection.start, cx)
4141 .always_treat_brackets_as_autoclosed;
4142
4143 if !always_treat_brackets_as_autoclosed {
4144 return selection;
4145 }
4146
4147 if let Some(scope) = buffer.language_scope_at(selection.start) {
4148 for (pair, enabled) in scope.brackets() {
4149 if !enabled || !pair.close {
4150 continue;
4151 }
4152
4153 if buffer.contains_str_at(selection.start, &pair.end) {
4154 let pair_start_len = pair.start.len();
4155 if buffer.contains_str_at(
4156 selection.start.saturating_sub(pair_start_len),
4157 &pair.start,
4158 ) {
4159 selection.start -= pair_start_len;
4160 selection.end += pair.end.len();
4161
4162 return selection;
4163 }
4164 }
4165 }
4166 }
4167
4168 selection
4169 })
4170 .collect();
4171
4172 drop(buffer);
4173 self.change_selections(None, window, cx, |selections| {
4174 selections.select(new_selections)
4175 });
4176 }
4177
4178 /// Iterate the given selections, and for each one, find the smallest surrounding
4179 /// autoclose region. This uses the ordering of the selections and the autoclose
4180 /// regions to avoid repeated comparisons.
4181 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4182 &'a self,
4183 selections: impl IntoIterator<Item = Selection<D>>,
4184 buffer: &'a MultiBufferSnapshot,
4185 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4186 let mut i = 0;
4187 let mut regions = self.autoclose_regions.as_slice();
4188 selections.into_iter().map(move |selection| {
4189 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4190
4191 let mut enclosing = None;
4192 while let Some(pair_state) = regions.get(i) {
4193 if pair_state.range.end.to_offset(buffer) < range.start {
4194 regions = ®ions[i + 1..];
4195 i = 0;
4196 } else if pair_state.range.start.to_offset(buffer) > range.end {
4197 break;
4198 } else {
4199 if pair_state.selection_id == selection.id {
4200 enclosing = Some(pair_state);
4201 }
4202 i += 1;
4203 }
4204 }
4205
4206 (selection, enclosing)
4207 })
4208 }
4209
4210 /// Remove any autoclose regions that no longer contain their selection.
4211 fn invalidate_autoclose_regions(
4212 &mut self,
4213 mut selections: &[Selection<Anchor>],
4214 buffer: &MultiBufferSnapshot,
4215 ) {
4216 self.autoclose_regions.retain(|state| {
4217 let mut i = 0;
4218 while let Some(selection) = selections.get(i) {
4219 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4220 selections = &selections[1..];
4221 continue;
4222 }
4223 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4224 break;
4225 }
4226 if selection.id == state.selection_id {
4227 return true;
4228 } else {
4229 i += 1;
4230 }
4231 }
4232 false
4233 });
4234 }
4235
4236 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4237 let offset = position.to_offset(buffer);
4238 let (word_range, kind) = buffer.surrounding_word(offset, true);
4239 if offset > word_range.start && kind == Some(CharKind::Word) {
4240 Some(
4241 buffer
4242 .text_for_range(word_range.start..offset)
4243 .collect::<String>(),
4244 )
4245 } else {
4246 None
4247 }
4248 }
4249
4250 pub fn toggle_inline_values(
4251 &mut self,
4252 _: &ToggleInlineValues,
4253 _: &mut Window,
4254 cx: &mut Context<Self>,
4255 ) {
4256 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4257
4258 self.refresh_inline_values(cx);
4259 }
4260
4261 pub fn toggle_inlay_hints(
4262 &mut self,
4263 _: &ToggleInlayHints,
4264 _: &mut Window,
4265 cx: &mut Context<Self>,
4266 ) {
4267 self.refresh_inlay_hints(
4268 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4269 cx,
4270 );
4271 }
4272
4273 pub fn inlay_hints_enabled(&self) -> bool {
4274 self.inlay_hint_cache.enabled
4275 }
4276
4277 pub fn inline_values_enabled(&self) -> bool {
4278 self.inline_value_cache.enabled
4279 }
4280
4281 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4282 if self.semantics_provider.is_none() || !self.mode.is_full() {
4283 return;
4284 }
4285
4286 let reason_description = reason.description();
4287 let ignore_debounce = matches!(
4288 reason,
4289 InlayHintRefreshReason::SettingsChange(_)
4290 | InlayHintRefreshReason::Toggle(_)
4291 | InlayHintRefreshReason::ExcerptsRemoved(_)
4292 | InlayHintRefreshReason::ModifiersChanged(_)
4293 );
4294 let (invalidate_cache, required_languages) = match reason {
4295 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4296 match self.inlay_hint_cache.modifiers_override(enabled) {
4297 Some(enabled) => {
4298 if enabled {
4299 (InvalidationStrategy::RefreshRequested, None)
4300 } else {
4301 self.splice_inlays(
4302 &self
4303 .visible_inlay_hints(cx)
4304 .iter()
4305 .map(|inlay| inlay.id)
4306 .collect::<Vec<InlayId>>(),
4307 Vec::new(),
4308 cx,
4309 );
4310 return;
4311 }
4312 }
4313 None => return,
4314 }
4315 }
4316 InlayHintRefreshReason::Toggle(enabled) => {
4317 if self.inlay_hint_cache.toggle(enabled) {
4318 if enabled {
4319 (InvalidationStrategy::RefreshRequested, None)
4320 } else {
4321 self.splice_inlays(
4322 &self
4323 .visible_inlay_hints(cx)
4324 .iter()
4325 .map(|inlay| inlay.id)
4326 .collect::<Vec<InlayId>>(),
4327 Vec::new(),
4328 cx,
4329 );
4330 return;
4331 }
4332 } else {
4333 return;
4334 }
4335 }
4336 InlayHintRefreshReason::SettingsChange(new_settings) => {
4337 match self.inlay_hint_cache.update_settings(
4338 &self.buffer,
4339 new_settings,
4340 self.visible_inlay_hints(cx),
4341 cx,
4342 ) {
4343 ControlFlow::Break(Some(InlaySplice {
4344 to_remove,
4345 to_insert,
4346 })) => {
4347 self.splice_inlays(&to_remove, to_insert, cx);
4348 return;
4349 }
4350 ControlFlow::Break(None) => return,
4351 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4352 }
4353 }
4354 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4355 if let Some(InlaySplice {
4356 to_remove,
4357 to_insert,
4358 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4359 {
4360 self.splice_inlays(&to_remove, to_insert, cx);
4361 }
4362 self.display_map.update(cx, |display_map, _| {
4363 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4364 });
4365 return;
4366 }
4367 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4368 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4369 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4370 }
4371 InlayHintRefreshReason::RefreshRequested => {
4372 (InvalidationStrategy::RefreshRequested, None)
4373 }
4374 };
4375
4376 if let Some(InlaySplice {
4377 to_remove,
4378 to_insert,
4379 }) = self.inlay_hint_cache.spawn_hint_refresh(
4380 reason_description,
4381 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4382 invalidate_cache,
4383 ignore_debounce,
4384 cx,
4385 ) {
4386 self.splice_inlays(&to_remove, to_insert, cx);
4387 }
4388 }
4389
4390 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4391 self.display_map
4392 .read(cx)
4393 .current_inlays()
4394 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4395 .cloned()
4396 .collect()
4397 }
4398
4399 pub fn excerpts_for_inlay_hints_query(
4400 &self,
4401 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4402 cx: &mut Context<Editor>,
4403 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4404 let Some(project) = self.project.as_ref() else {
4405 return HashMap::default();
4406 };
4407 let project = project.read(cx);
4408 let multi_buffer = self.buffer().read(cx);
4409 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4410 let multi_buffer_visible_start = self
4411 .scroll_manager
4412 .anchor()
4413 .anchor
4414 .to_point(&multi_buffer_snapshot);
4415 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4416 multi_buffer_visible_start
4417 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4418 Bias::Left,
4419 );
4420 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4421 multi_buffer_snapshot
4422 .range_to_buffer_ranges(multi_buffer_visible_range)
4423 .into_iter()
4424 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4425 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4426 let buffer_file = project::File::from_dyn(buffer.file())?;
4427 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4428 let worktree_entry = buffer_worktree
4429 .read(cx)
4430 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4431 if worktree_entry.is_ignored {
4432 return None;
4433 }
4434
4435 let language = buffer.language()?;
4436 if let Some(restrict_to_languages) = restrict_to_languages {
4437 if !restrict_to_languages.contains(language) {
4438 return None;
4439 }
4440 }
4441 Some((
4442 excerpt_id,
4443 (
4444 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4445 buffer.version().clone(),
4446 excerpt_visible_range,
4447 ),
4448 ))
4449 })
4450 .collect()
4451 }
4452
4453 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4454 TextLayoutDetails {
4455 text_system: window.text_system().clone(),
4456 editor_style: self.style.clone().unwrap(),
4457 rem_size: window.rem_size(),
4458 scroll_anchor: self.scroll_manager.anchor(),
4459 visible_rows: self.visible_line_count(),
4460 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4461 }
4462 }
4463
4464 pub fn splice_inlays(
4465 &self,
4466 to_remove: &[InlayId],
4467 to_insert: Vec<Inlay>,
4468 cx: &mut Context<Self>,
4469 ) {
4470 self.display_map.update(cx, |display_map, cx| {
4471 display_map.splice_inlays(to_remove, to_insert, cx)
4472 });
4473 cx.notify();
4474 }
4475
4476 fn trigger_on_type_formatting(
4477 &self,
4478 input: String,
4479 window: &mut Window,
4480 cx: &mut Context<Self>,
4481 ) -> Option<Task<Result<()>>> {
4482 if input.len() != 1 {
4483 return None;
4484 }
4485
4486 let project = self.project.as_ref()?;
4487 let position = self.selections.newest_anchor().head();
4488 let (buffer, buffer_position) = self
4489 .buffer
4490 .read(cx)
4491 .text_anchor_for_position(position, cx)?;
4492
4493 let settings = language_settings::language_settings(
4494 buffer
4495 .read(cx)
4496 .language_at(buffer_position)
4497 .map(|l| l.name()),
4498 buffer.read(cx).file(),
4499 cx,
4500 );
4501 if !settings.use_on_type_format {
4502 return None;
4503 }
4504
4505 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4506 // hence we do LSP request & edit on host side only — add formats to host's history.
4507 let push_to_lsp_host_history = true;
4508 // If this is not the host, append its history with new edits.
4509 let push_to_client_history = project.read(cx).is_via_collab();
4510
4511 let on_type_formatting = project.update(cx, |project, cx| {
4512 project.on_type_format(
4513 buffer.clone(),
4514 buffer_position,
4515 input,
4516 push_to_lsp_host_history,
4517 cx,
4518 )
4519 });
4520 Some(cx.spawn_in(window, async move |editor, cx| {
4521 if let Some(transaction) = on_type_formatting.await? {
4522 if push_to_client_history {
4523 buffer
4524 .update(cx, |buffer, _| {
4525 buffer.push_transaction(transaction, Instant::now());
4526 buffer.finalize_last_transaction();
4527 })
4528 .ok();
4529 }
4530 editor.update(cx, |editor, cx| {
4531 editor.refresh_document_highlights(cx);
4532 })?;
4533 }
4534 Ok(())
4535 }))
4536 }
4537
4538 pub fn show_word_completions(
4539 &mut self,
4540 _: &ShowWordCompletions,
4541 window: &mut Window,
4542 cx: &mut Context<Self>,
4543 ) {
4544 self.open_completions_menu(true, None, window, cx);
4545 }
4546
4547 pub fn show_completions(
4548 &mut self,
4549 options: &ShowCompletions,
4550 window: &mut Window,
4551 cx: &mut Context<Self>,
4552 ) {
4553 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4554 }
4555
4556 fn open_completions_menu(
4557 &mut self,
4558 ignore_completion_provider: bool,
4559 trigger: Option<&str>,
4560 window: &mut Window,
4561 cx: &mut Context<Self>,
4562 ) {
4563 if self.pending_rename.is_some() {
4564 return;
4565 }
4566 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4567 return;
4568 }
4569
4570 let position = self.selections.newest_anchor().head();
4571 if position.diff_base_anchor.is_some() {
4572 return;
4573 }
4574 let (buffer, buffer_position) =
4575 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4576 output
4577 } else {
4578 return;
4579 };
4580 let buffer_snapshot = buffer.read(cx).snapshot();
4581 let show_completion_documentation = buffer_snapshot
4582 .settings_at(buffer_position, cx)
4583 .show_completion_documentation;
4584
4585 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4586
4587 let trigger_kind = match trigger {
4588 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4589 CompletionTriggerKind::TRIGGER_CHARACTER
4590 }
4591 _ => CompletionTriggerKind::INVOKED,
4592 };
4593 let completion_context = CompletionContext {
4594 trigger_character: trigger.and_then(|trigger| {
4595 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4596 Some(String::from(trigger))
4597 } else {
4598 None
4599 }
4600 }),
4601 trigger_kind,
4602 };
4603
4604 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4605 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4606 let word_to_exclude = buffer_snapshot
4607 .text_for_range(old_range.clone())
4608 .collect::<String>();
4609 (
4610 buffer_snapshot.anchor_before(old_range.start)
4611 ..buffer_snapshot.anchor_after(old_range.end),
4612 Some(word_to_exclude),
4613 )
4614 } else {
4615 (buffer_position..buffer_position, None)
4616 };
4617
4618 let completion_settings = language_settings(
4619 buffer_snapshot
4620 .language_at(buffer_position)
4621 .map(|language| language.name()),
4622 buffer_snapshot.file(),
4623 cx,
4624 )
4625 .completions;
4626
4627 // The document can be large, so stay in reasonable bounds when searching for words,
4628 // otherwise completion pop-up might be slow to appear.
4629 const WORD_LOOKUP_ROWS: u32 = 5_000;
4630 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4631 let min_word_search = buffer_snapshot.clip_point(
4632 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4633 Bias::Left,
4634 );
4635 let max_word_search = buffer_snapshot.clip_point(
4636 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4637 Bias::Right,
4638 );
4639 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4640 ..buffer_snapshot.point_to_offset(max_word_search);
4641
4642 let provider = self
4643 .completion_provider
4644 .as_ref()
4645 .filter(|_| !ignore_completion_provider);
4646 let skip_digits = query
4647 .as_ref()
4648 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4649
4650 let (mut words, provided_completions) = match provider {
4651 Some(provider) => {
4652 let completions = provider.completions(
4653 position.excerpt_id,
4654 &buffer,
4655 buffer_position,
4656 completion_context,
4657 window,
4658 cx,
4659 );
4660
4661 let words = match completion_settings.words {
4662 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4663 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4664 .background_spawn(async move {
4665 buffer_snapshot.words_in_range(WordsQuery {
4666 fuzzy_contents: None,
4667 range: word_search_range,
4668 skip_digits,
4669 })
4670 }),
4671 };
4672
4673 (words, completions)
4674 }
4675 None => (
4676 cx.background_spawn(async move {
4677 buffer_snapshot.words_in_range(WordsQuery {
4678 fuzzy_contents: None,
4679 range: word_search_range,
4680 skip_digits,
4681 })
4682 }),
4683 Task::ready(Ok(None)),
4684 ),
4685 };
4686
4687 let sort_completions = provider
4688 .as_ref()
4689 .map_or(false, |provider| provider.sort_completions());
4690
4691 let filter_completions = provider
4692 .as_ref()
4693 .map_or(true, |provider| provider.filter_completions());
4694
4695 let id = post_inc(&mut self.next_completion_id);
4696 let task = cx.spawn_in(window, async move |editor, cx| {
4697 async move {
4698 editor.update(cx, |this, _| {
4699 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4700 })?;
4701
4702 let mut completions = Vec::new();
4703 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4704 completions.extend(provided_completions);
4705 if completion_settings.words == WordsCompletionMode::Fallback {
4706 words = Task::ready(BTreeMap::default());
4707 }
4708 }
4709
4710 let mut words = words.await;
4711 if let Some(word_to_exclude) = &word_to_exclude {
4712 words.remove(word_to_exclude);
4713 }
4714 for lsp_completion in &completions {
4715 words.remove(&lsp_completion.new_text);
4716 }
4717 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4718 replace_range: old_range.clone(),
4719 new_text: word.clone(),
4720 label: CodeLabel::plain(word, None),
4721 icon_path: None,
4722 documentation: None,
4723 source: CompletionSource::BufferWord {
4724 word_range,
4725 resolved: false,
4726 },
4727 insert_text_mode: Some(InsertTextMode::AS_IS),
4728 confirm: None,
4729 }));
4730
4731 let menu = if completions.is_empty() {
4732 None
4733 } else {
4734 let mut menu = CompletionsMenu::new(
4735 id,
4736 sort_completions,
4737 show_completion_documentation,
4738 ignore_completion_provider,
4739 position,
4740 buffer.clone(),
4741 completions.into(),
4742 );
4743
4744 menu.filter(
4745 if filter_completions {
4746 query.as_deref()
4747 } else {
4748 None
4749 },
4750 cx.background_executor().clone(),
4751 )
4752 .await;
4753
4754 menu.visible().then_some(menu)
4755 };
4756
4757 editor.update_in(cx, |editor, window, cx| {
4758 match editor.context_menu.borrow().as_ref() {
4759 None => {}
4760 Some(CodeContextMenu::Completions(prev_menu)) => {
4761 if prev_menu.id > id {
4762 return;
4763 }
4764 }
4765 _ => return,
4766 }
4767
4768 if editor.focus_handle.is_focused(window) && menu.is_some() {
4769 let mut menu = menu.unwrap();
4770 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4771
4772 *editor.context_menu.borrow_mut() =
4773 Some(CodeContextMenu::Completions(menu));
4774
4775 if editor.show_edit_predictions_in_menu() {
4776 editor.update_visible_inline_completion(window, cx);
4777 } else {
4778 editor.discard_inline_completion(false, cx);
4779 }
4780
4781 cx.notify();
4782 } else if editor.completion_tasks.len() <= 1 {
4783 // If there are no more completion tasks and the last menu was
4784 // empty, we should hide it.
4785 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4786 // If it was already hidden and we don't show inline
4787 // completions in the menu, we should also show the
4788 // inline-completion when available.
4789 if was_hidden && editor.show_edit_predictions_in_menu() {
4790 editor.update_visible_inline_completion(window, cx);
4791 }
4792 }
4793 })?;
4794
4795 anyhow::Ok(())
4796 }
4797 .log_err()
4798 .await
4799 });
4800
4801 self.completion_tasks.push((id, task));
4802 }
4803
4804 #[cfg(feature = "test-support")]
4805 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4806 let menu = self.context_menu.borrow();
4807 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4808 let completions = menu.completions.borrow();
4809 Some(completions.to_vec())
4810 } else {
4811 None
4812 }
4813 }
4814
4815 pub fn confirm_completion(
4816 &mut self,
4817 action: &ConfirmCompletion,
4818 window: &mut Window,
4819 cx: &mut Context<Self>,
4820 ) -> Option<Task<Result<()>>> {
4821 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4822 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4823 }
4824
4825 pub fn confirm_completion_insert(
4826 &mut self,
4827 _: &ConfirmCompletionInsert,
4828 window: &mut Window,
4829 cx: &mut Context<Self>,
4830 ) -> Option<Task<Result<()>>> {
4831 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4832 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4833 }
4834
4835 pub fn confirm_completion_replace(
4836 &mut self,
4837 _: &ConfirmCompletionReplace,
4838 window: &mut Window,
4839 cx: &mut Context<Self>,
4840 ) -> Option<Task<Result<()>>> {
4841 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4842 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4843 }
4844
4845 pub fn compose_completion(
4846 &mut self,
4847 action: &ComposeCompletion,
4848 window: &mut Window,
4849 cx: &mut Context<Self>,
4850 ) -> Option<Task<Result<()>>> {
4851 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4852 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4853 }
4854
4855 fn do_completion(
4856 &mut self,
4857 item_ix: Option<usize>,
4858 intent: CompletionIntent,
4859 window: &mut Window,
4860 cx: &mut Context<Editor>,
4861 ) -> Option<Task<Result<()>>> {
4862 use language::ToOffset as _;
4863
4864 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4865 else {
4866 return None;
4867 };
4868
4869 let candidate_id = {
4870 let entries = completions_menu.entries.borrow();
4871 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4872 if self.show_edit_predictions_in_menu() {
4873 self.discard_inline_completion(true, cx);
4874 }
4875 mat.candidate_id
4876 };
4877
4878 let buffer_handle = completions_menu.buffer;
4879 let completion = completions_menu
4880 .completions
4881 .borrow()
4882 .get(candidate_id)?
4883 .clone();
4884 cx.stop_propagation();
4885
4886 let snippet;
4887 let new_text;
4888 if completion.is_snippet() {
4889 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4890 new_text = snippet.as_ref().unwrap().text.clone();
4891 } else {
4892 snippet = None;
4893 new_text = completion.new_text.clone();
4894 };
4895
4896 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4897 let buffer = buffer_handle.read(cx);
4898 let snapshot = self.buffer.read(cx).snapshot(cx);
4899 let replace_range_multibuffer = {
4900 let excerpt = snapshot
4901 .excerpt_containing(self.selections.newest_anchor().range())
4902 .unwrap();
4903 let multibuffer_anchor = snapshot
4904 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4905 .unwrap()
4906 ..snapshot
4907 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4908 .unwrap();
4909 multibuffer_anchor.start.to_offset(&snapshot)
4910 ..multibuffer_anchor.end.to_offset(&snapshot)
4911 };
4912 let newest_anchor = self.selections.newest_anchor();
4913 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4914 return None;
4915 }
4916
4917 let old_text = buffer
4918 .text_for_range(replace_range.clone())
4919 .collect::<String>();
4920 let lookbehind = newest_anchor
4921 .start
4922 .text_anchor
4923 .to_offset(buffer)
4924 .saturating_sub(replace_range.start);
4925 let lookahead = replace_range
4926 .end
4927 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4928 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4929 let suffix = &old_text[lookbehind.min(old_text.len())..];
4930
4931 let selections = self.selections.all::<usize>(cx);
4932 let mut ranges = Vec::new();
4933 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4934
4935 for selection in &selections {
4936 let range = if selection.id == newest_anchor.id {
4937 replace_range_multibuffer.clone()
4938 } else {
4939 let mut range = selection.range();
4940
4941 // if prefix is present, don't duplicate it
4942 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4943 range.start = range.start.saturating_sub(lookbehind);
4944
4945 // if suffix is also present, mimic the newest cursor and replace it
4946 if selection.id != newest_anchor.id
4947 && snapshot.contains_str_at(range.end, suffix)
4948 {
4949 range.end += lookahead;
4950 }
4951 }
4952 range
4953 };
4954
4955 ranges.push(range);
4956
4957 if !self.linked_edit_ranges.is_empty() {
4958 let start_anchor = snapshot.anchor_before(selection.head());
4959 let end_anchor = snapshot.anchor_after(selection.tail());
4960 if let Some(ranges) = self
4961 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4962 {
4963 for (buffer, edits) in ranges {
4964 linked_edits
4965 .entry(buffer.clone())
4966 .or_default()
4967 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4968 }
4969 }
4970 }
4971 }
4972
4973 cx.emit(EditorEvent::InputHandled {
4974 utf16_range_to_replace: None,
4975 text: new_text.clone().into(),
4976 });
4977
4978 self.transact(window, cx, |this, window, cx| {
4979 if let Some(mut snippet) = snippet {
4980 snippet.text = new_text.to_string();
4981 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4982 } else {
4983 this.buffer.update(cx, |buffer, cx| {
4984 let auto_indent = match completion.insert_text_mode {
4985 Some(InsertTextMode::AS_IS) => None,
4986 _ => this.autoindent_mode.clone(),
4987 };
4988 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4989 buffer.edit(edits, auto_indent, cx);
4990 });
4991 }
4992 for (buffer, edits) in linked_edits {
4993 buffer.update(cx, |buffer, cx| {
4994 let snapshot = buffer.snapshot();
4995 let edits = edits
4996 .into_iter()
4997 .map(|(range, text)| {
4998 use text::ToPoint as TP;
4999 let end_point = TP::to_point(&range.end, &snapshot);
5000 let start_point = TP::to_point(&range.start, &snapshot);
5001 (start_point..end_point, text)
5002 })
5003 .sorted_by_key(|(range, _)| range.start);
5004 buffer.edit(edits, None, cx);
5005 })
5006 }
5007
5008 this.refresh_inline_completion(true, false, window, cx);
5009 });
5010
5011 let show_new_completions_on_confirm = completion
5012 .confirm
5013 .as_ref()
5014 .map_or(false, |confirm| confirm(intent, window, cx));
5015 if show_new_completions_on_confirm {
5016 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5017 }
5018
5019 let provider = self.completion_provider.as_ref()?;
5020 drop(completion);
5021 let apply_edits = provider.apply_additional_edits_for_completion(
5022 buffer_handle,
5023 completions_menu.completions.clone(),
5024 candidate_id,
5025 true,
5026 cx,
5027 );
5028
5029 let editor_settings = EditorSettings::get_global(cx);
5030 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5031 // After the code completion is finished, users often want to know what signatures are needed.
5032 // so we should automatically call signature_help
5033 self.show_signature_help(&ShowSignatureHelp, window, cx);
5034 }
5035
5036 Some(cx.foreground_executor().spawn(async move {
5037 apply_edits.await?;
5038 Ok(())
5039 }))
5040 }
5041
5042 pub fn toggle_code_actions(
5043 &mut self,
5044 action: &ToggleCodeActions,
5045 window: &mut Window,
5046 cx: &mut Context<Self>,
5047 ) {
5048 let mut context_menu = self.context_menu.borrow_mut();
5049 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5050 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5051 // Toggle if we're selecting the same one
5052 *context_menu = None;
5053 cx.notify();
5054 return;
5055 } else {
5056 // Otherwise, clear it and start a new one
5057 *context_menu = None;
5058 cx.notify();
5059 }
5060 }
5061 drop(context_menu);
5062 let snapshot = self.snapshot(window, cx);
5063 let deployed_from_indicator = action.deployed_from_indicator;
5064 let mut task = self.code_actions_task.take();
5065 let action = action.clone();
5066 cx.spawn_in(window, async move |editor, cx| {
5067 while let Some(prev_task) = task {
5068 prev_task.await.log_err();
5069 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5070 }
5071
5072 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5073 if editor.focus_handle.is_focused(window) {
5074 let multibuffer_point = action
5075 .deployed_from_indicator
5076 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5077 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5078 let (buffer, buffer_row) = snapshot
5079 .buffer_snapshot
5080 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5081 .and_then(|(buffer_snapshot, range)| {
5082 editor
5083 .buffer
5084 .read(cx)
5085 .buffer(buffer_snapshot.remote_id())
5086 .map(|buffer| (buffer, range.start.row))
5087 })?;
5088 let (_, code_actions) = editor
5089 .available_code_actions
5090 .clone()
5091 .and_then(|(location, code_actions)| {
5092 let snapshot = location.buffer.read(cx).snapshot();
5093 let point_range = location.range.to_point(&snapshot);
5094 let point_range = point_range.start.row..=point_range.end.row;
5095 if point_range.contains(&buffer_row) {
5096 Some((location, code_actions))
5097 } else {
5098 None
5099 }
5100 })
5101 .unzip();
5102 let buffer_id = buffer.read(cx).remote_id();
5103 let tasks = editor
5104 .tasks
5105 .get(&(buffer_id, buffer_row))
5106 .map(|t| Arc::new(t.to_owned()));
5107 if tasks.is_none() && code_actions.is_none() {
5108 return None;
5109 }
5110
5111 editor.completion_tasks.clear();
5112 editor.discard_inline_completion(false, cx);
5113 let task_context =
5114 tasks
5115 .as_ref()
5116 .zip(editor.project.clone())
5117 .map(|(tasks, project)| {
5118 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5119 });
5120
5121 let debugger_flag = cx.has_flag::<Debugger>();
5122
5123 Some(cx.spawn_in(window, async move |editor, cx| {
5124 let task_context = match task_context {
5125 Some(task_context) => task_context.await,
5126 None => None,
5127 };
5128 let resolved_tasks =
5129 tasks
5130 .zip(task_context)
5131 .map(|(tasks, task_context)| ResolvedTasks {
5132 templates: tasks.resolve(&task_context).collect(),
5133 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5134 multibuffer_point.row,
5135 tasks.column,
5136 )),
5137 });
5138 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
5139 tasks
5140 .templates
5141 .iter()
5142 .filter(|task| {
5143 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5144 debugger_flag
5145 } else {
5146 true
5147 }
5148 })
5149 .count()
5150 == 1
5151 }) && code_actions
5152 .as_ref()
5153 .map_or(true, |actions| actions.is_empty());
5154 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5155 *editor.context_menu.borrow_mut() =
5156 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5157 buffer,
5158 actions: CodeActionContents::new(
5159 resolved_tasks,
5160 code_actions,
5161 cx,
5162 ),
5163 selected_item: Default::default(),
5164 scroll_handle: UniformListScrollHandle::default(),
5165 deployed_from_indicator,
5166 }));
5167 if spawn_straight_away {
5168 if let Some(task) = editor.confirm_code_action(
5169 &ConfirmCodeAction { item_ix: Some(0) },
5170 window,
5171 cx,
5172 ) {
5173 cx.notify();
5174 return task;
5175 }
5176 }
5177 cx.notify();
5178 Task::ready(Ok(()))
5179 }) {
5180 task.await
5181 } else {
5182 Ok(())
5183 }
5184 }))
5185 } else {
5186 Some(Task::ready(Ok(())))
5187 }
5188 })?;
5189 if let Some(task) = spawned_test_task {
5190 task.await?;
5191 }
5192
5193 Ok::<_, anyhow::Error>(())
5194 })
5195 .detach_and_log_err(cx);
5196 }
5197
5198 pub fn confirm_code_action(
5199 &mut self,
5200 action: &ConfirmCodeAction,
5201 window: &mut Window,
5202 cx: &mut Context<Self>,
5203 ) -> Option<Task<Result<()>>> {
5204 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5205
5206 let actions_menu =
5207 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5208 menu
5209 } else {
5210 return None;
5211 };
5212
5213 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5214 let action = actions_menu.actions.get(action_ix)?;
5215 let title = action.label();
5216 let buffer = actions_menu.buffer;
5217 let workspace = self.workspace()?;
5218
5219 match action {
5220 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5221 match resolved_task.task_type() {
5222 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5223 workspace.schedule_resolved_task(
5224 task_source_kind,
5225 resolved_task,
5226 false,
5227 window,
5228 cx,
5229 );
5230
5231 Some(Task::ready(Ok(())))
5232 }),
5233 task::TaskType::Debug(_) => {
5234 workspace.update(cx, |workspace, cx| {
5235 workspace.schedule_debug_task(resolved_task, window, cx);
5236 });
5237 Some(Task::ready(Ok(())))
5238 }
5239 }
5240 }
5241 CodeActionsItem::CodeAction {
5242 excerpt_id,
5243 action,
5244 provider,
5245 } => {
5246 let apply_code_action =
5247 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5248 let workspace = workspace.downgrade();
5249 Some(cx.spawn_in(window, async move |editor, cx| {
5250 let project_transaction = apply_code_action.await?;
5251 Self::open_project_transaction(
5252 &editor,
5253 workspace,
5254 project_transaction,
5255 title,
5256 cx,
5257 )
5258 .await
5259 }))
5260 }
5261 }
5262 }
5263
5264 pub async fn open_project_transaction(
5265 this: &WeakEntity<Editor>,
5266 workspace: WeakEntity<Workspace>,
5267 transaction: ProjectTransaction,
5268 title: String,
5269 cx: &mut AsyncWindowContext,
5270 ) -> Result<()> {
5271 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5272 cx.update(|_, cx| {
5273 entries.sort_unstable_by_key(|(buffer, _)| {
5274 buffer.read(cx).file().map(|f| f.path().clone())
5275 });
5276 })?;
5277
5278 // If the project transaction's edits are all contained within this editor, then
5279 // avoid opening a new editor to display them.
5280
5281 if let Some((buffer, transaction)) = entries.first() {
5282 if entries.len() == 1 {
5283 let excerpt = this.update(cx, |editor, cx| {
5284 editor
5285 .buffer()
5286 .read(cx)
5287 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5288 })?;
5289 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5290 if excerpted_buffer == *buffer {
5291 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5292 let excerpt_range = excerpt_range.to_offset(buffer);
5293 buffer
5294 .edited_ranges_for_transaction::<usize>(transaction)
5295 .all(|range| {
5296 excerpt_range.start <= range.start
5297 && excerpt_range.end >= range.end
5298 })
5299 })?;
5300
5301 if all_edits_within_excerpt {
5302 return Ok(());
5303 }
5304 }
5305 }
5306 }
5307 } else {
5308 return Ok(());
5309 }
5310
5311 let mut ranges_to_highlight = Vec::new();
5312 let excerpt_buffer = cx.new(|cx| {
5313 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5314 for (buffer_handle, transaction) in &entries {
5315 let edited_ranges = buffer_handle
5316 .read(cx)
5317 .edited_ranges_for_transaction::<Point>(transaction)
5318 .collect::<Vec<_>>();
5319 let (ranges, _) = multibuffer.set_excerpts_for_path(
5320 PathKey::for_buffer(buffer_handle, cx),
5321 buffer_handle.clone(),
5322 edited_ranges,
5323 DEFAULT_MULTIBUFFER_CONTEXT,
5324 cx,
5325 );
5326
5327 ranges_to_highlight.extend(ranges);
5328 }
5329 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5330 multibuffer
5331 })?;
5332
5333 workspace.update_in(cx, |workspace, window, cx| {
5334 let project = workspace.project().clone();
5335 let editor =
5336 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5337 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5338 editor.update(cx, |editor, cx| {
5339 editor.highlight_background::<Self>(
5340 &ranges_to_highlight,
5341 |theme| theme.editor_highlighted_line_background,
5342 cx,
5343 );
5344 });
5345 })?;
5346
5347 Ok(())
5348 }
5349
5350 pub fn clear_code_action_providers(&mut self) {
5351 self.code_action_providers.clear();
5352 self.available_code_actions.take();
5353 }
5354
5355 pub fn add_code_action_provider(
5356 &mut self,
5357 provider: Rc<dyn CodeActionProvider>,
5358 window: &mut Window,
5359 cx: &mut Context<Self>,
5360 ) {
5361 if self
5362 .code_action_providers
5363 .iter()
5364 .any(|existing_provider| existing_provider.id() == provider.id())
5365 {
5366 return;
5367 }
5368
5369 self.code_action_providers.push(provider);
5370 self.refresh_code_actions(window, cx);
5371 }
5372
5373 pub fn remove_code_action_provider(
5374 &mut self,
5375 id: Arc<str>,
5376 window: &mut Window,
5377 cx: &mut Context<Self>,
5378 ) {
5379 self.code_action_providers
5380 .retain(|provider| provider.id() != id);
5381 self.refresh_code_actions(window, cx);
5382 }
5383
5384 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5385 let newest_selection = self.selections.newest_anchor().clone();
5386 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5387 let buffer = self.buffer.read(cx);
5388 if newest_selection.head().diff_base_anchor.is_some() {
5389 return None;
5390 }
5391 let (start_buffer, start) =
5392 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5393 let (end_buffer, end) =
5394 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5395 if start_buffer != end_buffer {
5396 return None;
5397 }
5398
5399 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5400 cx.background_executor()
5401 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5402 .await;
5403
5404 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5405 let providers = this.code_action_providers.clone();
5406 let tasks = this
5407 .code_action_providers
5408 .iter()
5409 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5410 .collect::<Vec<_>>();
5411 (providers, tasks)
5412 })?;
5413
5414 let mut actions = Vec::new();
5415 for (provider, provider_actions) in
5416 providers.into_iter().zip(future::join_all(tasks).await)
5417 {
5418 if let Some(provider_actions) = provider_actions.log_err() {
5419 actions.extend(provider_actions.into_iter().map(|action| {
5420 AvailableCodeAction {
5421 excerpt_id: newest_selection.start.excerpt_id,
5422 action,
5423 provider: provider.clone(),
5424 }
5425 }));
5426 }
5427 }
5428
5429 this.update(cx, |this, cx| {
5430 this.available_code_actions = if actions.is_empty() {
5431 None
5432 } else {
5433 Some((
5434 Location {
5435 buffer: start_buffer,
5436 range: start..end,
5437 },
5438 actions.into(),
5439 ))
5440 };
5441 cx.notify();
5442 })
5443 }));
5444 None
5445 }
5446
5447 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5448 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5449 self.show_git_blame_inline = false;
5450
5451 self.show_git_blame_inline_delay_task =
5452 Some(cx.spawn_in(window, async move |this, cx| {
5453 cx.background_executor().timer(delay).await;
5454
5455 this.update(cx, |this, cx| {
5456 this.show_git_blame_inline = true;
5457 cx.notify();
5458 })
5459 .log_err();
5460 }));
5461 }
5462 }
5463
5464 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5465 if self.pending_rename.is_some() {
5466 return None;
5467 }
5468
5469 let provider = self.semantics_provider.clone()?;
5470 let buffer = self.buffer.read(cx);
5471 let newest_selection = self.selections.newest_anchor().clone();
5472 let cursor_position = newest_selection.head();
5473 let (cursor_buffer, cursor_buffer_position) =
5474 buffer.text_anchor_for_position(cursor_position, cx)?;
5475 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5476 if cursor_buffer != tail_buffer {
5477 return None;
5478 }
5479 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5480 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5481 cx.background_executor()
5482 .timer(Duration::from_millis(debounce))
5483 .await;
5484
5485 let highlights = if let Some(highlights) = cx
5486 .update(|cx| {
5487 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5488 })
5489 .ok()
5490 .flatten()
5491 {
5492 highlights.await.log_err()
5493 } else {
5494 None
5495 };
5496
5497 if let Some(highlights) = highlights {
5498 this.update(cx, |this, cx| {
5499 if this.pending_rename.is_some() {
5500 return;
5501 }
5502
5503 let buffer_id = cursor_position.buffer_id;
5504 let buffer = this.buffer.read(cx);
5505 if !buffer
5506 .text_anchor_for_position(cursor_position, cx)
5507 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5508 {
5509 return;
5510 }
5511
5512 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5513 let mut write_ranges = Vec::new();
5514 let mut read_ranges = Vec::new();
5515 for highlight in highlights {
5516 for (excerpt_id, excerpt_range) in
5517 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5518 {
5519 let start = highlight
5520 .range
5521 .start
5522 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5523 let end = highlight
5524 .range
5525 .end
5526 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5527 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5528 continue;
5529 }
5530
5531 let range = Anchor {
5532 buffer_id,
5533 excerpt_id,
5534 text_anchor: start,
5535 diff_base_anchor: None,
5536 }..Anchor {
5537 buffer_id,
5538 excerpt_id,
5539 text_anchor: end,
5540 diff_base_anchor: None,
5541 };
5542 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5543 write_ranges.push(range);
5544 } else {
5545 read_ranges.push(range);
5546 }
5547 }
5548 }
5549
5550 this.highlight_background::<DocumentHighlightRead>(
5551 &read_ranges,
5552 |theme| theme.editor_document_highlight_read_background,
5553 cx,
5554 );
5555 this.highlight_background::<DocumentHighlightWrite>(
5556 &write_ranges,
5557 |theme| theme.editor_document_highlight_write_background,
5558 cx,
5559 );
5560 cx.notify();
5561 })
5562 .log_err();
5563 }
5564 }));
5565 None
5566 }
5567
5568 fn prepare_highlight_query_from_selection(
5569 &mut self,
5570 cx: &mut Context<Editor>,
5571 ) -> Option<(String, Range<Anchor>)> {
5572 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5573 return None;
5574 }
5575 if !EditorSettings::get_global(cx).selection_highlight {
5576 return None;
5577 }
5578 if self.selections.count() != 1 || self.selections.line_mode {
5579 return None;
5580 }
5581 let selection = self.selections.newest::<Point>(cx);
5582 if selection.is_empty() || selection.start.row != selection.end.row {
5583 return None;
5584 }
5585 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5586 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5587 let query = multi_buffer_snapshot
5588 .text_for_range(selection_anchor_range.clone())
5589 .collect::<String>();
5590 if query.trim().is_empty() {
5591 return None;
5592 }
5593 Some((query, selection_anchor_range))
5594 }
5595
5596 fn update_selection_occurrence_highlights(
5597 &mut self,
5598 query_text: String,
5599 query_range: Range<Anchor>,
5600 multi_buffer_range_to_query: Range<Point>,
5601 use_debounce: bool,
5602 window: &mut Window,
5603 cx: &mut Context<Editor>,
5604 ) -> Task<()> {
5605 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5606 cx.spawn_in(window, async move |editor, cx| {
5607 if use_debounce {
5608 cx.background_executor()
5609 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5610 .await;
5611 }
5612 let match_task = cx.background_spawn(async move {
5613 let buffer_ranges = multi_buffer_snapshot
5614 .range_to_buffer_ranges(multi_buffer_range_to_query)
5615 .into_iter()
5616 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5617 let mut match_ranges = Vec::new();
5618 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5619 match_ranges.extend(
5620 project::search::SearchQuery::text(
5621 query_text.clone(),
5622 false,
5623 false,
5624 false,
5625 Default::default(),
5626 Default::default(),
5627 false,
5628 None,
5629 )
5630 .unwrap()
5631 .search(&buffer_snapshot, Some(search_range.clone()))
5632 .await
5633 .into_iter()
5634 .filter_map(|match_range| {
5635 let match_start = buffer_snapshot
5636 .anchor_after(search_range.start + match_range.start);
5637 let match_end =
5638 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5639 let match_anchor_range = Anchor::range_in_buffer(
5640 excerpt_id,
5641 buffer_snapshot.remote_id(),
5642 match_start..match_end,
5643 );
5644 (match_anchor_range != query_range).then_some(match_anchor_range)
5645 }),
5646 );
5647 }
5648 match_ranges
5649 });
5650 let match_ranges = match_task.await;
5651 editor
5652 .update_in(cx, |editor, _, cx| {
5653 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5654 if !match_ranges.is_empty() {
5655 editor.highlight_background::<SelectedTextHighlight>(
5656 &match_ranges,
5657 |theme| theme.editor_document_highlight_bracket_background,
5658 cx,
5659 )
5660 }
5661 })
5662 .log_err();
5663 })
5664 }
5665
5666 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5667 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5668 else {
5669 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5670 self.quick_selection_highlight_task.take();
5671 self.debounced_selection_highlight_task.take();
5672 return;
5673 };
5674 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5675 if self
5676 .quick_selection_highlight_task
5677 .as_ref()
5678 .map_or(true, |(prev_anchor_range, _)| {
5679 prev_anchor_range != &query_range
5680 })
5681 {
5682 let multi_buffer_visible_start = self
5683 .scroll_manager
5684 .anchor()
5685 .anchor
5686 .to_point(&multi_buffer_snapshot);
5687 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5688 multi_buffer_visible_start
5689 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5690 Bias::Left,
5691 );
5692 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5693 self.quick_selection_highlight_task = Some((
5694 query_range.clone(),
5695 self.update_selection_occurrence_highlights(
5696 query_text.clone(),
5697 query_range.clone(),
5698 multi_buffer_visible_range,
5699 false,
5700 window,
5701 cx,
5702 ),
5703 ));
5704 }
5705 if self
5706 .debounced_selection_highlight_task
5707 .as_ref()
5708 .map_or(true, |(prev_anchor_range, _)| {
5709 prev_anchor_range != &query_range
5710 })
5711 {
5712 let multi_buffer_start = multi_buffer_snapshot
5713 .anchor_before(0)
5714 .to_point(&multi_buffer_snapshot);
5715 let multi_buffer_end = multi_buffer_snapshot
5716 .anchor_after(multi_buffer_snapshot.len())
5717 .to_point(&multi_buffer_snapshot);
5718 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5719 self.debounced_selection_highlight_task = Some((
5720 query_range.clone(),
5721 self.update_selection_occurrence_highlights(
5722 query_text,
5723 query_range,
5724 multi_buffer_full_range,
5725 true,
5726 window,
5727 cx,
5728 ),
5729 ));
5730 }
5731 }
5732
5733 pub fn refresh_inline_completion(
5734 &mut self,
5735 debounce: bool,
5736 user_requested: bool,
5737 window: &mut Window,
5738 cx: &mut Context<Self>,
5739 ) -> Option<()> {
5740 let provider = self.edit_prediction_provider()?;
5741 let cursor = self.selections.newest_anchor().head();
5742 let (buffer, cursor_buffer_position) =
5743 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5744
5745 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5746 self.discard_inline_completion(false, cx);
5747 return None;
5748 }
5749
5750 if !user_requested
5751 && (!self.should_show_edit_predictions()
5752 || !self.is_focused(window)
5753 || buffer.read(cx).is_empty())
5754 {
5755 self.discard_inline_completion(false, cx);
5756 return None;
5757 }
5758
5759 self.update_visible_inline_completion(window, cx);
5760 provider.refresh(
5761 self.project.clone(),
5762 buffer,
5763 cursor_buffer_position,
5764 debounce,
5765 cx,
5766 );
5767 Some(())
5768 }
5769
5770 fn show_edit_predictions_in_menu(&self) -> bool {
5771 match self.edit_prediction_settings {
5772 EditPredictionSettings::Disabled => false,
5773 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5774 }
5775 }
5776
5777 pub fn edit_predictions_enabled(&self) -> bool {
5778 match self.edit_prediction_settings {
5779 EditPredictionSettings::Disabled => false,
5780 EditPredictionSettings::Enabled { .. } => true,
5781 }
5782 }
5783
5784 fn edit_prediction_requires_modifier(&self) -> bool {
5785 match self.edit_prediction_settings {
5786 EditPredictionSettings::Disabled => false,
5787 EditPredictionSettings::Enabled {
5788 preview_requires_modifier,
5789 ..
5790 } => preview_requires_modifier,
5791 }
5792 }
5793
5794 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5795 if self.edit_prediction_provider.is_none() {
5796 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5797 } else {
5798 let selection = self.selections.newest_anchor();
5799 let cursor = selection.head();
5800
5801 if let Some((buffer, cursor_buffer_position)) =
5802 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5803 {
5804 self.edit_prediction_settings =
5805 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5806 }
5807 }
5808 }
5809
5810 fn edit_prediction_settings_at_position(
5811 &self,
5812 buffer: &Entity<Buffer>,
5813 buffer_position: language::Anchor,
5814 cx: &App,
5815 ) -> EditPredictionSettings {
5816 if !self.mode.is_full()
5817 || !self.show_inline_completions_override.unwrap_or(true)
5818 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5819 {
5820 return EditPredictionSettings::Disabled;
5821 }
5822
5823 let buffer = buffer.read(cx);
5824
5825 let file = buffer.file();
5826
5827 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5828 return EditPredictionSettings::Disabled;
5829 };
5830
5831 let by_provider = matches!(
5832 self.menu_inline_completions_policy,
5833 MenuInlineCompletionsPolicy::ByProvider
5834 );
5835
5836 let show_in_menu = by_provider
5837 && self
5838 .edit_prediction_provider
5839 .as_ref()
5840 .map_or(false, |provider| {
5841 provider.provider.show_completions_in_menu()
5842 });
5843
5844 let preview_requires_modifier =
5845 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5846
5847 EditPredictionSettings::Enabled {
5848 show_in_menu,
5849 preview_requires_modifier,
5850 }
5851 }
5852
5853 fn should_show_edit_predictions(&self) -> bool {
5854 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5855 }
5856
5857 pub fn edit_prediction_preview_is_active(&self) -> bool {
5858 matches!(
5859 self.edit_prediction_preview,
5860 EditPredictionPreview::Active { .. }
5861 )
5862 }
5863
5864 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5865 let cursor = self.selections.newest_anchor().head();
5866 if let Some((buffer, cursor_position)) =
5867 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5868 {
5869 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5870 } else {
5871 false
5872 }
5873 }
5874
5875 fn edit_predictions_enabled_in_buffer(
5876 &self,
5877 buffer: &Entity<Buffer>,
5878 buffer_position: language::Anchor,
5879 cx: &App,
5880 ) -> bool {
5881 maybe!({
5882 if self.read_only(cx) {
5883 return Some(false);
5884 }
5885 let provider = self.edit_prediction_provider()?;
5886 if !provider.is_enabled(&buffer, buffer_position, cx) {
5887 return Some(false);
5888 }
5889 let buffer = buffer.read(cx);
5890 let Some(file) = buffer.file() else {
5891 return Some(true);
5892 };
5893 let settings = all_language_settings(Some(file), cx);
5894 Some(settings.edit_predictions_enabled_for_file(file, cx))
5895 })
5896 .unwrap_or(false)
5897 }
5898
5899 fn cycle_inline_completion(
5900 &mut self,
5901 direction: Direction,
5902 window: &mut Window,
5903 cx: &mut Context<Self>,
5904 ) -> Option<()> {
5905 let provider = self.edit_prediction_provider()?;
5906 let cursor = self.selections.newest_anchor().head();
5907 let (buffer, cursor_buffer_position) =
5908 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5909 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5910 return None;
5911 }
5912
5913 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5914 self.update_visible_inline_completion(window, cx);
5915
5916 Some(())
5917 }
5918
5919 pub fn show_inline_completion(
5920 &mut self,
5921 _: &ShowEditPrediction,
5922 window: &mut Window,
5923 cx: &mut Context<Self>,
5924 ) {
5925 if !self.has_active_inline_completion() {
5926 self.refresh_inline_completion(false, true, window, cx);
5927 return;
5928 }
5929
5930 self.update_visible_inline_completion(window, cx);
5931 }
5932
5933 pub fn display_cursor_names(
5934 &mut self,
5935 _: &DisplayCursorNames,
5936 window: &mut Window,
5937 cx: &mut Context<Self>,
5938 ) {
5939 self.show_cursor_names(window, cx);
5940 }
5941
5942 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5943 self.show_cursor_names = true;
5944 cx.notify();
5945 cx.spawn_in(window, async move |this, cx| {
5946 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5947 this.update(cx, |this, cx| {
5948 this.show_cursor_names = false;
5949 cx.notify()
5950 })
5951 .ok()
5952 })
5953 .detach();
5954 }
5955
5956 pub fn next_edit_prediction(
5957 &mut self,
5958 _: &NextEditPrediction,
5959 window: &mut Window,
5960 cx: &mut Context<Self>,
5961 ) {
5962 if self.has_active_inline_completion() {
5963 self.cycle_inline_completion(Direction::Next, window, cx);
5964 } else {
5965 let is_copilot_disabled = self
5966 .refresh_inline_completion(false, true, window, cx)
5967 .is_none();
5968 if is_copilot_disabled {
5969 cx.propagate();
5970 }
5971 }
5972 }
5973
5974 pub fn previous_edit_prediction(
5975 &mut self,
5976 _: &PreviousEditPrediction,
5977 window: &mut Window,
5978 cx: &mut Context<Self>,
5979 ) {
5980 if self.has_active_inline_completion() {
5981 self.cycle_inline_completion(Direction::Prev, window, cx);
5982 } else {
5983 let is_copilot_disabled = self
5984 .refresh_inline_completion(false, true, window, cx)
5985 .is_none();
5986 if is_copilot_disabled {
5987 cx.propagate();
5988 }
5989 }
5990 }
5991
5992 pub fn accept_edit_prediction(
5993 &mut self,
5994 _: &AcceptEditPrediction,
5995 window: &mut Window,
5996 cx: &mut Context<Self>,
5997 ) {
5998 if self.show_edit_predictions_in_menu() {
5999 self.hide_context_menu(window, cx);
6000 }
6001
6002 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6003 return;
6004 };
6005
6006 self.report_inline_completion_event(
6007 active_inline_completion.completion_id.clone(),
6008 true,
6009 cx,
6010 );
6011
6012 match &active_inline_completion.completion {
6013 InlineCompletion::Move { target, .. } => {
6014 let target = *target;
6015
6016 if let Some(position_map) = &self.last_position_map {
6017 if position_map
6018 .visible_row_range
6019 .contains(&target.to_display_point(&position_map.snapshot).row())
6020 || !self.edit_prediction_requires_modifier()
6021 {
6022 self.unfold_ranges(&[target..target], true, false, cx);
6023 // Note that this is also done in vim's handler of the Tab action.
6024 self.change_selections(
6025 Some(Autoscroll::newest()),
6026 window,
6027 cx,
6028 |selections| {
6029 selections.select_anchor_ranges([target..target]);
6030 },
6031 );
6032 self.clear_row_highlights::<EditPredictionPreview>();
6033
6034 self.edit_prediction_preview
6035 .set_previous_scroll_position(None);
6036 } else {
6037 self.edit_prediction_preview
6038 .set_previous_scroll_position(Some(
6039 position_map.snapshot.scroll_anchor,
6040 ));
6041
6042 self.highlight_rows::<EditPredictionPreview>(
6043 target..target,
6044 cx.theme().colors().editor_highlighted_line_background,
6045 RowHighlightOptions {
6046 autoscroll: true,
6047 ..Default::default()
6048 },
6049 cx,
6050 );
6051 self.request_autoscroll(Autoscroll::fit(), cx);
6052 }
6053 }
6054 }
6055 InlineCompletion::Edit { edits, .. } => {
6056 if let Some(provider) = self.edit_prediction_provider() {
6057 provider.accept(cx);
6058 }
6059
6060 let snapshot = self.buffer.read(cx).snapshot(cx);
6061 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6062
6063 self.buffer.update(cx, |buffer, cx| {
6064 buffer.edit(edits.iter().cloned(), None, cx)
6065 });
6066
6067 self.change_selections(None, window, cx, |s| {
6068 s.select_anchor_ranges([last_edit_end..last_edit_end])
6069 });
6070
6071 self.update_visible_inline_completion(window, cx);
6072 if self.active_inline_completion.is_none() {
6073 self.refresh_inline_completion(true, true, window, cx);
6074 }
6075
6076 cx.notify();
6077 }
6078 }
6079
6080 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6081 }
6082
6083 pub fn accept_partial_inline_completion(
6084 &mut self,
6085 _: &AcceptPartialEditPrediction,
6086 window: &mut Window,
6087 cx: &mut Context<Self>,
6088 ) {
6089 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6090 return;
6091 };
6092 if self.selections.count() != 1 {
6093 return;
6094 }
6095
6096 self.report_inline_completion_event(
6097 active_inline_completion.completion_id.clone(),
6098 true,
6099 cx,
6100 );
6101
6102 match &active_inline_completion.completion {
6103 InlineCompletion::Move { target, .. } => {
6104 let target = *target;
6105 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6106 selections.select_anchor_ranges([target..target]);
6107 });
6108 }
6109 InlineCompletion::Edit { edits, .. } => {
6110 // Find an insertion that starts at the cursor position.
6111 let snapshot = self.buffer.read(cx).snapshot(cx);
6112 let cursor_offset = self.selections.newest::<usize>(cx).head();
6113 let insertion = edits.iter().find_map(|(range, text)| {
6114 let range = range.to_offset(&snapshot);
6115 if range.is_empty() && range.start == cursor_offset {
6116 Some(text)
6117 } else {
6118 None
6119 }
6120 });
6121
6122 if let Some(text) = insertion {
6123 let mut partial_completion = text
6124 .chars()
6125 .by_ref()
6126 .take_while(|c| c.is_alphabetic())
6127 .collect::<String>();
6128 if partial_completion.is_empty() {
6129 partial_completion = text
6130 .chars()
6131 .by_ref()
6132 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6133 .collect::<String>();
6134 }
6135
6136 cx.emit(EditorEvent::InputHandled {
6137 utf16_range_to_replace: None,
6138 text: partial_completion.clone().into(),
6139 });
6140
6141 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6142
6143 self.refresh_inline_completion(true, true, window, cx);
6144 cx.notify();
6145 } else {
6146 self.accept_edit_prediction(&Default::default(), window, cx);
6147 }
6148 }
6149 }
6150 }
6151
6152 fn discard_inline_completion(
6153 &mut self,
6154 should_report_inline_completion_event: bool,
6155 cx: &mut Context<Self>,
6156 ) -> bool {
6157 if should_report_inline_completion_event {
6158 let completion_id = self
6159 .active_inline_completion
6160 .as_ref()
6161 .and_then(|active_completion| active_completion.completion_id.clone());
6162
6163 self.report_inline_completion_event(completion_id, false, cx);
6164 }
6165
6166 if let Some(provider) = self.edit_prediction_provider() {
6167 provider.discard(cx);
6168 }
6169
6170 self.take_active_inline_completion(cx)
6171 }
6172
6173 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6174 let Some(provider) = self.edit_prediction_provider() else {
6175 return;
6176 };
6177
6178 let Some((_, buffer, _)) = self
6179 .buffer
6180 .read(cx)
6181 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6182 else {
6183 return;
6184 };
6185
6186 let extension = buffer
6187 .read(cx)
6188 .file()
6189 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6190
6191 let event_type = match accepted {
6192 true => "Edit Prediction Accepted",
6193 false => "Edit Prediction Discarded",
6194 };
6195 telemetry::event!(
6196 event_type,
6197 provider = provider.name(),
6198 prediction_id = id,
6199 suggestion_accepted = accepted,
6200 file_extension = extension,
6201 );
6202 }
6203
6204 pub fn has_active_inline_completion(&self) -> bool {
6205 self.active_inline_completion.is_some()
6206 }
6207
6208 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6209 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6210 return false;
6211 };
6212
6213 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6214 self.clear_highlights::<InlineCompletionHighlight>(cx);
6215 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6216 true
6217 }
6218
6219 /// Returns true when we're displaying the edit prediction popover below the cursor
6220 /// like we are not previewing and the LSP autocomplete menu is visible
6221 /// or we are in `when_holding_modifier` mode.
6222 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6223 if self.edit_prediction_preview_is_active()
6224 || !self.show_edit_predictions_in_menu()
6225 || !self.edit_predictions_enabled()
6226 {
6227 return false;
6228 }
6229
6230 if self.has_visible_completions_menu() {
6231 return true;
6232 }
6233
6234 has_completion && self.edit_prediction_requires_modifier()
6235 }
6236
6237 fn handle_modifiers_changed(
6238 &mut self,
6239 modifiers: Modifiers,
6240 position_map: &PositionMap,
6241 window: &mut Window,
6242 cx: &mut Context<Self>,
6243 ) {
6244 if self.show_edit_predictions_in_menu() {
6245 self.update_edit_prediction_preview(&modifiers, window, cx);
6246 }
6247
6248 self.update_selection_mode(&modifiers, position_map, window, cx);
6249
6250 let mouse_position = window.mouse_position();
6251 if !position_map.text_hitbox.is_hovered(window) {
6252 return;
6253 }
6254
6255 self.update_hovered_link(
6256 position_map.point_for_position(mouse_position),
6257 &position_map.snapshot,
6258 modifiers,
6259 window,
6260 cx,
6261 )
6262 }
6263
6264 fn update_selection_mode(
6265 &mut self,
6266 modifiers: &Modifiers,
6267 position_map: &PositionMap,
6268 window: &mut Window,
6269 cx: &mut Context<Self>,
6270 ) {
6271 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6272 return;
6273 }
6274
6275 let mouse_position = window.mouse_position();
6276 let point_for_position = position_map.point_for_position(mouse_position);
6277 let position = point_for_position.previous_valid;
6278
6279 self.select(
6280 SelectPhase::BeginColumnar {
6281 position,
6282 reset: false,
6283 goal_column: point_for_position.exact_unclipped.column(),
6284 },
6285 window,
6286 cx,
6287 );
6288 }
6289
6290 fn update_edit_prediction_preview(
6291 &mut self,
6292 modifiers: &Modifiers,
6293 window: &mut Window,
6294 cx: &mut Context<Self>,
6295 ) {
6296 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6297 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6298 return;
6299 };
6300
6301 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6302 if matches!(
6303 self.edit_prediction_preview,
6304 EditPredictionPreview::Inactive { .. }
6305 ) {
6306 self.edit_prediction_preview = EditPredictionPreview::Active {
6307 previous_scroll_position: None,
6308 since: Instant::now(),
6309 };
6310
6311 self.update_visible_inline_completion(window, cx);
6312 cx.notify();
6313 }
6314 } else if let EditPredictionPreview::Active {
6315 previous_scroll_position,
6316 since,
6317 } = self.edit_prediction_preview
6318 {
6319 if let (Some(previous_scroll_position), Some(position_map)) =
6320 (previous_scroll_position, self.last_position_map.as_ref())
6321 {
6322 self.set_scroll_position(
6323 previous_scroll_position
6324 .scroll_position(&position_map.snapshot.display_snapshot),
6325 window,
6326 cx,
6327 );
6328 }
6329
6330 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6331 released_too_fast: since.elapsed() < Duration::from_millis(200),
6332 };
6333 self.clear_row_highlights::<EditPredictionPreview>();
6334 self.update_visible_inline_completion(window, cx);
6335 cx.notify();
6336 }
6337 }
6338
6339 fn update_visible_inline_completion(
6340 &mut self,
6341 _window: &mut Window,
6342 cx: &mut Context<Self>,
6343 ) -> Option<()> {
6344 let selection = self.selections.newest_anchor();
6345 let cursor = selection.head();
6346 let multibuffer = self.buffer.read(cx).snapshot(cx);
6347 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6348 let excerpt_id = cursor.excerpt_id;
6349
6350 let show_in_menu = self.show_edit_predictions_in_menu();
6351 let completions_menu_has_precedence = !show_in_menu
6352 && (self.context_menu.borrow().is_some()
6353 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6354
6355 if completions_menu_has_precedence
6356 || !offset_selection.is_empty()
6357 || self
6358 .active_inline_completion
6359 .as_ref()
6360 .map_or(false, |completion| {
6361 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6362 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6363 !invalidation_range.contains(&offset_selection.head())
6364 })
6365 {
6366 self.discard_inline_completion(false, cx);
6367 return None;
6368 }
6369
6370 self.take_active_inline_completion(cx);
6371 let Some(provider) = self.edit_prediction_provider() else {
6372 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6373 return None;
6374 };
6375
6376 let (buffer, cursor_buffer_position) =
6377 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6378
6379 self.edit_prediction_settings =
6380 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6381
6382 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6383
6384 if self.edit_prediction_indent_conflict {
6385 let cursor_point = cursor.to_point(&multibuffer);
6386
6387 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6388
6389 if let Some((_, indent)) = indents.iter().next() {
6390 if indent.len == cursor_point.column {
6391 self.edit_prediction_indent_conflict = false;
6392 }
6393 }
6394 }
6395
6396 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6397 let edits = inline_completion
6398 .edits
6399 .into_iter()
6400 .flat_map(|(range, new_text)| {
6401 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6402 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6403 Some((start..end, new_text))
6404 })
6405 .collect::<Vec<_>>();
6406 if edits.is_empty() {
6407 return None;
6408 }
6409
6410 let first_edit_start = edits.first().unwrap().0.start;
6411 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6412 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6413
6414 let last_edit_end = edits.last().unwrap().0.end;
6415 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6416 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6417
6418 let cursor_row = cursor.to_point(&multibuffer).row;
6419
6420 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6421
6422 let mut inlay_ids = Vec::new();
6423 let invalidation_row_range;
6424 let move_invalidation_row_range = if cursor_row < edit_start_row {
6425 Some(cursor_row..edit_end_row)
6426 } else if cursor_row > edit_end_row {
6427 Some(edit_start_row..cursor_row)
6428 } else {
6429 None
6430 };
6431 let is_move =
6432 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6433 let completion = if is_move {
6434 invalidation_row_range =
6435 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6436 let target = first_edit_start;
6437 InlineCompletion::Move { target, snapshot }
6438 } else {
6439 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6440 && !self.inline_completions_hidden_for_vim_mode;
6441
6442 if show_completions_in_buffer {
6443 if edits
6444 .iter()
6445 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6446 {
6447 let mut inlays = Vec::new();
6448 for (range, new_text) in &edits {
6449 let inlay = Inlay::inline_completion(
6450 post_inc(&mut self.next_inlay_id),
6451 range.start,
6452 new_text.as_str(),
6453 );
6454 inlay_ids.push(inlay.id);
6455 inlays.push(inlay);
6456 }
6457
6458 self.splice_inlays(&[], inlays, cx);
6459 } else {
6460 let background_color = cx.theme().status().deleted_background;
6461 self.highlight_text::<InlineCompletionHighlight>(
6462 edits.iter().map(|(range, _)| range.clone()).collect(),
6463 HighlightStyle {
6464 background_color: Some(background_color),
6465 ..Default::default()
6466 },
6467 cx,
6468 );
6469 }
6470 }
6471
6472 invalidation_row_range = edit_start_row..edit_end_row;
6473
6474 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6475 if provider.show_tab_accept_marker() {
6476 EditDisplayMode::TabAccept
6477 } else {
6478 EditDisplayMode::Inline
6479 }
6480 } else {
6481 EditDisplayMode::DiffPopover
6482 };
6483
6484 InlineCompletion::Edit {
6485 edits,
6486 edit_preview: inline_completion.edit_preview,
6487 display_mode,
6488 snapshot,
6489 }
6490 };
6491
6492 let invalidation_range = multibuffer
6493 .anchor_before(Point::new(invalidation_row_range.start, 0))
6494 ..multibuffer.anchor_after(Point::new(
6495 invalidation_row_range.end,
6496 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6497 ));
6498
6499 self.stale_inline_completion_in_menu = None;
6500 self.active_inline_completion = Some(InlineCompletionState {
6501 inlay_ids,
6502 completion,
6503 completion_id: inline_completion.id,
6504 invalidation_range,
6505 });
6506
6507 cx.notify();
6508
6509 Some(())
6510 }
6511
6512 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6513 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6514 }
6515
6516 fn render_code_actions_indicator(
6517 &self,
6518 _style: &EditorStyle,
6519 row: DisplayRow,
6520 is_active: bool,
6521 breakpoint: Option<&(Anchor, Breakpoint)>,
6522 cx: &mut Context<Self>,
6523 ) -> Option<IconButton> {
6524 let color = Color::Muted;
6525 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6526 let show_tooltip = !self.context_menu_visible();
6527
6528 if self.available_code_actions.is_some() {
6529 Some(
6530 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6531 .shape(ui::IconButtonShape::Square)
6532 .icon_size(IconSize::XSmall)
6533 .icon_color(color)
6534 .toggle_state(is_active)
6535 .when(show_tooltip, |this| {
6536 this.tooltip({
6537 let focus_handle = self.focus_handle.clone();
6538 move |window, cx| {
6539 Tooltip::for_action_in(
6540 "Toggle Code Actions",
6541 &ToggleCodeActions {
6542 deployed_from_indicator: None,
6543 },
6544 &focus_handle,
6545 window,
6546 cx,
6547 )
6548 }
6549 })
6550 })
6551 .on_click(cx.listener(move |editor, _e, window, cx| {
6552 window.focus(&editor.focus_handle(cx));
6553 editor.toggle_code_actions(
6554 &ToggleCodeActions {
6555 deployed_from_indicator: Some(row),
6556 },
6557 window,
6558 cx,
6559 );
6560 }))
6561 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6562 editor.set_breakpoint_context_menu(
6563 row,
6564 position,
6565 event.down.position,
6566 window,
6567 cx,
6568 );
6569 })),
6570 )
6571 } else {
6572 None
6573 }
6574 }
6575
6576 fn clear_tasks(&mut self) {
6577 self.tasks.clear()
6578 }
6579
6580 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6581 if self.tasks.insert(key, value).is_some() {
6582 // This case should hopefully be rare, but just in case...
6583 log::error!(
6584 "multiple different run targets found on a single line, only the last target will be rendered"
6585 )
6586 }
6587 }
6588
6589 /// Get all display points of breakpoints that will be rendered within editor
6590 ///
6591 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6592 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6593 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6594 fn active_breakpoints(
6595 &self,
6596 range: Range<DisplayRow>,
6597 window: &mut Window,
6598 cx: &mut Context<Self>,
6599 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6600 let mut breakpoint_display_points = HashMap::default();
6601
6602 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6603 return breakpoint_display_points;
6604 };
6605
6606 let snapshot = self.snapshot(window, cx);
6607
6608 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6609 let Some(project) = self.project.as_ref() else {
6610 return breakpoint_display_points;
6611 };
6612
6613 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6614 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6615
6616 for (buffer_snapshot, range, excerpt_id) in
6617 multi_buffer_snapshot.range_to_buffer_ranges(range)
6618 {
6619 let Some(buffer) = project.read_with(cx, |this, cx| {
6620 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6621 }) else {
6622 continue;
6623 };
6624 let breakpoints = breakpoint_store.read(cx).breakpoints(
6625 &buffer,
6626 Some(
6627 buffer_snapshot.anchor_before(range.start)
6628 ..buffer_snapshot.anchor_after(range.end),
6629 ),
6630 buffer_snapshot,
6631 cx,
6632 );
6633 for (anchor, breakpoint) in breakpoints {
6634 let multi_buffer_anchor =
6635 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6636 let position = multi_buffer_anchor
6637 .to_point(&multi_buffer_snapshot)
6638 .to_display_point(&snapshot);
6639
6640 breakpoint_display_points
6641 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6642 }
6643 }
6644
6645 breakpoint_display_points
6646 }
6647
6648 fn breakpoint_context_menu(
6649 &self,
6650 anchor: Anchor,
6651 window: &mut Window,
6652 cx: &mut Context<Self>,
6653 ) -> Entity<ui::ContextMenu> {
6654 let weak_editor = cx.weak_entity();
6655 let focus_handle = self.focus_handle(cx);
6656
6657 let row = self
6658 .buffer
6659 .read(cx)
6660 .snapshot(cx)
6661 .summary_for_anchor::<Point>(&anchor)
6662 .row;
6663
6664 let breakpoint = self
6665 .breakpoint_at_row(row, window, cx)
6666 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6667
6668 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6669 "Edit Log Breakpoint"
6670 } else {
6671 "Set Log Breakpoint"
6672 };
6673
6674 let condition_breakpoint_msg = if breakpoint
6675 .as_ref()
6676 .is_some_and(|bp| bp.1.condition.is_some())
6677 {
6678 "Edit Condition Breakpoint"
6679 } else {
6680 "Set Condition Breakpoint"
6681 };
6682
6683 let hit_condition_breakpoint_msg = if breakpoint
6684 .as_ref()
6685 .is_some_and(|bp| bp.1.hit_condition.is_some())
6686 {
6687 "Edit Hit Condition Breakpoint"
6688 } else {
6689 "Set Hit Condition Breakpoint"
6690 };
6691
6692 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6693 "Unset Breakpoint"
6694 } else {
6695 "Set Breakpoint"
6696 };
6697
6698 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6699 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6700
6701 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6702 BreakpointState::Enabled => Some("Disable"),
6703 BreakpointState::Disabled => Some("Enable"),
6704 });
6705
6706 let (anchor, breakpoint) =
6707 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6708
6709 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6710 menu.on_blur_subscription(Subscription::new(|| {}))
6711 .context(focus_handle)
6712 .when(run_to_cursor, |this| {
6713 let weak_editor = weak_editor.clone();
6714 this.entry("Run to cursor", None, move |window, cx| {
6715 weak_editor
6716 .update(cx, |editor, cx| {
6717 editor.change_selections(None, window, cx, |s| {
6718 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6719 });
6720 })
6721 .ok();
6722
6723 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6724 })
6725 .separator()
6726 })
6727 .when_some(toggle_state_msg, |this, msg| {
6728 this.entry(msg, None, {
6729 let weak_editor = weak_editor.clone();
6730 let breakpoint = breakpoint.clone();
6731 move |_window, cx| {
6732 weak_editor
6733 .update(cx, |this, cx| {
6734 this.edit_breakpoint_at_anchor(
6735 anchor,
6736 breakpoint.as_ref().clone(),
6737 BreakpointEditAction::InvertState,
6738 cx,
6739 );
6740 })
6741 .log_err();
6742 }
6743 })
6744 })
6745 .entry(set_breakpoint_msg, None, {
6746 let weak_editor = weak_editor.clone();
6747 let breakpoint = breakpoint.clone();
6748 move |_window, cx| {
6749 weak_editor
6750 .update(cx, |this, cx| {
6751 this.edit_breakpoint_at_anchor(
6752 anchor,
6753 breakpoint.as_ref().clone(),
6754 BreakpointEditAction::Toggle,
6755 cx,
6756 );
6757 })
6758 .log_err();
6759 }
6760 })
6761 .entry(log_breakpoint_msg, None, {
6762 let breakpoint = breakpoint.clone();
6763 let weak_editor = weak_editor.clone();
6764 move |window, cx| {
6765 weak_editor
6766 .update(cx, |this, cx| {
6767 this.add_edit_breakpoint_block(
6768 anchor,
6769 breakpoint.as_ref(),
6770 BreakpointPromptEditAction::Log,
6771 window,
6772 cx,
6773 );
6774 })
6775 .log_err();
6776 }
6777 })
6778 .entry(condition_breakpoint_msg, None, {
6779 let breakpoint = breakpoint.clone();
6780 let weak_editor = weak_editor.clone();
6781 move |window, cx| {
6782 weak_editor
6783 .update(cx, |this, cx| {
6784 this.add_edit_breakpoint_block(
6785 anchor,
6786 breakpoint.as_ref(),
6787 BreakpointPromptEditAction::Condition,
6788 window,
6789 cx,
6790 );
6791 })
6792 .log_err();
6793 }
6794 })
6795 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6796 weak_editor
6797 .update(cx, |this, cx| {
6798 this.add_edit_breakpoint_block(
6799 anchor,
6800 breakpoint.as_ref(),
6801 BreakpointPromptEditAction::HitCondition,
6802 window,
6803 cx,
6804 );
6805 })
6806 .log_err();
6807 })
6808 })
6809 }
6810
6811 fn render_breakpoint(
6812 &self,
6813 position: Anchor,
6814 row: DisplayRow,
6815 breakpoint: &Breakpoint,
6816 cx: &mut Context<Self>,
6817 ) -> IconButton {
6818 let (color, icon) = {
6819 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6820 (false, false) => ui::IconName::DebugBreakpoint,
6821 (true, false) => ui::IconName::DebugLogBreakpoint,
6822 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6823 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6824 };
6825
6826 let color = if self
6827 .gutter_breakpoint_indicator
6828 .0
6829 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6830 {
6831 Color::Hint
6832 } else {
6833 Color::Debugger
6834 };
6835
6836 (color, icon)
6837 };
6838
6839 let breakpoint = Arc::from(breakpoint.clone());
6840
6841 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6842 .icon_size(IconSize::XSmall)
6843 .size(ui::ButtonSize::None)
6844 .icon_color(color)
6845 .style(ButtonStyle::Transparent)
6846 .on_click(cx.listener({
6847 let breakpoint = breakpoint.clone();
6848
6849 move |editor, event: &ClickEvent, window, cx| {
6850 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6851 BreakpointEditAction::InvertState
6852 } else {
6853 BreakpointEditAction::Toggle
6854 };
6855
6856 window.focus(&editor.focus_handle(cx));
6857 editor.edit_breakpoint_at_anchor(
6858 position,
6859 breakpoint.as_ref().clone(),
6860 edit_action,
6861 cx,
6862 );
6863 }
6864 }))
6865 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6866 editor.set_breakpoint_context_menu(
6867 row,
6868 Some(position),
6869 event.down.position,
6870 window,
6871 cx,
6872 );
6873 }))
6874 }
6875
6876 fn build_tasks_context(
6877 project: &Entity<Project>,
6878 buffer: &Entity<Buffer>,
6879 buffer_row: u32,
6880 tasks: &Arc<RunnableTasks>,
6881 cx: &mut Context<Self>,
6882 ) -> Task<Option<task::TaskContext>> {
6883 let position = Point::new(buffer_row, tasks.column);
6884 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6885 let location = Location {
6886 buffer: buffer.clone(),
6887 range: range_start..range_start,
6888 };
6889 // Fill in the environmental variables from the tree-sitter captures
6890 let mut captured_task_variables = TaskVariables::default();
6891 for (capture_name, value) in tasks.extra_variables.clone() {
6892 captured_task_variables.insert(
6893 task::VariableName::Custom(capture_name.into()),
6894 value.clone(),
6895 );
6896 }
6897 project.update(cx, |project, cx| {
6898 project.task_store().update(cx, |task_store, cx| {
6899 task_store.task_context_for_location(captured_task_variables, location, cx)
6900 })
6901 })
6902 }
6903
6904 pub fn spawn_nearest_task(
6905 &mut self,
6906 action: &SpawnNearestTask,
6907 window: &mut Window,
6908 cx: &mut Context<Self>,
6909 ) {
6910 let Some((workspace, _)) = self.workspace.clone() else {
6911 return;
6912 };
6913 let Some(project) = self.project.clone() else {
6914 return;
6915 };
6916
6917 // Try to find a closest, enclosing node using tree-sitter that has a
6918 // task
6919 let Some((buffer, buffer_row, tasks)) = self
6920 .find_enclosing_node_task(cx)
6921 // Or find the task that's closest in row-distance.
6922 .or_else(|| self.find_closest_task(cx))
6923 else {
6924 return;
6925 };
6926
6927 let reveal_strategy = action.reveal;
6928 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6929 cx.spawn_in(window, async move |_, cx| {
6930 let context = task_context.await?;
6931 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6932
6933 let resolved = resolved_task.resolved.as_mut()?;
6934 resolved.reveal = reveal_strategy;
6935
6936 workspace
6937 .update_in(cx, |workspace, window, cx| {
6938 workspace.schedule_resolved_task(
6939 task_source_kind,
6940 resolved_task,
6941 false,
6942 window,
6943 cx,
6944 );
6945 })
6946 .ok()
6947 })
6948 .detach();
6949 }
6950
6951 fn find_closest_task(
6952 &mut self,
6953 cx: &mut Context<Self>,
6954 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6955 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6956
6957 let ((buffer_id, row), tasks) = self
6958 .tasks
6959 .iter()
6960 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6961
6962 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6963 let tasks = Arc::new(tasks.to_owned());
6964 Some((buffer, *row, tasks))
6965 }
6966
6967 fn find_enclosing_node_task(
6968 &mut self,
6969 cx: &mut Context<Self>,
6970 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6971 let snapshot = self.buffer.read(cx).snapshot(cx);
6972 let offset = self.selections.newest::<usize>(cx).head();
6973 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6974 let buffer_id = excerpt.buffer().remote_id();
6975
6976 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6977 let mut cursor = layer.node().walk();
6978
6979 while cursor.goto_first_child_for_byte(offset).is_some() {
6980 if cursor.node().end_byte() == offset {
6981 cursor.goto_next_sibling();
6982 }
6983 }
6984
6985 // Ascend to the smallest ancestor that contains the range and has a task.
6986 loop {
6987 let node = cursor.node();
6988 let node_range = node.byte_range();
6989 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6990
6991 // Check if this node contains our offset
6992 if node_range.start <= offset && node_range.end >= offset {
6993 // If it contains offset, check for task
6994 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6995 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6996 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6997 }
6998 }
6999
7000 if !cursor.goto_parent() {
7001 break;
7002 }
7003 }
7004 None
7005 }
7006
7007 fn render_run_indicator(
7008 &self,
7009 _style: &EditorStyle,
7010 is_active: bool,
7011 row: DisplayRow,
7012 breakpoint: Option<(Anchor, Breakpoint)>,
7013 cx: &mut Context<Self>,
7014 ) -> IconButton {
7015 let color = Color::Muted;
7016 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7017
7018 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7019 .shape(ui::IconButtonShape::Square)
7020 .icon_size(IconSize::XSmall)
7021 .icon_color(color)
7022 .toggle_state(is_active)
7023 .on_click(cx.listener(move |editor, _e, window, cx| {
7024 window.focus(&editor.focus_handle(cx));
7025 editor.toggle_code_actions(
7026 &ToggleCodeActions {
7027 deployed_from_indicator: Some(row),
7028 },
7029 window,
7030 cx,
7031 );
7032 }))
7033 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7034 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7035 }))
7036 }
7037
7038 pub fn context_menu_visible(&self) -> bool {
7039 !self.edit_prediction_preview_is_active()
7040 && self
7041 .context_menu
7042 .borrow()
7043 .as_ref()
7044 .map_or(false, |menu| menu.visible())
7045 }
7046
7047 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7048 self.context_menu
7049 .borrow()
7050 .as_ref()
7051 .map(|menu| menu.origin())
7052 }
7053
7054 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7055 self.context_menu_options = Some(options);
7056 }
7057
7058 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7059 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7060
7061 fn render_edit_prediction_popover(
7062 &mut self,
7063 text_bounds: &Bounds<Pixels>,
7064 content_origin: gpui::Point<Pixels>,
7065 editor_snapshot: &EditorSnapshot,
7066 visible_row_range: Range<DisplayRow>,
7067 scroll_top: f32,
7068 scroll_bottom: f32,
7069 line_layouts: &[LineWithInvisibles],
7070 line_height: Pixels,
7071 scroll_pixel_position: gpui::Point<Pixels>,
7072 newest_selection_head: Option<DisplayPoint>,
7073 editor_width: Pixels,
7074 style: &EditorStyle,
7075 window: &mut Window,
7076 cx: &mut App,
7077 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7078 let active_inline_completion = self.active_inline_completion.as_ref()?;
7079
7080 if self.edit_prediction_visible_in_cursor_popover(true) {
7081 return None;
7082 }
7083
7084 match &active_inline_completion.completion {
7085 InlineCompletion::Move { target, .. } => {
7086 let target_display_point = target.to_display_point(editor_snapshot);
7087
7088 if self.edit_prediction_requires_modifier() {
7089 if !self.edit_prediction_preview_is_active() {
7090 return None;
7091 }
7092
7093 self.render_edit_prediction_modifier_jump_popover(
7094 text_bounds,
7095 content_origin,
7096 visible_row_range,
7097 line_layouts,
7098 line_height,
7099 scroll_pixel_position,
7100 newest_selection_head,
7101 target_display_point,
7102 window,
7103 cx,
7104 )
7105 } else {
7106 self.render_edit_prediction_eager_jump_popover(
7107 text_bounds,
7108 content_origin,
7109 editor_snapshot,
7110 visible_row_range,
7111 scroll_top,
7112 scroll_bottom,
7113 line_height,
7114 scroll_pixel_position,
7115 target_display_point,
7116 editor_width,
7117 window,
7118 cx,
7119 )
7120 }
7121 }
7122 InlineCompletion::Edit {
7123 display_mode: EditDisplayMode::Inline,
7124 ..
7125 } => None,
7126 InlineCompletion::Edit {
7127 display_mode: EditDisplayMode::TabAccept,
7128 edits,
7129 ..
7130 } => {
7131 let range = &edits.first()?.0;
7132 let target_display_point = range.end.to_display_point(editor_snapshot);
7133
7134 self.render_edit_prediction_end_of_line_popover(
7135 "Accept",
7136 editor_snapshot,
7137 visible_row_range,
7138 target_display_point,
7139 line_height,
7140 scroll_pixel_position,
7141 content_origin,
7142 editor_width,
7143 window,
7144 cx,
7145 )
7146 }
7147 InlineCompletion::Edit {
7148 edits,
7149 edit_preview,
7150 display_mode: EditDisplayMode::DiffPopover,
7151 snapshot,
7152 } => self.render_edit_prediction_diff_popover(
7153 text_bounds,
7154 content_origin,
7155 editor_snapshot,
7156 visible_row_range,
7157 line_layouts,
7158 line_height,
7159 scroll_pixel_position,
7160 newest_selection_head,
7161 editor_width,
7162 style,
7163 edits,
7164 edit_preview,
7165 snapshot,
7166 window,
7167 cx,
7168 ),
7169 }
7170 }
7171
7172 fn render_edit_prediction_modifier_jump_popover(
7173 &mut self,
7174 text_bounds: &Bounds<Pixels>,
7175 content_origin: gpui::Point<Pixels>,
7176 visible_row_range: Range<DisplayRow>,
7177 line_layouts: &[LineWithInvisibles],
7178 line_height: Pixels,
7179 scroll_pixel_position: gpui::Point<Pixels>,
7180 newest_selection_head: Option<DisplayPoint>,
7181 target_display_point: DisplayPoint,
7182 window: &mut Window,
7183 cx: &mut App,
7184 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7185 let scrolled_content_origin =
7186 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7187
7188 const SCROLL_PADDING_Y: Pixels = px(12.);
7189
7190 if target_display_point.row() < visible_row_range.start {
7191 return self.render_edit_prediction_scroll_popover(
7192 |_| SCROLL_PADDING_Y,
7193 IconName::ArrowUp,
7194 visible_row_range,
7195 line_layouts,
7196 newest_selection_head,
7197 scrolled_content_origin,
7198 window,
7199 cx,
7200 );
7201 } else if target_display_point.row() >= visible_row_range.end {
7202 return self.render_edit_prediction_scroll_popover(
7203 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7204 IconName::ArrowDown,
7205 visible_row_range,
7206 line_layouts,
7207 newest_selection_head,
7208 scrolled_content_origin,
7209 window,
7210 cx,
7211 );
7212 }
7213
7214 const POLE_WIDTH: Pixels = px(2.);
7215
7216 let line_layout =
7217 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7218 let target_column = target_display_point.column() as usize;
7219
7220 let target_x = line_layout.x_for_index(target_column);
7221 let target_y =
7222 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7223
7224 let flag_on_right = target_x < text_bounds.size.width / 2.;
7225
7226 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7227 border_color.l += 0.001;
7228
7229 let mut element = v_flex()
7230 .items_end()
7231 .when(flag_on_right, |el| el.items_start())
7232 .child(if flag_on_right {
7233 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7234 .rounded_bl(px(0.))
7235 .rounded_tl(px(0.))
7236 .border_l_2()
7237 .border_color(border_color)
7238 } else {
7239 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7240 .rounded_br(px(0.))
7241 .rounded_tr(px(0.))
7242 .border_r_2()
7243 .border_color(border_color)
7244 })
7245 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7246 .into_any();
7247
7248 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7249
7250 let mut origin = scrolled_content_origin + point(target_x, target_y)
7251 - point(
7252 if flag_on_right {
7253 POLE_WIDTH
7254 } else {
7255 size.width - POLE_WIDTH
7256 },
7257 size.height - line_height,
7258 );
7259
7260 origin.x = origin.x.max(content_origin.x);
7261
7262 element.prepaint_at(origin, window, cx);
7263
7264 Some((element, origin))
7265 }
7266
7267 fn render_edit_prediction_scroll_popover(
7268 &mut self,
7269 to_y: impl Fn(Size<Pixels>) -> Pixels,
7270 scroll_icon: IconName,
7271 visible_row_range: Range<DisplayRow>,
7272 line_layouts: &[LineWithInvisibles],
7273 newest_selection_head: Option<DisplayPoint>,
7274 scrolled_content_origin: gpui::Point<Pixels>,
7275 window: &mut Window,
7276 cx: &mut App,
7277 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7278 let mut element = self
7279 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7280 .into_any();
7281
7282 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7283
7284 let cursor = newest_selection_head?;
7285 let cursor_row_layout =
7286 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7287 let cursor_column = cursor.column() as usize;
7288
7289 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7290
7291 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7292
7293 element.prepaint_at(origin, window, cx);
7294 Some((element, origin))
7295 }
7296
7297 fn render_edit_prediction_eager_jump_popover(
7298 &mut self,
7299 text_bounds: &Bounds<Pixels>,
7300 content_origin: gpui::Point<Pixels>,
7301 editor_snapshot: &EditorSnapshot,
7302 visible_row_range: Range<DisplayRow>,
7303 scroll_top: f32,
7304 scroll_bottom: f32,
7305 line_height: Pixels,
7306 scroll_pixel_position: gpui::Point<Pixels>,
7307 target_display_point: DisplayPoint,
7308 editor_width: Pixels,
7309 window: &mut Window,
7310 cx: &mut App,
7311 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7312 if target_display_point.row().as_f32() < scroll_top {
7313 let mut element = self
7314 .render_edit_prediction_line_popover(
7315 "Jump to Edit",
7316 Some(IconName::ArrowUp),
7317 window,
7318 cx,
7319 )?
7320 .into_any();
7321
7322 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7323 let offset = point(
7324 (text_bounds.size.width - size.width) / 2.,
7325 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7326 );
7327
7328 let origin = text_bounds.origin + offset;
7329 element.prepaint_at(origin, window, cx);
7330 Some((element, origin))
7331 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7332 let mut element = self
7333 .render_edit_prediction_line_popover(
7334 "Jump to Edit",
7335 Some(IconName::ArrowDown),
7336 window,
7337 cx,
7338 )?
7339 .into_any();
7340
7341 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7342 let offset = point(
7343 (text_bounds.size.width - size.width) / 2.,
7344 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7345 );
7346
7347 let origin = text_bounds.origin + offset;
7348 element.prepaint_at(origin, window, cx);
7349 Some((element, origin))
7350 } else {
7351 self.render_edit_prediction_end_of_line_popover(
7352 "Jump to Edit",
7353 editor_snapshot,
7354 visible_row_range,
7355 target_display_point,
7356 line_height,
7357 scroll_pixel_position,
7358 content_origin,
7359 editor_width,
7360 window,
7361 cx,
7362 )
7363 }
7364 }
7365
7366 fn render_edit_prediction_end_of_line_popover(
7367 self: &mut Editor,
7368 label: &'static str,
7369 editor_snapshot: &EditorSnapshot,
7370 visible_row_range: Range<DisplayRow>,
7371 target_display_point: DisplayPoint,
7372 line_height: Pixels,
7373 scroll_pixel_position: gpui::Point<Pixels>,
7374 content_origin: gpui::Point<Pixels>,
7375 editor_width: Pixels,
7376 window: &mut Window,
7377 cx: &mut App,
7378 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7379 let target_line_end = DisplayPoint::new(
7380 target_display_point.row(),
7381 editor_snapshot.line_len(target_display_point.row()),
7382 );
7383
7384 let mut element = self
7385 .render_edit_prediction_line_popover(label, None, window, cx)?
7386 .into_any();
7387
7388 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7389
7390 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7391
7392 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7393 let mut origin = start_point
7394 + line_origin
7395 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7396 origin.x = origin.x.max(content_origin.x);
7397
7398 let max_x = content_origin.x + editor_width - size.width;
7399
7400 if origin.x > max_x {
7401 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7402
7403 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7404 origin.y += offset;
7405 IconName::ArrowUp
7406 } else {
7407 origin.y -= offset;
7408 IconName::ArrowDown
7409 };
7410
7411 element = self
7412 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7413 .into_any();
7414
7415 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7416
7417 origin.x = content_origin.x + editor_width - size.width - px(2.);
7418 }
7419
7420 element.prepaint_at(origin, window, cx);
7421 Some((element, origin))
7422 }
7423
7424 fn render_edit_prediction_diff_popover(
7425 self: &Editor,
7426 text_bounds: &Bounds<Pixels>,
7427 content_origin: gpui::Point<Pixels>,
7428 editor_snapshot: &EditorSnapshot,
7429 visible_row_range: Range<DisplayRow>,
7430 line_layouts: &[LineWithInvisibles],
7431 line_height: Pixels,
7432 scroll_pixel_position: gpui::Point<Pixels>,
7433 newest_selection_head: Option<DisplayPoint>,
7434 editor_width: Pixels,
7435 style: &EditorStyle,
7436 edits: &Vec<(Range<Anchor>, String)>,
7437 edit_preview: &Option<language::EditPreview>,
7438 snapshot: &language::BufferSnapshot,
7439 window: &mut Window,
7440 cx: &mut App,
7441 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7442 let edit_start = edits
7443 .first()
7444 .unwrap()
7445 .0
7446 .start
7447 .to_display_point(editor_snapshot);
7448 let edit_end = edits
7449 .last()
7450 .unwrap()
7451 .0
7452 .end
7453 .to_display_point(editor_snapshot);
7454
7455 let is_visible = visible_row_range.contains(&edit_start.row())
7456 || visible_row_range.contains(&edit_end.row());
7457 if !is_visible {
7458 return None;
7459 }
7460
7461 let highlighted_edits =
7462 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7463
7464 let styled_text = highlighted_edits.to_styled_text(&style.text);
7465 let line_count = highlighted_edits.text.lines().count();
7466
7467 const BORDER_WIDTH: Pixels = px(1.);
7468
7469 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7470 let has_keybind = keybind.is_some();
7471
7472 let mut element = h_flex()
7473 .items_start()
7474 .child(
7475 h_flex()
7476 .bg(cx.theme().colors().editor_background)
7477 .border(BORDER_WIDTH)
7478 .shadow_sm()
7479 .border_color(cx.theme().colors().border)
7480 .rounded_l_lg()
7481 .when(line_count > 1, |el| el.rounded_br_lg())
7482 .pr_1()
7483 .child(styled_text),
7484 )
7485 .child(
7486 h_flex()
7487 .h(line_height + BORDER_WIDTH * 2.)
7488 .px_1p5()
7489 .gap_1()
7490 // Workaround: For some reason, there's a gap if we don't do this
7491 .ml(-BORDER_WIDTH)
7492 .shadow(smallvec![gpui::BoxShadow {
7493 color: gpui::black().opacity(0.05),
7494 offset: point(px(1.), px(1.)),
7495 blur_radius: px(2.),
7496 spread_radius: px(0.),
7497 }])
7498 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7499 .border(BORDER_WIDTH)
7500 .border_color(cx.theme().colors().border)
7501 .rounded_r_lg()
7502 .id("edit_prediction_diff_popover_keybind")
7503 .when(!has_keybind, |el| {
7504 let status_colors = cx.theme().status();
7505
7506 el.bg(status_colors.error_background)
7507 .border_color(status_colors.error.opacity(0.6))
7508 .child(Icon::new(IconName::Info).color(Color::Error))
7509 .cursor_default()
7510 .hoverable_tooltip(move |_window, cx| {
7511 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7512 })
7513 })
7514 .children(keybind),
7515 )
7516 .into_any();
7517
7518 let longest_row =
7519 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7520 let longest_line_width = if visible_row_range.contains(&longest_row) {
7521 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7522 } else {
7523 layout_line(
7524 longest_row,
7525 editor_snapshot,
7526 style,
7527 editor_width,
7528 |_| false,
7529 window,
7530 cx,
7531 )
7532 .width
7533 };
7534
7535 let viewport_bounds =
7536 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7537 right: -EditorElement::SCROLLBAR_WIDTH,
7538 ..Default::default()
7539 });
7540
7541 let x_after_longest =
7542 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7543 - scroll_pixel_position.x;
7544
7545 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7546
7547 // Fully visible if it can be displayed within the window (allow overlapping other
7548 // panes). However, this is only allowed if the popover starts within text_bounds.
7549 let can_position_to_the_right = x_after_longest < text_bounds.right()
7550 && x_after_longest + element_bounds.width < viewport_bounds.right();
7551
7552 let mut origin = if can_position_to_the_right {
7553 point(
7554 x_after_longest,
7555 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7556 - scroll_pixel_position.y,
7557 )
7558 } else {
7559 let cursor_row = newest_selection_head.map(|head| head.row());
7560 let above_edit = edit_start
7561 .row()
7562 .0
7563 .checked_sub(line_count as u32)
7564 .map(DisplayRow);
7565 let below_edit = Some(edit_end.row() + 1);
7566 let above_cursor =
7567 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7568 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7569
7570 // Place the edit popover adjacent to the edit if there is a location
7571 // available that is onscreen and does not obscure the cursor. Otherwise,
7572 // place it adjacent to the cursor.
7573 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7574 .into_iter()
7575 .flatten()
7576 .find(|&start_row| {
7577 let end_row = start_row + line_count as u32;
7578 visible_row_range.contains(&start_row)
7579 && visible_row_range.contains(&end_row)
7580 && cursor_row.map_or(true, |cursor_row| {
7581 !((start_row..end_row).contains(&cursor_row))
7582 })
7583 })?;
7584
7585 content_origin
7586 + point(
7587 -scroll_pixel_position.x,
7588 row_target.as_f32() * line_height - scroll_pixel_position.y,
7589 )
7590 };
7591
7592 origin.x -= BORDER_WIDTH;
7593
7594 window.defer_draw(element, origin, 1);
7595
7596 // Do not return an element, since it will already be drawn due to defer_draw.
7597 None
7598 }
7599
7600 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7601 px(30.)
7602 }
7603
7604 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7605 if self.read_only(cx) {
7606 cx.theme().players().read_only()
7607 } else {
7608 self.style.as_ref().unwrap().local_player
7609 }
7610 }
7611
7612 fn render_edit_prediction_accept_keybind(
7613 &self,
7614 window: &mut Window,
7615 cx: &App,
7616 ) -> Option<AnyElement> {
7617 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7618 let accept_keystroke = accept_binding.keystroke()?;
7619
7620 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7621
7622 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7623 Color::Accent
7624 } else {
7625 Color::Muted
7626 };
7627
7628 h_flex()
7629 .px_0p5()
7630 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7631 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7632 .text_size(TextSize::XSmall.rems(cx))
7633 .child(h_flex().children(ui::render_modifiers(
7634 &accept_keystroke.modifiers,
7635 PlatformStyle::platform(),
7636 Some(modifiers_color),
7637 Some(IconSize::XSmall.rems().into()),
7638 true,
7639 )))
7640 .when(is_platform_style_mac, |parent| {
7641 parent.child(accept_keystroke.key.clone())
7642 })
7643 .when(!is_platform_style_mac, |parent| {
7644 parent.child(
7645 Key::new(
7646 util::capitalize(&accept_keystroke.key),
7647 Some(Color::Default),
7648 )
7649 .size(Some(IconSize::XSmall.rems().into())),
7650 )
7651 })
7652 .into_any()
7653 .into()
7654 }
7655
7656 fn render_edit_prediction_line_popover(
7657 &self,
7658 label: impl Into<SharedString>,
7659 icon: Option<IconName>,
7660 window: &mut Window,
7661 cx: &App,
7662 ) -> Option<Stateful<Div>> {
7663 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7664
7665 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7666 let has_keybind = keybind.is_some();
7667
7668 let result = h_flex()
7669 .id("ep-line-popover")
7670 .py_0p5()
7671 .pl_1()
7672 .pr(padding_right)
7673 .gap_1()
7674 .rounded_md()
7675 .border_1()
7676 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7677 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7678 .shadow_sm()
7679 .when(!has_keybind, |el| {
7680 let status_colors = cx.theme().status();
7681
7682 el.bg(status_colors.error_background)
7683 .border_color(status_colors.error.opacity(0.6))
7684 .pl_2()
7685 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7686 .cursor_default()
7687 .hoverable_tooltip(move |_window, cx| {
7688 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7689 })
7690 })
7691 .children(keybind)
7692 .child(
7693 Label::new(label)
7694 .size(LabelSize::Small)
7695 .when(!has_keybind, |el| {
7696 el.color(cx.theme().status().error.into()).strikethrough()
7697 }),
7698 )
7699 .when(!has_keybind, |el| {
7700 el.child(
7701 h_flex().ml_1().child(
7702 Icon::new(IconName::Info)
7703 .size(IconSize::Small)
7704 .color(cx.theme().status().error.into()),
7705 ),
7706 )
7707 })
7708 .when_some(icon, |element, icon| {
7709 element.child(
7710 div()
7711 .mt(px(1.5))
7712 .child(Icon::new(icon).size(IconSize::Small)),
7713 )
7714 });
7715
7716 Some(result)
7717 }
7718
7719 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7720 let accent_color = cx.theme().colors().text_accent;
7721 let editor_bg_color = cx.theme().colors().editor_background;
7722 editor_bg_color.blend(accent_color.opacity(0.1))
7723 }
7724
7725 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7726 let accent_color = cx.theme().colors().text_accent;
7727 let editor_bg_color = cx.theme().colors().editor_background;
7728 editor_bg_color.blend(accent_color.opacity(0.6))
7729 }
7730
7731 fn render_edit_prediction_cursor_popover(
7732 &self,
7733 min_width: Pixels,
7734 max_width: Pixels,
7735 cursor_point: Point,
7736 style: &EditorStyle,
7737 accept_keystroke: Option<&gpui::Keystroke>,
7738 _window: &Window,
7739 cx: &mut Context<Editor>,
7740 ) -> Option<AnyElement> {
7741 let provider = self.edit_prediction_provider.as_ref()?;
7742
7743 if provider.provider.needs_terms_acceptance(cx) {
7744 return Some(
7745 h_flex()
7746 .min_w(min_width)
7747 .flex_1()
7748 .px_2()
7749 .py_1()
7750 .gap_3()
7751 .elevation_2(cx)
7752 .hover(|style| style.bg(cx.theme().colors().element_hover))
7753 .id("accept-terms")
7754 .cursor_pointer()
7755 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7756 .on_click(cx.listener(|this, _event, window, cx| {
7757 cx.stop_propagation();
7758 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7759 window.dispatch_action(
7760 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7761 cx,
7762 );
7763 }))
7764 .child(
7765 h_flex()
7766 .flex_1()
7767 .gap_2()
7768 .child(Icon::new(IconName::ZedPredict))
7769 .child(Label::new("Accept Terms of Service"))
7770 .child(div().w_full())
7771 .child(
7772 Icon::new(IconName::ArrowUpRight)
7773 .color(Color::Muted)
7774 .size(IconSize::Small),
7775 )
7776 .into_any_element(),
7777 )
7778 .into_any(),
7779 );
7780 }
7781
7782 let is_refreshing = provider.provider.is_refreshing(cx);
7783
7784 fn pending_completion_container() -> Div {
7785 h_flex()
7786 .h_full()
7787 .flex_1()
7788 .gap_2()
7789 .child(Icon::new(IconName::ZedPredict))
7790 }
7791
7792 let completion = match &self.active_inline_completion {
7793 Some(prediction) => {
7794 if !self.has_visible_completions_menu() {
7795 const RADIUS: Pixels = px(6.);
7796 const BORDER_WIDTH: Pixels = px(1.);
7797
7798 return Some(
7799 h_flex()
7800 .elevation_2(cx)
7801 .border(BORDER_WIDTH)
7802 .border_color(cx.theme().colors().border)
7803 .when(accept_keystroke.is_none(), |el| {
7804 el.border_color(cx.theme().status().error)
7805 })
7806 .rounded(RADIUS)
7807 .rounded_tl(px(0.))
7808 .overflow_hidden()
7809 .child(div().px_1p5().child(match &prediction.completion {
7810 InlineCompletion::Move { target, snapshot } => {
7811 use text::ToPoint as _;
7812 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7813 {
7814 Icon::new(IconName::ZedPredictDown)
7815 } else {
7816 Icon::new(IconName::ZedPredictUp)
7817 }
7818 }
7819 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7820 }))
7821 .child(
7822 h_flex()
7823 .gap_1()
7824 .py_1()
7825 .px_2()
7826 .rounded_r(RADIUS - BORDER_WIDTH)
7827 .border_l_1()
7828 .border_color(cx.theme().colors().border)
7829 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7830 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7831 el.child(
7832 Label::new("Hold")
7833 .size(LabelSize::Small)
7834 .when(accept_keystroke.is_none(), |el| {
7835 el.strikethrough()
7836 })
7837 .line_height_style(LineHeightStyle::UiLabel),
7838 )
7839 })
7840 .id("edit_prediction_cursor_popover_keybind")
7841 .when(accept_keystroke.is_none(), |el| {
7842 let status_colors = cx.theme().status();
7843
7844 el.bg(status_colors.error_background)
7845 .border_color(status_colors.error.opacity(0.6))
7846 .child(Icon::new(IconName::Info).color(Color::Error))
7847 .cursor_default()
7848 .hoverable_tooltip(move |_window, cx| {
7849 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7850 .into()
7851 })
7852 })
7853 .when_some(
7854 accept_keystroke.as_ref(),
7855 |el, accept_keystroke| {
7856 el.child(h_flex().children(ui::render_modifiers(
7857 &accept_keystroke.modifiers,
7858 PlatformStyle::platform(),
7859 Some(Color::Default),
7860 Some(IconSize::XSmall.rems().into()),
7861 false,
7862 )))
7863 },
7864 ),
7865 )
7866 .into_any(),
7867 );
7868 }
7869
7870 self.render_edit_prediction_cursor_popover_preview(
7871 prediction,
7872 cursor_point,
7873 style,
7874 cx,
7875 )?
7876 }
7877
7878 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7879 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7880 stale_completion,
7881 cursor_point,
7882 style,
7883 cx,
7884 )?,
7885
7886 None => {
7887 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7888 }
7889 },
7890
7891 None => pending_completion_container().child(Label::new("No Prediction")),
7892 };
7893
7894 let completion = if is_refreshing {
7895 completion
7896 .with_animation(
7897 "loading-completion",
7898 Animation::new(Duration::from_secs(2))
7899 .repeat()
7900 .with_easing(pulsating_between(0.4, 0.8)),
7901 |label, delta| label.opacity(delta),
7902 )
7903 .into_any_element()
7904 } else {
7905 completion.into_any_element()
7906 };
7907
7908 let has_completion = self.active_inline_completion.is_some();
7909
7910 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7911 Some(
7912 h_flex()
7913 .min_w(min_width)
7914 .max_w(max_width)
7915 .flex_1()
7916 .elevation_2(cx)
7917 .border_color(cx.theme().colors().border)
7918 .child(
7919 div()
7920 .flex_1()
7921 .py_1()
7922 .px_2()
7923 .overflow_hidden()
7924 .child(completion),
7925 )
7926 .when_some(accept_keystroke, |el, accept_keystroke| {
7927 if !accept_keystroke.modifiers.modified() {
7928 return el;
7929 }
7930
7931 el.child(
7932 h_flex()
7933 .h_full()
7934 .border_l_1()
7935 .rounded_r_lg()
7936 .border_color(cx.theme().colors().border)
7937 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7938 .gap_1()
7939 .py_1()
7940 .px_2()
7941 .child(
7942 h_flex()
7943 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7944 .when(is_platform_style_mac, |parent| parent.gap_1())
7945 .child(h_flex().children(ui::render_modifiers(
7946 &accept_keystroke.modifiers,
7947 PlatformStyle::platform(),
7948 Some(if !has_completion {
7949 Color::Muted
7950 } else {
7951 Color::Default
7952 }),
7953 None,
7954 false,
7955 ))),
7956 )
7957 .child(Label::new("Preview").into_any_element())
7958 .opacity(if has_completion { 1.0 } else { 0.4 }),
7959 )
7960 })
7961 .into_any(),
7962 )
7963 }
7964
7965 fn render_edit_prediction_cursor_popover_preview(
7966 &self,
7967 completion: &InlineCompletionState,
7968 cursor_point: Point,
7969 style: &EditorStyle,
7970 cx: &mut Context<Editor>,
7971 ) -> Option<Div> {
7972 use text::ToPoint as _;
7973
7974 fn render_relative_row_jump(
7975 prefix: impl Into<String>,
7976 current_row: u32,
7977 target_row: u32,
7978 ) -> Div {
7979 let (row_diff, arrow) = if target_row < current_row {
7980 (current_row - target_row, IconName::ArrowUp)
7981 } else {
7982 (target_row - current_row, IconName::ArrowDown)
7983 };
7984
7985 h_flex()
7986 .child(
7987 Label::new(format!("{}{}", prefix.into(), row_diff))
7988 .color(Color::Muted)
7989 .size(LabelSize::Small),
7990 )
7991 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7992 }
7993
7994 match &completion.completion {
7995 InlineCompletion::Move {
7996 target, snapshot, ..
7997 } => Some(
7998 h_flex()
7999 .px_2()
8000 .gap_2()
8001 .flex_1()
8002 .child(
8003 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8004 Icon::new(IconName::ZedPredictDown)
8005 } else {
8006 Icon::new(IconName::ZedPredictUp)
8007 },
8008 )
8009 .child(Label::new("Jump to Edit")),
8010 ),
8011
8012 InlineCompletion::Edit {
8013 edits,
8014 edit_preview,
8015 snapshot,
8016 display_mode: _,
8017 } => {
8018 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8019
8020 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8021 &snapshot,
8022 &edits,
8023 edit_preview.as_ref()?,
8024 true,
8025 cx,
8026 )
8027 .first_line_preview();
8028
8029 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8030 .with_default_highlights(&style.text, highlighted_edits.highlights);
8031
8032 let preview = h_flex()
8033 .gap_1()
8034 .min_w_16()
8035 .child(styled_text)
8036 .when(has_more_lines, |parent| parent.child("…"));
8037
8038 let left = if first_edit_row != cursor_point.row {
8039 render_relative_row_jump("", cursor_point.row, first_edit_row)
8040 .into_any_element()
8041 } else {
8042 Icon::new(IconName::ZedPredict).into_any_element()
8043 };
8044
8045 Some(
8046 h_flex()
8047 .h_full()
8048 .flex_1()
8049 .gap_2()
8050 .pr_1()
8051 .overflow_x_hidden()
8052 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8053 .child(left)
8054 .child(preview),
8055 )
8056 }
8057 }
8058 }
8059
8060 fn render_context_menu(
8061 &self,
8062 style: &EditorStyle,
8063 max_height_in_lines: u32,
8064 window: &mut Window,
8065 cx: &mut Context<Editor>,
8066 ) -> Option<AnyElement> {
8067 let menu = self.context_menu.borrow();
8068 let menu = menu.as_ref()?;
8069 if !menu.visible() {
8070 return None;
8071 };
8072 Some(menu.render(style, max_height_in_lines, window, cx))
8073 }
8074
8075 fn render_context_menu_aside(
8076 &mut self,
8077 max_size: Size<Pixels>,
8078 window: &mut Window,
8079 cx: &mut Context<Editor>,
8080 ) -> Option<AnyElement> {
8081 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8082 if menu.visible() {
8083 menu.render_aside(self, max_size, window, cx)
8084 } else {
8085 None
8086 }
8087 })
8088 }
8089
8090 fn hide_context_menu(
8091 &mut self,
8092 window: &mut Window,
8093 cx: &mut Context<Self>,
8094 ) -> Option<CodeContextMenu> {
8095 cx.notify();
8096 self.completion_tasks.clear();
8097 let context_menu = self.context_menu.borrow_mut().take();
8098 self.stale_inline_completion_in_menu.take();
8099 self.update_visible_inline_completion(window, cx);
8100 context_menu
8101 }
8102
8103 fn show_snippet_choices(
8104 &mut self,
8105 choices: &Vec<String>,
8106 selection: Range<Anchor>,
8107 cx: &mut Context<Self>,
8108 ) {
8109 if selection.start.buffer_id.is_none() {
8110 return;
8111 }
8112 let buffer_id = selection.start.buffer_id.unwrap();
8113 let buffer = self.buffer().read(cx).buffer(buffer_id);
8114 let id = post_inc(&mut self.next_completion_id);
8115
8116 if let Some(buffer) = buffer {
8117 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8118 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
8119 ));
8120 }
8121 }
8122
8123 pub fn insert_snippet(
8124 &mut self,
8125 insertion_ranges: &[Range<usize>],
8126 snippet: Snippet,
8127 window: &mut Window,
8128 cx: &mut Context<Self>,
8129 ) -> Result<()> {
8130 struct Tabstop<T> {
8131 is_end_tabstop: bool,
8132 ranges: Vec<Range<T>>,
8133 choices: Option<Vec<String>>,
8134 }
8135
8136 let tabstops = self.buffer.update(cx, |buffer, cx| {
8137 let snippet_text: Arc<str> = snippet.text.clone().into();
8138 let edits = insertion_ranges
8139 .iter()
8140 .cloned()
8141 .map(|range| (range, snippet_text.clone()));
8142 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8143
8144 let snapshot = &*buffer.read(cx);
8145 let snippet = &snippet;
8146 snippet
8147 .tabstops
8148 .iter()
8149 .map(|tabstop| {
8150 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8151 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8152 });
8153 let mut tabstop_ranges = tabstop
8154 .ranges
8155 .iter()
8156 .flat_map(|tabstop_range| {
8157 let mut delta = 0_isize;
8158 insertion_ranges.iter().map(move |insertion_range| {
8159 let insertion_start = insertion_range.start as isize + delta;
8160 delta +=
8161 snippet.text.len() as isize - insertion_range.len() as isize;
8162
8163 let start = ((insertion_start + tabstop_range.start) as usize)
8164 .min(snapshot.len());
8165 let end = ((insertion_start + tabstop_range.end) as usize)
8166 .min(snapshot.len());
8167 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8168 })
8169 })
8170 .collect::<Vec<_>>();
8171 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8172
8173 Tabstop {
8174 is_end_tabstop,
8175 ranges: tabstop_ranges,
8176 choices: tabstop.choices.clone(),
8177 }
8178 })
8179 .collect::<Vec<_>>()
8180 });
8181 if let Some(tabstop) = tabstops.first() {
8182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8183 s.select_ranges(tabstop.ranges.iter().cloned());
8184 });
8185
8186 if let Some(choices) = &tabstop.choices {
8187 if let Some(selection) = tabstop.ranges.first() {
8188 self.show_snippet_choices(choices, selection.clone(), cx)
8189 }
8190 }
8191
8192 // If we're already at the last tabstop and it's at the end of the snippet,
8193 // we're done, we don't need to keep the state around.
8194 if !tabstop.is_end_tabstop {
8195 let choices = tabstops
8196 .iter()
8197 .map(|tabstop| tabstop.choices.clone())
8198 .collect();
8199
8200 let ranges = tabstops
8201 .into_iter()
8202 .map(|tabstop| tabstop.ranges)
8203 .collect::<Vec<_>>();
8204
8205 self.snippet_stack.push(SnippetState {
8206 active_index: 0,
8207 ranges,
8208 choices,
8209 });
8210 }
8211
8212 // Check whether the just-entered snippet ends with an auto-closable bracket.
8213 if self.autoclose_regions.is_empty() {
8214 let snapshot = self.buffer.read(cx).snapshot(cx);
8215 for selection in &mut self.selections.all::<Point>(cx) {
8216 let selection_head = selection.head();
8217 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8218 continue;
8219 };
8220
8221 let mut bracket_pair = None;
8222 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8223 let prev_chars = snapshot
8224 .reversed_chars_at(selection_head)
8225 .collect::<String>();
8226 for (pair, enabled) in scope.brackets() {
8227 if enabled
8228 && pair.close
8229 && prev_chars.starts_with(pair.start.as_str())
8230 && next_chars.starts_with(pair.end.as_str())
8231 {
8232 bracket_pair = Some(pair.clone());
8233 break;
8234 }
8235 }
8236 if let Some(pair) = bracket_pair {
8237 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8238 let autoclose_enabled =
8239 self.use_autoclose && snapshot_settings.use_autoclose;
8240 if autoclose_enabled {
8241 let start = snapshot.anchor_after(selection_head);
8242 let end = snapshot.anchor_after(selection_head);
8243 self.autoclose_regions.push(AutocloseRegion {
8244 selection_id: selection.id,
8245 range: start..end,
8246 pair,
8247 });
8248 }
8249 }
8250 }
8251 }
8252 }
8253 Ok(())
8254 }
8255
8256 pub fn move_to_next_snippet_tabstop(
8257 &mut self,
8258 window: &mut Window,
8259 cx: &mut Context<Self>,
8260 ) -> bool {
8261 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8262 }
8263
8264 pub fn move_to_prev_snippet_tabstop(
8265 &mut self,
8266 window: &mut Window,
8267 cx: &mut Context<Self>,
8268 ) -> bool {
8269 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8270 }
8271
8272 pub fn move_to_snippet_tabstop(
8273 &mut self,
8274 bias: Bias,
8275 window: &mut Window,
8276 cx: &mut Context<Self>,
8277 ) -> bool {
8278 if let Some(mut snippet) = self.snippet_stack.pop() {
8279 match bias {
8280 Bias::Left => {
8281 if snippet.active_index > 0 {
8282 snippet.active_index -= 1;
8283 } else {
8284 self.snippet_stack.push(snippet);
8285 return false;
8286 }
8287 }
8288 Bias::Right => {
8289 if snippet.active_index + 1 < snippet.ranges.len() {
8290 snippet.active_index += 1;
8291 } else {
8292 self.snippet_stack.push(snippet);
8293 return false;
8294 }
8295 }
8296 }
8297 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8298 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8299 s.select_anchor_ranges(current_ranges.iter().cloned())
8300 });
8301
8302 if let Some(choices) = &snippet.choices[snippet.active_index] {
8303 if let Some(selection) = current_ranges.first() {
8304 self.show_snippet_choices(&choices, selection.clone(), cx);
8305 }
8306 }
8307
8308 // If snippet state is not at the last tabstop, push it back on the stack
8309 if snippet.active_index + 1 < snippet.ranges.len() {
8310 self.snippet_stack.push(snippet);
8311 }
8312 return true;
8313 }
8314 }
8315
8316 false
8317 }
8318
8319 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8320 self.transact(window, cx, |this, window, cx| {
8321 this.select_all(&SelectAll, window, cx);
8322 this.insert("", window, cx);
8323 });
8324 }
8325
8326 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8327 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8328 self.transact(window, cx, |this, window, cx| {
8329 this.select_autoclose_pair(window, cx);
8330 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8331 if !this.linked_edit_ranges.is_empty() {
8332 let selections = this.selections.all::<MultiBufferPoint>(cx);
8333 let snapshot = this.buffer.read(cx).snapshot(cx);
8334
8335 for selection in selections.iter() {
8336 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8337 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8338 if selection_start.buffer_id != selection_end.buffer_id {
8339 continue;
8340 }
8341 if let Some(ranges) =
8342 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8343 {
8344 for (buffer, entries) in ranges {
8345 linked_ranges.entry(buffer).or_default().extend(entries);
8346 }
8347 }
8348 }
8349 }
8350
8351 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8352 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8353 for selection in &mut selections {
8354 if selection.is_empty() {
8355 let old_head = selection.head();
8356 let mut new_head =
8357 movement::left(&display_map, old_head.to_display_point(&display_map))
8358 .to_point(&display_map);
8359 if let Some((buffer, line_buffer_range)) = display_map
8360 .buffer_snapshot
8361 .buffer_line_for_row(MultiBufferRow(old_head.row))
8362 {
8363 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8364 let indent_len = match indent_size.kind {
8365 IndentKind::Space => {
8366 buffer.settings_at(line_buffer_range.start, cx).tab_size
8367 }
8368 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8369 };
8370 if old_head.column <= indent_size.len && old_head.column > 0 {
8371 let indent_len = indent_len.get();
8372 new_head = cmp::min(
8373 new_head,
8374 MultiBufferPoint::new(
8375 old_head.row,
8376 ((old_head.column - 1) / indent_len) * indent_len,
8377 ),
8378 );
8379 }
8380 }
8381
8382 selection.set_head(new_head, SelectionGoal::None);
8383 }
8384 }
8385
8386 this.signature_help_state.set_backspace_pressed(true);
8387 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8388 s.select(selections)
8389 });
8390 this.insert("", window, cx);
8391 let empty_str: Arc<str> = Arc::from("");
8392 for (buffer, edits) in linked_ranges {
8393 let snapshot = buffer.read(cx).snapshot();
8394 use text::ToPoint as TP;
8395
8396 let edits = edits
8397 .into_iter()
8398 .map(|range| {
8399 let end_point = TP::to_point(&range.end, &snapshot);
8400 let mut start_point = TP::to_point(&range.start, &snapshot);
8401
8402 if end_point == start_point {
8403 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8404 .saturating_sub(1);
8405 start_point =
8406 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8407 };
8408
8409 (start_point..end_point, empty_str.clone())
8410 })
8411 .sorted_by_key(|(range, _)| range.start)
8412 .collect::<Vec<_>>();
8413 buffer.update(cx, |this, cx| {
8414 this.edit(edits, None, cx);
8415 })
8416 }
8417 this.refresh_inline_completion(true, false, window, cx);
8418 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8419 });
8420 }
8421
8422 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8423 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8424 self.transact(window, cx, |this, window, cx| {
8425 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8426 s.move_with(|map, selection| {
8427 if selection.is_empty() {
8428 let cursor = movement::right(map, selection.head());
8429 selection.end = cursor;
8430 selection.reversed = true;
8431 selection.goal = SelectionGoal::None;
8432 }
8433 })
8434 });
8435 this.insert("", window, cx);
8436 this.refresh_inline_completion(true, false, window, cx);
8437 });
8438 }
8439
8440 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8441 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8442 if self.move_to_prev_snippet_tabstop(window, cx) {
8443 return;
8444 }
8445 self.outdent(&Outdent, window, cx);
8446 }
8447
8448 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8449 if self.move_to_next_snippet_tabstop(window, cx) {
8450 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8451 return;
8452 }
8453 if self.read_only(cx) {
8454 return;
8455 }
8456 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8457 let mut selections = self.selections.all_adjusted(cx);
8458 let buffer = self.buffer.read(cx);
8459 let snapshot = buffer.snapshot(cx);
8460 let rows_iter = selections.iter().map(|s| s.head().row);
8461 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8462
8463 let mut edits = Vec::new();
8464 let mut prev_edited_row = 0;
8465 let mut row_delta = 0;
8466 for selection in &mut selections {
8467 if selection.start.row != prev_edited_row {
8468 row_delta = 0;
8469 }
8470 prev_edited_row = selection.end.row;
8471
8472 // If the selection is non-empty, then increase the indentation of the selected lines.
8473 if !selection.is_empty() {
8474 row_delta =
8475 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8476 continue;
8477 }
8478
8479 // If the selection is empty and the cursor is in the leading whitespace before the
8480 // suggested indentation, then auto-indent the line.
8481 let cursor = selection.head();
8482 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8483 if let Some(suggested_indent) =
8484 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8485 {
8486 if cursor.column < suggested_indent.len
8487 && cursor.column <= current_indent.len
8488 && current_indent.len <= suggested_indent.len
8489 {
8490 selection.start = Point::new(cursor.row, suggested_indent.len);
8491 selection.end = selection.start;
8492 if row_delta == 0 {
8493 edits.extend(Buffer::edit_for_indent_size_adjustment(
8494 cursor.row,
8495 current_indent,
8496 suggested_indent,
8497 ));
8498 row_delta = suggested_indent.len - current_indent.len;
8499 }
8500 continue;
8501 }
8502 }
8503
8504 // Otherwise, insert a hard or soft tab.
8505 let settings = buffer.language_settings_at(cursor, cx);
8506 let tab_size = if settings.hard_tabs {
8507 IndentSize::tab()
8508 } else {
8509 let tab_size = settings.tab_size.get();
8510 let indent_remainder = snapshot
8511 .text_for_range(Point::new(cursor.row, 0)..cursor)
8512 .flat_map(str::chars)
8513 .fold(row_delta % tab_size, |counter: u32, c| {
8514 if c == '\t' {
8515 0
8516 } else {
8517 (counter + 1) % tab_size
8518 }
8519 });
8520
8521 let chars_to_next_tab_stop = tab_size - indent_remainder;
8522 IndentSize::spaces(chars_to_next_tab_stop)
8523 };
8524 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8525 selection.end = selection.start;
8526 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8527 row_delta += tab_size.len;
8528 }
8529
8530 self.transact(window, cx, |this, window, cx| {
8531 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8532 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8533 s.select(selections)
8534 });
8535 this.refresh_inline_completion(true, false, window, cx);
8536 });
8537 }
8538
8539 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8540 if self.read_only(cx) {
8541 return;
8542 }
8543 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8544 let mut selections = self.selections.all::<Point>(cx);
8545 let mut prev_edited_row = 0;
8546 let mut row_delta = 0;
8547 let mut edits = Vec::new();
8548 let buffer = self.buffer.read(cx);
8549 let snapshot = buffer.snapshot(cx);
8550 for selection in &mut selections {
8551 if selection.start.row != prev_edited_row {
8552 row_delta = 0;
8553 }
8554 prev_edited_row = selection.end.row;
8555
8556 row_delta =
8557 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8558 }
8559
8560 self.transact(window, cx, |this, window, cx| {
8561 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8562 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8563 s.select(selections)
8564 });
8565 });
8566 }
8567
8568 fn indent_selection(
8569 buffer: &MultiBuffer,
8570 snapshot: &MultiBufferSnapshot,
8571 selection: &mut Selection<Point>,
8572 edits: &mut Vec<(Range<Point>, String)>,
8573 delta_for_start_row: u32,
8574 cx: &App,
8575 ) -> u32 {
8576 let settings = buffer.language_settings_at(selection.start, cx);
8577 let tab_size = settings.tab_size.get();
8578 let indent_kind = if settings.hard_tabs {
8579 IndentKind::Tab
8580 } else {
8581 IndentKind::Space
8582 };
8583 let mut start_row = selection.start.row;
8584 let mut end_row = selection.end.row + 1;
8585
8586 // If a selection ends at the beginning of a line, don't indent
8587 // that last line.
8588 if selection.end.column == 0 && selection.end.row > selection.start.row {
8589 end_row -= 1;
8590 }
8591
8592 // Avoid re-indenting a row that has already been indented by a
8593 // previous selection, but still update this selection's column
8594 // to reflect that indentation.
8595 if delta_for_start_row > 0 {
8596 start_row += 1;
8597 selection.start.column += delta_for_start_row;
8598 if selection.end.row == selection.start.row {
8599 selection.end.column += delta_for_start_row;
8600 }
8601 }
8602
8603 let mut delta_for_end_row = 0;
8604 let has_multiple_rows = start_row + 1 != end_row;
8605 for row in start_row..end_row {
8606 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8607 let indent_delta = match (current_indent.kind, indent_kind) {
8608 (IndentKind::Space, IndentKind::Space) => {
8609 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8610 IndentSize::spaces(columns_to_next_tab_stop)
8611 }
8612 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8613 (_, IndentKind::Tab) => IndentSize::tab(),
8614 };
8615
8616 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8617 0
8618 } else {
8619 selection.start.column
8620 };
8621 let row_start = Point::new(row, start);
8622 edits.push((
8623 row_start..row_start,
8624 indent_delta.chars().collect::<String>(),
8625 ));
8626
8627 // Update this selection's endpoints to reflect the indentation.
8628 if row == selection.start.row {
8629 selection.start.column += indent_delta.len;
8630 }
8631 if row == selection.end.row {
8632 selection.end.column += indent_delta.len;
8633 delta_for_end_row = indent_delta.len;
8634 }
8635 }
8636
8637 if selection.start.row == selection.end.row {
8638 delta_for_start_row + delta_for_end_row
8639 } else {
8640 delta_for_end_row
8641 }
8642 }
8643
8644 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8645 if self.read_only(cx) {
8646 return;
8647 }
8648 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8649 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8650 let selections = self.selections.all::<Point>(cx);
8651 let mut deletion_ranges = Vec::new();
8652 let mut last_outdent = None;
8653 {
8654 let buffer = self.buffer.read(cx);
8655 let snapshot = buffer.snapshot(cx);
8656 for selection in &selections {
8657 let settings = buffer.language_settings_at(selection.start, cx);
8658 let tab_size = settings.tab_size.get();
8659 let mut rows = selection.spanned_rows(false, &display_map);
8660
8661 // Avoid re-outdenting a row that has already been outdented by a
8662 // previous selection.
8663 if let Some(last_row) = last_outdent {
8664 if last_row == rows.start {
8665 rows.start = rows.start.next_row();
8666 }
8667 }
8668 let has_multiple_rows = rows.len() > 1;
8669 for row in rows.iter_rows() {
8670 let indent_size = snapshot.indent_size_for_line(row);
8671 if indent_size.len > 0 {
8672 let deletion_len = match indent_size.kind {
8673 IndentKind::Space => {
8674 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8675 if columns_to_prev_tab_stop == 0 {
8676 tab_size
8677 } else {
8678 columns_to_prev_tab_stop
8679 }
8680 }
8681 IndentKind::Tab => 1,
8682 };
8683 let start = if has_multiple_rows
8684 || deletion_len > selection.start.column
8685 || indent_size.len < selection.start.column
8686 {
8687 0
8688 } else {
8689 selection.start.column - deletion_len
8690 };
8691 deletion_ranges.push(
8692 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8693 );
8694 last_outdent = Some(row);
8695 }
8696 }
8697 }
8698 }
8699
8700 self.transact(window, cx, |this, window, cx| {
8701 this.buffer.update(cx, |buffer, cx| {
8702 let empty_str: Arc<str> = Arc::default();
8703 buffer.edit(
8704 deletion_ranges
8705 .into_iter()
8706 .map(|range| (range, empty_str.clone())),
8707 None,
8708 cx,
8709 );
8710 });
8711 let selections = this.selections.all::<usize>(cx);
8712 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8713 s.select(selections)
8714 });
8715 });
8716 }
8717
8718 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8719 if self.read_only(cx) {
8720 return;
8721 }
8722 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8723 let selections = self
8724 .selections
8725 .all::<usize>(cx)
8726 .into_iter()
8727 .map(|s| s.range());
8728
8729 self.transact(window, cx, |this, window, cx| {
8730 this.buffer.update(cx, |buffer, cx| {
8731 buffer.autoindent_ranges(selections, cx);
8732 });
8733 let selections = this.selections.all::<usize>(cx);
8734 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8735 s.select(selections)
8736 });
8737 });
8738 }
8739
8740 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8741 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8743 let selections = self.selections.all::<Point>(cx);
8744
8745 let mut new_cursors = Vec::new();
8746 let mut edit_ranges = Vec::new();
8747 let mut selections = selections.iter().peekable();
8748 while let Some(selection) = selections.next() {
8749 let mut rows = selection.spanned_rows(false, &display_map);
8750 let goal_display_column = selection.head().to_display_point(&display_map).column();
8751
8752 // Accumulate contiguous regions of rows that we want to delete.
8753 while let Some(next_selection) = selections.peek() {
8754 let next_rows = next_selection.spanned_rows(false, &display_map);
8755 if next_rows.start <= rows.end {
8756 rows.end = next_rows.end;
8757 selections.next().unwrap();
8758 } else {
8759 break;
8760 }
8761 }
8762
8763 let buffer = &display_map.buffer_snapshot;
8764 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8765 let edit_end;
8766 let cursor_buffer_row;
8767 if buffer.max_point().row >= rows.end.0 {
8768 // If there's a line after the range, delete the \n from the end of the row range
8769 // and position the cursor on the next line.
8770 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8771 cursor_buffer_row = rows.end;
8772 } else {
8773 // If there isn't a line after the range, delete the \n from the line before the
8774 // start of the row range and position the cursor there.
8775 edit_start = edit_start.saturating_sub(1);
8776 edit_end = buffer.len();
8777 cursor_buffer_row = rows.start.previous_row();
8778 }
8779
8780 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8781 *cursor.column_mut() =
8782 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8783
8784 new_cursors.push((
8785 selection.id,
8786 buffer.anchor_after(cursor.to_point(&display_map)),
8787 ));
8788 edit_ranges.push(edit_start..edit_end);
8789 }
8790
8791 self.transact(window, cx, |this, window, cx| {
8792 let buffer = this.buffer.update(cx, |buffer, cx| {
8793 let empty_str: Arc<str> = Arc::default();
8794 buffer.edit(
8795 edit_ranges
8796 .into_iter()
8797 .map(|range| (range, empty_str.clone())),
8798 None,
8799 cx,
8800 );
8801 buffer.snapshot(cx)
8802 });
8803 let new_selections = new_cursors
8804 .into_iter()
8805 .map(|(id, cursor)| {
8806 let cursor = cursor.to_point(&buffer);
8807 Selection {
8808 id,
8809 start: cursor,
8810 end: cursor,
8811 reversed: false,
8812 goal: SelectionGoal::None,
8813 }
8814 })
8815 .collect();
8816
8817 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8818 s.select(new_selections);
8819 });
8820 });
8821 }
8822
8823 pub fn join_lines_impl(
8824 &mut self,
8825 insert_whitespace: bool,
8826 window: &mut Window,
8827 cx: &mut Context<Self>,
8828 ) {
8829 if self.read_only(cx) {
8830 return;
8831 }
8832 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8833 for selection in self.selections.all::<Point>(cx) {
8834 let start = MultiBufferRow(selection.start.row);
8835 // Treat single line selections as if they include the next line. Otherwise this action
8836 // would do nothing for single line selections individual cursors.
8837 let end = if selection.start.row == selection.end.row {
8838 MultiBufferRow(selection.start.row + 1)
8839 } else {
8840 MultiBufferRow(selection.end.row)
8841 };
8842
8843 if let Some(last_row_range) = row_ranges.last_mut() {
8844 if start <= last_row_range.end {
8845 last_row_range.end = end;
8846 continue;
8847 }
8848 }
8849 row_ranges.push(start..end);
8850 }
8851
8852 let snapshot = self.buffer.read(cx).snapshot(cx);
8853 let mut cursor_positions = Vec::new();
8854 for row_range in &row_ranges {
8855 let anchor = snapshot.anchor_before(Point::new(
8856 row_range.end.previous_row().0,
8857 snapshot.line_len(row_range.end.previous_row()),
8858 ));
8859 cursor_positions.push(anchor..anchor);
8860 }
8861
8862 self.transact(window, cx, |this, window, cx| {
8863 for row_range in row_ranges.into_iter().rev() {
8864 for row in row_range.iter_rows().rev() {
8865 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8866 let next_line_row = row.next_row();
8867 let indent = snapshot.indent_size_for_line(next_line_row);
8868 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8869
8870 let replace =
8871 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8872 " "
8873 } else {
8874 ""
8875 };
8876
8877 this.buffer.update(cx, |buffer, cx| {
8878 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8879 });
8880 }
8881 }
8882
8883 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8884 s.select_anchor_ranges(cursor_positions)
8885 });
8886 });
8887 }
8888
8889 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8890 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8891 self.join_lines_impl(true, window, cx);
8892 }
8893
8894 pub fn sort_lines_case_sensitive(
8895 &mut self,
8896 _: &SortLinesCaseSensitive,
8897 window: &mut Window,
8898 cx: &mut Context<Self>,
8899 ) {
8900 self.manipulate_lines(window, cx, |lines| lines.sort())
8901 }
8902
8903 pub fn sort_lines_case_insensitive(
8904 &mut self,
8905 _: &SortLinesCaseInsensitive,
8906 window: &mut Window,
8907 cx: &mut Context<Self>,
8908 ) {
8909 self.manipulate_lines(window, cx, |lines| {
8910 lines.sort_by_key(|line| line.to_lowercase())
8911 })
8912 }
8913
8914 pub fn unique_lines_case_insensitive(
8915 &mut self,
8916 _: &UniqueLinesCaseInsensitive,
8917 window: &mut Window,
8918 cx: &mut Context<Self>,
8919 ) {
8920 self.manipulate_lines(window, cx, |lines| {
8921 let mut seen = HashSet::default();
8922 lines.retain(|line| seen.insert(line.to_lowercase()));
8923 })
8924 }
8925
8926 pub fn unique_lines_case_sensitive(
8927 &mut self,
8928 _: &UniqueLinesCaseSensitive,
8929 window: &mut Window,
8930 cx: &mut Context<Self>,
8931 ) {
8932 self.manipulate_lines(window, cx, |lines| {
8933 let mut seen = HashSet::default();
8934 lines.retain(|line| seen.insert(*line));
8935 })
8936 }
8937
8938 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8939 let Some(project) = self.project.clone() else {
8940 return;
8941 };
8942 self.reload(project, window, cx)
8943 .detach_and_notify_err(window, cx);
8944 }
8945
8946 pub fn restore_file(
8947 &mut self,
8948 _: &::git::RestoreFile,
8949 window: &mut Window,
8950 cx: &mut Context<Self>,
8951 ) {
8952 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8953 let mut buffer_ids = HashSet::default();
8954 let snapshot = self.buffer().read(cx).snapshot(cx);
8955 for selection in self.selections.all::<usize>(cx) {
8956 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8957 }
8958
8959 let buffer = self.buffer().read(cx);
8960 let ranges = buffer_ids
8961 .into_iter()
8962 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8963 .collect::<Vec<_>>();
8964
8965 self.restore_hunks_in_ranges(ranges, window, cx);
8966 }
8967
8968 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8969 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8970 let selections = self
8971 .selections
8972 .all(cx)
8973 .into_iter()
8974 .map(|s| s.range())
8975 .collect();
8976 self.restore_hunks_in_ranges(selections, window, cx);
8977 }
8978
8979 pub fn restore_hunks_in_ranges(
8980 &mut self,
8981 ranges: Vec<Range<Point>>,
8982 window: &mut Window,
8983 cx: &mut Context<Editor>,
8984 ) {
8985 let mut revert_changes = HashMap::default();
8986 let chunk_by = self
8987 .snapshot(window, cx)
8988 .hunks_for_ranges(ranges)
8989 .into_iter()
8990 .chunk_by(|hunk| hunk.buffer_id);
8991 for (buffer_id, hunks) in &chunk_by {
8992 let hunks = hunks.collect::<Vec<_>>();
8993 for hunk in &hunks {
8994 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8995 }
8996 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8997 }
8998 drop(chunk_by);
8999 if !revert_changes.is_empty() {
9000 self.transact(window, cx, |editor, window, cx| {
9001 editor.restore(revert_changes, window, cx);
9002 });
9003 }
9004 }
9005
9006 pub fn open_active_item_in_terminal(
9007 &mut self,
9008 _: &OpenInTerminal,
9009 window: &mut Window,
9010 cx: &mut Context<Self>,
9011 ) {
9012 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9013 let project_path = buffer.read(cx).project_path(cx)?;
9014 let project = self.project.as_ref()?.read(cx);
9015 let entry = project.entry_for_path(&project_path, cx)?;
9016 let parent = match &entry.canonical_path {
9017 Some(canonical_path) => canonical_path.to_path_buf(),
9018 None => project.absolute_path(&project_path, cx)?,
9019 }
9020 .parent()?
9021 .to_path_buf();
9022 Some(parent)
9023 }) {
9024 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9025 }
9026 }
9027
9028 fn set_breakpoint_context_menu(
9029 &mut self,
9030 display_row: DisplayRow,
9031 position: Option<Anchor>,
9032 clicked_point: gpui::Point<Pixels>,
9033 window: &mut Window,
9034 cx: &mut Context<Self>,
9035 ) {
9036 if !cx.has_flag::<Debugger>() {
9037 return;
9038 }
9039 let source = self
9040 .buffer
9041 .read(cx)
9042 .snapshot(cx)
9043 .anchor_before(Point::new(display_row.0, 0u32));
9044
9045 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9046
9047 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9048 self,
9049 source,
9050 clicked_point,
9051 context_menu,
9052 window,
9053 cx,
9054 );
9055 }
9056
9057 fn add_edit_breakpoint_block(
9058 &mut self,
9059 anchor: Anchor,
9060 breakpoint: &Breakpoint,
9061 edit_action: BreakpointPromptEditAction,
9062 window: &mut Window,
9063 cx: &mut Context<Self>,
9064 ) {
9065 let weak_editor = cx.weak_entity();
9066 let bp_prompt = cx.new(|cx| {
9067 BreakpointPromptEditor::new(
9068 weak_editor,
9069 anchor,
9070 breakpoint.clone(),
9071 edit_action,
9072 window,
9073 cx,
9074 )
9075 });
9076
9077 let height = bp_prompt.update(cx, |this, cx| {
9078 this.prompt
9079 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9080 });
9081 let cloned_prompt = bp_prompt.clone();
9082 let blocks = vec![BlockProperties {
9083 style: BlockStyle::Sticky,
9084 placement: BlockPlacement::Above(anchor),
9085 height: Some(height),
9086 render: Arc::new(move |cx| {
9087 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9088 cloned_prompt.clone().into_any_element()
9089 }),
9090 priority: 0,
9091 }];
9092
9093 let focus_handle = bp_prompt.focus_handle(cx);
9094 window.focus(&focus_handle);
9095
9096 let block_ids = self.insert_blocks(blocks, None, cx);
9097 bp_prompt.update(cx, |prompt, _| {
9098 prompt.add_block_ids(block_ids);
9099 });
9100 }
9101
9102 pub(crate) fn breakpoint_at_row(
9103 &self,
9104 row: u32,
9105 window: &mut Window,
9106 cx: &mut Context<Self>,
9107 ) -> Option<(Anchor, Breakpoint)> {
9108 let snapshot = self.snapshot(window, cx);
9109 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9110
9111 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9112 }
9113
9114 pub(crate) fn breakpoint_at_anchor(
9115 &self,
9116 breakpoint_position: Anchor,
9117 snapshot: &EditorSnapshot,
9118 cx: &mut Context<Self>,
9119 ) -> Option<(Anchor, Breakpoint)> {
9120 let project = self.project.clone()?;
9121
9122 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9123 snapshot
9124 .buffer_snapshot
9125 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9126 })?;
9127
9128 let enclosing_excerpt = breakpoint_position.excerpt_id;
9129 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9130 let buffer_snapshot = buffer.read(cx).snapshot();
9131
9132 let row = buffer_snapshot
9133 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9134 .row;
9135
9136 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9137 let anchor_end = snapshot
9138 .buffer_snapshot
9139 .anchor_after(Point::new(row, line_len));
9140
9141 let bp = self
9142 .breakpoint_store
9143 .as_ref()?
9144 .read_with(cx, |breakpoint_store, cx| {
9145 breakpoint_store
9146 .breakpoints(
9147 &buffer,
9148 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9149 &buffer_snapshot,
9150 cx,
9151 )
9152 .next()
9153 .and_then(|(anchor, bp)| {
9154 let breakpoint_row = buffer_snapshot
9155 .summary_for_anchor::<text::PointUtf16>(anchor)
9156 .row;
9157
9158 if breakpoint_row == row {
9159 snapshot
9160 .buffer_snapshot
9161 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9162 .map(|anchor| (anchor, bp.clone()))
9163 } else {
9164 None
9165 }
9166 })
9167 });
9168 bp
9169 }
9170
9171 pub fn edit_log_breakpoint(
9172 &mut self,
9173 _: &EditLogBreakpoint,
9174 window: &mut Window,
9175 cx: &mut Context<Self>,
9176 ) {
9177 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9178 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9179 message: None,
9180 state: BreakpointState::Enabled,
9181 condition: None,
9182 hit_condition: None,
9183 });
9184
9185 self.add_edit_breakpoint_block(
9186 anchor,
9187 &breakpoint,
9188 BreakpointPromptEditAction::Log,
9189 window,
9190 cx,
9191 );
9192 }
9193 }
9194
9195 fn breakpoints_at_cursors(
9196 &self,
9197 window: &mut Window,
9198 cx: &mut Context<Self>,
9199 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9200 let snapshot = self.snapshot(window, cx);
9201 let cursors = self
9202 .selections
9203 .disjoint_anchors()
9204 .into_iter()
9205 .map(|selection| {
9206 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9207
9208 let breakpoint_position = self
9209 .breakpoint_at_row(cursor_position.row, window, cx)
9210 .map(|bp| bp.0)
9211 .unwrap_or_else(|| {
9212 snapshot
9213 .display_snapshot
9214 .buffer_snapshot
9215 .anchor_after(Point::new(cursor_position.row, 0))
9216 });
9217
9218 let breakpoint = self
9219 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9220 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9221
9222 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9223 })
9224 // 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.
9225 .collect::<HashMap<Anchor, _>>();
9226
9227 cursors.into_iter().collect()
9228 }
9229
9230 pub fn enable_breakpoint(
9231 &mut self,
9232 _: &crate::actions::EnableBreakpoint,
9233 window: &mut Window,
9234 cx: &mut Context<Self>,
9235 ) {
9236 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9237 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9238 continue;
9239 };
9240 self.edit_breakpoint_at_anchor(
9241 anchor,
9242 breakpoint,
9243 BreakpointEditAction::InvertState,
9244 cx,
9245 );
9246 }
9247 }
9248
9249 pub fn disable_breakpoint(
9250 &mut self,
9251 _: &crate::actions::DisableBreakpoint,
9252 window: &mut Window,
9253 cx: &mut Context<Self>,
9254 ) {
9255 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9256 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9257 continue;
9258 };
9259 self.edit_breakpoint_at_anchor(
9260 anchor,
9261 breakpoint,
9262 BreakpointEditAction::InvertState,
9263 cx,
9264 );
9265 }
9266 }
9267
9268 pub fn toggle_breakpoint(
9269 &mut self,
9270 _: &crate::actions::ToggleBreakpoint,
9271 window: &mut Window,
9272 cx: &mut Context<Self>,
9273 ) {
9274 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9275 if let Some(breakpoint) = breakpoint {
9276 self.edit_breakpoint_at_anchor(
9277 anchor,
9278 breakpoint,
9279 BreakpointEditAction::Toggle,
9280 cx,
9281 );
9282 } else {
9283 self.edit_breakpoint_at_anchor(
9284 anchor,
9285 Breakpoint::new_standard(),
9286 BreakpointEditAction::Toggle,
9287 cx,
9288 );
9289 }
9290 }
9291 }
9292
9293 pub fn edit_breakpoint_at_anchor(
9294 &mut self,
9295 breakpoint_position: Anchor,
9296 breakpoint: Breakpoint,
9297 edit_action: BreakpointEditAction,
9298 cx: &mut Context<Self>,
9299 ) {
9300 let Some(breakpoint_store) = &self.breakpoint_store else {
9301 return;
9302 };
9303
9304 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9305 if breakpoint_position == Anchor::min() {
9306 self.buffer()
9307 .read(cx)
9308 .excerpt_buffer_ids()
9309 .into_iter()
9310 .next()
9311 } else {
9312 None
9313 }
9314 }) else {
9315 return;
9316 };
9317
9318 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9319 return;
9320 };
9321
9322 breakpoint_store.update(cx, |breakpoint_store, cx| {
9323 breakpoint_store.toggle_breakpoint(
9324 buffer,
9325 (breakpoint_position.text_anchor, breakpoint),
9326 edit_action,
9327 cx,
9328 );
9329 });
9330
9331 cx.notify();
9332 }
9333
9334 #[cfg(any(test, feature = "test-support"))]
9335 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9336 self.breakpoint_store.clone()
9337 }
9338
9339 pub fn prepare_restore_change(
9340 &self,
9341 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9342 hunk: &MultiBufferDiffHunk,
9343 cx: &mut App,
9344 ) -> Option<()> {
9345 if hunk.is_created_file() {
9346 return None;
9347 }
9348 let buffer = self.buffer.read(cx);
9349 let diff = buffer.diff_for(hunk.buffer_id)?;
9350 let buffer = buffer.buffer(hunk.buffer_id)?;
9351 let buffer = buffer.read(cx);
9352 let original_text = diff
9353 .read(cx)
9354 .base_text()
9355 .as_rope()
9356 .slice(hunk.diff_base_byte_range.clone());
9357 let buffer_snapshot = buffer.snapshot();
9358 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9359 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9360 probe
9361 .0
9362 .start
9363 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9364 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9365 }) {
9366 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9367 Some(())
9368 } else {
9369 None
9370 }
9371 }
9372
9373 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9374 self.manipulate_lines(window, cx, |lines| lines.reverse())
9375 }
9376
9377 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9378 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9379 }
9380
9381 fn manipulate_lines<Fn>(
9382 &mut self,
9383 window: &mut Window,
9384 cx: &mut Context<Self>,
9385 mut callback: Fn,
9386 ) where
9387 Fn: FnMut(&mut Vec<&str>),
9388 {
9389 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9390
9391 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9392 let buffer = self.buffer.read(cx).snapshot(cx);
9393
9394 let mut edits = Vec::new();
9395
9396 let selections = self.selections.all::<Point>(cx);
9397 let mut selections = selections.iter().peekable();
9398 let mut contiguous_row_selections = Vec::new();
9399 let mut new_selections = Vec::new();
9400 let mut added_lines = 0;
9401 let mut removed_lines = 0;
9402
9403 while let Some(selection) = selections.next() {
9404 let (start_row, end_row) = consume_contiguous_rows(
9405 &mut contiguous_row_selections,
9406 selection,
9407 &display_map,
9408 &mut selections,
9409 );
9410
9411 let start_point = Point::new(start_row.0, 0);
9412 let end_point = Point::new(
9413 end_row.previous_row().0,
9414 buffer.line_len(end_row.previous_row()),
9415 );
9416 let text = buffer
9417 .text_for_range(start_point..end_point)
9418 .collect::<String>();
9419
9420 let mut lines = text.split('\n').collect_vec();
9421
9422 let lines_before = lines.len();
9423 callback(&mut lines);
9424 let lines_after = lines.len();
9425
9426 edits.push((start_point..end_point, lines.join("\n")));
9427
9428 // Selections must change based on added and removed line count
9429 let start_row =
9430 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9431 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9432 new_selections.push(Selection {
9433 id: selection.id,
9434 start: start_row,
9435 end: end_row,
9436 goal: SelectionGoal::None,
9437 reversed: selection.reversed,
9438 });
9439
9440 if lines_after > lines_before {
9441 added_lines += lines_after - lines_before;
9442 } else if lines_before > lines_after {
9443 removed_lines += lines_before - lines_after;
9444 }
9445 }
9446
9447 self.transact(window, cx, |this, window, cx| {
9448 let buffer = this.buffer.update(cx, |buffer, cx| {
9449 buffer.edit(edits, None, cx);
9450 buffer.snapshot(cx)
9451 });
9452
9453 // Recalculate offsets on newly edited buffer
9454 let new_selections = new_selections
9455 .iter()
9456 .map(|s| {
9457 let start_point = Point::new(s.start.0, 0);
9458 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9459 Selection {
9460 id: s.id,
9461 start: buffer.point_to_offset(start_point),
9462 end: buffer.point_to_offset(end_point),
9463 goal: s.goal,
9464 reversed: s.reversed,
9465 }
9466 })
9467 .collect();
9468
9469 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9470 s.select(new_selections);
9471 });
9472
9473 this.request_autoscroll(Autoscroll::fit(), cx);
9474 });
9475 }
9476
9477 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9478 self.manipulate_text(window, cx, |text| {
9479 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9480 if has_upper_case_characters {
9481 text.to_lowercase()
9482 } else {
9483 text.to_uppercase()
9484 }
9485 })
9486 }
9487
9488 pub fn convert_to_upper_case(
9489 &mut self,
9490 _: &ConvertToUpperCase,
9491 window: &mut Window,
9492 cx: &mut Context<Self>,
9493 ) {
9494 self.manipulate_text(window, cx, |text| text.to_uppercase())
9495 }
9496
9497 pub fn convert_to_lower_case(
9498 &mut self,
9499 _: &ConvertToLowerCase,
9500 window: &mut Window,
9501 cx: &mut Context<Self>,
9502 ) {
9503 self.manipulate_text(window, cx, |text| text.to_lowercase())
9504 }
9505
9506 pub fn convert_to_title_case(
9507 &mut self,
9508 _: &ConvertToTitleCase,
9509 window: &mut Window,
9510 cx: &mut Context<Self>,
9511 ) {
9512 self.manipulate_text(window, cx, |text| {
9513 text.split('\n')
9514 .map(|line| line.to_case(Case::Title))
9515 .join("\n")
9516 })
9517 }
9518
9519 pub fn convert_to_snake_case(
9520 &mut self,
9521 _: &ConvertToSnakeCase,
9522 window: &mut Window,
9523 cx: &mut Context<Self>,
9524 ) {
9525 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9526 }
9527
9528 pub fn convert_to_kebab_case(
9529 &mut self,
9530 _: &ConvertToKebabCase,
9531 window: &mut Window,
9532 cx: &mut Context<Self>,
9533 ) {
9534 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9535 }
9536
9537 pub fn convert_to_upper_camel_case(
9538 &mut self,
9539 _: &ConvertToUpperCamelCase,
9540 window: &mut Window,
9541 cx: &mut Context<Self>,
9542 ) {
9543 self.manipulate_text(window, cx, |text| {
9544 text.split('\n')
9545 .map(|line| line.to_case(Case::UpperCamel))
9546 .join("\n")
9547 })
9548 }
9549
9550 pub fn convert_to_lower_camel_case(
9551 &mut self,
9552 _: &ConvertToLowerCamelCase,
9553 window: &mut Window,
9554 cx: &mut Context<Self>,
9555 ) {
9556 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9557 }
9558
9559 pub fn convert_to_opposite_case(
9560 &mut self,
9561 _: &ConvertToOppositeCase,
9562 window: &mut Window,
9563 cx: &mut Context<Self>,
9564 ) {
9565 self.manipulate_text(window, cx, |text| {
9566 text.chars()
9567 .fold(String::with_capacity(text.len()), |mut t, c| {
9568 if c.is_uppercase() {
9569 t.extend(c.to_lowercase());
9570 } else {
9571 t.extend(c.to_uppercase());
9572 }
9573 t
9574 })
9575 })
9576 }
9577
9578 pub fn convert_to_rot13(
9579 &mut self,
9580 _: &ConvertToRot13,
9581 window: &mut Window,
9582 cx: &mut Context<Self>,
9583 ) {
9584 self.manipulate_text(window, cx, |text| {
9585 text.chars()
9586 .map(|c| match c {
9587 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9588 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9589 _ => c,
9590 })
9591 .collect()
9592 })
9593 }
9594
9595 pub fn convert_to_rot47(
9596 &mut self,
9597 _: &ConvertToRot47,
9598 window: &mut Window,
9599 cx: &mut Context<Self>,
9600 ) {
9601 self.manipulate_text(window, cx, |text| {
9602 text.chars()
9603 .map(|c| {
9604 let code_point = c as u32;
9605 if code_point >= 33 && code_point <= 126 {
9606 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9607 }
9608 c
9609 })
9610 .collect()
9611 })
9612 }
9613
9614 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9615 where
9616 Fn: FnMut(&str) -> String,
9617 {
9618 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9619 let buffer = self.buffer.read(cx).snapshot(cx);
9620
9621 let mut new_selections = Vec::new();
9622 let mut edits = Vec::new();
9623 let mut selection_adjustment = 0i32;
9624
9625 for selection in self.selections.all::<usize>(cx) {
9626 let selection_is_empty = selection.is_empty();
9627
9628 let (start, end) = if selection_is_empty {
9629 let word_range = movement::surrounding_word(
9630 &display_map,
9631 selection.start.to_display_point(&display_map),
9632 );
9633 let start = word_range.start.to_offset(&display_map, Bias::Left);
9634 let end = word_range.end.to_offset(&display_map, Bias::Left);
9635 (start, end)
9636 } else {
9637 (selection.start, selection.end)
9638 };
9639
9640 let text = buffer.text_for_range(start..end).collect::<String>();
9641 let old_length = text.len() as i32;
9642 let text = callback(&text);
9643
9644 new_selections.push(Selection {
9645 start: (start as i32 - selection_adjustment) as usize,
9646 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9647 goal: SelectionGoal::None,
9648 ..selection
9649 });
9650
9651 selection_adjustment += old_length - text.len() as i32;
9652
9653 edits.push((start..end, text));
9654 }
9655
9656 self.transact(window, cx, |this, window, cx| {
9657 this.buffer.update(cx, |buffer, cx| {
9658 buffer.edit(edits, None, cx);
9659 });
9660
9661 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9662 s.select(new_selections);
9663 });
9664
9665 this.request_autoscroll(Autoscroll::fit(), cx);
9666 });
9667 }
9668
9669 pub fn duplicate(
9670 &mut self,
9671 upwards: bool,
9672 whole_lines: bool,
9673 window: &mut Window,
9674 cx: &mut Context<Self>,
9675 ) {
9676 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9677
9678 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9679 let buffer = &display_map.buffer_snapshot;
9680 let selections = self.selections.all::<Point>(cx);
9681
9682 let mut edits = Vec::new();
9683 let mut selections_iter = selections.iter().peekable();
9684 while let Some(selection) = selections_iter.next() {
9685 let mut rows = selection.spanned_rows(false, &display_map);
9686 // duplicate line-wise
9687 if whole_lines || selection.start == selection.end {
9688 // Avoid duplicating the same lines twice.
9689 while let Some(next_selection) = selections_iter.peek() {
9690 let next_rows = next_selection.spanned_rows(false, &display_map);
9691 if next_rows.start < rows.end {
9692 rows.end = next_rows.end;
9693 selections_iter.next().unwrap();
9694 } else {
9695 break;
9696 }
9697 }
9698
9699 // Copy the text from the selected row region and splice it either at the start
9700 // or end of the region.
9701 let start = Point::new(rows.start.0, 0);
9702 let end = Point::new(
9703 rows.end.previous_row().0,
9704 buffer.line_len(rows.end.previous_row()),
9705 );
9706 let text = buffer
9707 .text_for_range(start..end)
9708 .chain(Some("\n"))
9709 .collect::<String>();
9710 let insert_location = if upwards {
9711 Point::new(rows.end.0, 0)
9712 } else {
9713 start
9714 };
9715 edits.push((insert_location..insert_location, text));
9716 } else {
9717 // duplicate character-wise
9718 let start = selection.start;
9719 let end = selection.end;
9720 let text = buffer.text_for_range(start..end).collect::<String>();
9721 edits.push((selection.end..selection.end, text));
9722 }
9723 }
9724
9725 self.transact(window, cx, |this, _, cx| {
9726 this.buffer.update(cx, |buffer, cx| {
9727 buffer.edit(edits, None, cx);
9728 });
9729
9730 this.request_autoscroll(Autoscroll::fit(), cx);
9731 });
9732 }
9733
9734 pub fn duplicate_line_up(
9735 &mut self,
9736 _: &DuplicateLineUp,
9737 window: &mut Window,
9738 cx: &mut Context<Self>,
9739 ) {
9740 self.duplicate(true, true, window, cx);
9741 }
9742
9743 pub fn duplicate_line_down(
9744 &mut self,
9745 _: &DuplicateLineDown,
9746 window: &mut Window,
9747 cx: &mut Context<Self>,
9748 ) {
9749 self.duplicate(false, true, window, cx);
9750 }
9751
9752 pub fn duplicate_selection(
9753 &mut self,
9754 _: &DuplicateSelection,
9755 window: &mut Window,
9756 cx: &mut Context<Self>,
9757 ) {
9758 self.duplicate(false, false, window, cx);
9759 }
9760
9761 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9762 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9763
9764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9765 let buffer = self.buffer.read(cx).snapshot(cx);
9766
9767 let mut edits = Vec::new();
9768 let mut unfold_ranges = Vec::new();
9769 let mut refold_creases = Vec::new();
9770
9771 let selections = self.selections.all::<Point>(cx);
9772 let mut selections = selections.iter().peekable();
9773 let mut contiguous_row_selections = Vec::new();
9774 let mut new_selections = Vec::new();
9775
9776 while let Some(selection) = selections.next() {
9777 // Find all the selections that span a contiguous row range
9778 let (start_row, end_row) = consume_contiguous_rows(
9779 &mut contiguous_row_selections,
9780 selection,
9781 &display_map,
9782 &mut selections,
9783 );
9784
9785 // Move the text spanned by the row range to be before the line preceding the row range
9786 if start_row.0 > 0 {
9787 let range_to_move = Point::new(
9788 start_row.previous_row().0,
9789 buffer.line_len(start_row.previous_row()),
9790 )
9791 ..Point::new(
9792 end_row.previous_row().0,
9793 buffer.line_len(end_row.previous_row()),
9794 );
9795 let insertion_point = display_map
9796 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9797 .0;
9798
9799 // Don't move lines across excerpts
9800 if buffer
9801 .excerpt_containing(insertion_point..range_to_move.end)
9802 .is_some()
9803 {
9804 let text = buffer
9805 .text_for_range(range_to_move.clone())
9806 .flat_map(|s| s.chars())
9807 .skip(1)
9808 .chain(['\n'])
9809 .collect::<String>();
9810
9811 edits.push((
9812 buffer.anchor_after(range_to_move.start)
9813 ..buffer.anchor_before(range_to_move.end),
9814 String::new(),
9815 ));
9816 let insertion_anchor = buffer.anchor_after(insertion_point);
9817 edits.push((insertion_anchor..insertion_anchor, text));
9818
9819 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9820
9821 // Move selections up
9822 new_selections.extend(contiguous_row_selections.drain(..).map(
9823 |mut selection| {
9824 selection.start.row -= row_delta;
9825 selection.end.row -= row_delta;
9826 selection
9827 },
9828 ));
9829
9830 // Move folds up
9831 unfold_ranges.push(range_to_move.clone());
9832 for fold in display_map.folds_in_range(
9833 buffer.anchor_before(range_to_move.start)
9834 ..buffer.anchor_after(range_to_move.end),
9835 ) {
9836 let mut start = fold.range.start.to_point(&buffer);
9837 let mut end = fold.range.end.to_point(&buffer);
9838 start.row -= row_delta;
9839 end.row -= row_delta;
9840 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9841 }
9842 }
9843 }
9844
9845 // If we didn't move line(s), preserve the existing selections
9846 new_selections.append(&mut contiguous_row_selections);
9847 }
9848
9849 self.transact(window, cx, |this, window, cx| {
9850 this.unfold_ranges(&unfold_ranges, true, true, cx);
9851 this.buffer.update(cx, |buffer, cx| {
9852 for (range, text) in edits {
9853 buffer.edit([(range, text)], None, cx);
9854 }
9855 });
9856 this.fold_creases(refold_creases, true, window, cx);
9857 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9858 s.select(new_selections);
9859 })
9860 });
9861 }
9862
9863 pub fn move_line_down(
9864 &mut self,
9865 _: &MoveLineDown,
9866 window: &mut Window,
9867 cx: &mut Context<Self>,
9868 ) {
9869 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9870
9871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9872 let buffer = self.buffer.read(cx).snapshot(cx);
9873
9874 let mut edits = Vec::new();
9875 let mut unfold_ranges = Vec::new();
9876 let mut refold_creases = Vec::new();
9877
9878 let selections = self.selections.all::<Point>(cx);
9879 let mut selections = selections.iter().peekable();
9880 let mut contiguous_row_selections = Vec::new();
9881 let mut new_selections = Vec::new();
9882
9883 while let Some(selection) = selections.next() {
9884 // Find all the selections that span a contiguous row range
9885 let (start_row, end_row) = consume_contiguous_rows(
9886 &mut contiguous_row_selections,
9887 selection,
9888 &display_map,
9889 &mut selections,
9890 );
9891
9892 // Move the text spanned by the row range to be after the last line of the row range
9893 if end_row.0 <= buffer.max_point().row {
9894 let range_to_move =
9895 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9896 let insertion_point = display_map
9897 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9898 .0;
9899
9900 // Don't move lines across excerpt boundaries
9901 if buffer
9902 .excerpt_containing(range_to_move.start..insertion_point)
9903 .is_some()
9904 {
9905 let mut text = String::from("\n");
9906 text.extend(buffer.text_for_range(range_to_move.clone()));
9907 text.pop(); // Drop trailing newline
9908 edits.push((
9909 buffer.anchor_after(range_to_move.start)
9910 ..buffer.anchor_before(range_to_move.end),
9911 String::new(),
9912 ));
9913 let insertion_anchor = buffer.anchor_after(insertion_point);
9914 edits.push((insertion_anchor..insertion_anchor, text));
9915
9916 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9917
9918 // Move selections down
9919 new_selections.extend(contiguous_row_selections.drain(..).map(
9920 |mut selection| {
9921 selection.start.row += row_delta;
9922 selection.end.row += row_delta;
9923 selection
9924 },
9925 ));
9926
9927 // Move folds down
9928 unfold_ranges.push(range_to_move.clone());
9929 for fold in display_map.folds_in_range(
9930 buffer.anchor_before(range_to_move.start)
9931 ..buffer.anchor_after(range_to_move.end),
9932 ) {
9933 let mut start = fold.range.start.to_point(&buffer);
9934 let mut end = fold.range.end.to_point(&buffer);
9935 start.row += row_delta;
9936 end.row += row_delta;
9937 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9938 }
9939 }
9940 }
9941
9942 // If we didn't move line(s), preserve the existing selections
9943 new_selections.append(&mut contiguous_row_selections);
9944 }
9945
9946 self.transact(window, cx, |this, window, cx| {
9947 this.unfold_ranges(&unfold_ranges, true, true, cx);
9948 this.buffer.update(cx, |buffer, cx| {
9949 for (range, text) in edits {
9950 buffer.edit([(range, text)], None, cx);
9951 }
9952 });
9953 this.fold_creases(refold_creases, true, window, cx);
9954 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9955 s.select(new_selections)
9956 });
9957 });
9958 }
9959
9960 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9961 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9962 let text_layout_details = &self.text_layout_details(window);
9963 self.transact(window, cx, |this, window, cx| {
9964 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9965 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9966 s.move_with(|display_map, selection| {
9967 if !selection.is_empty() {
9968 return;
9969 }
9970
9971 let mut head = selection.head();
9972 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9973 if head.column() == display_map.line_len(head.row()) {
9974 transpose_offset = display_map
9975 .buffer_snapshot
9976 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9977 }
9978
9979 if transpose_offset == 0 {
9980 return;
9981 }
9982
9983 *head.column_mut() += 1;
9984 head = display_map.clip_point(head, Bias::Right);
9985 let goal = SelectionGoal::HorizontalPosition(
9986 display_map
9987 .x_for_display_point(head, text_layout_details)
9988 .into(),
9989 );
9990 selection.collapse_to(head, goal);
9991
9992 let transpose_start = display_map
9993 .buffer_snapshot
9994 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9995 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9996 let transpose_end = display_map
9997 .buffer_snapshot
9998 .clip_offset(transpose_offset + 1, Bias::Right);
9999 if let Some(ch) =
10000 display_map.buffer_snapshot.chars_at(transpose_start).next()
10001 {
10002 edits.push((transpose_start..transpose_offset, String::new()));
10003 edits.push((transpose_end..transpose_end, ch.to_string()));
10004 }
10005 }
10006 });
10007 edits
10008 });
10009 this.buffer
10010 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10011 let selections = this.selections.all::<usize>(cx);
10012 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10013 s.select(selections);
10014 });
10015 });
10016 }
10017
10018 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10019 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10020 self.rewrap_impl(RewrapOptions::default(), cx)
10021 }
10022
10023 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10024 let buffer = self.buffer.read(cx).snapshot(cx);
10025 let selections = self.selections.all::<Point>(cx);
10026 let mut selections = selections.iter().peekable();
10027
10028 let mut edits = Vec::new();
10029 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10030
10031 while let Some(selection) = selections.next() {
10032 let mut start_row = selection.start.row;
10033 let mut end_row = selection.end.row;
10034
10035 // Skip selections that overlap with a range that has already been rewrapped.
10036 let selection_range = start_row..end_row;
10037 if rewrapped_row_ranges
10038 .iter()
10039 .any(|range| range.overlaps(&selection_range))
10040 {
10041 continue;
10042 }
10043
10044 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10045
10046 // Since not all lines in the selection may be at the same indent
10047 // level, choose the indent size that is the most common between all
10048 // of the lines.
10049 //
10050 // If there is a tie, we use the deepest indent.
10051 let (indent_size, indent_end) = {
10052 let mut indent_size_occurrences = HashMap::default();
10053 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10054
10055 for row in start_row..=end_row {
10056 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10057 rows_by_indent_size.entry(indent).or_default().push(row);
10058 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10059 }
10060
10061 let indent_size = indent_size_occurrences
10062 .into_iter()
10063 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10064 .map(|(indent, _)| indent)
10065 .unwrap_or_default();
10066 let row = rows_by_indent_size[&indent_size][0];
10067 let indent_end = Point::new(row, indent_size.len);
10068
10069 (indent_size, indent_end)
10070 };
10071
10072 let mut line_prefix = indent_size.chars().collect::<String>();
10073
10074 let mut inside_comment = false;
10075 if let Some(comment_prefix) =
10076 buffer
10077 .language_scope_at(selection.head())
10078 .and_then(|language| {
10079 language
10080 .line_comment_prefixes()
10081 .iter()
10082 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10083 .cloned()
10084 })
10085 {
10086 line_prefix.push_str(&comment_prefix);
10087 inside_comment = true;
10088 }
10089
10090 let language_settings = buffer.language_settings_at(selection.head(), cx);
10091 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10092 RewrapBehavior::InComments => inside_comment,
10093 RewrapBehavior::InSelections => !selection.is_empty(),
10094 RewrapBehavior::Anywhere => true,
10095 };
10096
10097 let should_rewrap = options.override_language_settings
10098 || allow_rewrap_based_on_language
10099 || self.hard_wrap.is_some();
10100 if !should_rewrap {
10101 continue;
10102 }
10103
10104 if selection.is_empty() {
10105 'expand_upwards: while start_row > 0 {
10106 let prev_row = start_row - 1;
10107 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10108 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10109 {
10110 start_row = prev_row;
10111 } else {
10112 break 'expand_upwards;
10113 }
10114 }
10115
10116 'expand_downwards: while end_row < buffer.max_point().row {
10117 let next_row = end_row + 1;
10118 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10119 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10120 {
10121 end_row = next_row;
10122 } else {
10123 break 'expand_downwards;
10124 }
10125 }
10126 }
10127
10128 let start = Point::new(start_row, 0);
10129 let start_offset = start.to_offset(&buffer);
10130 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10131 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10132 let Some(lines_without_prefixes) = selection_text
10133 .lines()
10134 .map(|line| {
10135 line.strip_prefix(&line_prefix)
10136 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10137 .ok_or_else(|| {
10138 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10139 })
10140 })
10141 .collect::<Result<Vec<_>, _>>()
10142 .log_err()
10143 else {
10144 continue;
10145 };
10146
10147 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10148 buffer
10149 .language_settings_at(Point::new(start_row, 0), cx)
10150 .preferred_line_length as usize
10151 });
10152 let wrapped_text = wrap_with_prefix(
10153 line_prefix,
10154 lines_without_prefixes.join("\n"),
10155 wrap_column,
10156 tab_size,
10157 options.preserve_existing_whitespace,
10158 );
10159
10160 // TODO: should always use char-based diff while still supporting cursor behavior that
10161 // matches vim.
10162 let mut diff_options = DiffOptions::default();
10163 if options.override_language_settings {
10164 diff_options.max_word_diff_len = 0;
10165 diff_options.max_word_diff_line_count = 0;
10166 } else {
10167 diff_options.max_word_diff_len = usize::MAX;
10168 diff_options.max_word_diff_line_count = usize::MAX;
10169 }
10170
10171 for (old_range, new_text) in
10172 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10173 {
10174 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10175 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10176 edits.push((edit_start..edit_end, new_text));
10177 }
10178
10179 rewrapped_row_ranges.push(start_row..=end_row);
10180 }
10181
10182 self.buffer
10183 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10184 }
10185
10186 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10187 let mut text = String::new();
10188 let buffer = self.buffer.read(cx).snapshot(cx);
10189 let mut selections = self.selections.all::<Point>(cx);
10190 let mut clipboard_selections = Vec::with_capacity(selections.len());
10191 {
10192 let max_point = buffer.max_point();
10193 let mut is_first = true;
10194 for selection in &mut selections {
10195 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10196 if is_entire_line {
10197 selection.start = Point::new(selection.start.row, 0);
10198 if !selection.is_empty() && selection.end.column == 0 {
10199 selection.end = cmp::min(max_point, selection.end);
10200 } else {
10201 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10202 }
10203 selection.goal = SelectionGoal::None;
10204 }
10205 if is_first {
10206 is_first = false;
10207 } else {
10208 text += "\n";
10209 }
10210 let mut len = 0;
10211 for chunk in buffer.text_for_range(selection.start..selection.end) {
10212 text.push_str(chunk);
10213 len += chunk.len();
10214 }
10215 clipboard_selections.push(ClipboardSelection {
10216 len,
10217 is_entire_line,
10218 first_line_indent: buffer
10219 .indent_size_for_line(MultiBufferRow(selection.start.row))
10220 .len,
10221 });
10222 }
10223 }
10224
10225 self.transact(window, cx, |this, window, cx| {
10226 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10227 s.select(selections);
10228 });
10229 this.insert("", window, cx);
10230 });
10231 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10232 }
10233
10234 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10235 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10236 let item = self.cut_common(window, cx);
10237 cx.write_to_clipboard(item);
10238 }
10239
10240 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10241 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10242 self.change_selections(None, window, cx, |s| {
10243 s.move_with(|snapshot, sel| {
10244 if sel.is_empty() {
10245 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10246 }
10247 });
10248 });
10249 let item = self.cut_common(window, cx);
10250 cx.set_global(KillRing(item))
10251 }
10252
10253 pub fn kill_ring_yank(
10254 &mut self,
10255 _: &KillRingYank,
10256 window: &mut Window,
10257 cx: &mut Context<Self>,
10258 ) {
10259 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10260 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10261 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10262 (kill_ring.text().to_string(), kill_ring.metadata_json())
10263 } else {
10264 return;
10265 }
10266 } else {
10267 return;
10268 };
10269 self.do_paste(&text, metadata, false, window, cx);
10270 }
10271
10272 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10273 self.do_copy(true, cx);
10274 }
10275
10276 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10277 self.do_copy(false, cx);
10278 }
10279
10280 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10281 let selections = self.selections.all::<Point>(cx);
10282 let buffer = self.buffer.read(cx).read(cx);
10283 let mut text = String::new();
10284
10285 let mut clipboard_selections = Vec::with_capacity(selections.len());
10286 {
10287 let max_point = buffer.max_point();
10288 let mut is_first = true;
10289 for selection in &selections {
10290 let mut start = selection.start;
10291 let mut end = selection.end;
10292 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10293 if is_entire_line {
10294 start = Point::new(start.row, 0);
10295 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10296 }
10297
10298 let mut trimmed_selections = Vec::new();
10299 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10300 let row = MultiBufferRow(start.row);
10301 let first_indent = buffer.indent_size_for_line(row);
10302 if first_indent.len == 0 || start.column > first_indent.len {
10303 trimmed_selections.push(start..end);
10304 } else {
10305 trimmed_selections.push(
10306 Point::new(row.0, first_indent.len)
10307 ..Point::new(row.0, buffer.line_len(row)),
10308 );
10309 for row in start.row + 1..=end.row {
10310 let mut line_len = buffer.line_len(MultiBufferRow(row));
10311 if row == end.row {
10312 line_len = end.column;
10313 }
10314 if line_len == 0 {
10315 trimmed_selections
10316 .push(Point::new(row, 0)..Point::new(row, line_len));
10317 continue;
10318 }
10319 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10320 if row_indent_size.len >= first_indent.len {
10321 trimmed_selections.push(
10322 Point::new(row, first_indent.len)..Point::new(row, line_len),
10323 );
10324 } else {
10325 trimmed_selections.clear();
10326 trimmed_selections.push(start..end);
10327 break;
10328 }
10329 }
10330 }
10331 } else {
10332 trimmed_selections.push(start..end);
10333 }
10334
10335 for trimmed_range in trimmed_selections {
10336 if is_first {
10337 is_first = false;
10338 } else {
10339 text += "\n";
10340 }
10341 let mut len = 0;
10342 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10343 text.push_str(chunk);
10344 len += chunk.len();
10345 }
10346 clipboard_selections.push(ClipboardSelection {
10347 len,
10348 is_entire_line,
10349 first_line_indent: buffer
10350 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10351 .len,
10352 });
10353 }
10354 }
10355 }
10356
10357 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10358 text,
10359 clipboard_selections,
10360 ));
10361 }
10362
10363 pub fn do_paste(
10364 &mut self,
10365 text: &String,
10366 clipboard_selections: Option<Vec<ClipboardSelection>>,
10367 handle_entire_lines: bool,
10368 window: &mut Window,
10369 cx: &mut Context<Self>,
10370 ) {
10371 if self.read_only(cx) {
10372 return;
10373 }
10374
10375 let clipboard_text = Cow::Borrowed(text);
10376
10377 self.transact(window, cx, |this, window, cx| {
10378 if let Some(mut clipboard_selections) = clipboard_selections {
10379 let old_selections = this.selections.all::<usize>(cx);
10380 let all_selections_were_entire_line =
10381 clipboard_selections.iter().all(|s| s.is_entire_line);
10382 let first_selection_indent_column =
10383 clipboard_selections.first().map(|s| s.first_line_indent);
10384 if clipboard_selections.len() != old_selections.len() {
10385 clipboard_selections.drain(..);
10386 }
10387 let cursor_offset = this.selections.last::<usize>(cx).head();
10388 let mut auto_indent_on_paste = true;
10389
10390 this.buffer.update(cx, |buffer, cx| {
10391 let snapshot = buffer.read(cx);
10392 auto_indent_on_paste = snapshot
10393 .language_settings_at(cursor_offset, cx)
10394 .auto_indent_on_paste;
10395
10396 let mut start_offset = 0;
10397 let mut edits = Vec::new();
10398 let mut original_indent_columns = Vec::new();
10399 for (ix, selection) in old_selections.iter().enumerate() {
10400 let to_insert;
10401 let entire_line;
10402 let original_indent_column;
10403 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10404 let end_offset = start_offset + clipboard_selection.len;
10405 to_insert = &clipboard_text[start_offset..end_offset];
10406 entire_line = clipboard_selection.is_entire_line;
10407 start_offset = end_offset + 1;
10408 original_indent_column = Some(clipboard_selection.first_line_indent);
10409 } else {
10410 to_insert = clipboard_text.as_str();
10411 entire_line = all_selections_were_entire_line;
10412 original_indent_column = first_selection_indent_column
10413 }
10414
10415 // If the corresponding selection was empty when this slice of the
10416 // clipboard text was written, then the entire line containing the
10417 // selection was copied. If this selection is also currently empty,
10418 // then paste the line before the current line of the buffer.
10419 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10420 let column = selection.start.to_point(&snapshot).column as usize;
10421 let line_start = selection.start - column;
10422 line_start..line_start
10423 } else {
10424 selection.range()
10425 };
10426
10427 edits.push((range, to_insert));
10428 original_indent_columns.push(original_indent_column);
10429 }
10430 drop(snapshot);
10431
10432 buffer.edit(
10433 edits,
10434 if auto_indent_on_paste {
10435 Some(AutoindentMode::Block {
10436 original_indent_columns,
10437 })
10438 } else {
10439 None
10440 },
10441 cx,
10442 );
10443 });
10444
10445 let selections = this.selections.all::<usize>(cx);
10446 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10447 s.select(selections)
10448 });
10449 } else {
10450 this.insert(&clipboard_text, window, cx);
10451 }
10452 });
10453 }
10454
10455 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10456 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10457 if let Some(item) = cx.read_from_clipboard() {
10458 let entries = item.entries();
10459
10460 match entries.first() {
10461 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10462 // of all the pasted entries.
10463 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10464 .do_paste(
10465 clipboard_string.text(),
10466 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10467 true,
10468 window,
10469 cx,
10470 ),
10471 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10472 }
10473 }
10474 }
10475
10476 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10477 if self.read_only(cx) {
10478 return;
10479 }
10480
10481 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10482
10483 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10484 if let Some((selections, _)) =
10485 self.selection_history.transaction(transaction_id).cloned()
10486 {
10487 self.change_selections(None, window, cx, |s| {
10488 s.select_anchors(selections.to_vec());
10489 });
10490 } else {
10491 log::error!(
10492 "No entry in selection_history found for undo. \
10493 This may correspond to a bug where undo does not update the selection. \
10494 If this is occurring, please add details to \
10495 https://github.com/zed-industries/zed/issues/22692"
10496 );
10497 }
10498 self.request_autoscroll(Autoscroll::fit(), cx);
10499 self.unmark_text(window, cx);
10500 self.refresh_inline_completion(true, false, window, cx);
10501 cx.emit(EditorEvent::Edited { transaction_id });
10502 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10503 }
10504 }
10505
10506 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10507 if self.read_only(cx) {
10508 return;
10509 }
10510
10511 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10512
10513 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10514 if let Some((_, Some(selections))) =
10515 self.selection_history.transaction(transaction_id).cloned()
10516 {
10517 self.change_selections(None, window, cx, |s| {
10518 s.select_anchors(selections.to_vec());
10519 });
10520 } else {
10521 log::error!(
10522 "No entry in selection_history found for redo. \
10523 This may correspond to a bug where undo does not update the selection. \
10524 If this is occurring, please add details to \
10525 https://github.com/zed-industries/zed/issues/22692"
10526 );
10527 }
10528 self.request_autoscroll(Autoscroll::fit(), cx);
10529 self.unmark_text(window, cx);
10530 self.refresh_inline_completion(true, false, window, cx);
10531 cx.emit(EditorEvent::Edited { transaction_id });
10532 }
10533 }
10534
10535 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10536 self.buffer
10537 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10538 }
10539
10540 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10541 self.buffer
10542 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10543 }
10544
10545 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10546 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10547 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10548 s.move_with(|map, selection| {
10549 let cursor = if selection.is_empty() {
10550 movement::left(map, selection.start)
10551 } else {
10552 selection.start
10553 };
10554 selection.collapse_to(cursor, SelectionGoal::None);
10555 });
10556 })
10557 }
10558
10559 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10560 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10561 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10562 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10563 })
10564 }
10565
10566 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10567 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10568 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10569 s.move_with(|map, selection| {
10570 let cursor = if selection.is_empty() {
10571 movement::right(map, selection.end)
10572 } else {
10573 selection.end
10574 };
10575 selection.collapse_to(cursor, SelectionGoal::None)
10576 });
10577 })
10578 }
10579
10580 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10581 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10582 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10583 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10584 })
10585 }
10586
10587 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10588 if self.take_rename(true, window, cx).is_some() {
10589 return;
10590 }
10591
10592 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10593 cx.propagate();
10594 return;
10595 }
10596
10597 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10598
10599 let text_layout_details = &self.text_layout_details(window);
10600 let selection_count = self.selections.count();
10601 let first_selection = self.selections.first_anchor();
10602
10603 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10604 s.move_with(|map, selection| {
10605 if !selection.is_empty() {
10606 selection.goal = SelectionGoal::None;
10607 }
10608 let (cursor, goal) = movement::up(
10609 map,
10610 selection.start,
10611 selection.goal,
10612 false,
10613 text_layout_details,
10614 );
10615 selection.collapse_to(cursor, goal);
10616 });
10617 });
10618
10619 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10620 {
10621 cx.propagate();
10622 }
10623 }
10624
10625 pub fn move_up_by_lines(
10626 &mut self,
10627 action: &MoveUpByLines,
10628 window: &mut Window,
10629 cx: &mut Context<Self>,
10630 ) {
10631 if self.take_rename(true, window, cx).is_some() {
10632 return;
10633 }
10634
10635 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10636 cx.propagate();
10637 return;
10638 }
10639
10640 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10641
10642 let text_layout_details = &self.text_layout_details(window);
10643
10644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10645 s.move_with(|map, selection| {
10646 if !selection.is_empty() {
10647 selection.goal = SelectionGoal::None;
10648 }
10649 let (cursor, goal) = movement::up_by_rows(
10650 map,
10651 selection.start,
10652 action.lines,
10653 selection.goal,
10654 false,
10655 text_layout_details,
10656 );
10657 selection.collapse_to(cursor, goal);
10658 });
10659 })
10660 }
10661
10662 pub fn move_down_by_lines(
10663 &mut self,
10664 action: &MoveDownByLines,
10665 window: &mut Window,
10666 cx: &mut Context<Self>,
10667 ) {
10668 if self.take_rename(true, window, cx).is_some() {
10669 return;
10670 }
10671
10672 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10673 cx.propagate();
10674 return;
10675 }
10676
10677 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10678
10679 let text_layout_details = &self.text_layout_details(window);
10680
10681 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10682 s.move_with(|map, selection| {
10683 if !selection.is_empty() {
10684 selection.goal = SelectionGoal::None;
10685 }
10686 let (cursor, goal) = movement::down_by_rows(
10687 map,
10688 selection.start,
10689 action.lines,
10690 selection.goal,
10691 false,
10692 text_layout_details,
10693 );
10694 selection.collapse_to(cursor, goal);
10695 });
10696 })
10697 }
10698
10699 pub fn select_down_by_lines(
10700 &mut self,
10701 action: &SelectDownByLines,
10702 window: &mut Window,
10703 cx: &mut Context<Self>,
10704 ) {
10705 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10706 let text_layout_details = &self.text_layout_details(window);
10707 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10708 s.move_heads_with(|map, head, goal| {
10709 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10710 })
10711 })
10712 }
10713
10714 pub fn select_up_by_lines(
10715 &mut self,
10716 action: &SelectUpByLines,
10717 window: &mut Window,
10718 cx: &mut Context<Self>,
10719 ) {
10720 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10721 let text_layout_details = &self.text_layout_details(window);
10722 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10723 s.move_heads_with(|map, head, goal| {
10724 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10725 })
10726 })
10727 }
10728
10729 pub fn select_page_up(
10730 &mut self,
10731 _: &SelectPageUp,
10732 window: &mut Window,
10733 cx: &mut Context<Self>,
10734 ) {
10735 let Some(row_count) = self.visible_row_count() else {
10736 return;
10737 };
10738
10739 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10740
10741 let text_layout_details = &self.text_layout_details(window);
10742
10743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10744 s.move_heads_with(|map, head, goal| {
10745 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10746 })
10747 })
10748 }
10749
10750 pub fn move_page_up(
10751 &mut self,
10752 action: &MovePageUp,
10753 window: &mut Window,
10754 cx: &mut Context<Self>,
10755 ) {
10756 if self.take_rename(true, window, cx).is_some() {
10757 return;
10758 }
10759
10760 if self
10761 .context_menu
10762 .borrow_mut()
10763 .as_mut()
10764 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10765 .unwrap_or(false)
10766 {
10767 return;
10768 }
10769
10770 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10771 cx.propagate();
10772 return;
10773 }
10774
10775 let Some(row_count) = self.visible_row_count() else {
10776 return;
10777 };
10778
10779 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10780
10781 let autoscroll = if action.center_cursor {
10782 Autoscroll::center()
10783 } else {
10784 Autoscroll::fit()
10785 };
10786
10787 let text_layout_details = &self.text_layout_details(window);
10788
10789 self.change_selections(Some(autoscroll), window, cx, |s| {
10790 s.move_with(|map, selection| {
10791 if !selection.is_empty() {
10792 selection.goal = SelectionGoal::None;
10793 }
10794 let (cursor, goal) = movement::up_by_rows(
10795 map,
10796 selection.end,
10797 row_count,
10798 selection.goal,
10799 false,
10800 text_layout_details,
10801 );
10802 selection.collapse_to(cursor, goal);
10803 });
10804 });
10805 }
10806
10807 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10808 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10809 let text_layout_details = &self.text_layout_details(window);
10810 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10811 s.move_heads_with(|map, head, goal| {
10812 movement::up(map, head, goal, false, text_layout_details)
10813 })
10814 })
10815 }
10816
10817 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10818 self.take_rename(true, window, cx);
10819
10820 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10821 cx.propagate();
10822 return;
10823 }
10824
10825 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10826
10827 let text_layout_details = &self.text_layout_details(window);
10828 let selection_count = self.selections.count();
10829 let first_selection = self.selections.first_anchor();
10830
10831 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10832 s.move_with(|map, selection| {
10833 if !selection.is_empty() {
10834 selection.goal = SelectionGoal::None;
10835 }
10836 let (cursor, goal) = movement::down(
10837 map,
10838 selection.end,
10839 selection.goal,
10840 false,
10841 text_layout_details,
10842 );
10843 selection.collapse_to(cursor, goal);
10844 });
10845 });
10846
10847 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10848 {
10849 cx.propagate();
10850 }
10851 }
10852
10853 pub fn select_page_down(
10854 &mut self,
10855 _: &SelectPageDown,
10856 window: &mut Window,
10857 cx: &mut Context<Self>,
10858 ) {
10859 let Some(row_count) = self.visible_row_count() else {
10860 return;
10861 };
10862
10863 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10864
10865 let text_layout_details = &self.text_layout_details(window);
10866
10867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10868 s.move_heads_with(|map, head, goal| {
10869 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10870 })
10871 })
10872 }
10873
10874 pub fn move_page_down(
10875 &mut self,
10876 action: &MovePageDown,
10877 window: &mut Window,
10878 cx: &mut Context<Self>,
10879 ) {
10880 if self.take_rename(true, window, cx).is_some() {
10881 return;
10882 }
10883
10884 if self
10885 .context_menu
10886 .borrow_mut()
10887 .as_mut()
10888 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10889 .unwrap_or(false)
10890 {
10891 return;
10892 }
10893
10894 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10895 cx.propagate();
10896 return;
10897 }
10898
10899 let Some(row_count) = self.visible_row_count() else {
10900 return;
10901 };
10902
10903 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10904
10905 let autoscroll = if action.center_cursor {
10906 Autoscroll::center()
10907 } else {
10908 Autoscroll::fit()
10909 };
10910
10911 let text_layout_details = &self.text_layout_details(window);
10912 self.change_selections(Some(autoscroll), window, cx, |s| {
10913 s.move_with(|map, selection| {
10914 if !selection.is_empty() {
10915 selection.goal = SelectionGoal::None;
10916 }
10917 let (cursor, goal) = movement::down_by_rows(
10918 map,
10919 selection.end,
10920 row_count,
10921 selection.goal,
10922 false,
10923 text_layout_details,
10924 );
10925 selection.collapse_to(cursor, goal);
10926 });
10927 });
10928 }
10929
10930 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10931 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10932 let text_layout_details = &self.text_layout_details(window);
10933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10934 s.move_heads_with(|map, head, goal| {
10935 movement::down(map, head, goal, false, text_layout_details)
10936 })
10937 });
10938 }
10939
10940 pub fn context_menu_first(
10941 &mut self,
10942 _: &ContextMenuFirst,
10943 _window: &mut Window,
10944 cx: &mut Context<Self>,
10945 ) {
10946 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10947 context_menu.select_first(self.completion_provider.as_deref(), cx);
10948 }
10949 }
10950
10951 pub fn context_menu_prev(
10952 &mut self,
10953 _: &ContextMenuPrevious,
10954 _window: &mut Window,
10955 cx: &mut Context<Self>,
10956 ) {
10957 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10958 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10959 }
10960 }
10961
10962 pub fn context_menu_next(
10963 &mut self,
10964 _: &ContextMenuNext,
10965 _window: &mut Window,
10966 cx: &mut Context<Self>,
10967 ) {
10968 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10969 context_menu.select_next(self.completion_provider.as_deref(), cx);
10970 }
10971 }
10972
10973 pub fn context_menu_last(
10974 &mut self,
10975 _: &ContextMenuLast,
10976 _window: &mut Window,
10977 cx: &mut Context<Self>,
10978 ) {
10979 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10980 context_menu.select_last(self.completion_provider.as_deref(), cx);
10981 }
10982 }
10983
10984 pub fn move_to_previous_word_start(
10985 &mut self,
10986 _: &MoveToPreviousWordStart,
10987 window: &mut Window,
10988 cx: &mut Context<Self>,
10989 ) {
10990 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10992 s.move_cursors_with(|map, head, _| {
10993 (
10994 movement::previous_word_start(map, head),
10995 SelectionGoal::None,
10996 )
10997 });
10998 })
10999 }
11000
11001 pub fn move_to_previous_subword_start(
11002 &mut self,
11003 _: &MoveToPreviousSubwordStart,
11004 window: &mut Window,
11005 cx: &mut Context<Self>,
11006 ) {
11007 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11008 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11009 s.move_cursors_with(|map, head, _| {
11010 (
11011 movement::previous_subword_start(map, head),
11012 SelectionGoal::None,
11013 )
11014 });
11015 })
11016 }
11017
11018 pub fn select_to_previous_word_start(
11019 &mut self,
11020 _: &SelectToPreviousWordStart,
11021 window: &mut Window,
11022 cx: &mut Context<Self>,
11023 ) {
11024 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11025 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11026 s.move_heads_with(|map, head, _| {
11027 (
11028 movement::previous_word_start(map, head),
11029 SelectionGoal::None,
11030 )
11031 });
11032 })
11033 }
11034
11035 pub fn select_to_previous_subword_start(
11036 &mut self,
11037 _: &SelectToPreviousSubwordStart,
11038 window: &mut Window,
11039 cx: &mut Context<Self>,
11040 ) {
11041 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11042 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11043 s.move_heads_with(|map, head, _| {
11044 (
11045 movement::previous_subword_start(map, head),
11046 SelectionGoal::None,
11047 )
11048 });
11049 })
11050 }
11051
11052 pub fn delete_to_previous_word_start(
11053 &mut self,
11054 action: &DeleteToPreviousWordStart,
11055 window: &mut Window,
11056 cx: &mut Context<Self>,
11057 ) {
11058 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11059 self.transact(window, cx, |this, window, cx| {
11060 this.select_autoclose_pair(window, cx);
11061 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11062 s.move_with(|map, selection| {
11063 if selection.is_empty() {
11064 let cursor = if action.ignore_newlines {
11065 movement::previous_word_start(map, selection.head())
11066 } else {
11067 movement::previous_word_start_or_newline(map, selection.head())
11068 };
11069 selection.set_head(cursor, SelectionGoal::None);
11070 }
11071 });
11072 });
11073 this.insert("", window, cx);
11074 });
11075 }
11076
11077 pub fn delete_to_previous_subword_start(
11078 &mut self,
11079 _: &DeleteToPreviousSubwordStart,
11080 window: &mut Window,
11081 cx: &mut Context<Self>,
11082 ) {
11083 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11084 self.transact(window, cx, |this, window, cx| {
11085 this.select_autoclose_pair(window, cx);
11086 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11087 s.move_with(|map, selection| {
11088 if selection.is_empty() {
11089 let cursor = movement::previous_subword_start(map, selection.head());
11090 selection.set_head(cursor, SelectionGoal::None);
11091 }
11092 });
11093 });
11094 this.insert("", window, cx);
11095 });
11096 }
11097
11098 pub fn move_to_next_word_end(
11099 &mut self,
11100 _: &MoveToNextWordEnd,
11101 window: &mut Window,
11102 cx: &mut Context<Self>,
11103 ) {
11104 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11105 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11106 s.move_cursors_with(|map, head, _| {
11107 (movement::next_word_end(map, head), SelectionGoal::None)
11108 });
11109 })
11110 }
11111
11112 pub fn move_to_next_subword_end(
11113 &mut self,
11114 _: &MoveToNextSubwordEnd,
11115 window: &mut Window,
11116 cx: &mut Context<Self>,
11117 ) {
11118 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11119 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11120 s.move_cursors_with(|map, head, _| {
11121 (movement::next_subword_end(map, head), SelectionGoal::None)
11122 });
11123 })
11124 }
11125
11126 pub fn select_to_next_word_end(
11127 &mut self,
11128 _: &SelectToNextWordEnd,
11129 window: &mut Window,
11130 cx: &mut Context<Self>,
11131 ) {
11132 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11133 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11134 s.move_heads_with(|map, head, _| {
11135 (movement::next_word_end(map, head), SelectionGoal::None)
11136 });
11137 })
11138 }
11139
11140 pub fn select_to_next_subword_end(
11141 &mut self,
11142 _: &SelectToNextSubwordEnd,
11143 window: &mut Window,
11144 cx: &mut Context<Self>,
11145 ) {
11146 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11147 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11148 s.move_heads_with(|map, head, _| {
11149 (movement::next_subword_end(map, head), SelectionGoal::None)
11150 });
11151 })
11152 }
11153
11154 pub fn delete_to_next_word_end(
11155 &mut self,
11156 action: &DeleteToNextWordEnd,
11157 window: &mut Window,
11158 cx: &mut Context<Self>,
11159 ) {
11160 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11161 self.transact(window, cx, |this, window, cx| {
11162 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11163 s.move_with(|map, selection| {
11164 if selection.is_empty() {
11165 let cursor = if action.ignore_newlines {
11166 movement::next_word_end(map, selection.head())
11167 } else {
11168 movement::next_word_end_or_newline(map, selection.head())
11169 };
11170 selection.set_head(cursor, SelectionGoal::None);
11171 }
11172 });
11173 });
11174 this.insert("", window, cx);
11175 });
11176 }
11177
11178 pub fn delete_to_next_subword_end(
11179 &mut self,
11180 _: &DeleteToNextSubwordEnd,
11181 window: &mut Window,
11182 cx: &mut Context<Self>,
11183 ) {
11184 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11185 self.transact(window, cx, |this, window, cx| {
11186 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11187 s.move_with(|map, selection| {
11188 if selection.is_empty() {
11189 let cursor = movement::next_subword_end(map, selection.head());
11190 selection.set_head(cursor, SelectionGoal::None);
11191 }
11192 });
11193 });
11194 this.insert("", window, cx);
11195 });
11196 }
11197
11198 pub fn move_to_beginning_of_line(
11199 &mut self,
11200 action: &MoveToBeginningOfLine,
11201 window: &mut Window,
11202 cx: &mut Context<Self>,
11203 ) {
11204 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11206 s.move_cursors_with(|map, head, _| {
11207 (
11208 movement::indented_line_beginning(
11209 map,
11210 head,
11211 action.stop_at_soft_wraps,
11212 action.stop_at_indent,
11213 ),
11214 SelectionGoal::None,
11215 )
11216 });
11217 })
11218 }
11219
11220 pub fn select_to_beginning_of_line(
11221 &mut self,
11222 action: &SelectToBeginningOfLine,
11223 window: &mut Window,
11224 cx: &mut Context<Self>,
11225 ) {
11226 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11228 s.move_heads_with(|map, head, _| {
11229 (
11230 movement::indented_line_beginning(
11231 map,
11232 head,
11233 action.stop_at_soft_wraps,
11234 action.stop_at_indent,
11235 ),
11236 SelectionGoal::None,
11237 )
11238 });
11239 });
11240 }
11241
11242 pub fn delete_to_beginning_of_line(
11243 &mut self,
11244 action: &DeleteToBeginningOfLine,
11245 window: &mut Window,
11246 cx: &mut Context<Self>,
11247 ) {
11248 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11249 self.transact(window, cx, |this, window, cx| {
11250 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11251 s.move_with(|_, selection| {
11252 selection.reversed = true;
11253 });
11254 });
11255
11256 this.select_to_beginning_of_line(
11257 &SelectToBeginningOfLine {
11258 stop_at_soft_wraps: false,
11259 stop_at_indent: action.stop_at_indent,
11260 },
11261 window,
11262 cx,
11263 );
11264 this.backspace(&Backspace, window, cx);
11265 });
11266 }
11267
11268 pub fn move_to_end_of_line(
11269 &mut self,
11270 action: &MoveToEndOfLine,
11271 window: &mut Window,
11272 cx: &mut Context<Self>,
11273 ) {
11274 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11275 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11276 s.move_cursors_with(|map, head, _| {
11277 (
11278 movement::line_end(map, head, action.stop_at_soft_wraps),
11279 SelectionGoal::None,
11280 )
11281 });
11282 })
11283 }
11284
11285 pub fn select_to_end_of_line(
11286 &mut self,
11287 action: &SelectToEndOfLine,
11288 window: &mut Window,
11289 cx: &mut Context<Self>,
11290 ) {
11291 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11292 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11293 s.move_heads_with(|map, head, _| {
11294 (
11295 movement::line_end(map, head, action.stop_at_soft_wraps),
11296 SelectionGoal::None,
11297 )
11298 });
11299 })
11300 }
11301
11302 pub fn delete_to_end_of_line(
11303 &mut self,
11304 _: &DeleteToEndOfLine,
11305 window: &mut Window,
11306 cx: &mut Context<Self>,
11307 ) {
11308 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11309 self.transact(window, cx, |this, window, cx| {
11310 this.select_to_end_of_line(
11311 &SelectToEndOfLine {
11312 stop_at_soft_wraps: false,
11313 },
11314 window,
11315 cx,
11316 );
11317 this.delete(&Delete, window, cx);
11318 });
11319 }
11320
11321 pub fn cut_to_end_of_line(
11322 &mut self,
11323 _: &CutToEndOfLine,
11324 window: &mut Window,
11325 cx: &mut Context<Self>,
11326 ) {
11327 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11328 self.transact(window, cx, |this, window, cx| {
11329 this.select_to_end_of_line(
11330 &SelectToEndOfLine {
11331 stop_at_soft_wraps: false,
11332 },
11333 window,
11334 cx,
11335 );
11336 this.cut(&Cut, window, cx);
11337 });
11338 }
11339
11340 pub fn move_to_start_of_paragraph(
11341 &mut self,
11342 _: &MoveToStartOfParagraph,
11343 window: &mut Window,
11344 cx: &mut Context<Self>,
11345 ) {
11346 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11347 cx.propagate();
11348 return;
11349 }
11350 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11352 s.move_with(|map, selection| {
11353 selection.collapse_to(
11354 movement::start_of_paragraph(map, selection.head(), 1),
11355 SelectionGoal::None,
11356 )
11357 });
11358 })
11359 }
11360
11361 pub fn move_to_end_of_paragraph(
11362 &mut self,
11363 _: &MoveToEndOfParagraph,
11364 window: &mut Window,
11365 cx: &mut Context<Self>,
11366 ) {
11367 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11368 cx.propagate();
11369 return;
11370 }
11371 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11373 s.move_with(|map, selection| {
11374 selection.collapse_to(
11375 movement::end_of_paragraph(map, selection.head(), 1),
11376 SelectionGoal::None,
11377 )
11378 });
11379 })
11380 }
11381
11382 pub fn select_to_start_of_paragraph(
11383 &mut self,
11384 _: &SelectToStartOfParagraph,
11385 window: &mut Window,
11386 cx: &mut Context<Self>,
11387 ) {
11388 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11389 cx.propagate();
11390 return;
11391 }
11392 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11393 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11394 s.move_heads_with(|map, head, _| {
11395 (
11396 movement::start_of_paragraph(map, head, 1),
11397 SelectionGoal::None,
11398 )
11399 });
11400 })
11401 }
11402
11403 pub fn select_to_end_of_paragraph(
11404 &mut self,
11405 _: &SelectToEndOfParagraph,
11406 window: &mut Window,
11407 cx: &mut Context<Self>,
11408 ) {
11409 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11410 cx.propagate();
11411 return;
11412 }
11413 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11414 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11415 s.move_heads_with(|map, head, _| {
11416 (
11417 movement::end_of_paragraph(map, head, 1),
11418 SelectionGoal::None,
11419 )
11420 });
11421 })
11422 }
11423
11424 pub fn move_to_start_of_excerpt(
11425 &mut self,
11426 _: &MoveToStartOfExcerpt,
11427 window: &mut Window,
11428 cx: &mut Context<Self>,
11429 ) {
11430 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11431 cx.propagate();
11432 return;
11433 }
11434 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11435 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11436 s.move_with(|map, selection| {
11437 selection.collapse_to(
11438 movement::start_of_excerpt(
11439 map,
11440 selection.head(),
11441 workspace::searchable::Direction::Prev,
11442 ),
11443 SelectionGoal::None,
11444 )
11445 });
11446 })
11447 }
11448
11449 pub fn move_to_start_of_next_excerpt(
11450 &mut self,
11451 _: &MoveToStartOfNextExcerpt,
11452 window: &mut Window,
11453 cx: &mut Context<Self>,
11454 ) {
11455 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11456 cx.propagate();
11457 return;
11458 }
11459
11460 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11461 s.move_with(|map, selection| {
11462 selection.collapse_to(
11463 movement::start_of_excerpt(
11464 map,
11465 selection.head(),
11466 workspace::searchable::Direction::Next,
11467 ),
11468 SelectionGoal::None,
11469 )
11470 });
11471 })
11472 }
11473
11474 pub fn move_to_end_of_excerpt(
11475 &mut self,
11476 _: &MoveToEndOfExcerpt,
11477 window: &mut Window,
11478 cx: &mut Context<Self>,
11479 ) {
11480 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11481 cx.propagate();
11482 return;
11483 }
11484 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11485 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11486 s.move_with(|map, selection| {
11487 selection.collapse_to(
11488 movement::end_of_excerpt(
11489 map,
11490 selection.head(),
11491 workspace::searchable::Direction::Next,
11492 ),
11493 SelectionGoal::None,
11494 )
11495 });
11496 })
11497 }
11498
11499 pub fn move_to_end_of_previous_excerpt(
11500 &mut self,
11501 _: &MoveToEndOfPreviousExcerpt,
11502 window: &mut Window,
11503 cx: &mut Context<Self>,
11504 ) {
11505 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11506 cx.propagate();
11507 return;
11508 }
11509 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11510 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11511 s.move_with(|map, selection| {
11512 selection.collapse_to(
11513 movement::end_of_excerpt(
11514 map,
11515 selection.head(),
11516 workspace::searchable::Direction::Prev,
11517 ),
11518 SelectionGoal::None,
11519 )
11520 });
11521 })
11522 }
11523
11524 pub fn select_to_start_of_excerpt(
11525 &mut self,
11526 _: &SelectToStartOfExcerpt,
11527 window: &mut Window,
11528 cx: &mut Context<Self>,
11529 ) {
11530 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11531 cx.propagate();
11532 return;
11533 }
11534 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11535 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11536 s.move_heads_with(|map, head, _| {
11537 (
11538 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11539 SelectionGoal::None,
11540 )
11541 });
11542 })
11543 }
11544
11545 pub fn select_to_start_of_next_excerpt(
11546 &mut self,
11547 _: &SelectToStartOfNextExcerpt,
11548 window: &mut Window,
11549 cx: &mut Context<Self>,
11550 ) {
11551 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11552 cx.propagate();
11553 return;
11554 }
11555 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11556 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11557 s.move_heads_with(|map, head, _| {
11558 (
11559 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11560 SelectionGoal::None,
11561 )
11562 });
11563 })
11564 }
11565
11566 pub fn select_to_end_of_excerpt(
11567 &mut self,
11568 _: &SelectToEndOfExcerpt,
11569 window: &mut Window,
11570 cx: &mut Context<Self>,
11571 ) {
11572 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11573 cx.propagate();
11574 return;
11575 }
11576 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11577 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11578 s.move_heads_with(|map, head, _| {
11579 (
11580 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11581 SelectionGoal::None,
11582 )
11583 });
11584 })
11585 }
11586
11587 pub fn select_to_end_of_previous_excerpt(
11588 &mut self,
11589 _: &SelectToEndOfPreviousExcerpt,
11590 window: &mut Window,
11591 cx: &mut Context<Self>,
11592 ) {
11593 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11594 cx.propagate();
11595 return;
11596 }
11597 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11598 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11599 s.move_heads_with(|map, head, _| {
11600 (
11601 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11602 SelectionGoal::None,
11603 )
11604 });
11605 })
11606 }
11607
11608 pub fn move_to_beginning(
11609 &mut self,
11610 _: &MoveToBeginning,
11611 window: &mut Window,
11612 cx: &mut Context<Self>,
11613 ) {
11614 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11615 cx.propagate();
11616 return;
11617 }
11618 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11619 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11620 s.select_ranges(vec![0..0]);
11621 });
11622 }
11623
11624 pub fn select_to_beginning(
11625 &mut self,
11626 _: &SelectToBeginning,
11627 window: &mut Window,
11628 cx: &mut Context<Self>,
11629 ) {
11630 let mut selection = self.selections.last::<Point>(cx);
11631 selection.set_head(Point::zero(), SelectionGoal::None);
11632 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11633 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11634 s.select(vec![selection]);
11635 });
11636 }
11637
11638 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11639 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11640 cx.propagate();
11641 return;
11642 }
11643 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11644 let cursor = self.buffer.read(cx).read(cx).len();
11645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11646 s.select_ranges(vec![cursor..cursor])
11647 });
11648 }
11649
11650 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11651 self.nav_history = nav_history;
11652 }
11653
11654 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11655 self.nav_history.as_ref()
11656 }
11657
11658 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11659 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11660 }
11661
11662 fn push_to_nav_history(
11663 &mut self,
11664 cursor_anchor: Anchor,
11665 new_position: Option<Point>,
11666 is_deactivate: bool,
11667 cx: &mut Context<Self>,
11668 ) {
11669 if let Some(nav_history) = self.nav_history.as_mut() {
11670 let buffer = self.buffer.read(cx).read(cx);
11671 let cursor_position = cursor_anchor.to_point(&buffer);
11672 let scroll_state = self.scroll_manager.anchor();
11673 let scroll_top_row = scroll_state.top_row(&buffer);
11674 drop(buffer);
11675
11676 if let Some(new_position) = new_position {
11677 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11678 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11679 return;
11680 }
11681 }
11682
11683 nav_history.push(
11684 Some(NavigationData {
11685 cursor_anchor,
11686 cursor_position,
11687 scroll_anchor: scroll_state,
11688 scroll_top_row,
11689 }),
11690 cx,
11691 );
11692 cx.emit(EditorEvent::PushedToNavHistory {
11693 anchor: cursor_anchor,
11694 is_deactivate,
11695 })
11696 }
11697 }
11698
11699 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11700 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11701 let buffer = self.buffer.read(cx).snapshot(cx);
11702 let mut selection = self.selections.first::<usize>(cx);
11703 selection.set_head(buffer.len(), SelectionGoal::None);
11704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11705 s.select(vec![selection]);
11706 });
11707 }
11708
11709 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11710 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11711 let end = self.buffer.read(cx).read(cx).len();
11712 self.change_selections(None, window, cx, |s| {
11713 s.select_ranges(vec![0..end]);
11714 });
11715 }
11716
11717 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11718 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11719 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11720 let mut selections = self.selections.all::<Point>(cx);
11721 let max_point = display_map.buffer_snapshot.max_point();
11722 for selection in &mut selections {
11723 let rows = selection.spanned_rows(true, &display_map);
11724 selection.start = Point::new(rows.start.0, 0);
11725 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11726 selection.reversed = false;
11727 }
11728 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11729 s.select(selections);
11730 });
11731 }
11732
11733 pub fn split_selection_into_lines(
11734 &mut self,
11735 _: &SplitSelectionIntoLines,
11736 window: &mut Window,
11737 cx: &mut Context<Self>,
11738 ) {
11739 let selections = self
11740 .selections
11741 .all::<Point>(cx)
11742 .into_iter()
11743 .map(|selection| selection.start..selection.end)
11744 .collect::<Vec<_>>();
11745 self.unfold_ranges(&selections, true, true, cx);
11746
11747 let mut new_selection_ranges = Vec::new();
11748 {
11749 let buffer = self.buffer.read(cx).read(cx);
11750 for selection in selections {
11751 for row in selection.start.row..selection.end.row {
11752 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11753 new_selection_ranges.push(cursor..cursor);
11754 }
11755
11756 let is_multiline_selection = selection.start.row != selection.end.row;
11757 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11758 // so this action feels more ergonomic when paired with other selection operations
11759 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11760 if !should_skip_last {
11761 new_selection_ranges.push(selection.end..selection.end);
11762 }
11763 }
11764 }
11765 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11766 s.select_ranges(new_selection_ranges);
11767 });
11768 }
11769
11770 pub fn add_selection_above(
11771 &mut self,
11772 _: &AddSelectionAbove,
11773 window: &mut Window,
11774 cx: &mut Context<Self>,
11775 ) {
11776 self.add_selection(true, window, cx);
11777 }
11778
11779 pub fn add_selection_below(
11780 &mut self,
11781 _: &AddSelectionBelow,
11782 window: &mut Window,
11783 cx: &mut Context<Self>,
11784 ) {
11785 self.add_selection(false, window, cx);
11786 }
11787
11788 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11789 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11790
11791 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11792 let mut selections = self.selections.all::<Point>(cx);
11793 let text_layout_details = self.text_layout_details(window);
11794 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11795 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11796 let range = oldest_selection.display_range(&display_map).sorted();
11797
11798 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11799 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11800 let positions = start_x.min(end_x)..start_x.max(end_x);
11801
11802 selections.clear();
11803 let mut stack = Vec::new();
11804 for row in range.start.row().0..=range.end.row().0 {
11805 if let Some(selection) = self.selections.build_columnar_selection(
11806 &display_map,
11807 DisplayRow(row),
11808 &positions,
11809 oldest_selection.reversed,
11810 &text_layout_details,
11811 ) {
11812 stack.push(selection.id);
11813 selections.push(selection);
11814 }
11815 }
11816
11817 if above {
11818 stack.reverse();
11819 }
11820
11821 AddSelectionsState { above, stack }
11822 });
11823
11824 let last_added_selection = *state.stack.last().unwrap();
11825 let mut new_selections = Vec::new();
11826 if above == state.above {
11827 let end_row = if above {
11828 DisplayRow(0)
11829 } else {
11830 display_map.max_point().row()
11831 };
11832
11833 'outer: for selection in selections {
11834 if selection.id == last_added_selection {
11835 let range = selection.display_range(&display_map).sorted();
11836 debug_assert_eq!(range.start.row(), range.end.row());
11837 let mut row = range.start.row();
11838 let positions =
11839 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11840 px(start)..px(end)
11841 } else {
11842 let start_x =
11843 display_map.x_for_display_point(range.start, &text_layout_details);
11844 let end_x =
11845 display_map.x_for_display_point(range.end, &text_layout_details);
11846 start_x.min(end_x)..start_x.max(end_x)
11847 };
11848
11849 while row != end_row {
11850 if above {
11851 row.0 -= 1;
11852 } else {
11853 row.0 += 1;
11854 }
11855
11856 if let Some(new_selection) = self.selections.build_columnar_selection(
11857 &display_map,
11858 row,
11859 &positions,
11860 selection.reversed,
11861 &text_layout_details,
11862 ) {
11863 state.stack.push(new_selection.id);
11864 if above {
11865 new_selections.push(new_selection);
11866 new_selections.push(selection);
11867 } else {
11868 new_selections.push(selection);
11869 new_selections.push(new_selection);
11870 }
11871
11872 continue 'outer;
11873 }
11874 }
11875 }
11876
11877 new_selections.push(selection);
11878 }
11879 } else {
11880 new_selections = selections;
11881 new_selections.retain(|s| s.id != last_added_selection);
11882 state.stack.pop();
11883 }
11884
11885 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11886 s.select(new_selections);
11887 });
11888 if state.stack.len() > 1 {
11889 self.add_selections_state = Some(state);
11890 }
11891 }
11892
11893 pub fn select_next_match_internal(
11894 &mut self,
11895 display_map: &DisplaySnapshot,
11896 replace_newest: bool,
11897 autoscroll: Option<Autoscroll>,
11898 window: &mut Window,
11899 cx: &mut Context<Self>,
11900 ) -> Result<()> {
11901 fn select_next_match_ranges(
11902 this: &mut Editor,
11903 range: Range<usize>,
11904 reversed: bool,
11905 replace_newest: bool,
11906 auto_scroll: Option<Autoscroll>,
11907 window: &mut Window,
11908 cx: &mut Context<Editor>,
11909 ) {
11910 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11911 this.change_selections(auto_scroll, window, cx, |s| {
11912 if replace_newest {
11913 s.delete(s.newest_anchor().id);
11914 }
11915 if reversed {
11916 s.insert_range(range.end..range.start);
11917 } else {
11918 s.insert_range(range);
11919 }
11920 });
11921 }
11922
11923 let buffer = &display_map.buffer_snapshot;
11924 let mut selections = self.selections.all::<usize>(cx);
11925 if let Some(mut select_next_state) = self.select_next_state.take() {
11926 let query = &select_next_state.query;
11927 if !select_next_state.done {
11928 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11929 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11930 let mut next_selected_range = None;
11931
11932 let bytes_after_last_selection =
11933 buffer.bytes_in_range(last_selection.end..buffer.len());
11934 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11935 let query_matches = query
11936 .stream_find_iter(bytes_after_last_selection)
11937 .map(|result| (last_selection.end, result))
11938 .chain(
11939 query
11940 .stream_find_iter(bytes_before_first_selection)
11941 .map(|result| (0, result)),
11942 );
11943
11944 for (start_offset, query_match) in query_matches {
11945 let query_match = query_match.unwrap(); // can only fail due to I/O
11946 let offset_range =
11947 start_offset + query_match.start()..start_offset + query_match.end();
11948 let display_range = offset_range.start.to_display_point(display_map)
11949 ..offset_range.end.to_display_point(display_map);
11950
11951 if !select_next_state.wordwise
11952 || (!movement::is_inside_word(display_map, display_range.start)
11953 && !movement::is_inside_word(display_map, display_range.end))
11954 {
11955 // TODO: This is n^2, because we might check all the selections
11956 if !selections
11957 .iter()
11958 .any(|selection| selection.range().overlaps(&offset_range))
11959 {
11960 next_selected_range = Some(offset_range);
11961 break;
11962 }
11963 }
11964 }
11965
11966 if let Some(next_selected_range) = next_selected_range {
11967 select_next_match_ranges(
11968 self,
11969 next_selected_range,
11970 last_selection.reversed,
11971 replace_newest,
11972 autoscroll,
11973 window,
11974 cx,
11975 );
11976 } else {
11977 select_next_state.done = true;
11978 }
11979 }
11980
11981 self.select_next_state = Some(select_next_state);
11982 } else {
11983 let mut only_carets = true;
11984 let mut same_text_selected = true;
11985 let mut selected_text = None;
11986
11987 let mut selections_iter = selections.iter().peekable();
11988 while let Some(selection) = selections_iter.next() {
11989 if selection.start != selection.end {
11990 only_carets = false;
11991 }
11992
11993 if same_text_selected {
11994 if selected_text.is_none() {
11995 selected_text =
11996 Some(buffer.text_for_range(selection.range()).collect::<String>());
11997 }
11998
11999 if let Some(next_selection) = selections_iter.peek() {
12000 if next_selection.range().len() == selection.range().len() {
12001 let next_selected_text = buffer
12002 .text_for_range(next_selection.range())
12003 .collect::<String>();
12004 if Some(next_selected_text) != selected_text {
12005 same_text_selected = false;
12006 selected_text = None;
12007 }
12008 } else {
12009 same_text_selected = false;
12010 selected_text = None;
12011 }
12012 }
12013 }
12014 }
12015
12016 if only_carets {
12017 for selection in &mut selections {
12018 let word_range = movement::surrounding_word(
12019 display_map,
12020 selection.start.to_display_point(display_map),
12021 );
12022 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12023 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12024 selection.goal = SelectionGoal::None;
12025 selection.reversed = false;
12026 select_next_match_ranges(
12027 self,
12028 selection.start..selection.end,
12029 selection.reversed,
12030 replace_newest,
12031 autoscroll,
12032 window,
12033 cx,
12034 );
12035 }
12036
12037 if selections.len() == 1 {
12038 let selection = selections
12039 .last()
12040 .expect("ensured that there's only one selection");
12041 let query = buffer
12042 .text_for_range(selection.start..selection.end)
12043 .collect::<String>();
12044 let is_empty = query.is_empty();
12045 let select_state = SelectNextState {
12046 query: AhoCorasick::new(&[query])?,
12047 wordwise: true,
12048 done: is_empty,
12049 };
12050 self.select_next_state = Some(select_state);
12051 } else {
12052 self.select_next_state = None;
12053 }
12054 } else if let Some(selected_text) = selected_text {
12055 self.select_next_state = Some(SelectNextState {
12056 query: AhoCorasick::new(&[selected_text])?,
12057 wordwise: false,
12058 done: false,
12059 });
12060 self.select_next_match_internal(
12061 display_map,
12062 replace_newest,
12063 autoscroll,
12064 window,
12065 cx,
12066 )?;
12067 }
12068 }
12069 Ok(())
12070 }
12071
12072 pub fn select_all_matches(
12073 &mut self,
12074 _action: &SelectAllMatches,
12075 window: &mut Window,
12076 cx: &mut Context<Self>,
12077 ) -> Result<()> {
12078 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12079
12080 self.push_to_selection_history();
12081 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12082
12083 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12084 let Some(select_next_state) = self.select_next_state.as_mut() else {
12085 return Ok(());
12086 };
12087 if select_next_state.done {
12088 return Ok(());
12089 }
12090
12091 let mut new_selections = Vec::new();
12092
12093 let reversed = self.selections.oldest::<usize>(cx).reversed;
12094 let buffer = &display_map.buffer_snapshot;
12095 let query_matches = select_next_state
12096 .query
12097 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12098
12099 for query_match in query_matches.into_iter() {
12100 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12101 let offset_range = if reversed {
12102 query_match.end()..query_match.start()
12103 } else {
12104 query_match.start()..query_match.end()
12105 };
12106 let display_range = offset_range.start.to_display_point(&display_map)
12107 ..offset_range.end.to_display_point(&display_map);
12108
12109 if !select_next_state.wordwise
12110 || (!movement::is_inside_word(&display_map, display_range.start)
12111 && !movement::is_inside_word(&display_map, display_range.end))
12112 {
12113 new_selections.push(offset_range.start..offset_range.end);
12114 }
12115 }
12116
12117 select_next_state.done = true;
12118 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12119 self.change_selections(None, window, cx, |selections| {
12120 selections.select_ranges(new_selections)
12121 });
12122
12123 Ok(())
12124 }
12125
12126 pub fn select_next(
12127 &mut self,
12128 action: &SelectNext,
12129 window: &mut Window,
12130 cx: &mut Context<Self>,
12131 ) -> Result<()> {
12132 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12133 self.push_to_selection_history();
12134 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12135 self.select_next_match_internal(
12136 &display_map,
12137 action.replace_newest,
12138 Some(Autoscroll::newest()),
12139 window,
12140 cx,
12141 )?;
12142 Ok(())
12143 }
12144
12145 pub fn select_previous(
12146 &mut self,
12147 action: &SelectPrevious,
12148 window: &mut Window,
12149 cx: &mut Context<Self>,
12150 ) -> Result<()> {
12151 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12152 self.push_to_selection_history();
12153 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12154 let buffer = &display_map.buffer_snapshot;
12155 let mut selections = self.selections.all::<usize>(cx);
12156 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12157 let query = &select_prev_state.query;
12158 if !select_prev_state.done {
12159 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12160 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12161 let mut next_selected_range = None;
12162 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12163 let bytes_before_last_selection =
12164 buffer.reversed_bytes_in_range(0..last_selection.start);
12165 let bytes_after_first_selection =
12166 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12167 let query_matches = query
12168 .stream_find_iter(bytes_before_last_selection)
12169 .map(|result| (last_selection.start, result))
12170 .chain(
12171 query
12172 .stream_find_iter(bytes_after_first_selection)
12173 .map(|result| (buffer.len(), result)),
12174 );
12175 for (end_offset, query_match) in query_matches {
12176 let query_match = query_match.unwrap(); // can only fail due to I/O
12177 let offset_range =
12178 end_offset - query_match.end()..end_offset - query_match.start();
12179 let display_range = offset_range.start.to_display_point(&display_map)
12180 ..offset_range.end.to_display_point(&display_map);
12181
12182 if !select_prev_state.wordwise
12183 || (!movement::is_inside_word(&display_map, display_range.start)
12184 && !movement::is_inside_word(&display_map, display_range.end))
12185 {
12186 next_selected_range = Some(offset_range);
12187 break;
12188 }
12189 }
12190
12191 if let Some(next_selected_range) = next_selected_range {
12192 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12193 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12194 if action.replace_newest {
12195 s.delete(s.newest_anchor().id);
12196 }
12197 if last_selection.reversed {
12198 s.insert_range(next_selected_range.end..next_selected_range.start);
12199 } else {
12200 s.insert_range(next_selected_range);
12201 }
12202 });
12203 } else {
12204 select_prev_state.done = true;
12205 }
12206 }
12207
12208 self.select_prev_state = Some(select_prev_state);
12209 } else {
12210 let mut only_carets = true;
12211 let mut same_text_selected = true;
12212 let mut selected_text = None;
12213
12214 let mut selections_iter = selections.iter().peekable();
12215 while let Some(selection) = selections_iter.next() {
12216 if selection.start != selection.end {
12217 only_carets = false;
12218 }
12219
12220 if same_text_selected {
12221 if selected_text.is_none() {
12222 selected_text =
12223 Some(buffer.text_for_range(selection.range()).collect::<String>());
12224 }
12225
12226 if let Some(next_selection) = selections_iter.peek() {
12227 if next_selection.range().len() == selection.range().len() {
12228 let next_selected_text = buffer
12229 .text_for_range(next_selection.range())
12230 .collect::<String>();
12231 if Some(next_selected_text) != selected_text {
12232 same_text_selected = false;
12233 selected_text = None;
12234 }
12235 } else {
12236 same_text_selected = false;
12237 selected_text = None;
12238 }
12239 }
12240 }
12241 }
12242
12243 if only_carets {
12244 for selection in &mut selections {
12245 let word_range = movement::surrounding_word(
12246 &display_map,
12247 selection.start.to_display_point(&display_map),
12248 );
12249 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12250 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12251 selection.goal = SelectionGoal::None;
12252 selection.reversed = false;
12253 }
12254 if selections.len() == 1 {
12255 let selection = selections
12256 .last()
12257 .expect("ensured that there's only one selection");
12258 let query = buffer
12259 .text_for_range(selection.start..selection.end)
12260 .collect::<String>();
12261 let is_empty = query.is_empty();
12262 let select_state = SelectNextState {
12263 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12264 wordwise: true,
12265 done: is_empty,
12266 };
12267 self.select_prev_state = Some(select_state);
12268 } else {
12269 self.select_prev_state = None;
12270 }
12271
12272 self.unfold_ranges(
12273 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12274 false,
12275 true,
12276 cx,
12277 );
12278 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12279 s.select(selections);
12280 });
12281 } else if let Some(selected_text) = selected_text {
12282 self.select_prev_state = Some(SelectNextState {
12283 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12284 wordwise: false,
12285 done: false,
12286 });
12287 self.select_previous(action, window, cx)?;
12288 }
12289 }
12290 Ok(())
12291 }
12292
12293 pub fn find_next_match(
12294 &mut self,
12295 _: &FindNextMatch,
12296 window: &mut Window,
12297 cx: &mut Context<Self>,
12298 ) -> Result<()> {
12299 let selections = self.selections.disjoint_anchors();
12300 match selections.first() {
12301 Some(first) if selections.len() >= 2 => {
12302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12303 s.select_ranges([first.range()]);
12304 });
12305 }
12306 _ => self.select_next(
12307 &SelectNext {
12308 replace_newest: true,
12309 },
12310 window,
12311 cx,
12312 )?,
12313 }
12314 Ok(())
12315 }
12316
12317 pub fn find_previous_match(
12318 &mut self,
12319 _: &FindPreviousMatch,
12320 window: &mut Window,
12321 cx: &mut Context<Self>,
12322 ) -> Result<()> {
12323 let selections = self.selections.disjoint_anchors();
12324 match selections.last() {
12325 Some(last) if selections.len() >= 2 => {
12326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12327 s.select_ranges([last.range()]);
12328 });
12329 }
12330 _ => self.select_previous(
12331 &SelectPrevious {
12332 replace_newest: true,
12333 },
12334 window,
12335 cx,
12336 )?,
12337 }
12338 Ok(())
12339 }
12340
12341 pub fn toggle_comments(
12342 &mut self,
12343 action: &ToggleComments,
12344 window: &mut Window,
12345 cx: &mut Context<Self>,
12346 ) {
12347 if self.read_only(cx) {
12348 return;
12349 }
12350 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12351 let text_layout_details = &self.text_layout_details(window);
12352 self.transact(window, cx, |this, window, cx| {
12353 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12354 let mut edits = Vec::new();
12355 let mut selection_edit_ranges = Vec::new();
12356 let mut last_toggled_row = None;
12357 let snapshot = this.buffer.read(cx).read(cx);
12358 let empty_str: Arc<str> = Arc::default();
12359 let mut suffixes_inserted = Vec::new();
12360 let ignore_indent = action.ignore_indent;
12361
12362 fn comment_prefix_range(
12363 snapshot: &MultiBufferSnapshot,
12364 row: MultiBufferRow,
12365 comment_prefix: &str,
12366 comment_prefix_whitespace: &str,
12367 ignore_indent: bool,
12368 ) -> Range<Point> {
12369 let indent_size = if ignore_indent {
12370 0
12371 } else {
12372 snapshot.indent_size_for_line(row).len
12373 };
12374
12375 let start = Point::new(row.0, indent_size);
12376
12377 let mut line_bytes = snapshot
12378 .bytes_in_range(start..snapshot.max_point())
12379 .flatten()
12380 .copied();
12381
12382 // If this line currently begins with the line comment prefix, then record
12383 // the range containing the prefix.
12384 if line_bytes
12385 .by_ref()
12386 .take(comment_prefix.len())
12387 .eq(comment_prefix.bytes())
12388 {
12389 // Include any whitespace that matches the comment prefix.
12390 let matching_whitespace_len = line_bytes
12391 .zip(comment_prefix_whitespace.bytes())
12392 .take_while(|(a, b)| a == b)
12393 .count() as u32;
12394 let end = Point::new(
12395 start.row,
12396 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12397 );
12398 start..end
12399 } else {
12400 start..start
12401 }
12402 }
12403
12404 fn comment_suffix_range(
12405 snapshot: &MultiBufferSnapshot,
12406 row: MultiBufferRow,
12407 comment_suffix: &str,
12408 comment_suffix_has_leading_space: bool,
12409 ) -> Range<Point> {
12410 let end = Point::new(row.0, snapshot.line_len(row));
12411 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12412
12413 let mut line_end_bytes = snapshot
12414 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12415 .flatten()
12416 .copied();
12417
12418 let leading_space_len = if suffix_start_column > 0
12419 && line_end_bytes.next() == Some(b' ')
12420 && comment_suffix_has_leading_space
12421 {
12422 1
12423 } else {
12424 0
12425 };
12426
12427 // If this line currently begins with the line comment prefix, then record
12428 // the range containing the prefix.
12429 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12430 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12431 start..end
12432 } else {
12433 end..end
12434 }
12435 }
12436
12437 // TODO: Handle selections that cross excerpts
12438 for selection in &mut selections {
12439 let start_column = snapshot
12440 .indent_size_for_line(MultiBufferRow(selection.start.row))
12441 .len;
12442 let language = if let Some(language) =
12443 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12444 {
12445 language
12446 } else {
12447 continue;
12448 };
12449
12450 selection_edit_ranges.clear();
12451
12452 // If multiple selections contain a given row, avoid processing that
12453 // row more than once.
12454 let mut start_row = MultiBufferRow(selection.start.row);
12455 if last_toggled_row == Some(start_row) {
12456 start_row = start_row.next_row();
12457 }
12458 let end_row =
12459 if selection.end.row > selection.start.row && selection.end.column == 0 {
12460 MultiBufferRow(selection.end.row - 1)
12461 } else {
12462 MultiBufferRow(selection.end.row)
12463 };
12464 last_toggled_row = Some(end_row);
12465
12466 if start_row > end_row {
12467 continue;
12468 }
12469
12470 // If the language has line comments, toggle those.
12471 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12472
12473 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12474 if ignore_indent {
12475 full_comment_prefixes = full_comment_prefixes
12476 .into_iter()
12477 .map(|s| Arc::from(s.trim_end()))
12478 .collect();
12479 }
12480
12481 if !full_comment_prefixes.is_empty() {
12482 let first_prefix = full_comment_prefixes
12483 .first()
12484 .expect("prefixes is non-empty");
12485 let prefix_trimmed_lengths = full_comment_prefixes
12486 .iter()
12487 .map(|p| p.trim_end_matches(' ').len())
12488 .collect::<SmallVec<[usize; 4]>>();
12489
12490 let mut all_selection_lines_are_comments = true;
12491
12492 for row in start_row.0..=end_row.0 {
12493 let row = MultiBufferRow(row);
12494 if start_row < end_row && snapshot.is_line_blank(row) {
12495 continue;
12496 }
12497
12498 let prefix_range = full_comment_prefixes
12499 .iter()
12500 .zip(prefix_trimmed_lengths.iter().copied())
12501 .map(|(prefix, trimmed_prefix_len)| {
12502 comment_prefix_range(
12503 snapshot.deref(),
12504 row,
12505 &prefix[..trimmed_prefix_len],
12506 &prefix[trimmed_prefix_len..],
12507 ignore_indent,
12508 )
12509 })
12510 .max_by_key(|range| range.end.column - range.start.column)
12511 .expect("prefixes is non-empty");
12512
12513 if prefix_range.is_empty() {
12514 all_selection_lines_are_comments = false;
12515 }
12516
12517 selection_edit_ranges.push(prefix_range);
12518 }
12519
12520 if all_selection_lines_are_comments {
12521 edits.extend(
12522 selection_edit_ranges
12523 .iter()
12524 .cloned()
12525 .map(|range| (range, empty_str.clone())),
12526 );
12527 } else {
12528 let min_column = selection_edit_ranges
12529 .iter()
12530 .map(|range| range.start.column)
12531 .min()
12532 .unwrap_or(0);
12533 edits.extend(selection_edit_ranges.iter().map(|range| {
12534 let position = Point::new(range.start.row, min_column);
12535 (position..position, first_prefix.clone())
12536 }));
12537 }
12538 } else if let Some((full_comment_prefix, comment_suffix)) =
12539 language.block_comment_delimiters()
12540 {
12541 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12542 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12543 let prefix_range = comment_prefix_range(
12544 snapshot.deref(),
12545 start_row,
12546 comment_prefix,
12547 comment_prefix_whitespace,
12548 ignore_indent,
12549 );
12550 let suffix_range = comment_suffix_range(
12551 snapshot.deref(),
12552 end_row,
12553 comment_suffix.trim_start_matches(' '),
12554 comment_suffix.starts_with(' '),
12555 );
12556
12557 if prefix_range.is_empty() || suffix_range.is_empty() {
12558 edits.push((
12559 prefix_range.start..prefix_range.start,
12560 full_comment_prefix.clone(),
12561 ));
12562 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12563 suffixes_inserted.push((end_row, comment_suffix.len()));
12564 } else {
12565 edits.push((prefix_range, empty_str.clone()));
12566 edits.push((suffix_range, empty_str.clone()));
12567 }
12568 } else {
12569 continue;
12570 }
12571 }
12572
12573 drop(snapshot);
12574 this.buffer.update(cx, |buffer, cx| {
12575 buffer.edit(edits, None, cx);
12576 });
12577
12578 // Adjust selections so that they end before any comment suffixes that
12579 // were inserted.
12580 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12581 let mut selections = this.selections.all::<Point>(cx);
12582 let snapshot = this.buffer.read(cx).read(cx);
12583 for selection in &mut selections {
12584 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12585 match row.cmp(&MultiBufferRow(selection.end.row)) {
12586 Ordering::Less => {
12587 suffixes_inserted.next();
12588 continue;
12589 }
12590 Ordering::Greater => break,
12591 Ordering::Equal => {
12592 if selection.end.column == snapshot.line_len(row) {
12593 if selection.is_empty() {
12594 selection.start.column -= suffix_len as u32;
12595 }
12596 selection.end.column -= suffix_len as u32;
12597 }
12598 break;
12599 }
12600 }
12601 }
12602 }
12603
12604 drop(snapshot);
12605 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12606 s.select(selections)
12607 });
12608
12609 let selections = this.selections.all::<Point>(cx);
12610 let selections_on_single_row = selections.windows(2).all(|selections| {
12611 selections[0].start.row == selections[1].start.row
12612 && selections[0].end.row == selections[1].end.row
12613 && selections[0].start.row == selections[0].end.row
12614 });
12615 let selections_selecting = selections
12616 .iter()
12617 .any(|selection| selection.start != selection.end);
12618 let advance_downwards = action.advance_downwards
12619 && selections_on_single_row
12620 && !selections_selecting
12621 && !matches!(this.mode, EditorMode::SingleLine { .. });
12622
12623 if advance_downwards {
12624 let snapshot = this.buffer.read(cx).snapshot(cx);
12625
12626 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12627 s.move_cursors_with(|display_snapshot, display_point, _| {
12628 let mut point = display_point.to_point(display_snapshot);
12629 point.row += 1;
12630 point = snapshot.clip_point(point, Bias::Left);
12631 let display_point = point.to_display_point(display_snapshot);
12632 let goal = SelectionGoal::HorizontalPosition(
12633 display_snapshot
12634 .x_for_display_point(display_point, text_layout_details)
12635 .into(),
12636 );
12637 (display_point, goal)
12638 })
12639 });
12640 }
12641 });
12642 }
12643
12644 pub fn select_enclosing_symbol(
12645 &mut self,
12646 _: &SelectEnclosingSymbol,
12647 window: &mut Window,
12648 cx: &mut Context<Self>,
12649 ) {
12650 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12651
12652 let buffer = self.buffer.read(cx).snapshot(cx);
12653 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12654
12655 fn update_selection(
12656 selection: &Selection<usize>,
12657 buffer_snap: &MultiBufferSnapshot,
12658 ) -> Option<Selection<usize>> {
12659 let cursor = selection.head();
12660 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12661 for symbol in symbols.iter().rev() {
12662 let start = symbol.range.start.to_offset(buffer_snap);
12663 let end = symbol.range.end.to_offset(buffer_snap);
12664 let new_range = start..end;
12665 if start < selection.start || end > selection.end {
12666 return Some(Selection {
12667 id: selection.id,
12668 start: new_range.start,
12669 end: new_range.end,
12670 goal: SelectionGoal::None,
12671 reversed: selection.reversed,
12672 });
12673 }
12674 }
12675 None
12676 }
12677
12678 let mut selected_larger_symbol = false;
12679 let new_selections = old_selections
12680 .iter()
12681 .map(|selection| match update_selection(selection, &buffer) {
12682 Some(new_selection) => {
12683 if new_selection.range() != selection.range() {
12684 selected_larger_symbol = true;
12685 }
12686 new_selection
12687 }
12688 None => selection.clone(),
12689 })
12690 .collect::<Vec<_>>();
12691
12692 if selected_larger_symbol {
12693 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12694 s.select(new_selections);
12695 });
12696 }
12697 }
12698
12699 pub fn select_larger_syntax_node(
12700 &mut self,
12701 _: &SelectLargerSyntaxNode,
12702 window: &mut Window,
12703 cx: &mut Context<Self>,
12704 ) {
12705 let Some(visible_row_count) = self.visible_row_count() else {
12706 return;
12707 };
12708 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12709 if old_selections.is_empty() {
12710 return;
12711 }
12712
12713 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12714
12715 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12716 let buffer = self.buffer.read(cx).snapshot(cx);
12717
12718 let mut selected_larger_node = false;
12719 let mut new_selections = old_selections
12720 .iter()
12721 .map(|selection| {
12722 let old_range = selection.start..selection.end;
12723
12724 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12725 // manually select word at selection
12726 if ["string_content", "inline"].contains(&node.kind()) {
12727 let word_range = {
12728 let display_point = buffer
12729 .offset_to_point(old_range.start)
12730 .to_display_point(&display_map);
12731 let Range { start, end } =
12732 movement::surrounding_word(&display_map, display_point);
12733 start.to_point(&display_map).to_offset(&buffer)
12734 ..end.to_point(&display_map).to_offset(&buffer)
12735 };
12736 // ignore if word is already selected
12737 if !word_range.is_empty() && old_range != word_range {
12738 let last_word_range = {
12739 let display_point = buffer
12740 .offset_to_point(old_range.end)
12741 .to_display_point(&display_map);
12742 let Range { start, end } =
12743 movement::surrounding_word(&display_map, display_point);
12744 start.to_point(&display_map).to_offset(&buffer)
12745 ..end.to_point(&display_map).to_offset(&buffer)
12746 };
12747 // only select word if start and end point belongs to same word
12748 if word_range == last_word_range {
12749 selected_larger_node = true;
12750 return Selection {
12751 id: selection.id,
12752 start: word_range.start,
12753 end: word_range.end,
12754 goal: SelectionGoal::None,
12755 reversed: selection.reversed,
12756 };
12757 }
12758 }
12759 }
12760 }
12761
12762 let mut new_range = old_range.clone();
12763 let mut new_node = None;
12764 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12765 {
12766 new_node = Some(node);
12767 new_range = match containing_range {
12768 MultiOrSingleBufferOffsetRange::Single(_) => break,
12769 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12770 };
12771 if !display_map.intersects_fold(new_range.start)
12772 && !display_map.intersects_fold(new_range.end)
12773 {
12774 break;
12775 }
12776 }
12777
12778 if let Some(node) = new_node {
12779 // Log the ancestor, to support using this action as a way to explore TreeSitter
12780 // nodes. Parent and grandparent are also logged because this operation will not
12781 // visit nodes that have the same range as their parent.
12782 log::info!("Node: {node:?}");
12783 let parent = node.parent();
12784 log::info!("Parent: {parent:?}");
12785 let grandparent = parent.and_then(|x| x.parent());
12786 log::info!("Grandparent: {grandparent:?}");
12787 }
12788
12789 selected_larger_node |= new_range != old_range;
12790 Selection {
12791 id: selection.id,
12792 start: new_range.start,
12793 end: new_range.end,
12794 goal: SelectionGoal::None,
12795 reversed: selection.reversed,
12796 }
12797 })
12798 .collect::<Vec<_>>();
12799
12800 if !selected_larger_node {
12801 return; // don't put this call in the history
12802 }
12803
12804 // scroll based on transformation done to the last selection created by the user
12805 let (last_old, last_new) = old_selections
12806 .last()
12807 .zip(new_selections.last().cloned())
12808 .expect("old_selections isn't empty");
12809
12810 // revert selection
12811 let is_selection_reversed = {
12812 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12813 new_selections.last_mut().expect("checked above").reversed =
12814 should_newest_selection_be_reversed;
12815 should_newest_selection_be_reversed
12816 };
12817
12818 if selected_larger_node {
12819 self.select_syntax_node_history.disable_clearing = true;
12820 self.change_selections(None, window, cx, |s| {
12821 s.select(new_selections.clone());
12822 });
12823 self.select_syntax_node_history.disable_clearing = false;
12824 }
12825
12826 let start_row = last_new.start.to_display_point(&display_map).row().0;
12827 let end_row = last_new.end.to_display_point(&display_map).row().0;
12828 let selection_height = end_row - start_row + 1;
12829 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12830
12831 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12832 let scroll_behavior = if fits_on_the_screen {
12833 self.request_autoscroll(Autoscroll::fit(), cx);
12834 SelectSyntaxNodeScrollBehavior::FitSelection
12835 } else if is_selection_reversed {
12836 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12837 SelectSyntaxNodeScrollBehavior::CursorTop
12838 } else {
12839 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12840 SelectSyntaxNodeScrollBehavior::CursorBottom
12841 };
12842
12843 self.select_syntax_node_history.push((
12844 old_selections,
12845 scroll_behavior,
12846 is_selection_reversed,
12847 ));
12848 }
12849
12850 pub fn select_smaller_syntax_node(
12851 &mut self,
12852 _: &SelectSmallerSyntaxNode,
12853 window: &mut Window,
12854 cx: &mut Context<Self>,
12855 ) {
12856 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12857
12858 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12859 self.select_syntax_node_history.pop()
12860 {
12861 if let Some(selection) = selections.last_mut() {
12862 selection.reversed = is_selection_reversed;
12863 }
12864
12865 self.select_syntax_node_history.disable_clearing = true;
12866 self.change_selections(None, window, cx, |s| {
12867 s.select(selections.to_vec());
12868 });
12869 self.select_syntax_node_history.disable_clearing = false;
12870
12871 match scroll_behavior {
12872 SelectSyntaxNodeScrollBehavior::CursorTop => {
12873 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12874 }
12875 SelectSyntaxNodeScrollBehavior::FitSelection => {
12876 self.request_autoscroll(Autoscroll::fit(), cx);
12877 }
12878 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12879 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12880 }
12881 }
12882 }
12883 }
12884
12885 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12886 if !EditorSettings::get_global(cx).gutter.runnables {
12887 self.clear_tasks();
12888 return Task::ready(());
12889 }
12890 let project = self.project.as_ref().map(Entity::downgrade);
12891 let task_sources = self.lsp_task_sources(cx);
12892 cx.spawn_in(window, async move |editor, cx| {
12893 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12894 let Some(project) = project.and_then(|p| p.upgrade()) else {
12895 return;
12896 };
12897 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12898 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12899 }) else {
12900 return;
12901 };
12902
12903 let hide_runnables = project
12904 .update(cx, |project, cx| {
12905 // Do not display any test indicators in non-dev server remote projects.
12906 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12907 })
12908 .unwrap_or(true);
12909 if hide_runnables {
12910 return;
12911 }
12912 let new_rows =
12913 cx.background_spawn({
12914 let snapshot = display_snapshot.clone();
12915 async move {
12916 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12917 }
12918 })
12919 .await;
12920 let Ok(lsp_tasks) =
12921 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12922 else {
12923 return;
12924 };
12925 let lsp_tasks = lsp_tasks.await;
12926
12927 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12928 lsp_tasks
12929 .into_iter()
12930 .flat_map(|(kind, tasks)| {
12931 tasks.into_iter().filter_map(move |(location, task)| {
12932 Some((kind.clone(), location?, task))
12933 })
12934 })
12935 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12936 let buffer = location.target.buffer;
12937 let buffer_snapshot = buffer.read(cx).snapshot();
12938 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12939 |(excerpt_id, snapshot, _)| {
12940 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12941 display_snapshot
12942 .buffer_snapshot
12943 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12944 } else {
12945 None
12946 }
12947 },
12948 );
12949 if let Some(offset) = offset {
12950 let task_buffer_range =
12951 location.target.range.to_point(&buffer_snapshot);
12952 let context_buffer_range =
12953 task_buffer_range.to_offset(&buffer_snapshot);
12954 let context_range = BufferOffset(context_buffer_range.start)
12955 ..BufferOffset(context_buffer_range.end);
12956
12957 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12958 .or_insert_with(|| RunnableTasks {
12959 templates: Vec::new(),
12960 offset,
12961 column: task_buffer_range.start.column,
12962 extra_variables: HashMap::default(),
12963 context_range,
12964 })
12965 .templates
12966 .push((kind, task.original_task().clone()));
12967 }
12968
12969 acc
12970 })
12971 }) else {
12972 return;
12973 };
12974
12975 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12976 editor
12977 .update(cx, |editor, _| {
12978 editor.clear_tasks();
12979 for (key, mut value) in rows {
12980 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12981 value.templates.extend(lsp_tasks.templates);
12982 }
12983
12984 editor.insert_tasks(key, value);
12985 }
12986 for (key, value) in lsp_tasks_by_rows {
12987 editor.insert_tasks(key, value);
12988 }
12989 })
12990 .ok();
12991 })
12992 }
12993 fn fetch_runnable_ranges(
12994 snapshot: &DisplaySnapshot,
12995 range: Range<Anchor>,
12996 ) -> Vec<language::RunnableRange> {
12997 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12998 }
12999
13000 fn runnable_rows(
13001 project: Entity<Project>,
13002 snapshot: DisplaySnapshot,
13003 runnable_ranges: Vec<RunnableRange>,
13004 mut cx: AsyncWindowContext,
13005 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13006 runnable_ranges
13007 .into_iter()
13008 .filter_map(|mut runnable| {
13009 let tasks = cx
13010 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13011 .ok()?;
13012 if tasks.is_empty() {
13013 return None;
13014 }
13015
13016 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13017
13018 let row = snapshot
13019 .buffer_snapshot
13020 .buffer_line_for_row(MultiBufferRow(point.row))?
13021 .1
13022 .start
13023 .row;
13024
13025 let context_range =
13026 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13027 Some((
13028 (runnable.buffer_id, row),
13029 RunnableTasks {
13030 templates: tasks,
13031 offset: snapshot
13032 .buffer_snapshot
13033 .anchor_before(runnable.run_range.start),
13034 context_range,
13035 column: point.column,
13036 extra_variables: runnable.extra_captures,
13037 },
13038 ))
13039 })
13040 .collect()
13041 }
13042
13043 fn templates_with_tags(
13044 project: &Entity<Project>,
13045 runnable: &mut Runnable,
13046 cx: &mut App,
13047 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13048 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13049 let (worktree_id, file) = project
13050 .buffer_for_id(runnable.buffer, cx)
13051 .and_then(|buffer| buffer.read(cx).file())
13052 .map(|file| (file.worktree_id(cx), file.clone()))
13053 .unzip();
13054
13055 (
13056 project.task_store().read(cx).task_inventory().cloned(),
13057 worktree_id,
13058 file,
13059 )
13060 });
13061
13062 let mut templates_with_tags = mem::take(&mut runnable.tags)
13063 .into_iter()
13064 .flat_map(|RunnableTag(tag)| {
13065 inventory
13066 .as_ref()
13067 .into_iter()
13068 .flat_map(|inventory| {
13069 inventory.read(cx).list_tasks(
13070 file.clone(),
13071 Some(runnable.language.clone()),
13072 worktree_id,
13073 cx,
13074 )
13075 })
13076 .filter(move |(_, template)| {
13077 template.tags.iter().any(|source_tag| source_tag == &tag)
13078 })
13079 })
13080 .sorted_by_key(|(kind, _)| kind.to_owned())
13081 .collect::<Vec<_>>();
13082 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13083 // Strongest source wins; if we have worktree tag binding, prefer that to
13084 // global and language bindings;
13085 // if we have a global binding, prefer that to language binding.
13086 let first_mismatch = templates_with_tags
13087 .iter()
13088 .position(|(tag_source, _)| tag_source != leading_tag_source);
13089 if let Some(index) = first_mismatch {
13090 templates_with_tags.truncate(index);
13091 }
13092 }
13093
13094 templates_with_tags
13095 }
13096
13097 pub fn move_to_enclosing_bracket(
13098 &mut self,
13099 _: &MoveToEnclosingBracket,
13100 window: &mut Window,
13101 cx: &mut Context<Self>,
13102 ) {
13103 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13105 s.move_offsets_with(|snapshot, selection| {
13106 let Some(enclosing_bracket_ranges) =
13107 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13108 else {
13109 return;
13110 };
13111
13112 let mut best_length = usize::MAX;
13113 let mut best_inside = false;
13114 let mut best_in_bracket_range = false;
13115 let mut best_destination = None;
13116 for (open, close) in enclosing_bracket_ranges {
13117 let close = close.to_inclusive();
13118 let length = close.end() - open.start;
13119 let inside = selection.start >= open.end && selection.end <= *close.start();
13120 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13121 || close.contains(&selection.head());
13122
13123 // If best is next to a bracket and current isn't, skip
13124 if !in_bracket_range && best_in_bracket_range {
13125 continue;
13126 }
13127
13128 // Prefer smaller lengths unless best is inside and current isn't
13129 if length > best_length && (best_inside || !inside) {
13130 continue;
13131 }
13132
13133 best_length = length;
13134 best_inside = inside;
13135 best_in_bracket_range = in_bracket_range;
13136 best_destination = Some(
13137 if close.contains(&selection.start) && close.contains(&selection.end) {
13138 if inside { open.end } else { open.start }
13139 } else if inside {
13140 *close.start()
13141 } else {
13142 *close.end()
13143 },
13144 );
13145 }
13146
13147 if let Some(destination) = best_destination {
13148 selection.collapse_to(destination, SelectionGoal::None);
13149 }
13150 })
13151 });
13152 }
13153
13154 pub fn undo_selection(
13155 &mut self,
13156 _: &UndoSelection,
13157 window: &mut Window,
13158 cx: &mut Context<Self>,
13159 ) {
13160 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13161 self.end_selection(window, cx);
13162 self.selection_history.mode = SelectionHistoryMode::Undoing;
13163 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13164 self.change_selections(None, window, cx, |s| {
13165 s.select_anchors(entry.selections.to_vec())
13166 });
13167 self.select_next_state = entry.select_next_state;
13168 self.select_prev_state = entry.select_prev_state;
13169 self.add_selections_state = entry.add_selections_state;
13170 self.request_autoscroll(Autoscroll::newest(), cx);
13171 }
13172 self.selection_history.mode = SelectionHistoryMode::Normal;
13173 }
13174
13175 pub fn redo_selection(
13176 &mut self,
13177 _: &RedoSelection,
13178 window: &mut Window,
13179 cx: &mut Context<Self>,
13180 ) {
13181 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13182 self.end_selection(window, cx);
13183 self.selection_history.mode = SelectionHistoryMode::Redoing;
13184 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13185 self.change_selections(None, window, cx, |s| {
13186 s.select_anchors(entry.selections.to_vec())
13187 });
13188 self.select_next_state = entry.select_next_state;
13189 self.select_prev_state = entry.select_prev_state;
13190 self.add_selections_state = entry.add_selections_state;
13191 self.request_autoscroll(Autoscroll::newest(), cx);
13192 }
13193 self.selection_history.mode = SelectionHistoryMode::Normal;
13194 }
13195
13196 pub fn expand_excerpts(
13197 &mut self,
13198 action: &ExpandExcerpts,
13199 _: &mut Window,
13200 cx: &mut Context<Self>,
13201 ) {
13202 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13203 }
13204
13205 pub fn expand_excerpts_down(
13206 &mut self,
13207 action: &ExpandExcerptsDown,
13208 _: &mut Window,
13209 cx: &mut Context<Self>,
13210 ) {
13211 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13212 }
13213
13214 pub fn expand_excerpts_up(
13215 &mut self,
13216 action: &ExpandExcerptsUp,
13217 _: &mut Window,
13218 cx: &mut Context<Self>,
13219 ) {
13220 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13221 }
13222
13223 pub fn expand_excerpts_for_direction(
13224 &mut self,
13225 lines: u32,
13226 direction: ExpandExcerptDirection,
13227
13228 cx: &mut Context<Self>,
13229 ) {
13230 let selections = self.selections.disjoint_anchors();
13231
13232 let lines = if lines == 0 {
13233 EditorSettings::get_global(cx).expand_excerpt_lines
13234 } else {
13235 lines
13236 };
13237
13238 self.buffer.update(cx, |buffer, cx| {
13239 let snapshot = buffer.snapshot(cx);
13240 let mut excerpt_ids = selections
13241 .iter()
13242 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13243 .collect::<Vec<_>>();
13244 excerpt_ids.sort();
13245 excerpt_ids.dedup();
13246 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13247 })
13248 }
13249
13250 pub fn expand_excerpt(
13251 &mut self,
13252 excerpt: ExcerptId,
13253 direction: ExpandExcerptDirection,
13254 window: &mut Window,
13255 cx: &mut Context<Self>,
13256 ) {
13257 let current_scroll_position = self.scroll_position(cx);
13258 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13259 let mut should_scroll_up = false;
13260
13261 if direction == ExpandExcerptDirection::Down {
13262 let multi_buffer = self.buffer.read(cx);
13263 let snapshot = multi_buffer.snapshot(cx);
13264 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13265 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13266 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13267 let buffer_snapshot = buffer.read(cx).snapshot();
13268 let excerpt_end_row =
13269 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13270 let last_row = buffer_snapshot.max_point().row;
13271 let lines_below = last_row.saturating_sub(excerpt_end_row);
13272 should_scroll_up = lines_below >= lines_to_expand;
13273 }
13274 }
13275 }
13276 }
13277
13278 self.buffer.update(cx, |buffer, cx| {
13279 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13280 });
13281
13282 if should_scroll_up {
13283 let new_scroll_position =
13284 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13285 self.set_scroll_position(new_scroll_position, window, cx);
13286 }
13287 }
13288
13289 pub fn go_to_singleton_buffer_point(
13290 &mut self,
13291 point: Point,
13292 window: &mut Window,
13293 cx: &mut Context<Self>,
13294 ) {
13295 self.go_to_singleton_buffer_range(point..point, window, cx);
13296 }
13297
13298 pub fn go_to_singleton_buffer_range(
13299 &mut self,
13300 range: Range<Point>,
13301 window: &mut Window,
13302 cx: &mut Context<Self>,
13303 ) {
13304 let multibuffer = self.buffer().read(cx);
13305 let Some(buffer) = multibuffer.as_singleton() else {
13306 return;
13307 };
13308 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13309 return;
13310 };
13311 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13312 return;
13313 };
13314 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13315 s.select_anchor_ranges([start..end])
13316 });
13317 }
13318
13319 pub fn go_to_diagnostic(
13320 &mut self,
13321 _: &GoToDiagnostic,
13322 window: &mut Window,
13323 cx: &mut Context<Self>,
13324 ) {
13325 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13326 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13327 }
13328
13329 pub fn go_to_prev_diagnostic(
13330 &mut self,
13331 _: &GoToPreviousDiagnostic,
13332 window: &mut Window,
13333 cx: &mut Context<Self>,
13334 ) {
13335 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13336 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13337 }
13338
13339 pub fn go_to_diagnostic_impl(
13340 &mut self,
13341 direction: Direction,
13342 window: &mut Window,
13343 cx: &mut Context<Self>,
13344 ) {
13345 let buffer = self.buffer.read(cx).snapshot(cx);
13346 let selection = self.selections.newest::<usize>(cx);
13347
13348 let mut active_group_id = None;
13349 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13350 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13351 active_group_id = Some(active_group.group_id);
13352 }
13353 }
13354
13355 fn filtered(
13356 snapshot: EditorSnapshot,
13357 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13358 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13359 diagnostics
13360 .filter(|entry| entry.range.start != entry.range.end)
13361 .filter(|entry| !entry.diagnostic.is_unnecessary)
13362 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13363 }
13364
13365 let snapshot = self.snapshot(window, cx);
13366 let before = filtered(
13367 snapshot.clone(),
13368 buffer
13369 .diagnostics_in_range(0..selection.start)
13370 .filter(|entry| entry.range.start <= selection.start),
13371 );
13372 let after = filtered(
13373 snapshot,
13374 buffer
13375 .diagnostics_in_range(selection.start..buffer.len())
13376 .filter(|entry| entry.range.start >= selection.start),
13377 );
13378
13379 let mut found: Option<DiagnosticEntry<usize>> = None;
13380 if direction == Direction::Prev {
13381 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13382 {
13383 for diagnostic in prev_diagnostics.into_iter().rev() {
13384 if diagnostic.range.start != selection.start
13385 || active_group_id
13386 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13387 {
13388 found = Some(diagnostic);
13389 break 'outer;
13390 }
13391 }
13392 }
13393 } else {
13394 for diagnostic in after.chain(before) {
13395 if diagnostic.range.start != selection.start
13396 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13397 {
13398 found = Some(diagnostic);
13399 break;
13400 }
13401 }
13402 }
13403 let Some(next_diagnostic) = found else {
13404 return;
13405 };
13406
13407 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13408 return;
13409 };
13410 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13411 s.select_ranges(vec![
13412 next_diagnostic.range.start..next_diagnostic.range.start,
13413 ])
13414 });
13415 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13416 self.refresh_inline_completion(false, true, window, cx);
13417 }
13418
13419 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13420 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13421 let snapshot = self.snapshot(window, cx);
13422 let selection = self.selections.newest::<Point>(cx);
13423 self.go_to_hunk_before_or_after_position(
13424 &snapshot,
13425 selection.head(),
13426 Direction::Next,
13427 window,
13428 cx,
13429 );
13430 }
13431
13432 pub fn go_to_hunk_before_or_after_position(
13433 &mut self,
13434 snapshot: &EditorSnapshot,
13435 position: Point,
13436 direction: Direction,
13437 window: &mut Window,
13438 cx: &mut Context<Editor>,
13439 ) {
13440 let row = if direction == Direction::Next {
13441 self.hunk_after_position(snapshot, position)
13442 .map(|hunk| hunk.row_range.start)
13443 } else {
13444 self.hunk_before_position(snapshot, position)
13445 };
13446
13447 if let Some(row) = row {
13448 let destination = Point::new(row.0, 0);
13449 let autoscroll = Autoscroll::center();
13450
13451 self.unfold_ranges(&[destination..destination], false, false, cx);
13452 self.change_selections(Some(autoscroll), window, cx, |s| {
13453 s.select_ranges([destination..destination]);
13454 });
13455 }
13456 }
13457
13458 fn hunk_after_position(
13459 &mut self,
13460 snapshot: &EditorSnapshot,
13461 position: Point,
13462 ) -> Option<MultiBufferDiffHunk> {
13463 snapshot
13464 .buffer_snapshot
13465 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13466 .find(|hunk| hunk.row_range.start.0 > position.row)
13467 .or_else(|| {
13468 snapshot
13469 .buffer_snapshot
13470 .diff_hunks_in_range(Point::zero()..position)
13471 .find(|hunk| hunk.row_range.end.0 < position.row)
13472 })
13473 }
13474
13475 fn go_to_prev_hunk(
13476 &mut self,
13477 _: &GoToPreviousHunk,
13478 window: &mut Window,
13479 cx: &mut Context<Self>,
13480 ) {
13481 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13482 let snapshot = self.snapshot(window, cx);
13483 let selection = self.selections.newest::<Point>(cx);
13484 self.go_to_hunk_before_or_after_position(
13485 &snapshot,
13486 selection.head(),
13487 Direction::Prev,
13488 window,
13489 cx,
13490 );
13491 }
13492
13493 fn hunk_before_position(
13494 &mut self,
13495 snapshot: &EditorSnapshot,
13496 position: Point,
13497 ) -> Option<MultiBufferRow> {
13498 snapshot
13499 .buffer_snapshot
13500 .diff_hunk_before(position)
13501 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13502 }
13503
13504 fn go_to_next_change(
13505 &mut self,
13506 _: &GoToNextChange,
13507 window: &mut Window,
13508 cx: &mut Context<Self>,
13509 ) {
13510 if let Some(selections) = self
13511 .change_list
13512 .next_change(1, Direction::Next)
13513 .map(|s| s.to_vec())
13514 {
13515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13516 let map = s.display_map();
13517 s.select_display_ranges(selections.iter().map(|a| {
13518 let point = a.to_display_point(&map);
13519 point..point
13520 }))
13521 })
13522 }
13523 }
13524
13525 fn go_to_previous_change(
13526 &mut self,
13527 _: &GoToPreviousChange,
13528 window: &mut Window,
13529 cx: &mut Context<Self>,
13530 ) {
13531 if let Some(selections) = self
13532 .change_list
13533 .next_change(1, Direction::Prev)
13534 .map(|s| s.to_vec())
13535 {
13536 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13537 let map = s.display_map();
13538 s.select_display_ranges(selections.iter().map(|a| {
13539 let point = a.to_display_point(&map);
13540 point..point
13541 }))
13542 })
13543 }
13544 }
13545
13546 fn go_to_line<T: 'static>(
13547 &mut self,
13548 position: Anchor,
13549 highlight_color: Option<Hsla>,
13550 window: &mut Window,
13551 cx: &mut Context<Self>,
13552 ) {
13553 let snapshot = self.snapshot(window, cx).display_snapshot;
13554 let position = position.to_point(&snapshot.buffer_snapshot);
13555 let start = snapshot
13556 .buffer_snapshot
13557 .clip_point(Point::new(position.row, 0), Bias::Left);
13558 let end = start + Point::new(1, 0);
13559 let start = snapshot.buffer_snapshot.anchor_before(start);
13560 let end = snapshot.buffer_snapshot.anchor_before(end);
13561
13562 self.highlight_rows::<T>(
13563 start..end,
13564 highlight_color
13565 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13566 Default::default(),
13567 cx,
13568 );
13569 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13570 }
13571
13572 pub fn go_to_definition(
13573 &mut self,
13574 _: &GoToDefinition,
13575 window: &mut Window,
13576 cx: &mut Context<Self>,
13577 ) -> Task<Result<Navigated>> {
13578 let definition =
13579 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13580 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13581 cx.spawn_in(window, async move |editor, cx| {
13582 if definition.await? == Navigated::Yes {
13583 return Ok(Navigated::Yes);
13584 }
13585 match fallback_strategy {
13586 GoToDefinitionFallback::None => Ok(Navigated::No),
13587 GoToDefinitionFallback::FindAllReferences => {
13588 match editor.update_in(cx, |editor, window, cx| {
13589 editor.find_all_references(&FindAllReferences, window, cx)
13590 })? {
13591 Some(references) => references.await,
13592 None => Ok(Navigated::No),
13593 }
13594 }
13595 }
13596 })
13597 }
13598
13599 pub fn go_to_declaration(
13600 &mut self,
13601 _: &GoToDeclaration,
13602 window: &mut Window,
13603 cx: &mut Context<Self>,
13604 ) -> Task<Result<Navigated>> {
13605 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13606 }
13607
13608 pub fn go_to_declaration_split(
13609 &mut self,
13610 _: &GoToDeclaration,
13611 window: &mut Window,
13612 cx: &mut Context<Self>,
13613 ) -> Task<Result<Navigated>> {
13614 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13615 }
13616
13617 pub fn go_to_implementation(
13618 &mut self,
13619 _: &GoToImplementation,
13620 window: &mut Window,
13621 cx: &mut Context<Self>,
13622 ) -> Task<Result<Navigated>> {
13623 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13624 }
13625
13626 pub fn go_to_implementation_split(
13627 &mut self,
13628 _: &GoToImplementationSplit,
13629 window: &mut Window,
13630 cx: &mut Context<Self>,
13631 ) -> Task<Result<Navigated>> {
13632 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13633 }
13634
13635 pub fn go_to_type_definition(
13636 &mut self,
13637 _: &GoToTypeDefinition,
13638 window: &mut Window,
13639 cx: &mut Context<Self>,
13640 ) -> Task<Result<Navigated>> {
13641 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13642 }
13643
13644 pub fn go_to_definition_split(
13645 &mut self,
13646 _: &GoToDefinitionSplit,
13647 window: &mut Window,
13648 cx: &mut Context<Self>,
13649 ) -> Task<Result<Navigated>> {
13650 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13651 }
13652
13653 pub fn go_to_type_definition_split(
13654 &mut self,
13655 _: &GoToTypeDefinitionSplit,
13656 window: &mut Window,
13657 cx: &mut Context<Self>,
13658 ) -> Task<Result<Navigated>> {
13659 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13660 }
13661
13662 fn go_to_definition_of_kind(
13663 &mut self,
13664 kind: GotoDefinitionKind,
13665 split: bool,
13666 window: &mut Window,
13667 cx: &mut Context<Self>,
13668 ) -> Task<Result<Navigated>> {
13669 let Some(provider) = self.semantics_provider.clone() else {
13670 return Task::ready(Ok(Navigated::No));
13671 };
13672 let head = self.selections.newest::<usize>(cx).head();
13673 let buffer = self.buffer.read(cx);
13674 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13675 text_anchor
13676 } else {
13677 return Task::ready(Ok(Navigated::No));
13678 };
13679
13680 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13681 return Task::ready(Ok(Navigated::No));
13682 };
13683
13684 cx.spawn_in(window, async move |editor, cx| {
13685 let definitions = definitions.await?;
13686 let navigated = editor
13687 .update_in(cx, |editor, window, cx| {
13688 editor.navigate_to_hover_links(
13689 Some(kind),
13690 definitions
13691 .into_iter()
13692 .filter(|location| {
13693 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13694 })
13695 .map(HoverLink::Text)
13696 .collect::<Vec<_>>(),
13697 split,
13698 window,
13699 cx,
13700 )
13701 })?
13702 .await?;
13703 anyhow::Ok(navigated)
13704 })
13705 }
13706
13707 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13708 let selection = self.selections.newest_anchor();
13709 let head = selection.head();
13710 let tail = selection.tail();
13711
13712 let Some((buffer, start_position)) =
13713 self.buffer.read(cx).text_anchor_for_position(head, cx)
13714 else {
13715 return;
13716 };
13717
13718 let end_position = if head != tail {
13719 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13720 return;
13721 };
13722 Some(pos)
13723 } else {
13724 None
13725 };
13726
13727 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13728 let url = if let Some(end_pos) = end_position {
13729 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13730 } else {
13731 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13732 };
13733
13734 if let Some(url) = url {
13735 editor.update(cx, |_, cx| {
13736 cx.open_url(&url);
13737 })
13738 } else {
13739 Ok(())
13740 }
13741 });
13742
13743 url_finder.detach();
13744 }
13745
13746 pub fn open_selected_filename(
13747 &mut self,
13748 _: &OpenSelectedFilename,
13749 window: &mut Window,
13750 cx: &mut Context<Self>,
13751 ) {
13752 let Some(workspace) = self.workspace() else {
13753 return;
13754 };
13755
13756 let position = self.selections.newest_anchor().head();
13757
13758 let Some((buffer, buffer_position)) =
13759 self.buffer.read(cx).text_anchor_for_position(position, cx)
13760 else {
13761 return;
13762 };
13763
13764 let project = self.project.clone();
13765
13766 cx.spawn_in(window, async move |_, cx| {
13767 let result = find_file(&buffer, project, buffer_position, cx).await;
13768
13769 if let Some((_, path)) = result {
13770 workspace
13771 .update_in(cx, |workspace, window, cx| {
13772 workspace.open_resolved_path(path, window, cx)
13773 })?
13774 .await?;
13775 }
13776 anyhow::Ok(())
13777 })
13778 .detach();
13779 }
13780
13781 pub(crate) fn navigate_to_hover_links(
13782 &mut self,
13783 kind: Option<GotoDefinitionKind>,
13784 mut definitions: Vec<HoverLink>,
13785 split: bool,
13786 window: &mut Window,
13787 cx: &mut Context<Editor>,
13788 ) -> Task<Result<Navigated>> {
13789 // If there is one definition, just open it directly
13790 if definitions.len() == 1 {
13791 let definition = definitions.pop().unwrap();
13792
13793 enum TargetTaskResult {
13794 Location(Option<Location>),
13795 AlreadyNavigated,
13796 }
13797
13798 let target_task = match definition {
13799 HoverLink::Text(link) => {
13800 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13801 }
13802 HoverLink::InlayHint(lsp_location, server_id) => {
13803 let computation =
13804 self.compute_target_location(lsp_location, server_id, window, cx);
13805 cx.background_spawn(async move {
13806 let location = computation.await?;
13807 Ok(TargetTaskResult::Location(location))
13808 })
13809 }
13810 HoverLink::Url(url) => {
13811 cx.open_url(&url);
13812 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13813 }
13814 HoverLink::File(path) => {
13815 if let Some(workspace) = self.workspace() {
13816 cx.spawn_in(window, async move |_, cx| {
13817 workspace
13818 .update_in(cx, |workspace, window, cx| {
13819 workspace.open_resolved_path(path, window, cx)
13820 })?
13821 .await
13822 .map(|_| TargetTaskResult::AlreadyNavigated)
13823 })
13824 } else {
13825 Task::ready(Ok(TargetTaskResult::Location(None)))
13826 }
13827 }
13828 };
13829 cx.spawn_in(window, async move |editor, cx| {
13830 let target = match target_task.await.context("target resolution task")? {
13831 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13832 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13833 TargetTaskResult::Location(Some(target)) => target,
13834 };
13835
13836 editor.update_in(cx, |editor, window, cx| {
13837 let Some(workspace) = editor.workspace() else {
13838 return Navigated::No;
13839 };
13840 let pane = workspace.read(cx).active_pane().clone();
13841
13842 let range = target.range.to_point(target.buffer.read(cx));
13843 let range = editor.range_for_match(&range);
13844 let range = collapse_multiline_range(range);
13845
13846 if !split
13847 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13848 {
13849 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13850 } else {
13851 window.defer(cx, move |window, cx| {
13852 let target_editor: Entity<Self> =
13853 workspace.update(cx, |workspace, cx| {
13854 let pane = if split {
13855 workspace.adjacent_pane(window, cx)
13856 } else {
13857 workspace.active_pane().clone()
13858 };
13859
13860 workspace.open_project_item(
13861 pane,
13862 target.buffer.clone(),
13863 true,
13864 true,
13865 window,
13866 cx,
13867 )
13868 });
13869 target_editor.update(cx, |target_editor, cx| {
13870 // When selecting a definition in a different buffer, disable the nav history
13871 // to avoid creating a history entry at the previous cursor location.
13872 pane.update(cx, |pane, _| pane.disable_history());
13873 target_editor.go_to_singleton_buffer_range(range, window, cx);
13874 pane.update(cx, |pane, _| pane.enable_history());
13875 });
13876 });
13877 }
13878 Navigated::Yes
13879 })
13880 })
13881 } else if !definitions.is_empty() {
13882 cx.spawn_in(window, async move |editor, cx| {
13883 let (title, location_tasks, workspace) = editor
13884 .update_in(cx, |editor, window, cx| {
13885 let tab_kind = match kind {
13886 Some(GotoDefinitionKind::Implementation) => "Implementations",
13887 _ => "Definitions",
13888 };
13889 let title = definitions
13890 .iter()
13891 .find_map(|definition| match definition {
13892 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13893 let buffer = origin.buffer.read(cx);
13894 format!(
13895 "{} for {}",
13896 tab_kind,
13897 buffer
13898 .text_for_range(origin.range.clone())
13899 .collect::<String>()
13900 )
13901 }),
13902 HoverLink::InlayHint(_, _) => None,
13903 HoverLink::Url(_) => None,
13904 HoverLink::File(_) => None,
13905 })
13906 .unwrap_or(tab_kind.to_string());
13907 let location_tasks = definitions
13908 .into_iter()
13909 .map(|definition| match definition {
13910 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13911 HoverLink::InlayHint(lsp_location, server_id) => editor
13912 .compute_target_location(lsp_location, server_id, window, cx),
13913 HoverLink::Url(_) => Task::ready(Ok(None)),
13914 HoverLink::File(_) => Task::ready(Ok(None)),
13915 })
13916 .collect::<Vec<_>>();
13917 (title, location_tasks, editor.workspace().clone())
13918 })
13919 .context("location tasks preparation")?;
13920
13921 let locations = future::join_all(location_tasks)
13922 .await
13923 .into_iter()
13924 .filter_map(|location| location.transpose())
13925 .collect::<Result<_>>()
13926 .context("location tasks")?;
13927
13928 let Some(workspace) = workspace else {
13929 return Ok(Navigated::No);
13930 };
13931 let opened = workspace
13932 .update_in(cx, |workspace, window, cx| {
13933 Self::open_locations_in_multibuffer(
13934 workspace,
13935 locations,
13936 title,
13937 split,
13938 MultibufferSelectionMode::First,
13939 window,
13940 cx,
13941 )
13942 })
13943 .ok();
13944
13945 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13946 })
13947 } else {
13948 Task::ready(Ok(Navigated::No))
13949 }
13950 }
13951
13952 fn compute_target_location(
13953 &self,
13954 lsp_location: lsp::Location,
13955 server_id: LanguageServerId,
13956 window: &mut Window,
13957 cx: &mut Context<Self>,
13958 ) -> Task<anyhow::Result<Option<Location>>> {
13959 let Some(project) = self.project.clone() else {
13960 return Task::ready(Ok(None));
13961 };
13962
13963 cx.spawn_in(window, async move |editor, cx| {
13964 let location_task = editor.update(cx, |_, cx| {
13965 project.update(cx, |project, cx| {
13966 let language_server_name = project
13967 .language_server_statuses(cx)
13968 .find(|(id, _)| server_id == *id)
13969 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13970 language_server_name.map(|language_server_name| {
13971 project.open_local_buffer_via_lsp(
13972 lsp_location.uri.clone(),
13973 server_id,
13974 language_server_name,
13975 cx,
13976 )
13977 })
13978 })
13979 })?;
13980 let location = match location_task {
13981 Some(task) => Some({
13982 let target_buffer_handle = task.await.context("open local buffer")?;
13983 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13984 let target_start = target_buffer
13985 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13986 let target_end = target_buffer
13987 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13988 target_buffer.anchor_after(target_start)
13989 ..target_buffer.anchor_before(target_end)
13990 })?;
13991 Location {
13992 buffer: target_buffer_handle,
13993 range,
13994 }
13995 }),
13996 None => None,
13997 };
13998 Ok(location)
13999 })
14000 }
14001
14002 pub fn find_all_references(
14003 &mut self,
14004 _: &FindAllReferences,
14005 window: &mut Window,
14006 cx: &mut Context<Self>,
14007 ) -> Option<Task<Result<Navigated>>> {
14008 let selection = self.selections.newest::<usize>(cx);
14009 let multi_buffer = self.buffer.read(cx);
14010 let head = selection.head();
14011
14012 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14013 let head_anchor = multi_buffer_snapshot.anchor_at(
14014 head,
14015 if head < selection.tail() {
14016 Bias::Right
14017 } else {
14018 Bias::Left
14019 },
14020 );
14021
14022 match self
14023 .find_all_references_task_sources
14024 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14025 {
14026 Ok(_) => {
14027 log::info!(
14028 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14029 );
14030 return None;
14031 }
14032 Err(i) => {
14033 self.find_all_references_task_sources.insert(i, head_anchor);
14034 }
14035 }
14036
14037 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14038 let workspace = self.workspace()?;
14039 let project = workspace.read(cx).project().clone();
14040 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14041 Some(cx.spawn_in(window, async move |editor, cx| {
14042 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14043 if let Ok(i) = editor
14044 .find_all_references_task_sources
14045 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14046 {
14047 editor.find_all_references_task_sources.remove(i);
14048 }
14049 });
14050
14051 let locations = references.await?;
14052 if locations.is_empty() {
14053 return anyhow::Ok(Navigated::No);
14054 }
14055
14056 workspace.update_in(cx, |workspace, window, cx| {
14057 let title = locations
14058 .first()
14059 .as_ref()
14060 .map(|location| {
14061 let buffer = location.buffer.read(cx);
14062 format!(
14063 "References to `{}`",
14064 buffer
14065 .text_for_range(location.range.clone())
14066 .collect::<String>()
14067 )
14068 })
14069 .unwrap();
14070 Self::open_locations_in_multibuffer(
14071 workspace,
14072 locations,
14073 title,
14074 false,
14075 MultibufferSelectionMode::First,
14076 window,
14077 cx,
14078 );
14079 Navigated::Yes
14080 })
14081 }))
14082 }
14083
14084 /// Opens a multibuffer with the given project locations in it
14085 pub fn open_locations_in_multibuffer(
14086 workspace: &mut Workspace,
14087 mut locations: Vec<Location>,
14088 title: String,
14089 split: bool,
14090 multibuffer_selection_mode: MultibufferSelectionMode,
14091 window: &mut Window,
14092 cx: &mut Context<Workspace>,
14093 ) {
14094 // If there are multiple definitions, open them in a multibuffer
14095 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14096 let mut locations = locations.into_iter().peekable();
14097 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14098 let capability = workspace.project().read(cx).capability();
14099
14100 let excerpt_buffer = cx.new(|cx| {
14101 let mut multibuffer = MultiBuffer::new(capability);
14102 while let Some(location) = locations.next() {
14103 let buffer = location.buffer.read(cx);
14104 let mut ranges_for_buffer = Vec::new();
14105 let range = location.range.to_point(buffer);
14106 ranges_for_buffer.push(range.clone());
14107
14108 while let Some(next_location) = locations.peek() {
14109 if next_location.buffer == location.buffer {
14110 ranges_for_buffer.push(next_location.range.to_point(buffer));
14111 locations.next();
14112 } else {
14113 break;
14114 }
14115 }
14116
14117 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14118 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14119 PathKey::for_buffer(&location.buffer, cx),
14120 location.buffer.clone(),
14121 ranges_for_buffer,
14122 DEFAULT_MULTIBUFFER_CONTEXT,
14123 cx,
14124 );
14125 ranges.extend(new_ranges)
14126 }
14127
14128 multibuffer.with_title(title)
14129 });
14130
14131 let editor = cx.new(|cx| {
14132 Editor::for_multibuffer(
14133 excerpt_buffer,
14134 Some(workspace.project().clone()),
14135 window,
14136 cx,
14137 )
14138 });
14139 editor.update(cx, |editor, cx| {
14140 match multibuffer_selection_mode {
14141 MultibufferSelectionMode::First => {
14142 if let Some(first_range) = ranges.first() {
14143 editor.change_selections(None, window, cx, |selections| {
14144 selections.clear_disjoint();
14145 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14146 });
14147 }
14148 editor.highlight_background::<Self>(
14149 &ranges,
14150 |theme| theme.editor_highlighted_line_background,
14151 cx,
14152 );
14153 }
14154 MultibufferSelectionMode::All => {
14155 editor.change_selections(None, window, cx, |selections| {
14156 selections.clear_disjoint();
14157 selections.select_anchor_ranges(ranges);
14158 });
14159 }
14160 }
14161 editor.register_buffers_with_language_servers(cx);
14162 });
14163
14164 let item = Box::new(editor);
14165 let item_id = item.item_id();
14166
14167 if split {
14168 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14169 } else {
14170 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14171 let (preview_item_id, preview_item_idx) =
14172 workspace.active_pane().update(cx, |pane, _| {
14173 (pane.preview_item_id(), pane.preview_item_idx())
14174 });
14175
14176 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14177
14178 if let Some(preview_item_id) = preview_item_id {
14179 workspace.active_pane().update(cx, |pane, cx| {
14180 pane.remove_item(preview_item_id, false, false, window, cx);
14181 });
14182 }
14183 } else {
14184 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14185 }
14186 }
14187 workspace.active_pane().update(cx, |pane, cx| {
14188 pane.set_preview_item_id(Some(item_id), cx);
14189 });
14190 }
14191
14192 pub fn rename(
14193 &mut self,
14194 _: &Rename,
14195 window: &mut Window,
14196 cx: &mut Context<Self>,
14197 ) -> Option<Task<Result<()>>> {
14198 use language::ToOffset as _;
14199
14200 let provider = self.semantics_provider.clone()?;
14201 let selection = self.selections.newest_anchor().clone();
14202 let (cursor_buffer, cursor_buffer_position) = self
14203 .buffer
14204 .read(cx)
14205 .text_anchor_for_position(selection.head(), cx)?;
14206 let (tail_buffer, cursor_buffer_position_end) = self
14207 .buffer
14208 .read(cx)
14209 .text_anchor_for_position(selection.tail(), cx)?;
14210 if tail_buffer != cursor_buffer {
14211 return None;
14212 }
14213
14214 let snapshot = cursor_buffer.read(cx).snapshot();
14215 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14216 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14217 let prepare_rename = provider
14218 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14219 .unwrap_or_else(|| Task::ready(Ok(None)));
14220 drop(snapshot);
14221
14222 Some(cx.spawn_in(window, async move |this, cx| {
14223 let rename_range = if let Some(range) = prepare_rename.await? {
14224 Some(range)
14225 } else {
14226 this.update(cx, |this, cx| {
14227 let buffer = this.buffer.read(cx).snapshot(cx);
14228 let mut buffer_highlights = this
14229 .document_highlights_for_position(selection.head(), &buffer)
14230 .filter(|highlight| {
14231 highlight.start.excerpt_id == selection.head().excerpt_id
14232 && highlight.end.excerpt_id == selection.head().excerpt_id
14233 });
14234 buffer_highlights
14235 .next()
14236 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14237 })?
14238 };
14239 if let Some(rename_range) = rename_range {
14240 this.update_in(cx, |this, window, cx| {
14241 let snapshot = cursor_buffer.read(cx).snapshot();
14242 let rename_buffer_range = rename_range.to_offset(&snapshot);
14243 let cursor_offset_in_rename_range =
14244 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14245 let cursor_offset_in_rename_range_end =
14246 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14247
14248 this.take_rename(false, window, cx);
14249 let buffer = this.buffer.read(cx).read(cx);
14250 let cursor_offset = selection.head().to_offset(&buffer);
14251 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14252 let rename_end = rename_start + rename_buffer_range.len();
14253 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14254 let mut old_highlight_id = None;
14255 let old_name: Arc<str> = buffer
14256 .chunks(rename_start..rename_end, true)
14257 .map(|chunk| {
14258 if old_highlight_id.is_none() {
14259 old_highlight_id = chunk.syntax_highlight_id;
14260 }
14261 chunk.text
14262 })
14263 .collect::<String>()
14264 .into();
14265
14266 drop(buffer);
14267
14268 // Position the selection in the rename editor so that it matches the current selection.
14269 this.show_local_selections = false;
14270 let rename_editor = cx.new(|cx| {
14271 let mut editor = Editor::single_line(window, cx);
14272 editor.buffer.update(cx, |buffer, cx| {
14273 buffer.edit([(0..0, old_name.clone())], None, cx)
14274 });
14275 let rename_selection_range = match cursor_offset_in_rename_range
14276 .cmp(&cursor_offset_in_rename_range_end)
14277 {
14278 Ordering::Equal => {
14279 editor.select_all(&SelectAll, window, cx);
14280 return editor;
14281 }
14282 Ordering::Less => {
14283 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14284 }
14285 Ordering::Greater => {
14286 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14287 }
14288 };
14289 if rename_selection_range.end > old_name.len() {
14290 editor.select_all(&SelectAll, window, cx);
14291 } else {
14292 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14293 s.select_ranges([rename_selection_range]);
14294 });
14295 }
14296 editor
14297 });
14298 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14299 if e == &EditorEvent::Focused {
14300 cx.emit(EditorEvent::FocusedIn)
14301 }
14302 })
14303 .detach();
14304
14305 let write_highlights =
14306 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14307 let read_highlights =
14308 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14309 let ranges = write_highlights
14310 .iter()
14311 .flat_map(|(_, ranges)| ranges.iter())
14312 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14313 .cloned()
14314 .collect();
14315
14316 this.highlight_text::<Rename>(
14317 ranges,
14318 HighlightStyle {
14319 fade_out: Some(0.6),
14320 ..Default::default()
14321 },
14322 cx,
14323 );
14324 let rename_focus_handle = rename_editor.focus_handle(cx);
14325 window.focus(&rename_focus_handle);
14326 let block_id = this.insert_blocks(
14327 [BlockProperties {
14328 style: BlockStyle::Flex,
14329 placement: BlockPlacement::Below(range.start),
14330 height: Some(1),
14331 render: Arc::new({
14332 let rename_editor = rename_editor.clone();
14333 move |cx: &mut BlockContext| {
14334 let mut text_style = cx.editor_style.text.clone();
14335 if let Some(highlight_style) = old_highlight_id
14336 .and_then(|h| h.style(&cx.editor_style.syntax))
14337 {
14338 text_style = text_style.highlight(highlight_style);
14339 }
14340 div()
14341 .block_mouse_down()
14342 .pl(cx.anchor_x)
14343 .child(EditorElement::new(
14344 &rename_editor,
14345 EditorStyle {
14346 background: cx.theme().system().transparent,
14347 local_player: cx.editor_style.local_player,
14348 text: text_style,
14349 scrollbar_width: cx.editor_style.scrollbar_width,
14350 syntax: cx.editor_style.syntax.clone(),
14351 status: cx.editor_style.status.clone(),
14352 inlay_hints_style: HighlightStyle {
14353 font_weight: Some(FontWeight::BOLD),
14354 ..make_inlay_hints_style(cx.app)
14355 },
14356 inline_completion_styles: make_suggestion_styles(
14357 cx.app,
14358 ),
14359 ..EditorStyle::default()
14360 },
14361 ))
14362 .into_any_element()
14363 }
14364 }),
14365 priority: 0,
14366 }],
14367 Some(Autoscroll::fit()),
14368 cx,
14369 )[0];
14370 this.pending_rename = Some(RenameState {
14371 range,
14372 old_name,
14373 editor: rename_editor,
14374 block_id,
14375 });
14376 })?;
14377 }
14378
14379 Ok(())
14380 }))
14381 }
14382
14383 pub fn confirm_rename(
14384 &mut self,
14385 _: &ConfirmRename,
14386 window: &mut Window,
14387 cx: &mut Context<Self>,
14388 ) -> Option<Task<Result<()>>> {
14389 let rename = self.take_rename(false, window, cx)?;
14390 let workspace = self.workspace()?.downgrade();
14391 let (buffer, start) = self
14392 .buffer
14393 .read(cx)
14394 .text_anchor_for_position(rename.range.start, cx)?;
14395 let (end_buffer, _) = self
14396 .buffer
14397 .read(cx)
14398 .text_anchor_for_position(rename.range.end, cx)?;
14399 if buffer != end_buffer {
14400 return None;
14401 }
14402
14403 let old_name = rename.old_name;
14404 let new_name = rename.editor.read(cx).text(cx);
14405
14406 let rename = self.semantics_provider.as_ref()?.perform_rename(
14407 &buffer,
14408 start,
14409 new_name.clone(),
14410 cx,
14411 )?;
14412
14413 Some(cx.spawn_in(window, async move |editor, cx| {
14414 let project_transaction = rename.await?;
14415 Self::open_project_transaction(
14416 &editor,
14417 workspace,
14418 project_transaction,
14419 format!("Rename: {} → {}", old_name, new_name),
14420 cx,
14421 )
14422 .await?;
14423
14424 editor.update(cx, |editor, cx| {
14425 editor.refresh_document_highlights(cx);
14426 })?;
14427 Ok(())
14428 }))
14429 }
14430
14431 fn take_rename(
14432 &mut self,
14433 moving_cursor: bool,
14434 window: &mut Window,
14435 cx: &mut Context<Self>,
14436 ) -> Option<RenameState> {
14437 let rename = self.pending_rename.take()?;
14438 if rename.editor.focus_handle(cx).is_focused(window) {
14439 window.focus(&self.focus_handle);
14440 }
14441
14442 self.remove_blocks(
14443 [rename.block_id].into_iter().collect(),
14444 Some(Autoscroll::fit()),
14445 cx,
14446 );
14447 self.clear_highlights::<Rename>(cx);
14448 self.show_local_selections = true;
14449
14450 if moving_cursor {
14451 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14452 editor.selections.newest::<usize>(cx).head()
14453 });
14454
14455 // Update the selection to match the position of the selection inside
14456 // the rename editor.
14457 let snapshot = self.buffer.read(cx).read(cx);
14458 let rename_range = rename.range.to_offset(&snapshot);
14459 let cursor_in_editor = snapshot
14460 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14461 .min(rename_range.end);
14462 drop(snapshot);
14463
14464 self.change_selections(None, window, cx, |s| {
14465 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14466 });
14467 } else {
14468 self.refresh_document_highlights(cx);
14469 }
14470
14471 Some(rename)
14472 }
14473
14474 pub fn pending_rename(&self) -> Option<&RenameState> {
14475 self.pending_rename.as_ref()
14476 }
14477
14478 fn format(
14479 &mut self,
14480 _: &Format,
14481 window: &mut Window,
14482 cx: &mut Context<Self>,
14483 ) -> Option<Task<Result<()>>> {
14484 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14485
14486 let project = match &self.project {
14487 Some(project) => project.clone(),
14488 None => return None,
14489 };
14490
14491 Some(self.perform_format(
14492 project,
14493 FormatTrigger::Manual,
14494 FormatTarget::Buffers,
14495 window,
14496 cx,
14497 ))
14498 }
14499
14500 fn format_selections(
14501 &mut self,
14502 _: &FormatSelections,
14503 window: &mut Window,
14504 cx: &mut Context<Self>,
14505 ) -> Option<Task<Result<()>>> {
14506 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14507
14508 let project = match &self.project {
14509 Some(project) => project.clone(),
14510 None => return None,
14511 };
14512
14513 let ranges = self
14514 .selections
14515 .all_adjusted(cx)
14516 .into_iter()
14517 .map(|selection| selection.range())
14518 .collect_vec();
14519
14520 Some(self.perform_format(
14521 project,
14522 FormatTrigger::Manual,
14523 FormatTarget::Ranges(ranges),
14524 window,
14525 cx,
14526 ))
14527 }
14528
14529 fn perform_format(
14530 &mut self,
14531 project: Entity<Project>,
14532 trigger: FormatTrigger,
14533 target: FormatTarget,
14534 window: &mut Window,
14535 cx: &mut Context<Self>,
14536 ) -> Task<Result<()>> {
14537 let buffer = self.buffer.clone();
14538 let (buffers, target) = match target {
14539 FormatTarget::Buffers => {
14540 let mut buffers = buffer.read(cx).all_buffers();
14541 if trigger == FormatTrigger::Save {
14542 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14543 }
14544 (buffers, LspFormatTarget::Buffers)
14545 }
14546 FormatTarget::Ranges(selection_ranges) => {
14547 let multi_buffer = buffer.read(cx);
14548 let snapshot = multi_buffer.read(cx);
14549 let mut buffers = HashSet::default();
14550 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14551 BTreeMap::new();
14552 for selection_range in selection_ranges {
14553 for (buffer, buffer_range, _) in
14554 snapshot.range_to_buffer_ranges(selection_range)
14555 {
14556 let buffer_id = buffer.remote_id();
14557 let start = buffer.anchor_before(buffer_range.start);
14558 let end = buffer.anchor_after(buffer_range.end);
14559 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14560 buffer_id_to_ranges
14561 .entry(buffer_id)
14562 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14563 .or_insert_with(|| vec![start..end]);
14564 }
14565 }
14566 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14567 }
14568 };
14569
14570 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14571 let selections_prev = transaction_id_prev
14572 .and_then(|transaction_id_prev| {
14573 // default to selections as they were after the last edit, if we have them,
14574 // instead of how they are now.
14575 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14576 // will take you back to where you made the last edit, instead of staying where you scrolled
14577 self.selection_history
14578 .transaction(transaction_id_prev)
14579 .map(|t| t.0.clone())
14580 })
14581 .unwrap_or_else(|| {
14582 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14583 self.selections.disjoint_anchors()
14584 });
14585
14586 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14587 let format = project.update(cx, |project, cx| {
14588 project.format(buffers, target, true, trigger, cx)
14589 });
14590
14591 cx.spawn_in(window, async move |editor, cx| {
14592 let transaction = futures::select_biased! {
14593 transaction = format.log_err().fuse() => transaction,
14594 () = timeout => {
14595 log::warn!("timed out waiting for formatting");
14596 None
14597 }
14598 };
14599
14600 buffer
14601 .update(cx, |buffer, cx| {
14602 if let Some(transaction) = transaction {
14603 if !buffer.is_singleton() {
14604 buffer.push_transaction(&transaction.0, cx);
14605 }
14606 }
14607 cx.notify();
14608 })
14609 .ok();
14610
14611 if let Some(transaction_id_now) =
14612 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14613 {
14614 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14615 if has_new_transaction {
14616 _ = editor.update(cx, |editor, _| {
14617 editor
14618 .selection_history
14619 .insert_transaction(transaction_id_now, selections_prev);
14620 });
14621 }
14622 }
14623
14624 Ok(())
14625 })
14626 }
14627
14628 fn organize_imports(
14629 &mut self,
14630 _: &OrganizeImports,
14631 window: &mut Window,
14632 cx: &mut Context<Self>,
14633 ) -> Option<Task<Result<()>>> {
14634 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14635 let project = match &self.project {
14636 Some(project) => project.clone(),
14637 None => return None,
14638 };
14639 Some(self.perform_code_action_kind(
14640 project,
14641 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14642 window,
14643 cx,
14644 ))
14645 }
14646
14647 fn perform_code_action_kind(
14648 &mut self,
14649 project: Entity<Project>,
14650 kind: CodeActionKind,
14651 window: &mut Window,
14652 cx: &mut Context<Self>,
14653 ) -> Task<Result<()>> {
14654 let buffer = self.buffer.clone();
14655 let buffers = buffer.read(cx).all_buffers();
14656 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14657 let apply_action = project.update(cx, |project, cx| {
14658 project.apply_code_action_kind(buffers, kind, true, cx)
14659 });
14660 cx.spawn_in(window, async move |_, cx| {
14661 let transaction = futures::select_biased! {
14662 () = timeout => {
14663 log::warn!("timed out waiting for executing code action");
14664 None
14665 }
14666 transaction = apply_action.log_err().fuse() => transaction,
14667 };
14668 buffer
14669 .update(cx, |buffer, cx| {
14670 // check if we need this
14671 if let Some(transaction) = transaction {
14672 if !buffer.is_singleton() {
14673 buffer.push_transaction(&transaction.0, cx);
14674 }
14675 }
14676 cx.notify();
14677 })
14678 .ok();
14679 Ok(())
14680 })
14681 }
14682
14683 fn restart_language_server(
14684 &mut self,
14685 _: &RestartLanguageServer,
14686 _: &mut Window,
14687 cx: &mut Context<Self>,
14688 ) {
14689 if let Some(project) = self.project.clone() {
14690 self.buffer.update(cx, |multi_buffer, cx| {
14691 project.update(cx, |project, cx| {
14692 project.restart_language_servers_for_buffers(
14693 multi_buffer.all_buffers().into_iter().collect(),
14694 cx,
14695 );
14696 });
14697 })
14698 }
14699 }
14700
14701 fn stop_language_server(
14702 &mut self,
14703 _: &StopLanguageServer,
14704 _: &mut Window,
14705 cx: &mut Context<Self>,
14706 ) {
14707 if let Some(project) = self.project.clone() {
14708 self.buffer.update(cx, |multi_buffer, cx| {
14709 project.update(cx, |project, cx| {
14710 project.stop_language_servers_for_buffers(
14711 multi_buffer.all_buffers().into_iter().collect(),
14712 cx,
14713 );
14714 cx.emit(project::Event::RefreshInlayHints);
14715 });
14716 });
14717 }
14718 }
14719
14720 fn cancel_language_server_work(
14721 workspace: &mut Workspace,
14722 _: &actions::CancelLanguageServerWork,
14723 _: &mut Window,
14724 cx: &mut Context<Workspace>,
14725 ) {
14726 let project = workspace.project();
14727 let buffers = workspace
14728 .active_item(cx)
14729 .and_then(|item| item.act_as::<Editor>(cx))
14730 .map_or(HashSet::default(), |editor| {
14731 editor.read(cx).buffer.read(cx).all_buffers()
14732 });
14733 project.update(cx, |project, cx| {
14734 project.cancel_language_server_work_for_buffers(buffers, cx);
14735 });
14736 }
14737
14738 fn show_character_palette(
14739 &mut self,
14740 _: &ShowCharacterPalette,
14741 window: &mut Window,
14742 _: &mut Context<Self>,
14743 ) {
14744 window.show_character_palette();
14745 }
14746
14747 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14748 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14749 let buffer = self.buffer.read(cx).snapshot(cx);
14750 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14751 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14752 let is_valid = buffer
14753 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14754 .any(|entry| {
14755 entry.diagnostic.is_primary
14756 && !entry.range.is_empty()
14757 && entry.range.start == primary_range_start
14758 && entry.diagnostic.message == active_diagnostics.active_message
14759 });
14760
14761 if !is_valid {
14762 self.dismiss_diagnostics(cx);
14763 }
14764 }
14765 }
14766
14767 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14768 match &self.active_diagnostics {
14769 ActiveDiagnostic::Group(group) => Some(group),
14770 _ => None,
14771 }
14772 }
14773
14774 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14775 self.dismiss_diagnostics(cx);
14776 self.active_diagnostics = ActiveDiagnostic::All;
14777 }
14778
14779 fn activate_diagnostics(
14780 &mut self,
14781 buffer_id: BufferId,
14782 diagnostic: DiagnosticEntry<usize>,
14783 window: &mut Window,
14784 cx: &mut Context<Self>,
14785 ) {
14786 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14787 return;
14788 }
14789 self.dismiss_diagnostics(cx);
14790 let snapshot = self.snapshot(window, cx);
14791 let Some(diagnostic_renderer) = cx
14792 .try_global::<GlobalDiagnosticRenderer>()
14793 .map(|g| g.0.clone())
14794 else {
14795 return;
14796 };
14797 let buffer = self.buffer.read(cx).snapshot(cx);
14798
14799 let diagnostic_group = buffer
14800 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14801 .collect::<Vec<_>>();
14802
14803 let blocks = diagnostic_renderer.render_group(
14804 diagnostic_group,
14805 buffer_id,
14806 snapshot,
14807 cx.weak_entity(),
14808 cx,
14809 );
14810
14811 let blocks = self.display_map.update(cx, |display_map, cx| {
14812 display_map.insert_blocks(blocks, cx).into_iter().collect()
14813 });
14814 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14815 active_range: buffer.anchor_before(diagnostic.range.start)
14816 ..buffer.anchor_after(diagnostic.range.end),
14817 active_message: diagnostic.diagnostic.message.clone(),
14818 group_id: diagnostic.diagnostic.group_id,
14819 blocks,
14820 });
14821 cx.notify();
14822 }
14823
14824 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14825 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14826 return;
14827 };
14828
14829 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14830 if let ActiveDiagnostic::Group(group) = prev {
14831 self.display_map.update(cx, |display_map, cx| {
14832 display_map.remove_blocks(group.blocks, cx);
14833 });
14834 cx.notify();
14835 }
14836 }
14837
14838 /// Disable inline diagnostics rendering for this editor.
14839 pub fn disable_inline_diagnostics(&mut self) {
14840 self.inline_diagnostics_enabled = false;
14841 self.inline_diagnostics_update = Task::ready(());
14842 self.inline_diagnostics.clear();
14843 }
14844
14845 pub fn inline_diagnostics_enabled(&self) -> bool {
14846 self.inline_diagnostics_enabled
14847 }
14848
14849 pub fn show_inline_diagnostics(&self) -> bool {
14850 self.show_inline_diagnostics
14851 }
14852
14853 pub fn toggle_inline_diagnostics(
14854 &mut self,
14855 _: &ToggleInlineDiagnostics,
14856 window: &mut Window,
14857 cx: &mut Context<Editor>,
14858 ) {
14859 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14860 self.refresh_inline_diagnostics(false, window, cx);
14861 }
14862
14863 fn refresh_inline_diagnostics(
14864 &mut self,
14865 debounce: bool,
14866 window: &mut Window,
14867 cx: &mut Context<Self>,
14868 ) {
14869 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14870 self.inline_diagnostics_update = Task::ready(());
14871 self.inline_diagnostics.clear();
14872 return;
14873 }
14874
14875 let debounce_ms = ProjectSettings::get_global(cx)
14876 .diagnostics
14877 .inline
14878 .update_debounce_ms;
14879 let debounce = if debounce && debounce_ms > 0 {
14880 Some(Duration::from_millis(debounce_ms))
14881 } else {
14882 None
14883 };
14884 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14885 let editor = editor.upgrade().unwrap();
14886
14887 if let Some(debounce) = debounce {
14888 cx.background_executor().timer(debounce).await;
14889 }
14890 let Some(snapshot) = editor
14891 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14892 .ok()
14893 else {
14894 return;
14895 };
14896
14897 let new_inline_diagnostics = cx
14898 .background_spawn(async move {
14899 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14900 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14901 let message = diagnostic_entry
14902 .diagnostic
14903 .message
14904 .split_once('\n')
14905 .map(|(line, _)| line)
14906 .map(SharedString::new)
14907 .unwrap_or_else(|| {
14908 SharedString::from(diagnostic_entry.diagnostic.message)
14909 });
14910 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14911 let (Ok(i) | Err(i)) = inline_diagnostics
14912 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14913 inline_diagnostics.insert(
14914 i,
14915 (
14916 start_anchor,
14917 InlineDiagnostic {
14918 message,
14919 group_id: diagnostic_entry.diagnostic.group_id,
14920 start: diagnostic_entry.range.start.to_point(&snapshot),
14921 is_primary: diagnostic_entry.diagnostic.is_primary,
14922 severity: diagnostic_entry.diagnostic.severity,
14923 },
14924 ),
14925 );
14926 }
14927 inline_diagnostics
14928 })
14929 .await;
14930
14931 editor
14932 .update(cx, |editor, cx| {
14933 editor.inline_diagnostics = new_inline_diagnostics;
14934 cx.notify();
14935 })
14936 .ok();
14937 });
14938 }
14939
14940 pub fn set_selections_from_remote(
14941 &mut self,
14942 selections: Vec<Selection<Anchor>>,
14943 pending_selection: Option<Selection<Anchor>>,
14944 window: &mut Window,
14945 cx: &mut Context<Self>,
14946 ) {
14947 let old_cursor_position = self.selections.newest_anchor().head();
14948 self.selections.change_with(cx, |s| {
14949 s.select_anchors(selections);
14950 if let Some(pending_selection) = pending_selection {
14951 s.set_pending(pending_selection, SelectMode::Character);
14952 } else {
14953 s.clear_pending();
14954 }
14955 });
14956 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14957 }
14958
14959 fn push_to_selection_history(&mut self) {
14960 self.selection_history.push(SelectionHistoryEntry {
14961 selections: self.selections.disjoint_anchors(),
14962 select_next_state: self.select_next_state.clone(),
14963 select_prev_state: self.select_prev_state.clone(),
14964 add_selections_state: self.add_selections_state.clone(),
14965 });
14966 }
14967
14968 pub fn transact(
14969 &mut self,
14970 window: &mut Window,
14971 cx: &mut Context<Self>,
14972 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14973 ) -> Option<TransactionId> {
14974 self.start_transaction_at(Instant::now(), window, cx);
14975 update(self, window, cx);
14976 self.end_transaction_at(Instant::now(), cx)
14977 }
14978
14979 pub fn start_transaction_at(
14980 &mut self,
14981 now: Instant,
14982 window: &mut Window,
14983 cx: &mut Context<Self>,
14984 ) {
14985 self.end_selection(window, cx);
14986 if let Some(tx_id) = self
14987 .buffer
14988 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14989 {
14990 self.selection_history
14991 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14992 cx.emit(EditorEvent::TransactionBegun {
14993 transaction_id: tx_id,
14994 })
14995 }
14996 }
14997
14998 pub fn end_transaction_at(
14999 &mut self,
15000 now: Instant,
15001 cx: &mut Context<Self>,
15002 ) -> Option<TransactionId> {
15003 if let Some(transaction_id) = self
15004 .buffer
15005 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15006 {
15007 if let Some((_, end_selections)) =
15008 self.selection_history.transaction_mut(transaction_id)
15009 {
15010 *end_selections = Some(self.selections.disjoint_anchors());
15011 } else {
15012 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15013 }
15014
15015 cx.emit(EditorEvent::Edited { transaction_id });
15016 Some(transaction_id)
15017 } else {
15018 None
15019 }
15020 }
15021
15022 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15023 if self.selection_mark_mode {
15024 self.change_selections(None, window, cx, |s| {
15025 s.move_with(|_, sel| {
15026 sel.collapse_to(sel.head(), SelectionGoal::None);
15027 });
15028 })
15029 }
15030 self.selection_mark_mode = true;
15031 cx.notify();
15032 }
15033
15034 pub fn swap_selection_ends(
15035 &mut self,
15036 _: &actions::SwapSelectionEnds,
15037 window: &mut Window,
15038 cx: &mut Context<Self>,
15039 ) {
15040 self.change_selections(None, window, cx, |s| {
15041 s.move_with(|_, sel| {
15042 if sel.start != sel.end {
15043 sel.reversed = !sel.reversed
15044 }
15045 });
15046 });
15047 self.request_autoscroll(Autoscroll::newest(), cx);
15048 cx.notify();
15049 }
15050
15051 pub fn toggle_fold(
15052 &mut self,
15053 _: &actions::ToggleFold,
15054 window: &mut Window,
15055 cx: &mut Context<Self>,
15056 ) {
15057 if self.is_singleton(cx) {
15058 let selection = self.selections.newest::<Point>(cx);
15059
15060 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15061 let range = if selection.is_empty() {
15062 let point = selection.head().to_display_point(&display_map);
15063 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15064 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15065 .to_point(&display_map);
15066 start..end
15067 } else {
15068 selection.range()
15069 };
15070 if display_map.folds_in_range(range).next().is_some() {
15071 self.unfold_lines(&Default::default(), window, cx)
15072 } else {
15073 self.fold(&Default::default(), window, cx)
15074 }
15075 } else {
15076 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15077 let buffer_ids: HashSet<_> = self
15078 .selections
15079 .disjoint_anchor_ranges()
15080 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15081 .collect();
15082
15083 let should_unfold = buffer_ids
15084 .iter()
15085 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15086
15087 for buffer_id in buffer_ids {
15088 if should_unfold {
15089 self.unfold_buffer(buffer_id, cx);
15090 } else {
15091 self.fold_buffer(buffer_id, cx);
15092 }
15093 }
15094 }
15095 }
15096
15097 pub fn toggle_fold_recursive(
15098 &mut self,
15099 _: &actions::ToggleFoldRecursive,
15100 window: &mut Window,
15101 cx: &mut Context<Self>,
15102 ) {
15103 let selection = self.selections.newest::<Point>(cx);
15104
15105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15106 let range = if selection.is_empty() {
15107 let point = selection.head().to_display_point(&display_map);
15108 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15109 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15110 .to_point(&display_map);
15111 start..end
15112 } else {
15113 selection.range()
15114 };
15115 if display_map.folds_in_range(range).next().is_some() {
15116 self.unfold_recursive(&Default::default(), window, cx)
15117 } else {
15118 self.fold_recursive(&Default::default(), window, cx)
15119 }
15120 }
15121
15122 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15123 if self.is_singleton(cx) {
15124 let mut to_fold = Vec::new();
15125 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15126 let selections = self.selections.all_adjusted(cx);
15127
15128 for selection in selections {
15129 let range = selection.range().sorted();
15130 let buffer_start_row = range.start.row;
15131
15132 if range.start.row != range.end.row {
15133 let mut found = false;
15134 let mut row = range.start.row;
15135 while row <= range.end.row {
15136 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15137 {
15138 found = true;
15139 row = crease.range().end.row + 1;
15140 to_fold.push(crease);
15141 } else {
15142 row += 1
15143 }
15144 }
15145 if found {
15146 continue;
15147 }
15148 }
15149
15150 for row in (0..=range.start.row).rev() {
15151 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15152 if crease.range().end.row >= buffer_start_row {
15153 to_fold.push(crease);
15154 if row <= range.start.row {
15155 break;
15156 }
15157 }
15158 }
15159 }
15160 }
15161
15162 self.fold_creases(to_fold, true, window, cx);
15163 } else {
15164 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15165 let buffer_ids = self
15166 .selections
15167 .disjoint_anchor_ranges()
15168 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15169 .collect::<HashSet<_>>();
15170 for buffer_id in buffer_ids {
15171 self.fold_buffer(buffer_id, cx);
15172 }
15173 }
15174 }
15175
15176 fn fold_at_level(
15177 &mut self,
15178 fold_at: &FoldAtLevel,
15179 window: &mut Window,
15180 cx: &mut Context<Self>,
15181 ) {
15182 if !self.buffer.read(cx).is_singleton() {
15183 return;
15184 }
15185
15186 let fold_at_level = fold_at.0;
15187 let snapshot = self.buffer.read(cx).snapshot(cx);
15188 let mut to_fold = Vec::new();
15189 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15190
15191 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15192 while start_row < end_row {
15193 match self
15194 .snapshot(window, cx)
15195 .crease_for_buffer_row(MultiBufferRow(start_row))
15196 {
15197 Some(crease) => {
15198 let nested_start_row = crease.range().start.row + 1;
15199 let nested_end_row = crease.range().end.row;
15200
15201 if current_level < fold_at_level {
15202 stack.push((nested_start_row, nested_end_row, current_level + 1));
15203 } else if current_level == fold_at_level {
15204 to_fold.push(crease);
15205 }
15206
15207 start_row = nested_end_row + 1;
15208 }
15209 None => start_row += 1,
15210 }
15211 }
15212 }
15213
15214 self.fold_creases(to_fold, true, window, cx);
15215 }
15216
15217 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15218 if self.buffer.read(cx).is_singleton() {
15219 let mut fold_ranges = Vec::new();
15220 let snapshot = self.buffer.read(cx).snapshot(cx);
15221
15222 for row in 0..snapshot.max_row().0 {
15223 if let Some(foldable_range) = self
15224 .snapshot(window, cx)
15225 .crease_for_buffer_row(MultiBufferRow(row))
15226 {
15227 fold_ranges.push(foldable_range);
15228 }
15229 }
15230
15231 self.fold_creases(fold_ranges, true, window, cx);
15232 } else {
15233 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15234 editor
15235 .update_in(cx, |editor, _, cx| {
15236 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15237 editor.fold_buffer(buffer_id, cx);
15238 }
15239 })
15240 .ok();
15241 });
15242 }
15243 }
15244
15245 pub fn fold_function_bodies(
15246 &mut self,
15247 _: &actions::FoldFunctionBodies,
15248 window: &mut Window,
15249 cx: &mut Context<Self>,
15250 ) {
15251 let snapshot = self.buffer.read(cx).snapshot(cx);
15252
15253 let ranges = snapshot
15254 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15255 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15256 .collect::<Vec<_>>();
15257
15258 let creases = ranges
15259 .into_iter()
15260 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15261 .collect();
15262
15263 self.fold_creases(creases, true, window, cx);
15264 }
15265
15266 pub fn fold_recursive(
15267 &mut self,
15268 _: &actions::FoldRecursive,
15269 window: &mut Window,
15270 cx: &mut Context<Self>,
15271 ) {
15272 let mut to_fold = Vec::new();
15273 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15274 let selections = self.selections.all_adjusted(cx);
15275
15276 for selection in selections {
15277 let range = selection.range().sorted();
15278 let buffer_start_row = range.start.row;
15279
15280 if range.start.row != range.end.row {
15281 let mut found = false;
15282 for row in range.start.row..=range.end.row {
15283 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15284 found = true;
15285 to_fold.push(crease);
15286 }
15287 }
15288 if found {
15289 continue;
15290 }
15291 }
15292
15293 for row in (0..=range.start.row).rev() {
15294 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15295 if crease.range().end.row >= buffer_start_row {
15296 to_fold.push(crease);
15297 } else {
15298 break;
15299 }
15300 }
15301 }
15302 }
15303
15304 self.fold_creases(to_fold, true, window, cx);
15305 }
15306
15307 pub fn fold_at(
15308 &mut self,
15309 buffer_row: MultiBufferRow,
15310 window: &mut Window,
15311 cx: &mut Context<Self>,
15312 ) {
15313 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15314
15315 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15316 let autoscroll = self
15317 .selections
15318 .all::<Point>(cx)
15319 .iter()
15320 .any(|selection| crease.range().overlaps(&selection.range()));
15321
15322 self.fold_creases(vec![crease], autoscroll, window, cx);
15323 }
15324 }
15325
15326 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15327 if self.is_singleton(cx) {
15328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15329 let buffer = &display_map.buffer_snapshot;
15330 let selections = self.selections.all::<Point>(cx);
15331 let ranges = selections
15332 .iter()
15333 .map(|s| {
15334 let range = s.display_range(&display_map).sorted();
15335 let mut start = range.start.to_point(&display_map);
15336 let mut end = range.end.to_point(&display_map);
15337 start.column = 0;
15338 end.column = buffer.line_len(MultiBufferRow(end.row));
15339 start..end
15340 })
15341 .collect::<Vec<_>>();
15342
15343 self.unfold_ranges(&ranges, true, true, cx);
15344 } else {
15345 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15346 let buffer_ids = self
15347 .selections
15348 .disjoint_anchor_ranges()
15349 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15350 .collect::<HashSet<_>>();
15351 for buffer_id in buffer_ids {
15352 self.unfold_buffer(buffer_id, cx);
15353 }
15354 }
15355 }
15356
15357 pub fn unfold_recursive(
15358 &mut self,
15359 _: &UnfoldRecursive,
15360 _window: &mut Window,
15361 cx: &mut Context<Self>,
15362 ) {
15363 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15364 let selections = self.selections.all::<Point>(cx);
15365 let ranges = selections
15366 .iter()
15367 .map(|s| {
15368 let mut range = s.display_range(&display_map).sorted();
15369 *range.start.column_mut() = 0;
15370 *range.end.column_mut() = display_map.line_len(range.end.row());
15371 let start = range.start.to_point(&display_map);
15372 let end = range.end.to_point(&display_map);
15373 start..end
15374 })
15375 .collect::<Vec<_>>();
15376
15377 self.unfold_ranges(&ranges, true, true, cx);
15378 }
15379
15380 pub fn unfold_at(
15381 &mut self,
15382 buffer_row: MultiBufferRow,
15383 _window: &mut Window,
15384 cx: &mut Context<Self>,
15385 ) {
15386 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15387
15388 let intersection_range = Point::new(buffer_row.0, 0)
15389 ..Point::new(
15390 buffer_row.0,
15391 display_map.buffer_snapshot.line_len(buffer_row),
15392 );
15393
15394 let autoscroll = self
15395 .selections
15396 .all::<Point>(cx)
15397 .iter()
15398 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15399
15400 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15401 }
15402
15403 pub fn unfold_all(
15404 &mut self,
15405 _: &actions::UnfoldAll,
15406 _window: &mut Window,
15407 cx: &mut Context<Self>,
15408 ) {
15409 if self.buffer.read(cx).is_singleton() {
15410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15411 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15412 } else {
15413 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15414 editor
15415 .update(cx, |editor, cx| {
15416 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15417 editor.unfold_buffer(buffer_id, cx);
15418 }
15419 })
15420 .ok();
15421 });
15422 }
15423 }
15424
15425 pub fn fold_selected_ranges(
15426 &mut self,
15427 _: &FoldSelectedRanges,
15428 window: &mut Window,
15429 cx: &mut Context<Self>,
15430 ) {
15431 let selections = self.selections.all_adjusted(cx);
15432 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15433 let ranges = selections
15434 .into_iter()
15435 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15436 .collect::<Vec<_>>();
15437 self.fold_creases(ranges, true, window, cx);
15438 }
15439
15440 pub fn fold_ranges<T: ToOffset + Clone>(
15441 &mut self,
15442 ranges: Vec<Range<T>>,
15443 auto_scroll: bool,
15444 window: &mut Window,
15445 cx: &mut Context<Self>,
15446 ) {
15447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15448 let ranges = ranges
15449 .into_iter()
15450 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15451 .collect::<Vec<_>>();
15452 self.fold_creases(ranges, auto_scroll, window, cx);
15453 }
15454
15455 pub fn fold_creases<T: ToOffset + Clone>(
15456 &mut self,
15457 creases: Vec<Crease<T>>,
15458 auto_scroll: bool,
15459 _window: &mut Window,
15460 cx: &mut Context<Self>,
15461 ) {
15462 if creases.is_empty() {
15463 return;
15464 }
15465
15466 let mut buffers_affected = HashSet::default();
15467 let multi_buffer = self.buffer().read(cx);
15468 for crease in &creases {
15469 if let Some((_, buffer, _)) =
15470 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15471 {
15472 buffers_affected.insert(buffer.read(cx).remote_id());
15473 };
15474 }
15475
15476 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15477
15478 if auto_scroll {
15479 self.request_autoscroll(Autoscroll::fit(), cx);
15480 }
15481
15482 cx.notify();
15483
15484 self.scrollbar_marker_state.dirty = true;
15485 self.folds_did_change(cx);
15486 }
15487
15488 /// Removes any folds whose ranges intersect any of the given ranges.
15489 pub fn unfold_ranges<T: ToOffset + Clone>(
15490 &mut self,
15491 ranges: &[Range<T>],
15492 inclusive: bool,
15493 auto_scroll: bool,
15494 cx: &mut Context<Self>,
15495 ) {
15496 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15497 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15498 });
15499 self.folds_did_change(cx);
15500 }
15501
15502 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15503 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15504 return;
15505 }
15506 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15507 self.display_map.update(cx, |display_map, cx| {
15508 display_map.fold_buffers([buffer_id], cx)
15509 });
15510 cx.emit(EditorEvent::BufferFoldToggled {
15511 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15512 folded: true,
15513 });
15514 cx.notify();
15515 }
15516
15517 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15518 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15519 return;
15520 }
15521 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15522 self.display_map.update(cx, |display_map, cx| {
15523 display_map.unfold_buffers([buffer_id], cx);
15524 });
15525 cx.emit(EditorEvent::BufferFoldToggled {
15526 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15527 folded: false,
15528 });
15529 cx.notify();
15530 }
15531
15532 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15533 self.display_map.read(cx).is_buffer_folded(buffer)
15534 }
15535
15536 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15537 self.display_map.read(cx).folded_buffers()
15538 }
15539
15540 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15541 self.display_map.update(cx, |display_map, cx| {
15542 display_map.disable_header_for_buffer(buffer_id, cx);
15543 });
15544 cx.notify();
15545 }
15546
15547 /// Removes any folds with the given ranges.
15548 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15549 &mut self,
15550 ranges: &[Range<T>],
15551 type_id: TypeId,
15552 auto_scroll: bool,
15553 cx: &mut Context<Self>,
15554 ) {
15555 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15556 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15557 });
15558 self.folds_did_change(cx);
15559 }
15560
15561 fn remove_folds_with<T: ToOffset + Clone>(
15562 &mut self,
15563 ranges: &[Range<T>],
15564 auto_scroll: bool,
15565 cx: &mut Context<Self>,
15566 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15567 ) {
15568 if ranges.is_empty() {
15569 return;
15570 }
15571
15572 let mut buffers_affected = HashSet::default();
15573 let multi_buffer = self.buffer().read(cx);
15574 for range in ranges {
15575 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15576 buffers_affected.insert(buffer.read(cx).remote_id());
15577 };
15578 }
15579
15580 self.display_map.update(cx, update);
15581
15582 if auto_scroll {
15583 self.request_autoscroll(Autoscroll::fit(), cx);
15584 }
15585
15586 cx.notify();
15587 self.scrollbar_marker_state.dirty = true;
15588 self.active_indent_guides_state.dirty = true;
15589 }
15590
15591 pub fn update_fold_widths(
15592 &mut self,
15593 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15594 cx: &mut Context<Self>,
15595 ) -> bool {
15596 self.display_map
15597 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15598 }
15599
15600 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15601 self.display_map.read(cx).fold_placeholder.clone()
15602 }
15603
15604 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15605 self.buffer.update(cx, |buffer, cx| {
15606 buffer.set_all_diff_hunks_expanded(cx);
15607 });
15608 }
15609
15610 pub fn expand_all_diff_hunks(
15611 &mut self,
15612 _: &ExpandAllDiffHunks,
15613 _window: &mut Window,
15614 cx: &mut Context<Self>,
15615 ) {
15616 self.buffer.update(cx, |buffer, cx| {
15617 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15618 });
15619 }
15620
15621 pub fn toggle_selected_diff_hunks(
15622 &mut self,
15623 _: &ToggleSelectedDiffHunks,
15624 _window: &mut Window,
15625 cx: &mut Context<Self>,
15626 ) {
15627 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15628 self.toggle_diff_hunks_in_ranges(ranges, cx);
15629 }
15630
15631 pub fn diff_hunks_in_ranges<'a>(
15632 &'a self,
15633 ranges: &'a [Range<Anchor>],
15634 buffer: &'a MultiBufferSnapshot,
15635 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15636 ranges.iter().flat_map(move |range| {
15637 let end_excerpt_id = range.end.excerpt_id;
15638 let range = range.to_point(buffer);
15639 let mut peek_end = range.end;
15640 if range.end.row < buffer.max_row().0 {
15641 peek_end = Point::new(range.end.row + 1, 0);
15642 }
15643 buffer
15644 .diff_hunks_in_range(range.start..peek_end)
15645 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15646 })
15647 }
15648
15649 pub fn has_stageable_diff_hunks_in_ranges(
15650 &self,
15651 ranges: &[Range<Anchor>],
15652 snapshot: &MultiBufferSnapshot,
15653 ) -> bool {
15654 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15655 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15656 }
15657
15658 pub fn toggle_staged_selected_diff_hunks(
15659 &mut self,
15660 _: &::git::ToggleStaged,
15661 _: &mut Window,
15662 cx: &mut Context<Self>,
15663 ) {
15664 let snapshot = self.buffer.read(cx).snapshot(cx);
15665 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15666 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15667 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15668 }
15669
15670 pub fn set_render_diff_hunk_controls(
15671 &mut self,
15672 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15673 cx: &mut Context<Self>,
15674 ) {
15675 self.render_diff_hunk_controls = render_diff_hunk_controls;
15676 cx.notify();
15677 }
15678
15679 pub fn stage_and_next(
15680 &mut self,
15681 _: &::git::StageAndNext,
15682 window: &mut Window,
15683 cx: &mut Context<Self>,
15684 ) {
15685 self.do_stage_or_unstage_and_next(true, window, cx);
15686 }
15687
15688 pub fn unstage_and_next(
15689 &mut self,
15690 _: &::git::UnstageAndNext,
15691 window: &mut Window,
15692 cx: &mut Context<Self>,
15693 ) {
15694 self.do_stage_or_unstage_and_next(false, window, cx);
15695 }
15696
15697 pub fn stage_or_unstage_diff_hunks(
15698 &mut self,
15699 stage: bool,
15700 ranges: Vec<Range<Anchor>>,
15701 cx: &mut Context<Self>,
15702 ) {
15703 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15704 cx.spawn(async move |this, cx| {
15705 task.await?;
15706 this.update(cx, |this, cx| {
15707 let snapshot = this.buffer.read(cx).snapshot(cx);
15708 let chunk_by = this
15709 .diff_hunks_in_ranges(&ranges, &snapshot)
15710 .chunk_by(|hunk| hunk.buffer_id);
15711 for (buffer_id, hunks) in &chunk_by {
15712 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15713 }
15714 })
15715 })
15716 .detach_and_log_err(cx);
15717 }
15718
15719 fn save_buffers_for_ranges_if_needed(
15720 &mut self,
15721 ranges: &[Range<Anchor>],
15722 cx: &mut Context<Editor>,
15723 ) -> Task<Result<()>> {
15724 let multibuffer = self.buffer.read(cx);
15725 let snapshot = multibuffer.read(cx);
15726 let buffer_ids: HashSet<_> = ranges
15727 .iter()
15728 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15729 .collect();
15730 drop(snapshot);
15731
15732 let mut buffers = HashSet::default();
15733 for buffer_id in buffer_ids {
15734 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15735 let buffer = buffer_entity.read(cx);
15736 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15737 {
15738 buffers.insert(buffer_entity);
15739 }
15740 }
15741 }
15742
15743 if let Some(project) = &self.project {
15744 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15745 } else {
15746 Task::ready(Ok(()))
15747 }
15748 }
15749
15750 fn do_stage_or_unstage_and_next(
15751 &mut self,
15752 stage: bool,
15753 window: &mut Window,
15754 cx: &mut Context<Self>,
15755 ) {
15756 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15757
15758 if ranges.iter().any(|range| range.start != range.end) {
15759 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15760 return;
15761 }
15762
15763 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15764 let snapshot = self.snapshot(window, cx);
15765 let position = self.selections.newest::<Point>(cx).head();
15766 let mut row = snapshot
15767 .buffer_snapshot
15768 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15769 .find(|hunk| hunk.row_range.start.0 > position.row)
15770 .map(|hunk| hunk.row_range.start);
15771
15772 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15773 // Outside of the project diff editor, wrap around to the beginning.
15774 if !all_diff_hunks_expanded {
15775 row = row.or_else(|| {
15776 snapshot
15777 .buffer_snapshot
15778 .diff_hunks_in_range(Point::zero()..position)
15779 .find(|hunk| hunk.row_range.end.0 < position.row)
15780 .map(|hunk| hunk.row_range.start)
15781 });
15782 }
15783
15784 if let Some(row) = row {
15785 let destination = Point::new(row.0, 0);
15786 let autoscroll = Autoscroll::center();
15787
15788 self.unfold_ranges(&[destination..destination], false, false, cx);
15789 self.change_selections(Some(autoscroll), window, cx, |s| {
15790 s.select_ranges([destination..destination]);
15791 });
15792 }
15793 }
15794
15795 fn do_stage_or_unstage(
15796 &self,
15797 stage: bool,
15798 buffer_id: BufferId,
15799 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15800 cx: &mut App,
15801 ) -> Option<()> {
15802 let project = self.project.as_ref()?;
15803 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15804 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15805 let buffer_snapshot = buffer.read(cx).snapshot();
15806 let file_exists = buffer_snapshot
15807 .file()
15808 .is_some_and(|file| file.disk_state().exists());
15809 diff.update(cx, |diff, cx| {
15810 diff.stage_or_unstage_hunks(
15811 stage,
15812 &hunks
15813 .map(|hunk| buffer_diff::DiffHunk {
15814 buffer_range: hunk.buffer_range,
15815 diff_base_byte_range: hunk.diff_base_byte_range,
15816 secondary_status: hunk.secondary_status,
15817 range: Point::zero()..Point::zero(), // unused
15818 })
15819 .collect::<Vec<_>>(),
15820 &buffer_snapshot,
15821 file_exists,
15822 cx,
15823 )
15824 });
15825 None
15826 }
15827
15828 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15829 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15830 self.buffer
15831 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15832 }
15833
15834 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15835 self.buffer.update(cx, |buffer, cx| {
15836 let ranges = vec![Anchor::min()..Anchor::max()];
15837 if !buffer.all_diff_hunks_expanded()
15838 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15839 {
15840 buffer.collapse_diff_hunks(ranges, cx);
15841 true
15842 } else {
15843 false
15844 }
15845 })
15846 }
15847
15848 fn toggle_diff_hunks_in_ranges(
15849 &mut self,
15850 ranges: Vec<Range<Anchor>>,
15851 cx: &mut Context<Editor>,
15852 ) {
15853 self.buffer.update(cx, |buffer, cx| {
15854 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15855 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15856 })
15857 }
15858
15859 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15860 self.buffer.update(cx, |buffer, cx| {
15861 let snapshot = buffer.snapshot(cx);
15862 let excerpt_id = range.end.excerpt_id;
15863 let point_range = range.to_point(&snapshot);
15864 let expand = !buffer.single_hunk_is_expanded(range, cx);
15865 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15866 })
15867 }
15868
15869 pub(crate) fn apply_all_diff_hunks(
15870 &mut self,
15871 _: &ApplyAllDiffHunks,
15872 window: &mut Window,
15873 cx: &mut Context<Self>,
15874 ) {
15875 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15876
15877 let buffers = self.buffer.read(cx).all_buffers();
15878 for branch_buffer in buffers {
15879 branch_buffer.update(cx, |branch_buffer, cx| {
15880 branch_buffer.merge_into_base(Vec::new(), cx);
15881 });
15882 }
15883
15884 if let Some(project) = self.project.clone() {
15885 self.save(true, project, window, cx).detach_and_log_err(cx);
15886 }
15887 }
15888
15889 pub(crate) fn apply_selected_diff_hunks(
15890 &mut self,
15891 _: &ApplyDiffHunk,
15892 window: &mut Window,
15893 cx: &mut Context<Self>,
15894 ) {
15895 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15896 let snapshot = self.snapshot(window, cx);
15897 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15898 let mut ranges_by_buffer = HashMap::default();
15899 self.transact(window, cx, |editor, _window, cx| {
15900 for hunk in hunks {
15901 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15902 ranges_by_buffer
15903 .entry(buffer.clone())
15904 .or_insert_with(Vec::new)
15905 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15906 }
15907 }
15908
15909 for (buffer, ranges) in ranges_by_buffer {
15910 buffer.update(cx, |buffer, cx| {
15911 buffer.merge_into_base(ranges, cx);
15912 });
15913 }
15914 });
15915
15916 if let Some(project) = self.project.clone() {
15917 self.save(true, project, window, cx).detach_and_log_err(cx);
15918 }
15919 }
15920
15921 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15922 if hovered != self.gutter_hovered {
15923 self.gutter_hovered = hovered;
15924 cx.notify();
15925 }
15926 }
15927
15928 pub fn insert_blocks(
15929 &mut self,
15930 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15931 autoscroll: Option<Autoscroll>,
15932 cx: &mut Context<Self>,
15933 ) -> Vec<CustomBlockId> {
15934 let blocks = self
15935 .display_map
15936 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15937 if let Some(autoscroll) = autoscroll {
15938 self.request_autoscroll(autoscroll, cx);
15939 }
15940 cx.notify();
15941 blocks
15942 }
15943
15944 pub fn resize_blocks(
15945 &mut self,
15946 heights: HashMap<CustomBlockId, u32>,
15947 autoscroll: Option<Autoscroll>,
15948 cx: &mut Context<Self>,
15949 ) {
15950 self.display_map
15951 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15952 if let Some(autoscroll) = autoscroll {
15953 self.request_autoscroll(autoscroll, cx);
15954 }
15955 cx.notify();
15956 }
15957
15958 pub fn replace_blocks(
15959 &mut self,
15960 renderers: HashMap<CustomBlockId, RenderBlock>,
15961 autoscroll: Option<Autoscroll>,
15962 cx: &mut Context<Self>,
15963 ) {
15964 self.display_map
15965 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15966 if let Some(autoscroll) = autoscroll {
15967 self.request_autoscroll(autoscroll, cx);
15968 }
15969 cx.notify();
15970 }
15971
15972 pub fn remove_blocks(
15973 &mut self,
15974 block_ids: HashSet<CustomBlockId>,
15975 autoscroll: Option<Autoscroll>,
15976 cx: &mut Context<Self>,
15977 ) {
15978 self.display_map.update(cx, |display_map, cx| {
15979 display_map.remove_blocks(block_ids, cx)
15980 });
15981 if let Some(autoscroll) = autoscroll {
15982 self.request_autoscroll(autoscroll, cx);
15983 }
15984 cx.notify();
15985 }
15986
15987 pub fn row_for_block(
15988 &self,
15989 block_id: CustomBlockId,
15990 cx: &mut Context<Self>,
15991 ) -> Option<DisplayRow> {
15992 self.display_map
15993 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15994 }
15995
15996 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15997 self.focused_block = Some(focused_block);
15998 }
15999
16000 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16001 self.focused_block.take()
16002 }
16003
16004 pub fn insert_creases(
16005 &mut self,
16006 creases: impl IntoIterator<Item = Crease<Anchor>>,
16007 cx: &mut Context<Self>,
16008 ) -> Vec<CreaseId> {
16009 self.display_map
16010 .update(cx, |map, cx| map.insert_creases(creases, cx))
16011 }
16012
16013 pub fn remove_creases(
16014 &mut self,
16015 ids: impl IntoIterator<Item = CreaseId>,
16016 cx: &mut Context<Self>,
16017 ) {
16018 self.display_map
16019 .update(cx, |map, cx| map.remove_creases(ids, cx));
16020 }
16021
16022 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16023 self.display_map
16024 .update(cx, |map, cx| map.snapshot(cx))
16025 .longest_row()
16026 }
16027
16028 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16029 self.display_map
16030 .update(cx, |map, cx| map.snapshot(cx))
16031 .max_point()
16032 }
16033
16034 pub fn text(&self, cx: &App) -> String {
16035 self.buffer.read(cx).read(cx).text()
16036 }
16037
16038 pub fn is_empty(&self, cx: &App) -> bool {
16039 self.buffer.read(cx).read(cx).is_empty()
16040 }
16041
16042 pub fn text_option(&self, cx: &App) -> Option<String> {
16043 let text = self.text(cx);
16044 let text = text.trim();
16045
16046 if text.is_empty() {
16047 return None;
16048 }
16049
16050 Some(text.to_string())
16051 }
16052
16053 pub fn set_text(
16054 &mut self,
16055 text: impl Into<Arc<str>>,
16056 window: &mut Window,
16057 cx: &mut Context<Self>,
16058 ) {
16059 self.transact(window, cx, |this, _, cx| {
16060 this.buffer
16061 .read(cx)
16062 .as_singleton()
16063 .expect("you can only call set_text on editors for singleton buffers")
16064 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16065 });
16066 }
16067
16068 pub fn display_text(&self, cx: &mut App) -> String {
16069 self.display_map
16070 .update(cx, |map, cx| map.snapshot(cx))
16071 .text()
16072 }
16073
16074 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16075 let mut wrap_guides = smallvec::smallvec![];
16076
16077 if self.show_wrap_guides == Some(false) {
16078 return wrap_guides;
16079 }
16080
16081 let settings = self.buffer.read(cx).language_settings(cx);
16082 if settings.show_wrap_guides {
16083 match self.soft_wrap_mode(cx) {
16084 SoftWrap::Column(soft_wrap) => {
16085 wrap_guides.push((soft_wrap as usize, true));
16086 }
16087 SoftWrap::Bounded(soft_wrap) => {
16088 wrap_guides.push((soft_wrap as usize, true));
16089 }
16090 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16091 }
16092 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16093 }
16094
16095 wrap_guides
16096 }
16097
16098 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16099 let settings = self.buffer.read(cx).language_settings(cx);
16100 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16101 match mode {
16102 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16103 SoftWrap::None
16104 }
16105 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16106 language_settings::SoftWrap::PreferredLineLength => {
16107 SoftWrap::Column(settings.preferred_line_length)
16108 }
16109 language_settings::SoftWrap::Bounded => {
16110 SoftWrap::Bounded(settings.preferred_line_length)
16111 }
16112 }
16113 }
16114
16115 pub fn set_soft_wrap_mode(
16116 &mut self,
16117 mode: language_settings::SoftWrap,
16118
16119 cx: &mut Context<Self>,
16120 ) {
16121 self.soft_wrap_mode_override = Some(mode);
16122 cx.notify();
16123 }
16124
16125 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16126 self.hard_wrap = hard_wrap;
16127 cx.notify();
16128 }
16129
16130 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16131 self.text_style_refinement = Some(style);
16132 }
16133
16134 /// called by the Element so we know what style we were most recently rendered with.
16135 pub(crate) fn set_style(
16136 &mut self,
16137 style: EditorStyle,
16138 window: &mut Window,
16139 cx: &mut Context<Self>,
16140 ) {
16141 let rem_size = window.rem_size();
16142 self.display_map.update(cx, |map, cx| {
16143 map.set_font(
16144 style.text.font(),
16145 style.text.font_size.to_pixels(rem_size),
16146 cx,
16147 )
16148 });
16149 self.style = Some(style);
16150 }
16151
16152 pub fn style(&self) -> Option<&EditorStyle> {
16153 self.style.as_ref()
16154 }
16155
16156 // Called by the element. This method is not designed to be called outside of the editor
16157 // element's layout code because it does not notify when rewrapping is computed synchronously.
16158 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16159 self.display_map
16160 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16161 }
16162
16163 pub fn set_soft_wrap(&mut self) {
16164 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16165 }
16166
16167 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16168 if self.soft_wrap_mode_override.is_some() {
16169 self.soft_wrap_mode_override.take();
16170 } else {
16171 let soft_wrap = match self.soft_wrap_mode(cx) {
16172 SoftWrap::GitDiff => return,
16173 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16174 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16175 language_settings::SoftWrap::None
16176 }
16177 };
16178 self.soft_wrap_mode_override = Some(soft_wrap);
16179 }
16180 cx.notify();
16181 }
16182
16183 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16184 let Some(workspace) = self.workspace() else {
16185 return;
16186 };
16187 let fs = workspace.read(cx).app_state().fs.clone();
16188 let current_show = TabBarSettings::get_global(cx).show;
16189 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16190 setting.show = Some(!current_show);
16191 });
16192 }
16193
16194 pub fn toggle_indent_guides(
16195 &mut self,
16196 _: &ToggleIndentGuides,
16197 _: &mut Window,
16198 cx: &mut Context<Self>,
16199 ) {
16200 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16201 self.buffer
16202 .read(cx)
16203 .language_settings(cx)
16204 .indent_guides
16205 .enabled
16206 });
16207 self.show_indent_guides = Some(!currently_enabled);
16208 cx.notify();
16209 }
16210
16211 fn should_show_indent_guides(&self) -> Option<bool> {
16212 self.show_indent_guides
16213 }
16214
16215 pub fn toggle_line_numbers(
16216 &mut self,
16217 _: &ToggleLineNumbers,
16218 _: &mut Window,
16219 cx: &mut Context<Self>,
16220 ) {
16221 let mut editor_settings = EditorSettings::get_global(cx).clone();
16222 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16223 EditorSettings::override_global(editor_settings, cx);
16224 }
16225
16226 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16227 if let Some(show_line_numbers) = self.show_line_numbers {
16228 return show_line_numbers;
16229 }
16230 EditorSettings::get_global(cx).gutter.line_numbers
16231 }
16232
16233 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16234 self.use_relative_line_numbers
16235 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16236 }
16237
16238 pub fn toggle_relative_line_numbers(
16239 &mut self,
16240 _: &ToggleRelativeLineNumbers,
16241 _: &mut Window,
16242 cx: &mut Context<Self>,
16243 ) {
16244 let is_relative = self.should_use_relative_line_numbers(cx);
16245 self.set_relative_line_number(Some(!is_relative), cx)
16246 }
16247
16248 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16249 self.use_relative_line_numbers = is_relative;
16250 cx.notify();
16251 }
16252
16253 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16254 self.show_gutter = show_gutter;
16255 cx.notify();
16256 }
16257
16258 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16259 self.show_scrollbars = show_scrollbars;
16260 cx.notify();
16261 }
16262
16263 pub fn disable_scrolling(&mut self, cx: &mut Context<Self>) {
16264 self.disable_scrolling = true;
16265 cx.notify();
16266 }
16267
16268 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16269 self.show_line_numbers = Some(show_line_numbers);
16270 cx.notify();
16271 }
16272
16273 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16274 self.disable_expand_excerpt_buttons = true;
16275 cx.notify();
16276 }
16277
16278 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16279 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16280 cx.notify();
16281 }
16282
16283 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16284 self.show_code_actions = Some(show_code_actions);
16285 cx.notify();
16286 }
16287
16288 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16289 self.show_runnables = Some(show_runnables);
16290 cx.notify();
16291 }
16292
16293 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16294 self.show_breakpoints = Some(show_breakpoints);
16295 cx.notify();
16296 }
16297
16298 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16299 if self.display_map.read(cx).masked != masked {
16300 self.display_map.update(cx, |map, _| map.masked = masked);
16301 }
16302 cx.notify()
16303 }
16304
16305 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16306 self.show_wrap_guides = Some(show_wrap_guides);
16307 cx.notify();
16308 }
16309
16310 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16311 self.show_indent_guides = Some(show_indent_guides);
16312 cx.notify();
16313 }
16314
16315 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16316 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16317 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16318 if let Some(dir) = file.abs_path(cx).parent() {
16319 return Some(dir.to_owned());
16320 }
16321 }
16322
16323 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16324 return Some(project_path.path.to_path_buf());
16325 }
16326 }
16327
16328 None
16329 }
16330
16331 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16332 self.active_excerpt(cx)?
16333 .1
16334 .read(cx)
16335 .file()
16336 .and_then(|f| f.as_local())
16337 }
16338
16339 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16340 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16341 let buffer = buffer.read(cx);
16342 if let Some(project_path) = buffer.project_path(cx) {
16343 let project = self.project.as_ref()?.read(cx);
16344 project.absolute_path(&project_path, cx)
16345 } else {
16346 buffer
16347 .file()
16348 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16349 }
16350 })
16351 }
16352
16353 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16354 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16355 let project_path = buffer.read(cx).project_path(cx)?;
16356 let project = self.project.as_ref()?.read(cx);
16357 let entry = project.entry_for_path(&project_path, cx)?;
16358 let path = entry.path.to_path_buf();
16359 Some(path)
16360 })
16361 }
16362
16363 pub fn reveal_in_finder(
16364 &mut self,
16365 _: &RevealInFileManager,
16366 _window: &mut Window,
16367 cx: &mut Context<Self>,
16368 ) {
16369 if let Some(target) = self.target_file(cx) {
16370 cx.reveal_path(&target.abs_path(cx));
16371 }
16372 }
16373
16374 pub fn copy_path(
16375 &mut self,
16376 _: &zed_actions::workspace::CopyPath,
16377 _window: &mut Window,
16378 cx: &mut Context<Self>,
16379 ) {
16380 if let Some(path) = self.target_file_abs_path(cx) {
16381 if let Some(path) = path.to_str() {
16382 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16383 }
16384 }
16385 }
16386
16387 pub fn copy_relative_path(
16388 &mut self,
16389 _: &zed_actions::workspace::CopyRelativePath,
16390 _window: &mut Window,
16391 cx: &mut Context<Self>,
16392 ) {
16393 if let Some(path) = self.target_file_path(cx) {
16394 if let Some(path) = path.to_str() {
16395 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16396 }
16397 }
16398 }
16399
16400 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16401 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16402 buffer.read(cx).project_path(cx)
16403 } else {
16404 None
16405 }
16406 }
16407
16408 // Returns true if the editor handled a go-to-line request
16409 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16410 maybe!({
16411 let breakpoint_store = self.breakpoint_store.as_ref()?;
16412
16413 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16414 else {
16415 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16416 return None;
16417 };
16418
16419 let position = active_stack_frame.position;
16420 let buffer_id = position.buffer_id?;
16421 let snapshot = self
16422 .project
16423 .as_ref()?
16424 .read(cx)
16425 .buffer_for_id(buffer_id, cx)?
16426 .read(cx)
16427 .snapshot();
16428
16429 let mut handled = false;
16430 for (id, ExcerptRange { context, .. }) in
16431 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16432 {
16433 if context.start.cmp(&position, &snapshot).is_ge()
16434 || context.end.cmp(&position, &snapshot).is_lt()
16435 {
16436 continue;
16437 }
16438 let snapshot = self.buffer.read(cx).snapshot(cx);
16439 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16440
16441 handled = true;
16442 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16443 self.go_to_line::<DebugCurrentRowHighlight>(
16444 multibuffer_anchor,
16445 Some(cx.theme().colors().editor_debugger_active_line_background),
16446 window,
16447 cx,
16448 );
16449
16450 cx.notify();
16451 }
16452
16453 handled.then_some(())
16454 })
16455 .is_some()
16456 }
16457
16458 pub fn copy_file_name_without_extension(
16459 &mut self,
16460 _: &CopyFileNameWithoutExtension,
16461 _: &mut Window,
16462 cx: &mut Context<Self>,
16463 ) {
16464 if let Some(file) = self.target_file(cx) {
16465 if let Some(file_stem) = file.path().file_stem() {
16466 if let Some(name) = file_stem.to_str() {
16467 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16468 }
16469 }
16470 }
16471 }
16472
16473 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16474 if let Some(file) = self.target_file(cx) {
16475 if let Some(file_name) = file.path().file_name() {
16476 if let Some(name) = file_name.to_str() {
16477 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16478 }
16479 }
16480 }
16481 }
16482
16483 pub fn toggle_git_blame(
16484 &mut self,
16485 _: &::git::Blame,
16486 window: &mut Window,
16487 cx: &mut Context<Self>,
16488 ) {
16489 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16490
16491 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16492 self.start_git_blame(true, window, cx);
16493 }
16494
16495 cx.notify();
16496 }
16497
16498 pub fn toggle_git_blame_inline(
16499 &mut self,
16500 _: &ToggleGitBlameInline,
16501 window: &mut Window,
16502 cx: &mut Context<Self>,
16503 ) {
16504 self.toggle_git_blame_inline_internal(true, window, cx);
16505 cx.notify();
16506 }
16507
16508 pub fn open_git_blame_commit(
16509 &mut self,
16510 _: &OpenGitBlameCommit,
16511 window: &mut Window,
16512 cx: &mut Context<Self>,
16513 ) {
16514 self.open_git_blame_commit_internal(window, cx);
16515 }
16516
16517 fn open_git_blame_commit_internal(
16518 &mut self,
16519 window: &mut Window,
16520 cx: &mut Context<Self>,
16521 ) -> Option<()> {
16522 let blame = self.blame.as_ref()?;
16523 let snapshot = self.snapshot(window, cx);
16524 let cursor = self.selections.newest::<Point>(cx).head();
16525 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16526 let blame_entry = blame
16527 .update(cx, |blame, cx| {
16528 blame
16529 .blame_for_rows(
16530 &[RowInfo {
16531 buffer_id: Some(buffer.remote_id()),
16532 buffer_row: Some(point.row),
16533 ..Default::default()
16534 }],
16535 cx,
16536 )
16537 .next()
16538 })
16539 .flatten()?;
16540 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16541 let repo = blame.read(cx).repository(cx)?;
16542 let workspace = self.workspace()?.downgrade();
16543 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16544 None
16545 }
16546
16547 pub fn git_blame_inline_enabled(&self) -> bool {
16548 self.git_blame_inline_enabled
16549 }
16550
16551 pub fn toggle_selection_menu(
16552 &mut self,
16553 _: &ToggleSelectionMenu,
16554 _: &mut Window,
16555 cx: &mut Context<Self>,
16556 ) {
16557 self.show_selection_menu = self
16558 .show_selection_menu
16559 .map(|show_selections_menu| !show_selections_menu)
16560 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16561
16562 cx.notify();
16563 }
16564
16565 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16566 self.show_selection_menu
16567 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16568 }
16569
16570 fn start_git_blame(
16571 &mut self,
16572 user_triggered: bool,
16573 window: &mut Window,
16574 cx: &mut Context<Self>,
16575 ) {
16576 if let Some(project) = self.project.as_ref() {
16577 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16578 return;
16579 };
16580
16581 if buffer.read(cx).file().is_none() {
16582 return;
16583 }
16584
16585 let focused = self.focus_handle(cx).contains_focused(window, cx);
16586
16587 let project = project.clone();
16588 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16589 self.blame_subscription =
16590 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16591 self.blame = Some(blame);
16592 }
16593 }
16594
16595 fn toggle_git_blame_inline_internal(
16596 &mut self,
16597 user_triggered: bool,
16598 window: &mut Window,
16599 cx: &mut Context<Self>,
16600 ) {
16601 if self.git_blame_inline_enabled {
16602 self.git_blame_inline_enabled = false;
16603 self.show_git_blame_inline = false;
16604 self.show_git_blame_inline_delay_task.take();
16605 } else {
16606 self.git_blame_inline_enabled = true;
16607 self.start_git_blame_inline(user_triggered, window, cx);
16608 }
16609
16610 cx.notify();
16611 }
16612
16613 fn start_git_blame_inline(
16614 &mut self,
16615 user_triggered: bool,
16616 window: &mut Window,
16617 cx: &mut Context<Self>,
16618 ) {
16619 self.start_git_blame(user_triggered, window, cx);
16620
16621 if ProjectSettings::get_global(cx)
16622 .git
16623 .inline_blame_delay()
16624 .is_some()
16625 {
16626 self.start_inline_blame_timer(window, cx);
16627 } else {
16628 self.show_git_blame_inline = true
16629 }
16630 }
16631
16632 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16633 self.blame.as_ref()
16634 }
16635
16636 pub fn show_git_blame_gutter(&self) -> bool {
16637 self.show_git_blame_gutter
16638 }
16639
16640 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16641 self.show_git_blame_gutter && self.has_blame_entries(cx)
16642 }
16643
16644 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16645 self.show_git_blame_inline
16646 && (self.focus_handle.is_focused(window)
16647 || self
16648 .git_blame_inline_tooltip
16649 .as_ref()
16650 .and_then(|t| t.upgrade())
16651 .is_some())
16652 && !self.newest_selection_head_on_empty_line(cx)
16653 && self.has_blame_entries(cx)
16654 }
16655
16656 fn has_blame_entries(&self, cx: &App) -> bool {
16657 self.blame()
16658 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16659 }
16660
16661 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16662 let cursor_anchor = self.selections.newest_anchor().head();
16663
16664 let snapshot = self.buffer.read(cx).snapshot(cx);
16665 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16666
16667 snapshot.line_len(buffer_row) == 0
16668 }
16669
16670 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16671 let buffer_and_selection = maybe!({
16672 let selection = self.selections.newest::<Point>(cx);
16673 let selection_range = selection.range();
16674
16675 let multi_buffer = self.buffer().read(cx);
16676 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16677 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16678
16679 let (buffer, range, _) = if selection.reversed {
16680 buffer_ranges.first()
16681 } else {
16682 buffer_ranges.last()
16683 }?;
16684
16685 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16686 ..text::ToPoint::to_point(&range.end, &buffer).row;
16687 Some((
16688 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16689 selection,
16690 ))
16691 });
16692
16693 let Some((buffer, selection)) = buffer_and_selection else {
16694 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16695 };
16696
16697 let Some(project) = self.project.as_ref() else {
16698 return Task::ready(Err(anyhow!("editor does not have project")));
16699 };
16700
16701 project.update(cx, |project, cx| {
16702 project.get_permalink_to_line(&buffer, selection, cx)
16703 })
16704 }
16705
16706 pub fn copy_permalink_to_line(
16707 &mut self,
16708 _: &CopyPermalinkToLine,
16709 window: &mut Window,
16710 cx: &mut Context<Self>,
16711 ) {
16712 let permalink_task = self.get_permalink_to_line(cx);
16713 let workspace = self.workspace();
16714
16715 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16716 Ok(permalink) => {
16717 cx.update(|_, cx| {
16718 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16719 })
16720 .ok();
16721 }
16722 Err(err) => {
16723 let message = format!("Failed to copy permalink: {err}");
16724
16725 Err::<(), anyhow::Error>(err).log_err();
16726
16727 if let Some(workspace) = workspace {
16728 workspace
16729 .update_in(cx, |workspace, _, cx| {
16730 struct CopyPermalinkToLine;
16731
16732 workspace.show_toast(
16733 Toast::new(
16734 NotificationId::unique::<CopyPermalinkToLine>(),
16735 message,
16736 ),
16737 cx,
16738 )
16739 })
16740 .ok();
16741 }
16742 }
16743 })
16744 .detach();
16745 }
16746
16747 pub fn copy_file_location(
16748 &mut self,
16749 _: &CopyFileLocation,
16750 _: &mut Window,
16751 cx: &mut Context<Self>,
16752 ) {
16753 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16754 if let Some(file) = self.target_file(cx) {
16755 if let Some(path) = file.path().to_str() {
16756 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16757 }
16758 }
16759 }
16760
16761 pub fn open_permalink_to_line(
16762 &mut self,
16763 _: &OpenPermalinkToLine,
16764 window: &mut Window,
16765 cx: &mut Context<Self>,
16766 ) {
16767 let permalink_task = self.get_permalink_to_line(cx);
16768 let workspace = self.workspace();
16769
16770 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16771 Ok(permalink) => {
16772 cx.update(|_, cx| {
16773 cx.open_url(permalink.as_ref());
16774 })
16775 .ok();
16776 }
16777 Err(err) => {
16778 let message = format!("Failed to open permalink: {err}");
16779
16780 Err::<(), anyhow::Error>(err).log_err();
16781
16782 if let Some(workspace) = workspace {
16783 workspace
16784 .update(cx, |workspace, cx| {
16785 struct OpenPermalinkToLine;
16786
16787 workspace.show_toast(
16788 Toast::new(
16789 NotificationId::unique::<OpenPermalinkToLine>(),
16790 message,
16791 ),
16792 cx,
16793 )
16794 })
16795 .ok();
16796 }
16797 }
16798 })
16799 .detach();
16800 }
16801
16802 pub fn insert_uuid_v4(
16803 &mut self,
16804 _: &InsertUuidV4,
16805 window: &mut Window,
16806 cx: &mut Context<Self>,
16807 ) {
16808 self.insert_uuid(UuidVersion::V4, window, cx);
16809 }
16810
16811 pub fn insert_uuid_v7(
16812 &mut self,
16813 _: &InsertUuidV7,
16814 window: &mut Window,
16815 cx: &mut Context<Self>,
16816 ) {
16817 self.insert_uuid(UuidVersion::V7, window, cx);
16818 }
16819
16820 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16821 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16822 self.transact(window, cx, |this, window, cx| {
16823 let edits = this
16824 .selections
16825 .all::<Point>(cx)
16826 .into_iter()
16827 .map(|selection| {
16828 let uuid = match version {
16829 UuidVersion::V4 => uuid::Uuid::new_v4(),
16830 UuidVersion::V7 => uuid::Uuid::now_v7(),
16831 };
16832
16833 (selection.range(), uuid.to_string())
16834 });
16835 this.edit(edits, cx);
16836 this.refresh_inline_completion(true, false, window, cx);
16837 });
16838 }
16839
16840 pub fn open_selections_in_multibuffer(
16841 &mut self,
16842 _: &OpenSelectionsInMultibuffer,
16843 window: &mut Window,
16844 cx: &mut Context<Self>,
16845 ) {
16846 let multibuffer = self.buffer.read(cx);
16847
16848 let Some(buffer) = multibuffer.as_singleton() else {
16849 return;
16850 };
16851
16852 let Some(workspace) = self.workspace() else {
16853 return;
16854 };
16855
16856 let locations = self
16857 .selections
16858 .disjoint_anchors()
16859 .iter()
16860 .map(|range| Location {
16861 buffer: buffer.clone(),
16862 range: range.start.text_anchor..range.end.text_anchor,
16863 })
16864 .collect::<Vec<_>>();
16865
16866 let title = multibuffer.title(cx).to_string();
16867
16868 cx.spawn_in(window, async move |_, cx| {
16869 workspace.update_in(cx, |workspace, window, cx| {
16870 Self::open_locations_in_multibuffer(
16871 workspace,
16872 locations,
16873 format!("Selections for '{title}'"),
16874 false,
16875 MultibufferSelectionMode::All,
16876 window,
16877 cx,
16878 );
16879 })
16880 })
16881 .detach();
16882 }
16883
16884 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16885 /// last highlight added will be used.
16886 ///
16887 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16888 pub fn highlight_rows<T: 'static>(
16889 &mut self,
16890 range: Range<Anchor>,
16891 color: Hsla,
16892 options: RowHighlightOptions,
16893 cx: &mut Context<Self>,
16894 ) {
16895 let snapshot = self.buffer().read(cx).snapshot(cx);
16896 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16897 let ix = row_highlights.binary_search_by(|highlight| {
16898 Ordering::Equal
16899 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16900 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16901 });
16902
16903 if let Err(mut ix) = ix {
16904 let index = post_inc(&mut self.highlight_order);
16905
16906 // If this range intersects with the preceding highlight, then merge it with
16907 // the preceding highlight. Otherwise insert a new highlight.
16908 let mut merged = false;
16909 if ix > 0 {
16910 let prev_highlight = &mut row_highlights[ix - 1];
16911 if prev_highlight
16912 .range
16913 .end
16914 .cmp(&range.start, &snapshot)
16915 .is_ge()
16916 {
16917 ix -= 1;
16918 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16919 prev_highlight.range.end = range.end;
16920 }
16921 merged = true;
16922 prev_highlight.index = index;
16923 prev_highlight.color = color;
16924 prev_highlight.options = options;
16925 }
16926 }
16927
16928 if !merged {
16929 row_highlights.insert(
16930 ix,
16931 RowHighlight {
16932 range: range.clone(),
16933 index,
16934 color,
16935 options,
16936 type_id: TypeId::of::<T>(),
16937 },
16938 );
16939 }
16940
16941 // If any of the following highlights intersect with this one, merge them.
16942 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16943 let highlight = &row_highlights[ix];
16944 if next_highlight
16945 .range
16946 .start
16947 .cmp(&highlight.range.end, &snapshot)
16948 .is_le()
16949 {
16950 if next_highlight
16951 .range
16952 .end
16953 .cmp(&highlight.range.end, &snapshot)
16954 .is_gt()
16955 {
16956 row_highlights[ix].range.end = next_highlight.range.end;
16957 }
16958 row_highlights.remove(ix + 1);
16959 } else {
16960 break;
16961 }
16962 }
16963 }
16964 }
16965
16966 /// Remove any highlighted row ranges of the given type that intersect the
16967 /// given ranges.
16968 pub fn remove_highlighted_rows<T: 'static>(
16969 &mut self,
16970 ranges_to_remove: Vec<Range<Anchor>>,
16971 cx: &mut Context<Self>,
16972 ) {
16973 let snapshot = self.buffer().read(cx).snapshot(cx);
16974 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16975 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16976 row_highlights.retain(|highlight| {
16977 while let Some(range_to_remove) = ranges_to_remove.peek() {
16978 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16979 Ordering::Less | Ordering::Equal => {
16980 ranges_to_remove.next();
16981 }
16982 Ordering::Greater => {
16983 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16984 Ordering::Less | Ordering::Equal => {
16985 return false;
16986 }
16987 Ordering::Greater => break,
16988 }
16989 }
16990 }
16991 }
16992
16993 true
16994 })
16995 }
16996
16997 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16998 pub fn clear_row_highlights<T: 'static>(&mut self) {
16999 self.highlighted_rows.remove(&TypeId::of::<T>());
17000 }
17001
17002 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17003 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17004 self.highlighted_rows
17005 .get(&TypeId::of::<T>())
17006 .map_or(&[] as &[_], |vec| vec.as_slice())
17007 .iter()
17008 .map(|highlight| (highlight.range.clone(), highlight.color))
17009 }
17010
17011 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17012 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17013 /// Allows to ignore certain kinds of highlights.
17014 pub fn highlighted_display_rows(
17015 &self,
17016 window: &mut Window,
17017 cx: &mut App,
17018 ) -> BTreeMap<DisplayRow, LineHighlight> {
17019 let snapshot = self.snapshot(window, cx);
17020 let mut used_highlight_orders = HashMap::default();
17021 self.highlighted_rows
17022 .iter()
17023 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17024 .fold(
17025 BTreeMap::<DisplayRow, LineHighlight>::new(),
17026 |mut unique_rows, highlight| {
17027 let start = highlight.range.start.to_display_point(&snapshot);
17028 let end = highlight.range.end.to_display_point(&snapshot);
17029 let start_row = start.row().0;
17030 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17031 && end.column() == 0
17032 {
17033 end.row().0.saturating_sub(1)
17034 } else {
17035 end.row().0
17036 };
17037 for row in start_row..=end_row {
17038 let used_index =
17039 used_highlight_orders.entry(row).or_insert(highlight.index);
17040 if highlight.index >= *used_index {
17041 *used_index = highlight.index;
17042 unique_rows.insert(
17043 DisplayRow(row),
17044 LineHighlight {
17045 include_gutter: highlight.options.include_gutter,
17046 border: None,
17047 background: highlight.color.into(),
17048 type_id: Some(highlight.type_id),
17049 },
17050 );
17051 }
17052 }
17053 unique_rows
17054 },
17055 )
17056 }
17057
17058 pub fn highlighted_display_row_for_autoscroll(
17059 &self,
17060 snapshot: &DisplaySnapshot,
17061 ) -> Option<DisplayRow> {
17062 self.highlighted_rows
17063 .values()
17064 .flat_map(|highlighted_rows| highlighted_rows.iter())
17065 .filter_map(|highlight| {
17066 if highlight.options.autoscroll {
17067 Some(highlight.range.start.to_display_point(snapshot).row())
17068 } else {
17069 None
17070 }
17071 })
17072 .min()
17073 }
17074
17075 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17076 self.highlight_background::<SearchWithinRange>(
17077 ranges,
17078 |colors| colors.editor_document_highlight_read_background,
17079 cx,
17080 )
17081 }
17082
17083 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17084 self.breadcrumb_header = Some(new_header);
17085 }
17086
17087 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17088 self.clear_background_highlights::<SearchWithinRange>(cx);
17089 }
17090
17091 pub fn highlight_background<T: 'static>(
17092 &mut self,
17093 ranges: &[Range<Anchor>],
17094 color_fetcher: fn(&ThemeColors) -> Hsla,
17095 cx: &mut Context<Self>,
17096 ) {
17097 self.background_highlights
17098 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17099 self.scrollbar_marker_state.dirty = true;
17100 cx.notify();
17101 }
17102
17103 pub fn clear_background_highlights<T: 'static>(
17104 &mut self,
17105 cx: &mut Context<Self>,
17106 ) -> Option<BackgroundHighlight> {
17107 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17108 if !text_highlights.1.is_empty() {
17109 self.scrollbar_marker_state.dirty = true;
17110 cx.notify();
17111 }
17112 Some(text_highlights)
17113 }
17114
17115 pub fn highlight_gutter<T: 'static>(
17116 &mut self,
17117 ranges: &[Range<Anchor>],
17118 color_fetcher: fn(&App) -> Hsla,
17119 cx: &mut Context<Self>,
17120 ) {
17121 self.gutter_highlights
17122 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17123 cx.notify();
17124 }
17125
17126 pub fn clear_gutter_highlights<T: 'static>(
17127 &mut self,
17128 cx: &mut Context<Self>,
17129 ) -> Option<GutterHighlight> {
17130 cx.notify();
17131 self.gutter_highlights.remove(&TypeId::of::<T>())
17132 }
17133
17134 #[cfg(feature = "test-support")]
17135 pub fn all_text_background_highlights(
17136 &self,
17137 window: &mut Window,
17138 cx: &mut Context<Self>,
17139 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17140 let snapshot = self.snapshot(window, cx);
17141 let buffer = &snapshot.buffer_snapshot;
17142 let start = buffer.anchor_before(0);
17143 let end = buffer.anchor_after(buffer.len());
17144 let theme = cx.theme().colors();
17145 self.background_highlights_in_range(start..end, &snapshot, theme)
17146 }
17147
17148 #[cfg(feature = "test-support")]
17149 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17150 let snapshot = self.buffer().read(cx).snapshot(cx);
17151
17152 let highlights = self
17153 .background_highlights
17154 .get(&TypeId::of::<items::BufferSearchHighlights>());
17155
17156 if let Some((_color, ranges)) = highlights {
17157 ranges
17158 .iter()
17159 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17160 .collect_vec()
17161 } else {
17162 vec![]
17163 }
17164 }
17165
17166 fn document_highlights_for_position<'a>(
17167 &'a self,
17168 position: Anchor,
17169 buffer: &'a MultiBufferSnapshot,
17170 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17171 let read_highlights = self
17172 .background_highlights
17173 .get(&TypeId::of::<DocumentHighlightRead>())
17174 .map(|h| &h.1);
17175 let write_highlights = self
17176 .background_highlights
17177 .get(&TypeId::of::<DocumentHighlightWrite>())
17178 .map(|h| &h.1);
17179 let left_position = position.bias_left(buffer);
17180 let right_position = position.bias_right(buffer);
17181 read_highlights
17182 .into_iter()
17183 .chain(write_highlights)
17184 .flat_map(move |ranges| {
17185 let start_ix = match ranges.binary_search_by(|probe| {
17186 let cmp = probe.end.cmp(&left_position, buffer);
17187 if cmp.is_ge() {
17188 Ordering::Greater
17189 } else {
17190 Ordering::Less
17191 }
17192 }) {
17193 Ok(i) | Err(i) => i,
17194 };
17195
17196 ranges[start_ix..]
17197 .iter()
17198 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17199 })
17200 }
17201
17202 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17203 self.background_highlights
17204 .get(&TypeId::of::<T>())
17205 .map_or(false, |(_, highlights)| !highlights.is_empty())
17206 }
17207
17208 pub fn background_highlights_in_range(
17209 &self,
17210 search_range: Range<Anchor>,
17211 display_snapshot: &DisplaySnapshot,
17212 theme: &ThemeColors,
17213 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17214 let mut results = Vec::new();
17215 for (color_fetcher, ranges) in self.background_highlights.values() {
17216 let color = color_fetcher(theme);
17217 let start_ix = match ranges.binary_search_by(|probe| {
17218 let cmp = probe
17219 .end
17220 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17221 if cmp.is_gt() {
17222 Ordering::Greater
17223 } else {
17224 Ordering::Less
17225 }
17226 }) {
17227 Ok(i) | Err(i) => i,
17228 };
17229 for range in &ranges[start_ix..] {
17230 if range
17231 .start
17232 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17233 .is_ge()
17234 {
17235 break;
17236 }
17237
17238 let start = range.start.to_display_point(display_snapshot);
17239 let end = range.end.to_display_point(display_snapshot);
17240 results.push((start..end, color))
17241 }
17242 }
17243 results
17244 }
17245
17246 pub fn background_highlight_row_ranges<T: 'static>(
17247 &self,
17248 search_range: Range<Anchor>,
17249 display_snapshot: &DisplaySnapshot,
17250 count: usize,
17251 ) -> Vec<RangeInclusive<DisplayPoint>> {
17252 let mut results = Vec::new();
17253 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17254 return vec![];
17255 };
17256
17257 let start_ix = match ranges.binary_search_by(|probe| {
17258 let cmp = probe
17259 .end
17260 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17261 if cmp.is_gt() {
17262 Ordering::Greater
17263 } else {
17264 Ordering::Less
17265 }
17266 }) {
17267 Ok(i) | Err(i) => i,
17268 };
17269 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17270 if let (Some(start_display), Some(end_display)) = (start, end) {
17271 results.push(
17272 start_display.to_display_point(display_snapshot)
17273 ..=end_display.to_display_point(display_snapshot),
17274 );
17275 }
17276 };
17277 let mut start_row: Option<Point> = None;
17278 let mut end_row: Option<Point> = None;
17279 if ranges.len() > count {
17280 return Vec::new();
17281 }
17282 for range in &ranges[start_ix..] {
17283 if range
17284 .start
17285 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17286 .is_ge()
17287 {
17288 break;
17289 }
17290 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17291 if let Some(current_row) = &end_row {
17292 if end.row == current_row.row {
17293 continue;
17294 }
17295 }
17296 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17297 if start_row.is_none() {
17298 assert_eq!(end_row, None);
17299 start_row = Some(start);
17300 end_row = Some(end);
17301 continue;
17302 }
17303 if let Some(current_end) = end_row.as_mut() {
17304 if start.row > current_end.row + 1 {
17305 push_region(start_row, end_row);
17306 start_row = Some(start);
17307 end_row = Some(end);
17308 } else {
17309 // Merge two hunks.
17310 *current_end = end;
17311 }
17312 } else {
17313 unreachable!();
17314 }
17315 }
17316 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17317 push_region(start_row, end_row);
17318 results
17319 }
17320
17321 pub fn gutter_highlights_in_range(
17322 &self,
17323 search_range: Range<Anchor>,
17324 display_snapshot: &DisplaySnapshot,
17325 cx: &App,
17326 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17327 let mut results = Vec::new();
17328 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17329 let color = color_fetcher(cx);
17330 let start_ix = match ranges.binary_search_by(|probe| {
17331 let cmp = probe
17332 .end
17333 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17334 if cmp.is_gt() {
17335 Ordering::Greater
17336 } else {
17337 Ordering::Less
17338 }
17339 }) {
17340 Ok(i) | Err(i) => i,
17341 };
17342 for range in &ranges[start_ix..] {
17343 if range
17344 .start
17345 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17346 .is_ge()
17347 {
17348 break;
17349 }
17350
17351 let start = range.start.to_display_point(display_snapshot);
17352 let end = range.end.to_display_point(display_snapshot);
17353 results.push((start..end, color))
17354 }
17355 }
17356 results
17357 }
17358
17359 /// Get the text ranges corresponding to the redaction query
17360 pub fn redacted_ranges(
17361 &self,
17362 search_range: Range<Anchor>,
17363 display_snapshot: &DisplaySnapshot,
17364 cx: &App,
17365 ) -> Vec<Range<DisplayPoint>> {
17366 display_snapshot
17367 .buffer_snapshot
17368 .redacted_ranges(search_range, |file| {
17369 if let Some(file) = file {
17370 file.is_private()
17371 && EditorSettings::get(
17372 Some(SettingsLocation {
17373 worktree_id: file.worktree_id(cx),
17374 path: file.path().as_ref(),
17375 }),
17376 cx,
17377 )
17378 .redact_private_values
17379 } else {
17380 false
17381 }
17382 })
17383 .map(|range| {
17384 range.start.to_display_point(display_snapshot)
17385 ..range.end.to_display_point(display_snapshot)
17386 })
17387 .collect()
17388 }
17389
17390 pub fn highlight_text<T: 'static>(
17391 &mut self,
17392 ranges: Vec<Range<Anchor>>,
17393 style: HighlightStyle,
17394 cx: &mut Context<Self>,
17395 ) {
17396 self.display_map.update(cx, |map, _| {
17397 map.highlight_text(TypeId::of::<T>(), ranges, style)
17398 });
17399 cx.notify();
17400 }
17401
17402 pub(crate) fn highlight_inlays<T: 'static>(
17403 &mut self,
17404 highlights: Vec<InlayHighlight>,
17405 style: HighlightStyle,
17406 cx: &mut Context<Self>,
17407 ) {
17408 self.display_map.update(cx, |map, _| {
17409 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17410 });
17411 cx.notify();
17412 }
17413
17414 pub fn text_highlights<'a, T: 'static>(
17415 &'a self,
17416 cx: &'a App,
17417 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17418 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17419 }
17420
17421 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17422 let cleared = self
17423 .display_map
17424 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17425 if cleared {
17426 cx.notify();
17427 }
17428 }
17429
17430 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17431 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17432 && self.focus_handle.is_focused(window)
17433 }
17434
17435 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17436 self.show_cursor_when_unfocused = is_enabled;
17437 cx.notify();
17438 }
17439
17440 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17441 cx.notify();
17442 }
17443
17444 fn on_debug_session_event(
17445 &mut self,
17446 _session: Entity<Session>,
17447 event: &SessionEvent,
17448 cx: &mut Context<Self>,
17449 ) {
17450 match event {
17451 SessionEvent::InvalidateInlineValue => {
17452 self.refresh_inline_values(cx);
17453 }
17454 _ => {}
17455 }
17456 }
17457
17458 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17459 let Some(project) = self.project.clone() else {
17460 return;
17461 };
17462 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17463 return;
17464 };
17465 if !self.inline_value_cache.enabled {
17466 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17467 self.splice_inlays(&inlays, Vec::new(), cx);
17468 return;
17469 }
17470
17471 let current_execution_position = self
17472 .highlighted_rows
17473 .get(&TypeId::of::<DebugCurrentRowHighlight>())
17474 .and_then(|lines| lines.last().map(|line| line.range.start));
17475
17476 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17477 let snapshot = editor
17478 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17479 .ok()?;
17480
17481 let inline_values = editor
17482 .update(cx, |_, cx| {
17483 let Some(current_execution_position) = current_execution_position else {
17484 return Some(Task::ready(Ok(Vec::new())));
17485 };
17486
17487 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17488 // anchor is in the same buffer
17489 let range =
17490 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17491 project.inline_values(buffer, range, cx)
17492 })
17493 .ok()
17494 .flatten()?
17495 .await
17496 .context("refreshing debugger inlays")
17497 .log_err()?;
17498
17499 let (excerpt_id, buffer_id) = snapshot
17500 .excerpts()
17501 .next()
17502 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17503 editor
17504 .update(cx, |editor, cx| {
17505 let new_inlays = inline_values
17506 .into_iter()
17507 .map(|debugger_value| {
17508 Inlay::debugger_hint(
17509 post_inc(&mut editor.next_inlay_id),
17510 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17511 debugger_value.text(),
17512 )
17513 })
17514 .collect::<Vec<_>>();
17515 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17516 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17517
17518 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17519 })
17520 .ok()?;
17521 Some(())
17522 });
17523 }
17524
17525 fn on_buffer_event(
17526 &mut self,
17527 multibuffer: &Entity<MultiBuffer>,
17528 event: &multi_buffer::Event,
17529 window: &mut Window,
17530 cx: &mut Context<Self>,
17531 ) {
17532 match event {
17533 multi_buffer::Event::Edited {
17534 singleton_buffer_edited,
17535 edited_buffer: buffer_edited,
17536 } => {
17537 self.scrollbar_marker_state.dirty = true;
17538 self.active_indent_guides_state.dirty = true;
17539 self.refresh_active_diagnostics(cx);
17540 self.refresh_code_actions(window, cx);
17541 if self.has_active_inline_completion() {
17542 self.update_visible_inline_completion(window, cx);
17543 }
17544 if let Some(buffer) = buffer_edited {
17545 let buffer_id = buffer.read(cx).remote_id();
17546 if !self.registered_buffers.contains_key(&buffer_id) {
17547 if let Some(project) = self.project.as_ref() {
17548 project.update(cx, |project, cx| {
17549 self.registered_buffers.insert(
17550 buffer_id,
17551 project.register_buffer_with_language_servers(&buffer, cx),
17552 );
17553 })
17554 }
17555 }
17556 }
17557 cx.emit(EditorEvent::BufferEdited);
17558 cx.emit(SearchEvent::MatchesInvalidated);
17559 if *singleton_buffer_edited {
17560 if let Some(project) = &self.project {
17561 #[allow(clippy::mutable_key_type)]
17562 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17563 multibuffer
17564 .all_buffers()
17565 .into_iter()
17566 .filter_map(|buffer| {
17567 buffer.update(cx, |buffer, cx| {
17568 let language = buffer.language()?;
17569 let should_discard = project.update(cx, |project, cx| {
17570 project.is_local()
17571 && !project.has_language_servers_for(buffer, cx)
17572 });
17573 should_discard.not().then_some(language.clone())
17574 })
17575 })
17576 .collect::<HashSet<_>>()
17577 });
17578 if !languages_affected.is_empty() {
17579 self.refresh_inlay_hints(
17580 InlayHintRefreshReason::BufferEdited(languages_affected),
17581 cx,
17582 );
17583 }
17584 }
17585 }
17586
17587 let Some(project) = &self.project else { return };
17588 let (telemetry, is_via_ssh) = {
17589 let project = project.read(cx);
17590 let telemetry = project.client().telemetry().clone();
17591 let is_via_ssh = project.is_via_ssh();
17592 (telemetry, is_via_ssh)
17593 };
17594 refresh_linked_ranges(self, window, cx);
17595 telemetry.log_edit_event("editor", is_via_ssh);
17596 }
17597 multi_buffer::Event::ExcerptsAdded {
17598 buffer,
17599 predecessor,
17600 excerpts,
17601 } => {
17602 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17603 let buffer_id = buffer.read(cx).remote_id();
17604 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17605 if let Some(project) = &self.project {
17606 get_uncommitted_diff_for_buffer(
17607 project,
17608 [buffer.clone()],
17609 self.buffer.clone(),
17610 cx,
17611 )
17612 .detach();
17613 }
17614 }
17615 cx.emit(EditorEvent::ExcerptsAdded {
17616 buffer: buffer.clone(),
17617 predecessor: *predecessor,
17618 excerpts: excerpts.clone(),
17619 });
17620 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17621 }
17622 multi_buffer::Event::ExcerptsRemoved {
17623 ids,
17624 removed_buffer_ids,
17625 } => {
17626 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17627 let buffer = self.buffer.read(cx);
17628 self.registered_buffers
17629 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17630 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17631 cx.emit(EditorEvent::ExcerptsRemoved {
17632 ids: ids.clone(),
17633 removed_buffer_ids: removed_buffer_ids.clone(),
17634 })
17635 }
17636 multi_buffer::Event::ExcerptsEdited {
17637 excerpt_ids,
17638 buffer_ids,
17639 } => {
17640 self.display_map.update(cx, |map, cx| {
17641 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17642 });
17643 cx.emit(EditorEvent::ExcerptsEdited {
17644 ids: excerpt_ids.clone(),
17645 })
17646 }
17647 multi_buffer::Event::ExcerptsExpanded { ids } => {
17648 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17649 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17650 }
17651 multi_buffer::Event::Reparsed(buffer_id) => {
17652 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17653 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17654
17655 cx.emit(EditorEvent::Reparsed(*buffer_id));
17656 }
17657 multi_buffer::Event::DiffHunksToggled => {
17658 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17659 }
17660 multi_buffer::Event::LanguageChanged(buffer_id) => {
17661 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17662 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17663 cx.emit(EditorEvent::Reparsed(*buffer_id));
17664 cx.notify();
17665 }
17666 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17667 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17668 multi_buffer::Event::FileHandleChanged
17669 | multi_buffer::Event::Reloaded
17670 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17671 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17672 multi_buffer::Event::DiagnosticsUpdated => {
17673 self.refresh_active_diagnostics(cx);
17674 self.refresh_inline_diagnostics(true, window, cx);
17675 self.scrollbar_marker_state.dirty = true;
17676 cx.notify();
17677 }
17678 _ => {}
17679 };
17680 }
17681
17682 fn on_display_map_changed(
17683 &mut self,
17684 _: Entity<DisplayMap>,
17685 _: &mut Window,
17686 cx: &mut Context<Self>,
17687 ) {
17688 cx.notify();
17689 }
17690
17691 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17692 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17693 self.update_edit_prediction_settings(cx);
17694 self.refresh_inline_completion(true, false, window, cx);
17695 self.refresh_inlay_hints(
17696 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17697 self.selections.newest_anchor().head(),
17698 &self.buffer.read(cx).snapshot(cx),
17699 cx,
17700 )),
17701 cx,
17702 );
17703
17704 let old_cursor_shape = self.cursor_shape;
17705
17706 {
17707 let editor_settings = EditorSettings::get_global(cx);
17708 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17709 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17710 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17711 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17712 }
17713
17714 if old_cursor_shape != self.cursor_shape {
17715 cx.emit(EditorEvent::CursorShapeChanged);
17716 }
17717
17718 let project_settings = ProjectSettings::get_global(cx);
17719 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17720
17721 if self.mode.is_full() {
17722 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17723 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17724 if self.show_inline_diagnostics != show_inline_diagnostics {
17725 self.show_inline_diagnostics = show_inline_diagnostics;
17726 self.refresh_inline_diagnostics(false, window, cx);
17727 }
17728
17729 if self.git_blame_inline_enabled != inline_blame_enabled {
17730 self.toggle_git_blame_inline_internal(false, window, cx);
17731 }
17732 }
17733
17734 cx.notify();
17735 }
17736
17737 pub fn set_searchable(&mut self, searchable: bool) {
17738 self.searchable = searchable;
17739 }
17740
17741 pub fn searchable(&self) -> bool {
17742 self.searchable
17743 }
17744
17745 fn open_proposed_changes_editor(
17746 &mut self,
17747 _: &OpenProposedChangesEditor,
17748 window: &mut Window,
17749 cx: &mut Context<Self>,
17750 ) {
17751 let Some(workspace) = self.workspace() else {
17752 cx.propagate();
17753 return;
17754 };
17755
17756 let selections = self.selections.all::<usize>(cx);
17757 let multi_buffer = self.buffer.read(cx);
17758 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17759 let mut new_selections_by_buffer = HashMap::default();
17760 for selection in selections {
17761 for (buffer, range, _) in
17762 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17763 {
17764 let mut range = range.to_point(buffer);
17765 range.start.column = 0;
17766 range.end.column = buffer.line_len(range.end.row);
17767 new_selections_by_buffer
17768 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17769 .or_insert(Vec::new())
17770 .push(range)
17771 }
17772 }
17773
17774 let proposed_changes_buffers = new_selections_by_buffer
17775 .into_iter()
17776 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17777 .collect::<Vec<_>>();
17778 let proposed_changes_editor = cx.new(|cx| {
17779 ProposedChangesEditor::new(
17780 "Proposed changes",
17781 proposed_changes_buffers,
17782 self.project.clone(),
17783 window,
17784 cx,
17785 )
17786 });
17787
17788 window.defer(cx, move |window, cx| {
17789 workspace.update(cx, |workspace, cx| {
17790 workspace.active_pane().update(cx, |pane, cx| {
17791 pane.add_item(
17792 Box::new(proposed_changes_editor),
17793 true,
17794 true,
17795 None,
17796 window,
17797 cx,
17798 );
17799 });
17800 });
17801 });
17802 }
17803
17804 pub fn open_excerpts_in_split(
17805 &mut self,
17806 _: &OpenExcerptsSplit,
17807 window: &mut Window,
17808 cx: &mut Context<Self>,
17809 ) {
17810 self.open_excerpts_common(None, true, window, cx)
17811 }
17812
17813 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17814 self.open_excerpts_common(None, false, window, cx)
17815 }
17816
17817 fn open_excerpts_common(
17818 &mut self,
17819 jump_data: Option<JumpData>,
17820 split: bool,
17821 window: &mut Window,
17822 cx: &mut Context<Self>,
17823 ) {
17824 let Some(workspace) = self.workspace() else {
17825 cx.propagate();
17826 return;
17827 };
17828
17829 if self.buffer.read(cx).is_singleton() {
17830 cx.propagate();
17831 return;
17832 }
17833
17834 let mut new_selections_by_buffer = HashMap::default();
17835 match &jump_data {
17836 Some(JumpData::MultiBufferPoint {
17837 excerpt_id,
17838 position,
17839 anchor,
17840 line_offset_from_top,
17841 }) => {
17842 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17843 if let Some(buffer) = multi_buffer_snapshot
17844 .buffer_id_for_excerpt(*excerpt_id)
17845 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17846 {
17847 let buffer_snapshot = buffer.read(cx).snapshot();
17848 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17849 language::ToPoint::to_point(anchor, &buffer_snapshot)
17850 } else {
17851 buffer_snapshot.clip_point(*position, Bias::Left)
17852 };
17853 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17854 new_selections_by_buffer.insert(
17855 buffer,
17856 (
17857 vec![jump_to_offset..jump_to_offset],
17858 Some(*line_offset_from_top),
17859 ),
17860 );
17861 }
17862 }
17863 Some(JumpData::MultiBufferRow {
17864 row,
17865 line_offset_from_top,
17866 }) => {
17867 let point = MultiBufferPoint::new(row.0, 0);
17868 if let Some((buffer, buffer_point, _)) =
17869 self.buffer.read(cx).point_to_buffer_point(point, cx)
17870 {
17871 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17872 new_selections_by_buffer
17873 .entry(buffer)
17874 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17875 .0
17876 .push(buffer_offset..buffer_offset)
17877 }
17878 }
17879 None => {
17880 let selections = self.selections.all::<usize>(cx);
17881 let multi_buffer = self.buffer.read(cx);
17882 for selection in selections {
17883 for (snapshot, range, _, anchor) in multi_buffer
17884 .snapshot(cx)
17885 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17886 {
17887 if let Some(anchor) = anchor {
17888 // selection is in a deleted hunk
17889 let Some(buffer_id) = anchor.buffer_id else {
17890 continue;
17891 };
17892 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17893 continue;
17894 };
17895 let offset = text::ToOffset::to_offset(
17896 &anchor.text_anchor,
17897 &buffer_handle.read(cx).snapshot(),
17898 );
17899 let range = offset..offset;
17900 new_selections_by_buffer
17901 .entry(buffer_handle)
17902 .or_insert((Vec::new(), None))
17903 .0
17904 .push(range)
17905 } else {
17906 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17907 else {
17908 continue;
17909 };
17910 new_selections_by_buffer
17911 .entry(buffer_handle)
17912 .or_insert((Vec::new(), None))
17913 .0
17914 .push(range)
17915 }
17916 }
17917 }
17918 }
17919 }
17920
17921 new_selections_by_buffer
17922 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17923
17924 if new_selections_by_buffer.is_empty() {
17925 return;
17926 }
17927
17928 // We defer the pane interaction because we ourselves are a workspace item
17929 // and activating a new item causes the pane to call a method on us reentrantly,
17930 // which panics if we're on the stack.
17931 window.defer(cx, move |window, cx| {
17932 workspace.update(cx, |workspace, cx| {
17933 let pane = if split {
17934 workspace.adjacent_pane(window, cx)
17935 } else {
17936 workspace.active_pane().clone()
17937 };
17938
17939 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17940 let editor = buffer
17941 .read(cx)
17942 .file()
17943 .is_none()
17944 .then(|| {
17945 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17946 // so `workspace.open_project_item` will never find them, always opening a new editor.
17947 // Instead, we try to activate the existing editor in the pane first.
17948 let (editor, pane_item_index) =
17949 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17950 let editor = item.downcast::<Editor>()?;
17951 let singleton_buffer =
17952 editor.read(cx).buffer().read(cx).as_singleton()?;
17953 if singleton_buffer == buffer {
17954 Some((editor, i))
17955 } else {
17956 None
17957 }
17958 })?;
17959 pane.update(cx, |pane, cx| {
17960 pane.activate_item(pane_item_index, true, true, window, cx)
17961 });
17962 Some(editor)
17963 })
17964 .flatten()
17965 .unwrap_or_else(|| {
17966 workspace.open_project_item::<Self>(
17967 pane.clone(),
17968 buffer,
17969 true,
17970 true,
17971 window,
17972 cx,
17973 )
17974 });
17975
17976 editor.update(cx, |editor, cx| {
17977 let autoscroll = match scroll_offset {
17978 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17979 None => Autoscroll::newest(),
17980 };
17981 let nav_history = editor.nav_history.take();
17982 editor.change_selections(Some(autoscroll), window, cx, |s| {
17983 s.select_ranges(ranges);
17984 });
17985 editor.nav_history = nav_history;
17986 });
17987 }
17988 })
17989 });
17990 }
17991
17992 // For now, don't allow opening excerpts in buffers that aren't backed by
17993 // regular project files.
17994 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17995 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17996 }
17997
17998 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17999 let snapshot = self.buffer.read(cx).read(cx);
18000 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18001 Some(
18002 ranges
18003 .iter()
18004 .map(move |range| {
18005 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18006 })
18007 .collect(),
18008 )
18009 }
18010
18011 fn selection_replacement_ranges(
18012 &self,
18013 range: Range<OffsetUtf16>,
18014 cx: &mut App,
18015 ) -> Vec<Range<OffsetUtf16>> {
18016 let selections = self.selections.all::<OffsetUtf16>(cx);
18017 let newest_selection = selections
18018 .iter()
18019 .max_by_key(|selection| selection.id)
18020 .unwrap();
18021 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18022 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18023 let snapshot = self.buffer.read(cx).read(cx);
18024 selections
18025 .into_iter()
18026 .map(|mut selection| {
18027 selection.start.0 =
18028 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18029 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18030 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18031 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18032 })
18033 .collect()
18034 }
18035
18036 fn report_editor_event(
18037 &self,
18038 event_type: &'static str,
18039 file_extension: Option<String>,
18040 cx: &App,
18041 ) {
18042 if cfg!(any(test, feature = "test-support")) {
18043 return;
18044 }
18045
18046 let Some(project) = &self.project else { return };
18047
18048 // If None, we are in a file without an extension
18049 let file = self
18050 .buffer
18051 .read(cx)
18052 .as_singleton()
18053 .and_then(|b| b.read(cx).file());
18054 let file_extension = file_extension.or(file
18055 .as_ref()
18056 .and_then(|file| Path::new(file.file_name(cx)).extension())
18057 .and_then(|e| e.to_str())
18058 .map(|a| a.to_string()));
18059
18060 let vim_mode = vim_enabled(cx);
18061
18062 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18063 let copilot_enabled = edit_predictions_provider
18064 == language::language_settings::EditPredictionProvider::Copilot;
18065 let copilot_enabled_for_language = self
18066 .buffer
18067 .read(cx)
18068 .language_settings(cx)
18069 .show_edit_predictions;
18070
18071 let project = project.read(cx);
18072 telemetry::event!(
18073 event_type,
18074 file_extension,
18075 vim_mode,
18076 copilot_enabled,
18077 copilot_enabled_for_language,
18078 edit_predictions_provider,
18079 is_via_ssh = project.is_via_ssh(),
18080 );
18081 }
18082
18083 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18084 /// with each line being an array of {text, highlight} objects.
18085 fn copy_highlight_json(
18086 &mut self,
18087 _: &CopyHighlightJson,
18088 window: &mut Window,
18089 cx: &mut Context<Self>,
18090 ) {
18091 #[derive(Serialize)]
18092 struct Chunk<'a> {
18093 text: String,
18094 highlight: Option<&'a str>,
18095 }
18096
18097 let snapshot = self.buffer.read(cx).snapshot(cx);
18098 let range = self
18099 .selected_text_range(false, window, cx)
18100 .and_then(|selection| {
18101 if selection.range.is_empty() {
18102 None
18103 } else {
18104 Some(selection.range)
18105 }
18106 })
18107 .unwrap_or_else(|| 0..snapshot.len());
18108
18109 let chunks = snapshot.chunks(range, true);
18110 let mut lines = Vec::new();
18111 let mut line: VecDeque<Chunk> = VecDeque::new();
18112
18113 let Some(style) = self.style.as_ref() else {
18114 return;
18115 };
18116
18117 for chunk in chunks {
18118 let highlight = chunk
18119 .syntax_highlight_id
18120 .and_then(|id| id.name(&style.syntax));
18121 let mut chunk_lines = chunk.text.split('\n').peekable();
18122 while let Some(text) = chunk_lines.next() {
18123 let mut merged_with_last_token = false;
18124 if let Some(last_token) = line.back_mut() {
18125 if last_token.highlight == highlight {
18126 last_token.text.push_str(text);
18127 merged_with_last_token = true;
18128 }
18129 }
18130
18131 if !merged_with_last_token {
18132 line.push_back(Chunk {
18133 text: text.into(),
18134 highlight,
18135 });
18136 }
18137
18138 if chunk_lines.peek().is_some() {
18139 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18140 line.pop_front();
18141 }
18142 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18143 line.pop_back();
18144 }
18145
18146 lines.push(mem::take(&mut line));
18147 }
18148 }
18149 }
18150
18151 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18152 return;
18153 };
18154 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18155 }
18156
18157 pub fn open_context_menu(
18158 &mut self,
18159 _: &OpenContextMenu,
18160 window: &mut Window,
18161 cx: &mut Context<Self>,
18162 ) {
18163 self.request_autoscroll(Autoscroll::newest(), cx);
18164 let position = self.selections.newest_display(cx).start;
18165 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18166 }
18167
18168 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18169 &self.inlay_hint_cache
18170 }
18171
18172 pub fn replay_insert_event(
18173 &mut self,
18174 text: &str,
18175 relative_utf16_range: Option<Range<isize>>,
18176 window: &mut Window,
18177 cx: &mut Context<Self>,
18178 ) {
18179 if !self.input_enabled {
18180 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18181 return;
18182 }
18183 if let Some(relative_utf16_range) = relative_utf16_range {
18184 let selections = self.selections.all::<OffsetUtf16>(cx);
18185 self.change_selections(None, window, cx, |s| {
18186 let new_ranges = selections.into_iter().map(|range| {
18187 let start = OffsetUtf16(
18188 range
18189 .head()
18190 .0
18191 .saturating_add_signed(relative_utf16_range.start),
18192 );
18193 let end = OffsetUtf16(
18194 range
18195 .head()
18196 .0
18197 .saturating_add_signed(relative_utf16_range.end),
18198 );
18199 start..end
18200 });
18201 s.select_ranges(new_ranges);
18202 });
18203 }
18204
18205 self.handle_input(text, window, cx);
18206 }
18207
18208 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18209 let Some(provider) = self.semantics_provider.as_ref() else {
18210 return false;
18211 };
18212
18213 let mut supports = false;
18214 self.buffer().update(cx, |this, cx| {
18215 this.for_each_buffer(|buffer| {
18216 supports |= provider.supports_inlay_hints(buffer, cx);
18217 });
18218 });
18219
18220 supports
18221 }
18222
18223 pub fn is_focused(&self, window: &Window) -> bool {
18224 self.focus_handle.is_focused(window)
18225 }
18226
18227 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18228 cx.emit(EditorEvent::Focused);
18229
18230 if let Some(descendant) = self
18231 .last_focused_descendant
18232 .take()
18233 .and_then(|descendant| descendant.upgrade())
18234 {
18235 window.focus(&descendant);
18236 } else {
18237 if let Some(blame) = self.blame.as_ref() {
18238 blame.update(cx, GitBlame::focus)
18239 }
18240
18241 self.blink_manager.update(cx, BlinkManager::enable);
18242 self.show_cursor_names(window, cx);
18243 self.buffer.update(cx, |buffer, cx| {
18244 buffer.finalize_last_transaction(cx);
18245 if self.leader_peer_id.is_none() {
18246 buffer.set_active_selections(
18247 &self.selections.disjoint_anchors(),
18248 self.selections.line_mode,
18249 self.cursor_shape,
18250 cx,
18251 );
18252 }
18253 });
18254 }
18255 }
18256
18257 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18258 cx.emit(EditorEvent::FocusedIn)
18259 }
18260
18261 fn handle_focus_out(
18262 &mut self,
18263 event: FocusOutEvent,
18264 _window: &mut Window,
18265 cx: &mut Context<Self>,
18266 ) {
18267 if event.blurred != self.focus_handle {
18268 self.last_focused_descendant = Some(event.blurred);
18269 }
18270 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18271 }
18272
18273 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18274 self.blink_manager.update(cx, BlinkManager::disable);
18275 self.buffer
18276 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18277
18278 if let Some(blame) = self.blame.as_ref() {
18279 blame.update(cx, GitBlame::blur)
18280 }
18281 if !self.hover_state.focused(window, cx) {
18282 hide_hover(self, cx);
18283 }
18284 if !self
18285 .context_menu
18286 .borrow()
18287 .as_ref()
18288 .is_some_and(|context_menu| context_menu.focused(window, cx))
18289 {
18290 self.hide_context_menu(window, cx);
18291 }
18292 self.discard_inline_completion(false, cx);
18293 cx.emit(EditorEvent::Blurred);
18294 cx.notify();
18295 }
18296
18297 pub fn register_action<A: Action>(
18298 &mut self,
18299 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18300 ) -> Subscription {
18301 let id = self.next_editor_action_id.post_inc();
18302 let listener = Arc::new(listener);
18303 self.editor_actions.borrow_mut().insert(
18304 id,
18305 Box::new(move |window, _| {
18306 let listener = listener.clone();
18307 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18308 let action = action.downcast_ref().unwrap();
18309 if phase == DispatchPhase::Bubble {
18310 listener(action, window, cx)
18311 }
18312 })
18313 }),
18314 );
18315
18316 let editor_actions = self.editor_actions.clone();
18317 Subscription::new(move || {
18318 editor_actions.borrow_mut().remove(&id);
18319 })
18320 }
18321
18322 pub fn file_header_size(&self) -> u32 {
18323 FILE_HEADER_HEIGHT
18324 }
18325
18326 pub fn restore(
18327 &mut self,
18328 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18329 window: &mut Window,
18330 cx: &mut Context<Self>,
18331 ) {
18332 let workspace = self.workspace();
18333 let project = self.project.as_ref();
18334 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18335 let mut tasks = Vec::new();
18336 for (buffer_id, changes) in revert_changes {
18337 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18338 buffer.update(cx, |buffer, cx| {
18339 buffer.edit(
18340 changes
18341 .into_iter()
18342 .map(|(range, text)| (range, text.to_string())),
18343 None,
18344 cx,
18345 );
18346 });
18347
18348 if let Some(project) =
18349 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18350 {
18351 project.update(cx, |project, cx| {
18352 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18353 })
18354 }
18355 }
18356 }
18357 tasks
18358 });
18359 cx.spawn_in(window, async move |_, cx| {
18360 for (buffer, task) in save_tasks {
18361 let result = task.await;
18362 if result.is_err() {
18363 let Some(path) = buffer
18364 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18365 .ok()
18366 else {
18367 continue;
18368 };
18369 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18370 let Some(task) = cx
18371 .update_window_entity(&workspace, |workspace, window, cx| {
18372 workspace
18373 .open_path_preview(path, None, false, false, false, window, cx)
18374 })
18375 .ok()
18376 else {
18377 continue;
18378 };
18379 task.await.log_err();
18380 }
18381 }
18382 }
18383 })
18384 .detach();
18385 self.change_selections(None, window, cx, |selections| selections.refresh());
18386 }
18387
18388 pub fn to_pixel_point(
18389 &self,
18390 source: multi_buffer::Anchor,
18391 editor_snapshot: &EditorSnapshot,
18392 window: &mut Window,
18393 ) -> Option<gpui::Point<Pixels>> {
18394 let source_point = source.to_display_point(editor_snapshot);
18395 self.display_to_pixel_point(source_point, editor_snapshot, window)
18396 }
18397
18398 pub fn display_to_pixel_point(
18399 &self,
18400 source: DisplayPoint,
18401 editor_snapshot: &EditorSnapshot,
18402 window: &mut Window,
18403 ) -> Option<gpui::Point<Pixels>> {
18404 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18405 let text_layout_details = self.text_layout_details(window);
18406 let scroll_top = text_layout_details
18407 .scroll_anchor
18408 .scroll_position(editor_snapshot)
18409 .y;
18410
18411 if source.row().as_f32() < scroll_top.floor() {
18412 return None;
18413 }
18414 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18415 let source_y = line_height * (source.row().as_f32() - scroll_top);
18416 Some(gpui::Point::new(source_x, source_y))
18417 }
18418
18419 pub fn has_visible_completions_menu(&self) -> bool {
18420 !self.edit_prediction_preview_is_active()
18421 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18422 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18423 })
18424 }
18425
18426 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18427 self.addons
18428 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18429 }
18430
18431 pub fn unregister_addon<T: Addon>(&mut self) {
18432 self.addons.remove(&std::any::TypeId::of::<T>());
18433 }
18434
18435 pub fn addon<T: Addon>(&self) -> Option<&T> {
18436 let type_id = std::any::TypeId::of::<T>();
18437 self.addons
18438 .get(&type_id)
18439 .and_then(|item| item.to_any().downcast_ref::<T>())
18440 }
18441
18442 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18443 let type_id = std::any::TypeId::of::<T>();
18444 self.addons
18445 .get_mut(&type_id)
18446 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18447 }
18448
18449 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18450 let text_layout_details = self.text_layout_details(window);
18451 let style = &text_layout_details.editor_style;
18452 let font_id = window.text_system().resolve_font(&style.text.font());
18453 let font_size = style.text.font_size.to_pixels(window.rem_size());
18454 let line_height = style.text.line_height_in_pixels(window.rem_size());
18455 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18456
18457 gpui::Size::new(em_width, line_height)
18458 }
18459
18460 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18461 self.load_diff_task.clone()
18462 }
18463
18464 fn read_metadata_from_db(
18465 &mut self,
18466 item_id: u64,
18467 workspace_id: WorkspaceId,
18468 window: &mut Window,
18469 cx: &mut Context<Editor>,
18470 ) {
18471 if self.is_singleton(cx)
18472 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18473 {
18474 let buffer_snapshot = OnceCell::new();
18475
18476 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18477 if !folds.is_empty() {
18478 let snapshot =
18479 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18480 self.fold_ranges(
18481 folds
18482 .into_iter()
18483 .map(|(start, end)| {
18484 snapshot.clip_offset(start, Bias::Left)
18485 ..snapshot.clip_offset(end, Bias::Right)
18486 })
18487 .collect(),
18488 false,
18489 window,
18490 cx,
18491 );
18492 }
18493 }
18494
18495 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18496 if !selections.is_empty() {
18497 let snapshot =
18498 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18499 self.change_selections(None, window, cx, |s| {
18500 s.select_ranges(selections.into_iter().map(|(start, end)| {
18501 snapshot.clip_offset(start, Bias::Left)
18502 ..snapshot.clip_offset(end, Bias::Right)
18503 }));
18504 });
18505 }
18506 };
18507 }
18508
18509 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18510 }
18511}
18512
18513fn vim_enabled(cx: &App) -> bool {
18514 cx.global::<SettingsStore>()
18515 .raw_user_settings()
18516 .get("vim_mode")
18517 == Some(&serde_json::Value::Bool(true))
18518}
18519
18520// Consider user intent and default settings
18521fn choose_completion_range(
18522 completion: &Completion,
18523 intent: CompletionIntent,
18524 buffer: &Entity<Buffer>,
18525 cx: &mut Context<Editor>,
18526) -> Range<usize> {
18527 fn should_replace(
18528 completion: &Completion,
18529 insert_range: &Range<text::Anchor>,
18530 intent: CompletionIntent,
18531 completion_mode_setting: LspInsertMode,
18532 buffer: &Buffer,
18533 ) -> bool {
18534 // specific actions take precedence over settings
18535 match intent {
18536 CompletionIntent::CompleteWithInsert => return false,
18537 CompletionIntent::CompleteWithReplace => return true,
18538 CompletionIntent::Complete | CompletionIntent::Compose => {}
18539 }
18540
18541 match completion_mode_setting {
18542 LspInsertMode::Insert => false,
18543 LspInsertMode::Replace => true,
18544 LspInsertMode::ReplaceSubsequence => {
18545 let mut text_to_replace = buffer.chars_for_range(
18546 buffer.anchor_before(completion.replace_range.start)
18547 ..buffer.anchor_after(completion.replace_range.end),
18548 );
18549 let mut completion_text = completion.new_text.chars();
18550
18551 // is `text_to_replace` a subsequence of `completion_text`
18552 text_to_replace
18553 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18554 }
18555 LspInsertMode::ReplaceSuffix => {
18556 let range_after_cursor = insert_range.end..completion.replace_range.end;
18557
18558 let text_after_cursor = buffer
18559 .text_for_range(
18560 buffer.anchor_before(range_after_cursor.start)
18561 ..buffer.anchor_after(range_after_cursor.end),
18562 )
18563 .collect::<String>();
18564 completion.new_text.ends_with(&text_after_cursor)
18565 }
18566 }
18567 }
18568
18569 let buffer = buffer.read(cx);
18570
18571 if let CompletionSource::Lsp {
18572 insert_range: Some(insert_range),
18573 ..
18574 } = &completion.source
18575 {
18576 let completion_mode_setting =
18577 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18578 .completions
18579 .lsp_insert_mode;
18580
18581 if !should_replace(
18582 completion,
18583 &insert_range,
18584 intent,
18585 completion_mode_setting,
18586 buffer,
18587 ) {
18588 return insert_range.to_offset(buffer);
18589 }
18590 }
18591
18592 completion.replace_range.to_offset(buffer)
18593}
18594
18595fn insert_extra_newline_brackets(
18596 buffer: &MultiBufferSnapshot,
18597 range: Range<usize>,
18598 language: &language::LanguageScope,
18599) -> bool {
18600 let leading_whitespace_len = buffer
18601 .reversed_chars_at(range.start)
18602 .take_while(|c| c.is_whitespace() && *c != '\n')
18603 .map(|c| c.len_utf8())
18604 .sum::<usize>();
18605 let trailing_whitespace_len = buffer
18606 .chars_at(range.end)
18607 .take_while(|c| c.is_whitespace() && *c != '\n')
18608 .map(|c| c.len_utf8())
18609 .sum::<usize>();
18610 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18611
18612 language.brackets().any(|(pair, enabled)| {
18613 let pair_start = pair.start.trim_end();
18614 let pair_end = pair.end.trim_start();
18615
18616 enabled
18617 && pair.newline
18618 && buffer.contains_str_at(range.end, pair_end)
18619 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18620 })
18621}
18622
18623fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18624 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18625 [(buffer, range, _)] => (*buffer, range.clone()),
18626 _ => return false,
18627 };
18628 let pair = {
18629 let mut result: Option<BracketMatch> = None;
18630
18631 for pair in buffer
18632 .all_bracket_ranges(range.clone())
18633 .filter(move |pair| {
18634 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18635 })
18636 {
18637 let len = pair.close_range.end - pair.open_range.start;
18638
18639 if let Some(existing) = &result {
18640 let existing_len = existing.close_range.end - existing.open_range.start;
18641 if len > existing_len {
18642 continue;
18643 }
18644 }
18645
18646 result = Some(pair);
18647 }
18648
18649 result
18650 };
18651 let Some(pair) = pair else {
18652 return false;
18653 };
18654 pair.newline_only
18655 && buffer
18656 .chars_for_range(pair.open_range.end..range.start)
18657 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18658 .all(|c| c.is_whitespace() && c != '\n')
18659}
18660
18661fn get_uncommitted_diff_for_buffer(
18662 project: &Entity<Project>,
18663 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18664 buffer: Entity<MultiBuffer>,
18665 cx: &mut App,
18666) -> Task<()> {
18667 let mut tasks = Vec::new();
18668 project.update(cx, |project, cx| {
18669 for buffer in buffers {
18670 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18671 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18672 }
18673 }
18674 });
18675 cx.spawn(async move |cx| {
18676 let diffs = future::join_all(tasks).await;
18677 buffer
18678 .update(cx, |buffer, cx| {
18679 for diff in diffs.into_iter().flatten() {
18680 buffer.add_diff(diff, cx);
18681 }
18682 })
18683 .ok();
18684 })
18685}
18686
18687fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18688 let tab_size = tab_size.get() as usize;
18689 let mut width = offset;
18690
18691 for ch in text.chars() {
18692 width += if ch == '\t' {
18693 tab_size - (width % tab_size)
18694 } else {
18695 1
18696 };
18697 }
18698
18699 width - offset
18700}
18701
18702#[cfg(test)]
18703mod tests {
18704 use super::*;
18705
18706 #[test]
18707 fn test_string_size_with_expanded_tabs() {
18708 let nz = |val| NonZeroU32::new(val).unwrap();
18709 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18710 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18711 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18712 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18713 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18714 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18715 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18716 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18717 }
18718}
18719
18720/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18721struct WordBreakingTokenizer<'a> {
18722 input: &'a str,
18723}
18724
18725impl<'a> WordBreakingTokenizer<'a> {
18726 fn new(input: &'a str) -> Self {
18727 Self { input }
18728 }
18729}
18730
18731fn is_char_ideographic(ch: char) -> bool {
18732 use unicode_script::Script::*;
18733 use unicode_script::UnicodeScript;
18734 matches!(ch.script(), Han | Tangut | Yi)
18735}
18736
18737fn is_grapheme_ideographic(text: &str) -> bool {
18738 text.chars().any(is_char_ideographic)
18739}
18740
18741fn is_grapheme_whitespace(text: &str) -> bool {
18742 text.chars().any(|x| x.is_whitespace())
18743}
18744
18745fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18746 text.chars().next().map_or(false, |ch| {
18747 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18748 })
18749}
18750
18751#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18752enum WordBreakToken<'a> {
18753 Word { token: &'a str, grapheme_len: usize },
18754 InlineWhitespace { token: &'a str, grapheme_len: usize },
18755 Newline,
18756}
18757
18758impl<'a> Iterator for WordBreakingTokenizer<'a> {
18759 /// Yields a span, the count of graphemes in the token, and whether it was
18760 /// whitespace. Note that it also breaks at word boundaries.
18761 type Item = WordBreakToken<'a>;
18762
18763 fn next(&mut self) -> Option<Self::Item> {
18764 use unicode_segmentation::UnicodeSegmentation;
18765 if self.input.is_empty() {
18766 return None;
18767 }
18768
18769 let mut iter = self.input.graphemes(true).peekable();
18770 let mut offset = 0;
18771 let mut grapheme_len = 0;
18772 if let Some(first_grapheme) = iter.next() {
18773 let is_newline = first_grapheme == "\n";
18774 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18775 offset += first_grapheme.len();
18776 grapheme_len += 1;
18777 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18778 if let Some(grapheme) = iter.peek().copied() {
18779 if should_stay_with_preceding_ideograph(grapheme) {
18780 offset += grapheme.len();
18781 grapheme_len += 1;
18782 }
18783 }
18784 } else {
18785 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18786 let mut next_word_bound = words.peek().copied();
18787 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18788 next_word_bound = words.next();
18789 }
18790 while let Some(grapheme) = iter.peek().copied() {
18791 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18792 break;
18793 };
18794 if is_grapheme_whitespace(grapheme) != is_whitespace
18795 || (grapheme == "\n") != is_newline
18796 {
18797 break;
18798 };
18799 offset += grapheme.len();
18800 grapheme_len += 1;
18801 iter.next();
18802 }
18803 }
18804 let token = &self.input[..offset];
18805 self.input = &self.input[offset..];
18806 if token == "\n" {
18807 Some(WordBreakToken::Newline)
18808 } else if is_whitespace {
18809 Some(WordBreakToken::InlineWhitespace {
18810 token,
18811 grapheme_len,
18812 })
18813 } else {
18814 Some(WordBreakToken::Word {
18815 token,
18816 grapheme_len,
18817 })
18818 }
18819 } else {
18820 None
18821 }
18822 }
18823}
18824
18825#[test]
18826fn test_word_breaking_tokenizer() {
18827 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18828 ("", &[]),
18829 (" ", &[whitespace(" ", 2)]),
18830 ("Ʒ", &[word("Ʒ", 1)]),
18831 ("Ǽ", &[word("Ǽ", 1)]),
18832 ("⋑", &[word("⋑", 1)]),
18833 ("⋑⋑", &[word("⋑⋑", 2)]),
18834 (
18835 "原理,进而",
18836 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18837 ),
18838 (
18839 "hello world",
18840 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18841 ),
18842 (
18843 "hello, world",
18844 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18845 ),
18846 (
18847 " hello world",
18848 &[
18849 whitespace(" ", 2),
18850 word("hello", 5),
18851 whitespace(" ", 1),
18852 word("world", 5),
18853 ],
18854 ),
18855 (
18856 "这是什么 \n 钢笔",
18857 &[
18858 word("这", 1),
18859 word("是", 1),
18860 word("什", 1),
18861 word("么", 1),
18862 whitespace(" ", 1),
18863 newline(),
18864 whitespace(" ", 1),
18865 word("钢", 1),
18866 word("笔", 1),
18867 ],
18868 ),
18869 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18870 ];
18871
18872 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18873 WordBreakToken::Word {
18874 token,
18875 grapheme_len,
18876 }
18877 }
18878
18879 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18880 WordBreakToken::InlineWhitespace {
18881 token,
18882 grapheme_len,
18883 }
18884 }
18885
18886 fn newline() -> WordBreakToken<'static> {
18887 WordBreakToken::Newline
18888 }
18889
18890 for (input, result) in tests {
18891 assert_eq!(
18892 WordBreakingTokenizer::new(input)
18893 .collect::<Vec<_>>()
18894 .as_slice(),
18895 *result,
18896 );
18897 }
18898}
18899
18900fn wrap_with_prefix(
18901 line_prefix: String,
18902 unwrapped_text: String,
18903 wrap_column: usize,
18904 tab_size: NonZeroU32,
18905 preserve_existing_whitespace: bool,
18906) -> String {
18907 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18908 let mut wrapped_text = String::new();
18909 let mut current_line = line_prefix.clone();
18910
18911 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18912 let mut current_line_len = line_prefix_len;
18913 let mut in_whitespace = false;
18914 for token in tokenizer {
18915 let have_preceding_whitespace = in_whitespace;
18916 match token {
18917 WordBreakToken::Word {
18918 token,
18919 grapheme_len,
18920 } => {
18921 in_whitespace = false;
18922 if current_line_len + grapheme_len > wrap_column
18923 && current_line_len != line_prefix_len
18924 {
18925 wrapped_text.push_str(current_line.trim_end());
18926 wrapped_text.push('\n');
18927 current_line.truncate(line_prefix.len());
18928 current_line_len = line_prefix_len;
18929 }
18930 current_line.push_str(token);
18931 current_line_len += grapheme_len;
18932 }
18933 WordBreakToken::InlineWhitespace {
18934 mut token,
18935 mut grapheme_len,
18936 } => {
18937 in_whitespace = true;
18938 if have_preceding_whitespace && !preserve_existing_whitespace {
18939 continue;
18940 }
18941 if !preserve_existing_whitespace {
18942 token = " ";
18943 grapheme_len = 1;
18944 }
18945 if current_line_len + grapheme_len > wrap_column {
18946 wrapped_text.push_str(current_line.trim_end());
18947 wrapped_text.push('\n');
18948 current_line.truncate(line_prefix.len());
18949 current_line_len = line_prefix_len;
18950 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18951 current_line.push_str(token);
18952 current_line_len += grapheme_len;
18953 }
18954 }
18955 WordBreakToken::Newline => {
18956 in_whitespace = true;
18957 if preserve_existing_whitespace {
18958 wrapped_text.push_str(current_line.trim_end());
18959 wrapped_text.push('\n');
18960 current_line.truncate(line_prefix.len());
18961 current_line_len = line_prefix_len;
18962 } else if have_preceding_whitespace {
18963 continue;
18964 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18965 {
18966 wrapped_text.push_str(current_line.trim_end());
18967 wrapped_text.push('\n');
18968 current_line.truncate(line_prefix.len());
18969 current_line_len = line_prefix_len;
18970 } else if current_line_len != line_prefix_len {
18971 current_line.push(' ');
18972 current_line_len += 1;
18973 }
18974 }
18975 }
18976 }
18977
18978 if !current_line.is_empty() {
18979 wrapped_text.push_str(¤t_line);
18980 }
18981 wrapped_text
18982}
18983
18984#[test]
18985fn test_wrap_with_prefix() {
18986 assert_eq!(
18987 wrap_with_prefix(
18988 "# ".to_string(),
18989 "abcdefg".to_string(),
18990 4,
18991 NonZeroU32::new(4).unwrap(),
18992 false,
18993 ),
18994 "# abcdefg"
18995 );
18996 assert_eq!(
18997 wrap_with_prefix(
18998 "".to_string(),
18999 "\thello world".to_string(),
19000 8,
19001 NonZeroU32::new(4).unwrap(),
19002 false,
19003 ),
19004 "hello\nworld"
19005 );
19006 assert_eq!(
19007 wrap_with_prefix(
19008 "// ".to_string(),
19009 "xx \nyy zz aa bb cc".to_string(),
19010 12,
19011 NonZeroU32::new(4).unwrap(),
19012 false,
19013 ),
19014 "// xx yy zz\n// aa bb cc"
19015 );
19016 assert_eq!(
19017 wrap_with_prefix(
19018 String::new(),
19019 "这是什么 \n 钢笔".to_string(),
19020 3,
19021 NonZeroU32::new(4).unwrap(),
19022 false,
19023 ),
19024 "这是什\n么 钢\n笔"
19025 );
19026}
19027
19028pub trait CollaborationHub {
19029 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19030 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19031 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19032}
19033
19034impl CollaborationHub for Entity<Project> {
19035 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19036 self.read(cx).collaborators()
19037 }
19038
19039 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19040 self.read(cx).user_store().read(cx).participant_indices()
19041 }
19042
19043 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19044 let this = self.read(cx);
19045 let user_ids = this.collaborators().values().map(|c| c.user_id);
19046 this.user_store().read_with(cx, |user_store, cx| {
19047 user_store.participant_names(user_ids, cx)
19048 })
19049 }
19050}
19051
19052pub trait SemanticsProvider {
19053 fn hover(
19054 &self,
19055 buffer: &Entity<Buffer>,
19056 position: text::Anchor,
19057 cx: &mut App,
19058 ) -> Option<Task<Vec<project::Hover>>>;
19059
19060 fn inline_values(
19061 &self,
19062 buffer_handle: Entity<Buffer>,
19063 range: Range<text::Anchor>,
19064 cx: &mut App,
19065 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19066
19067 fn inlay_hints(
19068 &self,
19069 buffer_handle: Entity<Buffer>,
19070 range: Range<text::Anchor>,
19071 cx: &mut App,
19072 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19073
19074 fn resolve_inlay_hint(
19075 &self,
19076 hint: InlayHint,
19077 buffer_handle: Entity<Buffer>,
19078 server_id: LanguageServerId,
19079 cx: &mut App,
19080 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19081
19082 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19083
19084 fn document_highlights(
19085 &self,
19086 buffer: &Entity<Buffer>,
19087 position: text::Anchor,
19088 cx: &mut App,
19089 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19090
19091 fn definitions(
19092 &self,
19093 buffer: &Entity<Buffer>,
19094 position: text::Anchor,
19095 kind: GotoDefinitionKind,
19096 cx: &mut App,
19097 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19098
19099 fn range_for_rename(
19100 &self,
19101 buffer: &Entity<Buffer>,
19102 position: text::Anchor,
19103 cx: &mut App,
19104 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19105
19106 fn perform_rename(
19107 &self,
19108 buffer: &Entity<Buffer>,
19109 position: text::Anchor,
19110 new_name: String,
19111 cx: &mut App,
19112 ) -> Option<Task<Result<ProjectTransaction>>>;
19113}
19114
19115pub trait CompletionProvider {
19116 fn completions(
19117 &self,
19118 excerpt_id: ExcerptId,
19119 buffer: &Entity<Buffer>,
19120 buffer_position: text::Anchor,
19121 trigger: CompletionContext,
19122 window: &mut Window,
19123 cx: &mut Context<Editor>,
19124 ) -> Task<Result<Option<Vec<Completion>>>>;
19125
19126 fn resolve_completions(
19127 &self,
19128 buffer: Entity<Buffer>,
19129 completion_indices: Vec<usize>,
19130 completions: Rc<RefCell<Box<[Completion]>>>,
19131 cx: &mut Context<Editor>,
19132 ) -> Task<Result<bool>>;
19133
19134 fn apply_additional_edits_for_completion(
19135 &self,
19136 _buffer: Entity<Buffer>,
19137 _completions: Rc<RefCell<Box<[Completion]>>>,
19138 _completion_index: usize,
19139 _push_to_history: bool,
19140 _cx: &mut Context<Editor>,
19141 ) -> Task<Result<Option<language::Transaction>>> {
19142 Task::ready(Ok(None))
19143 }
19144
19145 fn is_completion_trigger(
19146 &self,
19147 buffer: &Entity<Buffer>,
19148 position: language::Anchor,
19149 text: &str,
19150 trigger_in_words: bool,
19151 cx: &mut Context<Editor>,
19152 ) -> bool;
19153
19154 fn sort_completions(&self) -> bool {
19155 true
19156 }
19157
19158 fn filter_completions(&self) -> bool {
19159 true
19160 }
19161}
19162
19163pub trait CodeActionProvider {
19164 fn id(&self) -> Arc<str>;
19165
19166 fn code_actions(
19167 &self,
19168 buffer: &Entity<Buffer>,
19169 range: Range<text::Anchor>,
19170 window: &mut Window,
19171 cx: &mut App,
19172 ) -> Task<Result<Vec<CodeAction>>>;
19173
19174 fn apply_code_action(
19175 &self,
19176 buffer_handle: Entity<Buffer>,
19177 action: CodeAction,
19178 excerpt_id: ExcerptId,
19179 push_to_history: bool,
19180 window: &mut Window,
19181 cx: &mut App,
19182 ) -> Task<Result<ProjectTransaction>>;
19183}
19184
19185impl CodeActionProvider for Entity<Project> {
19186 fn id(&self) -> Arc<str> {
19187 "project".into()
19188 }
19189
19190 fn code_actions(
19191 &self,
19192 buffer: &Entity<Buffer>,
19193 range: Range<text::Anchor>,
19194 _window: &mut Window,
19195 cx: &mut App,
19196 ) -> Task<Result<Vec<CodeAction>>> {
19197 self.update(cx, |project, cx| {
19198 let code_lens = project.code_lens(buffer, range.clone(), cx);
19199 let code_actions = project.code_actions(buffer, range, None, cx);
19200 cx.background_spawn(async move {
19201 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19202 Ok(code_lens
19203 .context("code lens fetch")?
19204 .into_iter()
19205 .chain(code_actions.context("code action fetch")?)
19206 .collect())
19207 })
19208 })
19209 }
19210
19211 fn apply_code_action(
19212 &self,
19213 buffer_handle: Entity<Buffer>,
19214 action: CodeAction,
19215 _excerpt_id: ExcerptId,
19216 push_to_history: bool,
19217 _window: &mut Window,
19218 cx: &mut App,
19219 ) -> Task<Result<ProjectTransaction>> {
19220 self.update(cx, |project, cx| {
19221 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19222 })
19223 }
19224}
19225
19226fn snippet_completions(
19227 project: &Project,
19228 buffer: &Entity<Buffer>,
19229 buffer_position: text::Anchor,
19230 cx: &mut App,
19231) -> Task<Result<Vec<Completion>>> {
19232 let languages = buffer.read(cx).languages_at(buffer_position);
19233 let snippet_store = project.snippets().read(cx);
19234
19235 let scopes: Vec<_> = languages
19236 .iter()
19237 .filter_map(|language| {
19238 let language_name = language.lsp_id();
19239 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19240
19241 if snippets.is_empty() {
19242 None
19243 } else {
19244 Some((language.default_scope(), snippets))
19245 }
19246 })
19247 .collect();
19248
19249 if scopes.is_empty() {
19250 return Task::ready(Ok(vec![]));
19251 }
19252
19253 let snapshot = buffer.read(cx).text_snapshot();
19254 let chars: String = snapshot
19255 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19256 .collect();
19257 let executor = cx.background_executor().clone();
19258
19259 cx.background_spawn(async move {
19260 let mut all_results: Vec<Completion> = Vec::new();
19261 for (scope, snippets) in scopes.into_iter() {
19262 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19263 let mut last_word = chars
19264 .chars()
19265 .take_while(|c| classifier.is_word(*c))
19266 .collect::<String>();
19267 last_word = last_word.chars().rev().collect();
19268
19269 if last_word.is_empty() {
19270 return Ok(vec![]);
19271 }
19272
19273 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19274 let to_lsp = |point: &text::Anchor| {
19275 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19276 point_to_lsp(end)
19277 };
19278 let lsp_end = to_lsp(&buffer_position);
19279
19280 let candidates = snippets
19281 .iter()
19282 .enumerate()
19283 .flat_map(|(ix, snippet)| {
19284 snippet
19285 .prefix
19286 .iter()
19287 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19288 })
19289 .collect::<Vec<StringMatchCandidate>>();
19290
19291 let mut matches = fuzzy::match_strings(
19292 &candidates,
19293 &last_word,
19294 last_word.chars().any(|c| c.is_uppercase()),
19295 100,
19296 &Default::default(),
19297 executor.clone(),
19298 )
19299 .await;
19300
19301 // Remove all candidates where the query's start does not match the start of any word in the candidate
19302 if let Some(query_start) = last_word.chars().next() {
19303 matches.retain(|string_match| {
19304 split_words(&string_match.string).any(|word| {
19305 // Check that the first codepoint of the word as lowercase matches the first
19306 // codepoint of the query as lowercase
19307 word.chars()
19308 .flat_map(|codepoint| codepoint.to_lowercase())
19309 .zip(query_start.to_lowercase())
19310 .all(|(word_cp, query_cp)| word_cp == query_cp)
19311 })
19312 });
19313 }
19314
19315 let matched_strings = matches
19316 .into_iter()
19317 .map(|m| m.string)
19318 .collect::<HashSet<_>>();
19319
19320 let mut result: Vec<Completion> = snippets
19321 .iter()
19322 .filter_map(|snippet| {
19323 let matching_prefix = snippet
19324 .prefix
19325 .iter()
19326 .find(|prefix| matched_strings.contains(*prefix))?;
19327 let start = as_offset - last_word.len();
19328 let start = snapshot.anchor_before(start);
19329 let range = start..buffer_position;
19330 let lsp_start = to_lsp(&start);
19331 let lsp_range = lsp::Range {
19332 start: lsp_start,
19333 end: lsp_end,
19334 };
19335 Some(Completion {
19336 replace_range: range,
19337 new_text: snippet.body.clone(),
19338 source: CompletionSource::Lsp {
19339 insert_range: None,
19340 server_id: LanguageServerId(usize::MAX),
19341 resolved: true,
19342 lsp_completion: Box::new(lsp::CompletionItem {
19343 label: snippet.prefix.first().unwrap().clone(),
19344 kind: Some(CompletionItemKind::SNIPPET),
19345 label_details: snippet.description.as_ref().map(|description| {
19346 lsp::CompletionItemLabelDetails {
19347 detail: Some(description.clone()),
19348 description: None,
19349 }
19350 }),
19351 insert_text_format: Some(InsertTextFormat::SNIPPET),
19352 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19353 lsp::InsertReplaceEdit {
19354 new_text: snippet.body.clone(),
19355 insert: lsp_range,
19356 replace: lsp_range,
19357 },
19358 )),
19359 filter_text: Some(snippet.body.clone()),
19360 sort_text: Some(char::MAX.to_string()),
19361 ..lsp::CompletionItem::default()
19362 }),
19363 lsp_defaults: None,
19364 },
19365 label: CodeLabel {
19366 text: matching_prefix.clone(),
19367 runs: Vec::new(),
19368 filter_range: 0..matching_prefix.len(),
19369 },
19370 icon_path: None,
19371 documentation: snippet.description.clone().map(|description| {
19372 CompletionDocumentation::SingleLine(description.into())
19373 }),
19374 insert_text_mode: None,
19375 confirm: None,
19376 })
19377 })
19378 .collect();
19379
19380 all_results.append(&mut result);
19381 }
19382
19383 Ok(all_results)
19384 })
19385}
19386
19387impl CompletionProvider for Entity<Project> {
19388 fn completions(
19389 &self,
19390 _excerpt_id: ExcerptId,
19391 buffer: &Entity<Buffer>,
19392 buffer_position: text::Anchor,
19393 options: CompletionContext,
19394 _window: &mut Window,
19395 cx: &mut Context<Editor>,
19396 ) -> Task<Result<Option<Vec<Completion>>>> {
19397 self.update(cx, |project, cx| {
19398 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19399 let project_completions = project.completions(buffer, buffer_position, options, cx);
19400 cx.background_spawn(async move {
19401 let snippets_completions = snippets.await?;
19402 match project_completions.await? {
19403 Some(mut completions) => {
19404 completions.extend(snippets_completions);
19405 Ok(Some(completions))
19406 }
19407 None => {
19408 if snippets_completions.is_empty() {
19409 Ok(None)
19410 } else {
19411 Ok(Some(snippets_completions))
19412 }
19413 }
19414 }
19415 })
19416 })
19417 }
19418
19419 fn resolve_completions(
19420 &self,
19421 buffer: Entity<Buffer>,
19422 completion_indices: Vec<usize>,
19423 completions: Rc<RefCell<Box<[Completion]>>>,
19424 cx: &mut Context<Editor>,
19425 ) -> Task<Result<bool>> {
19426 self.update(cx, |project, cx| {
19427 project.lsp_store().update(cx, |lsp_store, cx| {
19428 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19429 })
19430 })
19431 }
19432
19433 fn apply_additional_edits_for_completion(
19434 &self,
19435 buffer: Entity<Buffer>,
19436 completions: Rc<RefCell<Box<[Completion]>>>,
19437 completion_index: usize,
19438 push_to_history: bool,
19439 cx: &mut Context<Editor>,
19440 ) -> Task<Result<Option<language::Transaction>>> {
19441 self.update(cx, |project, cx| {
19442 project.lsp_store().update(cx, |lsp_store, cx| {
19443 lsp_store.apply_additional_edits_for_completion(
19444 buffer,
19445 completions,
19446 completion_index,
19447 push_to_history,
19448 cx,
19449 )
19450 })
19451 })
19452 }
19453
19454 fn is_completion_trigger(
19455 &self,
19456 buffer: &Entity<Buffer>,
19457 position: language::Anchor,
19458 text: &str,
19459 trigger_in_words: bool,
19460 cx: &mut Context<Editor>,
19461 ) -> bool {
19462 let mut chars = text.chars();
19463 let char = if let Some(char) = chars.next() {
19464 char
19465 } else {
19466 return false;
19467 };
19468 if chars.next().is_some() {
19469 return false;
19470 }
19471
19472 let buffer = buffer.read(cx);
19473 let snapshot = buffer.snapshot();
19474 if !snapshot.settings_at(position, cx).show_completions_on_input {
19475 return false;
19476 }
19477 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19478 if trigger_in_words && classifier.is_word(char) {
19479 return true;
19480 }
19481
19482 buffer.completion_triggers().contains(text)
19483 }
19484}
19485
19486impl SemanticsProvider for Entity<Project> {
19487 fn hover(
19488 &self,
19489 buffer: &Entity<Buffer>,
19490 position: text::Anchor,
19491 cx: &mut App,
19492 ) -> Option<Task<Vec<project::Hover>>> {
19493 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19494 }
19495
19496 fn document_highlights(
19497 &self,
19498 buffer: &Entity<Buffer>,
19499 position: text::Anchor,
19500 cx: &mut App,
19501 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19502 Some(self.update(cx, |project, cx| {
19503 project.document_highlights(buffer, position, cx)
19504 }))
19505 }
19506
19507 fn definitions(
19508 &self,
19509 buffer: &Entity<Buffer>,
19510 position: text::Anchor,
19511 kind: GotoDefinitionKind,
19512 cx: &mut App,
19513 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19514 Some(self.update(cx, |project, cx| match kind {
19515 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19516 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19517 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19518 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19519 }))
19520 }
19521
19522 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19523 // TODO: make this work for remote projects
19524 self.update(cx, |project, cx| {
19525 if project
19526 .active_debug_session(cx)
19527 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19528 {
19529 return true;
19530 }
19531
19532 buffer.update(cx, |buffer, cx| {
19533 project.any_language_server_supports_inlay_hints(buffer, cx)
19534 })
19535 })
19536 }
19537
19538 fn inline_values(
19539 &self,
19540 buffer_handle: Entity<Buffer>,
19541 range: Range<text::Anchor>,
19542 cx: &mut App,
19543 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19544 self.update(cx, |project, cx| {
19545 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19546
19547 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19548 })
19549 }
19550
19551 fn inlay_hints(
19552 &self,
19553 buffer_handle: Entity<Buffer>,
19554 range: Range<text::Anchor>,
19555 cx: &mut App,
19556 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19557 Some(self.update(cx, |project, cx| {
19558 project.inlay_hints(buffer_handle, range, cx)
19559 }))
19560 }
19561
19562 fn resolve_inlay_hint(
19563 &self,
19564 hint: InlayHint,
19565 buffer_handle: Entity<Buffer>,
19566 server_id: LanguageServerId,
19567 cx: &mut App,
19568 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19569 Some(self.update(cx, |project, cx| {
19570 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19571 }))
19572 }
19573
19574 fn range_for_rename(
19575 &self,
19576 buffer: &Entity<Buffer>,
19577 position: text::Anchor,
19578 cx: &mut App,
19579 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19580 Some(self.update(cx, |project, cx| {
19581 let buffer = buffer.clone();
19582 let task = project.prepare_rename(buffer.clone(), position, cx);
19583 cx.spawn(async move |_, cx| {
19584 Ok(match task.await? {
19585 PrepareRenameResponse::Success(range) => Some(range),
19586 PrepareRenameResponse::InvalidPosition => None,
19587 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19588 // Fallback on using TreeSitter info to determine identifier range
19589 buffer.update(cx, |buffer, _| {
19590 let snapshot = buffer.snapshot();
19591 let (range, kind) = snapshot.surrounding_word(position);
19592 if kind != Some(CharKind::Word) {
19593 return None;
19594 }
19595 Some(
19596 snapshot.anchor_before(range.start)
19597 ..snapshot.anchor_after(range.end),
19598 )
19599 })?
19600 }
19601 })
19602 })
19603 }))
19604 }
19605
19606 fn perform_rename(
19607 &self,
19608 buffer: &Entity<Buffer>,
19609 position: text::Anchor,
19610 new_name: String,
19611 cx: &mut App,
19612 ) -> Option<Task<Result<ProjectTransaction>>> {
19613 Some(self.update(cx, |project, cx| {
19614 project.perform_rename(buffer.clone(), position, new_name, cx)
19615 }))
19616 }
19617}
19618
19619fn inlay_hint_settings(
19620 location: Anchor,
19621 snapshot: &MultiBufferSnapshot,
19622 cx: &mut Context<Editor>,
19623) -> InlayHintSettings {
19624 let file = snapshot.file_at(location);
19625 let language = snapshot.language_at(location).map(|l| l.name());
19626 language_settings(language, file, cx).inlay_hints
19627}
19628
19629fn consume_contiguous_rows(
19630 contiguous_row_selections: &mut Vec<Selection<Point>>,
19631 selection: &Selection<Point>,
19632 display_map: &DisplaySnapshot,
19633 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19634) -> (MultiBufferRow, MultiBufferRow) {
19635 contiguous_row_selections.push(selection.clone());
19636 let start_row = MultiBufferRow(selection.start.row);
19637 let mut end_row = ending_row(selection, display_map);
19638
19639 while let Some(next_selection) = selections.peek() {
19640 if next_selection.start.row <= end_row.0 {
19641 end_row = ending_row(next_selection, display_map);
19642 contiguous_row_selections.push(selections.next().unwrap().clone());
19643 } else {
19644 break;
19645 }
19646 }
19647 (start_row, end_row)
19648}
19649
19650fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19651 if next_selection.end.column > 0 || next_selection.is_empty() {
19652 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19653 } else {
19654 MultiBufferRow(next_selection.end.row)
19655 }
19656}
19657
19658impl EditorSnapshot {
19659 pub fn remote_selections_in_range<'a>(
19660 &'a self,
19661 range: &'a Range<Anchor>,
19662 collaboration_hub: &dyn CollaborationHub,
19663 cx: &'a App,
19664 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19665 let participant_names = collaboration_hub.user_names(cx);
19666 let participant_indices = collaboration_hub.user_participant_indices(cx);
19667 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19668 let collaborators_by_replica_id = collaborators_by_peer_id
19669 .iter()
19670 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19671 .collect::<HashMap<_, _>>();
19672 self.buffer_snapshot
19673 .selections_in_range(range, false)
19674 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19675 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19676 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19677 let user_name = participant_names.get(&collaborator.user_id).cloned();
19678 Some(RemoteSelection {
19679 replica_id,
19680 selection,
19681 cursor_shape,
19682 line_mode,
19683 participant_index,
19684 peer_id: collaborator.peer_id,
19685 user_name,
19686 })
19687 })
19688 }
19689
19690 pub fn hunks_for_ranges(
19691 &self,
19692 ranges: impl IntoIterator<Item = Range<Point>>,
19693 ) -> Vec<MultiBufferDiffHunk> {
19694 let mut hunks = Vec::new();
19695 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19696 HashMap::default();
19697 for query_range in ranges {
19698 let query_rows =
19699 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19700 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19701 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19702 ) {
19703 // Include deleted hunks that are adjacent to the query range, because
19704 // otherwise they would be missed.
19705 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19706 if hunk.status().is_deleted() {
19707 intersects_range |= hunk.row_range.start == query_rows.end;
19708 intersects_range |= hunk.row_range.end == query_rows.start;
19709 }
19710 if intersects_range {
19711 if !processed_buffer_rows
19712 .entry(hunk.buffer_id)
19713 .or_default()
19714 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19715 {
19716 continue;
19717 }
19718 hunks.push(hunk);
19719 }
19720 }
19721 }
19722
19723 hunks
19724 }
19725
19726 fn display_diff_hunks_for_rows<'a>(
19727 &'a self,
19728 display_rows: Range<DisplayRow>,
19729 folded_buffers: &'a HashSet<BufferId>,
19730 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19731 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19732 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19733
19734 self.buffer_snapshot
19735 .diff_hunks_in_range(buffer_start..buffer_end)
19736 .filter_map(|hunk| {
19737 if folded_buffers.contains(&hunk.buffer_id) {
19738 return None;
19739 }
19740
19741 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19742 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19743
19744 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19745 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19746
19747 let display_hunk = if hunk_display_start.column() != 0 {
19748 DisplayDiffHunk::Folded {
19749 display_row: hunk_display_start.row(),
19750 }
19751 } else {
19752 let mut end_row = hunk_display_end.row();
19753 if hunk_display_end.column() > 0 {
19754 end_row.0 += 1;
19755 }
19756 let is_created_file = hunk.is_created_file();
19757 DisplayDiffHunk::Unfolded {
19758 status: hunk.status(),
19759 diff_base_byte_range: hunk.diff_base_byte_range,
19760 display_row_range: hunk_display_start.row()..end_row,
19761 multi_buffer_range: Anchor::range_in_buffer(
19762 hunk.excerpt_id,
19763 hunk.buffer_id,
19764 hunk.buffer_range,
19765 ),
19766 is_created_file,
19767 }
19768 };
19769
19770 Some(display_hunk)
19771 })
19772 }
19773
19774 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19775 self.display_snapshot.buffer_snapshot.language_at(position)
19776 }
19777
19778 pub fn is_focused(&self) -> bool {
19779 self.is_focused
19780 }
19781
19782 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19783 self.placeholder_text.as_ref()
19784 }
19785
19786 pub fn scroll_position(&self) -> gpui::Point<f32> {
19787 self.scroll_anchor.scroll_position(&self.display_snapshot)
19788 }
19789
19790 fn gutter_dimensions(
19791 &self,
19792 font_id: FontId,
19793 font_size: Pixels,
19794 max_line_number_width: Pixels,
19795 cx: &App,
19796 ) -> Option<GutterDimensions> {
19797 if !self.show_gutter {
19798 return None;
19799 }
19800
19801 let descent = cx.text_system().descent(font_id, font_size);
19802 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19803 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19804
19805 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19806 matches!(
19807 ProjectSettings::get_global(cx).git.git_gutter,
19808 Some(GitGutterSetting::TrackedFiles)
19809 )
19810 });
19811 let gutter_settings = EditorSettings::get_global(cx).gutter;
19812 let show_line_numbers = self
19813 .show_line_numbers
19814 .unwrap_or(gutter_settings.line_numbers);
19815 let line_gutter_width = if show_line_numbers {
19816 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19817 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19818 max_line_number_width.max(min_width_for_number_on_gutter)
19819 } else {
19820 0.0.into()
19821 };
19822
19823 let show_code_actions = self
19824 .show_code_actions
19825 .unwrap_or(gutter_settings.code_actions);
19826
19827 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19828 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19829
19830 let git_blame_entries_width =
19831 self.git_blame_gutter_max_author_length
19832 .map(|max_author_length| {
19833 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19834 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19835
19836 /// The number of characters to dedicate to gaps and margins.
19837 const SPACING_WIDTH: usize = 4;
19838
19839 let max_char_count = max_author_length.min(renderer.max_author_length())
19840 + ::git::SHORT_SHA_LENGTH
19841 + MAX_RELATIVE_TIMESTAMP.len()
19842 + SPACING_WIDTH;
19843
19844 em_advance * max_char_count
19845 });
19846
19847 let is_singleton = self.buffer_snapshot.is_singleton();
19848
19849 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19850 left_padding += if !is_singleton {
19851 em_width * 4.0
19852 } else if show_code_actions || show_runnables || show_breakpoints {
19853 em_width * 3.0
19854 } else if show_git_gutter && show_line_numbers {
19855 em_width * 2.0
19856 } else if show_git_gutter || show_line_numbers {
19857 em_width
19858 } else {
19859 px(0.)
19860 };
19861
19862 let shows_folds = is_singleton && gutter_settings.folds;
19863
19864 let right_padding = if shows_folds && show_line_numbers {
19865 em_width * 4.0
19866 } else if shows_folds || (!is_singleton && show_line_numbers) {
19867 em_width * 3.0
19868 } else if show_line_numbers {
19869 em_width
19870 } else {
19871 px(0.)
19872 };
19873
19874 Some(GutterDimensions {
19875 left_padding,
19876 right_padding,
19877 width: line_gutter_width + left_padding + right_padding,
19878 margin: -descent,
19879 git_blame_entries_width,
19880 })
19881 }
19882
19883 pub fn render_crease_toggle(
19884 &self,
19885 buffer_row: MultiBufferRow,
19886 row_contains_cursor: bool,
19887 editor: Entity<Editor>,
19888 window: &mut Window,
19889 cx: &mut App,
19890 ) -> Option<AnyElement> {
19891 let folded = self.is_line_folded(buffer_row);
19892 let mut is_foldable = false;
19893
19894 if let Some(crease) = self
19895 .crease_snapshot
19896 .query_row(buffer_row, &self.buffer_snapshot)
19897 {
19898 is_foldable = true;
19899 match crease {
19900 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19901 if let Some(render_toggle) = render_toggle {
19902 let toggle_callback =
19903 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19904 if folded {
19905 editor.update(cx, |editor, cx| {
19906 editor.fold_at(buffer_row, window, cx)
19907 });
19908 } else {
19909 editor.update(cx, |editor, cx| {
19910 editor.unfold_at(buffer_row, window, cx)
19911 });
19912 }
19913 });
19914 return Some((render_toggle)(
19915 buffer_row,
19916 folded,
19917 toggle_callback,
19918 window,
19919 cx,
19920 ));
19921 }
19922 }
19923 }
19924 }
19925
19926 is_foldable |= self.starts_indent(buffer_row);
19927
19928 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19929 Some(
19930 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19931 .toggle_state(folded)
19932 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19933 if folded {
19934 this.unfold_at(buffer_row, window, cx);
19935 } else {
19936 this.fold_at(buffer_row, window, cx);
19937 }
19938 }))
19939 .into_any_element(),
19940 )
19941 } else {
19942 None
19943 }
19944 }
19945
19946 pub fn render_crease_trailer(
19947 &self,
19948 buffer_row: MultiBufferRow,
19949 window: &mut Window,
19950 cx: &mut App,
19951 ) -> Option<AnyElement> {
19952 let folded = self.is_line_folded(buffer_row);
19953 if let Crease::Inline { render_trailer, .. } = self
19954 .crease_snapshot
19955 .query_row(buffer_row, &self.buffer_snapshot)?
19956 {
19957 let render_trailer = render_trailer.as_ref()?;
19958 Some(render_trailer(buffer_row, folded, window, cx))
19959 } else {
19960 None
19961 }
19962 }
19963}
19964
19965impl Deref for EditorSnapshot {
19966 type Target = DisplaySnapshot;
19967
19968 fn deref(&self) -> &Self::Target {
19969 &self.display_snapshot
19970 }
19971}
19972
19973#[derive(Clone, Debug, PartialEq, Eq)]
19974pub enum EditorEvent {
19975 InputIgnored {
19976 text: Arc<str>,
19977 },
19978 InputHandled {
19979 utf16_range_to_replace: Option<Range<isize>>,
19980 text: Arc<str>,
19981 },
19982 ExcerptsAdded {
19983 buffer: Entity<Buffer>,
19984 predecessor: ExcerptId,
19985 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19986 },
19987 ExcerptsRemoved {
19988 ids: Vec<ExcerptId>,
19989 removed_buffer_ids: Vec<BufferId>,
19990 },
19991 BufferFoldToggled {
19992 ids: Vec<ExcerptId>,
19993 folded: bool,
19994 },
19995 ExcerptsEdited {
19996 ids: Vec<ExcerptId>,
19997 },
19998 ExcerptsExpanded {
19999 ids: Vec<ExcerptId>,
20000 },
20001 BufferEdited,
20002 Edited {
20003 transaction_id: clock::Lamport,
20004 },
20005 Reparsed(BufferId),
20006 Focused,
20007 FocusedIn,
20008 Blurred,
20009 DirtyChanged,
20010 Saved,
20011 TitleChanged,
20012 DiffBaseChanged,
20013 SelectionsChanged {
20014 local: bool,
20015 },
20016 ScrollPositionChanged {
20017 local: bool,
20018 autoscroll: bool,
20019 },
20020 Closed,
20021 TransactionUndone {
20022 transaction_id: clock::Lamport,
20023 },
20024 TransactionBegun {
20025 transaction_id: clock::Lamport,
20026 },
20027 Reloaded,
20028 CursorShapeChanged,
20029 PushedToNavHistory {
20030 anchor: Anchor,
20031 is_deactivate: bool,
20032 },
20033}
20034
20035impl EventEmitter<EditorEvent> for Editor {}
20036
20037impl Focusable for Editor {
20038 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20039 self.focus_handle.clone()
20040 }
20041}
20042
20043impl Render for Editor {
20044 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20045 let settings = ThemeSettings::get_global(cx);
20046
20047 let mut text_style = match self.mode {
20048 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20049 color: cx.theme().colors().editor_foreground,
20050 font_family: settings.ui_font.family.clone(),
20051 font_features: settings.ui_font.features.clone(),
20052 font_fallbacks: settings.ui_font.fallbacks.clone(),
20053 font_size: rems(0.875).into(),
20054 font_weight: settings.ui_font.weight,
20055 line_height: relative(settings.buffer_line_height.value()),
20056 ..Default::default()
20057 },
20058 EditorMode::Full { .. } => TextStyle {
20059 color: cx.theme().colors().editor_foreground,
20060 font_family: settings.buffer_font.family.clone(),
20061 font_features: settings.buffer_font.features.clone(),
20062 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20063 font_size: settings.buffer_font_size(cx).into(),
20064 font_weight: settings.buffer_font.weight,
20065 line_height: relative(settings.buffer_line_height.value()),
20066 ..Default::default()
20067 },
20068 };
20069 if let Some(text_style_refinement) = &self.text_style_refinement {
20070 text_style.refine(text_style_refinement)
20071 }
20072
20073 let background = match self.mode {
20074 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20075 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20076 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20077 };
20078
20079 EditorElement::new(
20080 &cx.entity(),
20081 EditorStyle {
20082 background,
20083 local_player: cx.theme().players().local(),
20084 text: text_style,
20085 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20086 syntax: cx.theme().syntax().clone(),
20087 status: cx.theme().status().clone(),
20088 inlay_hints_style: make_inlay_hints_style(cx),
20089 inline_completion_styles: make_suggestion_styles(cx),
20090 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20091 },
20092 )
20093 }
20094}
20095
20096impl EntityInputHandler for Editor {
20097 fn text_for_range(
20098 &mut self,
20099 range_utf16: Range<usize>,
20100 adjusted_range: &mut Option<Range<usize>>,
20101 _: &mut Window,
20102 cx: &mut Context<Self>,
20103 ) -> Option<String> {
20104 let snapshot = self.buffer.read(cx).read(cx);
20105 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20106 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20107 if (start.0..end.0) != range_utf16 {
20108 adjusted_range.replace(start.0..end.0);
20109 }
20110 Some(snapshot.text_for_range(start..end).collect())
20111 }
20112
20113 fn selected_text_range(
20114 &mut self,
20115 ignore_disabled_input: bool,
20116 _: &mut Window,
20117 cx: &mut Context<Self>,
20118 ) -> Option<UTF16Selection> {
20119 // Prevent the IME menu from appearing when holding down an alphabetic key
20120 // while input is disabled.
20121 if !ignore_disabled_input && !self.input_enabled {
20122 return None;
20123 }
20124
20125 let selection = self.selections.newest::<OffsetUtf16>(cx);
20126 let range = selection.range();
20127
20128 Some(UTF16Selection {
20129 range: range.start.0..range.end.0,
20130 reversed: selection.reversed,
20131 })
20132 }
20133
20134 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20135 let snapshot = self.buffer.read(cx).read(cx);
20136 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20137 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20138 }
20139
20140 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20141 self.clear_highlights::<InputComposition>(cx);
20142 self.ime_transaction.take();
20143 }
20144
20145 fn replace_text_in_range(
20146 &mut self,
20147 range_utf16: Option<Range<usize>>,
20148 text: &str,
20149 window: &mut Window,
20150 cx: &mut Context<Self>,
20151 ) {
20152 if !self.input_enabled {
20153 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20154 return;
20155 }
20156
20157 self.transact(window, cx, |this, window, cx| {
20158 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20159 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20160 Some(this.selection_replacement_ranges(range_utf16, cx))
20161 } else {
20162 this.marked_text_ranges(cx)
20163 };
20164
20165 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20166 let newest_selection_id = this.selections.newest_anchor().id;
20167 this.selections
20168 .all::<OffsetUtf16>(cx)
20169 .iter()
20170 .zip(ranges_to_replace.iter())
20171 .find_map(|(selection, range)| {
20172 if selection.id == newest_selection_id {
20173 Some(
20174 (range.start.0 as isize - selection.head().0 as isize)
20175 ..(range.end.0 as isize - selection.head().0 as isize),
20176 )
20177 } else {
20178 None
20179 }
20180 })
20181 });
20182
20183 cx.emit(EditorEvent::InputHandled {
20184 utf16_range_to_replace: range_to_replace,
20185 text: text.into(),
20186 });
20187
20188 if let Some(new_selected_ranges) = new_selected_ranges {
20189 this.change_selections(None, window, cx, |selections| {
20190 selections.select_ranges(new_selected_ranges)
20191 });
20192 this.backspace(&Default::default(), window, cx);
20193 }
20194
20195 this.handle_input(text, window, cx);
20196 });
20197
20198 if let Some(transaction) = self.ime_transaction {
20199 self.buffer.update(cx, |buffer, cx| {
20200 buffer.group_until_transaction(transaction, cx);
20201 });
20202 }
20203
20204 self.unmark_text(window, cx);
20205 }
20206
20207 fn replace_and_mark_text_in_range(
20208 &mut self,
20209 range_utf16: Option<Range<usize>>,
20210 text: &str,
20211 new_selected_range_utf16: Option<Range<usize>>,
20212 window: &mut Window,
20213 cx: &mut Context<Self>,
20214 ) {
20215 if !self.input_enabled {
20216 return;
20217 }
20218
20219 let transaction = self.transact(window, cx, |this, window, cx| {
20220 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20221 let snapshot = this.buffer.read(cx).read(cx);
20222 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20223 for marked_range in &mut marked_ranges {
20224 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20225 marked_range.start.0 += relative_range_utf16.start;
20226 marked_range.start =
20227 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20228 marked_range.end =
20229 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20230 }
20231 }
20232 Some(marked_ranges)
20233 } else if let Some(range_utf16) = range_utf16 {
20234 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20235 Some(this.selection_replacement_ranges(range_utf16, cx))
20236 } else {
20237 None
20238 };
20239
20240 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20241 let newest_selection_id = this.selections.newest_anchor().id;
20242 this.selections
20243 .all::<OffsetUtf16>(cx)
20244 .iter()
20245 .zip(ranges_to_replace.iter())
20246 .find_map(|(selection, range)| {
20247 if selection.id == newest_selection_id {
20248 Some(
20249 (range.start.0 as isize - selection.head().0 as isize)
20250 ..(range.end.0 as isize - selection.head().0 as isize),
20251 )
20252 } else {
20253 None
20254 }
20255 })
20256 });
20257
20258 cx.emit(EditorEvent::InputHandled {
20259 utf16_range_to_replace: range_to_replace,
20260 text: text.into(),
20261 });
20262
20263 if let Some(ranges) = ranges_to_replace {
20264 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20265 }
20266
20267 let marked_ranges = {
20268 let snapshot = this.buffer.read(cx).read(cx);
20269 this.selections
20270 .disjoint_anchors()
20271 .iter()
20272 .map(|selection| {
20273 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20274 })
20275 .collect::<Vec<_>>()
20276 };
20277
20278 if text.is_empty() {
20279 this.unmark_text(window, cx);
20280 } else {
20281 this.highlight_text::<InputComposition>(
20282 marked_ranges.clone(),
20283 HighlightStyle {
20284 underline: Some(UnderlineStyle {
20285 thickness: px(1.),
20286 color: None,
20287 wavy: false,
20288 }),
20289 ..Default::default()
20290 },
20291 cx,
20292 );
20293 }
20294
20295 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20296 let use_autoclose = this.use_autoclose;
20297 let use_auto_surround = this.use_auto_surround;
20298 this.set_use_autoclose(false);
20299 this.set_use_auto_surround(false);
20300 this.handle_input(text, window, cx);
20301 this.set_use_autoclose(use_autoclose);
20302 this.set_use_auto_surround(use_auto_surround);
20303
20304 if let Some(new_selected_range) = new_selected_range_utf16 {
20305 let snapshot = this.buffer.read(cx).read(cx);
20306 let new_selected_ranges = marked_ranges
20307 .into_iter()
20308 .map(|marked_range| {
20309 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20310 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20311 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20312 snapshot.clip_offset_utf16(new_start, Bias::Left)
20313 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20314 })
20315 .collect::<Vec<_>>();
20316
20317 drop(snapshot);
20318 this.change_selections(None, window, cx, |selections| {
20319 selections.select_ranges(new_selected_ranges)
20320 });
20321 }
20322 });
20323
20324 self.ime_transaction = self.ime_transaction.or(transaction);
20325 if let Some(transaction) = self.ime_transaction {
20326 self.buffer.update(cx, |buffer, cx| {
20327 buffer.group_until_transaction(transaction, cx);
20328 });
20329 }
20330
20331 if self.text_highlights::<InputComposition>(cx).is_none() {
20332 self.ime_transaction.take();
20333 }
20334 }
20335
20336 fn bounds_for_range(
20337 &mut self,
20338 range_utf16: Range<usize>,
20339 element_bounds: gpui::Bounds<Pixels>,
20340 window: &mut Window,
20341 cx: &mut Context<Self>,
20342 ) -> Option<gpui::Bounds<Pixels>> {
20343 let text_layout_details = self.text_layout_details(window);
20344 let gpui::Size {
20345 width: em_width,
20346 height: line_height,
20347 } = self.character_size(window);
20348
20349 let snapshot = self.snapshot(window, cx);
20350 let scroll_position = snapshot.scroll_position();
20351 let scroll_left = scroll_position.x * em_width;
20352
20353 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20354 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20355 + self.gutter_dimensions.width
20356 + self.gutter_dimensions.margin;
20357 let y = line_height * (start.row().as_f32() - scroll_position.y);
20358
20359 Some(Bounds {
20360 origin: element_bounds.origin + point(x, y),
20361 size: size(em_width, line_height),
20362 })
20363 }
20364
20365 fn character_index_for_point(
20366 &mut self,
20367 point: gpui::Point<Pixels>,
20368 _window: &mut Window,
20369 _cx: &mut Context<Self>,
20370 ) -> Option<usize> {
20371 let position_map = self.last_position_map.as_ref()?;
20372 if !position_map.text_hitbox.contains(&point) {
20373 return None;
20374 }
20375 let display_point = position_map.point_for_position(point).previous_valid;
20376 let anchor = position_map
20377 .snapshot
20378 .display_point_to_anchor(display_point, Bias::Left);
20379 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20380 Some(utf16_offset.0)
20381 }
20382}
20383
20384trait SelectionExt {
20385 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20386 fn spanned_rows(
20387 &self,
20388 include_end_if_at_line_start: bool,
20389 map: &DisplaySnapshot,
20390 ) -> Range<MultiBufferRow>;
20391}
20392
20393impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20394 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20395 let start = self
20396 .start
20397 .to_point(&map.buffer_snapshot)
20398 .to_display_point(map);
20399 let end = self
20400 .end
20401 .to_point(&map.buffer_snapshot)
20402 .to_display_point(map);
20403 if self.reversed {
20404 end..start
20405 } else {
20406 start..end
20407 }
20408 }
20409
20410 fn spanned_rows(
20411 &self,
20412 include_end_if_at_line_start: bool,
20413 map: &DisplaySnapshot,
20414 ) -> Range<MultiBufferRow> {
20415 let start = self.start.to_point(&map.buffer_snapshot);
20416 let mut end = self.end.to_point(&map.buffer_snapshot);
20417 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20418 end.row -= 1;
20419 }
20420
20421 let buffer_start = map.prev_line_boundary(start).0;
20422 let buffer_end = map.next_line_boundary(end).0;
20423 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20424 }
20425}
20426
20427impl<T: InvalidationRegion> InvalidationStack<T> {
20428 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20429 where
20430 S: Clone + ToOffset,
20431 {
20432 while let Some(region) = self.last() {
20433 let all_selections_inside_invalidation_ranges =
20434 if selections.len() == region.ranges().len() {
20435 selections
20436 .iter()
20437 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20438 .all(|(selection, invalidation_range)| {
20439 let head = selection.head().to_offset(buffer);
20440 invalidation_range.start <= head && invalidation_range.end >= head
20441 })
20442 } else {
20443 false
20444 };
20445
20446 if all_selections_inside_invalidation_ranges {
20447 break;
20448 } else {
20449 self.pop();
20450 }
20451 }
20452 }
20453}
20454
20455impl<T> Default for InvalidationStack<T> {
20456 fn default() -> Self {
20457 Self(Default::default())
20458 }
20459}
20460
20461impl<T> Deref for InvalidationStack<T> {
20462 type Target = Vec<T>;
20463
20464 fn deref(&self) -> &Self::Target {
20465 &self.0
20466 }
20467}
20468
20469impl<T> DerefMut for InvalidationStack<T> {
20470 fn deref_mut(&mut self) -> &mut Self::Target {
20471 &mut self.0
20472 }
20473}
20474
20475impl InvalidationRegion for SnippetState {
20476 fn ranges(&self) -> &[Range<Anchor>] {
20477 &self.ranges[self.active_index]
20478 }
20479}
20480
20481fn inline_completion_edit_text(
20482 current_snapshot: &BufferSnapshot,
20483 edits: &[(Range<Anchor>, String)],
20484 edit_preview: &EditPreview,
20485 include_deletions: bool,
20486 cx: &App,
20487) -> HighlightedText {
20488 let edits = edits
20489 .iter()
20490 .map(|(anchor, text)| {
20491 (
20492 anchor.start.text_anchor..anchor.end.text_anchor,
20493 text.clone(),
20494 )
20495 })
20496 .collect::<Vec<_>>();
20497
20498 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20499}
20500
20501pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20502 match severity {
20503 DiagnosticSeverity::ERROR => colors.error,
20504 DiagnosticSeverity::WARNING => colors.warning,
20505 DiagnosticSeverity::INFORMATION => colors.info,
20506 DiagnosticSeverity::HINT => colors.info,
20507 _ => colors.ignored,
20508 }
20509}
20510
20511pub fn styled_runs_for_code_label<'a>(
20512 label: &'a CodeLabel,
20513 syntax_theme: &'a theme::SyntaxTheme,
20514) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20515 let fade_out = HighlightStyle {
20516 fade_out: Some(0.35),
20517 ..Default::default()
20518 };
20519
20520 let mut prev_end = label.filter_range.end;
20521 label
20522 .runs
20523 .iter()
20524 .enumerate()
20525 .flat_map(move |(ix, (range, highlight_id))| {
20526 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20527 style
20528 } else {
20529 return Default::default();
20530 };
20531 let mut muted_style = style;
20532 muted_style.highlight(fade_out);
20533
20534 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20535 if range.start >= label.filter_range.end {
20536 if range.start > prev_end {
20537 runs.push((prev_end..range.start, fade_out));
20538 }
20539 runs.push((range.clone(), muted_style));
20540 } else if range.end <= label.filter_range.end {
20541 runs.push((range.clone(), style));
20542 } else {
20543 runs.push((range.start..label.filter_range.end, style));
20544 runs.push((label.filter_range.end..range.end, muted_style));
20545 }
20546 prev_end = cmp::max(prev_end, range.end);
20547
20548 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20549 runs.push((prev_end..label.text.len(), fade_out));
20550 }
20551
20552 runs
20553 })
20554}
20555
20556pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20557 let mut prev_index = 0;
20558 let mut prev_codepoint: Option<char> = None;
20559 text.char_indices()
20560 .chain([(text.len(), '\0')])
20561 .filter_map(move |(index, codepoint)| {
20562 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20563 let is_boundary = index == text.len()
20564 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20565 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20566 if is_boundary {
20567 let chunk = &text[prev_index..index];
20568 prev_index = index;
20569 Some(chunk)
20570 } else {
20571 None
20572 }
20573 })
20574}
20575
20576pub trait RangeToAnchorExt: Sized {
20577 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20578
20579 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20580 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20581 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20582 }
20583}
20584
20585impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20586 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20587 let start_offset = self.start.to_offset(snapshot);
20588 let end_offset = self.end.to_offset(snapshot);
20589 if start_offset == end_offset {
20590 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20591 } else {
20592 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20593 }
20594 }
20595}
20596
20597pub trait RowExt {
20598 fn as_f32(&self) -> f32;
20599
20600 fn next_row(&self) -> Self;
20601
20602 fn previous_row(&self) -> Self;
20603
20604 fn minus(&self, other: Self) -> u32;
20605}
20606
20607impl RowExt for DisplayRow {
20608 fn as_f32(&self) -> f32 {
20609 self.0 as f32
20610 }
20611
20612 fn next_row(&self) -> Self {
20613 Self(self.0 + 1)
20614 }
20615
20616 fn previous_row(&self) -> Self {
20617 Self(self.0.saturating_sub(1))
20618 }
20619
20620 fn minus(&self, other: Self) -> u32 {
20621 self.0 - other.0
20622 }
20623}
20624
20625impl RowExt for MultiBufferRow {
20626 fn as_f32(&self) -> f32 {
20627 self.0 as f32
20628 }
20629
20630 fn next_row(&self) -> Self {
20631 Self(self.0 + 1)
20632 }
20633
20634 fn previous_row(&self) -> Self {
20635 Self(self.0.saturating_sub(1))
20636 }
20637
20638 fn minus(&self, other: Self) -> u32 {
20639 self.0 - other.0
20640 }
20641}
20642
20643trait RowRangeExt {
20644 type Row;
20645
20646 fn len(&self) -> usize;
20647
20648 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20649}
20650
20651impl RowRangeExt for Range<MultiBufferRow> {
20652 type Row = MultiBufferRow;
20653
20654 fn len(&self) -> usize {
20655 (self.end.0 - self.start.0) as usize
20656 }
20657
20658 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20659 (self.start.0..self.end.0).map(MultiBufferRow)
20660 }
20661}
20662
20663impl RowRangeExt for Range<DisplayRow> {
20664 type Row = DisplayRow;
20665
20666 fn len(&self) -> usize {
20667 (self.end.0 - self.start.0) as usize
20668 }
20669
20670 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20671 (self.start.0..self.end.0).map(DisplayRow)
20672 }
20673}
20674
20675/// If select range has more than one line, we
20676/// just point the cursor to range.start.
20677fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20678 if range.start.row == range.end.row {
20679 range
20680 } else {
20681 range.start..range.start
20682 }
20683}
20684pub struct KillRing(ClipboardItem);
20685impl Global for KillRing {}
20686
20687const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20688
20689enum BreakpointPromptEditAction {
20690 Log,
20691 Condition,
20692 HitCondition,
20693}
20694
20695struct BreakpointPromptEditor {
20696 pub(crate) prompt: Entity<Editor>,
20697 editor: WeakEntity<Editor>,
20698 breakpoint_anchor: Anchor,
20699 breakpoint: Breakpoint,
20700 edit_action: BreakpointPromptEditAction,
20701 block_ids: HashSet<CustomBlockId>,
20702 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20703 _subscriptions: Vec<Subscription>,
20704}
20705
20706impl BreakpointPromptEditor {
20707 const MAX_LINES: u8 = 4;
20708
20709 fn new(
20710 editor: WeakEntity<Editor>,
20711 breakpoint_anchor: Anchor,
20712 breakpoint: Breakpoint,
20713 edit_action: BreakpointPromptEditAction,
20714 window: &mut Window,
20715 cx: &mut Context<Self>,
20716 ) -> Self {
20717 let base_text = match edit_action {
20718 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20719 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20720 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20721 }
20722 .map(|msg| msg.to_string())
20723 .unwrap_or_default();
20724
20725 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20726 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20727
20728 let prompt = cx.new(|cx| {
20729 let mut prompt = Editor::new(
20730 EditorMode::AutoHeight {
20731 max_lines: Self::MAX_LINES as usize,
20732 },
20733 buffer,
20734 None,
20735 window,
20736 cx,
20737 );
20738 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20739 prompt.set_show_cursor_when_unfocused(false, cx);
20740 prompt.set_placeholder_text(
20741 match edit_action {
20742 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20743 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20744 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20745 },
20746 cx,
20747 );
20748
20749 prompt
20750 });
20751
20752 Self {
20753 prompt,
20754 editor,
20755 breakpoint_anchor,
20756 breakpoint,
20757 edit_action,
20758 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20759 block_ids: Default::default(),
20760 _subscriptions: vec![],
20761 }
20762 }
20763
20764 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20765 self.block_ids.extend(block_ids)
20766 }
20767
20768 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20769 if let Some(editor) = self.editor.upgrade() {
20770 let message = self
20771 .prompt
20772 .read(cx)
20773 .buffer
20774 .read(cx)
20775 .as_singleton()
20776 .expect("A multi buffer in breakpoint prompt isn't possible")
20777 .read(cx)
20778 .as_rope()
20779 .to_string();
20780
20781 editor.update(cx, |editor, cx| {
20782 editor.edit_breakpoint_at_anchor(
20783 self.breakpoint_anchor,
20784 self.breakpoint.clone(),
20785 match self.edit_action {
20786 BreakpointPromptEditAction::Log => {
20787 BreakpointEditAction::EditLogMessage(message.into())
20788 }
20789 BreakpointPromptEditAction::Condition => {
20790 BreakpointEditAction::EditCondition(message.into())
20791 }
20792 BreakpointPromptEditAction::HitCondition => {
20793 BreakpointEditAction::EditHitCondition(message.into())
20794 }
20795 },
20796 cx,
20797 );
20798
20799 editor.remove_blocks(self.block_ids.clone(), None, cx);
20800 cx.focus_self(window);
20801 });
20802 }
20803 }
20804
20805 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20806 self.editor
20807 .update(cx, |editor, cx| {
20808 editor.remove_blocks(self.block_ids.clone(), None, cx);
20809 window.focus(&editor.focus_handle);
20810 })
20811 .log_err();
20812 }
20813
20814 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20815 let settings = ThemeSettings::get_global(cx);
20816 let text_style = TextStyle {
20817 color: if self.prompt.read(cx).read_only(cx) {
20818 cx.theme().colors().text_disabled
20819 } else {
20820 cx.theme().colors().text
20821 },
20822 font_family: settings.buffer_font.family.clone(),
20823 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20824 font_size: settings.buffer_font_size(cx).into(),
20825 font_weight: settings.buffer_font.weight,
20826 line_height: relative(settings.buffer_line_height.value()),
20827 ..Default::default()
20828 };
20829 EditorElement::new(
20830 &self.prompt,
20831 EditorStyle {
20832 background: cx.theme().colors().editor_background,
20833 local_player: cx.theme().players().local(),
20834 text: text_style,
20835 ..Default::default()
20836 },
20837 )
20838 }
20839}
20840
20841impl Render for BreakpointPromptEditor {
20842 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20843 let gutter_dimensions = *self.gutter_dimensions.lock();
20844 h_flex()
20845 .key_context("Editor")
20846 .bg(cx.theme().colors().editor_background)
20847 .border_y_1()
20848 .border_color(cx.theme().status().info_border)
20849 .size_full()
20850 .py(window.line_height() / 2.5)
20851 .on_action(cx.listener(Self::confirm))
20852 .on_action(cx.listener(Self::cancel))
20853 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20854 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20855 }
20856}
20857
20858impl Focusable for BreakpointPromptEditor {
20859 fn focus_handle(&self, cx: &App) -> FocusHandle {
20860 self.prompt.focus_handle(cx)
20861 }
20862}
20863
20864fn all_edits_insertions_or_deletions(
20865 edits: &Vec<(Range<Anchor>, String)>,
20866 snapshot: &MultiBufferSnapshot,
20867) -> bool {
20868 let mut all_insertions = true;
20869 let mut all_deletions = true;
20870
20871 for (range, new_text) in edits.iter() {
20872 let range_is_empty = range.to_offset(&snapshot).is_empty();
20873 let text_is_empty = new_text.is_empty();
20874
20875 if range_is_empty != text_is_empty {
20876 if range_is_empty {
20877 all_deletions = false;
20878 } else {
20879 all_insertions = false;
20880 }
20881 } else {
20882 return false;
20883 }
20884
20885 if !all_insertions && !all_deletions {
20886 return false;
20887 }
20888 }
20889 all_insertions || all_deletions
20890}
20891
20892struct MissingEditPredictionKeybindingTooltip;
20893
20894impl Render for MissingEditPredictionKeybindingTooltip {
20895 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20896 ui::tooltip_container(window, cx, |container, _, cx| {
20897 container
20898 .flex_shrink_0()
20899 .max_w_80()
20900 .min_h(rems_from_px(124.))
20901 .justify_between()
20902 .child(
20903 v_flex()
20904 .flex_1()
20905 .text_ui_sm(cx)
20906 .child(Label::new("Conflict with Accept Keybinding"))
20907 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20908 )
20909 .child(
20910 h_flex()
20911 .pb_1()
20912 .gap_1()
20913 .items_end()
20914 .w_full()
20915 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20916 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20917 }))
20918 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20919 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20920 })),
20921 )
20922 })
20923 }
20924}
20925
20926#[derive(Debug, Clone, Copy, PartialEq)]
20927pub struct LineHighlight {
20928 pub background: Background,
20929 pub border: Option<gpui::Hsla>,
20930 pub include_gutter: bool,
20931 pub type_id: Option<TypeId>,
20932}
20933
20934fn render_diff_hunk_controls(
20935 row: u32,
20936 status: &DiffHunkStatus,
20937 hunk_range: Range<Anchor>,
20938 is_created_file: bool,
20939 line_height: Pixels,
20940 editor: &Entity<Editor>,
20941 _window: &mut Window,
20942 cx: &mut App,
20943) -> AnyElement {
20944 h_flex()
20945 .h(line_height)
20946 .mr_1()
20947 .gap_1()
20948 .px_0p5()
20949 .pb_1()
20950 .border_x_1()
20951 .border_b_1()
20952 .border_color(cx.theme().colors().border_variant)
20953 .rounded_b_lg()
20954 .bg(cx.theme().colors().editor_background)
20955 .gap_1()
20956 .occlude()
20957 .shadow_md()
20958 .child(if status.has_secondary_hunk() {
20959 Button::new(("stage", row as u64), "Stage")
20960 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20961 .tooltip({
20962 let focus_handle = editor.focus_handle(cx);
20963 move |window, cx| {
20964 Tooltip::for_action_in(
20965 "Stage Hunk",
20966 &::git::ToggleStaged,
20967 &focus_handle,
20968 window,
20969 cx,
20970 )
20971 }
20972 })
20973 .on_click({
20974 let editor = editor.clone();
20975 move |_event, _window, cx| {
20976 editor.update(cx, |editor, cx| {
20977 editor.stage_or_unstage_diff_hunks(
20978 true,
20979 vec![hunk_range.start..hunk_range.start],
20980 cx,
20981 );
20982 });
20983 }
20984 })
20985 } else {
20986 Button::new(("unstage", row as u64), "Unstage")
20987 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20988 .tooltip({
20989 let focus_handle = editor.focus_handle(cx);
20990 move |window, cx| {
20991 Tooltip::for_action_in(
20992 "Unstage Hunk",
20993 &::git::ToggleStaged,
20994 &focus_handle,
20995 window,
20996 cx,
20997 )
20998 }
20999 })
21000 .on_click({
21001 let editor = editor.clone();
21002 move |_event, _window, cx| {
21003 editor.update(cx, |editor, cx| {
21004 editor.stage_or_unstage_diff_hunks(
21005 false,
21006 vec![hunk_range.start..hunk_range.start],
21007 cx,
21008 );
21009 });
21010 }
21011 })
21012 })
21013 .child(
21014 Button::new(("restore", row as u64), "Restore")
21015 .tooltip({
21016 let focus_handle = editor.focus_handle(cx);
21017 move |window, cx| {
21018 Tooltip::for_action_in(
21019 "Restore Hunk",
21020 &::git::Restore,
21021 &focus_handle,
21022 window,
21023 cx,
21024 )
21025 }
21026 })
21027 .on_click({
21028 let editor = editor.clone();
21029 move |_event, window, cx| {
21030 editor.update(cx, |editor, cx| {
21031 let snapshot = editor.snapshot(window, cx);
21032 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21033 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21034 });
21035 }
21036 })
21037 .disabled(is_created_file),
21038 )
21039 .when(
21040 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21041 |el| {
21042 el.child(
21043 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21044 .shape(IconButtonShape::Square)
21045 .icon_size(IconSize::Small)
21046 // .disabled(!has_multiple_hunks)
21047 .tooltip({
21048 let focus_handle = editor.focus_handle(cx);
21049 move |window, cx| {
21050 Tooltip::for_action_in(
21051 "Next Hunk",
21052 &GoToHunk,
21053 &focus_handle,
21054 window,
21055 cx,
21056 )
21057 }
21058 })
21059 .on_click({
21060 let editor = editor.clone();
21061 move |_event, window, cx| {
21062 editor.update(cx, |editor, cx| {
21063 let snapshot = editor.snapshot(window, cx);
21064 let position =
21065 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21066 editor.go_to_hunk_before_or_after_position(
21067 &snapshot,
21068 position,
21069 Direction::Next,
21070 window,
21071 cx,
21072 );
21073 editor.expand_selected_diff_hunks(cx);
21074 });
21075 }
21076 }),
21077 )
21078 .child(
21079 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21080 .shape(IconButtonShape::Square)
21081 .icon_size(IconSize::Small)
21082 // .disabled(!has_multiple_hunks)
21083 .tooltip({
21084 let focus_handle = editor.focus_handle(cx);
21085 move |window, cx| {
21086 Tooltip::for_action_in(
21087 "Previous Hunk",
21088 &GoToPreviousHunk,
21089 &focus_handle,
21090 window,
21091 cx,
21092 )
21093 }
21094 })
21095 .on_click({
21096 let editor = editor.clone();
21097 move |_event, window, cx| {
21098 editor.update(cx, |editor, cx| {
21099 let snapshot = editor.snapshot(window, cx);
21100 let point =
21101 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21102 editor.go_to_hunk_before_or_after_position(
21103 &snapshot,
21104 point,
21105 Direction::Prev,
21106 window,
21107 cx,
21108 );
21109 editor.expand_selected_diff_hunks(cx);
21110 });
21111 }
21112 }),
21113 )
21114 },
21115 )
21116 .into_any_element()
21117}