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;
26mod 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 editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{Context as _, Result, anyhow};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
62use editor_settings::GoToDefinitionFallback;
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
65 ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use feature_flags::{Debugger, FeatureFlagAppExt};
73use futures::{
74 FutureExt,
75 future::{self, Shared, join},
76};
77use fuzzy::StringMatchCandidate;
78
79use ::git::Restore;
80use code_context_menus::{
81 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
82 CompletionsMenu, ContextMenuOrigin,
83};
84use git::blame::{GitBlame, GlobalBlameRenderer};
85use gpui::{
86 Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
87 AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
88 ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
89 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
90 KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
91 SharedString, Size, Stateful, Styled, StyledText, Subscription, Task, TextStyle,
92 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
93 WeakFocusHandle, Window, div, impl_actions, point, prelude::*, pulsating_between, px, relative,
94 size,
95};
96use highlight_matching_bracket::refresh_matching_bracket_highlights;
97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
98pub use hover_popover::hover_markdown_style;
99use hover_popover::{HoverState, hide_hover};
100use indent_guides::ActiveIndentGuidesState;
101use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
102pub use inline_completion::Direction;
103use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
104pub use items::MAX_TAB_TITLE_LEN;
105use itertools::Itertools;
106use language::{
107 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
108 CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
109 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
110 TransactionId, TreeSitterOptions, WordsQuery,
111 language_settings::{
112 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
113 all_language_settings, language_settings,
114 },
115 point_from_lsp, text_diff_with_options,
116};
117use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
118use linked_editing_ranges::refresh_linked_ranges;
119use mouse_context_menu::MouseContextMenu;
120use persistence::DB;
121use project::{
122 ProjectPath,
123 debugger::breakpoint_store::{
124 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
125 },
126};
127
128pub use git::blame::BlameRenderer;
129pub use proposed_changes_editor::{
130 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
131};
132use smallvec::smallvec;
133use std::{cell::OnceCell, iter::Peekable};
134use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
135
136pub use lsp::CompletionContext;
137use lsp::{
138 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
139 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
140};
141
142use language::BufferSnapshot;
143pub use lsp_ext::lsp_tasks;
144use movement::TextLayoutDetails;
145pub use multi_buffer::{
146 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
147 ToOffset, ToPoint,
148};
149use multi_buffer::{
150 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
151 MultiOrSingleBufferOffsetRange, PathKey, ToOffsetUtf16,
152};
153use parking_lot::Mutex;
154use project::{
155 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
156 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
157 TaskSourceKind,
158 debugger::breakpoint_store::Breakpoint,
159 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
160 project_settings::{GitGutterSetting, ProjectSettings},
161};
162use rand::prelude::*;
163use rpc::{ErrorExt, proto::*};
164use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
165use selections_collection::{
166 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
167};
168use serde::{Deserialize, Serialize};
169use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
170use smallvec::SmallVec;
171use snippet::Snippet;
172use std::sync::Arc;
173use std::{
174 any::TypeId,
175 borrow::Cow,
176 cell::RefCell,
177 cmp::{self, Ordering, Reverse},
178 mem,
179 num::NonZeroU32,
180 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
181 path::{Path, PathBuf},
182 rc::Rc,
183 time::{Duration, Instant},
184};
185pub use sum_tree::Bias;
186use sum_tree::TreeMap;
187use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
188use theme::{
189 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
190 observe_buffer_font_size_adjustment,
191};
192use ui::{
193 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
194 IconSize, Key, Tooltip, h_flex, prelude::*,
195};
196use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
197use workspace::{
198 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
199 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
200 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
201 item::{ItemHandle, PreviewTabsSettings},
202 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
203 searchable::SearchEvent,
204};
205
206use crate::hover_links::{find_url, find_url_from_range};
207use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
208
209pub const FILE_HEADER_HEIGHT: u32 = 2;
210pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
211pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
212const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
213const MAX_LINE_LEN: usize = 1024;
214const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
215const MAX_SELECTION_HISTORY_LEN: usize = 1024;
216pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
217#[doc(hidden)]
218pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
219
220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
223
224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
227
228pub type RenderDiffHunkControlsFn = Arc<
229 dyn Fn(
230 u32,
231 &DiffHunkStatus,
232 Range<Anchor>,
233 bool,
234 Pixels,
235 &Entity<Editor>,
236 &mut Window,
237 &mut App,
238 ) -> AnyElement,
239>;
240
241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
242 alt: true,
243 shift: true,
244 control: false,
245 platform: false,
246 function: false,
247};
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
250pub enum InlayId {
251 InlineCompletion(usize),
252 Hint(usize),
253}
254
255impl InlayId {
256 fn id(&self) -> usize {
257 match self {
258 Self::InlineCompletion(id) => *id,
259 Self::Hint(id) => *id,
260 }
261 }
262}
263
264pub enum DebugCurrentRowHighlight {}
265enum DocumentHighlightRead {}
266enum DocumentHighlightWrite {}
267enum InputComposition {}
268enum SelectedTextHighlight {}
269
270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
271pub enum Navigated {
272 Yes,
273 No,
274}
275
276impl Navigated {
277 pub fn from_bool(yes: bool) -> Navigated {
278 if yes { Navigated::Yes } else { Navigated::No }
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283enum DisplayDiffHunk {
284 Folded {
285 display_row: DisplayRow,
286 },
287 Unfolded {
288 is_created_file: bool,
289 diff_base_byte_range: Range<usize>,
290 display_row_range: Range<DisplayRow>,
291 multi_buffer_range: Range<Anchor>,
292 status: DiffHunkStatus,
293 },
294}
295
296pub enum HideMouseCursorOrigin {
297 TypingAction,
298 MovementAction,
299}
300
301pub fn init_settings(cx: &mut App) {
302 EditorSettings::register(cx);
303}
304
305pub fn init(cx: &mut App) {
306 init_settings(cx);
307
308 cx.set_global(GlobalBlameRenderer(Arc::new(())));
309
310 workspace::register_project_item::<Editor>(cx);
311 workspace::FollowableViewRegistry::register::<Editor>(cx);
312 workspace::register_serializable_item::<Editor>(cx);
313
314 cx.observe_new(
315 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
316 workspace.register_action(Editor::new_file);
317 workspace.register_action(Editor::new_file_vertical);
318 workspace.register_action(Editor::new_file_horizontal);
319 workspace.register_action(Editor::cancel_language_server_work);
320 },
321 )
322 .detach();
323
324 cx.on_action(move |_: &workspace::NewFile, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(
328 Default::default(),
329 app_state,
330 cx,
331 |workspace, window, cx| {
332 Editor::new_file(workspace, &Default::default(), window, cx)
333 },
334 )
335 .detach();
336 }
337 });
338 cx.on_action(move |_: &workspace::NewWindow, cx| {
339 let app_state = workspace::AppState::global(cx);
340 if let Some(app_state) = app_state.upgrade() {
341 workspace::open_new(
342 Default::default(),
343 app_state,
344 cx,
345 |workspace, window, cx| {
346 cx.activate(true);
347 Editor::new_file(workspace, &Default::default(), window, cx)
348 },
349 )
350 .detach();
351 }
352 });
353}
354
355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
356 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
357}
358
359pub struct SearchWithinRange;
360
361trait InvalidationRegion {
362 fn ranges(&self) -> &[Range<Anchor>];
363}
364
365#[derive(Clone, Debug, PartialEq)]
366pub enum SelectPhase {
367 Begin {
368 position: DisplayPoint,
369 add: bool,
370 click_count: usize,
371 },
372 BeginColumnar {
373 position: DisplayPoint,
374 reset: bool,
375 goal_column: u32,
376 },
377 Extend {
378 position: DisplayPoint,
379 click_count: usize,
380 },
381 Update {
382 position: DisplayPoint,
383 goal_column: u32,
384 scroll_delta: gpui::Point<f32>,
385 },
386 End,
387}
388
389#[derive(Clone, Debug)]
390pub enum SelectMode {
391 Character,
392 Word(Range<Anchor>),
393 Line(Range<Anchor>),
394 All,
395}
396
397#[derive(Copy, Clone, PartialEq, Eq, Debug)]
398pub enum EditorMode {
399 SingleLine {
400 auto_width: bool,
401 },
402 AutoHeight {
403 max_lines: usize,
404 },
405 Full {
406 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
407 scale_ui_elements_with_buffer_font_size: bool,
408 /// When set to `true`, the editor will render a background for the active line.
409 show_active_line_background: bool,
410 },
411}
412
413impl EditorMode {
414 pub fn full() -> Self {
415 Self::Full {
416 scale_ui_elements_with_buffer_font_size: true,
417 show_active_line_background: true,
418 }
419 }
420
421 pub fn is_full(&self) -> bool {
422 matches!(self, Self::Full { .. })
423 }
424}
425
426#[derive(Copy, Clone, Debug)]
427pub enum SoftWrap {
428 /// Prefer not to wrap at all.
429 ///
430 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
431 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
432 GitDiff,
433 /// Prefer a single line generally, unless an overly long line is encountered.
434 None,
435 /// Soft wrap lines that exceed the editor width.
436 EditorWidth,
437 /// Soft wrap lines at the preferred line length.
438 Column(u32),
439 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
440 Bounded(u32),
441}
442
443#[derive(Clone)]
444pub struct EditorStyle {
445 pub background: Hsla,
446 pub local_player: PlayerColor,
447 pub text: TextStyle,
448 pub scrollbar_width: Pixels,
449 pub syntax: Arc<SyntaxTheme>,
450 pub status: StatusColors,
451 pub inlay_hints_style: HighlightStyle,
452 pub inline_completion_styles: InlineCompletionStyles,
453 pub unnecessary_code_fade: f32,
454}
455
456impl Default for EditorStyle {
457 fn default() -> Self {
458 Self {
459 background: Hsla::default(),
460 local_player: PlayerColor::default(),
461 text: TextStyle::default(),
462 scrollbar_width: Pixels::default(),
463 syntax: Default::default(),
464 // HACK: Status colors don't have a real default.
465 // We should look into removing the status colors from the editor
466 // style and retrieve them directly from the theme.
467 status: StatusColors::dark(),
468 inlay_hints_style: HighlightStyle::default(),
469 inline_completion_styles: InlineCompletionStyles {
470 insertion: HighlightStyle::default(),
471 whitespace: HighlightStyle::default(),
472 },
473 unnecessary_code_fade: Default::default(),
474 }
475 }
476}
477
478pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
479 let show_background = language_settings::language_settings(None, None, cx)
480 .inlay_hints
481 .show_background;
482
483 HighlightStyle {
484 color: Some(cx.theme().status().hint),
485 background_color: show_background.then(|| cx.theme().status().hint_background),
486 ..HighlightStyle::default()
487 }
488}
489
490pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
491 InlineCompletionStyles {
492 insertion: HighlightStyle {
493 color: Some(cx.theme().status().predictive),
494 ..HighlightStyle::default()
495 },
496 whitespace: HighlightStyle {
497 background_color: Some(cx.theme().status().created_background),
498 ..HighlightStyle::default()
499 },
500 }
501}
502
503type CompletionId = usize;
504
505pub(crate) enum EditDisplayMode {
506 TabAccept,
507 DiffPopover,
508 Inline,
509}
510
511enum InlineCompletion {
512 Edit {
513 edits: Vec<(Range<Anchor>, String)>,
514 edit_preview: Option<EditPreview>,
515 display_mode: EditDisplayMode,
516 snapshot: BufferSnapshot,
517 },
518 Move {
519 target: Anchor,
520 snapshot: BufferSnapshot,
521 },
522}
523
524struct InlineCompletionState {
525 inlay_ids: Vec<InlayId>,
526 completion: InlineCompletion,
527 completion_id: Option<SharedString>,
528 invalidation_range: Range<Anchor>,
529}
530
531enum EditPredictionSettings {
532 Disabled,
533 Enabled {
534 show_in_menu: bool,
535 preview_requires_modifier: bool,
536 },
537}
538
539enum InlineCompletionHighlight {}
540
541#[derive(Debug, Clone)]
542struct InlineDiagnostic {
543 message: SharedString,
544 group_id: usize,
545 is_primary: bool,
546 start: Point,
547 severity: DiagnosticSeverity,
548}
549
550pub enum MenuInlineCompletionsPolicy {
551 Never,
552 ByProvider,
553}
554
555pub enum EditPredictionPreview {
556 /// Modifier is not pressed
557 Inactive { released_too_fast: bool },
558 /// Modifier pressed
559 Active {
560 since: Instant,
561 previous_scroll_position: Option<ScrollAnchor>,
562 },
563}
564
565impl EditPredictionPreview {
566 pub fn released_too_fast(&self) -> bool {
567 match self {
568 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
569 EditPredictionPreview::Active { .. } => false,
570 }
571 }
572
573 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
574 if let EditPredictionPreview::Active {
575 previous_scroll_position,
576 ..
577 } = self
578 {
579 *previous_scroll_position = scroll_position;
580 }
581 }
582}
583
584pub struct ContextMenuOptions {
585 pub min_entries_visible: usize,
586 pub max_entries_visible: usize,
587 pub placement: Option<ContextMenuPlacement>,
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum ContextMenuPlacement {
592 Above,
593 Below,
594}
595
596#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
597struct EditorActionId(usize);
598
599impl EditorActionId {
600 pub fn post_inc(&mut self) -> Self {
601 let answer = self.0;
602
603 *self = Self(answer + 1);
604
605 Self(answer)
606 }
607}
608
609// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
610// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
611
612type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
613type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
614
615#[derive(Default)]
616struct ScrollbarMarkerState {
617 scrollbar_size: Size<Pixels>,
618 dirty: bool,
619 markers: Arc<[PaintQuad]>,
620 pending_refresh: Option<Task<Result<()>>>,
621}
622
623impl ScrollbarMarkerState {
624 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
625 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
626 }
627}
628
629#[derive(Clone, Debug)]
630struct RunnableTasks {
631 templates: Vec<(TaskSourceKind, TaskTemplate)>,
632 offset: multi_buffer::Anchor,
633 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
634 column: u32,
635 // Values of all named captures, including those starting with '_'
636 extra_variables: HashMap<String, String>,
637 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
638 context_range: Range<BufferOffset>,
639}
640
641impl RunnableTasks {
642 fn resolve<'a>(
643 &'a self,
644 cx: &'a task::TaskContext,
645 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
646 self.templates.iter().filter_map(|(kind, template)| {
647 template
648 .resolve_task(&kind.to_id_base(), cx)
649 .map(|task| (kind.clone(), task))
650 })
651 }
652}
653
654#[derive(Clone)]
655struct ResolvedTasks {
656 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
657 position: Anchor,
658}
659
660#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
661struct BufferOffset(usize);
662
663// Addons allow storing per-editor state in other crates (e.g. Vim)
664pub trait Addon: 'static {
665 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
666
667 fn render_buffer_header_controls(
668 &self,
669 _: &ExcerptInfo,
670 _: &Window,
671 _: &App,
672 ) -> Option<AnyElement> {
673 None
674 }
675
676 fn to_any(&self) -> &dyn std::any::Any;
677}
678
679/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
680///
681/// See the [module level documentation](self) for more information.
682pub struct Editor {
683 focus_handle: FocusHandle,
684 last_focused_descendant: Option<WeakFocusHandle>,
685 /// The text buffer being edited
686 buffer: Entity<MultiBuffer>,
687 /// Map of how text in the buffer should be displayed.
688 /// Handles soft wraps, folds, fake inlay text insertions, etc.
689 pub display_map: Entity<DisplayMap>,
690 pub selections: SelectionsCollection,
691 pub scroll_manager: ScrollManager,
692 /// When inline assist editors are linked, they all render cursors because
693 /// typing enters text into each of them, even the ones that aren't focused.
694 pub(crate) show_cursor_when_unfocused: bool,
695 columnar_selection_tail: Option<Anchor>,
696 add_selections_state: Option<AddSelectionsState>,
697 select_next_state: Option<SelectNextState>,
698 select_prev_state: Option<SelectNextState>,
699 selection_history: SelectionHistory,
700 autoclose_regions: Vec<AutocloseRegion>,
701 snippet_stack: InvalidationStack<SnippetState>,
702 select_syntax_node_history: SelectSyntaxNodeHistory,
703 ime_transaction: Option<TransactionId>,
704 active_diagnostics: Option<ActiveDiagnosticGroup>,
705 show_inline_diagnostics: bool,
706 inline_diagnostics_update: Task<()>,
707 inline_diagnostics_enabled: bool,
708 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
709 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
710 hard_wrap: Option<usize>,
711
712 // TODO: make this a access method
713 pub project: Option<Entity<Project>>,
714 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
715 completion_provider: Option<Box<dyn CompletionProvider>>,
716 collaboration_hub: Option<Box<dyn CollaborationHub>>,
717 blink_manager: Entity<BlinkManager>,
718 show_cursor_names: bool,
719 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
720 pub show_local_selections: bool,
721 mode: EditorMode,
722 show_breadcrumbs: bool,
723 show_gutter: bool,
724 show_scrollbars: bool,
725 show_line_numbers: Option<bool>,
726 use_relative_line_numbers: Option<bool>,
727 show_git_diff_gutter: Option<bool>,
728 show_code_actions: Option<bool>,
729 show_runnables: Option<bool>,
730 show_breakpoints: Option<bool>,
731 show_wrap_guides: Option<bool>,
732 show_indent_guides: Option<bool>,
733 placeholder_text: Option<Arc<str>>,
734 highlight_order: usize,
735 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
736 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
737 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
738 scrollbar_marker_state: ScrollbarMarkerState,
739 active_indent_guides_state: ActiveIndentGuidesState,
740 nav_history: Option<ItemNavHistory>,
741 context_menu: RefCell<Option<CodeContextMenu>>,
742 context_menu_options: Option<ContextMenuOptions>,
743 mouse_context_menu: Option<MouseContextMenu>,
744 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
745 signature_help_state: SignatureHelpState,
746 auto_signature_help: Option<bool>,
747 find_all_references_task_sources: Vec<Anchor>,
748 next_completion_id: CompletionId,
749 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
750 code_actions_task: Option<Task<Result<()>>>,
751 selection_highlight_task: Option<Task<()>>,
752 document_highlights_task: Option<Task<()>>,
753 linked_editing_range_task: Option<Task<Option<()>>>,
754 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
755 pending_rename: Option<RenameState>,
756 searchable: bool,
757 cursor_shape: CursorShape,
758 current_line_highlight: Option<CurrentLineHighlight>,
759 collapse_matches: bool,
760 autoindent_mode: Option<AutoindentMode>,
761 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
762 input_enabled: bool,
763 use_modal_editing: bool,
764 read_only: bool,
765 leader_peer_id: Option<PeerId>,
766 remote_id: Option<ViewId>,
767 hover_state: HoverState,
768 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
769 gutter_hovered: bool,
770 hovered_link_state: Option<HoveredLinkState>,
771 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
772 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
773 active_inline_completion: Option<InlineCompletionState>,
774 /// Used to prevent flickering as the user types while the menu is open
775 stale_inline_completion_in_menu: Option<InlineCompletionState>,
776 edit_prediction_settings: EditPredictionSettings,
777 inline_completions_hidden_for_vim_mode: bool,
778 show_inline_completions_override: Option<bool>,
779 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
780 edit_prediction_preview: EditPredictionPreview,
781 edit_prediction_indent_conflict: bool,
782 edit_prediction_requires_modifier_in_indent_conflict: bool,
783 inlay_hint_cache: InlayHintCache,
784 next_inlay_id: usize,
785 _subscriptions: Vec<Subscription>,
786 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
787 gutter_dimensions: GutterDimensions,
788 style: Option<EditorStyle>,
789 text_style_refinement: Option<TextStyleRefinement>,
790 next_editor_action_id: EditorActionId,
791 editor_actions:
792 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
793 use_autoclose: bool,
794 use_auto_surround: bool,
795 auto_replace_emoji_shortcode: bool,
796 jsx_tag_auto_close_enabled_in_any_buffer: bool,
797 show_git_blame_gutter: bool,
798 show_git_blame_inline: bool,
799 show_git_blame_inline_delay_task: Option<Task<()>>,
800 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
801 git_blame_inline_enabled: bool,
802 render_diff_hunk_controls: RenderDiffHunkControlsFn,
803 serialize_dirty_buffers: bool,
804 show_selection_menu: Option<bool>,
805 blame: Option<Entity<GitBlame>>,
806 blame_subscription: Option<Subscription>,
807 custom_context_menu: Option<
808 Box<
809 dyn 'static
810 + Fn(
811 &mut Self,
812 DisplayPoint,
813 &mut Window,
814 &mut Context<Self>,
815 ) -> Option<Entity<ui::ContextMenu>>,
816 >,
817 >,
818 last_bounds: Option<Bounds<Pixels>>,
819 last_position_map: Option<Rc<PositionMap>>,
820 expect_bounds_change: Option<Bounds<Pixels>>,
821 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
822 tasks_update_task: Option<Task<()>>,
823 breakpoint_store: Option<Entity<BreakpointStore>>,
824 /// Allow's a user to create a breakpoint by selecting this indicator
825 /// It should be None while a user is not hovering over the gutter
826 /// Otherwise it represents the point that the breakpoint will be shown
827 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
828 in_project_search: bool,
829 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
830 breadcrumb_header: Option<String>,
831 focused_block: Option<FocusedBlock>,
832 next_scroll_position: NextScrollCursorCenterTopBottom,
833 addons: HashMap<TypeId, Box<dyn Addon>>,
834 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
835 load_diff_task: Option<Shared<Task<()>>>,
836 selection_mark_mode: bool,
837 toggle_fold_multiple_buffers: Task<()>,
838 _scroll_cursor_center_top_bottom_task: Task<()>,
839 serialize_selections: Task<()>,
840 serialize_folds: Task<()>,
841 mouse_cursor_hidden: bool,
842 hide_mouse_mode: HideMouseMode,
843}
844
845#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
846enum NextScrollCursorCenterTopBottom {
847 #[default]
848 Center,
849 Top,
850 Bottom,
851}
852
853impl NextScrollCursorCenterTopBottom {
854 fn next(&self) -> Self {
855 match self {
856 Self::Center => Self::Top,
857 Self::Top => Self::Bottom,
858 Self::Bottom => Self::Center,
859 }
860 }
861}
862
863#[derive(Clone)]
864pub struct EditorSnapshot {
865 pub mode: EditorMode,
866 show_gutter: bool,
867 show_line_numbers: Option<bool>,
868 show_git_diff_gutter: Option<bool>,
869 show_code_actions: Option<bool>,
870 show_runnables: Option<bool>,
871 show_breakpoints: Option<bool>,
872 git_blame_gutter_max_author_length: Option<usize>,
873 pub display_snapshot: DisplaySnapshot,
874 pub placeholder_text: Option<Arc<str>>,
875 is_focused: bool,
876 scroll_anchor: ScrollAnchor,
877 ongoing_scroll: OngoingScroll,
878 current_line_highlight: CurrentLineHighlight,
879 gutter_hovered: bool,
880}
881
882#[derive(Default, Debug, Clone, Copy)]
883pub struct GutterDimensions {
884 pub left_padding: Pixels,
885 pub right_padding: Pixels,
886 pub width: Pixels,
887 pub margin: Pixels,
888 pub git_blame_entries_width: Option<Pixels>,
889}
890
891impl GutterDimensions {
892 /// The full width of the space taken up by the gutter.
893 pub fn full_width(&self) -> Pixels {
894 self.margin + self.width
895 }
896
897 /// The width of the space reserved for the fold indicators,
898 /// use alongside 'justify_end' and `gutter_width` to
899 /// right align content with the line numbers
900 pub fn fold_area_width(&self) -> Pixels {
901 self.margin + self.right_padding
902 }
903}
904
905#[derive(Debug)]
906pub struct RemoteSelection {
907 pub replica_id: ReplicaId,
908 pub selection: Selection<Anchor>,
909 pub cursor_shape: CursorShape,
910 pub peer_id: PeerId,
911 pub line_mode: bool,
912 pub participant_index: Option<ParticipantIndex>,
913 pub user_name: Option<SharedString>,
914}
915
916#[derive(Clone, Debug)]
917struct SelectionHistoryEntry {
918 selections: Arc<[Selection<Anchor>]>,
919 select_next_state: Option<SelectNextState>,
920 select_prev_state: Option<SelectNextState>,
921 add_selections_state: Option<AddSelectionsState>,
922}
923
924enum SelectionHistoryMode {
925 Normal,
926 Undoing,
927 Redoing,
928}
929
930#[derive(Clone, PartialEq, Eq, Hash)]
931struct HoveredCursor {
932 replica_id: u16,
933 selection_id: usize,
934}
935
936impl Default for SelectionHistoryMode {
937 fn default() -> Self {
938 Self::Normal
939 }
940}
941
942#[derive(Default)]
943struct SelectionHistory {
944 #[allow(clippy::type_complexity)]
945 selections_by_transaction:
946 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
947 mode: SelectionHistoryMode,
948 undo_stack: VecDeque<SelectionHistoryEntry>,
949 redo_stack: VecDeque<SelectionHistoryEntry>,
950}
951
952impl SelectionHistory {
953 fn insert_transaction(
954 &mut self,
955 transaction_id: TransactionId,
956 selections: Arc<[Selection<Anchor>]>,
957 ) {
958 self.selections_by_transaction
959 .insert(transaction_id, (selections, None));
960 }
961
962 #[allow(clippy::type_complexity)]
963 fn transaction(
964 &self,
965 transaction_id: TransactionId,
966 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
967 self.selections_by_transaction.get(&transaction_id)
968 }
969
970 #[allow(clippy::type_complexity)]
971 fn transaction_mut(
972 &mut self,
973 transaction_id: TransactionId,
974 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
975 self.selections_by_transaction.get_mut(&transaction_id)
976 }
977
978 fn push(&mut self, entry: SelectionHistoryEntry) {
979 if !entry.selections.is_empty() {
980 match self.mode {
981 SelectionHistoryMode::Normal => {
982 self.push_undo(entry);
983 self.redo_stack.clear();
984 }
985 SelectionHistoryMode::Undoing => self.push_redo(entry),
986 SelectionHistoryMode::Redoing => self.push_undo(entry),
987 }
988 }
989 }
990
991 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
992 if self
993 .undo_stack
994 .back()
995 .map_or(true, |e| e.selections != entry.selections)
996 {
997 self.undo_stack.push_back(entry);
998 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
999 self.undo_stack.pop_front();
1000 }
1001 }
1002 }
1003
1004 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1005 if self
1006 .redo_stack
1007 .back()
1008 .map_or(true, |e| e.selections != entry.selections)
1009 {
1010 self.redo_stack.push_back(entry);
1011 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1012 self.redo_stack.pop_front();
1013 }
1014 }
1015 }
1016}
1017
1018struct RowHighlight {
1019 index: usize,
1020 range: Range<Anchor>,
1021 color: Hsla,
1022 should_autoscroll: bool,
1023}
1024
1025#[derive(Clone, Debug)]
1026struct AddSelectionsState {
1027 above: bool,
1028 stack: Vec<usize>,
1029}
1030
1031#[derive(Clone)]
1032struct SelectNextState {
1033 query: AhoCorasick,
1034 wordwise: bool,
1035 done: bool,
1036}
1037
1038impl std::fmt::Debug for SelectNextState {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 f.debug_struct(std::any::type_name::<Self>())
1041 .field("wordwise", &self.wordwise)
1042 .field("done", &self.done)
1043 .finish()
1044 }
1045}
1046
1047#[derive(Debug)]
1048struct AutocloseRegion {
1049 selection_id: usize,
1050 range: Range<Anchor>,
1051 pair: BracketPair,
1052}
1053
1054#[derive(Debug)]
1055struct SnippetState {
1056 ranges: Vec<Vec<Range<Anchor>>>,
1057 active_index: usize,
1058 choices: Vec<Option<Vec<String>>>,
1059}
1060
1061#[doc(hidden)]
1062pub struct RenameState {
1063 pub range: Range<Anchor>,
1064 pub old_name: Arc<str>,
1065 pub editor: Entity<Editor>,
1066 block_id: CustomBlockId,
1067}
1068
1069struct InvalidationStack<T>(Vec<T>);
1070
1071struct RegisteredInlineCompletionProvider {
1072 provider: Arc<dyn InlineCompletionProviderHandle>,
1073 _subscription: Subscription,
1074}
1075
1076#[derive(Debug, PartialEq, Eq)]
1077struct ActiveDiagnosticGroup {
1078 primary_range: Range<Anchor>,
1079 primary_message: String,
1080 group_id: usize,
1081 blocks: HashMap<CustomBlockId, Diagnostic>,
1082 is_valid: bool,
1083}
1084
1085#[derive(Serialize, Deserialize, Clone, Debug)]
1086pub struct ClipboardSelection {
1087 /// The number of bytes in this selection.
1088 pub len: usize,
1089 /// Whether this was a full-line selection.
1090 pub is_entire_line: bool,
1091 /// The indentation of the first line when this content was originally copied.
1092 pub first_line_indent: u32,
1093}
1094
1095// selections, scroll behavior, was newest selection reversed
1096type SelectSyntaxNodeHistoryState = (
1097 Box<[Selection<usize>]>,
1098 SelectSyntaxNodeScrollBehavior,
1099 bool,
1100);
1101
1102#[derive(Default)]
1103struct SelectSyntaxNodeHistory {
1104 stack: Vec<SelectSyntaxNodeHistoryState>,
1105 // disable temporarily to allow changing selections without losing the stack
1106 pub disable_clearing: bool,
1107}
1108
1109impl SelectSyntaxNodeHistory {
1110 pub fn try_clear(&mut self) {
1111 if !self.disable_clearing {
1112 self.stack.clear();
1113 }
1114 }
1115
1116 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1117 self.stack.push(selection);
1118 }
1119
1120 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1121 self.stack.pop()
1122 }
1123}
1124
1125enum SelectSyntaxNodeScrollBehavior {
1126 CursorTop,
1127 FitSelection,
1128 CursorBottom,
1129}
1130
1131#[derive(Debug)]
1132pub(crate) struct NavigationData {
1133 cursor_anchor: Anchor,
1134 cursor_position: Point,
1135 scroll_anchor: ScrollAnchor,
1136 scroll_top_row: u32,
1137}
1138
1139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1140pub enum GotoDefinitionKind {
1141 Symbol,
1142 Declaration,
1143 Type,
1144 Implementation,
1145}
1146
1147#[derive(Debug, Clone)]
1148enum InlayHintRefreshReason {
1149 ModifiersChanged(bool),
1150 Toggle(bool),
1151 SettingsChange(InlayHintSettings),
1152 NewLinesShown,
1153 BufferEdited(HashSet<Arc<Language>>),
1154 RefreshRequested,
1155 ExcerptsRemoved(Vec<ExcerptId>),
1156}
1157
1158impl InlayHintRefreshReason {
1159 fn description(&self) -> &'static str {
1160 match self {
1161 Self::ModifiersChanged(_) => "modifiers changed",
1162 Self::Toggle(_) => "toggle",
1163 Self::SettingsChange(_) => "settings change",
1164 Self::NewLinesShown => "new lines shown",
1165 Self::BufferEdited(_) => "buffer edited",
1166 Self::RefreshRequested => "refresh requested",
1167 Self::ExcerptsRemoved(_) => "excerpts removed",
1168 }
1169 }
1170}
1171
1172pub enum FormatTarget {
1173 Buffers,
1174 Ranges(Vec<Range<MultiBufferPoint>>),
1175}
1176
1177pub(crate) struct FocusedBlock {
1178 id: BlockId,
1179 focus_handle: WeakFocusHandle,
1180}
1181
1182#[derive(Clone)]
1183enum JumpData {
1184 MultiBufferRow {
1185 row: MultiBufferRow,
1186 line_offset_from_top: u32,
1187 },
1188 MultiBufferPoint {
1189 excerpt_id: ExcerptId,
1190 position: Point,
1191 anchor: text::Anchor,
1192 line_offset_from_top: u32,
1193 },
1194}
1195
1196pub enum MultibufferSelectionMode {
1197 First,
1198 All,
1199}
1200
1201#[derive(Clone, Copy, Debug, Default)]
1202pub struct RewrapOptions {
1203 pub override_language_settings: bool,
1204 pub preserve_existing_whitespace: bool,
1205}
1206
1207impl Editor {
1208 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1209 let buffer = cx.new(|cx| Buffer::local("", cx));
1210 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1211 Self::new(
1212 EditorMode::SingleLine { auto_width: false },
1213 buffer,
1214 None,
1215 window,
1216 cx,
1217 )
1218 }
1219
1220 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1221 let buffer = cx.new(|cx| Buffer::local("", cx));
1222 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1223 Self::new(EditorMode::full(), buffer, None, window, cx)
1224 }
1225
1226 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1227 let buffer = cx.new(|cx| Buffer::local("", cx));
1228 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1229 Self::new(
1230 EditorMode::SingleLine { auto_width: true },
1231 buffer,
1232 None,
1233 window,
1234 cx,
1235 )
1236 }
1237
1238 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1239 let buffer = cx.new(|cx| Buffer::local("", cx));
1240 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1241 Self::new(
1242 EditorMode::AutoHeight { max_lines },
1243 buffer,
1244 None,
1245 window,
1246 cx,
1247 )
1248 }
1249
1250 pub fn for_buffer(
1251 buffer: Entity<Buffer>,
1252 project: Option<Entity<Project>>,
1253 window: &mut Window,
1254 cx: &mut Context<Self>,
1255 ) -> Self {
1256 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1257 Self::new(EditorMode::full(), buffer, project, window, cx)
1258 }
1259
1260 pub fn for_multibuffer(
1261 buffer: Entity<MultiBuffer>,
1262 project: Option<Entity<Project>>,
1263 window: &mut Window,
1264 cx: &mut Context<Self>,
1265 ) -> Self {
1266 Self::new(EditorMode::full(), buffer, project, window, cx)
1267 }
1268
1269 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1270 let mut clone = Self::new(
1271 self.mode,
1272 self.buffer.clone(),
1273 self.project.clone(),
1274 window,
1275 cx,
1276 );
1277 self.display_map.update(cx, |display_map, cx| {
1278 let snapshot = display_map.snapshot(cx);
1279 clone.display_map.update(cx, |display_map, cx| {
1280 display_map.set_state(&snapshot, cx);
1281 });
1282 });
1283 clone.folds_did_change(cx);
1284 clone.selections.clone_state(&self.selections);
1285 clone.scroll_manager.clone_state(&self.scroll_manager);
1286 clone.searchable = self.searchable;
1287 clone.read_only = self.read_only;
1288 clone
1289 }
1290
1291 pub fn new(
1292 mode: EditorMode,
1293 buffer: Entity<MultiBuffer>,
1294 project: Option<Entity<Project>>,
1295 window: &mut Window,
1296 cx: &mut Context<Self>,
1297 ) -> Self {
1298 let style = window.text_style();
1299 let font_size = style.font_size.to_pixels(window.rem_size());
1300 let editor = cx.entity().downgrade();
1301 let fold_placeholder = FoldPlaceholder {
1302 constrain_width: true,
1303 render: Arc::new(move |fold_id, fold_range, cx| {
1304 let editor = editor.clone();
1305 div()
1306 .id(fold_id)
1307 .bg(cx.theme().colors().ghost_element_background)
1308 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1309 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1310 .rounded_xs()
1311 .size_full()
1312 .cursor_pointer()
1313 .child("⋯")
1314 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1315 .on_click(move |_, _window, cx| {
1316 editor
1317 .update(cx, |editor, cx| {
1318 editor.unfold_ranges(
1319 &[fold_range.start..fold_range.end],
1320 true,
1321 false,
1322 cx,
1323 );
1324 cx.stop_propagation();
1325 })
1326 .ok();
1327 })
1328 .into_any()
1329 }),
1330 merge_adjacent: true,
1331 ..Default::default()
1332 };
1333 let display_map = cx.new(|cx| {
1334 DisplayMap::new(
1335 buffer.clone(),
1336 style.font(),
1337 font_size,
1338 None,
1339 FILE_HEADER_HEIGHT,
1340 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1341 fold_placeholder,
1342 cx,
1343 )
1344 });
1345
1346 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1347
1348 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1349
1350 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1351 .then(|| language_settings::SoftWrap::None);
1352
1353 let mut project_subscriptions = Vec::new();
1354 if mode.is_full() {
1355 if let Some(project) = project.as_ref() {
1356 project_subscriptions.push(cx.subscribe_in(
1357 project,
1358 window,
1359 |editor, _, event, window, cx| match event {
1360 project::Event::RefreshCodeLens => {
1361 // we always query lens with actions, without storing them, always refreshing them
1362 }
1363 project::Event::RefreshInlayHints => {
1364 editor
1365 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1366 }
1367 project::Event::SnippetEdit(id, snippet_edits) => {
1368 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1369 let focus_handle = editor.focus_handle(cx);
1370 if focus_handle.is_focused(window) {
1371 let snapshot = buffer.read(cx).snapshot();
1372 for (range, snippet) in snippet_edits {
1373 let editor_range =
1374 language::range_from_lsp(*range).to_offset(&snapshot);
1375 editor
1376 .insert_snippet(
1377 &[editor_range],
1378 snippet.clone(),
1379 window,
1380 cx,
1381 )
1382 .ok();
1383 }
1384 }
1385 }
1386 }
1387 _ => {}
1388 },
1389 ));
1390 if let Some(task_inventory) = project
1391 .read(cx)
1392 .task_store()
1393 .read(cx)
1394 .task_inventory()
1395 .cloned()
1396 {
1397 project_subscriptions.push(cx.observe_in(
1398 &task_inventory,
1399 window,
1400 |editor, _, window, cx| {
1401 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1402 },
1403 ));
1404 };
1405
1406 project_subscriptions.push(cx.subscribe_in(
1407 &project.read(cx).breakpoint_store(),
1408 window,
1409 |editor, _, event, window, cx| match event {
1410 BreakpointStoreEvent::ActiveDebugLineChanged => {
1411 if editor.go_to_active_debug_line(window, cx) {
1412 cx.stop_propagation();
1413 }
1414 }
1415 _ => {}
1416 },
1417 ));
1418 }
1419 }
1420
1421 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1422
1423 let inlay_hint_settings =
1424 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1425 let focus_handle = cx.focus_handle();
1426 cx.on_focus(&focus_handle, window, Self::handle_focus)
1427 .detach();
1428 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1429 .detach();
1430 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1431 .detach();
1432 cx.on_blur(&focus_handle, window, Self::handle_blur)
1433 .detach();
1434
1435 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1436 Some(false)
1437 } else {
1438 None
1439 };
1440
1441 let breakpoint_store = match (mode, project.as_ref()) {
1442 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1443 _ => None,
1444 };
1445
1446 let mut code_action_providers = Vec::new();
1447 let mut load_uncommitted_diff = None;
1448 if let Some(project) = project.clone() {
1449 load_uncommitted_diff = Some(
1450 get_uncommitted_diff_for_buffer(
1451 &project,
1452 buffer.read(cx).all_buffers(),
1453 buffer.clone(),
1454 cx,
1455 )
1456 .shared(),
1457 );
1458 code_action_providers.push(Rc::new(project) as Rc<_>);
1459 }
1460
1461 let mut this = Self {
1462 focus_handle,
1463 show_cursor_when_unfocused: false,
1464 last_focused_descendant: None,
1465 buffer: buffer.clone(),
1466 display_map: display_map.clone(),
1467 selections,
1468 scroll_manager: ScrollManager::new(cx),
1469 columnar_selection_tail: None,
1470 add_selections_state: None,
1471 select_next_state: None,
1472 select_prev_state: None,
1473 selection_history: Default::default(),
1474 autoclose_regions: Default::default(),
1475 snippet_stack: Default::default(),
1476 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1477 ime_transaction: Default::default(),
1478 active_diagnostics: None,
1479 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1480 inline_diagnostics_update: Task::ready(()),
1481 inline_diagnostics: Vec::new(),
1482 soft_wrap_mode_override,
1483 hard_wrap: None,
1484 completion_provider: project.clone().map(|project| Box::new(project) as _),
1485 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1486 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1487 project,
1488 blink_manager: blink_manager.clone(),
1489 show_local_selections: true,
1490 show_scrollbars: true,
1491 mode,
1492 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1493 show_gutter: mode.is_full(),
1494 show_line_numbers: None,
1495 use_relative_line_numbers: None,
1496 show_git_diff_gutter: None,
1497 show_code_actions: None,
1498 show_runnables: None,
1499 show_breakpoints: None,
1500 show_wrap_guides: None,
1501 show_indent_guides,
1502 placeholder_text: None,
1503 highlight_order: 0,
1504 highlighted_rows: HashMap::default(),
1505 background_highlights: Default::default(),
1506 gutter_highlights: TreeMap::default(),
1507 scrollbar_marker_state: ScrollbarMarkerState::default(),
1508 active_indent_guides_state: ActiveIndentGuidesState::default(),
1509 nav_history: None,
1510 context_menu: RefCell::new(None),
1511 context_menu_options: None,
1512 mouse_context_menu: None,
1513 completion_tasks: Default::default(),
1514 signature_help_state: SignatureHelpState::default(),
1515 auto_signature_help: None,
1516 find_all_references_task_sources: Vec::new(),
1517 next_completion_id: 0,
1518 next_inlay_id: 0,
1519 code_action_providers,
1520 available_code_actions: Default::default(),
1521 code_actions_task: Default::default(),
1522 selection_highlight_task: Default::default(),
1523 document_highlights_task: Default::default(),
1524 linked_editing_range_task: Default::default(),
1525 pending_rename: Default::default(),
1526 searchable: true,
1527 cursor_shape: EditorSettings::get_global(cx)
1528 .cursor_shape
1529 .unwrap_or_default(),
1530 current_line_highlight: None,
1531 autoindent_mode: Some(AutoindentMode::EachLine),
1532 collapse_matches: false,
1533 workspace: None,
1534 input_enabled: true,
1535 use_modal_editing: mode.is_full(),
1536 read_only: false,
1537 use_autoclose: true,
1538 use_auto_surround: true,
1539 auto_replace_emoji_shortcode: false,
1540 jsx_tag_auto_close_enabled_in_any_buffer: false,
1541 leader_peer_id: None,
1542 remote_id: None,
1543 hover_state: Default::default(),
1544 pending_mouse_down: None,
1545 hovered_link_state: Default::default(),
1546 edit_prediction_provider: None,
1547 active_inline_completion: None,
1548 stale_inline_completion_in_menu: None,
1549 edit_prediction_preview: EditPredictionPreview::Inactive {
1550 released_too_fast: false,
1551 },
1552 inline_diagnostics_enabled: mode.is_full(),
1553 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1554
1555 gutter_hovered: false,
1556 pixel_position_of_newest_cursor: None,
1557 last_bounds: None,
1558 last_position_map: None,
1559 expect_bounds_change: None,
1560 gutter_dimensions: GutterDimensions::default(),
1561 style: None,
1562 show_cursor_names: false,
1563 hovered_cursors: Default::default(),
1564 next_editor_action_id: EditorActionId::default(),
1565 editor_actions: Rc::default(),
1566 inline_completions_hidden_for_vim_mode: false,
1567 show_inline_completions_override: None,
1568 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1569 edit_prediction_settings: EditPredictionSettings::Disabled,
1570 edit_prediction_indent_conflict: false,
1571 edit_prediction_requires_modifier_in_indent_conflict: true,
1572 custom_context_menu: None,
1573 show_git_blame_gutter: false,
1574 show_git_blame_inline: false,
1575 show_selection_menu: None,
1576 show_git_blame_inline_delay_task: None,
1577 git_blame_inline_tooltip: None,
1578 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1579 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1580 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1581 .session
1582 .restore_unsaved_buffers,
1583 blame: None,
1584 blame_subscription: None,
1585 tasks: Default::default(),
1586
1587 breakpoint_store,
1588 gutter_breakpoint_indicator: (None, None),
1589 _subscriptions: vec![
1590 cx.observe(&buffer, Self::on_buffer_changed),
1591 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1592 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1593 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1594 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1595 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1596 cx.observe_window_activation(window, |editor, window, cx| {
1597 let active = window.is_window_active();
1598 editor.blink_manager.update(cx, |blink_manager, cx| {
1599 if active {
1600 blink_manager.enable(cx);
1601 } else {
1602 blink_manager.disable(cx);
1603 }
1604 });
1605 }),
1606 ],
1607 tasks_update_task: None,
1608 linked_edit_ranges: Default::default(),
1609 in_project_search: false,
1610 previous_search_ranges: None,
1611 breadcrumb_header: None,
1612 focused_block: None,
1613 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1614 addons: HashMap::default(),
1615 registered_buffers: HashMap::default(),
1616 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1617 selection_mark_mode: false,
1618 toggle_fold_multiple_buffers: Task::ready(()),
1619 serialize_selections: Task::ready(()),
1620 serialize_folds: Task::ready(()),
1621 text_style_refinement: None,
1622 load_diff_task: load_uncommitted_diff,
1623 mouse_cursor_hidden: false,
1624 hide_mouse_mode: EditorSettings::get_global(cx)
1625 .hide_mouse
1626 .unwrap_or_default(),
1627 };
1628 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1629 this._subscriptions
1630 .push(cx.observe(breakpoints, |_, _, cx| {
1631 cx.notify();
1632 }));
1633 }
1634 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1635 this._subscriptions.extend(project_subscriptions);
1636
1637 this._subscriptions.push(cx.subscribe_in(
1638 &cx.entity(),
1639 window,
1640 |editor, _, e: &EditorEvent, window, cx| {
1641 if let EditorEvent::SelectionsChanged { local } = e {
1642 if *local {
1643 let new_anchor = editor.scroll_manager.anchor();
1644 let snapshot = editor.snapshot(window, cx);
1645 editor.update_restoration_data(cx, move |data| {
1646 data.scroll_position = (
1647 new_anchor.top_row(&snapshot.buffer_snapshot),
1648 new_anchor.offset,
1649 );
1650 });
1651 }
1652 }
1653 },
1654 ));
1655
1656 this.end_selection(window, cx);
1657 this.scroll_manager.show_scrollbars(window, cx);
1658 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1659
1660 if mode.is_full() {
1661 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1662 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1663
1664 if this.git_blame_inline_enabled {
1665 this.git_blame_inline_enabled = true;
1666 this.start_git_blame_inline(false, window, cx);
1667 }
1668
1669 this.go_to_active_debug_line(window, cx);
1670
1671 if let Some(buffer) = buffer.read(cx).as_singleton() {
1672 if let Some(project) = this.project.as_ref() {
1673 let handle = project.update(cx, |project, cx| {
1674 project.register_buffer_with_language_servers(&buffer, cx)
1675 });
1676 this.registered_buffers
1677 .insert(buffer.read(cx).remote_id(), handle);
1678 }
1679 }
1680 }
1681
1682 this.report_editor_event("Editor Opened", None, cx);
1683 this
1684 }
1685
1686 pub fn deploy_mouse_context_menu(
1687 &mut self,
1688 position: gpui::Point<Pixels>,
1689 context_menu: Entity<ContextMenu>,
1690 window: &mut Window,
1691 cx: &mut Context<Self>,
1692 ) {
1693 self.mouse_context_menu = Some(MouseContextMenu::new(
1694 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1695 context_menu,
1696 window,
1697 cx,
1698 ));
1699 }
1700
1701 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1702 self.mouse_context_menu
1703 .as_ref()
1704 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1705 }
1706
1707 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1708 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1709 }
1710
1711 fn key_context_internal(
1712 &self,
1713 has_active_edit_prediction: bool,
1714 window: &Window,
1715 cx: &App,
1716 ) -> KeyContext {
1717 let mut key_context = KeyContext::new_with_defaults();
1718 key_context.add("Editor");
1719 let mode = match self.mode {
1720 EditorMode::SingleLine { .. } => "single_line",
1721 EditorMode::AutoHeight { .. } => "auto_height",
1722 EditorMode::Full { .. } => "full",
1723 };
1724
1725 if EditorSettings::jupyter_enabled(cx) {
1726 key_context.add("jupyter");
1727 }
1728
1729 key_context.set("mode", mode);
1730 if self.pending_rename.is_some() {
1731 key_context.add("renaming");
1732 }
1733
1734 match self.context_menu.borrow().as_ref() {
1735 Some(CodeContextMenu::Completions(_)) => {
1736 key_context.add("menu");
1737 key_context.add("showing_completions");
1738 }
1739 Some(CodeContextMenu::CodeActions(_)) => {
1740 key_context.add("menu");
1741 key_context.add("showing_code_actions")
1742 }
1743 None => {}
1744 }
1745
1746 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1747 if !self.focus_handle(cx).contains_focused(window, cx)
1748 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1749 {
1750 for addon in self.addons.values() {
1751 addon.extend_key_context(&mut key_context, cx)
1752 }
1753 }
1754
1755 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1756 if let Some(extension) = singleton_buffer
1757 .read(cx)
1758 .file()
1759 .and_then(|file| file.path().extension()?.to_str())
1760 {
1761 key_context.set("extension", extension.to_string());
1762 }
1763 } else {
1764 key_context.add("multibuffer");
1765 }
1766
1767 if has_active_edit_prediction {
1768 if self.edit_prediction_in_conflict() {
1769 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1770 } else {
1771 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1772 key_context.add("copilot_suggestion");
1773 }
1774 }
1775
1776 if self.selection_mark_mode {
1777 key_context.add("selection_mode");
1778 }
1779
1780 key_context
1781 }
1782
1783 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1784 self.mouse_cursor_hidden = match origin {
1785 HideMouseCursorOrigin::TypingAction => {
1786 matches!(
1787 self.hide_mouse_mode,
1788 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1789 )
1790 }
1791 HideMouseCursorOrigin::MovementAction => {
1792 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1793 }
1794 };
1795 }
1796
1797 pub fn edit_prediction_in_conflict(&self) -> bool {
1798 if !self.show_edit_predictions_in_menu() {
1799 return false;
1800 }
1801
1802 let showing_completions = self
1803 .context_menu
1804 .borrow()
1805 .as_ref()
1806 .map_or(false, |context| {
1807 matches!(context, CodeContextMenu::Completions(_))
1808 });
1809
1810 showing_completions
1811 || self.edit_prediction_requires_modifier()
1812 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1813 // bindings to insert tab characters.
1814 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1815 }
1816
1817 pub fn accept_edit_prediction_keybind(
1818 &self,
1819 window: &Window,
1820 cx: &App,
1821 ) -> AcceptEditPredictionBinding {
1822 let key_context = self.key_context_internal(true, window, cx);
1823 let in_conflict = self.edit_prediction_in_conflict();
1824
1825 AcceptEditPredictionBinding(
1826 window
1827 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1828 .into_iter()
1829 .filter(|binding| {
1830 !in_conflict
1831 || binding
1832 .keystrokes()
1833 .first()
1834 .map_or(false, |keystroke| keystroke.modifiers.modified())
1835 })
1836 .rev()
1837 .min_by_key(|binding| {
1838 binding
1839 .keystrokes()
1840 .first()
1841 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1842 }),
1843 )
1844 }
1845
1846 pub fn new_file(
1847 workspace: &mut Workspace,
1848 _: &workspace::NewFile,
1849 window: &mut Window,
1850 cx: &mut Context<Workspace>,
1851 ) {
1852 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1853 "Failed to create buffer",
1854 window,
1855 cx,
1856 |e, _, _| match e.error_code() {
1857 ErrorCode::RemoteUpgradeRequired => Some(format!(
1858 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1859 e.error_tag("required").unwrap_or("the latest version")
1860 )),
1861 _ => None,
1862 },
1863 );
1864 }
1865
1866 pub fn new_in_workspace(
1867 workspace: &mut Workspace,
1868 window: &mut Window,
1869 cx: &mut Context<Workspace>,
1870 ) -> Task<Result<Entity<Editor>>> {
1871 let project = workspace.project().clone();
1872 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1873
1874 cx.spawn_in(window, async move |workspace, cx| {
1875 let buffer = create.await?;
1876 workspace.update_in(cx, |workspace, window, cx| {
1877 let editor =
1878 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1879 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1880 editor
1881 })
1882 })
1883 }
1884
1885 fn new_file_vertical(
1886 workspace: &mut Workspace,
1887 _: &workspace::NewFileSplitVertical,
1888 window: &mut Window,
1889 cx: &mut Context<Workspace>,
1890 ) {
1891 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1892 }
1893
1894 fn new_file_horizontal(
1895 workspace: &mut Workspace,
1896 _: &workspace::NewFileSplitHorizontal,
1897 window: &mut Window,
1898 cx: &mut Context<Workspace>,
1899 ) {
1900 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1901 }
1902
1903 fn new_file_in_direction(
1904 workspace: &mut Workspace,
1905 direction: SplitDirection,
1906 window: &mut Window,
1907 cx: &mut Context<Workspace>,
1908 ) {
1909 let project = workspace.project().clone();
1910 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1911
1912 cx.spawn_in(window, async move |workspace, cx| {
1913 let buffer = create.await?;
1914 workspace.update_in(cx, move |workspace, window, cx| {
1915 workspace.split_item(
1916 direction,
1917 Box::new(
1918 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1919 ),
1920 window,
1921 cx,
1922 )
1923 })?;
1924 anyhow::Ok(())
1925 })
1926 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1927 match e.error_code() {
1928 ErrorCode::RemoteUpgradeRequired => Some(format!(
1929 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1930 e.error_tag("required").unwrap_or("the latest version")
1931 )),
1932 _ => None,
1933 }
1934 });
1935 }
1936
1937 pub fn leader_peer_id(&self) -> Option<PeerId> {
1938 self.leader_peer_id
1939 }
1940
1941 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1942 &self.buffer
1943 }
1944
1945 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1946 self.workspace.as_ref()?.0.upgrade()
1947 }
1948
1949 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1950 self.buffer().read(cx).title(cx)
1951 }
1952
1953 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1954 let git_blame_gutter_max_author_length = self
1955 .render_git_blame_gutter(cx)
1956 .then(|| {
1957 if let Some(blame) = self.blame.as_ref() {
1958 let max_author_length =
1959 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1960 Some(max_author_length)
1961 } else {
1962 None
1963 }
1964 })
1965 .flatten();
1966
1967 EditorSnapshot {
1968 mode: self.mode,
1969 show_gutter: self.show_gutter,
1970 show_line_numbers: self.show_line_numbers,
1971 show_git_diff_gutter: self.show_git_diff_gutter,
1972 show_code_actions: self.show_code_actions,
1973 show_runnables: self.show_runnables,
1974 show_breakpoints: self.show_breakpoints,
1975 git_blame_gutter_max_author_length,
1976 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1977 scroll_anchor: self.scroll_manager.anchor(),
1978 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1979 placeholder_text: self.placeholder_text.clone(),
1980 is_focused: self.focus_handle.is_focused(window),
1981 current_line_highlight: self
1982 .current_line_highlight
1983 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1984 gutter_hovered: self.gutter_hovered,
1985 }
1986 }
1987
1988 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1989 self.buffer.read(cx).language_at(point, cx)
1990 }
1991
1992 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1993 self.buffer.read(cx).read(cx).file_at(point).cloned()
1994 }
1995
1996 pub fn active_excerpt(
1997 &self,
1998 cx: &App,
1999 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2000 self.buffer
2001 .read(cx)
2002 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2003 }
2004
2005 pub fn mode(&self) -> EditorMode {
2006 self.mode
2007 }
2008
2009 pub fn set_mode(&mut self, mode: EditorMode) {
2010 self.mode = mode;
2011 }
2012
2013 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2014 self.collaboration_hub.as_deref()
2015 }
2016
2017 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2018 self.collaboration_hub = Some(hub);
2019 }
2020
2021 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2022 self.in_project_search = in_project_search;
2023 }
2024
2025 pub fn set_custom_context_menu(
2026 &mut self,
2027 f: impl 'static
2028 + Fn(
2029 &mut Self,
2030 DisplayPoint,
2031 &mut Window,
2032 &mut Context<Self>,
2033 ) -> Option<Entity<ui::ContextMenu>>,
2034 ) {
2035 self.custom_context_menu = Some(Box::new(f))
2036 }
2037
2038 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2039 self.completion_provider = provider;
2040 }
2041
2042 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2043 self.semantics_provider.clone()
2044 }
2045
2046 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2047 self.semantics_provider = provider;
2048 }
2049
2050 pub fn set_edit_prediction_provider<T>(
2051 &mut self,
2052 provider: Option<Entity<T>>,
2053 window: &mut Window,
2054 cx: &mut Context<Self>,
2055 ) where
2056 T: EditPredictionProvider,
2057 {
2058 self.edit_prediction_provider =
2059 provider.map(|provider| RegisteredInlineCompletionProvider {
2060 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2061 if this.focus_handle.is_focused(window) {
2062 this.update_visible_inline_completion(window, cx);
2063 }
2064 }),
2065 provider: Arc::new(provider),
2066 });
2067 self.update_edit_prediction_settings(cx);
2068 self.refresh_inline_completion(false, false, window, cx);
2069 }
2070
2071 pub fn placeholder_text(&self) -> Option<&str> {
2072 self.placeholder_text.as_deref()
2073 }
2074
2075 pub fn set_placeholder_text(
2076 &mut self,
2077 placeholder_text: impl Into<Arc<str>>,
2078 cx: &mut Context<Self>,
2079 ) {
2080 let placeholder_text = Some(placeholder_text.into());
2081 if self.placeholder_text != placeholder_text {
2082 self.placeholder_text = placeholder_text;
2083 cx.notify();
2084 }
2085 }
2086
2087 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2088 self.cursor_shape = cursor_shape;
2089
2090 // Disrupt blink for immediate user feedback that the cursor shape has changed
2091 self.blink_manager.update(cx, BlinkManager::show_cursor);
2092
2093 cx.notify();
2094 }
2095
2096 pub fn set_current_line_highlight(
2097 &mut self,
2098 current_line_highlight: Option<CurrentLineHighlight>,
2099 ) {
2100 self.current_line_highlight = current_line_highlight;
2101 }
2102
2103 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2104 self.collapse_matches = collapse_matches;
2105 }
2106
2107 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2108 let buffers = self.buffer.read(cx).all_buffers();
2109 let Some(project) = self.project.as_ref() else {
2110 return;
2111 };
2112 project.update(cx, |project, cx| {
2113 for buffer in buffers {
2114 self.registered_buffers
2115 .entry(buffer.read(cx).remote_id())
2116 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2117 }
2118 })
2119 }
2120
2121 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2122 if self.collapse_matches {
2123 return range.start..range.start;
2124 }
2125 range.clone()
2126 }
2127
2128 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2129 if self.display_map.read(cx).clip_at_line_ends != clip {
2130 self.display_map
2131 .update(cx, |map, _| map.clip_at_line_ends = clip);
2132 }
2133 }
2134
2135 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2136 self.input_enabled = input_enabled;
2137 }
2138
2139 pub fn set_inline_completions_hidden_for_vim_mode(
2140 &mut self,
2141 hidden: bool,
2142 window: &mut Window,
2143 cx: &mut Context<Self>,
2144 ) {
2145 if hidden != self.inline_completions_hidden_for_vim_mode {
2146 self.inline_completions_hidden_for_vim_mode = hidden;
2147 if hidden {
2148 self.update_visible_inline_completion(window, cx);
2149 } else {
2150 self.refresh_inline_completion(true, false, window, cx);
2151 }
2152 }
2153 }
2154
2155 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2156 self.menu_inline_completions_policy = value;
2157 }
2158
2159 pub fn set_autoindent(&mut self, autoindent: bool) {
2160 if autoindent {
2161 self.autoindent_mode = Some(AutoindentMode::EachLine);
2162 } else {
2163 self.autoindent_mode = None;
2164 }
2165 }
2166
2167 pub fn read_only(&self, cx: &App) -> bool {
2168 self.read_only || self.buffer.read(cx).read_only()
2169 }
2170
2171 pub fn set_read_only(&mut self, read_only: bool) {
2172 self.read_only = read_only;
2173 }
2174
2175 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2176 self.use_autoclose = autoclose;
2177 }
2178
2179 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2180 self.use_auto_surround = auto_surround;
2181 }
2182
2183 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2184 self.auto_replace_emoji_shortcode = auto_replace;
2185 }
2186
2187 pub fn toggle_edit_predictions(
2188 &mut self,
2189 _: &ToggleEditPrediction,
2190 window: &mut Window,
2191 cx: &mut Context<Self>,
2192 ) {
2193 if self.show_inline_completions_override.is_some() {
2194 self.set_show_edit_predictions(None, window, cx);
2195 } else {
2196 let show_edit_predictions = !self.edit_predictions_enabled();
2197 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2198 }
2199 }
2200
2201 pub fn set_show_edit_predictions(
2202 &mut self,
2203 show_edit_predictions: Option<bool>,
2204 window: &mut Window,
2205 cx: &mut Context<Self>,
2206 ) {
2207 self.show_inline_completions_override = show_edit_predictions;
2208 self.update_edit_prediction_settings(cx);
2209
2210 if let Some(false) = show_edit_predictions {
2211 self.discard_inline_completion(false, cx);
2212 } else {
2213 self.refresh_inline_completion(false, true, window, cx);
2214 }
2215 }
2216
2217 fn inline_completions_disabled_in_scope(
2218 &self,
2219 buffer: &Entity<Buffer>,
2220 buffer_position: language::Anchor,
2221 cx: &App,
2222 ) -> bool {
2223 let snapshot = buffer.read(cx).snapshot();
2224 let settings = snapshot.settings_at(buffer_position, cx);
2225
2226 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2227 return false;
2228 };
2229
2230 scope.override_name().map_or(false, |scope_name| {
2231 settings
2232 .edit_predictions_disabled_in
2233 .iter()
2234 .any(|s| s == scope_name)
2235 })
2236 }
2237
2238 pub fn set_use_modal_editing(&mut self, to: bool) {
2239 self.use_modal_editing = to;
2240 }
2241
2242 pub fn use_modal_editing(&self) -> bool {
2243 self.use_modal_editing
2244 }
2245
2246 fn selections_did_change(
2247 &mut self,
2248 local: bool,
2249 old_cursor_position: &Anchor,
2250 show_completions: bool,
2251 window: &mut Window,
2252 cx: &mut Context<Self>,
2253 ) {
2254 window.invalidate_character_coordinates();
2255
2256 // Copy selections to primary selection buffer
2257 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2258 if local {
2259 let selections = self.selections.all::<usize>(cx);
2260 let buffer_handle = self.buffer.read(cx).read(cx);
2261
2262 let mut text = String::new();
2263 for (index, selection) in selections.iter().enumerate() {
2264 let text_for_selection = buffer_handle
2265 .text_for_range(selection.start..selection.end)
2266 .collect::<String>();
2267
2268 text.push_str(&text_for_selection);
2269 if index != selections.len() - 1 {
2270 text.push('\n');
2271 }
2272 }
2273
2274 if !text.is_empty() {
2275 cx.write_to_primary(ClipboardItem::new_string(text));
2276 }
2277 }
2278
2279 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2280 self.buffer.update(cx, |buffer, cx| {
2281 buffer.set_active_selections(
2282 &self.selections.disjoint_anchors(),
2283 self.selections.line_mode,
2284 self.cursor_shape,
2285 cx,
2286 )
2287 });
2288 }
2289 let display_map = self
2290 .display_map
2291 .update(cx, |display_map, cx| display_map.snapshot(cx));
2292 let buffer = &display_map.buffer_snapshot;
2293 self.add_selections_state = None;
2294 self.select_next_state = None;
2295 self.select_prev_state = None;
2296 self.select_syntax_node_history.try_clear();
2297 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2298 self.snippet_stack
2299 .invalidate(&self.selections.disjoint_anchors(), buffer);
2300 self.take_rename(false, window, cx);
2301
2302 let new_cursor_position = self.selections.newest_anchor().head();
2303
2304 self.push_to_nav_history(
2305 *old_cursor_position,
2306 Some(new_cursor_position.to_point(buffer)),
2307 false,
2308 cx,
2309 );
2310
2311 if local {
2312 let new_cursor_position = self.selections.newest_anchor().head();
2313 let mut context_menu = self.context_menu.borrow_mut();
2314 let completion_menu = match context_menu.as_ref() {
2315 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2316 _ => {
2317 *context_menu = None;
2318 None
2319 }
2320 };
2321 if let Some(buffer_id) = new_cursor_position.buffer_id {
2322 if !self.registered_buffers.contains_key(&buffer_id) {
2323 if let Some(project) = self.project.as_ref() {
2324 project.update(cx, |project, cx| {
2325 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2326 return;
2327 };
2328 self.registered_buffers.insert(
2329 buffer_id,
2330 project.register_buffer_with_language_servers(&buffer, cx),
2331 );
2332 })
2333 }
2334 }
2335 }
2336
2337 if let Some(completion_menu) = completion_menu {
2338 let cursor_position = new_cursor_position.to_offset(buffer);
2339 let (word_range, kind) =
2340 buffer.surrounding_word(completion_menu.initial_position, true);
2341 if kind == Some(CharKind::Word)
2342 && word_range.to_inclusive().contains(&cursor_position)
2343 {
2344 let mut completion_menu = completion_menu.clone();
2345 drop(context_menu);
2346
2347 let query = Self::completion_query(buffer, cursor_position);
2348 cx.spawn(async move |this, cx| {
2349 completion_menu
2350 .filter(query.as_deref(), cx.background_executor().clone())
2351 .await;
2352
2353 this.update(cx, |this, cx| {
2354 let mut context_menu = this.context_menu.borrow_mut();
2355 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2356 else {
2357 return;
2358 };
2359
2360 if menu.id > completion_menu.id {
2361 return;
2362 }
2363
2364 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2365 drop(context_menu);
2366 cx.notify();
2367 })
2368 })
2369 .detach();
2370
2371 if show_completions {
2372 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2373 }
2374 } else {
2375 drop(context_menu);
2376 self.hide_context_menu(window, cx);
2377 }
2378 } else {
2379 drop(context_menu);
2380 }
2381
2382 hide_hover(self, cx);
2383
2384 if old_cursor_position.to_display_point(&display_map).row()
2385 != new_cursor_position.to_display_point(&display_map).row()
2386 {
2387 self.available_code_actions.take();
2388 }
2389 self.refresh_code_actions(window, cx);
2390 self.refresh_document_highlights(cx);
2391 self.refresh_selected_text_highlights(window, cx);
2392 refresh_matching_bracket_highlights(self, window, cx);
2393 self.update_visible_inline_completion(window, cx);
2394 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2395 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2396 if self.git_blame_inline_enabled {
2397 self.start_inline_blame_timer(window, cx);
2398 }
2399 }
2400
2401 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2402 cx.emit(EditorEvent::SelectionsChanged { local });
2403
2404 let selections = &self.selections.disjoint;
2405 if selections.len() == 1 {
2406 cx.emit(SearchEvent::ActiveMatchChanged)
2407 }
2408 if local {
2409 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2410 let inmemory_selections = selections
2411 .iter()
2412 .map(|s| {
2413 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2414 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2415 })
2416 .collect();
2417 self.update_restoration_data(cx, |data| {
2418 data.selections = inmemory_selections;
2419 });
2420
2421 if WorkspaceSettings::get(None, cx).restore_on_startup
2422 != RestoreOnStartupBehavior::None
2423 {
2424 if let Some(workspace_id) =
2425 self.workspace.as_ref().and_then(|workspace| workspace.1)
2426 {
2427 let snapshot = self.buffer().read(cx).snapshot(cx);
2428 let selections = selections.clone();
2429 let background_executor = cx.background_executor().clone();
2430 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2431 self.serialize_selections = cx.background_spawn(async move {
2432 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2433 let db_selections = selections
2434 .iter()
2435 .map(|selection| {
2436 (
2437 selection.start.to_offset(&snapshot),
2438 selection.end.to_offset(&snapshot),
2439 )
2440 })
2441 .collect();
2442
2443 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2444 .await
2445 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2446 .log_err();
2447 });
2448 }
2449 }
2450 }
2451 }
2452
2453 cx.notify();
2454 }
2455
2456 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2457 use text::ToOffset as _;
2458 use text::ToPoint as _;
2459
2460 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2461 return;
2462 }
2463
2464 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2465 return;
2466 };
2467
2468 let snapshot = singleton.read(cx).snapshot();
2469 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2470 let display_snapshot = display_map.snapshot(cx);
2471
2472 display_snapshot
2473 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2474 .map(|fold| {
2475 fold.range.start.text_anchor.to_point(&snapshot)
2476 ..fold.range.end.text_anchor.to_point(&snapshot)
2477 })
2478 .collect()
2479 });
2480 self.update_restoration_data(cx, |data| {
2481 data.folds = inmemory_folds;
2482 });
2483
2484 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2485 return;
2486 };
2487 let background_executor = cx.background_executor().clone();
2488 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2489 let db_folds = self.display_map.update(cx, |display_map, cx| {
2490 display_map
2491 .snapshot(cx)
2492 .folds_in_range(0..snapshot.len())
2493 .map(|fold| {
2494 (
2495 fold.range.start.text_anchor.to_offset(&snapshot),
2496 fold.range.end.text_anchor.to_offset(&snapshot),
2497 )
2498 })
2499 .collect()
2500 });
2501 self.serialize_folds = cx.background_spawn(async move {
2502 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2503 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2504 .await
2505 .with_context(|| {
2506 format!(
2507 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2508 )
2509 })
2510 .log_err();
2511 });
2512 }
2513
2514 pub fn sync_selections(
2515 &mut self,
2516 other: Entity<Editor>,
2517 cx: &mut Context<Self>,
2518 ) -> gpui::Subscription {
2519 let other_selections = other.read(cx).selections.disjoint.to_vec();
2520 self.selections.change_with(cx, |selections| {
2521 selections.select_anchors(other_selections);
2522 });
2523
2524 let other_subscription =
2525 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2526 EditorEvent::SelectionsChanged { local: true } => {
2527 let other_selections = other.read(cx).selections.disjoint.to_vec();
2528 if other_selections.is_empty() {
2529 return;
2530 }
2531 this.selections.change_with(cx, |selections| {
2532 selections.select_anchors(other_selections);
2533 });
2534 }
2535 _ => {}
2536 });
2537
2538 let this_subscription =
2539 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2540 EditorEvent::SelectionsChanged { local: true } => {
2541 let these_selections = this.selections.disjoint.to_vec();
2542 if these_selections.is_empty() {
2543 return;
2544 }
2545 other.update(cx, |other_editor, cx| {
2546 other_editor.selections.change_with(cx, |selections| {
2547 selections.select_anchors(these_selections);
2548 })
2549 });
2550 }
2551 _ => {}
2552 });
2553
2554 Subscription::join(other_subscription, this_subscription)
2555 }
2556
2557 pub fn change_selections<R>(
2558 &mut self,
2559 autoscroll: Option<Autoscroll>,
2560 window: &mut Window,
2561 cx: &mut Context<Self>,
2562 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2563 ) -> R {
2564 self.change_selections_inner(autoscroll, true, window, cx, change)
2565 }
2566
2567 fn change_selections_inner<R>(
2568 &mut self,
2569 autoscroll: Option<Autoscroll>,
2570 request_completions: bool,
2571 window: &mut Window,
2572 cx: &mut Context<Self>,
2573 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2574 ) -> R {
2575 let old_cursor_position = self.selections.newest_anchor().head();
2576 self.push_to_selection_history();
2577
2578 let (changed, result) = self.selections.change_with(cx, change);
2579
2580 if changed {
2581 if let Some(autoscroll) = autoscroll {
2582 self.request_autoscroll(autoscroll, cx);
2583 }
2584 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2585
2586 if self.should_open_signature_help_automatically(
2587 &old_cursor_position,
2588 self.signature_help_state.backspace_pressed(),
2589 cx,
2590 ) {
2591 self.show_signature_help(&ShowSignatureHelp, window, cx);
2592 }
2593 self.signature_help_state.set_backspace_pressed(false);
2594 }
2595
2596 result
2597 }
2598
2599 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2600 where
2601 I: IntoIterator<Item = (Range<S>, T)>,
2602 S: ToOffset,
2603 T: Into<Arc<str>>,
2604 {
2605 if self.read_only(cx) {
2606 return;
2607 }
2608
2609 self.buffer
2610 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2611 }
2612
2613 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2614 where
2615 I: IntoIterator<Item = (Range<S>, T)>,
2616 S: ToOffset,
2617 T: Into<Arc<str>>,
2618 {
2619 if self.read_only(cx) {
2620 return;
2621 }
2622
2623 self.buffer.update(cx, |buffer, cx| {
2624 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2625 });
2626 }
2627
2628 pub fn edit_with_block_indent<I, S, T>(
2629 &mut self,
2630 edits: I,
2631 original_indent_columns: Vec<Option<u32>>,
2632 cx: &mut Context<Self>,
2633 ) where
2634 I: IntoIterator<Item = (Range<S>, T)>,
2635 S: ToOffset,
2636 T: Into<Arc<str>>,
2637 {
2638 if self.read_only(cx) {
2639 return;
2640 }
2641
2642 self.buffer.update(cx, |buffer, cx| {
2643 buffer.edit(
2644 edits,
2645 Some(AutoindentMode::Block {
2646 original_indent_columns,
2647 }),
2648 cx,
2649 )
2650 });
2651 }
2652
2653 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2654 self.hide_context_menu(window, cx);
2655
2656 match phase {
2657 SelectPhase::Begin {
2658 position,
2659 add,
2660 click_count,
2661 } => self.begin_selection(position, add, click_count, window, cx),
2662 SelectPhase::BeginColumnar {
2663 position,
2664 goal_column,
2665 reset,
2666 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2667 SelectPhase::Extend {
2668 position,
2669 click_count,
2670 } => self.extend_selection(position, click_count, window, cx),
2671 SelectPhase::Update {
2672 position,
2673 goal_column,
2674 scroll_delta,
2675 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2676 SelectPhase::End => self.end_selection(window, cx),
2677 }
2678 }
2679
2680 fn extend_selection(
2681 &mut self,
2682 position: DisplayPoint,
2683 click_count: usize,
2684 window: &mut Window,
2685 cx: &mut Context<Self>,
2686 ) {
2687 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2688 let tail = self.selections.newest::<usize>(cx).tail();
2689 self.begin_selection(position, false, click_count, window, cx);
2690
2691 let position = position.to_offset(&display_map, Bias::Left);
2692 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2693
2694 let mut pending_selection = self
2695 .selections
2696 .pending_anchor()
2697 .expect("extend_selection not called with pending selection");
2698 if position >= tail {
2699 pending_selection.start = tail_anchor;
2700 } else {
2701 pending_selection.end = tail_anchor;
2702 pending_selection.reversed = true;
2703 }
2704
2705 let mut pending_mode = self.selections.pending_mode().unwrap();
2706 match &mut pending_mode {
2707 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2708 _ => {}
2709 }
2710
2711 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2712 s.set_pending(pending_selection, pending_mode)
2713 });
2714 }
2715
2716 fn begin_selection(
2717 &mut self,
2718 position: DisplayPoint,
2719 add: bool,
2720 click_count: usize,
2721 window: &mut Window,
2722 cx: &mut Context<Self>,
2723 ) {
2724 if !self.focus_handle.is_focused(window) {
2725 self.last_focused_descendant = None;
2726 window.focus(&self.focus_handle);
2727 }
2728
2729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2730 let buffer = &display_map.buffer_snapshot;
2731 let newest_selection = self.selections.newest_anchor().clone();
2732 let position = display_map.clip_point(position, Bias::Left);
2733
2734 let start;
2735 let end;
2736 let mode;
2737 let mut auto_scroll;
2738 match click_count {
2739 1 => {
2740 start = buffer.anchor_before(position.to_point(&display_map));
2741 end = start;
2742 mode = SelectMode::Character;
2743 auto_scroll = true;
2744 }
2745 2 => {
2746 let range = movement::surrounding_word(&display_map, position);
2747 start = buffer.anchor_before(range.start.to_point(&display_map));
2748 end = buffer.anchor_before(range.end.to_point(&display_map));
2749 mode = SelectMode::Word(start..end);
2750 auto_scroll = true;
2751 }
2752 3 => {
2753 let position = display_map
2754 .clip_point(position, Bias::Left)
2755 .to_point(&display_map);
2756 let line_start = display_map.prev_line_boundary(position).0;
2757 let next_line_start = buffer.clip_point(
2758 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2759 Bias::Left,
2760 );
2761 start = buffer.anchor_before(line_start);
2762 end = buffer.anchor_before(next_line_start);
2763 mode = SelectMode::Line(start..end);
2764 auto_scroll = true;
2765 }
2766 _ => {
2767 start = buffer.anchor_before(0);
2768 end = buffer.anchor_before(buffer.len());
2769 mode = SelectMode::All;
2770 auto_scroll = false;
2771 }
2772 }
2773 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2774
2775 let point_to_delete: Option<usize> = {
2776 let selected_points: Vec<Selection<Point>> =
2777 self.selections.disjoint_in_range(start..end, cx);
2778
2779 if !add || click_count > 1 {
2780 None
2781 } else if !selected_points.is_empty() {
2782 Some(selected_points[0].id)
2783 } else {
2784 let clicked_point_already_selected =
2785 self.selections.disjoint.iter().find(|selection| {
2786 selection.start.to_point(buffer) == start.to_point(buffer)
2787 || selection.end.to_point(buffer) == end.to_point(buffer)
2788 });
2789
2790 clicked_point_already_selected.map(|selection| selection.id)
2791 }
2792 };
2793
2794 let selections_count = self.selections.count();
2795
2796 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2797 if let Some(point_to_delete) = point_to_delete {
2798 s.delete(point_to_delete);
2799
2800 if selections_count == 1 {
2801 s.set_pending_anchor_range(start..end, mode);
2802 }
2803 } else {
2804 if !add {
2805 s.clear_disjoint();
2806 } else if click_count > 1 {
2807 s.delete(newest_selection.id)
2808 }
2809
2810 s.set_pending_anchor_range(start..end, mode);
2811 }
2812 });
2813 }
2814
2815 fn begin_columnar_selection(
2816 &mut self,
2817 position: DisplayPoint,
2818 goal_column: u32,
2819 reset: bool,
2820 window: &mut Window,
2821 cx: &mut Context<Self>,
2822 ) {
2823 if !self.focus_handle.is_focused(window) {
2824 self.last_focused_descendant = None;
2825 window.focus(&self.focus_handle);
2826 }
2827
2828 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2829
2830 if reset {
2831 let pointer_position = display_map
2832 .buffer_snapshot
2833 .anchor_before(position.to_point(&display_map));
2834
2835 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2836 s.clear_disjoint();
2837 s.set_pending_anchor_range(
2838 pointer_position..pointer_position,
2839 SelectMode::Character,
2840 );
2841 });
2842 }
2843
2844 let tail = self.selections.newest::<Point>(cx).tail();
2845 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2846
2847 if !reset {
2848 self.select_columns(
2849 tail.to_display_point(&display_map),
2850 position,
2851 goal_column,
2852 &display_map,
2853 window,
2854 cx,
2855 );
2856 }
2857 }
2858
2859 fn update_selection(
2860 &mut self,
2861 position: DisplayPoint,
2862 goal_column: u32,
2863 scroll_delta: gpui::Point<f32>,
2864 window: &mut Window,
2865 cx: &mut Context<Self>,
2866 ) {
2867 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2868
2869 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2870 let tail = tail.to_display_point(&display_map);
2871 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2872 } else if let Some(mut pending) = self.selections.pending_anchor() {
2873 let buffer = self.buffer.read(cx).snapshot(cx);
2874 let head;
2875 let tail;
2876 let mode = self.selections.pending_mode().unwrap();
2877 match &mode {
2878 SelectMode::Character => {
2879 head = position.to_point(&display_map);
2880 tail = pending.tail().to_point(&buffer);
2881 }
2882 SelectMode::Word(original_range) => {
2883 let original_display_range = original_range.start.to_display_point(&display_map)
2884 ..original_range.end.to_display_point(&display_map);
2885 let original_buffer_range = original_display_range.start.to_point(&display_map)
2886 ..original_display_range.end.to_point(&display_map);
2887 if movement::is_inside_word(&display_map, position)
2888 || original_display_range.contains(&position)
2889 {
2890 let word_range = movement::surrounding_word(&display_map, position);
2891 if word_range.start < original_display_range.start {
2892 head = word_range.start.to_point(&display_map);
2893 } else {
2894 head = word_range.end.to_point(&display_map);
2895 }
2896 } else {
2897 head = position.to_point(&display_map);
2898 }
2899
2900 if head <= original_buffer_range.start {
2901 tail = original_buffer_range.end;
2902 } else {
2903 tail = original_buffer_range.start;
2904 }
2905 }
2906 SelectMode::Line(original_range) => {
2907 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2908
2909 let position = display_map
2910 .clip_point(position, Bias::Left)
2911 .to_point(&display_map);
2912 let line_start = display_map.prev_line_boundary(position).0;
2913 let next_line_start = buffer.clip_point(
2914 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2915 Bias::Left,
2916 );
2917
2918 if line_start < original_range.start {
2919 head = line_start
2920 } else {
2921 head = next_line_start
2922 }
2923
2924 if head <= original_range.start {
2925 tail = original_range.end;
2926 } else {
2927 tail = original_range.start;
2928 }
2929 }
2930 SelectMode::All => {
2931 return;
2932 }
2933 };
2934
2935 if head < tail {
2936 pending.start = buffer.anchor_before(head);
2937 pending.end = buffer.anchor_before(tail);
2938 pending.reversed = true;
2939 } else {
2940 pending.start = buffer.anchor_before(tail);
2941 pending.end = buffer.anchor_before(head);
2942 pending.reversed = false;
2943 }
2944
2945 self.change_selections(None, window, cx, |s| {
2946 s.set_pending(pending, mode);
2947 });
2948 } else {
2949 log::error!("update_selection dispatched with no pending selection");
2950 return;
2951 }
2952
2953 self.apply_scroll_delta(scroll_delta, window, cx);
2954 cx.notify();
2955 }
2956
2957 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2958 self.columnar_selection_tail.take();
2959 if self.selections.pending_anchor().is_some() {
2960 let selections = self.selections.all::<usize>(cx);
2961 self.change_selections(None, window, cx, |s| {
2962 s.select(selections);
2963 s.clear_pending();
2964 });
2965 }
2966 }
2967
2968 fn select_columns(
2969 &mut self,
2970 tail: DisplayPoint,
2971 head: DisplayPoint,
2972 goal_column: u32,
2973 display_map: &DisplaySnapshot,
2974 window: &mut Window,
2975 cx: &mut Context<Self>,
2976 ) {
2977 let start_row = cmp::min(tail.row(), head.row());
2978 let end_row = cmp::max(tail.row(), head.row());
2979 let start_column = cmp::min(tail.column(), goal_column);
2980 let end_column = cmp::max(tail.column(), goal_column);
2981 let reversed = start_column < tail.column();
2982
2983 let selection_ranges = (start_row.0..=end_row.0)
2984 .map(DisplayRow)
2985 .filter_map(|row| {
2986 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2987 let start = display_map
2988 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2989 .to_point(display_map);
2990 let end = display_map
2991 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2992 .to_point(display_map);
2993 if reversed {
2994 Some(end..start)
2995 } else {
2996 Some(start..end)
2997 }
2998 } else {
2999 None
3000 }
3001 })
3002 .collect::<Vec<_>>();
3003
3004 self.change_selections(None, window, cx, |s| {
3005 s.select_ranges(selection_ranges);
3006 });
3007 cx.notify();
3008 }
3009
3010 pub fn has_pending_nonempty_selection(&self) -> bool {
3011 let pending_nonempty_selection = match self.selections.pending_anchor() {
3012 Some(Selection { start, end, .. }) => start != end,
3013 None => false,
3014 };
3015
3016 pending_nonempty_selection
3017 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3018 }
3019
3020 pub fn has_pending_selection(&self) -> bool {
3021 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3022 }
3023
3024 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3025 self.selection_mark_mode = false;
3026
3027 if self.clear_expanded_diff_hunks(cx) {
3028 cx.notify();
3029 return;
3030 }
3031 if self.dismiss_menus_and_popups(true, window, cx) {
3032 return;
3033 }
3034
3035 if self.mode.is_full()
3036 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3037 {
3038 return;
3039 }
3040
3041 cx.propagate();
3042 }
3043
3044 pub fn dismiss_menus_and_popups(
3045 &mut self,
3046 is_user_requested: bool,
3047 window: &mut Window,
3048 cx: &mut Context<Self>,
3049 ) -> bool {
3050 if self.take_rename(false, window, cx).is_some() {
3051 return true;
3052 }
3053
3054 if hide_hover(self, cx) {
3055 return true;
3056 }
3057
3058 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3059 return true;
3060 }
3061
3062 if self.hide_context_menu(window, cx).is_some() {
3063 return true;
3064 }
3065
3066 if self.mouse_context_menu.take().is_some() {
3067 return true;
3068 }
3069
3070 if is_user_requested && self.discard_inline_completion(true, cx) {
3071 return true;
3072 }
3073
3074 if self.snippet_stack.pop().is_some() {
3075 return true;
3076 }
3077
3078 if self.mode.is_full() && self.active_diagnostics.is_some() {
3079 self.dismiss_diagnostics(cx);
3080 return true;
3081 }
3082
3083 false
3084 }
3085
3086 fn linked_editing_ranges_for(
3087 &self,
3088 selection: Range<text::Anchor>,
3089 cx: &App,
3090 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3091 if self.linked_edit_ranges.is_empty() {
3092 return None;
3093 }
3094 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3095 selection.end.buffer_id.and_then(|end_buffer_id| {
3096 if selection.start.buffer_id != Some(end_buffer_id) {
3097 return None;
3098 }
3099 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3100 let snapshot = buffer.read(cx).snapshot();
3101 self.linked_edit_ranges
3102 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3103 .map(|ranges| (ranges, snapshot, buffer))
3104 })?;
3105 use text::ToOffset as TO;
3106 // find offset from the start of current range to current cursor position
3107 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3108
3109 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3110 let start_difference = start_offset - start_byte_offset;
3111 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3112 let end_difference = end_offset - start_byte_offset;
3113 // Current range has associated linked ranges.
3114 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3115 for range in linked_ranges.iter() {
3116 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3117 let end_offset = start_offset + end_difference;
3118 let start_offset = start_offset + start_difference;
3119 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3120 continue;
3121 }
3122 if self.selections.disjoint_anchor_ranges().any(|s| {
3123 if s.start.buffer_id != selection.start.buffer_id
3124 || s.end.buffer_id != selection.end.buffer_id
3125 {
3126 return false;
3127 }
3128 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3129 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3130 }) {
3131 continue;
3132 }
3133 let start = buffer_snapshot.anchor_after(start_offset);
3134 let end = buffer_snapshot.anchor_after(end_offset);
3135 linked_edits
3136 .entry(buffer.clone())
3137 .or_default()
3138 .push(start..end);
3139 }
3140 Some(linked_edits)
3141 }
3142
3143 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3144 let text: Arc<str> = text.into();
3145
3146 if self.read_only(cx) {
3147 return;
3148 }
3149
3150 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3151
3152 let selections = self.selections.all_adjusted(cx);
3153 let mut bracket_inserted = false;
3154 let mut edits = Vec::new();
3155 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3156 let mut new_selections = Vec::with_capacity(selections.len());
3157 let mut new_autoclose_regions = Vec::new();
3158 let snapshot = self.buffer.read(cx).read(cx);
3159
3160 for (selection, autoclose_region) in
3161 self.selections_with_autoclose_regions(selections, &snapshot)
3162 {
3163 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3164 // Determine if the inserted text matches the opening or closing
3165 // bracket of any of this language's bracket pairs.
3166 let mut bracket_pair = None;
3167 let mut is_bracket_pair_start = false;
3168 let mut is_bracket_pair_end = false;
3169 if !text.is_empty() {
3170 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3171 // and they are removing the character that triggered IME popup.
3172 for (pair, enabled) in scope.brackets() {
3173 if !pair.close && !pair.surround {
3174 continue;
3175 }
3176
3177 if enabled && pair.start.ends_with(text.as_ref()) {
3178 let prefix_len = pair.start.len() - text.len();
3179 let preceding_text_matches_prefix = prefix_len == 0
3180 || (selection.start.column >= (prefix_len as u32)
3181 && snapshot.contains_str_at(
3182 Point::new(
3183 selection.start.row,
3184 selection.start.column - (prefix_len as u32),
3185 ),
3186 &pair.start[..prefix_len],
3187 ));
3188 if preceding_text_matches_prefix {
3189 bracket_pair = Some(pair.clone());
3190 is_bracket_pair_start = true;
3191 break;
3192 }
3193 }
3194 if pair.end.as_str() == text.as_ref() {
3195 bracket_pair = Some(pair.clone());
3196 is_bracket_pair_end = true;
3197 break;
3198 }
3199 }
3200 }
3201
3202 if let Some(bracket_pair) = bracket_pair {
3203 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3204 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3205 let auto_surround =
3206 self.use_auto_surround && snapshot_settings.use_auto_surround;
3207 if selection.is_empty() {
3208 if is_bracket_pair_start {
3209 // If the inserted text is a suffix of an opening bracket and the
3210 // selection is preceded by the rest of the opening bracket, then
3211 // insert the closing bracket.
3212 let following_text_allows_autoclose = snapshot
3213 .chars_at(selection.start)
3214 .next()
3215 .map_or(true, |c| scope.should_autoclose_before(c));
3216
3217 let preceding_text_allows_autoclose = selection.start.column == 0
3218 || snapshot.reversed_chars_at(selection.start).next().map_or(
3219 true,
3220 |c| {
3221 bracket_pair.start != bracket_pair.end
3222 || !snapshot
3223 .char_classifier_at(selection.start)
3224 .is_word(c)
3225 },
3226 );
3227
3228 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3229 && bracket_pair.start.len() == 1
3230 {
3231 let target = bracket_pair.start.chars().next().unwrap();
3232 let current_line_count = snapshot
3233 .reversed_chars_at(selection.start)
3234 .take_while(|&c| c != '\n')
3235 .filter(|&c| c == target)
3236 .count();
3237 current_line_count % 2 == 1
3238 } else {
3239 false
3240 };
3241
3242 if autoclose
3243 && bracket_pair.close
3244 && following_text_allows_autoclose
3245 && preceding_text_allows_autoclose
3246 && !is_closing_quote
3247 {
3248 let anchor = snapshot.anchor_before(selection.end);
3249 new_selections.push((selection.map(|_| anchor), text.len()));
3250 new_autoclose_regions.push((
3251 anchor,
3252 text.len(),
3253 selection.id,
3254 bracket_pair.clone(),
3255 ));
3256 edits.push((
3257 selection.range(),
3258 format!("{}{}", text, bracket_pair.end).into(),
3259 ));
3260 bracket_inserted = true;
3261 continue;
3262 }
3263 }
3264
3265 if let Some(region) = autoclose_region {
3266 // If the selection is followed by an auto-inserted closing bracket,
3267 // then don't insert that closing bracket again; just move the selection
3268 // past the closing bracket.
3269 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3270 && text.as_ref() == region.pair.end.as_str();
3271 if should_skip {
3272 let anchor = snapshot.anchor_after(selection.end);
3273 new_selections
3274 .push((selection.map(|_| anchor), region.pair.end.len()));
3275 continue;
3276 }
3277 }
3278
3279 let always_treat_brackets_as_autoclosed = snapshot
3280 .language_settings_at(selection.start, cx)
3281 .always_treat_brackets_as_autoclosed;
3282 if always_treat_brackets_as_autoclosed
3283 && is_bracket_pair_end
3284 && snapshot.contains_str_at(selection.end, text.as_ref())
3285 {
3286 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3287 // and the inserted text is a closing bracket and the selection is followed
3288 // by the closing bracket then move the selection past the closing bracket.
3289 let anchor = snapshot.anchor_after(selection.end);
3290 new_selections.push((selection.map(|_| anchor), text.len()));
3291 continue;
3292 }
3293 }
3294 // If an opening bracket is 1 character long and is typed while
3295 // text is selected, then surround that text with the bracket pair.
3296 else if auto_surround
3297 && bracket_pair.surround
3298 && is_bracket_pair_start
3299 && bracket_pair.start.chars().count() == 1
3300 {
3301 edits.push((selection.start..selection.start, text.clone()));
3302 edits.push((
3303 selection.end..selection.end,
3304 bracket_pair.end.as_str().into(),
3305 ));
3306 bracket_inserted = true;
3307 new_selections.push((
3308 Selection {
3309 id: selection.id,
3310 start: snapshot.anchor_after(selection.start),
3311 end: snapshot.anchor_before(selection.end),
3312 reversed: selection.reversed,
3313 goal: selection.goal,
3314 },
3315 0,
3316 ));
3317 continue;
3318 }
3319 }
3320 }
3321
3322 if self.auto_replace_emoji_shortcode
3323 && selection.is_empty()
3324 && text.as_ref().ends_with(':')
3325 {
3326 if let Some(possible_emoji_short_code) =
3327 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3328 {
3329 if !possible_emoji_short_code.is_empty() {
3330 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3331 let emoji_shortcode_start = Point::new(
3332 selection.start.row,
3333 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3334 );
3335
3336 // Remove shortcode from buffer
3337 edits.push((
3338 emoji_shortcode_start..selection.start,
3339 "".to_string().into(),
3340 ));
3341 new_selections.push((
3342 Selection {
3343 id: selection.id,
3344 start: snapshot.anchor_after(emoji_shortcode_start),
3345 end: snapshot.anchor_before(selection.start),
3346 reversed: selection.reversed,
3347 goal: selection.goal,
3348 },
3349 0,
3350 ));
3351
3352 // Insert emoji
3353 let selection_start_anchor = snapshot.anchor_after(selection.start);
3354 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3355 edits.push((selection.start..selection.end, emoji.to_string().into()));
3356
3357 continue;
3358 }
3359 }
3360 }
3361 }
3362
3363 // If not handling any auto-close operation, then just replace the selected
3364 // text with the given input and move the selection to the end of the
3365 // newly inserted text.
3366 let anchor = snapshot.anchor_after(selection.end);
3367 if !self.linked_edit_ranges.is_empty() {
3368 let start_anchor = snapshot.anchor_before(selection.start);
3369
3370 let is_word_char = text.chars().next().map_or(true, |char| {
3371 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3372 classifier.is_word(char)
3373 });
3374
3375 if is_word_char {
3376 if let Some(ranges) = self
3377 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3378 {
3379 for (buffer, edits) in ranges {
3380 linked_edits
3381 .entry(buffer.clone())
3382 .or_default()
3383 .extend(edits.into_iter().map(|range| (range, text.clone())));
3384 }
3385 }
3386 }
3387 }
3388
3389 new_selections.push((selection.map(|_| anchor), 0));
3390 edits.push((selection.start..selection.end, text.clone()));
3391 }
3392
3393 drop(snapshot);
3394
3395 self.transact(window, cx, |this, window, cx| {
3396 let initial_buffer_versions =
3397 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3398
3399 this.buffer.update(cx, |buffer, cx| {
3400 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3401 });
3402 for (buffer, edits) in linked_edits {
3403 buffer.update(cx, |buffer, cx| {
3404 let snapshot = buffer.snapshot();
3405 let edits = edits
3406 .into_iter()
3407 .map(|(range, text)| {
3408 use text::ToPoint as TP;
3409 let end_point = TP::to_point(&range.end, &snapshot);
3410 let start_point = TP::to_point(&range.start, &snapshot);
3411 (start_point..end_point, text)
3412 })
3413 .sorted_by_key(|(range, _)| range.start);
3414 buffer.edit(edits, None, cx);
3415 })
3416 }
3417 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3418 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3419 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3420 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3421 .zip(new_selection_deltas)
3422 .map(|(selection, delta)| Selection {
3423 id: selection.id,
3424 start: selection.start + delta,
3425 end: selection.end + delta,
3426 reversed: selection.reversed,
3427 goal: SelectionGoal::None,
3428 })
3429 .collect::<Vec<_>>();
3430
3431 let mut i = 0;
3432 for (position, delta, selection_id, pair) in new_autoclose_regions {
3433 let position = position.to_offset(&map.buffer_snapshot) + delta;
3434 let start = map.buffer_snapshot.anchor_before(position);
3435 let end = map.buffer_snapshot.anchor_after(position);
3436 while let Some(existing_state) = this.autoclose_regions.get(i) {
3437 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3438 Ordering::Less => i += 1,
3439 Ordering::Greater => break,
3440 Ordering::Equal => {
3441 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3442 Ordering::Less => i += 1,
3443 Ordering::Equal => break,
3444 Ordering::Greater => break,
3445 }
3446 }
3447 }
3448 }
3449 this.autoclose_regions.insert(
3450 i,
3451 AutocloseRegion {
3452 selection_id,
3453 range: start..end,
3454 pair,
3455 },
3456 );
3457 }
3458
3459 let had_active_inline_completion = this.has_active_inline_completion();
3460 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3461 s.select(new_selections)
3462 });
3463
3464 if !bracket_inserted {
3465 if let Some(on_type_format_task) =
3466 this.trigger_on_type_formatting(text.to_string(), window, cx)
3467 {
3468 on_type_format_task.detach_and_log_err(cx);
3469 }
3470 }
3471
3472 let editor_settings = EditorSettings::get_global(cx);
3473 if bracket_inserted
3474 && (editor_settings.auto_signature_help
3475 || editor_settings.show_signature_help_after_edits)
3476 {
3477 this.show_signature_help(&ShowSignatureHelp, window, cx);
3478 }
3479
3480 let trigger_in_words =
3481 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3482 if this.hard_wrap.is_some() {
3483 let latest: Range<Point> = this.selections.newest(cx).range();
3484 if latest.is_empty()
3485 && this
3486 .buffer()
3487 .read(cx)
3488 .snapshot(cx)
3489 .line_len(MultiBufferRow(latest.start.row))
3490 == latest.start.column
3491 {
3492 this.rewrap_impl(
3493 RewrapOptions {
3494 override_language_settings: true,
3495 preserve_existing_whitespace: true,
3496 },
3497 cx,
3498 )
3499 }
3500 }
3501 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3502 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3503 this.refresh_inline_completion(true, false, window, cx);
3504 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3505 });
3506 }
3507
3508 fn find_possible_emoji_shortcode_at_position(
3509 snapshot: &MultiBufferSnapshot,
3510 position: Point,
3511 ) -> Option<String> {
3512 let mut chars = Vec::new();
3513 let mut found_colon = false;
3514 for char in snapshot.reversed_chars_at(position).take(100) {
3515 // Found a possible emoji shortcode in the middle of the buffer
3516 if found_colon {
3517 if char.is_whitespace() {
3518 chars.reverse();
3519 return Some(chars.iter().collect());
3520 }
3521 // If the previous character is not a whitespace, we are in the middle of a word
3522 // and we only want to complete the shortcode if the word is made up of other emojis
3523 let mut containing_word = String::new();
3524 for ch in snapshot
3525 .reversed_chars_at(position)
3526 .skip(chars.len() + 1)
3527 .take(100)
3528 {
3529 if ch.is_whitespace() {
3530 break;
3531 }
3532 containing_word.push(ch);
3533 }
3534 let containing_word = containing_word.chars().rev().collect::<String>();
3535 if util::word_consists_of_emojis(containing_word.as_str()) {
3536 chars.reverse();
3537 return Some(chars.iter().collect());
3538 }
3539 }
3540
3541 if char.is_whitespace() || !char.is_ascii() {
3542 return None;
3543 }
3544 if char == ':' {
3545 found_colon = true;
3546 } else {
3547 chars.push(char);
3548 }
3549 }
3550 // Found a possible emoji shortcode at the beginning of the buffer
3551 chars.reverse();
3552 Some(chars.iter().collect())
3553 }
3554
3555 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3556 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3557 self.transact(window, cx, |this, window, cx| {
3558 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3559 let selections = this.selections.all::<usize>(cx);
3560 let multi_buffer = this.buffer.read(cx);
3561 let buffer = multi_buffer.snapshot(cx);
3562 selections
3563 .iter()
3564 .map(|selection| {
3565 let start_point = selection.start.to_point(&buffer);
3566 let mut indent =
3567 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3568 indent.len = cmp::min(indent.len, start_point.column);
3569 let start = selection.start;
3570 let end = selection.end;
3571 let selection_is_empty = start == end;
3572 let language_scope = buffer.language_scope_at(start);
3573 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3574 &language_scope
3575 {
3576 let insert_extra_newline =
3577 insert_extra_newline_brackets(&buffer, start..end, language)
3578 || insert_extra_newline_tree_sitter(&buffer, start..end);
3579
3580 // Comment extension on newline is allowed only for cursor selections
3581 let comment_delimiter = maybe!({
3582 if !selection_is_empty {
3583 return None;
3584 }
3585
3586 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3587 return None;
3588 }
3589
3590 let delimiters = language.line_comment_prefixes();
3591 let max_len_of_delimiter =
3592 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3593 let (snapshot, range) =
3594 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3595
3596 let mut index_of_first_non_whitespace = 0;
3597 let comment_candidate = snapshot
3598 .chars_for_range(range)
3599 .skip_while(|c| {
3600 let should_skip = c.is_whitespace();
3601 if should_skip {
3602 index_of_first_non_whitespace += 1;
3603 }
3604 should_skip
3605 })
3606 .take(max_len_of_delimiter)
3607 .collect::<String>();
3608 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3609 comment_candidate.starts_with(comment_prefix.as_ref())
3610 })?;
3611 let cursor_is_placed_after_comment_marker =
3612 index_of_first_non_whitespace + comment_prefix.len()
3613 <= start_point.column as usize;
3614 if cursor_is_placed_after_comment_marker {
3615 Some(comment_prefix.clone())
3616 } else {
3617 None
3618 }
3619 });
3620 (comment_delimiter, insert_extra_newline)
3621 } else {
3622 (None, false)
3623 };
3624
3625 let capacity_for_delimiter = comment_delimiter
3626 .as_deref()
3627 .map(str::len)
3628 .unwrap_or_default();
3629 let mut new_text =
3630 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3631 new_text.push('\n');
3632 new_text.extend(indent.chars());
3633 if let Some(delimiter) = &comment_delimiter {
3634 new_text.push_str(delimiter);
3635 }
3636 if insert_extra_newline {
3637 new_text = new_text.repeat(2);
3638 }
3639
3640 let anchor = buffer.anchor_after(end);
3641 let new_selection = selection.map(|_| anchor);
3642 (
3643 (start..end, new_text),
3644 (insert_extra_newline, new_selection),
3645 )
3646 })
3647 .unzip()
3648 };
3649
3650 this.edit_with_autoindent(edits, cx);
3651 let buffer = this.buffer.read(cx).snapshot(cx);
3652 let new_selections = selection_fixup_info
3653 .into_iter()
3654 .map(|(extra_newline_inserted, new_selection)| {
3655 let mut cursor = new_selection.end.to_point(&buffer);
3656 if extra_newline_inserted {
3657 cursor.row -= 1;
3658 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3659 }
3660 new_selection.map(|_| cursor)
3661 })
3662 .collect();
3663
3664 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3665 s.select(new_selections)
3666 });
3667 this.refresh_inline_completion(true, false, window, cx);
3668 });
3669 }
3670
3671 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3672 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3673
3674 let buffer = self.buffer.read(cx);
3675 let snapshot = buffer.snapshot(cx);
3676
3677 let mut edits = Vec::new();
3678 let mut rows = Vec::new();
3679
3680 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3681 let cursor = selection.head();
3682 let row = cursor.row;
3683
3684 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3685
3686 let newline = "\n".to_string();
3687 edits.push((start_of_line..start_of_line, newline));
3688
3689 rows.push(row + rows_inserted as u32);
3690 }
3691
3692 self.transact(window, cx, |editor, window, cx| {
3693 editor.edit(edits, cx);
3694
3695 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3696 let mut index = 0;
3697 s.move_cursors_with(|map, _, _| {
3698 let row = rows[index];
3699 index += 1;
3700
3701 let point = Point::new(row, 0);
3702 let boundary = map.next_line_boundary(point).1;
3703 let clipped = map.clip_point(boundary, Bias::Left);
3704
3705 (clipped, SelectionGoal::None)
3706 });
3707 });
3708
3709 let mut indent_edits = Vec::new();
3710 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3711 for row in rows {
3712 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3713 for (row, indent) in indents {
3714 if indent.len == 0 {
3715 continue;
3716 }
3717
3718 let text = match indent.kind {
3719 IndentKind::Space => " ".repeat(indent.len as usize),
3720 IndentKind::Tab => "\t".repeat(indent.len as usize),
3721 };
3722 let point = Point::new(row.0, 0);
3723 indent_edits.push((point..point, text));
3724 }
3725 }
3726 editor.edit(indent_edits, cx);
3727 });
3728 }
3729
3730 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3731 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3732
3733 let buffer = self.buffer.read(cx);
3734 let snapshot = buffer.snapshot(cx);
3735
3736 let mut edits = Vec::new();
3737 let mut rows = Vec::new();
3738 let mut rows_inserted = 0;
3739
3740 for selection in self.selections.all_adjusted(cx) {
3741 let cursor = selection.head();
3742 let row = cursor.row;
3743
3744 let point = Point::new(row + 1, 0);
3745 let start_of_line = snapshot.clip_point(point, Bias::Left);
3746
3747 let newline = "\n".to_string();
3748 edits.push((start_of_line..start_of_line, newline));
3749
3750 rows_inserted += 1;
3751 rows.push(row + rows_inserted);
3752 }
3753
3754 self.transact(window, cx, |editor, window, cx| {
3755 editor.edit(edits, cx);
3756
3757 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3758 let mut index = 0;
3759 s.move_cursors_with(|map, _, _| {
3760 let row = rows[index];
3761 index += 1;
3762
3763 let point = Point::new(row, 0);
3764 let boundary = map.next_line_boundary(point).1;
3765 let clipped = map.clip_point(boundary, Bias::Left);
3766
3767 (clipped, SelectionGoal::None)
3768 });
3769 });
3770
3771 let mut indent_edits = Vec::new();
3772 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3773 for row in rows {
3774 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3775 for (row, indent) in indents {
3776 if indent.len == 0 {
3777 continue;
3778 }
3779
3780 let text = match indent.kind {
3781 IndentKind::Space => " ".repeat(indent.len as usize),
3782 IndentKind::Tab => "\t".repeat(indent.len as usize),
3783 };
3784 let point = Point::new(row.0, 0);
3785 indent_edits.push((point..point, text));
3786 }
3787 }
3788 editor.edit(indent_edits, cx);
3789 });
3790 }
3791
3792 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3793 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3794 original_indent_columns: Vec::new(),
3795 });
3796 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3797 }
3798
3799 fn insert_with_autoindent_mode(
3800 &mut self,
3801 text: &str,
3802 autoindent_mode: Option<AutoindentMode>,
3803 window: &mut Window,
3804 cx: &mut Context<Self>,
3805 ) {
3806 if self.read_only(cx) {
3807 return;
3808 }
3809
3810 let text: Arc<str> = text.into();
3811 self.transact(window, cx, |this, window, cx| {
3812 let old_selections = this.selections.all_adjusted(cx);
3813 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3814 let anchors = {
3815 let snapshot = buffer.read(cx);
3816 old_selections
3817 .iter()
3818 .map(|s| {
3819 let anchor = snapshot.anchor_after(s.head());
3820 s.map(|_| anchor)
3821 })
3822 .collect::<Vec<_>>()
3823 };
3824 buffer.edit(
3825 old_selections
3826 .iter()
3827 .map(|s| (s.start..s.end, text.clone())),
3828 autoindent_mode,
3829 cx,
3830 );
3831 anchors
3832 });
3833
3834 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3835 s.select_anchors(selection_anchors);
3836 });
3837
3838 cx.notify();
3839 });
3840 }
3841
3842 fn trigger_completion_on_input(
3843 &mut self,
3844 text: &str,
3845 trigger_in_words: bool,
3846 window: &mut Window,
3847 cx: &mut Context<Self>,
3848 ) {
3849 let ignore_completion_provider = self
3850 .context_menu
3851 .borrow()
3852 .as_ref()
3853 .map(|menu| match menu {
3854 CodeContextMenu::Completions(completions_menu) => {
3855 completions_menu.ignore_completion_provider
3856 }
3857 CodeContextMenu::CodeActions(_) => false,
3858 })
3859 .unwrap_or(false);
3860
3861 if ignore_completion_provider {
3862 self.show_word_completions(&ShowWordCompletions, window, cx);
3863 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3864 self.show_completions(
3865 &ShowCompletions {
3866 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3867 },
3868 window,
3869 cx,
3870 );
3871 } else {
3872 self.hide_context_menu(window, cx);
3873 }
3874 }
3875
3876 fn is_completion_trigger(
3877 &self,
3878 text: &str,
3879 trigger_in_words: bool,
3880 cx: &mut Context<Self>,
3881 ) -> bool {
3882 let position = self.selections.newest_anchor().head();
3883 let multibuffer = self.buffer.read(cx);
3884 let Some(buffer) = position
3885 .buffer_id
3886 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3887 else {
3888 return false;
3889 };
3890
3891 if let Some(completion_provider) = &self.completion_provider {
3892 completion_provider.is_completion_trigger(
3893 &buffer,
3894 position.text_anchor,
3895 text,
3896 trigger_in_words,
3897 cx,
3898 )
3899 } else {
3900 false
3901 }
3902 }
3903
3904 /// If any empty selections is touching the start of its innermost containing autoclose
3905 /// region, expand it to select the brackets.
3906 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3907 let selections = self.selections.all::<usize>(cx);
3908 let buffer = self.buffer.read(cx).read(cx);
3909 let new_selections = self
3910 .selections_with_autoclose_regions(selections, &buffer)
3911 .map(|(mut selection, region)| {
3912 if !selection.is_empty() {
3913 return selection;
3914 }
3915
3916 if let Some(region) = region {
3917 let mut range = region.range.to_offset(&buffer);
3918 if selection.start == range.start && range.start >= region.pair.start.len() {
3919 range.start -= region.pair.start.len();
3920 if buffer.contains_str_at(range.start, ®ion.pair.start)
3921 && buffer.contains_str_at(range.end, ®ion.pair.end)
3922 {
3923 range.end += region.pair.end.len();
3924 selection.start = range.start;
3925 selection.end = range.end;
3926
3927 return selection;
3928 }
3929 }
3930 }
3931
3932 let always_treat_brackets_as_autoclosed = buffer
3933 .language_settings_at(selection.start, cx)
3934 .always_treat_brackets_as_autoclosed;
3935
3936 if !always_treat_brackets_as_autoclosed {
3937 return selection;
3938 }
3939
3940 if let Some(scope) = buffer.language_scope_at(selection.start) {
3941 for (pair, enabled) in scope.brackets() {
3942 if !enabled || !pair.close {
3943 continue;
3944 }
3945
3946 if buffer.contains_str_at(selection.start, &pair.end) {
3947 let pair_start_len = pair.start.len();
3948 if buffer.contains_str_at(
3949 selection.start.saturating_sub(pair_start_len),
3950 &pair.start,
3951 ) {
3952 selection.start -= pair_start_len;
3953 selection.end += pair.end.len();
3954
3955 return selection;
3956 }
3957 }
3958 }
3959 }
3960
3961 selection
3962 })
3963 .collect();
3964
3965 drop(buffer);
3966 self.change_selections(None, window, cx, |selections| {
3967 selections.select(new_selections)
3968 });
3969 }
3970
3971 /// Iterate the given selections, and for each one, find the smallest surrounding
3972 /// autoclose region. This uses the ordering of the selections and the autoclose
3973 /// regions to avoid repeated comparisons.
3974 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3975 &'a self,
3976 selections: impl IntoIterator<Item = Selection<D>>,
3977 buffer: &'a MultiBufferSnapshot,
3978 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3979 let mut i = 0;
3980 let mut regions = self.autoclose_regions.as_slice();
3981 selections.into_iter().map(move |selection| {
3982 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3983
3984 let mut enclosing = None;
3985 while let Some(pair_state) = regions.get(i) {
3986 if pair_state.range.end.to_offset(buffer) < range.start {
3987 regions = ®ions[i + 1..];
3988 i = 0;
3989 } else if pair_state.range.start.to_offset(buffer) > range.end {
3990 break;
3991 } else {
3992 if pair_state.selection_id == selection.id {
3993 enclosing = Some(pair_state);
3994 }
3995 i += 1;
3996 }
3997 }
3998
3999 (selection, enclosing)
4000 })
4001 }
4002
4003 /// Remove any autoclose regions that no longer contain their selection.
4004 fn invalidate_autoclose_regions(
4005 &mut self,
4006 mut selections: &[Selection<Anchor>],
4007 buffer: &MultiBufferSnapshot,
4008 ) {
4009 self.autoclose_regions.retain(|state| {
4010 let mut i = 0;
4011 while let Some(selection) = selections.get(i) {
4012 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4013 selections = &selections[1..];
4014 continue;
4015 }
4016 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4017 break;
4018 }
4019 if selection.id == state.selection_id {
4020 return true;
4021 } else {
4022 i += 1;
4023 }
4024 }
4025 false
4026 });
4027 }
4028
4029 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4030 let offset = position.to_offset(buffer);
4031 let (word_range, kind) = buffer.surrounding_word(offset, true);
4032 if offset > word_range.start && kind == Some(CharKind::Word) {
4033 Some(
4034 buffer
4035 .text_for_range(word_range.start..offset)
4036 .collect::<String>(),
4037 )
4038 } else {
4039 None
4040 }
4041 }
4042
4043 pub fn toggle_inlay_hints(
4044 &mut self,
4045 _: &ToggleInlayHints,
4046 _: &mut Window,
4047 cx: &mut Context<Self>,
4048 ) {
4049 self.refresh_inlay_hints(
4050 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4051 cx,
4052 );
4053 }
4054
4055 pub fn inlay_hints_enabled(&self) -> bool {
4056 self.inlay_hint_cache.enabled
4057 }
4058
4059 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4060 if self.semantics_provider.is_none() || !self.mode.is_full() {
4061 return;
4062 }
4063
4064 let reason_description = reason.description();
4065 let ignore_debounce = matches!(
4066 reason,
4067 InlayHintRefreshReason::SettingsChange(_)
4068 | InlayHintRefreshReason::Toggle(_)
4069 | InlayHintRefreshReason::ExcerptsRemoved(_)
4070 | InlayHintRefreshReason::ModifiersChanged(_)
4071 );
4072 let (invalidate_cache, required_languages) = match reason {
4073 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4074 match self.inlay_hint_cache.modifiers_override(enabled) {
4075 Some(enabled) => {
4076 if enabled {
4077 (InvalidationStrategy::RefreshRequested, None)
4078 } else {
4079 self.splice_inlays(
4080 &self
4081 .visible_inlay_hints(cx)
4082 .iter()
4083 .map(|inlay| inlay.id)
4084 .collect::<Vec<InlayId>>(),
4085 Vec::new(),
4086 cx,
4087 );
4088 return;
4089 }
4090 }
4091 None => return,
4092 }
4093 }
4094 InlayHintRefreshReason::Toggle(enabled) => {
4095 if self.inlay_hint_cache.toggle(enabled) {
4096 if enabled {
4097 (InvalidationStrategy::RefreshRequested, None)
4098 } else {
4099 self.splice_inlays(
4100 &self
4101 .visible_inlay_hints(cx)
4102 .iter()
4103 .map(|inlay| inlay.id)
4104 .collect::<Vec<InlayId>>(),
4105 Vec::new(),
4106 cx,
4107 );
4108 return;
4109 }
4110 } else {
4111 return;
4112 }
4113 }
4114 InlayHintRefreshReason::SettingsChange(new_settings) => {
4115 match self.inlay_hint_cache.update_settings(
4116 &self.buffer,
4117 new_settings,
4118 self.visible_inlay_hints(cx),
4119 cx,
4120 ) {
4121 ControlFlow::Break(Some(InlaySplice {
4122 to_remove,
4123 to_insert,
4124 })) => {
4125 self.splice_inlays(&to_remove, to_insert, cx);
4126 return;
4127 }
4128 ControlFlow::Break(None) => return,
4129 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4130 }
4131 }
4132 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4133 if let Some(InlaySplice {
4134 to_remove,
4135 to_insert,
4136 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4137 {
4138 self.splice_inlays(&to_remove, to_insert, cx);
4139 }
4140 self.display_map.update(cx, |display_map, _| {
4141 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4142 });
4143 return;
4144 }
4145 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4146 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4147 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4148 }
4149 InlayHintRefreshReason::RefreshRequested => {
4150 (InvalidationStrategy::RefreshRequested, None)
4151 }
4152 };
4153
4154 if let Some(InlaySplice {
4155 to_remove,
4156 to_insert,
4157 }) = self.inlay_hint_cache.spawn_hint_refresh(
4158 reason_description,
4159 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4160 invalidate_cache,
4161 ignore_debounce,
4162 cx,
4163 ) {
4164 self.splice_inlays(&to_remove, to_insert, cx);
4165 }
4166 }
4167
4168 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4169 self.display_map
4170 .read(cx)
4171 .current_inlays()
4172 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4173 .cloned()
4174 .collect()
4175 }
4176
4177 pub fn excerpts_for_inlay_hints_query(
4178 &self,
4179 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4180 cx: &mut Context<Editor>,
4181 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4182 let Some(project) = self.project.as_ref() else {
4183 return HashMap::default();
4184 };
4185 let project = project.read(cx);
4186 let multi_buffer = self.buffer().read(cx);
4187 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4188 let multi_buffer_visible_start = self
4189 .scroll_manager
4190 .anchor()
4191 .anchor
4192 .to_point(&multi_buffer_snapshot);
4193 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4194 multi_buffer_visible_start
4195 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4196 Bias::Left,
4197 );
4198 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4199 multi_buffer_snapshot
4200 .range_to_buffer_ranges(multi_buffer_visible_range)
4201 .into_iter()
4202 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4203 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4204 let buffer_file = project::File::from_dyn(buffer.file())?;
4205 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4206 let worktree_entry = buffer_worktree
4207 .read(cx)
4208 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4209 if worktree_entry.is_ignored {
4210 return None;
4211 }
4212
4213 let language = buffer.language()?;
4214 if let Some(restrict_to_languages) = restrict_to_languages {
4215 if !restrict_to_languages.contains(language) {
4216 return None;
4217 }
4218 }
4219 Some((
4220 excerpt_id,
4221 (
4222 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4223 buffer.version().clone(),
4224 excerpt_visible_range,
4225 ),
4226 ))
4227 })
4228 .collect()
4229 }
4230
4231 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4232 TextLayoutDetails {
4233 text_system: window.text_system().clone(),
4234 editor_style: self.style.clone().unwrap(),
4235 rem_size: window.rem_size(),
4236 scroll_anchor: self.scroll_manager.anchor(),
4237 visible_rows: self.visible_line_count(),
4238 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4239 }
4240 }
4241
4242 pub fn splice_inlays(
4243 &self,
4244 to_remove: &[InlayId],
4245 to_insert: Vec<Inlay>,
4246 cx: &mut Context<Self>,
4247 ) {
4248 self.display_map.update(cx, |display_map, cx| {
4249 display_map.splice_inlays(to_remove, to_insert, cx)
4250 });
4251 cx.notify();
4252 }
4253
4254 fn trigger_on_type_formatting(
4255 &self,
4256 input: String,
4257 window: &mut Window,
4258 cx: &mut Context<Self>,
4259 ) -> Option<Task<Result<()>>> {
4260 if input.len() != 1 {
4261 return None;
4262 }
4263
4264 let project = self.project.as_ref()?;
4265 let position = self.selections.newest_anchor().head();
4266 let (buffer, buffer_position) = self
4267 .buffer
4268 .read(cx)
4269 .text_anchor_for_position(position, cx)?;
4270
4271 let settings = language_settings::language_settings(
4272 buffer
4273 .read(cx)
4274 .language_at(buffer_position)
4275 .map(|l| l.name()),
4276 buffer.read(cx).file(),
4277 cx,
4278 );
4279 if !settings.use_on_type_format {
4280 return None;
4281 }
4282
4283 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4284 // hence we do LSP request & edit on host side only — add formats to host's history.
4285 let push_to_lsp_host_history = true;
4286 // If this is not the host, append its history with new edits.
4287 let push_to_client_history = project.read(cx).is_via_collab();
4288
4289 let on_type_formatting = project.update(cx, |project, cx| {
4290 project.on_type_format(
4291 buffer.clone(),
4292 buffer_position,
4293 input,
4294 push_to_lsp_host_history,
4295 cx,
4296 )
4297 });
4298 Some(cx.spawn_in(window, async move |editor, cx| {
4299 if let Some(transaction) = on_type_formatting.await? {
4300 if push_to_client_history {
4301 buffer
4302 .update(cx, |buffer, _| {
4303 buffer.push_transaction(transaction, Instant::now());
4304 buffer.finalize_last_transaction();
4305 })
4306 .ok();
4307 }
4308 editor.update(cx, |editor, cx| {
4309 editor.refresh_document_highlights(cx);
4310 })?;
4311 }
4312 Ok(())
4313 }))
4314 }
4315
4316 pub fn show_word_completions(
4317 &mut self,
4318 _: &ShowWordCompletions,
4319 window: &mut Window,
4320 cx: &mut Context<Self>,
4321 ) {
4322 self.open_completions_menu(true, None, window, cx);
4323 }
4324
4325 pub fn show_completions(
4326 &mut self,
4327 options: &ShowCompletions,
4328 window: &mut Window,
4329 cx: &mut Context<Self>,
4330 ) {
4331 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4332 }
4333
4334 fn open_completions_menu(
4335 &mut self,
4336 ignore_completion_provider: bool,
4337 trigger: Option<&str>,
4338 window: &mut Window,
4339 cx: &mut Context<Self>,
4340 ) {
4341 if self.pending_rename.is_some() {
4342 return;
4343 }
4344 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4345 return;
4346 }
4347
4348 let position = self.selections.newest_anchor().head();
4349 if position.diff_base_anchor.is_some() {
4350 return;
4351 }
4352 let (buffer, buffer_position) =
4353 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4354 output
4355 } else {
4356 return;
4357 };
4358 let buffer_snapshot = buffer.read(cx).snapshot();
4359 let show_completion_documentation = buffer_snapshot
4360 .settings_at(buffer_position, cx)
4361 .show_completion_documentation;
4362
4363 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4364
4365 let trigger_kind = match trigger {
4366 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4367 CompletionTriggerKind::TRIGGER_CHARACTER
4368 }
4369 _ => CompletionTriggerKind::INVOKED,
4370 };
4371 let completion_context = CompletionContext {
4372 trigger_character: trigger.and_then(|trigger| {
4373 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4374 Some(String::from(trigger))
4375 } else {
4376 None
4377 }
4378 }),
4379 trigger_kind,
4380 };
4381
4382 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4383 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4384 let word_to_exclude = buffer_snapshot
4385 .text_for_range(old_range.clone())
4386 .collect::<String>();
4387 (
4388 buffer_snapshot.anchor_before(old_range.start)
4389 ..buffer_snapshot.anchor_after(old_range.end),
4390 Some(word_to_exclude),
4391 )
4392 } else {
4393 (buffer_position..buffer_position, None)
4394 };
4395
4396 let completion_settings = language_settings(
4397 buffer_snapshot
4398 .language_at(buffer_position)
4399 .map(|language| language.name()),
4400 buffer_snapshot.file(),
4401 cx,
4402 )
4403 .completions;
4404
4405 // The document can be large, so stay in reasonable bounds when searching for words,
4406 // otherwise completion pop-up might be slow to appear.
4407 const WORD_LOOKUP_ROWS: u32 = 5_000;
4408 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4409 let min_word_search = buffer_snapshot.clip_point(
4410 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4411 Bias::Left,
4412 );
4413 let max_word_search = buffer_snapshot.clip_point(
4414 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4415 Bias::Right,
4416 );
4417 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4418 ..buffer_snapshot.point_to_offset(max_word_search);
4419
4420 let provider = self
4421 .completion_provider
4422 .as_ref()
4423 .filter(|_| !ignore_completion_provider);
4424 let skip_digits = query
4425 .as_ref()
4426 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4427
4428 let (mut words, provided_completions) = match provider {
4429 Some(provider) => {
4430 let completions = provider.completions(
4431 position.excerpt_id,
4432 &buffer,
4433 buffer_position,
4434 completion_context,
4435 window,
4436 cx,
4437 );
4438
4439 let words = match completion_settings.words {
4440 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4441 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4442 .background_spawn(async move {
4443 buffer_snapshot.words_in_range(WordsQuery {
4444 fuzzy_contents: None,
4445 range: word_search_range,
4446 skip_digits,
4447 })
4448 }),
4449 };
4450
4451 (words, completions)
4452 }
4453 None => (
4454 cx.background_spawn(async move {
4455 buffer_snapshot.words_in_range(WordsQuery {
4456 fuzzy_contents: None,
4457 range: word_search_range,
4458 skip_digits,
4459 })
4460 }),
4461 Task::ready(Ok(None)),
4462 ),
4463 };
4464
4465 let sort_completions = provider
4466 .as_ref()
4467 .map_or(false, |provider| provider.sort_completions());
4468
4469 let filter_completions = provider
4470 .as_ref()
4471 .map_or(true, |provider| provider.filter_completions());
4472
4473 let id = post_inc(&mut self.next_completion_id);
4474 let task = cx.spawn_in(window, async move |editor, cx| {
4475 async move {
4476 editor.update(cx, |this, _| {
4477 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4478 })?;
4479
4480 let mut completions = Vec::new();
4481 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4482 completions.extend(provided_completions);
4483 if completion_settings.words == WordsCompletionMode::Fallback {
4484 words = Task::ready(BTreeMap::default());
4485 }
4486 }
4487
4488 let mut words = words.await;
4489 if let Some(word_to_exclude) = &word_to_exclude {
4490 words.remove(word_to_exclude);
4491 }
4492 for lsp_completion in &completions {
4493 words.remove(&lsp_completion.new_text);
4494 }
4495 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4496 replace_range: old_range.clone(),
4497 new_text: word.clone(),
4498 label: CodeLabel::plain(word, None),
4499 icon_path: None,
4500 documentation: None,
4501 source: CompletionSource::BufferWord {
4502 word_range,
4503 resolved: false,
4504 },
4505 insert_text_mode: Some(InsertTextMode::AS_IS),
4506 confirm: None,
4507 }));
4508
4509 let menu = if completions.is_empty() {
4510 None
4511 } else {
4512 let mut menu = CompletionsMenu::new(
4513 id,
4514 sort_completions,
4515 show_completion_documentation,
4516 ignore_completion_provider,
4517 position,
4518 buffer.clone(),
4519 completions.into(),
4520 );
4521
4522 menu.filter(
4523 if filter_completions {
4524 query.as_deref()
4525 } else {
4526 None
4527 },
4528 cx.background_executor().clone(),
4529 )
4530 .await;
4531
4532 menu.visible().then_some(menu)
4533 };
4534
4535 editor.update_in(cx, |editor, window, cx| {
4536 match editor.context_menu.borrow().as_ref() {
4537 None => {}
4538 Some(CodeContextMenu::Completions(prev_menu)) => {
4539 if prev_menu.id > id {
4540 return;
4541 }
4542 }
4543 _ => return,
4544 }
4545
4546 if editor.focus_handle.is_focused(window) && menu.is_some() {
4547 let mut menu = menu.unwrap();
4548 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4549
4550 *editor.context_menu.borrow_mut() =
4551 Some(CodeContextMenu::Completions(menu));
4552
4553 if editor.show_edit_predictions_in_menu() {
4554 editor.update_visible_inline_completion(window, cx);
4555 } else {
4556 editor.discard_inline_completion(false, cx);
4557 }
4558
4559 cx.notify();
4560 } else if editor.completion_tasks.len() <= 1 {
4561 // If there are no more completion tasks and the last menu was
4562 // empty, we should hide it.
4563 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4564 // If it was already hidden and we don't show inline
4565 // completions in the menu, we should also show the
4566 // inline-completion when available.
4567 if was_hidden && editor.show_edit_predictions_in_menu() {
4568 editor.update_visible_inline_completion(window, cx);
4569 }
4570 }
4571 })?;
4572
4573 anyhow::Ok(())
4574 }
4575 .log_err()
4576 .await
4577 });
4578
4579 self.completion_tasks.push((id, task));
4580 }
4581
4582 #[cfg(feature = "test-support")]
4583 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4584 let menu = self.context_menu.borrow();
4585 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4586 let completions = menu.completions.borrow();
4587 Some(completions.to_vec())
4588 } else {
4589 None
4590 }
4591 }
4592
4593 pub fn confirm_completion(
4594 &mut self,
4595 action: &ConfirmCompletion,
4596 window: &mut Window,
4597 cx: &mut Context<Self>,
4598 ) -> Option<Task<Result<()>>> {
4599 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4600 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4601 }
4602
4603 pub fn confirm_completion_insert(
4604 &mut self,
4605 _: &ConfirmCompletionInsert,
4606 window: &mut Window,
4607 cx: &mut Context<Self>,
4608 ) -> Option<Task<Result<()>>> {
4609 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4610 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4611 }
4612
4613 pub fn confirm_completion_replace(
4614 &mut self,
4615 _: &ConfirmCompletionReplace,
4616 window: &mut Window,
4617 cx: &mut Context<Self>,
4618 ) -> Option<Task<Result<()>>> {
4619 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4620 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4621 }
4622
4623 pub fn compose_completion(
4624 &mut self,
4625 action: &ComposeCompletion,
4626 window: &mut Window,
4627 cx: &mut Context<Self>,
4628 ) -> Option<Task<Result<()>>> {
4629 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4630 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4631 }
4632
4633 fn do_completion(
4634 &mut self,
4635 item_ix: Option<usize>,
4636 intent: CompletionIntent,
4637 window: &mut Window,
4638 cx: &mut Context<Editor>,
4639 ) -> Option<Task<Result<()>>> {
4640 use language::ToOffset as _;
4641
4642 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4643 else {
4644 return None;
4645 };
4646
4647 let candidate_id = {
4648 let entries = completions_menu.entries.borrow();
4649 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4650 if self.show_edit_predictions_in_menu() {
4651 self.discard_inline_completion(true, cx);
4652 }
4653 mat.candidate_id
4654 };
4655
4656 let buffer_handle = completions_menu.buffer;
4657 let completion = completions_menu
4658 .completions
4659 .borrow()
4660 .get(candidate_id)?
4661 .clone();
4662 cx.stop_propagation();
4663
4664 let snippet;
4665 let new_text;
4666 if completion.is_snippet() {
4667 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4668 new_text = snippet.as_ref().unwrap().text.clone();
4669 } else {
4670 snippet = None;
4671 new_text = completion.new_text.clone();
4672 };
4673 let selections = self.selections.all::<usize>(cx);
4674
4675 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4676 let buffer = buffer_handle.read(cx);
4677 let old_text = buffer
4678 .text_for_range(replace_range.clone())
4679 .collect::<String>();
4680
4681 let newest_selection = self.selections.newest_anchor();
4682 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4683 return None;
4684 }
4685
4686 let lookbehind = newest_selection
4687 .start
4688 .text_anchor
4689 .to_offset(buffer)
4690 .saturating_sub(replace_range.start);
4691 let lookahead = replace_range
4692 .end
4693 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4694 let mut common_prefix_len = 0;
4695 for (a, b) in old_text.chars().zip(new_text.chars()) {
4696 if a == b {
4697 common_prefix_len += a.len_utf8();
4698 } else {
4699 break;
4700 }
4701 }
4702
4703 let snapshot = self.buffer.read(cx).snapshot(cx);
4704 let mut range_to_replace: Option<Range<usize>> = None;
4705 let mut ranges = Vec::new();
4706 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4707 for selection in &selections {
4708 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4709 let start = selection.start.saturating_sub(lookbehind);
4710 let end = selection.end + lookahead;
4711 if selection.id == newest_selection.id {
4712 range_to_replace = Some(start + common_prefix_len..end);
4713 }
4714 ranges.push(start + common_prefix_len..end);
4715 } else {
4716 common_prefix_len = 0;
4717 ranges.clear();
4718 ranges.extend(selections.iter().map(|s| {
4719 if s.id == newest_selection.id {
4720 range_to_replace = Some(replace_range.clone());
4721 replace_range.clone()
4722 } else {
4723 s.start..s.end
4724 }
4725 }));
4726 break;
4727 }
4728 if !self.linked_edit_ranges.is_empty() {
4729 let start_anchor = snapshot.anchor_before(selection.head());
4730 let end_anchor = snapshot.anchor_after(selection.tail());
4731 if let Some(ranges) = self
4732 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4733 {
4734 for (buffer, edits) in ranges {
4735 linked_edits.entry(buffer.clone()).or_default().extend(
4736 edits
4737 .into_iter()
4738 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4739 );
4740 }
4741 }
4742 }
4743 }
4744 let text = &new_text[common_prefix_len..];
4745
4746 let utf16_range_to_replace = range_to_replace.map(|range| {
4747 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4748 let selection_start_utf16 = newest_selection.start.0 as isize;
4749
4750 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4751 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4752 });
4753 cx.emit(EditorEvent::InputHandled {
4754 utf16_range_to_replace,
4755 text: text.into(),
4756 });
4757
4758 self.transact(window, cx, |this, window, cx| {
4759 if let Some(mut snippet) = snippet {
4760 snippet.text = text.to_string();
4761 for tabstop in snippet
4762 .tabstops
4763 .iter_mut()
4764 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4765 {
4766 tabstop.start -= common_prefix_len as isize;
4767 tabstop.end -= common_prefix_len as isize;
4768 }
4769
4770 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4771 } else {
4772 this.buffer.update(cx, |buffer, cx| {
4773 let edits = ranges.iter().map(|range| (range.clone(), text));
4774 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4775 {
4776 None
4777 } else {
4778 this.autoindent_mode.clone()
4779 };
4780 buffer.edit(edits, auto_indent, cx);
4781 });
4782 }
4783 for (buffer, edits) in linked_edits {
4784 buffer.update(cx, |buffer, cx| {
4785 let snapshot = buffer.snapshot();
4786 let edits = edits
4787 .into_iter()
4788 .map(|(range, text)| {
4789 use text::ToPoint as TP;
4790 let end_point = TP::to_point(&range.end, &snapshot);
4791 let start_point = TP::to_point(&range.start, &snapshot);
4792 (start_point..end_point, text)
4793 })
4794 .sorted_by_key(|(range, _)| range.start);
4795 buffer.edit(edits, None, cx);
4796 })
4797 }
4798
4799 this.refresh_inline_completion(true, false, window, cx);
4800 });
4801
4802 let show_new_completions_on_confirm = completion
4803 .confirm
4804 .as_ref()
4805 .map_or(false, |confirm| confirm(intent, window, cx));
4806 if show_new_completions_on_confirm {
4807 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4808 }
4809
4810 let provider = self.completion_provider.as_ref()?;
4811 drop(completion);
4812 let apply_edits = provider.apply_additional_edits_for_completion(
4813 buffer_handle,
4814 completions_menu.completions.clone(),
4815 candidate_id,
4816 true,
4817 cx,
4818 );
4819
4820 let editor_settings = EditorSettings::get_global(cx);
4821 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4822 // After the code completion is finished, users often want to know what signatures are needed.
4823 // so we should automatically call signature_help
4824 self.show_signature_help(&ShowSignatureHelp, window, cx);
4825 }
4826
4827 Some(cx.foreground_executor().spawn(async move {
4828 apply_edits.await?;
4829 Ok(())
4830 }))
4831 }
4832
4833 pub fn toggle_code_actions(
4834 &mut self,
4835 action: &ToggleCodeActions,
4836 window: &mut Window,
4837 cx: &mut Context<Self>,
4838 ) {
4839 let mut context_menu = self.context_menu.borrow_mut();
4840 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4841 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4842 // Toggle if we're selecting the same one
4843 *context_menu = None;
4844 cx.notify();
4845 return;
4846 } else {
4847 // Otherwise, clear it and start a new one
4848 *context_menu = None;
4849 cx.notify();
4850 }
4851 }
4852 drop(context_menu);
4853 let snapshot = self.snapshot(window, cx);
4854 let deployed_from_indicator = action.deployed_from_indicator;
4855 let mut task = self.code_actions_task.take();
4856 let action = action.clone();
4857 cx.spawn_in(window, async move |editor, cx| {
4858 while let Some(prev_task) = task {
4859 prev_task.await.log_err();
4860 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4861 }
4862
4863 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4864 if editor.focus_handle.is_focused(window) {
4865 let multibuffer_point = action
4866 .deployed_from_indicator
4867 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4868 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4869 let (buffer, buffer_row) = snapshot
4870 .buffer_snapshot
4871 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4872 .and_then(|(buffer_snapshot, range)| {
4873 editor
4874 .buffer
4875 .read(cx)
4876 .buffer(buffer_snapshot.remote_id())
4877 .map(|buffer| (buffer, range.start.row))
4878 })?;
4879 let (_, code_actions) = editor
4880 .available_code_actions
4881 .clone()
4882 .and_then(|(location, code_actions)| {
4883 let snapshot = location.buffer.read(cx).snapshot();
4884 let point_range = location.range.to_point(&snapshot);
4885 let point_range = point_range.start.row..=point_range.end.row;
4886 if point_range.contains(&buffer_row) {
4887 Some((location, code_actions))
4888 } else {
4889 None
4890 }
4891 })
4892 .unzip();
4893 let buffer_id = buffer.read(cx).remote_id();
4894 let tasks = editor
4895 .tasks
4896 .get(&(buffer_id, buffer_row))
4897 .map(|t| Arc::new(t.to_owned()));
4898 if tasks.is_none() && code_actions.is_none() {
4899 return None;
4900 }
4901
4902 editor.completion_tasks.clear();
4903 editor.discard_inline_completion(false, cx);
4904 let task_context =
4905 tasks
4906 .as_ref()
4907 .zip(editor.project.clone())
4908 .map(|(tasks, project)| {
4909 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4910 });
4911
4912 let debugger_flag = cx.has_flag::<Debugger>();
4913
4914 Some(cx.spawn_in(window, async move |editor, cx| {
4915 let task_context = match task_context {
4916 Some(task_context) => task_context.await,
4917 None => None,
4918 };
4919 let resolved_tasks =
4920 tasks.zip(task_context).map(|(tasks, task_context)| {
4921 Rc::new(ResolvedTasks {
4922 templates: tasks.resolve(&task_context).collect(),
4923 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4924 multibuffer_point.row,
4925 tasks.column,
4926 )),
4927 })
4928 });
4929 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4930 tasks
4931 .templates
4932 .iter()
4933 .filter(|task| {
4934 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4935 debugger_flag
4936 } else {
4937 true
4938 }
4939 })
4940 .count()
4941 == 1
4942 }) && code_actions
4943 .as_ref()
4944 .map_or(true, |actions| actions.is_empty());
4945 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4946 *editor.context_menu.borrow_mut() =
4947 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4948 buffer,
4949 actions: CodeActionContents {
4950 tasks: resolved_tasks,
4951 actions: code_actions,
4952 },
4953 selected_item: Default::default(),
4954 scroll_handle: UniformListScrollHandle::default(),
4955 deployed_from_indicator,
4956 }));
4957 if spawn_straight_away {
4958 if let Some(task) = editor.confirm_code_action(
4959 &ConfirmCodeAction { item_ix: Some(0) },
4960 window,
4961 cx,
4962 ) {
4963 cx.notify();
4964 return task;
4965 }
4966 }
4967 cx.notify();
4968 Task::ready(Ok(()))
4969 }) {
4970 task.await
4971 } else {
4972 Ok(())
4973 }
4974 }))
4975 } else {
4976 Some(Task::ready(Ok(())))
4977 }
4978 })?;
4979 if let Some(task) = spawned_test_task {
4980 task.await?;
4981 }
4982
4983 Ok::<_, anyhow::Error>(())
4984 })
4985 .detach_and_log_err(cx);
4986 }
4987
4988 pub fn confirm_code_action(
4989 &mut self,
4990 action: &ConfirmCodeAction,
4991 window: &mut Window,
4992 cx: &mut Context<Self>,
4993 ) -> Option<Task<Result<()>>> {
4994 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4995
4996 let actions_menu =
4997 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4998 menu
4999 } else {
5000 return None;
5001 };
5002
5003 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5004 let action = actions_menu.actions.get(action_ix)?;
5005 let title = action.label();
5006 let buffer = actions_menu.buffer;
5007 let workspace = self.workspace()?;
5008
5009 match action {
5010 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5011 match resolved_task.task_type() {
5012 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5013 workspace::tasks::schedule_resolved_task(
5014 workspace,
5015 task_source_kind,
5016 resolved_task,
5017 false,
5018 cx,
5019 );
5020
5021 Some(Task::ready(Ok(())))
5022 }),
5023 task::TaskType::Debug(debug_args) => {
5024 if debug_args.locator.is_some() {
5025 workspace.update(cx, |workspace, cx| {
5026 workspace::tasks::schedule_resolved_task(
5027 workspace,
5028 task_source_kind,
5029 resolved_task,
5030 false,
5031 cx,
5032 );
5033 });
5034
5035 return Some(Task::ready(Ok(())));
5036 }
5037
5038 if let Some(project) = self.project.as_ref() {
5039 project
5040 .update(cx, |project, cx| {
5041 project.start_debug_session(
5042 resolved_task.resolved_debug_adapter_config().unwrap(),
5043 cx,
5044 )
5045 })
5046 .detach_and_log_err(cx);
5047 Some(Task::ready(Ok(())))
5048 } else {
5049 Some(Task::ready(Ok(())))
5050 }
5051 }
5052 }
5053 }
5054 CodeActionsItem::CodeAction {
5055 excerpt_id,
5056 action,
5057 provider,
5058 } => {
5059 let apply_code_action =
5060 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5061 let workspace = workspace.downgrade();
5062 Some(cx.spawn_in(window, async move |editor, cx| {
5063 let project_transaction = apply_code_action.await?;
5064 Self::open_project_transaction(
5065 &editor,
5066 workspace,
5067 project_transaction,
5068 title,
5069 cx,
5070 )
5071 .await
5072 }))
5073 }
5074 }
5075 }
5076
5077 pub async fn open_project_transaction(
5078 this: &WeakEntity<Editor>,
5079 workspace: WeakEntity<Workspace>,
5080 transaction: ProjectTransaction,
5081 title: String,
5082 cx: &mut AsyncWindowContext,
5083 ) -> Result<()> {
5084 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5085 cx.update(|_, cx| {
5086 entries.sort_unstable_by_key(|(buffer, _)| {
5087 buffer.read(cx).file().map(|f| f.path().clone())
5088 });
5089 })?;
5090
5091 // If the project transaction's edits are all contained within this editor, then
5092 // avoid opening a new editor to display them.
5093
5094 if let Some((buffer, transaction)) = entries.first() {
5095 if entries.len() == 1 {
5096 let excerpt = this.update(cx, |editor, cx| {
5097 editor
5098 .buffer()
5099 .read(cx)
5100 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5101 })?;
5102 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5103 if excerpted_buffer == *buffer {
5104 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5105 let excerpt_range = excerpt_range.to_offset(buffer);
5106 buffer
5107 .edited_ranges_for_transaction::<usize>(transaction)
5108 .all(|range| {
5109 excerpt_range.start <= range.start
5110 && excerpt_range.end >= range.end
5111 })
5112 })?;
5113
5114 if all_edits_within_excerpt {
5115 return Ok(());
5116 }
5117 }
5118 }
5119 }
5120 } else {
5121 return Ok(());
5122 }
5123
5124 let mut ranges_to_highlight = Vec::new();
5125 let excerpt_buffer = cx.new(|cx| {
5126 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5127 for (buffer_handle, transaction) in &entries {
5128 let edited_ranges = buffer_handle
5129 .read(cx)
5130 .edited_ranges_for_transaction::<Point>(transaction)
5131 .collect::<Vec<_>>();
5132 let (ranges, _) = multibuffer.set_excerpts_for_path(
5133 PathKey::for_buffer(buffer_handle, cx),
5134 buffer_handle.clone(),
5135 edited_ranges,
5136 DEFAULT_MULTIBUFFER_CONTEXT,
5137 cx,
5138 );
5139
5140 ranges_to_highlight.extend(ranges);
5141 }
5142 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5143 multibuffer
5144 })?;
5145
5146 workspace.update_in(cx, |workspace, window, cx| {
5147 let project = workspace.project().clone();
5148 let editor =
5149 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5150 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5151 editor.update(cx, |editor, cx| {
5152 editor.highlight_background::<Self>(
5153 &ranges_to_highlight,
5154 |theme| theme.editor_highlighted_line_background,
5155 cx,
5156 );
5157 });
5158 })?;
5159
5160 Ok(())
5161 }
5162
5163 pub fn clear_code_action_providers(&mut self) {
5164 self.code_action_providers.clear();
5165 self.available_code_actions.take();
5166 }
5167
5168 pub fn add_code_action_provider(
5169 &mut self,
5170 provider: Rc<dyn CodeActionProvider>,
5171 window: &mut Window,
5172 cx: &mut Context<Self>,
5173 ) {
5174 if self
5175 .code_action_providers
5176 .iter()
5177 .any(|existing_provider| existing_provider.id() == provider.id())
5178 {
5179 return;
5180 }
5181
5182 self.code_action_providers.push(provider);
5183 self.refresh_code_actions(window, cx);
5184 }
5185
5186 pub fn remove_code_action_provider(
5187 &mut self,
5188 id: Arc<str>,
5189 window: &mut Window,
5190 cx: &mut Context<Self>,
5191 ) {
5192 self.code_action_providers
5193 .retain(|provider| provider.id() != id);
5194 self.refresh_code_actions(window, cx);
5195 }
5196
5197 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5198 let buffer = self.buffer.read(cx);
5199 let newest_selection = self.selections.newest_anchor().clone();
5200 if newest_selection.head().diff_base_anchor.is_some() {
5201 return None;
5202 }
5203 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5204 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5205 if start_buffer != end_buffer {
5206 return None;
5207 }
5208
5209 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5210 cx.background_executor()
5211 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5212 .await;
5213
5214 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5215 let providers = this.code_action_providers.clone();
5216 let tasks = this
5217 .code_action_providers
5218 .iter()
5219 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5220 .collect::<Vec<_>>();
5221 (providers, tasks)
5222 })?;
5223
5224 let mut actions = Vec::new();
5225 for (provider, provider_actions) in
5226 providers.into_iter().zip(future::join_all(tasks).await)
5227 {
5228 if let Some(provider_actions) = provider_actions.log_err() {
5229 actions.extend(provider_actions.into_iter().map(|action| {
5230 AvailableCodeAction {
5231 excerpt_id: newest_selection.start.excerpt_id,
5232 action,
5233 provider: provider.clone(),
5234 }
5235 }));
5236 }
5237 }
5238
5239 this.update(cx, |this, cx| {
5240 this.available_code_actions = if actions.is_empty() {
5241 None
5242 } else {
5243 Some((
5244 Location {
5245 buffer: start_buffer,
5246 range: start..end,
5247 },
5248 actions.into(),
5249 ))
5250 };
5251 cx.notify();
5252 })
5253 }));
5254 None
5255 }
5256
5257 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5258 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5259 self.show_git_blame_inline = false;
5260
5261 self.show_git_blame_inline_delay_task =
5262 Some(cx.spawn_in(window, async move |this, cx| {
5263 cx.background_executor().timer(delay).await;
5264
5265 this.update(cx, |this, cx| {
5266 this.show_git_blame_inline = true;
5267 cx.notify();
5268 })
5269 .log_err();
5270 }));
5271 }
5272 }
5273
5274 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5275 if self.pending_rename.is_some() {
5276 return None;
5277 }
5278
5279 let provider = self.semantics_provider.clone()?;
5280 let buffer = self.buffer.read(cx);
5281 let newest_selection = self.selections.newest_anchor().clone();
5282 let cursor_position = newest_selection.head();
5283 let (cursor_buffer, cursor_buffer_position) =
5284 buffer.text_anchor_for_position(cursor_position, cx)?;
5285 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5286 if cursor_buffer != tail_buffer {
5287 return None;
5288 }
5289 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5290 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5291 cx.background_executor()
5292 .timer(Duration::from_millis(debounce))
5293 .await;
5294
5295 let highlights = if let Some(highlights) = cx
5296 .update(|cx| {
5297 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5298 })
5299 .ok()
5300 .flatten()
5301 {
5302 highlights.await.log_err()
5303 } else {
5304 None
5305 };
5306
5307 if let Some(highlights) = highlights {
5308 this.update(cx, |this, cx| {
5309 if this.pending_rename.is_some() {
5310 return;
5311 }
5312
5313 let buffer_id = cursor_position.buffer_id;
5314 let buffer = this.buffer.read(cx);
5315 if !buffer
5316 .text_anchor_for_position(cursor_position, cx)
5317 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5318 {
5319 return;
5320 }
5321
5322 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5323 let mut write_ranges = Vec::new();
5324 let mut read_ranges = Vec::new();
5325 for highlight in highlights {
5326 for (excerpt_id, excerpt_range) in
5327 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5328 {
5329 let start = highlight
5330 .range
5331 .start
5332 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5333 let end = highlight
5334 .range
5335 .end
5336 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5337 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5338 continue;
5339 }
5340
5341 let range = Anchor {
5342 buffer_id,
5343 excerpt_id,
5344 text_anchor: start,
5345 diff_base_anchor: None,
5346 }..Anchor {
5347 buffer_id,
5348 excerpt_id,
5349 text_anchor: end,
5350 diff_base_anchor: None,
5351 };
5352 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5353 write_ranges.push(range);
5354 } else {
5355 read_ranges.push(range);
5356 }
5357 }
5358 }
5359
5360 this.highlight_background::<DocumentHighlightRead>(
5361 &read_ranges,
5362 |theme| theme.editor_document_highlight_read_background,
5363 cx,
5364 );
5365 this.highlight_background::<DocumentHighlightWrite>(
5366 &write_ranges,
5367 |theme| theme.editor_document_highlight_write_background,
5368 cx,
5369 );
5370 cx.notify();
5371 })
5372 .log_err();
5373 }
5374 }));
5375 None
5376 }
5377
5378 pub fn refresh_selected_text_highlights(
5379 &mut self,
5380 window: &mut Window,
5381 cx: &mut Context<Editor>,
5382 ) {
5383 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5384 return;
5385 }
5386 self.selection_highlight_task.take();
5387 if !EditorSettings::get_global(cx).selection_highlight {
5388 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5389 return;
5390 }
5391 if self.selections.count() != 1 || self.selections.line_mode {
5392 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5393 return;
5394 }
5395 let selection = self.selections.newest::<Point>(cx);
5396 if selection.is_empty() || selection.start.row != selection.end.row {
5397 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5398 return;
5399 }
5400 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5401 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5402 cx.background_executor()
5403 .timer(Duration::from_millis(debounce))
5404 .await;
5405 let Some(Some(matches_task)) = editor
5406 .update_in(cx, |editor, _, cx| {
5407 if editor.selections.count() != 1 || editor.selections.line_mode {
5408 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5409 return None;
5410 }
5411 let selection = editor.selections.newest::<Point>(cx);
5412 if selection.is_empty() || selection.start.row != selection.end.row {
5413 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5414 return None;
5415 }
5416 let buffer = editor.buffer().read(cx).snapshot(cx);
5417 let query = buffer.text_for_range(selection.range()).collect::<String>();
5418 if query.trim().is_empty() {
5419 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5420 return None;
5421 }
5422 Some(cx.background_spawn(async move {
5423 let mut ranges = Vec::new();
5424 let selection_anchors = selection.range().to_anchors(&buffer);
5425 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5426 for (search_buffer, search_range, excerpt_id) in
5427 buffer.range_to_buffer_ranges(range)
5428 {
5429 ranges.extend(
5430 project::search::SearchQuery::text(
5431 query.clone(),
5432 false,
5433 false,
5434 false,
5435 Default::default(),
5436 Default::default(),
5437 None,
5438 )
5439 .unwrap()
5440 .search(search_buffer, Some(search_range.clone()))
5441 .await
5442 .into_iter()
5443 .filter_map(
5444 |match_range| {
5445 let start = search_buffer.anchor_after(
5446 search_range.start + match_range.start,
5447 );
5448 let end = search_buffer.anchor_before(
5449 search_range.start + match_range.end,
5450 );
5451 let range = Anchor::range_in_buffer(
5452 excerpt_id,
5453 search_buffer.remote_id(),
5454 start..end,
5455 );
5456 (range != selection_anchors).then_some(range)
5457 },
5458 ),
5459 );
5460 }
5461 }
5462 ranges
5463 }))
5464 })
5465 .log_err()
5466 else {
5467 return;
5468 };
5469 let matches = matches_task.await;
5470 editor
5471 .update_in(cx, |editor, _, cx| {
5472 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5473 if !matches.is_empty() {
5474 editor.highlight_background::<SelectedTextHighlight>(
5475 &matches,
5476 |theme| theme.editor_document_highlight_bracket_background,
5477 cx,
5478 )
5479 }
5480 })
5481 .log_err();
5482 }));
5483 }
5484
5485 pub fn refresh_inline_completion(
5486 &mut self,
5487 debounce: bool,
5488 user_requested: bool,
5489 window: &mut Window,
5490 cx: &mut Context<Self>,
5491 ) -> Option<()> {
5492 let provider = self.edit_prediction_provider()?;
5493 let cursor = self.selections.newest_anchor().head();
5494 let (buffer, cursor_buffer_position) =
5495 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5496
5497 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5498 self.discard_inline_completion(false, cx);
5499 return None;
5500 }
5501
5502 if !user_requested
5503 && (!self.should_show_edit_predictions()
5504 || !self.is_focused(window)
5505 || buffer.read(cx).is_empty())
5506 {
5507 self.discard_inline_completion(false, cx);
5508 return None;
5509 }
5510
5511 self.update_visible_inline_completion(window, cx);
5512 provider.refresh(
5513 self.project.clone(),
5514 buffer,
5515 cursor_buffer_position,
5516 debounce,
5517 cx,
5518 );
5519 Some(())
5520 }
5521
5522 fn show_edit_predictions_in_menu(&self) -> bool {
5523 match self.edit_prediction_settings {
5524 EditPredictionSettings::Disabled => false,
5525 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5526 }
5527 }
5528
5529 pub fn edit_predictions_enabled(&self) -> bool {
5530 match self.edit_prediction_settings {
5531 EditPredictionSettings::Disabled => false,
5532 EditPredictionSettings::Enabled { .. } => true,
5533 }
5534 }
5535
5536 fn edit_prediction_requires_modifier(&self) -> bool {
5537 match self.edit_prediction_settings {
5538 EditPredictionSettings::Disabled => false,
5539 EditPredictionSettings::Enabled {
5540 preview_requires_modifier,
5541 ..
5542 } => preview_requires_modifier,
5543 }
5544 }
5545
5546 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5547 if self.edit_prediction_provider.is_none() {
5548 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5549 } else {
5550 let selection = self.selections.newest_anchor();
5551 let cursor = selection.head();
5552
5553 if let Some((buffer, cursor_buffer_position)) =
5554 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5555 {
5556 self.edit_prediction_settings =
5557 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5558 }
5559 }
5560 }
5561
5562 fn edit_prediction_settings_at_position(
5563 &self,
5564 buffer: &Entity<Buffer>,
5565 buffer_position: language::Anchor,
5566 cx: &App,
5567 ) -> EditPredictionSettings {
5568 if !self.mode.is_full()
5569 || !self.show_inline_completions_override.unwrap_or(true)
5570 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5571 {
5572 return EditPredictionSettings::Disabled;
5573 }
5574
5575 let buffer = buffer.read(cx);
5576
5577 let file = buffer.file();
5578
5579 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5580 return EditPredictionSettings::Disabled;
5581 };
5582
5583 let by_provider = matches!(
5584 self.menu_inline_completions_policy,
5585 MenuInlineCompletionsPolicy::ByProvider
5586 );
5587
5588 let show_in_menu = by_provider
5589 && self
5590 .edit_prediction_provider
5591 .as_ref()
5592 .map_or(false, |provider| {
5593 provider.provider.show_completions_in_menu()
5594 });
5595
5596 let preview_requires_modifier =
5597 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5598
5599 EditPredictionSettings::Enabled {
5600 show_in_menu,
5601 preview_requires_modifier,
5602 }
5603 }
5604
5605 fn should_show_edit_predictions(&self) -> bool {
5606 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5607 }
5608
5609 pub fn edit_prediction_preview_is_active(&self) -> bool {
5610 matches!(
5611 self.edit_prediction_preview,
5612 EditPredictionPreview::Active { .. }
5613 )
5614 }
5615
5616 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5617 let cursor = self.selections.newest_anchor().head();
5618 if let Some((buffer, cursor_position)) =
5619 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5620 {
5621 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5622 } else {
5623 false
5624 }
5625 }
5626
5627 fn edit_predictions_enabled_in_buffer(
5628 &self,
5629 buffer: &Entity<Buffer>,
5630 buffer_position: language::Anchor,
5631 cx: &App,
5632 ) -> bool {
5633 maybe!({
5634 if self.read_only(cx) {
5635 return Some(false);
5636 }
5637 let provider = self.edit_prediction_provider()?;
5638 if !provider.is_enabled(&buffer, buffer_position, cx) {
5639 return Some(false);
5640 }
5641 let buffer = buffer.read(cx);
5642 let Some(file) = buffer.file() else {
5643 return Some(true);
5644 };
5645 let settings = all_language_settings(Some(file), cx);
5646 Some(settings.edit_predictions_enabled_for_file(file, cx))
5647 })
5648 .unwrap_or(false)
5649 }
5650
5651 fn cycle_inline_completion(
5652 &mut self,
5653 direction: Direction,
5654 window: &mut Window,
5655 cx: &mut Context<Self>,
5656 ) -> Option<()> {
5657 let provider = self.edit_prediction_provider()?;
5658 let cursor = self.selections.newest_anchor().head();
5659 let (buffer, cursor_buffer_position) =
5660 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5661 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5662 return None;
5663 }
5664
5665 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5666 self.update_visible_inline_completion(window, cx);
5667
5668 Some(())
5669 }
5670
5671 pub fn show_inline_completion(
5672 &mut self,
5673 _: &ShowEditPrediction,
5674 window: &mut Window,
5675 cx: &mut Context<Self>,
5676 ) {
5677 if !self.has_active_inline_completion() {
5678 self.refresh_inline_completion(false, true, window, cx);
5679 return;
5680 }
5681
5682 self.update_visible_inline_completion(window, cx);
5683 }
5684
5685 pub fn display_cursor_names(
5686 &mut self,
5687 _: &DisplayCursorNames,
5688 window: &mut Window,
5689 cx: &mut Context<Self>,
5690 ) {
5691 self.show_cursor_names(window, cx);
5692 }
5693
5694 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5695 self.show_cursor_names = true;
5696 cx.notify();
5697 cx.spawn_in(window, async move |this, cx| {
5698 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5699 this.update(cx, |this, cx| {
5700 this.show_cursor_names = false;
5701 cx.notify()
5702 })
5703 .ok()
5704 })
5705 .detach();
5706 }
5707
5708 pub fn next_edit_prediction(
5709 &mut self,
5710 _: &NextEditPrediction,
5711 window: &mut Window,
5712 cx: &mut Context<Self>,
5713 ) {
5714 if self.has_active_inline_completion() {
5715 self.cycle_inline_completion(Direction::Next, window, cx);
5716 } else {
5717 let is_copilot_disabled = self
5718 .refresh_inline_completion(false, true, window, cx)
5719 .is_none();
5720 if is_copilot_disabled {
5721 cx.propagate();
5722 }
5723 }
5724 }
5725
5726 pub fn previous_edit_prediction(
5727 &mut self,
5728 _: &PreviousEditPrediction,
5729 window: &mut Window,
5730 cx: &mut Context<Self>,
5731 ) {
5732 if self.has_active_inline_completion() {
5733 self.cycle_inline_completion(Direction::Prev, window, cx);
5734 } else {
5735 let is_copilot_disabled = self
5736 .refresh_inline_completion(false, true, window, cx)
5737 .is_none();
5738 if is_copilot_disabled {
5739 cx.propagate();
5740 }
5741 }
5742 }
5743
5744 pub fn accept_edit_prediction(
5745 &mut self,
5746 _: &AcceptEditPrediction,
5747 window: &mut Window,
5748 cx: &mut Context<Self>,
5749 ) {
5750 if self.show_edit_predictions_in_menu() {
5751 self.hide_context_menu(window, cx);
5752 }
5753
5754 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5755 return;
5756 };
5757
5758 self.report_inline_completion_event(
5759 active_inline_completion.completion_id.clone(),
5760 true,
5761 cx,
5762 );
5763
5764 match &active_inline_completion.completion {
5765 InlineCompletion::Move { target, .. } => {
5766 let target = *target;
5767
5768 if let Some(position_map) = &self.last_position_map {
5769 if position_map
5770 .visible_row_range
5771 .contains(&target.to_display_point(&position_map.snapshot).row())
5772 || !self.edit_prediction_requires_modifier()
5773 {
5774 self.unfold_ranges(&[target..target], true, false, cx);
5775 // Note that this is also done in vim's handler of the Tab action.
5776 self.change_selections(
5777 Some(Autoscroll::newest()),
5778 window,
5779 cx,
5780 |selections| {
5781 selections.select_anchor_ranges([target..target]);
5782 },
5783 );
5784 self.clear_row_highlights::<EditPredictionPreview>();
5785
5786 self.edit_prediction_preview
5787 .set_previous_scroll_position(None);
5788 } else {
5789 self.edit_prediction_preview
5790 .set_previous_scroll_position(Some(
5791 position_map.snapshot.scroll_anchor,
5792 ));
5793
5794 self.highlight_rows::<EditPredictionPreview>(
5795 target..target,
5796 cx.theme().colors().editor_highlighted_line_background,
5797 true,
5798 cx,
5799 );
5800 self.request_autoscroll(Autoscroll::fit(), cx);
5801 }
5802 }
5803 }
5804 InlineCompletion::Edit { edits, .. } => {
5805 if let Some(provider) = self.edit_prediction_provider() {
5806 provider.accept(cx);
5807 }
5808
5809 let snapshot = self.buffer.read(cx).snapshot(cx);
5810 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5811
5812 self.buffer.update(cx, |buffer, cx| {
5813 buffer.edit(edits.iter().cloned(), None, cx)
5814 });
5815
5816 self.change_selections(None, window, cx, |s| {
5817 s.select_anchor_ranges([last_edit_end..last_edit_end])
5818 });
5819
5820 self.update_visible_inline_completion(window, cx);
5821 if self.active_inline_completion.is_none() {
5822 self.refresh_inline_completion(true, true, window, cx);
5823 }
5824
5825 cx.notify();
5826 }
5827 }
5828
5829 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5830 }
5831
5832 pub fn accept_partial_inline_completion(
5833 &mut self,
5834 _: &AcceptPartialEditPrediction,
5835 window: &mut Window,
5836 cx: &mut Context<Self>,
5837 ) {
5838 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5839 return;
5840 };
5841 if self.selections.count() != 1 {
5842 return;
5843 }
5844
5845 self.report_inline_completion_event(
5846 active_inline_completion.completion_id.clone(),
5847 true,
5848 cx,
5849 );
5850
5851 match &active_inline_completion.completion {
5852 InlineCompletion::Move { target, .. } => {
5853 let target = *target;
5854 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5855 selections.select_anchor_ranges([target..target]);
5856 });
5857 }
5858 InlineCompletion::Edit { edits, .. } => {
5859 // Find an insertion that starts at the cursor position.
5860 let snapshot = self.buffer.read(cx).snapshot(cx);
5861 let cursor_offset = self.selections.newest::<usize>(cx).head();
5862 let insertion = edits.iter().find_map(|(range, text)| {
5863 let range = range.to_offset(&snapshot);
5864 if range.is_empty() && range.start == cursor_offset {
5865 Some(text)
5866 } else {
5867 None
5868 }
5869 });
5870
5871 if let Some(text) = insertion {
5872 let mut partial_completion = text
5873 .chars()
5874 .by_ref()
5875 .take_while(|c| c.is_alphabetic())
5876 .collect::<String>();
5877 if partial_completion.is_empty() {
5878 partial_completion = text
5879 .chars()
5880 .by_ref()
5881 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5882 .collect::<String>();
5883 }
5884
5885 cx.emit(EditorEvent::InputHandled {
5886 utf16_range_to_replace: None,
5887 text: partial_completion.clone().into(),
5888 });
5889
5890 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5891
5892 self.refresh_inline_completion(true, true, window, cx);
5893 cx.notify();
5894 } else {
5895 self.accept_edit_prediction(&Default::default(), window, cx);
5896 }
5897 }
5898 }
5899 }
5900
5901 fn discard_inline_completion(
5902 &mut self,
5903 should_report_inline_completion_event: bool,
5904 cx: &mut Context<Self>,
5905 ) -> bool {
5906 if should_report_inline_completion_event {
5907 let completion_id = self
5908 .active_inline_completion
5909 .as_ref()
5910 .and_then(|active_completion| active_completion.completion_id.clone());
5911
5912 self.report_inline_completion_event(completion_id, false, cx);
5913 }
5914
5915 if let Some(provider) = self.edit_prediction_provider() {
5916 provider.discard(cx);
5917 }
5918
5919 self.take_active_inline_completion(cx)
5920 }
5921
5922 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5923 let Some(provider) = self.edit_prediction_provider() else {
5924 return;
5925 };
5926
5927 let Some((_, buffer, _)) = self
5928 .buffer
5929 .read(cx)
5930 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5931 else {
5932 return;
5933 };
5934
5935 let extension = buffer
5936 .read(cx)
5937 .file()
5938 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5939
5940 let event_type = match accepted {
5941 true => "Edit Prediction Accepted",
5942 false => "Edit Prediction Discarded",
5943 };
5944 telemetry::event!(
5945 event_type,
5946 provider = provider.name(),
5947 prediction_id = id,
5948 suggestion_accepted = accepted,
5949 file_extension = extension,
5950 );
5951 }
5952
5953 pub fn has_active_inline_completion(&self) -> bool {
5954 self.active_inline_completion.is_some()
5955 }
5956
5957 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5958 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5959 return false;
5960 };
5961
5962 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5963 self.clear_highlights::<InlineCompletionHighlight>(cx);
5964 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5965 true
5966 }
5967
5968 /// Returns true when we're displaying the edit prediction popover below the cursor
5969 /// like we are not previewing and the LSP autocomplete menu is visible
5970 /// or we are in `when_holding_modifier` mode.
5971 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5972 if self.edit_prediction_preview_is_active()
5973 || !self.show_edit_predictions_in_menu()
5974 || !self.edit_predictions_enabled()
5975 {
5976 return false;
5977 }
5978
5979 if self.has_visible_completions_menu() {
5980 return true;
5981 }
5982
5983 has_completion && self.edit_prediction_requires_modifier()
5984 }
5985
5986 fn handle_modifiers_changed(
5987 &mut self,
5988 modifiers: Modifiers,
5989 position_map: &PositionMap,
5990 window: &mut Window,
5991 cx: &mut Context<Self>,
5992 ) {
5993 if self.show_edit_predictions_in_menu() {
5994 self.update_edit_prediction_preview(&modifiers, window, cx);
5995 }
5996
5997 self.update_selection_mode(&modifiers, position_map, window, cx);
5998
5999 let mouse_position = window.mouse_position();
6000 if !position_map.text_hitbox.is_hovered(window) {
6001 return;
6002 }
6003
6004 self.update_hovered_link(
6005 position_map.point_for_position(mouse_position),
6006 &position_map.snapshot,
6007 modifiers,
6008 window,
6009 cx,
6010 )
6011 }
6012
6013 fn update_selection_mode(
6014 &mut self,
6015 modifiers: &Modifiers,
6016 position_map: &PositionMap,
6017 window: &mut Window,
6018 cx: &mut Context<Self>,
6019 ) {
6020 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6021 return;
6022 }
6023
6024 let mouse_position = window.mouse_position();
6025 let point_for_position = position_map.point_for_position(mouse_position);
6026 let position = point_for_position.previous_valid;
6027
6028 self.select(
6029 SelectPhase::BeginColumnar {
6030 position,
6031 reset: false,
6032 goal_column: point_for_position.exact_unclipped.column(),
6033 },
6034 window,
6035 cx,
6036 );
6037 }
6038
6039 fn update_edit_prediction_preview(
6040 &mut self,
6041 modifiers: &Modifiers,
6042 window: &mut Window,
6043 cx: &mut Context<Self>,
6044 ) {
6045 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6046 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6047 return;
6048 };
6049
6050 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6051 if matches!(
6052 self.edit_prediction_preview,
6053 EditPredictionPreview::Inactive { .. }
6054 ) {
6055 self.edit_prediction_preview = EditPredictionPreview::Active {
6056 previous_scroll_position: None,
6057 since: Instant::now(),
6058 };
6059
6060 self.update_visible_inline_completion(window, cx);
6061 cx.notify();
6062 }
6063 } else if let EditPredictionPreview::Active {
6064 previous_scroll_position,
6065 since,
6066 } = self.edit_prediction_preview
6067 {
6068 if let (Some(previous_scroll_position), Some(position_map)) =
6069 (previous_scroll_position, self.last_position_map.as_ref())
6070 {
6071 self.set_scroll_position(
6072 previous_scroll_position
6073 .scroll_position(&position_map.snapshot.display_snapshot),
6074 window,
6075 cx,
6076 );
6077 }
6078
6079 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6080 released_too_fast: since.elapsed() < Duration::from_millis(200),
6081 };
6082 self.clear_row_highlights::<EditPredictionPreview>();
6083 self.update_visible_inline_completion(window, cx);
6084 cx.notify();
6085 }
6086 }
6087
6088 fn update_visible_inline_completion(
6089 &mut self,
6090 _window: &mut Window,
6091 cx: &mut Context<Self>,
6092 ) -> Option<()> {
6093 let selection = self.selections.newest_anchor();
6094 let cursor = selection.head();
6095 let multibuffer = self.buffer.read(cx).snapshot(cx);
6096 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6097 let excerpt_id = cursor.excerpt_id;
6098
6099 let show_in_menu = self.show_edit_predictions_in_menu();
6100 let completions_menu_has_precedence = !show_in_menu
6101 && (self.context_menu.borrow().is_some()
6102 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6103
6104 if completions_menu_has_precedence
6105 || !offset_selection.is_empty()
6106 || self
6107 .active_inline_completion
6108 .as_ref()
6109 .map_or(false, |completion| {
6110 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6111 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6112 !invalidation_range.contains(&offset_selection.head())
6113 })
6114 {
6115 self.discard_inline_completion(false, cx);
6116 return None;
6117 }
6118
6119 self.take_active_inline_completion(cx);
6120 let Some(provider) = self.edit_prediction_provider() else {
6121 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6122 return None;
6123 };
6124
6125 let (buffer, cursor_buffer_position) =
6126 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6127
6128 self.edit_prediction_settings =
6129 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6130
6131 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6132
6133 if self.edit_prediction_indent_conflict {
6134 let cursor_point = cursor.to_point(&multibuffer);
6135
6136 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6137
6138 if let Some((_, indent)) = indents.iter().next() {
6139 if indent.len == cursor_point.column {
6140 self.edit_prediction_indent_conflict = false;
6141 }
6142 }
6143 }
6144
6145 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6146 let edits = inline_completion
6147 .edits
6148 .into_iter()
6149 .flat_map(|(range, new_text)| {
6150 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6151 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6152 Some((start..end, new_text))
6153 })
6154 .collect::<Vec<_>>();
6155 if edits.is_empty() {
6156 return None;
6157 }
6158
6159 let first_edit_start = edits.first().unwrap().0.start;
6160 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6161 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6162
6163 let last_edit_end = edits.last().unwrap().0.end;
6164 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6165 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6166
6167 let cursor_row = cursor.to_point(&multibuffer).row;
6168
6169 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6170
6171 let mut inlay_ids = Vec::new();
6172 let invalidation_row_range;
6173 let move_invalidation_row_range = if cursor_row < edit_start_row {
6174 Some(cursor_row..edit_end_row)
6175 } else if cursor_row > edit_end_row {
6176 Some(edit_start_row..cursor_row)
6177 } else {
6178 None
6179 };
6180 let is_move =
6181 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6182 let completion = if is_move {
6183 invalidation_row_range =
6184 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6185 let target = first_edit_start;
6186 InlineCompletion::Move { target, snapshot }
6187 } else {
6188 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6189 && !self.inline_completions_hidden_for_vim_mode;
6190
6191 if show_completions_in_buffer {
6192 if edits
6193 .iter()
6194 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6195 {
6196 let mut inlays = Vec::new();
6197 for (range, new_text) in &edits {
6198 let inlay = Inlay::inline_completion(
6199 post_inc(&mut self.next_inlay_id),
6200 range.start,
6201 new_text.as_str(),
6202 );
6203 inlay_ids.push(inlay.id);
6204 inlays.push(inlay);
6205 }
6206
6207 self.splice_inlays(&[], inlays, cx);
6208 } else {
6209 let background_color = cx.theme().status().deleted_background;
6210 self.highlight_text::<InlineCompletionHighlight>(
6211 edits.iter().map(|(range, _)| range.clone()).collect(),
6212 HighlightStyle {
6213 background_color: Some(background_color),
6214 ..Default::default()
6215 },
6216 cx,
6217 );
6218 }
6219 }
6220
6221 invalidation_row_range = edit_start_row..edit_end_row;
6222
6223 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6224 if provider.show_tab_accept_marker() {
6225 EditDisplayMode::TabAccept
6226 } else {
6227 EditDisplayMode::Inline
6228 }
6229 } else {
6230 EditDisplayMode::DiffPopover
6231 };
6232
6233 InlineCompletion::Edit {
6234 edits,
6235 edit_preview: inline_completion.edit_preview,
6236 display_mode,
6237 snapshot,
6238 }
6239 };
6240
6241 let invalidation_range = multibuffer
6242 .anchor_before(Point::new(invalidation_row_range.start, 0))
6243 ..multibuffer.anchor_after(Point::new(
6244 invalidation_row_range.end,
6245 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6246 ));
6247
6248 self.stale_inline_completion_in_menu = None;
6249 self.active_inline_completion = Some(InlineCompletionState {
6250 inlay_ids,
6251 completion,
6252 completion_id: inline_completion.id,
6253 invalidation_range,
6254 });
6255
6256 cx.notify();
6257
6258 Some(())
6259 }
6260
6261 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6262 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6263 }
6264
6265 fn render_code_actions_indicator(
6266 &self,
6267 _style: &EditorStyle,
6268 row: DisplayRow,
6269 is_active: bool,
6270 breakpoint: Option<&(Anchor, Breakpoint)>,
6271 cx: &mut Context<Self>,
6272 ) -> Option<IconButton> {
6273 let color = Color::Muted;
6274 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6275 let show_tooltip = !self.context_menu_visible();
6276
6277 if self.available_code_actions.is_some() {
6278 Some(
6279 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6280 .shape(ui::IconButtonShape::Square)
6281 .icon_size(IconSize::XSmall)
6282 .icon_color(color)
6283 .toggle_state(is_active)
6284 .when(show_tooltip, |this| {
6285 this.tooltip({
6286 let focus_handle = self.focus_handle.clone();
6287 move |window, cx| {
6288 Tooltip::for_action_in(
6289 "Toggle Code Actions",
6290 &ToggleCodeActions {
6291 deployed_from_indicator: None,
6292 },
6293 &focus_handle,
6294 window,
6295 cx,
6296 )
6297 }
6298 })
6299 })
6300 .on_click(cx.listener(move |editor, _e, window, cx| {
6301 window.focus(&editor.focus_handle(cx));
6302 editor.toggle_code_actions(
6303 &ToggleCodeActions {
6304 deployed_from_indicator: Some(row),
6305 },
6306 window,
6307 cx,
6308 );
6309 }))
6310 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6311 editor.set_breakpoint_context_menu(
6312 row,
6313 position,
6314 event.down.position,
6315 window,
6316 cx,
6317 );
6318 })),
6319 )
6320 } else {
6321 None
6322 }
6323 }
6324
6325 fn clear_tasks(&mut self) {
6326 self.tasks.clear()
6327 }
6328
6329 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6330 if self.tasks.insert(key, value).is_some() {
6331 // This case should hopefully be rare, but just in case...
6332 log::error!(
6333 "multiple different run targets found on a single line, only the last target will be rendered"
6334 )
6335 }
6336 }
6337
6338 /// Get all display points of breakpoints that will be rendered within editor
6339 ///
6340 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6341 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6342 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6343 fn active_breakpoints(
6344 &self,
6345 range: Range<DisplayRow>,
6346 window: &mut Window,
6347 cx: &mut Context<Self>,
6348 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6349 let mut breakpoint_display_points = HashMap::default();
6350
6351 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6352 return breakpoint_display_points;
6353 };
6354
6355 let snapshot = self.snapshot(window, cx);
6356
6357 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6358 let Some(project) = self.project.as_ref() else {
6359 return breakpoint_display_points;
6360 };
6361
6362 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6363 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6364
6365 for (buffer_snapshot, range, excerpt_id) in
6366 multi_buffer_snapshot.range_to_buffer_ranges(range)
6367 {
6368 let Some(buffer) = project.read_with(cx, |this, cx| {
6369 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6370 }) else {
6371 continue;
6372 };
6373 let breakpoints = breakpoint_store.read(cx).breakpoints(
6374 &buffer,
6375 Some(
6376 buffer_snapshot.anchor_before(range.start)
6377 ..buffer_snapshot.anchor_after(range.end),
6378 ),
6379 buffer_snapshot,
6380 cx,
6381 );
6382 for (anchor, breakpoint) in breakpoints {
6383 let multi_buffer_anchor =
6384 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6385 let position = multi_buffer_anchor
6386 .to_point(&multi_buffer_snapshot)
6387 .to_display_point(&snapshot);
6388
6389 breakpoint_display_points
6390 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6391 }
6392 }
6393
6394 breakpoint_display_points
6395 }
6396
6397 fn breakpoint_context_menu(
6398 &self,
6399 anchor: Anchor,
6400 window: &mut Window,
6401 cx: &mut Context<Self>,
6402 ) -> Entity<ui::ContextMenu> {
6403 let weak_editor = cx.weak_entity();
6404 let focus_handle = self.focus_handle(cx);
6405
6406 let row = self
6407 .buffer
6408 .read(cx)
6409 .snapshot(cx)
6410 .summary_for_anchor::<Point>(&anchor)
6411 .row;
6412
6413 let breakpoint = self
6414 .breakpoint_at_row(row, window, cx)
6415 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6416
6417 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6418 "Edit Log Breakpoint"
6419 } else {
6420 "Set Log Breakpoint"
6421 };
6422
6423 let condition_breakpoint_msg = if breakpoint
6424 .as_ref()
6425 .is_some_and(|bp| bp.1.condition.is_some())
6426 {
6427 "Edit Condition Breakpoint"
6428 } else {
6429 "Set Condition Breakpoint"
6430 };
6431
6432 let hit_condition_breakpoint_msg = if breakpoint
6433 .as_ref()
6434 .is_some_and(|bp| bp.1.hit_condition.is_some())
6435 {
6436 "Edit Hit Condition Breakpoint"
6437 } else {
6438 "Set Hit Condition Breakpoint"
6439 };
6440
6441 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6442 "Unset Breakpoint"
6443 } else {
6444 "Set Breakpoint"
6445 };
6446
6447 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6448 BreakpointState::Enabled => Some("Disable"),
6449 BreakpointState::Disabled => Some("Enable"),
6450 });
6451
6452 let (anchor, breakpoint) =
6453 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6454
6455 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6456 menu.on_blur_subscription(Subscription::new(|| {}))
6457 .context(focus_handle)
6458 .when_some(toggle_state_msg, |this, msg| {
6459 this.entry(msg, None, {
6460 let weak_editor = weak_editor.clone();
6461 let breakpoint = breakpoint.clone();
6462 move |_window, cx| {
6463 weak_editor
6464 .update(cx, |this, cx| {
6465 this.edit_breakpoint_at_anchor(
6466 anchor,
6467 breakpoint.as_ref().clone(),
6468 BreakpointEditAction::InvertState,
6469 cx,
6470 );
6471 })
6472 .log_err();
6473 }
6474 })
6475 })
6476 .entry(set_breakpoint_msg, None, {
6477 let weak_editor = weak_editor.clone();
6478 let breakpoint = breakpoint.clone();
6479 move |_window, cx| {
6480 weak_editor
6481 .update(cx, |this, cx| {
6482 this.edit_breakpoint_at_anchor(
6483 anchor,
6484 breakpoint.as_ref().clone(),
6485 BreakpointEditAction::Toggle,
6486 cx,
6487 );
6488 })
6489 .log_err();
6490 }
6491 })
6492 .entry(log_breakpoint_msg, None, {
6493 let breakpoint = breakpoint.clone();
6494 let weak_editor = weak_editor.clone();
6495 move |window, cx| {
6496 weak_editor
6497 .update(cx, |this, cx| {
6498 this.add_edit_breakpoint_block(
6499 anchor,
6500 breakpoint.as_ref(),
6501 BreakpointPromptEditAction::Log,
6502 window,
6503 cx,
6504 );
6505 })
6506 .log_err();
6507 }
6508 })
6509 .entry(condition_breakpoint_msg, None, {
6510 let breakpoint = breakpoint.clone();
6511 let weak_editor = weak_editor.clone();
6512 move |window, cx| {
6513 weak_editor
6514 .update(cx, |this, cx| {
6515 this.add_edit_breakpoint_block(
6516 anchor,
6517 breakpoint.as_ref(),
6518 BreakpointPromptEditAction::Condition,
6519 window,
6520 cx,
6521 );
6522 })
6523 .log_err();
6524 }
6525 })
6526 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6527 weak_editor
6528 .update(cx, |this, cx| {
6529 this.add_edit_breakpoint_block(
6530 anchor,
6531 breakpoint.as_ref(),
6532 BreakpointPromptEditAction::HitCondition,
6533 window,
6534 cx,
6535 );
6536 })
6537 .log_err();
6538 })
6539 })
6540 }
6541
6542 fn render_breakpoint(
6543 &self,
6544 position: Anchor,
6545 row: DisplayRow,
6546 breakpoint: &Breakpoint,
6547 cx: &mut Context<Self>,
6548 ) -> IconButton {
6549 let (color, icon) = {
6550 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6551 (false, false) => ui::IconName::DebugBreakpoint,
6552 (true, false) => ui::IconName::DebugLogBreakpoint,
6553 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6554 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6555 };
6556
6557 let color = if self
6558 .gutter_breakpoint_indicator
6559 .0
6560 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6561 {
6562 Color::Hint
6563 } else {
6564 Color::Debugger
6565 };
6566
6567 (color, icon)
6568 };
6569
6570 let breakpoint = Arc::from(breakpoint.clone());
6571
6572 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6573 .icon_size(IconSize::XSmall)
6574 .size(ui::ButtonSize::None)
6575 .icon_color(color)
6576 .style(ButtonStyle::Transparent)
6577 .on_click(cx.listener({
6578 let breakpoint = breakpoint.clone();
6579
6580 move |editor, event: &ClickEvent, window, cx| {
6581 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6582 BreakpointEditAction::InvertState
6583 } else {
6584 BreakpointEditAction::Toggle
6585 };
6586
6587 window.focus(&editor.focus_handle(cx));
6588 editor.edit_breakpoint_at_anchor(
6589 position,
6590 breakpoint.as_ref().clone(),
6591 edit_action,
6592 cx,
6593 );
6594 }
6595 }))
6596 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6597 editor.set_breakpoint_context_menu(
6598 row,
6599 Some(position),
6600 event.down.position,
6601 window,
6602 cx,
6603 );
6604 }))
6605 }
6606
6607 fn build_tasks_context(
6608 project: &Entity<Project>,
6609 buffer: &Entity<Buffer>,
6610 buffer_row: u32,
6611 tasks: &Arc<RunnableTasks>,
6612 cx: &mut Context<Self>,
6613 ) -> Task<Option<task::TaskContext>> {
6614 let position = Point::new(buffer_row, tasks.column);
6615 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6616 let location = Location {
6617 buffer: buffer.clone(),
6618 range: range_start..range_start,
6619 };
6620 // Fill in the environmental variables from the tree-sitter captures
6621 let mut captured_task_variables = TaskVariables::default();
6622 for (capture_name, value) in tasks.extra_variables.clone() {
6623 captured_task_variables.insert(
6624 task::VariableName::Custom(capture_name.into()),
6625 value.clone(),
6626 );
6627 }
6628 project.update(cx, |project, cx| {
6629 project.task_store().update(cx, |task_store, cx| {
6630 task_store.task_context_for_location(captured_task_variables, location, cx)
6631 })
6632 })
6633 }
6634
6635 pub fn spawn_nearest_task(
6636 &mut self,
6637 action: &SpawnNearestTask,
6638 window: &mut Window,
6639 cx: &mut Context<Self>,
6640 ) {
6641 let Some((workspace, _)) = self.workspace.clone() else {
6642 return;
6643 };
6644 let Some(project) = self.project.clone() else {
6645 return;
6646 };
6647
6648 // Try to find a closest, enclosing node using tree-sitter that has a
6649 // task
6650 let Some((buffer, buffer_row, tasks)) = self
6651 .find_enclosing_node_task(cx)
6652 // Or find the task that's closest in row-distance.
6653 .or_else(|| self.find_closest_task(cx))
6654 else {
6655 return;
6656 };
6657
6658 let reveal_strategy = action.reveal;
6659 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6660 cx.spawn_in(window, async move |_, cx| {
6661 let context = task_context.await?;
6662 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6663
6664 let resolved = resolved_task.resolved.as_mut()?;
6665 resolved.reveal = reveal_strategy;
6666
6667 workspace
6668 .update(cx, |workspace, cx| {
6669 workspace::tasks::schedule_resolved_task(
6670 workspace,
6671 task_source_kind,
6672 resolved_task,
6673 false,
6674 cx,
6675 );
6676 })
6677 .ok()
6678 })
6679 .detach();
6680 }
6681
6682 fn find_closest_task(
6683 &mut self,
6684 cx: &mut Context<Self>,
6685 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6686 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6687
6688 let ((buffer_id, row), tasks) = self
6689 .tasks
6690 .iter()
6691 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6692
6693 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6694 let tasks = Arc::new(tasks.to_owned());
6695 Some((buffer, *row, tasks))
6696 }
6697
6698 fn find_enclosing_node_task(
6699 &mut self,
6700 cx: &mut Context<Self>,
6701 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6702 let snapshot = self.buffer.read(cx).snapshot(cx);
6703 let offset = self.selections.newest::<usize>(cx).head();
6704 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6705 let buffer_id = excerpt.buffer().remote_id();
6706
6707 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6708 let mut cursor = layer.node().walk();
6709
6710 while cursor.goto_first_child_for_byte(offset).is_some() {
6711 if cursor.node().end_byte() == offset {
6712 cursor.goto_next_sibling();
6713 }
6714 }
6715
6716 // Ascend to the smallest ancestor that contains the range and has a task.
6717 loop {
6718 let node = cursor.node();
6719 let node_range = node.byte_range();
6720 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6721
6722 // Check if this node contains our offset
6723 if node_range.start <= offset && node_range.end >= offset {
6724 // If it contains offset, check for task
6725 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6726 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6727 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6728 }
6729 }
6730
6731 if !cursor.goto_parent() {
6732 break;
6733 }
6734 }
6735 None
6736 }
6737
6738 fn render_run_indicator(
6739 &self,
6740 _style: &EditorStyle,
6741 is_active: bool,
6742 row: DisplayRow,
6743 breakpoint: Option<(Anchor, Breakpoint)>,
6744 cx: &mut Context<Self>,
6745 ) -> IconButton {
6746 let color = Color::Muted;
6747 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6748
6749 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6750 .shape(ui::IconButtonShape::Square)
6751 .icon_size(IconSize::XSmall)
6752 .icon_color(color)
6753 .toggle_state(is_active)
6754 .on_click(cx.listener(move |editor, _e, window, cx| {
6755 window.focus(&editor.focus_handle(cx));
6756 editor.toggle_code_actions(
6757 &ToggleCodeActions {
6758 deployed_from_indicator: Some(row),
6759 },
6760 window,
6761 cx,
6762 );
6763 }))
6764 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6765 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6766 }))
6767 }
6768
6769 pub fn context_menu_visible(&self) -> bool {
6770 !self.edit_prediction_preview_is_active()
6771 && self
6772 .context_menu
6773 .borrow()
6774 .as_ref()
6775 .map_or(false, |menu| menu.visible())
6776 }
6777
6778 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6779 self.context_menu
6780 .borrow()
6781 .as_ref()
6782 .map(|menu| menu.origin())
6783 }
6784
6785 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6786 self.context_menu_options = Some(options);
6787 }
6788
6789 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6790 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6791
6792 fn render_edit_prediction_popover(
6793 &mut self,
6794 text_bounds: &Bounds<Pixels>,
6795 content_origin: gpui::Point<Pixels>,
6796 editor_snapshot: &EditorSnapshot,
6797 visible_row_range: Range<DisplayRow>,
6798 scroll_top: f32,
6799 scroll_bottom: f32,
6800 line_layouts: &[LineWithInvisibles],
6801 line_height: Pixels,
6802 scroll_pixel_position: gpui::Point<Pixels>,
6803 newest_selection_head: Option<DisplayPoint>,
6804 editor_width: Pixels,
6805 style: &EditorStyle,
6806 window: &mut Window,
6807 cx: &mut App,
6808 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6809 let active_inline_completion = self.active_inline_completion.as_ref()?;
6810
6811 if self.edit_prediction_visible_in_cursor_popover(true) {
6812 return None;
6813 }
6814
6815 match &active_inline_completion.completion {
6816 InlineCompletion::Move { target, .. } => {
6817 let target_display_point = target.to_display_point(editor_snapshot);
6818
6819 if self.edit_prediction_requires_modifier() {
6820 if !self.edit_prediction_preview_is_active() {
6821 return None;
6822 }
6823
6824 self.render_edit_prediction_modifier_jump_popover(
6825 text_bounds,
6826 content_origin,
6827 visible_row_range,
6828 line_layouts,
6829 line_height,
6830 scroll_pixel_position,
6831 newest_selection_head,
6832 target_display_point,
6833 window,
6834 cx,
6835 )
6836 } else {
6837 self.render_edit_prediction_eager_jump_popover(
6838 text_bounds,
6839 content_origin,
6840 editor_snapshot,
6841 visible_row_range,
6842 scroll_top,
6843 scroll_bottom,
6844 line_height,
6845 scroll_pixel_position,
6846 target_display_point,
6847 editor_width,
6848 window,
6849 cx,
6850 )
6851 }
6852 }
6853 InlineCompletion::Edit {
6854 display_mode: EditDisplayMode::Inline,
6855 ..
6856 } => None,
6857 InlineCompletion::Edit {
6858 display_mode: EditDisplayMode::TabAccept,
6859 edits,
6860 ..
6861 } => {
6862 let range = &edits.first()?.0;
6863 let target_display_point = range.end.to_display_point(editor_snapshot);
6864
6865 self.render_edit_prediction_end_of_line_popover(
6866 "Accept",
6867 editor_snapshot,
6868 visible_row_range,
6869 target_display_point,
6870 line_height,
6871 scroll_pixel_position,
6872 content_origin,
6873 editor_width,
6874 window,
6875 cx,
6876 )
6877 }
6878 InlineCompletion::Edit {
6879 edits,
6880 edit_preview,
6881 display_mode: EditDisplayMode::DiffPopover,
6882 snapshot,
6883 } => self.render_edit_prediction_diff_popover(
6884 text_bounds,
6885 content_origin,
6886 editor_snapshot,
6887 visible_row_range,
6888 line_layouts,
6889 line_height,
6890 scroll_pixel_position,
6891 newest_selection_head,
6892 editor_width,
6893 style,
6894 edits,
6895 edit_preview,
6896 snapshot,
6897 window,
6898 cx,
6899 ),
6900 }
6901 }
6902
6903 fn render_edit_prediction_modifier_jump_popover(
6904 &mut self,
6905 text_bounds: &Bounds<Pixels>,
6906 content_origin: gpui::Point<Pixels>,
6907 visible_row_range: Range<DisplayRow>,
6908 line_layouts: &[LineWithInvisibles],
6909 line_height: Pixels,
6910 scroll_pixel_position: gpui::Point<Pixels>,
6911 newest_selection_head: Option<DisplayPoint>,
6912 target_display_point: DisplayPoint,
6913 window: &mut Window,
6914 cx: &mut App,
6915 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6916 let scrolled_content_origin =
6917 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6918
6919 const SCROLL_PADDING_Y: Pixels = px(12.);
6920
6921 if target_display_point.row() < visible_row_range.start {
6922 return self.render_edit_prediction_scroll_popover(
6923 |_| SCROLL_PADDING_Y,
6924 IconName::ArrowUp,
6925 visible_row_range,
6926 line_layouts,
6927 newest_selection_head,
6928 scrolled_content_origin,
6929 window,
6930 cx,
6931 );
6932 } else if target_display_point.row() >= visible_row_range.end {
6933 return self.render_edit_prediction_scroll_popover(
6934 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6935 IconName::ArrowDown,
6936 visible_row_range,
6937 line_layouts,
6938 newest_selection_head,
6939 scrolled_content_origin,
6940 window,
6941 cx,
6942 );
6943 }
6944
6945 const POLE_WIDTH: Pixels = px(2.);
6946
6947 let line_layout =
6948 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6949 let target_column = target_display_point.column() as usize;
6950
6951 let target_x = line_layout.x_for_index(target_column);
6952 let target_y =
6953 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6954
6955 let flag_on_right = target_x < text_bounds.size.width / 2.;
6956
6957 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6958 border_color.l += 0.001;
6959
6960 let mut element = v_flex()
6961 .items_end()
6962 .when(flag_on_right, |el| el.items_start())
6963 .child(if flag_on_right {
6964 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6965 .rounded_bl(px(0.))
6966 .rounded_tl(px(0.))
6967 .border_l_2()
6968 .border_color(border_color)
6969 } else {
6970 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6971 .rounded_br(px(0.))
6972 .rounded_tr(px(0.))
6973 .border_r_2()
6974 .border_color(border_color)
6975 })
6976 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6977 .into_any();
6978
6979 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6980
6981 let mut origin = scrolled_content_origin + point(target_x, target_y)
6982 - point(
6983 if flag_on_right {
6984 POLE_WIDTH
6985 } else {
6986 size.width - POLE_WIDTH
6987 },
6988 size.height - line_height,
6989 );
6990
6991 origin.x = origin.x.max(content_origin.x);
6992
6993 element.prepaint_at(origin, window, cx);
6994
6995 Some((element, origin))
6996 }
6997
6998 fn render_edit_prediction_scroll_popover(
6999 &mut self,
7000 to_y: impl Fn(Size<Pixels>) -> Pixels,
7001 scroll_icon: IconName,
7002 visible_row_range: Range<DisplayRow>,
7003 line_layouts: &[LineWithInvisibles],
7004 newest_selection_head: Option<DisplayPoint>,
7005 scrolled_content_origin: gpui::Point<Pixels>,
7006 window: &mut Window,
7007 cx: &mut App,
7008 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7009 let mut element = self
7010 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7011 .into_any();
7012
7013 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7014
7015 let cursor = newest_selection_head?;
7016 let cursor_row_layout =
7017 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7018 let cursor_column = cursor.column() as usize;
7019
7020 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7021
7022 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7023
7024 element.prepaint_at(origin, window, cx);
7025 Some((element, origin))
7026 }
7027
7028 fn render_edit_prediction_eager_jump_popover(
7029 &mut self,
7030 text_bounds: &Bounds<Pixels>,
7031 content_origin: gpui::Point<Pixels>,
7032 editor_snapshot: &EditorSnapshot,
7033 visible_row_range: Range<DisplayRow>,
7034 scroll_top: f32,
7035 scroll_bottom: f32,
7036 line_height: Pixels,
7037 scroll_pixel_position: gpui::Point<Pixels>,
7038 target_display_point: DisplayPoint,
7039 editor_width: Pixels,
7040 window: &mut Window,
7041 cx: &mut App,
7042 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7043 if target_display_point.row().as_f32() < scroll_top {
7044 let mut element = self
7045 .render_edit_prediction_line_popover(
7046 "Jump to Edit",
7047 Some(IconName::ArrowUp),
7048 window,
7049 cx,
7050 )?
7051 .into_any();
7052
7053 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7054 let offset = point(
7055 (text_bounds.size.width - size.width) / 2.,
7056 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7057 );
7058
7059 let origin = text_bounds.origin + offset;
7060 element.prepaint_at(origin, window, cx);
7061 Some((element, origin))
7062 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7063 let mut element = self
7064 .render_edit_prediction_line_popover(
7065 "Jump to Edit",
7066 Some(IconName::ArrowDown),
7067 window,
7068 cx,
7069 )?
7070 .into_any();
7071
7072 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7073 let offset = point(
7074 (text_bounds.size.width - size.width) / 2.,
7075 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7076 );
7077
7078 let origin = text_bounds.origin + offset;
7079 element.prepaint_at(origin, window, cx);
7080 Some((element, origin))
7081 } else {
7082 self.render_edit_prediction_end_of_line_popover(
7083 "Jump to Edit",
7084 editor_snapshot,
7085 visible_row_range,
7086 target_display_point,
7087 line_height,
7088 scroll_pixel_position,
7089 content_origin,
7090 editor_width,
7091 window,
7092 cx,
7093 )
7094 }
7095 }
7096
7097 fn render_edit_prediction_end_of_line_popover(
7098 self: &mut Editor,
7099 label: &'static str,
7100 editor_snapshot: &EditorSnapshot,
7101 visible_row_range: Range<DisplayRow>,
7102 target_display_point: DisplayPoint,
7103 line_height: Pixels,
7104 scroll_pixel_position: gpui::Point<Pixels>,
7105 content_origin: gpui::Point<Pixels>,
7106 editor_width: Pixels,
7107 window: &mut Window,
7108 cx: &mut App,
7109 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7110 let target_line_end = DisplayPoint::new(
7111 target_display_point.row(),
7112 editor_snapshot.line_len(target_display_point.row()),
7113 );
7114
7115 let mut element = self
7116 .render_edit_prediction_line_popover(label, None, window, cx)?
7117 .into_any();
7118
7119 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7120
7121 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7122
7123 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7124 let mut origin = start_point
7125 + line_origin
7126 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7127 origin.x = origin.x.max(content_origin.x);
7128
7129 let max_x = content_origin.x + editor_width - size.width;
7130
7131 if origin.x > max_x {
7132 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7133
7134 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7135 origin.y += offset;
7136 IconName::ArrowUp
7137 } else {
7138 origin.y -= offset;
7139 IconName::ArrowDown
7140 };
7141
7142 element = self
7143 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7144 .into_any();
7145
7146 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7147
7148 origin.x = content_origin.x + editor_width - size.width - px(2.);
7149 }
7150
7151 element.prepaint_at(origin, window, cx);
7152 Some((element, origin))
7153 }
7154
7155 fn render_edit_prediction_diff_popover(
7156 self: &Editor,
7157 text_bounds: &Bounds<Pixels>,
7158 content_origin: gpui::Point<Pixels>,
7159 editor_snapshot: &EditorSnapshot,
7160 visible_row_range: Range<DisplayRow>,
7161 line_layouts: &[LineWithInvisibles],
7162 line_height: Pixels,
7163 scroll_pixel_position: gpui::Point<Pixels>,
7164 newest_selection_head: Option<DisplayPoint>,
7165 editor_width: Pixels,
7166 style: &EditorStyle,
7167 edits: &Vec<(Range<Anchor>, String)>,
7168 edit_preview: &Option<language::EditPreview>,
7169 snapshot: &language::BufferSnapshot,
7170 window: &mut Window,
7171 cx: &mut App,
7172 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7173 let edit_start = edits
7174 .first()
7175 .unwrap()
7176 .0
7177 .start
7178 .to_display_point(editor_snapshot);
7179 let edit_end = edits
7180 .last()
7181 .unwrap()
7182 .0
7183 .end
7184 .to_display_point(editor_snapshot);
7185
7186 let is_visible = visible_row_range.contains(&edit_start.row())
7187 || visible_row_range.contains(&edit_end.row());
7188 if !is_visible {
7189 return None;
7190 }
7191
7192 let highlighted_edits =
7193 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7194
7195 let styled_text = highlighted_edits.to_styled_text(&style.text);
7196 let line_count = highlighted_edits.text.lines().count();
7197
7198 const BORDER_WIDTH: Pixels = px(1.);
7199
7200 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7201 let has_keybind = keybind.is_some();
7202
7203 let mut element = h_flex()
7204 .items_start()
7205 .child(
7206 h_flex()
7207 .bg(cx.theme().colors().editor_background)
7208 .border(BORDER_WIDTH)
7209 .shadow_sm()
7210 .border_color(cx.theme().colors().border)
7211 .rounded_l_lg()
7212 .when(line_count > 1, |el| el.rounded_br_lg())
7213 .pr_1()
7214 .child(styled_text),
7215 )
7216 .child(
7217 h_flex()
7218 .h(line_height + BORDER_WIDTH * 2.)
7219 .px_1p5()
7220 .gap_1()
7221 // Workaround: For some reason, there's a gap if we don't do this
7222 .ml(-BORDER_WIDTH)
7223 .shadow(smallvec![gpui::BoxShadow {
7224 color: gpui::black().opacity(0.05),
7225 offset: point(px(1.), px(1.)),
7226 blur_radius: px(2.),
7227 spread_radius: px(0.),
7228 }])
7229 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7230 .border(BORDER_WIDTH)
7231 .border_color(cx.theme().colors().border)
7232 .rounded_r_lg()
7233 .id("edit_prediction_diff_popover_keybind")
7234 .when(!has_keybind, |el| {
7235 let status_colors = cx.theme().status();
7236
7237 el.bg(status_colors.error_background)
7238 .border_color(status_colors.error.opacity(0.6))
7239 .child(Icon::new(IconName::Info).color(Color::Error))
7240 .cursor_default()
7241 .hoverable_tooltip(move |_window, cx| {
7242 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7243 })
7244 })
7245 .children(keybind),
7246 )
7247 .into_any();
7248
7249 let longest_row =
7250 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7251 let longest_line_width = if visible_row_range.contains(&longest_row) {
7252 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7253 } else {
7254 layout_line(
7255 longest_row,
7256 editor_snapshot,
7257 style,
7258 editor_width,
7259 |_| false,
7260 window,
7261 cx,
7262 )
7263 .width
7264 };
7265
7266 let viewport_bounds =
7267 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7268 right: -EditorElement::SCROLLBAR_WIDTH,
7269 ..Default::default()
7270 });
7271
7272 let x_after_longest =
7273 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7274 - scroll_pixel_position.x;
7275
7276 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7277
7278 // Fully visible if it can be displayed within the window (allow overlapping other
7279 // panes). However, this is only allowed if the popover starts within text_bounds.
7280 let can_position_to_the_right = x_after_longest < text_bounds.right()
7281 && x_after_longest + element_bounds.width < viewport_bounds.right();
7282
7283 let mut origin = if can_position_to_the_right {
7284 point(
7285 x_after_longest,
7286 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7287 - scroll_pixel_position.y,
7288 )
7289 } else {
7290 let cursor_row = newest_selection_head.map(|head| head.row());
7291 let above_edit = edit_start
7292 .row()
7293 .0
7294 .checked_sub(line_count as u32)
7295 .map(DisplayRow);
7296 let below_edit = Some(edit_end.row() + 1);
7297 let above_cursor =
7298 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7299 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7300
7301 // Place the edit popover adjacent to the edit if there is a location
7302 // available that is onscreen and does not obscure the cursor. Otherwise,
7303 // place it adjacent to the cursor.
7304 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7305 .into_iter()
7306 .flatten()
7307 .find(|&start_row| {
7308 let end_row = start_row + line_count as u32;
7309 visible_row_range.contains(&start_row)
7310 && visible_row_range.contains(&end_row)
7311 && cursor_row.map_or(true, |cursor_row| {
7312 !((start_row..end_row).contains(&cursor_row))
7313 })
7314 })?;
7315
7316 content_origin
7317 + point(
7318 -scroll_pixel_position.x,
7319 row_target.as_f32() * line_height - scroll_pixel_position.y,
7320 )
7321 };
7322
7323 origin.x -= BORDER_WIDTH;
7324
7325 window.defer_draw(element, origin, 1);
7326
7327 // Do not return an element, since it will already be drawn due to defer_draw.
7328 None
7329 }
7330
7331 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7332 px(30.)
7333 }
7334
7335 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7336 if self.read_only(cx) {
7337 cx.theme().players().read_only()
7338 } else {
7339 self.style.as_ref().unwrap().local_player
7340 }
7341 }
7342
7343 fn render_edit_prediction_accept_keybind(
7344 &self,
7345 window: &mut Window,
7346 cx: &App,
7347 ) -> Option<AnyElement> {
7348 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7349 let accept_keystroke = accept_binding.keystroke()?;
7350
7351 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7352
7353 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7354 Color::Accent
7355 } else {
7356 Color::Muted
7357 };
7358
7359 h_flex()
7360 .px_0p5()
7361 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7362 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7363 .text_size(TextSize::XSmall.rems(cx))
7364 .child(h_flex().children(ui::render_modifiers(
7365 &accept_keystroke.modifiers,
7366 PlatformStyle::platform(),
7367 Some(modifiers_color),
7368 Some(IconSize::XSmall.rems().into()),
7369 true,
7370 )))
7371 .when(is_platform_style_mac, |parent| {
7372 parent.child(accept_keystroke.key.clone())
7373 })
7374 .when(!is_platform_style_mac, |parent| {
7375 parent.child(
7376 Key::new(
7377 util::capitalize(&accept_keystroke.key),
7378 Some(Color::Default),
7379 )
7380 .size(Some(IconSize::XSmall.rems().into())),
7381 )
7382 })
7383 .into_any()
7384 .into()
7385 }
7386
7387 fn render_edit_prediction_line_popover(
7388 &self,
7389 label: impl Into<SharedString>,
7390 icon: Option<IconName>,
7391 window: &mut Window,
7392 cx: &App,
7393 ) -> Option<Stateful<Div>> {
7394 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7395
7396 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7397 let has_keybind = keybind.is_some();
7398
7399 let result = h_flex()
7400 .id("ep-line-popover")
7401 .py_0p5()
7402 .pl_1()
7403 .pr(padding_right)
7404 .gap_1()
7405 .rounded_md()
7406 .border_1()
7407 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7408 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7409 .shadow_sm()
7410 .when(!has_keybind, |el| {
7411 let status_colors = cx.theme().status();
7412
7413 el.bg(status_colors.error_background)
7414 .border_color(status_colors.error.opacity(0.6))
7415 .pl_2()
7416 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7417 .cursor_default()
7418 .hoverable_tooltip(move |_window, cx| {
7419 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7420 })
7421 })
7422 .children(keybind)
7423 .child(
7424 Label::new(label)
7425 .size(LabelSize::Small)
7426 .when(!has_keybind, |el| {
7427 el.color(cx.theme().status().error.into()).strikethrough()
7428 }),
7429 )
7430 .when(!has_keybind, |el| {
7431 el.child(
7432 h_flex().ml_1().child(
7433 Icon::new(IconName::Info)
7434 .size(IconSize::Small)
7435 .color(cx.theme().status().error.into()),
7436 ),
7437 )
7438 })
7439 .when_some(icon, |element, icon| {
7440 element.child(
7441 div()
7442 .mt(px(1.5))
7443 .child(Icon::new(icon).size(IconSize::Small)),
7444 )
7445 });
7446
7447 Some(result)
7448 }
7449
7450 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7451 let accent_color = cx.theme().colors().text_accent;
7452 let editor_bg_color = cx.theme().colors().editor_background;
7453 editor_bg_color.blend(accent_color.opacity(0.1))
7454 }
7455
7456 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7457 let accent_color = cx.theme().colors().text_accent;
7458 let editor_bg_color = cx.theme().colors().editor_background;
7459 editor_bg_color.blend(accent_color.opacity(0.6))
7460 }
7461
7462 fn render_edit_prediction_cursor_popover(
7463 &self,
7464 min_width: Pixels,
7465 max_width: Pixels,
7466 cursor_point: Point,
7467 style: &EditorStyle,
7468 accept_keystroke: Option<&gpui::Keystroke>,
7469 _window: &Window,
7470 cx: &mut Context<Editor>,
7471 ) -> Option<AnyElement> {
7472 let provider = self.edit_prediction_provider.as_ref()?;
7473
7474 if provider.provider.needs_terms_acceptance(cx) {
7475 return Some(
7476 h_flex()
7477 .min_w(min_width)
7478 .flex_1()
7479 .px_2()
7480 .py_1()
7481 .gap_3()
7482 .elevation_2(cx)
7483 .hover(|style| style.bg(cx.theme().colors().element_hover))
7484 .id("accept-terms")
7485 .cursor_pointer()
7486 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7487 .on_click(cx.listener(|this, _event, window, cx| {
7488 cx.stop_propagation();
7489 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7490 window.dispatch_action(
7491 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7492 cx,
7493 );
7494 }))
7495 .child(
7496 h_flex()
7497 .flex_1()
7498 .gap_2()
7499 .child(Icon::new(IconName::ZedPredict))
7500 .child(Label::new("Accept Terms of Service"))
7501 .child(div().w_full())
7502 .child(
7503 Icon::new(IconName::ArrowUpRight)
7504 .color(Color::Muted)
7505 .size(IconSize::Small),
7506 )
7507 .into_any_element(),
7508 )
7509 .into_any(),
7510 );
7511 }
7512
7513 let is_refreshing = provider.provider.is_refreshing(cx);
7514
7515 fn pending_completion_container() -> Div {
7516 h_flex()
7517 .h_full()
7518 .flex_1()
7519 .gap_2()
7520 .child(Icon::new(IconName::ZedPredict))
7521 }
7522
7523 let completion = match &self.active_inline_completion {
7524 Some(prediction) => {
7525 if !self.has_visible_completions_menu() {
7526 const RADIUS: Pixels = px(6.);
7527 const BORDER_WIDTH: Pixels = px(1.);
7528
7529 return Some(
7530 h_flex()
7531 .elevation_2(cx)
7532 .border(BORDER_WIDTH)
7533 .border_color(cx.theme().colors().border)
7534 .when(accept_keystroke.is_none(), |el| {
7535 el.border_color(cx.theme().status().error)
7536 })
7537 .rounded(RADIUS)
7538 .rounded_tl(px(0.))
7539 .overflow_hidden()
7540 .child(div().px_1p5().child(match &prediction.completion {
7541 InlineCompletion::Move { target, snapshot } => {
7542 use text::ToPoint as _;
7543 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7544 {
7545 Icon::new(IconName::ZedPredictDown)
7546 } else {
7547 Icon::new(IconName::ZedPredictUp)
7548 }
7549 }
7550 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7551 }))
7552 .child(
7553 h_flex()
7554 .gap_1()
7555 .py_1()
7556 .px_2()
7557 .rounded_r(RADIUS - BORDER_WIDTH)
7558 .border_l_1()
7559 .border_color(cx.theme().colors().border)
7560 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7561 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7562 el.child(
7563 Label::new("Hold")
7564 .size(LabelSize::Small)
7565 .when(accept_keystroke.is_none(), |el| {
7566 el.strikethrough()
7567 })
7568 .line_height_style(LineHeightStyle::UiLabel),
7569 )
7570 })
7571 .id("edit_prediction_cursor_popover_keybind")
7572 .when(accept_keystroke.is_none(), |el| {
7573 let status_colors = cx.theme().status();
7574
7575 el.bg(status_colors.error_background)
7576 .border_color(status_colors.error.opacity(0.6))
7577 .child(Icon::new(IconName::Info).color(Color::Error))
7578 .cursor_default()
7579 .hoverable_tooltip(move |_window, cx| {
7580 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7581 .into()
7582 })
7583 })
7584 .when_some(
7585 accept_keystroke.as_ref(),
7586 |el, accept_keystroke| {
7587 el.child(h_flex().children(ui::render_modifiers(
7588 &accept_keystroke.modifiers,
7589 PlatformStyle::platform(),
7590 Some(Color::Default),
7591 Some(IconSize::XSmall.rems().into()),
7592 false,
7593 )))
7594 },
7595 ),
7596 )
7597 .into_any(),
7598 );
7599 }
7600
7601 self.render_edit_prediction_cursor_popover_preview(
7602 prediction,
7603 cursor_point,
7604 style,
7605 cx,
7606 )?
7607 }
7608
7609 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7610 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7611 stale_completion,
7612 cursor_point,
7613 style,
7614 cx,
7615 )?,
7616
7617 None => {
7618 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7619 }
7620 },
7621
7622 None => pending_completion_container().child(Label::new("No Prediction")),
7623 };
7624
7625 let completion = if is_refreshing {
7626 completion
7627 .with_animation(
7628 "loading-completion",
7629 Animation::new(Duration::from_secs(2))
7630 .repeat()
7631 .with_easing(pulsating_between(0.4, 0.8)),
7632 |label, delta| label.opacity(delta),
7633 )
7634 .into_any_element()
7635 } else {
7636 completion.into_any_element()
7637 };
7638
7639 let has_completion = self.active_inline_completion.is_some();
7640
7641 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7642 Some(
7643 h_flex()
7644 .min_w(min_width)
7645 .max_w(max_width)
7646 .flex_1()
7647 .elevation_2(cx)
7648 .border_color(cx.theme().colors().border)
7649 .child(
7650 div()
7651 .flex_1()
7652 .py_1()
7653 .px_2()
7654 .overflow_hidden()
7655 .child(completion),
7656 )
7657 .when_some(accept_keystroke, |el, accept_keystroke| {
7658 if !accept_keystroke.modifiers.modified() {
7659 return el;
7660 }
7661
7662 el.child(
7663 h_flex()
7664 .h_full()
7665 .border_l_1()
7666 .rounded_r_lg()
7667 .border_color(cx.theme().colors().border)
7668 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7669 .gap_1()
7670 .py_1()
7671 .px_2()
7672 .child(
7673 h_flex()
7674 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7675 .when(is_platform_style_mac, |parent| parent.gap_1())
7676 .child(h_flex().children(ui::render_modifiers(
7677 &accept_keystroke.modifiers,
7678 PlatformStyle::platform(),
7679 Some(if !has_completion {
7680 Color::Muted
7681 } else {
7682 Color::Default
7683 }),
7684 None,
7685 false,
7686 ))),
7687 )
7688 .child(Label::new("Preview").into_any_element())
7689 .opacity(if has_completion { 1.0 } else { 0.4 }),
7690 )
7691 })
7692 .into_any(),
7693 )
7694 }
7695
7696 fn render_edit_prediction_cursor_popover_preview(
7697 &self,
7698 completion: &InlineCompletionState,
7699 cursor_point: Point,
7700 style: &EditorStyle,
7701 cx: &mut Context<Editor>,
7702 ) -> Option<Div> {
7703 use text::ToPoint as _;
7704
7705 fn render_relative_row_jump(
7706 prefix: impl Into<String>,
7707 current_row: u32,
7708 target_row: u32,
7709 ) -> Div {
7710 let (row_diff, arrow) = if target_row < current_row {
7711 (current_row - target_row, IconName::ArrowUp)
7712 } else {
7713 (target_row - current_row, IconName::ArrowDown)
7714 };
7715
7716 h_flex()
7717 .child(
7718 Label::new(format!("{}{}", prefix.into(), row_diff))
7719 .color(Color::Muted)
7720 .size(LabelSize::Small),
7721 )
7722 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7723 }
7724
7725 match &completion.completion {
7726 InlineCompletion::Move {
7727 target, snapshot, ..
7728 } => Some(
7729 h_flex()
7730 .px_2()
7731 .gap_2()
7732 .flex_1()
7733 .child(
7734 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7735 Icon::new(IconName::ZedPredictDown)
7736 } else {
7737 Icon::new(IconName::ZedPredictUp)
7738 },
7739 )
7740 .child(Label::new("Jump to Edit")),
7741 ),
7742
7743 InlineCompletion::Edit {
7744 edits,
7745 edit_preview,
7746 snapshot,
7747 display_mode: _,
7748 } => {
7749 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7750
7751 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7752 &snapshot,
7753 &edits,
7754 edit_preview.as_ref()?,
7755 true,
7756 cx,
7757 )
7758 .first_line_preview();
7759
7760 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7761 .with_default_highlights(&style.text, highlighted_edits.highlights);
7762
7763 let preview = h_flex()
7764 .gap_1()
7765 .min_w_16()
7766 .child(styled_text)
7767 .when(has_more_lines, |parent| parent.child("…"));
7768
7769 let left = if first_edit_row != cursor_point.row {
7770 render_relative_row_jump("", cursor_point.row, first_edit_row)
7771 .into_any_element()
7772 } else {
7773 Icon::new(IconName::ZedPredict).into_any_element()
7774 };
7775
7776 Some(
7777 h_flex()
7778 .h_full()
7779 .flex_1()
7780 .gap_2()
7781 .pr_1()
7782 .overflow_x_hidden()
7783 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7784 .child(left)
7785 .child(preview),
7786 )
7787 }
7788 }
7789 }
7790
7791 fn render_context_menu(
7792 &self,
7793 style: &EditorStyle,
7794 max_height_in_lines: u32,
7795 window: &mut Window,
7796 cx: &mut Context<Editor>,
7797 ) -> Option<AnyElement> {
7798 let menu = self.context_menu.borrow();
7799 let menu = menu.as_ref()?;
7800 if !menu.visible() {
7801 return None;
7802 };
7803 Some(menu.render(style, max_height_in_lines, window, cx))
7804 }
7805
7806 fn render_context_menu_aside(
7807 &mut self,
7808 max_size: Size<Pixels>,
7809 window: &mut Window,
7810 cx: &mut Context<Editor>,
7811 ) -> Option<AnyElement> {
7812 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7813 if menu.visible() {
7814 menu.render_aside(self, max_size, window, cx)
7815 } else {
7816 None
7817 }
7818 })
7819 }
7820
7821 fn hide_context_menu(
7822 &mut self,
7823 window: &mut Window,
7824 cx: &mut Context<Self>,
7825 ) -> Option<CodeContextMenu> {
7826 cx.notify();
7827 self.completion_tasks.clear();
7828 let context_menu = self.context_menu.borrow_mut().take();
7829 self.stale_inline_completion_in_menu.take();
7830 self.update_visible_inline_completion(window, cx);
7831 context_menu
7832 }
7833
7834 fn show_snippet_choices(
7835 &mut self,
7836 choices: &Vec<String>,
7837 selection: Range<Anchor>,
7838 cx: &mut Context<Self>,
7839 ) {
7840 if selection.start.buffer_id.is_none() {
7841 return;
7842 }
7843 let buffer_id = selection.start.buffer_id.unwrap();
7844 let buffer = self.buffer().read(cx).buffer(buffer_id);
7845 let id = post_inc(&mut self.next_completion_id);
7846
7847 if let Some(buffer) = buffer {
7848 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7849 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7850 ));
7851 }
7852 }
7853
7854 pub fn insert_snippet(
7855 &mut self,
7856 insertion_ranges: &[Range<usize>],
7857 snippet: Snippet,
7858 window: &mut Window,
7859 cx: &mut Context<Self>,
7860 ) -> Result<()> {
7861 struct Tabstop<T> {
7862 is_end_tabstop: bool,
7863 ranges: Vec<Range<T>>,
7864 choices: Option<Vec<String>>,
7865 }
7866
7867 let tabstops = self.buffer.update(cx, |buffer, cx| {
7868 let snippet_text: Arc<str> = snippet.text.clone().into();
7869 let edits = insertion_ranges
7870 .iter()
7871 .cloned()
7872 .map(|range| (range, snippet_text.clone()));
7873 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7874
7875 let snapshot = &*buffer.read(cx);
7876 let snippet = &snippet;
7877 snippet
7878 .tabstops
7879 .iter()
7880 .map(|tabstop| {
7881 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7882 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7883 });
7884 let mut tabstop_ranges = tabstop
7885 .ranges
7886 .iter()
7887 .flat_map(|tabstop_range| {
7888 let mut delta = 0_isize;
7889 insertion_ranges.iter().map(move |insertion_range| {
7890 let insertion_start = insertion_range.start as isize + delta;
7891 delta +=
7892 snippet.text.len() as isize - insertion_range.len() as isize;
7893
7894 let start = ((insertion_start + tabstop_range.start) as usize)
7895 .min(snapshot.len());
7896 let end = ((insertion_start + tabstop_range.end) as usize)
7897 .min(snapshot.len());
7898 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7899 })
7900 })
7901 .collect::<Vec<_>>();
7902 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7903
7904 Tabstop {
7905 is_end_tabstop,
7906 ranges: tabstop_ranges,
7907 choices: tabstop.choices.clone(),
7908 }
7909 })
7910 .collect::<Vec<_>>()
7911 });
7912 if let Some(tabstop) = tabstops.first() {
7913 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7914 s.select_ranges(tabstop.ranges.iter().cloned());
7915 });
7916
7917 if let Some(choices) = &tabstop.choices {
7918 if let Some(selection) = tabstop.ranges.first() {
7919 self.show_snippet_choices(choices, selection.clone(), cx)
7920 }
7921 }
7922
7923 // If we're already at the last tabstop and it's at the end of the snippet,
7924 // we're done, we don't need to keep the state around.
7925 if !tabstop.is_end_tabstop {
7926 let choices = tabstops
7927 .iter()
7928 .map(|tabstop| tabstop.choices.clone())
7929 .collect();
7930
7931 let ranges = tabstops
7932 .into_iter()
7933 .map(|tabstop| tabstop.ranges)
7934 .collect::<Vec<_>>();
7935
7936 self.snippet_stack.push(SnippetState {
7937 active_index: 0,
7938 ranges,
7939 choices,
7940 });
7941 }
7942
7943 // Check whether the just-entered snippet ends with an auto-closable bracket.
7944 if self.autoclose_regions.is_empty() {
7945 let snapshot = self.buffer.read(cx).snapshot(cx);
7946 for selection in &mut self.selections.all::<Point>(cx) {
7947 let selection_head = selection.head();
7948 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7949 continue;
7950 };
7951
7952 let mut bracket_pair = None;
7953 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7954 let prev_chars = snapshot
7955 .reversed_chars_at(selection_head)
7956 .collect::<String>();
7957 for (pair, enabled) in scope.brackets() {
7958 if enabled
7959 && pair.close
7960 && prev_chars.starts_with(pair.start.as_str())
7961 && next_chars.starts_with(pair.end.as_str())
7962 {
7963 bracket_pair = Some(pair.clone());
7964 break;
7965 }
7966 }
7967 if let Some(pair) = bracket_pair {
7968 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
7969 let autoclose_enabled =
7970 self.use_autoclose && snapshot_settings.use_autoclose;
7971 if autoclose_enabled {
7972 let start = snapshot.anchor_after(selection_head);
7973 let end = snapshot.anchor_after(selection_head);
7974 self.autoclose_regions.push(AutocloseRegion {
7975 selection_id: selection.id,
7976 range: start..end,
7977 pair,
7978 });
7979 }
7980 }
7981 }
7982 }
7983 }
7984 Ok(())
7985 }
7986
7987 pub fn move_to_next_snippet_tabstop(
7988 &mut self,
7989 window: &mut Window,
7990 cx: &mut Context<Self>,
7991 ) -> bool {
7992 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7993 }
7994
7995 pub fn move_to_prev_snippet_tabstop(
7996 &mut self,
7997 window: &mut Window,
7998 cx: &mut Context<Self>,
7999 ) -> bool {
8000 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8001 }
8002
8003 pub fn move_to_snippet_tabstop(
8004 &mut self,
8005 bias: Bias,
8006 window: &mut Window,
8007 cx: &mut Context<Self>,
8008 ) -> bool {
8009 if let Some(mut snippet) = self.snippet_stack.pop() {
8010 match bias {
8011 Bias::Left => {
8012 if snippet.active_index > 0 {
8013 snippet.active_index -= 1;
8014 } else {
8015 self.snippet_stack.push(snippet);
8016 return false;
8017 }
8018 }
8019 Bias::Right => {
8020 if snippet.active_index + 1 < snippet.ranges.len() {
8021 snippet.active_index += 1;
8022 } else {
8023 self.snippet_stack.push(snippet);
8024 return false;
8025 }
8026 }
8027 }
8028 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8029 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8030 s.select_anchor_ranges(current_ranges.iter().cloned())
8031 });
8032
8033 if let Some(choices) = &snippet.choices[snippet.active_index] {
8034 if let Some(selection) = current_ranges.first() {
8035 self.show_snippet_choices(&choices, selection.clone(), cx);
8036 }
8037 }
8038
8039 // If snippet state is not at the last tabstop, push it back on the stack
8040 if snippet.active_index + 1 < snippet.ranges.len() {
8041 self.snippet_stack.push(snippet);
8042 }
8043 return true;
8044 }
8045 }
8046
8047 false
8048 }
8049
8050 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8051 self.transact(window, cx, |this, window, cx| {
8052 this.select_all(&SelectAll, window, cx);
8053 this.insert("", window, cx);
8054 });
8055 }
8056
8057 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8058 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8059 self.transact(window, cx, |this, window, cx| {
8060 this.select_autoclose_pair(window, cx);
8061 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8062 if !this.linked_edit_ranges.is_empty() {
8063 let selections = this.selections.all::<MultiBufferPoint>(cx);
8064 let snapshot = this.buffer.read(cx).snapshot(cx);
8065
8066 for selection in selections.iter() {
8067 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8068 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8069 if selection_start.buffer_id != selection_end.buffer_id {
8070 continue;
8071 }
8072 if let Some(ranges) =
8073 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8074 {
8075 for (buffer, entries) in ranges {
8076 linked_ranges.entry(buffer).or_default().extend(entries);
8077 }
8078 }
8079 }
8080 }
8081
8082 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8083 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8084 for selection in &mut selections {
8085 if selection.is_empty() {
8086 let old_head = selection.head();
8087 let mut new_head =
8088 movement::left(&display_map, old_head.to_display_point(&display_map))
8089 .to_point(&display_map);
8090 if let Some((buffer, line_buffer_range)) = display_map
8091 .buffer_snapshot
8092 .buffer_line_for_row(MultiBufferRow(old_head.row))
8093 {
8094 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8095 let indent_len = match indent_size.kind {
8096 IndentKind::Space => {
8097 buffer.settings_at(line_buffer_range.start, cx).tab_size
8098 }
8099 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8100 };
8101 if old_head.column <= indent_size.len && old_head.column > 0 {
8102 let indent_len = indent_len.get();
8103 new_head = cmp::min(
8104 new_head,
8105 MultiBufferPoint::new(
8106 old_head.row,
8107 ((old_head.column - 1) / indent_len) * indent_len,
8108 ),
8109 );
8110 }
8111 }
8112
8113 selection.set_head(new_head, SelectionGoal::None);
8114 }
8115 }
8116
8117 this.signature_help_state.set_backspace_pressed(true);
8118 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8119 s.select(selections)
8120 });
8121 this.insert("", window, cx);
8122 let empty_str: Arc<str> = Arc::from("");
8123 for (buffer, edits) in linked_ranges {
8124 let snapshot = buffer.read(cx).snapshot();
8125 use text::ToPoint as TP;
8126
8127 let edits = edits
8128 .into_iter()
8129 .map(|range| {
8130 let end_point = TP::to_point(&range.end, &snapshot);
8131 let mut start_point = TP::to_point(&range.start, &snapshot);
8132
8133 if end_point == start_point {
8134 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8135 .saturating_sub(1);
8136 start_point =
8137 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8138 };
8139
8140 (start_point..end_point, empty_str.clone())
8141 })
8142 .sorted_by_key(|(range, _)| range.start)
8143 .collect::<Vec<_>>();
8144 buffer.update(cx, |this, cx| {
8145 this.edit(edits, None, cx);
8146 })
8147 }
8148 this.refresh_inline_completion(true, false, window, cx);
8149 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8150 });
8151 }
8152
8153 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8154 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8155 self.transact(window, cx, |this, window, cx| {
8156 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8157 s.move_with(|map, selection| {
8158 if selection.is_empty() {
8159 let cursor = movement::right(map, selection.head());
8160 selection.end = cursor;
8161 selection.reversed = true;
8162 selection.goal = SelectionGoal::None;
8163 }
8164 })
8165 });
8166 this.insert("", window, cx);
8167 this.refresh_inline_completion(true, false, window, cx);
8168 });
8169 }
8170
8171 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8172 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8173 if self.move_to_prev_snippet_tabstop(window, cx) {
8174 return;
8175 }
8176 self.outdent(&Outdent, window, cx);
8177 }
8178
8179 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8180 if self.move_to_next_snippet_tabstop(window, cx) {
8181 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8182 return;
8183 }
8184 if self.read_only(cx) {
8185 return;
8186 }
8187 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8188 let mut selections = self.selections.all_adjusted(cx);
8189 let buffer = self.buffer.read(cx);
8190 let snapshot = buffer.snapshot(cx);
8191 let rows_iter = selections.iter().map(|s| s.head().row);
8192 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8193
8194 let mut edits = Vec::new();
8195 let mut prev_edited_row = 0;
8196 let mut row_delta = 0;
8197 for selection in &mut selections {
8198 if selection.start.row != prev_edited_row {
8199 row_delta = 0;
8200 }
8201 prev_edited_row = selection.end.row;
8202
8203 // If the selection is non-empty, then increase the indentation of the selected lines.
8204 if !selection.is_empty() {
8205 row_delta =
8206 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8207 continue;
8208 }
8209
8210 // If the selection is empty and the cursor is in the leading whitespace before the
8211 // suggested indentation, then auto-indent the line.
8212 let cursor = selection.head();
8213 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8214 if let Some(suggested_indent) =
8215 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8216 {
8217 if cursor.column < suggested_indent.len
8218 && cursor.column <= current_indent.len
8219 && current_indent.len <= suggested_indent.len
8220 {
8221 selection.start = Point::new(cursor.row, suggested_indent.len);
8222 selection.end = selection.start;
8223 if row_delta == 0 {
8224 edits.extend(Buffer::edit_for_indent_size_adjustment(
8225 cursor.row,
8226 current_indent,
8227 suggested_indent,
8228 ));
8229 row_delta = suggested_indent.len - current_indent.len;
8230 }
8231 continue;
8232 }
8233 }
8234
8235 // Otherwise, insert a hard or soft tab.
8236 let settings = buffer.language_settings_at(cursor, cx);
8237 let tab_size = if settings.hard_tabs {
8238 IndentSize::tab()
8239 } else {
8240 let tab_size = settings.tab_size.get();
8241 let char_column = snapshot
8242 .text_for_range(Point::new(cursor.row, 0)..cursor)
8243 .flat_map(str::chars)
8244 .count()
8245 + row_delta as usize;
8246 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
8247 IndentSize::spaces(chars_to_next_tab_stop)
8248 };
8249 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8250 selection.end = selection.start;
8251 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8252 row_delta += tab_size.len;
8253 }
8254
8255 self.transact(window, cx, |this, window, cx| {
8256 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8257 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8258 s.select(selections)
8259 });
8260 this.refresh_inline_completion(true, false, window, cx);
8261 });
8262 }
8263
8264 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8265 if self.read_only(cx) {
8266 return;
8267 }
8268 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8269 let mut selections = self.selections.all::<Point>(cx);
8270 let mut prev_edited_row = 0;
8271 let mut row_delta = 0;
8272 let mut edits = Vec::new();
8273 let buffer = self.buffer.read(cx);
8274 let snapshot = buffer.snapshot(cx);
8275 for selection in &mut selections {
8276 if selection.start.row != prev_edited_row {
8277 row_delta = 0;
8278 }
8279 prev_edited_row = selection.end.row;
8280
8281 row_delta =
8282 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8283 }
8284
8285 self.transact(window, cx, |this, window, cx| {
8286 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8287 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8288 s.select(selections)
8289 });
8290 });
8291 }
8292
8293 fn indent_selection(
8294 buffer: &MultiBuffer,
8295 snapshot: &MultiBufferSnapshot,
8296 selection: &mut Selection<Point>,
8297 edits: &mut Vec<(Range<Point>, String)>,
8298 delta_for_start_row: u32,
8299 cx: &App,
8300 ) -> u32 {
8301 let settings = buffer.language_settings_at(selection.start, cx);
8302 let tab_size = settings.tab_size.get();
8303 let indent_kind = if settings.hard_tabs {
8304 IndentKind::Tab
8305 } else {
8306 IndentKind::Space
8307 };
8308 let mut start_row = selection.start.row;
8309 let mut end_row = selection.end.row + 1;
8310
8311 // If a selection ends at the beginning of a line, don't indent
8312 // that last line.
8313 if selection.end.column == 0 && selection.end.row > selection.start.row {
8314 end_row -= 1;
8315 }
8316
8317 // Avoid re-indenting a row that has already been indented by a
8318 // previous selection, but still update this selection's column
8319 // to reflect that indentation.
8320 if delta_for_start_row > 0 {
8321 start_row += 1;
8322 selection.start.column += delta_for_start_row;
8323 if selection.end.row == selection.start.row {
8324 selection.end.column += delta_for_start_row;
8325 }
8326 }
8327
8328 let mut delta_for_end_row = 0;
8329 let has_multiple_rows = start_row + 1 != end_row;
8330 for row in start_row..end_row {
8331 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8332 let indent_delta = match (current_indent.kind, indent_kind) {
8333 (IndentKind::Space, IndentKind::Space) => {
8334 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8335 IndentSize::spaces(columns_to_next_tab_stop)
8336 }
8337 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8338 (_, IndentKind::Tab) => IndentSize::tab(),
8339 };
8340
8341 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8342 0
8343 } else {
8344 selection.start.column
8345 };
8346 let row_start = Point::new(row, start);
8347 edits.push((
8348 row_start..row_start,
8349 indent_delta.chars().collect::<String>(),
8350 ));
8351
8352 // Update this selection's endpoints to reflect the indentation.
8353 if row == selection.start.row {
8354 selection.start.column += indent_delta.len;
8355 }
8356 if row == selection.end.row {
8357 selection.end.column += indent_delta.len;
8358 delta_for_end_row = indent_delta.len;
8359 }
8360 }
8361
8362 if selection.start.row == selection.end.row {
8363 delta_for_start_row + delta_for_end_row
8364 } else {
8365 delta_for_end_row
8366 }
8367 }
8368
8369 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8370 if self.read_only(cx) {
8371 return;
8372 }
8373 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8374 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8375 let selections = self.selections.all::<Point>(cx);
8376 let mut deletion_ranges = Vec::new();
8377 let mut last_outdent = None;
8378 {
8379 let buffer = self.buffer.read(cx);
8380 let snapshot = buffer.snapshot(cx);
8381 for selection in &selections {
8382 let settings = buffer.language_settings_at(selection.start, cx);
8383 let tab_size = settings.tab_size.get();
8384 let mut rows = selection.spanned_rows(false, &display_map);
8385
8386 // Avoid re-outdenting a row that has already been outdented by a
8387 // previous selection.
8388 if let Some(last_row) = last_outdent {
8389 if last_row == rows.start {
8390 rows.start = rows.start.next_row();
8391 }
8392 }
8393 let has_multiple_rows = rows.len() > 1;
8394 for row in rows.iter_rows() {
8395 let indent_size = snapshot.indent_size_for_line(row);
8396 if indent_size.len > 0 {
8397 let deletion_len = match indent_size.kind {
8398 IndentKind::Space => {
8399 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8400 if columns_to_prev_tab_stop == 0 {
8401 tab_size
8402 } else {
8403 columns_to_prev_tab_stop
8404 }
8405 }
8406 IndentKind::Tab => 1,
8407 };
8408 let start = if has_multiple_rows
8409 || deletion_len > selection.start.column
8410 || indent_size.len < selection.start.column
8411 {
8412 0
8413 } else {
8414 selection.start.column - deletion_len
8415 };
8416 deletion_ranges.push(
8417 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8418 );
8419 last_outdent = Some(row);
8420 }
8421 }
8422 }
8423 }
8424
8425 self.transact(window, cx, |this, window, cx| {
8426 this.buffer.update(cx, |buffer, cx| {
8427 let empty_str: Arc<str> = Arc::default();
8428 buffer.edit(
8429 deletion_ranges
8430 .into_iter()
8431 .map(|range| (range, empty_str.clone())),
8432 None,
8433 cx,
8434 );
8435 });
8436 let selections = this.selections.all::<usize>(cx);
8437 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8438 s.select(selections)
8439 });
8440 });
8441 }
8442
8443 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8444 if self.read_only(cx) {
8445 return;
8446 }
8447 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8448 let selections = self
8449 .selections
8450 .all::<usize>(cx)
8451 .into_iter()
8452 .map(|s| s.range());
8453
8454 self.transact(window, cx, |this, window, cx| {
8455 this.buffer.update(cx, |buffer, cx| {
8456 buffer.autoindent_ranges(selections, cx);
8457 });
8458 let selections = this.selections.all::<usize>(cx);
8459 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8460 s.select(selections)
8461 });
8462 });
8463 }
8464
8465 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8466 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8468 let selections = self.selections.all::<Point>(cx);
8469
8470 let mut new_cursors = Vec::new();
8471 let mut edit_ranges = Vec::new();
8472 let mut selections = selections.iter().peekable();
8473 while let Some(selection) = selections.next() {
8474 let mut rows = selection.spanned_rows(false, &display_map);
8475 let goal_display_column = selection.head().to_display_point(&display_map).column();
8476
8477 // Accumulate contiguous regions of rows that we want to delete.
8478 while let Some(next_selection) = selections.peek() {
8479 let next_rows = next_selection.spanned_rows(false, &display_map);
8480 if next_rows.start <= rows.end {
8481 rows.end = next_rows.end;
8482 selections.next().unwrap();
8483 } else {
8484 break;
8485 }
8486 }
8487
8488 let buffer = &display_map.buffer_snapshot;
8489 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8490 let edit_end;
8491 let cursor_buffer_row;
8492 if buffer.max_point().row >= rows.end.0 {
8493 // If there's a line after the range, delete the \n from the end of the row range
8494 // and position the cursor on the next line.
8495 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8496 cursor_buffer_row = rows.end;
8497 } else {
8498 // If there isn't a line after the range, delete the \n from the line before the
8499 // start of the row range and position the cursor there.
8500 edit_start = edit_start.saturating_sub(1);
8501 edit_end = buffer.len();
8502 cursor_buffer_row = rows.start.previous_row();
8503 }
8504
8505 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8506 *cursor.column_mut() =
8507 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8508
8509 new_cursors.push((
8510 selection.id,
8511 buffer.anchor_after(cursor.to_point(&display_map)),
8512 ));
8513 edit_ranges.push(edit_start..edit_end);
8514 }
8515
8516 self.transact(window, cx, |this, window, cx| {
8517 let buffer = this.buffer.update(cx, |buffer, cx| {
8518 let empty_str: Arc<str> = Arc::default();
8519 buffer.edit(
8520 edit_ranges
8521 .into_iter()
8522 .map(|range| (range, empty_str.clone())),
8523 None,
8524 cx,
8525 );
8526 buffer.snapshot(cx)
8527 });
8528 let new_selections = new_cursors
8529 .into_iter()
8530 .map(|(id, cursor)| {
8531 let cursor = cursor.to_point(&buffer);
8532 Selection {
8533 id,
8534 start: cursor,
8535 end: cursor,
8536 reversed: false,
8537 goal: SelectionGoal::None,
8538 }
8539 })
8540 .collect();
8541
8542 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8543 s.select(new_selections);
8544 });
8545 });
8546 }
8547
8548 pub fn join_lines_impl(
8549 &mut self,
8550 insert_whitespace: bool,
8551 window: &mut Window,
8552 cx: &mut Context<Self>,
8553 ) {
8554 if self.read_only(cx) {
8555 return;
8556 }
8557 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8558 for selection in self.selections.all::<Point>(cx) {
8559 let start = MultiBufferRow(selection.start.row);
8560 // Treat single line selections as if they include the next line. Otherwise this action
8561 // would do nothing for single line selections individual cursors.
8562 let end = if selection.start.row == selection.end.row {
8563 MultiBufferRow(selection.start.row + 1)
8564 } else {
8565 MultiBufferRow(selection.end.row)
8566 };
8567
8568 if let Some(last_row_range) = row_ranges.last_mut() {
8569 if start <= last_row_range.end {
8570 last_row_range.end = end;
8571 continue;
8572 }
8573 }
8574 row_ranges.push(start..end);
8575 }
8576
8577 let snapshot = self.buffer.read(cx).snapshot(cx);
8578 let mut cursor_positions = Vec::new();
8579 for row_range in &row_ranges {
8580 let anchor = snapshot.anchor_before(Point::new(
8581 row_range.end.previous_row().0,
8582 snapshot.line_len(row_range.end.previous_row()),
8583 ));
8584 cursor_positions.push(anchor..anchor);
8585 }
8586
8587 self.transact(window, cx, |this, window, cx| {
8588 for row_range in row_ranges.into_iter().rev() {
8589 for row in row_range.iter_rows().rev() {
8590 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8591 let next_line_row = row.next_row();
8592 let indent = snapshot.indent_size_for_line(next_line_row);
8593 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8594
8595 let replace =
8596 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8597 " "
8598 } else {
8599 ""
8600 };
8601
8602 this.buffer.update(cx, |buffer, cx| {
8603 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8604 });
8605 }
8606 }
8607
8608 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8609 s.select_anchor_ranges(cursor_positions)
8610 });
8611 });
8612 }
8613
8614 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8615 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8616 self.join_lines_impl(true, window, cx);
8617 }
8618
8619 pub fn sort_lines_case_sensitive(
8620 &mut self,
8621 _: &SortLinesCaseSensitive,
8622 window: &mut Window,
8623 cx: &mut Context<Self>,
8624 ) {
8625 self.manipulate_lines(window, cx, |lines| lines.sort())
8626 }
8627
8628 pub fn sort_lines_case_insensitive(
8629 &mut self,
8630 _: &SortLinesCaseInsensitive,
8631 window: &mut Window,
8632 cx: &mut Context<Self>,
8633 ) {
8634 self.manipulate_lines(window, cx, |lines| {
8635 lines.sort_by_key(|line| line.to_lowercase())
8636 })
8637 }
8638
8639 pub fn unique_lines_case_insensitive(
8640 &mut self,
8641 _: &UniqueLinesCaseInsensitive,
8642 window: &mut Window,
8643 cx: &mut Context<Self>,
8644 ) {
8645 self.manipulate_lines(window, cx, |lines| {
8646 let mut seen = HashSet::default();
8647 lines.retain(|line| seen.insert(line.to_lowercase()));
8648 })
8649 }
8650
8651 pub fn unique_lines_case_sensitive(
8652 &mut self,
8653 _: &UniqueLinesCaseSensitive,
8654 window: &mut Window,
8655 cx: &mut Context<Self>,
8656 ) {
8657 self.manipulate_lines(window, cx, |lines| {
8658 let mut seen = HashSet::default();
8659 lines.retain(|line| seen.insert(*line));
8660 })
8661 }
8662
8663 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8664 let Some(project) = self.project.clone() else {
8665 return;
8666 };
8667 self.reload(project, window, cx)
8668 .detach_and_notify_err(window, cx);
8669 }
8670
8671 pub fn restore_file(
8672 &mut self,
8673 _: &::git::RestoreFile,
8674 window: &mut Window,
8675 cx: &mut Context<Self>,
8676 ) {
8677 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8678 let mut buffer_ids = HashSet::default();
8679 let snapshot = self.buffer().read(cx).snapshot(cx);
8680 for selection in self.selections.all::<usize>(cx) {
8681 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8682 }
8683
8684 let buffer = self.buffer().read(cx);
8685 let ranges = buffer_ids
8686 .into_iter()
8687 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8688 .collect::<Vec<_>>();
8689
8690 self.restore_hunks_in_ranges(ranges, window, cx);
8691 }
8692
8693 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8694 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8695 let selections = self
8696 .selections
8697 .all(cx)
8698 .into_iter()
8699 .map(|s| s.range())
8700 .collect();
8701 self.restore_hunks_in_ranges(selections, window, cx);
8702 }
8703
8704 pub fn restore_hunks_in_ranges(
8705 &mut self,
8706 ranges: Vec<Range<Point>>,
8707 window: &mut Window,
8708 cx: &mut Context<Editor>,
8709 ) {
8710 let mut revert_changes = HashMap::default();
8711 let chunk_by = self
8712 .snapshot(window, cx)
8713 .hunks_for_ranges(ranges)
8714 .into_iter()
8715 .chunk_by(|hunk| hunk.buffer_id);
8716 for (buffer_id, hunks) in &chunk_by {
8717 let hunks = hunks.collect::<Vec<_>>();
8718 for hunk in &hunks {
8719 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8720 }
8721 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8722 }
8723 drop(chunk_by);
8724 if !revert_changes.is_empty() {
8725 self.transact(window, cx, |editor, window, cx| {
8726 editor.restore(revert_changes, window, cx);
8727 });
8728 }
8729 }
8730
8731 pub fn open_active_item_in_terminal(
8732 &mut self,
8733 _: &OpenInTerminal,
8734 window: &mut Window,
8735 cx: &mut Context<Self>,
8736 ) {
8737 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8738 let project_path = buffer.read(cx).project_path(cx)?;
8739 let project = self.project.as_ref()?.read(cx);
8740 let entry = project.entry_for_path(&project_path, cx)?;
8741 let parent = match &entry.canonical_path {
8742 Some(canonical_path) => canonical_path.to_path_buf(),
8743 None => project.absolute_path(&project_path, cx)?,
8744 }
8745 .parent()?
8746 .to_path_buf();
8747 Some(parent)
8748 }) {
8749 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8750 }
8751 }
8752
8753 fn set_breakpoint_context_menu(
8754 &mut self,
8755 display_row: DisplayRow,
8756 position: Option<Anchor>,
8757 clicked_point: gpui::Point<Pixels>,
8758 window: &mut Window,
8759 cx: &mut Context<Self>,
8760 ) {
8761 if !cx.has_flag::<Debugger>() {
8762 return;
8763 }
8764 let source = self
8765 .buffer
8766 .read(cx)
8767 .snapshot(cx)
8768 .anchor_before(Point::new(display_row.0, 0u32));
8769
8770 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8771
8772 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8773 self,
8774 source,
8775 clicked_point,
8776 context_menu,
8777 window,
8778 cx,
8779 );
8780 }
8781
8782 fn add_edit_breakpoint_block(
8783 &mut self,
8784 anchor: Anchor,
8785 breakpoint: &Breakpoint,
8786 edit_action: BreakpointPromptEditAction,
8787 window: &mut Window,
8788 cx: &mut Context<Self>,
8789 ) {
8790 let weak_editor = cx.weak_entity();
8791 let bp_prompt = cx.new(|cx| {
8792 BreakpointPromptEditor::new(
8793 weak_editor,
8794 anchor,
8795 breakpoint.clone(),
8796 edit_action,
8797 window,
8798 cx,
8799 )
8800 });
8801
8802 let height = bp_prompt.update(cx, |this, cx| {
8803 this.prompt
8804 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8805 });
8806 let cloned_prompt = bp_prompt.clone();
8807 let blocks = vec![BlockProperties {
8808 style: BlockStyle::Sticky,
8809 placement: BlockPlacement::Above(anchor),
8810 height: Some(height),
8811 render: Arc::new(move |cx| {
8812 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8813 cloned_prompt.clone().into_any_element()
8814 }),
8815 priority: 0,
8816 }];
8817
8818 let focus_handle = bp_prompt.focus_handle(cx);
8819 window.focus(&focus_handle);
8820
8821 let block_ids = self.insert_blocks(blocks, None, cx);
8822 bp_prompt.update(cx, |prompt, _| {
8823 prompt.add_block_ids(block_ids);
8824 });
8825 }
8826
8827 fn breakpoint_at_cursor_head(
8828 &self,
8829 window: &mut Window,
8830 cx: &mut Context<Self>,
8831 ) -> Option<(Anchor, Breakpoint)> {
8832 let cursor_position: Point = self.selections.newest(cx).head();
8833 self.breakpoint_at_row(cursor_position.row, window, cx)
8834 }
8835
8836 pub(crate) fn breakpoint_at_row(
8837 &self,
8838 row: u32,
8839 window: &mut Window,
8840 cx: &mut Context<Self>,
8841 ) -> Option<(Anchor, Breakpoint)> {
8842 let snapshot = self.snapshot(window, cx);
8843 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8844
8845 let project = self.project.clone()?;
8846
8847 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8848 snapshot
8849 .buffer_snapshot
8850 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8851 })?;
8852
8853 let enclosing_excerpt = breakpoint_position.excerpt_id;
8854 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8855 let buffer_snapshot = buffer.read(cx).snapshot();
8856
8857 let row = buffer_snapshot
8858 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8859 .row;
8860
8861 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8862 let anchor_end = snapshot
8863 .buffer_snapshot
8864 .anchor_after(Point::new(row, line_len));
8865
8866 let bp = self
8867 .breakpoint_store
8868 .as_ref()?
8869 .read_with(cx, |breakpoint_store, cx| {
8870 breakpoint_store
8871 .breakpoints(
8872 &buffer,
8873 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8874 &buffer_snapshot,
8875 cx,
8876 )
8877 .next()
8878 .and_then(|(anchor, bp)| {
8879 let breakpoint_row = buffer_snapshot
8880 .summary_for_anchor::<text::PointUtf16>(anchor)
8881 .row;
8882
8883 if breakpoint_row == row {
8884 snapshot
8885 .buffer_snapshot
8886 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8887 .map(|anchor| (anchor, bp.clone()))
8888 } else {
8889 None
8890 }
8891 })
8892 });
8893 bp
8894 }
8895
8896 pub fn edit_log_breakpoint(
8897 &mut self,
8898 _: &EditLogBreakpoint,
8899 window: &mut Window,
8900 cx: &mut Context<Self>,
8901 ) {
8902 let (anchor, bp) = self
8903 .breakpoint_at_cursor_head(window, cx)
8904 .unwrap_or_else(|| {
8905 let cursor_position: Point = self.selections.newest(cx).head();
8906
8907 let breakpoint_position = self
8908 .snapshot(window, cx)
8909 .display_snapshot
8910 .buffer_snapshot
8911 .anchor_after(Point::new(cursor_position.row, 0));
8912
8913 (
8914 breakpoint_position,
8915 Breakpoint {
8916 message: None,
8917 state: BreakpointState::Enabled,
8918 condition: None,
8919 hit_condition: None,
8920 },
8921 )
8922 });
8923
8924 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8925 }
8926
8927 pub fn enable_breakpoint(
8928 &mut self,
8929 _: &crate::actions::EnableBreakpoint,
8930 window: &mut Window,
8931 cx: &mut Context<Self>,
8932 ) {
8933 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8934 if breakpoint.is_disabled() {
8935 self.edit_breakpoint_at_anchor(
8936 anchor,
8937 breakpoint,
8938 BreakpointEditAction::InvertState,
8939 cx,
8940 );
8941 }
8942 }
8943 }
8944
8945 pub fn disable_breakpoint(
8946 &mut self,
8947 _: &crate::actions::DisableBreakpoint,
8948 window: &mut Window,
8949 cx: &mut Context<Self>,
8950 ) {
8951 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8952 if breakpoint.is_enabled() {
8953 self.edit_breakpoint_at_anchor(
8954 anchor,
8955 breakpoint,
8956 BreakpointEditAction::InvertState,
8957 cx,
8958 );
8959 }
8960 }
8961 }
8962
8963 pub fn toggle_breakpoint(
8964 &mut self,
8965 _: &crate::actions::ToggleBreakpoint,
8966 window: &mut Window,
8967 cx: &mut Context<Self>,
8968 ) {
8969 let edit_action = BreakpointEditAction::Toggle;
8970
8971 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8972 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8973 } else {
8974 let cursor_position: Point = self.selections.newest(cx).head();
8975
8976 let breakpoint_position = self
8977 .snapshot(window, cx)
8978 .display_snapshot
8979 .buffer_snapshot
8980 .anchor_after(Point::new(cursor_position.row, 0));
8981
8982 self.edit_breakpoint_at_anchor(
8983 breakpoint_position,
8984 Breakpoint::new_standard(),
8985 edit_action,
8986 cx,
8987 );
8988 }
8989 }
8990
8991 pub fn edit_breakpoint_at_anchor(
8992 &mut self,
8993 breakpoint_position: Anchor,
8994 breakpoint: Breakpoint,
8995 edit_action: BreakpointEditAction,
8996 cx: &mut Context<Self>,
8997 ) {
8998 let Some(breakpoint_store) = &self.breakpoint_store else {
8999 return;
9000 };
9001
9002 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9003 if breakpoint_position == Anchor::min() {
9004 self.buffer()
9005 .read(cx)
9006 .excerpt_buffer_ids()
9007 .into_iter()
9008 .next()
9009 } else {
9010 None
9011 }
9012 }) else {
9013 return;
9014 };
9015
9016 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9017 return;
9018 };
9019
9020 breakpoint_store.update(cx, |breakpoint_store, cx| {
9021 breakpoint_store.toggle_breakpoint(
9022 buffer,
9023 (breakpoint_position.text_anchor, breakpoint),
9024 edit_action,
9025 cx,
9026 );
9027 });
9028
9029 cx.notify();
9030 }
9031
9032 #[cfg(any(test, feature = "test-support"))]
9033 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9034 self.breakpoint_store.clone()
9035 }
9036
9037 pub fn prepare_restore_change(
9038 &self,
9039 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9040 hunk: &MultiBufferDiffHunk,
9041 cx: &mut App,
9042 ) -> Option<()> {
9043 if hunk.is_created_file() {
9044 return None;
9045 }
9046 let buffer = self.buffer.read(cx);
9047 let diff = buffer.diff_for(hunk.buffer_id)?;
9048 let buffer = buffer.buffer(hunk.buffer_id)?;
9049 let buffer = buffer.read(cx);
9050 let original_text = diff
9051 .read(cx)
9052 .base_text()
9053 .as_rope()
9054 .slice(hunk.diff_base_byte_range.clone());
9055 let buffer_snapshot = buffer.snapshot();
9056 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9057 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9058 probe
9059 .0
9060 .start
9061 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9062 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9063 }) {
9064 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9065 Some(())
9066 } else {
9067 None
9068 }
9069 }
9070
9071 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9072 self.manipulate_lines(window, cx, |lines| lines.reverse())
9073 }
9074
9075 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9076 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9077 }
9078
9079 fn manipulate_lines<Fn>(
9080 &mut self,
9081 window: &mut Window,
9082 cx: &mut Context<Self>,
9083 mut callback: Fn,
9084 ) where
9085 Fn: FnMut(&mut Vec<&str>),
9086 {
9087 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9088
9089 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9090 let buffer = self.buffer.read(cx).snapshot(cx);
9091
9092 let mut edits = Vec::new();
9093
9094 let selections = self.selections.all::<Point>(cx);
9095 let mut selections = selections.iter().peekable();
9096 let mut contiguous_row_selections = Vec::new();
9097 let mut new_selections = Vec::new();
9098 let mut added_lines = 0;
9099 let mut removed_lines = 0;
9100
9101 while let Some(selection) = selections.next() {
9102 let (start_row, end_row) = consume_contiguous_rows(
9103 &mut contiguous_row_selections,
9104 selection,
9105 &display_map,
9106 &mut selections,
9107 );
9108
9109 let start_point = Point::new(start_row.0, 0);
9110 let end_point = Point::new(
9111 end_row.previous_row().0,
9112 buffer.line_len(end_row.previous_row()),
9113 );
9114 let text = buffer
9115 .text_for_range(start_point..end_point)
9116 .collect::<String>();
9117
9118 let mut lines = text.split('\n').collect_vec();
9119
9120 let lines_before = lines.len();
9121 callback(&mut lines);
9122 let lines_after = lines.len();
9123
9124 edits.push((start_point..end_point, lines.join("\n")));
9125
9126 // Selections must change based on added and removed line count
9127 let start_row =
9128 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9129 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9130 new_selections.push(Selection {
9131 id: selection.id,
9132 start: start_row,
9133 end: end_row,
9134 goal: SelectionGoal::None,
9135 reversed: selection.reversed,
9136 });
9137
9138 if lines_after > lines_before {
9139 added_lines += lines_after - lines_before;
9140 } else if lines_before > lines_after {
9141 removed_lines += lines_before - lines_after;
9142 }
9143 }
9144
9145 self.transact(window, cx, |this, window, cx| {
9146 let buffer = this.buffer.update(cx, |buffer, cx| {
9147 buffer.edit(edits, None, cx);
9148 buffer.snapshot(cx)
9149 });
9150
9151 // Recalculate offsets on newly edited buffer
9152 let new_selections = new_selections
9153 .iter()
9154 .map(|s| {
9155 let start_point = Point::new(s.start.0, 0);
9156 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9157 Selection {
9158 id: s.id,
9159 start: buffer.point_to_offset(start_point),
9160 end: buffer.point_to_offset(end_point),
9161 goal: s.goal,
9162 reversed: s.reversed,
9163 }
9164 })
9165 .collect();
9166
9167 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9168 s.select(new_selections);
9169 });
9170
9171 this.request_autoscroll(Autoscroll::fit(), cx);
9172 });
9173 }
9174
9175 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9176 self.manipulate_text(window, cx, |text| {
9177 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9178 if has_upper_case_characters {
9179 text.to_lowercase()
9180 } else {
9181 text.to_uppercase()
9182 }
9183 })
9184 }
9185
9186 pub fn convert_to_upper_case(
9187 &mut self,
9188 _: &ConvertToUpperCase,
9189 window: &mut Window,
9190 cx: &mut Context<Self>,
9191 ) {
9192 self.manipulate_text(window, cx, |text| text.to_uppercase())
9193 }
9194
9195 pub fn convert_to_lower_case(
9196 &mut self,
9197 _: &ConvertToLowerCase,
9198 window: &mut Window,
9199 cx: &mut Context<Self>,
9200 ) {
9201 self.manipulate_text(window, cx, |text| text.to_lowercase())
9202 }
9203
9204 pub fn convert_to_title_case(
9205 &mut self,
9206 _: &ConvertToTitleCase,
9207 window: &mut Window,
9208 cx: &mut Context<Self>,
9209 ) {
9210 self.manipulate_text(window, cx, |text| {
9211 text.split('\n')
9212 .map(|line| line.to_case(Case::Title))
9213 .join("\n")
9214 })
9215 }
9216
9217 pub fn convert_to_snake_case(
9218 &mut self,
9219 _: &ConvertToSnakeCase,
9220 window: &mut Window,
9221 cx: &mut Context<Self>,
9222 ) {
9223 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9224 }
9225
9226 pub fn convert_to_kebab_case(
9227 &mut self,
9228 _: &ConvertToKebabCase,
9229 window: &mut Window,
9230 cx: &mut Context<Self>,
9231 ) {
9232 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9233 }
9234
9235 pub fn convert_to_upper_camel_case(
9236 &mut self,
9237 _: &ConvertToUpperCamelCase,
9238 window: &mut Window,
9239 cx: &mut Context<Self>,
9240 ) {
9241 self.manipulate_text(window, cx, |text| {
9242 text.split('\n')
9243 .map(|line| line.to_case(Case::UpperCamel))
9244 .join("\n")
9245 })
9246 }
9247
9248 pub fn convert_to_lower_camel_case(
9249 &mut self,
9250 _: &ConvertToLowerCamelCase,
9251 window: &mut Window,
9252 cx: &mut Context<Self>,
9253 ) {
9254 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9255 }
9256
9257 pub fn convert_to_opposite_case(
9258 &mut self,
9259 _: &ConvertToOppositeCase,
9260 window: &mut Window,
9261 cx: &mut Context<Self>,
9262 ) {
9263 self.manipulate_text(window, cx, |text| {
9264 text.chars()
9265 .fold(String::with_capacity(text.len()), |mut t, c| {
9266 if c.is_uppercase() {
9267 t.extend(c.to_lowercase());
9268 } else {
9269 t.extend(c.to_uppercase());
9270 }
9271 t
9272 })
9273 })
9274 }
9275
9276 pub fn convert_to_rot13(
9277 &mut self,
9278 _: &ConvertToRot13,
9279 window: &mut Window,
9280 cx: &mut Context<Self>,
9281 ) {
9282 self.manipulate_text(window, cx, |text| {
9283 text.chars()
9284 .map(|c| match c {
9285 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9286 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9287 _ => c,
9288 })
9289 .collect()
9290 })
9291 }
9292
9293 pub fn convert_to_rot47(
9294 &mut self,
9295 _: &ConvertToRot47,
9296 window: &mut Window,
9297 cx: &mut Context<Self>,
9298 ) {
9299 self.manipulate_text(window, cx, |text| {
9300 text.chars()
9301 .map(|c| {
9302 let code_point = c as u32;
9303 if code_point >= 33 && code_point <= 126 {
9304 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9305 }
9306 c
9307 })
9308 .collect()
9309 })
9310 }
9311
9312 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9313 where
9314 Fn: FnMut(&str) -> String,
9315 {
9316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9317 let buffer = self.buffer.read(cx).snapshot(cx);
9318
9319 let mut new_selections = Vec::new();
9320 let mut edits = Vec::new();
9321 let mut selection_adjustment = 0i32;
9322
9323 for selection in self.selections.all::<usize>(cx) {
9324 let selection_is_empty = selection.is_empty();
9325
9326 let (start, end) = if selection_is_empty {
9327 let word_range = movement::surrounding_word(
9328 &display_map,
9329 selection.start.to_display_point(&display_map),
9330 );
9331 let start = word_range.start.to_offset(&display_map, Bias::Left);
9332 let end = word_range.end.to_offset(&display_map, Bias::Left);
9333 (start, end)
9334 } else {
9335 (selection.start, selection.end)
9336 };
9337
9338 let text = buffer.text_for_range(start..end).collect::<String>();
9339 let old_length = text.len() as i32;
9340 let text = callback(&text);
9341
9342 new_selections.push(Selection {
9343 start: (start as i32 - selection_adjustment) as usize,
9344 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9345 goal: SelectionGoal::None,
9346 ..selection
9347 });
9348
9349 selection_adjustment += old_length - text.len() as i32;
9350
9351 edits.push((start..end, text));
9352 }
9353
9354 self.transact(window, cx, |this, window, cx| {
9355 this.buffer.update(cx, |buffer, cx| {
9356 buffer.edit(edits, None, cx);
9357 });
9358
9359 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9360 s.select(new_selections);
9361 });
9362
9363 this.request_autoscroll(Autoscroll::fit(), cx);
9364 });
9365 }
9366
9367 pub fn duplicate(
9368 &mut self,
9369 upwards: bool,
9370 whole_lines: bool,
9371 window: &mut Window,
9372 cx: &mut Context<Self>,
9373 ) {
9374 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9375
9376 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9377 let buffer = &display_map.buffer_snapshot;
9378 let selections = self.selections.all::<Point>(cx);
9379
9380 let mut edits = Vec::new();
9381 let mut selections_iter = selections.iter().peekable();
9382 while let Some(selection) = selections_iter.next() {
9383 let mut rows = selection.spanned_rows(false, &display_map);
9384 // duplicate line-wise
9385 if whole_lines || selection.start == selection.end {
9386 // Avoid duplicating the same lines twice.
9387 while let Some(next_selection) = selections_iter.peek() {
9388 let next_rows = next_selection.spanned_rows(false, &display_map);
9389 if next_rows.start < rows.end {
9390 rows.end = next_rows.end;
9391 selections_iter.next().unwrap();
9392 } else {
9393 break;
9394 }
9395 }
9396
9397 // Copy the text from the selected row region and splice it either at the start
9398 // or end of the region.
9399 let start = Point::new(rows.start.0, 0);
9400 let end = Point::new(
9401 rows.end.previous_row().0,
9402 buffer.line_len(rows.end.previous_row()),
9403 );
9404 let text = buffer
9405 .text_for_range(start..end)
9406 .chain(Some("\n"))
9407 .collect::<String>();
9408 let insert_location = if upwards {
9409 Point::new(rows.end.0, 0)
9410 } else {
9411 start
9412 };
9413 edits.push((insert_location..insert_location, text));
9414 } else {
9415 // duplicate character-wise
9416 let start = selection.start;
9417 let end = selection.end;
9418 let text = buffer.text_for_range(start..end).collect::<String>();
9419 edits.push((selection.end..selection.end, text));
9420 }
9421 }
9422
9423 self.transact(window, cx, |this, _, cx| {
9424 this.buffer.update(cx, |buffer, cx| {
9425 buffer.edit(edits, None, cx);
9426 });
9427
9428 this.request_autoscroll(Autoscroll::fit(), cx);
9429 });
9430 }
9431
9432 pub fn duplicate_line_up(
9433 &mut self,
9434 _: &DuplicateLineUp,
9435 window: &mut Window,
9436 cx: &mut Context<Self>,
9437 ) {
9438 self.duplicate(true, true, window, cx);
9439 }
9440
9441 pub fn duplicate_line_down(
9442 &mut self,
9443 _: &DuplicateLineDown,
9444 window: &mut Window,
9445 cx: &mut Context<Self>,
9446 ) {
9447 self.duplicate(false, true, window, cx);
9448 }
9449
9450 pub fn duplicate_selection(
9451 &mut self,
9452 _: &DuplicateSelection,
9453 window: &mut Window,
9454 cx: &mut Context<Self>,
9455 ) {
9456 self.duplicate(false, false, window, cx);
9457 }
9458
9459 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9460 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9461
9462 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9463 let buffer = self.buffer.read(cx).snapshot(cx);
9464
9465 let mut edits = Vec::new();
9466 let mut unfold_ranges = Vec::new();
9467 let mut refold_creases = Vec::new();
9468
9469 let selections = self.selections.all::<Point>(cx);
9470 let mut selections = selections.iter().peekable();
9471 let mut contiguous_row_selections = Vec::new();
9472 let mut new_selections = Vec::new();
9473
9474 while let Some(selection) = selections.next() {
9475 // Find all the selections that span a contiguous row range
9476 let (start_row, end_row) = consume_contiguous_rows(
9477 &mut contiguous_row_selections,
9478 selection,
9479 &display_map,
9480 &mut selections,
9481 );
9482
9483 // Move the text spanned by the row range to be before the line preceding the row range
9484 if start_row.0 > 0 {
9485 let range_to_move = Point::new(
9486 start_row.previous_row().0,
9487 buffer.line_len(start_row.previous_row()),
9488 )
9489 ..Point::new(
9490 end_row.previous_row().0,
9491 buffer.line_len(end_row.previous_row()),
9492 );
9493 let insertion_point = display_map
9494 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9495 .0;
9496
9497 // Don't move lines across excerpts
9498 if buffer
9499 .excerpt_containing(insertion_point..range_to_move.end)
9500 .is_some()
9501 {
9502 let text = buffer
9503 .text_for_range(range_to_move.clone())
9504 .flat_map(|s| s.chars())
9505 .skip(1)
9506 .chain(['\n'])
9507 .collect::<String>();
9508
9509 edits.push((
9510 buffer.anchor_after(range_to_move.start)
9511 ..buffer.anchor_before(range_to_move.end),
9512 String::new(),
9513 ));
9514 let insertion_anchor = buffer.anchor_after(insertion_point);
9515 edits.push((insertion_anchor..insertion_anchor, text));
9516
9517 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9518
9519 // Move selections up
9520 new_selections.extend(contiguous_row_selections.drain(..).map(
9521 |mut selection| {
9522 selection.start.row -= row_delta;
9523 selection.end.row -= row_delta;
9524 selection
9525 },
9526 ));
9527
9528 // Move folds up
9529 unfold_ranges.push(range_to_move.clone());
9530 for fold in display_map.folds_in_range(
9531 buffer.anchor_before(range_to_move.start)
9532 ..buffer.anchor_after(range_to_move.end),
9533 ) {
9534 let mut start = fold.range.start.to_point(&buffer);
9535 let mut end = fold.range.end.to_point(&buffer);
9536 start.row -= row_delta;
9537 end.row -= row_delta;
9538 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9539 }
9540 }
9541 }
9542
9543 // If we didn't move line(s), preserve the existing selections
9544 new_selections.append(&mut contiguous_row_selections);
9545 }
9546
9547 self.transact(window, cx, |this, window, cx| {
9548 this.unfold_ranges(&unfold_ranges, true, true, cx);
9549 this.buffer.update(cx, |buffer, cx| {
9550 for (range, text) in edits {
9551 buffer.edit([(range, text)], None, cx);
9552 }
9553 });
9554 this.fold_creases(refold_creases, true, window, cx);
9555 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9556 s.select(new_selections);
9557 })
9558 });
9559 }
9560
9561 pub fn move_line_down(
9562 &mut self,
9563 _: &MoveLineDown,
9564 window: &mut Window,
9565 cx: &mut Context<Self>,
9566 ) {
9567 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9568
9569 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9570 let buffer = self.buffer.read(cx).snapshot(cx);
9571
9572 let mut edits = Vec::new();
9573 let mut unfold_ranges = Vec::new();
9574 let mut refold_creases = Vec::new();
9575
9576 let selections = self.selections.all::<Point>(cx);
9577 let mut selections = selections.iter().peekable();
9578 let mut contiguous_row_selections = Vec::new();
9579 let mut new_selections = Vec::new();
9580
9581 while let Some(selection) = selections.next() {
9582 // Find all the selections that span a contiguous row range
9583 let (start_row, end_row) = consume_contiguous_rows(
9584 &mut contiguous_row_selections,
9585 selection,
9586 &display_map,
9587 &mut selections,
9588 );
9589
9590 // Move the text spanned by the row range to be after the last line of the row range
9591 if end_row.0 <= buffer.max_point().row {
9592 let range_to_move =
9593 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9594 let insertion_point = display_map
9595 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9596 .0;
9597
9598 // Don't move lines across excerpt boundaries
9599 if buffer
9600 .excerpt_containing(range_to_move.start..insertion_point)
9601 .is_some()
9602 {
9603 let mut text = String::from("\n");
9604 text.extend(buffer.text_for_range(range_to_move.clone()));
9605 text.pop(); // Drop trailing newline
9606 edits.push((
9607 buffer.anchor_after(range_to_move.start)
9608 ..buffer.anchor_before(range_to_move.end),
9609 String::new(),
9610 ));
9611 let insertion_anchor = buffer.anchor_after(insertion_point);
9612 edits.push((insertion_anchor..insertion_anchor, text));
9613
9614 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9615
9616 // Move selections down
9617 new_selections.extend(contiguous_row_selections.drain(..).map(
9618 |mut selection| {
9619 selection.start.row += row_delta;
9620 selection.end.row += row_delta;
9621 selection
9622 },
9623 ));
9624
9625 // Move folds down
9626 unfold_ranges.push(range_to_move.clone());
9627 for fold in display_map.folds_in_range(
9628 buffer.anchor_before(range_to_move.start)
9629 ..buffer.anchor_after(range_to_move.end),
9630 ) {
9631 let mut start = fold.range.start.to_point(&buffer);
9632 let mut end = fold.range.end.to_point(&buffer);
9633 start.row += row_delta;
9634 end.row += row_delta;
9635 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9636 }
9637 }
9638 }
9639
9640 // If we didn't move line(s), preserve the existing selections
9641 new_selections.append(&mut contiguous_row_selections);
9642 }
9643
9644 self.transact(window, cx, |this, window, cx| {
9645 this.unfold_ranges(&unfold_ranges, true, true, cx);
9646 this.buffer.update(cx, |buffer, cx| {
9647 for (range, text) in edits {
9648 buffer.edit([(range, text)], None, cx);
9649 }
9650 });
9651 this.fold_creases(refold_creases, true, window, cx);
9652 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9653 s.select(new_selections)
9654 });
9655 });
9656 }
9657
9658 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9659 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9660 let text_layout_details = &self.text_layout_details(window);
9661 self.transact(window, cx, |this, window, cx| {
9662 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9663 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9664 s.move_with(|display_map, selection| {
9665 if !selection.is_empty() {
9666 return;
9667 }
9668
9669 let mut head = selection.head();
9670 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9671 if head.column() == display_map.line_len(head.row()) {
9672 transpose_offset = display_map
9673 .buffer_snapshot
9674 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9675 }
9676
9677 if transpose_offset == 0 {
9678 return;
9679 }
9680
9681 *head.column_mut() += 1;
9682 head = display_map.clip_point(head, Bias::Right);
9683 let goal = SelectionGoal::HorizontalPosition(
9684 display_map
9685 .x_for_display_point(head, text_layout_details)
9686 .into(),
9687 );
9688 selection.collapse_to(head, goal);
9689
9690 let transpose_start = display_map
9691 .buffer_snapshot
9692 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9693 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9694 let transpose_end = display_map
9695 .buffer_snapshot
9696 .clip_offset(transpose_offset + 1, Bias::Right);
9697 if let Some(ch) =
9698 display_map.buffer_snapshot.chars_at(transpose_start).next()
9699 {
9700 edits.push((transpose_start..transpose_offset, String::new()));
9701 edits.push((transpose_end..transpose_end, ch.to_string()));
9702 }
9703 }
9704 });
9705 edits
9706 });
9707 this.buffer
9708 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9709 let selections = this.selections.all::<usize>(cx);
9710 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9711 s.select(selections);
9712 });
9713 });
9714 }
9715
9716 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9717 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9718 self.rewrap_impl(RewrapOptions::default(), cx)
9719 }
9720
9721 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9722 let buffer = self.buffer.read(cx).snapshot(cx);
9723 let selections = self.selections.all::<Point>(cx);
9724 let mut selections = selections.iter().peekable();
9725
9726 let mut edits = Vec::new();
9727 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9728
9729 while let Some(selection) = selections.next() {
9730 let mut start_row = selection.start.row;
9731 let mut end_row = selection.end.row;
9732
9733 // Skip selections that overlap with a range that has already been rewrapped.
9734 let selection_range = start_row..end_row;
9735 if rewrapped_row_ranges
9736 .iter()
9737 .any(|range| range.overlaps(&selection_range))
9738 {
9739 continue;
9740 }
9741
9742 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9743
9744 // Since not all lines in the selection may be at the same indent
9745 // level, choose the indent size that is the most common between all
9746 // of the lines.
9747 //
9748 // If there is a tie, we use the deepest indent.
9749 let (indent_size, indent_end) = {
9750 let mut indent_size_occurrences = HashMap::default();
9751 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9752
9753 for row in start_row..=end_row {
9754 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9755 rows_by_indent_size.entry(indent).or_default().push(row);
9756 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9757 }
9758
9759 let indent_size = indent_size_occurrences
9760 .into_iter()
9761 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9762 .map(|(indent, _)| indent)
9763 .unwrap_or_default();
9764 let row = rows_by_indent_size[&indent_size][0];
9765 let indent_end = Point::new(row, indent_size.len);
9766
9767 (indent_size, indent_end)
9768 };
9769
9770 let mut line_prefix = indent_size.chars().collect::<String>();
9771
9772 let mut inside_comment = false;
9773 if let Some(comment_prefix) =
9774 buffer
9775 .language_scope_at(selection.head())
9776 .and_then(|language| {
9777 language
9778 .line_comment_prefixes()
9779 .iter()
9780 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9781 .cloned()
9782 })
9783 {
9784 line_prefix.push_str(&comment_prefix);
9785 inside_comment = true;
9786 }
9787
9788 let language_settings = buffer.language_settings_at(selection.head(), cx);
9789 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9790 RewrapBehavior::InComments => inside_comment,
9791 RewrapBehavior::InSelections => !selection.is_empty(),
9792 RewrapBehavior::Anywhere => true,
9793 };
9794
9795 let should_rewrap = options.override_language_settings
9796 || allow_rewrap_based_on_language
9797 || self.hard_wrap.is_some();
9798 if !should_rewrap {
9799 continue;
9800 }
9801
9802 if selection.is_empty() {
9803 'expand_upwards: while start_row > 0 {
9804 let prev_row = start_row - 1;
9805 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9806 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9807 {
9808 start_row = prev_row;
9809 } else {
9810 break 'expand_upwards;
9811 }
9812 }
9813
9814 'expand_downwards: while end_row < buffer.max_point().row {
9815 let next_row = end_row + 1;
9816 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9817 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9818 {
9819 end_row = next_row;
9820 } else {
9821 break 'expand_downwards;
9822 }
9823 }
9824 }
9825
9826 let start = Point::new(start_row, 0);
9827 let start_offset = start.to_offset(&buffer);
9828 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9829 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9830 let Some(lines_without_prefixes) = selection_text
9831 .lines()
9832 .map(|line| {
9833 line.strip_prefix(&line_prefix)
9834 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9835 .ok_or_else(|| {
9836 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9837 })
9838 })
9839 .collect::<Result<Vec<_>, _>>()
9840 .log_err()
9841 else {
9842 continue;
9843 };
9844
9845 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9846 buffer
9847 .language_settings_at(Point::new(start_row, 0), cx)
9848 .preferred_line_length as usize
9849 });
9850 let wrapped_text = wrap_with_prefix(
9851 line_prefix,
9852 lines_without_prefixes.join("\n"),
9853 wrap_column,
9854 tab_size,
9855 options.preserve_existing_whitespace,
9856 );
9857
9858 // TODO: should always use char-based diff while still supporting cursor behavior that
9859 // matches vim.
9860 let mut diff_options = DiffOptions::default();
9861 if options.override_language_settings {
9862 diff_options.max_word_diff_len = 0;
9863 diff_options.max_word_diff_line_count = 0;
9864 } else {
9865 diff_options.max_word_diff_len = usize::MAX;
9866 diff_options.max_word_diff_line_count = usize::MAX;
9867 }
9868
9869 for (old_range, new_text) in
9870 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9871 {
9872 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9873 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9874 edits.push((edit_start..edit_end, new_text));
9875 }
9876
9877 rewrapped_row_ranges.push(start_row..=end_row);
9878 }
9879
9880 self.buffer
9881 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9882 }
9883
9884 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9885 let mut text = String::new();
9886 let buffer = self.buffer.read(cx).snapshot(cx);
9887 let mut selections = self.selections.all::<Point>(cx);
9888 let mut clipboard_selections = Vec::with_capacity(selections.len());
9889 {
9890 let max_point = buffer.max_point();
9891 let mut is_first = true;
9892 for selection in &mut selections {
9893 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9894 if is_entire_line {
9895 selection.start = Point::new(selection.start.row, 0);
9896 if !selection.is_empty() && selection.end.column == 0 {
9897 selection.end = cmp::min(max_point, selection.end);
9898 } else {
9899 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9900 }
9901 selection.goal = SelectionGoal::None;
9902 }
9903 if is_first {
9904 is_first = false;
9905 } else {
9906 text += "\n";
9907 }
9908 let mut len = 0;
9909 for chunk in buffer.text_for_range(selection.start..selection.end) {
9910 text.push_str(chunk);
9911 len += chunk.len();
9912 }
9913 clipboard_selections.push(ClipboardSelection {
9914 len,
9915 is_entire_line,
9916 first_line_indent: buffer
9917 .indent_size_for_line(MultiBufferRow(selection.start.row))
9918 .len,
9919 });
9920 }
9921 }
9922
9923 self.transact(window, cx, |this, window, cx| {
9924 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9925 s.select(selections);
9926 });
9927 this.insert("", window, cx);
9928 });
9929 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9930 }
9931
9932 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9933 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9934 let item = self.cut_common(window, cx);
9935 cx.write_to_clipboard(item);
9936 }
9937
9938 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9939 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9940 self.change_selections(None, window, cx, |s| {
9941 s.move_with(|snapshot, sel| {
9942 if sel.is_empty() {
9943 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9944 }
9945 });
9946 });
9947 let item = self.cut_common(window, cx);
9948 cx.set_global(KillRing(item))
9949 }
9950
9951 pub fn kill_ring_yank(
9952 &mut self,
9953 _: &KillRingYank,
9954 window: &mut Window,
9955 cx: &mut Context<Self>,
9956 ) {
9957 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9958 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9959 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9960 (kill_ring.text().to_string(), kill_ring.metadata_json())
9961 } else {
9962 return;
9963 }
9964 } else {
9965 return;
9966 };
9967 self.do_paste(&text, metadata, false, window, cx);
9968 }
9969
9970 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9971 self.do_copy(true, cx);
9972 }
9973
9974 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9975 self.do_copy(false, cx);
9976 }
9977
9978 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9979 let selections = self.selections.all::<Point>(cx);
9980 let buffer = self.buffer.read(cx).read(cx);
9981 let mut text = String::new();
9982
9983 let mut clipboard_selections = Vec::with_capacity(selections.len());
9984 {
9985 let max_point = buffer.max_point();
9986 let mut is_first = true;
9987 for selection in &selections {
9988 let mut start = selection.start;
9989 let mut end = selection.end;
9990 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9991 if is_entire_line {
9992 start = Point::new(start.row, 0);
9993 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9994 }
9995
9996 let mut trimmed_selections = Vec::new();
9997 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9998 let row = MultiBufferRow(start.row);
9999 let first_indent = buffer.indent_size_for_line(row);
10000 if first_indent.len == 0 || start.column > first_indent.len {
10001 trimmed_selections.push(start..end);
10002 } else {
10003 trimmed_selections.push(
10004 Point::new(row.0, first_indent.len)
10005 ..Point::new(row.0, buffer.line_len(row)),
10006 );
10007 for row in start.row + 1..=end.row {
10008 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10009 if row_indent_size.len >= first_indent.len {
10010 trimmed_selections.push(
10011 Point::new(row, first_indent.len)
10012 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10013 );
10014 } else {
10015 trimmed_selections.clear();
10016 trimmed_selections.push(start..end);
10017 break;
10018 }
10019 }
10020 }
10021 } else {
10022 trimmed_selections.push(start..end);
10023 }
10024
10025 for trimmed_range in trimmed_selections {
10026 if is_first {
10027 is_first = false;
10028 } else {
10029 text += "\n";
10030 }
10031 let mut len = 0;
10032 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10033 text.push_str(chunk);
10034 len += chunk.len();
10035 }
10036 clipboard_selections.push(ClipboardSelection {
10037 len,
10038 is_entire_line,
10039 first_line_indent: buffer
10040 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10041 .len,
10042 });
10043 }
10044 }
10045 }
10046
10047 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10048 text,
10049 clipboard_selections,
10050 ));
10051 }
10052
10053 pub fn do_paste(
10054 &mut self,
10055 text: &String,
10056 clipboard_selections: Option<Vec<ClipboardSelection>>,
10057 handle_entire_lines: bool,
10058 window: &mut Window,
10059 cx: &mut Context<Self>,
10060 ) {
10061 if self.read_only(cx) {
10062 return;
10063 }
10064
10065 let clipboard_text = Cow::Borrowed(text);
10066
10067 self.transact(window, cx, |this, window, cx| {
10068 if let Some(mut clipboard_selections) = clipboard_selections {
10069 let old_selections = this.selections.all::<usize>(cx);
10070 let all_selections_were_entire_line =
10071 clipboard_selections.iter().all(|s| s.is_entire_line);
10072 let first_selection_indent_column =
10073 clipboard_selections.first().map(|s| s.first_line_indent);
10074 if clipboard_selections.len() != old_selections.len() {
10075 clipboard_selections.drain(..);
10076 }
10077 let cursor_offset = this.selections.last::<usize>(cx).head();
10078 let mut auto_indent_on_paste = true;
10079
10080 this.buffer.update(cx, |buffer, cx| {
10081 let snapshot = buffer.read(cx);
10082 auto_indent_on_paste = snapshot
10083 .language_settings_at(cursor_offset, cx)
10084 .auto_indent_on_paste;
10085
10086 let mut start_offset = 0;
10087 let mut edits = Vec::new();
10088 let mut original_indent_columns = Vec::new();
10089 for (ix, selection) in old_selections.iter().enumerate() {
10090 let to_insert;
10091 let entire_line;
10092 let original_indent_column;
10093 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10094 let end_offset = start_offset + clipboard_selection.len;
10095 to_insert = &clipboard_text[start_offset..end_offset];
10096 entire_line = clipboard_selection.is_entire_line;
10097 start_offset = end_offset + 1;
10098 original_indent_column = Some(clipboard_selection.first_line_indent);
10099 } else {
10100 to_insert = clipboard_text.as_str();
10101 entire_line = all_selections_were_entire_line;
10102 original_indent_column = first_selection_indent_column
10103 }
10104
10105 // If the corresponding selection was empty when this slice of the
10106 // clipboard text was written, then the entire line containing the
10107 // selection was copied. If this selection is also currently empty,
10108 // then paste the line before the current line of the buffer.
10109 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10110 let column = selection.start.to_point(&snapshot).column as usize;
10111 let line_start = selection.start - column;
10112 line_start..line_start
10113 } else {
10114 selection.range()
10115 };
10116
10117 edits.push((range, to_insert));
10118 original_indent_columns.push(original_indent_column);
10119 }
10120 drop(snapshot);
10121
10122 buffer.edit(
10123 edits,
10124 if auto_indent_on_paste {
10125 Some(AutoindentMode::Block {
10126 original_indent_columns,
10127 })
10128 } else {
10129 None
10130 },
10131 cx,
10132 );
10133 });
10134
10135 let selections = this.selections.all::<usize>(cx);
10136 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10137 s.select(selections)
10138 });
10139 } else {
10140 this.insert(&clipboard_text, window, cx);
10141 }
10142 });
10143 }
10144
10145 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10146 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10147 if let Some(item) = cx.read_from_clipboard() {
10148 let entries = item.entries();
10149
10150 match entries.first() {
10151 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10152 // of all the pasted entries.
10153 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10154 .do_paste(
10155 clipboard_string.text(),
10156 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10157 true,
10158 window,
10159 cx,
10160 ),
10161 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10162 }
10163 }
10164 }
10165
10166 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10167 if self.read_only(cx) {
10168 return;
10169 }
10170
10171 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10172
10173 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10174 if let Some((selections, _)) =
10175 self.selection_history.transaction(transaction_id).cloned()
10176 {
10177 self.change_selections(None, window, cx, |s| {
10178 s.select_anchors(selections.to_vec());
10179 });
10180 } else {
10181 log::error!(
10182 "No entry in selection_history found for undo. \
10183 This may correspond to a bug where undo does not update the selection. \
10184 If this is occurring, please add details to \
10185 https://github.com/zed-industries/zed/issues/22692"
10186 );
10187 }
10188 self.request_autoscroll(Autoscroll::fit(), cx);
10189 self.unmark_text(window, cx);
10190 self.refresh_inline_completion(true, false, window, cx);
10191 cx.emit(EditorEvent::Edited { transaction_id });
10192 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10193 }
10194 }
10195
10196 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10197 if self.read_only(cx) {
10198 return;
10199 }
10200
10201 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10202
10203 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10204 if let Some((_, Some(selections))) =
10205 self.selection_history.transaction(transaction_id).cloned()
10206 {
10207 self.change_selections(None, window, cx, |s| {
10208 s.select_anchors(selections.to_vec());
10209 });
10210 } else {
10211 log::error!(
10212 "No entry in selection_history found for redo. \
10213 This may correspond to a bug where undo does not update the selection. \
10214 If this is occurring, please add details to \
10215 https://github.com/zed-industries/zed/issues/22692"
10216 );
10217 }
10218 self.request_autoscroll(Autoscroll::fit(), cx);
10219 self.unmark_text(window, cx);
10220 self.refresh_inline_completion(true, false, window, cx);
10221 cx.emit(EditorEvent::Edited { transaction_id });
10222 }
10223 }
10224
10225 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10226 self.buffer
10227 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10228 }
10229
10230 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10231 self.buffer
10232 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10233 }
10234
10235 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10236 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10237 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10238 s.move_with(|map, selection| {
10239 let cursor = if selection.is_empty() {
10240 movement::left(map, selection.start)
10241 } else {
10242 selection.start
10243 };
10244 selection.collapse_to(cursor, SelectionGoal::None);
10245 });
10246 })
10247 }
10248
10249 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10250 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10251 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10253 })
10254 }
10255
10256 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10257 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10259 s.move_with(|map, selection| {
10260 let cursor = if selection.is_empty() {
10261 movement::right(map, selection.end)
10262 } else {
10263 selection.end
10264 };
10265 selection.collapse_to(cursor, SelectionGoal::None)
10266 });
10267 })
10268 }
10269
10270 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10271 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10273 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10274 })
10275 }
10276
10277 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10278 if self.take_rename(true, window, cx).is_some() {
10279 return;
10280 }
10281
10282 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10283 cx.propagate();
10284 return;
10285 }
10286
10287 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10288
10289 let text_layout_details = &self.text_layout_details(window);
10290 let selection_count = self.selections.count();
10291 let first_selection = self.selections.first_anchor();
10292
10293 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10294 s.move_with(|map, selection| {
10295 if !selection.is_empty() {
10296 selection.goal = SelectionGoal::None;
10297 }
10298 let (cursor, goal) = movement::up(
10299 map,
10300 selection.start,
10301 selection.goal,
10302 false,
10303 text_layout_details,
10304 );
10305 selection.collapse_to(cursor, goal);
10306 });
10307 });
10308
10309 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10310 {
10311 cx.propagate();
10312 }
10313 }
10314
10315 pub fn move_up_by_lines(
10316 &mut self,
10317 action: &MoveUpByLines,
10318 window: &mut Window,
10319 cx: &mut Context<Self>,
10320 ) {
10321 if self.take_rename(true, window, cx).is_some() {
10322 return;
10323 }
10324
10325 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10326 cx.propagate();
10327 return;
10328 }
10329
10330 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10331
10332 let text_layout_details = &self.text_layout_details(window);
10333
10334 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10335 s.move_with(|map, selection| {
10336 if !selection.is_empty() {
10337 selection.goal = SelectionGoal::None;
10338 }
10339 let (cursor, goal) = movement::up_by_rows(
10340 map,
10341 selection.start,
10342 action.lines,
10343 selection.goal,
10344 false,
10345 text_layout_details,
10346 );
10347 selection.collapse_to(cursor, goal);
10348 });
10349 })
10350 }
10351
10352 pub fn move_down_by_lines(
10353 &mut self,
10354 action: &MoveDownByLines,
10355 window: &mut Window,
10356 cx: &mut Context<Self>,
10357 ) {
10358 if self.take_rename(true, window, cx).is_some() {
10359 return;
10360 }
10361
10362 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10363 cx.propagate();
10364 return;
10365 }
10366
10367 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10368
10369 let text_layout_details = &self.text_layout_details(window);
10370
10371 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10372 s.move_with(|map, selection| {
10373 if !selection.is_empty() {
10374 selection.goal = SelectionGoal::None;
10375 }
10376 let (cursor, goal) = movement::down_by_rows(
10377 map,
10378 selection.start,
10379 action.lines,
10380 selection.goal,
10381 false,
10382 text_layout_details,
10383 );
10384 selection.collapse_to(cursor, goal);
10385 });
10386 })
10387 }
10388
10389 pub fn select_down_by_lines(
10390 &mut self,
10391 action: &SelectDownByLines,
10392 window: &mut Window,
10393 cx: &mut Context<Self>,
10394 ) {
10395 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10396 let text_layout_details = &self.text_layout_details(window);
10397 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10398 s.move_heads_with(|map, head, goal| {
10399 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10400 })
10401 })
10402 }
10403
10404 pub fn select_up_by_lines(
10405 &mut self,
10406 action: &SelectUpByLines,
10407 window: &mut Window,
10408 cx: &mut Context<Self>,
10409 ) {
10410 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10411 let text_layout_details = &self.text_layout_details(window);
10412 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10413 s.move_heads_with(|map, head, goal| {
10414 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10415 })
10416 })
10417 }
10418
10419 pub fn select_page_up(
10420 &mut self,
10421 _: &SelectPageUp,
10422 window: &mut Window,
10423 cx: &mut Context<Self>,
10424 ) {
10425 let Some(row_count) = self.visible_row_count() else {
10426 return;
10427 };
10428
10429 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10430
10431 let text_layout_details = &self.text_layout_details(window);
10432
10433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10434 s.move_heads_with(|map, head, goal| {
10435 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10436 })
10437 })
10438 }
10439
10440 pub fn move_page_up(
10441 &mut self,
10442 action: &MovePageUp,
10443 window: &mut Window,
10444 cx: &mut Context<Self>,
10445 ) {
10446 if self.take_rename(true, window, cx).is_some() {
10447 return;
10448 }
10449
10450 if self
10451 .context_menu
10452 .borrow_mut()
10453 .as_mut()
10454 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10455 .unwrap_or(false)
10456 {
10457 return;
10458 }
10459
10460 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10461 cx.propagate();
10462 return;
10463 }
10464
10465 let Some(row_count) = self.visible_row_count() else {
10466 return;
10467 };
10468
10469 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10470
10471 let autoscroll = if action.center_cursor {
10472 Autoscroll::center()
10473 } else {
10474 Autoscroll::fit()
10475 };
10476
10477 let text_layout_details = &self.text_layout_details(window);
10478
10479 self.change_selections(Some(autoscroll), window, cx, |s| {
10480 s.move_with(|map, selection| {
10481 if !selection.is_empty() {
10482 selection.goal = SelectionGoal::None;
10483 }
10484 let (cursor, goal) = movement::up_by_rows(
10485 map,
10486 selection.end,
10487 row_count,
10488 selection.goal,
10489 false,
10490 text_layout_details,
10491 );
10492 selection.collapse_to(cursor, goal);
10493 });
10494 });
10495 }
10496
10497 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10498 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10499 let text_layout_details = &self.text_layout_details(window);
10500 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10501 s.move_heads_with(|map, head, goal| {
10502 movement::up(map, head, goal, false, text_layout_details)
10503 })
10504 })
10505 }
10506
10507 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10508 self.take_rename(true, window, cx);
10509
10510 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10511 cx.propagate();
10512 return;
10513 }
10514
10515 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10516
10517 let text_layout_details = &self.text_layout_details(window);
10518 let selection_count = self.selections.count();
10519 let first_selection = self.selections.first_anchor();
10520
10521 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10522 s.move_with(|map, selection| {
10523 if !selection.is_empty() {
10524 selection.goal = SelectionGoal::None;
10525 }
10526 let (cursor, goal) = movement::down(
10527 map,
10528 selection.end,
10529 selection.goal,
10530 false,
10531 text_layout_details,
10532 );
10533 selection.collapse_to(cursor, goal);
10534 });
10535 });
10536
10537 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10538 {
10539 cx.propagate();
10540 }
10541 }
10542
10543 pub fn select_page_down(
10544 &mut self,
10545 _: &SelectPageDown,
10546 window: &mut Window,
10547 cx: &mut Context<Self>,
10548 ) {
10549 let Some(row_count) = self.visible_row_count() else {
10550 return;
10551 };
10552
10553 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10554
10555 let text_layout_details = &self.text_layout_details(window);
10556
10557 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10558 s.move_heads_with(|map, head, goal| {
10559 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10560 })
10561 })
10562 }
10563
10564 pub fn move_page_down(
10565 &mut self,
10566 action: &MovePageDown,
10567 window: &mut Window,
10568 cx: &mut Context<Self>,
10569 ) {
10570 if self.take_rename(true, window, cx).is_some() {
10571 return;
10572 }
10573
10574 if self
10575 .context_menu
10576 .borrow_mut()
10577 .as_mut()
10578 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10579 .unwrap_or(false)
10580 {
10581 return;
10582 }
10583
10584 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10585 cx.propagate();
10586 return;
10587 }
10588
10589 let Some(row_count) = self.visible_row_count() else {
10590 return;
10591 };
10592
10593 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10594
10595 let autoscroll = if action.center_cursor {
10596 Autoscroll::center()
10597 } else {
10598 Autoscroll::fit()
10599 };
10600
10601 let text_layout_details = &self.text_layout_details(window);
10602 self.change_selections(Some(autoscroll), window, cx, |s| {
10603 s.move_with(|map, selection| {
10604 if !selection.is_empty() {
10605 selection.goal = SelectionGoal::None;
10606 }
10607 let (cursor, goal) = movement::down_by_rows(
10608 map,
10609 selection.end,
10610 row_count,
10611 selection.goal,
10612 false,
10613 text_layout_details,
10614 );
10615 selection.collapse_to(cursor, goal);
10616 });
10617 });
10618 }
10619
10620 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10621 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10622 let text_layout_details = &self.text_layout_details(window);
10623 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10624 s.move_heads_with(|map, head, goal| {
10625 movement::down(map, head, goal, false, text_layout_details)
10626 })
10627 });
10628 }
10629
10630 pub fn context_menu_first(
10631 &mut self,
10632 _: &ContextMenuFirst,
10633 _window: &mut Window,
10634 cx: &mut Context<Self>,
10635 ) {
10636 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10637 context_menu.select_first(self.completion_provider.as_deref(), cx);
10638 }
10639 }
10640
10641 pub fn context_menu_prev(
10642 &mut self,
10643 _: &ContextMenuPrevious,
10644 _window: &mut Window,
10645 cx: &mut Context<Self>,
10646 ) {
10647 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10648 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10649 }
10650 }
10651
10652 pub fn context_menu_next(
10653 &mut self,
10654 _: &ContextMenuNext,
10655 _window: &mut Window,
10656 cx: &mut Context<Self>,
10657 ) {
10658 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10659 context_menu.select_next(self.completion_provider.as_deref(), cx);
10660 }
10661 }
10662
10663 pub fn context_menu_last(
10664 &mut self,
10665 _: &ContextMenuLast,
10666 _window: &mut Window,
10667 cx: &mut Context<Self>,
10668 ) {
10669 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10670 context_menu.select_last(self.completion_provider.as_deref(), cx);
10671 }
10672 }
10673
10674 pub fn move_to_previous_word_start(
10675 &mut self,
10676 _: &MoveToPreviousWordStart,
10677 window: &mut Window,
10678 cx: &mut Context<Self>,
10679 ) {
10680 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10681 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10682 s.move_cursors_with(|map, head, _| {
10683 (
10684 movement::previous_word_start(map, head),
10685 SelectionGoal::None,
10686 )
10687 });
10688 })
10689 }
10690
10691 pub fn move_to_previous_subword_start(
10692 &mut self,
10693 _: &MoveToPreviousSubwordStart,
10694 window: &mut Window,
10695 cx: &mut Context<Self>,
10696 ) {
10697 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10698 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10699 s.move_cursors_with(|map, head, _| {
10700 (
10701 movement::previous_subword_start(map, head),
10702 SelectionGoal::None,
10703 )
10704 });
10705 })
10706 }
10707
10708 pub fn select_to_previous_word_start(
10709 &mut self,
10710 _: &SelectToPreviousWordStart,
10711 window: &mut Window,
10712 cx: &mut Context<Self>,
10713 ) {
10714 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10716 s.move_heads_with(|map, head, _| {
10717 (
10718 movement::previous_word_start(map, head),
10719 SelectionGoal::None,
10720 )
10721 });
10722 })
10723 }
10724
10725 pub fn select_to_previous_subword_start(
10726 &mut self,
10727 _: &SelectToPreviousSubwordStart,
10728 window: &mut Window,
10729 cx: &mut Context<Self>,
10730 ) {
10731 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10732 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10733 s.move_heads_with(|map, head, _| {
10734 (
10735 movement::previous_subword_start(map, head),
10736 SelectionGoal::None,
10737 )
10738 });
10739 })
10740 }
10741
10742 pub fn delete_to_previous_word_start(
10743 &mut self,
10744 action: &DeleteToPreviousWordStart,
10745 window: &mut Window,
10746 cx: &mut Context<Self>,
10747 ) {
10748 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10749 self.transact(window, cx, |this, window, cx| {
10750 this.select_autoclose_pair(window, cx);
10751 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10752 s.move_with(|map, selection| {
10753 if selection.is_empty() {
10754 let cursor = if action.ignore_newlines {
10755 movement::previous_word_start(map, selection.head())
10756 } else {
10757 movement::previous_word_start_or_newline(map, selection.head())
10758 };
10759 selection.set_head(cursor, SelectionGoal::None);
10760 }
10761 });
10762 });
10763 this.insert("", window, cx);
10764 });
10765 }
10766
10767 pub fn delete_to_previous_subword_start(
10768 &mut self,
10769 _: &DeleteToPreviousSubwordStart,
10770 window: &mut Window,
10771 cx: &mut Context<Self>,
10772 ) {
10773 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10774 self.transact(window, cx, |this, window, cx| {
10775 this.select_autoclose_pair(window, cx);
10776 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10777 s.move_with(|map, selection| {
10778 if selection.is_empty() {
10779 let cursor = movement::previous_subword_start(map, selection.head());
10780 selection.set_head(cursor, SelectionGoal::None);
10781 }
10782 });
10783 });
10784 this.insert("", window, cx);
10785 });
10786 }
10787
10788 pub fn move_to_next_word_end(
10789 &mut self,
10790 _: &MoveToNextWordEnd,
10791 window: &mut Window,
10792 cx: &mut Context<Self>,
10793 ) {
10794 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10795 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10796 s.move_cursors_with(|map, head, _| {
10797 (movement::next_word_end(map, head), SelectionGoal::None)
10798 });
10799 })
10800 }
10801
10802 pub fn move_to_next_subword_end(
10803 &mut self,
10804 _: &MoveToNextSubwordEnd,
10805 window: &mut Window,
10806 cx: &mut Context<Self>,
10807 ) {
10808 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10809 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10810 s.move_cursors_with(|map, head, _| {
10811 (movement::next_subword_end(map, head), SelectionGoal::None)
10812 });
10813 })
10814 }
10815
10816 pub fn select_to_next_word_end(
10817 &mut self,
10818 _: &SelectToNextWordEnd,
10819 window: &mut Window,
10820 cx: &mut Context<Self>,
10821 ) {
10822 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10823 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10824 s.move_heads_with(|map, head, _| {
10825 (movement::next_word_end(map, head), SelectionGoal::None)
10826 });
10827 })
10828 }
10829
10830 pub fn select_to_next_subword_end(
10831 &mut self,
10832 _: &SelectToNextSubwordEnd,
10833 window: &mut Window,
10834 cx: &mut Context<Self>,
10835 ) {
10836 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10838 s.move_heads_with(|map, head, _| {
10839 (movement::next_subword_end(map, head), SelectionGoal::None)
10840 });
10841 })
10842 }
10843
10844 pub fn delete_to_next_word_end(
10845 &mut self,
10846 action: &DeleteToNextWordEnd,
10847 window: &mut Window,
10848 cx: &mut Context<Self>,
10849 ) {
10850 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10851 self.transact(window, cx, |this, window, cx| {
10852 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10853 s.move_with(|map, selection| {
10854 if selection.is_empty() {
10855 let cursor = if action.ignore_newlines {
10856 movement::next_word_end(map, selection.head())
10857 } else {
10858 movement::next_word_end_or_newline(map, selection.head())
10859 };
10860 selection.set_head(cursor, SelectionGoal::None);
10861 }
10862 });
10863 });
10864 this.insert("", window, cx);
10865 });
10866 }
10867
10868 pub fn delete_to_next_subword_end(
10869 &mut self,
10870 _: &DeleteToNextSubwordEnd,
10871 window: &mut Window,
10872 cx: &mut Context<Self>,
10873 ) {
10874 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10875 self.transact(window, cx, |this, window, cx| {
10876 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10877 s.move_with(|map, selection| {
10878 if selection.is_empty() {
10879 let cursor = movement::next_subword_end(map, selection.head());
10880 selection.set_head(cursor, SelectionGoal::None);
10881 }
10882 });
10883 });
10884 this.insert("", window, cx);
10885 });
10886 }
10887
10888 pub fn move_to_beginning_of_line(
10889 &mut self,
10890 action: &MoveToBeginningOfLine,
10891 window: &mut Window,
10892 cx: &mut Context<Self>,
10893 ) {
10894 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10895 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10896 s.move_cursors_with(|map, head, _| {
10897 (
10898 movement::indented_line_beginning(
10899 map,
10900 head,
10901 action.stop_at_soft_wraps,
10902 action.stop_at_indent,
10903 ),
10904 SelectionGoal::None,
10905 )
10906 });
10907 })
10908 }
10909
10910 pub fn select_to_beginning_of_line(
10911 &mut self,
10912 action: &SelectToBeginningOfLine,
10913 window: &mut Window,
10914 cx: &mut Context<Self>,
10915 ) {
10916 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10917 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10918 s.move_heads_with(|map, head, _| {
10919 (
10920 movement::indented_line_beginning(
10921 map,
10922 head,
10923 action.stop_at_soft_wraps,
10924 action.stop_at_indent,
10925 ),
10926 SelectionGoal::None,
10927 )
10928 });
10929 });
10930 }
10931
10932 pub fn delete_to_beginning_of_line(
10933 &mut self,
10934 action: &DeleteToBeginningOfLine,
10935 window: &mut Window,
10936 cx: &mut Context<Self>,
10937 ) {
10938 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10939 self.transact(window, cx, |this, window, cx| {
10940 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10941 s.move_with(|_, selection| {
10942 selection.reversed = true;
10943 });
10944 });
10945
10946 this.select_to_beginning_of_line(
10947 &SelectToBeginningOfLine {
10948 stop_at_soft_wraps: false,
10949 stop_at_indent: action.stop_at_indent,
10950 },
10951 window,
10952 cx,
10953 );
10954 this.backspace(&Backspace, window, cx);
10955 });
10956 }
10957
10958 pub fn move_to_end_of_line(
10959 &mut self,
10960 action: &MoveToEndOfLine,
10961 window: &mut Window,
10962 cx: &mut Context<Self>,
10963 ) {
10964 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10965 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10966 s.move_cursors_with(|map, head, _| {
10967 (
10968 movement::line_end(map, head, action.stop_at_soft_wraps),
10969 SelectionGoal::None,
10970 )
10971 });
10972 })
10973 }
10974
10975 pub fn select_to_end_of_line(
10976 &mut self,
10977 action: &SelectToEndOfLine,
10978 window: &mut Window,
10979 cx: &mut Context<Self>,
10980 ) {
10981 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10982 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10983 s.move_heads_with(|map, head, _| {
10984 (
10985 movement::line_end(map, head, action.stop_at_soft_wraps),
10986 SelectionGoal::None,
10987 )
10988 });
10989 })
10990 }
10991
10992 pub fn delete_to_end_of_line(
10993 &mut self,
10994 _: &DeleteToEndOfLine,
10995 window: &mut Window,
10996 cx: &mut Context<Self>,
10997 ) {
10998 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10999 self.transact(window, cx, |this, window, cx| {
11000 this.select_to_end_of_line(
11001 &SelectToEndOfLine {
11002 stop_at_soft_wraps: false,
11003 },
11004 window,
11005 cx,
11006 );
11007 this.delete(&Delete, window, cx);
11008 });
11009 }
11010
11011 pub fn cut_to_end_of_line(
11012 &mut self,
11013 _: &CutToEndOfLine,
11014 window: &mut Window,
11015 cx: &mut Context<Self>,
11016 ) {
11017 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11018 self.transact(window, cx, |this, window, cx| {
11019 this.select_to_end_of_line(
11020 &SelectToEndOfLine {
11021 stop_at_soft_wraps: false,
11022 },
11023 window,
11024 cx,
11025 );
11026 this.cut(&Cut, window, cx);
11027 });
11028 }
11029
11030 pub fn move_to_start_of_paragraph(
11031 &mut self,
11032 _: &MoveToStartOfParagraph,
11033 window: &mut Window,
11034 cx: &mut Context<Self>,
11035 ) {
11036 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11037 cx.propagate();
11038 return;
11039 }
11040 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11042 s.move_with(|map, selection| {
11043 selection.collapse_to(
11044 movement::start_of_paragraph(map, selection.head(), 1),
11045 SelectionGoal::None,
11046 )
11047 });
11048 })
11049 }
11050
11051 pub fn move_to_end_of_paragraph(
11052 &mut self,
11053 _: &MoveToEndOfParagraph,
11054 window: &mut Window,
11055 cx: &mut Context<Self>,
11056 ) {
11057 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11058 cx.propagate();
11059 return;
11060 }
11061 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11062 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11063 s.move_with(|map, selection| {
11064 selection.collapse_to(
11065 movement::end_of_paragraph(map, selection.head(), 1),
11066 SelectionGoal::None,
11067 )
11068 });
11069 })
11070 }
11071
11072 pub fn select_to_start_of_paragraph(
11073 &mut self,
11074 _: &SelectToStartOfParagraph,
11075 window: &mut Window,
11076 cx: &mut Context<Self>,
11077 ) {
11078 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11079 cx.propagate();
11080 return;
11081 }
11082 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11083 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11084 s.move_heads_with(|map, head, _| {
11085 (
11086 movement::start_of_paragraph(map, head, 1),
11087 SelectionGoal::None,
11088 )
11089 });
11090 })
11091 }
11092
11093 pub fn select_to_end_of_paragraph(
11094 &mut self,
11095 _: &SelectToEndOfParagraph,
11096 window: &mut Window,
11097 cx: &mut Context<Self>,
11098 ) {
11099 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11100 cx.propagate();
11101 return;
11102 }
11103 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11105 s.move_heads_with(|map, head, _| {
11106 (
11107 movement::end_of_paragraph(map, head, 1),
11108 SelectionGoal::None,
11109 )
11110 });
11111 })
11112 }
11113
11114 pub fn move_to_start_of_excerpt(
11115 &mut self,
11116 _: &MoveToStartOfExcerpt,
11117 window: &mut Window,
11118 cx: &mut Context<Self>,
11119 ) {
11120 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11121 cx.propagate();
11122 return;
11123 }
11124 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11125 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11126 s.move_with(|map, selection| {
11127 selection.collapse_to(
11128 movement::start_of_excerpt(
11129 map,
11130 selection.head(),
11131 workspace::searchable::Direction::Prev,
11132 ),
11133 SelectionGoal::None,
11134 )
11135 });
11136 })
11137 }
11138
11139 pub fn move_to_start_of_next_excerpt(
11140 &mut self,
11141 _: &MoveToStartOfNextExcerpt,
11142 window: &mut Window,
11143 cx: &mut Context<Self>,
11144 ) {
11145 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11146 cx.propagate();
11147 return;
11148 }
11149
11150 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11151 s.move_with(|map, selection| {
11152 selection.collapse_to(
11153 movement::start_of_excerpt(
11154 map,
11155 selection.head(),
11156 workspace::searchable::Direction::Next,
11157 ),
11158 SelectionGoal::None,
11159 )
11160 });
11161 })
11162 }
11163
11164 pub fn move_to_end_of_excerpt(
11165 &mut self,
11166 _: &MoveToEndOfExcerpt,
11167 window: &mut Window,
11168 cx: &mut Context<Self>,
11169 ) {
11170 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11171 cx.propagate();
11172 return;
11173 }
11174 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11175 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11176 s.move_with(|map, selection| {
11177 selection.collapse_to(
11178 movement::end_of_excerpt(
11179 map,
11180 selection.head(),
11181 workspace::searchable::Direction::Next,
11182 ),
11183 SelectionGoal::None,
11184 )
11185 });
11186 })
11187 }
11188
11189 pub fn move_to_end_of_previous_excerpt(
11190 &mut self,
11191 _: &MoveToEndOfPreviousExcerpt,
11192 window: &mut Window,
11193 cx: &mut Context<Self>,
11194 ) {
11195 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11196 cx.propagate();
11197 return;
11198 }
11199 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11200 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11201 s.move_with(|map, selection| {
11202 selection.collapse_to(
11203 movement::end_of_excerpt(
11204 map,
11205 selection.head(),
11206 workspace::searchable::Direction::Prev,
11207 ),
11208 SelectionGoal::None,
11209 )
11210 });
11211 })
11212 }
11213
11214 pub fn select_to_start_of_excerpt(
11215 &mut self,
11216 _: &SelectToStartOfExcerpt,
11217 window: &mut Window,
11218 cx: &mut Context<Self>,
11219 ) {
11220 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11221 cx.propagate();
11222 return;
11223 }
11224 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11225 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11226 s.move_heads_with(|map, head, _| {
11227 (
11228 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11229 SelectionGoal::None,
11230 )
11231 });
11232 })
11233 }
11234
11235 pub fn select_to_start_of_next_excerpt(
11236 &mut self,
11237 _: &SelectToStartOfNextExcerpt,
11238 window: &mut Window,
11239 cx: &mut Context<Self>,
11240 ) {
11241 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11242 cx.propagate();
11243 return;
11244 }
11245 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11246 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247 s.move_heads_with(|map, head, _| {
11248 (
11249 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11250 SelectionGoal::None,
11251 )
11252 });
11253 })
11254 }
11255
11256 pub fn select_to_end_of_excerpt(
11257 &mut self,
11258 _: &SelectToEndOfExcerpt,
11259 window: &mut Window,
11260 cx: &mut Context<Self>,
11261 ) {
11262 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11263 cx.propagate();
11264 return;
11265 }
11266 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11267 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11268 s.move_heads_with(|map, head, _| {
11269 (
11270 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11271 SelectionGoal::None,
11272 )
11273 });
11274 })
11275 }
11276
11277 pub fn select_to_end_of_previous_excerpt(
11278 &mut self,
11279 _: &SelectToEndOfPreviousExcerpt,
11280 window: &mut Window,
11281 cx: &mut Context<Self>,
11282 ) {
11283 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11284 cx.propagate();
11285 return;
11286 }
11287 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11288 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289 s.move_heads_with(|map, head, _| {
11290 (
11291 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11292 SelectionGoal::None,
11293 )
11294 });
11295 })
11296 }
11297
11298 pub fn move_to_beginning(
11299 &mut self,
11300 _: &MoveToBeginning,
11301 window: &mut Window,
11302 cx: &mut Context<Self>,
11303 ) {
11304 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11305 cx.propagate();
11306 return;
11307 }
11308 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11309 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11310 s.select_ranges(vec![0..0]);
11311 });
11312 }
11313
11314 pub fn select_to_beginning(
11315 &mut self,
11316 _: &SelectToBeginning,
11317 window: &mut Window,
11318 cx: &mut Context<Self>,
11319 ) {
11320 let mut selection = self.selections.last::<Point>(cx);
11321 selection.set_head(Point::zero(), SelectionGoal::None);
11322 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11323 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11324 s.select(vec![selection]);
11325 });
11326 }
11327
11328 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11329 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11330 cx.propagate();
11331 return;
11332 }
11333 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11334 let cursor = self.buffer.read(cx).read(cx).len();
11335 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11336 s.select_ranges(vec![cursor..cursor])
11337 });
11338 }
11339
11340 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11341 self.nav_history = nav_history;
11342 }
11343
11344 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11345 self.nav_history.as_ref()
11346 }
11347
11348 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11349 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11350 }
11351
11352 fn push_to_nav_history(
11353 &mut self,
11354 cursor_anchor: Anchor,
11355 new_position: Option<Point>,
11356 is_deactivate: bool,
11357 cx: &mut Context<Self>,
11358 ) {
11359 if let Some(nav_history) = self.nav_history.as_mut() {
11360 let buffer = self.buffer.read(cx).read(cx);
11361 let cursor_position = cursor_anchor.to_point(&buffer);
11362 let scroll_state = self.scroll_manager.anchor();
11363 let scroll_top_row = scroll_state.top_row(&buffer);
11364 drop(buffer);
11365
11366 if let Some(new_position) = new_position {
11367 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11368 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11369 return;
11370 }
11371 }
11372
11373 nav_history.push(
11374 Some(NavigationData {
11375 cursor_anchor,
11376 cursor_position,
11377 scroll_anchor: scroll_state,
11378 scroll_top_row,
11379 }),
11380 cx,
11381 );
11382 cx.emit(EditorEvent::PushedToNavHistory {
11383 anchor: cursor_anchor,
11384 is_deactivate,
11385 })
11386 }
11387 }
11388
11389 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11390 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11391 let buffer = self.buffer.read(cx).snapshot(cx);
11392 let mut selection = self.selections.first::<usize>(cx);
11393 selection.set_head(buffer.len(), SelectionGoal::None);
11394 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11395 s.select(vec![selection]);
11396 });
11397 }
11398
11399 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11400 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11401 let end = self.buffer.read(cx).read(cx).len();
11402 self.change_selections(None, window, cx, |s| {
11403 s.select_ranges(vec![0..end]);
11404 });
11405 }
11406
11407 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11408 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11410 let mut selections = self.selections.all::<Point>(cx);
11411 let max_point = display_map.buffer_snapshot.max_point();
11412 for selection in &mut selections {
11413 let rows = selection.spanned_rows(true, &display_map);
11414 selection.start = Point::new(rows.start.0, 0);
11415 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11416 selection.reversed = false;
11417 }
11418 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11419 s.select(selections);
11420 });
11421 }
11422
11423 pub fn split_selection_into_lines(
11424 &mut self,
11425 _: &SplitSelectionIntoLines,
11426 window: &mut Window,
11427 cx: &mut Context<Self>,
11428 ) {
11429 let selections = self
11430 .selections
11431 .all::<Point>(cx)
11432 .into_iter()
11433 .map(|selection| selection.start..selection.end)
11434 .collect::<Vec<_>>();
11435 self.unfold_ranges(&selections, true, true, cx);
11436
11437 let mut new_selection_ranges = Vec::new();
11438 {
11439 let buffer = self.buffer.read(cx).read(cx);
11440 for selection in selections {
11441 for row in selection.start.row..selection.end.row {
11442 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11443 new_selection_ranges.push(cursor..cursor);
11444 }
11445
11446 let is_multiline_selection = selection.start.row != selection.end.row;
11447 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11448 // so this action feels more ergonomic when paired with other selection operations
11449 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11450 if !should_skip_last {
11451 new_selection_ranges.push(selection.end..selection.end);
11452 }
11453 }
11454 }
11455 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11456 s.select_ranges(new_selection_ranges);
11457 });
11458 }
11459
11460 pub fn add_selection_above(
11461 &mut self,
11462 _: &AddSelectionAbove,
11463 window: &mut Window,
11464 cx: &mut Context<Self>,
11465 ) {
11466 self.add_selection(true, window, cx);
11467 }
11468
11469 pub fn add_selection_below(
11470 &mut self,
11471 _: &AddSelectionBelow,
11472 window: &mut Window,
11473 cx: &mut Context<Self>,
11474 ) {
11475 self.add_selection(false, window, cx);
11476 }
11477
11478 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11479 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11480
11481 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11482 let mut selections = self.selections.all::<Point>(cx);
11483 let text_layout_details = self.text_layout_details(window);
11484 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11485 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11486 let range = oldest_selection.display_range(&display_map).sorted();
11487
11488 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11489 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11490 let positions = start_x.min(end_x)..start_x.max(end_x);
11491
11492 selections.clear();
11493 let mut stack = Vec::new();
11494 for row in range.start.row().0..=range.end.row().0 {
11495 if let Some(selection) = self.selections.build_columnar_selection(
11496 &display_map,
11497 DisplayRow(row),
11498 &positions,
11499 oldest_selection.reversed,
11500 &text_layout_details,
11501 ) {
11502 stack.push(selection.id);
11503 selections.push(selection);
11504 }
11505 }
11506
11507 if above {
11508 stack.reverse();
11509 }
11510
11511 AddSelectionsState { above, stack }
11512 });
11513
11514 let last_added_selection = *state.stack.last().unwrap();
11515 let mut new_selections = Vec::new();
11516 if above == state.above {
11517 let end_row = if above {
11518 DisplayRow(0)
11519 } else {
11520 display_map.max_point().row()
11521 };
11522
11523 'outer: for selection in selections {
11524 if selection.id == last_added_selection {
11525 let range = selection.display_range(&display_map).sorted();
11526 debug_assert_eq!(range.start.row(), range.end.row());
11527 let mut row = range.start.row();
11528 let positions =
11529 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11530 px(start)..px(end)
11531 } else {
11532 let start_x =
11533 display_map.x_for_display_point(range.start, &text_layout_details);
11534 let end_x =
11535 display_map.x_for_display_point(range.end, &text_layout_details);
11536 start_x.min(end_x)..start_x.max(end_x)
11537 };
11538
11539 while row != end_row {
11540 if above {
11541 row.0 -= 1;
11542 } else {
11543 row.0 += 1;
11544 }
11545
11546 if let Some(new_selection) = self.selections.build_columnar_selection(
11547 &display_map,
11548 row,
11549 &positions,
11550 selection.reversed,
11551 &text_layout_details,
11552 ) {
11553 state.stack.push(new_selection.id);
11554 if above {
11555 new_selections.push(new_selection);
11556 new_selections.push(selection);
11557 } else {
11558 new_selections.push(selection);
11559 new_selections.push(new_selection);
11560 }
11561
11562 continue 'outer;
11563 }
11564 }
11565 }
11566
11567 new_selections.push(selection);
11568 }
11569 } else {
11570 new_selections = selections;
11571 new_selections.retain(|s| s.id != last_added_selection);
11572 state.stack.pop();
11573 }
11574
11575 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11576 s.select(new_selections);
11577 });
11578 if state.stack.len() > 1 {
11579 self.add_selections_state = Some(state);
11580 }
11581 }
11582
11583 pub fn select_next_match_internal(
11584 &mut self,
11585 display_map: &DisplaySnapshot,
11586 replace_newest: bool,
11587 autoscroll: Option<Autoscroll>,
11588 window: &mut Window,
11589 cx: &mut Context<Self>,
11590 ) -> Result<()> {
11591 fn select_next_match_ranges(
11592 this: &mut Editor,
11593 range: Range<usize>,
11594 replace_newest: bool,
11595 auto_scroll: Option<Autoscroll>,
11596 window: &mut Window,
11597 cx: &mut Context<Editor>,
11598 ) {
11599 this.unfold_ranges(&[range.clone()], false, true, cx);
11600 this.change_selections(auto_scroll, window, cx, |s| {
11601 if replace_newest {
11602 s.delete(s.newest_anchor().id);
11603 }
11604 s.insert_range(range.clone());
11605 });
11606 }
11607
11608 let buffer = &display_map.buffer_snapshot;
11609 let mut selections = self.selections.all::<usize>(cx);
11610 if let Some(mut select_next_state) = self.select_next_state.take() {
11611 let query = &select_next_state.query;
11612 if !select_next_state.done {
11613 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11614 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11615 let mut next_selected_range = None;
11616
11617 let bytes_after_last_selection =
11618 buffer.bytes_in_range(last_selection.end..buffer.len());
11619 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11620 let query_matches = query
11621 .stream_find_iter(bytes_after_last_selection)
11622 .map(|result| (last_selection.end, result))
11623 .chain(
11624 query
11625 .stream_find_iter(bytes_before_first_selection)
11626 .map(|result| (0, result)),
11627 );
11628
11629 for (start_offset, query_match) in query_matches {
11630 let query_match = query_match.unwrap(); // can only fail due to I/O
11631 let offset_range =
11632 start_offset + query_match.start()..start_offset + query_match.end();
11633 let display_range = offset_range.start.to_display_point(display_map)
11634 ..offset_range.end.to_display_point(display_map);
11635
11636 if !select_next_state.wordwise
11637 || (!movement::is_inside_word(display_map, display_range.start)
11638 && !movement::is_inside_word(display_map, display_range.end))
11639 {
11640 // TODO: This is n^2, because we might check all the selections
11641 if !selections
11642 .iter()
11643 .any(|selection| selection.range().overlaps(&offset_range))
11644 {
11645 next_selected_range = Some(offset_range);
11646 break;
11647 }
11648 }
11649 }
11650
11651 if let Some(next_selected_range) = next_selected_range {
11652 select_next_match_ranges(
11653 self,
11654 next_selected_range,
11655 replace_newest,
11656 autoscroll,
11657 window,
11658 cx,
11659 );
11660 } else {
11661 select_next_state.done = true;
11662 }
11663 }
11664
11665 self.select_next_state = Some(select_next_state);
11666 } else {
11667 let mut only_carets = true;
11668 let mut same_text_selected = true;
11669 let mut selected_text = None;
11670
11671 let mut selections_iter = selections.iter().peekable();
11672 while let Some(selection) = selections_iter.next() {
11673 if selection.start != selection.end {
11674 only_carets = false;
11675 }
11676
11677 if same_text_selected {
11678 if selected_text.is_none() {
11679 selected_text =
11680 Some(buffer.text_for_range(selection.range()).collect::<String>());
11681 }
11682
11683 if let Some(next_selection) = selections_iter.peek() {
11684 if next_selection.range().len() == selection.range().len() {
11685 let next_selected_text = buffer
11686 .text_for_range(next_selection.range())
11687 .collect::<String>();
11688 if Some(next_selected_text) != selected_text {
11689 same_text_selected = false;
11690 selected_text = None;
11691 }
11692 } else {
11693 same_text_selected = false;
11694 selected_text = None;
11695 }
11696 }
11697 }
11698 }
11699
11700 if only_carets {
11701 for selection in &mut selections {
11702 let word_range = movement::surrounding_word(
11703 display_map,
11704 selection.start.to_display_point(display_map),
11705 );
11706 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11707 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11708 selection.goal = SelectionGoal::None;
11709 selection.reversed = false;
11710 select_next_match_ranges(
11711 self,
11712 selection.start..selection.end,
11713 replace_newest,
11714 autoscroll,
11715 window,
11716 cx,
11717 );
11718 }
11719
11720 if selections.len() == 1 {
11721 let selection = selections
11722 .last()
11723 .expect("ensured that there's only one selection");
11724 let query = buffer
11725 .text_for_range(selection.start..selection.end)
11726 .collect::<String>();
11727 let is_empty = query.is_empty();
11728 let select_state = SelectNextState {
11729 query: AhoCorasick::new(&[query])?,
11730 wordwise: true,
11731 done: is_empty,
11732 };
11733 self.select_next_state = Some(select_state);
11734 } else {
11735 self.select_next_state = None;
11736 }
11737 } else if let Some(selected_text) = selected_text {
11738 self.select_next_state = Some(SelectNextState {
11739 query: AhoCorasick::new(&[selected_text])?,
11740 wordwise: false,
11741 done: false,
11742 });
11743 self.select_next_match_internal(
11744 display_map,
11745 replace_newest,
11746 autoscroll,
11747 window,
11748 cx,
11749 )?;
11750 }
11751 }
11752 Ok(())
11753 }
11754
11755 pub fn select_all_matches(
11756 &mut self,
11757 _action: &SelectAllMatches,
11758 window: &mut Window,
11759 cx: &mut Context<Self>,
11760 ) -> Result<()> {
11761 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11762
11763 self.push_to_selection_history();
11764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11765
11766 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11767 let Some(select_next_state) = self.select_next_state.as_mut() else {
11768 return Ok(());
11769 };
11770 if select_next_state.done {
11771 return Ok(());
11772 }
11773
11774 let mut new_selections = self.selections.all::<usize>(cx);
11775
11776 let buffer = &display_map.buffer_snapshot;
11777 let query_matches = select_next_state
11778 .query
11779 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11780
11781 for query_match in query_matches {
11782 let query_match = query_match.unwrap(); // can only fail due to I/O
11783 let offset_range = query_match.start()..query_match.end();
11784 let display_range = offset_range.start.to_display_point(&display_map)
11785 ..offset_range.end.to_display_point(&display_map);
11786
11787 if !select_next_state.wordwise
11788 || (!movement::is_inside_word(&display_map, display_range.start)
11789 && !movement::is_inside_word(&display_map, display_range.end))
11790 {
11791 self.selections.change_with(cx, |selections| {
11792 new_selections.push(Selection {
11793 id: selections.new_selection_id(),
11794 start: offset_range.start,
11795 end: offset_range.end,
11796 reversed: false,
11797 goal: SelectionGoal::None,
11798 });
11799 });
11800 }
11801 }
11802
11803 new_selections.sort_by_key(|selection| selection.start);
11804 let mut ix = 0;
11805 while ix + 1 < new_selections.len() {
11806 let current_selection = &new_selections[ix];
11807 let next_selection = &new_selections[ix + 1];
11808 if current_selection.range().overlaps(&next_selection.range()) {
11809 if current_selection.id < next_selection.id {
11810 new_selections.remove(ix + 1);
11811 } else {
11812 new_selections.remove(ix);
11813 }
11814 } else {
11815 ix += 1;
11816 }
11817 }
11818
11819 let reversed = self.selections.oldest::<usize>(cx).reversed;
11820
11821 for selection in new_selections.iter_mut() {
11822 selection.reversed = reversed;
11823 }
11824
11825 select_next_state.done = true;
11826 self.unfold_ranges(
11827 &new_selections
11828 .iter()
11829 .map(|selection| selection.range())
11830 .collect::<Vec<_>>(),
11831 false,
11832 false,
11833 cx,
11834 );
11835 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11836 selections.select(new_selections)
11837 });
11838
11839 Ok(())
11840 }
11841
11842 pub fn select_next(
11843 &mut self,
11844 action: &SelectNext,
11845 window: &mut Window,
11846 cx: &mut Context<Self>,
11847 ) -> Result<()> {
11848 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11849 self.push_to_selection_history();
11850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11851 self.select_next_match_internal(
11852 &display_map,
11853 action.replace_newest,
11854 Some(Autoscroll::newest()),
11855 window,
11856 cx,
11857 )?;
11858 Ok(())
11859 }
11860
11861 pub fn select_previous(
11862 &mut self,
11863 action: &SelectPrevious,
11864 window: &mut Window,
11865 cx: &mut Context<Self>,
11866 ) -> Result<()> {
11867 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11868 self.push_to_selection_history();
11869 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11870 let buffer = &display_map.buffer_snapshot;
11871 let mut selections = self.selections.all::<usize>(cx);
11872 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11873 let query = &select_prev_state.query;
11874 if !select_prev_state.done {
11875 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11876 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11877 let mut next_selected_range = None;
11878 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11879 let bytes_before_last_selection =
11880 buffer.reversed_bytes_in_range(0..last_selection.start);
11881 let bytes_after_first_selection =
11882 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11883 let query_matches = query
11884 .stream_find_iter(bytes_before_last_selection)
11885 .map(|result| (last_selection.start, result))
11886 .chain(
11887 query
11888 .stream_find_iter(bytes_after_first_selection)
11889 .map(|result| (buffer.len(), result)),
11890 );
11891 for (end_offset, query_match) in query_matches {
11892 let query_match = query_match.unwrap(); // can only fail due to I/O
11893 let offset_range =
11894 end_offset - query_match.end()..end_offset - query_match.start();
11895 let display_range = offset_range.start.to_display_point(&display_map)
11896 ..offset_range.end.to_display_point(&display_map);
11897
11898 if !select_prev_state.wordwise
11899 || (!movement::is_inside_word(&display_map, display_range.start)
11900 && !movement::is_inside_word(&display_map, display_range.end))
11901 {
11902 next_selected_range = Some(offset_range);
11903 break;
11904 }
11905 }
11906
11907 if let Some(next_selected_range) = next_selected_range {
11908 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11909 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11910 if action.replace_newest {
11911 s.delete(s.newest_anchor().id);
11912 }
11913 s.insert_range(next_selected_range);
11914 });
11915 } else {
11916 select_prev_state.done = true;
11917 }
11918 }
11919
11920 self.select_prev_state = Some(select_prev_state);
11921 } else {
11922 let mut only_carets = true;
11923 let mut same_text_selected = true;
11924 let mut selected_text = None;
11925
11926 let mut selections_iter = selections.iter().peekable();
11927 while let Some(selection) = selections_iter.next() {
11928 if selection.start != selection.end {
11929 only_carets = false;
11930 }
11931
11932 if same_text_selected {
11933 if selected_text.is_none() {
11934 selected_text =
11935 Some(buffer.text_for_range(selection.range()).collect::<String>());
11936 }
11937
11938 if let Some(next_selection) = selections_iter.peek() {
11939 if next_selection.range().len() == selection.range().len() {
11940 let next_selected_text = buffer
11941 .text_for_range(next_selection.range())
11942 .collect::<String>();
11943 if Some(next_selected_text) != selected_text {
11944 same_text_selected = false;
11945 selected_text = None;
11946 }
11947 } else {
11948 same_text_selected = false;
11949 selected_text = None;
11950 }
11951 }
11952 }
11953 }
11954
11955 if only_carets {
11956 for selection in &mut selections {
11957 let word_range = movement::surrounding_word(
11958 &display_map,
11959 selection.start.to_display_point(&display_map),
11960 );
11961 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11962 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11963 selection.goal = SelectionGoal::None;
11964 selection.reversed = false;
11965 }
11966 if selections.len() == 1 {
11967 let selection = selections
11968 .last()
11969 .expect("ensured that there's only one selection");
11970 let query = buffer
11971 .text_for_range(selection.start..selection.end)
11972 .collect::<String>();
11973 let is_empty = query.is_empty();
11974 let select_state = SelectNextState {
11975 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11976 wordwise: true,
11977 done: is_empty,
11978 };
11979 self.select_prev_state = Some(select_state);
11980 } else {
11981 self.select_prev_state = None;
11982 }
11983
11984 self.unfold_ranges(
11985 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11986 false,
11987 true,
11988 cx,
11989 );
11990 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11991 s.select(selections);
11992 });
11993 } else if let Some(selected_text) = selected_text {
11994 self.select_prev_state = Some(SelectNextState {
11995 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11996 wordwise: false,
11997 done: false,
11998 });
11999 self.select_previous(action, window, cx)?;
12000 }
12001 }
12002 Ok(())
12003 }
12004
12005 pub fn toggle_comments(
12006 &mut self,
12007 action: &ToggleComments,
12008 window: &mut Window,
12009 cx: &mut Context<Self>,
12010 ) {
12011 if self.read_only(cx) {
12012 return;
12013 }
12014 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12015 let text_layout_details = &self.text_layout_details(window);
12016 self.transact(window, cx, |this, window, cx| {
12017 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12018 let mut edits = Vec::new();
12019 let mut selection_edit_ranges = Vec::new();
12020 let mut last_toggled_row = None;
12021 let snapshot = this.buffer.read(cx).read(cx);
12022 let empty_str: Arc<str> = Arc::default();
12023 let mut suffixes_inserted = Vec::new();
12024 let ignore_indent = action.ignore_indent;
12025
12026 fn comment_prefix_range(
12027 snapshot: &MultiBufferSnapshot,
12028 row: MultiBufferRow,
12029 comment_prefix: &str,
12030 comment_prefix_whitespace: &str,
12031 ignore_indent: bool,
12032 ) -> Range<Point> {
12033 let indent_size = if ignore_indent {
12034 0
12035 } else {
12036 snapshot.indent_size_for_line(row).len
12037 };
12038
12039 let start = Point::new(row.0, indent_size);
12040
12041 let mut line_bytes = snapshot
12042 .bytes_in_range(start..snapshot.max_point())
12043 .flatten()
12044 .copied();
12045
12046 // If this line currently begins with the line comment prefix, then record
12047 // the range containing the prefix.
12048 if line_bytes
12049 .by_ref()
12050 .take(comment_prefix.len())
12051 .eq(comment_prefix.bytes())
12052 {
12053 // Include any whitespace that matches the comment prefix.
12054 let matching_whitespace_len = line_bytes
12055 .zip(comment_prefix_whitespace.bytes())
12056 .take_while(|(a, b)| a == b)
12057 .count() as u32;
12058 let end = Point::new(
12059 start.row,
12060 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12061 );
12062 start..end
12063 } else {
12064 start..start
12065 }
12066 }
12067
12068 fn comment_suffix_range(
12069 snapshot: &MultiBufferSnapshot,
12070 row: MultiBufferRow,
12071 comment_suffix: &str,
12072 comment_suffix_has_leading_space: bool,
12073 ) -> Range<Point> {
12074 let end = Point::new(row.0, snapshot.line_len(row));
12075 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12076
12077 let mut line_end_bytes = snapshot
12078 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12079 .flatten()
12080 .copied();
12081
12082 let leading_space_len = if suffix_start_column > 0
12083 && line_end_bytes.next() == Some(b' ')
12084 && comment_suffix_has_leading_space
12085 {
12086 1
12087 } else {
12088 0
12089 };
12090
12091 // If this line currently begins with the line comment prefix, then record
12092 // the range containing the prefix.
12093 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12094 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12095 start..end
12096 } else {
12097 end..end
12098 }
12099 }
12100
12101 // TODO: Handle selections that cross excerpts
12102 for selection in &mut selections {
12103 let start_column = snapshot
12104 .indent_size_for_line(MultiBufferRow(selection.start.row))
12105 .len;
12106 let language = if let Some(language) =
12107 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12108 {
12109 language
12110 } else {
12111 continue;
12112 };
12113
12114 selection_edit_ranges.clear();
12115
12116 // If multiple selections contain a given row, avoid processing that
12117 // row more than once.
12118 let mut start_row = MultiBufferRow(selection.start.row);
12119 if last_toggled_row == Some(start_row) {
12120 start_row = start_row.next_row();
12121 }
12122 let end_row =
12123 if selection.end.row > selection.start.row && selection.end.column == 0 {
12124 MultiBufferRow(selection.end.row - 1)
12125 } else {
12126 MultiBufferRow(selection.end.row)
12127 };
12128 last_toggled_row = Some(end_row);
12129
12130 if start_row > end_row {
12131 continue;
12132 }
12133
12134 // If the language has line comments, toggle those.
12135 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12136
12137 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12138 if ignore_indent {
12139 full_comment_prefixes = full_comment_prefixes
12140 .into_iter()
12141 .map(|s| Arc::from(s.trim_end()))
12142 .collect();
12143 }
12144
12145 if !full_comment_prefixes.is_empty() {
12146 let first_prefix = full_comment_prefixes
12147 .first()
12148 .expect("prefixes is non-empty");
12149 let prefix_trimmed_lengths = full_comment_prefixes
12150 .iter()
12151 .map(|p| p.trim_end_matches(' ').len())
12152 .collect::<SmallVec<[usize; 4]>>();
12153
12154 let mut all_selection_lines_are_comments = true;
12155
12156 for row in start_row.0..=end_row.0 {
12157 let row = MultiBufferRow(row);
12158 if start_row < end_row && snapshot.is_line_blank(row) {
12159 continue;
12160 }
12161
12162 let prefix_range = full_comment_prefixes
12163 .iter()
12164 .zip(prefix_trimmed_lengths.iter().copied())
12165 .map(|(prefix, trimmed_prefix_len)| {
12166 comment_prefix_range(
12167 snapshot.deref(),
12168 row,
12169 &prefix[..trimmed_prefix_len],
12170 &prefix[trimmed_prefix_len..],
12171 ignore_indent,
12172 )
12173 })
12174 .max_by_key(|range| range.end.column - range.start.column)
12175 .expect("prefixes is non-empty");
12176
12177 if prefix_range.is_empty() {
12178 all_selection_lines_are_comments = false;
12179 }
12180
12181 selection_edit_ranges.push(prefix_range);
12182 }
12183
12184 if all_selection_lines_are_comments {
12185 edits.extend(
12186 selection_edit_ranges
12187 .iter()
12188 .cloned()
12189 .map(|range| (range, empty_str.clone())),
12190 );
12191 } else {
12192 let min_column = selection_edit_ranges
12193 .iter()
12194 .map(|range| range.start.column)
12195 .min()
12196 .unwrap_or(0);
12197 edits.extend(selection_edit_ranges.iter().map(|range| {
12198 let position = Point::new(range.start.row, min_column);
12199 (position..position, first_prefix.clone())
12200 }));
12201 }
12202 } else if let Some((full_comment_prefix, comment_suffix)) =
12203 language.block_comment_delimiters()
12204 {
12205 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12206 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12207 let prefix_range = comment_prefix_range(
12208 snapshot.deref(),
12209 start_row,
12210 comment_prefix,
12211 comment_prefix_whitespace,
12212 ignore_indent,
12213 );
12214 let suffix_range = comment_suffix_range(
12215 snapshot.deref(),
12216 end_row,
12217 comment_suffix.trim_start_matches(' '),
12218 comment_suffix.starts_with(' '),
12219 );
12220
12221 if prefix_range.is_empty() || suffix_range.is_empty() {
12222 edits.push((
12223 prefix_range.start..prefix_range.start,
12224 full_comment_prefix.clone(),
12225 ));
12226 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12227 suffixes_inserted.push((end_row, comment_suffix.len()));
12228 } else {
12229 edits.push((prefix_range, empty_str.clone()));
12230 edits.push((suffix_range, empty_str.clone()));
12231 }
12232 } else {
12233 continue;
12234 }
12235 }
12236
12237 drop(snapshot);
12238 this.buffer.update(cx, |buffer, cx| {
12239 buffer.edit(edits, None, cx);
12240 });
12241
12242 // Adjust selections so that they end before any comment suffixes that
12243 // were inserted.
12244 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12245 let mut selections = this.selections.all::<Point>(cx);
12246 let snapshot = this.buffer.read(cx).read(cx);
12247 for selection in &mut selections {
12248 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12249 match row.cmp(&MultiBufferRow(selection.end.row)) {
12250 Ordering::Less => {
12251 suffixes_inserted.next();
12252 continue;
12253 }
12254 Ordering::Greater => break,
12255 Ordering::Equal => {
12256 if selection.end.column == snapshot.line_len(row) {
12257 if selection.is_empty() {
12258 selection.start.column -= suffix_len as u32;
12259 }
12260 selection.end.column -= suffix_len as u32;
12261 }
12262 break;
12263 }
12264 }
12265 }
12266 }
12267
12268 drop(snapshot);
12269 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12270 s.select(selections)
12271 });
12272
12273 let selections = this.selections.all::<Point>(cx);
12274 let selections_on_single_row = selections.windows(2).all(|selections| {
12275 selections[0].start.row == selections[1].start.row
12276 && selections[0].end.row == selections[1].end.row
12277 && selections[0].start.row == selections[0].end.row
12278 });
12279 let selections_selecting = selections
12280 .iter()
12281 .any(|selection| selection.start != selection.end);
12282 let advance_downwards = action.advance_downwards
12283 && selections_on_single_row
12284 && !selections_selecting
12285 && !matches!(this.mode, EditorMode::SingleLine { .. });
12286
12287 if advance_downwards {
12288 let snapshot = this.buffer.read(cx).snapshot(cx);
12289
12290 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12291 s.move_cursors_with(|display_snapshot, display_point, _| {
12292 let mut point = display_point.to_point(display_snapshot);
12293 point.row += 1;
12294 point = snapshot.clip_point(point, Bias::Left);
12295 let display_point = point.to_display_point(display_snapshot);
12296 let goal = SelectionGoal::HorizontalPosition(
12297 display_snapshot
12298 .x_for_display_point(display_point, text_layout_details)
12299 .into(),
12300 );
12301 (display_point, goal)
12302 })
12303 });
12304 }
12305 });
12306 }
12307
12308 pub fn select_enclosing_symbol(
12309 &mut self,
12310 _: &SelectEnclosingSymbol,
12311 window: &mut Window,
12312 cx: &mut Context<Self>,
12313 ) {
12314 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12315
12316 let buffer = self.buffer.read(cx).snapshot(cx);
12317 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12318
12319 fn update_selection(
12320 selection: &Selection<usize>,
12321 buffer_snap: &MultiBufferSnapshot,
12322 ) -> Option<Selection<usize>> {
12323 let cursor = selection.head();
12324 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12325 for symbol in symbols.iter().rev() {
12326 let start = symbol.range.start.to_offset(buffer_snap);
12327 let end = symbol.range.end.to_offset(buffer_snap);
12328 let new_range = start..end;
12329 if start < selection.start || end > selection.end {
12330 return Some(Selection {
12331 id: selection.id,
12332 start: new_range.start,
12333 end: new_range.end,
12334 goal: SelectionGoal::None,
12335 reversed: selection.reversed,
12336 });
12337 }
12338 }
12339 None
12340 }
12341
12342 let mut selected_larger_symbol = false;
12343 let new_selections = old_selections
12344 .iter()
12345 .map(|selection| match update_selection(selection, &buffer) {
12346 Some(new_selection) => {
12347 if new_selection.range() != selection.range() {
12348 selected_larger_symbol = true;
12349 }
12350 new_selection
12351 }
12352 None => selection.clone(),
12353 })
12354 .collect::<Vec<_>>();
12355
12356 if selected_larger_symbol {
12357 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12358 s.select(new_selections);
12359 });
12360 }
12361 }
12362
12363 pub fn select_larger_syntax_node(
12364 &mut self,
12365 _: &SelectLargerSyntaxNode,
12366 window: &mut Window,
12367 cx: &mut Context<Self>,
12368 ) {
12369 let Some(visible_row_count) = self.visible_row_count() else {
12370 return;
12371 };
12372 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12373 if old_selections.is_empty() {
12374 return;
12375 }
12376
12377 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12378
12379 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12380 let buffer = self.buffer.read(cx).snapshot(cx);
12381
12382 let mut selected_larger_node = false;
12383 let mut new_selections = old_selections
12384 .iter()
12385 .map(|selection| {
12386 let old_range = selection.start..selection.end;
12387 let mut new_range = old_range.clone();
12388 let mut new_node = None;
12389 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12390 {
12391 new_node = Some(node);
12392 new_range = match containing_range {
12393 MultiOrSingleBufferOffsetRange::Single(_) => break,
12394 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12395 };
12396 if !display_map.intersects_fold(new_range.start)
12397 && !display_map.intersects_fold(new_range.end)
12398 {
12399 break;
12400 }
12401 }
12402
12403 if let Some(node) = new_node {
12404 // Log the ancestor, to support using this action as a way to explore TreeSitter
12405 // nodes. Parent and grandparent are also logged because this operation will not
12406 // visit nodes that have the same range as their parent.
12407 log::info!("Node: {node:?}");
12408 let parent = node.parent();
12409 log::info!("Parent: {parent:?}");
12410 let grandparent = parent.and_then(|x| x.parent());
12411 log::info!("Grandparent: {grandparent:?}");
12412 }
12413
12414 selected_larger_node |= new_range != old_range;
12415 Selection {
12416 id: selection.id,
12417 start: new_range.start,
12418 end: new_range.end,
12419 goal: SelectionGoal::None,
12420 reversed: selection.reversed,
12421 }
12422 })
12423 .collect::<Vec<_>>();
12424
12425 if !selected_larger_node {
12426 return; // don't put this call in the history
12427 }
12428
12429 // scroll based on transformation done to the last selection created by the user
12430 let (last_old, last_new) = old_selections
12431 .last()
12432 .zip(new_selections.last().cloned())
12433 .expect("old_selections isn't empty");
12434
12435 // revert selection
12436 let is_selection_reversed = {
12437 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12438 new_selections.last_mut().expect("checked above").reversed =
12439 should_newest_selection_be_reversed;
12440 should_newest_selection_be_reversed
12441 };
12442
12443 if selected_larger_node {
12444 self.select_syntax_node_history.disable_clearing = true;
12445 self.change_selections(None, window, cx, |s| {
12446 s.select(new_selections.clone());
12447 });
12448 self.select_syntax_node_history.disable_clearing = false;
12449 }
12450
12451 let start_row = last_new.start.to_display_point(&display_map).row().0;
12452 let end_row = last_new.end.to_display_point(&display_map).row().0;
12453 let selection_height = end_row - start_row + 1;
12454 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12455
12456 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12457 let scroll_behavior = if fits_on_the_screen {
12458 self.request_autoscroll(Autoscroll::fit(), cx);
12459 SelectSyntaxNodeScrollBehavior::FitSelection
12460 } else if is_selection_reversed {
12461 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12462 SelectSyntaxNodeScrollBehavior::CursorTop
12463 } else {
12464 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12465 SelectSyntaxNodeScrollBehavior::CursorBottom
12466 };
12467
12468 self.select_syntax_node_history.push((
12469 old_selections,
12470 scroll_behavior,
12471 is_selection_reversed,
12472 ));
12473 }
12474
12475 pub fn select_smaller_syntax_node(
12476 &mut self,
12477 _: &SelectSmallerSyntaxNode,
12478 window: &mut Window,
12479 cx: &mut Context<Self>,
12480 ) {
12481 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12482
12483 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12484 self.select_syntax_node_history.pop()
12485 {
12486 if let Some(selection) = selections.last_mut() {
12487 selection.reversed = is_selection_reversed;
12488 }
12489
12490 self.select_syntax_node_history.disable_clearing = true;
12491 self.change_selections(None, window, cx, |s| {
12492 s.select(selections.to_vec());
12493 });
12494 self.select_syntax_node_history.disable_clearing = false;
12495
12496 match scroll_behavior {
12497 SelectSyntaxNodeScrollBehavior::CursorTop => {
12498 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12499 }
12500 SelectSyntaxNodeScrollBehavior::FitSelection => {
12501 self.request_autoscroll(Autoscroll::fit(), cx);
12502 }
12503 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12504 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12505 }
12506 }
12507 }
12508 }
12509
12510 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12511 if !EditorSettings::get_global(cx).gutter.runnables {
12512 self.clear_tasks();
12513 return Task::ready(());
12514 }
12515 let project = self.project.as_ref().map(Entity::downgrade);
12516 let task_sources = self.lsp_task_sources(cx);
12517 cx.spawn_in(window, async move |editor, cx| {
12518 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12519 let Some(project) = project.and_then(|p| p.upgrade()) else {
12520 return;
12521 };
12522 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12523 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12524 }) else {
12525 return;
12526 };
12527
12528 let hide_runnables = project
12529 .update(cx, |project, cx| {
12530 // Do not display any test indicators in non-dev server remote projects.
12531 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12532 })
12533 .unwrap_or(true);
12534 if hide_runnables {
12535 return;
12536 }
12537 let new_rows =
12538 cx.background_spawn({
12539 let snapshot = display_snapshot.clone();
12540 async move {
12541 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12542 }
12543 })
12544 .await;
12545 let Ok(lsp_tasks) =
12546 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12547 else {
12548 return;
12549 };
12550 let lsp_tasks = lsp_tasks.await;
12551
12552 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12553 lsp_tasks
12554 .into_iter()
12555 .flat_map(|(kind, tasks)| {
12556 tasks.into_iter().filter_map(move |(location, task)| {
12557 Some((kind.clone(), location?, task))
12558 })
12559 })
12560 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12561 let buffer = location.target.buffer;
12562 let buffer_snapshot = buffer.read(cx).snapshot();
12563 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12564 |(excerpt_id, snapshot, _)| {
12565 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12566 display_snapshot
12567 .buffer_snapshot
12568 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12569 } else {
12570 None
12571 }
12572 },
12573 );
12574 if let Some(offset) = offset {
12575 let task_buffer_range =
12576 location.target.range.to_point(&buffer_snapshot);
12577 let context_buffer_range =
12578 task_buffer_range.to_offset(&buffer_snapshot);
12579 let context_range = BufferOffset(context_buffer_range.start)
12580 ..BufferOffset(context_buffer_range.end);
12581
12582 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12583 .or_insert_with(|| RunnableTasks {
12584 templates: Vec::new(),
12585 offset,
12586 column: task_buffer_range.start.column,
12587 extra_variables: HashMap::default(),
12588 context_range,
12589 })
12590 .templates
12591 .push((kind, task.original_task().clone()));
12592 }
12593
12594 acc
12595 })
12596 }) else {
12597 return;
12598 };
12599
12600 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12601 editor
12602 .update(cx, |editor, _| {
12603 editor.clear_tasks();
12604 for (key, mut value) in rows {
12605 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12606 value.templates.extend(lsp_tasks.templates);
12607 }
12608
12609 editor.insert_tasks(key, value);
12610 }
12611 for (key, value) in lsp_tasks_by_rows {
12612 editor.insert_tasks(key, value);
12613 }
12614 })
12615 .ok();
12616 })
12617 }
12618 fn fetch_runnable_ranges(
12619 snapshot: &DisplaySnapshot,
12620 range: Range<Anchor>,
12621 ) -> Vec<language::RunnableRange> {
12622 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12623 }
12624
12625 fn runnable_rows(
12626 project: Entity<Project>,
12627 snapshot: DisplaySnapshot,
12628 runnable_ranges: Vec<RunnableRange>,
12629 mut cx: AsyncWindowContext,
12630 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12631 runnable_ranges
12632 .into_iter()
12633 .filter_map(|mut runnable| {
12634 let tasks = cx
12635 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12636 .ok()?;
12637 if tasks.is_empty() {
12638 return None;
12639 }
12640
12641 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12642
12643 let row = snapshot
12644 .buffer_snapshot
12645 .buffer_line_for_row(MultiBufferRow(point.row))?
12646 .1
12647 .start
12648 .row;
12649
12650 let context_range =
12651 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12652 Some((
12653 (runnable.buffer_id, row),
12654 RunnableTasks {
12655 templates: tasks,
12656 offset: snapshot
12657 .buffer_snapshot
12658 .anchor_before(runnable.run_range.start),
12659 context_range,
12660 column: point.column,
12661 extra_variables: runnable.extra_captures,
12662 },
12663 ))
12664 })
12665 .collect()
12666 }
12667
12668 fn templates_with_tags(
12669 project: &Entity<Project>,
12670 runnable: &mut Runnable,
12671 cx: &mut App,
12672 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12673 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12674 let (worktree_id, file) = project
12675 .buffer_for_id(runnable.buffer, cx)
12676 .and_then(|buffer| buffer.read(cx).file())
12677 .map(|file| (file.worktree_id(cx), file.clone()))
12678 .unzip();
12679
12680 (
12681 project.task_store().read(cx).task_inventory().cloned(),
12682 worktree_id,
12683 file,
12684 )
12685 });
12686
12687 let mut templates_with_tags = mem::take(&mut runnable.tags)
12688 .into_iter()
12689 .flat_map(|RunnableTag(tag)| {
12690 inventory
12691 .as_ref()
12692 .into_iter()
12693 .flat_map(|inventory| {
12694 inventory.read(cx).list_tasks(
12695 file.clone(),
12696 Some(runnable.language.clone()),
12697 worktree_id,
12698 cx,
12699 )
12700 })
12701 .filter(move |(_, template)| {
12702 template.tags.iter().any(|source_tag| source_tag == &tag)
12703 })
12704 })
12705 .sorted_by_key(|(kind, _)| kind.to_owned())
12706 .collect::<Vec<_>>();
12707 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12708 // Strongest source wins; if we have worktree tag binding, prefer that to
12709 // global and language bindings;
12710 // if we have a global binding, prefer that to language binding.
12711 let first_mismatch = templates_with_tags
12712 .iter()
12713 .position(|(tag_source, _)| tag_source != leading_tag_source);
12714 if let Some(index) = first_mismatch {
12715 templates_with_tags.truncate(index);
12716 }
12717 }
12718
12719 templates_with_tags
12720 }
12721
12722 pub fn move_to_enclosing_bracket(
12723 &mut self,
12724 _: &MoveToEnclosingBracket,
12725 window: &mut Window,
12726 cx: &mut Context<Self>,
12727 ) {
12728 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12729 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12730 s.move_offsets_with(|snapshot, selection| {
12731 let Some(enclosing_bracket_ranges) =
12732 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12733 else {
12734 return;
12735 };
12736
12737 let mut best_length = usize::MAX;
12738 let mut best_inside = false;
12739 let mut best_in_bracket_range = false;
12740 let mut best_destination = None;
12741 for (open, close) in enclosing_bracket_ranges {
12742 let close = close.to_inclusive();
12743 let length = close.end() - open.start;
12744 let inside = selection.start >= open.end && selection.end <= *close.start();
12745 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12746 || close.contains(&selection.head());
12747
12748 // If best is next to a bracket and current isn't, skip
12749 if !in_bracket_range && best_in_bracket_range {
12750 continue;
12751 }
12752
12753 // Prefer smaller lengths unless best is inside and current isn't
12754 if length > best_length && (best_inside || !inside) {
12755 continue;
12756 }
12757
12758 best_length = length;
12759 best_inside = inside;
12760 best_in_bracket_range = in_bracket_range;
12761 best_destination = Some(
12762 if close.contains(&selection.start) && close.contains(&selection.end) {
12763 if inside { open.end } else { open.start }
12764 } else if inside {
12765 *close.start()
12766 } else {
12767 *close.end()
12768 },
12769 );
12770 }
12771
12772 if let Some(destination) = best_destination {
12773 selection.collapse_to(destination, SelectionGoal::None);
12774 }
12775 })
12776 });
12777 }
12778
12779 pub fn undo_selection(
12780 &mut self,
12781 _: &UndoSelection,
12782 window: &mut Window,
12783 cx: &mut Context<Self>,
12784 ) {
12785 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12786 self.end_selection(window, cx);
12787 self.selection_history.mode = SelectionHistoryMode::Undoing;
12788 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12789 self.change_selections(None, window, cx, |s| {
12790 s.select_anchors(entry.selections.to_vec())
12791 });
12792 self.select_next_state = entry.select_next_state;
12793 self.select_prev_state = entry.select_prev_state;
12794 self.add_selections_state = entry.add_selections_state;
12795 self.request_autoscroll(Autoscroll::newest(), cx);
12796 }
12797 self.selection_history.mode = SelectionHistoryMode::Normal;
12798 }
12799
12800 pub fn redo_selection(
12801 &mut self,
12802 _: &RedoSelection,
12803 window: &mut Window,
12804 cx: &mut Context<Self>,
12805 ) {
12806 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12807 self.end_selection(window, cx);
12808 self.selection_history.mode = SelectionHistoryMode::Redoing;
12809 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12810 self.change_selections(None, window, cx, |s| {
12811 s.select_anchors(entry.selections.to_vec())
12812 });
12813 self.select_next_state = entry.select_next_state;
12814 self.select_prev_state = entry.select_prev_state;
12815 self.add_selections_state = entry.add_selections_state;
12816 self.request_autoscroll(Autoscroll::newest(), cx);
12817 }
12818 self.selection_history.mode = SelectionHistoryMode::Normal;
12819 }
12820
12821 pub fn expand_excerpts(
12822 &mut self,
12823 action: &ExpandExcerpts,
12824 _: &mut Window,
12825 cx: &mut Context<Self>,
12826 ) {
12827 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12828 }
12829
12830 pub fn expand_excerpts_down(
12831 &mut self,
12832 action: &ExpandExcerptsDown,
12833 _: &mut Window,
12834 cx: &mut Context<Self>,
12835 ) {
12836 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12837 }
12838
12839 pub fn expand_excerpts_up(
12840 &mut self,
12841 action: &ExpandExcerptsUp,
12842 _: &mut Window,
12843 cx: &mut Context<Self>,
12844 ) {
12845 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12846 }
12847
12848 pub fn expand_excerpts_for_direction(
12849 &mut self,
12850 lines: u32,
12851 direction: ExpandExcerptDirection,
12852
12853 cx: &mut Context<Self>,
12854 ) {
12855 let selections = self.selections.disjoint_anchors();
12856
12857 let lines = if lines == 0 {
12858 EditorSettings::get_global(cx).expand_excerpt_lines
12859 } else {
12860 lines
12861 };
12862
12863 self.buffer.update(cx, |buffer, cx| {
12864 let snapshot = buffer.snapshot(cx);
12865 let mut excerpt_ids = selections
12866 .iter()
12867 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12868 .collect::<Vec<_>>();
12869 excerpt_ids.sort();
12870 excerpt_ids.dedup();
12871 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12872 })
12873 }
12874
12875 pub fn expand_excerpt(
12876 &mut self,
12877 excerpt: ExcerptId,
12878 direction: ExpandExcerptDirection,
12879 window: &mut Window,
12880 cx: &mut Context<Self>,
12881 ) {
12882 let current_scroll_position = self.scroll_position(cx);
12883 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12884 let mut should_scroll_up = false;
12885
12886 if direction == ExpandExcerptDirection::Down {
12887 let multi_buffer = self.buffer.read(cx);
12888 let snapshot = multi_buffer.snapshot(cx);
12889 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12890 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12891 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12892 let buffer_snapshot = buffer.read(cx).snapshot();
12893 let excerpt_end_row =
12894 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12895 let last_row = buffer_snapshot.max_point().row;
12896 let lines_below = last_row.saturating_sub(excerpt_end_row);
12897 should_scroll_up = lines_below >= lines_to_expand;
12898 }
12899 }
12900 }
12901 }
12902
12903 self.buffer.update(cx, |buffer, cx| {
12904 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12905 });
12906
12907 if should_scroll_up {
12908 let new_scroll_position =
12909 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12910 self.set_scroll_position(new_scroll_position, window, cx);
12911 }
12912 }
12913
12914 pub fn go_to_singleton_buffer_point(
12915 &mut self,
12916 point: Point,
12917 window: &mut Window,
12918 cx: &mut Context<Self>,
12919 ) {
12920 self.go_to_singleton_buffer_range(point..point, window, cx);
12921 }
12922
12923 pub fn go_to_singleton_buffer_range(
12924 &mut self,
12925 range: Range<Point>,
12926 window: &mut Window,
12927 cx: &mut Context<Self>,
12928 ) {
12929 let multibuffer = self.buffer().read(cx);
12930 let Some(buffer) = multibuffer.as_singleton() else {
12931 return;
12932 };
12933 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12934 return;
12935 };
12936 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12937 return;
12938 };
12939 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12940 s.select_anchor_ranges([start..end])
12941 });
12942 }
12943
12944 fn go_to_diagnostic(
12945 &mut self,
12946 _: &GoToDiagnostic,
12947 window: &mut Window,
12948 cx: &mut Context<Self>,
12949 ) {
12950 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12951 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12952 }
12953
12954 fn go_to_prev_diagnostic(
12955 &mut self,
12956 _: &GoToPreviousDiagnostic,
12957 window: &mut Window,
12958 cx: &mut Context<Self>,
12959 ) {
12960 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12961 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12962 }
12963
12964 pub fn go_to_diagnostic_impl(
12965 &mut self,
12966 direction: Direction,
12967 window: &mut Window,
12968 cx: &mut Context<Self>,
12969 ) {
12970 let buffer = self.buffer.read(cx).snapshot(cx);
12971 let selection = self.selections.newest::<usize>(cx);
12972 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12973 if direction == Direction::Next {
12974 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12975 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12976 return;
12977 };
12978 self.activate_diagnostics(
12979 buffer_id,
12980 popover.local_diagnostic.diagnostic.group_id,
12981 window,
12982 cx,
12983 );
12984 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12985 let primary_range_start = active_diagnostics.primary_range.start;
12986 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12987 let mut new_selection = s.newest_anchor().clone();
12988 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12989 s.select_anchors(vec![new_selection.clone()]);
12990 });
12991 self.refresh_inline_completion(false, true, window, cx);
12992 }
12993 return;
12994 }
12995 }
12996
12997 let active_group_id = self
12998 .active_diagnostics
12999 .as_ref()
13000 .map(|active_group| active_group.group_id);
13001 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
13002 active_diagnostics
13003 .primary_range
13004 .to_offset(&buffer)
13005 .to_inclusive()
13006 });
13007 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
13008 if active_primary_range.contains(&selection.head()) {
13009 *active_primary_range.start()
13010 } else {
13011 selection.head()
13012 }
13013 } else {
13014 selection.head()
13015 };
13016
13017 let snapshot = self.snapshot(window, cx);
13018 let primary_diagnostics_before = buffer
13019 .diagnostics_in_range::<usize>(0..search_start)
13020 .filter(|entry| entry.diagnostic.is_primary)
13021 .filter(|entry| entry.range.start != entry.range.end)
13022 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13023 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
13024 .collect::<Vec<_>>();
13025 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
13026 primary_diagnostics_before
13027 .iter()
13028 .position(|entry| entry.diagnostic.group_id == active_group_id)
13029 });
13030
13031 let primary_diagnostics_after = buffer
13032 .diagnostics_in_range::<usize>(search_start..buffer.len())
13033 .filter(|entry| entry.diagnostic.is_primary)
13034 .filter(|entry| entry.range.start != entry.range.end)
13035 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13036 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
13037 .collect::<Vec<_>>();
13038 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
13039 primary_diagnostics_after
13040 .iter()
13041 .enumerate()
13042 .rev()
13043 .find_map(|(i, entry)| {
13044 if entry.diagnostic.group_id == active_group_id {
13045 Some(i)
13046 } else {
13047 None
13048 }
13049 })
13050 });
13051
13052 let next_primary_diagnostic = match direction {
13053 Direction::Prev => primary_diagnostics_before
13054 .iter()
13055 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
13056 .rev()
13057 .next(),
13058 Direction::Next => primary_diagnostics_after
13059 .iter()
13060 .skip(
13061 last_same_group_diagnostic_after
13062 .map(|index| index + 1)
13063 .unwrap_or(0),
13064 )
13065 .next(),
13066 };
13067
13068 // Cycle around to the start of the buffer, potentially moving back to the start of
13069 // the currently active diagnostic.
13070 let cycle_around = || match direction {
13071 Direction::Prev => primary_diagnostics_after
13072 .iter()
13073 .rev()
13074 .chain(primary_diagnostics_before.iter().rev())
13075 .next(),
13076 Direction::Next => primary_diagnostics_before
13077 .iter()
13078 .chain(primary_diagnostics_after.iter())
13079 .next(),
13080 };
13081
13082 if let Some((primary_range, group_id)) = next_primary_diagnostic
13083 .or_else(cycle_around)
13084 .map(|entry| (&entry.range, entry.diagnostic.group_id))
13085 {
13086 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
13087 return;
13088 };
13089 self.activate_diagnostics(buffer_id, group_id, window, cx);
13090 if self.active_diagnostics.is_some() {
13091 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13092 s.select(vec![Selection {
13093 id: selection.id,
13094 start: primary_range.start,
13095 end: primary_range.start,
13096 reversed: false,
13097 goal: SelectionGoal::None,
13098 }]);
13099 });
13100 self.refresh_inline_completion(false, true, window, cx);
13101 }
13102 }
13103 }
13104
13105 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13106 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13107 let snapshot = self.snapshot(window, cx);
13108 let selection = self.selections.newest::<Point>(cx);
13109 self.go_to_hunk_before_or_after_position(
13110 &snapshot,
13111 selection.head(),
13112 Direction::Next,
13113 window,
13114 cx,
13115 );
13116 }
13117
13118 pub fn go_to_hunk_before_or_after_position(
13119 &mut self,
13120 snapshot: &EditorSnapshot,
13121 position: Point,
13122 direction: Direction,
13123 window: &mut Window,
13124 cx: &mut Context<Editor>,
13125 ) {
13126 let row = if direction == Direction::Next {
13127 self.hunk_after_position(snapshot, position)
13128 .map(|hunk| hunk.row_range.start)
13129 } else {
13130 self.hunk_before_position(snapshot, position)
13131 };
13132
13133 if let Some(row) = row {
13134 let destination = Point::new(row.0, 0);
13135 let autoscroll = Autoscroll::center();
13136
13137 self.unfold_ranges(&[destination..destination], false, false, cx);
13138 self.change_selections(Some(autoscroll), window, cx, |s| {
13139 s.select_ranges([destination..destination]);
13140 });
13141 }
13142 }
13143
13144 fn hunk_after_position(
13145 &mut self,
13146 snapshot: &EditorSnapshot,
13147 position: Point,
13148 ) -> Option<MultiBufferDiffHunk> {
13149 snapshot
13150 .buffer_snapshot
13151 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13152 .find(|hunk| hunk.row_range.start.0 > position.row)
13153 .or_else(|| {
13154 snapshot
13155 .buffer_snapshot
13156 .diff_hunks_in_range(Point::zero()..position)
13157 .find(|hunk| hunk.row_range.end.0 < position.row)
13158 })
13159 }
13160
13161 fn go_to_prev_hunk(
13162 &mut self,
13163 _: &GoToPreviousHunk,
13164 window: &mut Window,
13165 cx: &mut Context<Self>,
13166 ) {
13167 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13168 let snapshot = self.snapshot(window, cx);
13169 let selection = self.selections.newest::<Point>(cx);
13170 self.go_to_hunk_before_or_after_position(
13171 &snapshot,
13172 selection.head(),
13173 Direction::Prev,
13174 window,
13175 cx,
13176 );
13177 }
13178
13179 fn hunk_before_position(
13180 &mut self,
13181 snapshot: &EditorSnapshot,
13182 position: Point,
13183 ) -> Option<MultiBufferRow> {
13184 snapshot
13185 .buffer_snapshot
13186 .diff_hunk_before(position)
13187 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13188 }
13189
13190 fn go_to_line<T: 'static>(
13191 &mut self,
13192 position: Anchor,
13193 highlight_color: Option<Hsla>,
13194 window: &mut Window,
13195 cx: &mut Context<Self>,
13196 ) {
13197 let snapshot = self.snapshot(window, cx).display_snapshot;
13198 let position = position.to_point(&snapshot.buffer_snapshot);
13199 let start = snapshot
13200 .buffer_snapshot
13201 .clip_point(Point::new(position.row, 0), Bias::Left);
13202 let end = start + Point::new(1, 0);
13203 let start = snapshot.buffer_snapshot.anchor_before(start);
13204 let end = snapshot.buffer_snapshot.anchor_before(end);
13205
13206 self.highlight_rows::<T>(
13207 start..end,
13208 highlight_color
13209 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13210 false,
13211 cx,
13212 );
13213 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13214 }
13215
13216 pub fn go_to_definition(
13217 &mut self,
13218 _: &GoToDefinition,
13219 window: &mut Window,
13220 cx: &mut Context<Self>,
13221 ) -> Task<Result<Navigated>> {
13222 let definition =
13223 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13224 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13225 cx.spawn_in(window, async move |editor, cx| {
13226 if definition.await? == Navigated::Yes {
13227 return Ok(Navigated::Yes);
13228 }
13229 match fallback_strategy {
13230 GoToDefinitionFallback::None => Ok(Navigated::No),
13231 GoToDefinitionFallback::FindAllReferences => {
13232 match editor.update_in(cx, |editor, window, cx| {
13233 editor.find_all_references(&FindAllReferences, window, cx)
13234 })? {
13235 Some(references) => references.await,
13236 None => Ok(Navigated::No),
13237 }
13238 }
13239 }
13240 })
13241 }
13242
13243 pub fn go_to_declaration(
13244 &mut self,
13245 _: &GoToDeclaration,
13246 window: &mut Window,
13247 cx: &mut Context<Self>,
13248 ) -> Task<Result<Navigated>> {
13249 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13250 }
13251
13252 pub fn go_to_declaration_split(
13253 &mut self,
13254 _: &GoToDeclaration,
13255 window: &mut Window,
13256 cx: &mut Context<Self>,
13257 ) -> Task<Result<Navigated>> {
13258 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13259 }
13260
13261 pub fn go_to_implementation(
13262 &mut self,
13263 _: &GoToImplementation,
13264 window: &mut Window,
13265 cx: &mut Context<Self>,
13266 ) -> Task<Result<Navigated>> {
13267 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13268 }
13269
13270 pub fn go_to_implementation_split(
13271 &mut self,
13272 _: &GoToImplementationSplit,
13273 window: &mut Window,
13274 cx: &mut Context<Self>,
13275 ) -> Task<Result<Navigated>> {
13276 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13277 }
13278
13279 pub fn go_to_type_definition(
13280 &mut self,
13281 _: &GoToTypeDefinition,
13282 window: &mut Window,
13283 cx: &mut Context<Self>,
13284 ) -> Task<Result<Navigated>> {
13285 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13286 }
13287
13288 pub fn go_to_definition_split(
13289 &mut self,
13290 _: &GoToDefinitionSplit,
13291 window: &mut Window,
13292 cx: &mut Context<Self>,
13293 ) -> Task<Result<Navigated>> {
13294 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13295 }
13296
13297 pub fn go_to_type_definition_split(
13298 &mut self,
13299 _: &GoToTypeDefinitionSplit,
13300 window: &mut Window,
13301 cx: &mut Context<Self>,
13302 ) -> Task<Result<Navigated>> {
13303 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13304 }
13305
13306 fn go_to_definition_of_kind(
13307 &mut self,
13308 kind: GotoDefinitionKind,
13309 split: bool,
13310 window: &mut Window,
13311 cx: &mut Context<Self>,
13312 ) -> Task<Result<Navigated>> {
13313 let Some(provider) = self.semantics_provider.clone() else {
13314 return Task::ready(Ok(Navigated::No));
13315 };
13316 let head = self.selections.newest::<usize>(cx).head();
13317 let buffer = self.buffer.read(cx);
13318 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13319 text_anchor
13320 } else {
13321 return Task::ready(Ok(Navigated::No));
13322 };
13323
13324 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13325 return Task::ready(Ok(Navigated::No));
13326 };
13327
13328 cx.spawn_in(window, async move |editor, cx| {
13329 let definitions = definitions.await?;
13330 let navigated = editor
13331 .update_in(cx, |editor, window, cx| {
13332 editor.navigate_to_hover_links(
13333 Some(kind),
13334 definitions
13335 .into_iter()
13336 .filter(|location| {
13337 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13338 })
13339 .map(HoverLink::Text)
13340 .collect::<Vec<_>>(),
13341 split,
13342 window,
13343 cx,
13344 )
13345 })?
13346 .await?;
13347 anyhow::Ok(navigated)
13348 })
13349 }
13350
13351 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13352 let selection = self.selections.newest_anchor();
13353 let head = selection.head();
13354 let tail = selection.tail();
13355
13356 let Some((buffer, start_position)) =
13357 self.buffer.read(cx).text_anchor_for_position(head, cx)
13358 else {
13359 return;
13360 };
13361
13362 let end_position = if head != tail {
13363 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13364 return;
13365 };
13366 Some(pos)
13367 } else {
13368 None
13369 };
13370
13371 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13372 let url = if let Some(end_pos) = end_position {
13373 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13374 } else {
13375 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13376 };
13377
13378 if let Some(url) = url {
13379 editor.update(cx, |_, cx| {
13380 cx.open_url(&url);
13381 })
13382 } else {
13383 Ok(())
13384 }
13385 });
13386
13387 url_finder.detach();
13388 }
13389
13390 pub fn open_selected_filename(
13391 &mut self,
13392 _: &OpenSelectedFilename,
13393 window: &mut Window,
13394 cx: &mut Context<Self>,
13395 ) {
13396 let Some(workspace) = self.workspace() else {
13397 return;
13398 };
13399
13400 let position = self.selections.newest_anchor().head();
13401
13402 let Some((buffer, buffer_position)) =
13403 self.buffer.read(cx).text_anchor_for_position(position, cx)
13404 else {
13405 return;
13406 };
13407
13408 let project = self.project.clone();
13409
13410 cx.spawn_in(window, async move |_, cx| {
13411 let result = find_file(&buffer, project, buffer_position, cx).await;
13412
13413 if let Some((_, path)) = result {
13414 workspace
13415 .update_in(cx, |workspace, window, cx| {
13416 workspace.open_resolved_path(path, window, cx)
13417 })?
13418 .await?;
13419 }
13420 anyhow::Ok(())
13421 })
13422 .detach();
13423 }
13424
13425 pub(crate) fn navigate_to_hover_links(
13426 &mut self,
13427 kind: Option<GotoDefinitionKind>,
13428 mut definitions: Vec<HoverLink>,
13429 split: bool,
13430 window: &mut Window,
13431 cx: &mut Context<Editor>,
13432 ) -> Task<Result<Navigated>> {
13433 // If there is one definition, just open it directly
13434 if definitions.len() == 1 {
13435 let definition = definitions.pop().unwrap();
13436
13437 enum TargetTaskResult {
13438 Location(Option<Location>),
13439 AlreadyNavigated,
13440 }
13441
13442 let target_task = match definition {
13443 HoverLink::Text(link) => {
13444 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13445 }
13446 HoverLink::InlayHint(lsp_location, server_id) => {
13447 let computation =
13448 self.compute_target_location(lsp_location, server_id, window, cx);
13449 cx.background_spawn(async move {
13450 let location = computation.await?;
13451 Ok(TargetTaskResult::Location(location))
13452 })
13453 }
13454 HoverLink::Url(url) => {
13455 cx.open_url(&url);
13456 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13457 }
13458 HoverLink::File(path) => {
13459 if let Some(workspace) = self.workspace() {
13460 cx.spawn_in(window, async move |_, cx| {
13461 workspace
13462 .update_in(cx, |workspace, window, cx| {
13463 workspace.open_resolved_path(path, window, cx)
13464 })?
13465 .await
13466 .map(|_| TargetTaskResult::AlreadyNavigated)
13467 })
13468 } else {
13469 Task::ready(Ok(TargetTaskResult::Location(None)))
13470 }
13471 }
13472 };
13473 cx.spawn_in(window, async move |editor, cx| {
13474 let target = match target_task.await.context("target resolution task")? {
13475 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13476 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13477 TargetTaskResult::Location(Some(target)) => target,
13478 };
13479
13480 editor.update_in(cx, |editor, window, cx| {
13481 let Some(workspace) = editor.workspace() else {
13482 return Navigated::No;
13483 };
13484 let pane = workspace.read(cx).active_pane().clone();
13485
13486 let range = target.range.to_point(target.buffer.read(cx));
13487 let range = editor.range_for_match(&range);
13488 let range = collapse_multiline_range(range);
13489
13490 if !split
13491 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13492 {
13493 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13494 } else {
13495 window.defer(cx, move |window, cx| {
13496 let target_editor: Entity<Self> =
13497 workspace.update(cx, |workspace, cx| {
13498 let pane = if split {
13499 workspace.adjacent_pane(window, cx)
13500 } else {
13501 workspace.active_pane().clone()
13502 };
13503
13504 workspace.open_project_item(
13505 pane,
13506 target.buffer.clone(),
13507 true,
13508 true,
13509 window,
13510 cx,
13511 )
13512 });
13513 target_editor.update(cx, |target_editor, cx| {
13514 // When selecting a definition in a different buffer, disable the nav history
13515 // to avoid creating a history entry at the previous cursor location.
13516 pane.update(cx, |pane, _| pane.disable_history());
13517 target_editor.go_to_singleton_buffer_range(range, window, cx);
13518 pane.update(cx, |pane, _| pane.enable_history());
13519 });
13520 });
13521 }
13522 Navigated::Yes
13523 })
13524 })
13525 } else if !definitions.is_empty() {
13526 cx.spawn_in(window, async move |editor, cx| {
13527 let (title, location_tasks, workspace) = editor
13528 .update_in(cx, |editor, window, cx| {
13529 let tab_kind = match kind {
13530 Some(GotoDefinitionKind::Implementation) => "Implementations",
13531 _ => "Definitions",
13532 };
13533 let title = definitions
13534 .iter()
13535 .find_map(|definition| match definition {
13536 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13537 let buffer = origin.buffer.read(cx);
13538 format!(
13539 "{} for {}",
13540 tab_kind,
13541 buffer
13542 .text_for_range(origin.range.clone())
13543 .collect::<String>()
13544 )
13545 }),
13546 HoverLink::InlayHint(_, _) => None,
13547 HoverLink::Url(_) => None,
13548 HoverLink::File(_) => None,
13549 })
13550 .unwrap_or(tab_kind.to_string());
13551 let location_tasks = definitions
13552 .into_iter()
13553 .map(|definition| match definition {
13554 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13555 HoverLink::InlayHint(lsp_location, server_id) => editor
13556 .compute_target_location(lsp_location, server_id, window, cx),
13557 HoverLink::Url(_) => Task::ready(Ok(None)),
13558 HoverLink::File(_) => Task::ready(Ok(None)),
13559 })
13560 .collect::<Vec<_>>();
13561 (title, location_tasks, editor.workspace().clone())
13562 })
13563 .context("location tasks preparation")?;
13564
13565 let locations = future::join_all(location_tasks)
13566 .await
13567 .into_iter()
13568 .filter_map(|location| location.transpose())
13569 .collect::<Result<_>>()
13570 .context("location tasks")?;
13571
13572 let Some(workspace) = workspace else {
13573 return Ok(Navigated::No);
13574 };
13575 let opened = workspace
13576 .update_in(cx, |workspace, window, cx| {
13577 Self::open_locations_in_multibuffer(
13578 workspace,
13579 locations,
13580 title,
13581 split,
13582 MultibufferSelectionMode::First,
13583 window,
13584 cx,
13585 )
13586 })
13587 .ok();
13588
13589 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13590 })
13591 } else {
13592 Task::ready(Ok(Navigated::No))
13593 }
13594 }
13595
13596 fn compute_target_location(
13597 &self,
13598 lsp_location: lsp::Location,
13599 server_id: LanguageServerId,
13600 window: &mut Window,
13601 cx: &mut Context<Self>,
13602 ) -> Task<anyhow::Result<Option<Location>>> {
13603 let Some(project) = self.project.clone() else {
13604 return Task::ready(Ok(None));
13605 };
13606
13607 cx.spawn_in(window, async move |editor, cx| {
13608 let location_task = editor.update(cx, |_, cx| {
13609 project.update(cx, |project, cx| {
13610 let language_server_name = project
13611 .language_server_statuses(cx)
13612 .find(|(id, _)| server_id == *id)
13613 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13614 language_server_name.map(|language_server_name| {
13615 project.open_local_buffer_via_lsp(
13616 lsp_location.uri.clone(),
13617 server_id,
13618 language_server_name,
13619 cx,
13620 )
13621 })
13622 })
13623 })?;
13624 let location = match location_task {
13625 Some(task) => Some({
13626 let target_buffer_handle = task.await.context("open local buffer")?;
13627 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13628 let target_start = target_buffer
13629 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13630 let target_end = target_buffer
13631 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13632 target_buffer.anchor_after(target_start)
13633 ..target_buffer.anchor_before(target_end)
13634 })?;
13635 Location {
13636 buffer: target_buffer_handle,
13637 range,
13638 }
13639 }),
13640 None => None,
13641 };
13642 Ok(location)
13643 })
13644 }
13645
13646 pub fn find_all_references(
13647 &mut self,
13648 _: &FindAllReferences,
13649 window: &mut Window,
13650 cx: &mut Context<Self>,
13651 ) -> Option<Task<Result<Navigated>>> {
13652 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13653
13654 let selection = self.selections.newest::<usize>(cx);
13655 let multi_buffer = self.buffer.read(cx);
13656 let head = selection.head();
13657
13658 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13659 let head_anchor = multi_buffer_snapshot.anchor_at(
13660 head,
13661 if head < selection.tail() {
13662 Bias::Right
13663 } else {
13664 Bias::Left
13665 },
13666 );
13667
13668 match self
13669 .find_all_references_task_sources
13670 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13671 {
13672 Ok(_) => {
13673 log::info!(
13674 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13675 );
13676 return None;
13677 }
13678 Err(i) => {
13679 self.find_all_references_task_sources.insert(i, head_anchor);
13680 }
13681 }
13682
13683 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13684 let workspace = self.workspace()?;
13685 let project = workspace.read(cx).project().clone();
13686 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13687 Some(cx.spawn_in(window, async move |editor, cx| {
13688 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13689 if let Ok(i) = editor
13690 .find_all_references_task_sources
13691 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13692 {
13693 editor.find_all_references_task_sources.remove(i);
13694 }
13695 });
13696
13697 let locations = references.await?;
13698 if locations.is_empty() {
13699 return anyhow::Ok(Navigated::No);
13700 }
13701
13702 workspace.update_in(cx, |workspace, window, cx| {
13703 let title = locations
13704 .first()
13705 .as_ref()
13706 .map(|location| {
13707 let buffer = location.buffer.read(cx);
13708 format!(
13709 "References to `{}`",
13710 buffer
13711 .text_for_range(location.range.clone())
13712 .collect::<String>()
13713 )
13714 })
13715 .unwrap();
13716 Self::open_locations_in_multibuffer(
13717 workspace,
13718 locations,
13719 title,
13720 false,
13721 MultibufferSelectionMode::First,
13722 window,
13723 cx,
13724 );
13725 Navigated::Yes
13726 })
13727 }))
13728 }
13729
13730 /// Opens a multibuffer with the given project locations in it
13731 pub fn open_locations_in_multibuffer(
13732 workspace: &mut Workspace,
13733 mut locations: Vec<Location>,
13734 title: String,
13735 split: bool,
13736 multibuffer_selection_mode: MultibufferSelectionMode,
13737 window: &mut Window,
13738 cx: &mut Context<Workspace>,
13739 ) {
13740 // If there are multiple definitions, open them in a multibuffer
13741 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13742 let mut locations = locations.into_iter().peekable();
13743 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13744 let capability = workspace.project().read(cx).capability();
13745
13746 let excerpt_buffer = cx.new(|cx| {
13747 let mut multibuffer = MultiBuffer::new(capability);
13748 while let Some(location) = locations.next() {
13749 let buffer = location.buffer.read(cx);
13750 let mut ranges_for_buffer = Vec::new();
13751 let range = location.range.to_point(buffer);
13752 ranges_for_buffer.push(range.clone());
13753
13754 while let Some(next_location) = locations.peek() {
13755 if next_location.buffer == location.buffer {
13756 ranges_for_buffer.push(next_location.range.to_point(buffer));
13757 locations.next();
13758 } else {
13759 break;
13760 }
13761 }
13762
13763 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13764 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13765 PathKey::for_buffer(&location.buffer, cx),
13766 location.buffer.clone(),
13767 ranges_for_buffer,
13768 DEFAULT_MULTIBUFFER_CONTEXT,
13769 cx,
13770 );
13771 ranges.extend(new_ranges)
13772 }
13773
13774 multibuffer.with_title(title)
13775 });
13776
13777 let editor = cx.new(|cx| {
13778 Editor::for_multibuffer(
13779 excerpt_buffer,
13780 Some(workspace.project().clone()),
13781 window,
13782 cx,
13783 )
13784 });
13785 editor.update(cx, |editor, cx| {
13786 match multibuffer_selection_mode {
13787 MultibufferSelectionMode::First => {
13788 if let Some(first_range) = ranges.first() {
13789 editor.change_selections(None, window, cx, |selections| {
13790 selections.clear_disjoint();
13791 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13792 });
13793 }
13794 editor.highlight_background::<Self>(
13795 &ranges,
13796 |theme| theme.editor_highlighted_line_background,
13797 cx,
13798 );
13799 }
13800 MultibufferSelectionMode::All => {
13801 editor.change_selections(None, window, cx, |selections| {
13802 selections.clear_disjoint();
13803 selections.select_anchor_ranges(ranges);
13804 });
13805 }
13806 }
13807 editor.register_buffers_with_language_servers(cx);
13808 });
13809
13810 let item = Box::new(editor);
13811 let item_id = item.item_id();
13812
13813 if split {
13814 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13815 } else {
13816 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13817 let (preview_item_id, preview_item_idx) =
13818 workspace.active_pane().update(cx, |pane, _| {
13819 (pane.preview_item_id(), pane.preview_item_idx())
13820 });
13821
13822 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13823
13824 if let Some(preview_item_id) = preview_item_id {
13825 workspace.active_pane().update(cx, |pane, cx| {
13826 pane.remove_item(preview_item_id, false, false, window, cx);
13827 });
13828 }
13829 } else {
13830 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13831 }
13832 }
13833 workspace.active_pane().update(cx, |pane, cx| {
13834 pane.set_preview_item_id(Some(item_id), cx);
13835 });
13836 }
13837
13838 pub fn rename(
13839 &mut self,
13840 _: &Rename,
13841 window: &mut Window,
13842 cx: &mut Context<Self>,
13843 ) -> Option<Task<Result<()>>> {
13844 use language::ToOffset as _;
13845
13846 let provider = self.semantics_provider.clone()?;
13847 let selection = self.selections.newest_anchor().clone();
13848 let (cursor_buffer, cursor_buffer_position) = self
13849 .buffer
13850 .read(cx)
13851 .text_anchor_for_position(selection.head(), cx)?;
13852 let (tail_buffer, cursor_buffer_position_end) = self
13853 .buffer
13854 .read(cx)
13855 .text_anchor_for_position(selection.tail(), cx)?;
13856 if tail_buffer != cursor_buffer {
13857 return None;
13858 }
13859
13860 let snapshot = cursor_buffer.read(cx).snapshot();
13861 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13862 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13863 let prepare_rename = provider
13864 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13865 .unwrap_or_else(|| Task::ready(Ok(None)));
13866 drop(snapshot);
13867
13868 Some(cx.spawn_in(window, async move |this, cx| {
13869 let rename_range = if let Some(range) = prepare_rename.await? {
13870 Some(range)
13871 } else {
13872 this.update(cx, |this, cx| {
13873 let buffer = this.buffer.read(cx).snapshot(cx);
13874 let mut buffer_highlights = this
13875 .document_highlights_for_position(selection.head(), &buffer)
13876 .filter(|highlight| {
13877 highlight.start.excerpt_id == selection.head().excerpt_id
13878 && highlight.end.excerpt_id == selection.head().excerpt_id
13879 });
13880 buffer_highlights
13881 .next()
13882 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13883 })?
13884 };
13885 if let Some(rename_range) = rename_range {
13886 this.update_in(cx, |this, window, cx| {
13887 let snapshot = cursor_buffer.read(cx).snapshot();
13888 let rename_buffer_range = rename_range.to_offset(&snapshot);
13889 let cursor_offset_in_rename_range =
13890 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13891 let cursor_offset_in_rename_range_end =
13892 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13893
13894 this.take_rename(false, window, cx);
13895 let buffer = this.buffer.read(cx).read(cx);
13896 let cursor_offset = selection.head().to_offset(&buffer);
13897 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13898 let rename_end = rename_start + rename_buffer_range.len();
13899 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13900 let mut old_highlight_id = None;
13901 let old_name: Arc<str> = buffer
13902 .chunks(rename_start..rename_end, true)
13903 .map(|chunk| {
13904 if old_highlight_id.is_none() {
13905 old_highlight_id = chunk.syntax_highlight_id;
13906 }
13907 chunk.text
13908 })
13909 .collect::<String>()
13910 .into();
13911
13912 drop(buffer);
13913
13914 // Position the selection in the rename editor so that it matches the current selection.
13915 this.show_local_selections = false;
13916 let rename_editor = cx.new(|cx| {
13917 let mut editor = Editor::single_line(window, cx);
13918 editor.buffer.update(cx, |buffer, cx| {
13919 buffer.edit([(0..0, old_name.clone())], None, cx)
13920 });
13921 let rename_selection_range = match cursor_offset_in_rename_range
13922 .cmp(&cursor_offset_in_rename_range_end)
13923 {
13924 Ordering::Equal => {
13925 editor.select_all(&SelectAll, window, cx);
13926 return editor;
13927 }
13928 Ordering::Less => {
13929 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13930 }
13931 Ordering::Greater => {
13932 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13933 }
13934 };
13935 if rename_selection_range.end > old_name.len() {
13936 editor.select_all(&SelectAll, window, cx);
13937 } else {
13938 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13939 s.select_ranges([rename_selection_range]);
13940 });
13941 }
13942 editor
13943 });
13944 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13945 if e == &EditorEvent::Focused {
13946 cx.emit(EditorEvent::FocusedIn)
13947 }
13948 })
13949 .detach();
13950
13951 let write_highlights =
13952 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13953 let read_highlights =
13954 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13955 let ranges = write_highlights
13956 .iter()
13957 .flat_map(|(_, ranges)| ranges.iter())
13958 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13959 .cloned()
13960 .collect();
13961
13962 this.highlight_text::<Rename>(
13963 ranges,
13964 HighlightStyle {
13965 fade_out: Some(0.6),
13966 ..Default::default()
13967 },
13968 cx,
13969 );
13970 let rename_focus_handle = rename_editor.focus_handle(cx);
13971 window.focus(&rename_focus_handle);
13972 let block_id = this.insert_blocks(
13973 [BlockProperties {
13974 style: BlockStyle::Flex,
13975 placement: BlockPlacement::Below(range.start),
13976 height: Some(1),
13977 render: Arc::new({
13978 let rename_editor = rename_editor.clone();
13979 move |cx: &mut BlockContext| {
13980 let mut text_style = cx.editor_style.text.clone();
13981 if let Some(highlight_style) = old_highlight_id
13982 .and_then(|h| h.style(&cx.editor_style.syntax))
13983 {
13984 text_style = text_style.highlight(highlight_style);
13985 }
13986 div()
13987 .block_mouse_down()
13988 .pl(cx.anchor_x)
13989 .child(EditorElement::new(
13990 &rename_editor,
13991 EditorStyle {
13992 background: cx.theme().system().transparent,
13993 local_player: cx.editor_style.local_player,
13994 text: text_style,
13995 scrollbar_width: cx.editor_style.scrollbar_width,
13996 syntax: cx.editor_style.syntax.clone(),
13997 status: cx.editor_style.status.clone(),
13998 inlay_hints_style: HighlightStyle {
13999 font_weight: Some(FontWeight::BOLD),
14000 ..make_inlay_hints_style(cx.app)
14001 },
14002 inline_completion_styles: make_suggestion_styles(
14003 cx.app,
14004 ),
14005 ..EditorStyle::default()
14006 },
14007 ))
14008 .into_any_element()
14009 }
14010 }),
14011 priority: 0,
14012 }],
14013 Some(Autoscroll::fit()),
14014 cx,
14015 )[0];
14016 this.pending_rename = Some(RenameState {
14017 range,
14018 old_name,
14019 editor: rename_editor,
14020 block_id,
14021 });
14022 })?;
14023 }
14024
14025 Ok(())
14026 }))
14027 }
14028
14029 pub fn confirm_rename(
14030 &mut self,
14031 _: &ConfirmRename,
14032 window: &mut Window,
14033 cx: &mut Context<Self>,
14034 ) -> Option<Task<Result<()>>> {
14035 let rename = self.take_rename(false, window, cx)?;
14036 let workspace = self.workspace()?.downgrade();
14037 let (buffer, start) = self
14038 .buffer
14039 .read(cx)
14040 .text_anchor_for_position(rename.range.start, cx)?;
14041 let (end_buffer, _) = self
14042 .buffer
14043 .read(cx)
14044 .text_anchor_for_position(rename.range.end, cx)?;
14045 if buffer != end_buffer {
14046 return None;
14047 }
14048
14049 let old_name = rename.old_name;
14050 let new_name = rename.editor.read(cx).text(cx);
14051
14052 let rename = self.semantics_provider.as_ref()?.perform_rename(
14053 &buffer,
14054 start,
14055 new_name.clone(),
14056 cx,
14057 )?;
14058
14059 Some(cx.spawn_in(window, async move |editor, cx| {
14060 let project_transaction = rename.await?;
14061 Self::open_project_transaction(
14062 &editor,
14063 workspace,
14064 project_transaction,
14065 format!("Rename: {} → {}", old_name, new_name),
14066 cx,
14067 )
14068 .await?;
14069
14070 editor.update(cx, |editor, cx| {
14071 editor.refresh_document_highlights(cx);
14072 })?;
14073 Ok(())
14074 }))
14075 }
14076
14077 fn take_rename(
14078 &mut self,
14079 moving_cursor: bool,
14080 window: &mut Window,
14081 cx: &mut Context<Self>,
14082 ) -> Option<RenameState> {
14083 let rename = self.pending_rename.take()?;
14084 if rename.editor.focus_handle(cx).is_focused(window) {
14085 window.focus(&self.focus_handle);
14086 }
14087
14088 self.remove_blocks(
14089 [rename.block_id].into_iter().collect(),
14090 Some(Autoscroll::fit()),
14091 cx,
14092 );
14093 self.clear_highlights::<Rename>(cx);
14094 self.show_local_selections = true;
14095
14096 if moving_cursor {
14097 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14098 editor.selections.newest::<usize>(cx).head()
14099 });
14100
14101 // Update the selection to match the position of the selection inside
14102 // the rename editor.
14103 let snapshot = self.buffer.read(cx).read(cx);
14104 let rename_range = rename.range.to_offset(&snapshot);
14105 let cursor_in_editor = snapshot
14106 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14107 .min(rename_range.end);
14108 drop(snapshot);
14109
14110 self.change_selections(None, window, cx, |s| {
14111 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14112 });
14113 } else {
14114 self.refresh_document_highlights(cx);
14115 }
14116
14117 Some(rename)
14118 }
14119
14120 pub fn pending_rename(&self) -> Option<&RenameState> {
14121 self.pending_rename.as_ref()
14122 }
14123
14124 fn format(
14125 &mut self,
14126 _: &Format,
14127 window: &mut Window,
14128 cx: &mut Context<Self>,
14129 ) -> Option<Task<Result<()>>> {
14130 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14131
14132 let project = match &self.project {
14133 Some(project) => project.clone(),
14134 None => return None,
14135 };
14136
14137 Some(self.perform_format(
14138 project,
14139 FormatTrigger::Manual,
14140 FormatTarget::Buffers,
14141 window,
14142 cx,
14143 ))
14144 }
14145
14146 fn format_selections(
14147 &mut self,
14148 _: &FormatSelections,
14149 window: &mut Window,
14150 cx: &mut Context<Self>,
14151 ) -> Option<Task<Result<()>>> {
14152 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14153
14154 let project = match &self.project {
14155 Some(project) => project.clone(),
14156 None => return None,
14157 };
14158
14159 let ranges = self
14160 .selections
14161 .all_adjusted(cx)
14162 .into_iter()
14163 .map(|selection| selection.range())
14164 .collect_vec();
14165
14166 Some(self.perform_format(
14167 project,
14168 FormatTrigger::Manual,
14169 FormatTarget::Ranges(ranges),
14170 window,
14171 cx,
14172 ))
14173 }
14174
14175 fn perform_format(
14176 &mut self,
14177 project: Entity<Project>,
14178 trigger: FormatTrigger,
14179 target: FormatTarget,
14180 window: &mut Window,
14181 cx: &mut Context<Self>,
14182 ) -> Task<Result<()>> {
14183 let buffer = self.buffer.clone();
14184 let (buffers, target) = match target {
14185 FormatTarget::Buffers => {
14186 let mut buffers = buffer.read(cx).all_buffers();
14187 if trigger == FormatTrigger::Save {
14188 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14189 }
14190 (buffers, LspFormatTarget::Buffers)
14191 }
14192 FormatTarget::Ranges(selection_ranges) => {
14193 let multi_buffer = buffer.read(cx);
14194 let snapshot = multi_buffer.read(cx);
14195 let mut buffers = HashSet::default();
14196 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14197 BTreeMap::new();
14198 for selection_range in selection_ranges {
14199 for (buffer, buffer_range, _) in
14200 snapshot.range_to_buffer_ranges(selection_range)
14201 {
14202 let buffer_id = buffer.remote_id();
14203 let start = buffer.anchor_before(buffer_range.start);
14204 let end = buffer.anchor_after(buffer_range.end);
14205 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14206 buffer_id_to_ranges
14207 .entry(buffer_id)
14208 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14209 .or_insert_with(|| vec![start..end]);
14210 }
14211 }
14212 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14213 }
14214 };
14215
14216 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14217 let format = project.update(cx, |project, cx| {
14218 project.format(buffers, target, true, trigger, cx)
14219 });
14220
14221 cx.spawn_in(window, async move |_, cx| {
14222 let transaction = futures::select_biased! {
14223 transaction = format.log_err().fuse() => transaction,
14224 () = timeout => {
14225 log::warn!("timed out waiting for formatting");
14226 None
14227 }
14228 };
14229
14230 buffer
14231 .update(cx, |buffer, cx| {
14232 if let Some(transaction) = transaction {
14233 if !buffer.is_singleton() {
14234 buffer.push_transaction(&transaction.0, cx);
14235 }
14236 }
14237 cx.notify();
14238 })
14239 .ok();
14240
14241 Ok(())
14242 })
14243 }
14244
14245 fn organize_imports(
14246 &mut self,
14247 _: &OrganizeImports,
14248 window: &mut Window,
14249 cx: &mut Context<Self>,
14250 ) -> Option<Task<Result<()>>> {
14251 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14252 let project = match &self.project {
14253 Some(project) => project.clone(),
14254 None => return None,
14255 };
14256 Some(self.perform_code_action_kind(
14257 project,
14258 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14259 window,
14260 cx,
14261 ))
14262 }
14263
14264 fn perform_code_action_kind(
14265 &mut self,
14266 project: Entity<Project>,
14267 kind: CodeActionKind,
14268 window: &mut Window,
14269 cx: &mut Context<Self>,
14270 ) -> Task<Result<()>> {
14271 let buffer = self.buffer.clone();
14272 let buffers = buffer.read(cx).all_buffers();
14273 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14274 let apply_action = project.update(cx, |project, cx| {
14275 project.apply_code_action_kind(buffers, kind, true, cx)
14276 });
14277 cx.spawn_in(window, async move |_, cx| {
14278 let transaction = futures::select_biased! {
14279 () = timeout => {
14280 log::warn!("timed out waiting for executing code action");
14281 None
14282 }
14283 transaction = apply_action.log_err().fuse() => transaction,
14284 };
14285 buffer
14286 .update(cx, |buffer, cx| {
14287 // check if we need this
14288 if let Some(transaction) = transaction {
14289 if !buffer.is_singleton() {
14290 buffer.push_transaction(&transaction.0, cx);
14291 }
14292 }
14293 cx.notify();
14294 })
14295 .ok();
14296 Ok(())
14297 })
14298 }
14299
14300 fn restart_language_server(
14301 &mut self,
14302 _: &RestartLanguageServer,
14303 _: &mut Window,
14304 cx: &mut Context<Self>,
14305 ) {
14306 if let Some(project) = self.project.clone() {
14307 self.buffer.update(cx, |multi_buffer, cx| {
14308 project.update(cx, |project, cx| {
14309 project.restart_language_servers_for_buffers(
14310 multi_buffer.all_buffers().into_iter().collect(),
14311 cx,
14312 );
14313 });
14314 })
14315 }
14316 }
14317
14318 fn stop_language_server(
14319 &mut self,
14320 _: &StopLanguageServer,
14321 _: &mut Window,
14322 cx: &mut Context<Self>,
14323 ) {
14324 if let Some(project) = self.project.clone() {
14325 self.buffer.update(cx, |multi_buffer, cx| {
14326 project.update(cx, |project, cx| {
14327 project.stop_language_servers_for_buffers(
14328 multi_buffer.all_buffers().into_iter().collect(),
14329 cx,
14330 );
14331 cx.emit(project::Event::RefreshInlayHints);
14332 });
14333 });
14334 }
14335 }
14336
14337 fn cancel_language_server_work(
14338 workspace: &mut Workspace,
14339 _: &actions::CancelLanguageServerWork,
14340 _: &mut Window,
14341 cx: &mut Context<Workspace>,
14342 ) {
14343 let project = workspace.project();
14344 let buffers = workspace
14345 .active_item(cx)
14346 .and_then(|item| item.act_as::<Editor>(cx))
14347 .map_or(HashSet::default(), |editor| {
14348 editor.read(cx).buffer.read(cx).all_buffers()
14349 });
14350 project.update(cx, |project, cx| {
14351 project.cancel_language_server_work_for_buffers(buffers, cx);
14352 });
14353 }
14354
14355 fn show_character_palette(
14356 &mut self,
14357 _: &ShowCharacterPalette,
14358 window: &mut Window,
14359 _: &mut Context<Self>,
14360 ) {
14361 window.show_character_palette();
14362 }
14363
14364 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14365 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14366 let buffer = self.buffer.read(cx).snapshot(cx);
14367 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14368 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14369 let is_valid = buffer
14370 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14371 .any(|entry| {
14372 entry.diagnostic.is_primary
14373 && !entry.range.is_empty()
14374 && entry.range.start == primary_range_start
14375 && entry.diagnostic.message == active_diagnostics.primary_message
14376 });
14377
14378 if is_valid != active_diagnostics.is_valid {
14379 active_diagnostics.is_valid = is_valid;
14380 if is_valid {
14381 let mut new_styles = HashMap::default();
14382 for (block_id, diagnostic) in &active_diagnostics.blocks {
14383 new_styles.insert(
14384 *block_id,
14385 diagnostic_block_renderer(diagnostic.clone(), None, true),
14386 );
14387 }
14388 self.display_map.update(cx, |display_map, _cx| {
14389 display_map.replace_blocks(new_styles);
14390 });
14391 } else {
14392 self.dismiss_diagnostics(cx);
14393 }
14394 }
14395 }
14396 }
14397
14398 fn activate_diagnostics(
14399 &mut self,
14400 buffer_id: BufferId,
14401 group_id: usize,
14402 window: &mut Window,
14403 cx: &mut Context<Self>,
14404 ) {
14405 self.dismiss_diagnostics(cx);
14406 let snapshot = self.snapshot(window, cx);
14407 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14408 let buffer = self.buffer.read(cx).snapshot(cx);
14409
14410 let mut primary_range = None;
14411 let mut primary_message = None;
14412 let diagnostic_group = buffer
14413 .diagnostic_group(buffer_id, group_id)
14414 .filter_map(|entry| {
14415 let start = entry.range.start;
14416 let end = entry.range.end;
14417 if snapshot.is_line_folded(MultiBufferRow(start.row))
14418 && (start.row == end.row
14419 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14420 {
14421 return None;
14422 }
14423 if entry.diagnostic.is_primary {
14424 primary_range = Some(entry.range.clone());
14425 primary_message = Some(entry.diagnostic.message.clone());
14426 }
14427 Some(entry)
14428 })
14429 .collect::<Vec<_>>();
14430 let primary_range = primary_range?;
14431 let primary_message = primary_message?;
14432
14433 let blocks = display_map
14434 .insert_blocks(
14435 diagnostic_group.iter().map(|entry| {
14436 let diagnostic = entry.diagnostic.clone();
14437 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14438 BlockProperties {
14439 style: BlockStyle::Fixed,
14440 placement: BlockPlacement::Below(
14441 buffer.anchor_after(entry.range.start),
14442 ),
14443 height: Some(message_height),
14444 render: diagnostic_block_renderer(diagnostic, None, true),
14445 priority: 0,
14446 }
14447 }),
14448 cx,
14449 )
14450 .into_iter()
14451 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14452 .collect();
14453
14454 Some(ActiveDiagnosticGroup {
14455 primary_range: buffer.anchor_before(primary_range.start)
14456 ..buffer.anchor_after(primary_range.end),
14457 primary_message,
14458 group_id,
14459 blocks,
14460 is_valid: true,
14461 })
14462 });
14463 }
14464
14465 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14466 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14467 self.display_map.update(cx, |display_map, cx| {
14468 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14469 });
14470 cx.notify();
14471 }
14472 }
14473
14474 /// Disable inline diagnostics rendering for this editor.
14475 pub fn disable_inline_diagnostics(&mut self) {
14476 self.inline_diagnostics_enabled = false;
14477 self.inline_diagnostics_update = Task::ready(());
14478 self.inline_diagnostics.clear();
14479 }
14480
14481 pub fn inline_diagnostics_enabled(&self) -> bool {
14482 self.inline_diagnostics_enabled
14483 }
14484
14485 pub fn show_inline_diagnostics(&self) -> bool {
14486 self.show_inline_diagnostics
14487 }
14488
14489 pub fn toggle_inline_diagnostics(
14490 &mut self,
14491 _: &ToggleInlineDiagnostics,
14492 window: &mut Window,
14493 cx: &mut Context<Editor>,
14494 ) {
14495 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14496 self.refresh_inline_diagnostics(false, window, cx);
14497 }
14498
14499 fn refresh_inline_diagnostics(
14500 &mut self,
14501 debounce: bool,
14502 window: &mut Window,
14503 cx: &mut Context<Self>,
14504 ) {
14505 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14506 self.inline_diagnostics_update = Task::ready(());
14507 self.inline_diagnostics.clear();
14508 return;
14509 }
14510
14511 let debounce_ms = ProjectSettings::get_global(cx)
14512 .diagnostics
14513 .inline
14514 .update_debounce_ms;
14515 let debounce = if debounce && debounce_ms > 0 {
14516 Some(Duration::from_millis(debounce_ms))
14517 } else {
14518 None
14519 };
14520 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14521 if let Some(debounce) = debounce {
14522 cx.background_executor().timer(debounce).await;
14523 }
14524 let Some(snapshot) = editor
14525 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14526 .ok()
14527 else {
14528 return;
14529 };
14530
14531 let new_inline_diagnostics = cx
14532 .background_spawn(async move {
14533 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14534 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14535 let message = diagnostic_entry
14536 .diagnostic
14537 .message
14538 .split_once('\n')
14539 .map(|(line, _)| line)
14540 .map(SharedString::new)
14541 .unwrap_or_else(|| {
14542 SharedString::from(diagnostic_entry.diagnostic.message)
14543 });
14544 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14545 let (Ok(i) | Err(i)) = inline_diagnostics
14546 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14547 inline_diagnostics.insert(
14548 i,
14549 (
14550 start_anchor,
14551 InlineDiagnostic {
14552 message,
14553 group_id: diagnostic_entry.diagnostic.group_id,
14554 start: diagnostic_entry.range.start.to_point(&snapshot),
14555 is_primary: diagnostic_entry.diagnostic.is_primary,
14556 severity: diagnostic_entry.diagnostic.severity,
14557 },
14558 ),
14559 );
14560 }
14561 inline_diagnostics
14562 })
14563 .await;
14564
14565 editor
14566 .update(cx, |editor, cx| {
14567 editor.inline_diagnostics = new_inline_diagnostics;
14568 cx.notify();
14569 })
14570 .ok();
14571 });
14572 }
14573
14574 pub fn set_selections_from_remote(
14575 &mut self,
14576 selections: Vec<Selection<Anchor>>,
14577 pending_selection: Option<Selection<Anchor>>,
14578 window: &mut Window,
14579 cx: &mut Context<Self>,
14580 ) {
14581 let old_cursor_position = self.selections.newest_anchor().head();
14582 self.selections.change_with(cx, |s| {
14583 s.select_anchors(selections);
14584 if let Some(pending_selection) = pending_selection {
14585 s.set_pending(pending_selection, SelectMode::Character);
14586 } else {
14587 s.clear_pending();
14588 }
14589 });
14590 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14591 }
14592
14593 fn push_to_selection_history(&mut self) {
14594 self.selection_history.push(SelectionHistoryEntry {
14595 selections: self.selections.disjoint_anchors(),
14596 select_next_state: self.select_next_state.clone(),
14597 select_prev_state: self.select_prev_state.clone(),
14598 add_selections_state: self.add_selections_state.clone(),
14599 });
14600 }
14601
14602 pub fn transact(
14603 &mut self,
14604 window: &mut Window,
14605 cx: &mut Context<Self>,
14606 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14607 ) -> Option<TransactionId> {
14608 self.start_transaction_at(Instant::now(), window, cx);
14609 update(self, window, cx);
14610 self.end_transaction_at(Instant::now(), cx)
14611 }
14612
14613 pub fn start_transaction_at(
14614 &mut self,
14615 now: Instant,
14616 window: &mut Window,
14617 cx: &mut Context<Self>,
14618 ) {
14619 self.end_selection(window, cx);
14620 if let Some(tx_id) = self
14621 .buffer
14622 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14623 {
14624 self.selection_history
14625 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14626 cx.emit(EditorEvent::TransactionBegun {
14627 transaction_id: tx_id,
14628 })
14629 }
14630 }
14631
14632 pub fn end_transaction_at(
14633 &mut self,
14634 now: Instant,
14635 cx: &mut Context<Self>,
14636 ) -> Option<TransactionId> {
14637 if let Some(transaction_id) = self
14638 .buffer
14639 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14640 {
14641 if let Some((_, end_selections)) =
14642 self.selection_history.transaction_mut(transaction_id)
14643 {
14644 *end_selections = Some(self.selections.disjoint_anchors());
14645 } else {
14646 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14647 }
14648
14649 cx.emit(EditorEvent::Edited { transaction_id });
14650 Some(transaction_id)
14651 } else {
14652 None
14653 }
14654 }
14655
14656 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14657 if self.selection_mark_mode {
14658 self.change_selections(None, window, cx, |s| {
14659 s.move_with(|_, sel| {
14660 sel.collapse_to(sel.head(), SelectionGoal::None);
14661 });
14662 })
14663 }
14664 self.selection_mark_mode = true;
14665 cx.notify();
14666 }
14667
14668 pub fn swap_selection_ends(
14669 &mut self,
14670 _: &actions::SwapSelectionEnds,
14671 window: &mut Window,
14672 cx: &mut Context<Self>,
14673 ) {
14674 self.change_selections(None, window, cx, |s| {
14675 s.move_with(|_, sel| {
14676 if sel.start != sel.end {
14677 sel.reversed = !sel.reversed
14678 }
14679 });
14680 });
14681 self.request_autoscroll(Autoscroll::newest(), cx);
14682 cx.notify();
14683 }
14684
14685 pub fn toggle_fold(
14686 &mut self,
14687 _: &actions::ToggleFold,
14688 window: &mut Window,
14689 cx: &mut Context<Self>,
14690 ) {
14691 if self.is_singleton(cx) {
14692 let selection = self.selections.newest::<Point>(cx);
14693
14694 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14695 let range = if selection.is_empty() {
14696 let point = selection.head().to_display_point(&display_map);
14697 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14698 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14699 .to_point(&display_map);
14700 start..end
14701 } else {
14702 selection.range()
14703 };
14704 if display_map.folds_in_range(range).next().is_some() {
14705 self.unfold_lines(&Default::default(), window, cx)
14706 } else {
14707 self.fold(&Default::default(), window, cx)
14708 }
14709 } else {
14710 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14711 let buffer_ids: HashSet<_> = self
14712 .selections
14713 .disjoint_anchor_ranges()
14714 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14715 .collect();
14716
14717 let should_unfold = buffer_ids
14718 .iter()
14719 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14720
14721 for buffer_id in buffer_ids {
14722 if should_unfold {
14723 self.unfold_buffer(buffer_id, cx);
14724 } else {
14725 self.fold_buffer(buffer_id, cx);
14726 }
14727 }
14728 }
14729 }
14730
14731 pub fn toggle_fold_recursive(
14732 &mut self,
14733 _: &actions::ToggleFoldRecursive,
14734 window: &mut Window,
14735 cx: &mut Context<Self>,
14736 ) {
14737 let selection = self.selections.newest::<Point>(cx);
14738
14739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14740 let range = if selection.is_empty() {
14741 let point = selection.head().to_display_point(&display_map);
14742 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14743 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14744 .to_point(&display_map);
14745 start..end
14746 } else {
14747 selection.range()
14748 };
14749 if display_map.folds_in_range(range).next().is_some() {
14750 self.unfold_recursive(&Default::default(), window, cx)
14751 } else {
14752 self.fold_recursive(&Default::default(), window, cx)
14753 }
14754 }
14755
14756 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14757 if self.is_singleton(cx) {
14758 let mut to_fold = Vec::new();
14759 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14760 let selections = self.selections.all_adjusted(cx);
14761
14762 for selection in selections {
14763 let range = selection.range().sorted();
14764 let buffer_start_row = range.start.row;
14765
14766 if range.start.row != range.end.row {
14767 let mut found = false;
14768 let mut row = range.start.row;
14769 while row <= range.end.row {
14770 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14771 {
14772 found = true;
14773 row = crease.range().end.row + 1;
14774 to_fold.push(crease);
14775 } else {
14776 row += 1
14777 }
14778 }
14779 if found {
14780 continue;
14781 }
14782 }
14783
14784 for row in (0..=range.start.row).rev() {
14785 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14786 if crease.range().end.row >= buffer_start_row {
14787 to_fold.push(crease);
14788 if row <= range.start.row {
14789 break;
14790 }
14791 }
14792 }
14793 }
14794 }
14795
14796 self.fold_creases(to_fold, true, window, cx);
14797 } else {
14798 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14799 let buffer_ids = self
14800 .selections
14801 .disjoint_anchor_ranges()
14802 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14803 .collect::<HashSet<_>>();
14804 for buffer_id in buffer_ids {
14805 self.fold_buffer(buffer_id, cx);
14806 }
14807 }
14808 }
14809
14810 fn fold_at_level(
14811 &mut self,
14812 fold_at: &FoldAtLevel,
14813 window: &mut Window,
14814 cx: &mut Context<Self>,
14815 ) {
14816 if !self.buffer.read(cx).is_singleton() {
14817 return;
14818 }
14819
14820 let fold_at_level = fold_at.0;
14821 let snapshot = self.buffer.read(cx).snapshot(cx);
14822 let mut to_fold = Vec::new();
14823 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14824
14825 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14826 while start_row < end_row {
14827 match self
14828 .snapshot(window, cx)
14829 .crease_for_buffer_row(MultiBufferRow(start_row))
14830 {
14831 Some(crease) => {
14832 let nested_start_row = crease.range().start.row + 1;
14833 let nested_end_row = crease.range().end.row;
14834
14835 if current_level < fold_at_level {
14836 stack.push((nested_start_row, nested_end_row, current_level + 1));
14837 } else if current_level == fold_at_level {
14838 to_fold.push(crease);
14839 }
14840
14841 start_row = nested_end_row + 1;
14842 }
14843 None => start_row += 1,
14844 }
14845 }
14846 }
14847
14848 self.fold_creases(to_fold, true, window, cx);
14849 }
14850
14851 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14852 if self.buffer.read(cx).is_singleton() {
14853 let mut fold_ranges = Vec::new();
14854 let snapshot = self.buffer.read(cx).snapshot(cx);
14855
14856 for row in 0..snapshot.max_row().0 {
14857 if let Some(foldable_range) = self
14858 .snapshot(window, cx)
14859 .crease_for_buffer_row(MultiBufferRow(row))
14860 {
14861 fold_ranges.push(foldable_range);
14862 }
14863 }
14864
14865 self.fold_creases(fold_ranges, true, window, cx);
14866 } else {
14867 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14868 editor
14869 .update_in(cx, |editor, _, cx| {
14870 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14871 editor.fold_buffer(buffer_id, cx);
14872 }
14873 })
14874 .ok();
14875 });
14876 }
14877 }
14878
14879 pub fn fold_function_bodies(
14880 &mut self,
14881 _: &actions::FoldFunctionBodies,
14882 window: &mut Window,
14883 cx: &mut Context<Self>,
14884 ) {
14885 let snapshot = self.buffer.read(cx).snapshot(cx);
14886
14887 let ranges = snapshot
14888 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14889 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14890 .collect::<Vec<_>>();
14891
14892 let creases = ranges
14893 .into_iter()
14894 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14895 .collect();
14896
14897 self.fold_creases(creases, true, window, cx);
14898 }
14899
14900 pub fn fold_recursive(
14901 &mut self,
14902 _: &actions::FoldRecursive,
14903 window: &mut Window,
14904 cx: &mut Context<Self>,
14905 ) {
14906 let mut to_fold = Vec::new();
14907 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14908 let selections = self.selections.all_adjusted(cx);
14909
14910 for selection in selections {
14911 let range = selection.range().sorted();
14912 let buffer_start_row = range.start.row;
14913
14914 if range.start.row != range.end.row {
14915 let mut found = false;
14916 for row in range.start.row..=range.end.row {
14917 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14918 found = true;
14919 to_fold.push(crease);
14920 }
14921 }
14922 if found {
14923 continue;
14924 }
14925 }
14926
14927 for row in (0..=range.start.row).rev() {
14928 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14929 if crease.range().end.row >= buffer_start_row {
14930 to_fold.push(crease);
14931 } else {
14932 break;
14933 }
14934 }
14935 }
14936 }
14937
14938 self.fold_creases(to_fold, true, window, cx);
14939 }
14940
14941 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14942 let buffer_row = fold_at.buffer_row;
14943 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14944
14945 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14946 let autoscroll = self
14947 .selections
14948 .all::<Point>(cx)
14949 .iter()
14950 .any(|selection| crease.range().overlaps(&selection.range()));
14951
14952 self.fold_creases(vec![crease], autoscroll, window, cx);
14953 }
14954 }
14955
14956 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14957 if self.is_singleton(cx) {
14958 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14959 let buffer = &display_map.buffer_snapshot;
14960 let selections = self.selections.all::<Point>(cx);
14961 let ranges = selections
14962 .iter()
14963 .map(|s| {
14964 let range = s.display_range(&display_map).sorted();
14965 let mut start = range.start.to_point(&display_map);
14966 let mut end = range.end.to_point(&display_map);
14967 start.column = 0;
14968 end.column = buffer.line_len(MultiBufferRow(end.row));
14969 start..end
14970 })
14971 .collect::<Vec<_>>();
14972
14973 self.unfold_ranges(&ranges, true, true, cx);
14974 } else {
14975 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14976 let buffer_ids = self
14977 .selections
14978 .disjoint_anchor_ranges()
14979 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14980 .collect::<HashSet<_>>();
14981 for buffer_id in buffer_ids {
14982 self.unfold_buffer(buffer_id, cx);
14983 }
14984 }
14985 }
14986
14987 pub fn unfold_recursive(
14988 &mut self,
14989 _: &UnfoldRecursive,
14990 _window: &mut Window,
14991 cx: &mut Context<Self>,
14992 ) {
14993 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14994 let selections = self.selections.all::<Point>(cx);
14995 let ranges = selections
14996 .iter()
14997 .map(|s| {
14998 let mut range = s.display_range(&display_map).sorted();
14999 *range.start.column_mut() = 0;
15000 *range.end.column_mut() = display_map.line_len(range.end.row());
15001 let start = range.start.to_point(&display_map);
15002 let end = range.end.to_point(&display_map);
15003 start..end
15004 })
15005 .collect::<Vec<_>>();
15006
15007 self.unfold_ranges(&ranges, true, true, cx);
15008 }
15009
15010 pub fn unfold_at(
15011 &mut self,
15012 unfold_at: &UnfoldAt,
15013 _window: &mut Window,
15014 cx: &mut Context<Self>,
15015 ) {
15016 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15017
15018 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
15019 ..Point::new(
15020 unfold_at.buffer_row.0,
15021 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
15022 );
15023
15024 let autoscroll = self
15025 .selections
15026 .all::<Point>(cx)
15027 .iter()
15028 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15029
15030 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15031 }
15032
15033 pub fn unfold_all(
15034 &mut self,
15035 _: &actions::UnfoldAll,
15036 _window: &mut Window,
15037 cx: &mut Context<Self>,
15038 ) {
15039 if self.buffer.read(cx).is_singleton() {
15040 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15041 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15042 } else {
15043 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15044 editor
15045 .update(cx, |editor, cx| {
15046 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15047 editor.unfold_buffer(buffer_id, cx);
15048 }
15049 })
15050 .ok();
15051 });
15052 }
15053 }
15054
15055 pub fn fold_selected_ranges(
15056 &mut self,
15057 _: &FoldSelectedRanges,
15058 window: &mut Window,
15059 cx: &mut Context<Self>,
15060 ) {
15061 let selections = self.selections.all_adjusted(cx);
15062 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15063 let ranges = selections
15064 .into_iter()
15065 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15066 .collect::<Vec<_>>();
15067 self.fold_creases(ranges, true, window, cx);
15068 }
15069
15070 pub fn fold_ranges<T: ToOffset + Clone>(
15071 &mut self,
15072 ranges: Vec<Range<T>>,
15073 auto_scroll: bool,
15074 window: &mut Window,
15075 cx: &mut Context<Self>,
15076 ) {
15077 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15078 let ranges = ranges
15079 .into_iter()
15080 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15081 .collect::<Vec<_>>();
15082 self.fold_creases(ranges, auto_scroll, window, cx);
15083 }
15084
15085 pub fn fold_creases<T: ToOffset + Clone>(
15086 &mut self,
15087 creases: Vec<Crease<T>>,
15088 auto_scroll: bool,
15089 window: &mut Window,
15090 cx: &mut Context<Self>,
15091 ) {
15092 if creases.is_empty() {
15093 return;
15094 }
15095
15096 let mut buffers_affected = HashSet::default();
15097 let multi_buffer = self.buffer().read(cx);
15098 for crease in &creases {
15099 if let Some((_, buffer, _)) =
15100 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15101 {
15102 buffers_affected.insert(buffer.read(cx).remote_id());
15103 };
15104 }
15105
15106 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15107
15108 if auto_scroll {
15109 self.request_autoscroll(Autoscroll::fit(), cx);
15110 }
15111
15112 cx.notify();
15113
15114 if let Some(active_diagnostics) = self.active_diagnostics.take() {
15115 // Clear diagnostics block when folding a range that contains it.
15116 let snapshot = self.snapshot(window, cx);
15117 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
15118 drop(snapshot);
15119 self.active_diagnostics = Some(active_diagnostics);
15120 self.dismiss_diagnostics(cx);
15121 } else {
15122 self.active_diagnostics = Some(active_diagnostics);
15123 }
15124 }
15125
15126 self.scrollbar_marker_state.dirty = true;
15127 self.folds_did_change(cx);
15128 }
15129
15130 /// Removes any folds whose ranges intersect any of the given ranges.
15131 pub fn unfold_ranges<T: ToOffset + Clone>(
15132 &mut self,
15133 ranges: &[Range<T>],
15134 inclusive: bool,
15135 auto_scroll: bool,
15136 cx: &mut Context<Self>,
15137 ) {
15138 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15139 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15140 });
15141 self.folds_did_change(cx);
15142 }
15143
15144 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15145 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15146 return;
15147 }
15148 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15149 self.display_map.update(cx, |display_map, cx| {
15150 display_map.fold_buffers([buffer_id], cx)
15151 });
15152 cx.emit(EditorEvent::BufferFoldToggled {
15153 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15154 folded: true,
15155 });
15156 cx.notify();
15157 }
15158
15159 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15160 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15161 return;
15162 }
15163 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15164 self.display_map.update(cx, |display_map, cx| {
15165 display_map.unfold_buffers([buffer_id], cx);
15166 });
15167 cx.emit(EditorEvent::BufferFoldToggled {
15168 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15169 folded: false,
15170 });
15171 cx.notify();
15172 }
15173
15174 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15175 self.display_map.read(cx).is_buffer_folded(buffer)
15176 }
15177
15178 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15179 self.display_map.read(cx).folded_buffers()
15180 }
15181
15182 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15183 self.display_map.update(cx, |display_map, cx| {
15184 display_map.disable_header_for_buffer(buffer_id, cx);
15185 });
15186 cx.notify();
15187 }
15188
15189 /// Removes any folds with the given ranges.
15190 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15191 &mut self,
15192 ranges: &[Range<T>],
15193 type_id: TypeId,
15194 auto_scroll: bool,
15195 cx: &mut Context<Self>,
15196 ) {
15197 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15198 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15199 });
15200 self.folds_did_change(cx);
15201 }
15202
15203 fn remove_folds_with<T: ToOffset + Clone>(
15204 &mut self,
15205 ranges: &[Range<T>],
15206 auto_scroll: bool,
15207 cx: &mut Context<Self>,
15208 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15209 ) {
15210 if ranges.is_empty() {
15211 return;
15212 }
15213
15214 let mut buffers_affected = HashSet::default();
15215 let multi_buffer = self.buffer().read(cx);
15216 for range in ranges {
15217 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15218 buffers_affected.insert(buffer.read(cx).remote_id());
15219 };
15220 }
15221
15222 self.display_map.update(cx, update);
15223
15224 if auto_scroll {
15225 self.request_autoscroll(Autoscroll::fit(), cx);
15226 }
15227
15228 cx.notify();
15229 self.scrollbar_marker_state.dirty = true;
15230 self.active_indent_guides_state.dirty = true;
15231 }
15232
15233 pub fn update_fold_widths(
15234 &mut self,
15235 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15236 cx: &mut Context<Self>,
15237 ) -> bool {
15238 self.display_map
15239 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15240 }
15241
15242 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15243 self.display_map.read(cx).fold_placeholder.clone()
15244 }
15245
15246 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15247 self.buffer.update(cx, |buffer, cx| {
15248 buffer.set_all_diff_hunks_expanded(cx);
15249 });
15250 }
15251
15252 pub fn expand_all_diff_hunks(
15253 &mut self,
15254 _: &ExpandAllDiffHunks,
15255 _window: &mut Window,
15256 cx: &mut Context<Self>,
15257 ) {
15258 self.buffer.update(cx, |buffer, cx| {
15259 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15260 });
15261 }
15262
15263 pub fn toggle_selected_diff_hunks(
15264 &mut self,
15265 _: &ToggleSelectedDiffHunks,
15266 _window: &mut Window,
15267 cx: &mut Context<Self>,
15268 ) {
15269 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15270 self.toggle_diff_hunks_in_ranges(ranges, cx);
15271 }
15272
15273 pub fn diff_hunks_in_ranges<'a>(
15274 &'a self,
15275 ranges: &'a [Range<Anchor>],
15276 buffer: &'a MultiBufferSnapshot,
15277 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15278 ranges.iter().flat_map(move |range| {
15279 let end_excerpt_id = range.end.excerpt_id;
15280 let range = range.to_point(buffer);
15281 let mut peek_end = range.end;
15282 if range.end.row < buffer.max_row().0 {
15283 peek_end = Point::new(range.end.row + 1, 0);
15284 }
15285 buffer
15286 .diff_hunks_in_range(range.start..peek_end)
15287 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15288 })
15289 }
15290
15291 pub fn has_stageable_diff_hunks_in_ranges(
15292 &self,
15293 ranges: &[Range<Anchor>],
15294 snapshot: &MultiBufferSnapshot,
15295 ) -> bool {
15296 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15297 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15298 }
15299
15300 pub fn toggle_staged_selected_diff_hunks(
15301 &mut self,
15302 _: &::git::ToggleStaged,
15303 _: &mut Window,
15304 cx: &mut Context<Self>,
15305 ) {
15306 let snapshot = self.buffer.read(cx).snapshot(cx);
15307 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15308 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15309 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15310 }
15311
15312 pub fn set_render_diff_hunk_controls(
15313 &mut self,
15314 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15315 cx: &mut Context<Self>,
15316 ) {
15317 self.render_diff_hunk_controls = render_diff_hunk_controls;
15318 cx.notify();
15319 }
15320
15321 pub fn stage_and_next(
15322 &mut self,
15323 _: &::git::StageAndNext,
15324 window: &mut Window,
15325 cx: &mut Context<Self>,
15326 ) {
15327 self.do_stage_or_unstage_and_next(true, window, cx);
15328 }
15329
15330 pub fn unstage_and_next(
15331 &mut self,
15332 _: &::git::UnstageAndNext,
15333 window: &mut Window,
15334 cx: &mut Context<Self>,
15335 ) {
15336 self.do_stage_or_unstage_and_next(false, window, cx);
15337 }
15338
15339 pub fn stage_or_unstage_diff_hunks(
15340 &mut self,
15341 stage: bool,
15342 ranges: Vec<Range<Anchor>>,
15343 cx: &mut Context<Self>,
15344 ) {
15345 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15346 cx.spawn(async move |this, cx| {
15347 task.await?;
15348 this.update(cx, |this, cx| {
15349 let snapshot = this.buffer.read(cx).snapshot(cx);
15350 let chunk_by = this
15351 .diff_hunks_in_ranges(&ranges, &snapshot)
15352 .chunk_by(|hunk| hunk.buffer_id);
15353 for (buffer_id, hunks) in &chunk_by {
15354 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15355 }
15356 })
15357 })
15358 .detach_and_log_err(cx);
15359 }
15360
15361 fn save_buffers_for_ranges_if_needed(
15362 &mut self,
15363 ranges: &[Range<Anchor>],
15364 cx: &mut Context<Editor>,
15365 ) -> Task<Result<()>> {
15366 let multibuffer = self.buffer.read(cx);
15367 let snapshot = multibuffer.read(cx);
15368 let buffer_ids: HashSet<_> = ranges
15369 .iter()
15370 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15371 .collect();
15372 drop(snapshot);
15373
15374 let mut buffers = HashSet::default();
15375 for buffer_id in buffer_ids {
15376 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15377 let buffer = buffer_entity.read(cx);
15378 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15379 {
15380 buffers.insert(buffer_entity);
15381 }
15382 }
15383 }
15384
15385 if let Some(project) = &self.project {
15386 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15387 } else {
15388 Task::ready(Ok(()))
15389 }
15390 }
15391
15392 fn do_stage_or_unstage_and_next(
15393 &mut self,
15394 stage: bool,
15395 window: &mut Window,
15396 cx: &mut Context<Self>,
15397 ) {
15398 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15399
15400 if ranges.iter().any(|range| range.start != range.end) {
15401 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15402 return;
15403 }
15404
15405 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15406 let snapshot = self.snapshot(window, cx);
15407 let position = self.selections.newest::<Point>(cx).head();
15408 let mut row = snapshot
15409 .buffer_snapshot
15410 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15411 .find(|hunk| hunk.row_range.start.0 > position.row)
15412 .map(|hunk| hunk.row_range.start);
15413
15414 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15415 // Outside of the project diff editor, wrap around to the beginning.
15416 if !all_diff_hunks_expanded {
15417 row = row.or_else(|| {
15418 snapshot
15419 .buffer_snapshot
15420 .diff_hunks_in_range(Point::zero()..position)
15421 .find(|hunk| hunk.row_range.end.0 < position.row)
15422 .map(|hunk| hunk.row_range.start)
15423 });
15424 }
15425
15426 if let Some(row) = row {
15427 let destination = Point::new(row.0, 0);
15428 let autoscroll = Autoscroll::center();
15429
15430 self.unfold_ranges(&[destination..destination], false, false, cx);
15431 self.change_selections(Some(autoscroll), window, cx, |s| {
15432 s.select_ranges([destination..destination]);
15433 });
15434 }
15435 }
15436
15437 fn do_stage_or_unstage(
15438 &self,
15439 stage: bool,
15440 buffer_id: BufferId,
15441 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15442 cx: &mut App,
15443 ) -> Option<()> {
15444 let project = self.project.as_ref()?;
15445 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15446 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15447 let buffer_snapshot = buffer.read(cx).snapshot();
15448 let file_exists = buffer_snapshot
15449 .file()
15450 .is_some_and(|file| file.disk_state().exists());
15451 diff.update(cx, |diff, cx| {
15452 diff.stage_or_unstage_hunks(
15453 stage,
15454 &hunks
15455 .map(|hunk| buffer_diff::DiffHunk {
15456 buffer_range: hunk.buffer_range,
15457 diff_base_byte_range: hunk.diff_base_byte_range,
15458 secondary_status: hunk.secondary_status,
15459 range: Point::zero()..Point::zero(), // unused
15460 })
15461 .collect::<Vec<_>>(),
15462 &buffer_snapshot,
15463 file_exists,
15464 cx,
15465 )
15466 });
15467 None
15468 }
15469
15470 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15471 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15472 self.buffer
15473 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15474 }
15475
15476 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15477 self.buffer.update(cx, |buffer, cx| {
15478 let ranges = vec![Anchor::min()..Anchor::max()];
15479 if !buffer.all_diff_hunks_expanded()
15480 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15481 {
15482 buffer.collapse_diff_hunks(ranges, cx);
15483 true
15484 } else {
15485 false
15486 }
15487 })
15488 }
15489
15490 fn toggle_diff_hunks_in_ranges(
15491 &mut self,
15492 ranges: Vec<Range<Anchor>>,
15493 cx: &mut Context<Editor>,
15494 ) {
15495 self.buffer.update(cx, |buffer, cx| {
15496 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15497 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15498 })
15499 }
15500
15501 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15502 self.buffer.update(cx, |buffer, cx| {
15503 let snapshot = buffer.snapshot(cx);
15504 let excerpt_id = range.end.excerpt_id;
15505 let point_range = range.to_point(&snapshot);
15506 let expand = !buffer.single_hunk_is_expanded(range, cx);
15507 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15508 })
15509 }
15510
15511 pub(crate) fn apply_all_diff_hunks(
15512 &mut self,
15513 _: &ApplyAllDiffHunks,
15514 window: &mut Window,
15515 cx: &mut Context<Self>,
15516 ) {
15517 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15518
15519 let buffers = self.buffer.read(cx).all_buffers();
15520 for branch_buffer in buffers {
15521 branch_buffer.update(cx, |branch_buffer, cx| {
15522 branch_buffer.merge_into_base(Vec::new(), cx);
15523 });
15524 }
15525
15526 if let Some(project) = self.project.clone() {
15527 self.save(true, project, window, cx).detach_and_log_err(cx);
15528 }
15529 }
15530
15531 pub(crate) fn apply_selected_diff_hunks(
15532 &mut self,
15533 _: &ApplyDiffHunk,
15534 window: &mut Window,
15535 cx: &mut Context<Self>,
15536 ) {
15537 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15538 let snapshot = self.snapshot(window, cx);
15539 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15540 let mut ranges_by_buffer = HashMap::default();
15541 self.transact(window, cx, |editor, _window, cx| {
15542 for hunk in hunks {
15543 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15544 ranges_by_buffer
15545 .entry(buffer.clone())
15546 .or_insert_with(Vec::new)
15547 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15548 }
15549 }
15550
15551 for (buffer, ranges) in ranges_by_buffer {
15552 buffer.update(cx, |buffer, cx| {
15553 buffer.merge_into_base(ranges, cx);
15554 });
15555 }
15556 });
15557
15558 if let Some(project) = self.project.clone() {
15559 self.save(true, project, window, cx).detach_and_log_err(cx);
15560 }
15561 }
15562
15563 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15564 if hovered != self.gutter_hovered {
15565 self.gutter_hovered = hovered;
15566 cx.notify();
15567 }
15568 }
15569
15570 pub fn insert_blocks(
15571 &mut self,
15572 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15573 autoscroll: Option<Autoscroll>,
15574 cx: &mut Context<Self>,
15575 ) -> Vec<CustomBlockId> {
15576 let blocks = self
15577 .display_map
15578 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15579 if let Some(autoscroll) = autoscroll {
15580 self.request_autoscroll(autoscroll, cx);
15581 }
15582 cx.notify();
15583 blocks
15584 }
15585
15586 pub fn resize_blocks(
15587 &mut self,
15588 heights: HashMap<CustomBlockId, u32>,
15589 autoscroll: Option<Autoscroll>,
15590 cx: &mut Context<Self>,
15591 ) {
15592 self.display_map
15593 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15594 if let Some(autoscroll) = autoscroll {
15595 self.request_autoscroll(autoscroll, cx);
15596 }
15597 cx.notify();
15598 }
15599
15600 pub fn replace_blocks(
15601 &mut self,
15602 renderers: HashMap<CustomBlockId, RenderBlock>,
15603 autoscroll: Option<Autoscroll>,
15604 cx: &mut Context<Self>,
15605 ) {
15606 self.display_map
15607 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15608 if let Some(autoscroll) = autoscroll {
15609 self.request_autoscroll(autoscroll, cx);
15610 }
15611 cx.notify();
15612 }
15613
15614 pub fn remove_blocks(
15615 &mut self,
15616 block_ids: HashSet<CustomBlockId>,
15617 autoscroll: Option<Autoscroll>,
15618 cx: &mut Context<Self>,
15619 ) {
15620 self.display_map.update(cx, |display_map, cx| {
15621 display_map.remove_blocks(block_ids, cx)
15622 });
15623 if let Some(autoscroll) = autoscroll {
15624 self.request_autoscroll(autoscroll, cx);
15625 }
15626 cx.notify();
15627 }
15628
15629 pub fn row_for_block(
15630 &self,
15631 block_id: CustomBlockId,
15632 cx: &mut Context<Self>,
15633 ) -> Option<DisplayRow> {
15634 self.display_map
15635 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15636 }
15637
15638 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15639 self.focused_block = Some(focused_block);
15640 }
15641
15642 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15643 self.focused_block.take()
15644 }
15645
15646 pub fn insert_creases(
15647 &mut self,
15648 creases: impl IntoIterator<Item = Crease<Anchor>>,
15649 cx: &mut Context<Self>,
15650 ) -> Vec<CreaseId> {
15651 self.display_map
15652 .update(cx, |map, cx| map.insert_creases(creases, cx))
15653 }
15654
15655 pub fn remove_creases(
15656 &mut self,
15657 ids: impl IntoIterator<Item = CreaseId>,
15658 cx: &mut Context<Self>,
15659 ) {
15660 self.display_map
15661 .update(cx, |map, cx| map.remove_creases(ids, cx));
15662 }
15663
15664 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15665 self.display_map
15666 .update(cx, |map, cx| map.snapshot(cx))
15667 .longest_row()
15668 }
15669
15670 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15671 self.display_map
15672 .update(cx, |map, cx| map.snapshot(cx))
15673 .max_point()
15674 }
15675
15676 pub fn text(&self, cx: &App) -> String {
15677 self.buffer.read(cx).read(cx).text()
15678 }
15679
15680 pub fn is_empty(&self, cx: &App) -> bool {
15681 self.buffer.read(cx).read(cx).is_empty()
15682 }
15683
15684 pub fn text_option(&self, cx: &App) -> Option<String> {
15685 let text = self.text(cx);
15686 let text = text.trim();
15687
15688 if text.is_empty() {
15689 return None;
15690 }
15691
15692 Some(text.to_string())
15693 }
15694
15695 pub fn set_text(
15696 &mut self,
15697 text: impl Into<Arc<str>>,
15698 window: &mut Window,
15699 cx: &mut Context<Self>,
15700 ) {
15701 self.transact(window, cx, |this, _, cx| {
15702 this.buffer
15703 .read(cx)
15704 .as_singleton()
15705 .expect("you can only call set_text on editors for singleton buffers")
15706 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15707 });
15708 }
15709
15710 pub fn display_text(&self, cx: &mut App) -> String {
15711 self.display_map
15712 .update(cx, |map, cx| map.snapshot(cx))
15713 .text()
15714 }
15715
15716 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15717 let mut wrap_guides = smallvec::smallvec![];
15718
15719 if self.show_wrap_guides == Some(false) {
15720 return wrap_guides;
15721 }
15722
15723 let settings = self.buffer.read(cx).language_settings(cx);
15724 if settings.show_wrap_guides {
15725 match self.soft_wrap_mode(cx) {
15726 SoftWrap::Column(soft_wrap) => {
15727 wrap_guides.push((soft_wrap as usize, true));
15728 }
15729 SoftWrap::Bounded(soft_wrap) => {
15730 wrap_guides.push((soft_wrap as usize, true));
15731 }
15732 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15733 }
15734 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15735 }
15736
15737 wrap_guides
15738 }
15739
15740 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15741 let settings = self.buffer.read(cx).language_settings(cx);
15742 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15743 match mode {
15744 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15745 SoftWrap::None
15746 }
15747 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15748 language_settings::SoftWrap::PreferredLineLength => {
15749 SoftWrap::Column(settings.preferred_line_length)
15750 }
15751 language_settings::SoftWrap::Bounded => {
15752 SoftWrap::Bounded(settings.preferred_line_length)
15753 }
15754 }
15755 }
15756
15757 pub fn set_soft_wrap_mode(
15758 &mut self,
15759 mode: language_settings::SoftWrap,
15760
15761 cx: &mut Context<Self>,
15762 ) {
15763 self.soft_wrap_mode_override = Some(mode);
15764 cx.notify();
15765 }
15766
15767 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15768 self.hard_wrap = hard_wrap;
15769 cx.notify();
15770 }
15771
15772 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15773 self.text_style_refinement = Some(style);
15774 }
15775
15776 /// called by the Element so we know what style we were most recently rendered with.
15777 pub(crate) fn set_style(
15778 &mut self,
15779 style: EditorStyle,
15780 window: &mut Window,
15781 cx: &mut Context<Self>,
15782 ) {
15783 let rem_size = window.rem_size();
15784 self.display_map.update(cx, |map, cx| {
15785 map.set_font(
15786 style.text.font(),
15787 style.text.font_size.to_pixels(rem_size),
15788 cx,
15789 )
15790 });
15791 self.style = Some(style);
15792 }
15793
15794 pub fn style(&self) -> Option<&EditorStyle> {
15795 self.style.as_ref()
15796 }
15797
15798 // Called by the element. This method is not designed to be called outside of the editor
15799 // element's layout code because it does not notify when rewrapping is computed synchronously.
15800 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15801 self.display_map
15802 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15803 }
15804
15805 pub fn set_soft_wrap(&mut self) {
15806 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15807 }
15808
15809 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15810 if self.soft_wrap_mode_override.is_some() {
15811 self.soft_wrap_mode_override.take();
15812 } else {
15813 let soft_wrap = match self.soft_wrap_mode(cx) {
15814 SoftWrap::GitDiff => return,
15815 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15816 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15817 language_settings::SoftWrap::None
15818 }
15819 };
15820 self.soft_wrap_mode_override = Some(soft_wrap);
15821 }
15822 cx.notify();
15823 }
15824
15825 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15826 let Some(workspace) = self.workspace() else {
15827 return;
15828 };
15829 let fs = workspace.read(cx).app_state().fs.clone();
15830 let current_show = TabBarSettings::get_global(cx).show;
15831 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15832 setting.show = Some(!current_show);
15833 });
15834 }
15835
15836 pub fn toggle_indent_guides(
15837 &mut self,
15838 _: &ToggleIndentGuides,
15839 _: &mut Window,
15840 cx: &mut Context<Self>,
15841 ) {
15842 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15843 self.buffer
15844 .read(cx)
15845 .language_settings(cx)
15846 .indent_guides
15847 .enabled
15848 });
15849 self.show_indent_guides = Some(!currently_enabled);
15850 cx.notify();
15851 }
15852
15853 fn should_show_indent_guides(&self) -> Option<bool> {
15854 self.show_indent_guides
15855 }
15856
15857 pub fn toggle_line_numbers(
15858 &mut self,
15859 _: &ToggleLineNumbers,
15860 _: &mut Window,
15861 cx: &mut Context<Self>,
15862 ) {
15863 let mut editor_settings = EditorSettings::get_global(cx).clone();
15864 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15865 EditorSettings::override_global(editor_settings, cx);
15866 }
15867
15868 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15869 if let Some(show_line_numbers) = self.show_line_numbers {
15870 return show_line_numbers;
15871 }
15872 EditorSettings::get_global(cx).gutter.line_numbers
15873 }
15874
15875 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15876 self.use_relative_line_numbers
15877 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15878 }
15879
15880 pub fn toggle_relative_line_numbers(
15881 &mut self,
15882 _: &ToggleRelativeLineNumbers,
15883 _: &mut Window,
15884 cx: &mut Context<Self>,
15885 ) {
15886 let is_relative = self.should_use_relative_line_numbers(cx);
15887 self.set_relative_line_number(Some(!is_relative), cx)
15888 }
15889
15890 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15891 self.use_relative_line_numbers = is_relative;
15892 cx.notify();
15893 }
15894
15895 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15896 self.show_gutter = show_gutter;
15897 cx.notify();
15898 }
15899
15900 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15901 self.show_scrollbars = show_scrollbars;
15902 cx.notify();
15903 }
15904
15905 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15906 self.show_line_numbers = Some(show_line_numbers);
15907 cx.notify();
15908 }
15909
15910 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15911 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15912 cx.notify();
15913 }
15914
15915 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15916 self.show_code_actions = Some(show_code_actions);
15917 cx.notify();
15918 }
15919
15920 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15921 self.show_runnables = Some(show_runnables);
15922 cx.notify();
15923 }
15924
15925 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15926 self.show_breakpoints = Some(show_breakpoints);
15927 cx.notify();
15928 }
15929
15930 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15931 if self.display_map.read(cx).masked != masked {
15932 self.display_map.update(cx, |map, _| map.masked = masked);
15933 }
15934 cx.notify()
15935 }
15936
15937 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15938 self.show_wrap_guides = Some(show_wrap_guides);
15939 cx.notify();
15940 }
15941
15942 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15943 self.show_indent_guides = Some(show_indent_guides);
15944 cx.notify();
15945 }
15946
15947 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15948 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15949 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15950 if let Some(dir) = file.abs_path(cx).parent() {
15951 return Some(dir.to_owned());
15952 }
15953 }
15954
15955 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15956 return Some(project_path.path.to_path_buf());
15957 }
15958 }
15959
15960 None
15961 }
15962
15963 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15964 self.active_excerpt(cx)?
15965 .1
15966 .read(cx)
15967 .file()
15968 .and_then(|f| f.as_local())
15969 }
15970
15971 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15972 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15973 let buffer = buffer.read(cx);
15974 if let Some(project_path) = buffer.project_path(cx) {
15975 let project = self.project.as_ref()?.read(cx);
15976 project.absolute_path(&project_path, cx)
15977 } else {
15978 buffer
15979 .file()
15980 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15981 }
15982 })
15983 }
15984
15985 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15986 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15987 let project_path = buffer.read(cx).project_path(cx)?;
15988 let project = self.project.as_ref()?.read(cx);
15989 let entry = project.entry_for_path(&project_path, cx)?;
15990 let path = entry.path.to_path_buf();
15991 Some(path)
15992 })
15993 }
15994
15995 pub fn reveal_in_finder(
15996 &mut self,
15997 _: &RevealInFileManager,
15998 _window: &mut Window,
15999 cx: &mut Context<Self>,
16000 ) {
16001 if let Some(target) = self.target_file(cx) {
16002 cx.reveal_path(&target.abs_path(cx));
16003 }
16004 }
16005
16006 pub fn copy_path(
16007 &mut self,
16008 _: &zed_actions::workspace::CopyPath,
16009 _window: &mut Window,
16010 cx: &mut Context<Self>,
16011 ) {
16012 if let Some(path) = self.target_file_abs_path(cx) {
16013 if let Some(path) = path.to_str() {
16014 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16015 }
16016 }
16017 }
16018
16019 pub fn copy_relative_path(
16020 &mut self,
16021 _: &zed_actions::workspace::CopyRelativePath,
16022 _window: &mut Window,
16023 cx: &mut Context<Self>,
16024 ) {
16025 if let Some(path) = self.target_file_path(cx) {
16026 if let Some(path) = path.to_str() {
16027 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16028 }
16029 }
16030 }
16031
16032 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16033 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16034 buffer.read(cx).project_path(cx)
16035 } else {
16036 None
16037 }
16038 }
16039
16040 // Returns true if the editor handled a go-to-line request
16041 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16042 maybe!({
16043 let breakpoint_store = self.breakpoint_store.as_ref()?;
16044
16045 let Some((_, _, active_position)) =
16046 breakpoint_store.read(cx).active_position().cloned()
16047 else {
16048 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16049 return None;
16050 };
16051
16052 let snapshot = self
16053 .project
16054 .as_ref()?
16055 .read(cx)
16056 .buffer_for_id(active_position.buffer_id?, cx)?
16057 .read(cx)
16058 .snapshot();
16059
16060 let mut handled = false;
16061 for (id, ExcerptRange { context, .. }) in self
16062 .buffer
16063 .read(cx)
16064 .excerpts_for_buffer(active_position.buffer_id?, cx)
16065 {
16066 if context.start.cmp(&active_position, &snapshot).is_ge()
16067 || context.end.cmp(&active_position, &snapshot).is_lt()
16068 {
16069 continue;
16070 }
16071 let snapshot = self.buffer.read(cx).snapshot(cx);
16072 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16073
16074 handled = true;
16075 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16076 self.go_to_line::<DebugCurrentRowHighlight>(
16077 multibuffer_anchor,
16078 Some(cx.theme().colors().editor_debugger_active_line_background),
16079 window,
16080 cx,
16081 );
16082
16083 cx.notify();
16084 }
16085 handled.then_some(())
16086 })
16087 .is_some()
16088 }
16089
16090 pub fn copy_file_name_without_extension(
16091 &mut self,
16092 _: &CopyFileNameWithoutExtension,
16093 _: &mut Window,
16094 cx: &mut Context<Self>,
16095 ) {
16096 if let Some(file) = self.target_file(cx) {
16097 if let Some(file_stem) = file.path().file_stem() {
16098 if let Some(name) = file_stem.to_str() {
16099 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16100 }
16101 }
16102 }
16103 }
16104
16105 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16106 if let Some(file) = self.target_file(cx) {
16107 if let Some(file_name) = file.path().file_name() {
16108 if let Some(name) = file_name.to_str() {
16109 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16110 }
16111 }
16112 }
16113 }
16114
16115 pub fn toggle_git_blame(
16116 &mut self,
16117 _: &::git::Blame,
16118 window: &mut Window,
16119 cx: &mut Context<Self>,
16120 ) {
16121 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16122
16123 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16124 self.start_git_blame(true, window, cx);
16125 }
16126
16127 cx.notify();
16128 }
16129
16130 pub fn toggle_git_blame_inline(
16131 &mut self,
16132 _: &ToggleGitBlameInline,
16133 window: &mut Window,
16134 cx: &mut Context<Self>,
16135 ) {
16136 self.toggle_git_blame_inline_internal(true, window, cx);
16137 cx.notify();
16138 }
16139
16140 pub fn open_git_blame_commit(
16141 &mut self,
16142 _: &OpenGitBlameCommit,
16143 window: &mut Window,
16144 cx: &mut Context<Self>,
16145 ) {
16146 self.open_git_blame_commit_internal(window, cx);
16147 }
16148
16149 fn open_git_blame_commit_internal(
16150 &mut self,
16151 window: &mut Window,
16152 cx: &mut Context<Self>,
16153 ) -> Option<()> {
16154 let blame = self.blame.as_ref()?;
16155 let snapshot = self.snapshot(window, cx);
16156 let cursor = self.selections.newest::<Point>(cx).head();
16157 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16158 let blame_entry = blame
16159 .update(cx, |blame, cx| {
16160 blame
16161 .blame_for_rows(
16162 &[RowInfo {
16163 buffer_id: Some(buffer.remote_id()),
16164 buffer_row: Some(point.row),
16165 ..Default::default()
16166 }],
16167 cx,
16168 )
16169 .next()
16170 })
16171 .flatten()?;
16172 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16173 let repo = blame.read(cx).repository(cx)?;
16174 let workspace = self.workspace()?.downgrade();
16175 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16176 None
16177 }
16178
16179 pub fn git_blame_inline_enabled(&self) -> bool {
16180 self.git_blame_inline_enabled
16181 }
16182
16183 pub fn toggle_selection_menu(
16184 &mut self,
16185 _: &ToggleSelectionMenu,
16186 _: &mut Window,
16187 cx: &mut Context<Self>,
16188 ) {
16189 self.show_selection_menu = self
16190 .show_selection_menu
16191 .map(|show_selections_menu| !show_selections_menu)
16192 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16193
16194 cx.notify();
16195 }
16196
16197 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16198 self.show_selection_menu
16199 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16200 }
16201
16202 fn start_git_blame(
16203 &mut self,
16204 user_triggered: bool,
16205 window: &mut Window,
16206 cx: &mut Context<Self>,
16207 ) {
16208 if let Some(project) = self.project.as_ref() {
16209 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16210 return;
16211 };
16212
16213 if buffer.read(cx).file().is_none() {
16214 return;
16215 }
16216
16217 let focused = self.focus_handle(cx).contains_focused(window, cx);
16218
16219 let project = project.clone();
16220 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16221 self.blame_subscription =
16222 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16223 self.blame = Some(blame);
16224 }
16225 }
16226
16227 fn toggle_git_blame_inline_internal(
16228 &mut self,
16229 user_triggered: bool,
16230 window: &mut Window,
16231 cx: &mut Context<Self>,
16232 ) {
16233 if self.git_blame_inline_enabled {
16234 self.git_blame_inline_enabled = false;
16235 self.show_git_blame_inline = false;
16236 self.show_git_blame_inline_delay_task.take();
16237 } else {
16238 self.git_blame_inline_enabled = true;
16239 self.start_git_blame_inline(user_triggered, window, cx);
16240 }
16241
16242 cx.notify();
16243 }
16244
16245 fn start_git_blame_inline(
16246 &mut self,
16247 user_triggered: bool,
16248 window: &mut Window,
16249 cx: &mut Context<Self>,
16250 ) {
16251 self.start_git_blame(user_triggered, window, cx);
16252
16253 if ProjectSettings::get_global(cx)
16254 .git
16255 .inline_blame_delay()
16256 .is_some()
16257 {
16258 self.start_inline_blame_timer(window, cx);
16259 } else {
16260 self.show_git_blame_inline = true
16261 }
16262 }
16263
16264 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16265 self.blame.as_ref()
16266 }
16267
16268 pub fn show_git_blame_gutter(&self) -> bool {
16269 self.show_git_blame_gutter
16270 }
16271
16272 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16273 self.show_git_blame_gutter && self.has_blame_entries(cx)
16274 }
16275
16276 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16277 self.show_git_blame_inline
16278 && (self.focus_handle.is_focused(window)
16279 || self
16280 .git_blame_inline_tooltip
16281 .as_ref()
16282 .and_then(|t| t.upgrade())
16283 .is_some())
16284 && !self.newest_selection_head_on_empty_line(cx)
16285 && self.has_blame_entries(cx)
16286 }
16287
16288 fn has_blame_entries(&self, cx: &App) -> bool {
16289 self.blame()
16290 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16291 }
16292
16293 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16294 let cursor_anchor = self.selections.newest_anchor().head();
16295
16296 let snapshot = self.buffer.read(cx).snapshot(cx);
16297 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16298
16299 snapshot.line_len(buffer_row) == 0
16300 }
16301
16302 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16303 let buffer_and_selection = maybe!({
16304 let selection = self.selections.newest::<Point>(cx);
16305 let selection_range = selection.range();
16306
16307 let multi_buffer = self.buffer().read(cx);
16308 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16309 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16310
16311 let (buffer, range, _) = if selection.reversed {
16312 buffer_ranges.first()
16313 } else {
16314 buffer_ranges.last()
16315 }?;
16316
16317 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16318 ..text::ToPoint::to_point(&range.end, &buffer).row;
16319 Some((
16320 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16321 selection,
16322 ))
16323 });
16324
16325 let Some((buffer, selection)) = buffer_and_selection else {
16326 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16327 };
16328
16329 let Some(project) = self.project.as_ref() else {
16330 return Task::ready(Err(anyhow!("editor does not have project")));
16331 };
16332
16333 project.update(cx, |project, cx| {
16334 project.get_permalink_to_line(&buffer, selection, cx)
16335 })
16336 }
16337
16338 pub fn copy_permalink_to_line(
16339 &mut self,
16340 _: &CopyPermalinkToLine,
16341 window: &mut Window,
16342 cx: &mut Context<Self>,
16343 ) {
16344 let permalink_task = self.get_permalink_to_line(cx);
16345 let workspace = self.workspace();
16346
16347 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16348 Ok(permalink) => {
16349 cx.update(|_, cx| {
16350 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16351 })
16352 .ok();
16353 }
16354 Err(err) => {
16355 let message = format!("Failed to copy permalink: {err}");
16356
16357 Err::<(), anyhow::Error>(err).log_err();
16358
16359 if let Some(workspace) = workspace {
16360 workspace
16361 .update_in(cx, |workspace, _, cx| {
16362 struct CopyPermalinkToLine;
16363
16364 workspace.show_toast(
16365 Toast::new(
16366 NotificationId::unique::<CopyPermalinkToLine>(),
16367 message,
16368 ),
16369 cx,
16370 )
16371 })
16372 .ok();
16373 }
16374 }
16375 })
16376 .detach();
16377 }
16378
16379 pub fn copy_file_location(
16380 &mut self,
16381 _: &CopyFileLocation,
16382 _: &mut Window,
16383 cx: &mut Context<Self>,
16384 ) {
16385 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16386 if let Some(file) = self.target_file(cx) {
16387 if let Some(path) = file.path().to_str() {
16388 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16389 }
16390 }
16391 }
16392
16393 pub fn open_permalink_to_line(
16394 &mut self,
16395 _: &OpenPermalinkToLine,
16396 window: &mut Window,
16397 cx: &mut Context<Self>,
16398 ) {
16399 let permalink_task = self.get_permalink_to_line(cx);
16400 let workspace = self.workspace();
16401
16402 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16403 Ok(permalink) => {
16404 cx.update(|_, cx| {
16405 cx.open_url(permalink.as_ref());
16406 })
16407 .ok();
16408 }
16409 Err(err) => {
16410 let message = format!("Failed to open permalink: {err}");
16411
16412 Err::<(), anyhow::Error>(err).log_err();
16413
16414 if let Some(workspace) = workspace {
16415 workspace
16416 .update(cx, |workspace, cx| {
16417 struct OpenPermalinkToLine;
16418
16419 workspace.show_toast(
16420 Toast::new(
16421 NotificationId::unique::<OpenPermalinkToLine>(),
16422 message,
16423 ),
16424 cx,
16425 )
16426 })
16427 .ok();
16428 }
16429 }
16430 })
16431 .detach();
16432 }
16433
16434 pub fn insert_uuid_v4(
16435 &mut self,
16436 _: &InsertUuidV4,
16437 window: &mut Window,
16438 cx: &mut Context<Self>,
16439 ) {
16440 self.insert_uuid(UuidVersion::V4, window, cx);
16441 }
16442
16443 pub fn insert_uuid_v7(
16444 &mut self,
16445 _: &InsertUuidV7,
16446 window: &mut Window,
16447 cx: &mut Context<Self>,
16448 ) {
16449 self.insert_uuid(UuidVersion::V7, window, cx);
16450 }
16451
16452 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16453 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16454 self.transact(window, cx, |this, window, cx| {
16455 let edits = this
16456 .selections
16457 .all::<Point>(cx)
16458 .into_iter()
16459 .map(|selection| {
16460 let uuid = match version {
16461 UuidVersion::V4 => uuid::Uuid::new_v4(),
16462 UuidVersion::V7 => uuid::Uuid::now_v7(),
16463 };
16464
16465 (selection.range(), uuid.to_string())
16466 });
16467 this.edit(edits, cx);
16468 this.refresh_inline_completion(true, false, window, cx);
16469 });
16470 }
16471
16472 pub fn open_selections_in_multibuffer(
16473 &mut self,
16474 _: &OpenSelectionsInMultibuffer,
16475 window: &mut Window,
16476 cx: &mut Context<Self>,
16477 ) {
16478 let multibuffer = self.buffer.read(cx);
16479
16480 let Some(buffer) = multibuffer.as_singleton() else {
16481 return;
16482 };
16483
16484 let Some(workspace) = self.workspace() else {
16485 return;
16486 };
16487
16488 let locations = self
16489 .selections
16490 .disjoint_anchors()
16491 .iter()
16492 .map(|range| Location {
16493 buffer: buffer.clone(),
16494 range: range.start.text_anchor..range.end.text_anchor,
16495 })
16496 .collect::<Vec<_>>();
16497
16498 let title = multibuffer.title(cx).to_string();
16499
16500 cx.spawn_in(window, async move |_, cx| {
16501 workspace.update_in(cx, |workspace, window, cx| {
16502 Self::open_locations_in_multibuffer(
16503 workspace,
16504 locations,
16505 format!("Selections for '{title}'"),
16506 false,
16507 MultibufferSelectionMode::All,
16508 window,
16509 cx,
16510 );
16511 })
16512 })
16513 .detach();
16514 }
16515
16516 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16517 /// last highlight added will be used.
16518 ///
16519 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16520 pub fn highlight_rows<T: 'static>(
16521 &mut self,
16522 range: Range<Anchor>,
16523 color: Hsla,
16524 should_autoscroll: bool,
16525 cx: &mut Context<Self>,
16526 ) {
16527 let snapshot = self.buffer().read(cx).snapshot(cx);
16528 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16529 let ix = row_highlights.binary_search_by(|highlight| {
16530 Ordering::Equal
16531 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16532 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16533 });
16534
16535 if let Err(mut ix) = ix {
16536 let index = post_inc(&mut self.highlight_order);
16537
16538 // If this range intersects with the preceding highlight, then merge it with
16539 // the preceding highlight. Otherwise insert a new highlight.
16540 let mut merged = false;
16541 if ix > 0 {
16542 let prev_highlight = &mut row_highlights[ix - 1];
16543 if prev_highlight
16544 .range
16545 .end
16546 .cmp(&range.start, &snapshot)
16547 .is_ge()
16548 {
16549 ix -= 1;
16550 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16551 prev_highlight.range.end = range.end;
16552 }
16553 merged = true;
16554 prev_highlight.index = index;
16555 prev_highlight.color = color;
16556 prev_highlight.should_autoscroll = should_autoscroll;
16557 }
16558 }
16559
16560 if !merged {
16561 row_highlights.insert(
16562 ix,
16563 RowHighlight {
16564 range: range.clone(),
16565 index,
16566 color,
16567 should_autoscroll,
16568 },
16569 );
16570 }
16571
16572 // If any of the following highlights intersect with this one, merge them.
16573 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16574 let highlight = &row_highlights[ix];
16575 if next_highlight
16576 .range
16577 .start
16578 .cmp(&highlight.range.end, &snapshot)
16579 .is_le()
16580 {
16581 if next_highlight
16582 .range
16583 .end
16584 .cmp(&highlight.range.end, &snapshot)
16585 .is_gt()
16586 {
16587 row_highlights[ix].range.end = next_highlight.range.end;
16588 }
16589 row_highlights.remove(ix + 1);
16590 } else {
16591 break;
16592 }
16593 }
16594 }
16595 }
16596
16597 /// Remove any highlighted row ranges of the given type that intersect the
16598 /// given ranges.
16599 pub fn remove_highlighted_rows<T: 'static>(
16600 &mut self,
16601 ranges_to_remove: Vec<Range<Anchor>>,
16602 cx: &mut Context<Self>,
16603 ) {
16604 let snapshot = self.buffer().read(cx).snapshot(cx);
16605 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16606 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16607 row_highlights.retain(|highlight| {
16608 while let Some(range_to_remove) = ranges_to_remove.peek() {
16609 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16610 Ordering::Less | Ordering::Equal => {
16611 ranges_to_remove.next();
16612 }
16613 Ordering::Greater => {
16614 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16615 Ordering::Less | Ordering::Equal => {
16616 return false;
16617 }
16618 Ordering::Greater => break,
16619 }
16620 }
16621 }
16622 }
16623
16624 true
16625 })
16626 }
16627
16628 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16629 pub fn clear_row_highlights<T: 'static>(&mut self) {
16630 self.highlighted_rows.remove(&TypeId::of::<T>());
16631 }
16632
16633 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16634 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16635 self.highlighted_rows
16636 .get(&TypeId::of::<T>())
16637 .map_or(&[] as &[_], |vec| vec.as_slice())
16638 .iter()
16639 .map(|highlight| (highlight.range.clone(), highlight.color))
16640 }
16641
16642 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16643 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16644 /// Allows to ignore certain kinds of highlights.
16645 pub fn highlighted_display_rows(
16646 &self,
16647 window: &mut Window,
16648 cx: &mut App,
16649 ) -> BTreeMap<DisplayRow, LineHighlight> {
16650 let snapshot = self.snapshot(window, cx);
16651 let mut used_highlight_orders = HashMap::default();
16652 self.highlighted_rows
16653 .iter()
16654 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16655 .fold(
16656 BTreeMap::<DisplayRow, LineHighlight>::new(),
16657 |mut unique_rows, highlight| {
16658 let start = highlight.range.start.to_display_point(&snapshot);
16659 let end = highlight.range.end.to_display_point(&snapshot);
16660 let start_row = start.row().0;
16661 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16662 && end.column() == 0
16663 {
16664 end.row().0.saturating_sub(1)
16665 } else {
16666 end.row().0
16667 };
16668 for row in start_row..=end_row {
16669 let used_index =
16670 used_highlight_orders.entry(row).or_insert(highlight.index);
16671 if highlight.index >= *used_index {
16672 *used_index = highlight.index;
16673 unique_rows.insert(DisplayRow(row), highlight.color.into());
16674 }
16675 }
16676 unique_rows
16677 },
16678 )
16679 }
16680
16681 pub fn highlighted_display_row_for_autoscroll(
16682 &self,
16683 snapshot: &DisplaySnapshot,
16684 ) -> Option<DisplayRow> {
16685 self.highlighted_rows
16686 .values()
16687 .flat_map(|highlighted_rows| highlighted_rows.iter())
16688 .filter_map(|highlight| {
16689 if highlight.should_autoscroll {
16690 Some(highlight.range.start.to_display_point(snapshot).row())
16691 } else {
16692 None
16693 }
16694 })
16695 .min()
16696 }
16697
16698 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16699 self.highlight_background::<SearchWithinRange>(
16700 ranges,
16701 |colors| colors.editor_document_highlight_read_background,
16702 cx,
16703 )
16704 }
16705
16706 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16707 self.breadcrumb_header = Some(new_header);
16708 }
16709
16710 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16711 self.clear_background_highlights::<SearchWithinRange>(cx);
16712 }
16713
16714 pub fn highlight_background<T: 'static>(
16715 &mut self,
16716 ranges: &[Range<Anchor>],
16717 color_fetcher: fn(&ThemeColors) -> Hsla,
16718 cx: &mut Context<Self>,
16719 ) {
16720 self.background_highlights
16721 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16722 self.scrollbar_marker_state.dirty = true;
16723 cx.notify();
16724 }
16725
16726 pub fn clear_background_highlights<T: 'static>(
16727 &mut self,
16728 cx: &mut Context<Self>,
16729 ) -> Option<BackgroundHighlight> {
16730 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16731 if !text_highlights.1.is_empty() {
16732 self.scrollbar_marker_state.dirty = true;
16733 cx.notify();
16734 }
16735 Some(text_highlights)
16736 }
16737
16738 pub fn highlight_gutter<T: 'static>(
16739 &mut self,
16740 ranges: &[Range<Anchor>],
16741 color_fetcher: fn(&App) -> Hsla,
16742 cx: &mut Context<Self>,
16743 ) {
16744 self.gutter_highlights
16745 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16746 cx.notify();
16747 }
16748
16749 pub fn clear_gutter_highlights<T: 'static>(
16750 &mut self,
16751 cx: &mut Context<Self>,
16752 ) -> Option<GutterHighlight> {
16753 cx.notify();
16754 self.gutter_highlights.remove(&TypeId::of::<T>())
16755 }
16756
16757 #[cfg(feature = "test-support")]
16758 pub fn all_text_background_highlights(
16759 &self,
16760 window: &mut Window,
16761 cx: &mut Context<Self>,
16762 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16763 let snapshot = self.snapshot(window, cx);
16764 let buffer = &snapshot.buffer_snapshot;
16765 let start = buffer.anchor_before(0);
16766 let end = buffer.anchor_after(buffer.len());
16767 let theme = cx.theme().colors();
16768 self.background_highlights_in_range(start..end, &snapshot, theme)
16769 }
16770
16771 #[cfg(feature = "test-support")]
16772 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16773 let snapshot = self.buffer().read(cx).snapshot(cx);
16774
16775 let highlights = self
16776 .background_highlights
16777 .get(&TypeId::of::<items::BufferSearchHighlights>());
16778
16779 if let Some((_color, ranges)) = highlights {
16780 ranges
16781 .iter()
16782 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16783 .collect_vec()
16784 } else {
16785 vec![]
16786 }
16787 }
16788
16789 fn document_highlights_for_position<'a>(
16790 &'a self,
16791 position: Anchor,
16792 buffer: &'a MultiBufferSnapshot,
16793 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16794 let read_highlights = self
16795 .background_highlights
16796 .get(&TypeId::of::<DocumentHighlightRead>())
16797 .map(|h| &h.1);
16798 let write_highlights = self
16799 .background_highlights
16800 .get(&TypeId::of::<DocumentHighlightWrite>())
16801 .map(|h| &h.1);
16802 let left_position = position.bias_left(buffer);
16803 let right_position = position.bias_right(buffer);
16804 read_highlights
16805 .into_iter()
16806 .chain(write_highlights)
16807 .flat_map(move |ranges| {
16808 let start_ix = match ranges.binary_search_by(|probe| {
16809 let cmp = probe.end.cmp(&left_position, buffer);
16810 if cmp.is_ge() {
16811 Ordering::Greater
16812 } else {
16813 Ordering::Less
16814 }
16815 }) {
16816 Ok(i) | Err(i) => i,
16817 };
16818
16819 ranges[start_ix..]
16820 .iter()
16821 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16822 })
16823 }
16824
16825 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16826 self.background_highlights
16827 .get(&TypeId::of::<T>())
16828 .map_or(false, |(_, highlights)| !highlights.is_empty())
16829 }
16830
16831 pub fn background_highlights_in_range(
16832 &self,
16833 search_range: Range<Anchor>,
16834 display_snapshot: &DisplaySnapshot,
16835 theme: &ThemeColors,
16836 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16837 let mut results = Vec::new();
16838 for (color_fetcher, ranges) in self.background_highlights.values() {
16839 let color = color_fetcher(theme);
16840 let start_ix = match ranges.binary_search_by(|probe| {
16841 let cmp = probe
16842 .end
16843 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16844 if cmp.is_gt() {
16845 Ordering::Greater
16846 } else {
16847 Ordering::Less
16848 }
16849 }) {
16850 Ok(i) | Err(i) => i,
16851 };
16852 for range in &ranges[start_ix..] {
16853 if range
16854 .start
16855 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16856 .is_ge()
16857 {
16858 break;
16859 }
16860
16861 let start = range.start.to_display_point(display_snapshot);
16862 let end = range.end.to_display_point(display_snapshot);
16863 results.push((start..end, color))
16864 }
16865 }
16866 results
16867 }
16868
16869 pub fn background_highlight_row_ranges<T: 'static>(
16870 &self,
16871 search_range: Range<Anchor>,
16872 display_snapshot: &DisplaySnapshot,
16873 count: usize,
16874 ) -> Vec<RangeInclusive<DisplayPoint>> {
16875 let mut results = Vec::new();
16876 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16877 return vec![];
16878 };
16879
16880 let start_ix = match ranges.binary_search_by(|probe| {
16881 let cmp = probe
16882 .end
16883 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16884 if cmp.is_gt() {
16885 Ordering::Greater
16886 } else {
16887 Ordering::Less
16888 }
16889 }) {
16890 Ok(i) | Err(i) => i,
16891 };
16892 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16893 if let (Some(start_display), Some(end_display)) = (start, end) {
16894 results.push(
16895 start_display.to_display_point(display_snapshot)
16896 ..=end_display.to_display_point(display_snapshot),
16897 );
16898 }
16899 };
16900 let mut start_row: Option<Point> = None;
16901 let mut end_row: Option<Point> = None;
16902 if ranges.len() > count {
16903 return Vec::new();
16904 }
16905 for range in &ranges[start_ix..] {
16906 if range
16907 .start
16908 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16909 .is_ge()
16910 {
16911 break;
16912 }
16913 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16914 if let Some(current_row) = &end_row {
16915 if end.row == current_row.row {
16916 continue;
16917 }
16918 }
16919 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16920 if start_row.is_none() {
16921 assert_eq!(end_row, None);
16922 start_row = Some(start);
16923 end_row = Some(end);
16924 continue;
16925 }
16926 if let Some(current_end) = end_row.as_mut() {
16927 if start.row > current_end.row + 1 {
16928 push_region(start_row, end_row);
16929 start_row = Some(start);
16930 end_row = Some(end);
16931 } else {
16932 // Merge two hunks.
16933 *current_end = end;
16934 }
16935 } else {
16936 unreachable!();
16937 }
16938 }
16939 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16940 push_region(start_row, end_row);
16941 results
16942 }
16943
16944 pub fn gutter_highlights_in_range(
16945 &self,
16946 search_range: Range<Anchor>,
16947 display_snapshot: &DisplaySnapshot,
16948 cx: &App,
16949 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16950 let mut results = Vec::new();
16951 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16952 let color = color_fetcher(cx);
16953 let start_ix = match ranges.binary_search_by(|probe| {
16954 let cmp = probe
16955 .end
16956 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16957 if cmp.is_gt() {
16958 Ordering::Greater
16959 } else {
16960 Ordering::Less
16961 }
16962 }) {
16963 Ok(i) | Err(i) => i,
16964 };
16965 for range in &ranges[start_ix..] {
16966 if range
16967 .start
16968 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16969 .is_ge()
16970 {
16971 break;
16972 }
16973
16974 let start = range.start.to_display_point(display_snapshot);
16975 let end = range.end.to_display_point(display_snapshot);
16976 results.push((start..end, color))
16977 }
16978 }
16979 results
16980 }
16981
16982 /// Get the text ranges corresponding to the redaction query
16983 pub fn redacted_ranges(
16984 &self,
16985 search_range: Range<Anchor>,
16986 display_snapshot: &DisplaySnapshot,
16987 cx: &App,
16988 ) -> Vec<Range<DisplayPoint>> {
16989 display_snapshot
16990 .buffer_snapshot
16991 .redacted_ranges(search_range, |file| {
16992 if let Some(file) = file {
16993 file.is_private()
16994 && EditorSettings::get(
16995 Some(SettingsLocation {
16996 worktree_id: file.worktree_id(cx),
16997 path: file.path().as_ref(),
16998 }),
16999 cx,
17000 )
17001 .redact_private_values
17002 } else {
17003 false
17004 }
17005 })
17006 .map(|range| {
17007 range.start.to_display_point(display_snapshot)
17008 ..range.end.to_display_point(display_snapshot)
17009 })
17010 .collect()
17011 }
17012
17013 pub fn highlight_text<T: 'static>(
17014 &mut self,
17015 ranges: Vec<Range<Anchor>>,
17016 style: HighlightStyle,
17017 cx: &mut Context<Self>,
17018 ) {
17019 self.display_map.update(cx, |map, _| {
17020 map.highlight_text(TypeId::of::<T>(), ranges, style)
17021 });
17022 cx.notify();
17023 }
17024
17025 pub(crate) fn highlight_inlays<T: 'static>(
17026 &mut self,
17027 highlights: Vec<InlayHighlight>,
17028 style: HighlightStyle,
17029 cx: &mut Context<Self>,
17030 ) {
17031 self.display_map.update(cx, |map, _| {
17032 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17033 });
17034 cx.notify();
17035 }
17036
17037 pub fn text_highlights<'a, T: 'static>(
17038 &'a self,
17039 cx: &'a App,
17040 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17041 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17042 }
17043
17044 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17045 let cleared = self
17046 .display_map
17047 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17048 if cleared {
17049 cx.notify();
17050 }
17051 }
17052
17053 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17054 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17055 && self.focus_handle.is_focused(window)
17056 }
17057
17058 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17059 self.show_cursor_when_unfocused = is_enabled;
17060 cx.notify();
17061 }
17062
17063 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17064 cx.notify();
17065 }
17066
17067 fn on_buffer_event(
17068 &mut self,
17069 multibuffer: &Entity<MultiBuffer>,
17070 event: &multi_buffer::Event,
17071 window: &mut Window,
17072 cx: &mut Context<Self>,
17073 ) {
17074 match event {
17075 multi_buffer::Event::Edited {
17076 singleton_buffer_edited,
17077 edited_buffer: buffer_edited,
17078 } => {
17079 self.scrollbar_marker_state.dirty = true;
17080 self.active_indent_guides_state.dirty = true;
17081 self.refresh_active_diagnostics(cx);
17082 self.refresh_code_actions(window, cx);
17083 if self.has_active_inline_completion() {
17084 self.update_visible_inline_completion(window, cx);
17085 }
17086 if let Some(buffer) = buffer_edited {
17087 let buffer_id = buffer.read(cx).remote_id();
17088 if !self.registered_buffers.contains_key(&buffer_id) {
17089 if let Some(project) = self.project.as_ref() {
17090 project.update(cx, |project, cx| {
17091 self.registered_buffers.insert(
17092 buffer_id,
17093 project.register_buffer_with_language_servers(&buffer, cx),
17094 );
17095 })
17096 }
17097 }
17098 }
17099 cx.emit(EditorEvent::BufferEdited);
17100 cx.emit(SearchEvent::MatchesInvalidated);
17101 if *singleton_buffer_edited {
17102 if let Some(project) = &self.project {
17103 #[allow(clippy::mutable_key_type)]
17104 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17105 multibuffer
17106 .all_buffers()
17107 .into_iter()
17108 .filter_map(|buffer| {
17109 buffer.update(cx, |buffer, cx| {
17110 let language = buffer.language()?;
17111 let should_discard = project.update(cx, |project, cx| {
17112 project.is_local()
17113 && !project.has_language_servers_for(buffer, cx)
17114 });
17115 should_discard.not().then_some(language.clone())
17116 })
17117 })
17118 .collect::<HashSet<_>>()
17119 });
17120 if !languages_affected.is_empty() {
17121 self.refresh_inlay_hints(
17122 InlayHintRefreshReason::BufferEdited(languages_affected),
17123 cx,
17124 );
17125 }
17126 }
17127 }
17128
17129 let Some(project) = &self.project else { return };
17130 let (telemetry, is_via_ssh) = {
17131 let project = project.read(cx);
17132 let telemetry = project.client().telemetry().clone();
17133 let is_via_ssh = project.is_via_ssh();
17134 (telemetry, is_via_ssh)
17135 };
17136 refresh_linked_ranges(self, window, cx);
17137 telemetry.log_edit_event("editor", is_via_ssh);
17138 }
17139 multi_buffer::Event::ExcerptsAdded {
17140 buffer,
17141 predecessor,
17142 excerpts,
17143 } => {
17144 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17145 let buffer_id = buffer.read(cx).remote_id();
17146 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17147 if let Some(project) = &self.project {
17148 get_uncommitted_diff_for_buffer(
17149 project,
17150 [buffer.clone()],
17151 self.buffer.clone(),
17152 cx,
17153 )
17154 .detach();
17155 }
17156 }
17157 cx.emit(EditorEvent::ExcerptsAdded {
17158 buffer: buffer.clone(),
17159 predecessor: *predecessor,
17160 excerpts: excerpts.clone(),
17161 });
17162 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17163 }
17164 multi_buffer::Event::ExcerptsRemoved { ids } => {
17165 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17166 let buffer = self.buffer.read(cx);
17167 self.registered_buffers
17168 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17169 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17170 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17171 }
17172 multi_buffer::Event::ExcerptsEdited {
17173 excerpt_ids,
17174 buffer_ids,
17175 } => {
17176 self.display_map.update(cx, |map, cx| {
17177 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17178 });
17179 cx.emit(EditorEvent::ExcerptsEdited {
17180 ids: excerpt_ids.clone(),
17181 })
17182 }
17183 multi_buffer::Event::ExcerptsExpanded { ids } => {
17184 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17185 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17186 }
17187 multi_buffer::Event::Reparsed(buffer_id) => {
17188 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17189 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17190
17191 cx.emit(EditorEvent::Reparsed(*buffer_id));
17192 }
17193 multi_buffer::Event::DiffHunksToggled => {
17194 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17195 }
17196 multi_buffer::Event::LanguageChanged(buffer_id) => {
17197 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17198 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17199 cx.emit(EditorEvent::Reparsed(*buffer_id));
17200 cx.notify();
17201 }
17202 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17203 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17204 multi_buffer::Event::FileHandleChanged
17205 | multi_buffer::Event::Reloaded
17206 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17207 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17208 multi_buffer::Event::DiagnosticsUpdated => {
17209 self.refresh_active_diagnostics(cx);
17210 self.refresh_inline_diagnostics(true, window, cx);
17211 self.scrollbar_marker_state.dirty = true;
17212 cx.notify();
17213 }
17214 _ => {}
17215 };
17216 }
17217
17218 fn on_display_map_changed(
17219 &mut self,
17220 _: Entity<DisplayMap>,
17221 _: &mut Window,
17222 cx: &mut Context<Self>,
17223 ) {
17224 cx.notify();
17225 }
17226
17227 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17228 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17229 self.update_edit_prediction_settings(cx);
17230 self.refresh_inline_completion(true, false, window, cx);
17231 self.refresh_inlay_hints(
17232 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17233 self.selections.newest_anchor().head(),
17234 &self.buffer.read(cx).snapshot(cx),
17235 cx,
17236 )),
17237 cx,
17238 );
17239
17240 let old_cursor_shape = self.cursor_shape;
17241
17242 {
17243 let editor_settings = EditorSettings::get_global(cx);
17244 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17245 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17246 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17247 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17248 }
17249
17250 if old_cursor_shape != self.cursor_shape {
17251 cx.emit(EditorEvent::CursorShapeChanged);
17252 }
17253
17254 let project_settings = ProjectSettings::get_global(cx);
17255 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17256
17257 if self.mode.is_full() {
17258 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17259 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17260 if self.show_inline_diagnostics != show_inline_diagnostics {
17261 self.show_inline_diagnostics = show_inline_diagnostics;
17262 self.refresh_inline_diagnostics(false, window, cx);
17263 }
17264
17265 if self.git_blame_inline_enabled != inline_blame_enabled {
17266 self.toggle_git_blame_inline_internal(false, window, cx);
17267 }
17268 }
17269
17270 cx.notify();
17271 }
17272
17273 pub fn set_searchable(&mut self, searchable: bool) {
17274 self.searchable = searchable;
17275 }
17276
17277 pub fn searchable(&self) -> bool {
17278 self.searchable
17279 }
17280
17281 fn open_proposed_changes_editor(
17282 &mut self,
17283 _: &OpenProposedChangesEditor,
17284 window: &mut Window,
17285 cx: &mut Context<Self>,
17286 ) {
17287 let Some(workspace) = self.workspace() else {
17288 cx.propagate();
17289 return;
17290 };
17291
17292 let selections = self.selections.all::<usize>(cx);
17293 let multi_buffer = self.buffer.read(cx);
17294 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17295 let mut new_selections_by_buffer = HashMap::default();
17296 for selection in selections {
17297 for (buffer, range, _) in
17298 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17299 {
17300 let mut range = range.to_point(buffer);
17301 range.start.column = 0;
17302 range.end.column = buffer.line_len(range.end.row);
17303 new_selections_by_buffer
17304 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17305 .or_insert(Vec::new())
17306 .push(range)
17307 }
17308 }
17309
17310 let proposed_changes_buffers = new_selections_by_buffer
17311 .into_iter()
17312 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17313 .collect::<Vec<_>>();
17314 let proposed_changes_editor = cx.new(|cx| {
17315 ProposedChangesEditor::new(
17316 "Proposed changes",
17317 proposed_changes_buffers,
17318 self.project.clone(),
17319 window,
17320 cx,
17321 )
17322 });
17323
17324 window.defer(cx, move |window, cx| {
17325 workspace.update(cx, |workspace, cx| {
17326 workspace.active_pane().update(cx, |pane, cx| {
17327 pane.add_item(
17328 Box::new(proposed_changes_editor),
17329 true,
17330 true,
17331 None,
17332 window,
17333 cx,
17334 );
17335 });
17336 });
17337 });
17338 }
17339
17340 pub fn open_excerpts_in_split(
17341 &mut self,
17342 _: &OpenExcerptsSplit,
17343 window: &mut Window,
17344 cx: &mut Context<Self>,
17345 ) {
17346 self.open_excerpts_common(None, true, window, cx)
17347 }
17348
17349 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17350 self.open_excerpts_common(None, false, window, cx)
17351 }
17352
17353 fn open_excerpts_common(
17354 &mut self,
17355 jump_data: Option<JumpData>,
17356 split: bool,
17357 window: &mut Window,
17358 cx: &mut Context<Self>,
17359 ) {
17360 let Some(workspace) = self.workspace() else {
17361 cx.propagate();
17362 return;
17363 };
17364
17365 if self.buffer.read(cx).is_singleton() {
17366 cx.propagate();
17367 return;
17368 }
17369
17370 let mut new_selections_by_buffer = HashMap::default();
17371 match &jump_data {
17372 Some(JumpData::MultiBufferPoint {
17373 excerpt_id,
17374 position,
17375 anchor,
17376 line_offset_from_top,
17377 }) => {
17378 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17379 if let Some(buffer) = multi_buffer_snapshot
17380 .buffer_id_for_excerpt(*excerpt_id)
17381 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17382 {
17383 let buffer_snapshot = buffer.read(cx).snapshot();
17384 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17385 language::ToPoint::to_point(anchor, &buffer_snapshot)
17386 } else {
17387 buffer_snapshot.clip_point(*position, Bias::Left)
17388 };
17389 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17390 new_selections_by_buffer.insert(
17391 buffer,
17392 (
17393 vec![jump_to_offset..jump_to_offset],
17394 Some(*line_offset_from_top),
17395 ),
17396 );
17397 }
17398 }
17399 Some(JumpData::MultiBufferRow {
17400 row,
17401 line_offset_from_top,
17402 }) => {
17403 let point = MultiBufferPoint::new(row.0, 0);
17404 if let Some((buffer, buffer_point, _)) =
17405 self.buffer.read(cx).point_to_buffer_point(point, cx)
17406 {
17407 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17408 new_selections_by_buffer
17409 .entry(buffer)
17410 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17411 .0
17412 .push(buffer_offset..buffer_offset)
17413 }
17414 }
17415 None => {
17416 let selections = self.selections.all::<usize>(cx);
17417 let multi_buffer = self.buffer.read(cx);
17418 for selection in selections {
17419 for (snapshot, range, _, anchor) in multi_buffer
17420 .snapshot(cx)
17421 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17422 {
17423 if let Some(anchor) = anchor {
17424 // selection is in a deleted hunk
17425 let Some(buffer_id) = anchor.buffer_id else {
17426 continue;
17427 };
17428 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17429 continue;
17430 };
17431 let offset = text::ToOffset::to_offset(
17432 &anchor.text_anchor,
17433 &buffer_handle.read(cx).snapshot(),
17434 );
17435 let range = offset..offset;
17436 new_selections_by_buffer
17437 .entry(buffer_handle)
17438 .or_insert((Vec::new(), None))
17439 .0
17440 .push(range)
17441 } else {
17442 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17443 else {
17444 continue;
17445 };
17446 new_selections_by_buffer
17447 .entry(buffer_handle)
17448 .or_insert((Vec::new(), None))
17449 .0
17450 .push(range)
17451 }
17452 }
17453 }
17454 }
17455 }
17456
17457 new_selections_by_buffer
17458 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17459
17460 if new_selections_by_buffer.is_empty() {
17461 return;
17462 }
17463
17464 // We defer the pane interaction because we ourselves are a workspace item
17465 // and activating a new item causes the pane to call a method on us reentrantly,
17466 // which panics if we're on the stack.
17467 window.defer(cx, move |window, cx| {
17468 workspace.update(cx, |workspace, cx| {
17469 let pane = if split {
17470 workspace.adjacent_pane(window, cx)
17471 } else {
17472 workspace.active_pane().clone()
17473 };
17474
17475 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17476 let editor = buffer
17477 .read(cx)
17478 .file()
17479 .is_none()
17480 .then(|| {
17481 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17482 // so `workspace.open_project_item` will never find them, always opening a new editor.
17483 // Instead, we try to activate the existing editor in the pane first.
17484 let (editor, pane_item_index) =
17485 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17486 let editor = item.downcast::<Editor>()?;
17487 let singleton_buffer =
17488 editor.read(cx).buffer().read(cx).as_singleton()?;
17489 if singleton_buffer == buffer {
17490 Some((editor, i))
17491 } else {
17492 None
17493 }
17494 })?;
17495 pane.update(cx, |pane, cx| {
17496 pane.activate_item(pane_item_index, true, true, window, cx)
17497 });
17498 Some(editor)
17499 })
17500 .flatten()
17501 .unwrap_or_else(|| {
17502 workspace.open_project_item::<Self>(
17503 pane.clone(),
17504 buffer,
17505 true,
17506 true,
17507 window,
17508 cx,
17509 )
17510 });
17511
17512 editor.update(cx, |editor, cx| {
17513 let autoscroll = match scroll_offset {
17514 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17515 None => Autoscroll::newest(),
17516 };
17517 let nav_history = editor.nav_history.take();
17518 editor.change_selections(Some(autoscroll), window, cx, |s| {
17519 s.select_ranges(ranges);
17520 });
17521 editor.nav_history = nav_history;
17522 });
17523 }
17524 })
17525 });
17526 }
17527
17528 // For now, don't allow opening excerpts in buffers that aren't backed by
17529 // regular project files.
17530 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17531 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17532 }
17533
17534 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17535 let snapshot = self.buffer.read(cx).read(cx);
17536 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17537 Some(
17538 ranges
17539 .iter()
17540 .map(move |range| {
17541 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17542 })
17543 .collect(),
17544 )
17545 }
17546
17547 fn selection_replacement_ranges(
17548 &self,
17549 range: Range<OffsetUtf16>,
17550 cx: &mut App,
17551 ) -> Vec<Range<OffsetUtf16>> {
17552 let selections = self.selections.all::<OffsetUtf16>(cx);
17553 let newest_selection = selections
17554 .iter()
17555 .max_by_key(|selection| selection.id)
17556 .unwrap();
17557 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17558 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17559 let snapshot = self.buffer.read(cx).read(cx);
17560 selections
17561 .into_iter()
17562 .map(|mut selection| {
17563 selection.start.0 =
17564 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17565 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17566 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17567 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17568 })
17569 .collect()
17570 }
17571
17572 fn report_editor_event(
17573 &self,
17574 event_type: &'static str,
17575 file_extension: Option<String>,
17576 cx: &App,
17577 ) {
17578 if cfg!(any(test, feature = "test-support")) {
17579 return;
17580 }
17581
17582 let Some(project) = &self.project else { return };
17583
17584 // If None, we are in a file without an extension
17585 let file = self
17586 .buffer
17587 .read(cx)
17588 .as_singleton()
17589 .and_then(|b| b.read(cx).file());
17590 let file_extension = file_extension.or(file
17591 .as_ref()
17592 .and_then(|file| Path::new(file.file_name(cx)).extension())
17593 .and_then(|e| e.to_str())
17594 .map(|a| a.to_string()));
17595
17596 let vim_mode = cx
17597 .global::<SettingsStore>()
17598 .raw_user_settings()
17599 .get("vim_mode")
17600 == Some(&serde_json::Value::Bool(true));
17601
17602 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17603 let copilot_enabled = edit_predictions_provider
17604 == language::language_settings::EditPredictionProvider::Copilot;
17605 let copilot_enabled_for_language = self
17606 .buffer
17607 .read(cx)
17608 .language_settings(cx)
17609 .show_edit_predictions;
17610
17611 let project = project.read(cx);
17612 telemetry::event!(
17613 event_type,
17614 file_extension,
17615 vim_mode,
17616 copilot_enabled,
17617 copilot_enabled_for_language,
17618 edit_predictions_provider,
17619 is_via_ssh = project.is_via_ssh(),
17620 );
17621 }
17622
17623 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17624 /// with each line being an array of {text, highlight} objects.
17625 fn copy_highlight_json(
17626 &mut self,
17627 _: &CopyHighlightJson,
17628 window: &mut Window,
17629 cx: &mut Context<Self>,
17630 ) {
17631 #[derive(Serialize)]
17632 struct Chunk<'a> {
17633 text: String,
17634 highlight: Option<&'a str>,
17635 }
17636
17637 let snapshot = self.buffer.read(cx).snapshot(cx);
17638 let range = self
17639 .selected_text_range(false, window, cx)
17640 .and_then(|selection| {
17641 if selection.range.is_empty() {
17642 None
17643 } else {
17644 Some(selection.range)
17645 }
17646 })
17647 .unwrap_or_else(|| 0..snapshot.len());
17648
17649 let chunks = snapshot.chunks(range, true);
17650 let mut lines = Vec::new();
17651 let mut line: VecDeque<Chunk> = VecDeque::new();
17652
17653 let Some(style) = self.style.as_ref() else {
17654 return;
17655 };
17656
17657 for chunk in chunks {
17658 let highlight = chunk
17659 .syntax_highlight_id
17660 .and_then(|id| id.name(&style.syntax));
17661 let mut chunk_lines = chunk.text.split('\n').peekable();
17662 while let Some(text) = chunk_lines.next() {
17663 let mut merged_with_last_token = false;
17664 if let Some(last_token) = line.back_mut() {
17665 if last_token.highlight == highlight {
17666 last_token.text.push_str(text);
17667 merged_with_last_token = true;
17668 }
17669 }
17670
17671 if !merged_with_last_token {
17672 line.push_back(Chunk {
17673 text: text.into(),
17674 highlight,
17675 });
17676 }
17677
17678 if chunk_lines.peek().is_some() {
17679 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17680 line.pop_front();
17681 }
17682 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17683 line.pop_back();
17684 }
17685
17686 lines.push(mem::take(&mut line));
17687 }
17688 }
17689 }
17690
17691 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17692 return;
17693 };
17694 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17695 }
17696
17697 pub fn open_context_menu(
17698 &mut self,
17699 _: &OpenContextMenu,
17700 window: &mut Window,
17701 cx: &mut Context<Self>,
17702 ) {
17703 self.request_autoscroll(Autoscroll::newest(), cx);
17704 let position = self.selections.newest_display(cx).start;
17705 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17706 }
17707
17708 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17709 &self.inlay_hint_cache
17710 }
17711
17712 pub fn replay_insert_event(
17713 &mut self,
17714 text: &str,
17715 relative_utf16_range: Option<Range<isize>>,
17716 window: &mut Window,
17717 cx: &mut Context<Self>,
17718 ) {
17719 if !self.input_enabled {
17720 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17721 return;
17722 }
17723 if let Some(relative_utf16_range) = relative_utf16_range {
17724 let selections = self.selections.all::<OffsetUtf16>(cx);
17725 self.change_selections(None, window, cx, |s| {
17726 let new_ranges = selections.into_iter().map(|range| {
17727 let start = OffsetUtf16(
17728 range
17729 .head()
17730 .0
17731 .saturating_add_signed(relative_utf16_range.start),
17732 );
17733 let end = OffsetUtf16(
17734 range
17735 .head()
17736 .0
17737 .saturating_add_signed(relative_utf16_range.end),
17738 );
17739 start..end
17740 });
17741 s.select_ranges(new_ranges);
17742 });
17743 }
17744
17745 self.handle_input(text, window, cx);
17746 }
17747
17748 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17749 let Some(provider) = self.semantics_provider.as_ref() else {
17750 return false;
17751 };
17752
17753 let mut supports = false;
17754 self.buffer().update(cx, |this, cx| {
17755 this.for_each_buffer(|buffer| {
17756 supports |= provider.supports_inlay_hints(buffer, cx);
17757 });
17758 });
17759
17760 supports
17761 }
17762
17763 pub fn is_focused(&self, window: &Window) -> bool {
17764 self.focus_handle.is_focused(window)
17765 }
17766
17767 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17768 cx.emit(EditorEvent::Focused);
17769
17770 if let Some(descendant) = self
17771 .last_focused_descendant
17772 .take()
17773 .and_then(|descendant| descendant.upgrade())
17774 {
17775 window.focus(&descendant);
17776 } else {
17777 if let Some(blame) = self.blame.as_ref() {
17778 blame.update(cx, GitBlame::focus)
17779 }
17780
17781 self.blink_manager.update(cx, BlinkManager::enable);
17782 self.show_cursor_names(window, cx);
17783 self.buffer.update(cx, |buffer, cx| {
17784 buffer.finalize_last_transaction(cx);
17785 if self.leader_peer_id.is_none() {
17786 buffer.set_active_selections(
17787 &self.selections.disjoint_anchors(),
17788 self.selections.line_mode,
17789 self.cursor_shape,
17790 cx,
17791 );
17792 }
17793 });
17794 }
17795 }
17796
17797 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17798 cx.emit(EditorEvent::FocusedIn)
17799 }
17800
17801 fn handle_focus_out(
17802 &mut self,
17803 event: FocusOutEvent,
17804 _window: &mut Window,
17805 cx: &mut Context<Self>,
17806 ) {
17807 if event.blurred != self.focus_handle {
17808 self.last_focused_descendant = Some(event.blurred);
17809 }
17810 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17811 }
17812
17813 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17814 self.blink_manager.update(cx, BlinkManager::disable);
17815 self.buffer
17816 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17817
17818 if let Some(blame) = self.blame.as_ref() {
17819 blame.update(cx, GitBlame::blur)
17820 }
17821 if !self.hover_state.focused(window, cx) {
17822 hide_hover(self, cx);
17823 }
17824 if !self
17825 .context_menu
17826 .borrow()
17827 .as_ref()
17828 .is_some_and(|context_menu| context_menu.focused(window, cx))
17829 {
17830 self.hide_context_menu(window, cx);
17831 }
17832 self.discard_inline_completion(false, cx);
17833 cx.emit(EditorEvent::Blurred);
17834 cx.notify();
17835 }
17836
17837 pub fn register_action<A: Action>(
17838 &mut self,
17839 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17840 ) -> Subscription {
17841 let id = self.next_editor_action_id.post_inc();
17842 let listener = Arc::new(listener);
17843 self.editor_actions.borrow_mut().insert(
17844 id,
17845 Box::new(move |window, _| {
17846 let listener = listener.clone();
17847 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17848 let action = action.downcast_ref().unwrap();
17849 if phase == DispatchPhase::Bubble {
17850 listener(action, window, cx)
17851 }
17852 })
17853 }),
17854 );
17855
17856 let editor_actions = self.editor_actions.clone();
17857 Subscription::new(move || {
17858 editor_actions.borrow_mut().remove(&id);
17859 })
17860 }
17861
17862 pub fn file_header_size(&self) -> u32 {
17863 FILE_HEADER_HEIGHT
17864 }
17865
17866 pub fn restore(
17867 &mut self,
17868 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17869 window: &mut Window,
17870 cx: &mut Context<Self>,
17871 ) {
17872 let workspace = self.workspace();
17873 let project = self.project.as_ref();
17874 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17875 let mut tasks = Vec::new();
17876 for (buffer_id, changes) in revert_changes {
17877 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17878 buffer.update(cx, |buffer, cx| {
17879 buffer.edit(
17880 changes
17881 .into_iter()
17882 .map(|(range, text)| (range, text.to_string())),
17883 None,
17884 cx,
17885 );
17886 });
17887
17888 if let Some(project) =
17889 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17890 {
17891 project.update(cx, |project, cx| {
17892 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17893 })
17894 }
17895 }
17896 }
17897 tasks
17898 });
17899 cx.spawn_in(window, async move |_, cx| {
17900 for (buffer, task) in save_tasks {
17901 let result = task.await;
17902 if result.is_err() {
17903 let Some(path) = buffer
17904 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17905 .ok()
17906 else {
17907 continue;
17908 };
17909 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17910 let Some(task) = cx
17911 .update_window_entity(&workspace, |workspace, window, cx| {
17912 workspace
17913 .open_path_preview(path, None, false, false, false, window, cx)
17914 })
17915 .ok()
17916 else {
17917 continue;
17918 };
17919 task.await.log_err();
17920 }
17921 }
17922 }
17923 })
17924 .detach();
17925 self.change_selections(None, window, cx, |selections| selections.refresh());
17926 }
17927
17928 pub fn to_pixel_point(
17929 &self,
17930 source: multi_buffer::Anchor,
17931 editor_snapshot: &EditorSnapshot,
17932 window: &mut Window,
17933 ) -> Option<gpui::Point<Pixels>> {
17934 let source_point = source.to_display_point(editor_snapshot);
17935 self.display_to_pixel_point(source_point, editor_snapshot, window)
17936 }
17937
17938 pub fn display_to_pixel_point(
17939 &self,
17940 source: DisplayPoint,
17941 editor_snapshot: &EditorSnapshot,
17942 window: &mut Window,
17943 ) -> Option<gpui::Point<Pixels>> {
17944 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17945 let text_layout_details = self.text_layout_details(window);
17946 let scroll_top = text_layout_details
17947 .scroll_anchor
17948 .scroll_position(editor_snapshot)
17949 .y;
17950
17951 if source.row().as_f32() < scroll_top.floor() {
17952 return None;
17953 }
17954 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17955 let source_y = line_height * (source.row().as_f32() - scroll_top);
17956 Some(gpui::Point::new(source_x, source_y))
17957 }
17958
17959 pub fn has_visible_completions_menu(&self) -> bool {
17960 !self.edit_prediction_preview_is_active()
17961 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17962 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17963 })
17964 }
17965
17966 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17967 self.addons
17968 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17969 }
17970
17971 pub fn unregister_addon<T: Addon>(&mut self) {
17972 self.addons.remove(&std::any::TypeId::of::<T>());
17973 }
17974
17975 pub fn addon<T: Addon>(&self) -> Option<&T> {
17976 let type_id = std::any::TypeId::of::<T>();
17977 self.addons
17978 .get(&type_id)
17979 .and_then(|item| item.to_any().downcast_ref::<T>())
17980 }
17981
17982 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17983 let text_layout_details = self.text_layout_details(window);
17984 let style = &text_layout_details.editor_style;
17985 let font_id = window.text_system().resolve_font(&style.text.font());
17986 let font_size = style.text.font_size.to_pixels(window.rem_size());
17987 let line_height = style.text.line_height_in_pixels(window.rem_size());
17988 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17989
17990 gpui::Size::new(em_width, line_height)
17991 }
17992
17993 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17994 self.load_diff_task.clone()
17995 }
17996
17997 fn read_metadata_from_db(
17998 &mut self,
17999 item_id: u64,
18000 workspace_id: WorkspaceId,
18001 window: &mut Window,
18002 cx: &mut Context<Editor>,
18003 ) {
18004 if self.is_singleton(cx)
18005 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18006 {
18007 let buffer_snapshot = OnceCell::new();
18008
18009 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18010 if !folds.is_empty() {
18011 let snapshot =
18012 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18013 self.fold_ranges(
18014 folds
18015 .into_iter()
18016 .map(|(start, end)| {
18017 snapshot.clip_offset(start, Bias::Left)
18018 ..snapshot.clip_offset(end, Bias::Right)
18019 })
18020 .collect(),
18021 false,
18022 window,
18023 cx,
18024 );
18025 }
18026 }
18027
18028 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18029 if !selections.is_empty() {
18030 let snapshot =
18031 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18032 self.change_selections(None, window, cx, |s| {
18033 s.select_ranges(selections.into_iter().map(|(start, end)| {
18034 snapshot.clip_offset(start, Bias::Left)
18035 ..snapshot.clip_offset(end, Bias::Right)
18036 }));
18037 });
18038 }
18039 };
18040 }
18041
18042 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18043 }
18044}
18045
18046// Consider user intent and default settings
18047fn choose_completion_range(
18048 completion: &Completion,
18049 intent: CompletionIntent,
18050 buffer: &Entity<Buffer>,
18051 cx: &mut Context<Editor>,
18052) -> Range<usize> {
18053 fn should_replace(
18054 completion: &Completion,
18055 insert_range: &Range<text::Anchor>,
18056 intent: CompletionIntent,
18057 completion_mode_setting: LspInsertMode,
18058 buffer: &Buffer,
18059 ) -> bool {
18060 // specific actions take precedence over settings
18061 match intent {
18062 CompletionIntent::CompleteWithInsert => return false,
18063 CompletionIntent::CompleteWithReplace => return true,
18064 CompletionIntent::Complete | CompletionIntent::Compose => {}
18065 }
18066
18067 match completion_mode_setting {
18068 LspInsertMode::Insert => false,
18069 LspInsertMode::Replace => true,
18070 LspInsertMode::ReplaceSubsequence => {
18071 let mut text_to_replace = buffer.chars_for_range(
18072 buffer.anchor_before(completion.replace_range.start)
18073 ..buffer.anchor_after(completion.replace_range.end),
18074 );
18075 let mut completion_text = completion.new_text.chars();
18076
18077 // is `text_to_replace` a subsequence of `completion_text`
18078 text_to_replace
18079 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18080 }
18081 LspInsertMode::ReplaceSuffix => {
18082 let range_after_cursor = insert_range.end..completion.replace_range.end;
18083
18084 let text_after_cursor = buffer
18085 .text_for_range(
18086 buffer.anchor_before(range_after_cursor.start)
18087 ..buffer.anchor_after(range_after_cursor.end),
18088 )
18089 .collect::<String>();
18090 completion.new_text.ends_with(&text_after_cursor)
18091 }
18092 }
18093 }
18094
18095 let buffer = buffer.read(cx);
18096
18097 if let CompletionSource::Lsp {
18098 insert_range: Some(insert_range),
18099 ..
18100 } = &completion.source
18101 {
18102 let completion_mode_setting =
18103 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18104 .completions
18105 .lsp_insert_mode;
18106
18107 if !should_replace(
18108 completion,
18109 &insert_range,
18110 intent,
18111 completion_mode_setting,
18112 buffer,
18113 ) {
18114 return insert_range.to_offset(buffer);
18115 }
18116 }
18117
18118 completion.replace_range.to_offset(buffer)
18119}
18120
18121fn insert_extra_newline_brackets(
18122 buffer: &MultiBufferSnapshot,
18123 range: Range<usize>,
18124 language: &language::LanguageScope,
18125) -> bool {
18126 let leading_whitespace_len = buffer
18127 .reversed_chars_at(range.start)
18128 .take_while(|c| c.is_whitespace() && *c != '\n')
18129 .map(|c| c.len_utf8())
18130 .sum::<usize>();
18131 let trailing_whitespace_len = buffer
18132 .chars_at(range.end)
18133 .take_while(|c| c.is_whitespace() && *c != '\n')
18134 .map(|c| c.len_utf8())
18135 .sum::<usize>();
18136 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18137
18138 language.brackets().any(|(pair, enabled)| {
18139 let pair_start = pair.start.trim_end();
18140 let pair_end = pair.end.trim_start();
18141
18142 enabled
18143 && pair.newline
18144 && buffer.contains_str_at(range.end, pair_end)
18145 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18146 })
18147}
18148
18149fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18150 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18151 [(buffer, range, _)] => (*buffer, range.clone()),
18152 _ => return false,
18153 };
18154 let pair = {
18155 let mut result: Option<BracketMatch> = None;
18156
18157 for pair in buffer
18158 .all_bracket_ranges(range.clone())
18159 .filter(move |pair| {
18160 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18161 })
18162 {
18163 let len = pair.close_range.end - pair.open_range.start;
18164
18165 if let Some(existing) = &result {
18166 let existing_len = existing.close_range.end - existing.open_range.start;
18167 if len > existing_len {
18168 continue;
18169 }
18170 }
18171
18172 result = Some(pair);
18173 }
18174
18175 result
18176 };
18177 let Some(pair) = pair else {
18178 return false;
18179 };
18180 pair.newline_only
18181 && buffer
18182 .chars_for_range(pair.open_range.end..range.start)
18183 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18184 .all(|c| c.is_whitespace() && c != '\n')
18185}
18186
18187fn get_uncommitted_diff_for_buffer(
18188 project: &Entity<Project>,
18189 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18190 buffer: Entity<MultiBuffer>,
18191 cx: &mut App,
18192) -> Task<()> {
18193 let mut tasks = Vec::new();
18194 project.update(cx, |project, cx| {
18195 for buffer in buffers {
18196 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18197 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18198 }
18199 }
18200 });
18201 cx.spawn(async move |cx| {
18202 let diffs = future::join_all(tasks).await;
18203 buffer
18204 .update(cx, |buffer, cx| {
18205 for diff in diffs.into_iter().flatten() {
18206 buffer.add_diff(diff, cx);
18207 }
18208 })
18209 .ok();
18210 })
18211}
18212
18213fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18214 let tab_size = tab_size.get() as usize;
18215 let mut width = offset;
18216
18217 for ch in text.chars() {
18218 width += if ch == '\t' {
18219 tab_size - (width % tab_size)
18220 } else {
18221 1
18222 };
18223 }
18224
18225 width - offset
18226}
18227
18228#[cfg(test)]
18229mod tests {
18230 use super::*;
18231
18232 #[test]
18233 fn test_string_size_with_expanded_tabs() {
18234 let nz = |val| NonZeroU32::new(val).unwrap();
18235 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18236 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18237 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18238 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18239 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18240 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18241 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18242 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18243 }
18244}
18245
18246/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18247struct WordBreakingTokenizer<'a> {
18248 input: &'a str,
18249}
18250
18251impl<'a> WordBreakingTokenizer<'a> {
18252 fn new(input: &'a str) -> Self {
18253 Self { input }
18254 }
18255}
18256
18257fn is_char_ideographic(ch: char) -> bool {
18258 use unicode_script::Script::*;
18259 use unicode_script::UnicodeScript;
18260 matches!(ch.script(), Han | Tangut | Yi)
18261}
18262
18263fn is_grapheme_ideographic(text: &str) -> bool {
18264 text.chars().any(is_char_ideographic)
18265}
18266
18267fn is_grapheme_whitespace(text: &str) -> bool {
18268 text.chars().any(|x| x.is_whitespace())
18269}
18270
18271fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18272 text.chars().next().map_or(false, |ch| {
18273 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18274 })
18275}
18276
18277#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18278enum WordBreakToken<'a> {
18279 Word { token: &'a str, grapheme_len: usize },
18280 InlineWhitespace { token: &'a str, grapheme_len: usize },
18281 Newline,
18282}
18283
18284impl<'a> Iterator for WordBreakingTokenizer<'a> {
18285 /// Yields a span, the count of graphemes in the token, and whether it was
18286 /// whitespace. Note that it also breaks at word boundaries.
18287 type Item = WordBreakToken<'a>;
18288
18289 fn next(&mut self) -> Option<Self::Item> {
18290 use unicode_segmentation::UnicodeSegmentation;
18291 if self.input.is_empty() {
18292 return None;
18293 }
18294
18295 let mut iter = self.input.graphemes(true).peekable();
18296 let mut offset = 0;
18297 let mut grapheme_len = 0;
18298 if let Some(first_grapheme) = iter.next() {
18299 let is_newline = first_grapheme == "\n";
18300 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18301 offset += first_grapheme.len();
18302 grapheme_len += 1;
18303 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18304 if let Some(grapheme) = iter.peek().copied() {
18305 if should_stay_with_preceding_ideograph(grapheme) {
18306 offset += grapheme.len();
18307 grapheme_len += 1;
18308 }
18309 }
18310 } else {
18311 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18312 let mut next_word_bound = words.peek().copied();
18313 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18314 next_word_bound = words.next();
18315 }
18316 while let Some(grapheme) = iter.peek().copied() {
18317 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18318 break;
18319 };
18320 if is_grapheme_whitespace(grapheme) != is_whitespace
18321 || (grapheme == "\n") != is_newline
18322 {
18323 break;
18324 };
18325 offset += grapheme.len();
18326 grapheme_len += 1;
18327 iter.next();
18328 }
18329 }
18330 let token = &self.input[..offset];
18331 self.input = &self.input[offset..];
18332 if token == "\n" {
18333 Some(WordBreakToken::Newline)
18334 } else if is_whitespace {
18335 Some(WordBreakToken::InlineWhitespace {
18336 token,
18337 grapheme_len,
18338 })
18339 } else {
18340 Some(WordBreakToken::Word {
18341 token,
18342 grapheme_len,
18343 })
18344 }
18345 } else {
18346 None
18347 }
18348 }
18349}
18350
18351#[test]
18352fn test_word_breaking_tokenizer() {
18353 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18354 ("", &[]),
18355 (" ", &[whitespace(" ", 2)]),
18356 ("Ʒ", &[word("Ʒ", 1)]),
18357 ("Ǽ", &[word("Ǽ", 1)]),
18358 ("⋑", &[word("⋑", 1)]),
18359 ("⋑⋑", &[word("⋑⋑", 2)]),
18360 (
18361 "原理,进而",
18362 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18363 ),
18364 (
18365 "hello world",
18366 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18367 ),
18368 (
18369 "hello, world",
18370 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18371 ),
18372 (
18373 " hello world",
18374 &[
18375 whitespace(" ", 2),
18376 word("hello", 5),
18377 whitespace(" ", 1),
18378 word("world", 5),
18379 ],
18380 ),
18381 (
18382 "这是什么 \n 钢笔",
18383 &[
18384 word("这", 1),
18385 word("是", 1),
18386 word("什", 1),
18387 word("么", 1),
18388 whitespace(" ", 1),
18389 newline(),
18390 whitespace(" ", 1),
18391 word("钢", 1),
18392 word("笔", 1),
18393 ],
18394 ),
18395 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18396 ];
18397
18398 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18399 WordBreakToken::Word {
18400 token,
18401 grapheme_len,
18402 }
18403 }
18404
18405 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18406 WordBreakToken::InlineWhitespace {
18407 token,
18408 grapheme_len,
18409 }
18410 }
18411
18412 fn newline() -> WordBreakToken<'static> {
18413 WordBreakToken::Newline
18414 }
18415
18416 for (input, result) in tests {
18417 assert_eq!(
18418 WordBreakingTokenizer::new(input)
18419 .collect::<Vec<_>>()
18420 .as_slice(),
18421 *result,
18422 );
18423 }
18424}
18425
18426fn wrap_with_prefix(
18427 line_prefix: String,
18428 unwrapped_text: String,
18429 wrap_column: usize,
18430 tab_size: NonZeroU32,
18431 preserve_existing_whitespace: bool,
18432) -> String {
18433 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18434 let mut wrapped_text = String::new();
18435 let mut current_line = line_prefix.clone();
18436
18437 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18438 let mut current_line_len = line_prefix_len;
18439 let mut in_whitespace = false;
18440 for token in tokenizer {
18441 let have_preceding_whitespace = in_whitespace;
18442 match token {
18443 WordBreakToken::Word {
18444 token,
18445 grapheme_len,
18446 } => {
18447 in_whitespace = false;
18448 if current_line_len + grapheme_len > wrap_column
18449 && current_line_len != line_prefix_len
18450 {
18451 wrapped_text.push_str(current_line.trim_end());
18452 wrapped_text.push('\n');
18453 current_line.truncate(line_prefix.len());
18454 current_line_len = line_prefix_len;
18455 }
18456 current_line.push_str(token);
18457 current_line_len += grapheme_len;
18458 }
18459 WordBreakToken::InlineWhitespace {
18460 mut token,
18461 mut grapheme_len,
18462 } => {
18463 in_whitespace = true;
18464 if have_preceding_whitespace && !preserve_existing_whitespace {
18465 continue;
18466 }
18467 if !preserve_existing_whitespace {
18468 token = " ";
18469 grapheme_len = 1;
18470 }
18471 if current_line_len + grapheme_len > wrap_column {
18472 wrapped_text.push_str(current_line.trim_end());
18473 wrapped_text.push('\n');
18474 current_line.truncate(line_prefix.len());
18475 current_line_len = line_prefix_len;
18476 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18477 current_line.push_str(token);
18478 current_line_len += grapheme_len;
18479 }
18480 }
18481 WordBreakToken::Newline => {
18482 in_whitespace = true;
18483 if preserve_existing_whitespace {
18484 wrapped_text.push_str(current_line.trim_end());
18485 wrapped_text.push('\n');
18486 current_line.truncate(line_prefix.len());
18487 current_line_len = line_prefix_len;
18488 } else if have_preceding_whitespace {
18489 continue;
18490 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18491 {
18492 wrapped_text.push_str(current_line.trim_end());
18493 wrapped_text.push('\n');
18494 current_line.truncate(line_prefix.len());
18495 current_line_len = line_prefix_len;
18496 } else if current_line_len != line_prefix_len {
18497 current_line.push(' ');
18498 current_line_len += 1;
18499 }
18500 }
18501 }
18502 }
18503
18504 if !current_line.is_empty() {
18505 wrapped_text.push_str(¤t_line);
18506 }
18507 wrapped_text
18508}
18509
18510#[test]
18511fn test_wrap_with_prefix() {
18512 assert_eq!(
18513 wrap_with_prefix(
18514 "# ".to_string(),
18515 "abcdefg".to_string(),
18516 4,
18517 NonZeroU32::new(4).unwrap(),
18518 false,
18519 ),
18520 "# abcdefg"
18521 );
18522 assert_eq!(
18523 wrap_with_prefix(
18524 "".to_string(),
18525 "\thello world".to_string(),
18526 8,
18527 NonZeroU32::new(4).unwrap(),
18528 false,
18529 ),
18530 "hello\nworld"
18531 );
18532 assert_eq!(
18533 wrap_with_prefix(
18534 "// ".to_string(),
18535 "xx \nyy zz aa bb cc".to_string(),
18536 12,
18537 NonZeroU32::new(4).unwrap(),
18538 false,
18539 ),
18540 "// xx yy zz\n// aa bb cc"
18541 );
18542 assert_eq!(
18543 wrap_with_prefix(
18544 String::new(),
18545 "这是什么 \n 钢笔".to_string(),
18546 3,
18547 NonZeroU32::new(4).unwrap(),
18548 false,
18549 ),
18550 "这是什\n么 钢\n笔"
18551 );
18552}
18553
18554pub trait CollaborationHub {
18555 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18556 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18557 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18558}
18559
18560impl CollaborationHub for Entity<Project> {
18561 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18562 self.read(cx).collaborators()
18563 }
18564
18565 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18566 self.read(cx).user_store().read(cx).participant_indices()
18567 }
18568
18569 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18570 let this = self.read(cx);
18571 let user_ids = this.collaborators().values().map(|c| c.user_id);
18572 this.user_store().read_with(cx, |user_store, cx| {
18573 user_store.participant_names(user_ids, cx)
18574 })
18575 }
18576}
18577
18578pub trait SemanticsProvider {
18579 fn hover(
18580 &self,
18581 buffer: &Entity<Buffer>,
18582 position: text::Anchor,
18583 cx: &mut App,
18584 ) -> Option<Task<Vec<project::Hover>>>;
18585
18586 fn inlay_hints(
18587 &self,
18588 buffer_handle: Entity<Buffer>,
18589 range: Range<text::Anchor>,
18590 cx: &mut App,
18591 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18592
18593 fn resolve_inlay_hint(
18594 &self,
18595 hint: InlayHint,
18596 buffer_handle: Entity<Buffer>,
18597 server_id: LanguageServerId,
18598 cx: &mut App,
18599 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18600
18601 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18602
18603 fn document_highlights(
18604 &self,
18605 buffer: &Entity<Buffer>,
18606 position: text::Anchor,
18607 cx: &mut App,
18608 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18609
18610 fn definitions(
18611 &self,
18612 buffer: &Entity<Buffer>,
18613 position: text::Anchor,
18614 kind: GotoDefinitionKind,
18615 cx: &mut App,
18616 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18617
18618 fn range_for_rename(
18619 &self,
18620 buffer: &Entity<Buffer>,
18621 position: text::Anchor,
18622 cx: &mut App,
18623 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18624
18625 fn perform_rename(
18626 &self,
18627 buffer: &Entity<Buffer>,
18628 position: text::Anchor,
18629 new_name: String,
18630 cx: &mut App,
18631 ) -> Option<Task<Result<ProjectTransaction>>>;
18632}
18633
18634pub trait CompletionProvider {
18635 fn completions(
18636 &self,
18637 excerpt_id: ExcerptId,
18638 buffer: &Entity<Buffer>,
18639 buffer_position: text::Anchor,
18640 trigger: CompletionContext,
18641 window: &mut Window,
18642 cx: &mut Context<Editor>,
18643 ) -> Task<Result<Option<Vec<Completion>>>>;
18644
18645 fn resolve_completions(
18646 &self,
18647 buffer: Entity<Buffer>,
18648 completion_indices: Vec<usize>,
18649 completions: Rc<RefCell<Box<[Completion]>>>,
18650 cx: &mut Context<Editor>,
18651 ) -> Task<Result<bool>>;
18652
18653 fn apply_additional_edits_for_completion(
18654 &self,
18655 _buffer: Entity<Buffer>,
18656 _completions: Rc<RefCell<Box<[Completion]>>>,
18657 _completion_index: usize,
18658 _push_to_history: bool,
18659 _cx: &mut Context<Editor>,
18660 ) -> Task<Result<Option<language::Transaction>>> {
18661 Task::ready(Ok(None))
18662 }
18663
18664 fn is_completion_trigger(
18665 &self,
18666 buffer: &Entity<Buffer>,
18667 position: language::Anchor,
18668 text: &str,
18669 trigger_in_words: bool,
18670 cx: &mut Context<Editor>,
18671 ) -> bool;
18672
18673 fn sort_completions(&self) -> bool {
18674 true
18675 }
18676
18677 fn filter_completions(&self) -> bool {
18678 true
18679 }
18680}
18681
18682pub trait CodeActionProvider {
18683 fn id(&self) -> Arc<str>;
18684
18685 fn code_actions(
18686 &self,
18687 buffer: &Entity<Buffer>,
18688 range: Range<text::Anchor>,
18689 window: &mut Window,
18690 cx: &mut App,
18691 ) -> Task<Result<Vec<CodeAction>>>;
18692
18693 fn apply_code_action(
18694 &self,
18695 buffer_handle: Entity<Buffer>,
18696 action: CodeAction,
18697 excerpt_id: ExcerptId,
18698 push_to_history: bool,
18699 window: &mut Window,
18700 cx: &mut App,
18701 ) -> Task<Result<ProjectTransaction>>;
18702}
18703
18704impl CodeActionProvider for Entity<Project> {
18705 fn id(&self) -> Arc<str> {
18706 "project".into()
18707 }
18708
18709 fn code_actions(
18710 &self,
18711 buffer: &Entity<Buffer>,
18712 range: Range<text::Anchor>,
18713 _window: &mut Window,
18714 cx: &mut App,
18715 ) -> Task<Result<Vec<CodeAction>>> {
18716 self.update(cx, |project, cx| {
18717 let code_lens = project.code_lens(buffer, range.clone(), cx);
18718 let code_actions = project.code_actions(buffer, range, None, cx);
18719 cx.background_spawn(async move {
18720 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18721 Ok(code_lens
18722 .context("code lens fetch")?
18723 .into_iter()
18724 .chain(code_actions.context("code action fetch")?)
18725 .collect())
18726 })
18727 })
18728 }
18729
18730 fn apply_code_action(
18731 &self,
18732 buffer_handle: Entity<Buffer>,
18733 action: CodeAction,
18734 _excerpt_id: ExcerptId,
18735 push_to_history: bool,
18736 _window: &mut Window,
18737 cx: &mut App,
18738 ) -> Task<Result<ProjectTransaction>> {
18739 self.update(cx, |project, cx| {
18740 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18741 })
18742 }
18743}
18744
18745fn snippet_completions(
18746 project: &Project,
18747 buffer: &Entity<Buffer>,
18748 buffer_position: text::Anchor,
18749 cx: &mut App,
18750) -> Task<Result<Vec<Completion>>> {
18751 let language = buffer.read(cx).language_at(buffer_position);
18752 let language_name = language.as_ref().map(|language| language.lsp_id());
18753 let snippet_store = project.snippets().read(cx);
18754 let snippets = snippet_store.snippets_for(language_name, cx);
18755
18756 if snippets.is_empty() {
18757 return Task::ready(Ok(vec![]));
18758 }
18759 let snapshot = buffer.read(cx).text_snapshot();
18760 let chars: String = snapshot
18761 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18762 .collect();
18763
18764 let scope = language.map(|language| language.default_scope());
18765 let executor = cx.background_executor().clone();
18766
18767 cx.background_spawn(async move {
18768 let classifier = CharClassifier::new(scope).for_completion(true);
18769 let mut last_word = chars
18770 .chars()
18771 .take_while(|c| classifier.is_word(*c))
18772 .collect::<String>();
18773 last_word = last_word.chars().rev().collect();
18774
18775 if last_word.is_empty() {
18776 return Ok(vec![]);
18777 }
18778
18779 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18780 let to_lsp = |point: &text::Anchor| {
18781 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18782 point_to_lsp(end)
18783 };
18784 let lsp_end = to_lsp(&buffer_position);
18785
18786 let candidates = snippets
18787 .iter()
18788 .enumerate()
18789 .flat_map(|(ix, snippet)| {
18790 snippet
18791 .prefix
18792 .iter()
18793 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18794 })
18795 .collect::<Vec<StringMatchCandidate>>();
18796
18797 let mut matches = fuzzy::match_strings(
18798 &candidates,
18799 &last_word,
18800 last_word.chars().any(|c| c.is_uppercase()),
18801 100,
18802 &Default::default(),
18803 executor,
18804 )
18805 .await;
18806
18807 // Remove all candidates where the query's start does not match the start of any word in the candidate
18808 if let Some(query_start) = last_word.chars().next() {
18809 matches.retain(|string_match| {
18810 split_words(&string_match.string).any(|word| {
18811 // Check that the first codepoint of the word as lowercase matches the first
18812 // codepoint of the query as lowercase
18813 word.chars()
18814 .flat_map(|codepoint| codepoint.to_lowercase())
18815 .zip(query_start.to_lowercase())
18816 .all(|(word_cp, query_cp)| word_cp == query_cp)
18817 })
18818 });
18819 }
18820
18821 let matched_strings = matches
18822 .into_iter()
18823 .map(|m| m.string)
18824 .collect::<HashSet<_>>();
18825
18826 let result: Vec<Completion> = snippets
18827 .into_iter()
18828 .filter_map(|snippet| {
18829 let matching_prefix = snippet
18830 .prefix
18831 .iter()
18832 .find(|prefix| matched_strings.contains(*prefix))?;
18833 let start = as_offset - last_word.len();
18834 let start = snapshot.anchor_before(start);
18835 let range = start..buffer_position;
18836 let lsp_start = to_lsp(&start);
18837 let lsp_range = lsp::Range {
18838 start: lsp_start,
18839 end: lsp_end,
18840 };
18841 Some(Completion {
18842 replace_range: range,
18843 new_text: snippet.body.clone(),
18844 source: CompletionSource::Lsp {
18845 insert_range: None,
18846 server_id: LanguageServerId(usize::MAX),
18847 resolved: true,
18848 lsp_completion: Box::new(lsp::CompletionItem {
18849 label: snippet.prefix.first().unwrap().clone(),
18850 kind: Some(CompletionItemKind::SNIPPET),
18851 label_details: snippet.description.as_ref().map(|description| {
18852 lsp::CompletionItemLabelDetails {
18853 detail: Some(description.clone()),
18854 description: None,
18855 }
18856 }),
18857 insert_text_format: Some(InsertTextFormat::SNIPPET),
18858 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18859 lsp::InsertReplaceEdit {
18860 new_text: snippet.body.clone(),
18861 insert: lsp_range,
18862 replace: lsp_range,
18863 },
18864 )),
18865 filter_text: Some(snippet.body.clone()),
18866 sort_text: Some(char::MAX.to_string()),
18867 ..lsp::CompletionItem::default()
18868 }),
18869 lsp_defaults: None,
18870 },
18871 label: CodeLabel {
18872 text: matching_prefix.clone(),
18873 runs: Vec::new(),
18874 filter_range: 0..matching_prefix.len(),
18875 },
18876 icon_path: None,
18877 documentation: snippet
18878 .description
18879 .clone()
18880 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18881 insert_text_mode: None,
18882 confirm: None,
18883 })
18884 })
18885 .collect();
18886
18887 Ok(result)
18888 })
18889}
18890
18891impl CompletionProvider for Entity<Project> {
18892 fn completions(
18893 &self,
18894 _excerpt_id: ExcerptId,
18895 buffer: &Entity<Buffer>,
18896 buffer_position: text::Anchor,
18897 options: CompletionContext,
18898 _window: &mut Window,
18899 cx: &mut Context<Editor>,
18900 ) -> Task<Result<Option<Vec<Completion>>>> {
18901 self.update(cx, |project, cx| {
18902 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18903 let project_completions = project.completions(buffer, buffer_position, options, cx);
18904 cx.background_spawn(async move {
18905 let snippets_completions = snippets.await?;
18906 match project_completions.await? {
18907 Some(mut completions) => {
18908 completions.extend(snippets_completions);
18909 Ok(Some(completions))
18910 }
18911 None => {
18912 if snippets_completions.is_empty() {
18913 Ok(None)
18914 } else {
18915 Ok(Some(snippets_completions))
18916 }
18917 }
18918 }
18919 })
18920 })
18921 }
18922
18923 fn resolve_completions(
18924 &self,
18925 buffer: Entity<Buffer>,
18926 completion_indices: Vec<usize>,
18927 completions: Rc<RefCell<Box<[Completion]>>>,
18928 cx: &mut Context<Editor>,
18929 ) -> Task<Result<bool>> {
18930 self.update(cx, |project, cx| {
18931 project.lsp_store().update(cx, |lsp_store, cx| {
18932 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18933 })
18934 })
18935 }
18936
18937 fn apply_additional_edits_for_completion(
18938 &self,
18939 buffer: Entity<Buffer>,
18940 completions: Rc<RefCell<Box<[Completion]>>>,
18941 completion_index: usize,
18942 push_to_history: bool,
18943 cx: &mut Context<Editor>,
18944 ) -> Task<Result<Option<language::Transaction>>> {
18945 self.update(cx, |project, cx| {
18946 project.lsp_store().update(cx, |lsp_store, cx| {
18947 lsp_store.apply_additional_edits_for_completion(
18948 buffer,
18949 completions,
18950 completion_index,
18951 push_to_history,
18952 cx,
18953 )
18954 })
18955 })
18956 }
18957
18958 fn is_completion_trigger(
18959 &self,
18960 buffer: &Entity<Buffer>,
18961 position: language::Anchor,
18962 text: &str,
18963 trigger_in_words: bool,
18964 cx: &mut Context<Editor>,
18965 ) -> bool {
18966 let mut chars = text.chars();
18967 let char = if let Some(char) = chars.next() {
18968 char
18969 } else {
18970 return false;
18971 };
18972 if chars.next().is_some() {
18973 return false;
18974 }
18975
18976 let buffer = buffer.read(cx);
18977 let snapshot = buffer.snapshot();
18978 if !snapshot.settings_at(position, cx).show_completions_on_input {
18979 return false;
18980 }
18981 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18982 if trigger_in_words && classifier.is_word(char) {
18983 return true;
18984 }
18985
18986 buffer.completion_triggers().contains(text)
18987 }
18988}
18989
18990impl SemanticsProvider for Entity<Project> {
18991 fn hover(
18992 &self,
18993 buffer: &Entity<Buffer>,
18994 position: text::Anchor,
18995 cx: &mut App,
18996 ) -> Option<Task<Vec<project::Hover>>> {
18997 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18998 }
18999
19000 fn document_highlights(
19001 &self,
19002 buffer: &Entity<Buffer>,
19003 position: text::Anchor,
19004 cx: &mut App,
19005 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19006 Some(self.update(cx, |project, cx| {
19007 project.document_highlights(buffer, position, cx)
19008 }))
19009 }
19010
19011 fn definitions(
19012 &self,
19013 buffer: &Entity<Buffer>,
19014 position: text::Anchor,
19015 kind: GotoDefinitionKind,
19016 cx: &mut App,
19017 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19018 Some(self.update(cx, |project, cx| match kind {
19019 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19020 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19021 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19022 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19023 }))
19024 }
19025
19026 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19027 // TODO: make this work for remote projects
19028 self.update(cx, |this, cx| {
19029 buffer.update(cx, |buffer, cx| {
19030 this.any_language_server_supports_inlay_hints(buffer, cx)
19031 })
19032 })
19033 }
19034
19035 fn inlay_hints(
19036 &self,
19037 buffer_handle: Entity<Buffer>,
19038 range: Range<text::Anchor>,
19039 cx: &mut App,
19040 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19041 Some(self.update(cx, |project, cx| {
19042 project.inlay_hints(buffer_handle, range, cx)
19043 }))
19044 }
19045
19046 fn resolve_inlay_hint(
19047 &self,
19048 hint: InlayHint,
19049 buffer_handle: Entity<Buffer>,
19050 server_id: LanguageServerId,
19051 cx: &mut App,
19052 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19053 Some(self.update(cx, |project, cx| {
19054 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19055 }))
19056 }
19057
19058 fn range_for_rename(
19059 &self,
19060 buffer: &Entity<Buffer>,
19061 position: text::Anchor,
19062 cx: &mut App,
19063 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19064 Some(self.update(cx, |project, cx| {
19065 let buffer = buffer.clone();
19066 let task = project.prepare_rename(buffer.clone(), position, cx);
19067 cx.spawn(async move |_, cx| {
19068 Ok(match task.await? {
19069 PrepareRenameResponse::Success(range) => Some(range),
19070 PrepareRenameResponse::InvalidPosition => None,
19071 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19072 // Fallback on using TreeSitter info to determine identifier range
19073 buffer.update(cx, |buffer, _| {
19074 let snapshot = buffer.snapshot();
19075 let (range, kind) = snapshot.surrounding_word(position);
19076 if kind != Some(CharKind::Word) {
19077 return None;
19078 }
19079 Some(
19080 snapshot.anchor_before(range.start)
19081 ..snapshot.anchor_after(range.end),
19082 )
19083 })?
19084 }
19085 })
19086 })
19087 }))
19088 }
19089
19090 fn perform_rename(
19091 &self,
19092 buffer: &Entity<Buffer>,
19093 position: text::Anchor,
19094 new_name: String,
19095 cx: &mut App,
19096 ) -> Option<Task<Result<ProjectTransaction>>> {
19097 Some(self.update(cx, |project, cx| {
19098 project.perform_rename(buffer.clone(), position, new_name, cx)
19099 }))
19100 }
19101}
19102
19103fn inlay_hint_settings(
19104 location: Anchor,
19105 snapshot: &MultiBufferSnapshot,
19106 cx: &mut Context<Editor>,
19107) -> InlayHintSettings {
19108 let file = snapshot.file_at(location);
19109 let language = snapshot.language_at(location).map(|l| l.name());
19110 language_settings(language, file, cx).inlay_hints
19111}
19112
19113fn consume_contiguous_rows(
19114 contiguous_row_selections: &mut Vec<Selection<Point>>,
19115 selection: &Selection<Point>,
19116 display_map: &DisplaySnapshot,
19117 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19118) -> (MultiBufferRow, MultiBufferRow) {
19119 contiguous_row_selections.push(selection.clone());
19120 let start_row = MultiBufferRow(selection.start.row);
19121 let mut end_row = ending_row(selection, display_map);
19122
19123 while let Some(next_selection) = selections.peek() {
19124 if next_selection.start.row <= end_row.0 {
19125 end_row = ending_row(next_selection, display_map);
19126 contiguous_row_selections.push(selections.next().unwrap().clone());
19127 } else {
19128 break;
19129 }
19130 }
19131 (start_row, end_row)
19132}
19133
19134fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19135 if next_selection.end.column > 0 || next_selection.is_empty() {
19136 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19137 } else {
19138 MultiBufferRow(next_selection.end.row)
19139 }
19140}
19141
19142impl EditorSnapshot {
19143 pub fn remote_selections_in_range<'a>(
19144 &'a self,
19145 range: &'a Range<Anchor>,
19146 collaboration_hub: &dyn CollaborationHub,
19147 cx: &'a App,
19148 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19149 let participant_names = collaboration_hub.user_names(cx);
19150 let participant_indices = collaboration_hub.user_participant_indices(cx);
19151 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19152 let collaborators_by_replica_id = collaborators_by_peer_id
19153 .iter()
19154 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19155 .collect::<HashMap<_, _>>();
19156 self.buffer_snapshot
19157 .selections_in_range(range, false)
19158 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19159 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19160 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19161 let user_name = participant_names.get(&collaborator.user_id).cloned();
19162 Some(RemoteSelection {
19163 replica_id,
19164 selection,
19165 cursor_shape,
19166 line_mode,
19167 participant_index,
19168 peer_id: collaborator.peer_id,
19169 user_name,
19170 })
19171 })
19172 }
19173
19174 pub fn hunks_for_ranges(
19175 &self,
19176 ranges: impl IntoIterator<Item = Range<Point>>,
19177 ) -> Vec<MultiBufferDiffHunk> {
19178 let mut hunks = Vec::new();
19179 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19180 HashMap::default();
19181 for query_range in ranges {
19182 let query_rows =
19183 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19184 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19185 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19186 ) {
19187 // Include deleted hunks that are adjacent to the query range, because
19188 // otherwise they would be missed.
19189 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19190 if hunk.status().is_deleted() {
19191 intersects_range |= hunk.row_range.start == query_rows.end;
19192 intersects_range |= hunk.row_range.end == query_rows.start;
19193 }
19194 if intersects_range {
19195 if !processed_buffer_rows
19196 .entry(hunk.buffer_id)
19197 .or_default()
19198 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19199 {
19200 continue;
19201 }
19202 hunks.push(hunk);
19203 }
19204 }
19205 }
19206
19207 hunks
19208 }
19209
19210 fn display_diff_hunks_for_rows<'a>(
19211 &'a self,
19212 display_rows: Range<DisplayRow>,
19213 folded_buffers: &'a HashSet<BufferId>,
19214 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19215 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19216 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19217
19218 self.buffer_snapshot
19219 .diff_hunks_in_range(buffer_start..buffer_end)
19220 .filter_map(|hunk| {
19221 if folded_buffers.contains(&hunk.buffer_id) {
19222 return None;
19223 }
19224
19225 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19226 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19227
19228 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19229 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19230
19231 let display_hunk = if hunk_display_start.column() != 0 {
19232 DisplayDiffHunk::Folded {
19233 display_row: hunk_display_start.row(),
19234 }
19235 } else {
19236 let mut end_row = hunk_display_end.row();
19237 if hunk_display_end.column() > 0 {
19238 end_row.0 += 1;
19239 }
19240 let is_created_file = hunk.is_created_file();
19241 DisplayDiffHunk::Unfolded {
19242 status: hunk.status(),
19243 diff_base_byte_range: hunk.diff_base_byte_range,
19244 display_row_range: hunk_display_start.row()..end_row,
19245 multi_buffer_range: Anchor::range_in_buffer(
19246 hunk.excerpt_id,
19247 hunk.buffer_id,
19248 hunk.buffer_range,
19249 ),
19250 is_created_file,
19251 }
19252 };
19253
19254 Some(display_hunk)
19255 })
19256 }
19257
19258 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19259 self.display_snapshot.buffer_snapshot.language_at(position)
19260 }
19261
19262 pub fn is_focused(&self) -> bool {
19263 self.is_focused
19264 }
19265
19266 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19267 self.placeholder_text.as_ref()
19268 }
19269
19270 pub fn scroll_position(&self) -> gpui::Point<f32> {
19271 self.scroll_anchor.scroll_position(&self.display_snapshot)
19272 }
19273
19274 fn gutter_dimensions(
19275 &self,
19276 font_id: FontId,
19277 font_size: Pixels,
19278 max_line_number_width: Pixels,
19279 cx: &App,
19280 ) -> Option<GutterDimensions> {
19281 if !self.show_gutter {
19282 return None;
19283 }
19284
19285 let descent = cx.text_system().descent(font_id, font_size);
19286 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19287 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19288
19289 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19290 matches!(
19291 ProjectSettings::get_global(cx).git.git_gutter,
19292 Some(GitGutterSetting::TrackedFiles)
19293 )
19294 });
19295 let gutter_settings = EditorSettings::get_global(cx).gutter;
19296 let show_line_numbers = self
19297 .show_line_numbers
19298 .unwrap_or(gutter_settings.line_numbers);
19299 let line_gutter_width = if show_line_numbers {
19300 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19301 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19302 max_line_number_width.max(min_width_for_number_on_gutter)
19303 } else {
19304 0.0.into()
19305 };
19306
19307 let show_code_actions = self
19308 .show_code_actions
19309 .unwrap_or(gutter_settings.code_actions);
19310
19311 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19312 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19313
19314 let git_blame_entries_width =
19315 self.git_blame_gutter_max_author_length
19316 .map(|max_author_length| {
19317 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19318 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19319
19320 /// The number of characters to dedicate to gaps and margins.
19321 const SPACING_WIDTH: usize = 4;
19322
19323 let max_char_count = max_author_length.min(renderer.max_author_length())
19324 + ::git::SHORT_SHA_LENGTH
19325 + MAX_RELATIVE_TIMESTAMP.len()
19326 + SPACING_WIDTH;
19327
19328 em_advance * max_char_count
19329 });
19330
19331 let is_singleton = self.buffer_snapshot.is_singleton();
19332
19333 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19334 left_padding += if !is_singleton {
19335 em_width * 4.0
19336 } else if show_code_actions || show_runnables || show_breakpoints {
19337 em_width * 3.0
19338 } else if show_git_gutter && show_line_numbers {
19339 em_width * 2.0
19340 } else if show_git_gutter || show_line_numbers {
19341 em_width
19342 } else {
19343 px(0.)
19344 };
19345
19346 let shows_folds = is_singleton && gutter_settings.folds;
19347
19348 let right_padding = if shows_folds && show_line_numbers {
19349 em_width * 4.0
19350 } else if shows_folds || (!is_singleton && show_line_numbers) {
19351 em_width * 3.0
19352 } else if show_line_numbers {
19353 em_width
19354 } else {
19355 px(0.)
19356 };
19357
19358 Some(GutterDimensions {
19359 left_padding,
19360 right_padding,
19361 width: line_gutter_width + left_padding + right_padding,
19362 margin: -descent,
19363 git_blame_entries_width,
19364 })
19365 }
19366
19367 pub fn render_crease_toggle(
19368 &self,
19369 buffer_row: MultiBufferRow,
19370 row_contains_cursor: bool,
19371 editor: Entity<Editor>,
19372 window: &mut Window,
19373 cx: &mut App,
19374 ) -> Option<AnyElement> {
19375 let folded = self.is_line_folded(buffer_row);
19376 let mut is_foldable = false;
19377
19378 if let Some(crease) = self
19379 .crease_snapshot
19380 .query_row(buffer_row, &self.buffer_snapshot)
19381 {
19382 is_foldable = true;
19383 match crease {
19384 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19385 if let Some(render_toggle) = render_toggle {
19386 let toggle_callback =
19387 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19388 if folded {
19389 editor.update(cx, |editor, cx| {
19390 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19391 });
19392 } else {
19393 editor.update(cx, |editor, cx| {
19394 editor.unfold_at(
19395 &crate::UnfoldAt { buffer_row },
19396 window,
19397 cx,
19398 )
19399 });
19400 }
19401 });
19402 return Some((render_toggle)(
19403 buffer_row,
19404 folded,
19405 toggle_callback,
19406 window,
19407 cx,
19408 ));
19409 }
19410 }
19411 }
19412 }
19413
19414 is_foldable |= self.starts_indent(buffer_row);
19415
19416 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19417 Some(
19418 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19419 .toggle_state(folded)
19420 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19421 if folded {
19422 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19423 } else {
19424 this.fold_at(&FoldAt { buffer_row }, window, cx);
19425 }
19426 }))
19427 .into_any_element(),
19428 )
19429 } else {
19430 None
19431 }
19432 }
19433
19434 pub fn render_crease_trailer(
19435 &self,
19436 buffer_row: MultiBufferRow,
19437 window: &mut Window,
19438 cx: &mut App,
19439 ) -> Option<AnyElement> {
19440 let folded = self.is_line_folded(buffer_row);
19441 if let Crease::Inline { render_trailer, .. } = self
19442 .crease_snapshot
19443 .query_row(buffer_row, &self.buffer_snapshot)?
19444 {
19445 let render_trailer = render_trailer.as_ref()?;
19446 Some(render_trailer(buffer_row, folded, window, cx))
19447 } else {
19448 None
19449 }
19450 }
19451}
19452
19453impl Deref for EditorSnapshot {
19454 type Target = DisplaySnapshot;
19455
19456 fn deref(&self) -> &Self::Target {
19457 &self.display_snapshot
19458 }
19459}
19460
19461#[derive(Clone, Debug, PartialEq, Eq)]
19462pub enum EditorEvent {
19463 InputIgnored {
19464 text: Arc<str>,
19465 },
19466 InputHandled {
19467 utf16_range_to_replace: Option<Range<isize>>,
19468 text: Arc<str>,
19469 },
19470 ExcerptsAdded {
19471 buffer: Entity<Buffer>,
19472 predecessor: ExcerptId,
19473 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19474 },
19475 ExcerptsRemoved {
19476 ids: Vec<ExcerptId>,
19477 },
19478 BufferFoldToggled {
19479 ids: Vec<ExcerptId>,
19480 folded: bool,
19481 },
19482 ExcerptsEdited {
19483 ids: Vec<ExcerptId>,
19484 },
19485 ExcerptsExpanded {
19486 ids: Vec<ExcerptId>,
19487 },
19488 BufferEdited,
19489 Edited {
19490 transaction_id: clock::Lamport,
19491 },
19492 Reparsed(BufferId),
19493 Focused,
19494 FocusedIn,
19495 Blurred,
19496 DirtyChanged,
19497 Saved,
19498 TitleChanged,
19499 DiffBaseChanged,
19500 SelectionsChanged {
19501 local: bool,
19502 },
19503 ScrollPositionChanged {
19504 local: bool,
19505 autoscroll: bool,
19506 },
19507 Closed,
19508 TransactionUndone {
19509 transaction_id: clock::Lamport,
19510 },
19511 TransactionBegun {
19512 transaction_id: clock::Lamport,
19513 },
19514 Reloaded,
19515 CursorShapeChanged,
19516 PushedToNavHistory {
19517 anchor: Anchor,
19518 is_deactivate: bool,
19519 },
19520}
19521
19522impl EventEmitter<EditorEvent> for Editor {}
19523
19524impl Focusable for Editor {
19525 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19526 self.focus_handle.clone()
19527 }
19528}
19529
19530impl Render for Editor {
19531 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19532 let settings = ThemeSettings::get_global(cx);
19533
19534 let mut text_style = match self.mode {
19535 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19536 color: cx.theme().colors().editor_foreground,
19537 font_family: settings.ui_font.family.clone(),
19538 font_features: settings.ui_font.features.clone(),
19539 font_fallbacks: settings.ui_font.fallbacks.clone(),
19540 font_size: rems(0.875).into(),
19541 font_weight: settings.ui_font.weight,
19542 line_height: relative(settings.buffer_line_height.value()),
19543 ..Default::default()
19544 },
19545 EditorMode::Full { .. } => TextStyle {
19546 color: cx.theme().colors().editor_foreground,
19547 font_family: settings.buffer_font.family.clone(),
19548 font_features: settings.buffer_font.features.clone(),
19549 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19550 font_size: settings.buffer_font_size(cx).into(),
19551 font_weight: settings.buffer_font.weight,
19552 line_height: relative(settings.buffer_line_height.value()),
19553 ..Default::default()
19554 },
19555 };
19556 if let Some(text_style_refinement) = &self.text_style_refinement {
19557 text_style.refine(text_style_refinement)
19558 }
19559
19560 let background = match self.mode {
19561 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19562 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19563 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19564 };
19565
19566 EditorElement::new(
19567 &cx.entity(),
19568 EditorStyle {
19569 background,
19570 local_player: cx.theme().players().local(),
19571 text: text_style,
19572 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19573 syntax: cx.theme().syntax().clone(),
19574 status: cx.theme().status().clone(),
19575 inlay_hints_style: make_inlay_hints_style(cx),
19576 inline_completion_styles: make_suggestion_styles(cx),
19577 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19578 },
19579 )
19580 }
19581}
19582
19583impl EntityInputHandler for Editor {
19584 fn text_for_range(
19585 &mut self,
19586 range_utf16: Range<usize>,
19587 adjusted_range: &mut Option<Range<usize>>,
19588 _: &mut Window,
19589 cx: &mut Context<Self>,
19590 ) -> Option<String> {
19591 let snapshot = self.buffer.read(cx).read(cx);
19592 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19593 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19594 if (start.0..end.0) != range_utf16 {
19595 adjusted_range.replace(start.0..end.0);
19596 }
19597 Some(snapshot.text_for_range(start..end).collect())
19598 }
19599
19600 fn selected_text_range(
19601 &mut self,
19602 ignore_disabled_input: bool,
19603 _: &mut Window,
19604 cx: &mut Context<Self>,
19605 ) -> Option<UTF16Selection> {
19606 // Prevent the IME menu from appearing when holding down an alphabetic key
19607 // while input is disabled.
19608 if !ignore_disabled_input && !self.input_enabled {
19609 return None;
19610 }
19611
19612 let selection = self.selections.newest::<OffsetUtf16>(cx);
19613 let range = selection.range();
19614
19615 Some(UTF16Selection {
19616 range: range.start.0..range.end.0,
19617 reversed: selection.reversed,
19618 })
19619 }
19620
19621 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19622 let snapshot = self.buffer.read(cx).read(cx);
19623 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19624 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19625 }
19626
19627 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19628 self.clear_highlights::<InputComposition>(cx);
19629 self.ime_transaction.take();
19630 }
19631
19632 fn replace_text_in_range(
19633 &mut self,
19634 range_utf16: Option<Range<usize>>,
19635 text: &str,
19636 window: &mut Window,
19637 cx: &mut Context<Self>,
19638 ) {
19639 if !self.input_enabled {
19640 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19641 return;
19642 }
19643
19644 self.transact(window, cx, |this, window, cx| {
19645 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19646 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19647 Some(this.selection_replacement_ranges(range_utf16, cx))
19648 } else {
19649 this.marked_text_ranges(cx)
19650 };
19651
19652 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19653 let newest_selection_id = this.selections.newest_anchor().id;
19654 this.selections
19655 .all::<OffsetUtf16>(cx)
19656 .iter()
19657 .zip(ranges_to_replace.iter())
19658 .find_map(|(selection, range)| {
19659 if selection.id == newest_selection_id {
19660 Some(
19661 (range.start.0 as isize - selection.head().0 as isize)
19662 ..(range.end.0 as isize - selection.head().0 as isize),
19663 )
19664 } else {
19665 None
19666 }
19667 })
19668 });
19669
19670 cx.emit(EditorEvent::InputHandled {
19671 utf16_range_to_replace: range_to_replace,
19672 text: text.into(),
19673 });
19674
19675 if let Some(new_selected_ranges) = new_selected_ranges {
19676 this.change_selections(None, window, cx, |selections| {
19677 selections.select_ranges(new_selected_ranges)
19678 });
19679 this.backspace(&Default::default(), window, cx);
19680 }
19681
19682 this.handle_input(text, window, cx);
19683 });
19684
19685 if let Some(transaction) = self.ime_transaction {
19686 self.buffer.update(cx, |buffer, cx| {
19687 buffer.group_until_transaction(transaction, cx);
19688 });
19689 }
19690
19691 self.unmark_text(window, cx);
19692 }
19693
19694 fn replace_and_mark_text_in_range(
19695 &mut self,
19696 range_utf16: Option<Range<usize>>,
19697 text: &str,
19698 new_selected_range_utf16: Option<Range<usize>>,
19699 window: &mut Window,
19700 cx: &mut Context<Self>,
19701 ) {
19702 if !self.input_enabled {
19703 return;
19704 }
19705
19706 let transaction = self.transact(window, cx, |this, window, cx| {
19707 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19708 let snapshot = this.buffer.read(cx).read(cx);
19709 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19710 for marked_range in &mut marked_ranges {
19711 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19712 marked_range.start.0 += relative_range_utf16.start;
19713 marked_range.start =
19714 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19715 marked_range.end =
19716 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19717 }
19718 }
19719 Some(marked_ranges)
19720 } else if let Some(range_utf16) = range_utf16 {
19721 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19722 Some(this.selection_replacement_ranges(range_utf16, cx))
19723 } else {
19724 None
19725 };
19726
19727 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19728 let newest_selection_id = this.selections.newest_anchor().id;
19729 this.selections
19730 .all::<OffsetUtf16>(cx)
19731 .iter()
19732 .zip(ranges_to_replace.iter())
19733 .find_map(|(selection, range)| {
19734 if selection.id == newest_selection_id {
19735 Some(
19736 (range.start.0 as isize - selection.head().0 as isize)
19737 ..(range.end.0 as isize - selection.head().0 as isize),
19738 )
19739 } else {
19740 None
19741 }
19742 })
19743 });
19744
19745 cx.emit(EditorEvent::InputHandled {
19746 utf16_range_to_replace: range_to_replace,
19747 text: text.into(),
19748 });
19749
19750 if let Some(ranges) = ranges_to_replace {
19751 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19752 }
19753
19754 let marked_ranges = {
19755 let snapshot = this.buffer.read(cx).read(cx);
19756 this.selections
19757 .disjoint_anchors()
19758 .iter()
19759 .map(|selection| {
19760 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19761 })
19762 .collect::<Vec<_>>()
19763 };
19764
19765 if text.is_empty() {
19766 this.unmark_text(window, cx);
19767 } else {
19768 this.highlight_text::<InputComposition>(
19769 marked_ranges.clone(),
19770 HighlightStyle {
19771 underline: Some(UnderlineStyle {
19772 thickness: px(1.),
19773 color: None,
19774 wavy: false,
19775 }),
19776 ..Default::default()
19777 },
19778 cx,
19779 );
19780 }
19781
19782 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19783 let use_autoclose = this.use_autoclose;
19784 let use_auto_surround = this.use_auto_surround;
19785 this.set_use_autoclose(false);
19786 this.set_use_auto_surround(false);
19787 this.handle_input(text, window, cx);
19788 this.set_use_autoclose(use_autoclose);
19789 this.set_use_auto_surround(use_auto_surround);
19790
19791 if let Some(new_selected_range) = new_selected_range_utf16 {
19792 let snapshot = this.buffer.read(cx).read(cx);
19793 let new_selected_ranges = marked_ranges
19794 .into_iter()
19795 .map(|marked_range| {
19796 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19797 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19798 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19799 snapshot.clip_offset_utf16(new_start, Bias::Left)
19800 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19801 })
19802 .collect::<Vec<_>>();
19803
19804 drop(snapshot);
19805 this.change_selections(None, window, cx, |selections| {
19806 selections.select_ranges(new_selected_ranges)
19807 });
19808 }
19809 });
19810
19811 self.ime_transaction = self.ime_transaction.or(transaction);
19812 if let Some(transaction) = self.ime_transaction {
19813 self.buffer.update(cx, |buffer, cx| {
19814 buffer.group_until_transaction(transaction, cx);
19815 });
19816 }
19817
19818 if self.text_highlights::<InputComposition>(cx).is_none() {
19819 self.ime_transaction.take();
19820 }
19821 }
19822
19823 fn bounds_for_range(
19824 &mut self,
19825 range_utf16: Range<usize>,
19826 element_bounds: gpui::Bounds<Pixels>,
19827 window: &mut Window,
19828 cx: &mut Context<Self>,
19829 ) -> Option<gpui::Bounds<Pixels>> {
19830 let text_layout_details = self.text_layout_details(window);
19831 let gpui::Size {
19832 width: em_width,
19833 height: line_height,
19834 } = self.character_size(window);
19835
19836 let snapshot = self.snapshot(window, cx);
19837 let scroll_position = snapshot.scroll_position();
19838 let scroll_left = scroll_position.x * em_width;
19839
19840 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19841 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19842 + self.gutter_dimensions.width
19843 + self.gutter_dimensions.margin;
19844 let y = line_height * (start.row().as_f32() - scroll_position.y);
19845
19846 Some(Bounds {
19847 origin: element_bounds.origin + point(x, y),
19848 size: size(em_width, line_height),
19849 })
19850 }
19851
19852 fn character_index_for_point(
19853 &mut self,
19854 point: gpui::Point<Pixels>,
19855 _window: &mut Window,
19856 _cx: &mut Context<Self>,
19857 ) -> Option<usize> {
19858 let position_map = self.last_position_map.as_ref()?;
19859 if !position_map.text_hitbox.contains(&point) {
19860 return None;
19861 }
19862 let display_point = position_map.point_for_position(point).previous_valid;
19863 let anchor = position_map
19864 .snapshot
19865 .display_point_to_anchor(display_point, Bias::Left);
19866 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19867 Some(utf16_offset.0)
19868 }
19869}
19870
19871trait SelectionExt {
19872 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19873 fn spanned_rows(
19874 &self,
19875 include_end_if_at_line_start: bool,
19876 map: &DisplaySnapshot,
19877 ) -> Range<MultiBufferRow>;
19878}
19879
19880impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19881 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19882 let start = self
19883 .start
19884 .to_point(&map.buffer_snapshot)
19885 .to_display_point(map);
19886 let end = self
19887 .end
19888 .to_point(&map.buffer_snapshot)
19889 .to_display_point(map);
19890 if self.reversed {
19891 end..start
19892 } else {
19893 start..end
19894 }
19895 }
19896
19897 fn spanned_rows(
19898 &self,
19899 include_end_if_at_line_start: bool,
19900 map: &DisplaySnapshot,
19901 ) -> Range<MultiBufferRow> {
19902 let start = self.start.to_point(&map.buffer_snapshot);
19903 let mut end = self.end.to_point(&map.buffer_snapshot);
19904 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19905 end.row -= 1;
19906 }
19907
19908 let buffer_start = map.prev_line_boundary(start).0;
19909 let buffer_end = map.next_line_boundary(end).0;
19910 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19911 }
19912}
19913
19914impl<T: InvalidationRegion> InvalidationStack<T> {
19915 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19916 where
19917 S: Clone + ToOffset,
19918 {
19919 while let Some(region) = self.last() {
19920 let all_selections_inside_invalidation_ranges =
19921 if selections.len() == region.ranges().len() {
19922 selections
19923 .iter()
19924 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19925 .all(|(selection, invalidation_range)| {
19926 let head = selection.head().to_offset(buffer);
19927 invalidation_range.start <= head && invalidation_range.end >= head
19928 })
19929 } else {
19930 false
19931 };
19932
19933 if all_selections_inside_invalidation_ranges {
19934 break;
19935 } else {
19936 self.pop();
19937 }
19938 }
19939 }
19940}
19941
19942impl<T> Default for InvalidationStack<T> {
19943 fn default() -> Self {
19944 Self(Default::default())
19945 }
19946}
19947
19948impl<T> Deref for InvalidationStack<T> {
19949 type Target = Vec<T>;
19950
19951 fn deref(&self) -> &Self::Target {
19952 &self.0
19953 }
19954}
19955
19956impl<T> DerefMut for InvalidationStack<T> {
19957 fn deref_mut(&mut self) -> &mut Self::Target {
19958 &mut self.0
19959 }
19960}
19961
19962impl InvalidationRegion for SnippetState {
19963 fn ranges(&self) -> &[Range<Anchor>] {
19964 &self.ranges[self.active_index]
19965 }
19966}
19967
19968pub fn diagnostic_block_renderer(
19969 diagnostic: Diagnostic,
19970 max_message_rows: Option<u8>,
19971 allow_closing: bool,
19972) -> RenderBlock {
19973 let (text_without_backticks, code_ranges) =
19974 highlight_diagnostic_message(&diagnostic, max_message_rows);
19975
19976 Arc::new(move |cx: &mut BlockContext| {
19977 let group_id: SharedString = cx.block_id.to_string().into();
19978
19979 let mut text_style = cx.window.text_style().clone();
19980 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19981 let theme_settings = ThemeSettings::get_global(cx);
19982 text_style.font_family = theme_settings.buffer_font.family.clone();
19983 text_style.font_style = theme_settings.buffer_font.style;
19984 text_style.font_features = theme_settings.buffer_font.features.clone();
19985 text_style.font_weight = theme_settings.buffer_font.weight;
19986
19987 let multi_line_diagnostic = diagnostic.message.contains('\n');
19988
19989 let buttons = |diagnostic: &Diagnostic| {
19990 if multi_line_diagnostic {
19991 v_flex()
19992 } else {
19993 h_flex()
19994 }
19995 .when(allow_closing, |div| {
19996 div.children(diagnostic.is_primary.then(|| {
19997 IconButton::new("close-block", IconName::XCircle)
19998 .icon_color(Color::Muted)
19999 .size(ButtonSize::Compact)
20000 .style(ButtonStyle::Transparent)
20001 .visible_on_hover(group_id.clone())
20002 .on_click(move |_click, window, cx| {
20003 window.dispatch_action(Box::new(Cancel), cx)
20004 })
20005 .tooltip(|window, cx| {
20006 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
20007 })
20008 }))
20009 })
20010 .child(
20011 IconButton::new("copy-block", IconName::Copy)
20012 .icon_color(Color::Muted)
20013 .size(ButtonSize::Compact)
20014 .style(ButtonStyle::Transparent)
20015 .visible_on_hover(group_id.clone())
20016 .on_click({
20017 let message = diagnostic.message.clone();
20018 move |_click, _, cx| {
20019 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
20020 }
20021 })
20022 .tooltip(Tooltip::text("Copy diagnostic message")),
20023 )
20024 };
20025
20026 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
20027 AvailableSpace::min_size(),
20028 cx.window,
20029 cx.app,
20030 );
20031
20032 h_flex()
20033 .id(cx.block_id)
20034 .group(group_id.clone())
20035 .relative()
20036 .size_full()
20037 .block_mouse_down()
20038 .pl(cx.gutter_dimensions.width)
20039 .w(cx.max_width - cx.gutter_dimensions.full_width())
20040 .child(
20041 div()
20042 .flex()
20043 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
20044 .flex_shrink(),
20045 )
20046 .child(buttons(&diagnostic))
20047 .child(div().flex().flex_shrink_0().child(
20048 StyledText::new(text_without_backticks.clone()).with_default_highlights(
20049 &text_style,
20050 code_ranges.iter().map(|range| {
20051 (
20052 range.clone(),
20053 HighlightStyle {
20054 font_weight: Some(FontWeight::BOLD),
20055 ..Default::default()
20056 },
20057 )
20058 }),
20059 ),
20060 ))
20061 .into_any_element()
20062 })
20063}
20064
20065fn inline_completion_edit_text(
20066 current_snapshot: &BufferSnapshot,
20067 edits: &[(Range<Anchor>, String)],
20068 edit_preview: &EditPreview,
20069 include_deletions: bool,
20070 cx: &App,
20071) -> HighlightedText {
20072 let edits = edits
20073 .iter()
20074 .map(|(anchor, text)| {
20075 (
20076 anchor.start.text_anchor..anchor.end.text_anchor,
20077 text.clone(),
20078 )
20079 })
20080 .collect::<Vec<_>>();
20081
20082 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20083}
20084
20085pub fn highlight_diagnostic_message(
20086 diagnostic: &Diagnostic,
20087 mut max_message_rows: Option<u8>,
20088) -> (SharedString, Vec<Range<usize>>) {
20089 let mut text_without_backticks = String::new();
20090 let mut code_ranges = Vec::new();
20091
20092 if let Some(source) = &diagnostic.source {
20093 text_without_backticks.push_str(source);
20094 code_ranges.push(0..source.len());
20095 text_without_backticks.push_str(": ");
20096 }
20097
20098 let mut prev_offset = 0;
20099 let mut in_code_block = false;
20100 let has_row_limit = max_message_rows.is_some();
20101 let mut newline_indices = diagnostic
20102 .message
20103 .match_indices('\n')
20104 .filter(|_| has_row_limit)
20105 .map(|(ix, _)| ix)
20106 .fuse()
20107 .peekable();
20108
20109 for (quote_ix, _) in diagnostic
20110 .message
20111 .match_indices('`')
20112 .chain([(diagnostic.message.len(), "")])
20113 {
20114 let mut first_newline_ix = None;
20115 let mut last_newline_ix = None;
20116 while let Some(newline_ix) = newline_indices.peek() {
20117 if *newline_ix < quote_ix {
20118 if first_newline_ix.is_none() {
20119 first_newline_ix = Some(*newline_ix);
20120 }
20121 last_newline_ix = Some(*newline_ix);
20122
20123 if let Some(rows_left) = &mut max_message_rows {
20124 if *rows_left == 0 {
20125 break;
20126 } else {
20127 *rows_left -= 1;
20128 }
20129 }
20130 let _ = newline_indices.next();
20131 } else {
20132 break;
20133 }
20134 }
20135 let prev_len = text_without_backticks.len();
20136 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
20137 text_without_backticks.push_str(new_text);
20138 if in_code_block {
20139 code_ranges.push(prev_len..text_without_backticks.len());
20140 }
20141 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
20142 in_code_block = !in_code_block;
20143 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
20144 text_without_backticks.push_str("...");
20145 break;
20146 }
20147 }
20148
20149 (text_without_backticks.into(), code_ranges)
20150}
20151
20152fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20153 match severity {
20154 DiagnosticSeverity::ERROR => colors.error,
20155 DiagnosticSeverity::WARNING => colors.warning,
20156 DiagnosticSeverity::INFORMATION => colors.info,
20157 DiagnosticSeverity::HINT => colors.info,
20158 _ => colors.ignored,
20159 }
20160}
20161
20162pub fn styled_runs_for_code_label<'a>(
20163 label: &'a CodeLabel,
20164 syntax_theme: &'a theme::SyntaxTheme,
20165) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20166 let fade_out = HighlightStyle {
20167 fade_out: Some(0.35),
20168 ..Default::default()
20169 };
20170
20171 let mut prev_end = label.filter_range.end;
20172 label
20173 .runs
20174 .iter()
20175 .enumerate()
20176 .flat_map(move |(ix, (range, highlight_id))| {
20177 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20178 style
20179 } else {
20180 return Default::default();
20181 };
20182 let mut muted_style = style;
20183 muted_style.highlight(fade_out);
20184
20185 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20186 if range.start >= label.filter_range.end {
20187 if range.start > prev_end {
20188 runs.push((prev_end..range.start, fade_out));
20189 }
20190 runs.push((range.clone(), muted_style));
20191 } else if range.end <= label.filter_range.end {
20192 runs.push((range.clone(), style));
20193 } else {
20194 runs.push((range.start..label.filter_range.end, style));
20195 runs.push((label.filter_range.end..range.end, muted_style));
20196 }
20197 prev_end = cmp::max(prev_end, range.end);
20198
20199 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20200 runs.push((prev_end..label.text.len(), fade_out));
20201 }
20202
20203 runs
20204 })
20205}
20206
20207pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20208 let mut prev_index = 0;
20209 let mut prev_codepoint: Option<char> = None;
20210 text.char_indices()
20211 .chain([(text.len(), '\0')])
20212 .filter_map(move |(index, codepoint)| {
20213 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20214 let is_boundary = index == text.len()
20215 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20216 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20217 if is_boundary {
20218 let chunk = &text[prev_index..index];
20219 prev_index = index;
20220 Some(chunk)
20221 } else {
20222 None
20223 }
20224 })
20225}
20226
20227pub trait RangeToAnchorExt: Sized {
20228 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20229
20230 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20231 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20232 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20233 }
20234}
20235
20236impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20237 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20238 let start_offset = self.start.to_offset(snapshot);
20239 let end_offset = self.end.to_offset(snapshot);
20240 if start_offset == end_offset {
20241 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20242 } else {
20243 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20244 }
20245 }
20246}
20247
20248pub trait RowExt {
20249 fn as_f32(&self) -> f32;
20250
20251 fn next_row(&self) -> Self;
20252
20253 fn previous_row(&self) -> Self;
20254
20255 fn minus(&self, other: Self) -> u32;
20256}
20257
20258impl RowExt for DisplayRow {
20259 fn as_f32(&self) -> f32 {
20260 self.0 as f32
20261 }
20262
20263 fn next_row(&self) -> Self {
20264 Self(self.0 + 1)
20265 }
20266
20267 fn previous_row(&self) -> Self {
20268 Self(self.0.saturating_sub(1))
20269 }
20270
20271 fn minus(&self, other: Self) -> u32 {
20272 self.0 - other.0
20273 }
20274}
20275
20276impl RowExt for MultiBufferRow {
20277 fn as_f32(&self) -> f32 {
20278 self.0 as f32
20279 }
20280
20281 fn next_row(&self) -> Self {
20282 Self(self.0 + 1)
20283 }
20284
20285 fn previous_row(&self) -> Self {
20286 Self(self.0.saturating_sub(1))
20287 }
20288
20289 fn minus(&self, other: Self) -> u32 {
20290 self.0 - other.0
20291 }
20292}
20293
20294trait RowRangeExt {
20295 type Row;
20296
20297 fn len(&self) -> usize;
20298
20299 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20300}
20301
20302impl RowRangeExt for Range<MultiBufferRow> {
20303 type Row = MultiBufferRow;
20304
20305 fn len(&self) -> usize {
20306 (self.end.0 - self.start.0) as usize
20307 }
20308
20309 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20310 (self.start.0..self.end.0).map(MultiBufferRow)
20311 }
20312}
20313
20314impl RowRangeExt for Range<DisplayRow> {
20315 type Row = DisplayRow;
20316
20317 fn len(&self) -> usize {
20318 (self.end.0 - self.start.0) as usize
20319 }
20320
20321 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20322 (self.start.0..self.end.0).map(DisplayRow)
20323 }
20324}
20325
20326/// If select range has more than one line, we
20327/// just point the cursor to range.start.
20328fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20329 if range.start.row == range.end.row {
20330 range
20331 } else {
20332 range.start..range.start
20333 }
20334}
20335pub struct KillRing(ClipboardItem);
20336impl Global for KillRing {}
20337
20338const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20339
20340enum BreakpointPromptEditAction {
20341 Log,
20342 Condition,
20343 HitCondition,
20344}
20345
20346struct BreakpointPromptEditor {
20347 pub(crate) prompt: Entity<Editor>,
20348 editor: WeakEntity<Editor>,
20349 breakpoint_anchor: Anchor,
20350 breakpoint: Breakpoint,
20351 edit_action: BreakpointPromptEditAction,
20352 block_ids: HashSet<CustomBlockId>,
20353 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20354 _subscriptions: Vec<Subscription>,
20355}
20356
20357impl BreakpointPromptEditor {
20358 const MAX_LINES: u8 = 4;
20359
20360 fn new(
20361 editor: WeakEntity<Editor>,
20362 breakpoint_anchor: Anchor,
20363 breakpoint: Breakpoint,
20364 edit_action: BreakpointPromptEditAction,
20365 window: &mut Window,
20366 cx: &mut Context<Self>,
20367 ) -> Self {
20368 let base_text = match edit_action {
20369 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20370 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20371 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20372 }
20373 .map(|msg| msg.to_string())
20374 .unwrap_or_default();
20375
20376 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20377 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20378
20379 let prompt = cx.new(|cx| {
20380 let mut prompt = Editor::new(
20381 EditorMode::AutoHeight {
20382 max_lines: Self::MAX_LINES as usize,
20383 },
20384 buffer,
20385 None,
20386 window,
20387 cx,
20388 );
20389 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20390 prompt.set_show_cursor_when_unfocused(false, cx);
20391 prompt.set_placeholder_text(
20392 match edit_action {
20393 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20394 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20395 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20396 },
20397 cx,
20398 );
20399
20400 prompt
20401 });
20402
20403 Self {
20404 prompt,
20405 editor,
20406 breakpoint_anchor,
20407 breakpoint,
20408 edit_action,
20409 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20410 block_ids: Default::default(),
20411 _subscriptions: vec![],
20412 }
20413 }
20414
20415 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20416 self.block_ids.extend(block_ids)
20417 }
20418
20419 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20420 if let Some(editor) = self.editor.upgrade() {
20421 let message = self
20422 .prompt
20423 .read(cx)
20424 .buffer
20425 .read(cx)
20426 .as_singleton()
20427 .expect("A multi buffer in breakpoint prompt isn't possible")
20428 .read(cx)
20429 .as_rope()
20430 .to_string();
20431
20432 editor.update(cx, |editor, cx| {
20433 editor.edit_breakpoint_at_anchor(
20434 self.breakpoint_anchor,
20435 self.breakpoint.clone(),
20436 match self.edit_action {
20437 BreakpointPromptEditAction::Log => {
20438 BreakpointEditAction::EditLogMessage(message.into())
20439 }
20440 BreakpointPromptEditAction::Condition => {
20441 BreakpointEditAction::EditCondition(message.into())
20442 }
20443 BreakpointPromptEditAction::HitCondition => {
20444 BreakpointEditAction::EditHitCondition(message.into())
20445 }
20446 },
20447 cx,
20448 );
20449
20450 editor.remove_blocks(self.block_ids.clone(), None, cx);
20451 cx.focus_self(window);
20452 });
20453 }
20454 }
20455
20456 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20457 self.editor
20458 .update(cx, |editor, cx| {
20459 editor.remove_blocks(self.block_ids.clone(), None, cx);
20460 window.focus(&editor.focus_handle);
20461 })
20462 .log_err();
20463 }
20464
20465 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20466 let settings = ThemeSettings::get_global(cx);
20467 let text_style = TextStyle {
20468 color: if self.prompt.read(cx).read_only(cx) {
20469 cx.theme().colors().text_disabled
20470 } else {
20471 cx.theme().colors().text
20472 },
20473 font_family: settings.buffer_font.family.clone(),
20474 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20475 font_size: settings.buffer_font_size(cx).into(),
20476 font_weight: settings.buffer_font.weight,
20477 line_height: relative(settings.buffer_line_height.value()),
20478 ..Default::default()
20479 };
20480 EditorElement::new(
20481 &self.prompt,
20482 EditorStyle {
20483 background: cx.theme().colors().editor_background,
20484 local_player: cx.theme().players().local(),
20485 text: text_style,
20486 ..Default::default()
20487 },
20488 )
20489 }
20490}
20491
20492impl Render for BreakpointPromptEditor {
20493 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20494 let gutter_dimensions = *self.gutter_dimensions.lock();
20495 h_flex()
20496 .key_context("Editor")
20497 .bg(cx.theme().colors().editor_background)
20498 .border_y_1()
20499 .border_color(cx.theme().status().info_border)
20500 .size_full()
20501 .py(window.line_height() / 2.5)
20502 .on_action(cx.listener(Self::confirm))
20503 .on_action(cx.listener(Self::cancel))
20504 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20505 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20506 }
20507}
20508
20509impl Focusable for BreakpointPromptEditor {
20510 fn focus_handle(&self, cx: &App) -> FocusHandle {
20511 self.prompt.focus_handle(cx)
20512 }
20513}
20514
20515fn all_edits_insertions_or_deletions(
20516 edits: &Vec<(Range<Anchor>, String)>,
20517 snapshot: &MultiBufferSnapshot,
20518) -> bool {
20519 let mut all_insertions = true;
20520 let mut all_deletions = true;
20521
20522 for (range, new_text) in edits.iter() {
20523 let range_is_empty = range.to_offset(&snapshot).is_empty();
20524 let text_is_empty = new_text.is_empty();
20525
20526 if range_is_empty != text_is_empty {
20527 if range_is_empty {
20528 all_deletions = false;
20529 } else {
20530 all_insertions = false;
20531 }
20532 } else {
20533 return false;
20534 }
20535
20536 if !all_insertions && !all_deletions {
20537 return false;
20538 }
20539 }
20540 all_insertions || all_deletions
20541}
20542
20543struct MissingEditPredictionKeybindingTooltip;
20544
20545impl Render for MissingEditPredictionKeybindingTooltip {
20546 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20547 ui::tooltip_container(window, cx, |container, _, cx| {
20548 container
20549 .flex_shrink_0()
20550 .max_w_80()
20551 .min_h(rems_from_px(124.))
20552 .justify_between()
20553 .child(
20554 v_flex()
20555 .flex_1()
20556 .text_ui_sm(cx)
20557 .child(Label::new("Conflict with Accept Keybinding"))
20558 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20559 )
20560 .child(
20561 h_flex()
20562 .pb_1()
20563 .gap_1()
20564 .items_end()
20565 .w_full()
20566 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20567 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20568 }))
20569 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20570 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20571 })),
20572 )
20573 })
20574 }
20575}
20576
20577#[derive(Debug, Clone, Copy, PartialEq)]
20578pub struct LineHighlight {
20579 pub background: Background,
20580 pub border: Option<gpui::Hsla>,
20581}
20582
20583impl From<Hsla> for LineHighlight {
20584 fn from(hsla: Hsla) -> Self {
20585 Self {
20586 background: hsla.into(),
20587 border: None,
20588 }
20589 }
20590}
20591
20592impl From<Background> for LineHighlight {
20593 fn from(background: Background) -> Self {
20594 Self {
20595 background,
20596 border: None,
20597 }
20598 }
20599}
20600
20601fn render_diff_hunk_controls(
20602 row: u32,
20603 status: &DiffHunkStatus,
20604 hunk_range: Range<Anchor>,
20605 is_created_file: bool,
20606 line_height: Pixels,
20607 editor: &Entity<Editor>,
20608 _window: &mut Window,
20609 cx: &mut App,
20610) -> AnyElement {
20611 h_flex()
20612 .h(line_height)
20613 .mr_1()
20614 .gap_1()
20615 .px_0p5()
20616 .pb_1()
20617 .border_x_1()
20618 .border_b_1()
20619 .border_color(cx.theme().colors().border_variant)
20620 .rounded_b_lg()
20621 .bg(cx.theme().colors().editor_background)
20622 .gap_1()
20623 .occlude()
20624 .shadow_md()
20625 .child(if status.has_secondary_hunk() {
20626 Button::new(("stage", row as u64), "Stage")
20627 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20628 .tooltip({
20629 let focus_handle = editor.focus_handle(cx);
20630 move |window, cx| {
20631 Tooltip::for_action_in(
20632 "Stage Hunk",
20633 &::git::ToggleStaged,
20634 &focus_handle,
20635 window,
20636 cx,
20637 )
20638 }
20639 })
20640 .on_click({
20641 let editor = editor.clone();
20642 move |_event, _window, cx| {
20643 editor.update(cx, |editor, cx| {
20644 editor.stage_or_unstage_diff_hunks(
20645 true,
20646 vec![hunk_range.start..hunk_range.start],
20647 cx,
20648 );
20649 });
20650 }
20651 })
20652 } else {
20653 Button::new(("unstage", row as u64), "Unstage")
20654 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20655 .tooltip({
20656 let focus_handle = editor.focus_handle(cx);
20657 move |window, cx| {
20658 Tooltip::for_action_in(
20659 "Unstage Hunk",
20660 &::git::ToggleStaged,
20661 &focus_handle,
20662 window,
20663 cx,
20664 )
20665 }
20666 })
20667 .on_click({
20668 let editor = editor.clone();
20669 move |_event, _window, cx| {
20670 editor.update(cx, |editor, cx| {
20671 editor.stage_or_unstage_diff_hunks(
20672 false,
20673 vec![hunk_range.start..hunk_range.start],
20674 cx,
20675 );
20676 });
20677 }
20678 })
20679 })
20680 .child(
20681 Button::new(("restore", row as u64), "Restore")
20682 .tooltip({
20683 let focus_handle = editor.focus_handle(cx);
20684 move |window, cx| {
20685 Tooltip::for_action_in(
20686 "Restore Hunk",
20687 &::git::Restore,
20688 &focus_handle,
20689 window,
20690 cx,
20691 )
20692 }
20693 })
20694 .on_click({
20695 let editor = editor.clone();
20696 move |_event, window, cx| {
20697 editor.update(cx, |editor, cx| {
20698 let snapshot = editor.snapshot(window, cx);
20699 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20700 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20701 });
20702 }
20703 })
20704 .disabled(is_created_file),
20705 )
20706 .when(
20707 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20708 |el| {
20709 el.child(
20710 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20711 .shape(IconButtonShape::Square)
20712 .icon_size(IconSize::Small)
20713 // .disabled(!has_multiple_hunks)
20714 .tooltip({
20715 let focus_handle = editor.focus_handle(cx);
20716 move |window, cx| {
20717 Tooltip::for_action_in(
20718 "Next Hunk",
20719 &GoToHunk,
20720 &focus_handle,
20721 window,
20722 cx,
20723 )
20724 }
20725 })
20726 .on_click({
20727 let editor = editor.clone();
20728 move |_event, window, cx| {
20729 editor.update(cx, |editor, cx| {
20730 let snapshot = editor.snapshot(window, cx);
20731 let position =
20732 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20733 editor.go_to_hunk_before_or_after_position(
20734 &snapshot,
20735 position,
20736 Direction::Next,
20737 window,
20738 cx,
20739 );
20740 editor.expand_selected_diff_hunks(cx);
20741 });
20742 }
20743 }),
20744 )
20745 .child(
20746 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20747 .shape(IconButtonShape::Square)
20748 .icon_size(IconSize::Small)
20749 // .disabled(!has_multiple_hunks)
20750 .tooltip({
20751 let focus_handle = editor.focus_handle(cx);
20752 move |window, cx| {
20753 Tooltip::for_action_in(
20754 "Previous Hunk",
20755 &GoToPreviousHunk,
20756 &focus_handle,
20757 window,
20758 cx,
20759 )
20760 }
20761 })
20762 .on_click({
20763 let editor = editor.clone();
20764 move |_event, window, cx| {
20765 editor.update(cx, |editor, cx| {
20766 let snapshot = editor.snapshot(window, cx);
20767 let point =
20768 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20769 editor.go_to_hunk_before_or_after_position(
20770 &snapshot,
20771 point,
20772 Direction::Prev,
20773 window,
20774 cx,
20775 );
20776 editor.expand_selected_diff_hunks(cx);
20777 });
20778 }
20779 }),
20780 )
20781 },
20782 )
20783 .into_any_element()
20784}